From 4f1d77165908edcf17a7250368bee895a4302057 Mon Sep 17 00:00:00 2001 From: Your Name Date: Mon, 18 Aug 2025 12:38:15 -0400 Subject: [PATCH] Add debug logging to see received auth data --- app.js | 7 + app_working.js | 454 + node_modules/.bin/ejs | 1 + node_modules/.bin/jake | 1 + node_modules/.bin/semver | 1 + node_modules/.package-lock.json | 1134 ++ node_modules/@noble/ciphers/LICENSE | 22 + node_modules/@noble/ciphers/README.md | 655 ++ node_modules/@noble/ciphers/_arx.d.ts | 14 + node_modules/@noble/ciphers/_arx.d.ts.map | 1 + node_modules/@noble/ciphers/_arx.js | 175 + node_modules/@noble/ciphers/_arx.js.map | 1 + node_modules/@noble/ciphers/_assert.d.ts | 24 + node_modules/@noble/ciphers/_assert.d.ts.map | 1 + node_modules/@noble/ciphers/_assert.js | 50 + node_modules/@noble/ciphers/_assert.js.map | 1 + node_modules/@noble/ciphers/_micro.d.ts | 70 + node_modules/@noble/ciphers/_micro.d.ts.map | 1 + node_modules/@noble/ciphers/_micro.js | 295 + node_modules/@noble/ciphers/_micro.js.map | 1 + node_modules/@noble/ciphers/_poly1305.d.ts | 15 + .../@noble/ciphers/_poly1305.d.ts.map | 1 + node_modules/@noble/ciphers/_poly1305.js | 268 + node_modules/@noble/ciphers/_poly1305.js.map | 1 + node_modules/@noble/ciphers/_polyval.d.ts | 27 + node_modules/@noble/ciphers/_polyval.d.ts.map | 1 + node_modules/@noble/ciphers/_polyval.js | 221 + node_modules/@noble/ciphers/_polyval.js.map | 1 + node_modules/@noble/ciphers/aes.d.ts | 86 + node_modules/@noble/ciphers/aes.d.ts.map | 1 + node_modules/@noble/ciphers/aes.js | 675 ++ node_modules/@noble/ciphers/aes.js.map | 1 + node_modules/@noble/ciphers/chacha.d.ts | 61 + node_modules/@noble/ciphers/chacha.d.ts.map | 1 + node_modules/@noble/ciphers/chacha.js | 323 + node_modules/@noble/ciphers/chacha.js.map | 1 + node_modules/@noble/ciphers/crypto.d.ts | 3 + node_modules/@noble/ciphers/crypto.d.ts.map | 1 + node_modules/@noble/ciphers/crypto.js | 17 + node_modules/@noble/ciphers/crypto.js.map | 1 + node_modules/@noble/ciphers/cryptoNode.d.ts | 3 + .../@noble/ciphers/cryptoNode.d.ts.map | 1 + node_modules/@noble/ciphers/cryptoNode.js | 22 + node_modules/@noble/ciphers/cryptoNode.js.map | 1 + node_modules/@noble/ciphers/esm/_arx.js | 170 + node_modules/@noble/ciphers/esm/_arx.js.map | 1 + node_modules/@noble/ciphers/esm/_assert.js | 41 + .../@noble/ciphers/esm/_assert.js.map | 1 + node_modules/@noble/ciphers/esm/_micro.js | 287 + node_modules/@noble/ciphers/esm/_micro.js.map | 1 + node_modules/@noble/ciphers/esm/_poly1305.js | 264 + .../@noble/ciphers/esm/_poly1305.js.map | 1 + node_modules/@noble/ciphers/esm/_polyval.js | 217 + .../@noble/ciphers/esm/_polyval.js.map | 1 + node_modules/@noble/ciphers/esm/aes.js | 670 ++ node_modules/@noble/ciphers/esm/aes.js.map | 1 + node_modules/@noble/ciphers/esm/chacha.js | 318 + node_modules/@noble/ciphers/esm/chacha.js.map | 1 + node_modules/@noble/ciphers/esm/crypto.js | 12 + node_modules/@noble/ciphers/esm/crypto.js.map | 1 + node_modules/@noble/ciphers/esm/cryptoNode.js | 17 + .../@noble/ciphers/esm/cryptoNode.js.map | 1 + node_modules/@noble/ciphers/esm/ff1.js | 149 + node_modules/@noble/ciphers/esm/ff1.js.map | 1 + node_modules/@noble/ciphers/esm/index.js | 3 + node_modules/@noble/ciphers/esm/index.js.map | 1 + node_modules/@noble/ciphers/esm/package.json | 11 + node_modules/@noble/ciphers/esm/salsa.js | 205 + node_modules/@noble/ciphers/esm/salsa.js.map | 1 + node_modules/@noble/ciphers/esm/utils.js | 182 + node_modules/@noble/ciphers/esm/utils.js.map | 1 + node_modules/@noble/ciphers/esm/webcrypto.js | 105 + .../@noble/ciphers/esm/webcrypto.js.map | 1 + node_modules/@noble/ciphers/ff1.d.ts | 7 + node_modules/@noble/ciphers/ff1.d.ts.map | 1 + node_modules/@noble/ciphers/ff1.js | 154 + node_modules/@noble/ciphers/ff1.js.map | 1 + node_modules/@noble/ciphers/index.d.ts | 1 + node_modules/@noble/ciphers/index.d.ts.map | 1 + node_modules/@noble/ciphers/index.js | 3 + node_modules/@noble/ciphers/index.js.map | 1 + node_modules/@noble/ciphers/package.json | 126 + node_modules/@noble/ciphers/salsa.d.ts | 36 + node_modules/@noble/ciphers/salsa.d.ts.map | 1 + node_modules/@noble/ciphers/salsa.js | 210 + node_modules/@noble/ciphers/salsa.js.map | 1 + node_modules/@noble/ciphers/src/_arx.ts | 217 + node_modules/@noble/ciphers/src/_assert.ts | 50 + node_modules/@noble/ciphers/src/_micro.ts | 325 + node_modules/@noble/ciphers/src/_poly1305.ts | 286 + node_modules/@noble/ciphers/src/_polyval.ts | 248 + node_modules/@noble/ciphers/src/aes.ts | 734 ++ node_modules/@noble/ciphers/src/chacha.ts | 285 + node_modules/@noble/ciphers/src/crypto.ts | 15 + node_modules/@noble/ciphers/src/cryptoNode.ts | 17 + node_modules/@noble/ciphers/src/ff1.ts | 147 + node_modules/@noble/ciphers/src/index.ts | 1 + node_modules/@noble/ciphers/src/package.json | 3 + node_modules/@noble/ciphers/src/salsa.ts | 178 + node_modules/@noble/ciphers/src/utils.ts | 253 + node_modules/@noble/ciphers/src/webcrypto.ts | 125 + node_modules/@noble/ciphers/utils.d.ts | 81 + node_modules/@noble/ciphers/utils.d.ts.map | 1 + node_modules/@noble/ciphers/utils.js | 206 + node_modules/@noble/ciphers/utils.js.map | 1 + node_modules/@noble/ciphers/webcrypto.d.ts | 20 + .../@noble/ciphers/webcrypto.d.ts.map | 1 + node_modules/@noble/ciphers/webcrypto.js | 107 + node_modules/@noble/ciphers/webcrypto.js.map | 1 + node_modules/@noble/curves/LICENSE | 21 + node_modules/@noble/curves/README.md | 1074 ++ node_modules/@noble/curves/_shortw_utils.d.ts | 62 + .../@noble/curves/_shortw_utils.d.ts.map | 1 + node_modules/@noble/curves/_shortw_utils.js | 22 + .../@noble/curves/_shortw_utils.js.map | 1 + node_modules/@noble/curves/abstract/bls.d.ts | 103 + .../@noble/curves/abstract/bls.d.ts.map | 1 + node_modules/@noble/curves/abstract/bls.js | 239 + .../@noble/curves/abstract/bls.js.map | 1 + .../@noble/curves/abstract/curve.d.ts | 70 + .../@noble/curves/abstract/curve.d.ts.map | 1 + node_modules/@noble/curves/abstract/curve.js | 161 + .../@noble/curves/abstract/curve.js.map | 1 + .../@noble/curves/abstract/edwards.d.ts | 89 + .../@noble/curves/abstract/edwards.d.ts.map | 1 + .../@noble/curves/abstract/edwards.js | 429 + .../@noble/curves/abstract/edwards.js.map | 1 + .../@noble/curves/abstract/hash-to-curve.d.ts | 57 + .../curves/abstract/hash-to-curve.d.ts.map | 1 + .../@noble/curves/abstract/hash-to-curve.js | 181 + .../curves/abstract/hash-to-curve.js.map | 1 + .../@noble/curves/abstract/modular.d.ts | 123 + .../@noble/curves/abstract/modular.d.ts.map | 1 + .../@noble/curves/abstract/modular.js | 439 + .../@noble/curves/abstract/modular.js.map | 1 + .../@noble/curves/abstract/montgomery.d.ts | 26 + .../curves/abstract/montgomery.d.ts.map | 1 + .../@noble/curves/abstract/montgomery.js | 161 + .../@noble/curves/abstract/montgomery.js.map | 1 + .../@noble/curves/abstract/poseidon.d.ts | 30 + .../@noble/curves/abstract/poseidon.d.ts.map | 1 + .../@noble/curves/abstract/poseidon.js | 114 + .../@noble/curves/abstract/poseidon.js.map | 1 + .../@noble/curves/abstract/utils.d.ts | 92 + .../@noble/curves/abstract/utils.d.ts.map | 1 + node_modules/@noble/curves/abstract/utils.js | 288 + .../@noble/curves/abstract/utils.js.map | 1 + .../@noble/curves/abstract/weierstrass.d.ts | 241 + .../curves/abstract/weierstrass.d.ts.map | 1 + .../@noble/curves/abstract/weierstrass.js | 1063 ++ .../@noble/curves/abstract/weierstrass.js.map | 1 + node_modules/@noble/curves/bls12-381.d.ts | 68 + node_modules/@noble/curves/bls12-381.d.ts.map | 1 + node_modules/@noble/curves/bls12-381.js | 1175 +++ node_modules/@noble/curves/bls12-381.js.map | 1 + node_modules/@noble/curves/bn254.d.ts | 8 + node_modules/@noble/curves/bn254.d.ts.map | 1 + node_modules/@noble/curves/bn254.js | 25 + node_modules/@noble/curves/bn254.js.map | 1 + node_modules/@noble/curves/ed25519.d.ts | 76 + node_modules/@noble/curves/ed25519.d.ts.map | 1 + node_modules/@noble/curves/ed25519.js | 439 + node_modules/@noble/curves/ed25519.js.map | 1 + node_modules/@noble/curves/ed448.d.ts | 65 + node_modules/@noble/curves/ed448.d.ts.map | 1 + node_modules/@noble/curves/ed448.js | 397 + node_modules/@noble/curves/ed448.js.map | 1 + .../@noble/curves/esm/_shortw_utils.js | 17 + .../@noble/curves/esm/_shortw_utils.js.map | 1 + .../@noble/curves/esm/abstract/bls.js | 235 + .../@noble/curves/esm/abstract/bls.js.map | 1 + .../@noble/curves/esm/abstract/curve.js | 156 + .../@noble/curves/esm/abstract/curve.js.map | 1 + .../@noble/curves/esm/abstract/edwards.js | 425 + .../@noble/curves/esm/abstract/edwards.js.map | 1 + .../curves/esm/abstract/hash-to-curve.js | 173 + .../curves/esm/abstract/hash-to-curve.js.map | 1 + .../@noble/curves/esm/abstract/modular.js | 416 + .../@noble/curves/esm/abstract/modular.js.map | 1 + .../@noble/curves/esm/abstract/montgomery.js | 157 + .../curves/esm/abstract/montgomery.js.map | 1 + .../@noble/curves/esm/abstract/poseidon.js | 108 + .../curves/esm/abstract/poseidon.js.map | 1 + .../@noble/curves/esm/abstract/utils.js | 266 + .../@noble/curves/esm/abstract/utils.js.map | 1 + .../@noble/curves/esm/abstract/weierstrass.js | 1056 ++ .../curves/esm/abstract/weierstrass.js.map | 1 + node_modules/@noble/curves/esm/bls12-381.js | 1172 +++ .../@noble/curves/esm/bls12-381.js.map | 1 + node_modules/@noble/curves/esm/bn254.js | 22 + node_modules/@noble/curves/esm/bn254.js.map | 1 + node_modules/@noble/curves/esm/ed25519.js | 433 + node_modules/@noble/curves/esm/ed25519.js.map | 1 + node_modules/@noble/curves/esm/ed448.js | 392 + node_modules/@noble/curves/esm/ed448.js.map | 1 + node_modules/@noble/curves/esm/index.js | 3 + node_modules/@noble/curves/esm/index.js.map | 1 + node_modules/@noble/curves/esm/jubjub.js | 54 + node_modules/@noble/curves/esm/jubjub.js.map | 1 + node_modules/@noble/curves/esm/p256.js | 42 + node_modules/@noble/curves/esm/p256.js.map | 1 + node_modules/@noble/curves/esm/p384.js | 46 + node_modules/@noble/curves/esm/p384.js.map | 1 + node_modules/@noble/curves/esm/p521.js | 53 + node_modules/@noble/curves/esm/p521.js.map | 1 + node_modules/@noble/curves/esm/package.json | 4 + node_modules/@noble/curves/esm/pasta.js | 30 + node_modules/@noble/curves/esm/pasta.js.map | 1 + node_modules/@noble/curves/esm/secp256k1.js | 254 + .../@noble/curves/esm/secp256k1.js.map | 1 + node_modules/@noble/curves/index.d.ts | 1 + node_modules/@noble/curves/index.d.ts.map | 1 + node_modules/@noble/curves/index.js | 3 + node_modules/@noble/curves/index.js.map | 1 + node_modules/@noble/curves/jubjub.d.ts | 9 + node_modules/@noble/curves/jubjub.d.ts.map | 1 + node_modules/@noble/curves/jubjub.js | 59 + node_modules/@noble/curves/jubjub.js.map | 1 + .../curves/node_modules/@noble/hashes/LICENSE | 21 + .../node_modules/@noble/hashes/README.md | 534 + .../node_modules/@noble/hashes/_assert.d.ts | 22 + .../node_modules/@noble/hashes/_assert.js | 45 + .../node_modules/@noble/hashes/_assert.js.map | 1 + .../node_modules/@noble/hashes/_blake2.d.ts | 27 + .../node_modules/@noble/hashes/_blake2.js | 112 + .../node_modules/@noble/hashes/_blake2.js.map | 1 + .../node_modules/@noble/hashes/_sha2.d.ts | 23 + .../node_modules/@noble/hashes/_sha2.js | 118 + .../node_modules/@noble/hashes/_sha2.js.map | 1 + .../node_modules/@noble/hashes/_u64.d.ts | 54 + .../curves/node_modules/@noble/hashes/_u64.js | 85 + .../node_modules/@noble/hashes/_u64.js.map | 1 + .../node_modules/@noble/hashes/argon2.d.ts | 16 + .../node_modules/@noble/hashes/argon2.js | 303 + .../node_modules/@noble/hashes/argon2.js.map | 1 + .../node_modules/@noble/hashes/blake2b.d.ts | 53 + .../node_modules/@noble/hashes/blake2b.js | 192 + .../node_modules/@noble/hashes/blake2b.js.map | 1 + .../node_modules/@noble/hashes/blake2s.d.ts | 47 + .../node_modules/@noble/hashes/blake2s.js | 122 + .../node_modules/@noble/hashes/blake2s.js.map | 1 + .../node_modules/@noble/hashes/blake3.d.ts | 46 + .../node_modules/@noble/hashes/blake3.js | 229 + .../node_modules/@noble/hashes/blake3.js.map | 1 + .../node_modules/@noble/hashes/crypto.d.ts | 1 + .../node_modules/@noble/hashes/crypto.js | 5 + .../node_modules/@noble/hashes/crypto.js.map | 1 + .../@noble/hashes/cryptoNode.d.ts | 1 + .../node_modules/@noble/hashes/cryptoNode.js | 10 + .../@noble/hashes/cryptoNode.js.map | 1 + .../node_modules/@noble/hashes/eskdf.d.ts | 46 + .../node_modules/@noble/hashes/eskdf.js | 162 + .../node_modules/@noble/hashes/eskdf.js.map | 1 + .../node_modules/@noble/hashes/esm/_assert.js | 37 + .../@noble/hashes/esm/_assert.js.map | 1 + .../node_modules/@noble/hashes/esm/_blake2.js | 108 + .../@noble/hashes/esm/_blake2.js.map | 1 + .../node_modules/@noble/hashes/esm/_sha2.js | 114 + .../@noble/hashes/esm/_sha2.js.map | 1 + .../node_modules/@noble/hashes/esm/_u64.js | 62 + .../@noble/hashes/esm/_u64.js.map | 1 + .../node_modules/@noble/hashes/esm/argon2.js | 297 + .../@noble/hashes/esm/argon2.js.map | 1 + .../node_modules/@noble/hashes/esm/blake2b.js | 189 + .../@noble/hashes/esm/blake2b.js.map | 1 + .../node_modules/@noble/hashes/esm/blake2s.js | 118 + .../@noble/hashes/esm/blake2s.js.map | 1 + .../node_modules/@noble/hashes/esm/blake3.js | 226 + .../@noble/hashes/esm/blake3.js.map | 1 + .../node_modules/@noble/hashes/esm/crypto.js | 2 + .../@noble/hashes/esm/crypto.js.map | 1 + .../@noble/hashes/esm/cryptoNode.js | 7 + .../@noble/hashes/esm/cryptoNode.js.map | 1 + .../node_modules/@noble/hashes/esm/eskdf.js | 155 + .../@noble/hashes/esm/eskdf.js.map | 1 + .../node_modules/@noble/hashes/esm/hkdf.js | 72 + .../@noble/hashes/esm/hkdf.js.map | 1 + .../node_modules/@noble/hashes/esm/hmac.js | 77 + .../@noble/hashes/esm/hmac.js.map | 1 + .../node_modules/@noble/hashes/esm/index.js | 3 + .../@noble/hashes/esm/index.js.map | 1 + .../@noble/hashes/esm/package.json | 10 + .../node_modules/@noble/hashes/esm/pbkdf2.js | 86 + .../@noble/hashes/esm/pbkdf2.js.map | 1 + .../@noble/hashes/esm/ripemd160.js | 104 + .../@noble/hashes/esm/ripemd160.js.map | 1 + .../node_modules/@noble/hashes/esm/scrypt.js | 218 + .../@noble/hashes/esm/scrypt.js.map | 1 + .../node_modules/@noble/hashes/esm/sha1.js | 87 + .../@noble/hashes/esm/sha1.js.map | 1 + .../node_modules/@noble/hashes/esm/sha256.js | 126 + .../@noble/hashes/esm/sha256.js.map | 1 + .../@noble/hashes/esm/sha3-addons.js | 347 + .../@noble/hashes/esm/sha3-addons.js.map | 1 + .../node_modules/@noble/hashes/esm/sha3.js | 208 + .../@noble/hashes/esm/sha3.js.map | 1 + .../node_modules/@noble/hashes/esm/sha512.js | 231 + .../@noble/hashes/esm/sha512.js.map | 1 + .../node_modules/@noble/hashes/esm/utils.js | 154 + .../@noble/hashes/esm/utils.js.map | 1 + .../node_modules/@noble/hashes/hkdf.d.ts | 26 + .../curves/node_modules/@noble/hashes/hkdf.js | 78 + .../node_modules/@noble/hashes/hkdf.js.map | 1 + .../node_modules/@noble/hashes/hmac.d.ts | 25 + .../curves/node_modules/@noble/hashes/hmac.js | 82 + .../node_modules/@noble/hashes/hmac.js.map | 1 + .../node_modules/@noble/hashes/index.d.ts | 0 .../node_modules/@noble/hashes/index.js | 3 + .../node_modules/@noble/hashes/index.js.map | 1 + .../node_modules/@noble/hashes/package.json | 174 + .../node_modules/@noble/hashes/pbkdf2.d.ts | 15 + .../node_modules/@noble/hashes/pbkdf2.js | 91 + .../node_modules/@noble/hashes/pbkdf2.js.map | 1 + .../node_modules/@noble/hashes/ripemd160.d.ts | 24 + .../node_modules/@noble/hashes/ripemd160.js | 108 + .../@noble/hashes/ripemd160.js.map | 1 + .../node_modules/@noble/hashes/scrypt.d.ts | 29 + .../node_modules/@noble/hashes/scrypt.js | 223 + .../node_modules/@noble/hashes/scrypt.js.map | 1 + .../node_modules/@noble/hashes/sha1.d.ts | 21 + .../curves/node_modules/@noble/hashes/sha1.js | 90 + .../node_modules/@noble/hashes/sha1.js.map | 1 + .../node_modules/@noble/hashes/sha256.d.ts | 34 + .../node_modules/@noble/hashes/sha256.js | 129 + .../node_modules/@noble/hashes/sha256.js.map | 1 + .../@noble/hashes/sha3-addons.d.ts | 138 + .../node_modules/@noble/hashes/sha3-addons.js | 351 + .../@noble/hashes/sha3-addons.js.map | 1 + .../node_modules/@noble/hashes/sha3.d.ts | 97 + .../curves/node_modules/@noble/hashes/sha3.js | 213 + .../node_modules/@noble/hashes/sha3.js.map | 1 + .../node_modules/@noble/hashes/sha512.d.ts | 66 + .../node_modules/@noble/hashes/sha512.js | 235 + .../node_modules/@noble/hashes/sha512.js.map | 1 + .../node_modules/@noble/hashes/src/_assert.ts | 43 + .../node_modules/@noble/hashes/src/_blake2.ts | 128 + .../node_modules/@noble/hashes/src/_sha2.ts | 118 + .../node_modules/@noble/hashes/src/_u64.ts | 77 + .../node_modules/@noble/hashes/src/argon2.ts | 374 + .../node_modules/@noble/hashes/src/blake2b.ts | 205 + .../node_modules/@noble/hashes/src/blake2s.ts | 136 + .../node_modules/@noble/hashes/src/blake3.ts | 250 + .../node_modules/@noble/hashes/src/crypto.ts | 5 + .../@noble/hashes/src/cryptoNode.ts | 7 + .../node_modules/@noble/hashes/src/eskdf.ts | 183 + .../node_modules/@noble/hashes/src/hkdf.ts | 79 + .../node_modules/@noble/hashes/src/hmac.ts | 81 + .../node_modules/@noble/hashes/src/index.ts | 1 + .../node_modules/@noble/hashes/src/pbkdf2.ts | 97 + .../@noble/hashes/src/ripemd160.ts | 110 + .../node_modules/@noble/hashes/src/scrypt.ts | 240 + .../node_modules/@noble/hashes/src/sha1.ts | 88 + .../node_modules/@noble/hashes/src/sha256.ts | 133 + .../@noble/hashes/src/sha3-addons.ts | 398 + .../node_modules/@noble/hashes/src/sha3.ts | 223 + .../node_modules/@noble/hashes/src/sha512.ts | 246 + .../node_modules/@noble/hashes/src/utils.ts | 215 + .../node_modules/@noble/hashes/utils.d.ts | 90 + .../node_modules/@noble/hashes/utils.js | 174 + .../node_modules/@noble/hashes/utils.js.map | 1 + node_modules/@noble/curves/p256.d.ts | 105 + node_modules/@noble/curves/p256.d.ts.map | 1 + node_modules/@noble/curves/p256.js | 45 + node_modules/@noble/curves/p256.js.map | 1 + node_modules/@noble/curves/p384.d.ts | 105 + node_modules/@noble/curves/p384.d.ts.map | 1 + node_modules/@noble/curves/p384.js | 49 + node_modules/@noble/curves/p384.js.map | 1 + node_modules/@noble/curves/p521.d.ts | 105 + node_modules/@noble/curves/p521.d.ts.map | 1 + node_modules/@noble/curves/p521.js | 56 + node_modules/@noble/curves/p521.js.map | 1 + node_modules/@noble/curves/package.json | 181 + node_modules/@noble/curves/pasta.d.ts | 5 + node_modules/@noble/curves/pasta.d.ts.map | 1 + node_modules/@noble/curves/pasta.js | 33 + node_modules/@noble/curves/pasta.js.map | 1 + node_modules/@noble/curves/secp256k1.d.ts | 93 + node_modules/@noble/curves/secp256k1.d.ts.map | 1 + node_modules/@noble/curves/secp256k1.js | 257 + node_modules/@noble/curves/secp256k1.js.map | 1 + .../@noble/curves/src/_shortw_utils.ts | 20 + .../@noble/curves/src/abstract/bls.ts | 398 + .../@noble/curves/src/abstract/curve.ts | 203 + .../@noble/curves/src/abstract/edwards.ts | 513 + .../curves/src/abstract/hash-to-curve.ts | 229 + .../@noble/curves/src/abstract/modular.ts | 484 + .../@noble/curves/src/abstract/montgomery.ts | 189 + .../@noble/curves/src/abstract/poseidon.ts | 118 + .../@noble/curves/src/abstract/utils.ts | 290 + .../@noble/curves/src/abstract/weierstrass.ts | 1222 +++ node_modules/@noble/curves/src/bls12-381.ts | 1350 +++ node_modules/@noble/curves/src/bn254.ts | 21 + node_modules/@noble/curves/src/ed25519.ts | 489 + node_modules/@noble/curves/src/ed448.ts | 465 + node_modules/@noble/curves/src/index.ts | 1 + node_modules/@noble/curves/src/jubjub.ts | 58 + node_modules/@noble/curves/src/p256.ts | 48 + node_modules/@noble/curves/src/p384.ts | 52 + node_modules/@noble/curves/src/p521.ts | 68 + node_modules/@noble/curves/src/pasta.ts | 31 + node_modules/@noble/curves/src/secp256k1.ts | 274 + node_modules/@noble/hashes/LICENSE | 21 + node_modules/@noble/hashes/README.md | 536 + node_modules/@noble/hashes/_assert.d.ts | 21 + node_modules/@noble/hashes/_assert.js | 52 + node_modules/@noble/hashes/_assert.js.map | 1 + node_modules/@noble/hashes/_blake2.d.ts | 27 + node_modules/@noble/hashes/_blake2.js | 111 + node_modules/@noble/hashes/_blake2.js.map | 1 + node_modules/@noble/hashes/_sha2.d.ts | 23 + node_modules/@noble/hashes/_sha2.js | 118 + node_modules/@noble/hashes/_sha2.js.map | 1 + node_modules/@noble/hashes/_u64.d.ts | 35 + node_modules/@noble/hashes/_u64.js | 68 + node_modules/@noble/hashes/_u64.js.map | 1 + node_modules/@noble/hashes/argon2.d.ts | 16 + node_modules/@noble/hashes/argon2.js | 310 + node_modules/@noble/hashes/argon2.js.map | 1 + node_modules/@noble/hashes/blake2b.d.ts | 53 + node_modules/@noble/hashes/blake2b.js | 192 + node_modules/@noble/hashes/blake2b.js.map | 1 + node_modules/@noble/hashes/blake2s.d.ts | 47 + node_modules/@noble/hashes/blake2s.js | 124 + node_modules/@noble/hashes/blake2s.js.map | 1 + node_modules/@noble/hashes/blake3.d.ts | 46 + node_modules/@noble/hashes/blake3.js | 240 + node_modules/@noble/hashes/blake3.js.map | 1 + node_modules/@noble/hashes/crypto.d.ts | 1 + node_modules/@noble/hashes/crypto.js | 5 + node_modules/@noble/hashes/crypto.js.map | 1 + node_modules/@noble/hashes/cryptoNode.d.ts | 1 + node_modules/@noble/hashes/cryptoNode.js | 10 + node_modules/@noble/hashes/cryptoNode.js.map | 1 + node_modules/@noble/hashes/eskdf.d.ts | 46 + node_modules/@noble/hashes/eskdf.js | 162 + node_modules/@noble/hashes/eskdf.js.map | 1 + node_modules/@noble/hashes/esm/_assert.js | 43 + node_modules/@noble/hashes/esm/_assert.js.map | 1 + node_modules/@noble/hashes/esm/_blake2.js | 107 + node_modules/@noble/hashes/esm/_blake2.js.map | 1 + node_modules/@noble/hashes/esm/_sha2.js | 114 + node_modules/@noble/hashes/esm/_sha2.js.map | 1 + node_modules/@noble/hashes/esm/_u64.js | 61 + node_modules/@noble/hashes/esm/_u64.js.map | 1 + node_modules/@noble/hashes/esm/argon2.js | 304 + node_modules/@noble/hashes/esm/argon2.js.map | 1 + node_modules/@noble/hashes/esm/blake2b.js | 189 + node_modules/@noble/hashes/esm/blake2b.js.map | 1 + node_modules/@noble/hashes/esm/blake2s.js | 120 + node_modules/@noble/hashes/esm/blake2s.js.map | 1 + node_modules/@noble/hashes/esm/blake3.js | 237 + node_modules/@noble/hashes/esm/blake3.js.map | 1 + node_modules/@noble/hashes/esm/crypto.js | 2 + node_modules/@noble/hashes/esm/crypto.js.map | 1 + node_modules/@noble/hashes/esm/cryptoNode.js | 7 + .../@noble/hashes/esm/cryptoNode.js.map | 1 + node_modules/@noble/hashes/esm/eskdf.js | 155 + node_modules/@noble/hashes/esm/eskdf.js.map | 1 + node_modules/@noble/hashes/esm/hkdf.js | 72 + node_modules/@noble/hashes/esm/hkdf.js.map | 1 + node_modules/@noble/hashes/esm/hmac.js | 77 + node_modules/@noble/hashes/esm/hmac.js.map | 1 + node_modules/@noble/hashes/esm/index.js | 3 + node_modules/@noble/hashes/esm/index.js.map | 1 + node_modules/@noble/hashes/esm/package.json | 9 + node_modules/@noble/hashes/esm/pbkdf2.js | 86 + node_modules/@noble/hashes/esm/pbkdf2.js.map | 1 + node_modules/@noble/hashes/esm/ripemd160.js | 100 + .../@noble/hashes/esm/ripemd160.js.map | 1 + node_modules/@noble/hashes/esm/scrypt.js | 218 + node_modules/@noble/hashes/esm/scrypt.js.map | 1 + node_modules/@noble/hashes/esm/sha1.js | 85 + node_modules/@noble/hashes/esm/sha1.js.map | 1 + node_modules/@noble/hashes/esm/sha256.js | 124 + node_modules/@noble/hashes/esm/sha256.js.map | 1 + node_modules/@noble/hashes/esm/sha3-addons.js | 347 + .../@noble/hashes/esm/sha3-addons.js.map | 1 + node_modules/@noble/hashes/esm/sha3.js | 206 + node_modules/@noble/hashes/esm/sha3.js.map | 1 + node_modules/@noble/hashes/esm/sha512.js | 231 + node_modules/@noble/hashes/esm/sha512.js.map | 1 + node_modules/@noble/hashes/esm/utils.js | 155 + node_modules/@noble/hashes/esm/utils.js.map | 1 + node_modules/@noble/hashes/hkdf.d.ts | 26 + node_modules/@noble/hashes/hkdf.js | 78 + node_modules/@noble/hashes/hkdf.js.map | 1 + node_modules/@noble/hashes/hmac.d.ts | 25 + node_modules/@noble/hashes/hmac.js | 82 + node_modules/@noble/hashes/hmac.js.map | 1 + node_modules/@noble/hashes/index.d.ts | 0 node_modules/@noble/hashes/index.js | 3 + node_modules/@noble/hashes/index.js.map | 1 + node_modules/@noble/hashes/package.json | 173 + node_modules/@noble/hashes/pbkdf2.d.ts | 15 + node_modules/@noble/hashes/pbkdf2.js | 91 + node_modules/@noble/hashes/pbkdf2.js.map | 1 + node_modules/@noble/hashes/ripemd160.d.ts | 24 + node_modules/@noble/hashes/ripemd160.js | 104 + node_modules/@noble/hashes/ripemd160.js.map | 1 + node_modules/@noble/hashes/scrypt.d.ts | 29 + node_modules/@noble/hashes/scrypt.js | 223 + node_modules/@noble/hashes/scrypt.js.map | 1 + node_modules/@noble/hashes/sha1.d.ts | 21 + node_modules/@noble/hashes/sha1.js | 88 + node_modules/@noble/hashes/sha1.js.map | 1 + node_modules/@noble/hashes/sha256.d.ts | 34 + node_modules/@noble/hashes/sha256.js | 127 + node_modules/@noble/hashes/sha256.js.map | 1 + node_modules/@noble/hashes/sha3-addons.d.ts | 138 + node_modules/@noble/hashes/sha3-addons.js | 351 + node_modules/@noble/hashes/sha3-addons.js.map | 1 + node_modules/@noble/hashes/sha3.d.ts | 97 + node_modules/@noble/hashes/sha3.js | 211 + node_modules/@noble/hashes/sha3.js.map | 1 + node_modules/@noble/hashes/sha512.d.ts | 66 + node_modules/@noble/hashes/sha512.js | 235 + node_modules/@noble/hashes/sha512.js.map | 1 + node_modules/@noble/hashes/src/_assert.ts | 49 + node_modules/@noble/hashes/src/_blake2.ts | 125 + node_modules/@noble/hashes/src/_sha2.ts | 118 + node_modules/@noble/hashes/src/_u64.ts | 69 + node_modules/@noble/hashes/src/argon2.ts | 374 + node_modules/@noble/hashes/src/blake2b.ts | 203 + node_modules/@noble/hashes/src/blake2s.ts | 136 + node_modules/@noble/hashes/src/blake3.ts | 246 + node_modules/@noble/hashes/src/crypto.ts | 5 + node_modules/@noble/hashes/src/cryptoNode.ts | 7 + node_modules/@noble/hashes/src/eskdf.ts | 183 + node_modules/@noble/hashes/src/hkdf.ts | 79 + node_modules/@noble/hashes/src/hmac.ts | 81 + node_modules/@noble/hashes/src/index.ts | 1 + node_modules/@noble/hashes/src/pbkdf2.ts | 97 + node_modules/@noble/hashes/src/ripemd160.ts | 108 + node_modules/@noble/hashes/src/scrypt.ts | 240 + node_modules/@noble/hashes/src/sha1.ts | 86 + node_modules/@noble/hashes/src/sha256.ts | 130 + node_modules/@noble/hashes/src/sha3-addons.ts | 398 + node_modules/@noble/hashes/src/sha3.ts | 222 + node_modules/@noble/hashes/src/sha512.ts | 247 + node_modules/@noble/hashes/src/utils.ts | 216 + node_modules/@noble/hashes/utils.d.ts | 90 + node_modules/@noble/hashes/utils.js | 175 + node_modules/@noble/hashes/utils.js.map | 1 + node_modules/@scure/base/LICENSE | 21 + node_modules/@scure/base/README.md | 147 + node_modules/@scure/base/lib/esm/index.js | 394 + node_modules/@scure/base/lib/esm/package.json | 1 + node_modules/@scure/base/lib/index.d.ts | 92 + node_modules/@scure/base/lib/index.js | 401 + node_modules/@scure/base/package.json | 60 + node_modules/@scure/bip32/LICENSE | 21 + node_modules/@scure/bip32/README.md | 107 + node_modules/@scure/bip32/index.ts | 307 + node_modules/@scure/bip32/lib/esm/index.js | 257 + .../@scure/bip32/lib/esm/index.js.map | 1 + .../@scure/bip32/lib/esm/package.json | 6 + node_modules/@scure/bip32/lib/index.d.ts | 49 + node_modules/@scure/bip32/lib/index.js | 261 + node_modules/@scure/bip32/lib/index.js.map | 1 + .../bip32/node_modules/@noble/curves/LICENSE | 21 + .../node_modules/@noble/curves/README.md | 971 ++ .../@noble/curves/_shortw_utils.d.ts | 62 + .../@noble/curves/_shortw_utils.d.ts.map | 1 + .../@noble/curves/_shortw_utils.js | 22 + .../@noble/curves/_shortw_utils.js.map | 1 + .../@noble/curves/abstract/bls.d.ts | 103 + .../@noble/curves/abstract/bls.d.ts.map | 1 + .../@noble/curves/abstract/bls.js | 239 + .../@noble/curves/abstract/bls.js.map | 1 + .../@noble/curves/abstract/curve.d.ts | 70 + .../@noble/curves/abstract/curve.d.ts.map | 1 + .../@noble/curves/abstract/curve.js | 161 + .../@noble/curves/abstract/curve.js.map | 1 + .../@noble/curves/abstract/edwards.d.ts | 89 + .../@noble/curves/abstract/edwards.d.ts.map | 1 + .../@noble/curves/abstract/edwards.js | 429 + .../@noble/curves/abstract/edwards.js.map | 1 + .../@noble/curves/abstract/hash-to-curve.d.ts | 57 + .../curves/abstract/hash-to-curve.d.ts.map | 1 + .../@noble/curves/abstract/hash-to-curve.js | 175 + .../curves/abstract/hash-to-curve.js.map | 1 + .../@noble/curves/abstract/modular.d.ts | 83 + .../@noble/curves/abstract/modular.d.ts.map | 1 + .../@noble/curves/abstract/modular.js | 381 + .../@noble/curves/abstract/modular.js.map | 1 + .../@noble/curves/abstract/montgomery.d.ts | 26 + .../curves/abstract/montgomery.d.ts.map | 1 + .../@noble/curves/abstract/montgomery.js | 161 + .../@noble/curves/abstract/montgomery.js.map | 1 + .../@noble/curves/abstract/poseidon.d.ts | 30 + .../@noble/curves/abstract/poseidon.d.ts.map | 1 + .../@noble/curves/abstract/poseidon.js | 116 + .../@noble/curves/abstract/poseidon.js.map | 1 + .../@noble/curves/abstract/utils.d.ts | 91 + .../@noble/curves/abstract/utils.d.ts.map | 1 + .../@noble/curves/abstract/utils.js | 287 + .../@noble/curves/abstract/utils.js.map | 1 + .../@noble/curves/abstract/weierstrass.d.ts | 240 + .../curves/abstract/weierstrass.d.ts.map | 1 + .../@noble/curves/abstract/weierstrass.js | 1061 ++ .../@noble/curves/abstract/weierstrass.js.map | 1 + .../node_modules/@noble/curves/bls12-381.d.ts | 68 + .../@noble/curves/bls12-381.d.ts.map | 1 + .../node_modules/@noble/curves/bls12-381.js | 1176 +++ .../@noble/curves/bls12-381.js.map | 1 + .../node_modules/@noble/curves/bn254.d.ts | 8 + .../node_modules/@noble/curves/bn254.d.ts.map | 1 + .../bip32/node_modules/@noble/curves/bn254.js | 25 + .../node_modules/@noble/curves/bn254.js.map | 1 + .../node_modules/@noble/curves/ed25519.d.ts | 75 + .../@noble/curves/ed25519.d.ts.map | 1 + .../node_modules/@noble/curves/ed25519.js | 436 + .../node_modules/@noble/curves/ed25519.js.map | 1 + .../node_modules/@noble/curves/ed448.d.ts | 16 + .../node_modules/@noble/curves/ed448.d.ts.map | 1 + .../bip32/node_modules/@noble/curves/ed448.js | 219 + .../node_modules/@noble/curves/ed448.js.map | 1 + .../@noble/curves/esm/_shortw_utils.js | 17 + .../@noble/curves/esm/_shortw_utils.js.map | 1 + .../@noble/curves/esm/abstract/bls.js | 235 + .../@noble/curves/esm/abstract/bls.js.map | 1 + .../@noble/curves/esm/abstract/curve.js | 156 + .../@noble/curves/esm/abstract/curve.js.map | 1 + .../@noble/curves/esm/abstract/edwards.js | 425 + .../@noble/curves/esm/abstract/edwards.js.map | 1 + .../curves/esm/abstract/hash-to-curve.js | 167 + .../curves/esm/abstract/hash-to-curve.js.map | 1 + .../@noble/curves/esm/abstract/modular.js | 361 + .../@noble/curves/esm/abstract/modular.js.map | 1 + .../@noble/curves/esm/abstract/montgomery.js | 157 + .../curves/esm/abstract/montgomery.js.map | 1 + .../@noble/curves/esm/abstract/poseidon.js | 110 + .../curves/esm/abstract/poseidon.js.map | 1 + .../@noble/curves/esm/abstract/utils.js | 265 + .../@noble/curves/esm/abstract/utils.js.map | 1 + .../@noble/curves/esm/abstract/weierstrass.js | 1054 ++ .../curves/esm/abstract/weierstrass.js.map | 1 + .../@noble/curves/esm/bls12-381.js | 1173 +++ .../@noble/curves/esm/bls12-381.js.map | 1 + .../node_modules/@noble/curves/esm/bn254.js | 22 + .../@noble/curves/esm/bn254.js.map | 1 + .../node_modules/@noble/curves/esm/ed25519.js | 430 + .../@noble/curves/esm/ed25519.js.map | 1 + .../node_modules/@noble/curves/esm/ed448.js | 215 + .../@noble/curves/esm/ed448.js.map | 1 + .../node_modules/@noble/curves/esm/index.js | 3 + .../@noble/curves/esm/index.js.map | 1 + .../node_modules/@noble/curves/esm/jubjub.js | 54 + .../@noble/curves/esm/jubjub.js.map | 1 + .../node_modules/@noble/curves/esm/p256.js | 42 + .../@noble/curves/esm/p256.js.map | 1 + .../node_modules/@noble/curves/esm/p384.js | 46 + .../@noble/curves/esm/p384.js.map | 1 + .../node_modules/@noble/curves/esm/p521.js | 53 + .../@noble/curves/esm/p521.js.map | 1 + .../@noble/curves/esm/package.json | 7 + .../node_modules/@noble/curves/esm/pasta.js | 30 + .../@noble/curves/esm/pasta.js.map | 1 + .../@noble/curves/esm/secp256k1.js | 254 + .../@noble/curves/esm/secp256k1.js.map | 1 + .../node_modules/@noble/curves/index.d.ts | 1 + .../node_modules/@noble/curves/index.d.ts.map | 1 + .../bip32/node_modules/@noble/curves/index.js | 3 + .../node_modules/@noble/curves/index.js.map | 1 + .../node_modules/@noble/curves/jubjub.d.ts | 9 + .../@noble/curves/jubjub.d.ts.map | 1 + .../node_modules/@noble/curves/jubjub.js | 59 + .../node_modules/@noble/curves/jubjub.js.map | 1 + .../node_modules/@noble/curves/p256.d.ts | 105 + .../node_modules/@noble/curves/p256.d.ts.map | 1 + .../bip32/node_modules/@noble/curves/p256.js | 45 + .../node_modules/@noble/curves/p256.js.map | 1 + .../node_modules/@noble/curves/p384.d.ts | 105 + .../node_modules/@noble/curves/p384.d.ts.map | 1 + .../bip32/node_modules/@noble/curves/p384.js | 49 + .../node_modules/@noble/curves/p384.js.map | 1 + .../node_modules/@noble/curves/p521.d.ts | 105 + .../node_modules/@noble/curves/p521.d.ts.map | 1 + .../bip32/node_modules/@noble/curves/p521.js | 56 + .../node_modules/@noble/curves/p521.js.map | 1 + .../node_modules/@noble/curves/package.json | 180 + .../node_modules/@noble/curves/pasta.d.ts | 5 + .../node_modules/@noble/curves/pasta.d.ts.map | 1 + .../bip32/node_modules/@noble/curves/pasta.js | 33 + .../node_modules/@noble/curves/pasta.js.map | 1 + .../node_modules/@noble/curves/secp256k1.d.ts | 93 + .../@noble/curves/secp256k1.d.ts.map | 1 + .../node_modules/@noble/curves/secp256k1.js | 257 + .../@noble/curves/secp256k1.js.map | 1 + .../@noble/curves/src/_shortw_utils.ts | 20 + .../@noble/curves/src/abstract/bls.ts | 398 + .../@noble/curves/src/abstract/curve.ts | 203 + .../@noble/curves/src/abstract/edwards.ts | 513 + .../curves/src/abstract/hash-to-curve.ts | 223 + .../@noble/curves/src/abstract/modular.ts | 425 + .../@noble/curves/src/abstract/montgomery.ts | 189 + .../@noble/curves/src/abstract/poseidon.ts | 119 + .../@noble/curves/src/abstract/utils.ts | 287 + .../@noble/curves/src/abstract/weierstrass.ts | 1220 +++ .../@noble/curves/src/bls12-381.ts | 1351 +++ .../node_modules/@noble/curves/src/bn254.ts | 21 + .../node_modules/@noble/curves/src/ed25519.ts | 486 + .../node_modules/@noble/curves/src/ed448.ts | 247 + .../node_modules/@noble/curves/src/index.ts | 1 + .../node_modules/@noble/curves/src/jubjub.ts | 58 + .../node_modules/@noble/curves/src/p256.ts | 48 + .../node_modules/@noble/curves/src/p384.ts | 52 + .../node_modules/@noble/curves/src/p521.ts | 68 + .../node_modules/@noble/curves/src/pasta.ts | 31 + .../@noble/curves/src/secp256k1.ts | 274 + node_modules/@scure/bip32/package.json | 72 + node_modules/@scure/bip39/LICENSE | 21 + node_modules/@scure/bip39/README.md | 97 + node_modules/@scure/bip39/esm/index.js | 69 + node_modules/@scure/bip39/esm/index.js.map | 1 + node_modules/@scure/bip39/esm/package.json | 3 + .../@scure/bip39/esm/wordlists/czech.js | 2049 ++++ .../@scure/bip39/esm/wordlists/czech.js.map | 1 + .../@scure/bip39/esm/wordlists/english.js | 2049 ++++ .../@scure/bip39/esm/wordlists/english.js.map | 1 + .../@scure/bip39/esm/wordlists/french.js | 2049 ++++ .../@scure/bip39/esm/wordlists/french.js.map | 1 + .../@scure/bip39/esm/wordlists/italian.js | 2049 ++++ .../@scure/bip39/esm/wordlists/italian.js.map | 1 + .../@scure/bip39/esm/wordlists/japanese.js | 2049 ++++ .../bip39/esm/wordlists/japanese.js.map | 1 + .../@scure/bip39/esm/wordlists/korean.js | 2049 ++++ .../@scure/bip39/esm/wordlists/korean.js.map | 1 + .../bip39/esm/wordlists/simplified-chinese.js | 2049 ++++ .../esm/wordlists/simplified-chinese.js.map | 1 + .../@scure/bip39/esm/wordlists/spanish.js | 2049 ++++ .../@scure/bip39/esm/wordlists/spanish.js.map | 1 + .../esm/wordlists/traditional-chinese.js | 2049 ++++ .../esm/wordlists/traditional-chinese.js.map | 1 + node_modules/@scure/bip39/index.d.ts | 63 + node_modules/@scure/bip39/index.js | 142 + node_modules/@scure/bip39/package.json | 116 + .../@scure/bip39/wordlists/czech.d.ts | 1 + node_modules/@scure/bip39/wordlists/czech.js | 2051 ++++ .../@scure/bip39/wordlists/english.d.ts | 1 + .../@scure/bip39/wordlists/english.js | 2051 ++++ .../@scure/bip39/wordlists/french.d.ts | 1 + node_modules/@scure/bip39/wordlists/french.js | 2051 ++++ .../@scure/bip39/wordlists/italian.d.ts | 1 + .../@scure/bip39/wordlists/italian.js | 2051 ++++ .../@scure/bip39/wordlists/japanese.d.ts | 1 + .../@scure/bip39/wordlists/japanese.js | 2051 ++++ .../@scure/bip39/wordlists/korean.d.ts | 1 + node_modules/@scure/bip39/wordlists/korean.js | 2051 ++++ .../bip39/wordlists/simplified-chinese.d.ts | 1 + .../bip39/wordlists/simplified-chinese.js | 2051 ++++ .../@scure/bip39/wordlists/spanish.d.ts | 1 + .../@scure/bip39/wordlists/spanish.js | 2051 ++++ .../bip39/wordlists/traditional-chinese.d.ts | 1 + .../bip39/wordlists/traditional-chinese.js | 2051 ++++ node_modules/accepts/HISTORY.md | 250 + node_modules/accepts/LICENSE | 23 + node_modules/accepts/README.md | 140 + node_modules/accepts/index.js | 238 + node_modules/accepts/package.json | 47 + node_modules/async/CHANGELOG.md | 351 + node_modules/async/LICENSE | 19 + node_modules/async/README.md | 59 + node_modules/async/all.js | 119 + node_modules/async/allLimit.js | 46 + node_modules/async/allSeries.js | 45 + node_modules/async/any.js | 122 + node_modules/async/anyLimit.js | 47 + node_modules/async/anySeries.js | 46 + node_modules/async/apply.js | 11 + node_modules/async/applyEach.js | 57 + node_modules/async/applyEachSeries.js | 37 + node_modules/async/asyncify.js | 118 + node_modules/async/auto.js | 333 + node_modules/async/autoInject.js | 182 + node_modules/async/bower.json | 17 + node_modules/async/cargo.js | 63 + node_modules/async/cargoQueue.js | 71 + node_modules/async/compose.js | 55 + node_modules/async/concat.js | 115 + node_modules/async/concatLimit.js | 60 + node_modules/async/concatSeries.js | 41 + node_modules/async/constant.js | 14 + node_modules/async/detect.js | 96 + node_modules/async/detectLimit.js | 48 + node_modules/async/detectSeries.js | 47 + node_modules/async/dir.js | 43 + node_modules/async/dist/async.js | 6061 +++++++++++ node_modules/async/dist/async.min.js | 1 + node_modules/async/dist/async.mjs | 5948 +++++++++++ node_modules/async/doDuring.js | 68 + node_modules/async/doUntil.js | 46 + node_modules/async/doWhilst.js | 68 + node_modules/async/during.js | 78 + node_modules/async/each.js | 129 + node_modules/async/eachLimit.js | 50 + node_modules/async/eachOf.js | 185 + node_modules/async/eachOfLimit.js | 47 + node_modules/async/eachOfSeries.js | 39 + node_modules/async/eachSeries.js | 44 + node_modules/async/ensureAsync.js | 67 + node_modules/async/every.js | 119 + node_modules/async/everyLimit.js | 46 + node_modules/async/everySeries.js | 45 + node_modules/async/filter.js | 93 + node_modules/async/filterLimit.js | 45 + node_modules/async/filterSeries.js | 43 + node_modules/async/find.js | 96 + node_modules/async/findLimit.js | 48 + node_modules/async/findSeries.js | 47 + node_modules/async/flatMap.js | 115 + node_modules/async/flatMapLimit.js | 60 + node_modules/async/flatMapSeries.js | 41 + node_modules/async/foldl.js | 153 + node_modules/async/foldr.js | 41 + node_modules/async/forEach.js | 129 + node_modules/async/forEachLimit.js | 50 + node_modules/async/forEachOf.js | 185 + node_modules/async/forEachOfLimit.js | 47 + node_modules/async/forEachOfSeries.js | 39 + node_modules/async/forEachSeries.js | 44 + node_modules/async/forever.js | 68 + node_modules/async/groupBy.js | 108 + node_modules/async/groupByLimit.js | 71 + node_modules/async/groupBySeries.js | 36 + node_modules/async/index.js | 588 ++ node_modules/async/inject.js | 153 + .../async/internal/DoublyLinkedList.js | 92 + node_modules/async/internal/Heap.js | 120 + node_modules/async/internal/applyEach.js | 29 + .../async/internal/asyncEachOfLimit.js | 75 + node_modules/async/internal/awaitify.js | 28 + node_modules/async/internal/breakLoop.js | 10 + node_modules/async/internal/consoleFunc.js | 31 + node_modules/async/internal/createTester.js | 40 + node_modules/async/internal/eachOfLimit.js | 90 + node_modules/async/internal/filter.js | 55 + node_modules/async/internal/getIterator.js | 11 + node_modules/async/internal/initialParams.js | 14 + node_modules/async/internal/isArrayLike.js | 10 + node_modules/async/internal/iterator.js | 57 + node_modules/async/internal/map.js | 30 + node_modules/async/internal/once.js | 17 + node_modules/async/internal/onlyOnce.js | 15 + node_modules/async/internal/parallel.js | 34 + .../async/internal/promiseCallback.js | 23 + node_modules/async/internal/queue.js | 294 + node_modules/async/internal/range.js | 14 + node_modules/async/internal/reject.js | 26 + node_modules/async/internal/setImmediate.js | 34 + node_modules/async/internal/withoutIndex.js | 10 + node_modules/async/internal/wrapAsync.js | 34 + node_modules/async/log.js | 41 + node_modules/async/map.js | 142 + node_modules/async/mapLimit.js | 45 + node_modules/async/mapSeries.js | 44 + node_modules/async/mapValues.js | 152 + node_modules/async/mapValuesLimit.js | 61 + node_modules/async/mapValuesSeries.js | 37 + node_modules/async/memoize.js | 91 + node_modules/async/nextTick.js | 52 + node_modules/async/package.json | 75 + node_modules/async/parallel.js | 180 + node_modules/async/parallelLimit.js | 41 + node_modules/async/priorityQueue.js | 60 + node_modules/async/queue.js | 24 + node_modules/async/race.js | 67 + node_modules/async/reduce.js | 153 + node_modules/async/reduceRight.js | 41 + node_modules/async/reflect.js | 78 + node_modules/async/reflectAll.js | 93 + node_modules/async/reject.js | 87 + node_modules/async/rejectLimit.js | 45 + node_modules/async/rejectSeries.js | 43 + node_modules/async/retry.js | 159 + node_modules/async/retryable.js | 77 + node_modules/async/select.js | 93 + node_modules/async/selectLimit.js | 45 + node_modules/async/selectSeries.js | 43 + node_modules/async/seq.js | 79 + node_modules/async/series.js | 186 + node_modules/async/setImmediate.js | 45 + node_modules/async/some.js | 122 + node_modules/async/someLimit.js | 47 + node_modules/async/someSeries.js | 46 + node_modules/async/sortBy.js | 190 + node_modules/async/timeout.js | 89 + node_modules/async/times.js | 50 + node_modules/async/timesLimit.js | 43 + node_modules/async/timesSeries.js | 32 + node_modules/async/transform.js | 173 + node_modules/async/tryEach.js | 78 + node_modules/async/unmemoize.js | 25 + node_modules/async/until.js | 61 + node_modules/async/waterfall.js | 105 + node_modules/async/whilst.js | 78 + node_modules/async/wrapSync.js | 118 + .../balanced-match/.github/FUNDING.yml | 2 + node_modules/balanced-match/LICENSE.md | 21 + node_modules/balanced-match/README.md | 97 + node_modules/balanced-match/index.js | 62 + node_modules/balanced-match/package.json | 48 + node_modules/body-parser/HISTORY.md | 731 ++ node_modules/body-parser/LICENSE | 23 + node_modules/body-parser/README.md | 491 + node_modules/body-parser/index.js | 80 + node_modules/body-parser/lib/read.js | 210 + node_modules/body-parser/lib/types/json.js | 206 + node_modules/body-parser/lib/types/raw.js | 75 + node_modules/body-parser/lib/types/text.js | 80 + .../body-parser/lib/types/urlencoded.js | 177 + node_modules/body-parser/lib/utils.js | 83 + node_modules/body-parser/package.json | 49 + .../brace-expansion/.github/FUNDING.yml | 2 + node_modules/brace-expansion/LICENSE | 21 + node_modules/brace-expansion/README.md | 135 + node_modules/brace-expansion/index.js | 203 + node_modules/brace-expansion/package.json | 49 + .../buffer-equal-constant-time/.npmignore | 2 + .../buffer-equal-constant-time/.travis.yml | 4 + .../buffer-equal-constant-time/LICENSE.txt | 12 + .../buffer-equal-constant-time/README.md | 50 + .../buffer-equal-constant-time/index.js | 41 + .../buffer-equal-constant-time/package.json | 21 + .../buffer-equal-constant-time/test.js | 42 + node_modules/bytes/History.md | 97 + node_modules/bytes/LICENSE | 23 + node_modules/bytes/Readme.md | 152 + node_modules/bytes/index.js | 170 + node_modules/bytes/package.json | 42 + .../call-bind-apply-helpers/.eslintrc | 17 + .../.github/FUNDING.yml | 12 + node_modules/call-bind-apply-helpers/.nycrc | 9 + .../call-bind-apply-helpers/CHANGELOG.md | 30 + node_modules/call-bind-apply-helpers/LICENSE | 21 + .../call-bind-apply-helpers/README.md | 62 + .../call-bind-apply-helpers/actualApply.d.ts | 1 + .../call-bind-apply-helpers/actualApply.js | 10 + .../call-bind-apply-helpers/applyBind.d.ts | 19 + .../call-bind-apply-helpers/applyBind.js | 10 + .../functionApply.d.ts | 1 + .../call-bind-apply-helpers/functionApply.js | 4 + .../call-bind-apply-helpers/functionCall.d.ts | 1 + .../call-bind-apply-helpers/functionCall.js | 4 + .../call-bind-apply-helpers/index.d.ts | 64 + node_modules/call-bind-apply-helpers/index.js | 15 + .../call-bind-apply-helpers/package.json | 85 + .../call-bind-apply-helpers/reflectApply.d.ts | 3 + .../call-bind-apply-helpers/reflectApply.js | 4 + .../call-bind-apply-helpers/test/index.js | 63 + .../call-bind-apply-helpers/tsconfig.json | 9 + node_modules/call-bound/.eslintrc | 13 + node_modules/call-bound/.github/FUNDING.yml | 12 + node_modules/call-bound/.nycrc | 9 + node_modules/call-bound/CHANGELOG.md | 42 + node_modules/call-bound/LICENSE | 21 + node_modules/call-bound/README.md | 53 + node_modules/call-bound/index.d.ts | 94 + node_modules/call-bound/index.js | 19 + node_modules/call-bound/package.json | 99 + node_modules/call-bound/test/index.js | 61 + node_modules/call-bound/tsconfig.json | 10 + node_modules/content-disposition/HISTORY.md | 66 + node_modules/content-disposition/LICENSE | 22 + node_modules/content-disposition/README.md | 142 + node_modules/content-disposition/index.js | 459 + node_modules/content-disposition/package.json | 44 + node_modules/content-type/HISTORY.md | 29 + node_modules/content-type/LICENSE | 22 + node_modules/content-type/README.md | 94 + node_modules/content-type/index.js | 225 + node_modules/content-type/package.json | 42 + node_modules/cookie-signature/History.md | 70 + node_modules/cookie-signature/LICENSE | 22 + node_modules/cookie-signature/Readme.md | 23 + node_modules/cookie-signature/index.js | 47 + node_modules/cookie-signature/package.json | 24 + node_modules/cookie/LICENSE | 24 + node_modules/cookie/README.md | 317 + node_modules/cookie/SECURITY.md | 25 + node_modules/cookie/index.js | 335 + node_modules/cookie/package.json | 44 + node_modules/debug/LICENSE | 20 + node_modules/debug/README.md | 481 + node_modules/debug/package.json | 64 + node_modules/debug/src/browser.js | 272 + node_modules/debug/src/common.js | 292 + node_modules/debug/src/index.js | 10 + node_modules/debug/src/node.js | 263 + node_modules/depd/History.md | 103 + node_modules/depd/LICENSE | 22 + node_modules/depd/Readme.md | 280 + node_modules/depd/index.js | 538 + node_modules/depd/lib/browser/index.js | 77 + node_modules/depd/package.json | 45 + node_modules/dunder-proto/.eslintrc | 5 + node_modules/dunder-proto/.github/FUNDING.yml | 12 + node_modules/dunder-proto/.nycrc | 13 + node_modules/dunder-proto/CHANGELOG.md | 24 + node_modules/dunder-proto/LICENSE | 21 + node_modules/dunder-proto/README.md | 54 + node_modules/dunder-proto/get.d.ts | 5 + node_modules/dunder-proto/get.js | 30 + node_modules/dunder-proto/package.json | 76 + node_modules/dunder-proto/set.d.ts | 5 + node_modules/dunder-proto/set.js | 35 + node_modules/dunder-proto/test/get.js | 34 + node_modules/dunder-proto/test/index.js | 4 + node_modules/dunder-proto/test/set.js | 50 + node_modules/dunder-proto/tsconfig.json | 9 + node_modules/ecdsa-sig-formatter/CODEOWNERS | 1 + node_modules/ecdsa-sig-formatter/LICENSE | 201 + node_modules/ecdsa-sig-formatter/README.md | 65 + node_modules/ecdsa-sig-formatter/package.json | 46 + .../src/ecdsa-sig-formatter.d.ts | 17 + .../src/ecdsa-sig-formatter.js | 187 + .../src/param-bytes-for-alg.js | 23 + node_modules/ee-first/LICENSE | 22 + node_modules/ee-first/README.md | 80 + node_modules/ee-first/index.js | 95 + node_modules/ee-first/package.json | 29 + node_modules/ejs/LICENSE | 202 + node_modules/ejs/README.md | 358 + node_modules/ejs/bin/cli.js | 211 + node_modules/ejs/ejs.js | 1746 +++ node_modules/ejs/ejs.min.js | 1 + node_modules/ejs/jakefile.js | 88 + node_modules/ejs/lib/ejs.js | 952 ++ node_modules/ejs/lib/utils.js | 250 + node_modules/ejs/package.json | 42 + node_modules/ejs/usage.txt | 24 + node_modules/encodeurl/LICENSE | 22 + node_modules/encodeurl/README.md | 109 + node_modules/encodeurl/index.js | 60 + node_modules/encodeurl/package.json | 40 + node_modules/es-define-property/.eslintrc | 13 + .../es-define-property/.github/FUNDING.yml | 12 + node_modules/es-define-property/.nycrc | 9 + node_modules/es-define-property/CHANGELOG.md | 29 + node_modules/es-define-property/LICENSE | 21 + node_modules/es-define-property/README.md | 49 + node_modules/es-define-property/index.d.ts | 3 + node_modules/es-define-property/index.js | 14 + node_modules/es-define-property/package.json | 81 + node_modules/es-define-property/test/index.js | 56 + node_modules/es-define-property/tsconfig.json | 10 + node_modules/es-errors/.eslintrc | 5 + node_modules/es-errors/.github/FUNDING.yml | 12 + node_modules/es-errors/CHANGELOG.md | 40 + node_modules/es-errors/LICENSE | 21 + node_modules/es-errors/README.md | 55 + node_modules/es-errors/eval.d.ts | 3 + node_modules/es-errors/eval.js | 4 + node_modules/es-errors/index.d.ts | 3 + node_modules/es-errors/index.js | 4 + node_modules/es-errors/package.json | 80 + node_modules/es-errors/range.d.ts | 3 + node_modules/es-errors/range.js | 4 + node_modules/es-errors/ref.d.ts | 3 + node_modules/es-errors/ref.js | 4 + node_modules/es-errors/syntax.d.ts | 3 + node_modules/es-errors/syntax.js | 4 + node_modules/es-errors/test/index.js | 19 + node_modules/es-errors/tsconfig.json | 49 + node_modules/es-errors/type.d.ts | 3 + node_modules/es-errors/type.js | 4 + node_modules/es-errors/uri.d.ts | 3 + node_modules/es-errors/uri.js | 4 + node_modules/es-object-atoms/.eslintrc | 16 + .../es-object-atoms/.github/FUNDING.yml | 12 + node_modules/es-object-atoms/CHANGELOG.md | 37 + node_modules/es-object-atoms/LICENSE | 21 + node_modules/es-object-atoms/README.md | 63 + .../RequireObjectCoercible.d.ts | 3 + .../es-object-atoms/RequireObjectCoercible.js | 11 + node_modules/es-object-atoms/ToObject.d.ts | 7 + node_modules/es-object-atoms/ToObject.js | 10 + node_modules/es-object-atoms/index.d.ts | 3 + node_modules/es-object-atoms/index.js | 4 + node_modules/es-object-atoms/isObject.d.ts | 3 + node_modules/es-object-atoms/isObject.js | 6 + node_modules/es-object-atoms/package.json | 80 + node_modules/es-object-atoms/test/index.js | 38 + node_modules/es-object-atoms/tsconfig.json | 6 + node_modules/escape-html/LICENSE | 24 + node_modules/escape-html/Readme.md | 43 + node_modules/escape-html/index.js | 78 + node_modules/escape-html/package.json | 24 + node_modules/etag/HISTORY.md | 83 + node_modules/etag/LICENSE | 22 + node_modules/etag/README.md | 159 + node_modules/etag/index.js | 131 + node_modules/etag/package.json | 47 + node_modules/express/History.md | 3858 +++++++ node_modules/express/LICENSE | 24 + node_modules/express/Readme.md | 266 + node_modules/express/index.js | 11 + node_modules/express/lib/application.js | 631 ++ node_modules/express/lib/express.js | 81 + node_modules/express/lib/request.js | 515 + node_modules/express/lib/response.js | 1039 ++ node_modules/express/lib/utils.js | 269 + node_modules/express/lib/view.js | 205 + node_modules/express/package.json | 98 + node_modules/filelist/README.md | 84 + node_modules/filelist/index.d.ts | 110 + node_modules/filelist/index.js | 495 + node_modules/filelist/jakefile.js | 15 + node_modules/filelist/package.json | 28 + node_modules/finalhandler/HISTORY.md | 233 + node_modules/finalhandler/LICENSE | 22 + node_modules/finalhandler/README.md | 147 + node_modules/finalhandler/index.js | 293 + node_modules/finalhandler/package.json | 43 + node_modules/forwarded/HISTORY.md | 21 + node_modules/forwarded/LICENSE | 22 + node_modules/forwarded/README.md | 57 + node_modules/forwarded/index.js | 90 + node_modules/forwarded/package.json | 45 + node_modules/fresh/HISTORY.md | 80 + node_modules/fresh/LICENSE | 23 + node_modules/fresh/README.md | 117 + node_modules/fresh/index.js | 136 + node_modules/fresh/package.json | 46 + node_modules/function-bind/.eslintrc | 21 + .../function-bind/.github/FUNDING.yml | 12 + .../function-bind/.github/SECURITY.md | 3 + node_modules/function-bind/.nycrc | 13 + node_modules/function-bind/CHANGELOG.md | 136 + node_modules/function-bind/LICENSE | 20 + node_modules/function-bind/README.md | 46 + node_modules/function-bind/implementation.js | 84 + node_modules/function-bind/index.js | 5 + node_modules/function-bind/package.json | 87 + node_modules/function-bind/test/.eslintrc | 9 + node_modules/function-bind/test/index.js | 252 + node_modules/get-intrinsic/.eslintrc | 42 + .../get-intrinsic/.github/FUNDING.yml | 12 + node_modules/get-intrinsic/.nycrc | 9 + node_modules/get-intrinsic/CHANGELOG.md | 186 + node_modules/get-intrinsic/LICENSE | 21 + node_modules/get-intrinsic/README.md | 71 + node_modules/get-intrinsic/index.js | 378 + node_modules/get-intrinsic/package.json | 97 + .../get-intrinsic/test/GetIntrinsic.js | 274 + node_modules/get-proto/.eslintrc | 10 + node_modules/get-proto/.github/FUNDING.yml | 12 + node_modules/get-proto/.nycrc | 9 + node_modules/get-proto/CHANGELOG.md | 21 + node_modules/get-proto/LICENSE | 21 + .../get-proto/Object.getPrototypeOf.d.ts | 5 + .../get-proto/Object.getPrototypeOf.js | 6 + node_modules/get-proto/README.md | 50 + .../get-proto/Reflect.getPrototypeOf.d.ts | 3 + .../get-proto/Reflect.getPrototypeOf.js | 4 + node_modules/get-proto/index.d.ts | 5 + node_modules/get-proto/index.js | 27 + node_modules/get-proto/package.json | 81 + node_modules/get-proto/test/index.js | 68 + node_modules/get-proto/tsconfig.json | 9 + node_modules/gopd/.eslintrc | 16 + node_modules/gopd/.github/FUNDING.yml | 12 + node_modules/gopd/CHANGELOG.md | 45 + node_modules/gopd/LICENSE | 21 + node_modules/gopd/README.md | 40 + node_modules/gopd/gOPD.d.ts | 1 + node_modules/gopd/gOPD.js | 4 + node_modules/gopd/index.d.ts | 5 + node_modules/gopd/index.js | 15 + node_modules/gopd/package.json | 77 + node_modules/gopd/test/index.js | 36 + node_modules/gopd/tsconfig.json | 9 + node_modules/has-symbols/.eslintrc | 11 + node_modules/has-symbols/.github/FUNDING.yml | 12 + node_modules/has-symbols/.nycrc | 9 + node_modules/has-symbols/CHANGELOG.md | 91 + node_modules/has-symbols/LICENSE | 21 + node_modules/has-symbols/README.md | 46 + node_modules/has-symbols/index.d.ts | 3 + node_modules/has-symbols/index.js | 14 + node_modules/has-symbols/package.json | 111 + node_modules/has-symbols/shams.d.ts | 3 + node_modules/has-symbols/shams.js | 45 + node_modules/has-symbols/test/index.js | 22 + .../has-symbols/test/shams/core-js.js | 29 + .../test/shams/get-own-property-symbols.js | 29 + node_modules/has-symbols/test/tests.js | 58 + node_modules/has-symbols/tsconfig.json | 10 + node_modules/hasown/.eslintrc | 5 + node_modules/hasown/.github/FUNDING.yml | 12 + node_modules/hasown/.nycrc | 13 + node_modules/hasown/CHANGELOG.md | 40 + node_modules/hasown/LICENSE | 21 + node_modules/hasown/README.md | 40 + node_modules/hasown/index.d.ts | 3 + node_modules/hasown/index.js | 8 + node_modules/hasown/package.json | 92 + node_modules/hasown/tsconfig.json | 6 + node_modules/http-errors/HISTORY.md | 180 + node_modules/http-errors/LICENSE | 23 + node_modules/http-errors/README.md | 169 + node_modules/http-errors/index.js | 289 + .../node_modules/statuses/HISTORY.md | 82 + .../http-errors/node_modules/statuses/LICENSE | 23 + .../node_modules/statuses/README.md | 136 + .../node_modules/statuses/codes.json | 65 + .../node_modules/statuses/index.js | 146 + .../node_modules/statuses/package.json | 49 + node_modules/http-errors/package.json | 50 + .../iconv-lite/.github/dependabot.yml | 11 + .../iconv-lite/.idea/codeStyles/Project.xml | 47 + .../.idea/codeStyles/codeStyleConfig.xml | 5 + node_modules/iconv-lite/.idea/iconv-lite.iml | 12 + .../inspectionProfiles/Project_Default.xml | 6 + node_modules/iconv-lite/.idea/modules.xml | 8 + node_modules/iconv-lite/.idea/vcs.xml | 6 + node_modules/iconv-lite/Changelog.md | 212 + node_modules/iconv-lite/LICENSE | 21 + node_modules/iconv-lite/README.md | 130 + .../iconv-lite/encodings/dbcs-codec.js | 597 ++ .../iconv-lite/encodings/dbcs-data.js | 188 + node_modules/iconv-lite/encodings/index.js | 23 + node_modules/iconv-lite/encodings/internal.js | 198 + .../iconv-lite/encodings/sbcs-codec.js | 72 + .../encodings/sbcs-data-generated.js | 451 + .../iconv-lite/encodings/sbcs-data.js | 179 + .../encodings/tables/big5-added.json | 122 + .../iconv-lite/encodings/tables/cp936.json | 264 + .../iconv-lite/encodings/tables/cp949.json | 273 + .../iconv-lite/encodings/tables/cp950.json | 177 + .../iconv-lite/encodings/tables/eucjp.json | 182 + .../encodings/tables/gb18030-ranges.json | 1 + .../encodings/tables/gbk-added.json | 56 + .../iconv-lite/encodings/tables/shiftjis.json | 125 + node_modules/iconv-lite/encodings/utf16.js | 197 + node_modules/iconv-lite/encodings/utf32.js | 319 + node_modules/iconv-lite/encodings/utf7.js | 290 + node_modules/iconv-lite/lib/bom-handling.js | 52 + node_modules/iconv-lite/lib/index.d.ts | 41 + node_modules/iconv-lite/lib/index.js | 180 + node_modules/iconv-lite/lib/streams.js | 109 + node_modules/iconv-lite/package.json | 44 + node_modules/inherits/LICENSE | 16 + node_modules/inherits/README.md | 42 + node_modules/inherits/inherits.js | 9 + node_modules/inherits/inherits_browser.js | 27 + node_modules/inherits/package.json | 29 + node_modules/ipaddr.js/LICENSE | 19 + node_modules/ipaddr.js/README.md | 233 + node_modules/ipaddr.js/ipaddr.min.js | 1 + node_modules/ipaddr.js/lib/ipaddr.js | 673 ++ node_modules/ipaddr.js/lib/ipaddr.js.d.ts | 68 + node_modules/ipaddr.js/package.json | 35 + node_modules/is-promise/LICENSE | 19 + node_modules/is-promise/index.d.ts | 2 + node_modules/is-promise/index.js | 6 + node_modules/is-promise/index.mjs | 3 + node_modules/is-promise/package.json | 30 + node_modules/is-promise/readme.md | 33 + node_modules/jake/Makefile | 44 + node_modules/jake/README.md | 17 + node_modules/jake/bin/bash_completion.sh | 41 + node_modules/jake/bin/cli.js | 31 + node_modules/jake/jakefile.js | 112 + node_modules/jake/lib/api.js | 409 + node_modules/jake/lib/jake.js | 330 + node_modules/jake/lib/loader.js | 174 + node_modules/jake/lib/namespace.js | 115 + node_modules/jake/lib/package_task.js | 406 + node_modules/jake/lib/parseargs.js | 134 + node_modules/jake/lib/program.js | 282 + node_modules/jake/lib/publish_task.js | 290 + node_modules/jake/lib/rule.js | 311 + node_modules/jake/lib/task/directory_task.js | 30 + node_modules/jake/lib/task/file_task.js | 126 + node_modules/jake/lib/task/index.js | 9 + node_modules/jake/lib/task/task.js | 458 + node_modules/jake/lib/test_task.js | 270 + node_modules/jake/lib/utils/file.js | 286 + node_modules/jake/lib/utils/index.js | 297 + node_modules/jake/lib/utils/logger.js | 24 + node_modules/jake/package.json | 44 + .../jake/test/integration/concurrent.js | 45 + node_modules/jake/test/integration/file.js | 228 + .../jake/test/integration/file_task.js | 141 + node_modules/jake/test/integration/helpers.js | 80 + .../jake/test/integration/jakefile.js | 352 + .../integration/jakelib/concurrent.jake.js | 113 + .../test/integration/jakelib/publish.jake.js | 49 + .../jakelib/required_module.jake.js | 10 + .../test/integration/jakelib/rule.jake.js | 222 + .../jake/test/integration/list_tasks.js | 15 + .../jake/test/integration/publish_task.js | 27 + node_modules/jake/test/integration/rule.js | 217 + node_modules/jake/test/integration/selfdep.js | 42 + .../jake/test/integration/task_base.js | 167 + node_modules/jake/test/unit/jakefile.js | 36 + node_modules/jake/test/unit/namespace.js | 77 + node_modules/jake/test/unit/parseargs.js | 169 + node_modules/jake/usage.txt | 17 + node_modules/jsonwebtoken/LICENSE | 21 + node_modules/jsonwebtoken/README.md | 396 + node_modules/jsonwebtoken/decode.js | 30 + node_modules/jsonwebtoken/index.js | 8 + .../jsonwebtoken/lib/JsonWebTokenError.js | 14 + .../jsonwebtoken/lib/NotBeforeError.js | 13 + .../jsonwebtoken/lib/TokenExpiredError.js | 13 + .../lib/asymmetricKeyDetailsSupported.js | 3 + node_modules/jsonwebtoken/lib/psSupported.js | 3 + .../lib/rsaPssKeyDetailsSupported.js | 3 + node_modules/jsonwebtoken/lib/timespan.js | 18 + .../jsonwebtoken/lib/validateAsymmetricKey.js | 66 + node_modules/jsonwebtoken/package.json | 71 + node_modules/jsonwebtoken/sign.js | 253 + node_modules/jsonwebtoken/verify.js | 263 + node_modules/jwa/LICENSE | 17 + node_modules/jwa/README.md | 150 + node_modules/jwa/index.js | 266 + node_modules/jwa/package.json | 37 + node_modules/jws/CHANGELOG.md | 34 + node_modules/jws/LICENSE | 17 + node_modules/jws/index.js | 22 + node_modules/jws/lib/data-stream.js | 55 + node_modules/jws/lib/sign-stream.js | 78 + node_modules/jws/lib/tostring.js | 10 + node_modules/jws/lib/verify-stream.js | 120 + node_modules/jws/package.json | 34 + node_modules/jws/readme.md | 255 + node_modules/lodash.includes/LICENSE | 47 + node_modules/lodash.includes/README.md | 18 + node_modules/lodash.includes/index.js | 745 ++ node_modules/lodash.includes/package.json | 17 + node_modules/lodash.isboolean/LICENSE | 22 + node_modules/lodash.isboolean/README.md | 18 + node_modules/lodash.isboolean/index.js | 70 + node_modules/lodash.isboolean/package.json | 17 + node_modules/lodash.isinteger/LICENSE | 47 + node_modules/lodash.isinteger/README.md | 18 + node_modules/lodash.isinteger/index.js | 265 + node_modules/lodash.isinteger/package.json | 17 + node_modules/lodash.isnumber/LICENSE | 22 + node_modules/lodash.isnumber/README.md | 18 + node_modules/lodash.isnumber/index.js | 79 + node_modules/lodash.isnumber/package.json | 17 + node_modules/lodash.isplainobject/LICENSE | 47 + node_modules/lodash.isplainobject/README.md | 18 + node_modules/lodash.isplainobject/index.js | 139 + .../lodash.isplainobject/package.json | 17 + node_modules/lodash.isstring/LICENSE | 22 + node_modules/lodash.isstring/README.md | 18 + node_modules/lodash.isstring/index.js | 95 + node_modules/lodash.isstring/package.json | 17 + node_modules/lodash.once/LICENSE | 47 + node_modules/lodash.once/README.md | 18 + node_modules/lodash.once/index.js | 294 + node_modules/lodash.once/package.json | 17 + node_modules/math-intrinsics/.eslintrc | 16 + .../math-intrinsics/.github/FUNDING.yml | 12 + node_modules/math-intrinsics/CHANGELOG.md | 24 + node_modules/math-intrinsics/LICENSE | 21 + node_modules/math-intrinsics/README.md | 50 + node_modules/math-intrinsics/abs.d.ts | 1 + node_modules/math-intrinsics/abs.js | 4 + .../constants/maxArrayLength.d.ts | 3 + .../constants/maxArrayLength.js | 4 + .../constants/maxSafeInteger.d.ts | 3 + .../constants/maxSafeInteger.js | 5 + .../math-intrinsics/constants/maxValue.d.ts | 3 + .../math-intrinsics/constants/maxValue.js | 5 + node_modules/math-intrinsics/floor.d.ts | 1 + node_modules/math-intrinsics/floor.js | 4 + node_modules/math-intrinsics/isFinite.d.ts | 3 + node_modules/math-intrinsics/isFinite.js | 12 + node_modules/math-intrinsics/isInteger.d.ts | 3 + node_modules/math-intrinsics/isInteger.js | 16 + node_modules/math-intrinsics/isNaN.d.ts | 1 + node_modules/math-intrinsics/isNaN.js | 6 + .../math-intrinsics/isNegativeZero.d.ts | 3 + .../math-intrinsics/isNegativeZero.js | 6 + node_modules/math-intrinsics/max.d.ts | 1 + node_modules/math-intrinsics/max.js | 4 + node_modules/math-intrinsics/min.d.ts | 1 + node_modules/math-intrinsics/min.js | 4 + node_modules/math-intrinsics/mod.d.ts | 3 + node_modules/math-intrinsics/mod.js | 9 + node_modules/math-intrinsics/package.json | 86 + node_modules/math-intrinsics/pow.d.ts | 1 + node_modules/math-intrinsics/pow.js | 4 + node_modules/math-intrinsics/round.d.ts | 1 + node_modules/math-intrinsics/round.js | 4 + node_modules/math-intrinsics/sign.d.ts | 3 + node_modules/math-intrinsics/sign.js | 11 + node_modules/math-intrinsics/test/index.js | 192 + node_modules/math-intrinsics/tsconfig.json | 3 + node_modules/media-typer/HISTORY.md | 50 + node_modules/media-typer/LICENSE | 22 + node_modules/media-typer/README.md | 93 + node_modules/media-typer/index.js | 143 + node_modules/media-typer/package.json | 33 + node_modules/merge-descriptors/index.d.ts | 11 + node_modules/merge-descriptors/index.js | 26 + node_modules/merge-descriptors/license | 11 + node_modules/merge-descriptors/package.json | 50 + node_modules/merge-descriptors/readme.md | 55 + node_modules/mime-db/HISTORY.md | 541 + node_modules/mime-db/LICENSE | 23 + node_modules/mime-db/README.md | 109 + node_modules/mime-db/db.json | 9342 +++++++++++++++++ node_modules/mime-db/index.js | 12 + node_modules/mime-db/package.json | 56 + node_modules/mime-types/HISTORY.md | 421 + node_modules/mime-types/LICENSE | 23 + node_modules/mime-types/README.md | 126 + node_modules/mime-types/index.js | 211 + node_modules/mime-types/mimeScore.js | 52 + node_modules/mime-types/package.json | 45 + node_modules/minimatch/LICENSE | 15 + node_modules/minimatch/README.md | 259 + node_modules/minimatch/lib/path.js | 4 + node_modules/minimatch/minimatch.js | 944 ++ node_modules/minimatch/package.json | 35 + node_modules/ms/index.js | 162 + node_modules/ms/license.md | 21 + node_modules/ms/package.json | 38 + node_modules/ms/readme.md | 59 + node_modules/negotiator/HISTORY.md | 114 + node_modules/negotiator/LICENSE | 24 + node_modules/negotiator/README.md | 212 + node_modules/negotiator/index.js | 83 + node_modules/negotiator/lib/charset.js | 169 + node_modules/negotiator/lib/encoding.js | 205 + node_modules/negotiator/lib/language.js | 179 + node_modules/negotiator/lib/mediaType.js | 294 + node_modules/negotiator/package.json | 43 + node_modules/nostr-tools/LICENSE | 24 + node_modules/nostr-tools/README.md | 383 + .../nostr-tools/lib/cjs/abstract-pool.js | 793 ++ .../nostr-tools/lib/cjs/abstract-pool.js.map | 7 + .../nostr-tools/lib/cjs/abstract-relay.js | 555 + .../nostr-tools/lib/cjs/abstract-relay.js.map | 7 + node_modules/nostr-tools/lib/cjs/fakejson.js | 66 + .../nostr-tools/lib/cjs/fakejson.js.map | 7 + node_modules/nostr-tools/lib/cjs/filter.js | 111 + .../nostr-tools/lib/cjs/filter.js.map | 7 + node_modules/nostr-tools/lib/cjs/index.js | 2780 +++++ node_modules/nostr-tools/lib/cjs/index.js.map | 7 + node_modules/nostr-tools/lib/cjs/kinds.js | 243 + node_modules/nostr-tools/lib/cjs/kinds.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip04.js | 61 + node_modules/nostr-tools/lib/cjs/nip04.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip05.js | 76 + node_modules/nostr-tools/lib/cjs/nip05.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip06.js | 82 + node_modules/nostr-tools/lib/cjs/nip06.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip07.js | 18 + node_modules/nostr-tools/lib/cjs/nip07.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip10.js | 124 + node_modules/nostr-tools/lib/cjs/nip10.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip11.js | 39 + node_modules/nostr-tools/lib/cjs/nip11.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip13.js | 73 + node_modules/nostr-tools/lib/cjs/nip13.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip17.js | 321 + node_modules/nostr-tools/lib/cjs/nip17.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip18.js | 188 + node_modules/nostr-tools/lib/cjs/nip18.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip19.js | 217 + node_modules/nostr-tools/lib/cjs/nip19.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip21.js | 140 + node_modules/nostr-tools/lib/cjs/nip21.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip25.js | 159 + node_modules/nostr-tools/lib/cjs/nip25.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip27.js | 229 + node_modules/nostr-tools/lib/cjs/nip27.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip28.js | 220 + node_modules/nostr-tools/lib/cjs/nip28.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip29.js | 495 + node_modules/nostr-tools/lib/cjs/nip29.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip30.js | 53 + node_modules/nostr-tools/lib/cjs/nip30.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip39.js | 42 + node_modules/nostr-tools/lib/cjs/nip39.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip40.js | 63 + node_modules/nostr-tools/lib/cjs/nip40.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip42.js | 41 + node_modules/nostr-tools/lib/cjs/nip42.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip44.js | 143 + node_modules/nostr-tools/lib/cjs/nip44.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip46.js | 1239 +++ node_modules/nostr-tools/lib/cjs/nip46.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip47.js | 168 + node_modules/nostr-tools/lib/cjs/nip47.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip49.js | 77 + node_modules/nostr-tools/lib/cjs/nip49.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip54.js | 35 + node_modules/nostr-tools/lib/cjs/nip54.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip55.js | 103 + node_modules/nostr-tools/lib/cjs/nip55.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip57.js | 274 + node_modules/nostr-tools/lib/cjs/nip57.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip58.js | 117 + node_modules/nostr-tools/lib/cjs/nip58.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip59.js | 298 + node_modules/nostr-tools/lib/cjs/nip59.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip75.js | 70 + node_modules/nostr-tools/lib/cjs/nip75.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip94.js | 142 + node_modules/nostr-tools/lib/cjs/nip94.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip98.js | 230 + node_modules/nostr-tools/lib/cjs/nip98.js.map | 7 + node_modules/nostr-tools/lib/cjs/nip99.js | 153 + node_modules/nostr-tools/lib/cjs/nip99.js.map | 7 + node_modules/nostr-tools/lib/cjs/nipb7.js | 184 + node_modules/nostr-tools/lib/cjs/nipb7.js.map | 7 + node_modules/nostr-tools/lib/cjs/package.json | 1 + node_modules/nostr-tools/lib/cjs/pool.js | 893 ++ node_modules/nostr-tools/lib/cjs/pool.js.map | 7 + node_modules/nostr-tools/lib/cjs/pure.js | 130 + node_modules/nostr-tools/lib/cjs/pure.js.map | 7 + .../nostr-tools/lib/cjs/references.js | 210 + .../nostr-tools/lib/cjs/references.js.map | 7 + node_modules/nostr-tools/lib/cjs/relay.js | 663 ++ node_modules/nostr-tools/lib/cjs/relay.js.map | 7 + node_modules/nostr-tools/lib/cjs/signer.js | 130 + .../nostr-tools/lib/cjs/signer.js.map | 7 + node_modules/nostr-tools/lib/cjs/utils.js | 145 + node_modules/nostr-tools/lib/cjs/utils.js.map | 7 + node_modules/nostr-tools/lib/cjs/wasm.js | 103 + node_modules/nostr-tools/lib/cjs/wasm.js.map | 7 + .../nostr-tools/lib/esm/abstract-pool.js | 770 ++ .../nostr-tools/lib/esm/abstract-pool.js.map | 7 + .../nostr-tools/lib/esm/abstract-relay.js | 532 + .../nostr-tools/lib/esm/abstract-relay.js.map | 7 + node_modules/nostr-tools/lib/esm/fakejson.js | 45 + .../nostr-tools/lib/esm/fakejson.js.map | 7 + node_modules/nostr-tools/lib/esm/filter.js | 88 + .../nostr-tools/lib/esm/filter.js.map | 7 + node_modules/nostr-tools/lib/esm/index.js | 2763 +++++ node_modules/nostr-tools/lib/esm/index.js.map | 7 + node_modules/nostr-tools/lib/esm/kinds.js | 220 + node_modules/nostr-tools/lib/esm/kinds.js.map | 7 + node_modules/nostr-tools/lib/esm/nip04.js | 40 + node_modules/nostr-tools/lib/esm/nip04.js.map | 7 + node_modules/nostr-tools/lib/esm/nip05.js | 55 + node_modules/nostr-tools/lib/esm/nip05.js.map | 7 + node_modules/nostr-tools/lib/esm/nip06.js | 61 + node_modules/nostr-tools/lib/esm/nip06.js.map | 7 + node_modules/nostr-tools/lib/esm/nip07.js | 0 node_modules/nostr-tools/lib/esm/nip07.js.map | 7 + node_modules/nostr-tools/lib/esm/nip10.js | 103 + node_modules/nostr-tools/lib/esm/nip10.js.map | 7 + node_modules/nostr-tools/lib/esm/nip11.js | 18 + node_modules/nostr-tools/lib/esm/nip11.js.map | 7 + node_modules/nostr-tools/lib/esm/nip13.js | 52 + node_modules/nostr-tools/lib/esm/nip13.js.map | 7 + node_modules/nostr-tools/lib/esm/nip17.js | 298 + node_modules/nostr-tools/lib/esm/nip17.js.map | 7 + node_modules/nostr-tools/lib/esm/nip18.js | 165 + node_modules/nostr-tools/lib/esm/nip18.js.map | 7 + node_modules/nostr-tools/lib/esm/nip19.js | 196 + node_modules/nostr-tools/lib/esm/nip19.js.map | 7 + node_modules/nostr-tools/lib/esm/nip21.js | 117 + node_modules/nostr-tools/lib/esm/nip21.js.map | 7 + node_modules/nostr-tools/lib/esm/nip25.js | 136 + node_modules/nostr-tools/lib/esm/nip25.js.map | 7 + node_modules/nostr-tools/lib/esm/nip27.js | 206 + node_modules/nostr-tools/lib/esm/nip27.js.map | 7 + node_modules/nostr-tools/lib/esm/nip28.js | 197 + node_modules/nostr-tools/lib/esm/nip28.js.map | 7 + node_modules/nostr-tools/lib/esm/nip29.js | 472 + node_modules/nostr-tools/lib/esm/nip29.js.map | 7 + node_modules/nostr-tools/lib/esm/nip30.js | 32 + node_modules/nostr-tools/lib/esm/nip30.js.map | 7 + node_modules/nostr-tools/lib/esm/nip39.js | 21 + node_modules/nostr-tools/lib/esm/nip39.js.map | 7 + node_modules/nostr-tools/lib/esm/nip40.js | 42 + node_modules/nostr-tools/lib/esm/nip40.js.map | 7 + node_modules/nostr-tools/lib/esm/nip42.js | 18 + node_modules/nostr-tools/lib/esm/nip42.js.map | 7 + node_modules/nostr-tools/lib/esm/nip44.js | 122 + node_modules/nostr-tools/lib/esm/nip44.js.map | 7 + node_modules/nostr-tools/lib/esm/nip46.js | 1216 +++ node_modules/nostr-tools/lib/esm/nip46.js.map | 7 + node_modules/nostr-tools/lib/esm/nip47.js | 145 + node_modules/nostr-tools/lib/esm/nip47.js.map | 7 + node_modules/nostr-tools/lib/esm/nip49.js | 56 + node_modules/nostr-tools/lib/esm/nip49.js.map | 7 + node_modules/nostr-tools/lib/esm/nip54.js | 14 + node_modules/nostr-tools/lib/esm/nip54.js.map | 7 + node_modules/nostr-tools/lib/esm/nip55.js | 82 + node_modules/nostr-tools/lib/esm/nip55.js.map | 7 + node_modules/nostr-tools/lib/esm/nip57.js | 253 + node_modules/nostr-tools/lib/esm/nip57.js.map | 7 + node_modules/nostr-tools/lib/esm/nip58.js | 94 + node_modules/nostr-tools/lib/esm/nip58.js.map | 7 + node_modules/nostr-tools/lib/esm/nip59.js | 275 + node_modules/nostr-tools/lib/esm/nip59.js.map | 7 + node_modules/nostr-tools/lib/esm/nip75.js | 47 + node_modules/nostr-tools/lib/esm/nip75.js.map | 7 + node_modules/nostr-tools/lib/esm/nip94.js | 119 + node_modules/nostr-tools/lib/esm/nip94.js.map | 7 + node_modules/nostr-tools/lib/esm/nip98.js | 209 + node_modules/nostr-tools/lib/esm/nip98.js.map | 7 + node_modules/nostr-tools/lib/esm/nip99.js | 130 + node_modules/nostr-tools/lib/esm/nip99.js.map | 7 + node_modules/nostr-tools/lib/esm/nipb7.js | 163 + node_modules/nostr-tools/lib/esm/nipb7.js.map | 7 + node_modules/nostr-tools/lib/esm/pool.js | 870 ++ node_modules/nostr-tools/lib/esm/pool.js.map | 7 + node_modules/nostr-tools/lib/esm/pure.js | 109 + node_modules/nostr-tools/lib/esm/pure.js.map | 7 + .../nostr-tools/lib/esm/references.js | 187 + .../nostr-tools/lib/esm/references.js.map | 7 + node_modules/nostr-tools/lib/esm/relay.js | 640 ++ node_modules/nostr-tools/lib/esm/relay.js.map | 7 + node_modules/nostr-tools/lib/esm/signer.js | 107 + .../nostr-tools/lib/esm/signer.js.map | 7 + node_modules/nostr-tools/lib/esm/utils.js | 124 + node_modules/nostr-tools/lib/esm/utils.js.map | 7 + node_modules/nostr-tools/lib/esm/wasm.js | 82 + node_modules/nostr-tools/lib/esm/wasm.js.map | 7 + node_modules/nostr-tools/lib/nostr.bundle.js | 6860 ++++++++++++ .../nostr-tools/lib/nostr.bundle.js.map | 7 + .../nostr-tools/lib/types/abstract-pool.d.ts | 44 + .../nostr-tools/lib/types/abstract-relay.d.ts | 96 + .../nostr-tools/lib/types/benchmarks.d.ts | 1 + node_modules/nostr-tools/lib/types/core.d.ts | 32 + .../nostr-tools/lib/types/core.test.d.ts | 1 + .../nostr-tools/lib/types/fakejson.d.ts | 6 + .../nostr-tools/lib/types/fakejson.test.d.ts | 1 + .../nostr-tools/lib/types/filter.d.ts | 19 + .../nostr-tools/lib/types/filter.test.d.ts | 1 + .../nostr-tools/lib/types/helpers.d.ts | 3 + node_modules/nostr-tools/lib/types/index.d.ts | 29 + node_modules/nostr-tools/lib/types/kinds.d.ts | 170 + .../nostr-tools/lib/types/kinds.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip04.d.ts | 2 + .../nostr-tools/lib/types/nip04.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip05.d.ts | 17 + .../nostr-tools/lib/types/nip05.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip06.d.ts | 15 + .../nostr-tools/lib/types/nip06.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip07.d.ts | 13 + node_modules/nostr-tools/lib/types/nip10.d.ts | 24 + .../nostr-tools/lib/types/nip10.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip11.d.ts | 266 + .../nostr-tools/lib/types/nip11.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip13.d.ts | 9 + .../nostr-tools/lib/types/nip13.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip17.d.ts | 15 + .../nostr-tools/lib/types/nip17.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip18.d.ts | 22 + .../nostr-tools/lib/types/nip18.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip19.d.ts | 81 + .../nostr-tools/lib/types/nip19.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip21.d.ts | 34 + .../nostr-tools/lib/types/nip21.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip25.d.ts | 15 + .../nostr-tools/lib/types/nip25.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip27.d.ts | 24 + .../nostr-tools/lib/types/nip27.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip28.d.ts | 46 + .../nostr-tools/lib/types/nip28.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip29.d.ts | 265 + node_modules/nostr-tools/lib/types/nip30.d.ts | 22 + .../nostr-tools/lib/types/nip30.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip39.d.ts | 2 + .../nostr-tools/lib/types/nip39.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip40.d.ts | 10 + .../nostr-tools/lib/types/nip40.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip42.d.ts | 5 + .../nostr-tools/lib/types/nip42.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip44.d.ts | 13 + .../nostr-tools/lib/types/nip44.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip46.d.ts | 96 + node_modules/nostr-tools/lib/types/nip47.d.ts | 9 + .../nostr-tools/lib/types/nip47.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip49.d.ts | 3 + .../nostr-tools/lib/types/nip49.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip54.d.ts | 1 + .../nostr-tools/lib/types/nip54.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip55.d.ts | 30 + .../nostr-tools/lib/types/nip55.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip57.d.ts | 25 + .../nostr-tools/lib/types/nip57.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip58.d.ts | 134 + .../nostr-tools/lib/types/nip58.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip59.d.ts | 12 + .../nostr-tools/lib/types/nip59.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip75.d.ts | 61 + .../nostr-tools/lib/types/nip75.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip94.d.ts | 87 + .../nostr-tools/lib/types/nip94.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip98.d.ts | 74 + .../nostr-tools/lib/types/nip98.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nip99.d.ts | 92 + .../nostr-tools/lib/types/nip99.test.d.ts | 1 + node_modules/nostr-tools/lib/types/nipb7.d.ts | 23 + .../nostr-tools/lib/types/nipb7.test.d.ts | 1 + node_modules/nostr-tools/lib/types/pool.d.ts | 8 + .../nostr-tools/lib/types/pool.test.d.ts | 1 + node_modules/nostr-tools/lib/types/pure.d.ts | 8 + .../nostr-tools/lib/types/pure.test.d.ts | 1 + .../nostr-tools/lib/types/references.d.ts | 10 + .../lib/types/references.test.d.ts | 1 + node_modules/nostr-tools/lib/types/relay.d.ts | 11 + .../nostr-tools/lib/types/relay.test.d.ts | 1 + .../nostr-tools/lib/types/signer.d.ts | 11 + .../nostr-tools/lib/types/test-helpers.d.ts | 13 + node_modules/nostr-tools/lib/types/utils.d.ts | 21 + .../nostr-tools/lib/types/utils.test.d.ts | 1 + node_modules/nostr-tools/lib/types/wasm.d.ts | 8 + node_modules/nostr-tools/package.json | 281 + node_modules/nostr-wasm/README.md | 91 + node_modules/nostr-wasm/dist/api/emsimp.d.ts | 3 + node_modules/nostr-wasm/dist/api/nostr.d.ts | 45 + .../nostr-wasm/dist/api/secp256k1-types.d.ts | 124 + .../nostr-wasm/dist/api/secp256k1.d.ts | 41 + node_modules/nostr-wasm/dist/api/types.d.ts | 124 + .../nostr-wasm/dist/api/wasm-env.d.ts | 3 + node_modules/nostr-wasm/dist/gen/wasm.d.ts | 27 + node_modules/nostr-wasm/dist/generate.d.ts | 1 + node_modules/nostr-wasm/dist/gzipped.d.ts | 3 + node_modules/nostr-wasm/dist/gzipped.js | 44 + node_modules/nostr-wasm/dist/headless.d.ts | 2 + node_modules/nostr-wasm/dist/main.d.ts | 3 + node_modules/nostr-wasm/dist/main.js | 9 + node_modules/nostr-wasm/dist/nostr.js | 248 + node_modules/nostr-wasm/dist/secp256k1.js | 230 + node_modules/nostr-wasm/dist/types.d.ts | 22 + node_modules/nostr-wasm/package.json | 37 + .../nostr-wasm/public/out/secp256k1.js | 1 + .../nostr-wasm/public/out/secp256k1.wasm | Bin 0 -> 217781 bytes node_modules/object-inspect/.eslintrc | 53 + .../object-inspect/.github/FUNDING.yml | 12 + node_modules/object-inspect/.nycrc | 13 + node_modules/object-inspect/CHANGELOG.md | 424 + node_modules/object-inspect/LICENSE | 21 + node_modules/object-inspect/example/all.js | 23 + .../object-inspect/example/circular.js | 6 + node_modules/object-inspect/example/fn.js | 5 + .../object-inspect/example/inspect.js | 10 + node_modules/object-inspect/index.js | 544 + .../object-inspect/package-support.json | 20 + node_modules/object-inspect/package.json | 105 + node_modules/object-inspect/readme.markdown | 84 + node_modules/object-inspect/test-core-js.js | 26 + node_modules/object-inspect/test/bigint.js | 58 + .../object-inspect/test/browser/dom.js | 15 + node_modules/object-inspect/test/circular.js | 16 + node_modules/object-inspect/test/deep.js | 12 + node_modules/object-inspect/test/element.js | 53 + node_modules/object-inspect/test/err.js | 48 + node_modules/object-inspect/test/fakes.js | 29 + node_modules/object-inspect/test/fn.js | 76 + node_modules/object-inspect/test/global.js | 17 + node_modules/object-inspect/test/has.js | 15 + node_modules/object-inspect/test/holes.js | 15 + .../object-inspect/test/indent-option.js | 271 + node_modules/object-inspect/test/inspect.js | 139 + node_modules/object-inspect/test/lowbyte.js | 12 + node_modules/object-inspect/test/number.js | 58 + .../object-inspect/test/quoteStyle.js | 26 + .../object-inspect/test/toStringTag.js | 40 + node_modules/object-inspect/test/undef.js | 12 + node_modules/object-inspect/test/values.js | 261 + node_modules/object-inspect/util.inspect.js | 1 + node_modules/on-finished/HISTORY.md | 98 + node_modules/on-finished/LICENSE | 23 + node_modules/on-finished/README.md | 162 + node_modules/on-finished/index.js | 234 + node_modules/on-finished/package.json | 39 + node_modules/once/LICENSE | 15 + node_modules/once/README.md | 79 + node_modules/once/once.js | 42 + node_modules/once/package.json | 33 + node_modules/parseurl/HISTORY.md | 58 + node_modules/parseurl/LICENSE | 24 + node_modules/parseurl/README.md | 133 + node_modules/parseurl/index.js | 158 + node_modules/parseurl/package.json | 40 + node_modules/path-to-regexp/LICENSE | 21 + node_modules/path-to-regexp/Readme.md | 216 + node_modules/path-to-regexp/dist/index.d.ts | 136 + node_modules/path-to-regexp/dist/index.js | 403 + node_modules/path-to-regexp/dist/index.js.map | 1 + node_modules/path-to-regexp/package.json | 62 + node_modules/picocolors/LICENSE | 15 + node_modules/picocolors/README.md | 21 + node_modules/picocolors/package.json | 25 + node_modules/picocolors/picocolors.browser.js | 4 + node_modules/picocolors/picocolors.d.ts | 5 + node_modules/picocolors/picocolors.js | 75 + node_modules/picocolors/types.d.ts | 51 + node_modules/proxy-addr/HISTORY.md | 161 + node_modules/proxy-addr/LICENSE | 22 + node_modules/proxy-addr/README.md | 139 + node_modules/proxy-addr/index.js | 327 + node_modules/proxy-addr/package.json | 47 + node_modules/qs/.editorconfig | 46 + node_modules/qs/.eslintrc | 39 + node_modules/qs/.github/FUNDING.yml | 12 + node_modules/qs/.nycrc | 13 + node_modules/qs/CHANGELOG.md | 622 ++ node_modules/qs/LICENSE.md | 29 + node_modules/qs/README.md | 733 ++ node_modules/qs/dist/qs.js | 141 + node_modules/qs/lib/formats.js | 23 + node_modules/qs/lib/index.js | 11 + node_modules/qs/lib/parse.js | 328 + node_modules/qs/lib/stringify.js | 356 + node_modules/qs/lib/utils.js | 268 + node_modules/qs/package.json | 93 + node_modules/qs/test/empty-keys-cases.js | 267 + node_modules/qs/test/parse.js | 1276 +++ node_modules/qs/test/stringify.js | 1306 +++ node_modules/qs/test/utils.js | 262 + node_modules/range-parser/HISTORY.md | 56 + node_modules/range-parser/LICENSE | 23 + node_modules/range-parser/README.md | 84 + node_modules/range-parser/index.js | 162 + node_modules/range-parser/package.json | 44 + node_modules/raw-body/HISTORY.md | 325 + node_modules/raw-body/LICENSE | 22 + node_modules/raw-body/README.md | 223 + node_modules/raw-body/SECURITY.md | 24 + node_modules/raw-body/index.d.ts | 85 + node_modules/raw-body/index.js | 336 + node_modules/raw-body/package.json | 50 + node_modules/router/HISTORY.md | 228 + node_modules/router/LICENSE | 23 + node_modules/router/README.md | 416 + node_modules/router/index.js | 748 ++ node_modules/router/lib/layer.js | 247 + node_modules/router/lib/route.js | 242 + node_modules/router/package.json | 44 + node_modules/safe-buffer/LICENSE | 21 + node_modules/safe-buffer/README.md | 584 ++ node_modules/safe-buffer/index.d.ts | 187 + node_modules/safe-buffer/index.js | 65 + node_modules/safe-buffer/package.json | 51 + node_modules/safer-buffer/LICENSE | 21 + node_modules/safer-buffer/Porting-Buffer.md | 268 + node_modules/safer-buffer/Readme.md | 156 + node_modules/safer-buffer/dangerous.js | 58 + node_modules/safer-buffer/package.json | 34 + node_modules/safer-buffer/safer.js | 77 + node_modules/safer-buffer/tests.js | 406 + node_modules/semver/LICENSE | 15 + node_modules/semver/README.md | 664 ++ node_modules/semver/bin/semver.js | 191 + node_modules/semver/classes/comparator.js | 143 + node_modules/semver/classes/index.js | 7 + node_modules/semver/classes/range.js | 556 + node_modules/semver/classes/semver.js | 319 + node_modules/semver/functions/clean.js | 8 + node_modules/semver/functions/cmp.js | 54 + node_modules/semver/functions/coerce.js | 62 + .../semver/functions/compare-build.js | 9 + .../semver/functions/compare-loose.js | 5 + node_modules/semver/functions/compare.js | 7 + node_modules/semver/functions/diff.js | 60 + node_modules/semver/functions/eq.js | 5 + node_modules/semver/functions/gt.js | 5 + node_modules/semver/functions/gte.js | 5 + node_modules/semver/functions/inc.js | 21 + node_modules/semver/functions/lt.js | 5 + node_modules/semver/functions/lte.js | 5 + node_modules/semver/functions/major.js | 5 + node_modules/semver/functions/minor.js | 5 + node_modules/semver/functions/neq.js | 5 + node_modules/semver/functions/parse.js | 18 + node_modules/semver/functions/patch.js | 5 + node_modules/semver/functions/prerelease.js | 8 + node_modules/semver/functions/rcompare.js | 5 + node_modules/semver/functions/rsort.js | 5 + node_modules/semver/functions/satisfies.js | 12 + node_modules/semver/functions/sort.js | 5 + node_modules/semver/functions/valid.js | 8 + node_modules/semver/index.js | 91 + node_modules/semver/internal/constants.js | 37 + node_modules/semver/internal/debug.js | 11 + node_modules/semver/internal/identifiers.js | 25 + node_modules/semver/internal/lrucache.js | 42 + node_modules/semver/internal/parse-options.js | 17 + node_modules/semver/internal/re.js | 223 + node_modules/semver/package.json | 78 + node_modules/semver/preload.js | 4 + node_modules/semver/range.bnf | 16 + node_modules/semver/ranges/gtr.js | 6 + node_modules/semver/ranges/intersects.js | 9 + node_modules/semver/ranges/ltr.js | 6 + node_modules/semver/ranges/max-satisfying.js | 27 + node_modules/semver/ranges/min-satisfying.js | 26 + node_modules/semver/ranges/min-version.js | 63 + node_modules/semver/ranges/outside.js | 82 + node_modules/semver/ranges/simplify.js | 49 + node_modules/semver/ranges/subset.js | 249 + node_modules/semver/ranges/to-comparators.js | 10 + node_modules/semver/ranges/valid.js | 13 + node_modules/send/HISTORY.md | 580 + node_modules/send/LICENSE | 23 + node_modules/send/README.md | 317 + node_modules/send/index.js | 997 ++ node_modules/send/package.json | 60 + node_modules/serve-static/HISTORY.md | 516 + node_modules/serve-static/LICENSE | 25 + node_modules/serve-static/README.md | 253 + node_modules/serve-static/index.js | 208 + node_modules/serve-static/package.json | 41 + node_modules/setprototypeof/LICENSE | 13 + node_modules/setprototypeof/README.md | 31 + node_modules/setprototypeof/index.d.ts | 2 + node_modules/setprototypeof/index.js | 17 + node_modules/setprototypeof/package.json | 38 + node_modules/setprototypeof/test/index.js | 24 + node_modules/side-channel-list/.editorconfig | 9 + node_modules/side-channel-list/.eslintrc | 11 + .../side-channel-list/.github/FUNDING.yml | 12 + node_modules/side-channel-list/.nycrc | 13 + node_modules/side-channel-list/CHANGELOG.md | 15 + node_modules/side-channel-list/LICENSE | 21 + node_modules/side-channel-list/README.md | 62 + node_modules/side-channel-list/index.d.ts | 13 + node_modules/side-channel-list/index.js | 113 + node_modules/side-channel-list/list.d.ts | 14 + node_modules/side-channel-list/package.json | 77 + node_modules/side-channel-list/test/index.js | 104 + node_modules/side-channel-list/tsconfig.json | 9 + node_modules/side-channel-map/.editorconfig | 9 + node_modules/side-channel-map/.eslintrc | 11 + .../side-channel-map/.github/FUNDING.yml | 12 + node_modules/side-channel-map/.nycrc | 13 + node_modules/side-channel-map/CHANGELOG.md | 22 + node_modules/side-channel-map/LICENSE | 21 + node_modules/side-channel-map/README.md | 62 + node_modules/side-channel-map/index.d.ts | 15 + node_modules/side-channel-map/index.js | 68 + node_modules/side-channel-map/package.json | 80 + node_modules/side-channel-map/test/index.js | 114 + node_modules/side-channel-map/tsconfig.json | 9 + .../side-channel-weakmap/.editorconfig | 9 + node_modules/side-channel-weakmap/.eslintrc | 12 + .../side-channel-weakmap/.github/FUNDING.yml | 12 + node_modules/side-channel-weakmap/.nycrc | 13 + .../side-channel-weakmap/CHANGELOG.md | 28 + node_modules/side-channel-weakmap/LICENSE | 21 + node_modules/side-channel-weakmap/README.md | 62 + node_modules/side-channel-weakmap/index.d.ts | 15 + node_modules/side-channel-weakmap/index.js | 84 + .../side-channel-weakmap/package.json | 87 + .../side-channel-weakmap/test/index.js | 114 + .../side-channel-weakmap/tsconfig.json | 9 + node_modules/side-channel/.editorconfig | 9 + node_modules/side-channel/.eslintrc | 12 + node_modules/side-channel/.github/FUNDING.yml | 12 + node_modules/side-channel/.nycrc | 13 + node_modules/side-channel/CHANGELOG.md | 110 + node_modules/side-channel/LICENSE | 21 + node_modules/side-channel/README.md | 61 + node_modules/side-channel/index.d.ts | 14 + node_modules/side-channel/index.js | 43 + node_modules/side-channel/package.json | 85 + node_modules/side-channel/test/index.js | 104 + node_modules/side-channel/tsconfig.json | 9 + node_modules/statuses/HISTORY.md | 87 + node_modules/statuses/LICENSE | 23 + node_modules/statuses/README.md | 139 + node_modules/statuses/codes.json | 65 + node_modules/statuses/index.js | 146 + node_modules/statuses/package.json | 49 + node_modules/toidentifier/HISTORY.md | 9 + node_modules/toidentifier/LICENSE | 21 + node_modules/toidentifier/README.md | 61 + node_modules/toidentifier/index.js | 32 + node_modules/toidentifier/package.json | 38 + node_modules/type-is/HISTORY.md | 292 + node_modules/type-is/LICENSE | 23 + node_modules/type-is/README.md | 198 + node_modules/type-is/index.js | 250 + node_modules/type-is/package.json | 47 + node_modules/unpipe/HISTORY.md | 4 + node_modules/unpipe/LICENSE | 22 + node_modules/unpipe/README.md | 43 + node_modules/unpipe/index.js | 69 + node_modules/unpipe/package.json | 27 + node_modules/vary/HISTORY.md | 39 + node_modules/vary/LICENSE | 22 + node_modules/vary/README.md | 101 + node_modules/vary/index.js | 149 + node_modules/vary/package.json | 43 + node_modules/wrappy/LICENSE | 15 + node_modules/wrappy/README.md | 36 + node_modules/wrappy/package.json | 29 + node_modules/wrappy/wrappy.js | 33 + nostr-oidc-bridge.code-workspace | 5 +- package-lock.json | 1145 ++ package.json | 14 +- 1999 files changed, 261047 insertions(+), 9 deletions(-) create mode 100644 app_working.js create mode 120000 node_modules/.bin/ejs create mode 120000 node_modules/.bin/jake create mode 120000 node_modules/.bin/semver create mode 100644 node_modules/.package-lock.json create mode 100644 node_modules/@noble/ciphers/LICENSE create mode 100644 node_modules/@noble/ciphers/README.md create mode 100644 node_modules/@noble/ciphers/_arx.d.ts create mode 100644 node_modules/@noble/ciphers/_arx.d.ts.map create mode 100644 node_modules/@noble/ciphers/_arx.js create mode 100644 node_modules/@noble/ciphers/_arx.js.map create mode 100644 node_modules/@noble/ciphers/_assert.d.ts create mode 100644 node_modules/@noble/ciphers/_assert.d.ts.map create mode 100644 node_modules/@noble/ciphers/_assert.js create mode 100644 node_modules/@noble/ciphers/_assert.js.map create mode 100644 node_modules/@noble/ciphers/_micro.d.ts create mode 100644 node_modules/@noble/ciphers/_micro.d.ts.map create mode 100644 node_modules/@noble/ciphers/_micro.js create mode 100644 node_modules/@noble/ciphers/_micro.js.map create mode 100644 node_modules/@noble/ciphers/_poly1305.d.ts create mode 100644 node_modules/@noble/ciphers/_poly1305.d.ts.map create mode 100644 node_modules/@noble/ciphers/_poly1305.js create mode 100644 node_modules/@noble/ciphers/_poly1305.js.map create mode 100644 node_modules/@noble/ciphers/_polyval.d.ts create mode 100644 node_modules/@noble/ciphers/_polyval.d.ts.map create mode 100644 node_modules/@noble/ciphers/_polyval.js create mode 100644 node_modules/@noble/ciphers/_polyval.js.map create mode 100644 node_modules/@noble/ciphers/aes.d.ts create mode 100644 node_modules/@noble/ciphers/aes.d.ts.map create mode 100644 node_modules/@noble/ciphers/aes.js create mode 100644 node_modules/@noble/ciphers/aes.js.map create mode 100644 node_modules/@noble/ciphers/chacha.d.ts create mode 100644 node_modules/@noble/ciphers/chacha.d.ts.map create mode 100644 node_modules/@noble/ciphers/chacha.js create mode 100644 node_modules/@noble/ciphers/chacha.js.map create mode 100644 node_modules/@noble/ciphers/crypto.d.ts create mode 100644 node_modules/@noble/ciphers/crypto.d.ts.map create mode 100644 node_modules/@noble/ciphers/crypto.js create mode 100644 node_modules/@noble/ciphers/crypto.js.map create mode 100644 node_modules/@noble/ciphers/cryptoNode.d.ts create mode 100644 node_modules/@noble/ciphers/cryptoNode.d.ts.map create mode 100644 node_modules/@noble/ciphers/cryptoNode.js create mode 100644 node_modules/@noble/ciphers/cryptoNode.js.map create mode 100644 node_modules/@noble/ciphers/esm/_arx.js create mode 100644 node_modules/@noble/ciphers/esm/_arx.js.map create mode 100644 node_modules/@noble/ciphers/esm/_assert.js create mode 100644 node_modules/@noble/ciphers/esm/_assert.js.map create mode 100644 node_modules/@noble/ciphers/esm/_micro.js create mode 100644 node_modules/@noble/ciphers/esm/_micro.js.map create mode 100644 node_modules/@noble/ciphers/esm/_poly1305.js create mode 100644 node_modules/@noble/ciphers/esm/_poly1305.js.map create mode 100644 node_modules/@noble/ciphers/esm/_polyval.js create mode 100644 node_modules/@noble/ciphers/esm/_polyval.js.map create mode 100644 node_modules/@noble/ciphers/esm/aes.js create mode 100644 node_modules/@noble/ciphers/esm/aes.js.map create mode 100644 node_modules/@noble/ciphers/esm/chacha.js create mode 100644 node_modules/@noble/ciphers/esm/chacha.js.map create mode 100644 node_modules/@noble/ciphers/esm/crypto.js create mode 100644 node_modules/@noble/ciphers/esm/crypto.js.map create mode 100644 node_modules/@noble/ciphers/esm/cryptoNode.js create mode 100644 node_modules/@noble/ciphers/esm/cryptoNode.js.map create mode 100644 node_modules/@noble/ciphers/esm/ff1.js create mode 100644 node_modules/@noble/ciphers/esm/ff1.js.map create mode 100644 node_modules/@noble/ciphers/esm/index.js create mode 100644 node_modules/@noble/ciphers/esm/index.js.map create mode 100644 node_modules/@noble/ciphers/esm/package.json create mode 100644 node_modules/@noble/ciphers/esm/salsa.js create mode 100644 node_modules/@noble/ciphers/esm/salsa.js.map create mode 100644 node_modules/@noble/ciphers/esm/utils.js create mode 100644 node_modules/@noble/ciphers/esm/utils.js.map create mode 100644 node_modules/@noble/ciphers/esm/webcrypto.js create mode 100644 node_modules/@noble/ciphers/esm/webcrypto.js.map create mode 100644 node_modules/@noble/ciphers/ff1.d.ts create mode 100644 node_modules/@noble/ciphers/ff1.d.ts.map create mode 100644 node_modules/@noble/ciphers/ff1.js create mode 100644 node_modules/@noble/ciphers/ff1.js.map create mode 100644 node_modules/@noble/ciphers/index.d.ts create mode 100644 node_modules/@noble/ciphers/index.d.ts.map create mode 100644 node_modules/@noble/ciphers/index.js create mode 100644 node_modules/@noble/ciphers/index.js.map create mode 100644 node_modules/@noble/ciphers/package.json create mode 100644 node_modules/@noble/ciphers/salsa.d.ts create mode 100644 node_modules/@noble/ciphers/salsa.d.ts.map create mode 100644 node_modules/@noble/ciphers/salsa.js create mode 100644 node_modules/@noble/ciphers/salsa.js.map create mode 100644 node_modules/@noble/ciphers/src/_arx.ts create mode 100644 node_modules/@noble/ciphers/src/_assert.ts create mode 100644 node_modules/@noble/ciphers/src/_micro.ts create mode 100644 node_modules/@noble/ciphers/src/_poly1305.ts create mode 100644 node_modules/@noble/ciphers/src/_polyval.ts create mode 100644 node_modules/@noble/ciphers/src/aes.ts create mode 100644 node_modules/@noble/ciphers/src/chacha.ts create mode 100644 node_modules/@noble/ciphers/src/crypto.ts create mode 100644 node_modules/@noble/ciphers/src/cryptoNode.ts create mode 100644 node_modules/@noble/ciphers/src/ff1.ts create mode 100644 node_modules/@noble/ciphers/src/index.ts create mode 100644 node_modules/@noble/ciphers/src/package.json create mode 100644 node_modules/@noble/ciphers/src/salsa.ts create mode 100644 node_modules/@noble/ciphers/src/utils.ts create mode 100644 node_modules/@noble/ciphers/src/webcrypto.ts create mode 100644 node_modules/@noble/ciphers/utils.d.ts create mode 100644 node_modules/@noble/ciphers/utils.d.ts.map create mode 100644 node_modules/@noble/ciphers/utils.js create mode 100644 node_modules/@noble/ciphers/utils.js.map create mode 100644 node_modules/@noble/ciphers/webcrypto.d.ts create mode 100644 node_modules/@noble/ciphers/webcrypto.d.ts.map create mode 100644 node_modules/@noble/ciphers/webcrypto.js create mode 100644 node_modules/@noble/ciphers/webcrypto.js.map create mode 100644 node_modules/@noble/curves/LICENSE create mode 100644 node_modules/@noble/curves/README.md create mode 100644 node_modules/@noble/curves/_shortw_utils.d.ts create mode 100644 node_modules/@noble/curves/_shortw_utils.d.ts.map create mode 100644 node_modules/@noble/curves/_shortw_utils.js create mode 100644 node_modules/@noble/curves/_shortw_utils.js.map create mode 100644 node_modules/@noble/curves/abstract/bls.d.ts create mode 100644 node_modules/@noble/curves/abstract/bls.d.ts.map create mode 100644 node_modules/@noble/curves/abstract/bls.js create mode 100644 node_modules/@noble/curves/abstract/bls.js.map create mode 100644 node_modules/@noble/curves/abstract/curve.d.ts create mode 100644 node_modules/@noble/curves/abstract/curve.d.ts.map create mode 100644 node_modules/@noble/curves/abstract/curve.js create mode 100644 node_modules/@noble/curves/abstract/curve.js.map create mode 100644 node_modules/@noble/curves/abstract/edwards.d.ts create mode 100644 node_modules/@noble/curves/abstract/edwards.d.ts.map create mode 100644 node_modules/@noble/curves/abstract/edwards.js create mode 100644 node_modules/@noble/curves/abstract/edwards.js.map create mode 100644 node_modules/@noble/curves/abstract/hash-to-curve.d.ts create mode 100644 node_modules/@noble/curves/abstract/hash-to-curve.d.ts.map create mode 100644 node_modules/@noble/curves/abstract/hash-to-curve.js create mode 100644 node_modules/@noble/curves/abstract/hash-to-curve.js.map create mode 100644 node_modules/@noble/curves/abstract/modular.d.ts create mode 100644 node_modules/@noble/curves/abstract/modular.d.ts.map create mode 100644 node_modules/@noble/curves/abstract/modular.js create mode 100644 node_modules/@noble/curves/abstract/modular.js.map create mode 100644 node_modules/@noble/curves/abstract/montgomery.d.ts create mode 100644 node_modules/@noble/curves/abstract/montgomery.d.ts.map create mode 100644 node_modules/@noble/curves/abstract/montgomery.js create mode 100644 node_modules/@noble/curves/abstract/montgomery.js.map create mode 100644 node_modules/@noble/curves/abstract/poseidon.d.ts create mode 100644 node_modules/@noble/curves/abstract/poseidon.d.ts.map create mode 100644 node_modules/@noble/curves/abstract/poseidon.js create mode 100644 node_modules/@noble/curves/abstract/poseidon.js.map create mode 100644 node_modules/@noble/curves/abstract/utils.d.ts create mode 100644 node_modules/@noble/curves/abstract/utils.d.ts.map create mode 100644 node_modules/@noble/curves/abstract/utils.js create mode 100644 node_modules/@noble/curves/abstract/utils.js.map create mode 100644 node_modules/@noble/curves/abstract/weierstrass.d.ts create mode 100644 node_modules/@noble/curves/abstract/weierstrass.d.ts.map create mode 100644 node_modules/@noble/curves/abstract/weierstrass.js create mode 100644 node_modules/@noble/curves/abstract/weierstrass.js.map create mode 100644 node_modules/@noble/curves/bls12-381.d.ts create mode 100644 node_modules/@noble/curves/bls12-381.d.ts.map create mode 100644 node_modules/@noble/curves/bls12-381.js create mode 100644 node_modules/@noble/curves/bls12-381.js.map create mode 100644 node_modules/@noble/curves/bn254.d.ts create mode 100644 node_modules/@noble/curves/bn254.d.ts.map create mode 100644 node_modules/@noble/curves/bn254.js create mode 100644 node_modules/@noble/curves/bn254.js.map create mode 100644 node_modules/@noble/curves/ed25519.d.ts create mode 100644 node_modules/@noble/curves/ed25519.d.ts.map create mode 100644 node_modules/@noble/curves/ed25519.js create mode 100644 node_modules/@noble/curves/ed25519.js.map create mode 100644 node_modules/@noble/curves/ed448.d.ts create mode 100644 node_modules/@noble/curves/ed448.d.ts.map create mode 100644 node_modules/@noble/curves/ed448.js create mode 100644 node_modules/@noble/curves/ed448.js.map create mode 100644 node_modules/@noble/curves/esm/_shortw_utils.js create mode 100644 node_modules/@noble/curves/esm/_shortw_utils.js.map create mode 100644 node_modules/@noble/curves/esm/abstract/bls.js create mode 100644 node_modules/@noble/curves/esm/abstract/bls.js.map create mode 100644 node_modules/@noble/curves/esm/abstract/curve.js create mode 100644 node_modules/@noble/curves/esm/abstract/curve.js.map create mode 100644 node_modules/@noble/curves/esm/abstract/edwards.js create mode 100644 node_modules/@noble/curves/esm/abstract/edwards.js.map create mode 100644 node_modules/@noble/curves/esm/abstract/hash-to-curve.js create mode 100644 node_modules/@noble/curves/esm/abstract/hash-to-curve.js.map create mode 100644 node_modules/@noble/curves/esm/abstract/modular.js create mode 100644 node_modules/@noble/curves/esm/abstract/modular.js.map create mode 100644 node_modules/@noble/curves/esm/abstract/montgomery.js create mode 100644 node_modules/@noble/curves/esm/abstract/montgomery.js.map create mode 100644 node_modules/@noble/curves/esm/abstract/poseidon.js create mode 100644 node_modules/@noble/curves/esm/abstract/poseidon.js.map create mode 100644 node_modules/@noble/curves/esm/abstract/utils.js create mode 100644 node_modules/@noble/curves/esm/abstract/utils.js.map create mode 100644 node_modules/@noble/curves/esm/abstract/weierstrass.js create mode 100644 node_modules/@noble/curves/esm/abstract/weierstrass.js.map create mode 100644 node_modules/@noble/curves/esm/bls12-381.js create mode 100644 node_modules/@noble/curves/esm/bls12-381.js.map create mode 100644 node_modules/@noble/curves/esm/bn254.js create mode 100644 node_modules/@noble/curves/esm/bn254.js.map create mode 100644 node_modules/@noble/curves/esm/ed25519.js create mode 100644 node_modules/@noble/curves/esm/ed25519.js.map create mode 100644 node_modules/@noble/curves/esm/ed448.js create mode 100644 node_modules/@noble/curves/esm/ed448.js.map create mode 100644 node_modules/@noble/curves/esm/index.js create mode 100644 node_modules/@noble/curves/esm/index.js.map create mode 100644 node_modules/@noble/curves/esm/jubjub.js create mode 100644 node_modules/@noble/curves/esm/jubjub.js.map create mode 100644 node_modules/@noble/curves/esm/p256.js create mode 100644 node_modules/@noble/curves/esm/p256.js.map create mode 100644 node_modules/@noble/curves/esm/p384.js create mode 100644 node_modules/@noble/curves/esm/p384.js.map create mode 100644 node_modules/@noble/curves/esm/p521.js create mode 100644 node_modules/@noble/curves/esm/p521.js.map create mode 100644 node_modules/@noble/curves/esm/package.json create mode 100644 node_modules/@noble/curves/esm/pasta.js create mode 100644 node_modules/@noble/curves/esm/pasta.js.map create mode 100644 node_modules/@noble/curves/esm/secp256k1.js create mode 100644 node_modules/@noble/curves/esm/secp256k1.js.map create mode 100644 node_modules/@noble/curves/index.d.ts create mode 100644 node_modules/@noble/curves/index.d.ts.map create mode 100644 node_modules/@noble/curves/index.js create mode 100644 node_modules/@noble/curves/index.js.map create mode 100644 node_modules/@noble/curves/jubjub.d.ts create mode 100644 node_modules/@noble/curves/jubjub.d.ts.map create mode 100644 node_modules/@noble/curves/jubjub.js create mode 100644 node_modules/@noble/curves/jubjub.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/LICENSE create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/README.md create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/_assert.d.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/_assert.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/_assert.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/_blake2.d.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/_blake2.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/_blake2.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/_sha2.d.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/_sha2.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/_sha2.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/_u64.d.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/_u64.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/_u64.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/argon2.d.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/argon2.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/argon2.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/blake2b.d.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/blake2b.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/blake2b.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/blake2s.d.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/blake2s.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/blake2s.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/blake3.d.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/blake3.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/blake3.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/crypto.d.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/crypto.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/crypto.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/cryptoNode.d.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/cryptoNode.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/cryptoNode.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/eskdf.d.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/eskdf.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/eskdf.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/_assert.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/_assert.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/_blake2.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/_blake2.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/_sha2.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/_sha2.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/_u64.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/_u64.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/argon2.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/argon2.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake2b.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake2b.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake2s.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake2s.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake3.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake3.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/crypto.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/crypto.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/cryptoNode.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/cryptoNode.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/eskdf.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/eskdf.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/hkdf.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/hkdf.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/hmac.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/hmac.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/index.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/index.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/package.json create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/pbkdf2.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/pbkdf2.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/ripemd160.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/ripemd160.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/scrypt.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/scrypt.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha1.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha1.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha256.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha256.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha3-addons.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha3-addons.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha3.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha3.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha512.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha512.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/hkdf.d.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/hkdf.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/hkdf.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/hmac.d.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/hmac.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/hmac.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/index.d.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/index.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/index.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/package.json create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/pbkdf2.d.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/pbkdf2.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/pbkdf2.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/ripemd160.d.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/ripemd160.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/ripemd160.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/scrypt.d.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/scrypt.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/scrypt.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/sha1.d.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/sha1.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/sha1.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/sha256.d.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/sha256.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/sha256.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/sha3-addons.d.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/sha3-addons.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/sha3-addons.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/sha3.d.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/sha3.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/sha3.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/sha512.d.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/sha512.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/sha512.js.map create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/src/_assert.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/src/_blake2.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/src/_sha2.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/src/_u64.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/src/argon2.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/src/blake2b.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/src/blake2s.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/src/blake3.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/src/crypto.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/src/cryptoNode.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/src/eskdf.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/src/hkdf.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/src/hmac.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/src/index.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/src/pbkdf2.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/src/ripemd160.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/src/scrypt.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/src/sha1.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/src/sha256.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/src/sha3-addons.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/src/sha3.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/src/sha512.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/src/utils.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/utils.d.ts create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/utils.js create mode 100644 node_modules/@noble/curves/node_modules/@noble/hashes/utils.js.map create mode 100644 node_modules/@noble/curves/p256.d.ts create mode 100644 node_modules/@noble/curves/p256.d.ts.map create mode 100644 node_modules/@noble/curves/p256.js create mode 100644 node_modules/@noble/curves/p256.js.map create mode 100644 node_modules/@noble/curves/p384.d.ts create mode 100644 node_modules/@noble/curves/p384.d.ts.map create mode 100644 node_modules/@noble/curves/p384.js create mode 100644 node_modules/@noble/curves/p384.js.map create mode 100644 node_modules/@noble/curves/p521.d.ts create mode 100644 node_modules/@noble/curves/p521.d.ts.map create mode 100644 node_modules/@noble/curves/p521.js create mode 100644 node_modules/@noble/curves/p521.js.map create mode 100644 node_modules/@noble/curves/package.json create mode 100644 node_modules/@noble/curves/pasta.d.ts create mode 100644 node_modules/@noble/curves/pasta.d.ts.map create mode 100644 node_modules/@noble/curves/pasta.js create mode 100644 node_modules/@noble/curves/pasta.js.map create mode 100644 node_modules/@noble/curves/secp256k1.d.ts create mode 100644 node_modules/@noble/curves/secp256k1.d.ts.map create mode 100644 node_modules/@noble/curves/secp256k1.js create mode 100644 node_modules/@noble/curves/secp256k1.js.map create mode 100644 node_modules/@noble/curves/src/_shortw_utils.ts create mode 100644 node_modules/@noble/curves/src/abstract/bls.ts create mode 100644 node_modules/@noble/curves/src/abstract/curve.ts create mode 100644 node_modules/@noble/curves/src/abstract/edwards.ts create mode 100644 node_modules/@noble/curves/src/abstract/hash-to-curve.ts create mode 100644 node_modules/@noble/curves/src/abstract/modular.ts create mode 100644 node_modules/@noble/curves/src/abstract/montgomery.ts create mode 100644 node_modules/@noble/curves/src/abstract/poseidon.ts create mode 100644 node_modules/@noble/curves/src/abstract/utils.ts create mode 100644 node_modules/@noble/curves/src/abstract/weierstrass.ts create mode 100644 node_modules/@noble/curves/src/bls12-381.ts create mode 100644 node_modules/@noble/curves/src/bn254.ts create mode 100644 node_modules/@noble/curves/src/ed25519.ts create mode 100644 node_modules/@noble/curves/src/ed448.ts create mode 100644 node_modules/@noble/curves/src/index.ts create mode 100644 node_modules/@noble/curves/src/jubjub.ts create mode 100644 node_modules/@noble/curves/src/p256.ts create mode 100644 node_modules/@noble/curves/src/p384.ts create mode 100644 node_modules/@noble/curves/src/p521.ts create mode 100644 node_modules/@noble/curves/src/pasta.ts create mode 100644 node_modules/@noble/curves/src/secp256k1.ts create mode 100644 node_modules/@noble/hashes/LICENSE create mode 100644 node_modules/@noble/hashes/README.md create mode 100644 node_modules/@noble/hashes/_assert.d.ts create mode 100644 node_modules/@noble/hashes/_assert.js create mode 100644 node_modules/@noble/hashes/_assert.js.map create mode 100644 node_modules/@noble/hashes/_blake2.d.ts create mode 100644 node_modules/@noble/hashes/_blake2.js create mode 100644 node_modules/@noble/hashes/_blake2.js.map create mode 100644 node_modules/@noble/hashes/_sha2.d.ts create mode 100644 node_modules/@noble/hashes/_sha2.js create mode 100644 node_modules/@noble/hashes/_sha2.js.map create mode 100644 node_modules/@noble/hashes/_u64.d.ts create mode 100644 node_modules/@noble/hashes/_u64.js create mode 100644 node_modules/@noble/hashes/_u64.js.map create mode 100644 node_modules/@noble/hashes/argon2.d.ts create mode 100644 node_modules/@noble/hashes/argon2.js create mode 100644 node_modules/@noble/hashes/argon2.js.map create mode 100644 node_modules/@noble/hashes/blake2b.d.ts create mode 100644 node_modules/@noble/hashes/blake2b.js create mode 100644 node_modules/@noble/hashes/blake2b.js.map create mode 100644 node_modules/@noble/hashes/blake2s.d.ts create mode 100644 node_modules/@noble/hashes/blake2s.js create mode 100644 node_modules/@noble/hashes/blake2s.js.map create mode 100644 node_modules/@noble/hashes/blake3.d.ts create mode 100644 node_modules/@noble/hashes/blake3.js create mode 100644 node_modules/@noble/hashes/blake3.js.map create mode 100644 node_modules/@noble/hashes/crypto.d.ts create mode 100644 node_modules/@noble/hashes/crypto.js create mode 100644 node_modules/@noble/hashes/crypto.js.map create mode 100644 node_modules/@noble/hashes/cryptoNode.d.ts create mode 100644 node_modules/@noble/hashes/cryptoNode.js create mode 100644 node_modules/@noble/hashes/cryptoNode.js.map create mode 100644 node_modules/@noble/hashes/eskdf.d.ts create mode 100644 node_modules/@noble/hashes/eskdf.js create mode 100644 node_modules/@noble/hashes/eskdf.js.map create mode 100644 node_modules/@noble/hashes/esm/_assert.js create mode 100644 node_modules/@noble/hashes/esm/_assert.js.map create mode 100644 node_modules/@noble/hashes/esm/_blake2.js create mode 100644 node_modules/@noble/hashes/esm/_blake2.js.map create mode 100644 node_modules/@noble/hashes/esm/_sha2.js create mode 100644 node_modules/@noble/hashes/esm/_sha2.js.map create mode 100644 node_modules/@noble/hashes/esm/_u64.js create mode 100644 node_modules/@noble/hashes/esm/_u64.js.map create mode 100644 node_modules/@noble/hashes/esm/argon2.js create mode 100644 node_modules/@noble/hashes/esm/argon2.js.map create mode 100644 node_modules/@noble/hashes/esm/blake2b.js create mode 100644 node_modules/@noble/hashes/esm/blake2b.js.map create mode 100644 node_modules/@noble/hashes/esm/blake2s.js create mode 100644 node_modules/@noble/hashes/esm/blake2s.js.map create mode 100644 node_modules/@noble/hashes/esm/blake3.js create mode 100644 node_modules/@noble/hashes/esm/blake3.js.map create mode 100644 node_modules/@noble/hashes/esm/crypto.js create mode 100644 node_modules/@noble/hashes/esm/crypto.js.map create mode 100644 node_modules/@noble/hashes/esm/cryptoNode.js create mode 100644 node_modules/@noble/hashes/esm/cryptoNode.js.map create mode 100644 node_modules/@noble/hashes/esm/eskdf.js create mode 100644 node_modules/@noble/hashes/esm/eskdf.js.map create mode 100644 node_modules/@noble/hashes/esm/hkdf.js create mode 100644 node_modules/@noble/hashes/esm/hkdf.js.map create mode 100644 node_modules/@noble/hashes/esm/hmac.js create mode 100644 node_modules/@noble/hashes/esm/hmac.js.map create mode 100644 node_modules/@noble/hashes/esm/index.js create mode 100644 node_modules/@noble/hashes/esm/index.js.map create mode 100644 node_modules/@noble/hashes/esm/package.json create mode 100644 node_modules/@noble/hashes/esm/pbkdf2.js create mode 100644 node_modules/@noble/hashes/esm/pbkdf2.js.map create mode 100644 node_modules/@noble/hashes/esm/ripemd160.js create mode 100644 node_modules/@noble/hashes/esm/ripemd160.js.map create mode 100644 node_modules/@noble/hashes/esm/scrypt.js create mode 100644 node_modules/@noble/hashes/esm/scrypt.js.map create mode 100644 node_modules/@noble/hashes/esm/sha1.js create mode 100644 node_modules/@noble/hashes/esm/sha1.js.map create mode 100644 node_modules/@noble/hashes/esm/sha256.js create mode 100644 node_modules/@noble/hashes/esm/sha256.js.map create mode 100644 node_modules/@noble/hashes/esm/sha3-addons.js create mode 100644 node_modules/@noble/hashes/esm/sha3-addons.js.map create mode 100644 node_modules/@noble/hashes/esm/sha3.js create mode 100644 node_modules/@noble/hashes/esm/sha3.js.map create mode 100644 node_modules/@noble/hashes/esm/sha512.js create mode 100644 node_modules/@noble/hashes/esm/sha512.js.map create mode 100644 node_modules/@noble/hashes/esm/utils.js create mode 100644 node_modules/@noble/hashes/esm/utils.js.map create mode 100644 node_modules/@noble/hashes/hkdf.d.ts create mode 100644 node_modules/@noble/hashes/hkdf.js create mode 100644 node_modules/@noble/hashes/hkdf.js.map create mode 100644 node_modules/@noble/hashes/hmac.d.ts create mode 100644 node_modules/@noble/hashes/hmac.js create mode 100644 node_modules/@noble/hashes/hmac.js.map create mode 100644 node_modules/@noble/hashes/index.d.ts create mode 100644 node_modules/@noble/hashes/index.js create mode 100644 node_modules/@noble/hashes/index.js.map create mode 100644 node_modules/@noble/hashes/package.json create mode 100644 node_modules/@noble/hashes/pbkdf2.d.ts create mode 100644 node_modules/@noble/hashes/pbkdf2.js create mode 100644 node_modules/@noble/hashes/pbkdf2.js.map create mode 100644 node_modules/@noble/hashes/ripemd160.d.ts create mode 100644 node_modules/@noble/hashes/ripemd160.js create mode 100644 node_modules/@noble/hashes/ripemd160.js.map create mode 100644 node_modules/@noble/hashes/scrypt.d.ts create mode 100644 node_modules/@noble/hashes/scrypt.js create mode 100644 node_modules/@noble/hashes/scrypt.js.map create mode 100644 node_modules/@noble/hashes/sha1.d.ts create mode 100644 node_modules/@noble/hashes/sha1.js create mode 100644 node_modules/@noble/hashes/sha1.js.map create mode 100644 node_modules/@noble/hashes/sha256.d.ts create mode 100644 node_modules/@noble/hashes/sha256.js create mode 100644 node_modules/@noble/hashes/sha256.js.map create mode 100644 node_modules/@noble/hashes/sha3-addons.d.ts create mode 100644 node_modules/@noble/hashes/sha3-addons.js create mode 100644 node_modules/@noble/hashes/sha3-addons.js.map create mode 100644 node_modules/@noble/hashes/sha3.d.ts create mode 100644 node_modules/@noble/hashes/sha3.js create mode 100644 node_modules/@noble/hashes/sha3.js.map create mode 100644 node_modules/@noble/hashes/sha512.d.ts create mode 100644 node_modules/@noble/hashes/sha512.js create mode 100644 node_modules/@noble/hashes/sha512.js.map create mode 100644 node_modules/@noble/hashes/src/_assert.ts create mode 100644 node_modules/@noble/hashes/src/_blake2.ts create mode 100644 node_modules/@noble/hashes/src/_sha2.ts create mode 100644 node_modules/@noble/hashes/src/_u64.ts create mode 100644 node_modules/@noble/hashes/src/argon2.ts create mode 100644 node_modules/@noble/hashes/src/blake2b.ts create mode 100644 node_modules/@noble/hashes/src/blake2s.ts create mode 100644 node_modules/@noble/hashes/src/blake3.ts create mode 100644 node_modules/@noble/hashes/src/crypto.ts create mode 100644 node_modules/@noble/hashes/src/cryptoNode.ts create mode 100644 node_modules/@noble/hashes/src/eskdf.ts create mode 100644 node_modules/@noble/hashes/src/hkdf.ts create mode 100644 node_modules/@noble/hashes/src/hmac.ts create mode 100644 node_modules/@noble/hashes/src/index.ts create mode 100644 node_modules/@noble/hashes/src/pbkdf2.ts create mode 100644 node_modules/@noble/hashes/src/ripemd160.ts create mode 100644 node_modules/@noble/hashes/src/scrypt.ts create mode 100644 node_modules/@noble/hashes/src/sha1.ts create mode 100644 node_modules/@noble/hashes/src/sha256.ts create mode 100644 node_modules/@noble/hashes/src/sha3-addons.ts create mode 100644 node_modules/@noble/hashes/src/sha3.ts create mode 100644 node_modules/@noble/hashes/src/sha512.ts create mode 100644 node_modules/@noble/hashes/src/utils.ts create mode 100644 node_modules/@noble/hashes/utils.d.ts create mode 100644 node_modules/@noble/hashes/utils.js create mode 100644 node_modules/@noble/hashes/utils.js.map create mode 100644 node_modules/@scure/base/LICENSE create mode 100644 node_modules/@scure/base/README.md create mode 100644 node_modules/@scure/base/lib/esm/index.js create mode 100644 node_modules/@scure/base/lib/esm/package.json create mode 100644 node_modules/@scure/base/lib/index.d.ts create mode 100644 node_modules/@scure/base/lib/index.js create mode 100644 node_modules/@scure/base/package.json create mode 100644 node_modules/@scure/bip32/LICENSE create mode 100644 node_modules/@scure/bip32/README.md create mode 100644 node_modules/@scure/bip32/index.ts create mode 100644 node_modules/@scure/bip32/lib/esm/index.js create mode 100644 node_modules/@scure/bip32/lib/esm/index.js.map create mode 100644 node_modules/@scure/bip32/lib/esm/package.json create mode 100644 node_modules/@scure/bip32/lib/index.d.ts create mode 100644 node_modules/@scure/bip32/lib/index.js create mode 100644 node_modules/@scure/bip32/lib/index.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/LICENSE create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/README.md create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/_shortw_utils.d.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/_shortw_utils.d.ts.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/_shortw_utils.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/_shortw_utils.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/bls.d.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/bls.d.ts.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/bls.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/bls.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/curve.d.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/curve.d.ts.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/curve.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/curve.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/edwards.d.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/edwards.d.ts.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/edwards.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/edwards.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/hash-to-curve.d.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/hash-to-curve.d.ts.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/hash-to-curve.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/hash-to-curve.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/modular.d.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/modular.d.ts.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/modular.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/modular.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/montgomery.d.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/montgomery.d.ts.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/montgomery.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/montgomery.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/poseidon.d.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/poseidon.d.ts.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/poseidon.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/poseidon.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/utils.d.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/utils.d.ts.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/utils.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/utils.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/weierstrass.d.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/weierstrass.d.ts.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/weierstrass.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/abstract/weierstrass.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/bls12-381.d.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/bls12-381.d.ts.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/bls12-381.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/bls12-381.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/bn254.d.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/bn254.d.ts.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/bn254.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/bn254.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/ed25519.d.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/ed25519.d.ts.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/ed25519.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/ed25519.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/ed448.d.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/ed448.d.ts.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/ed448.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/ed448.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/_shortw_utils.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/_shortw_utils.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/bls.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/bls.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/curve.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/curve.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/edwards.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/edwards.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/hash-to-curve.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/hash-to-curve.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/modular.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/modular.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/montgomery.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/montgomery.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/poseidon.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/poseidon.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/utils.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/utils.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/weierstrass.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/weierstrass.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/bls12-381.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/bls12-381.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/bn254.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/bn254.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/ed25519.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/ed25519.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/ed448.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/ed448.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/index.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/index.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/jubjub.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/jubjub.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/p256.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/p256.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/p384.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/p384.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/p521.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/p521.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/package.json create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/pasta.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/pasta.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/secp256k1.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/esm/secp256k1.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/index.d.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/index.d.ts.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/index.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/index.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/jubjub.d.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/jubjub.d.ts.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/jubjub.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/jubjub.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/p256.d.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/p256.d.ts.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/p256.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/p256.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/p384.d.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/p384.d.ts.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/p384.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/p384.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/p521.d.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/p521.d.ts.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/p521.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/p521.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/package.json create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/pasta.d.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/pasta.d.ts.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/pasta.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/pasta.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/secp256k1.d.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/secp256k1.d.ts.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/secp256k1.js create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/secp256k1.js.map create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/src/_shortw_utils.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/bls.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/curve.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/edwards.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/hash-to-curve.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/modular.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/montgomery.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/poseidon.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/utils.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/weierstrass.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/src/bls12-381.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/src/bn254.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/src/ed25519.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/src/ed448.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/src/index.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/src/jubjub.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/src/p256.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/src/p384.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/src/p521.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/src/pasta.ts create mode 100644 node_modules/@scure/bip32/node_modules/@noble/curves/src/secp256k1.ts create mode 100644 node_modules/@scure/bip32/package.json create mode 100644 node_modules/@scure/bip39/LICENSE create mode 100644 node_modules/@scure/bip39/README.md create mode 100644 node_modules/@scure/bip39/esm/index.js create mode 100644 node_modules/@scure/bip39/esm/index.js.map create mode 100644 node_modules/@scure/bip39/esm/package.json create mode 100644 node_modules/@scure/bip39/esm/wordlists/czech.js create mode 100644 node_modules/@scure/bip39/esm/wordlists/czech.js.map create mode 100644 node_modules/@scure/bip39/esm/wordlists/english.js create mode 100644 node_modules/@scure/bip39/esm/wordlists/english.js.map create mode 100644 node_modules/@scure/bip39/esm/wordlists/french.js create mode 100644 node_modules/@scure/bip39/esm/wordlists/french.js.map create mode 100644 node_modules/@scure/bip39/esm/wordlists/italian.js create mode 100644 node_modules/@scure/bip39/esm/wordlists/italian.js.map create mode 100644 node_modules/@scure/bip39/esm/wordlists/japanese.js create mode 100644 node_modules/@scure/bip39/esm/wordlists/japanese.js.map create mode 100644 node_modules/@scure/bip39/esm/wordlists/korean.js create mode 100644 node_modules/@scure/bip39/esm/wordlists/korean.js.map create mode 100644 node_modules/@scure/bip39/esm/wordlists/simplified-chinese.js create mode 100644 node_modules/@scure/bip39/esm/wordlists/simplified-chinese.js.map create mode 100644 node_modules/@scure/bip39/esm/wordlists/spanish.js create mode 100644 node_modules/@scure/bip39/esm/wordlists/spanish.js.map create mode 100644 node_modules/@scure/bip39/esm/wordlists/traditional-chinese.js create mode 100644 node_modules/@scure/bip39/esm/wordlists/traditional-chinese.js.map create mode 100644 node_modules/@scure/bip39/index.d.ts create mode 100644 node_modules/@scure/bip39/index.js create mode 100644 node_modules/@scure/bip39/package.json create mode 100644 node_modules/@scure/bip39/wordlists/czech.d.ts create mode 100644 node_modules/@scure/bip39/wordlists/czech.js create mode 100644 node_modules/@scure/bip39/wordlists/english.d.ts create mode 100644 node_modules/@scure/bip39/wordlists/english.js create mode 100644 node_modules/@scure/bip39/wordlists/french.d.ts create mode 100644 node_modules/@scure/bip39/wordlists/french.js create mode 100644 node_modules/@scure/bip39/wordlists/italian.d.ts create mode 100644 node_modules/@scure/bip39/wordlists/italian.js create mode 100644 node_modules/@scure/bip39/wordlists/japanese.d.ts create mode 100644 node_modules/@scure/bip39/wordlists/japanese.js create mode 100644 node_modules/@scure/bip39/wordlists/korean.d.ts create mode 100644 node_modules/@scure/bip39/wordlists/korean.js create mode 100644 node_modules/@scure/bip39/wordlists/simplified-chinese.d.ts create mode 100644 node_modules/@scure/bip39/wordlists/simplified-chinese.js create mode 100644 node_modules/@scure/bip39/wordlists/spanish.d.ts create mode 100644 node_modules/@scure/bip39/wordlists/spanish.js create mode 100644 node_modules/@scure/bip39/wordlists/traditional-chinese.d.ts create mode 100644 node_modules/@scure/bip39/wordlists/traditional-chinese.js create mode 100644 node_modules/accepts/HISTORY.md create mode 100644 node_modules/accepts/LICENSE create mode 100644 node_modules/accepts/README.md create mode 100644 node_modules/accepts/index.js create mode 100644 node_modules/accepts/package.json create mode 100644 node_modules/async/CHANGELOG.md create mode 100644 node_modules/async/LICENSE create mode 100644 node_modules/async/README.md create mode 100644 node_modules/async/all.js create mode 100644 node_modules/async/allLimit.js create mode 100644 node_modules/async/allSeries.js create mode 100644 node_modules/async/any.js create mode 100644 node_modules/async/anyLimit.js create mode 100644 node_modules/async/anySeries.js create mode 100644 node_modules/async/apply.js create mode 100644 node_modules/async/applyEach.js create mode 100644 node_modules/async/applyEachSeries.js create mode 100644 node_modules/async/asyncify.js create mode 100644 node_modules/async/auto.js create mode 100644 node_modules/async/autoInject.js create mode 100644 node_modules/async/bower.json create mode 100644 node_modules/async/cargo.js create mode 100644 node_modules/async/cargoQueue.js create mode 100644 node_modules/async/compose.js create mode 100644 node_modules/async/concat.js create mode 100644 node_modules/async/concatLimit.js create mode 100644 node_modules/async/concatSeries.js create mode 100644 node_modules/async/constant.js create mode 100644 node_modules/async/detect.js create mode 100644 node_modules/async/detectLimit.js create mode 100644 node_modules/async/detectSeries.js create mode 100644 node_modules/async/dir.js create mode 100644 node_modules/async/dist/async.js create mode 100644 node_modules/async/dist/async.min.js create mode 100644 node_modules/async/dist/async.mjs create mode 100644 node_modules/async/doDuring.js create mode 100644 node_modules/async/doUntil.js create mode 100644 node_modules/async/doWhilst.js create mode 100644 node_modules/async/during.js create mode 100644 node_modules/async/each.js create mode 100644 node_modules/async/eachLimit.js create mode 100644 node_modules/async/eachOf.js create mode 100644 node_modules/async/eachOfLimit.js create mode 100644 node_modules/async/eachOfSeries.js create mode 100644 node_modules/async/eachSeries.js create mode 100644 node_modules/async/ensureAsync.js create mode 100644 node_modules/async/every.js create mode 100644 node_modules/async/everyLimit.js create mode 100644 node_modules/async/everySeries.js create mode 100644 node_modules/async/filter.js create mode 100644 node_modules/async/filterLimit.js create mode 100644 node_modules/async/filterSeries.js create mode 100644 node_modules/async/find.js create mode 100644 node_modules/async/findLimit.js create mode 100644 node_modules/async/findSeries.js create mode 100644 node_modules/async/flatMap.js create mode 100644 node_modules/async/flatMapLimit.js create mode 100644 node_modules/async/flatMapSeries.js create mode 100644 node_modules/async/foldl.js create mode 100644 node_modules/async/foldr.js create mode 100644 node_modules/async/forEach.js create mode 100644 node_modules/async/forEachLimit.js create mode 100644 node_modules/async/forEachOf.js create mode 100644 node_modules/async/forEachOfLimit.js create mode 100644 node_modules/async/forEachOfSeries.js create mode 100644 node_modules/async/forEachSeries.js create mode 100644 node_modules/async/forever.js create mode 100644 node_modules/async/groupBy.js create mode 100644 node_modules/async/groupByLimit.js create mode 100644 node_modules/async/groupBySeries.js create mode 100644 node_modules/async/index.js create mode 100644 node_modules/async/inject.js create mode 100644 node_modules/async/internal/DoublyLinkedList.js create mode 100644 node_modules/async/internal/Heap.js create mode 100644 node_modules/async/internal/applyEach.js create mode 100644 node_modules/async/internal/asyncEachOfLimit.js create mode 100644 node_modules/async/internal/awaitify.js create mode 100644 node_modules/async/internal/breakLoop.js create mode 100644 node_modules/async/internal/consoleFunc.js create mode 100644 node_modules/async/internal/createTester.js create mode 100644 node_modules/async/internal/eachOfLimit.js create mode 100644 node_modules/async/internal/filter.js create mode 100644 node_modules/async/internal/getIterator.js create mode 100644 node_modules/async/internal/initialParams.js create mode 100644 node_modules/async/internal/isArrayLike.js create mode 100644 node_modules/async/internal/iterator.js create mode 100644 node_modules/async/internal/map.js create mode 100644 node_modules/async/internal/once.js create mode 100644 node_modules/async/internal/onlyOnce.js create mode 100644 node_modules/async/internal/parallel.js create mode 100644 node_modules/async/internal/promiseCallback.js create mode 100644 node_modules/async/internal/queue.js create mode 100644 node_modules/async/internal/range.js create mode 100644 node_modules/async/internal/reject.js create mode 100644 node_modules/async/internal/setImmediate.js create mode 100644 node_modules/async/internal/withoutIndex.js create mode 100644 node_modules/async/internal/wrapAsync.js create mode 100644 node_modules/async/log.js create mode 100644 node_modules/async/map.js create mode 100644 node_modules/async/mapLimit.js create mode 100644 node_modules/async/mapSeries.js create mode 100644 node_modules/async/mapValues.js create mode 100644 node_modules/async/mapValuesLimit.js create mode 100644 node_modules/async/mapValuesSeries.js create mode 100644 node_modules/async/memoize.js create mode 100644 node_modules/async/nextTick.js create mode 100644 node_modules/async/package.json create mode 100644 node_modules/async/parallel.js create mode 100644 node_modules/async/parallelLimit.js create mode 100644 node_modules/async/priorityQueue.js create mode 100644 node_modules/async/queue.js create mode 100644 node_modules/async/race.js create mode 100644 node_modules/async/reduce.js create mode 100644 node_modules/async/reduceRight.js create mode 100644 node_modules/async/reflect.js create mode 100644 node_modules/async/reflectAll.js create mode 100644 node_modules/async/reject.js create mode 100644 node_modules/async/rejectLimit.js create mode 100644 node_modules/async/rejectSeries.js create mode 100644 node_modules/async/retry.js create mode 100644 node_modules/async/retryable.js create mode 100644 node_modules/async/select.js create mode 100644 node_modules/async/selectLimit.js create mode 100644 node_modules/async/selectSeries.js create mode 100644 node_modules/async/seq.js create mode 100644 node_modules/async/series.js create mode 100644 node_modules/async/setImmediate.js create mode 100644 node_modules/async/some.js create mode 100644 node_modules/async/someLimit.js create mode 100644 node_modules/async/someSeries.js create mode 100644 node_modules/async/sortBy.js create mode 100644 node_modules/async/timeout.js create mode 100644 node_modules/async/times.js create mode 100644 node_modules/async/timesLimit.js create mode 100644 node_modules/async/timesSeries.js create mode 100644 node_modules/async/transform.js create mode 100644 node_modules/async/tryEach.js create mode 100644 node_modules/async/unmemoize.js create mode 100644 node_modules/async/until.js create mode 100644 node_modules/async/waterfall.js create mode 100644 node_modules/async/whilst.js create mode 100644 node_modules/async/wrapSync.js create mode 100644 node_modules/balanced-match/.github/FUNDING.yml create mode 100644 node_modules/balanced-match/LICENSE.md create mode 100644 node_modules/balanced-match/README.md create mode 100644 node_modules/balanced-match/index.js create mode 100644 node_modules/balanced-match/package.json create mode 100644 node_modules/body-parser/HISTORY.md create mode 100644 node_modules/body-parser/LICENSE create mode 100644 node_modules/body-parser/README.md create mode 100644 node_modules/body-parser/index.js create mode 100644 node_modules/body-parser/lib/read.js create mode 100644 node_modules/body-parser/lib/types/json.js create mode 100644 node_modules/body-parser/lib/types/raw.js create mode 100644 node_modules/body-parser/lib/types/text.js create mode 100644 node_modules/body-parser/lib/types/urlencoded.js create mode 100644 node_modules/body-parser/lib/utils.js create mode 100644 node_modules/body-parser/package.json create mode 100644 node_modules/brace-expansion/.github/FUNDING.yml create mode 100644 node_modules/brace-expansion/LICENSE create mode 100644 node_modules/brace-expansion/README.md create mode 100644 node_modules/brace-expansion/index.js create mode 100644 node_modules/brace-expansion/package.json create mode 100644 node_modules/buffer-equal-constant-time/.npmignore create mode 100644 node_modules/buffer-equal-constant-time/.travis.yml create mode 100644 node_modules/buffer-equal-constant-time/LICENSE.txt create mode 100644 node_modules/buffer-equal-constant-time/README.md create mode 100644 node_modules/buffer-equal-constant-time/index.js create mode 100644 node_modules/buffer-equal-constant-time/package.json create mode 100644 node_modules/buffer-equal-constant-time/test.js create mode 100644 node_modules/bytes/History.md create mode 100644 node_modules/bytes/LICENSE create mode 100644 node_modules/bytes/Readme.md create mode 100644 node_modules/bytes/index.js create mode 100644 node_modules/bytes/package.json create mode 100644 node_modules/call-bind-apply-helpers/.eslintrc create mode 100644 node_modules/call-bind-apply-helpers/.github/FUNDING.yml create mode 100644 node_modules/call-bind-apply-helpers/.nycrc create mode 100644 node_modules/call-bind-apply-helpers/CHANGELOG.md create mode 100644 node_modules/call-bind-apply-helpers/LICENSE create mode 100644 node_modules/call-bind-apply-helpers/README.md create mode 100644 node_modules/call-bind-apply-helpers/actualApply.d.ts create mode 100644 node_modules/call-bind-apply-helpers/actualApply.js create mode 100644 node_modules/call-bind-apply-helpers/applyBind.d.ts create mode 100644 node_modules/call-bind-apply-helpers/applyBind.js create mode 100644 node_modules/call-bind-apply-helpers/functionApply.d.ts create mode 100644 node_modules/call-bind-apply-helpers/functionApply.js create mode 100644 node_modules/call-bind-apply-helpers/functionCall.d.ts create mode 100644 node_modules/call-bind-apply-helpers/functionCall.js create mode 100644 node_modules/call-bind-apply-helpers/index.d.ts create mode 100644 node_modules/call-bind-apply-helpers/index.js create mode 100644 node_modules/call-bind-apply-helpers/package.json create mode 100644 node_modules/call-bind-apply-helpers/reflectApply.d.ts create mode 100644 node_modules/call-bind-apply-helpers/reflectApply.js create mode 100644 node_modules/call-bind-apply-helpers/test/index.js create mode 100644 node_modules/call-bind-apply-helpers/tsconfig.json create mode 100644 node_modules/call-bound/.eslintrc create mode 100644 node_modules/call-bound/.github/FUNDING.yml create mode 100644 node_modules/call-bound/.nycrc create mode 100644 node_modules/call-bound/CHANGELOG.md create mode 100644 node_modules/call-bound/LICENSE create mode 100644 node_modules/call-bound/README.md create mode 100644 node_modules/call-bound/index.d.ts create mode 100644 node_modules/call-bound/index.js create mode 100644 node_modules/call-bound/package.json create mode 100644 node_modules/call-bound/test/index.js create mode 100644 node_modules/call-bound/tsconfig.json create mode 100644 node_modules/content-disposition/HISTORY.md create mode 100644 node_modules/content-disposition/LICENSE create mode 100644 node_modules/content-disposition/README.md create mode 100644 node_modules/content-disposition/index.js create mode 100644 node_modules/content-disposition/package.json create mode 100644 node_modules/content-type/HISTORY.md create mode 100644 node_modules/content-type/LICENSE create mode 100644 node_modules/content-type/README.md create mode 100644 node_modules/content-type/index.js create mode 100644 node_modules/content-type/package.json create mode 100644 node_modules/cookie-signature/History.md create mode 100644 node_modules/cookie-signature/LICENSE create mode 100644 node_modules/cookie-signature/Readme.md create mode 100644 node_modules/cookie-signature/index.js create mode 100644 node_modules/cookie-signature/package.json create mode 100644 node_modules/cookie/LICENSE create mode 100644 node_modules/cookie/README.md create mode 100644 node_modules/cookie/SECURITY.md create mode 100644 node_modules/cookie/index.js create mode 100644 node_modules/cookie/package.json create mode 100644 node_modules/debug/LICENSE create mode 100644 node_modules/debug/README.md create mode 100644 node_modules/debug/package.json create mode 100644 node_modules/debug/src/browser.js create mode 100644 node_modules/debug/src/common.js create mode 100644 node_modules/debug/src/index.js create mode 100644 node_modules/debug/src/node.js create mode 100644 node_modules/depd/History.md create mode 100644 node_modules/depd/LICENSE create mode 100644 node_modules/depd/Readme.md create mode 100644 node_modules/depd/index.js create mode 100644 node_modules/depd/lib/browser/index.js create mode 100644 node_modules/depd/package.json create mode 100644 node_modules/dunder-proto/.eslintrc create mode 100644 node_modules/dunder-proto/.github/FUNDING.yml create mode 100644 node_modules/dunder-proto/.nycrc create mode 100644 node_modules/dunder-proto/CHANGELOG.md create mode 100644 node_modules/dunder-proto/LICENSE create mode 100644 node_modules/dunder-proto/README.md create mode 100644 node_modules/dunder-proto/get.d.ts create mode 100644 node_modules/dunder-proto/get.js create mode 100644 node_modules/dunder-proto/package.json create mode 100644 node_modules/dunder-proto/set.d.ts create mode 100644 node_modules/dunder-proto/set.js create mode 100644 node_modules/dunder-proto/test/get.js create mode 100644 node_modules/dunder-proto/test/index.js create mode 100644 node_modules/dunder-proto/test/set.js create mode 100644 node_modules/dunder-proto/tsconfig.json create mode 100644 node_modules/ecdsa-sig-formatter/CODEOWNERS create mode 100644 node_modules/ecdsa-sig-formatter/LICENSE create mode 100644 node_modules/ecdsa-sig-formatter/README.md create mode 100644 node_modules/ecdsa-sig-formatter/package.json create mode 100644 node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.d.ts create mode 100644 node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js create mode 100644 node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js create mode 100644 node_modules/ee-first/LICENSE create mode 100644 node_modules/ee-first/README.md create mode 100644 node_modules/ee-first/index.js create mode 100644 node_modules/ee-first/package.json create mode 100644 node_modules/ejs/LICENSE create mode 100644 node_modules/ejs/README.md create mode 100755 node_modules/ejs/bin/cli.js create mode 100644 node_modules/ejs/ejs.js create mode 100644 node_modules/ejs/ejs.min.js create mode 100644 node_modules/ejs/jakefile.js create mode 100755 node_modules/ejs/lib/ejs.js create mode 100644 node_modules/ejs/lib/utils.js create mode 100644 node_modules/ejs/package.json create mode 100644 node_modules/ejs/usage.txt create mode 100644 node_modules/encodeurl/LICENSE create mode 100644 node_modules/encodeurl/README.md create mode 100644 node_modules/encodeurl/index.js create mode 100644 node_modules/encodeurl/package.json create mode 100644 node_modules/es-define-property/.eslintrc create mode 100644 node_modules/es-define-property/.github/FUNDING.yml create mode 100644 node_modules/es-define-property/.nycrc create mode 100644 node_modules/es-define-property/CHANGELOG.md create mode 100644 node_modules/es-define-property/LICENSE create mode 100644 node_modules/es-define-property/README.md create mode 100644 node_modules/es-define-property/index.d.ts create mode 100644 node_modules/es-define-property/index.js create mode 100644 node_modules/es-define-property/package.json create mode 100644 node_modules/es-define-property/test/index.js create mode 100644 node_modules/es-define-property/tsconfig.json create mode 100644 node_modules/es-errors/.eslintrc create mode 100644 node_modules/es-errors/.github/FUNDING.yml create mode 100644 node_modules/es-errors/CHANGELOG.md create mode 100644 node_modules/es-errors/LICENSE create mode 100644 node_modules/es-errors/README.md create mode 100644 node_modules/es-errors/eval.d.ts create mode 100644 node_modules/es-errors/eval.js create mode 100644 node_modules/es-errors/index.d.ts create mode 100644 node_modules/es-errors/index.js create mode 100644 node_modules/es-errors/package.json create mode 100644 node_modules/es-errors/range.d.ts create mode 100644 node_modules/es-errors/range.js create mode 100644 node_modules/es-errors/ref.d.ts create mode 100644 node_modules/es-errors/ref.js create mode 100644 node_modules/es-errors/syntax.d.ts create mode 100644 node_modules/es-errors/syntax.js create mode 100644 node_modules/es-errors/test/index.js create mode 100644 node_modules/es-errors/tsconfig.json create mode 100644 node_modules/es-errors/type.d.ts create mode 100644 node_modules/es-errors/type.js create mode 100644 node_modules/es-errors/uri.d.ts create mode 100644 node_modules/es-errors/uri.js create mode 100644 node_modules/es-object-atoms/.eslintrc create mode 100644 node_modules/es-object-atoms/.github/FUNDING.yml create mode 100644 node_modules/es-object-atoms/CHANGELOG.md create mode 100644 node_modules/es-object-atoms/LICENSE create mode 100644 node_modules/es-object-atoms/README.md create mode 100644 node_modules/es-object-atoms/RequireObjectCoercible.d.ts create mode 100644 node_modules/es-object-atoms/RequireObjectCoercible.js create mode 100644 node_modules/es-object-atoms/ToObject.d.ts create mode 100644 node_modules/es-object-atoms/ToObject.js create mode 100644 node_modules/es-object-atoms/index.d.ts create mode 100644 node_modules/es-object-atoms/index.js create mode 100644 node_modules/es-object-atoms/isObject.d.ts create mode 100644 node_modules/es-object-atoms/isObject.js create mode 100644 node_modules/es-object-atoms/package.json create mode 100644 node_modules/es-object-atoms/test/index.js create mode 100644 node_modules/es-object-atoms/tsconfig.json create mode 100644 node_modules/escape-html/LICENSE create mode 100644 node_modules/escape-html/Readme.md create mode 100644 node_modules/escape-html/index.js create mode 100644 node_modules/escape-html/package.json create mode 100644 node_modules/etag/HISTORY.md create mode 100644 node_modules/etag/LICENSE create mode 100644 node_modules/etag/README.md create mode 100644 node_modules/etag/index.js create mode 100644 node_modules/etag/package.json create mode 100644 node_modules/express/History.md create mode 100644 node_modules/express/LICENSE create mode 100644 node_modules/express/Readme.md create mode 100644 node_modules/express/index.js create mode 100644 node_modules/express/lib/application.js create mode 100644 node_modules/express/lib/express.js create mode 100644 node_modules/express/lib/request.js create mode 100644 node_modules/express/lib/response.js create mode 100644 node_modules/express/lib/utils.js create mode 100644 node_modules/express/lib/view.js create mode 100644 node_modules/express/package.json create mode 100644 node_modules/filelist/README.md create mode 100644 node_modules/filelist/index.d.ts create mode 100644 node_modules/filelist/index.js create mode 100644 node_modules/filelist/jakefile.js create mode 100644 node_modules/filelist/package.json create mode 100644 node_modules/finalhandler/HISTORY.md create mode 100644 node_modules/finalhandler/LICENSE create mode 100644 node_modules/finalhandler/README.md create mode 100644 node_modules/finalhandler/index.js create mode 100644 node_modules/finalhandler/package.json create mode 100644 node_modules/forwarded/HISTORY.md create mode 100644 node_modules/forwarded/LICENSE create mode 100644 node_modules/forwarded/README.md create mode 100644 node_modules/forwarded/index.js create mode 100644 node_modules/forwarded/package.json create mode 100644 node_modules/fresh/HISTORY.md create mode 100644 node_modules/fresh/LICENSE create mode 100644 node_modules/fresh/README.md create mode 100644 node_modules/fresh/index.js create mode 100644 node_modules/fresh/package.json create mode 100644 node_modules/function-bind/.eslintrc create mode 100644 node_modules/function-bind/.github/FUNDING.yml create mode 100644 node_modules/function-bind/.github/SECURITY.md create mode 100644 node_modules/function-bind/.nycrc create mode 100644 node_modules/function-bind/CHANGELOG.md create mode 100644 node_modules/function-bind/LICENSE create mode 100644 node_modules/function-bind/README.md create mode 100644 node_modules/function-bind/implementation.js create mode 100644 node_modules/function-bind/index.js create mode 100644 node_modules/function-bind/package.json create mode 100644 node_modules/function-bind/test/.eslintrc create mode 100644 node_modules/function-bind/test/index.js create mode 100644 node_modules/get-intrinsic/.eslintrc create mode 100644 node_modules/get-intrinsic/.github/FUNDING.yml create mode 100644 node_modules/get-intrinsic/.nycrc create mode 100644 node_modules/get-intrinsic/CHANGELOG.md create mode 100644 node_modules/get-intrinsic/LICENSE create mode 100644 node_modules/get-intrinsic/README.md create mode 100644 node_modules/get-intrinsic/index.js create mode 100644 node_modules/get-intrinsic/package.json create mode 100644 node_modules/get-intrinsic/test/GetIntrinsic.js create mode 100644 node_modules/get-proto/.eslintrc create mode 100644 node_modules/get-proto/.github/FUNDING.yml create mode 100644 node_modules/get-proto/.nycrc create mode 100644 node_modules/get-proto/CHANGELOG.md create mode 100644 node_modules/get-proto/LICENSE create mode 100644 node_modules/get-proto/Object.getPrototypeOf.d.ts create mode 100644 node_modules/get-proto/Object.getPrototypeOf.js create mode 100644 node_modules/get-proto/README.md create mode 100644 node_modules/get-proto/Reflect.getPrototypeOf.d.ts create mode 100644 node_modules/get-proto/Reflect.getPrototypeOf.js create mode 100644 node_modules/get-proto/index.d.ts create mode 100644 node_modules/get-proto/index.js create mode 100644 node_modules/get-proto/package.json create mode 100644 node_modules/get-proto/test/index.js create mode 100644 node_modules/get-proto/tsconfig.json create mode 100644 node_modules/gopd/.eslintrc create mode 100644 node_modules/gopd/.github/FUNDING.yml create mode 100644 node_modules/gopd/CHANGELOG.md create mode 100644 node_modules/gopd/LICENSE create mode 100644 node_modules/gopd/README.md create mode 100644 node_modules/gopd/gOPD.d.ts create mode 100644 node_modules/gopd/gOPD.js create mode 100644 node_modules/gopd/index.d.ts create mode 100644 node_modules/gopd/index.js create mode 100644 node_modules/gopd/package.json create mode 100644 node_modules/gopd/test/index.js create mode 100644 node_modules/gopd/tsconfig.json create mode 100644 node_modules/has-symbols/.eslintrc create mode 100644 node_modules/has-symbols/.github/FUNDING.yml create mode 100644 node_modules/has-symbols/.nycrc create mode 100644 node_modules/has-symbols/CHANGELOG.md create mode 100644 node_modules/has-symbols/LICENSE create mode 100644 node_modules/has-symbols/README.md create mode 100644 node_modules/has-symbols/index.d.ts create mode 100644 node_modules/has-symbols/index.js create mode 100644 node_modules/has-symbols/package.json create mode 100644 node_modules/has-symbols/shams.d.ts create mode 100644 node_modules/has-symbols/shams.js create mode 100644 node_modules/has-symbols/test/index.js create mode 100644 node_modules/has-symbols/test/shams/core-js.js create mode 100644 node_modules/has-symbols/test/shams/get-own-property-symbols.js create mode 100644 node_modules/has-symbols/test/tests.js create mode 100644 node_modules/has-symbols/tsconfig.json create mode 100644 node_modules/hasown/.eslintrc create mode 100644 node_modules/hasown/.github/FUNDING.yml create mode 100644 node_modules/hasown/.nycrc create mode 100644 node_modules/hasown/CHANGELOG.md create mode 100644 node_modules/hasown/LICENSE create mode 100644 node_modules/hasown/README.md create mode 100644 node_modules/hasown/index.d.ts create mode 100644 node_modules/hasown/index.js create mode 100644 node_modules/hasown/package.json create mode 100644 node_modules/hasown/tsconfig.json create mode 100644 node_modules/http-errors/HISTORY.md create mode 100644 node_modules/http-errors/LICENSE create mode 100644 node_modules/http-errors/README.md create mode 100644 node_modules/http-errors/index.js create mode 100644 node_modules/http-errors/node_modules/statuses/HISTORY.md create mode 100644 node_modules/http-errors/node_modules/statuses/LICENSE create mode 100644 node_modules/http-errors/node_modules/statuses/README.md create mode 100644 node_modules/http-errors/node_modules/statuses/codes.json create mode 100644 node_modules/http-errors/node_modules/statuses/index.js create mode 100644 node_modules/http-errors/node_modules/statuses/package.json create mode 100644 node_modules/http-errors/package.json create mode 100644 node_modules/iconv-lite/.github/dependabot.yml create mode 100644 node_modules/iconv-lite/.idea/codeStyles/Project.xml create mode 100644 node_modules/iconv-lite/.idea/codeStyles/codeStyleConfig.xml create mode 100644 node_modules/iconv-lite/.idea/iconv-lite.iml create mode 100644 node_modules/iconv-lite/.idea/inspectionProfiles/Project_Default.xml create mode 100644 node_modules/iconv-lite/.idea/modules.xml create mode 100644 node_modules/iconv-lite/.idea/vcs.xml create mode 100644 node_modules/iconv-lite/Changelog.md create mode 100644 node_modules/iconv-lite/LICENSE create mode 100644 node_modules/iconv-lite/README.md create mode 100644 node_modules/iconv-lite/encodings/dbcs-codec.js create mode 100644 node_modules/iconv-lite/encodings/dbcs-data.js create mode 100644 node_modules/iconv-lite/encodings/index.js create mode 100644 node_modules/iconv-lite/encodings/internal.js create mode 100644 node_modules/iconv-lite/encodings/sbcs-codec.js create mode 100644 node_modules/iconv-lite/encodings/sbcs-data-generated.js create mode 100644 node_modules/iconv-lite/encodings/sbcs-data.js create mode 100644 node_modules/iconv-lite/encodings/tables/big5-added.json create mode 100644 node_modules/iconv-lite/encodings/tables/cp936.json create mode 100644 node_modules/iconv-lite/encodings/tables/cp949.json create mode 100644 node_modules/iconv-lite/encodings/tables/cp950.json create mode 100644 node_modules/iconv-lite/encodings/tables/eucjp.json create mode 100644 node_modules/iconv-lite/encodings/tables/gb18030-ranges.json create mode 100644 node_modules/iconv-lite/encodings/tables/gbk-added.json create mode 100644 node_modules/iconv-lite/encodings/tables/shiftjis.json create mode 100644 node_modules/iconv-lite/encodings/utf16.js create mode 100644 node_modules/iconv-lite/encodings/utf32.js create mode 100644 node_modules/iconv-lite/encodings/utf7.js create mode 100644 node_modules/iconv-lite/lib/bom-handling.js create mode 100644 node_modules/iconv-lite/lib/index.d.ts create mode 100644 node_modules/iconv-lite/lib/index.js create mode 100644 node_modules/iconv-lite/lib/streams.js create mode 100644 node_modules/iconv-lite/package.json create mode 100644 node_modules/inherits/LICENSE create mode 100644 node_modules/inherits/README.md create mode 100644 node_modules/inherits/inherits.js create mode 100644 node_modules/inherits/inherits_browser.js create mode 100644 node_modules/inherits/package.json create mode 100644 node_modules/ipaddr.js/LICENSE create mode 100644 node_modules/ipaddr.js/README.md create mode 100644 node_modules/ipaddr.js/ipaddr.min.js create mode 100644 node_modules/ipaddr.js/lib/ipaddr.js create mode 100644 node_modules/ipaddr.js/lib/ipaddr.js.d.ts create mode 100644 node_modules/ipaddr.js/package.json create mode 100644 node_modules/is-promise/LICENSE create mode 100644 node_modules/is-promise/index.d.ts create mode 100644 node_modules/is-promise/index.js create mode 100644 node_modules/is-promise/index.mjs create mode 100644 node_modules/is-promise/package.json create mode 100644 node_modules/is-promise/readme.md create mode 100644 node_modules/jake/Makefile create mode 100644 node_modules/jake/README.md create mode 100755 node_modules/jake/bin/bash_completion.sh create mode 100755 node_modules/jake/bin/cli.js create mode 100644 node_modules/jake/jakefile.js create mode 100644 node_modules/jake/lib/api.js create mode 100644 node_modules/jake/lib/jake.js create mode 100644 node_modules/jake/lib/loader.js create mode 100644 node_modules/jake/lib/namespace.js create mode 100644 node_modules/jake/lib/package_task.js create mode 100644 node_modules/jake/lib/parseargs.js create mode 100644 node_modules/jake/lib/program.js create mode 100644 node_modules/jake/lib/publish_task.js create mode 100644 node_modules/jake/lib/rule.js create mode 100644 node_modules/jake/lib/task/directory_task.js create mode 100644 node_modules/jake/lib/task/file_task.js create mode 100644 node_modules/jake/lib/task/index.js create mode 100644 node_modules/jake/lib/task/task.js create mode 100644 node_modules/jake/lib/test_task.js create mode 100644 node_modules/jake/lib/utils/file.js create mode 100644 node_modules/jake/lib/utils/index.js create mode 100644 node_modules/jake/lib/utils/logger.js create mode 100644 node_modules/jake/package.json create mode 100644 node_modules/jake/test/integration/concurrent.js create mode 100644 node_modules/jake/test/integration/file.js create mode 100644 node_modules/jake/test/integration/file_task.js create mode 100644 node_modules/jake/test/integration/helpers.js create mode 100644 node_modules/jake/test/integration/jakefile.js create mode 100644 node_modules/jake/test/integration/jakelib/concurrent.jake.js create mode 100644 node_modules/jake/test/integration/jakelib/publish.jake.js create mode 100644 node_modules/jake/test/integration/jakelib/required_module.jake.js create mode 100644 node_modules/jake/test/integration/jakelib/rule.jake.js create mode 100644 node_modules/jake/test/integration/list_tasks.js create mode 100644 node_modules/jake/test/integration/publish_task.js create mode 100644 node_modules/jake/test/integration/rule.js create mode 100644 node_modules/jake/test/integration/selfdep.js create mode 100644 node_modules/jake/test/integration/task_base.js create mode 100644 node_modules/jake/test/unit/jakefile.js create mode 100644 node_modules/jake/test/unit/namespace.js create mode 100644 node_modules/jake/test/unit/parseargs.js create mode 100644 node_modules/jake/usage.txt create mode 100644 node_modules/jsonwebtoken/LICENSE create mode 100644 node_modules/jsonwebtoken/README.md create mode 100644 node_modules/jsonwebtoken/decode.js create mode 100644 node_modules/jsonwebtoken/index.js create mode 100644 node_modules/jsonwebtoken/lib/JsonWebTokenError.js create mode 100644 node_modules/jsonwebtoken/lib/NotBeforeError.js create mode 100644 node_modules/jsonwebtoken/lib/TokenExpiredError.js create mode 100644 node_modules/jsonwebtoken/lib/asymmetricKeyDetailsSupported.js create mode 100644 node_modules/jsonwebtoken/lib/psSupported.js create mode 100644 node_modules/jsonwebtoken/lib/rsaPssKeyDetailsSupported.js create mode 100644 node_modules/jsonwebtoken/lib/timespan.js create mode 100644 node_modules/jsonwebtoken/lib/validateAsymmetricKey.js create mode 100644 node_modules/jsonwebtoken/package.json create mode 100644 node_modules/jsonwebtoken/sign.js create mode 100644 node_modules/jsonwebtoken/verify.js create mode 100644 node_modules/jwa/LICENSE create mode 100644 node_modules/jwa/README.md create mode 100644 node_modules/jwa/index.js create mode 100644 node_modules/jwa/package.json create mode 100644 node_modules/jws/CHANGELOG.md create mode 100644 node_modules/jws/LICENSE create mode 100644 node_modules/jws/index.js create mode 100644 node_modules/jws/lib/data-stream.js create mode 100644 node_modules/jws/lib/sign-stream.js create mode 100644 node_modules/jws/lib/tostring.js create mode 100644 node_modules/jws/lib/verify-stream.js create mode 100644 node_modules/jws/package.json create mode 100644 node_modules/jws/readme.md create mode 100644 node_modules/lodash.includes/LICENSE create mode 100644 node_modules/lodash.includes/README.md create mode 100644 node_modules/lodash.includes/index.js create mode 100644 node_modules/lodash.includes/package.json create mode 100644 node_modules/lodash.isboolean/LICENSE create mode 100644 node_modules/lodash.isboolean/README.md create mode 100644 node_modules/lodash.isboolean/index.js create mode 100644 node_modules/lodash.isboolean/package.json create mode 100644 node_modules/lodash.isinteger/LICENSE create mode 100644 node_modules/lodash.isinteger/README.md create mode 100644 node_modules/lodash.isinteger/index.js create mode 100644 node_modules/lodash.isinteger/package.json create mode 100644 node_modules/lodash.isnumber/LICENSE create mode 100644 node_modules/lodash.isnumber/README.md create mode 100644 node_modules/lodash.isnumber/index.js create mode 100644 node_modules/lodash.isnumber/package.json create mode 100644 node_modules/lodash.isplainobject/LICENSE create mode 100644 node_modules/lodash.isplainobject/README.md create mode 100644 node_modules/lodash.isplainobject/index.js create mode 100644 node_modules/lodash.isplainobject/package.json create mode 100644 node_modules/lodash.isstring/LICENSE create mode 100644 node_modules/lodash.isstring/README.md create mode 100644 node_modules/lodash.isstring/index.js create mode 100644 node_modules/lodash.isstring/package.json create mode 100644 node_modules/lodash.once/LICENSE create mode 100644 node_modules/lodash.once/README.md create mode 100644 node_modules/lodash.once/index.js create mode 100644 node_modules/lodash.once/package.json create mode 100644 node_modules/math-intrinsics/.eslintrc create mode 100644 node_modules/math-intrinsics/.github/FUNDING.yml create mode 100644 node_modules/math-intrinsics/CHANGELOG.md create mode 100644 node_modules/math-intrinsics/LICENSE create mode 100644 node_modules/math-intrinsics/README.md create mode 100644 node_modules/math-intrinsics/abs.d.ts create mode 100644 node_modules/math-intrinsics/abs.js create mode 100644 node_modules/math-intrinsics/constants/maxArrayLength.d.ts create mode 100644 node_modules/math-intrinsics/constants/maxArrayLength.js create mode 100644 node_modules/math-intrinsics/constants/maxSafeInteger.d.ts create mode 100644 node_modules/math-intrinsics/constants/maxSafeInteger.js create mode 100644 node_modules/math-intrinsics/constants/maxValue.d.ts create mode 100644 node_modules/math-intrinsics/constants/maxValue.js create mode 100644 node_modules/math-intrinsics/floor.d.ts create mode 100644 node_modules/math-intrinsics/floor.js create mode 100644 node_modules/math-intrinsics/isFinite.d.ts create mode 100644 node_modules/math-intrinsics/isFinite.js create mode 100644 node_modules/math-intrinsics/isInteger.d.ts create mode 100644 node_modules/math-intrinsics/isInteger.js create mode 100644 node_modules/math-intrinsics/isNaN.d.ts create mode 100644 node_modules/math-intrinsics/isNaN.js create mode 100644 node_modules/math-intrinsics/isNegativeZero.d.ts create mode 100644 node_modules/math-intrinsics/isNegativeZero.js create mode 100644 node_modules/math-intrinsics/max.d.ts create mode 100644 node_modules/math-intrinsics/max.js create mode 100644 node_modules/math-intrinsics/min.d.ts create mode 100644 node_modules/math-intrinsics/min.js create mode 100644 node_modules/math-intrinsics/mod.d.ts create mode 100644 node_modules/math-intrinsics/mod.js create mode 100644 node_modules/math-intrinsics/package.json create mode 100644 node_modules/math-intrinsics/pow.d.ts create mode 100644 node_modules/math-intrinsics/pow.js create mode 100644 node_modules/math-intrinsics/round.d.ts create mode 100644 node_modules/math-intrinsics/round.js create mode 100644 node_modules/math-intrinsics/sign.d.ts create mode 100644 node_modules/math-intrinsics/sign.js create mode 100644 node_modules/math-intrinsics/test/index.js create mode 100644 node_modules/math-intrinsics/tsconfig.json create mode 100644 node_modules/media-typer/HISTORY.md create mode 100644 node_modules/media-typer/LICENSE create mode 100644 node_modules/media-typer/README.md create mode 100644 node_modules/media-typer/index.js create mode 100644 node_modules/media-typer/package.json create mode 100644 node_modules/merge-descriptors/index.d.ts create mode 100644 node_modules/merge-descriptors/index.js create mode 100644 node_modules/merge-descriptors/license create mode 100644 node_modules/merge-descriptors/package.json create mode 100644 node_modules/merge-descriptors/readme.md create mode 100644 node_modules/mime-db/HISTORY.md create mode 100644 node_modules/mime-db/LICENSE create mode 100644 node_modules/mime-db/README.md create mode 100644 node_modules/mime-db/db.json create mode 100644 node_modules/mime-db/index.js create mode 100644 node_modules/mime-db/package.json create mode 100644 node_modules/mime-types/HISTORY.md create mode 100644 node_modules/mime-types/LICENSE create mode 100644 node_modules/mime-types/README.md create mode 100644 node_modules/mime-types/index.js create mode 100644 node_modules/mime-types/mimeScore.js create mode 100644 node_modules/mime-types/package.json create mode 100644 node_modules/minimatch/LICENSE create mode 100644 node_modules/minimatch/README.md create mode 100644 node_modules/minimatch/lib/path.js create mode 100644 node_modules/minimatch/minimatch.js create mode 100644 node_modules/minimatch/package.json create mode 100644 node_modules/ms/index.js create mode 100644 node_modules/ms/license.md create mode 100644 node_modules/ms/package.json create mode 100644 node_modules/ms/readme.md create mode 100644 node_modules/negotiator/HISTORY.md create mode 100644 node_modules/negotiator/LICENSE create mode 100644 node_modules/negotiator/README.md create mode 100644 node_modules/negotiator/index.js create mode 100644 node_modules/negotiator/lib/charset.js create mode 100644 node_modules/negotiator/lib/encoding.js create mode 100644 node_modules/negotiator/lib/language.js create mode 100644 node_modules/negotiator/lib/mediaType.js create mode 100644 node_modules/negotiator/package.json create mode 100644 node_modules/nostr-tools/LICENSE create mode 100644 node_modules/nostr-tools/README.md create mode 100644 node_modules/nostr-tools/lib/cjs/abstract-pool.js create mode 100644 node_modules/nostr-tools/lib/cjs/abstract-pool.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/abstract-relay.js create mode 100644 node_modules/nostr-tools/lib/cjs/abstract-relay.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/fakejson.js create mode 100644 node_modules/nostr-tools/lib/cjs/fakejson.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/filter.js create mode 100644 node_modules/nostr-tools/lib/cjs/filter.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/index.js create mode 100644 node_modules/nostr-tools/lib/cjs/index.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/kinds.js create mode 100644 node_modules/nostr-tools/lib/cjs/kinds.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip04.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip04.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip05.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip05.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip06.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip06.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip07.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip07.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip10.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip10.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip11.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip11.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip13.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip13.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip17.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip17.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip18.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip18.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip19.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip19.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip21.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip21.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip25.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip25.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip27.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip27.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip28.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip28.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip29.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip29.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip30.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip30.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip39.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip39.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip40.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip40.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip42.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip42.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip44.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip44.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip46.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip46.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip47.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip47.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip49.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip49.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip54.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip54.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip55.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip55.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip57.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip57.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip58.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip58.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip59.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip59.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip75.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip75.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip94.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip94.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip98.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip98.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nip99.js create mode 100644 node_modules/nostr-tools/lib/cjs/nip99.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/nipb7.js create mode 100644 node_modules/nostr-tools/lib/cjs/nipb7.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/package.json create mode 100644 node_modules/nostr-tools/lib/cjs/pool.js create mode 100644 node_modules/nostr-tools/lib/cjs/pool.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/pure.js create mode 100644 node_modules/nostr-tools/lib/cjs/pure.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/references.js create mode 100644 node_modules/nostr-tools/lib/cjs/references.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/relay.js create mode 100644 node_modules/nostr-tools/lib/cjs/relay.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/signer.js create mode 100644 node_modules/nostr-tools/lib/cjs/signer.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/utils.js create mode 100644 node_modules/nostr-tools/lib/cjs/utils.js.map create mode 100644 node_modules/nostr-tools/lib/cjs/wasm.js create mode 100644 node_modules/nostr-tools/lib/cjs/wasm.js.map create mode 100644 node_modules/nostr-tools/lib/esm/abstract-pool.js create mode 100644 node_modules/nostr-tools/lib/esm/abstract-pool.js.map create mode 100644 node_modules/nostr-tools/lib/esm/abstract-relay.js create mode 100644 node_modules/nostr-tools/lib/esm/abstract-relay.js.map create mode 100644 node_modules/nostr-tools/lib/esm/fakejson.js create mode 100644 node_modules/nostr-tools/lib/esm/fakejson.js.map create mode 100644 node_modules/nostr-tools/lib/esm/filter.js create mode 100644 node_modules/nostr-tools/lib/esm/filter.js.map create mode 100644 node_modules/nostr-tools/lib/esm/index.js create mode 100644 node_modules/nostr-tools/lib/esm/index.js.map create mode 100644 node_modules/nostr-tools/lib/esm/kinds.js create mode 100644 node_modules/nostr-tools/lib/esm/kinds.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip04.js create mode 100644 node_modules/nostr-tools/lib/esm/nip04.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip05.js create mode 100644 node_modules/nostr-tools/lib/esm/nip05.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip06.js create mode 100644 node_modules/nostr-tools/lib/esm/nip06.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip07.js create mode 100644 node_modules/nostr-tools/lib/esm/nip07.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip10.js create mode 100644 node_modules/nostr-tools/lib/esm/nip10.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip11.js create mode 100644 node_modules/nostr-tools/lib/esm/nip11.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip13.js create mode 100644 node_modules/nostr-tools/lib/esm/nip13.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip17.js create mode 100644 node_modules/nostr-tools/lib/esm/nip17.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip18.js create mode 100644 node_modules/nostr-tools/lib/esm/nip18.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip19.js create mode 100644 node_modules/nostr-tools/lib/esm/nip19.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip21.js create mode 100644 node_modules/nostr-tools/lib/esm/nip21.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip25.js create mode 100644 node_modules/nostr-tools/lib/esm/nip25.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip27.js create mode 100644 node_modules/nostr-tools/lib/esm/nip27.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip28.js create mode 100644 node_modules/nostr-tools/lib/esm/nip28.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip29.js create mode 100644 node_modules/nostr-tools/lib/esm/nip29.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip30.js create mode 100644 node_modules/nostr-tools/lib/esm/nip30.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip39.js create mode 100644 node_modules/nostr-tools/lib/esm/nip39.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip40.js create mode 100644 node_modules/nostr-tools/lib/esm/nip40.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip42.js create mode 100644 node_modules/nostr-tools/lib/esm/nip42.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip44.js create mode 100644 node_modules/nostr-tools/lib/esm/nip44.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip46.js create mode 100644 node_modules/nostr-tools/lib/esm/nip46.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip47.js create mode 100644 node_modules/nostr-tools/lib/esm/nip47.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip49.js create mode 100644 node_modules/nostr-tools/lib/esm/nip49.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip54.js create mode 100644 node_modules/nostr-tools/lib/esm/nip54.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip55.js create mode 100644 node_modules/nostr-tools/lib/esm/nip55.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip57.js create mode 100644 node_modules/nostr-tools/lib/esm/nip57.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip58.js create mode 100644 node_modules/nostr-tools/lib/esm/nip58.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip59.js create mode 100644 node_modules/nostr-tools/lib/esm/nip59.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip75.js create mode 100644 node_modules/nostr-tools/lib/esm/nip75.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip94.js create mode 100644 node_modules/nostr-tools/lib/esm/nip94.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip98.js create mode 100644 node_modules/nostr-tools/lib/esm/nip98.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nip99.js create mode 100644 node_modules/nostr-tools/lib/esm/nip99.js.map create mode 100644 node_modules/nostr-tools/lib/esm/nipb7.js create mode 100644 node_modules/nostr-tools/lib/esm/nipb7.js.map create mode 100644 node_modules/nostr-tools/lib/esm/pool.js create mode 100644 node_modules/nostr-tools/lib/esm/pool.js.map create mode 100644 node_modules/nostr-tools/lib/esm/pure.js create mode 100644 node_modules/nostr-tools/lib/esm/pure.js.map create mode 100644 node_modules/nostr-tools/lib/esm/references.js create mode 100644 node_modules/nostr-tools/lib/esm/references.js.map create mode 100644 node_modules/nostr-tools/lib/esm/relay.js create mode 100644 node_modules/nostr-tools/lib/esm/relay.js.map create mode 100644 node_modules/nostr-tools/lib/esm/signer.js create mode 100644 node_modules/nostr-tools/lib/esm/signer.js.map create mode 100644 node_modules/nostr-tools/lib/esm/utils.js create mode 100644 node_modules/nostr-tools/lib/esm/utils.js.map create mode 100644 node_modules/nostr-tools/lib/esm/wasm.js create mode 100644 node_modules/nostr-tools/lib/esm/wasm.js.map create mode 100644 node_modules/nostr-tools/lib/nostr.bundle.js create mode 100644 node_modules/nostr-tools/lib/nostr.bundle.js.map create mode 100644 node_modules/nostr-tools/lib/types/abstract-pool.d.ts create mode 100644 node_modules/nostr-tools/lib/types/abstract-relay.d.ts create mode 100644 node_modules/nostr-tools/lib/types/benchmarks.d.ts create mode 100644 node_modules/nostr-tools/lib/types/core.d.ts create mode 100644 node_modules/nostr-tools/lib/types/core.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/fakejson.d.ts create mode 100644 node_modules/nostr-tools/lib/types/fakejson.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/filter.d.ts create mode 100644 node_modules/nostr-tools/lib/types/filter.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/helpers.d.ts create mode 100644 node_modules/nostr-tools/lib/types/index.d.ts create mode 100644 node_modules/nostr-tools/lib/types/kinds.d.ts create mode 100644 node_modules/nostr-tools/lib/types/kinds.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip04.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip04.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip05.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip05.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip06.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip06.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip07.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip10.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip10.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip11.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip11.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip13.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip13.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip17.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip17.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip18.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip18.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip19.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip19.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip21.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip21.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip25.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip25.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip27.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip27.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip28.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip28.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip29.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip30.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip30.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip39.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip39.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip40.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip40.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip42.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip42.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip44.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip44.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip46.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip47.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip47.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip49.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip49.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip54.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip54.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip55.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip55.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip57.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip57.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip58.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip58.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip59.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip59.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip75.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip75.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip94.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip94.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip98.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip98.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip99.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nip99.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nipb7.d.ts create mode 100644 node_modules/nostr-tools/lib/types/nipb7.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/pool.d.ts create mode 100644 node_modules/nostr-tools/lib/types/pool.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/pure.d.ts create mode 100644 node_modules/nostr-tools/lib/types/pure.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/references.d.ts create mode 100644 node_modules/nostr-tools/lib/types/references.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/relay.d.ts create mode 100644 node_modules/nostr-tools/lib/types/relay.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/signer.d.ts create mode 100644 node_modules/nostr-tools/lib/types/test-helpers.d.ts create mode 100644 node_modules/nostr-tools/lib/types/utils.d.ts create mode 100644 node_modules/nostr-tools/lib/types/utils.test.d.ts create mode 100644 node_modules/nostr-tools/lib/types/wasm.d.ts create mode 100644 node_modules/nostr-tools/package.json create mode 100644 node_modules/nostr-wasm/README.md create mode 100644 node_modules/nostr-wasm/dist/api/emsimp.d.ts create mode 100644 node_modules/nostr-wasm/dist/api/nostr.d.ts create mode 100644 node_modules/nostr-wasm/dist/api/secp256k1-types.d.ts create mode 100644 node_modules/nostr-wasm/dist/api/secp256k1.d.ts create mode 100644 node_modules/nostr-wasm/dist/api/types.d.ts create mode 100644 node_modules/nostr-wasm/dist/api/wasm-env.d.ts create mode 100644 node_modules/nostr-wasm/dist/gen/wasm.d.ts create mode 100644 node_modules/nostr-wasm/dist/generate.d.ts create mode 100644 node_modules/nostr-wasm/dist/gzipped.d.ts create mode 100644 node_modules/nostr-wasm/dist/gzipped.js create mode 100644 node_modules/nostr-wasm/dist/headless.d.ts create mode 100644 node_modules/nostr-wasm/dist/main.d.ts create mode 100644 node_modules/nostr-wasm/dist/main.js create mode 100644 node_modules/nostr-wasm/dist/nostr.js create mode 100644 node_modules/nostr-wasm/dist/secp256k1.js create mode 100644 node_modules/nostr-wasm/dist/types.d.ts create mode 100644 node_modules/nostr-wasm/package.json create mode 100644 node_modules/nostr-wasm/public/out/secp256k1.js create mode 100755 node_modules/nostr-wasm/public/out/secp256k1.wasm create mode 100644 node_modules/object-inspect/.eslintrc create mode 100644 node_modules/object-inspect/.github/FUNDING.yml create mode 100644 node_modules/object-inspect/.nycrc create mode 100644 node_modules/object-inspect/CHANGELOG.md create mode 100644 node_modules/object-inspect/LICENSE create mode 100644 node_modules/object-inspect/example/all.js create mode 100644 node_modules/object-inspect/example/circular.js create mode 100644 node_modules/object-inspect/example/fn.js create mode 100644 node_modules/object-inspect/example/inspect.js create mode 100644 node_modules/object-inspect/index.js create mode 100644 node_modules/object-inspect/package-support.json create mode 100644 node_modules/object-inspect/package.json create mode 100644 node_modules/object-inspect/readme.markdown create mode 100644 node_modules/object-inspect/test-core-js.js create mode 100644 node_modules/object-inspect/test/bigint.js create mode 100644 node_modules/object-inspect/test/browser/dom.js create mode 100644 node_modules/object-inspect/test/circular.js create mode 100644 node_modules/object-inspect/test/deep.js create mode 100644 node_modules/object-inspect/test/element.js create mode 100644 node_modules/object-inspect/test/err.js create mode 100644 node_modules/object-inspect/test/fakes.js create mode 100644 node_modules/object-inspect/test/fn.js create mode 100644 node_modules/object-inspect/test/global.js create mode 100644 node_modules/object-inspect/test/has.js create mode 100644 node_modules/object-inspect/test/holes.js create mode 100644 node_modules/object-inspect/test/indent-option.js create mode 100644 node_modules/object-inspect/test/inspect.js create mode 100644 node_modules/object-inspect/test/lowbyte.js create mode 100644 node_modules/object-inspect/test/number.js create mode 100644 node_modules/object-inspect/test/quoteStyle.js create mode 100644 node_modules/object-inspect/test/toStringTag.js create mode 100644 node_modules/object-inspect/test/undef.js create mode 100644 node_modules/object-inspect/test/values.js create mode 100644 node_modules/object-inspect/util.inspect.js create mode 100644 node_modules/on-finished/HISTORY.md create mode 100644 node_modules/on-finished/LICENSE create mode 100644 node_modules/on-finished/README.md create mode 100644 node_modules/on-finished/index.js create mode 100644 node_modules/on-finished/package.json create mode 100644 node_modules/once/LICENSE create mode 100644 node_modules/once/README.md create mode 100644 node_modules/once/once.js create mode 100644 node_modules/once/package.json create mode 100644 node_modules/parseurl/HISTORY.md create mode 100644 node_modules/parseurl/LICENSE create mode 100644 node_modules/parseurl/README.md create mode 100644 node_modules/parseurl/index.js create mode 100644 node_modules/parseurl/package.json create mode 100644 node_modules/path-to-regexp/LICENSE create mode 100644 node_modules/path-to-regexp/Readme.md create mode 100644 node_modules/path-to-regexp/dist/index.d.ts create mode 100644 node_modules/path-to-regexp/dist/index.js create mode 100644 node_modules/path-to-regexp/dist/index.js.map create mode 100644 node_modules/path-to-regexp/package.json create mode 100644 node_modules/picocolors/LICENSE create mode 100644 node_modules/picocolors/README.md create mode 100644 node_modules/picocolors/package.json create mode 100644 node_modules/picocolors/picocolors.browser.js create mode 100644 node_modules/picocolors/picocolors.d.ts create mode 100644 node_modules/picocolors/picocolors.js create mode 100644 node_modules/picocolors/types.d.ts create mode 100644 node_modules/proxy-addr/HISTORY.md create mode 100644 node_modules/proxy-addr/LICENSE create mode 100644 node_modules/proxy-addr/README.md create mode 100644 node_modules/proxy-addr/index.js create mode 100644 node_modules/proxy-addr/package.json create mode 100644 node_modules/qs/.editorconfig create mode 100644 node_modules/qs/.eslintrc create mode 100644 node_modules/qs/.github/FUNDING.yml create mode 100644 node_modules/qs/.nycrc create mode 100644 node_modules/qs/CHANGELOG.md create mode 100644 node_modules/qs/LICENSE.md create mode 100644 node_modules/qs/README.md create mode 100644 node_modules/qs/dist/qs.js create mode 100644 node_modules/qs/lib/formats.js create mode 100644 node_modules/qs/lib/index.js create mode 100644 node_modules/qs/lib/parse.js create mode 100644 node_modules/qs/lib/stringify.js create mode 100644 node_modules/qs/lib/utils.js create mode 100644 node_modules/qs/package.json create mode 100644 node_modules/qs/test/empty-keys-cases.js create mode 100644 node_modules/qs/test/parse.js create mode 100644 node_modules/qs/test/stringify.js create mode 100644 node_modules/qs/test/utils.js create mode 100644 node_modules/range-parser/HISTORY.md create mode 100644 node_modules/range-parser/LICENSE create mode 100644 node_modules/range-parser/README.md create mode 100644 node_modules/range-parser/index.js create mode 100644 node_modules/range-parser/package.json create mode 100644 node_modules/raw-body/HISTORY.md create mode 100644 node_modules/raw-body/LICENSE create mode 100644 node_modules/raw-body/README.md create mode 100644 node_modules/raw-body/SECURITY.md create mode 100644 node_modules/raw-body/index.d.ts create mode 100644 node_modules/raw-body/index.js create mode 100644 node_modules/raw-body/package.json create mode 100644 node_modules/router/HISTORY.md create mode 100644 node_modules/router/LICENSE create mode 100644 node_modules/router/README.md create mode 100644 node_modules/router/index.js create mode 100644 node_modules/router/lib/layer.js create mode 100644 node_modules/router/lib/route.js create mode 100644 node_modules/router/package.json create mode 100644 node_modules/safe-buffer/LICENSE create mode 100644 node_modules/safe-buffer/README.md create mode 100644 node_modules/safe-buffer/index.d.ts create mode 100644 node_modules/safe-buffer/index.js create mode 100644 node_modules/safe-buffer/package.json create mode 100644 node_modules/safer-buffer/LICENSE create mode 100644 node_modules/safer-buffer/Porting-Buffer.md create mode 100644 node_modules/safer-buffer/Readme.md create mode 100644 node_modules/safer-buffer/dangerous.js create mode 100644 node_modules/safer-buffer/package.json create mode 100644 node_modules/safer-buffer/safer.js create mode 100644 node_modules/safer-buffer/tests.js create mode 100644 node_modules/semver/LICENSE create mode 100644 node_modules/semver/README.md create mode 100755 node_modules/semver/bin/semver.js create mode 100644 node_modules/semver/classes/comparator.js create mode 100644 node_modules/semver/classes/index.js create mode 100644 node_modules/semver/classes/range.js create mode 100644 node_modules/semver/classes/semver.js create mode 100644 node_modules/semver/functions/clean.js create mode 100644 node_modules/semver/functions/cmp.js create mode 100644 node_modules/semver/functions/coerce.js create mode 100644 node_modules/semver/functions/compare-build.js create mode 100644 node_modules/semver/functions/compare-loose.js create mode 100644 node_modules/semver/functions/compare.js create mode 100644 node_modules/semver/functions/diff.js create mode 100644 node_modules/semver/functions/eq.js create mode 100644 node_modules/semver/functions/gt.js create mode 100644 node_modules/semver/functions/gte.js create mode 100644 node_modules/semver/functions/inc.js create mode 100644 node_modules/semver/functions/lt.js create mode 100644 node_modules/semver/functions/lte.js create mode 100644 node_modules/semver/functions/major.js create mode 100644 node_modules/semver/functions/minor.js create mode 100644 node_modules/semver/functions/neq.js create mode 100644 node_modules/semver/functions/parse.js create mode 100644 node_modules/semver/functions/patch.js create mode 100644 node_modules/semver/functions/prerelease.js create mode 100644 node_modules/semver/functions/rcompare.js create mode 100644 node_modules/semver/functions/rsort.js create mode 100644 node_modules/semver/functions/satisfies.js create mode 100644 node_modules/semver/functions/sort.js create mode 100644 node_modules/semver/functions/valid.js create mode 100644 node_modules/semver/index.js create mode 100644 node_modules/semver/internal/constants.js create mode 100644 node_modules/semver/internal/debug.js create mode 100644 node_modules/semver/internal/identifiers.js create mode 100644 node_modules/semver/internal/lrucache.js create mode 100644 node_modules/semver/internal/parse-options.js create mode 100644 node_modules/semver/internal/re.js create mode 100644 node_modules/semver/package.json create mode 100644 node_modules/semver/preload.js create mode 100644 node_modules/semver/range.bnf create mode 100644 node_modules/semver/ranges/gtr.js create mode 100644 node_modules/semver/ranges/intersects.js create mode 100644 node_modules/semver/ranges/ltr.js create mode 100644 node_modules/semver/ranges/max-satisfying.js create mode 100644 node_modules/semver/ranges/min-satisfying.js create mode 100644 node_modules/semver/ranges/min-version.js create mode 100644 node_modules/semver/ranges/outside.js create mode 100644 node_modules/semver/ranges/simplify.js create mode 100644 node_modules/semver/ranges/subset.js create mode 100644 node_modules/semver/ranges/to-comparators.js create mode 100644 node_modules/semver/ranges/valid.js create mode 100644 node_modules/send/HISTORY.md create mode 100644 node_modules/send/LICENSE create mode 100644 node_modules/send/README.md create mode 100644 node_modules/send/index.js create mode 100644 node_modules/send/package.json create mode 100644 node_modules/serve-static/HISTORY.md create mode 100644 node_modules/serve-static/LICENSE create mode 100644 node_modules/serve-static/README.md create mode 100644 node_modules/serve-static/index.js create mode 100644 node_modules/serve-static/package.json create mode 100644 node_modules/setprototypeof/LICENSE create mode 100644 node_modules/setprototypeof/README.md create mode 100644 node_modules/setprototypeof/index.d.ts create mode 100644 node_modules/setprototypeof/index.js create mode 100644 node_modules/setprototypeof/package.json create mode 100644 node_modules/setprototypeof/test/index.js create mode 100644 node_modules/side-channel-list/.editorconfig create mode 100644 node_modules/side-channel-list/.eslintrc create mode 100644 node_modules/side-channel-list/.github/FUNDING.yml create mode 100644 node_modules/side-channel-list/.nycrc create mode 100644 node_modules/side-channel-list/CHANGELOG.md create mode 100644 node_modules/side-channel-list/LICENSE create mode 100644 node_modules/side-channel-list/README.md create mode 100644 node_modules/side-channel-list/index.d.ts create mode 100644 node_modules/side-channel-list/index.js create mode 100644 node_modules/side-channel-list/list.d.ts create mode 100644 node_modules/side-channel-list/package.json create mode 100644 node_modules/side-channel-list/test/index.js create mode 100644 node_modules/side-channel-list/tsconfig.json create mode 100644 node_modules/side-channel-map/.editorconfig create mode 100644 node_modules/side-channel-map/.eslintrc create mode 100644 node_modules/side-channel-map/.github/FUNDING.yml create mode 100644 node_modules/side-channel-map/.nycrc create mode 100644 node_modules/side-channel-map/CHANGELOG.md create mode 100644 node_modules/side-channel-map/LICENSE create mode 100644 node_modules/side-channel-map/README.md create mode 100644 node_modules/side-channel-map/index.d.ts create mode 100644 node_modules/side-channel-map/index.js create mode 100644 node_modules/side-channel-map/package.json create mode 100644 node_modules/side-channel-map/test/index.js create mode 100644 node_modules/side-channel-map/tsconfig.json create mode 100644 node_modules/side-channel-weakmap/.editorconfig create mode 100644 node_modules/side-channel-weakmap/.eslintrc create mode 100644 node_modules/side-channel-weakmap/.github/FUNDING.yml create mode 100644 node_modules/side-channel-weakmap/.nycrc create mode 100644 node_modules/side-channel-weakmap/CHANGELOG.md create mode 100644 node_modules/side-channel-weakmap/LICENSE create mode 100644 node_modules/side-channel-weakmap/README.md create mode 100644 node_modules/side-channel-weakmap/index.d.ts create mode 100644 node_modules/side-channel-weakmap/index.js create mode 100644 node_modules/side-channel-weakmap/package.json create mode 100644 node_modules/side-channel-weakmap/test/index.js create mode 100644 node_modules/side-channel-weakmap/tsconfig.json create mode 100644 node_modules/side-channel/.editorconfig create mode 100644 node_modules/side-channel/.eslintrc create mode 100644 node_modules/side-channel/.github/FUNDING.yml create mode 100644 node_modules/side-channel/.nycrc create mode 100644 node_modules/side-channel/CHANGELOG.md create mode 100644 node_modules/side-channel/LICENSE create mode 100644 node_modules/side-channel/README.md create mode 100644 node_modules/side-channel/index.d.ts create mode 100644 node_modules/side-channel/index.js create mode 100644 node_modules/side-channel/package.json create mode 100644 node_modules/side-channel/test/index.js create mode 100644 node_modules/side-channel/tsconfig.json create mode 100644 node_modules/statuses/HISTORY.md create mode 100644 node_modules/statuses/LICENSE create mode 100644 node_modules/statuses/README.md create mode 100644 node_modules/statuses/codes.json create mode 100644 node_modules/statuses/index.js create mode 100644 node_modules/statuses/package.json create mode 100644 node_modules/toidentifier/HISTORY.md create mode 100644 node_modules/toidentifier/LICENSE create mode 100644 node_modules/toidentifier/README.md create mode 100644 node_modules/toidentifier/index.js create mode 100644 node_modules/toidentifier/package.json create mode 100644 node_modules/type-is/HISTORY.md create mode 100644 node_modules/type-is/LICENSE create mode 100644 node_modules/type-is/README.md create mode 100644 node_modules/type-is/index.js create mode 100644 node_modules/type-is/package.json create mode 100644 node_modules/unpipe/HISTORY.md create mode 100644 node_modules/unpipe/LICENSE create mode 100644 node_modules/unpipe/README.md create mode 100644 node_modules/unpipe/index.js create mode 100644 node_modules/unpipe/package.json create mode 100644 node_modules/vary/HISTORY.md create mode 100644 node_modules/vary/LICENSE create mode 100644 node_modules/vary/README.md create mode 100644 node_modules/vary/index.js create mode 100644 node_modules/vary/package.json create mode 100644 node_modules/wrappy/LICENSE create mode 100644 node_modules/wrappy/README.md create mode 100644 node_modules/wrappy/package.json create mode 100644 node_modules/wrappy/wrappy.js create mode 100644 package-lock.json diff --git a/app.js b/app.js index 1489a11..48e5110 100644 --- a/app.js +++ b/app.js @@ -209,6 +209,13 @@ app.post('/complete-auth/:sessionId', async (req, res) => { const { sessionId } = req.params; const { npub, event_json } = req.body; + console.log('🐛 DEBUG - Received data:', { + sessionId, + npub: npub ? `"${npub}" (length: ${npub.length})` : 'undefined', + event_json: event_json ? `${event_json.substring(0, 100)}... (length: ${event_json.length})` : 'undefined', + allKeys: Object.keys(req.body) + }); + const session = sessions.get(sessionId); if (!session) { throw new Error('Session not found or expired'); diff --git a/app_working.js b/app_working.js new file mode 100644 index 0000000..28a410e --- /dev/null +++ b/app_working.js @@ -0,0 +1,454 @@ +import express from 'express'; +import crypto from 'crypto'; +import jwt from 'jsonwebtoken'; +import { nip19, getEventHash, verifyEvent, SimplePool } from 'nostr-tools'; + +const app = express(); +const PORT = 3001; + +// In-memory storage for demo purposes +const users = new Map(); +const authCodes = new Map(); +const sessions = new Map(); + +// JWT signing key (in production, use a proper key) +const JWT_SECRET = 'your-super-secret-jwt-signing-key-change-in-production'; +const ISSUER = 'https://auth.laantungir.net'; // Production HTTPS URL +const CLIENT_ID = 'GITEA'; +const CLIENT_SECRET = 'gitea-secret'; + +// Nostr relays for fetching user metadata +const NOSTR_RELAYS = [ + 'wss://relay.damus.io', + 'wss://nos.lol', + 'wss://relay.nostr.band', + 'wss://nostr-pub.wellorder.net' +]; + +// Initialize Nostr pool +const pool = new SimplePool(); + +// NIP-05 related functions +async function fetchUserMetadata(pubkey) { + try { + console.log('🔍 Fetching metadata for pubkey:', pubkey); + + const filter = { + kinds: [0], + authors: [pubkey], + limit: 1 + }; + + const events = await pool.querySync(NOSTR_RELAYS, filter); + + if (events.length > 0) { + const metadata = JSON.parse(events[0].content); + console.log('✅ Found metadata:', metadata); + return metadata; + } + + console.log('❌ No metadata found'); + return null; + } catch (error) { + console.error('❌ Error fetching metadata:', error); + return null; + } +} + +async function validateNip05(nip05, pubkey) { + try { + console.log('🔍 Validating NIP-05:', nip05); + + // Parse the NIP-05 identifier + let localPart, domain; + if (nip05.includes('@')) { + [localPart, domain] = nip05.split('@'); + } else { + // Handle _@domain.com format (root identifier) + localPart = '_'; + domain = nip05; + } + + // Fetch the well-known endpoint + const url = `https://${domain}/.well-known/nostr.json?name=${localPart}`; + console.log('🔍 Fetching well-known:', url); + + const response = await fetch(url, { + timeout: 5000, + headers: { + 'User-Agent': 'Nostr-OIDC-Bridge/1.0' + } + }); + + if (!response.ok) { + console.log('❌ Well-known fetch failed:', response.status); + return false; + } + + const data = await response.json(); + console.log('✅ Well-known response:', data); + + // Check if the pubkey matches + const expectedPubkey = data.names?.[localPart]; + const isValid = expectedPubkey === pubkey; + + console.log(`${isValid ? '✅' : '❌'} NIP-05 validation:`, { + expected: expectedPubkey, + actual: pubkey, + valid: isValid + }); + + return isValid; + } catch (error) { + console.error('❌ Error validating NIP-05:', error); + return false; + } +} + +function generateUsernameAndEmail(nip05, npub, pubkey) { + let username, email; + + if (nip05) { + if (nip05.includes('@')) { + // For user@domain.com format, use local part as username + const [local, domain] = nip05.split('@'); + + // Use local part as username (truncate if needed) + username = local.length <= 40 ? local : local.substring(0, 40); + + // Use full NIP-05 as email + email = nip05; + } else { + // For root identifier (domain.com), use domain as username + username = nip05.length <= 40 ? nip05 : nip05.substring(0, 40); + email = `_@${nip05}`; // Convert to standard email format + } + } else { + // Fallback to shortened npub + username = npub.length <= 40 ? npub.substring(0, 40) : npub.substring(0, 40); + email = `${pubkey.substring(0, 8)}@nostr.local`; + } + + return { username, email }; +} + +// Trust proxy for production deployment behind nginx +app.set('trust proxy', true); + +// Middleware +app.use(express.urlencoded({ extended: true })); +app.use(express.json()); +app.set('view engine', 'ejs'); +app.set('views', './views'); + +// Debug logging middleware +app.use((req, res, next) => { + console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`); + if (req.query && Object.keys(req.query).length > 0) { + console.log('Query params:', req.query); + } + next(); +}); + +// OIDC Discovery endpoint - manually controlled for production +app.get('/.well-known/openid-configuration', (req, res) => { + res.json({ + issuer: ISSUER, + authorization_endpoint: `${ISSUER}/auth`, + token_endpoint: `${ISSUER}/token`, + userinfo_endpoint: `${ISSUER}/userinfo`, + jwks_uri: `${ISSUER}/jwks`, + scopes_supported: ['openid', 'profile', 'email'], + response_types_supported: ['code'], + grant_types_supported: ['authorization_code'], + subject_types_supported: ['public'], + id_token_signing_alg_values_supported: ['HS256'], + claims_supported: ['sub', 'name', 'preferred_username', 'email'], + }); +}); + +// Authorization endpoint +app.get('/auth', (req, res) => { + const { client_id, redirect_uri, response_type, scope, state } = req.query; + + console.log('🔵 Authorization request:', { client_id, redirect_uri, response_type, scope, state }); + + // Validate client + if (client_id !== CLIENT_ID) { + const errorUrl = `${redirect_uri}?error=invalid_client&state=${state}`; + console.log('❌ Invalid client, redirecting to:', errorUrl); + return res.redirect(errorUrl); + } + + // Generate session + const sessionId = crypto.randomBytes(32).toString('hex'); + const challenge = crypto.randomBytes(32).toString('hex'); + + sessions.set(sessionId, { + client_id, + redirect_uri, + scope, + state, + challenge, + created_at: Date.now() + }); + + console.log('✅ Created session:', sessionId); + + // Render login page + res.render('login', { + challenge, + uid: sessionId, + returnTo: `/complete-auth/${sessionId}` + }); +}); + +// Handle Nostr authentication +app.post('/complete-auth/:sessionId', async (req, res) => { + try { + const { sessionId } = req.params; + const { npub, event_json } = req.body; + + const session = sessions.get(sessionId); + if (!session) { + throw new Error('Session not found or expired'); + } + + // Verify the Nostr event + const event = JSON.parse(event_json); + + if (!verifyEvent(event)) { + throw new Error('Invalid signature'); + } + + if (event.content !== session.challenge) { + throw new Error('Challenge mismatch'); + } + + const { data: pubkey } = nip19.decode(npub); + if (event.pubkey !== pubkey) { + throw new Error('Public key mismatch'); + } + + console.log('✅ Nostr authentication successful for:', pubkey); + + // Create or get user + let user = users.get(pubkey); + if (!user) { + // Try to fetch NIP-05 information + let nip05 = null; + let validatedNip05 = false; + + try { + console.log('🔍 Attempting to fetch NIP-05 for user...'); + const metadata = await fetchUserMetadata(pubkey); + + if (metadata && metadata.nip05) { + console.log('🔍 Found NIP-05 in metadata:', metadata.nip05); + validatedNip05 = await validateNip05(metadata.nip05, pubkey); + + if (validatedNip05) { + nip05 = metadata.nip05; + console.log('✅ NIP-05 validated successfully:', nip05); + } else { + console.log('❌ NIP-05 validation failed'); + } + } else { + console.log('❌ No NIP-05 found in metadata'); + } + } catch (error) { + console.error('❌ Error during NIP-05 lookup:', error); + } + + // Generate the best username and email + const { username, email } = generateUsernameAndEmail(validatedNip05 ? nip05 : null, npub, pubkey); + + user = { + id: pubkey, + name: nip05 && validatedNip05 ? nip05 : npub, + username: username, + email: email, + nip05: validatedNip05 ? nip05 : null, + }; + users.set(pubkey, user); + console.log('✅ Created new user:', user); + } + + // Generate authorization code + const authCode = crypto.randomBytes(32).toString('hex'); + authCodes.set(authCode, { + user_id: pubkey, + client_id: session.client_id, + redirect_uri: session.redirect_uri, + scope: session.scope, + created_at: Date.now(), + expires_at: Date.now() + (10 * 60 * 1000) // 10 minutes + }); + + console.log('✅ Generated auth code:', authCode); + + // Clean up session + sessions.delete(sessionId); + + // Redirect back to Gitea with auth code + const redirectUrl = `${session.redirect_uri}?code=${authCode}&state=${session.state}`; + console.log('✅ Redirecting to Gitea:', redirectUrl); + + res.redirect(redirectUrl); + + } catch (error) { + console.error('❌ Authentication error:', error); + const session = sessions.get(req.params.sessionId); + const challenge = session ? session.challenge : crypto.randomBytes(32).toString('hex'); + + res.render('login', { + error: error.message, + challenge, + uid: req.params.sessionId, + returnTo: `/complete-auth/${req.params.sessionId}` + }); + } +}); + +// Token endpoint +app.post('/token', (req, res) => { + try { + const { grant_type, code, client_id, client_secret, redirect_uri } = req.body; + + console.log('🔵 Token request:', { grant_type, code, client_id, redirect_uri }); + + // Validate grant type + if (grant_type !== 'authorization_code') { + return res.status(400).json({ error: 'unsupported_grant_type' }); + } + + // Validate client + if (client_id !== CLIENT_ID || client_secret !== CLIENT_SECRET) { + return res.status(401).json({ error: 'invalid_client' }); + } + + // Get auth code + const authData = authCodes.get(code); + if (!authData) { + return res.status(400).json({ error: 'invalid_grant' }); + } + + // Check expiration + if (Date.now() > authData.expires_at) { + authCodes.delete(code); + return res.status(400).json({ error: 'invalid_grant' }); + } + + // Validate redirect URI + if (authData.redirect_uri !== redirect_uri) { + return res.status(400).json({ error: 'invalid_grant' }); + } + + const user = users.get(authData.user_id); + if (!user) { + return res.status(400).json({ error: 'invalid_grant' }); + } + + // Generate tokens + const now = Math.floor(Date.now() / 1000); + + const accessToken = jwt.sign({ + sub: user.id, + aud: client_id, + iss: ISSUER, + iat: now, + exp: now + 3600, // 1 hour + scope: authData.scope + }, JWT_SECRET); + + const idToken = jwt.sign({ + sub: user.id, + aud: client_id, + iss: ISSUER, + iat: now, + exp: now + 3600, + name: user.name, + preferred_username: user.username, + email: user.email, + }, JWT_SECRET); + + // Clean up auth code (one-time use) + authCodes.delete(code); + + console.log('✅ Issued tokens for user:', user.id); + + res.json({ + access_token: accessToken, + token_type: 'Bearer', + expires_in: 3600, + id_token: idToken, + scope: authData.scope + }); + + } catch (error) { + console.error('❌ Token error:', error); + res.status(500).json({ error: 'server_error' }); + } +}); + +// Userinfo endpoint function +const handleUserInfo = (req, res) => { + try { + const authHeader = req.headers.authorization; + if (!authHeader || !authHeader.startsWith('Bearer ')) { + return res.status(401).json({ error: 'invalid_token' }); + } + + const token = authHeader.substring(7); + const decoded = jwt.verify(token, JWT_SECRET); + + const user = users.get(decoded.sub); + if (!user) { + return res.status(401).json({ error: 'invalid_token' }); + } + + console.log('✅ UserInfo request for user:', user.id); + + res.json({ + sub: user.id, + name: user.name, + preferred_username: user.username, + email: user.email, + }); + + } catch (error) { + console.error('❌ Userinfo error:', error); + res.status(401).json({ error: 'invalid_token' }); + } +}; + +// Userinfo endpoints (both /userinfo and /me for compatibility) +app.get('/userinfo', handleUserInfo); +app.get('/me', handleUserInfo); + +// JWKS endpoint (simplified) +app.get('/jwks', (req, res) => { + // This is a simplified implementation + // In production, use proper JWK format + res.json({ keys: [] }); +}); + +// Health check +app.get('/health', (req, res) => { + res.json({ status: 'ok', timestamp: new Date().toISOString() }); +}); + +// Error handler +app.use((err, req, res, next) => { + console.error('❌ Express Error:', err); + if (res.headersSent) { + return next(err); + } + res.status(500).json({ error: 'Internal server error', message: err.message }); +}); + +// Start server +app.listen(PORT, '0.0.0.0', () => { + console.log(`🚀 Simple Nostr OIDC Bridge running on http://0.0.0.0:${PORT}`); + console.log(`🔗 OIDC Discovery: ${ISSUER}/.well-known/openid-configuration`); +}); diff --git a/node_modules/.bin/ejs b/node_modules/.bin/ejs new file mode 120000 index 0000000..88e80d0 --- /dev/null +++ b/node_modules/.bin/ejs @@ -0,0 +1 @@ +../ejs/bin/cli.js \ No newline at end of file diff --git a/node_modules/.bin/jake b/node_modules/.bin/jake new file mode 120000 index 0000000..3626745 --- /dev/null +++ b/node_modules/.bin/jake @@ -0,0 +1 @@ +../jake/bin/cli.js \ No newline at end of file diff --git a/node_modules/.bin/semver b/node_modules/.bin/semver new file mode 120000 index 0000000..5aaadf4 --- /dev/null +++ b/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver.js \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..d5e5f7a --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,1134 @@ +{ + "name": "nostr-oidc-bridge", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@noble/ciphers": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-0.5.3.tgz", + "integrity": "sha512-B0+6IIHiqEs3BPMT0hcRmHvEj2QHOLu+uwt+tqDDeVd0oyVzh7BPrDcPjRnV1PV/5LaknXJJQvOuRGR0zQJz+w==", + "license": "MIT", + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/curves": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.2.0.tgz", + "integrity": "sha512-oYclrNgRaM9SsBUBVbb8M6DTV7ZHRTKugureoYEncY5c65HOmRzvSiTE3y5CYaPYJA/GVkrhXEoF0M3Ya9PMnw==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.3.2" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/curves/node_modules/@noble/hashes": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.2.tgz", + "integrity": "sha512-MVC8EAQp7MvEcm30KWENFjgR+Mkmf+D189XJTkFIlwohU5hcBbn1ZkKq7KVTi2Hme3PMGF390DaL52beVrIihQ==", + "license": "MIT", + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.1.tgz", + "integrity": "sha512-EbqwksQwz9xDRGfDST86whPBgM65E0OH/pCgqW0GBVzO22bNE+NuIbeTb714+IfSjU3aRk47EUvXIb5bTsenKA==", + "license": "MIT", + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/base": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@scure/base/-/base-1.1.1.tgz", + "integrity": "sha512-ZxOhsSyxYwLJj3pLZCefNitxsj093tb2vq90mp2txoYeBqbcjDjqFhyM8eUjq/uFm6zJ+mUuqxlS2FkuSY1MTA==", + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ], + "license": "MIT" + }, + "node_modules/@scure/bip32": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-1.3.1.tgz", + "integrity": "sha512-osvveYtyzdEVbt3OfwwXFr4P2iVBL5u1Q3q4ONBfDY/UpOuXmOlbgwc1xECEboY8wIays8Yt6onaWMUdUbfl0A==", + "license": "MIT", + "dependencies": { + "@noble/curves": "~1.1.0", + "@noble/hashes": "~1.3.1", + "@scure/base": "~1.1.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip32/node_modules/@noble/curves": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.1.0.tgz", + "integrity": "sha512-091oBExgENk/kGj3AZmtBDMpxQPDtxQABR2B9lb1JbVTs6ytdzZNwvhxQ4MWasRNEzlbEH8jCWFCwhF/Obj5AA==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.3.1" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip39": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-1.2.1.tgz", + "integrity": "sha512-Z3/Fsz1yr904dduJD0NpiyRHhRYHdcnyh73FZWiV+/qhWi83wNJ3NWolYqCEN+ZWsUz2TWwajJggcRE9r1zUYg==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "~1.3.0", + "@scure/base": "~1.1.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/async": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", + "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", + "license": "MIT" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT" + }, + "node_modules/body-parser": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.0.tgz", + "integrity": "sha512-02qvAaxv8tp7fBa/mw1ga98OGm+eCbqzJOKoRt70sLmfEEi+jyBYVTDGfCL/k06/4EMk/z01gCe7HoCH/f2LTg==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^1.0.5", + "debug": "^4.4.0", + "http-errors": "^2.0.0", + "iconv-lite": "^0.6.3", + "on-finished": "^2.4.1", + "qs": "^6.14.0", + "raw-body": "^3.0.0", + "type-is": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/brace-expansion": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", + "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.0.tgz", + "integrity": "sha512-Au9nRL8VNUut/XSzbQA38+M78dzP4D+eqg3gfJHMIHHYa3bg067xj1KxMUWj+VULbiZMowKngFFbKczUrNJ1mg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/debug": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz", + "integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/ejs": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz", + "integrity": "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==", + "license": "Apache-2.0", + "dependencies": { + "jake": "^10.8.5" + }, + "bin": { + "ejs": "bin/cli.js" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz", + "integrity": "sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.0", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/filelist": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.4.tgz", + "integrity": "sha512-w1cEuf3S+DrLCQL7ET6kz+gmlJdbq9J7yXCSjK/OZCPA+qEN1WyF4ZAf0YYJa4/shHJra2t/d/r8SV4Ji+x+8Q==", + "license": "Apache-2.0", + "dependencies": { + "minimatch": "^5.0.1" + } + }, + "node_modules/finalhandler": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.0.tgz", + "integrity": "sha512-/t88Ty3d5JWQbWYgaOGCCYfXRwV1+be02WqYYlL6h0lEiUAMPM8o8qKGO01YIkOHzka2up08wvgYD0mDiI+q3Q==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "license": "MIT", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/http-errors/node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/jake": { + "version": "10.9.4", + "resolved": "https://registry.npmjs.org/jake/-/jake-10.9.4.tgz", + "integrity": "sha512-wpHYzhxiVQL+IV05BLE2Xn34zW1S223hvjtqk0+gsPrwd/8JNLXJgZZM/iPFsYc1xyphF+6M6EvdE5E9MBGkDA==", + "license": "Apache-2.0", + "dependencies": { + "async": "^3.2.6", + "filelist": "^1.0.4", + "picocolors": "^1.1.1" + }, + "bin": { + "jake": "bin/cli.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/jsonwebtoken": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz", + "integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==", + "license": "MIT", + "dependencies": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=12", + "npm": ">=6" + } + }, + "node_modules/jwa": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.2.tgz", + "integrity": "sha512-eeH5JO+21J78qMvTIDdBXidBd6nG2kZjg5Ohz/1fpa28Z4CcsWUzJ1ZZyFq/3z3N17aZy+ZuBoHljASbL1WfOw==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", + "license": "MIT", + "dependencies": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==", + "license": "MIT" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==", + "license": "MIT" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==", + "license": "MIT" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==", + "license": "MIT" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", + "license": "MIT" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==", + "license": "MIT" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==", + "license": "MIT" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.1.tgz", + "integrity": "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minimatch": { + "version": "5.1.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz", + "integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/nostr-tools": { + "version": "2.16.2", + "resolved": "https://registry.npmjs.org/nostr-tools/-/nostr-tools-2.16.2.tgz", + "integrity": "sha512-ZxH9EbSt5ypURZj2TGNJxZd0Omb5ag5KZSu8IyJMCdLyg2KKz+2GA0sP/cSawCQEkyviIN4eRT4G2gB/t9lMRw==", + "license": "Unlicense", + "dependencies": { + "@noble/ciphers": "^0.5.1", + "@noble/curves": "1.2.0", + "@noble/hashes": "1.3.1", + "@scure/base": "1.1.1", + "@scure/bip32": "1.3.1", + "@scure/bip39": "1.2.1", + "nostr-wasm": "0.1.0" + }, + "peerDependencies": { + "typescript": ">=5.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/nostr-wasm": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/nostr-wasm/-/nostr-wasm-0.1.0.tgz", + "integrity": "sha512-78BTryCLcLYv96ONU8Ws3Q1JzjlAt+43pWQhIl86xZmWeegYCNLPml7yQ+gG3vR6V5h4XGj+TxO+SS5dsThQIA==", + "license": "MIT" + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.2.0.tgz", + "integrity": "sha512-TdrF7fW9Rphjq4RjrW0Kp2AW0Ahwu9sRGTkS6bvDi0SCwZlEZYmcfDbEsTz8RVk0EHIS/Vd1bv3JhG+1xZuAyQ==", + "license": "MIT", + "engines": { + "node": ">=16" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.0.tgz", + "integrity": "sha512-RmkhL8CAyCRPXCE28MMH0z2PNWQBNk2Q09ZdxM9IOOXwxwZbN+qbWaatPkdkWIKL2ZVDImrN/pK5HTRz2PcS4g==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.6.3", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.7.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz", + "integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.0.tgz", + "integrity": "sha512-uaW0WwXKpL9blXE2o0bRhoL2EGXIrZxQ2ZQ4mgcfoBxdFmQold+qWsD2jLrfZ0trjKL6vOw0j//eAwcALFjKSw==", + "license": "MIT", + "dependencies": { + "debug": "^4.3.5", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "mime-types": "^3.0.1", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/serve-static": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.0.tgz", + "integrity": "sha512-61g9pCh0Vnh7IutZjtLGGpTA355+OPn2TyDv/6ivP2h/AdAVX9azsoxmg2/M6nZeQZNYBEwIcsne1mJd9oQItQ==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/type-is": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", + "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", + "license": "MIT", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + } + } +} diff --git a/node_modules/@noble/ciphers/LICENSE b/node_modules/@noble/ciphers/LICENSE new file mode 100644 index 0000000..5a53d5f --- /dev/null +++ b/node_modules/@noble/ciphers/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) +Copyright (c) 2016 Thomas Pornin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/@noble/ciphers/README.md b/node_modules/@noble/ciphers/README.md new file mode 100644 index 0000000..068776c --- /dev/null +++ b/node_modules/@noble/ciphers/README.md @@ -0,0 +1,655 @@ +# noble-ciphers + +Auditable & minimal JS implementation of Salsa20, ChaCha and AES. + +- 🔒 Auditable +- 🔻 Tree-shaking-friendly: use only what's necessary, other code won't be included +- 🏎 [Ultra-fast](#speed), hand-optimized for caveats of JS engines +- 🔍 Unique tests ensure correctness: property-based, cross-library and Wycheproof vectors +- 💼 AES: ECB, CBC, CTR, CFB, GCM, SIV (nonce misuse-resistant) +- 💃 Salsa20, ChaCha, XSalsa20, XChaCha, Poly1305, ChaCha8, ChaCha12 +- 🥈 Two AES implementations: choose between friendly webcrypto wrapper and pure JS one +- 🪶 45KB (8KB gzipped) for everything, 10KB (3KB gzipped) for ChaCha build + +For discussions, questions and support, visit +[GitHub Discussions](https://github.com/paulmillr/noble-ciphers/discussions) +section of the repository. + +### This library belongs to _noble_ cryptography + +> **noble cryptography** — high-security, easily auditable set of contained cryptographic libraries and tools. + +- Zero or minimal dependencies +- Highly readable TypeScript / JS code +- PGP-signed releases and transparent NPM builds +- All libraries: + [ciphers](https://github.com/paulmillr/noble-ciphers), + [curves](https://github.com/paulmillr/noble-curves), + [hashes](https://github.com/paulmillr/noble-hashes), + [post-quantum](https://github.com/paulmillr/noble-post-quantum), + 4kb [secp256k1](https://github.com/paulmillr/noble-secp256k1) / + [ed25519](https://github.com/paulmillr/noble-ed25519) +- [Check out homepage](https://paulmillr.com/noble/) + for reading resources, documentation and apps built with noble + +## Usage + +> npm install @noble/ciphers + +We support all major platforms and runtimes. +For [Deno](https://deno.land), ensure to use +[npm specifier](https://deno.land/manual@v1.28.0/node/npm_specifiers). +For React Native, you may need a +[polyfill for getRandomValues](https://github.com/LinusU/react-native-get-random-values). +A standalone file +[noble-ciphers.js](https://github.com/paulmillr/noble-ciphers/releases) is also available. + +```js +// import * from '@noble/ciphers'; // Error: use sub-imports, to ensure small app size +import { xchacha20poly1305 } from '@noble/ciphers/chacha'; +// import { xchacha20poly1305 } from 'npm:@noble/ciphers@0.5.0/chacha'; // Deno +``` + +- [Examples](#examples) + - [Encrypt with XChaCha20-Poly1305](#encrypt-with-xchacha20-poly1305) + - [Encrypt with AES-256-GCM](#encrypt-with-aes-256-gcm) + - [Use existing key instead of a new one](#use-existing-key-instead-of-a-new-one) + - [Encrypt without nonce](#encrypt-without-nonce) + - [Use same array for input and output](#use-same-array-for-input-and-output) + - [All imports](#all-imports) +- [Implementations](#implementations) + - [Salsa20](#salsa) + - [ChaCha](#chacha) + - [AES](#aes) + - [Webcrypto AES](#webcrypto-aes) + - [Poly1305, GHash, Polyval](#poly1305-ghash-polyval) + - [FF1 format-preserving encryption](#ff1) + - [Managed nonces](#managed-nonces) +- [Guidance](#guidance) + - [Which cipher should I pick?](#which-cipher-should-i-pick) + - [How to encrypt properly](#how-to-encrypt-properly) + - [Nonces](#nonces) + - [Encryption limits](#encryption-limits) + - [AES internals and block modes](#aes-internals-and-block-modes) +- [Security](#security) +- [Speed](#speed) +- [Upgrading](#upgrading) +- [Contributing & testing](#contributing--testing) +- [Resources](#resources) + +## Examples + +#### Encrypt with XChaCha20-Poly1305 + +```js +import { xchacha20poly1305 } from '@noble/ciphers/chacha'; +import { utf8ToBytes } from '@noble/ciphers/utils'; +import { randomBytes } from '@noble/ciphers/webcrypto'; +const key = randomBytes(32); +const nonce = randomBytes(24); +const chacha = xchacha20poly1305(key, nonce); +const data = utf8ToBytes('hello, noble'); +const ciphertext = chacha.encrypt(data); +const data_ = chacha.decrypt(ciphertext); // utils.bytesToUtf8(data_) === data +``` + +#### Encrypt with AES-256-GCM + +```js +import { gcm } from '@noble/ciphers/aes'; +import { utf8ToBytes } from '@noble/ciphers/utils'; +import { randomBytes } from '@noble/ciphers/webcrypto'; +const key = randomBytes(32); +const nonce = randomBytes(24); +const aes = gcm(key, nonce); +const data = utf8ToBytes('hello, noble'); +const ciphertext = aes.encrypt(data); +const data_ = aes.decrypt(ciphertext); // utils.bytesToUtf8(data_) === data +``` + +#### Use existing key instead of a new one + +```js +const key = new Uint8Array([ + 169, 88, 160, 139, 168, 29, 147, 196, 14, 88, 237, 76, 243, 177, 109, 140, 195, 140, 80, 10, 216, + 134, 215, 71, 191, 48, 20, 104, 189, 37, 38, 55, +]); +const nonce = new Uint8Array([ + 180, 90, 27, 63, 160, 191, 150, 33, 67, 212, 86, 71, 144, 6, 200, 102, 218, 32, 23, 147, 8, 41, + 147, 11, +]); +// or, hex: +import { hexToBytes } from '@noble/ciphers/utils'; +const key2 = hexToBytes('4b7f89bac90a1086fef73f5da2cbe93b2fae9dfbf7678ae1f3e75fd118ddf999'); +const nonce2 = hexToBytes('9610467513de0bbd7c4cc2c3c64069f1802086fbd3232b13'); +``` + +#### Encrypt without nonce + +```js +import { xchacha20poly1305 } from '@noble/ciphers/chacha'; +import { managedNonce } from '@noble/ciphers/webcrypto'; +import { hexToBytes, utf8ToBytes } from '@noble/ciphers/utils'; +const key = hexToBytes('fa686bfdffd3758f6377abbc23bf3d9bdc1a0dda4a6e7f8dbdd579fa1ff6d7e1'); +const chacha = managedNonce(xchacha20poly1305)(key); // manages nonces for you +const data = utf8ToBytes('hello, noble'); +const ciphertext = chacha.encrypt(data); +const data_ = chacha.decrypt(ciphertext); +``` + +#### Use same array for input and output + +```js +import { chacha20poly1305 } from '@noble/ciphers/chacha'; +import { utf8ToBytes } from '@noble/ciphers/utils'; +import { randomBytes } from '@noble/ciphers/webcrypto'; + +const key = randomBytes(32); +const nonce = randomBytes(12); +const buf = new Uint8Array(12 + 16); +const _data = utf8ToBytes('hello, noble'); +buf.set(_data, 0); // first 12 bytes +const _12b = buf.subarray(0, 12); + +const chacha = chacha20poly1305(key, nonce); +chacha.encrypt(_12b, buf); +chacha.decrypt(buf, _12b); // _12b now same as _data +``` + +#### All imports + +```js +import { gcm, siv } from '@noble/ciphers/aes'; +import { xsalsa20poly1305 } from '@noble/ciphers/salsa'; +import { chacha20poly1305, xchacha20poly1305 } from '@noble/ciphers/chacha'; + +// Unauthenticated encryption: make sure to use HMAC or similar +import { ctr, cfb, cbc, ecb } from '@noble/ciphers/aes'; +import { salsa20, xsalsa20 } from '@noble/ciphers/salsa'; +import { chacha20, xchacha20, chacha8, chacha12 } from '@noble/ciphers/chacha'; + +// Utilities +import { bytesToHex, hexToBytes, bytesToUtf8, utf8ToBytes } from '@noble/ciphers/utils'; +import { managedNonce, randomBytes } from '@noble/ciphers/webcrypto'; +``` + +## Implementations + +### Salsa + +```js +import { xsalsa20poly1305 } from '@noble/ciphers/salsa'; +import { secretbox } from '@noble/ciphers/salsa'; // == xsalsa20poly1305 +import { salsa20, xsalsa20 } from '@noble/ciphers/salsa'; +``` + +[Salsa20](https://cr.yp.to/snuffle.html) stream cipher was released in 2005. +Salsa's goal was to implement AES replacement that does not rely on S-Boxes, +which are hard to implement in a constant-time manner. +Salsa20 is usually faster than AES, a big deal on slow, budget mobile phones. + +[XSalsa20](https://cr.yp.to/snuffle/xsalsa-20110204.pdf), extended-nonce +variant was released in 2008. It switched nonces from 96-bit to 192-bit, +and became safe to be picked at random. + +Nacl / Libsodium popularized term "secretbox", a simple black-box +authenticated encryption. Secretbox is just xsalsa20-poly1305. We provide the +alias and corresponding seal / open methods. We don't provide "box" or "sealedbox". + +Check out [PDF](https://cr.yp.to/snuffle/salsafamily-20071225.pdf) and +[wiki](https://en.wikipedia.org/wiki/Salsa20). + +### ChaCha + +```js +import { chacha20poly1305, xchacha20poly1305 } from '@noble/ciphers/chacha'; +import { chacha20, xchacha20, chacha8, chacha12 } from '@noble/ciphers/chacha'; +``` + +[ChaCha20](https://cr.yp.to/chacha.html) stream cipher was released +in 2008. ChaCha aims to increase the diffusion per round, but had slightly less +cryptanalysis. It was standardized in +[RFC 8439](https://datatracker.ietf.org/doc/html/rfc8439) and is now used in TLS 1.3. + +[XChaCha20](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha) +extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with +randomly-generated nonces. + +Check out [PDF](http://cr.yp.to/chacha/chacha-20080128.pdf) and [wiki](https://en.wikipedia.org/wiki/Salsa20). + +### AES + +```js +import { gcm, siv, ctr, cfb, cbc, ecb } from '@noble/ciphers/aes'; +import { randomBytes } from '@noble/ciphers/webcrypto'; +const plaintext = new Uint8Array(32).fill(16); +const key = randomBytes(32); // 24 for AES-192, 16 for AES-128 +for (let cipher of [gcm, siv]) { + const stream = cipher(key, randomBytes(12)); + const ciphertext_ = stream.encrypt(plaintext); + const plaintext_ = stream.decrypt(ciphertext_); +} +for (const cipher of [ctr, cbc, cbc]) { + const stream = cipher(key, randomBytes(16)); + const ciphertext_ = stream.encrypt(plaintext); + const plaintext_ = stream.decrypt(ciphertext_); +} +for (const cipher of [ecb]) { + const stream = cipher(key); + const ciphertext_ = stream.encrypt(plaintext); + const plaintext_ = stream.decrypt(ciphertext_); +} +``` + +[AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard) +is a variant of Rijndael block cipher, standardized by NIST in 2001. +We provide the fastest available pure JS implementation. + +We support AES-128, AES-192 and AES-256: the mode is selected dynamically, +based on key length (16, 24, 32). + +[AES-GCM-SIV](https://en.wikipedia.org/wiki/AES-GCM-SIV) +nonce-misuse-resistant mode is also provided. It's recommended to use it, +to prevent catastrophic consequences of nonce reuse. Our implementation of SIV +has the same speed as GCM: there is no performance hit. + +Check out [AES internals and block modes](#aes-internals-and-block-modes). + +### Webcrypto AES + +```js +import { gcm, ctr, cbc, randomBytes } from '@noble/ciphers/webcrypto'; +const plaintext = new Uint8Array(32).fill(16); +const key = randomBytes(32); +for (const cipher of [gcm]) { + const stream = cipher(key, randomBytes(12)); + const ciphertext_ = await stream.encrypt(plaintext); + const plaintext_ = await stream.decrypt(ciphertext_); +} +for (const cipher of [ctr, cbc]) { + const stream = cipher(key, randomBytes(16)); + const ciphertext_ = await stream.encrypt(plaintext); + const plaintext_ = await stream.decrypt(ciphertext_); +} +``` + +We also have a separate wrapper over WebCrypto built-in. + +It's the same as using `crypto.subtle`, but with massively simplified API. + +Unlike pure js version, it's asynchronous. + +### Poly1305, GHash, Polyval + +```js +import { poly1305 } from '@noble/ciphers/_poly1305'; +import { ghash, polyval } from '@noble/ciphers/_polyval'; +``` + +We expose polynomial-evaluation MACs: [Poly1305](https://cr.yp.to/mac.html), +AES-GCM's [GHash](https://en.wikipedia.org/wiki/Galois/Counter_Mode) and +AES-SIV's [Polyval](https://en.wikipedia.org/wiki/AES-GCM-SIV). + +Poly1305 ([PDF](https://cr.yp.to/mac/poly1305-20050329.pdf), +[wiki](https://en.wikipedia.org/wiki/Poly1305)) +is a fast and parallel secret-key message-authentication code suitable for +a wide variety of applications. It was standardized in +[RFC 8439](https://datatracker.ietf.org/doc/html/rfc8439) and is now used in TLS 1.3. + +Polynomial MACs are not perfect for every situation: +they lack Random Key Robustness: the MAC can be forged, and can't +be used in PAKE schemes. See +[invisible salamanders attack](https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/). +To combat invisible salamanders, `hash(key)` can be included in ciphertext, +however, this would violate ciphertext indistinguishability: +an attacker would know which key was used - so `HKDF(key, i)` +could be used instead. + +### FF1 + +Format-preserving encryption algorithm (FPE-FF1) specified in NIST Special Publication 800-38G. +[See more info](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf). + +### Managed nonces + +```js +import { managedNonce } from '@noble/ciphers/webcrypto'; +import { gcm, siv, ctr, cbc, cbc, ecb } from '@noble/ciphers/aes'; +import { xsalsa20poly1305 } from '@noble/ciphers/salsa'; +import { chacha20poly1305, xchacha20poly1305 } from '@noble/ciphers/chacha'; + +const wgcm = managedNonce(gcm); +const wsiv = managedNonce(siv); +const wcbc = managedNonce(cbc); +const wctr = managedNonce(ctr); +const wsalsapoly = managedNonce(xsalsa20poly1305); +const wchacha = managedNonce(chacha20poly1305); +const wxchacha = managedNonce(xchacha20poly1305); + +// Now: +const encrypted = wgcm(key).encrypt(data); // no nonces +``` + +We provide API that manages nonce internally instead of exposing them to library's user. + +For `encrypt`, a `nonceBytes`-length buffer is fetched from CSPRNG and prenended to encrypted ciphertext. + +For `decrypt`, first `nonceBytes` of ciphertext are treated as nonce. + +## Guidance + +### Which cipher should I pick? + +XChaCha20-Poly1305 is the safest bet these days. +AES-GCM-SIV is the second safest. +AES-GCM is the third. + +### How to encrypt properly + +- Use unpredictable key with enough entropy + - Random key must be using cryptographically secure random number generator (CSPRNG), not `Math.random` etc. + - Non-random key generated from KDF is fine + - Re-using key is fine, but be aware of rules for cryptographic key wear-out and [encryption limits](#encryption-limits) +- Use new nonce every time and [don't repeat it](#nonces) + - chacha and salsa20 are fine for sequential counters that _never_ repeat: `01, 02...` + - xchacha and xsalsa20 should be used for random nonces instead +- Prefer authenticated encryption (AEAD) + - HMAC+ChaCha / HMAC+AES / chacha20poly1305 / aes-gcm is good + - chacha20 without poly1305 or hmac / aes-ctr / aes-cbc is bad + - Flipping bits or ciphertext substitution won't be detected in unauthenticated ciphers +- Don't re-use keys between different protocols + - For example, using secp256k1 key in AES is bad + - Use hkdf or, at least, a hash function to create sub-key instead + +### Nonces + +Most ciphers need a key and a nonce (aka initialization vector / IV) to encrypt a data: + + ciphertext = encrypt(plaintext, key, nonce) + +Repeating (key, nonce) pair with different plaintexts would allow an attacker to decrypt it: + + ciphertext_a = encrypt(plaintext_a, key, nonce) + ciphertext_b = encrypt(plaintext_b, key, nonce) + stream_diff = xor(ciphertext_a, ciphertext_b) # Break encryption + +So, you can't repeat nonces. One way of doing so is using counters: + + for i in 0..: + ciphertext[i] = encrypt(plaintexts[i], key, i) + +Another is generating random nonce every time: + + for i in 0..: + rand_nonces[i] = random() + ciphertext[i] = encrypt(plaintexts[i], key, rand_nonces[i]) + +Counters are OK, but it's not always possible to store current counter value: +e.g. in decentralized, unsyncable systems. + +Randomness is OK, but there's a catch: +ChaCha20 and AES-GCM use 96-bit / 12-byte nonces, which implies +higher chance of collision. In the example above, +`random()` can collide and produce repeating nonce. + +To safely use random nonces, utilize XSalsa20 or XChaCha: +they increased nonce length to 192-bit, minimizing a chance of collision. +AES-SIV is also fine. In situations where you can't use eXtended-nonce +algorithms, key rotation is advised. hkdf would work great for this case. + +### Encryption limits + +A "protected message" would mean a probability of `2**-50` that a passive attacker +successfully distinguishes the ciphertext outputs of the AEAD scheme from the outputs +of a random function. See [draft-irtf-cfrg-aead-limits](https://datatracker.ietf.org/doc/draft-irtf-cfrg-aead-limits/) for details. + +- Max message size: + - AES-GCM: ~68GB, `2**36-256` + - Salsa, ChaCha, XSalsa, XChaCha: ~256GB, `2**38-64` +- Max amount of protected messages, under same key: + - AES-GCM: `2**32.5` + - Salsa, ChaCha: `2**46`, but only integrity is affected, not confidentiality + - XSalsa, XChaCha: `2**72` +- Max amount of protected messages, across all keys: + - AES-GCM: `2**69/B` where B is max blocks encrypted by a key. Meaning + `2**59` for 1KB, `2**49` for 1MB, `2**39` for 1GB + - Salsa, ChaCha, XSalsa, XChaCha: `2**100` + +##### AES internals and block modes + +`cipher = encrypt(block, key)`. Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256bit). Every round does: + +1. **S-box**, table substitution +2. **Shift rows**, cyclic shift left of all rows of data array +3. **Mix columns**, multiplying every column by fixed polynomial +4. **Add round key**, round_key xor i-th column of array + +For non-deterministic (not ECB) schemes, initialization vector (IV) is mixed to block/key; +and each new round either depends on previous block's key, or on some counter. + +- ECB — simple deterministic replacement. Dangerous: always map x to y. See [AES Penguin](https://words.filippo.io/the-ecb-penguin/) +- CBC — key is previous round’s block. Hard to use: need proper padding, also needs MAC +- CTR — counter, allows to create streaming cipher. Requires good IV. Parallelizable. OK, but no MAC +- GCM — modern CTR, parallel, with MAC +- SIV — synthetic initialization vector, nonce-misuse-resistant. Guarantees that, when a nonce is repeated, + the only security loss is that identical plaintexts will produce identical ciphertexts. +- XTS — used in hard drives. Similar to ECB (deterministic), but has `[i][j]` + tweak arguments corresponding to sector i and 16-byte block (part of sector) j. Not authenticated! + +GCM / SIV are not ideal: + +- Conservative key wear-out is `2**32` (4B) msgs +- MAC can be forged: see Poly1305 section above. Same for SIV + +## Security + +The library has not been independently audited yet. + +It is tested against property-based, cross-library and Wycheproof vectors, +and has fuzzing by [Guido Vranken's cryptofuzz](https://github.com/guidovranken/cryptofuzz). + +If you see anything unusual: investigate and report. + +### Constant-timeness + +_JIT-compiler_ and _Garbage Collector_ make "constant time" extremely hard to +achieve [timing attack](https://en.wikipedia.org/wiki/Timing_attack) resistance +in a scripting language. Which means _any other JS library can't have +constant-timeness_. Even statically typed Rust, a language without GC, +[makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security) +for some cases. If your goal is absolute security, don't use any JS lib — including bindings to native ones. +Use low-level libraries & languages. Nonetheless we're targetting algorithmic constant time. + +AES uses T-tables, which means it can't be done in constant-time in JS. + +### Supply chain security + +- **Commits** are signed with PGP keys, to prevent forgery. Make sure to verify commit signatures. +- **Releases** are transparent and built on GitHub CI. Make sure to verify [provenance](https://docs.npmjs.com/generating-provenance-statements) logs +- **Rare releasing** is followed to ensure less re-audit need for end-users +- **Dependencies** are minimized and locked-down: + - If your app has 500 dependencies, any dep could get hacked and you'll be downloading + malware with every install. We make sure to use as few dependencies as possible + - We prevent automatic dependency updates by locking-down version ranges. Every update is checked with `npm-diff` +- **Dev Dependencies** are only used if you want to contribute to the repo. They are disabled for end-users: + - scure-base, micro-bmark and micro-should are developed by the same author and follow identical security practices + - prettier (linter), fast-check (property-based testing) and typescript are used for code quality, vector generation and ts compilation. The packages are big, which makes it hard to audit their source code thoroughly and fully + +### Randomness + +We're deferring to built-in +[crypto.getRandomValues](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) +which is considered cryptographically secure (CSPRNG). + +In the past, browsers had bugs that made it weak: it may happen again. +Implementing a userspace CSPRNG to get resilient to the weakness +is even worse: there is no reliable userspace source of quality entropy. + +## Speed + +To summarize, noble is the fastest JS implementation of Salsa, ChaCha and AES. + +You can gain additional speed-up and +avoid memory allocations by passing `output` +uint8array into encrypt / decrypt methods. + +Benchmark results on Apple M2 with node v20: + +``` +encrypt (64B) +├─xsalsa20poly1305 x 485,672 ops/sec @ 2μs/op +├─chacha20poly1305 x 466,200 ops/sec @ 2μs/op +├─xchacha20poly1305 x 312,500 ops/sec @ 3μs/op +├─aes-256-gcm x 151,057 ops/sec @ 6μs/op +└─aes-256-gcm-siv x 124,984 ops/sec @ 8μs/op +encrypt (1KB) +├─xsalsa20poly1305 x 146,477 ops/sec @ 6μs/op +├─chacha20poly1305 x 145,518 ops/sec @ 6μs/op +├─xchacha20poly1305 x 126,119 ops/sec @ 7μs/op +├─aes-256-gcm x 43,207 ops/sec @ 23μs/op +└─aes-256-gcm-siv x 39,363 ops/sec @ 25μs/op +encrypt (8KB) +├─xsalsa20poly1305 x 23,773 ops/sec @ 42μs/op +├─chacha20poly1305 x 24,134 ops/sec @ 41μs/op +├─xchacha20poly1305 x 23,520 ops/sec @ 42μs/op +├─aes-256-gcm x 8,420 ops/sec @ 118μs/op +└─aes-256-gcm-siv x 8,126 ops/sec @ 123μs/op +encrypt (1MB) +├─xsalsa20poly1305 x 195 ops/sec @ 5ms/op +├─chacha20poly1305 x 199 ops/sec @ 5ms/op +├─xchacha20poly1305 x 198 ops/sec @ 5ms/op +├─aes-256-gcm x 76 ops/sec @ 13ms/op +└─aes-256-gcm-siv x 78 ops/sec @ 12ms/op +``` + +Unauthenticated encryption: + +``` +encrypt (64B) +├─salsa x 1,287,001 ops/sec @ 777ns/op +├─chacha x 1,555,209 ops/sec @ 643ns/op +├─xsalsa x 938,086 ops/sec @ 1μs/op +└─xchacha x 920,810 ops/sec @ 1μs/op +encrypt (1KB) +├─salsa x 353,107 ops/sec @ 2μs/op +├─chacha x 377,216 ops/sec @ 2μs/op +├─xsalsa x 331,674 ops/sec @ 3μs/op +└─xchacha x 336,247 ops/sec @ 2μs/op +encrypt (8KB) +├─salsa x 57,084 ops/sec @ 17μs/op +├─chacha x 59,520 ops/sec @ 16μs/op +├─xsalsa x 57,097 ops/sec @ 17μs/op +└─xchacha x 58,278 ops/sec @ 17μs/op +encrypt (1MB) +├─salsa x 479 ops/sec @ 2ms/op +├─chacha x 491 ops/sec @ 2ms/op +├─xsalsa x 483 ops/sec @ 2ms/op +└─xchacha x 492 ops/sec @ 2ms/op + +AES +encrypt (64B) +├─ctr-256 x 689,179 ops/sec @ 1μs/op +├─cbc-256 x 639,795 ops/sec @ 1μs/op +└─ecb-256 x 668,449 ops/sec @ 1μs/op +encrypt (1KB) +├─ctr-256 x 93,668 ops/sec @ 10μs/op +├─cbc-256 x 94,428 ops/sec @ 10μs/op +└─ecb-256 x 151,699 ops/sec @ 6μs/op +encrypt (8KB) +├─ctr-256 x 13,342 ops/sec @ 74μs/op +├─cbc-256 x 13,664 ops/sec @ 73μs/op +└─ecb-256 x 22,426 ops/sec @ 44μs/op +encrypt (1MB) +├─ctr-256 x 106 ops/sec @ 9ms/op +├─cbc-256 x 109 ops/sec @ 9ms/op +└─ecb-256 x 179 ops/sec @ 5ms/op +``` + +Compare to other implementations: + +``` +xsalsa20poly1305 (encrypt, 1MB) +├─tweetnacl x 108 ops/sec @ 9ms/op +└─noble x 190 ops/sec @ 5ms/op + +chacha20poly1305 (encrypt, 1MB) +├─node x 1,360 ops/sec @ 735μs/op +├─stablelib x 117 ops/sec @ 8ms/op +└─noble x 193 ops/sec @ 5ms/op + +chacha (encrypt, 1MB) +├─node x 2,035 ops/sec @ 491μs/op +├─stablelib x 206 ops/sec @ 4ms/op +└─noble x 474 ops/sec @ 2ms/op + +ctr-256 (encrypt, 1MB) +├─node x 3,530 ops/sec @ 283μs/op +├─stablelib x 70 ops/sec @ 14ms/op +├─aesjs x 31 ops/sec @ 32ms/op +├─noble-webcrypto x 4,589 ops/sec @ 217μs/op +└─noble x 107 ops/sec @ 9ms/op + +cbc-256 (encrypt, 1MB) +├─node x 993 ops/sec @ 1ms/op +├─stablelib x 63 ops/sec @ 15ms/op +├─aesjs x 29 ops/sec @ 34ms/op +├─noble-webcrypto x 1,087 ops/sec @ 919μs/op +└─noble x 110 ops/sec @ 9ms/op + +gcm-256 (encrypt, 1MB) +├─node x 3,196 ops/sec @ 312μs/op +├─stablelib x 27 ops/sec @ 36ms/op +├─noble-webcrypto x 4,059 ops/sec @ 246μs/op +└─noble x 74 ops/sec @ 13ms/op +``` + +## Upgrading + +Upgrade from `micro-aes-gcm` package is simple: + +```js +// prepare +const key = Uint8Array.from([ + 64, 196, 127, 247, 172, 2, 34, 159, 6, 241, 30, 174, 183, 229, 41, 114, 253, 122, 119, 168, 177, + 243, 155, 236, 164, 159, 98, 72, 162, 243, 224, 195, +]); +const message = 'Hello world'; + +// previous +import * as aes from 'micro-aes-gcm'; +const ciphertext = await aes.encrypt(key, aes.utils.utf8ToBytes(message)); +const plaintext = await aes.decrypt(key, ciphertext); +console.log(aes.utils.bytesToUtf8(plaintext) === message); + +// became => + +import { gcm } from '@noble/ciphers/aes'; +import { bytesToUtf8, utf8ToBytes } from '@noble/ciphers/utils'; +import { managedNonce } from '@noble/ciphers/webcrypto'; +const aes = managedNonce(gcm)(key); +const ciphertext = aes.encrypt(utf8ToBytes(message)); +const plaintext = aes.decrypt(key, ciphertext); +console.log(bytesToUtf8(plaintext) === message); +``` + +## Contributing & testing + +1. Clone the repository +2. `npm install` to install build dependencies like TypeScript +3. `npm run build` to compile TypeScript code +4. `npm run test` will execute all main tests + +## Resources + +Check out [paulmillr.com/noble](https://paulmillr.com/noble/) +for useful resources, articles, documentation and demos +related to the library. + +## License + +The MIT License (MIT) + +Copyright (c) 2023 Paul Miller [(https://paulmillr.com)](https://paulmillr.com) +Copyright (c) 2016 Thomas Pornin + +See LICENSE file. diff --git a/node_modules/@noble/ciphers/_arx.d.ts b/node_modules/@noble/ciphers/_arx.d.ts new file mode 100644 index 0000000..2566942 --- /dev/null +++ b/node_modules/@noble/ciphers/_arx.d.ts @@ -0,0 +1,14 @@ +import { XorStream } from './utils.js'; +export declare const sigma: Uint32Array; +export declare function rotl(a: number, b: number): number; +export type CipherCoreFn = (sigma: Uint32Array, key: Uint32Array, nonce: Uint32Array, output: Uint32Array, counter: number, rounds?: number) => void; +export type ExtendNonceFn = (sigma: Uint32Array, key: Uint32Array, input: Uint32Array, output: Uint32Array) => void; +export type CipherOpts = { + allowShortKeys?: boolean; + extendNonceFn?: ExtendNonceFn; + counterLength?: number; + counterRight?: boolean; + rounds?: number; +}; +export declare function createCipher(core: CipherCoreFn, opts: CipherOpts): XorStream; +//# sourceMappingURL=_arx.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_arx.d.ts.map b/node_modules/@noble/ciphers/_arx.d.ts.map new file mode 100644 index 0000000..43b5e16 --- /dev/null +++ b/node_modules/@noble/ciphers/_arx.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"_arx.d.ts","sourceRoot":"","sources":["src/_arx.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAkB,MAAM,YAAY,CAAC;AA4CvD,eAAO,MAAM,KAAK,aAAqB,CAAC;AAExC,wBAAgB,IAAI,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAEjD;AAED,MAAM,MAAM,YAAY,GAAG,CACzB,KAAK,EAAE,WAAW,EAClB,GAAG,EAAE,WAAW,EAChB,KAAK,EAAE,WAAW,EAClB,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,MAAM,EACf,MAAM,CAAC,EAAE,MAAM,KACZ,IAAI,CAAC;AAEV,MAAM,MAAM,aAAa,GAAG,CAC1B,KAAK,EAAE,WAAW,EAClB,GAAG,EAAE,WAAW,EAChB,KAAK,EAAE,WAAW,EAClB,MAAM,EAAE,WAAW,KAChB,IAAI,CAAC;AAEV,MAAM,MAAM,UAAU,GAAG;IACvB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AAwDF,wBAAgB,YAAY,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,UAAU,GAAG,SAAS,CAsF5E"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_arx.js b/node_modules/@noble/ciphers/_arx.js new file mode 100644 index 0000000..4da22df --- /dev/null +++ b/node_modules/@noble/ciphers/_arx.js @@ -0,0 +1,175 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createCipher = exports.rotl = exports.sigma = void 0; +// Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers. +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +/* +RFC8439 requires multi-step cipher stream, where +authKey starts with counter: 0, actual msg with counter: 1. + +For this, we need a way to re-use nonce / counter: + + const counter = new Uint8Array(4); + chacha(..., counter, ...); // counter is now 1 + chacha(..., counter, ...); // counter is now 2 + +This is complicated: + +- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB +- Original papers don't allow mutating counters +- Counter overflow is undefined [^1] +- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it +- Caveat: Cannot be re-used through all cases: +- * chacha has (counter | nonce) +- * xchacha has (nonce16 | counter | nonce16) +- Idea B: separate nonce / counter and provide separate API for counter re-use +- Caveat: there are different counter sizes depending on an algorithm. +- salsa & chacha also differ in structures of key & sigma: + salsa20: s[0] | k(4) | s[1] | nonce(2) | ctr(2) | s[2] | k(4) | s[3] + chacha: s(4) | k(8) | ctr(1) | nonce(3) + chacha20orig: s(4) | k(8) | ctr(2) | nonce(2) +- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)` +- Caveat: we can't re-use counter array + +xchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal +(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce). + +[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ +[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 +*/ +// We can't make top-level var depend on utils.utf8ToBytes +// because it's not present in all envs. Creating a similar fn here +const _utf8ToBytes = (str) => Uint8Array.from(str.split('').map((c) => c.charCodeAt(0))); +const sigma16 = _utf8ToBytes('expand 16-byte k'); +const sigma32 = _utf8ToBytes('expand 32-byte k'); +const sigma16_32 = (0, utils_js_1.u32)(sigma16); +const sigma32_32 = (0, utils_js_1.u32)(sigma32); +exports.sigma = sigma32_32.slice(); +function rotl(a, b) { + return (a << b) | (a >>> (32 - b)); +} +exports.rotl = rotl; +// Is byte array aligned to 4 byte offset (u32)? +function isAligned32(b) { + return b.byteOffset % 4 === 0; +} +// Salsa and Chacha block length is always 512-bit +const BLOCK_LEN = 64; +const BLOCK_LEN32 = 16; +// new Uint32Array([2**32]) // => Uint32Array(1) [ 0 ] +// new Uint32Array([2**32-1]) // => Uint32Array(1) [ 4294967295 ] +const MAX_COUNTER = 2 ** 32 - 1; +const U32_EMPTY = new Uint32Array(); +function runCipher(core, sigma, key, nonce, data, output, counter, rounds) { + const len = data.length; + const block = new Uint8Array(BLOCK_LEN); + const b32 = (0, utils_js_1.u32)(block); + // Make sure that buffers aligned to 4 bytes + const isAligned = isAligned32(data) && isAligned32(output); + const d32 = isAligned ? (0, utils_js_1.u32)(data) : U32_EMPTY; + const o32 = isAligned ? (0, utils_js_1.u32)(output) : U32_EMPTY; + for (let pos = 0; pos < len; counter++) { + core(sigma, key, nonce, b32, counter, rounds); + if (counter >= MAX_COUNTER) + throw new Error('arx: counter overflow'); + const take = Math.min(BLOCK_LEN, len - pos); + // aligned to 4 bytes + if (isAligned && take === BLOCK_LEN) { + const pos32 = pos / 4; + if (pos % 4 !== 0) + throw new Error('arx: invalid block position'); + for (let j = 0, posj; j < BLOCK_LEN32; j++) { + posj = pos32 + j; + o32[posj] = d32[posj] ^ b32[j]; + } + pos += BLOCK_LEN; + continue; + } + for (let j = 0, posj; j < take; j++) { + posj = pos + j; + output[posj] = data[posj] ^ block[j]; + } + pos += take; + } +} +function createCipher(core, opts) { + const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = (0, utils_js_1.checkOpts)({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts); + if (typeof core !== 'function') + throw new Error('core must be a function'); + (0, _assert_js_1.number)(counterLength); + (0, _assert_js_1.number)(rounds); + (0, _assert_js_1.bool)(counterRight); + (0, _assert_js_1.bool)(allowShortKeys); + return (key, nonce, data, output, counter = 0) => { + (0, _assert_js_1.bytes)(key); + (0, _assert_js_1.bytes)(nonce); + (0, _assert_js_1.bytes)(data); + const len = data.length; + if (!output) + output = new Uint8Array(len); + (0, _assert_js_1.bytes)(output); + (0, _assert_js_1.number)(counter); + if (counter < 0 || counter >= MAX_COUNTER) + throw new Error('arx: counter overflow'); + if (output.length < len) + throw new Error(`arx: output (${output.length}) is shorter than data (${len})`); + const toClean = []; + // Key & sigma + // key=16 -> sigma16, k=key|key + // key=32 -> sigma32, k=key + let l = key.length, k, sigma; + if (l === 32) { + k = key.slice(); + toClean.push(k); + sigma = sigma32_32; + } + else if (l === 16 && allowShortKeys) { + k = new Uint8Array(32); + k.set(key); + k.set(key, 16); + sigma = sigma16_32; + toClean.push(k); + } + else { + throw new Error(`arx: invalid 32-byte key, got length=${l}`); + } + // Nonce + // salsa20: 8 (8-byte counter) + // chacha20orig: 8 (8-byte counter) + // chacha20: 12 (4-byte counter) + // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce) + // xchacha20: 24 (16 -> hchacha, 8 -> old nonce) + // Align nonce to 4 bytes + if (!isAligned32(nonce)) { + nonce = nonce.slice(); + toClean.push(nonce); + } + const k32 = (0, utils_js_1.u32)(k); + // hsalsa & hchacha: handle extended nonce + if (extendNonceFn) { + if (nonce.length !== 24) + throw new Error(`arx: extended nonce must be 24 bytes`); + extendNonceFn(sigma, k32, (0, utils_js_1.u32)(nonce.subarray(0, 16)), k32); + nonce = nonce.subarray(16); + } + // Handle nonce counter + const nonceNcLen = 16 - counterLength; + if (nonceNcLen !== nonce.length) + throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`); + // Pad counter when nonce is 64 bit + if (nonceNcLen !== 12) { + const nc = new Uint8Array(12); + nc.set(nonce, counterRight ? 0 : 12 - nonce.length); + nonce = nc; + toClean.push(nonce); + } + const n32 = (0, utils_js_1.u32)(nonce); + runCipher(core, sigma, k32, n32, data, output, counter, rounds); + while (toClean.length > 0) + toClean.pop().fill(0); + return output; + }; +} +exports.createCipher = createCipher; +//# sourceMappingURL=_arx.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_arx.js.map b/node_modules/@noble/ciphers/_arx.js.map new file mode 100644 index 0000000..83bedcb --- /dev/null +++ b/node_modules/@noble/ciphers/_arx.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_arx.js","sourceRoot":"","sources":["src/_arx.ts"],"names":[],"mappings":";;;AAAA,iEAAiE;AACjE,6CAAiF;AACjF,yCAAuD;AAEvD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAiCE;AAEF,0DAA0D;AAC1D,mEAAmE;AACnE,MAAM,YAAY,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACjG,MAAM,OAAO,GAAG,YAAY,CAAC,kBAAkB,CAAC,CAAC;AACjD,MAAM,OAAO,GAAG,YAAY,CAAC,kBAAkB,CAAC,CAAC;AACjD,MAAM,UAAU,GAAG,IAAA,cAAG,EAAC,OAAO,CAAC,CAAC;AAChC,MAAM,UAAU,GAAG,IAAA,cAAG,EAAC,OAAO,CAAC,CAAC;AACnB,QAAA,KAAK,GAAG,UAAU,CAAC,KAAK,EAAE,CAAC;AAExC,SAAgB,IAAI,CAAC,CAAS,EAAE,CAAS;IACvC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;AACrC,CAAC;AAFD,oBAEC;AA0BD,gDAAgD;AAChD,SAAS,WAAW,CAAC,CAAa;IAChC,OAAO,CAAC,CAAC,UAAU,GAAG,CAAC,KAAK,CAAC,CAAC;AAChC,CAAC;AAED,kDAAkD;AAClD,MAAM,SAAS,GAAG,EAAE,CAAC;AACrB,MAAM,WAAW,GAAG,EAAE,CAAC;AAEv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CAAC,CAAC;YACpD,KAAK,GAAG,EAAE,CAAC;YACX,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACtB,CAAC;QACD,MAAM,GAAG,GAAG,IAAA,cAAG,EAAC,KAAK,CAAC,CAAC;QACvB,SAAS,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;QAChE,OAAO,OAAO,CAAC,MAAM,GAAG,CAAC;YAAE,OAAO,CAAC,GAAG,EAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAClD,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC;AAtFD,oCAsFC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_assert.d.ts b/node_modules/@noble/ciphers/_assert.d.ts new file mode 100644 index 0000000..4654379 --- /dev/null +++ b/node_modules/@noble/ciphers/_assert.d.ts @@ -0,0 +1,24 @@ +declare function number(n: number): void; +declare function bool(b: boolean): void; +export declare function isBytes(a: unknown): a is Uint8Array; +declare function bytes(b: Uint8Array | undefined, ...lengths: number[]): void; +export type Hash = { + (data: Uint8Array): Uint8Array; + blockLen: number; + outputLen: number; + create: any; +}; +declare function hash(hash: Hash): void; +declare function exists(instance: any, checkFinished?: boolean): void; +declare function output(out: any, instance: any): void; +export { number, bool, bytes, hash, exists, output }; +declare const assert: { + number: typeof number; + bool: typeof bool; + bytes: typeof bytes; + hash: typeof hash; + exists: typeof exists; + output: typeof output; +}; +export default assert; +//# sourceMappingURL=_assert.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_assert.d.ts.map b/node_modules/@noble/ciphers/_assert.d.ts.map new file mode 100644 index 0000000..8d89b75 --- /dev/null +++ b/node_modules/@noble/ciphers/_assert.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"_assert.d.ts","sourceRoot":"","sources":["src/_assert.ts"],"names":[],"mappings":"AAAA,iBAAS,MAAM,CAAC,CAAC,EAAE,MAAM,QAExB;AAED,iBAAS,IAAI,CAAC,CAAC,EAAE,OAAO,QAEvB;AAED,wBAAgB,OAAO,CAAC,CAAC,EAAE,OAAO,GAAG,CAAC,IAAI,UAAU,CAKnD;AAED,iBAAS,KAAK,CAAC,CAAC,EAAE,UAAU,GAAG,SAAS,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,QAI7D;AAED,MAAM,MAAM,IAAI,GAAG;IACjB,CAAC,IAAI,EAAE,UAAU,GAAG,UAAU,CAAC;IAC/B,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,GAAG,CAAC;CACb,CAAC;AACF,iBAAS,IAAI,CAAC,IAAI,EAAE,IAAI,QAKvB;AAED,iBAAS,MAAM,CAAC,QAAQ,EAAE,GAAG,EAAE,aAAa,UAAO,QAGlD;AAED,iBAAS,MAAM,CAAC,GAAG,EAAE,GAAG,EAAE,QAAQ,EAAE,GAAG,QAMtC;AAED,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AACrD,QAAA,MAAM,MAAM;;;;;;;CAAgD,CAAC;AAC7D,eAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_assert.js b/node_modules/@noble/ciphers/_assert.js new file mode 100644 index 0000000..83ace83 --- /dev/null +++ b/node_modules/@noble/ciphers/_assert.js @@ -0,0 +1,50 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.output = exports.exists = exports.hash = exports.bytes = exports.bool = exports.number = exports.isBytes = void 0; +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`positive integer expected, not ${n}`); +} +exports.number = number; +function bool(b) { + if (typeof b !== 'boolean') + throw new Error(`boolean expected, not ${b}`); +} +exports.bool = bool; +function isBytes(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +exports.isBytes = isBytes; +function bytes(b, ...lengths) { + if (!isBytes(b)) + throw new Error('Uint8Array expected'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`); +} +exports.bytes = bytes; +function hash(hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') + throw new Error('hash must be wrapped by utils.wrapConstructor'); + number(hash.outputLen); + number(hash.blockLen); +} +exports.hash = hash; +function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +exports.exists = exists; +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} +exports.output = output; +const assert = { number, bool, bytes, hash, exists, output }; +exports.default = assert; +//# sourceMappingURL=_assert.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_assert.js.map b/node_modules/@noble/ciphers/_assert.js.map new file mode 100644 index 0000000..234f148 --- /dev/null +++ b/node_modules/@noble/ciphers/_assert.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_assert.js","sourceRoot":"","sources":["src/_assert.ts"],"names":[],"mappings":";;;AAAA,SAAS,MAAM,CAAC,CAAS;IACvB,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,EAAE,CAAC,CAAC;AAChG,CAAC;AA6CQ,wBAAM;AA3Cf,SAAS,IAAI,CAAC,CAAU;IACtB,IAAI,OAAO,CAAC,KAAK,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,EAAE,CAAC,CAAC;AAC5E,CAAC;AAyCgB,oBAAI;AAvCrB,SAAgB,OAAO,CAAC,CAAU;IAChC,OAAO,CACL,CAAC,YAAY,UAAU;QACvB,CAAC,CAAC,I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AAM,IAAI,KAAK,CAAC,yDAAyD,GAAG,EAAE,CAAC,CAAC;IAClF,CAAC;AACH,CAAC;AAE2C,wBAAM;AAClD,MAAM,MAAM,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAC7D,kBAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_micro.d.ts b/node_modules/@noble/ciphers/_micro.d.ts new file mode 100644 index 0000000..aa4e38f --- /dev/null +++ b/node_modules/@noble/ciphers/_micro.d.ts @@ -0,0 +1,70 @@ +/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */ +import { Cipher, XorStream } from './utils.js'; +export declare function hsalsa(s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array): void; +export declare function hchacha(s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array): void; +/** + * salsa20, 12-byte nonce. + */ +export declare const salsa20: XorStream; +/** + * xsalsa20, 24-byte nonce. + */ +export declare const xsalsa20: XorStream; +/** + * chacha20 non-RFC, original version by djb. 8-byte nonce, 8-byte counter. + */ +export declare const chacha20orig: XorStream; +/** + * chacha20 RFC 8439 (IETF / TLS). 12-byte nonce, 4-byte counter. + */ +export declare const chacha20: XorStream; +/** + * xchacha20 eXtended-nonce. https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha + */ +export declare const xchacha20: XorStream; +/** + * 8-round chacha from the original paper. + */ +export declare const chacha8: XorStream; +/** + * 12-round chacha from the original paper. + */ +export declare const chacha12: XorStream; +export declare function poly1305(msg: Uint8Array, key: Uint8Array): Uint8Array; +/** + * xsalsa20-poly1305 eXtended-nonce (24 bytes) salsa. + */ +export declare const xsalsa20poly1305: ((key: Uint8Array, nonce: Uint8Array) => { + encrypt: (plaintext: Uint8Array) => Uint8Array; + decrypt: (ciphertext: Uint8Array) => Uint8Array; +}) & { + blockSize: number; + nonceLength: number; + tagLength: number; +}; +/** + * Alias to xsalsa20-poly1305 + */ +export declare function secretbox(key: Uint8Array, nonce: Uint8Array): { + seal: (plaintext: Uint8Array) => Uint8Array; + open: (ciphertext: Uint8Array) => Uint8Array; +}; +export declare const _poly1305_aead: (fn: XorStream) => (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => Cipher; +/** + * chacha20-poly1305 12-byte-nonce chacha. + */ +export declare const chacha20poly1305: ((key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => Cipher) & { + blockSize: number; + nonceLength: number; + tagLength: number; +}; +/** + * xchacha20-poly1305 eXtended-nonce (24 bytes) chacha. + * With 24-byte nonce, it's safe to use fill it with random (CSPRNG). + */ +export declare const xchacha20poly1305: ((key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => Cipher) & { + blockSize: number; + nonceLength: number; + tagLength: number; +}; +//# sourceMappingURL=_micro.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_micro.d.ts.map b/node_modules/@noble/ciphers/_micro.d.ts.map new file mode 100644 index 0000000..f6df3b2 --- /dev/null +++ b/node_modules/@noble/ciphers/_micro.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"_micro.d.ts","sourceRoot":"","sources":["src/_micro.ts"],"names":[],"mappings":"AAAA,uEAAuE;AAEvE,OAAO,EACL,MAAM,EAAE,SAAS,EAElB,MAAM,YAAY,CAAC;AA+EpB,wBAAgB,MAAM,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,GAAG,EAAE,WAAW,QAatF;AAuBD,wBAAgB,OAAO,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,GAAG,EAAE,WAAW,QAavF;AAED;;GAEG;AACH,eAAO,MAAM,OAAO,WAGlB,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,QAAQ,WAGnB,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,YAAY,WAIvB,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,QAAQ,WAGnB,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,SAAS,WAIpB,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,OAAO,WAIlB,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,QAAQ,WAInB,CAAC;AAQH,wBAAgB,QAAQ,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,EAAE,UAAU,GAAG,UAAU,CAcrE;AA4BD;;GAEG;AACH,eAAO,MAAM,gBAAgB,SAEI,UAAU,SAAS,UAAU;yBAInC,UAAU;0BAST,UAAU;;;;;CAWrC,CAAC;AAEF;;GAEG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU;;;EAG3D;AAED,eAAO,MAAM,cAAc,OACpB,SAAS,WACR,UAAU,SAAS,UAAU,QAAQ,UAAU,KAAG,MAuBvD,CAAC;AAEJ;;GAEG;AACH,eAAO,MAAM,gBAAgB,SA5BrB,UAAU,SAAS,UAAU,QAAQ,UAAU,KAAG,MAAM;;;;CA+B/D,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,iBAAiB,SArCtB,UAAU,SAAS,UAAU,QAAQ,UAAU,KAAG,MAAM;;;;CAwC/D,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_micro.js b/node_modules/@noble/ciphers/_micro.js new file mode 100644 index 0000000..523065c --- /dev/null +++ b/node_modules/@noble/ciphers/_micro.js @@ -0,0 +1,295 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.xchacha20poly1305 = exports.chacha20poly1305 = exports._poly1305_aead = exports.secretbox = exports.xsalsa20poly1305 = exports.poly1305 = exports.chacha12 = exports.chacha8 = exports.xchacha20 = exports.chacha20 = exports.chacha20orig = exports.xsalsa20 = exports.salsa20 = exports.hchacha = exports.hsalsa = void 0; +/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */ +// prettier-ignore +const utils_js_1 = require("./utils.js"); +const _arx_js_1 = require("./_arx.js"); +const _assert_js_1 = require("./_assert.js"); +/* +noble-ciphers-micro: more auditable, but slower version of salsa20, chacha & poly1305. +Implements the same algorithms that are present in other files, but without +unrolled loops (https://en.wikipedia.org/wiki/Loop_unrolling). +*/ +function bytesToNumberLE(bytes) { + return (0, utils_js_1.hexToNumber)((0, utils_js_1.bytesToHex)(Uint8Array.from(bytes).reverse())); +} +function numberToBytesLE(n, len) { + return (0, utils_js_1.numberToBytesBE)(n, len).reverse(); +} +function salsaQR(x, a, b, c, d) { + x[b] ^= (0, _arx_js_1.rotl)((x[a] + x[d]) | 0, 7); + x[c] ^= (0, _arx_js_1.rotl)((x[b] + x[a]) | 0, 9); + x[d] ^= (0, _arx_js_1.rotl)((x[c] + x[b]) | 0, 13); + x[a] ^= (0, _arx_js_1.rotl)((x[d] + x[c]) | 0, 18); +} +// prettier-ignore +function chachaQR(x, a, b, c, d) { + x[a] = (x[a] + x[b]) | 0; + x[d] = (0, _arx_js_1.rotl)(x[d] ^ x[a], 16); + x[c] = (x[c] + x[d]) | 0; + x[b] = (0, _arx_js_1.rotl)(x[b] ^ x[c], 12); + x[a] = (x[a] + x[b]) | 0; + x[d] = (0, _arx_js_1.rotl)(x[d] ^ x[a], 8); + x[c] = (x[c] + x[d]) | 0; + x[b] = (0, _arx_js_1.rotl)(x[b] ^ x[c], 7); +} +function salsaRound(x, rounds = 20) { + for (let r = 0; r < rounds; r += 2) { + salsaQR(x, 0, 4, 8, 12); + salsaQR(x, 5, 9, 13, 1); + salsaQR(x, 10, 14, 2, 6); + salsaQR(x, 15, 3, 7, 11); + salsaQR(x, 0, 1, 2, 3); + salsaQR(x, 5, 6, 7, 4); + salsaQR(x, 10, 11, 8, 9); + salsaQR(x, 15, 12, 13, 14); + } +} +function chachaRound(x, rounds = 20) { + for (let r = 0; r < rounds; r += 2) { + chachaQR(x, 0, 4, 8, 12); + chachaQR(x, 1, 5, 9, 13); + chachaQR(x, 2, 6, 10, 14); + chachaQR(x, 3, 7, 11, 15); + chachaQR(x, 0, 5, 10, 15); + chachaQR(x, 1, 6, 11, 12); + chachaQR(x, 2, 7, 8, 13); + chachaQR(x, 3, 4, 9, 14); + } +} +function salsaCore(s, k, n, out, cnt, rounds = 20) { + // prettier-ignore + const y = new Uint32Array([ + s[0], k[0], k[1], k[2], // "expa" Key Key Key + k[3], s[1], n[0], n[1], // Key "nd 3" Nonce Nonce + cnt, 0, s[2], k[4], // Pos. Pos. "2-by" Key + k[5], k[6], k[7], s[3], // Key Key Key "te k" + ]); + const x = y.slice(); + salsaRound(x, rounds); + for (let i = 0; i < 16; i++) + out[i] = (y[i] + x[i]) | 0; +} +// prettier-ignore +function hsalsa(s, k, i, o32) { + const x = new Uint32Array([ + s[0], k[0], k[1], k[2], + k[3], s[1], i[0], i[1], + i[2], i[3], s[2], k[4], + k[5], k[6], k[7], s[3] + ]); + salsaRound(x, 20); + let oi = 0; + o32[oi++] = x[0]; + o32[oi++] = x[5]; + o32[oi++] = x[10]; + o32[oi++] = x[15]; + o32[oi++] = x[6]; + o32[oi++] = x[7]; + o32[oi++] = x[8]; + o32[oi++] = x[9]; +} +exports.hsalsa = hsalsa; +function chachaCore(s, k, n, out, cnt, rounds = 20) { + // prettier-ignore + const y = new Uint32Array([ + s[0], s[1], s[2], s[3], // "expa" "nd 3" "2-by" "te k" + k[0], k[1], k[2], k[3], // Key Key Key Key + k[4], k[5], k[6], k[7], // Key Key Key Key + cnt, n[0], n[1], n[2], // Counter Counter Nonce Nonce + ]); + const x = y.slice(); + chachaRound(x, rounds); + for (let i = 0; i < 16; i++) + out[i] = (y[i] + x[i]) | 0; +} +// prettier-ignore +function hchacha(s, k, i, o32) { + const x = new Uint32Array([ + s[0], s[1], s[2], s[3], + k[0], k[1], k[2], k[3], + k[4], k[5], k[6], k[7], + i[0], i[1], i[2], i[3], + ]); + chachaRound(x, 20); + let oi = 0; + o32[oi++] = x[0]; + o32[oi++] = x[1]; + o32[oi++] = x[2]; + o32[oi++] = x[3]; + o32[oi++] = x[12]; + o32[oi++] = x[13]; + o32[oi++] = x[14]; + o32[oi++] = x[15]; +} +exports.hchacha = hchacha; +/** + * salsa20, 12-byte nonce. + */ +exports.salsa20 = (0, _arx_js_1.createCipher)(salsaCore, { + allowShortKeys: true, + counterRight: true, +}); +/** + * xsalsa20, 24-byte nonce. + */ +exports.xsalsa20 = (0, _arx_js_1.createCipher)(salsaCore, { + counterRight: true, + extendNonceFn: hsalsa, +}); +/** + * chacha20 non-RFC, original version by djb. 8-byte nonce, 8-byte counter. + */ +exports.chacha20orig = (0, _arx_js_1.createCipher)(chachaCore, { + allowShortKeys: true, + counterRight: false, + counterLength: 8, +}); +/** + * chacha20 RFC 8439 (IETF / TLS). 12-byte nonce, 4-byte counter. + */ +exports.chacha20 = (0, _arx_js_1.createCipher)(chachaCore, { + counterRight: false, + counterLength: 4, +}); +/** + * xchacha20 eXtended-nonce. https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha + */ +exports.xchacha20 = (0, _arx_js_1.createCipher)(chachaCore, { + counterRight: false, + counterLength: 8, + extendNonceFn: hchacha, +}); +/** + * 8-round chacha from the original paper. + */ +exports.chacha8 = (0, _arx_js_1.createCipher)(chachaCore, { + counterRight: false, + counterLength: 4, + rounds: 8, +}); +/** + * 12-round chacha from the original paper. + */ +exports.chacha12 = (0, _arx_js_1.createCipher)(chachaCore, { + counterRight: false, + counterLength: 4, + rounds: 12, +}); +const POW_2_130_5 = BigInt(2) ** BigInt(130) - BigInt(5); +const POW_2_128_1 = BigInt(2) ** BigInt(16 * 8) - BigInt(1); +const CLAMP_R = BigInt('0x0ffffffc0ffffffc0ffffffc0fffffff'); +const _0 = BigInt(0); +const _1 = BigInt(1); +// Can be speed-up using BigUint64Array, but would be more complicated +function poly1305(msg, key) { + (0, _assert_js_1.bytes)(msg); + (0, _assert_js_1.bytes)(key); + let acc = _0; + const r = bytesToNumberLE(key.subarray(0, 16)) & CLAMP_R; + const s = bytesToNumberLE(key.subarray(16)); + // Process by 16 byte chunks + for (let i = 0; i < msg.length; i += 16) { + const m = msg.subarray(i, i + 16); + const n = bytesToNumberLE(m) | (_1 << BigInt(8 * m.length)); + acc = ((acc + n) * r) % POW_2_130_5; + } + const res = (acc + s) & POW_2_128_1; + return numberToBytesLE(res, 16); +} +exports.poly1305 = poly1305; +function computeTag(fn, key, nonce, ciphertext, AAD) { + const res = []; + if (AAD) { + res.push(AAD); + const leftover = AAD.length % 16; + if (leftover > 0) + res.push(new Uint8Array(16 - leftover)); + } + res.push(ciphertext); + const leftover = ciphertext.length % 16; + if (leftover > 0) + res.push(new Uint8Array(16 - leftover)); + // Lengths + const num = new Uint8Array(16); + const view = (0, utils_js_1.createView)(num); + (0, utils_js_1.setBigUint64)(view, 0, BigInt(AAD ? AAD.length : 0), true); + (0, utils_js_1.setBigUint64)(view, 8, BigInt(ciphertext.length), true); + res.push(num); + const authKey = fn(key, nonce, new Uint8Array(32)); + return poly1305((0, utils_js_1.concatBytes)(...res), authKey); +} +/** + * xsalsa20-poly1305 eXtended-nonce (24 bytes) salsa. + */ +exports.xsalsa20poly1305 = (0, utils_js_1.wrapCipher)({ blockSize: 64, nonceLength: 24, tagLength: 16 }, function xsalsa20poly1305(key, nonce) { + (0, _assert_js_1.bytes)(key); + (0, _assert_js_1.bytes)(nonce); + return { + encrypt: (plaintext) => { + (0, _assert_js_1.bytes)(plaintext); + const m = (0, utils_js_1.concatBytes)(new Uint8Array(32), plaintext); + const c = (0, exports.xsalsa20)(key, nonce, m); + const authKey = c.subarray(0, 32); + const data = c.subarray(32); + const tag = poly1305(data, authKey); + return (0, utils_js_1.concatBytes)(tag, data); + }, + decrypt: (ciphertext) => { + (0, _assert_js_1.bytes)(ciphertext); + if (ciphertext.length < 16) + throw new Error('encrypted data must be at least 16 bytes'); + const c = (0, utils_js_1.concatBytes)(new Uint8Array(16), ciphertext); + const authKey = (0, exports.xsalsa20)(key, nonce, new Uint8Array(32)); + const tag = poly1305(c.subarray(32), authKey); + if (!(0, utils_js_1.equalBytes)(c.subarray(16, 32), tag)) + throw new Error('invalid poly1305 tag'); + return (0, exports.xsalsa20)(key, nonce, c).subarray(32); + }, + }; +}); +/** + * Alias to xsalsa20-poly1305 + */ +function secretbox(key, nonce) { + const xs = (0, exports.xsalsa20poly1305)(key, nonce); + return { seal: xs.encrypt, open: xs.decrypt }; +} +exports.secretbox = secretbox; +const _poly1305_aead = (fn) => (key, nonce, AAD) => { + const tagLength = 16; + const keyLength = 32; + (0, _assert_js_1.bytes)(key, keyLength); + (0, _assert_js_1.bytes)(nonce); + return { + encrypt: (plaintext) => { + (0, _assert_js_1.bytes)(plaintext); + const res = fn(key, nonce, plaintext, undefined, 1); + const tag = computeTag(fn, key, nonce, res, AAD); + return (0, utils_js_1.concatBytes)(res, tag); + }, + decrypt: (ciphertext) => { + (0, _assert_js_1.bytes)(ciphertext); + if (ciphertext.length < tagLength) + throw new Error(`encrypted data must be at least ${tagLength} bytes`); + const passedTag = ciphertext.subarray(-tagLength); + const data = ciphertext.subarray(0, -tagLength); + const tag = computeTag(fn, key, nonce, data, AAD); + if (!(0, utils_js_1.equalBytes)(passedTag, tag)) + throw new Error('invalid poly1305 tag'); + return fn(key, nonce, data, undefined, 1); + }, + }; +}; +exports._poly1305_aead = _poly1305_aead; +/** + * chacha20-poly1305 12-byte-nonce chacha. + */ +exports.chacha20poly1305 = (0, utils_js_1.wrapCipher)({ blockSize: 64, nonceLength: 12, tagLength: 16 }, (0, exports._poly1305_aead)(exports.chacha20)); +/** + * xchacha20-poly1305 eXtended-nonce (24 bytes) chacha. + * With 24-byte nonce, it's safe to use fill it with random (CSPRNG). + */ +exports.xchacha20poly1305 = (0, utils_js_1.wrapCipher)({ blockSize: 64, nonceLength: 24, tagLength: 16 }, (0, exports._poly1305_aead)(exports.xchacha20)); +//# sourceMappingURL=_micro.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_micro.js.map b/node_modules/@noble/ciphers/_micro.js.map new file mode 100644 index 0000000..eeb153c --- /dev/null +++ b/node_modules/@noble/ciphers/_micro.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_micro.js","sourceRoot":"","sources":["src/_micro.ts"],"names":[],"mappings":";;;AAAA,uEAAuE;AACvE,kBAAkB;AAClB,yCAGoB;AACpB,uCAA+C;AAC/C,6CAA+C;AAE/C;;;;EAIE;AAEF,SAAS,eAAe,CAAC,KAAiB;IACxC,OAAO,IAAA,sBAAW,EAAC,IAAA,qBAAU,EAAC,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;AACnE,CAAC;AAED,SAAS,eAAe,CAAC,CAAkB,EAAE,GAAW;IACtD,OAAO,IAAA,0BAAe,EAAC,CAAC,EAAE,GAAG,CAAC,CAAC,OAAO,EAAE,CAAC;AAC3C,CAAC;AAED,SAAS,OAAO,CAAC,CAAc,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS;IACzE,CAAC,CAAC,CAAC,CAAC,IAAI,IAAA,cAAI,EAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;IACnC,CAAC,CAAC,CAAC,CAAC,IAAI,IAAA,cAAI,EAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;IACnC,CAAC,CAAC,CAAC,CAAC,IAAI,IAAA,cAAI,EAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;IACpC,CAAC,CAAC,CAAC,CAAC,IAAI,IAAA,cAAI,EAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,C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Ac,EAAC,iBAAS,CAAC,CAC1B,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_poly1305.d.ts b/node_modules/@noble/ciphers/_poly1305.d.ts new file mode 100644 index 0000000..ca0dfb8 --- /dev/null +++ b/node_modules/@noble/ciphers/_poly1305.d.ts @@ -0,0 +1,15 @@ +import { Input, Hash } from './utils.js'; +export type CHash = ReturnType; +export declare function wrapConstructorWithKey>(hashCons: (key: Input) => Hash): { + (msg: Input, key: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(key: Input): Hash; +}; +export declare const poly1305: { + (msg: Input, key: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(key: Input): Hash>; +}; +//# sourceMappingURL=_poly1305.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_poly1305.d.ts.map b/node_modules/@noble/ciphers/_poly1305.d.ts.map new file mode 100644 index 0000000..cf19c27 --- /dev/null +++ b/node_modules/@noble/ciphers/_poly1305.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"_poly1305.d.ts","sourceRoot":"","sources":["src/_poly1305.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAW,IAAI,EAAE,MAAM,YAAY,CAAC;AAkRlD,MAAM,MAAM,KAAK,GAAG,UAAU,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAC9D,wBAAgB,sBAAsB,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,GAAG,EAAE,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC;UACrE,KAAK,OAAO,KAAK,GAAG,UAAU;;;gBAI7B,KAAK;EAE3B;AAED,eAAO,MAAM,QAAQ;UARC,KAAK,OAAO,KAAK,GAAG,UAAU;;;gBAI7B,KAAK;CAI8C,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_poly1305.js b/node_modules/@noble/ciphers/_poly1305.js new file mode 100644 index 0000000..0652e24 --- /dev/null +++ b/node_modules/@noble/ciphers/_poly1305.js @@ -0,0 +1,268 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.poly1305 = exports.wrapConstructorWithKey = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +// Poly1305 is a fast and parallel secret-key message-authentication code. +// https://cr.yp.to/mac.html, https://cr.yp.to/mac/poly1305-20050329.pdf +// https://datatracker.ietf.org/doc/html/rfc8439 +// Based on Public Domain poly1305-donna https://github.com/floodyberry/poly1305-donna +const u8to16 = (a, i) => (a[i++] & 0xff) | ((a[i++] & 0xff) << 8); +class Poly1305 { + constructor(key) { + this.blockLen = 16; + this.outputLen = 16; + this.buffer = new Uint8Array(16); + this.r = new Uint16Array(10); + this.h = new Uint16Array(10); + this.pad = new Uint16Array(8); + this.pos = 0; + this.finished = false; + key = (0, utils_js_1.toBytes)(key); + (0, _assert_js_1.bytes)(key, 32); + const t0 = u8to16(key, 0); + const t1 = u8to16(key, 2); + const t2 = u8to16(key, 4); + const t3 = u8to16(key, 6); + const t4 = u8to16(key, 8); + const t5 = u8to16(key, 10); + const t6 = u8to16(key, 12); + const t7 = u8to16(key, 14); + // https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47 + this.r[0] = t0 & 0x1fff; + this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; + this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; + this.r[5] = (t4 >>> 1) & 0x1ffe; + this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; + this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + this.r[9] = (t7 >>> 5) & 0x007f; + for (let i = 0; i < 8; i++) + this.pad[i] = u8to16(key, 16 + 2 * i); + } + process(data, offset, isLast = false) { + const hibit = isLast ? 0 : 1 << 11; + const { h, r } = this; + const r0 = r[0]; + const r1 = r[1]; + const r2 = r[2]; + const r3 = r[3]; + const r4 = r[4]; + const r5 = r[5]; + const r6 = r[6]; + const r7 = r[7]; + const r8 = r[8]; + const r9 = r[9]; + const t0 = u8to16(data, offset + 0); + const t1 = u8to16(data, offset + 2); + const t2 = u8to16(data, offset + 4); + const t3 = u8to16(data, offset + 6); + const t4 = u8to16(data, offset + 8); + const t5 = u8to16(data, offset + 10); + const t6 = u8to16(data, offset + 12); + const t7 = u8to16(data, offset + 14); + let h0 = h[0] + (t0 & 0x1fff); + let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff); + let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff); + let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff); + let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff); + let h5 = h[5] + ((t4 >>> 1) & 0x1fff); + let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff); + let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff); + let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff); + let h9 = h[9] + ((t7 >>> 5) | hibit); + let c = 0; + let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6); + c = d0 >>> 13; + d0 &= 0x1fff; + d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1); + c += d0 >>> 13; + d0 &= 0x1fff; + let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7); + c = d1 >>> 13; + d1 &= 0x1fff; + d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2); + c += d1 >>> 13; + d1 &= 0x1fff; + let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8); + c = d2 >>> 13; + d2 &= 0x1fff; + d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3); + c += d2 >>> 13; + d2 &= 0x1fff; + let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9); + c = d3 >>> 13; + d3 &= 0x1fff; + d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4); + c += d3 >>> 13; + d3 &= 0x1fff; + let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0; + c = d4 >>> 13; + d4 &= 0x1fff; + d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5); + c += d4 >>> 13; + d4 &= 0x1fff; + let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1; + c = d5 >>> 13; + d5 &= 0x1fff; + d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6); + c += d5 >>> 13; + d5 &= 0x1fff; + let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2; + c = d6 >>> 13; + d6 &= 0x1fff; + d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7); + c += d6 >>> 13; + d6 &= 0x1fff; + let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3; + c = d7 >>> 13; + d7 &= 0x1fff; + d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8); + c += d7 >>> 13; + d7 &= 0x1fff; + let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4; + c = d8 >>> 13; + d8 &= 0x1fff; + d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9); + c += d8 >>> 13; + d8 &= 0x1fff; + let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5; + c = d9 >>> 13; + d9 &= 0x1fff; + d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0; + c += d9 >>> 13; + d9 &= 0x1fff; + c = ((c << 2) + c) | 0; + c = (c + d0) | 0; + d0 = c & 0x1fff; + c = c >>> 13; + d1 += c; + h[0] = d0; + h[1] = d1; + h[2] = d2; + h[3] = d3; + h[4] = d4; + h[5] = d5; + h[6] = d6; + h[7] = d7; + h[8] = d8; + h[9] = d9; + } + finalize() { + const { h, pad } = this; + const g = new Uint16Array(10); + let c = h[1] >>> 13; + h[1] &= 0x1fff; + for (let i = 2; i < 10; i++) { + h[i] += c; + c = h[i] >>> 13; + h[i] &= 0x1fff; + } + h[0] += c * 5; + c = h[0] >>> 13; + h[0] &= 0x1fff; + h[1] += c; + c = h[1] >>> 13; + h[1] &= 0x1fff; + h[2] += c; + g[0] = h[0] + 5; + c = g[0] >>> 13; + g[0] &= 0x1fff; + for (let i = 1; i < 10; i++) { + g[i] = h[i] + c; + c = g[i] >>> 13; + g[i] &= 0x1fff; + } + g[9] -= 1 << 13; + let mask = (c ^ 1) - 1; + for (let i = 0; i < 10; i++) + g[i] &= mask; + mask = ~mask; + for (let i = 0; i < 10; i++) + h[i] = (h[i] & mask) | g[i]; + h[0] = (h[0] | (h[1] << 13)) & 0xffff; + h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff; + h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff; + h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff; + h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff; + h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff; + h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff; + h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff; + let f = h[0] + pad[0]; + h[0] = f & 0xffff; + for (let i = 1; i < 8; i++) { + f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0; + h[i] = f & 0xffff; + } + } + update(data) { + (0, _assert_js_1.exists)(this); + const { buffer, blockLen } = this; + data = (0, utils_js_1.toBytes)(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input + if (take === blockLen) { + for (; blockLen <= len - pos; pos += blockLen) + this.process(data, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(buffer, 0, false); + this.pos = 0; + } + } + return this; + } + destroy() { + this.h.fill(0); + this.r.fill(0); + this.buffer.fill(0); + this.pad.fill(0); + } + digestInto(out) { + (0, _assert_js_1.exists)(this); + (0, _assert_js_1.output)(out, this); + this.finished = true; + const { buffer, h } = this; + let { pos } = this; + if (pos) { + buffer[pos++] = 1; + // buffer.subarray(pos).fill(0); + for (; pos < 16; pos++) + buffer[pos] = 0; + this.process(buffer, 0, true); + } + this.finalize(); + let opos = 0; + for (let i = 0; i < 8; i++) { + out[opos++] = h[i] >>> 0; + out[opos++] = h[i] >>> 8; + } + return out; + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } +} +function wrapConstructorWithKey(hashCons) { + const hashC = (msg, key) => hashCons(key).update((0, utils_js_1.toBytes)(msg)).digest(); + const tmp = hashCons(new Uint8Array(32)); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (key) => hashCons(key); + return hashC; +} +exports.wrapConstructorWithKey = wrapConstructorWithKey; +exports.poly1305 = wrapConstructorWithKey((key) => new Poly1305(key)); +//# sourceMappingURL=_poly1305.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_poly1305.js.map b/node_modules/@noble/ciphers/_poly1305.js.map new file mode 100644 index 0000000..b99260f --- /dev/null +++ b/node_modules/@noble/ciphers/_poly1305.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_poly1305.js","sourceRoot":"","sources":["src/_poly1305.ts"],"names":[],"mappings":";;;AAAA,6CAAqF;AACrF,yCAAkD;AAElD,0EAA0E;AAC1E,wEAAwE;AACxE,gDAAgD;AAEhD,sFAAsF;AACtF,MAAM,MAAM,GAAG,CAAC,CAAa,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AACtF,MAAM,QAAQ;IAUZ,YAAY,GAAU;QATb,aAAQ,GAAG,EAAE,CAAC;QACd,cAAS,GAAG,EAAE,CAAC;QAChB,WAAM,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;QAC5B,MAAC,GAAG,IAAI,WAAW,CAAC,EAAE,CAAC,CAAC;QACxB,MAAC,GAAG,IAAI,WAAW,CAAC,EAAE,CAAC,CAAC;QACxB,QAAG,GAAG,IAAI,WAAW,CAAC,CAAC,CAAC,CAAC;QACzB,QAAG,GAAG,CAAC,CAAC;QACN,aAAQ,GAAG,KAAK,CAAC;QAGzB,GAAG,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QACnB,IAAA,kBAAM,EAAC,GAAG,EAAE,EAAE,CAAC,CAAC;QAChB,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;QAC1B,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;QAC1B,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;QAC1B,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,EAAE,CA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AM,CAAC,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;IAClG,MAAM,GAAG,GAAG,QAAQ,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC;IACzC,KAAK,CAAC,SAAS,GAAG,GAAG,CAAC,SAAS,CAAC;IAChC,KAAK,CAAC,QAAQ,GAAG,GAAG,CAAC,QAAQ,CAAC;IAC9B,KAAK,CAAC,MAAM,GAAG,CAAC,GAAU,EAAE,EAAE,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;IAC7C,OAAO,KAAK,CAAC;AACf,CAAC;AAPD,wDAOC;AAEY,QAAA,QAAQ,GAAG,sBAAsB,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_polyval.d.ts b/node_modules/@noble/ciphers/_polyval.d.ts new file mode 100644 index 0000000..a3af794 --- /dev/null +++ b/node_modules/@noble/ciphers/_polyval.d.ts @@ -0,0 +1,27 @@ +import { Input, Hash } from './utils.js'; +/** + * `mulX_POLYVAL(ByteReverse(H))` from spec + * @param k mutated in place + */ +export declare function _toGHASHKey(k: Uint8Array): Uint8Array; +export type CHash = ReturnType; +declare function wrapConstructorWithKey>(hashCons: (key: Input, expectedLength?: number) => Hash): { + (msg: Input, key: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(key: Input, expectedLength?: number): Hash; +}; +export declare const ghash: { + (msg: Input, key: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(key: Input, expectedLength?: number): Hash>; +}; +export declare const polyval: { + (msg: Input, key: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(key: Input, expectedLength?: number): Hash>; +}; +export {}; +//# sourceMappingURL=_polyval.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_polyval.d.ts.map b/node_modules/@noble/ciphers/_polyval.d.ts.map new file mode 100644 index 0000000..8cd96ca --- /dev/null +++ b/node_modules/@noble/ciphers/_polyval.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"_polyval.d.ts","sourceRoot":"","sources":["src/_polyval.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuB,KAAK,EAAE,IAAI,EAAO,MAAM,YAAY,CAAC;AAsCnE;;;GAGG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAAE,UAAU,GAAG,UAAU,CAYrD;AA+KD,MAAM,MAAM,KAAK,GAAG,UAAU,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAC9D,iBAAS,sBAAsB,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,EAC/C,QAAQ,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,cAAc,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC;UAEtC,KAAK,OAAO,KAAK,GAAG,UAAU;;;gBAK7B,KAAK,mBAAmB,MAAM;EAEpD;AAED,eAAO,MAAM,KAAK;UATI,KAAK,OAAO,KAAK,GAAG,UAAU;;;gBAK7B,KAAK,mBAAmB,MAAM;CAMpD,CAAC;AACF,eAAO,MAAM,OAAO;UAZE,KAAK,OAAO,KAAK,GAAG,UAAU;;;gBAK7B,KAAK,mBAAmB,MAAM;CASpD,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_polyval.js b/node_modules/@noble/ciphers/_polyval.js new file mode 100644 index 0000000..7183fc9 --- /dev/null +++ b/node_modules/@noble/ciphers/_polyval.js @@ -0,0 +1,221 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.polyval = exports.ghash = exports._toGHASHKey = void 0; +const utils_js_1 = require("./utils.js"); +const _assert_js_1 = require("./_assert.js"); +// GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV. +// Implemented in terms of GHash with conversion function for keys +// GCM GHASH from NIST SP800-38d, SIV from RFC 8452. +// https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf +// GHASH modulo: x^128 + x^7 + x^2 + x + 1 +// POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1 +const BLOCK_SIZE = 16; +// TODO: rewrite +// temporary padding buffer +const ZEROS16 = /* @__PURE__ */ new Uint8Array(16); +const ZEROS32 = (0, utils_js_1.u32)(ZEROS16); +const POLY = 0xe1; // v = 2*v % POLY +// v = 2*v % POLY +// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x +// We can multiply any number using montgomery ladder and this function (works as double, add is simple xor) +const mul2 = (s0, s1, s2, s3) => { + const hiBit = s3 & 1; + return { + s3: (s2 << 31) | (s3 >>> 1), + s2: (s1 << 31) | (s2 >>> 1), + s1: (s0 << 31) | (s1 >>> 1), + s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly + }; +}; +const swapLE = (n) => (((n >>> 0) & 0xff) << 24) | + (((n >>> 8) & 0xff) << 16) | + (((n >>> 16) & 0xff) << 8) | + ((n >>> 24) & 0xff) | + 0; +/** + * `mulX_POLYVAL(ByteReverse(H))` from spec + * @param k mutated in place + */ +function _toGHASHKey(k) { + k.reverse(); + const hiBit = k[15] & 1; + // k >>= 1 + let carry = 0; + for (let i = 0; i < k.length; i++) { + const t = k[i]; + k[i] = (t >>> 1) | carry; + carry = (t & 1) << 7; + } + k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000; + return k; +} +exports._toGHASHKey = _toGHASHKey; +const estimateWindow = (bytes) => { + if (bytes > 64 * 1024) + return 8; + if (bytes > 1024) + return 4; + return 2; +}; +class GHASH { + // We select bits per window adaptively based on expectedLength + constructor(key, expectedLength) { + this.blockLen = BLOCK_SIZE; + this.outputLen = BLOCK_SIZE; + this.s0 = 0; + this.s1 = 0; + this.s2 = 0; + this.s3 = 0; + this.finished = false; + key = (0, utils_js_1.toBytes)(key); + (0, _assert_js_1.bytes)(key, 16); + const kView = (0, utils_js_1.createView)(key); + let k0 = kView.getUint32(0, false); + let k1 = kView.getUint32(4, false); + let k2 = kView.getUint32(8, false); + let k3 = kView.getUint32(12, false); + // generate table of doubled keys (half of montgomery ladder) + const doubles = []; + for (let i = 0; i < 128; i++) { + doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) }); + ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3)); + } + const W = estimateWindow(expectedLength || 1024); + if (![1, 2, 4, 8].includes(W)) + throw new Error(`ghash: wrong window size=${W}, should be 2, 4 or 8`); + this.W = W; + const bits = 128; // always 128 bits; + const windows = bits / W; + const windowSize = (this.windowSize = 2 ** W); + const items = []; + // Create precompute table for window of W bits + for (let w = 0; w < windows; w++) { + // truth table: 00, 01, 10, 11 + for (let byte = 0; byte < windowSize; byte++) { + // prettier-ignore + let s0 = 0, s1 = 0, s2 = 0, s3 = 0; + for (let j = 0; j < W; j++) { + const bit = (byte >>> (W - j - 1)) & 1; + if (!bit) + continue; + const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j]; + (s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3); + } + items.push({ s0, s1, s2, s3 }); + } + } + this.t = items; + } + _updateBlock(s0, s1, s2, s3) { + (s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3); + const { W, t, windowSize } = this; + // prettier-ignore + let o0 = 0, o1 = 0, o2 = 0, o3 = 0; + const mask = (1 << W) - 1; // 2**W will kill performance. + let w = 0; + for (const num of [s0, s1, s2, s3]) { + for (let bytePos = 0; bytePos < 4; bytePos++) { + const byte = (num >>> (8 * bytePos)) & 0xff; + for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) { + const bit = (byte >>> (W * bitPos)) & mask; + const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit]; + (o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3); + w += 1; + } + } + } + this.s0 = o0; + this.s1 = o1; + this.s2 = o2; + this.s3 = o3; + } + update(data) { + data = (0, utils_js_1.toBytes)(data); + (0, _assert_js_1.exists)(this); + const b32 = (0, utils_js_1.u32)(data); + const blocks = Math.floor(data.length / BLOCK_SIZE); + const left = data.length % BLOCK_SIZE; + for (let i = 0; i < blocks; i++) { + this._updateBlock(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]); + } + if (left) { + ZEROS16.set(data.subarray(blocks * BLOCK_SIZE)); + this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]); + ZEROS32.fill(0); // clean tmp buffer + } + return this; + } + destroy() { + const { t } = this; + // clean precompute table + for (const elm of t) { + (elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0); + } + } + digestInto(out) { + (0, _assert_js_1.exists)(this); + (0, _assert_js_1.output)(out, this); + this.finished = true; + const { s0, s1, s2, s3 } = this; + const o32 = (0, utils_js_1.u32)(out); + o32[0] = s0; + o32[1] = s1; + o32[2] = s2; + o32[3] = s3; + return out; + } + digest() { + const res = new Uint8Array(BLOCK_SIZE); + this.digestInto(res); + this.destroy(); + return res; + } +} +class Polyval extends GHASH { + constructor(key, expectedLength) { + key = (0, utils_js_1.toBytes)(key); + const ghKey = _toGHASHKey(key.slice()); + super(ghKey, expectedLength); + ghKey.fill(0); + } + update(data) { + data = (0, utils_js_1.toBytes)(data); + (0, _assert_js_1.exists)(this); + const b32 = (0, utils_js_1.u32)(data); + const left = data.length % BLOCK_SIZE; + const blocks = Math.floor(data.length / BLOCK_SIZE); + for (let i = 0; i < blocks; i++) { + this._updateBlock(swapLE(b32[i * 4 + 3]), swapLE(b32[i * 4 + 2]), swapLE(b32[i * 4 + 1]), swapLE(b32[i * 4 + 0])); + } + if (left) { + ZEROS16.set(data.subarray(blocks * BLOCK_SIZE)); + this._updateBlock(swapLE(ZEROS32[3]), swapLE(ZEROS32[2]), swapLE(ZEROS32[1]), swapLE(ZEROS32[0])); + ZEROS32.fill(0); // clean tmp buffer + } + return this; + } + digestInto(out) { + (0, _assert_js_1.exists)(this); + (0, _assert_js_1.output)(out, this); + this.finished = true; + // tmp ugly hack + const { s0, s1, s2, s3 } = this; + const o32 = (0, utils_js_1.u32)(out); + o32[0] = s0; + o32[1] = s1; + o32[2] = s2; + o32[3] = s3; + return out.reverse(); + } +} +function wrapConstructorWithKey(hashCons) { + const hashC = (msg, key) => hashCons(key, msg.length).update((0, utils_js_1.toBytes)(msg)).digest(); + const tmp = hashCons(new Uint8Array(16), 0); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (key, expectedLength) => hashCons(key, expectedLength); + return hashC; +} +exports.ghash = wrapConstructorWithKey((key, expectedLength) => new GHASH(key, expectedLength)); +exports.polyval = wrapConstructorWithKey((key, expectedLength) => new Polyval(key, expectedLength)); +//# sourceMappingURL=_polyval.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_polyval.js.map b/node_modules/@noble/ciphers/_polyval.js.map new file mode 100644 index 0000000..0d29301 --- /dev/null +++ b/node_modules/@noble/ciphers/_polyval.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_polyval.js","sourceRoot":"","sources":["src/_polyval.ts"],"names":[],"mappings":";;;AAAA,yCAAmE;AACnE,6CAAqF;AAErF,gFAAgF;AAChF,kEAAkE;AAClE,oDAAoD;AACpD,gFAAgF;AAEhF,oDAAoD;AACpD,oDAAoD;AAEpD,MAAM,UAAU,GAAG,EAAE,CAAC;AACtB,gBAAgB;AAChB,2BAA2B;AAC3B,MAAM,OAAO,GAAG,eAAe,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;AACnD,MAAM,OAAO,GAAG,IAAA,cAAG,EAAC,OAAO,CAAC,CAAC;AAC7B,MAAM,IAAI,GAAG,IAAI,CAAC,CAAC,iBAAiB;AAEpC,iBAAiB;AACjB,4DAA4D;AAC5D,4GAA4G;AAC5G,MAAM,IAAI,GAAG,CAAC,EAAU,EAAE,E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EAAE,cAAc,CAAC,CAAC;IACtF,OAAO,KAAK,CAAC;AACf,CAAC;AAEY,QAAA,KAAK,GAAG,sBAAsB,CACzC,CAAC,GAAG,EAAE,cAAc,EAAE,EAAE,CAAC,IAAI,KAAK,CAAC,GAAG,EAAE,cAAc,CAAC,CACxD,CAAC;AACW,QAAA,OAAO,GAAG,sBAAsB,CAC3C,CAAC,GAAG,EAAE,cAAc,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,GAAG,EAAE,cAAc,CAAC,CAC1D,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/aes.d.ts b/node_modules/@noble/ciphers/aes.d.ts new file mode 100644 index 0000000..521cd9d --- /dev/null +++ b/node_modules/@noble/ciphers/aes.d.ts @@ -0,0 +1,86 @@ +import { Cipher, CipherWithOutput } from './utils.js'; +export declare function expandKeyLE(key: Uint8Array): Uint32Array; +export declare function expandKeyDecLE(key: Uint8Array): Uint32Array; +declare function encrypt(xk: Uint32Array, s0: number, s1: number, s2: number, s3: number): { + s0: number; + s1: number; + s2: number; + s3: number; +}; +declare function decrypt(xk: Uint32Array, s0: number, s1: number, s2: number, s3: number): { + s0: number; + s1: number; + s2: number; + s3: number; +}; +declare function ctrCounter(xk: Uint32Array, nonce: Uint8Array, src: Uint8Array, dst?: Uint8Array): Uint8Array; +declare function ctr32(xk: Uint32Array, isLE: boolean, nonce: Uint8Array, src: Uint8Array, dst?: Uint8Array): Uint8Array; +/** + * CTR: counter mode. Creates stream cipher. + * Requires good IV. Parallelizable. OK, but no MAC. + */ +export declare const ctr: ((key: Uint8Array, nonce: Uint8Array) => CipherWithOutput) & { + blockSize: number; + nonceLength: number; +}; +export type BlockOpts = { + disablePadding?: boolean; +}; +/** + * ECB: Electronic CodeBook. Simple deterministic replacement. + * Dangerous: always map x to y. See [AES Penguin](https://words.filippo.io/the-ecb-penguin/). + */ +export declare const ecb: ((key: Uint8Array, opts?: BlockOpts) => CipherWithOutput) & { + blockSize: number; +}; +/** + * CBC: Cipher-Block-Chaining. Key is previous round’s block. + * Fragile: needs proper padding. Unauthenticated: needs MAC. + */ +export declare const cbc: ((key: Uint8Array, iv: Uint8Array, opts?: BlockOpts) => CipherWithOutput) & { + blockSize: number; + nonceLength: number; +}; +/** + * CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output. + * Unauthenticated: needs MAC. + */ +export declare const cfb: ((key: Uint8Array, iv: Uint8Array) => CipherWithOutput) & { + blockSize: number; + nonceLength: number; +}; +/** + * GCM: Galois/Counter Mode. + * Good, modern version of CTR, parallel, with MAC. + * Be careful: MACs can be forged. + */ +export declare const gcm: ((key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => Cipher) & { + blockSize: number; + nonceLength: number; + tagLength: number; +}; +/** + * AES-GCM-SIV: classic AES-GCM with nonce-misuse resistance. + * Guarantees that, when a nonce is repeated, the only security loss is that identical + * plaintexts will produce identical ciphertexts. + * RFC 8452, https://datatracker.ietf.org/doc/html/rfc8452 + */ +export declare const siv: ((key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => Cipher) & { + blockSize: number; + nonceLength: number; + tagLength: number; +}; +declare function encryptBlock(xk: Uint32Array, block: Uint8Array): Uint8Array; +declare function decryptBlock(xk: Uint32Array, block: Uint8Array): Uint8Array; +export declare const unsafe: { + expandKeyLE: typeof expandKeyLE; + expandKeyDecLE: typeof expandKeyDecLE; + encrypt: typeof encrypt; + decrypt: typeof decrypt; + encryptBlock: typeof encryptBlock; + decryptBlock: typeof decryptBlock; + ctrCounter: typeof ctrCounter; + ctr32: typeof ctr32; +}; +export {}; +//# sourceMappingURL=aes.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/aes.d.ts.map b/node_modules/@noble/ciphers/aes.d.ts.map new file mode 100644 index 0000000..db1b217 --- /dev/null +++ b/node_modules/@noble/ciphers/aes.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"aes.d.ts","sourceRoot":"","sources":["src/aes.ts"],"names":[],"mappings":"AACA,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AC;AAqBF;;;;GAIG;AACH,eAAO,MAAM,GAAG,SAEI,UAAU,SAAS,UAAU,QAAQ,UAAU,KAAG,MAAM;;;;CAyD3E,CAAC;AAOF;;;;;GAKG;AACH,eAAO,MAAM,GAAG,SAEI,UAAU,SAAS,UAAU,QAAQ,UAAU,KAAG,MAAM;;;;CAqF3E,CAAC;AAUF,iBAAS,YAAY,CAAC,EAAE,EAAE,WAAW,EAAE,KAAK,EAAE,UAAU,cAOvD;AAED,iBAAS,YAAY,CAAC,EAAE,EAAE,WAAW,EAAE,KAAK,EAAE,UAAU,cAOvD;AAID,eAAO,MAAM,MAAM;;;;;;;;;CASlB,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/aes.js b/node_modules/@noble/ciphers/aes.js new file mode 100644 index 0000000..f0a4b65 --- /dev/null +++ b/node_modules/@noble/ciphers/aes.js @@ -0,0 +1,675 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.unsafe = exports.siv = exports.gcm = exports.cfb = exports.cbc = exports.ecb = exports.ctr = exports.expandKeyDecLE = exports.expandKeyLE = void 0; +// prettier-ignore +const utils_js_1 = require("./utils.js"); +const _polyval_js_1 = require("./_polyval.js"); +const _assert_js_1 = require("./_assert.js"); +/* +AES (Advanced Encryption Standard) aka Rijndael block cipher. + +Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round: +1. **S-box**, table substitution +2. **Shift rows**, cyclic shift left of all rows of data array +3. **Mix columns**, multiplying every column by fixed polynomial +4. **Add round key**, round_key xor i-th column of array + +Resources: +- FIPS-197 https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf +- Original proposal: https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf +*/ +const BLOCK_SIZE = 16; +const BLOCK_SIZE32 = 4; +const EMPTY_BLOCK = new Uint8Array(BLOCK_SIZE); +const POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8 +// TODO: remove multiplication, binary ops only +function mul2(n) { + return (n << 1) ^ (POLY & -(n >> 7)); +} +function mul(a, b) { + let res = 0; + for (; b > 0; b >>= 1) { + // Montgomery ladder + res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time). + a = mul2(a); // a = 2*a + } + return res; +} +// AES S-box is generated using finite field inversion, +// an affine transform, and xor of a constant 0x63. +const sbox = /* @__PURE__ */ (() => { + let t = new Uint8Array(256); + for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x)) + t[i] = x; + const box = new Uint8Array(256); + box[0] = 0x63; // first elm + for (let i = 0; i < 255; i++) { + let x = t[255 - i]; + x |= x << 8; + box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff; + } + return box; +})(); +// Inverted S-box +const invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j)); +// Rotate u32 by 8 +const rotr32_8 = (n) => (n << 24) | (n >>> 8); +const rotl32_8 = (n) => (n << 8) | (n >>> 24); +// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes: +// - LE instead of BE +// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23; +// so index is u16, instead of u8. This speeds up things, unexpectedly +function genTtable(sbox, fn) { + if (sbox.length !== 256) + throw new Error('Wrong sbox length'); + const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j])); + const T1 = T0.map(rotl32_8); + const T2 = T1.map(rotl32_8); + const T3 = T2.map(rotl32_8); + const T01 = new Uint32Array(256 * 256); + const T23 = new Uint32Array(256 * 256); + const sbox2 = new Uint16Array(256 * 256); + for (let i = 0; i < 256; i++) { + for (let j = 0; j < 256; j++) { + const idx = i * 256 + j; + T01[idx] = T0[i] ^ T1[j]; + T23[idx] = T2[i] ^ T3[j]; + sbox2[idx] = (sbox[i] << 8) | sbox[j]; + } + } + return { sbox, sbox2, T0, T1, T2, T3, T01, T23 }; +} +const tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2)); +const tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14)); +const xPowers = /* @__PURE__ */ (() => { + const p = new Uint8Array(16); + for (let i = 0, x = 1; i < 16; i++, x = mul2(x)) + p[i] = x; + return p; +})(); +function expandKeyLE(key) { + (0, _assert_js_1.bytes)(key); + const len = key.length; + if (![16, 24, 32].includes(len)) + throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`); + const { sbox2 } = tableEncoding; + const k32 = (0, utils_js_1.u32)(key); + const Nk = k32.length; + const subByte = (n) => applySbox(sbox2, n, n, n, n); + const xk = new Uint32Array(len + 28); // expanded key + xk.set(k32); + // 4.3.1 Key expansion + for (let i = Nk; i < xk.length; i++) { + let t = xk[i - 1]; + if (i % Nk === 0) + t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1]; + else if (Nk > 6 && i % Nk === 4) + t = subByte(t); + xk[i] = xk[i - Nk] ^ t; + } + return xk; +} +exports.expandKeyLE = expandKeyLE; +function expandKeyDecLE(key) { + const encKey = expandKeyLE(key); + const xk = encKey.slice(); + const Nk = encKey.length; + const { sbox2 } = tableEncoding; + const { T0, T1, T2, T3 } = tableDecoding; + // Inverse key by chunks of 4 (rounds) + for (let i = 0; i < Nk; i += 4) { + for (let j = 0; j < 4; j++) + xk[i + j] = encKey[Nk - i - 4 + j]; + } + encKey.fill(0); + // apply InvMixColumn except first & last round + for (let i = 4; i < Nk - 4; i++) { + const x = xk[i]; + const w = applySbox(sbox2, x, x, x, x); + xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24]; + } + return xk; +} +exports.expandKeyDecLE = expandKeyDecLE; +// Apply tables +function apply0123(T01, T23, s0, s1, s2, s3) { + return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^ + T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]); +} +function applySbox(sbox2, s0, s1, s2, s3) { + return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] | + (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16)); +} +function encrypt(xk, s0, s1, s2, s3) { + const { sbox2, T01, T23 } = tableEncoding; + let k = 0; + (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]); + const rounds = xk.length / 4 - 2; + for (let i = 0; i < rounds; i++) { + const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3); + const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0); + const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1); + const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2); + (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3); + } + // last round (without mixcolumns, so using SBOX2 table) + const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3); + const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0); + const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1); + const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; +} +function decrypt(xk, s0, s1, s2, s3) { + const { sbox2, T01, T23 } = tableDecoding; + let k = 0; + (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]); + const rounds = xk.length / 4 - 2; + for (let i = 0; i < rounds; i++) { + const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1); + const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2); + const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3); + const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0); + (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3); + } + // Last round + const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1); + const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2); + const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3); + const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; +} +function getDst(len, dst) { + if (!dst) + return new Uint8Array(len); + (0, _assert_js_1.bytes)(dst); + if (dst.length < len) + throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`); + return dst; +} +// TODO: investigate merging with ctr32 +function ctrCounter(xk, nonce, src, dst) { + (0, _assert_js_1.bytes)(nonce, BLOCK_SIZE); + (0, _assert_js_1.bytes)(src); + const srcLen = src.length; + dst = getDst(srcLen, dst); + const ctr = nonce; + const c32 = (0, utils_js_1.u32)(ctr); + // Fill block (empty, ctr=0) + let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]); + const src32 = (0, utils_js_1.u32)(src); + const dst32 = (0, utils_js_1.u32)(dst); + // process blocks + for (let i = 0; i + 4 <= src32.length; i += 4) { + dst32[i + 0] = src32[i + 0] ^ s0; + dst32[i + 1] = src32[i + 1] ^ s1; + dst32[i + 2] = src32[i + 2] ^ s2; + dst32[i + 3] = src32[i + 3] ^ s3; + // Full 128 bit counter with wrap around + let carry = 1; + for (let i = ctr.length - 1; i >= 0; i--) { + carry = (carry + (ctr[i] & 0xff)) | 0; + ctr[i] = carry & 0xff; + carry >>>= 8; + } + ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3])); + } + // leftovers (less than block) + // It's possible to handle > u32 fast, but is it worth it? + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + const b32 = new Uint32Array([s0, s1, s2, s3]); + const buf = (0, utils_js_1.u8)(b32); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + } + return dst; +} +// AES CTR with overflowing 32 bit counter +// It's possible to do 32le significantly simpler (and probably faster) by using u32. +// But, we need both, and perf bottleneck is in ghash anyway. +function ctr32(xk, isLE, nonce, src, dst) { + (0, _assert_js_1.bytes)(nonce, BLOCK_SIZE); + (0, _assert_js_1.bytes)(src); + dst = getDst(src.length, dst); + const ctr = nonce; // write new value to nonce, so it can be re-used + const c32 = (0, utils_js_1.u32)(ctr); + const view = (0, utils_js_1.createView)(ctr); + const src32 = (0, utils_js_1.u32)(src); + const dst32 = (0, utils_js_1.u32)(dst); + const ctrPos = isLE ? 0 : 12; + const srcLen = src.length; + // Fill block (empty, ctr=0) + let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value + let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]); + // process blocks + for (let i = 0; i + 4 <= src32.length; i += 4) { + dst32[i + 0] = src32[i + 0] ^ s0; + dst32[i + 1] = src32[i + 1] ^ s1; + dst32[i + 2] = src32[i + 2] ^ s2; + dst32[i + 3] = src32[i + 3] ^ s3; + ctrNum = (ctrNum + 1) >>> 0; // u32 wrap + view.setUint32(ctrPos, ctrNum, isLE); + ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3])); + } + // leftovers (less than a block) + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + const b32 = new Uint32Array([s0, s1, s2, s3]); + const buf = (0, utils_js_1.u8)(b32); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + } + return dst; +} +/** + * CTR: counter mode. Creates stream cipher. + * Requires good IV. Parallelizable. OK, but no MAC. + */ +exports.ctr = (0, utils_js_1.wrapCipher)({ blockSize: 16, nonceLength: 16 }, function ctr(key, nonce) { + (0, _assert_js_1.bytes)(key); + (0, _assert_js_1.bytes)(nonce, BLOCK_SIZE); + function processCtr(buf, dst) { + const xk = expandKeyLE(key); + const n = nonce.slice(); + const out = ctrCounter(xk, n, buf, dst); + xk.fill(0); + n.fill(0); + return out; + } + return { + encrypt: (plaintext, dst) => processCtr(plaintext, dst), + decrypt: (ciphertext, dst) => processCtr(ciphertext, dst), + }; +}); +function validateBlockDecrypt(data) { + (0, _assert_js_1.bytes)(data); + if (data.length % BLOCK_SIZE !== 0) { + throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`); + } +} +function validateBlockEncrypt(plaintext, pcks5, dst) { + let outLen = plaintext.length; + const remaining = outLen % BLOCK_SIZE; + if (!pcks5 && remaining !== 0) + throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding'); + const b = (0, utils_js_1.u32)(plaintext); + if (pcks5) { + let left = BLOCK_SIZE - remaining; + if (!left) + left = BLOCK_SIZE; // if no bytes left, create empty padding block + outLen = outLen + left; + } + const out = getDst(outLen, dst); + const o = (0, utils_js_1.u32)(out); + return { b, o, out }; +} +function validatePCKS(data, pcks5) { + if (!pcks5) + return data; + const len = data.length; + if (!len) + throw new Error(`aes/pcks5: empty ciphertext not allowed`); + const lastByte = data[len - 1]; + if (lastByte <= 0 || lastByte > 16) + throw new Error(`aes/pcks5: wrong padding byte: ${lastByte}`); + const out = data.subarray(0, -lastByte); + for (let i = 0; i < lastByte; i++) + if (data[len - i - 1] !== lastByte) + throw new Error(`aes/pcks5: wrong padding`); + return out; +} +function padPCKS(left) { + const tmp = new Uint8Array(16); + const tmp32 = (0, utils_js_1.u32)(tmp); + tmp.set(left); + const paddingByte = BLOCK_SIZE - left.length; + for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++) + tmp[i] = paddingByte; + return tmp32; +} +/** + * ECB: Electronic CodeBook. Simple deterministic replacement. + * Dangerous: always map x to y. See [AES Penguin](https://words.filippo.io/the-ecb-penguin/). + */ +exports.ecb = (0, utils_js_1.wrapCipher)({ blockSize: 16 }, function ecb(key, opts = {}) { + (0, _assert_js_1.bytes)(key); + const pcks5 = !opts.disablePadding; + return { + encrypt: (plaintext, dst) => { + (0, _assert_js_1.bytes)(plaintext); + const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst); + const xk = expandKeyLE(key); + let i = 0; + for (; i + 4 <= b.length;) { + const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); + } + if (pcks5) { + const tmp32 = padPCKS(plaintext.subarray(i * 4)); + const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); + } + xk.fill(0); + return _out; + }, + decrypt: (ciphertext, dst) => { + validateBlockDecrypt(ciphertext); + const xk = expandKeyDecLE(key); + const out = getDst(ciphertext.length, dst); + const b = (0, utils_js_1.u32)(ciphertext); + const o = (0, utils_js_1.u32)(out); + for (let i = 0; i + 4 <= b.length;) { + const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); + } + xk.fill(0); + return validatePCKS(out, pcks5); + }, + }; +}); +/** + * CBC: Cipher-Block-Chaining. Key is previous round’s block. + * Fragile: needs proper padding. Unauthenticated: needs MAC. + */ +exports.cbc = (0, utils_js_1.wrapCipher)({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv, opts = {}) { + (0, _assert_js_1.bytes)(key); + (0, _assert_js_1.bytes)(iv, 16); + const pcks5 = !opts.disablePadding; + return { + encrypt: (plaintext, dst) => { + const xk = expandKeyLE(key); + const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst); + const n32 = (0, utils_js_1.u32)(iv); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + let i = 0; + for (; i + 4 <= b.length;) { + (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]); + ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3)); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); + } + if (pcks5) { + const tmp32 = padPCKS(plaintext.subarray(i * 4)); + (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]); + ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3)); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); + } + xk.fill(0); + return _out; + }, + decrypt: (ciphertext, dst) => { + validateBlockDecrypt(ciphertext); + const xk = expandKeyDecLE(key); + const n32 = (0, utils_js_1.u32)(iv); + const out = getDst(ciphertext.length, dst); + const b = (0, utils_js_1.u32)(ciphertext); + const o = (0, utils_js_1.u32)(out); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + for (let i = 0; i + 4 <= b.length;) { + // prettier-ignore + const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3; + (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]); + const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3); + (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3); + } + xk.fill(0); + return validatePCKS(out, pcks5); + }, + }; +}); +/** + * CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output. + * Unauthenticated: needs MAC. + */ +exports.cfb = (0, utils_js_1.wrapCipher)({ blockSize: 16, nonceLength: 16 }, function cfb(key, iv) { + (0, _assert_js_1.bytes)(key); + (0, _assert_js_1.bytes)(iv, 16); + function processCfb(src, isEncrypt, dst) { + const xk = expandKeyLE(key); + const srcLen = src.length; + dst = getDst(srcLen, dst); + const src32 = (0, utils_js_1.u32)(src); + const dst32 = (0, utils_js_1.u32)(dst); + const next32 = isEncrypt ? dst32 : src32; + const n32 = (0, utils_js_1.u32)(iv); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + for (let i = 0; i + 4 <= src32.length;) { + const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3); + dst32[i + 0] = src32[i + 0] ^ e0; + dst32[i + 1] = src32[i + 1] ^ e1; + dst32[i + 2] = src32[i + 2] ^ e2; + dst32[i + 3] = src32[i + 3] ^ e3; + (s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]); + } + // leftovers (less than block) + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3)); + const buf = (0, utils_js_1.u8)(new Uint32Array([s0, s1, s2, s3])); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + buf.fill(0); + } + xk.fill(0); + return dst; + } + return { + encrypt: (plaintext, dst) => processCfb(plaintext, true, dst), + decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst), + }; +}); +// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen +function computeTag(fn, isLE, key, data, AAD) { + const h = fn.create(key, data.length + (AAD?.length || 0)); + if (AAD) + h.update(AAD); + h.update(data); + const num = new Uint8Array(16); + const view = (0, utils_js_1.createView)(num); + if (AAD) + (0, utils_js_1.setBigUint64)(view, 0, BigInt(AAD.length * 8), isLE); + (0, utils_js_1.setBigUint64)(view, 8, BigInt(data.length * 8), isLE); + h.update(num); + return h.digest(); +} +/** + * GCM: Galois/Counter Mode. + * Good, modern version of CTR, parallel, with MAC. + * Be careful: MACs can be forged. + */ +exports.gcm = (0, utils_js_1.wrapCipher)({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function gcm(key, nonce, AAD) { + (0, _assert_js_1.bytes)(nonce); + // Nonce can be pretty much anything (even 1 byte). But smaller nonces less secure. + if (nonce.length === 0) + throw new Error('aes/gcm: empty nonce'); + const tagLength = 16; + function _computeTag(authKey, tagMask, data) { + const tag = computeTag(_polyval_js_1.ghash, false, authKey, data, AAD); + for (let i = 0; i < tagMask.length; i++) + tag[i] ^= tagMask[i]; + return tag; + } + function deriveKeys() { + const xk = expandKeyLE(key); + const authKey = EMPTY_BLOCK.slice(); + const counter = EMPTY_BLOCK.slice(); + ctr32(xk, false, counter, counter, authKey); + if (nonce.length === 12) { + counter.set(nonce); + } + else { + // Spec (NIST 800-38d) supports variable size nonce. + // Not supported for now, but can be useful. + const nonceLen = EMPTY_BLOCK.slice(); + const view = (0, utils_js_1.createView)(nonceLen); + (0, utils_js_1.setBigUint64)(view, 8, BigInt(nonce.length * 8), false); + // ghash(nonce || u64be(0) || u64be(nonceLen*8)) + _polyval_js_1.ghash.create(authKey).update(nonce).update(nonceLen).digestInto(counter); + } + const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK); + return { xk, authKey, counter, tagMask }; + } + return { + encrypt: (plaintext) => { + (0, _assert_js_1.bytes)(plaintext); + const { xk, authKey, counter, tagMask } = deriveKeys(); + const out = new Uint8Array(plaintext.length + tagLength); + ctr32(xk, false, counter, plaintext, out); + const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength)); + out.set(tag, plaintext.length); + xk.fill(0); + return out; + }, + decrypt: (ciphertext) => { + (0, _assert_js_1.bytes)(ciphertext); + if (ciphertext.length < tagLength) + throw new Error(`aes/gcm: ciphertext less than tagLen (${tagLength})`); + const { xk, authKey, counter, tagMask } = deriveKeys(); + const data = ciphertext.subarray(0, -tagLength); + const passedTag = ciphertext.subarray(-tagLength); + const tag = _computeTag(authKey, tagMask, data); + if (!(0, utils_js_1.equalBytes)(tag, passedTag)) + throw new Error('aes/gcm: invalid ghash tag'); + const out = ctr32(xk, false, counter, data); + authKey.fill(0); + tagMask.fill(0); + xk.fill(0); + return out; + }, + }; +}); +const limit = (name, min, max) => (value) => { + if (!Number.isSafeInteger(value) || min > value || value > max) + throw new Error(`${name}: invalid value=${value}, must be [${min}..${max}]`); +}; +/** + * AES-GCM-SIV: classic AES-GCM with nonce-misuse resistance. + * Guarantees that, when a nonce is repeated, the only security loss is that identical + * plaintexts will produce identical ciphertexts. + * RFC 8452, https://datatracker.ietf.org/doc/html/rfc8452 + */ +exports.siv = (0, utils_js_1.wrapCipher)({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function siv(key, nonce, AAD) { + const tagLength = 16; + // From RFC 8452: Section 6 + const AAD_LIMIT = limit('AAD', 0, 2 ** 36); + const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36); + const NONCE_LIMIT = limit('nonce', 12, 12); + const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16); + (0, _assert_js_1.bytes)(nonce); + NONCE_LIMIT(nonce.length); + if (AAD) { + (0, _assert_js_1.bytes)(AAD); + AAD_LIMIT(AAD.length); + } + function deriveKeys() { + const len = key.length; + if (len !== 16 && len !== 24 && len !== 32) + throw new Error(`key length must be 16, 24 or 32 bytes, got: ${len} bytes`); + const xk = expandKeyLE(key); + const encKey = new Uint8Array(len); + const authKey = new Uint8Array(16); + const n32 = (0, utils_js_1.u32)(nonce); + // prettier-ignore + let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2]; + let counter = 0; + for (const derivedKey of [authKey, encKey].map(utils_js_1.u32)) { + const d32 = (0, utils_js_1.u32)(derivedKey); + for (let i = 0; i < d32.length; i += 2) { + // aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ... + const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3); + d32[i + 0] = o0; + d32[i + 1] = o1; + s0 = ++counter; // increment counter inside state + } + } + xk.fill(0); + return { authKey, encKey: expandKeyLE(encKey) }; + } + function _computeTag(encKey, authKey, data) { + const tag = computeTag(_polyval_js_1.polyval, true, authKey, data, AAD); + // Compute the expected tag by XORing S_s and the nonce, clearing the + // most significant bit of the last byte and encrypting with the + // message-encryption key. + for (let i = 0; i < 12; i++) + tag[i] ^= nonce[i]; + tag[15] &= 0x7f; // Clear the highest bit + // encrypt tag as block + const t32 = (0, utils_js_1.u32)(tag); + // prettier-ignore + let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3]; + ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3)); + (t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3); + return tag; + } + // actual decrypt/encrypt of message. + function processSiv(encKey, tag, input) { + let block = tag.slice(); + block[15] |= 0x80; // Force highest bit + return ctr32(encKey, true, block, input); + } + return { + encrypt: (plaintext) => { + (0, _assert_js_1.bytes)(plaintext); + PLAIN_LIMIT(plaintext.length); + const { encKey, authKey } = deriveKeys(); + const tag = _computeTag(encKey, authKey, plaintext); + const out = new Uint8Array(plaintext.length + tagLength); + out.set(tag, plaintext.length); + out.set(processSiv(encKey, tag, plaintext)); + encKey.fill(0); + authKey.fill(0); + return out; + }, + decrypt: (ciphertext) => { + (0, _assert_js_1.bytes)(ciphertext); + CIPHER_LIMIT(ciphertext.length); + const tag = ciphertext.subarray(-tagLength); + const { encKey, authKey } = deriveKeys(); + const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength)); + const expectedTag = _computeTag(encKey, authKey, plaintext); + encKey.fill(0); + authKey.fill(0); + if (!(0, utils_js_1.equalBytes)(tag, expectedTag)) + throw new Error('invalid polyval tag'); + return plaintext; + }, + }; +}); +function isBytes32(a) { + return (a != null && + typeof a === 'object' && + (a instanceof Uint32Array || a.constructor.name === 'Uint32Array')); +} +function encryptBlock(xk, block) { + (0, _assert_js_1.bytes)(block, 16); + if (!isBytes32(xk)) + throw new Error('_encryptBlock accepts result of expandKeyLE'); + const b32 = (0, utils_js_1.u32)(block); + let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]); + (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3); + return block; +} +function decryptBlock(xk, block) { + (0, _assert_js_1.bytes)(block, 16); + if (!isBytes32(xk)) + throw new Error('_decryptBlock accepts result of expandKeyLE'); + const b32 = (0, utils_js_1.u32)(block); + let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]); + (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3); + return block; +} +// Highly unsafe private functions for implementing new modes or ciphers based on AES +// Can change at any time, no API guarantees +exports.unsafe = { + expandKeyLE, + expandKeyDecLE, + encrypt, + decrypt, + encryptBlock, + decryptBlock, + ctrCounter, + ctr32, +}; +//# sourceMappingURL=aes.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/aes.js.map b/node_modules/@noble/ciphers/aes.js.map new file mode 100644 index 0000000..323709d --- /dev/null +++ b/node_modules/@noble/ciphers/aes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"aes.js","sourceRoot":"","sources":["src/aes.ts"],"names":[],"mappings":";;;AAAA,kBAAkB;AAClB,yCAGoB;AACpB,+CAA+C;AAC/C,6CAA+C;AAE/C;;;;;;;;;;;;EAYE;AAEF,MAAM,UAAU,GAAG,EAAE,CAAC;AACtB,MAAM,YAAY,GAAG,CAAC,CAAC;AACvB,MAAM,WAAW,GAAG,IAAI,UAAU,CAAC,UAAU,CAAC,CAAC;AAC/C,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,6BAA6B;AAEjD,+CAA+C;AAC/C,SAAS,IAAI,CAAC,CAAS;IACrB,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACvC,CAAC;AAED,SAAS,GAAG,CAAC,CAAS,EAAE,CAAS;IAC/B,IAAI,GAAG,GAAG,CAAC,CAAC;IACZ,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC;QACtB,oBAAoB;QACpB,GAAG,IAAI,CAAC,GAAG,C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AM,EAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IAClB,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAC;IACnF,MAAM,GAAG,GAAG,IAAA,cAAG,EAAC,KAAK,CAAC,CAAC;IACvB,IAAI,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IACrE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC;IAC3D,OAAO,KAAK,CAAC;AACf,CAAC;AAED,qFAAqF;AACrF,4CAA4C;AAC/B,QAAA,MAAM,GAAG;IACpB,WAAW;IACX,cAAc;IACd,OAAO;IACP,OAAO;IACP,YAAY;IACZ,YAAY;IACZ,UAAU;IACV,KAAK;CACN,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/chacha.d.ts b/node_modules/@noble/ciphers/chacha.d.ts new file mode 100644 index 0000000..8c8d892 --- /dev/null +++ b/node_modules/@noble/ciphers/chacha.d.ts @@ -0,0 +1,61 @@ +import { CipherWithOutput, XorStream } from './utils.js'; +/** + * hchacha helper method, used primarily in xchacha, to hash + * key and nonce into key' and nonce'. + * Same as chachaCore, but there doesn't seem to be a way to move the block + * out without 25% performance hit. + */ +export declare function hchacha(s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array): void; +/** + * Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter. + */ +export declare const chacha20orig: XorStream; +/** + * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter. + * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance. + */ +export declare const chacha20: XorStream; +/** + * XChaCha eXtended-nonce ChaCha. 24-byte nonce. + * With 24-byte nonce, it's safe to use fill it with random (CSPRNG). + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha + */ +export declare const xchacha20: XorStream; +/** + * Reduced 8-round chacha, described in original paper. + */ +export declare const chacha8: XorStream; +/** + * Reduced 12-round chacha, described in original paper. + */ +export declare const chacha12: XorStream; +/** + * AEAD algorithm from RFC 8439. + * Salsa20 and chacha (RFC 8439) use poly1305 differently. + * We could have composed them similar to: + * https://github.com/paulmillr/scure-base/blob/b266c73dde977b1dd7ef40ef7a23cc15aab526b3/index.ts#L250 + * But it's hard because of authKey: + * In salsa20, authKey changes position in salsa stream. + * In chacha, authKey can't be computed inside computeTag, it modifies the counter. + */ +export declare const _poly1305_aead: (xorStream: XorStream) => (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => CipherWithOutput; +/** + * ChaCha20-Poly1305 from RFC 8439. + * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance. + */ +export declare const chacha20poly1305: ((key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => CipherWithOutput) & { + blockSize: number; + nonceLength: number; + tagLength: number; +}; +/** + * XChaCha20-Poly1305 extended-nonce chacha. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha + * With 24-byte nonce, it's safe to use fill it with random (CSPRNG). + */ +export declare const xchacha20poly1305: ((key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => CipherWithOutput) & { + blockSize: number; + nonceLength: number; + tagLength: number; +}; +//# sourceMappingURL=chacha.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/chacha.d.ts.map b/node_modules/@noble/ciphers/chacha.d.ts.map new file mode 100644 index 0000000..2a46542 --- /dev/null +++ b/node_modules/@noble/ciphers/chacha.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"chacha.d.ts","sourceRoot":"","sources":["src/chacha.ts"],"names":[],"mappings":"AACA,OAAO,EACO,gBAAgB,EAAE,SAAS,EACxC,MAAM,YAAY,CAAC;AA6EpB;;;;;GAKG;AAEH,wBAAgB,OAAO,CACrB,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,GAAG,EAAE,WAAW,QAoDjE;AACD;;GAEG;AACH,eAAO,MAAM,YAAY,WAIvB,CAAC;AACH;;;GAGG;AACH,eAAO,MAAM,QAAQ,WAInB,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,SAAS,WAKpB,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,OAAO,WAIlB,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,QAAQ,WAInB,CAAC;AAgCH;;;;;;;;GAQG;AACH,eAAO,MAAM,cAAc,cACb,SAAS,WACf,UAAU,SAAS,UAAU,QAAQ,UAAU,KAAG,gBAoCvD,CAAC;AAEJ;;;GAGG;AACH,eAAO,MAAM,gBAAgB,SA1CrB,UAAU,SAAS,UAAU,QAAQ,UAAU,KAAG,gBAAgB;;;;CA6CzE,CAAC;AACF;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,SAnDtB,UAAU,SAAS,UAAU,QAAQ,UAAU,KAAG,gBAAgB;;;;CAsDzE,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/chacha.js b/node_modules/@noble/ciphers/chacha.js new file mode 100644 index 0000000..a10250d --- /dev/null +++ b/node_modules/@noble/ciphers/chacha.js @@ -0,0 +1,323 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.xchacha20poly1305 = exports.chacha20poly1305 = exports._poly1305_aead = exports.chacha12 = exports.chacha8 = exports.xchacha20 = exports.chacha20 = exports.chacha20orig = exports.hchacha = void 0; +// prettier-ignore +const utils_js_1 = require("./utils.js"); +const _poly1305_js_1 = require("./_poly1305.js"); +const _arx_js_1 = require("./_arx.js"); +const _assert_js_1 = require("./_assert.js"); +// ChaCha20 stream cipher was released in 2008. ChaCha aims to increase +// the diffusion per round, but had slightly less cryptanalysis. +// https://cr.yp.to/chacha.html, http://cr.yp.to/chacha/chacha-20080128.pdf +/** + * ChaCha core function. + */ +// prettier-ignore +function chachaCore(s, k, n, out, cnt, rounds = 20) { + let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // "expa" "nd 3" "2-by" "te k" + y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key + y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key + y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Counter Nonce Nonce + // Save state to temporary variables + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; + for (let r = 0; r < rounds; r += 2) { + x00 = (x00 + x04) | 0; + x12 = (0, _arx_js_1.rotl)(x12 ^ x00, 16); + x08 = (x08 + x12) | 0; + x04 = (0, _arx_js_1.rotl)(x04 ^ x08, 12); + x00 = (x00 + x04) | 0; + x12 = (0, _arx_js_1.rotl)(x12 ^ x00, 8); + x08 = (x08 + x12) | 0; + x04 = (0, _arx_js_1.rotl)(x04 ^ x08, 7); + x01 = (x01 + x05) | 0; + x13 = (0, _arx_js_1.rotl)(x13 ^ x01, 16); + x09 = (x09 + x13) | 0; + x05 = (0, _arx_js_1.rotl)(x05 ^ x09, 12); + x01 = (x01 + x05) | 0; + x13 = (0, _arx_js_1.rotl)(x13 ^ x01, 8); + x09 = (x09 + x13) | 0; + x05 = (0, _arx_js_1.rotl)(x05 ^ x09, 7); + x02 = (x02 + x06) | 0; + x14 = (0, _arx_js_1.rotl)(x14 ^ x02, 16); + x10 = (x10 + x14) | 0; + x06 = (0, _arx_js_1.rotl)(x06 ^ x10, 12); + x02 = (x02 + x06) | 0; + x14 = (0, _arx_js_1.rotl)(x14 ^ x02, 8); + x10 = (x10 + x14) | 0; + x06 = (0, _arx_js_1.rotl)(x06 ^ x10, 7); + x03 = (x03 + x07) | 0; + x15 = (0, _arx_js_1.rotl)(x15 ^ x03, 16); + x11 = (x11 + x15) | 0; + x07 = (0, _arx_js_1.rotl)(x07 ^ x11, 12); + x03 = (x03 + x07) | 0; + x15 = (0, _arx_js_1.rotl)(x15 ^ x03, 8); + x11 = (x11 + x15) | 0; + x07 = (0, _arx_js_1.rotl)(x07 ^ x11, 7); + x00 = (x00 + x05) | 0; + x15 = (0, _arx_js_1.rotl)(x15 ^ x00, 16); + x10 = (x10 + x15) | 0; + x05 = (0, _arx_js_1.rotl)(x05 ^ x10, 12); + x00 = (x00 + x05) | 0; + x15 = (0, _arx_js_1.rotl)(x15 ^ x00, 8); + x10 = (x10 + x15) | 0; + x05 = (0, _arx_js_1.rotl)(x05 ^ x10, 7); + x01 = (x01 + x06) | 0; + x12 = (0, _arx_js_1.rotl)(x12 ^ x01, 16); + x11 = (x11 + x12) | 0; + x06 = (0, _arx_js_1.rotl)(x06 ^ x11, 12); + x01 = (x01 + x06) | 0; + x12 = (0, _arx_js_1.rotl)(x12 ^ x01, 8); + x11 = (x11 + x12) | 0; + x06 = (0, _arx_js_1.rotl)(x06 ^ x11, 7); + x02 = (x02 + x07) | 0; + x13 = (0, _arx_js_1.rotl)(x13 ^ x02, 16); + x08 = (x08 + x13) | 0; + x07 = (0, _arx_js_1.rotl)(x07 ^ x08, 12); + x02 = (x02 + x07) | 0; + x13 = (0, _arx_js_1.rotl)(x13 ^ x02, 8); + x08 = (x08 + x13) | 0; + x07 = (0, _arx_js_1.rotl)(x07 ^ x08, 7); + x03 = (x03 + x04) | 0; + x14 = (0, _arx_js_1.rotl)(x14 ^ x03, 16); + x09 = (x09 + x14) | 0; + x04 = (0, _arx_js_1.rotl)(x04 ^ x09, 12); + x03 = (x03 + x04) | 0; + x14 = (0, _arx_js_1.rotl)(x14 ^ x03, 8); + x09 = (x09 + x14) | 0; + x04 = (0, _arx_js_1.rotl)(x04 ^ x09, 7); + } + // Write output + let oi = 0; + out[oi++] = (y00 + x00) | 0; + out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; + out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; + out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; + out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; + out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; + out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; + out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; + out[oi++] = (y15 + x15) | 0; +} +/** + * hchacha helper method, used primarily in xchacha, to hash + * key and nonce into key' and nonce'. + * Same as chachaCore, but there doesn't seem to be a way to move the block + * out without 25% performance hit. + */ +// prettier-ignore +function hchacha(s, k, i, o32) { + let x00 = s[0], x01 = s[1], x02 = s[2], x03 = s[3], x04 = k[0], x05 = k[1], x06 = k[2], x07 = k[3], x08 = k[4], x09 = k[5], x10 = k[6], x11 = k[7], x12 = i[0], x13 = i[1], x14 = i[2], x15 = i[3]; + for (let r = 0; r < 20; r += 2) { + x00 = (x00 + x04) | 0; + x12 = (0, _arx_js_1.rotl)(x12 ^ x00, 16); + x08 = (x08 + x12) | 0; + x04 = (0, _arx_js_1.rotl)(x04 ^ x08, 12); + x00 = (x00 + x04) | 0; + x12 = (0, _arx_js_1.rotl)(x12 ^ x00, 8); + x08 = (x08 + x12) | 0; + x04 = (0, _arx_js_1.rotl)(x04 ^ x08, 7); + x01 = (x01 + x05) | 0; + x13 = (0, _arx_js_1.rotl)(x13 ^ x01, 16); + x09 = (x09 + x13) | 0; + x05 = (0, _arx_js_1.rotl)(x05 ^ x09, 12); + x01 = (x01 + x05) | 0; + x13 = (0, _arx_js_1.rotl)(x13 ^ x01, 8); + x09 = (x09 + x13) | 0; + x05 = (0, _arx_js_1.rotl)(x05 ^ x09, 7); + x02 = (x02 + x06) | 0; + x14 = (0, _arx_js_1.rotl)(x14 ^ x02, 16); + x10 = (x10 + x14) | 0; + x06 = (0, _arx_js_1.rotl)(x06 ^ x10, 12); + x02 = (x02 + x06) | 0; + x14 = (0, _arx_js_1.rotl)(x14 ^ x02, 8); + x10 = (x10 + x14) | 0; + x06 = (0, _arx_js_1.rotl)(x06 ^ x10, 7); + x03 = (x03 + x07) | 0; + x15 = (0, _arx_js_1.rotl)(x15 ^ x03, 16); + x11 = (x11 + x15) | 0; + x07 = (0, _arx_js_1.rotl)(x07 ^ x11, 12); + x03 = (x03 + x07) | 0; + x15 = (0, _arx_js_1.rotl)(x15 ^ x03, 8); + x11 = (x11 + x15) | 0; + x07 = (0, _arx_js_1.rotl)(x07 ^ x11, 7); + x00 = (x00 + x05) | 0; + x15 = (0, _arx_js_1.rotl)(x15 ^ x00, 16); + x10 = (x10 + x15) | 0; + x05 = (0, _arx_js_1.rotl)(x05 ^ x10, 12); + x00 = (x00 + x05) | 0; + x15 = (0, _arx_js_1.rotl)(x15 ^ x00, 8); + x10 = (x10 + x15) | 0; + x05 = (0, _arx_js_1.rotl)(x05 ^ x10, 7); + x01 = (x01 + x06) | 0; + x12 = (0, _arx_js_1.rotl)(x12 ^ x01, 16); + x11 = (x11 + x12) | 0; + x06 = (0, _arx_js_1.rotl)(x06 ^ x11, 12); + x01 = (x01 + x06) | 0; + x12 = (0, _arx_js_1.rotl)(x12 ^ x01, 8); + x11 = (x11 + x12) | 0; + x06 = (0, _arx_js_1.rotl)(x06 ^ x11, 7); + x02 = (x02 + x07) | 0; + x13 = (0, _arx_js_1.rotl)(x13 ^ x02, 16); + x08 = (x08 + x13) | 0; + x07 = (0, _arx_js_1.rotl)(x07 ^ x08, 12); + x02 = (x02 + x07) | 0; + x13 = (0, _arx_js_1.rotl)(x13 ^ x02, 8); + x08 = (x08 + x13) | 0; + x07 = (0, _arx_js_1.rotl)(x07 ^ x08, 7); + x03 = (x03 + x04) | 0; + x14 = (0, _arx_js_1.rotl)(x14 ^ x03, 16); + x09 = (x09 + x14) | 0; + x04 = (0, _arx_js_1.rotl)(x04 ^ x09, 12); + x03 = (x03 + x04) | 0; + x14 = (0, _arx_js_1.rotl)(x14 ^ x03, 8); + x09 = (x09 + x14) | 0; + x04 = (0, _arx_js_1.rotl)(x04 ^ x09, 7); + } + let oi = 0; + o32[oi++] = x00; + o32[oi++] = x01; + o32[oi++] = x02; + o32[oi++] = x03; + o32[oi++] = x12; + o32[oi++] = x13; + o32[oi++] = x14; + o32[oi++] = x15; +} +exports.hchacha = hchacha; +/** + * Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter. + */ +exports.chacha20orig = (0, _arx_js_1.createCipher)(chachaCore, { + counterRight: false, + counterLength: 8, + allowShortKeys: true, +}); +/** + * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter. + * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance. + */ +exports.chacha20 = (0, _arx_js_1.createCipher)(chachaCore, { + counterRight: false, + counterLength: 4, + allowShortKeys: false, +}); +/** + * XChaCha eXtended-nonce ChaCha. 24-byte nonce. + * With 24-byte nonce, it's safe to use fill it with random (CSPRNG). + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha + */ +exports.xchacha20 = (0, _arx_js_1.createCipher)(chachaCore, { + counterRight: false, + counterLength: 8, + extendNonceFn: hchacha, + allowShortKeys: false, +}); +/** + * Reduced 8-round chacha, described in original paper. + */ +exports.chacha8 = (0, _arx_js_1.createCipher)(chachaCore, { + counterRight: false, + counterLength: 4, + rounds: 8, +}); +/** + * Reduced 12-round chacha, described in original paper. + */ +exports.chacha12 = (0, _arx_js_1.createCipher)(chachaCore, { + counterRight: false, + counterLength: 4, + rounds: 12, +}); +const ZEROS16 = /* @__PURE__ */ new Uint8Array(16); +// Pad to digest size with zeros +const updatePadded = (h, msg) => { + h.update(msg); + const left = msg.length % 16; + if (left) + h.update(ZEROS16.subarray(left)); +}; +const ZEROS32 = /* @__PURE__ */ new Uint8Array(32); +function computeTag(fn, key, nonce, data, AAD) { + const authKey = fn(key, nonce, ZEROS32); + const h = _poly1305_js_1.poly1305.create(authKey); + if (AAD) + updatePadded(h, AAD); + updatePadded(h, data); + const num = new Uint8Array(16); + const view = (0, utils_js_1.createView)(num); + (0, utils_js_1.setBigUint64)(view, 0, BigInt(AAD ? AAD.length : 0), true); + (0, utils_js_1.setBigUint64)(view, 8, BigInt(data.length), true); + h.update(num); + const res = h.digest(); + authKey.fill(0); + return res; +} +/** + * AEAD algorithm from RFC 8439. + * Salsa20 and chacha (RFC 8439) use poly1305 differently. + * We could have composed them similar to: + * https://github.com/paulmillr/scure-base/blob/b266c73dde977b1dd7ef40ef7a23cc15aab526b3/index.ts#L250 + * But it's hard because of authKey: + * In salsa20, authKey changes position in salsa stream. + * In chacha, authKey can't be computed inside computeTag, it modifies the counter. + */ +const _poly1305_aead = (xorStream) => (key, nonce, AAD) => { + const tagLength = 16; + (0, _assert_js_1.bytes)(key, 32); + (0, _assert_js_1.bytes)(nonce); + return { + encrypt: (plaintext, output) => { + const plength = plaintext.length; + const clength = plength + tagLength; + if (output) { + (0, _assert_js_1.bytes)(output, clength); + } + else { + output = new Uint8Array(clength); + } + xorStream(key, nonce, plaintext, output, 1); + const tag = computeTag(xorStream, key, nonce, output.subarray(0, -tagLength), AAD); + output.set(tag, plength); // append tag + return output; + }, + decrypt: (ciphertext, output) => { + const clength = ciphertext.length; + const plength = clength - tagLength; + if (clength < tagLength) + throw new Error(`encrypted data must be at least ${tagLength} bytes`); + if (output) { + (0, _assert_js_1.bytes)(output, plength); + } + else { + output = new Uint8Array(plength); + } + const data = ciphertext.subarray(0, -tagLength); + const passedTag = ciphertext.subarray(-tagLength); + const tag = computeTag(xorStream, key, nonce, data, AAD); + if (!(0, utils_js_1.equalBytes)(passedTag, tag)) + throw new Error('invalid tag'); + xorStream(key, nonce, data, output, 1); + return output; + }, + }; +}; +exports._poly1305_aead = _poly1305_aead; +/** + * ChaCha20-Poly1305 from RFC 8439. + * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance. + */ +exports.chacha20poly1305 = (0, utils_js_1.wrapCipher)({ blockSize: 64, nonceLength: 12, tagLength: 16 }, (0, exports._poly1305_aead)(exports.chacha20)); +/** + * XChaCha20-Poly1305 extended-nonce chacha. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha + * With 24-byte nonce, it's safe to use fill it with random (CSPRNG). + */ +exports.xchacha20poly1305 = (0, utils_js_1.wrapCipher)({ blockSize: 64, nonceLength: 24, tagLength: 16 }, (0, exports._poly1305_aead)(exports.xchacha20)); +//# sourceMappingURL=chacha.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/chacha.js.map b/node_modules/@noble/ciphers/chacha.js.map new file mode 100644 index 0000000..4b0a8d2 --- /dev/null +++ b/node_modules/@noble/ciphers/chacha.js.map @@ -0,0 +1 @@ +{"version":3,"file":"chacha.js","sourceRoot":"","sources":["src/chacha.ts"],"names":[],"mappings":";;;AAAA,kBAAkB;AAClB,yCAEoB;AACpB,iDAA0C;AAC1C,uCAA+C;AAC/C,6CAA+C;AAE/C,uEAAuE;AACvE,gEAAgE;AAChE,2EAA2E;AAE3E;;GAEG;AACH,kBAAkB;AAClB,SAAS,UAAU,CACjB,CAAc,EAAE,CAAc,EAAE,CAAc,EAAE,GAAgB,EAAE,GAAW,EAAE,MAAM,GAAG,EAAE;IAE1F,IAAI,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,kCAAkC;IAClF,GA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B,CAAC;KACF,CAAC;AACJ,CAAC,CAAC;AAtCS,QAAA,cAAc,kBAsCvB;AAEJ;;;GAGG;AACU,QAAA,gBAAgB,GAAmB,IAAA,qBAAU,EACxD,EAAE,SAAS,EAAE,EAAE,EAAE,WAAW,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,EACjD,IAAA,sBAAc,EAAC,gBAAQ,CAAC,CACzB,CAAC;AACF;;;;GAIG;AACU,QAAA,iBAAiB,GAAmB,IAAA,qBAAU,EACzD,EAAE,SAAS,EAAE,EAAE,EAAE,WAAW,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,EACjD,IAAA,sBAAc,EAAC,iBAAS,CAAC,CAC1B,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/crypto.d.ts b/node_modules/@noble/ciphers/crypto.d.ts new file mode 100644 index 0000000..0607c79 --- /dev/null +++ b/node_modules/@noble/ciphers/crypto.d.ts @@ -0,0 +1,3 @@ +export declare function randomBytes(bytesLength?: number): Uint8Array; +export declare function getWebcryptoSubtle(): any; +//# sourceMappingURL=crypto.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/crypto.d.ts.map b/node_modules/@noble/ciphers/crypto.d.ts.map new file mode 100644 index 0000000..43f7a2c --- /dev/null +++ b/node_modules/@noble/ciphers/crypto.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["src/crypto.ts"],"names":[],"mappings":"AAKA,wBAAgB,WAAW,CAAC,WAAW,SAAK,GAAG,UAAU,CAIxD;AAED,wBAAgB,kBAAkB,QAGjC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/crypto.js b/node_modules/@noble/ciphers/crypto.js new file mode 100644 index 0000000..e166f22 --- /dev/null +++ b/node_modules/@noble/ciphers/crypto.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getWebcryptoSubtle = exports.randomBytes = void 0; +const cr = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; +function randomBytes(bytesLength = 32) { + if (cr && typeof cr.getRandomValues === 'function') + return cr.getRandomValues(new Uint8Array(bytesLength)); + throw new Error('crypto.getRandomValues must be defined'); +} +exports.randomBytes = randomBytes; +function getWebcryptoSubtle() { + if (cr && typeof cr.subtle === 'object' && cr.subtle != null) + return cr.subtle; + throw new Error('crypto.subtle must be defined'); +} +exports.getWebcryptoSubtle = getWebcryptoSubtle; +//# sourceMappingURL=crypto.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/crypto.js.map b/node_modules/@noble/ciphers/crypto.js.map new file mode 100644 index 0000000..3f1b0c6 --- /dev/null +++ b/node_modules/@noble/ciphers/crypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.js","sourceRoot":"","sources":["src/crypto.ts"],"names":[],"mappings":";;;AAGA,MAAM,EAAE,GAAG,OAAO,UAAU,KAAK,QAAQ,IAAI,QAAQ,IAAI,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC;AAEpG,SAAgB,WAAW,CAAC,WAAW,GAAG,EAAE;IAC1C,IAAI,EAAE,IAAI,OAAO,EAAE,CAAC,eAAe,KAAK,UAAU;QAChD,OAAO,EAAE,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC;IACzD,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAC5D,CAAC;AAJD,kCAIC;AAED,SAAgB,kBAAkB;IAChC,IAAI,EAAE,IAAI,OAAO,EAAE,CAAC,MAAM,KAAK,QAAQ,IAAI,EAAE,CAAC,MAAM,IAAI,IAAI;QAAE,OAAO,EAAE,CAAC,MAAM,CAAC;IAC/E,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;AACnD,CAAC;AAHD,gDAGC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/cryptoNode.d.ts b/node_modules/@noble/ciphers/cryptoNode.d.ts new file mode 100644 index 0000000..42fc5c9 --- /dev/null +++ b/node_modules/@noble/ciphers/cryptoNode.d.ts @@ -0,0 +1,3 @@ +export declare function randomBytes(bytesLength?: number): Uint8Array; +export declare function getWebcryptoSubtle(): any; +//# sourceMappingURL=cryptoNode.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/cryptoNode.d.ts.map b/node_modules/@noble/ciphers/cryptoNode.d.ts.map new file mode 100644 index 0000000..bbedb25 --- /dev/null +++ b/node_modules/@noble/ciphers/cryptoNode.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"cryptoNode.d.ts","sourceRoot":"","sources":["src/cryptoNode.ts"],"names":[],"mappings":"AAOA,wBAAgB,WAAW,CAAC,WAAW,SAAK,GAAG,UAAU,CAIxD;AAED,wBAAgB,kBAAkB,QAGjC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/cryptoNode.js b/node_modules/@noble/ciphers/cryptoNode.js new file mode 100644 index 0000000..ac61d9d --- /dev/null +++ b/node_modules/@noble/ciphers/cryptoNode.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getWebcryptoSubtle = exports.randomBytes = void 0; +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +// The file will throw on node.js 14 and earlier. +// @ts-ignore +const nc = require("node:crypto"); +const cr = nc && typeof nc === 'object' && 'webcrypto' in nc ? nc.webcrypto : undefined; +function randomBytes(bytesLength = 32) { + if (cr && typeof cr.getRandomValues === 'function') + return cr.getRandomValues(new Uint8Array(bytesLength)); + throw new Error('crypto.getRandomValues must be defined'); +} +exports.randomBytes = randomBytes; +function getWebcryptoSubtle() { + if (cr && typeof cr.subtle === 'object' && cr.subtle != null) + return cr.subtle; + throw new Error('crypto.subtle must be defined'); +} +exports.getWebcryptoSubtle = getWebcryptoSubtle; +//# sourceMappingURL=cryptoNode.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/cryptoNode.js.map b/node_modules/@noble/ciphers/cryptoNode.js.map new file mode 100644 index 0000000..ed33671 --- /dev/null +++ b/node_modules/@noble/ciphers/cryptoNode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cryptoNode.js","sourceRoot":"","sources":["src/cryptoNode.ts"],"names":[],"mappings":";;;AAAA,oFAAoF;AACpF,4BAA4B;AAC5B,iDAAiD;AACjD,aAAa;AACb,kCAAkC;AAClC,MAAM,EAAE,GAAG,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,WAAW,IAAI,EAAE,CAAC,CAAC,CAAE,EAAE,CAAC,SAAiB,CAAC,CAAC,CAAC,SAAS,CAAC;AAEjG,SAAgB,WAAW,CAAC,WAAW,GAAG,EAAE;IAC1C,IAAI,EAAE,IAAI,OAAO,EAAE,CAAC,eAAe,KAAK,UAAU;QAChD,OAAO,EAAE,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC;IACzD,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAC5D,CAAC;AAJD,kCAIC;AAED,SAAgB,kBAAkB;IAChC,IAAI,EAAE,IAAI,OAAO,EAAE,CAAC,MAAM,KAAK,QAAQ,IAAI,EAAE,CAAC,MAAM,IAAI,IAAI;QAAE,OAAO,EAAE,CAAC,MAAM,CAAC;IAC/E,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;AACnD,CAAC;AAHD,gDAGC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/_arx.js b/node_modules/@noble/ciphers/esm/_arx.js new file mode 100644 index 0000000..3b0ee7c --- /dev/null +++ b/node_modules/@noble/ciphers/esm/_arx.js @@ -0,0 +1,170 @@ +// Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers. +import { number as anumber, bytes as abytes, bool as abool } from './_assert.js'; +import { checkOpts, u32 } from './utils.js'; +/* +RFC8439 requires multi-step cipher stream, where +authKey starts with counter: 0, actual msg with counter: 1. + +For this, we need a way to re-use nonce / counter: + + const counter = new Uint8Array(4); + chacha(..., counter, ...); // counter is now 1 + chacha(..., counter, ...); // counter is now 2 + +This is complicated: + +- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB +- Original papers don't allow mutating counters +- Counter overflow is undefined [^1] +- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it +- Caveat: Cannot be re-used through all cases: +- * chacha has (counter | nonce) +- * xchacha has (nonce16 | counter | nonce16) +- Idea B: separate nonce / counter and provide separate API for counter re-use +- Caveat: there are different counter sizes depending on an algorithm. +- salsa & chacha also differ in structures of key & sigma: + salsa20: s[0] | k(4) | s[1] | nonce(2) | ctr(2) | s[2] | k(4) | s[3] + chacha: s(4) | k(8) | ctr(1) | nonce(3) + chacha20orig: s(4) | k(8) | ctr(2) | nonce(2) +- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)` +- Caveat: we can't re-use counter array + +xchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal +(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce). + +[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ +[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 +*/ +// We can't make top-level var depend on utils.utf8ToBytes +// because it's not present in all envs. Creating a similar fn here +const _utf8ToBytes = (str) => Uint8Array.from(str.split('').map((c) => c.charCodeAt(0))); +const sigma16 = _utf8ToBytes('expand 16-byte k'); +const sigma32 = _utf8ToBytes('expand 32-byte k'); +const sigma16_32 = u32(sigma16); +const sigma32_32 = u32(sigma32); +export const sigma = sigma32_32.slice(); +export function rotl(a, b) { + return (a << b) | (a >>> (32 - b)); +} +// Is byte array aligned to 4 byte offset (u32)? +function isAligned32(b) { + return b.byteOffset % 4 === 0; +} +// Salsa and Chacha block length is always 512-bit +const BLOCK_LEN = 64; +const BLOCK_LEN32 = 16; +// new Uint32Array([2**32]) // => Uint32Array(1) [ 0 ] +// new Uint32Array([2**32-1]) // => Uint32Array(1) [ 4294967295 ] +const MAX_COUNTER = 2 ** 32 - 1; +const U32_EMPTY = new Uint32Array(); +function runCipher(core, sigma, key, nonce, data, output, counter, rounds) { + const len = data.length; + const block = new Uint8Array(BLOCK_LEN); + const b32 = u32(block); + // Make sure that buffers aligned to 4 bytes + const isAligned = isAligned32(data) && isAligned32(output); + const d32 = isAligned ? u32(data) : U32_EMPTY; + const o32 = isAligned ? u32(output) : U32_EMPTY; + for (let pos = 0; pos < len; counter++) { + core(sigma, key, nonce, b32, counter, rounds); + if (counter >= MAX_COUNTER) + throw new Error('arx: counter overflow'); + const take = Math.min(BLOCK_LEN, len - pos); + // aligned to 4 bytes + if (isAligned && take === BLOCK_LEN) { + const pos32 = pos / 4; + if (pos % 4 !== 0) + throw new Error('arx: invalid block position'); + for (let j = 0, posj; j < BLOCK_LEN32; j++) { + posj = pos32 + j; + o32[posj] = d32[posj] ^ b32[j]; + } + pos += BLOCK_LEN; + continue; + } + for (let j = 0, posj; j < take; j++) { + posj = pos + j; + output[posj] = data[posj] ^ block[j]; + } + pos += take; + } +} +export function createCipher(core, opts) { + const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts); + if (typeof core !== 'function') + throw new Error('core must be a function'); + anumber(counterLength); + anumber(rounds); + abool(counterRight); + abool(allowShortKeys); + return (key, nonce, data, output, counter = 0) => { + abytes(key); + abytes(nonce); + abytes(data); + const len = data.length; + if (!output) + output = new Uint8Array(len); + abytes(output); + anumber(counter); + if (counter < 0 || counter >= MAX_COUNTER) + throw new Error('arx: counter overflow'); + if (output.length < len) + throw new Error(`arx: output (${output.length}) is shorter than data (${len})`); + const toClean = []; + // Key & sigma + // key=16 -> sigma16, k=key|key + // key=32 -> sigma32, k=key + let l = key.length, k, sigma; + if (l === 32) { + k = key.slice(); + toClean.push(k); + sigma = sigma32_32; + } + else if (l === 16 && allowShortKeys) { + k = new Uint8Array(32); + k.set(key); + k.set(key, 16); + sigma = sigma16_32; + toClean.push(k); + } + else { + throw new Error(`arx: invalid 32-byte key, got length=${l}`); + } + // Nonce + // salsa20: 8 (8-byte counter) + // chacha20orig: 8 (8-byte counter) + // chacha20: 12 (4-byte counter) + // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce) + // xchacha20: 24 (16 -> hchacha, 8 -> old nonce) + // Align nonce to 4 bytes + if (!isAligned32(nonce)) { + nonce = nonce.slice(); + toClean.push(nonce); + } + const k32 = u32(k); + // hsalsa & hchacha: handle extended nonce + if (extendNonceFn) { + if (nonce.length !== 24) + throw new Error(`arx: extended nonce must be 24 bytes`); + extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32); + nonce = nonce.subarray(16); + } + // Handle nonce counter + const nonceNcLen = 16 - counterLength; + if (nonceNcLen !== nonce.length) + throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`); + // Pad counter when nonce is 64 bit + if (nonceNcLen !== 12) { + const nc = new Uint8Array(12); + nc.set(nonce, counterRight ? 0 : 12 - nonce.length); + nonce = nc; + toClean.push(nonce); + } + const n32 = u32(nonce); + runCipher(core, sigma, k32, n32, data, output, counter, rounds); + while (toClean.length > 0) + toClean.pop().fill(0); + return output; + }; +} +//# sourceMappingURL=_arx.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/_arx.js.map b/node_modules/@noble/ciphers/esm/_arx.js.map new file mode 100644 index 0000000..f20253e --- /dev/null +++ b/node_modules/@noble/ciphers/esm/_arx.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_arx.js","sourceRoot":"","sources":["../src/_arx.ts"],"names":[],"mappings":"AAAA,iEAAiE;AACjE,OAAO,EAAE,MAAM,IAAI,OAAO,EAAE,KAAK,IAAI,MAAM,EAAE,IAAI,IAAI,KAAK,EAAE,MAAM,cAAc,CAAC;AACjF,OAAO,EAAa,SAAS,EAAE,GAA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,EAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAClD,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/_assert.js b/node_modules/@noble/ciphers/esm/_assert.js new file mode 100644 index 0000000..330fa25 --- /dev/null +++ b/node_modules/@noble/ciphers/esm/_assert.js @@ -0,0 +1,41 @@ +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`positive integer expected, not ${n}`); +} +function bool(b) { + if (typeof b !== 'boolean') + throw new Error(`boolean expected, not ${b}`); +} +export function isBytes(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +function bytes(b, ...lengths) { + if (!isBytes(b)) + throw new Error('Uint8Array expected'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`); +} +function hash(hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') + throw new Error('hash must be wrapped by utils.wrapConstructor'); + number(hash.outputLen); + number(hash.blockLen); +} +function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} +export { number, bool, bytes, hash, exists, output }; +const assert = { number, bool, bytes, hash, exists, output }; +export default assert; +//# sourceMappingURL=_assert.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/_assert.js.map b/node_modules/@noble/ciphers/esm/_assert.js.map new file mode 100644 index 0000000..015be7d --- /dev/null +++ b/node_modules/@noble/ciphers/esm/_assert.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_assert.js","sourceRoot":"","sources":["../src/_assert.ts"],"names":[],"mappings":"AAAA,SAAS,MAAM,CAAC,CAAS;IACvB,IAAI,CAAC,M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AAC;IAC5E,IAAI,aAAa,IAAI,QAAQ,CAAC,QAAQ;QAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;AACnG,CAAC;AAED,SAAS,MAAM,CAAC,GAAQ,EAAE,QAAa;IACrC,KAAK,CAAC,GAAG,CAAC,CAAC;IACX,MAAM,GAAG,GAAG,QAAQ,CAAC,SAAS,CAAC;IAC/B,IAAI,GAAG,CAAC,MAAM,GAAG,GAAG,EAAE,CAAC;QACrB,MAAM,IAAI,KAAK,CAAC,yDAAyD,GAAG,EAAE,CAAC,CAAC;IAClF,CAAC;AACH,CAAC;AAED,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AACrD,MAAM,MAAM,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAC7D,eAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/_micro.js b/node_modules/@noble/ciphers/esm/_micro.js new file mode 100644 index 0000000..fae5252 --- /dev/null +++ b/node_modules/@noble/ciphers/esm/_micro.js @@ -0,0 +1,287 @@ +/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */ +// prettier-ignore +import { createView, setBigUint64, wrapCipher, bytesToHex, concatBytes, equalBytes, hexToNumber, numberToBytesBE, } from './utils.js'; +import { createCipher, rotl } from './_arx.js'; +import { bytes as abytes } from './_assert.js'; +/* +noble-ciphers-micro: more auditable, but slower version of salsa20, chacha & poly1305. +Implements the same algorithms that are present in other files, but without +unrolled loops (https://en.wikipedia.org/wiki/Loop_unrolling). +*/ +function bytesToNumberLE(bytes) { + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); +} +function numberToBytesLE(n, len) { + return numberToBytesBE(n, len).reverse(); +} +function salsaQR(x, a, b, c, d) { + x[b] ^= rotl((x[a] + x[d]) | 0, 7); + x[c] ^= rotl((x[b] + x[a]) | 0, 9); + x[d] ^= rotl((x[c] + x[b]) | 0, 13); + x[a] ^= rotl((x[d] + x[c]) | 0, 18); +} +// prettier-ignore +function chachaQR(x, a, b, c, d) { + x[a] = (x[a] + x[b]) | 0; + x[d] = rotl(x[d] ^ x[a], 16); + x[c] = (x[c] + x[d]) | 0; + x[b] = rotl(x[b] ^ x[c], 12); + x[a] = (x[a] + x[b]) | 0; + x[d] = rotl(x[d] ^ x[a], 8); + x[c] = (x[c] + x[d]) | 0; + x[b] = rotl(x[b] ^ x[c], 7); +} +function salsaRound(x, rounds = 20) { + for (let r = 0; r < rounds; r += 2) { + salsaQR(x, 0, 4, 8, 12); + salsaQR(x, 5, 9, 13, 1); + salsaQR(x, 10, 14, 2, 6); + salsaQR(x, 15, 3, 7, 11); + salsaQR(x, 0, 1, 2, 3); + salsaQR(x, 5, 6, 7, 4); + salsaQR(x, 10, 11, 8, 9); + salsaQR(x, 15, 12, 13, 14); + } +} +function chachaRound(x, rounds = 20) { + for (let r = 0; r < rounds; r += 2) { + chachaQR(x, 0, 4, 8, 12); + chachaQR(x, 1, 5, 9, 13); + chachaQR(x, 2, 6, 10, 14); + chachaQR(x, 3, 7, 11, 15); + chachaQR(x, 0, 5, 10, 15); + chachaQR(x, 1, 6, 11, 12); + chachaQR(x, 2, 7, 8, 13); + chachaQR(x, 3, 4, 9, 14); + } +} +function salsaCore(s, k, n, out, cnt, rounds = 20) { + // prettier-ignore + const y = new Uint32Array([ + s[0], k[0], k[1], k[2], // "expa" Key Key Key + k[3], s[1], n[0], n[1], // Key "nd 3" Nonce Nonce + cnt, 0, s[2], k[4], // Pos. Pos. "2-by" Key + k[5], k[6], k[7], s[3], // Key Key Key "te k" + ]); + const x = y.slice(); + salsaRound(x, rounds); + for (let i = 0; i < 16; i++) + out[i] = (y[i] + x[i]) | 0; +} +// prettier-ignore +export function hsalsa(s, k, i, o32) { + const x = new Uint32Array([ + s[0], k[0], k[1], k[2], + k[3], s[1], i[0], i[1], + i[2], i[3], s[2], k[4], + k[5], k[6], k[7], s[3] + ]); + salsaRound(x, 20); + let oi = 0; + o32[oi++] = x[0]; + o32[oi++] = x[5]; + o32[oi++] = x[10]; + o32[oi++] = x[15]; + o32[oi++] = x[6]; + o32[oi++] = x[7]; + o32[oi++] = x[8]; + o32[oi++] = x[9]; +} +function chachaCore(s, k, n, out, cnt, rounds = 20) { + // prettier-ignore + const y = new Uint32Array([ + s[0], s[1], s[2], s[3], // "expa" "nd 3" "2-by" "te k" + k[0], k[1], k[2], k[3], // Key Key Key Key + k[4], k[5], k[6], k[7], // Key Key Key Key + cnt, n[0], n[1], n[2], // Counter Counter Nonce Nonce + ]); + const x = y.slice(); + chachaRound(x, rounds); + for (let i = 0; i < 16; i++) + out[i] = (y[i] + x[i]) | 0; +} +// prettier-ignore +export function hchacha(s, k, i, o32) { + const x = new Uint32Array([ + s[0], s[1], s[2], s[3], + k[0], k[1], k[2], k[3], + k[4], k[5], k[6], k[7], + i[0], i[1], i[2], i[3], + ]); + chachaRound(x, 20); + let oi = 0; + o32[oi++] = x[0]; + o32[oi++] = x[1]; + o32[oi++] = x[2]; + o32[oi++] = x[3]; + o32[oi++] = x[12]; + o32[oi++] = x[13]; + o32[oi++] = x[14]; + o32[oi++] = x[15]; +} +/** + * salsa20, 12-byte nonce. + */ +export const salsa20 = /* @__PURE__ */ createCipher(salsaCore, { + allowShortKeys: true, + counterRight: true, +}); +/** + * xsalsa20, 24-byte nonce. + */ +export const xsalsa20 = /* @__PURE__ */ createCipher(salsaCore, { + counterRight: true, + extendNonceFn: hsalsa, +}); +/** + * chacha20 non-RFC, original version by djb. 8-byte nonce, 8-byte counter. + */ +export const chacha20orig = /* @__PURE__ */ createCipher(chachaCore, { + allowShortKeys: true, + counterRight: false, + counterLength: 8, +}); +/** + * chacha20 RFC 8439 (IETF / TLS). 12-byte nonce, 4-byte counter. + */ +export const chacha20 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 4, +}); +/** + * xchacha20 eXtended-nonce. https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha + */ +export const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 8, + extendNonceFn: hchacha, +}); +/** + * 8-round chacha from the original paper. + */ +export const chacha8 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 4, + rounds: 8, +}); +/** + * 12-round chacha from the original paper. + */ +export const chacha12 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 4, + rounds: 12, +}); +const POW_2_130_5 = BigInt(2) ** BigInt(130) - BigInt(5); +const POW_2_128_1 = BigInt(2) ** BigInt(16 * 8) - BigInt(1); +const CLAMP_R = BigInt('0x0ffffffc0ffffffc0ffffffc0fffffff'); +const _0 = BigInt(0); +const _1 = BigInt(1); +// Can be speed-up using BigUint64Array, but would be more complicated +export function poly1305(msg, key) { + abytes(msg); + abytes(key); + let acc = _0; + const r = bytesToNumberLE(key.subarray(0, 16)) & CLAMP_R; + const s = bytesToNumberLE(key.subarray(16)); + // Process by 16 byte chunks + for (let i = 0; i < msg.length; i += 16) { + const m = msg.subarray(i, i + 16); + const n = bytesToNumberLE(m) | (_1 << BigInt(8 * m.length)); + acc = ((acc + n) * r) % POW_2_130_5; + } + const res = (acc + s) & POW_2_128_1; + return numberToBytesLE(res, 16); +} +function computeTag(fn, key, nonce, ciphertext, AAD) { + const res = []; + if (AAD) { + res.push(AAD); + const leftover = AAD.length % 16; + if (leftover > 0) + res.push(new Uint8Array(16 - leftover)); + } + res.push(ciphertext); + const leftover = ciphertext.length % 16; + if (leftover > 0) + res.push(new Uint8Array(16 - leftover)); + // Lengths + const num = new Uint8Array(16); + const view = createView(num); + setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true); + setBigUint64(view, 8, BigInt(ciphertext.length), true); + res.push(num); + const authKey = fn(key, nonce, new Uint8Array(32)); + return poly1305(concatBytes(...res), authKey); +} +/** + * xsalsa20-poly1305 eXtended-nonce (24 bytes) salsa. + */ +export const xsalsa20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, function xsalsa20poly1305(key, nonce) { + abytes(key); + abytes(nonce); + return { + encrypt: (plaintext) => { + abytes(plaintext); + const m = concatBytes(new Uint8Array(32), plaintext); + const c = xsalsa20(key, nonce, m); + const authKey = c.subarray(0, 32); + const data = c.subarray(32); + const tag = poly1305(data, authKey); + return concatBytes(tag, data); + }, + decrypt: (ciphertext) => { + abytes(ciphertext); + if (ciphertext.length < 16) + throw new Error('encrypted data must be at least 16 bytes'); + const c = concatBytes(new Uint8Array(16), ciphertext); + const authKey = xsalsa20(key, nonce, new Uint8Array(32)); + const tag = poly1305(c.subarray(32), authKey); + if (!equalBytes(c.subarray(16, 32), tag)) + throw new Error('invalid poly1305 tag'); + return xsalsa20(key, nonce, c).subarray(32); + }, + }; +}); +/** + * Alias to xsalsa20-poly1305 + */ +export function secretbox(key, nonce) { + const xs = xsalsa20poly1305(key, nonce); + return { seal: xs.encrypt, open: xs.decrypt }; +} +export const _poly1305_aead = (fn) => (key, nonce, AAD) => { + const tagLength = 16; + const keyLength = 32; + abytes(key, keyLength); + abytes(nonce); + return { + encrypt: (plaintext) => { + abytes(plaintext); + const res = fn(key, nonce, plaintext, undefined, 1); + const tag = computeTag(fn, key, nonce, res, AAD); + return concatBytes(res, tag); + }, + decrypt: (ciphertext) => { + abytes(ciphertext); + if (ciphertext.length < tagLength) + throw new Error(`encrypted data must be at least ${tagLength} bytes`); + const passedTag = ciphertext.subarray(-tagLength); + const data = ciphertext.subarray(0, -tagLength); + const tag = computeTag(fn, key, nonce, data, AAD); + if (!equalBytes(passedTag, tag)) + throw new Error('invalid poly1305 tag'); + return fn(key, nonce, data, undefined, 1); + }, + }; +}; +/** + * chacha20-poly1305 12-byte-nonce chacha. + */ +export const chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16 }, _poly1305_aead(chacha20)); +/** + * xchacha20-poly1305 eXtended-nonce (24 bytes) chacha. + * With 24-byte nonce, it's safe to use fill it with random (CSPRNG). + */ +export const xchacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, _poly1305_aead(xchacha20)); +//# sourceMappingURL=_micro.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/_micro.js.map b/node_modules/@noble/ciphers/esm/_micro.js.map new file mode 100644 index 0000000..a026036 --- /dev/null +++ b/node_modules/@noble/ciphers/esm/_micro.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_micro.js","sourceRoot":"","sources":["../src/_micro.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,kBAAkB;AAClB,OAAO,EACc,UAAU,EAAE,YAAY,EAAE,UAAU,EACvD,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,WAAW,EAAE,eAAe,GAClE,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EAAE,KAAK,IAAI,MAAM,EAAE,MAAM,cAAc,CAAC;AAE/C;;;;EAIE;AAEF,SAAS,eAAe,CAAC,KAAiB;IACxC,OAAO,WAAW,CAAC,UAAU,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;AACnE,CAAC;AAED,SAAS,eAAe,CAAC,CAAkB,EAAE,GAAW;IACtD,OAAO,eAAe,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,OAAO,EAAE,CAAC;AAC3C,CAAC;AAED,SAAS,OAAO,CAAC,CAAc,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS;IACzE,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CA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M,gBAAgB,GAAG,eAAe,CAAC,UAAU,CACxD,EAAE,SAAS,EAAE,EAAE,EAAE,WAAW,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,EACjD,cAAc,CAAC,QAAQ,CAAC,CACzB,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,eAAe,CAAC,UAAU,CACzD,EAAE,SAAS,EAAE,EAAE,EAAE,WAAW,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,EACjD,cAAc,CAAC,SAAS,CAAC,CAC1B,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/_poly1305.js b/node_modules/@noble/ciphers/esm/_poly1305.js new file mode 100644 index 0000000..883c3a5 --- /dev/null +++ b/node_modules/@noble/ciphers/esm/_poly1305.js @@ -0,0 +1,264 @@ +import { exists as aexists, bytes as abytes, output as aoutput } from './_assert.js'; +import { toBytes } from './utils.js'; +// Poly1305 is a fast and parallel secret-key message-authentication code. +// https://cr.yp.to/mac.html, https://cr.yp.to/mac/poly1305-20050329.pdf +// https://datatracker.ietf.org/doc/html/rfc8439 +// Based on Public Domain poly1305-donna https://github.com/floodyberry/poly1305-donna +const u8to16 = (a, i) => (a[i++] & 0xff) | ((a[i++] & 0xff) << 8); +class Poly1305 { + constructor(key) { + this.blockLen = 16; + this.outputLen = 16; + this.buffer = new Uint8Array(16); + this.r = new Uint16Array(10); + this.h = new Uint16Array(10); + this.pad = new Uint16Array(8); + this.pos = 0; + this.finished = false; + key = toBytes(key); + abytes(key, 32); + const t0 = u8to16(key, 0); + const t1 = u8to16(key, 2); + const t2 = u8to16(key, 4); + const t3 = u8to16(key, 6); + const t4 = u8to16(key, 8); + const t5 = u8to16(key, 10); + const t6 = u8to16(key, 12); + const t7 = u8to16(key, 14); + // https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47 + this.r[0] = t0 & 0x1fff; + this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; + this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; + this.r[5] = (t4 >>> 1) & 0x1ffe; + this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; + this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + this.r[9] = (t7 >>> 5) & 0x007f; + for (let i = 0; i < 8; i++) + this.pad[i] = u8to16(key, 16 + 2 * i); + } + process(data, offset, isLast = false) { + const hibit = isLast ? 0 : 1 << 11; + const { h, r } = this; + const r0 = r[0]; + const r1 = r[1]; + const r2 = r[2]; + const r3 = r[3]; + const r4 = r[4]; + const r5 = r[5]; + const r6 = r[6]; + const r7 = r[7]; + const r8 = r[8]; + const r9 = r[9]; + const t0 = u8to16(data, offset + 0); + const t1 = u8to16(data, offset + 2); + const t2 = u8to16(data, offset + 4); + const t3 = u8to16(data, offset + 6); + const t4 = u8to16(data, offset + 8); + const t5 = u8to16(data, offset + 10); + const t6 = u8to16(data, offset + 12); + const t7 = u8to16(data, offset + 14); + let h0 = h[0] + (t0 & 0x1fff); + let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff); + let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff); + let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff); + let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff); + let h5 = h[5] + ((t4 >>> 1) & 0x1fff); + let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff); + let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff); + let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff); + let h9 = h[9] + ((t7 >>> 5) | hibit); + let c = 0; + let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6); + c = d0 >>> 13; + d0 &= 0x1fff; + d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1); + c += d0 >>> 13; + d0 &= 0x1fff; + let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7); + c = d1 >>> 13; + d1 &= 0x1fff; + d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2); + c += d1 >>> 13; + d1 &= 0x1fff; + let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8); + c = d2 >>> 13; + d2 &= 0x1fff; + d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3); + c += d2 >>> 13; + d2 &= 0x1fff; + let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9); + c = d3 >>> 13; + d3 &= 0x1fff; + d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4); + c += d3 >>> 13; + d3 &= 0x1fff; + let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0; + c = d4 >>> 13; + d4 &= 0x1fff; + d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5); + c += d4 >>> 13; + d4 &= 0x1fff; + let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1; + c = d5 >>> 13; + d5 &= 0x1fff; + d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6); + c += d5 >>> 13; + d5 &= 0x1fff; + let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2; + c = d6 >>> 13; + d6 &= 0x1fff; + d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7); + c += d6 >>> 13; + d6 &= 0x1fff; + let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3; + c = d7 >>> 13; + d7 &= 0x1fff; + d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8); + c += d7 >>> 13; + d7 &= 0x1fff; + let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4; + c = d8 >>> 13; + d8 &= 0x1fff; + d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9); + c += d8 >>> 13; + d8 &= 0x1fff; + let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5; + c = d9 >>> 13; + d9 &= 0x1fff; + d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0; + c += d9 >>> 13; + d9 &= 0x1fff; + c = ((c << 2) + c) | 0; + c = (c + d0) | 0; + d0 = c & 0x1fff; + c = c >>> 13; + d1 += c; + h[0] = d0; + h[1] = d1; + h[2] = d2; + h[3] = d3; + h[4] = d4; + h[5] = d5; + h[6] = d6; + h[7] = d7; + h[8] = d8; + h[9] = d9; + } + finalize() { + const { h, pad } = this; + const g = new Uint16Array(10); + let c = h[1] >>> 13; + h[1] &= 0x1fff; + for (let i = 2; i < 10; i++) { + h[i] += c; + c = h[i] >>> 13; + h[i] &= 0x1fff; + } + h[0] += c * 5; + c = h[0] >>> 13; + h[0] &= 0x1fff; + h[1] += c; + c = h[1] >>> 13; + h[1] &= 0x1fff; + h[2] += c; + g[0] = h[0] + 5; + c = g[0] >>> 13; + g[0] &= 0x1fff; + for (let i = 1; i < 10; i++) { + g[i] = h[i] + c; + c = g[i] >>> 13; + g[i] &= 0x1fff; + } + g[9] -= 1 << 13; + let mask = (c ^ 1) - 1; + for (let i = 0; i < 10; i++) + g[i] &= mask; + mask = ~mask; + for (let i = 0; i < 10; i++) + h[i] = (h[i] & mask) | g[i]; + h[0] = (h[0] | (h[1] << 13)) & 0xffff; + h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff; + h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff; + h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff; + h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff; + h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff; + h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff; + h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff; + let f = h[0] + pad[0]; + h[0] = f & 0xffff; + for (let i = 1; i < 8; i++) { + f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0; + h[i] = f & 0xffff; + } + } + update(data) { + aexists(this); + const { buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input + if (take === blockLen) { + for (; blockLen <= len - pos; pos += blockLen) + this.process(data, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(buffer, 0, false); + this.pos = 0; + } + } + return this; + } + destroy() { + this.h.fill(0); + this.r.fill(0); + this.buffer.fill(0); + this.pad.fill(0); + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + const { buffer, h } = this; + let { pos } = this; + if (pos) { + buffer[pos++] = 1; + // buffer.subarray(pos).fill(0); + for (; pos < 16; pos++) + buffer[pos] = 0; + this.process(buffer, 0, true); + } + this.finalize(); + let opos = 0; + for (let i = 0; i < 8; i++) { + out[opos++] = h[i] >>> 0; + out[opos++] = h[i] >>> 8; + } + return out; + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } +} +export function wrapConstructorWithKey(hashCons) { + const hashC = (msg, key) => hashCons(key).update(toBytes(msg)).digest(); + const tmp = hashCons(new Uint8Array(32)); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (key) => hashCons(key); + return hashC; +} +export const poly1305 = wrapConstructorWithKey((key) => new Poly1305(key)); +//# sourceMappingURL=_poly1305.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/_poly1305.js.map b/node_modules/@noble/ciphers/esm/_poly1305.js.map new file mode 100644 index 0000000..2b4366a --- /dev/null +++ b/node_modules/@noble/ciphers/esm/_poly1305.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_poly1305.js","sourceRoot":"","sources":["../src/_poly1305.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,OAAO,EAAE,KAAK,IAAI,MAAM,EAAE,MAAM,IAAI,OAAO,EAAE,MAAM,cAAc,CAAC;AACrF,OAAO,EAAS,OAAO,EAAQ,MAAM,YAAY,CAAC;AAElD,0EAA0E;AAC1E,wEAAwE;AACxE,gDAAgD;AAEhD,sFAAsF;AACtF,MAAM,MAAM,GAAG,CAAC,CAAa,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AACtF,MAAM,QAAQ;IAUZ,YAAY,GAAU;QATb,aAAQ,GAAG,EAAE,CAAC;QACd,cAAS,GAAG,EAAE,CAAC;QAChB,WAAM,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;QAC5B,MAAC,GAAG,IAAI,WAAW,CAAC,EAAE,CAAC,CAAC;QACxB,MAAC,GAAG,IAAI,WAAW,CAAC,EAAE,CAAC,CAAC;QACxB,QAAG,GAAG,IAAI,WAAW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ACD,MAAM;QACJ,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;QACnC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QACxB,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;QACvC,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,OAAO,GAAG,CAAC;IACb,CAAC;CACF;AAGD,MAAM,UAAU,sBAAsB,CAAoB,QAAiC;IACzF,MAAM,KAAK,GAAG,CAAC,GAAU,EAAE,GAAU,EAAc,EAAE,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;IAClG,MAAM,GAAG,GAAG,QAAQ,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC;IACzC,KAAK,CAAC,SAAS,GAAG,GAAG,CAAC,SAAS,CAAC;IAChC,KAAK,CAAC,QAAQ,GAAG,GAAG,CAAC,QAAQ,CAAC;IAC9B,KAAK,CAAC,MAAM,GAAG,CAAC,GAAU,EAAE,EAAE,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;IAC7C,OAAO,KAAK,CAAC;AACf,CAAC;AAED,MAAM,CAAC,MAAM,QAAQ,GAAG,sBAAsB,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/_polyval.js b/node_modules/@noble/ciphers/esm/_polyval.js new file mode 100644 index 0000000..4c64930 --- /dev/null +++ b/node_modules/@noble/ciphers/esm/_polyval.js @@ -0,0 +1,217 @@ +import { createView, toBytes, u32 } from './utils.js'; +import { bytes as abytes, exists as aexists, output as aoutput } from './_assert.js'; +// GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV. +// Implemented in terms of GHash with conversion function for keys +// GCM GHASH from NIST SP800-38d, SIV from RFC 8452. +// https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf +// GHASH modulo: x^128 + x^7 + x^2 + x + 1 +// POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1 +const BLOCK_SIZE = 16; +// TODO: rewrite +// temporary padding buffer +const ZEROS16 = /* @__PURE__ */ new Uint8Array(16); +const ZEROS32 = u32(ZEROS16); +const POLY = 0xe1; // v = 2*v % POLY +// v = 2*v % POLY +// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x +// We can multiply any number using montgomery ladder and this function (works as double, add is simple xor) +const mul2 = (s0, s1, s2, s3) => { + const hiBit = s3 & 1; + return { + s3: (s2 << 31) | (s3 >>> 1), + s2: (s1 << 31) | (s2 >>> 1), + s1: (s0 << 31) | (s1 >>> 1), + s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly + }; +}; +const swapLE = (n) => (((n >>> 0) & 0xff) << 24) | + (((n >>> 8) & 0xff) << 16) | + (((n >>> 16) & 0xff) << 8) | + ((n >>> 24) & 0xff) | + 0; +/** + * `mulX_POLYVAL(ByteReverse(H))` from spec + * @param k mutated in place + */ +export function _toGHASHKey(k) { + k.reverse(); + const hiBit = k[15] & 1; + // k >>= 1 + let carry = 0; + for (let i = 0; i < k.length; i++) { + const t = k[i]; + k[i] = (t >>> 1) | carry; + carry = (t & 1) << 7; + } + k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000; + return k; +} +const estimateWindow = (bytes) => { + if (bytes > 64 * 1024) + return 8; + if (bytes > 1024) + return 4; + return 2; +}; +class GHASH { + // We select bits per window adaptively based on expectedLength + constructor(key, expectedLength) { + this.blockLen = BLOCK_SIZE; + this.outputLen = BLOCK_SIZE; + this.s0 = 0; + this.s1 = 0; + this.s2 = 0; + this.s3 = 0; + this.finished = false; + key = toBytes(key); + abytes(key, 16); + const kView = createView(key); + let k0 = kView.getUint32(0, false); + let k1 = kView.getUint32(4, false); + let k2 = kView.getUint32(8, false); + let k3 = kView.getUint32(12, false); + // generate table of doubled keys (half of montgomery ladder) + const doubles = []; + for (let i = 0; i < 128; i++) { + doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) }); + ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3)); + } + const W = estimateWindow(expectedLength || 1024); + if (![1, 2, 4, 8].includes(W)) + throw new Error(`ghash: wrong window size=${W}, should be 2, 4 or 8`); + this.W = W; + const bits = 128; // always 128 bits; + const windows = bits / W; + const windowSize = (this.windowSize = 2 ** W); + const items = []; + // Create precompute table for window of W bits + for (let w = 0; w < windows; w++) { + // truth table: 00, 01, 10, 11 + for (let byte = 0; byte < windowSize; byte++) { + // prettier-ignore + let s0 = 0, s1 = 0, s2 = 0, s3 = 0; + for (let j = 0; j < W; j++) { + const bit = (byte >>> (W - j - 1)) & 1; + if (!bit) + continue; + const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j]; + (s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3); + } + items.push({ s0, s1, s2, s3 }); + } + } + this.t = items; + } + _updateBlock(s0, s1, s2, s3) { + (s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3); + const { W, t, windowSize } = this; + // prettier-ignore + let o0 = 0, o1 = 0, o2 = 0, o3 = 0; + const mask = (1 << W) - 1; // 2**W will kill performance. + let w = 0; + for (const num of [s0, s1, s2, s3]) { + for (let bytePos = 0; bytePos < 4; bytePos++) { + const byte = (num >>> (8 * bytePos)) & 0xff; + for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) { + const bit = (byte >>> (W * bitPos)) & mask; + const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit]; + (o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3); + w += 1; + } + } + } + this.s0 = o0; + this.s1 = o1; + this.s2 = o2; + this.s3 = o3; + } + update(data) { + data = toBytes(data); + aexists(this); + const b32 = u32(data); + const blocks = Math.floor(data.length / BLOCK_SIZE); + const left = data.length % BLOCK_SIZE; + for (let i = 0; i < blocks; i++) { + this._updateBlock(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]); + } + if (left) { + ZEROS16.set(data.subarray(blocks * BLOCK_SIZE)); + this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]); + ZEROS32.fill(0); // clean tmp buffer + } + return this; + } + destroy() { + const { t } = this; + // clean precompute table + for (const elm of t) { + (elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0); + } + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + const { s0, s1, s2, s3 } = this; + const o32 = u32(out); + o32[0] = s0; + o32[1] = s1; + o32[2] = s2; + o32[3] = s3; + return out; + } + digest() { + const res = new Uint8Array(BLOCK_SIZE); + this.digestInto(res); + this.destroy(); + return res; + } +} +class Polyval extends GHASH { + constructor(key, expectedLength) { + key = toBytes(key); + const ghKey = _toGHASHKey(key.slice()); + super(ghKey, expectedLength); + ghKey.fill(0); + } + update(data) { + data = toBytes(data); + aexists(this); + const b32 = u32(data); + const left = data.length % BLOCK_SIZE; + const blocks = Math.floor(data.length / BLOCK_SIZE); + for (let i = 0; i < blocks; i++) { + this._updateBlock(swapLE(b32[i * 4 + 3]), swapLE(b32[i * 4 + 2]), swapLE(b32[i * 4 + 1]), swapLE(b32[i * 4 + 0])); + } + if (left) { + ZEROS16.set(data.subarray(blocks * BLOCK_SIZE)); + this._updateBlock(swapLE(ZEROS32[3]), swapLE(ZEROS32[2]), swapLE(ZEROS32[1]), swapLE(ZEROS32[0])); + ZEROS32.fill(0); // clean tmp buffer + } + return this; + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + // tmp ugly hack + const { s0, s1, s2, s3 } = this; + const o32 = u32(out); + o32[0] = s0; + o32[1] = s1; + o32[2] = s2; + o32[3] = s3; + return out.reverse(); + } +} +function wrapConstructorWithKey(hashCons) { + const hashC = (msg, key) => hashCons(key, msg.length).update(toBytes(msg)).digest(); + const tmp = hashCons(new Uint8Array(16), 0); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (key, expectedLength) => hashCons(key, expectedLength); + return hashC; +} +export const ghash = wrapConstructorWithKey((key, expectedLength) => new GHASH(key, expectedLength)); +export const polyval = wrapConstructorWithKey((key, expectedLength) => new Polyval(key, expectedLength)); +//# sourceMappingURL=_polyval.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/_polyval.js.map b/node_modules/@noble/ciphers/esm/_polyval.js.map new file mode 100644 index 0000000..25a52fa --- /dev/null +++ b/node_modules/@noble/ciphers/esm/_polyval.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_polyval.js","sourceRoot":"","sources":["../src/_polyval.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,OAAO,EAAe,GAAG,EAAE,MAAM,YAAY,CAAC;AACnE,OAAO,EAAE,KAAK,IAAI,MAAM,EAAE,MAAM,IAAI,OAAO,EAAE,MAAM,IAAI,OAAO,EAAE,MAAM,cAAc,CAAC;AAErF,gFAAgF;AAChF,kEAAkE;AAClE,oDAAoD;AACpD,gFAAgF;AAEhF,oDAAoD;AACpD,oDAAoD;AAEpD,MAAM,UAAU,GAAG,EAAE,CAAC;AACtB,gBAAgB;AAChB,2BAA2B;AAC3B,MAAM,OAAO,GAAG,eAAe,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;AACnD,MAAM,OAAO,GAAG,GAAG,CAAC,OAAO,CAAC,CAAC;AAC7B,MAAM,IAAI,GAAG,IAAI,CAAC,CAAC,iBAAiB;AAEpC,iBAAiB;AACjB,4DAA4D;AAC5D,4GAA4G;AAC5G,MAAM,IAAI,GAAG,CAAC,EAAU,EAAE,EAAU,EAAE,EAAU,EAAE,E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IAAI,KAAK,CAAC,GAAG,EAAE,cAAc,CAAC,CACxD,CAAC;AACF,MAAM,CAAC,MAAM,OAAO,GAAG,sBAAsB,CAC3C,CAAC,GAAG,EAAE,cAAc,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,GAAG,EAAE,cAAc,CAAC,CAC1D,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/aes.js b/node_modules/@noble/ciphers/esm/aes.js new file mode 100644 index 0000000..1761914 --- /dev/null +++ b/node_modules/@noble/ciphers/esm/aes.js @@ -0,0 +1,670 @@ +// prettier-ignore +import { wrapCipher, createView, setBigUint64, equalBytes, u32, u8, } from './utils.js'; +import { ghash, polyval } from './_polyval.js'; +import { bytes as abytes } from './_assert.js'; +/* +AES (Advanced Encryption Standard) aka Rijndael block cipher. + +Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round: +1. **S-box**, table substitution +2. **Shift rows**, cyclic shift left of all rows of data array +3. **Mix columns**, multiplying every column by fixed polynomial +4. **Add round key**, round_key xor i-th column of array + +Resources: +- FIPS-197 https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf +- Original proposal: https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf +*/ +const BLOCK_SIZE = 16; +const BLOCK_SIZE32 = 4; +const EMPTY_BLOCK = new Uint8Array(BLOCK_SIZE); +const POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8 +// TODO: remove multiplication, binary ops only +function mul2(n) { + return (n << 1) ^ (POLY & -(n >> 7)); +} +function mul(a, b) { + let res = 0; + for (; b > 0; b >>= 1) { + // Montgomery ladder + res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time). + a = mul2(a); // a = 2*a + } + return res; +} +// AES S-box is generated using finite field inversion, +// an affine transform, and xor of a constant 0x63. +const sbox = /* @__PURE__ */ (() => { + let t = new Uint8Array(256); + for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x)) + t[i] = x; + const box = new Uint8Array(256); + box[0] = 0x63; // first elm + for (let i = 0; i < 255; i++) { + let x = t[255 - i]; + x |= x << 8; + box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff; + } + return box; +})(); +// Inverted S-box +const invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j)); +// Rotate u32 by 8 +const rotr32_8 = (n) => (n << 24) | (n >>> 8); +const rotl32_8 = (n) => (n << 8) | (n >>> 24); +// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes: +// - LE instead of BE +// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23; +// so index is u16, instead of u8. This speeds up things, unexpectedly +function genTtable(sbox, fn) { + if (sbox.length !== 256) + throw new Error('Wrong sbox length'); + const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j])); + const T1 = T0.map(rotl32_8); + const T2 = T1.map(rotl32_8); + const T3 = T2.map(rotl32_8); + const T01 = new Uint32Array(256 * 256); + const T23 = new Uint32Array(256 * 256); + const sbox2 = new Uint16Array(256 * 256); + for (let i = 0; i < 256; i++) { + for (let j = 0; j < 256; j++) { + const idx = i * 256 + j; + T01[idx] = T0[i] ^ T1[j]; + T23[idx] = T2[i] ^ T3[j]; + sbox2[idx] = (sbox[i] << 8) | sbox[j]; + } + } + return { sbox, sbox2, T0, T1, T2, T3, T01, T23 }; +} +const tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2)); +const tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14)); +const xPowers = /* @__PURE__ */ (() => { + const p = new Uint8Array(16); + for (let i = 0, x = 1; i < 16; i++, x = mul2(x)) + p[i] = x; + return p; +})(); +export function expandKeyLE(key) { + abytes(key); + const len = key.length; + if (![16, 24, 32].includes(len)) + throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`); + const { sbox2 } = tableEncoding; + const k32 = u32(key); + const Nk = k32.length; + const subByte = (n) => applySbox(sbox2, n, n, n, n); + const xk = new Uint32Array(len + 28); // expanded key + xk.set(k32); + // 4.3.1 Key expansion + for (let i = Nk; i < xk.length; i++) { + let t = xk[i - 1]; + if (i % Nk === 0) + t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1]; + else if (Nk > 6 && i % Nk === 4) + t = subByte(t); + xk[i] = xk[i - Nk] ^ t; + } + return xk; +} +export function expandKeyDecLE(key) { + const encKey = expandKeyLE(key); + const xk = encKey.slice(); + const Nk = encKey.length; + const { sbox2 } = tableEncoding; + const { T0, T1, T2, T3 } = tableDecoding; + // Inverse key by chunks of 4 (rounds) + for (let i = 0; i < Nk; i += 4) { + for (let j = 0; j < 4; j++) + xk[i + j] = encKey[Nk - i - 4 + j]; + } + encKey.fill(0); + // apply InvMixColumn except first & last round + for (let i = 4; i < Nk - 4; i++) { + const x = xk[i]; + const w = applySbox(sbox2, x, x, x, x); + xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24]; + } + return xk; +} +// Apply tables +function apply0123(T01, T23, s0, s1, s2, s3) { + return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^ + T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]); +} +function applySbox(sbox2, s0, s1, s2, s3) { + return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] | + (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16)); +} +function encrypt(xk, s0, s1, s2, s3) { + const { sbox2, T01, T23 } = tableEncoding; + let k = 0; + (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]); + const rounds = xk.length / 4 - 2; + for (let i = 0; i < rounds; i++) { + const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3); + const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0); + const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1); + const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2); + (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3); + } + // last round (without mixcolumns, so using SBOX2 table) + const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3); + const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0); + const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1); + const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; +} +function decrypt(xk, s0, s1, s2, s3) { + const { sbox2, T01, T23 } = tableDecoding; + let k = 0; + (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]); + const rounds = xk.length / 4 - 2; + for (let i = 0; i < rounds; i++) { + const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1); + const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2); + const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3); + const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0); + (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3); + } + // Last round + const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1); + const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2); + const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3); + const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; +} +function getDst(len, dst) { + if (!dst) + return new Uint8Array(len); + abytes(dst); + if (dst.length < len) + throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`); + return dst; +} +// TODO: investigate merging with ctr32 +function ctrCounter(xk, nonce, src, dst) { + abytes(nonce, BLOCK_SIZE); + abytes(src); + const srcLen = src.length; + dst = getDst(srcLen, dst); + const ctr = nonce; + const c32 = u32(ctr); + // Fill block (empty, ctr=0) + let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]); + const src32 = u32(src); + const dst32 = u32(dst); + // process blocks + for (let i = 0; i + 4 <= src32.length; i += 4) { + dst32[i + 0] = src32[i + 0] ^ s0; + dst32[i + 1] = src32[i + 1] ^ s1; + dst32[i + 2] = src32[i + 2] ^ s2; + dst32[i + 3] = src32[i + 3] ^ s3; + // Full 128 bit counter with wrap around + let carry = 1; + for (let i = ctr.length - 1; i >= 0; i--) { + carry = (carry + (ctr[i] & 0xff)) | 0; + ctr[i] = carry & 0xff; + carry >>>= 8; + } + ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3])); + } + // leftovers (less than block) + // It's possible to handle > u32 fast, but is it worth it? + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + const b32 = new Uint32Array([s0, s1, s2, s3]); + const buf = u8(b32); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + } + return dst; +} +// AES CTR with overflowing 32 bit counter +// It's possible to do 32le significantly simpler (and probably faster) by using u32. +// But, we need both, and perf bottleneck is in ghash anyway. +function ctr32(xk, isLE, nonce, src, dst) { + abytes(nonce, BLOCK_SIZE); + abytes(src); + dst = getDst(src.length, dst); + const ctr = nonce; // write new value to nonce, so it can be re-used + const c32 = u32(ctr); + const view = createView(ctr); + const src32 = u32(src); + const dst32 = u32(dst); + const ctrPos = isLE ? 0 : 12; + const srcLen = src.length; + // Fill block (empty, ctr=0) + let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value + let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]); + // process blocks + for (let i = 0; i + 4 <= src32.length; i += 4) { + dst32[i + 0] = src32[i + 0] ^ s0; + dst32[i + 1] = src32[i + 1] ^ s1; + dst32[i + 2] = src32[i + 2] ^ s2; + dst32[i + 3] = src32[i + 3] ^ s3; + ctrNum = (ctrNum + 1) >>> 0; // u32 wrap + view.setUint32(ctrPos, ctrNum, isLE); + ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3])); + } + // leftovers (less than a block) + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + const b32 = new Uint32Array([s0, s1, s2, s3]); + const buf = u8(b32); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + } + return dst; +} +/** + * CTR: counter mode. Creates stream cipher. + * Requires good IV. Parallelizable. OK, but no MAC. + */ +export const ctr = wrapCipher({ blockSize: 16, nonceLength: 16 }, function ctr(key, nonce) { + abytes(key); + abytes(nonce, BLOCK_SIZE); + function processCtr(buf, dst) { + const xk = expandKeyLE(key); + const n = nonce.slice(); + const out = ctrCounter(xk, n, buf, dst); + xk.fill(0); + n.fill(0); + return out; + } + return { + encrypt: (plaintext, dst) => processCtr(plaintext, dst), + decrypt: (ciphertext, dst) => processCtr(ciphertext, dst), + }; +}); +function validateBlockDecrypt(data) { + abytes(data); + if (data.length % BLOCK_SIZE !== 0) { + throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`); + } +} +function validateBlockEncrypt(plaintext, pcks5, dst) { + let outLen = plaintext.length; + const remaining = outLen % BLOCK_SIZE; + if (!pcks5 && remaining !== 0) + throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding'); + const b = u32(plaintext); + if (pcks5) { + let left = BLOCK_SIZE - remaining; + if (!left) + left = BLOCK_SIZE; // if no bytes left, create empty padding block + outLen = outLen + left; + } + const out = getDst(outLen, dst); + const o = u32(out); + return { b, o, out }; +} +function validatePCKS(data, pcks5) { + if (!pcks5) + return data; + const len = data.length; + if (!len) + throw new Error(`aes/pcks5: empty ciphertext not allowed`); + const lastByte = data[len - 1]; + if (lastByte <= 0 || lastByte > 16) + throw new Error(`aes/pcks5: wrong padding byte: ${lastByte}`); + const out = data.subarray(0, -lastByte); + for (let i = 0; i < lastByte; i++) + if (data[len - i - 1] !== lastByte) + throw new Error(`aes/pcks5: wrong padding`); + return out; +} +function padPCKS(left) { + const tmp = new Uint8Array(16); + const tmp32 = u32(tmp); + tmp.set(left); + const paddingByte = BLOCK_SIZE - left.length; + for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++) + tmp[i] = paddingByte; + return tmp32; +} +/** + * ECB: Electronic CodeBook. Simple deterministic replacement. + * Dangerous: always map x to y. See [AES Penguin](https://words.filippo.io/the-ecb-penguin/). + */ +export const ecb = wrapCipher({ blockSize: 16 }, function ecb(key, opts = {}) { + abytes(key); + const pcks5 = !opts.disablePadding; + return { + encrypt: (plaintext, dst) => { + abytes(plaintext); + const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst); + const xk = expandKeyLE(key); + let i = 0; + for (; i + 4 <= b.length;) { + const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); + } + if (pcks5) { + const tmp32 = padPCKS(plaintext.subarray(i * 4)); + const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); + } + xk.fill(0); + return _out; + }, + decrypt: (ciphertext, dst) => { + validateBlockDecrypt(ciphertext); + const xk = expandKeyDecLE(key); + const out = getDst(ciphertext.length, dst); + const b = u32(ciphertext); + const o = u32(out); + for (let i = 0; i + 4 <= b.length;) { + const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); + } + xk.fill(0); + return validatePCKS(out, pcks5); + }, + }; +}); +/** + * CBC: Cipher-Block-Chaining. Key is previous round’s block. + * Fragile: needs proper padding. Unauthenticated: needs MAC. + */ +export const cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv, opts = {}) { + abytes(key); + abytes(iv, 16); + const pcks5 = !opts.disablePadding; + return { + encrypt: (plaintext, dst) => { + const xk = expandKeyLE(key); + const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst); + const n32 = u32(iv); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + let i = 0; + for (; i + 4 <= b.length;) { + (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]); + ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3)); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); + } + if (pcks5) { + const tmp32 = padPCKS(plaintext.subarray(i * 4)); + (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]); + ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3)); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); + } + xk.fill(0); + return _out; + }, + decrypt: (ciphertext, dst) => { + validateBlockDecrypt(ciphertext); + const xk = expandKeyDecLE(key); + const n32 = u32(iv); + const out = getDst(ciphertext.length, dst); + const b = u32(ciphertext); + const o = u32(out); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + for (let i = 0; i + 4 <= b.length;) { + // prettier-ignore + const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3; + (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]); + const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3); + (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3); + } + xk.fill(0); + return validatePCKS(out, pcks5); + }, + }; +}); +/** + * CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output. + * Unauthenticated: needs MAC. + */ +export const cfb = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cfb(key, iv) { + abytes(key); + abytes(iv, 16); + function processCfb(src, isEncrypt, dst) { + const xk = expandKeyLE(key); + const srcLen = src.length; + dst = getDst(srcLen, dst); + const src32 = u32(src); + const dst32 = u32(dst); + const next32 = isEncrypt ? dst32 : src32; + const n32 = u32(iv); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + for (let i = 0; i + 4 <= src32.length;) { + const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3); + dst32[i + 0] = src32[i + 0] ^ e0; + dst32[i + 1] = src32[i + 1] ^ e1; + dst32[i + 2] = src32[i + 2] ^ e2; + dst32[i + 3] = src32[i + 3] ^ e3; + (s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]); + } + // leftovers (less than block) + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3)); + const buf = u8(new Uint32Array([s0, s1, s2, s3])); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + buf.fill(0); + } + xk.fill(0); + return dst; + } + return { + encrypt: (plaintext, dst) => processCfb(plaintext, true, dst), + decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst), + }; +}); +// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen +function computeTag(fn, isLE, key, data, AAD) { + const h = fn.create(key, data.length + (AAD?.length || 0)); + if (AAD) + h.update(AAD); + h.update(data); + const num = new Uint8Array(16); + const view = createView(num); + if (AAD) + setBigUint64(view, 0, BigInt(AAD.length * 8), isLE); + setBigUint64(view, 8, BigInt(data.length * 8), isLE); + h.update(num); + return h.digest(); +} +/** + * GCM: Galois/Counter Mode. + * Good, modern version of CTR, parallel, with MAC. + * Be careful: MACs can be forged. + */ +export const gcm = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function gcm(key, nonce, AAD) { + abytes(nonce); + // Nonce can be pretty much anything (even 1 byte). But smaller nonces less secure. + if (nonce.length === 0) + throw new Error('aes/gcm: empty nonce'); + const tagLength = 16; + function _computeTag(authKey, tagMask, data) { + const tag = computeTag(ghash, false, authKey, data, AAD); + for (let i = 0; i < tagMask.length; i++) + tag[i] ^= tagMask[i]; + return tag; + } + function deriveKeys() { + const xk = expandKeyLE(key); + const authKey = EMPTY_BLOCK.slice(); + const counter = EMPTY_BLOCK.slice(); + ctr32(xk, false, counter, counter, authKey); + if (nonce.length === 12) { + counter.set(nonce); + } + else { + // Spec (NIST 800-38d) supports variable size nonce. + // Not supported for now, but can be useful. + const nonceLen = EMPTY_BLOCK.slice(); + const view = createView(nonceLen); + setBigUint64(view, 8, BigInt(nonce.length * 8), false); + // ghash(nonce || u64be(0) || u64be(nonceLen*8)) + ghash.create(authKey).update(nonce).update(nonceLen).digestInto(counter); + } + const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK); + return { xk, authKey, counter, tagMask }; + } + return { + encrypt: (plaintext) => { + abytes(plaintext); + const { xk, authKey, counter, tagMask } = deriveKeys(); + const out = new Uint8Array(plaintext.length + tagLength); + ctr32(xk, false, counter, plaintext, out); + const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength)); + out.set(tag, plaintext.length); + xk.fill(0); + return out; + }, + decrypt: (ciphertext) => { + abytes(ciphertext); + if (ciphertext.length < tagLength) + throw new Error(`aes/gcm: ciphertext less than tagLen (${tagLength})`); + const { xk, authKey, counter, tagMask } = deriveKeys(); + const data = ciphertext.subarray(0, -tagLength); + const passedTag = ciphertext.subarray(-tagLength); + const tag = _computeTag(authKey, tagMask, data); + if (!equalBytes(tag, passedTag)) + throw new Error('aes/gcm: invalid ghash tag'); + const out = ctr32(xk, false, counter, data); + authKey.fill(0); + tagMask.fill(0); + xk.fill(0); + return out; + }, + }; +}); +const limit = (name, min, max) => (value) => { + if (!Number.isSafeInteger(value) || min > value || value > max) + throw new Error(`${name}: invalid value=${value}, must be [${min}..${max}]`); +}; +/** + * AES-GCM-SIV: classic AES-GCM with nonce-misuse resistance. + * Guarantees that, when a nonce is repeated, the only security loss is that identical + * plaintexts will produce identical ciphertexts. + * RFC 8452, https://datatracker.ietf.org/doc/html/rfc8452 + */ +export const siv = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function siv(key, nonce, AAD) { + const tagLength = 16; + // From RFC 8452: Section 6 + const AAD_LIMIT = limit('AAD', 0, 2 ** 36); + const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36); + const NONCE_LIMIT = limit('nonce', 12, 12); + const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16); + abytes(nonce); + NONCE_LIMIT(nonce.length); + if (AAD) { + abytes(AAD); + AAD_LIMIT(AAD.length); + } + function deriveKeys() { + const len = key.length; + if (len !== 16 && len !== 24 && len !== 32) + throw new Error(`key length must be 16, 24 or 32 bytes, got: ${len} bytes`); + const xk = expandKeyLE(key); + const encKey = new Uint8Array(len); + const authKey = new Uint8Array(16); + const n32 = u32(nonce); + // prettier-ignore + let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2]; + let counter = 0; + for (const derivedKey of [authKey, encKey].map(u32)) { + const d32 = u32(derivedKey); + for (let i = 0; i < d32.length; i += 2) { + // aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ... + const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3); + d32[i + 0] = o0; + d32[i + 1] = o1; + s0 = ++counter; // increment counter inside state + } + } + xk.fill(0); + return { authKey, encKey: expandKeyLE(encKey) }; + } + function _computeTag(encKey, authKey, data) { + const tag = computeTag(polyval, true, authKey, data, AAD); + // Compute the expected tag by XORing S_s and the nonce, clearing the + // most significant bit of the last byte and encrypting with the + // message-encryption key. + for (let i = 0; i < 12; i++) + tag[i] ^= nonce[i]; + tag[15] &= 0x7f; // Clear the highest bit + // encrypt tag as block + const t32 = u32(tag); + // prettier-ignore + let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3]; + ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3)); + (t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3); + return tag; + } + // actual decrypt/encrypt of message. + function processSiv(encKey, tag, input) { + let block = tag.slice(); + block[15] |= 0x80; // Force highest bit + return ctr32(encKey, true, block, input); + } + return { + encrypt: (plaintext) => { + abytes(plaintext); + PLAIN_LIMIT(plaintext.length); + const { encKey, authKey } = deriveKeys(); + const tag = _computeTag(encKey, authKey, plaintext); + const out = new Uint8Array(plaintext.length + tagLength); + out.set(tag, plaintext.length); + out.set(processSiv(encKey, tag, plaintext)); + encKey.fill(0); + authKey.fill(0); + return out; + }, + decrypt: (ciphertext) => { + abytes(ciphertext); + CIPHER_LIMIT(ciphertext.length); + const tag = ciphertext.subarray(-tagLength); + const { encKey, authKey } = deriveKeys(); + const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength)); + const expectedTag = _computeTag(encKey, authKey, plaintext); + encKey.fill(0); + authKey.fill(0); + if (!equalBytes(tag, expectedTag)) + throw new Error('invalid polyval tag'); + return plaintext; + }, + }; +}); +function isBytes32(a) { + return (a != null && + typeof a === 'object' && + (a instanceof Uint32Array || a.constructor.name === 'Uint32Array')); +} +function encryptBlock(xk, block) { + abytes(block, 16); + if (!isBytes32(xk)) + throw new Error('_encryptBlock accepts result of expandKeyLE'); + const b32 = u32(block); + let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]); + (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3); + return block; +} +function decryptBlock(xk, block) { + abytes(block, 16); + if (!isBytes32(xk)) + throw new Error('_decryptBlock accepts result of expandKeyLE'); + const b32 = u32(block); + let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]); + (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3); + return block; +} +// Highly unsafe private functions for implementing new modes or ciphers based on AES +// Can change at any time, no API guarantees +export const unsafe = { + expandKeyLE, + expandKeyDecLE, + encrypt, + decrypt, + encryptBlock, + decryptBlock, + ctrCounter, + ctr32, +}; +//# sourceMappingURL=aes.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/aes.js.map b/node_modules/@noble/ciphers/esm/aes.js.map new file mode 100644 index 0000000..7957708 --- /dev/null +++ b/node_modules/@noble/ciphers/esm/aes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"aes.js","sourceRoot":"","sources":["../src/aes.ts"],"names":[],"mappings":"AAAA,kBAAkB;AAClB,OAAO,EACL,UAAU,EACV,UAAU,EAAE,YAAY,EAAE,UAAU,EAAE,GAAG,EAAE,EAAE,GAC9C,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,KAAK,IAAI,MAAM,EAAE,MAAM,cAAc,CAAC;AAE/C;;;;;;;;;;;;EAYE;AAEF,MAAM,UAAU,GAAG,EAAE,CAAC;AACtB,MAAM,YAAY,GAAG,CAAC,CAAC;AACvB,MAAM,WAAW,GAAG,IAAI,UAAU,CAAC,UAAU,CAAC,CAAC;AAC/C,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,6BAA6B;AAEjD,+CAA+C;AAC/C,SAAS,IAAI,CAAC,CAAS;IACrB,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACvC,CAAC;AAED,SAAS,GAAG,CAAC,CAAS,EAAE,CAAS;IAC/B,IAAI,GAAG,GA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G,OAAO,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IACrE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC;IAC3D,OAAO,KAAK,CAAC;AACf,CAAC;AAED,qFAAqF;AACrF,4CAA4C;AAC5C,MAAM,CAAC,MAAM,MAAM,GAAG;IACpB,WAAW;IACX,cAAc;IACd,OAAO;IACP,OAAO;IACP,YAAY;IACZ,YAAY;IACZ,UAAU;IACV,KAAK;CACN,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/chacha.js b/node_modules/@noble/ciphers/esm/chacha.js new file mode 100644 index 0000000..e23fcce --- /dev/null +++ b/node_modules/@noble/ciphers/esm/chacha.js @@ -0,0 +1,318 @@ +// prettier-ignore +import { wrapCipher, createView, equalBytes, setBigUint64, } from './utils.js'; +import { poly1305 } from './_poly1305.js'; +import { createCipher, rotl } from './_arx.js'; +import { bytes as abytes } from './_assert.js'; +// ChaCha20 stream cipher was released in 2008. ChaCha aims to increase +// the diffusion per round, but had slightly less cryptanalysis. +// https://cr.yp.to/chacha.html, http://cr.yp.to/chacha/chacha-20080128.pdf +/** + * ChaCha core function. + */ +// prettier-ignore +function chachaCore(s, k, n, out, cnt, rounds = 20) { + let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // "expa" "nd 3" "2-by" "te k" + y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key + y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key + y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Counter Nonce Nonce + // Save state to temporary variables + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; + for (let r = 0; r < rounds; r += 2) { + x00 = (x00 + x04) | 0; + x12 = rotl(x12 ^ x00, 16); + x08 = (x08 + x12) | 0; + x04 = rotl(x04 ^ x08, 12); + x00 = (x00 + x04) | 0; + x12 = rotl(x12 ^ x00, 8); + x08 = (x08 + x12) | 0; + x04 = rotl(x04 ^ x08, 7); + x01 = (x01 + x05) | 0; + x13 = rotl(x13 ^ x01, 16); + x09 = (x09 + x13) | 0; + x05 = rotl(x05 ^ x09, 12); + x01 = (x01 + x05) | 0; + x13 = rotl(x13 ^ x01, 8); + x09 = (x09 + x13) | 0; + x05 = rotl(x05 ^ x09, 7); + x02 = (x02 + x06) | 0; + x14 = rotl(x14 ^ x02, 16); + x10 = (x10 + x14) | 0; + x06 = rotl(x06 ^ x10, 12); + x02 = (x02 + x06) | 0; + x14 = rotl(x14 ^ x02, 8); + x10 = (x10 + x14) | 0; + x06 = rotl(x06 ^ x10, 7); + x03 = (x03 + x07) | 0; + x15 = rotl(x15 ^ x03, 16); + x11 = (x11 + x15) | 0; + x07 = rotl(x07 ^ x11, 12); + x03 = (x03 + x07) | 0; + x15 = rotl(x15 ^ x03, 8); + x11 = (x11 + x15) | 0; + x07 = rotl(x07 ^ x11, 7); + x00 = (x00 + x05) | 0; + x15 = rotl(x15 ^ x00, 16); + x10 = (x10 + x15) | 0; + x05 = rotl(x05 ^ x10, 12); + x00 = (x00 + x05) | 0; + x15 = rotl(x15 ^ x00, 8); + x10 = (x10 + x15) | 0; + x05 = rotl(x05 ^ x10, 7); + x01 = (x01 + x06) | 0; + x12 = rotl(x12 ^ x01, 16); + x11 = (x11 + x12) | 0; + x06 = rotl(x06 ^ x11, 12); + x01 = (x01 + x06) | 0; + x12 = rotl(x12 ^ x01, 8); + x11 = (x11 + x12) | 0; + x06 = rotl(x06 ^ x11, 7); + x02 = (x02 + x07) | 0; + x13 = rotl(x13 ^ x02, 16); + x08 = (x08 + x13) | 0; + x07 = rotl(x07 ^ x08, 12); + x02 = (x02 + x07) | 0; + x13 = rotl(x13 ^ x02, 8); + x08 = (x08 + x13) | 0; + x07 = rotl(x07 ^ x08, 7); + x03 = (x03 + x04) | 0; + x14 = rotl(x14 ^ x03, 16); + x09 = (x09 + x14) | 0; + x04 = rotl(x04 ^ x09, 12); + x03 = (x03 + x04) | 0; + x14 = rotl(x14 ^ x03, 8); + x09 = (x09 + x14) | 0; + x04 = rotl(x04 ^ x09, 7); + } + // Write output + let oi = 0; + out[oi++] = (y00 + x00) | 0; + out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; + out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; + out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; + out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; + out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; + out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; + out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; + out[oi++] = (y15 + x15) | 0; +} +/** + * hchacha helper method, used primarily in xchacha, to hash + * key and nonce into key' and nonce'. + * Same as chachaCore, but there doesn't seem to be a way to move the block + * out without 25% performance hit. + */ +// prettier-ignore +export function hchacha(s, k, i, o32) { + let x00 = s[0], x01 = s[1], x02 = s[2], x03 = s[3], x04 = k[0], x05 = k[1], x06 = k[2], x07 = k[3], x08 = k[4], x09 = k[5], x10 = k[6], x11 = k[7], x12 = i[0], x13 = i[1], x14 = i[2], x15 = i[3]; + for (let r = 0; r < 20; r += 2) { + x00 = (x00 + x04) | 0; + x12 = rotl(x12 ^ x00, 16); + x08 = (x08 + x12) | 0; + x04 = rotl(x04 ^ x08, 12); + x00 = (x00 + x04) | 0; + x12 = rotl(x12 ^ x00, 8); + x08 = (x08 + x12) | 0; + x04 = rotl(x04 ^ x08, 7); + x01 = (x01 + x05) | 0; + x13 = rotl(x13 ^ x01, 16); + x09 = (x09 + x13) | 0; + x05 = rotl(x05 ^ x09, 12); + x01 = (x01 + x05) | 0; + x13 = rotl(x13 ^ x01, 8); + x09 = (x09 + x13) | 0; + x05 = rotl(x05 ^ x09, 7); + x02 = (x02 + x06) | 0; + x14 = rotl(x14 ^ x02, 16); + x10 = (x10 + x14) | 0; + x06 = rotl(x06 ^ x10, 12); + x02 = (x02 + x06) | 0; + x14 = rotl(x14 ^ x02, 8); + x10 = (x10 + x14) | 0; + x06 = rotl(x06 ^ x10, 7); + x03 = (x03 + x07) | 0; + x15 = rotl(x15 ^ x03, 16); + x11 = (x11 + x15) | 0; + x07 = rotl(x07 ^ x11, 12); + x03 = (x03 + x07) | 0; + x15 = rotl(x15 ^ x03, 8); + x11 = (x11 + x15) | 0; + x07 = rotl(x07 ^ x11, 7); + x00 = (x00 + x05) | 0; + x15 = rotl(x15 ^ x00, 16); + x10 = (x10 + x15) | 0; + x05 = rotl(x05 ^ x10, 12); + x00 = (x00 + x05) | 0; + x15 = rotl(x15 ^ x00, 8); + x10 = (x10 + x15) | 0; + x05 = rotl(x05 ^ x10, 7); + x01 = (x01 + x06) | 0; + x12 = rotl(x12 ^ x01, 16); + x11 = (x11 + x12) | 0; + x06 = rotl(x06 ^ x11, 12); + x01 = (x01 + x06) | 0; + x12 = rotl(x12 ^ x01, 8); + x11 = (x11 + x12) | 0; + x06 = rotl(x06 ^ x11, 7); + x02 = (x02 + x07) | 0; + x13 = rotl(x13 ^ x02, 16); + x08 = (x08 + x13) | 0; + x07 = rotl(x07 ^ x08, 12); + x02 = (x02 + x07) | 0; + x13 = rotl(x13 ^ x02, 8); + x08 = (x08 + x13) | 0; + x07 = rotl(x07 ^ x08, 7); + x03 = (x03 + x04) | 0; + x14 = rotl(x14 ^ x03, 16); + x09 = (x09 + x14) | 0; + x04 = rotl(x04 ^ x09, 12); + x03 = (x03 + x04) | 0; + x14 = rotl(x14 ^ x03, 8); + x09 = (x09 + x14) | 0; + x04 = rotl(x04 ^ x09, 7); + } + let oi = 0; + o32[oi++] = x00; + o32[oi++] = x01; + o32[oi++] = x02; + o32[oi++] = x03; + o32[oi++] = x12; + o32[oi++] = x13; + o32[oi++] = x14; + o32[oi++] = x15; +} +/** + * Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter. + */ +export const chacha20orig = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 8, + allowShortKeys: true, +}); +/** + * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter. + * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance. + */ +export const chacha20 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 4, + allowShortKeys: false, +}); +/** + * XChaCha eXtended-nonce ChaCha. 24-byte nonce. + * With 24-byte nonce, it's safe to use fill it with random (CSPRNG). + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha + */ +export const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 8, + extendNonceFn: hchacha, + allowShortKeys: false, +}); +/** + * Reduced 8-round chacha, described in original paper. + */ +export const chacha8 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 4, + rounds: 8, +}); +/** + * Reduced 12-round chacha, described in original paper. + */ +export const chacha12 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 4, + rounds: 12, +}); +const ZEROS16 = /* @__PURE__ */ new Uint8Array(16); +// Pad to digest size with zeros +const updatePadded = (h, msg) => { + h.update(msg); + const left = msg.length % 16; + if (left) + h.update(ZEROS16.subarray(left)); +}; +const ZEROS32 = /* @__PURE__ */ new Uint8Array(32); +function computeTag(fn, key, nonce, data, AAD) { + const authKey = fn(key, nonce, ZEROS32); + const h = poly1305.create(authKey); + if (AAD) + updatePadded(h, AAD); + updatePadded(h, data); + const num = new Uint8Array(16); + const view = createView(num); + setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true); + setBigUint64(view, 8, BigInt(data.length), true); + h.update(num); + const res = h.digest(); + authKey.fill(0); + return res; +} +/** + * AEAD algorithm from RFC 8439. + * Salsa20 and chacha (RFC 8439) use poly1305 differently. + * We could have composed them similar to: + * https://github.com/paulmillr/scure-base/blob/b266c73dde977b1dd7ef40ef7a23cc15aab526b3/index.ts#L250 + * But it's hard because of authKey: + * In salsa20, authKey changes position in salsa stream. + * In chacha, authKey can't be computed inside computeTag, it modifies the counter. + */ +export const _poly1305_aead = (xorStream) => (key, nonce, AAD) => { + const tagLength = 16; + abytes(key, 32); + abytes(nonce); + return { + encrypt: (plaintext, output) => { + const plength = plaintext.length; + const clength = plength + tagLength; + if (output) { + abytes(output, clength); + } + else { + output = new Uint8Array(clength); + } + xorStream(key, nonce, plaintext, output, 1); + const tag = computeTag(xorStream, key, nonce, output.subarray(0, -tagLength), AAD); + output.set(tag, plength); // append tag + return output; + }, + decrypt: (ciphertext, output) => { + const clength = ciphertext.length; + const plength = clength - tagLength; + if (clength < tagLength) + throw new Error(`encrypted data must be at least ${tagLength} bytes`); + if (output) { + abytes(output, plength); + } + else { + output = new Uint8Array(plength); + } + const data = ciphertext.subarray(0, -tagLength); + const passedTag = ciphertext.subarray(-tagLength); + const tag = computeTag(xorStream, key, nonce, data, AAD); + if (!equalBytes(passedTag, tag)) + throw new Error('invalid tag'); + xorStream(key, nonce, data, output, 1); + return output; + }, + }; +}; +/** + * ChaCha20-Poly1305 from RFC 8439. + * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance. + */ +export const chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16 }, _poly1305_aead(chacha20)); +/** + * XChaCha20-Poly1305 extended-nonce chacha. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha + * With 24-byte nonce, it's safe to use fill it with random (CSPRNG). + */ +export const xchacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, _poly1305_aead(xchacha20)); +//# sourceMappingURL=chacha.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/chacha.js.map b/node_modules/@noble/ciphers/esm/chacha.js.map new file mode 100644 index 0000000..a4ff5a7 --- /dev/null +++ b/node_modules/@noble/ciphers/esm/chacha.js.map @@ -0,0 +1 @@ +{"version":3,"file":"chacha.js","sourceRoot":"","sources":["../src/chacha.ts"],"names":[],"mappings":"AAAA,kBAAkB;AAClB,OAAO,EACL,UAAU,EAA+B,UAAU,EAAE,UAAU,EAAE,YAAY,GAC9E,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EAAE,KAAK,IAAI,MAAM,EAAE,MAAM,cAAc,CAAC;AAE/C,uEAAuE;AACvE,gEAAgE;AAChE,2EAA2E;AAE3E;;GAEG;AACH,kBAAkB;AAClB,SAAS,UAAU,CACjB,CAAc,EAAE,CAAc,EAAE,CAAc,EAAE,GAAgB,EAAE,GAAW,EAAE,MAAM,GAAG,EAAE;IAE1F,IAAI,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,kCAAkC;IAClF,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,E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rB,MAAM,IAAI,KAAK,CAAC,mCAAmC,SAAS,QAAQ,CAAC,CAAC;YACxE,IAAI,MAAM,EAAE,CAAC;gBACX,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;YAC1B,CAAC;iBAAM,CAAC;gBACN,MAAM,GAAG,IAAI,UAAU,CAAC,OAAO,CAAC,CAAC;YACnC,CAAC;YACD,MAAM,IAAI,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,SAAS,CAAC,CAAC;YAChD,MAAM,SAAS,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC,CAAC;YAClD,MAAM,GAAG,GAAG,UAAU,CAAC,SAAS,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC;YACzD,IAAI,CAAC,UAAU,CAAC,SAAS,EAAE,GAAG,CAAC;gBAAE,MAAM,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC;YAChE,SAAS,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC;YACvC,OAAO,MAAM,CAAC;QAChB,CAAC;KACF,CAAC;AACJ,CAAC,CAAC;AAEJ;;;GAGG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,eAAe,CAAC,UAAU,CACxD,EAAE,SAAS,EAAE,EAAE,EAAE,WAAW,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,EACjD,cAAc,CAAC,QAAQ,CAAC,CACzB,CAAC;AACF;;;;GAIG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,eAAe,CAAC,UAAU,CACzD,EAAE,SAAS,EAAE,EAAE,EAAE,WAAW,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,EACjD,cAAc,CAAC,SAAS,CAAC,CAC1B,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/crypto.js b/node_modules/@noble/ciphers/esm/crypto.js new file mode 100644 index 0000000..63bf63e --- /dev/null +++ b/node_modules/@noble/ciphers/esm/crypto.js @@ -0,0 +1,12 @@ +const cr = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; +export function randomBytes(bytesLength = 32) { + if (cr && typeof cr.getRandomValues === 'function') + return cr.getRandomValues(new Uint8Array(bytesLength)); + throw new Error('crypto.getRandomValues must be defined'); +} +export function getWebcryptoSubtle() { + if (cr && typeof cr.subtle === 'object' && cr.subtle != null) + return cr.subtle; + throw new Error('crypto.subtle must be defined'); +} +//# sourceMappingURL=crypto.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/crypto.js.map b/node_modules/@noble/ciphers/esm/crypto.js.map new file mode 100644 index 0000000..8fded12 --- /dev/null +++ b/node_modules/@noble/ciphers/esm/crypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.js","sourceRoot":"","sources":["../src/crypto.ts"],"names":[],"mappings":"AAGA,MAAM,EAAE,GAAG,OAAO,UAAU,KAAK,QAAQ,IAAI,QAAQ,IAAI,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC;AAEpG,MAAM,UAAU,WAAW,CAAC,WAAW,GAAG,EAAE;IAC1C,IAAI,EAAE,IAAI,OAAO,EAAE,CAAC,eAAe,KAAK,UAAU;QAChD,OAAO,EAAE,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC;IACzD,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAC5D,CAAC;AAED,MAAM,UAAU,kBAAkB;IAChC,IAAI,EAAE,IAAI,OAAO,EAAE,CAAC,MAAM,KAAK,QAAQ,IAAI,EAAE,CAAC,MAAM,IAAI,IAAI;QAAE,OAAO,EAAE,CAAC,MAAM,CAAC;IAC/E,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;AACnD,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/cryptoNode.js b/node_modules/@noble/ciphers/esm/cryptoNode.js new file mode 100644 index 0000000..956ce1b --- /dev/null +++ b/node_modules/@noble/ciphers/esm/cryptoNode.js @@ -0,0 +1,17 @@ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +// The file will throw on node.js 14 and earlier. +// @ts-ignore +import * as nc from 'node:crypto'; +const cr = nc && typeof nc === 'object' && 'webcrypto' in nc ? nc.webcrypto : undefined; +export function randomBytes(bytesLength = 32) { + if (cr && typeof cr.getRandomValues === 'function') + return cr.getRandomValues(new Uint8Array(bytesLength)); + throw new Error('crypto.getRandomValues must be defined'); +} +export function getWebcryptoSubtle() { + if (cr && typeof cr.subtle === 'object' && cr.subtle != null) + return cr.subtle; + throw new Error('crypto.subtle must be defined'); +} +//# sourceMappingURL=cryptoNode.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/cryptoNode.js.map b/node_modules/@noble/ciphers/esm/cryptoNode.js.map new file mode 100644 index 0000000..15dc43f --- /dev/null +++ b/node_modules/@noble/ciphers/esm/cryptoNode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cryptoNode.js","sourceRoot":"","sources":["../src/cryptoNode.ts"],"names":[],"mappings":"AAAA,oFAAoF;AACpF,4BAA4B;AAC5B,iDAAiD;AACjD,aAAa;AACb,OAAO,KAAK,EAAE,MAAM,aAAa,CAAC;AAClC,MAAM,EAAE,GAAG,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,WAAW,IAAI,EAAE,CAAC,CAAC,CAAE,EAAE,CAAC,SAAiB,CAAC,CAAC,CAAC,SAAS,CAAC;AAEjG,MAAM,UAAU,WAAW,CAAC,WAAW,GAAG,EAAE;IAC1C,IAAI,EAAE,IAAI,OAAO,EAAE,CAAC,eAAe,KAAK,UAAU;QAChD,OAAO,EAAE,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC;IACzD,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAC5D,CAAC;AAED,MAAM,UAAU,kBAAkB;IAChC,IAAI,EAAE,IAAI,OAAO,EAAE,CAAC,MAAM,KAAK,QAAQ,IAAI,EAAE,CAAC,MAAM,IAAI,IAAI;QAAE,OAAO,EAAE,CAAC,MAAM,CAAC;IAC/E,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;AACnD,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/ff1.js b/node_modules/@noble/ciphers/esm/ff1.js new file mode 100644 index 0000000..33907e1 --- /dev/null +++ b/node_modules/@noble/ciphers/esm/ff1.js @@ -0,0 +1,149 @@ +import { bytesToNumberBE, numberToBytesBE } from './utils.js'; +import { unsafe } from './aes.js'; +// NOTE: no point in inlining encrypt instead of encryptBlock, since BigInt stuff will be slow +const { expandKeyLE, encryptBlock } = unsafe; +// Format-preserving encryption algorithm (FPE-FF1) specified in NIST Special Publication 800-38G. +// https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf +const BLOCK_LEN = 16; +function mod(a, b) { + const result = a % b; + return result >= 0 ? result : b + result; +} +function NUMradix(radix, data) { + let res = BigInt(0); + for (let i of data) + res = res * BigInt(radix) + BigInt(i); + return res; +} +function getRound(radix, key, tweak, x) { + if (radix > 2 ** 16 - 1) + throw new Error(`Invalid radix: ${radix}`); + // radix**minlen ≥ 100 + const minLen = Math.ceil(Math.log(100) / Math.log(radix)); + const maxLen = 2 ** 32 - 1; + // 2 ≤ minlen ≤ maxlen < 2**32 + if (2 > minLen || minLen > maxLen || maxLen >= 2 ** 32) + throw new Error('Invalid radix: 2 ≤ minlen ≤ maxlen < 2**32'); + if (x.length < minLen || x.length > maxLen) + throw new Error('X is outside minLen..maxLen bounds'); + const u = Math.floor(x.length / 2); + const v = x.length - u; + const b = Math.ceil(Math.ceil(v * Math.log2(radix)) / 8); + const d = 4 * Math.ceil(b / 4) + 4; + const padding = mod(-tweak.length - b - 1, 16); + // P = [1]1 || [2]1 || [1]1 || [radix]3 || [10]1 || [u mod 256]1 || [n]4 || [t]4. + const P = new Uint8Array([1, 2, 1, 0, 0, 0, 10, u, 0, 0, 0, 0, 0, 0, 0, 0]); + const view = new DataView(P.buffer); + view.setUint16(4, radix, false); + view.setUint32(8, x.length, false); + view.setUint32(12, tweak.length, false); + // Q = T || [0](−t−b−1) mod 16 || [i]1 || [NUMradix(B)]b. + const PQ = new Uint8Array(P.length + tweak.length + padding + 1 + b); + PQ.set(P); + P.fill(0); + PQ.set(tweak, P.length); + const xk = expandKeyLE(key); + const round = (A, B, i, decrypt = false) => { + // Q = ... || [i]1 || [NUMradix(B)]b. + PQ[PQ.length - b - 1] = i; + if (b) + PQ.set(numberToBytesBE(NUMradix(radix, B), b), PQ.length - b); + // PRF + let r = new Uint8Array(16); + for (let j = 0; j < PQ.length / BLOCK_LEN; j++) { + for (let i = 0; i < BLOCK_LEN; i++) + r[i] ^= PQ[j * BLOCK_LEN + i]; + encryptBlock(xk, r); + } + // Let S be the first d bytes of the following string of ⎡d/16⎤ blocks: + // R || CIPHK(R ⊕[1]16) || CIPHK(R ⊕[2]16) ...CIPHK(R ⊕[⎡d / 16⎤ – 1]16). + let s = Array.from(r); + for (let j = 1; s.length < d; j++) { + const block = numberToBytesBE(BigInt(j), 16); + for (let k = 0; k < BLOCK_LEN; k++) + block[k] ^= r[k]; + s.push(...Array.from(encryptBlock(xk, block))); + } + let y = bytesToNumberBE(Uint8Array.from(s.slice(0, d))); + s.fill(0); + if (decrypt) + y = -y; + const m = i % 2 === 0 ? u : v; + let c = mod(NUMradix(radix, A) + y, BigInt(radix) ** BigInt(m)); + // STR(radix, m, c) + const C = Array(m).fill(0); + for (let i = 0; i < m; i++, c /= BigInt(radix)) + C[m - 1 - i] = Number(c % BigInt(radix)); + A.fill(0); + A = B; + B = C; + return [A, B]; + }; + const destroy = () => { + xk.fill(0); + PQ.fill(0); + }; + return { u, round, destroy }; +} +const EMPTY_BUF = new Uint8Array([]); +export function FF1(radix, key, tweak = EMPTY_BUF) { + const PQ = getRound.bind(null, radix, key, tweak); + return { + encrypt(x) { + const { u, round, destroy } = PQ(x); + let [A, B] = [x.slice(0, u), x.slice(u)]; + for (let i = 0; i < 10; i++) + [A, B] = round(A, B, i); + destroy(); + const res = A.concat(B); + A.fill(0); + B.fill(0); + return res; + }, + decrypt(x) { + const { u, round, destroy } = PQ(x); + // The FF1.Decrypt algorithm is similar to the FF1.Encrypt algorithm; + // the differences are in Step 6, where: + // 1) the order of the indices is reversed, + // 2) the roles of A and B are swapped + // 3) modular addition is replaced by modular subtraction, in Step 6vi. + let [B, A] = [x.slice(0, u), x.slice(u)]; + for (let i = 9; i >= 0; i--) + [A, B] = round(A, B, i, true); + destroy(); + const res = B.concat(A); + A.fill(0); + B.fill(0); + return res; + }, + }; +} +// Binary string which encodes each byte in little-endian byte order +const binLE = { + encode(bytes) { + const x = []; + for (let i = 0; i < bytes.length; i++) { + for (let j = 0, tmp = bytes[i]; j < 8; j++, tmp >>= 1) + x.push(tmp & 1); + } + return x; + }, + decode(b) { + if (b.length % 8) + throw new Error('Invalid binary string'); + const res = new Uint8Array(b.length / 8); + for (let i = 0, j = 0; i < res.length; i++) { + res[i] = b[j++] | (b[j++] << 1) | (b[j++] << 2) | (b[j++] << 3); + res[i] |= (b[j++] << 4) | (b[j++] << 5) | (b[j++] << 6) | (b[j++] << 7); + } + return res; + }, +}; +export function BinaryFF1(key, tweak = EMPTY_BUF) { + const ff1 = FF1(2, key, tweak); + return { + encrypt: (x) => binLE.decode(ff1.encrypt(binLE.encode(x))), + decrypt: (x) => binLE.decode(ff1.decrypt(binLE.encode(x))), + }; +} +//# sourceMappingURL=ff1.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/ff1.js.map b/node_modules/@noble/ciphers/esm/ff1.js.map new file mode 100644 index 0000000..f2543f1 --- /dev/null +++ b/node_modules/@noble/ciphers/esm/ff1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ff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KAAK,CAAC,CAAC;IAC/B,OAAO;QACL,OAAO,EAAE,CAAC,CAAa,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QACtE,OAAO,EAAE,CAAC,CAAa,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;KACvE,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/index.js b/node_modules/@noble/ciphers/esm/index.js new file mode 100644 index 0000000..9a9d7ac --- /dev/null +++ b/node_modules/@noble/ciphers/esm/index.js @@ -0,0 +1,3 @@ +throw new Error('noble-ciphers have no entry-point: consult README for usage'); +export {}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/index.js.map b/node_modules/@noble/ciphers/esm/index.js.map new file mode 100644 index 0000000..0fd4116 --- /dev/null +++ b/node_modules/@noble/ciphers/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,MAAM,IAAI,KAAK,CAAC,6DAA6D,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/package.json b/node_modules/@noble/ciphers/esm/package.json new file mode 100644 index 0000000..623827d --- /dev/null +++ b/node_modules/@noble/ciphers/esm/package.json @@ -0,0 +1,11 @@ +{ + "type": "module", + "sideEffects": false, + "browser": { + "node:crypto": false + }, + "node": { + "./crypto.js": "./esm/cryptoNode.js", + "./crypto": "./esm/cryptoNode.js" + } +} diff --git a/node_modules/@noble/ciphers/esm/salsa.js b/node_modules/@noble/ciphers/esm/salsa.js new file mode 100644 index 0000000..a956d46 --- /dev/null +++ b/node_modules/@noble/ciphers/esm/salsa.js @@ -0,0 +1,205 @@ +import { bytes as abytes } from './_assert.js'; +import { createCipher, rotl } from './_arx.js'; +import { poly1305 } from './_poly1305.js'; +import { wrapCipher, equalBytes } from './utils.js'; +// Salsa20 stream cipher was released in 2005. +// Salsa's goal was to implement AES replacement that does not rely on S-Boxes, +// which are hard to implement in a constant-time manner. +// https://cr.yp.to/snuffle.html, https://cr.yp.to/snuffle/salsafamily-20071225.pdf +/** + * Salsa20 core function. + */ +// prettier-ignore +function salsaCore(s, k, n, out, cnt, rounds = 20) { + // Based on https://cr.yp.to/salsa20.html + let y00 = s[0], y01 = k[0], y02 = k[1], y03 = k[2], // "expa" Key Key Key + y04 = k[3], y05 = s[1], y06 = n[0], y07 = n[1], // Key "nd 3" Nonce Nonce + y08 = cnt, y09 = 0, y10 = s[2], y11 = k[4], // Pos. Pos. "2-by" Key + y12 = k[5], y13 = k[6], y14 = k[7], y15 = s[3]; // Key Key Key "te k" + // Save state to temporary variables + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; + for (let r = 0; r < rounds; r += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); + x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); + x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); + x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); + x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); + x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); + x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); + x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); + x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); + x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); + x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); + x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); + x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); + x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); + x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); + x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); + x15 ^= rotl(x14 + x13 | 0, 18); + } + // Write output + let oi = 0; + out[oi++] = (y00 + x00) | 0; + out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; + out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; + out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; + out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; + out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; + out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; + out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; + out[oi++] = (y15 + x15) | 0; +} +/** + * hsalsa hashing function, used primarily in xsalsa, to hash + * key and nonce into key' and nonce'. + * Same as salsaCore, but there doesn't seem to be a way to move the block + * out without 25% performance hit. + */ +// prettier-ignore +export function hsalsa(s, k, i, o32) { + let x00 = s[0], x01 = k[0], x02 = k[1], x03 = k[2], x04 = k[3], x05 = s[1], x06 = i[0], x07 = i[1], x08 = i[2], x09 = i[3], x10 = s[2], x11 = k[4], x12 = k[5], x13 = k[6], x14 = k[7], x15 = s[3]; + for (let r = 0; r < 20; r += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); + x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); + x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); + x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); + x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); + x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); + x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); + x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); + x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); + x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); + x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); + x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); + x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); + x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); + x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); + x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); + x15 ^= rotl(x14 + x13 | 0, 18); + } + let oi = 0; + o32[oi++] = x00; + o32[oi++] = x05; + o32[oi++] = x10; + o32[oi++] = x15; + o32[oi++] = x06; + o32[oi++] = x07; + o32[oi++] = x08; + o32[oi++] = x09; +} +/** + * Salsa20 from original paper. + * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance. + */ +export const salsa20 = /* @__PURE__ */ createCipher(salsaCore, { + allowShortKeys: true, + counterRight: true, +}); +/** + * xsalsa20 eXtended-nonce salsa. + * With 24-byte nonce, it's safe to use fill it with random (CSPRNG). + */ +export const xsalsa20 = /* @__PURE__ */ createCipher(salsaCore, { + counterRight: true, + extendNonceFn: hsalsa, +}); +/** + * xsalsa20-poly1305 eXtended-nonce salsa. + * With 24-byte nonce, it's safe to use fill it with random (CSPRNG). + * Also known as secretbox from libsodium / nacl. + */ +export const xsalsa20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, (key, nonce) => { + const tagLength = 16; + abytes(key, 32); + abytes(nonce, 24); + return { + encrypt: (plaintext, output) => { + abytes(plaintext); + // This is small optimization (calculate auth key with same call as encryption itself) makes it hard + // to separate tag calculation and encryption itself, since 32 byte is half-block of salsa (64 byte) + const clength = plaintext.length + 32; + if (output) { + abytes(output, clength); + } + else { + output = new Uint8Array(clength); + } + output.set(plaintext, 32); + xsalsa20(key, nonce, output, output); + const authKey = output.subarray(0, 32); + const tag = poly1305(output.subarray(32), authKey); + // Clean auth key, even though JS provides no guarantees about memory cleaning + output.set(tag, tagLength); + output.subarray(0, tagLength).fill(0); + return output.subarray(tagLength); + }, + decrypt: (ciphertext) => { + abytes(ciphertext); + const clength = ciphertext.length; + if (clength < tagLength) + throw new Error('encrypted data should be at least 16 bytes'); + // Create new ciphertext array: + // auth tag auth tag from ciphertext ciphertext + // [bytes 0..16] [bytes 16..32] [bytes 32..] + // 16 instead of 32, because we already have 16 byte tag + const ciphertext_ = new Uint8Array(clength + tagLength); // alloc + ciphertext_.set(ciphertext, tagLength); + // Each xsalsa20 calls to hsalsa to calculate key, but seems not much perf difference + // Separate call to calculate authkey, since first bytes contains tag + const authKey = xsalsa20(key, nonce, new Uint8Array(32)); // alloc(32) + const tag = poly1305(ciphertext_.subarray(32), authKey); + if (!equalBytes(ciphertext_.subarray(16, 32), tag)) + throw new Error('invalid tag'); + const plaintext = xsalsa20(key, nonce, ciphertext_); // alloc + // Clean auth key, even though JS provides no guarantees about memory cleaning + plaintext.subarray(0, 32).fill(0); + authKey.fill(0); + return plaintext.subarray(32); + }, + }; +}); +/** + * Alias to xsalsa20poly1305, for compatibility with libsodium / nacl + */ +export function secretbox(key, nonce) { + const xs = xsalsa20poly1305(key, nonce); + return { seal: xs.encrypt, open: xs.decrypt }; +} +//# sourceMappingURL=salsa.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/salsa.js.map b/node_modules/@noble/ciphers/esm/salsa.js.map new file mode 100644 index 0000000..7656d87 --- /dev/null +++ b/node_modules/@noble/ciphers/esm/salsa.js.map @@ -0,0 +1 @@ +{"version":3,"file":"salsa.js","sourceRoot":"","sources":["../src/salsa.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,IAAI,MAAM,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAU,UAAU,EAAE,MAAM,YAAY,CAAC;AAE5D,8CAA8C;AAC9C,+EAA+E;AAC/E,yDAAyD;AACzD,mFAAmF;AAEnF;;GAEG;AACH,kBAAkB;AAClB,SAAS,SAAS,CAChB,CAAc,EAAE,CAAc,EAAE,CAAc,EAAE,GAAgB,EAAE,GAAW,EAAE,MAAM,GAAG,EAAE;IAE1F,yCAAyC;IACzC,IAAI,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,6BAA6B;IAC7E,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,+BAA+B;IAC/E,GAAG,GAAG,GAAG,EAAG,GAAG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C,CAAC;YACvC,qFAAqF;YACrF,qEAAqE;YACrE,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,YAAY;YACtE,MAAM,GAAG,GAAG,QAAQ,CAAC,WAAW,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE,OAAO,CAAC,CAAC;YACxD,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,QAAQ,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,GAAG,CAAC;gBAAE,MAAM,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC;YAEnF,MAAM,SAAS,GAAG,QAAQ,CAAC,GAAG,EAAE,KAAK,EAAE,WAAW,CAAC,CAAC,CAAC,QAAQ;YAC7D,8EAA8E;YAC9E,SAAS,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAClC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAChB,OAAO,SAAS,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QAChC,CAAC;KACF,CAAC;AACJ,CAAC,CACF,CAAC;AAEF;;GAEG;AACH,MAAM,UAAU,SAAS,CAAC,GAAe,EAAE,KAAiB;IAC1D,MAAM,EAAE,GAAG,gBAAgB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACxC,OAAO,EAAE,IAAI,EAAE,EAAE,CAAC,OAAO,EAAE,IAAI,EAAE,EAAE,CAAC,OAAO,EAAE,CAAC;AAChD,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/utils.js b/node_modules/@noble/ciphers/esm/utils.js new file mode 100644 index 0000000..90ceb2e --- /dev/null +++ b/node_modules/@noble/ciphers/esm/utils.js @@ -0,0 +1,182 @@ +/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */ +import { bytes as abytes, isBytes } from './_assert.js'; +// Cast array to different type +export const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +export const u16 = (arr) => new Uint16Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 2)); +export const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +// Cast array to view +export const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +// big-endian hardware is rare. Just in case someone still decides to run ciphers: +// early-throw an error because we don't support BE yet. +export const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!isLE) + throw new Error('Non little-endian hardware is not supported'); +// Array where index 0xf0 (240) is mapped to string 'f0' +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export function bytesToHex(bytes) { + abytes(bytes); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +// We use optimized technique to convert hex string to byte array +const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 }; +function asciiToBase16(char) { + if (char >= asciis._0 && char <= asciis._9) + return char - asciis._0; + if (char >= asciis._A && char <= asciis._F) + return char - (asciis._A - 10); + if (char >= asciis._a && char <= asciis._f) + return char - (asciis._a - 10); + return; +} +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const hl = hex.length; + const al = hl / 2; + if (hl % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + hl); + const array = new Uint8Array(al); + for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { + const n1 = asciiToBase16(hex.charCodeAt(hi)); + const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); + if (n1 === undefined || n2 === undefined) { + const char = hex[hi] + hex[hi + 1]; + throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi); + } + array[ai] = n1 * 16 + n2; + } + return array; +} +export function hexToNumber(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + // Big Endian + return BigInt(hex === '' ? '0' : `0x${hex}`); +} +// BE: Big Endian, LE: Little Endian +export function bytesToNumberBE(bytes) { + return hexToNumber(bytesToHex(bytes)); +} +export function numberToBytesBE(n, len) { + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} +// There is no setImmediate in browser and setTimeout is slow. +// call of async fn will return Promise, which will be fullfiled only on +// next scheduler queue processing step and this is exactly what we need. +export const nextTick = async () => { }; +// Returns control to thread each 'tick' ms to avoid blocking +export async function asyncLoop(iters, tick, cb) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) + continue; + await nextTick(); + ts += diff; + } +} +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`string expected, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +/** + * @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc' + */ +export function bytesToUtf8(bytes) { + return new TextDecoder().decode(bytes); +} +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +export function toBytes(data) { + if (typeof data === 'string') + data = utf8ToBytes(data); + else if (isBytes(data)) + data = data.slice(); + else + throw new Error(`Uint8Array expected, got ${typeof data}`); + return data; +} +/** + * Copies several Uint8Arrays into one. + */ +export function concatBytes(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + abytes(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; +} +export function checkOpts(defaults, opts) { + if (opts == null || typeof opts !== 'object') + throw new Error('options must be defined'); + const merged = Object.assign(defaults, opts); + return merged; +} +// Compares 2 u8a-s in kinda constant time +export function equalBytes(a, b) { + if (a.length !== b.length) + return false; + let diff = 0; + for (let i = 0; i < a.length; i++) + diff |= a[i] ^ b[i]; + return diff === 0; +} +// For runtime check if class implements interface +export class Hash { +} +/** + * @__NO_SIDE_EFFECTS__ + */ +export const wrapCipher = (params, c) => { + Object.assign(c, params); + return c; +}; +// Polyfill for Safari 14 +export function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +export function u64Lengths(ciphertext, AAD) { + const num = new Uint8Array(16); + const view = createView(num); + setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true); + setBigUint64(view, 8, BigInt(ciphertext.length), true); + return num; +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/utils.js.map b/node_modules/@noble/ciphers/esm/utils.js.map new file mode 100644 index 0000000..79af87a --- /dev/null +++ b/node_modules/@noble/ciphers/esm/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,OAAO,EAAE,KAAK,IAAI,MAAM,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAKxD,+BAA+B;AAC/B,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAe,EAAE,EAAE,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC,MAAM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CAAC,CAAC,CAAC;IACvB,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACvB,IAAI,CAAC,SAAS,CAAC,UAAU,GAAG,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;IACzC,IAAI,CAAC,SAAS,CAAC,UAAU,GAAG,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;AAC3C,CAAC;AAED,MAAM,UAAU,UAAU,CAAC,UAAsB,EAAE,GAAgB;IACjE,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;IAC/B,MAAM,IAAI,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC;IAC7B,YAAY,CAAC,IAAI,EAAE,CAAC,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;IAC1D,YAAY,CAAC,IAAI,EAAE,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC;IACvD,OAAO,GAAG,CAAC;AACb,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/webcrypto.js b/node_modules/@noble/ciphers/esm/webcrypto.js new file mode 100644 index 0000000..357eff5 --- /dev/null +++ b/node_modules/@noble/ciphers/esm/webcrypto.js @@ -0,0 +1,105 @@ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.js on#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated, we can just drop the import. +// +// Use full path so that Node.js can rewrite it to `cryptoNode.js`. +import { randomBytes, getWebcryptoSubtle } from '@noble/ciphers/crypto'; +import { concatBytes } from './utils.js'; +import { number, bytes as abytes } from './_assert.js'; +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +export { randomBytes, getWebcryptoSubtle }; +// Uses CSPRG for nonce, nonce injected in ciphertext +export function managedNonce(fn) { + number(fn.nonceLength); + return ((key, ...args) => ({ + encrypt: (plaintext, ...argsEnc) => { + const { nonceLength } = fn; + const nonce = randomBytes(nonceLength); + const ciphertext = fn(key, nonce, ...args).encrypt(plaintext, ...argsEnc); + const out = concatBytes(nonce, ciphertext); + ciphertext.fill(0); + return out; + }, + decrypt: (ciphertext, ...argsDec) => { + const { nonceLength } = fn; + const nonce = ciphertext.subarray(0, nonceLength); + const data = ciphertext.subarray(nonceLength); + return fn(key, nonce, ...args).decrypt(data, ...argsDec); + }, + })); +} +// Overridable +export const utils = { + async encrypt(key, keyParams, cryptParams, plaintext) { + const cr = getWebcryptoSubtle(); + const iKey = await cr.importKey('raw', key, keyParams, true, ['encrypt']); + const ciphertext = await cr.encrypt(cryptParams, iKey, plaintext); + return new Uint8Array(ciphertext); + }, + async decrypt(key, keyParams, cryptParams, ciphertext) { + const cr = getWebcryptoSubtle(); + const iKey = await cr.importKey('raw', key, keyParams, true, ['decrypt']); + const plaintext = await cr.decrypt(cryptParams, iKey, ciphertext); + return new Uint8Array(plaintext); + }, +}; +const mode = { + CBC: 'AES-CBC', + CTR: 'AES-CTR', + GCM: 'AES-GCM', +}; +function getCryptParams(algo, nonce, AAD) { + if (algo === mode.CBC) + return { name: mode.CBC, iv: nonce }; + if (algo === mode.CTR) + return { name: mode.CTR, counter: nonce, length: 64 }; + if (algo === mode.GCM) { + if (AAD) + return { name: mode.GCM, iv: nonce, additionalData: AAD }; + else + return { name: mode.GCM, iv: nonce }; + } + throw new Error('unknown aes block mode'); +} +function generate(algo) { + return (key, nonce, AAD) => { + abytes(key); + abytes(nonce); + const keyParams = { name: algo, length: key.length * 8 }; + const cryptParams = getCryptParams(algo, nonce, AAD); + return { + // keyLength, + encrypt(plaintext) { + abytes(plaintext); + return utils.encrypt(key, keyParams, cryptParams, plaintext); + }, + decrypt(ciphertext) { + abytes(ciphertext); + return utils.decrypt(key, keyParams, cryptParams, ciphertext); + }, + }; + }; +} +export const cbc = generate(mode.CBC); +export const ctr = generate(mode.CTR); +export const gcm = generate(mode.GCM); +// // Type tests +// import { siv, gcm, ctr, ecb, cbc } from '../aes.js'; +// import { xsalsa20poly1305 } from '../salsa.js'; +// import { chacha20poly1305, xchacha20poly1305 } from '../chacha.js'; +// const wsiv = managedNonce(siv); +// const wgcm = managedNonce(gcm); +// const wctr = managedNonce(ctr); +// const wcbc = managedNonce(cbc); +// const wsalsapoly = managedNonce(xsalsa20poly1305); +// const wchacha = managedNonce(chacha20poly1305); +// const wxchacha = managedNonce(xchacha20poly1305); +// // should fail +// const wcbc2 = managedNonce(managedNonce(cbc)); +// const wecb = managedNonce(ecb); +//# sourceMappingURL=webcrypto.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/esm/webcrypto.js.map b/node_modules/@noble/ciphers/esm/webcrypto.js.map new file mode 100644 index 0000000..453d0db --- /dev/null +++ b/node_modules/@noble/ciphers/esm/webcrypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"webcrypto.js","sourceRoot":"","sources":["../src/webcrypto.ts"],"names":[],"mappings":"AAAA,oFAAoF;AACpF,sEAAsE;AACtE,mEAAmE;AACnE,8DAA8D;AAC9D,+DAA+D;AAC/D,8DAA8D;AAC9D,EAAE;AACF,mEAAmE;AACnE,OAAO,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AACxE,OAAO,EAAuB,WAAW,EAAE,MAAM,YAAY,CAAC;AAC9D,OAAO,EAAE,MAAM,EAAE,KAAK,IAAI,MAAM,EAAE,MAAM,cAAc,CAAC;AAEvD;;GAEG;AACH,OAAO,EAAE,WAAW,EAAE,kBAAkB,EAAE,CAAC;AAe3C,qDAAqD;AACrD,MAAM,UAAU,YAAY,CAA4B,EAAK;IAC3D,MAAM,CAAC,EAAE,CAAC,WAAW,CAAC,CAAC;IACvB,OA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kC;AAClC,qDAAqD;AACrD,kDAAkD;AAClD,oDAAoD;AAEpD,iBAAiB;AACjB,iDAAiD;AACjD,kCAAkC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/ff1.d.ts b/node_modules/@noble/ciphers/ff1.d.ts new file mode 100644 index 0000000..d90be00 --- /dev/null +++ b/node_modules/@noble/ciphers/ff1.d.ts @@ -0,0 +1,7 @@ +import { Cipher } from './utils.js'; +export declare function FF1(radix: number, key: Uint8Array, tweak?: Uint8Array): { + encrypt(x: number[]): number[]; + decrypt(x: number[]): number[]; +}; +export declare function BinaryFF1(key: Uint8Array, tweak?: Uint8Array): Cipher; +//# sourceMappingURL=ff1.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/ff1.d.ts.map b/node_modules/@noble/ciphers/ff1.d.ts.map new file mode 100644 index 0000000..42d67b2 --- /dev/null +++ b/node_modules/@noble/ciphers/ff1.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ff1.d.ts","sourceRoot":"","sources":["src/ff1.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAoC,MAAM,YAAY,CAAC;AA0FtE,wBAAgB,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,UAAU,EAAE,KAAK,GAAE,UAAsB;eAGlE,MAAM,EAAE;eAUR,MAAM,EAAE;EAgBtB;AAqBD,wBAAgB,SAAS,CAAC,GAAG,EAAE,UAAU,EAAE,KAAK,GAAE,UAAsB,GAAG,MAAM,CAMhF"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/ff1.js b/node_modules/@noble/ciphers/ff1.js new file mode 100644 index 0000000..38018e7 --- /dev/null +++ b/node_modules/@noble/ciphers/ff1.js @@ -0,0 +1,154 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BinaryFF1 = exports.FF1 = void 0; +const utils_js_1 = require("./utils.js"); +const aes_js_1 = require("./aes.js"); +// NOTE: no point in inlining encrypt instead of encryptBlock, since BigInt stuff will be slow +const { expandKeyLE, encryptBlock } = aes_js_1.unsafe; +// Format-preserving encryption algorithm (FPE-FF1) specified in NIST Special Publication 800-38G. +// https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf +const BLOCK_LEN = 16; +function mod(a, b) { + const result = a % b; + return result >= 0 ? result : b + result; +} +function NUMradix(radix, data) { + let res = BigInt(0); + for (let i of data) + res = res * BigInt(radix) + BigInt(i); + return res; +} +function getRound(radix, key, tweak, x) { + if (radix > 2 ** 16 - 1) + throw new Error(`Invalid radix: ${radix}`); + // radix**minlen ≥ 100 + const minLen = Math.ceil(Math.log(100) / Math.log(radix)); + const maxLen = 2 ** 32 - 1; + // 2 ≤ minlen ≤ maxlen < 2**32 + if (2 > minLen || minLen > maxLen || maxLen >= 2 ** 32) + throw new Error('Invalid radix: 2 ≤ minlen ≤ maxlen < 2**32'); + if (x.length < minLen || x.length > maxLen) + throw new Error('X is outside minLen..maxLen bounds'); + const u = Math.floor(x.length / 2); + const v = x.length - u; + const b = Math.ceil(Math.ceil(v * Math.log2(radix)) / 8); + const d = 4 * Math.ceil(b / 4) + 4; + const padding = mod(-tweak.length - b - 1, 16); + // P = [1]1 || [2]1 || [1]1 || [radix]3 || [10]1 || [u mod 256]1 || [n]4 || [t]4. + const P = new Uint8Array([1, 2, 1, 0, 0, 0, 10, u, 0, 0, 0, 0, 0, 0, 0, 0]); + const view = new DataView(P.buffer); + view.setUint16(4, radix, false); + view.setUint32(8, x.length, false); + view.setUint32(12, tweak.length, false); + // Q = T || [0](−t−b−1) mod 16 || [i]1 || [NUMradix(B)]b. + const PQ = new Uint8Array(P.length + tweak.length + padding + 1 + b); + PQ.set(P); + P.fill(0); + PQ.set(tweak, P.length); + const xk = expandKeyLE(key); + const round = (A, B, i, decrypt = false) => { + // Q = ... || [i]1 || [NUMradix(B)]b. + PQ[PQ.length - b - 1] = i; + if (b) + PQ.set((0, utils_js_1.numberToBytesBE)(NUMradix(radix, B), b), PQ.length - b); + // PRF + let r = new Uint8Array(16); + for (let j = 0; j < PQ.length / BLOCK_LEN; j++) { + for (let i = 0; i < BLOCK_LEN; i++) + r[i] ^= PQ[j * BLOCK_LEN + i]; + encryptBlock(xk, r); + } + // Let S be the first d bytes of the following string of ⎡d/16⎤ blocks: + // R || CIPHK(R ⊕[1]16) || CIPHK(R ⊕[2]16) ...CIPHK(R ⊕[⎡d / 16⎤ – 1]16). + let s = Array.from(r); + for (let j = 1; s.length < d; j++) { + const block = (0, utils_js_1.numberToBytesBE)(BigInt(j), 16); + for (let k = 0; k < BLOCK_LEN; k++) + block[k] ^= r[k]; + s.push(...Array.from(encryptBlock(xk, block))); + } + let y = (0, utils_js_1.bytesToNumberBE)(Uint8Array.from(s.slice(0, d))); + s.fill(0); + if (decrypt) + y = -y; + const m = i % 2 === 0 ? u : v; + let c = mod(NUMradix(radix, A) + y, BigInt(radix) ** BigInt(m)); + // STR(radix, m, c) + const C = Array(m).fill(0); + for (let i = 0; i < m; i++, c /= BigInt(radix)) + C[m - 1 - i] = Number(c % BigInt(radix)); + A.fill(0); + A = B; + B = C; + return [A, B]; + }; + const destroy = () => { + xk.fill(0); + PQ.fill(0); + }; + return { u, round, destroy }; +} +const EMPTY_BUF = new Uint8Array([]); +function FF1(radix, key, tweak = EMPTY_BUF) { + const PQ = getRound.bind(null, radix, key, tweak); + return { + encrypt(x) { + const { u, round, destroy } = PQ(x); + let [A, B] = [x.slice(0, u), x.slice(u)]; + for (let i = 0; i < 10; i++) + [A, B] = round(A, B, i); + destroy(); + const res = A.concat(B); + A.fill(0); + B.fill(0); + return res; + }, + decrypt(x) { + const { u, round, destroy } = PQ(x); + // The FF1.Decrypt algorithm is similar to the FF1.Encrypt algorithm; + // the differences are in Step 6, where: + // 1) the order of the indices is reversed, + // 2) the roles of A and B are swapped + // 3) modular addition is replaced by modular subtraction, in Step 6vi. + let [B, A] = [x.slice(0, u), x.slice(u)]; + for (let i = 9; i >= 0; i--) + [A, B] = round(A, B, i, true); + destroy(); + const res = B.concat(A); + A.fill(0); + B.fill(0); + return res; + }, + }; +} +exports.FF1 = FF1; +// Binary string which encodes each byte in little-endian byte order +const binLE = { + encode(bytes) { + const x = []; + for (let i = 0; i < bytes.length; i++) { + for (let j = 0, tmp = bytes[i]; j < 8; j++, tmp >>= 1) + x.push(tmp & 1); + } + return x; + }, + decode(b) { + if (b.length % 8) + throw new Error('Invalid binary string'); + const res = new Uint8Array(b.length / 8); + for (let i = 0, j = 0; i < res.length; i++) { + res[i] = b[j++] | (b[j++] << 1) | (b[j++] << 2) | (b[j++] << 3); + res[i] |= (b[j++] << 4) | (b[j++] << 5) | (b[j++] << 6) | (b[j++] << 7); + } + return res; + }, +}; +function BinaryFF1(key, tweak = EMPTY_BUF) { + const ff1 = FF1(2, key, tweak); + return { + encrypt: (x) => binLE.decode(ff1.encrypt(binLE.encode(x))), + decrypt: (x) => binLE.decode(ff1.decrypt(binLE.encode(x))), + }; +} +exports.BinaryFF1 = BinaryFF1; +//# sourceMappingURL=ff1.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/ff1.js.map b/node_modules/@noble/ciphers/ff1.js.map new file mode 100644 index 0000000..0b5aa51 --- /dev/null +++ b/node_modules/@noble/ciphers/ff1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ff1.js","sourceRoot":"","sources":["src/ff1.ts"],"names":[],"mappings":";;;AAAA,yCAAsE;AACtE,qCAAkC;AAClC,8FAA8F;AAC9F,MAAM,EAAE,WAAW,EAAE,YAAY,EAAE,GAAG,eAAM,CAAC;AAE7C,kGAAkG;AAClG,4EAA4E;AAE5E,MAAM,SAAS,GAAG,EAAE,CAAC;AAKrB,SAAS,GAAG,CAAC,CAAM,EAAE,CAAM;IACzB,MAAM,MAAM,GAAG,CAAC,GAAG,CAAC,CAAC;IACrB,OAAO,MAAM,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC;AAC3C,CAAC;AAED,S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,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YAC3C,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;YAChE,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;QAC1E,CAAC;QACD,OAAO,GAAG,CAAC;IACb,CAAC;CACF,CAAC;AAEF,SAAgB,SAAS,CAAC,GAAe,EAAE,QAAoB,SAAS;IACtE,MAAM,GAAG,GAAG,GAAG,CAAC,CAAC,EAAE,GAAG,EAAE,KAAK,CAAC,CAAC;IAC/B,OAAO;QACL,OAAO,EAAE,CAAC,CAAa,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QACtE,OAAO,EAAE,CAAC,CAAa,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;KACvE,CAAC;AACJ,CAAC;AAND,8BAMC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/index.d.ts b/node_modules/@noble/ciphers/index.d.ts new file mode 100644 index 0000000..f36479a --- /dev/null +++ b/node_modules/@noble/ciphers/index.d.ts @@ -0,0 +1 @@ +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/index.d.ts.map b/node_modules/@noble/ciphers/index.d.ts.map new file mode 100644 index 0000000..4e8c581 --- /dev/null +++ b/node_modules/@noble/ciphers/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/index.js b/node_modules/@noble/ciphers/index.js new file mode 100644 index 0000000..5a9cbf1 --- /dev/null +++ b/node_modules/@noble/ciphers/index.js @@ -0,0 +1,3 @@ +"use strict"; +throw new Error('noble-ciphers have no entry-point: consult README for usage'); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/index.js.map b/node_modules/@noble/ciphers/index.js.map new file mode 100644 index 0000000..e3396da --- /dev/null +++ b/node_modules/@noble/ciphers/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":";AAAA,MAAM,IAAI,KAAK,CAAC,6DAA6D,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/package.json b/node_modules/@noble/ciphers/package.json new file mode 100644 index 0000000..e2b2dd2 --- /dev/null +++ b/node_modules/@noble/ciphers/package.json @@ -0,0 +1,126 @@ +{ + "name": "@noble/ciphers", + "version": "0.5.3", + "description": "Auditable & minimal JS implementation of Salsa20, ChaCha and AES", + "files": ["esm", "src", "*.js", "*.js.map", "*.d.ts", "*.d.ts.map"], + "scripts": { + "bench": "node benchmark/aead.js noble && node benchmark/ciphers.js noble", + "bench:all": "node benchmark/{aead,ciphers,poly}.js", + "bench:install": "cd benchmark && npm install && cd ../../", + "build": "npm run build:clean; tsc && tsc -p tsconfig.esm.json", + "build:release": "cd build && npm i && npm run build", + "build:clean": "rm *.{js,d.ts,js.map,d.ts.map} esm/*.{js,d.ts,js.map,d.ts.map} 2> /dev/null", + "lint": "prettier --check 'src/**/*.{js,ts}' 'test/**/*.{js,ts,mjs}'", + "format": "prettier --write 'src/**/*.{js,ts}' 'test/**/*.{js,ts,mjs}'", + "test": "node test/index.js" + }, + "author": "Paul Miller (https://paulmillr.com)", + "homepage": "https://paulmillr.com/noble/", + "repository": { + "type": "git", + "url": "git+https://github.com/paulmillr/noble-ciphers.git" + }, + "license": "MIT", + "sideEffects": false, + "devDependencies": { + "@paulmillr/jsbt": "0.1.0", + "@scure/base": "1.1.3", + "fast-check": "3.0.0", + "micro-bmark": "0.3.1", + "micro-should": "0.4.0", + "prettier": "3.1.1", + "typescript": "5.3.2" + }, + "main": "index.js", + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./esm/index.js", + "default": "./index.js" + }, + "./_micro": { + "types": "./_micro.d.ts", + "import": "./esm/_micro.js", + "default": "./_micro.js" + }, + "./_poly1305": { + "types": "./_poly1305.d.ts", + "import": "./esm/_poly1305.js", + "default": "./_poly1305.js" + }, + "./_polyval": { + "types": "./_polyval.d.ts", + "import": "./esm/_polyval.js", + "default": "./_polyval.js" + }, + "./crypto": { + "types": "./crypto.d.ts", + "node": { + "import": "./esm/cryptoNode.js", + "default": "./cryptoNode.js" + }, + "import": "./esm/crypto.js", + "default": "./crypto.js" + }, + "./aes": { + "types": "./aes.d.ts", + "import": "./esm/aes.js", + "default": "./aes.js" + }, + "./chacha": { + "types": "./chacha.d.ts", + "import": "./esm/chacha.js", + "default": "./chacha.js" + }, + "./salsa": { + "types": "./salsa.d.ts", + "import": "./esm/salsa.js", + "default": "./salsa.js" + }, + "./ff1": { + "types": "./ff1.d.ts", + "import": "./esm/ff1.js", + "default": "./ff1.js" + }, + "./utils": { + "types": "./utils.d.ts", + "import": "./esm/utils.js", + "default": "./utils.js" + }, + "./index": { + "types": "./index.d.ts", + "import": "./esm/index.js", + "default": "./index.js" + }, + "./webcrypto": { + "types": "./webcrypto.d.ts", + "import": "./esm/webcrypto.js", + "default": "./webcrypto.js" + } + }, + "browser": { + "node:crypto": false, + "./crypto": "./crypto.js" + }, + "keywords": [ + "salsa20", + "chacha", + "aes", + "cryptography", + "crypto", + "noble", + "cipher", + "ciphers", + "xsalsa20", + "xchacha20", + "poly1305", + "xsalsa20poly1305", + "chacha20poly1305", + "xchacha20poly1305", + "secretbox", + "rijndael", + "siv", + "ff1" + ], + "funding": "https://paulmillr.com/funding/" +} diff --git a/node_modules/@noble/ciphers/salsa.d.ts b/node_modules/@noble/ciphers/salsa.d.ts new file mode 100644 index 0000000..2741141 --- /dev/null +++ b/node_modules/@noble/ciphers/salsa.d.ts @@ -0,0 +1,36 @@ +import { Cipher } from './utils.js'; +/** + * hsalsa hashing function, used primarily in xsalsa, to hash + * key and nonce into key' and nonce'. + * Same as salsaCore, but there doesn't seem to be a way to move the block + * out without 25% performance hit. + */ +export declare function hsalsa(s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array): void; +/** + * Salsa20 from original paper. + * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance. + */ +export declare const salsa20: import("./utils.js").XorStream; +/** + * xsalsa20 eXtended-nonce salsa. + * With 24-byte nonce, it's safe to use fill it with random (CSPRNG). + */ +export declare const xsalsa20: import("./utils.js").XorStream; +/** + * xsalsa20-poly1305 eXtended-nonce salsa. + * With 24-byte nonce, it's safe to use fill it with random (CSPRNG). + * Also known as secretbox from libsodium / nacl. + */ +export declare const xsalsa20poly1305: ((key: Uint8Array, nonce: Uint8Array) => Cipher) & { + blockSize: number; + nonceLength: number; + tagLength: number; +}; +/** + * Alias to xsalsa20poly1305, for compatibility with libsodium / nacl + */ +export declare function secretbox(key: Uint8Array, nonce: Uint8Array): { + seal: (plaintext: Uint8Array) => Uint8Array; + open: (ciphertext: Uint8Array) => Uint8Array; +}; +//# sourceMappingURL=salsa.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/salsa.d.ts.map b/node_modules/@noble/ciphers/salsa.d.ts.map new file mode 100644 index 0000000..aa2f2ed --- /dev/null +++ b/node_modules/@noble/ciphers/salsa.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"salsa.d.ts","sourceRoot":"","sources":["src/salsa.ts"],"names":[],"mappings":"AAGA,OAAO,EAAc,MAAM,EAAc,MAAM,YAAY,CAAC;AAsD5D;;;;;GAKG;AAEH,wBAAgB,MAAM,CACpB,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,GAAG,EAAE,WAAW,QA6BjE;AAED;;;GAGG;AACH,eAAO,MAAM,OAAO,gCAGlB,CAAC;AAEH;;;GAGG;AACH,eAAO,MAAM,QAAQ,gCAGnB,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,SAErB,UAAU,SAAS,UAAU,KAAG,MAAM;;;;CAgD7C,CAAC;AAEF;;GAEG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU;;;EAG3D"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/salsa.js b/node_modules/@noble/ciphers/salsa.js new file mode 100644 index 0000000..7e151ce --- /dev/null +++ b/node_modules/@noble/ciphers/salsa.js @@ -0,0 +1,210 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.secretbox = exports.xsalsa20poly1305 = exports.xsalsa20 = exports.salsa20 = exports.hsalsa = void 0; +const _assert_js_1 = require("./_assert.js"); +const _arx_js_1 = require("./_arx.js"); +const _poly1305_js_1 = require("./_poly1305.js"); +const utils_js_1 = require("./utils.js"); +// Salsa20 stream cipher was released in 2005. +// Salsa's goal was to implement AES replacement that does not rely on S-Boxes, +// which are hard to implement in a constant-time manner. +// https://cr.yp.to/snuffle.html, https://cr.yp.to/snuffle/salsafamily-20071225.pdf +/** + * Salsa20 core function. + */ +// prettier-ignore +function salsaCore(s, k, n, out, cnt, rounds = 20) { + // Based on https://cr.yp.to/salsa20.html + let y00 = s[0], y01 = k[0], y02 = k[1], y03 = k[2], // "expa" Key Key Key + y04 = k[3], y05 = s[1], y06 = n[0], y07 = n[1], // Key "nd 3" Nonce Nonce + y08 = cnt, y09 = 0, y10 = s[2], y11 = k[4], // Pos. Pos. "2-by" Key + y12 = k[5], y13 = k[6], y14 = k[7], y15 = s[3]; // Key Key Key "te k" + // Save state to temporary variables + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; + for (let r = 0; r < rounds; r += 2) { + x04 ^= (0, _arx_js_1.rotl)(x00 + x12 | 0, 7); + x08 ^= (0, _arx_js_1.rotl)(x04 + x00 | 0, 9); + x12 ^= (0, _arx_js_1.rotl)(x08 + x04 | 0, 13); + x00 ^= (0, _arx_js_1.rotl)(x12 + x08 | 0, 18); + x09 ^= (0, _arx_js_1.rotl)(x05 + x01 | 0, 7); + x13 ^= (0, _arx_js_1.rotl)(x09 + x05 | 0, 9); + x01 ^= (0, _arx_js_1.rotl)(x13 + x09 | 0, 13); + x05 ^= (0, _arx_js_1.rotl)(x01 + x13 | 0, 18); + x14 ^= (0, _arx_js_1.rotl)(x10 + x06 | 0, 7); + x02 ^= (0, _arx_js_1.rotl)(x14 + x10 | 0, 9); + x06 ^= (0, _arx_js_1.rotl)(x02 + x14 | 0, 13); + x10 ^= (0, _arx_js_1.rotl)(x06 + x02 | 0, 18); + x03 ^= (0, _arx_js_1.rotl)(x15 + x11 | 0, 7); + x07 ^= (0, _arx_js_1.rotl)(x03 + x15 | 0, 9); + x11 ^= (0, _arx_js_1.rotl)(x07 + x03 | 0, 13); + x15 ^= (0, _arx_js_1.rotl)(x11 + x07 | 0, 18); + x01 ^= (0, _arx_js_1.rotl)(x00 + x03 | 0, 7); + x02 ^= (0, _arx_js_1.rotl)(x01 + x00 | 0, 9); + x03 ^= (0, _arx_js_1.rotl)(x02 + x01 | 0, 13); + x00 ^= (0, _arx_js_1.rotl)(x03 + x02 | 0, 18); + x06 ^= (0, _arx_js_1.rotl)(x05 + x04 | 0, 7); + x07 ^= (0, _arx_js_1.rotl)(x06 + x05 | 0, 9); + x04 ^= (0, _arx_js_1.rotl)(x07 + x06 | 0, 13); + x05 ^= (0, _arx_js_1.rotl)(x04 + x07 | 0, 18); + x11 ^= (0, _arx_js_1.rotl)(x10 + x09 | 0, 7); + x08 ^= (0, _arx_js_1.rotl)(x11 + x10 | 0, 9); + x09 ^= (0, _arx_js_1.rotl)(x08 + x11 | 0, 13); + x10 ^= (0, _arx_js_1.rotl)(x09 + x08 | 0, 18); + x12 ^= (0, _arx_js_1.rotl)(x15 + x14 | 0, 7); + x13 ^= (0, _arx_js_1.rotl)(x12 + x15 | 0, 9); + x14 ^= (0, _arx_js_1.rotl)(x13 + x12 | 0, 13); + x15 ^= (0, _arx_js_1.rotl)(x14 + x13 | 0, 18); + } + // Write output + let oi = 0; + out[oi++] = (y00 + x00) | 0; + out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; + out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; + out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; + out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; + out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; + out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; + out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; + out[oi++] = (y15 + x15) | 0; +} +/** + * hsalsa hashing function, used primarily in xsalsa, to hash + * key and nonce into key' and nonce'. + * Same as salsaCore, but there doesn't seem to be a way to move the block + * out without 25% performance hit. + */ +// prettier-ignore +function hsalsa(s, k, i, o32) { + let x00 = s[0], x01 = k[0], x02 = k[1], x03 = k[2], x04 = k[3], x05 = s[1], x06 = i[0], x07 = i[1], x08 = i[2], x09 = i[3], x10 = s[2], x11 = k[4], x12 = k[5], x13 = k[6], x14 = k[7], x15 = s[3]; + for (let r = 0; r < 20; r += 2) { + x04 ^= (0, _arx_js_1.rotl)(x00 + x12 | 0, 7); + x08 ^= (0, _arx_js_1.rotl)(x04 + x00 | 0, 9); + x12 ^= (0, _arx_js_1.rotl)(x08 + x04 | 0, 13); + x00 ^= (0, _arx_js_1.rotl)(x12 + x08 | 0, 18); + x09 ^= (0, _arx_js_1.rotl)(x05 + x01 | 0, 7); + x13 ^= (0, _arx_js_1.rotl)(x09 + x05 | 0, 9); + x01 ^= (0, _arx_js_1.rotl)(x13 + x09 | 0, 13); + x05 ^= (0, _arx_js_1.rotl)(x01 + x13 | 0, 18); + x14 ^= (0, _arx_js_1.rotl)(x10 + x06 | 0, 7); + x02 ^= (0, _arx_js_1.rotl)(x14 + x10 | 0, 9); + x06 ^= (0, _arx_js_1.rotl)(x02 + x14 | 0, 13); + x10 ^= (0, _arx_js_1.rotl)(x06 + x02 | 0, 18); + x03 ^= (0, _arx_js_1.rotl)(x15 + x11 | 0, 7); + x07 ^= (0, _arx_js_1.rotl)(x03 + x15 | 0, 9); + x11 ^= (0, _arx_js_1.rotl)(x07 + x03 | 0, 13); + x15 ^= (0, _arx_js_1.rotl)(x11 + x07 | 0, 18); + x01 ^= (0, _arx_js_1.rotl)(x00 + x03 | 0, 7); + x02 ^= (0, _arx_js_1.rotl)(x01 + x00 | 0, 9); + x03 ^= (0, _arx_js_1.rotl)(x02 + x01 | 0, 13); + x00 ^= (0, _arx_js_1.rotl)(x03 + x02 | 0, 18); + x06 ^= (0, _arx_js_1.rotl)(x05 + x04 | 0, 7); + x07 ^= (0, _arx_js_1.rotl)(x06 + x05 | 0, 9); + x04 ^= (0, _arx_js_1.rotl)(x07 + x06 | 0, 13); + x05 ^= (0, _arx_js_1.rotl)(x04 + x07 | 0, 18); + x11 ^= (0, _arx_js_1.rotl)(x10 + x09 | 0, 7); + x08 ^= (0, _arx_js_1.rotl)(x11 + x10 | 0, 9); + x09 ^= (0, _arx_js_1.rotl)(x08 + x11 | 0, 13); + x10 ^= (0, _arx_js_1.rotl)(x09 + x08 | 0, 18); + x12 ^= (0, _arx_js_1.rotl)(x15 + x14 | 0, 7); + x13 ^= (0, _arx_js_1.rotl)(x12 + x15 | 0, 9); + x14 ^= (0, _arx_js_1.rotl)(x13 + x12 | 0, 13); + x15 ^= (0, _arx_js_1.rotl)(x14 + x13 | 0, 18); + } + let oi = 0; + o32[oi++] = x00; + o32[oi++] = x05; + o32[oi++] = x10; + o32[oi++] = x15; + o32[oi++] = x06; + o32[oi++] = x07; + o32[oi++] = x08; + o32[oi++] = x09; +} +exports.hsalsa = hsalsa; +/** + * Salsa20 from original paper. + * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance. + */ +exports.salsa20 = (0, _arx_js_1.createCipher)(salsaCore, { + allowShortKeys: true, + counterRight: true, +}); +/** + * xsalsa20 eXtended-nonce salsa. + * With 24-byte nonce, it's safe to use fill it with random (CSPRNG). + */ +exports.xsalsa20 = (0, _arx_js_1.createCipher)(salsaCore, { + counterRight: true, + extendNonceFn: hsalsa, +}); +/** + * xsalsa20-poly1305 eXtended-nonce salsa. + * With 24-byte nonce, it's safe to use fill it with random (CSPRNG). + * Also known as secretbox from libsodium / nacl. + */ +exports.xsalsa20poly1305 = (0, utils_js_1.wrapCipher)({ blockSize: 64, nonceLength: 24, tagLength: 16 }, (key, nonce) => { + const tagLength = 16; + (0, _assert_js_1.bytes)(key, 32); + (0, _assert_js_1.bytes)(nonce, 24); + return { + encrypt: (plaintext, output) => { + (0, _assert_js_1.bytes)(plaintext); + // This is small optimization (calculate auth key with same call as encryption itself) makes it hard + // to separate tag calculation and encryption itself, since 32 byte is half-block of salsa (64 byte) + const clength = plaintext.length + 32; + if (output) { + (0, _assert_js_1.bytes)(output, clength); + } + else { + output = new Uint8Array(clength); + } + output.set(plaintext, 32); + (0, exports.xsalsa20)(key, nonce, output, output); + const authKey = output.subarray(0, 32); + const tag = (0, _poly1305_js_1.poly1305)(output.subarray(32), authKey); + // Clean auth key, even though JS provides no guarantees about memory cleaning + output.set(tag, tagLength); + output.subarray(0, tagLength).fill(0); + return output.subarray(tagLength); + }, + decrypt: (ciphertext) => { + (0, _assert_js_1.bytes)(ciphertext); + const clength = ciphertext.length; + if (clength < tagLength) + throw new Error('encrypted data should be at least 16 bytes'); + // Create new ciphertext array: + // auth tag auth tag from ciphertext ciphertext + // [bytes 0..16] [bytes 16..32] [bytes 32..] + // 16 instead of 32, because we already have 16 byte tag + const ciphertext_ = new Uint8Array(clength + tagLength); // alloc + ciphertext_.set(ciphertext, tagLength); + // Each xsalsa20 calls to hsalsa to calculate key, but seems not much perf difference + // Separate call to calculate authkey, since first bytes contains tag + const authKey = (0, exports.xsalsa20)(key, nonce, new Uint8Array(32)); // alloc(32) + const tag = (0, _poly1305_js_1.poly1305)(ciphertext_.subarray(32), authKey); + if (!(0, utils_js_1.equalBytes)(ciphertext_.subarray(16, 32), tag)) + throw new Error('invalid tag'); + const plaintext = (0, exports.xsalsa20)(key, nonce, ciphertext_); // alloc + // Clean auth key, even though JS provides no guarantees about memory cleaning + plaintext.subarray(0, 32).fill(0); + authKey.fill(0); + return plaintext.subarray(32); + }, + }; +}); +/** + * Alias to xsalsa20poly1305, for compatibility with libsodium / nacl + */ +function secretbox(key, nonce) { + const xs = (0, exports.xsalsa20poly1305)(key, nonce); + return { seal: xs.encrypt, open: xs.decrypt }; +} +exports.secretbox = secretbox; +//# sourceMappingURL=salsa.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/salsa.js.map b/node_modules/@noble/ciphers/salsa.js.map new file mode 100644 index 0000000..51f875a --- /dev/null +++ b/node_modules/@noble/ciphers/salsa.js.map @@ -0,0 +1 @@ +{"version":3,"file":"salsa.js","sourceRoot":"","sources":["src/salsa.ts"],"names":[],"mappings":";;;AAAA,6CAA+C;AAC/C,uCAA+C;AAC/C,iDAA0C;AAC1C,yCAA4D;AAE5D,8CAA8C;AAC9C,+EAA+E;AAC/E,y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AAC,CAAC;YACxD,IAAI,CAAC,IAAA,qBAAU,EAAC,WAAW,CAAC,QAAQ,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,GAAG,CAAC;gBAAE,MAAM,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC;YAEnF,MAAM,SAAS,GAAG,IAAA,gBAAQ,EAAC,GAAG,EAAE,KAAK,EAAE,WAAW,CAAC,CAAC,CAAC,QAAQ;YAC7D,8EAA8E;YAC9E,SAAS,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAClC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAChB,OAAO,SAAS,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QAChC,CAAC;KACF,CAAC;AACJ,CAAC,CACF,CAAC;AAEF;;GAEG;AACH,SAAgB,SAAS,CAAC,GAAe,EAAE,KAAiB;IAC1D,MAAM,EAAE,GAAG,IAAA,wBAAgB,EAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACxC,OAAO,EAAE,IAAI,EAAE,EAAE,CAAC,OAAO,EAAE,IAAI,EAAE,EAAE,CAAC,OAAO,EAAE,CAAC;AAChD,CAAC;AAHD,8BAGC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/src/_arx.ts b/node_modules/@noble/ciphers/src/_arx.ts new file mode 100644 index 0000000..f182246 --- /dev/null +++ b/node_modules/@noble/ciphers/src/_arx.ts @@ -0,0 +1,217 @@ +// Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers. +import { number as anumber, bytes as abytes, bool as abool } from './_assert.js'; +import { XorStream, checkOpts, u32 } from './utils.js'; + +/* +RFC8439 requires multi-step cipher stream, where +authKey starts with counter: 0, actual msg with counter: 1. + +For this, we need a way to re-use nonce / counter: + + const counter = new Uint8Array(4); + chacha(..., counter, ...); // counter is now 1 + chacha(..., counter, ...); // counter is now 2 + +This is complicated: + +- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB +- Original papers don't allow mutating counters +- Counter overflow is undefined [^1] +- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it +- Caveat: Cannot be re-used through all cases: +- * chacha has (counter | nonce) +- * xchacha has (nonce16 | counter | nonce16) +- Idea B: separate nonce / counter and provide separate API for counter re-use +- Caveat: there are different counter sizes depending on an algorithm. +- salsa & chacha also differ in structures of key & sigma: + salsa20: s[0] | k(4) | s[1] | nonce(2) | ctr(2) | s[2] | k(4) | s[3] + chacha: s(4) | k(8) | ctr(1) | nonce(3) + chacha20orig: s(4) | k(8) | ctr(2) | nonce(2) +- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)` +- Caveat: we can't re-use counter array + +xchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal +(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce). + +[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ +[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 +*/ + +// We can't make top-level var depend on utils.utf8ToBytes +// because it's not present in all envs. Creating a similar fn here +const _utf8ToBytes = (str: string) => Uint8Array.from(str.split('').map((c) => c.charCodeAt(0))); +const sigma16 = _utf8ToBytes('expand 16-byte k'); +const sigma32 = _utf8ToBytes('expand 32-byte k'); +const sigma16_32 = u32(sigma16); +const sigma32_32 = u32(sigma32); +export const sigma = sigma32_32.slice(); + +export function rotl(a: number, b: number): number { + return (a << b) | (a >>> (32 - b)); +} + +export type CipherCoreFn = ( + sigma: Uint32Array, + key: Uint32Array, + nonce: Uint32Array, + output: Uint32Array, + counter: number, + rounds?: number +) => void; + +export type ExtendNonceFn = ( + sigma: Uint32Array, + key: Uint32Array, + input: Uint32Array, + output: Uint32Array +) => void; + +export type CipherOpts = { + allowShortKeys?: boolean; // Original salsa / chacha allow 16-byte keys + extendNonceFn?: ExtendNonceFn; + counterLength?: number; + counterRight?: boolean; // right: nonce|counter; left: counter|nonce + rounds?: number; +}; + +// Is byte array aligned to 4 byte offset (u32)? +function isAligned32(b: Uint8Array) { + return b.byteOffset % 4 === 0; +} + +// Salsa and Chacha block length is always 512-bit +const BLOCK_LEN = 64; +const BLOCK_LEN32 = 16; + +// new Uint32Array([2**32]) // => Uint32Array(1) [ 0 ] +// new Uint32Array([2**32-1]) // => Uint32Array(1) [ 4294967295 ] +const MAX_COUNTER = 2 ** 32 - 1; + +const U32_EMPTY = new Uint32Array(); +function runCipher( + core: CipherCoreFn, + sigma: Uint32Array, + key: Uint32Array, + nonce: Uint32Array, + data: Uint8Array, + output: Uint8Array, + counter: number, + rounds: number +): void { + const len = data.length; + const block = new Uint8Array(BLOCK_LEN); + const b32 = u32(block); + // Make sure that buffers aligned to 4 bytes + const isAligned = isAligned32(data) && isAligned32(output); + const d32 = isAligned ? u32(data) : U32_EMPTY; + const o32 = isAligned ? u32(output) : U32_EMPTY; + for (let pos = 0; pos < len; counter++) { + core(sigma, key, nonce, b32, counter, rounds); + if (counter >= MAX_COUNTER) throw new Error('arx: counter overflow'); + const take = Math.min(BLOCK_LEN, len - pos); + // aligned to 4 bytes + if (isAligned && take === BLOCK_LEN) { + const pos32 = pos / 4; + if (pos % 4 !== 0) throw new Error('arx: invalid block position'); + for (let j = 0, posj: number; j < BLOCK_LEN32; j++) { + posj = pos32 + j; + o32[posj] = d32[posj] ^ b32[j]; + } + pos += BLOCK_LEN; + continue; + } + for (let j = 0, posj; j < take; j++) { + posj = pos + j; + output[posj] = data[posj] ^ block[j]; + } + pos += take; + } +} + +export function createCipher(core: CipherCoreFn, opts: CipherOpts): XorStream { + const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts( + { allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, + opts + ); + if (typeof core !== 'function') throw new Error('core must be a function'); + anumber(counterLength); + anumber(rounds); + abool(counterRight); + abool(allowShortKeys); + return ( + key: Uint8Array, + nonce: Uint8Array, + data: Uint8Array, + output?: Uint8Array, + counter = 0 + ): Uint8Array => { + abytes(key); + abytes(nonce); + abytes(data); + const len = data.length; + if (!output) output = new Uint8Array(len); + abytes(output); + anumber(counter); + if (counter < 0 || counter >= MAX_COUNTER) throw new Error('arx: counter overflow'); + if (output.length < len) + throw new Error(`arx: output (${output.length}) is shorter than data (${len})`); + const toClean = []; + + // Key & sigma + // key=16 -> sigma16, k=key|key + // key=32 -> sigma32, k=key + let l = key.length, + k: Uint8Array, + sigma: Uint32Array; + if (l === 32) { + k = key.slice(); + toClean.push(k); + sigma = sigma32_32; + } else if (l === 16 && allowShortKeys) { + k = new Uint8Array(32); + k.set(key); + k.set(key, 16); + sigma = sigma16_32; + toClean.push(k); + } else { + throw new Error(`arx: invalid 32-byte key, got length=${l}`); + } + + // Nonce + // salsa20: 8 (8-byte counter) + // chacha20orig: 8 (8-byte counter) + // chacha20: 12 (4-byte counter) + // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce) + // xchacha20: 24 (16 -> hchacha, 8 -> old nonce) + // Align nonce to 4 bytes + if (!isAligned32(nonce)) { + nonce = nonce.slice(); + toClean.push(nonce); + } + + const k32 = u32(k); + // hsalsa & hchacha: handle extended nonce + if (extendNonceFn) { + if (nonce.length !== 24) throw new Error(`arx: extended nonce must be 24 bytes`); + extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32); + nonce = nonce.subarray(16); + } + + // Handle nonce counter + const nonceNcLen = 16 - counterLength; + if (nonceNcLen !== nonce.length) + throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`); + + // Pad counter when nonce is 64 bit + if (nonceNcLen !== 12) { + const nc = new Uint8Array(12); + nc.set(nonce, counterRight ? 0 : 12 - nonce.length); + nonce = nc; + toClean.push(nonce); + } + const n32 = u32(nonce); + runCipher(core, sigma, k32, n32, data, output, counter, rounds); + while (toClean.length > 0) toClean.pop()!.fill(0); + return output; + }; +} diff --git a/node_modules/@noble/ciphers/src/_assert.ts b/node_modules/@noble/ciphers/src/_assert.ts new file mode 100644 index 0000000..e77e0f9 --- /dev/null +++ b/node_modules/@noble/ciphers/src/_assert.ts @@ -0,0 +1,50 @@ +function number(n: number) { + if (!Number.isSafeInteger(n) || n < 0) throw new Error(`positive integer expected, not ${n}`); +} + +function bool(b: boolean) { + if (typeof b !== 'boolean') throw new Error(`boolean expected, not ${b}`); +} + +export function isBytes(a: unknown): a is Uint8Array { + return ( + a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array') + ); +} + +function bytes(b: Uint8Array | undefined, ...lengths: number[]) { + if (!isBytes(b)) throw new Error('Uint8Array expected'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`); +} + +export type Hash = { + (data: Uint8Array): Uint8Array; + blockLen: number; + outputLen: number; + create: any; +}; +function hash(hash: Hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') + throw new Error('hash must be wrapped by utils.wrapConstructor'); + number(hash.outputLen); + number(hash.blockLen); +} + +function exists(instance: any, checkFinished = true) { + if (instance.destroyed) throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called'); +} + +function output(out: any, instance: any) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} + +export { number, bool, bytes, hash, exists, output }; +const assert = { number, bool, bytes, hash, exists, output }; +export default assert; diff --git a/node_modules/@noble/ciphers/src/_micro.ts b/node_modules/@noble/ciphers/src/_micro.ts new file mode 100644 index 0000000..77e42ee --- /dev/null +++ b/node_modules/@noble/ciphers/src/_micro.ts @@ -0,0 +1,325 @@ +/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */ +// prettier-ignore +import { + Cipher, XorStream, createView, setBigUint64, wrapCipher, + bytesToHex, concatBytes, equalBytes, hexToNumber, numberToBytesBE, +} from './utils.js'; +import { createCipher, rotl } from './_arx.js'; +import { bytes as abytes } from './_assert.js'; + +/* +noble-ciphers-micro: more auditable, but slower version of salsa20, chacha & poly1305. +Implements the same algorithms that are present in other files, but without +unrolled loops (https://en.wikipedia.org/wiki/Loop_unrolling). +*/ + +function bytesToNumberLE(bytes: Uint8Array): bigint { + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); +} + +function numberToBytesLE(n: number | bigint, len: number): Uint8Array { + return numberToBytesBE(n, len).reverse(); +} + +function salsaQR(x: Uint32Array, a: number, b: number, c: number, d: number) { + x[b] ^= rotl((x[a] + x[d]) | 0, 7); + x[c] ^= rotl((x[b] + x[a]) | 0, 9); + x[d] ^= rotl((x[c] + x[b]) | 0, 13); + x[a] ^= rotl((x[d] + x[c]) | 0, 18); +} +// prettier-ignore +function chachaQR(x: Uint32Array, a: number, b: number, c: number, d: number) { + x[a] = (x[a] + x[b]) | 0; x[d] = rotl(x[d] ^ x[a], 16); + x[c] = (x[c] + x[d]) | 0; x[b] = rotl(x[b] ^ x[c], 12); + x[a] = (x[a] + x[b]) | 0; x[d] = rotl(x[d] ^ x[a], 8); + x[c] = (x[c] + x[d]) | 0; x[b] = rotl(x[b] ^ x[c], 7); +} + +function salsaRound(x: Uint32Array, rounds = 20) { + for (let r = 0; r < rounds; r += 2) { + salsaQR(x, 0, 4, 8, 12); + salsaQR(x, 5, 9, 13, 1); + salsaQR(x, 10, 14, 2, 6); + salsaQR(x, 15, 3, 7, 11); + salsaQR(x, 0, 1, 2, 3); + salsaQR(x, 5, 6, 7, 4); + salsaQR(x, 10, 11, 8, 9); + salsaQR(x, 15, 12, 13, 14); + } +} + +function chachaRound(x: Uint32Array, rounds = 20) { + for (let r = 0; r < rounds; r += 2) { + chachaQR(x, 0, 4, 8, 12); + chachaQR(x, 1, 5, 9, 13); + chachaQR(x, 2, 6, 10, 14); + chachaQR(x, 3, 7, 11, 15); + chachaQR(x, 0, 5, 10, 15); + chachaQR(x, 1, 6, 11, 12); + chachaQR(x, 2, 7, 8, 13); + chachaQR(x, 3, 4, 9, 14); + } +} + +function salsaCore( + s: Uint32Array, + k: Uint32Array, + n: Uint32Array, + out: Uint32Array, + cnt: number, + rounds = 20 +): void { + // prettier-ignore + const y = new Uint32Array([ + s[0], k[0], k[1], k[2], // "expa" Key Key Key + k[3], s[1], n[0], n[1], // Key "nd 3" Nonce Nonce + cnt, 0 , s[2], k[4], // Pos. Pos. "2-by" Key + k[5], k[6], k[7], s[3], // Key Key Key "te k" + ]); + const x = y.slice(); + salsaRound(x, rounds); + for (let i = 0; i < 16; i++) out[i] = (y[i] + x[i]) | 0; +} + +// prettier-ignore +export function hsalsa(s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array) { + const x = new Uint32Array([ + s[0], k[0], k[1], k[2], + k[3], s[1], i[0], i[1], + i[2], i[3], s[2], k[4], + k[5], k[6], k[7], s[3] + ]); + salsaRound(x, 20); + let oi = 0; + o32[oi++] = x[0]; o32[oi++] = x[5]; + o32[oi++] = x[10]; o32[oi++] = x[15]; + o32[oi++] = x[6]; o32[oi++] = x[7]; + o32[oi++] = x[8]; o32[oi++] = x[9]; +} + +function chachaCore( + s: Uint32Array, + k: Uint32Array, + n: Uint32Array, + out: Uint32Array, + cnt: number, + rounds = 20 +): void { + // prettier-ignore + const y = new Uint32Array([ + s[0], s[1], s[2], s[3], // "expa" "nd 3" "2-by" "te k" + k[0], k[1], k[2], k[3], // Key Key Key Key + k[4], k[5], k[6], k[7], // Key Key Key Key + cnt, n[0], n[1], n[2], // Counter Counter Nonce Nonce + ]); + const x = y.slice(); + chachaRound(x, rounds); + for (let i = 0; i < 16; i++) out[i] = (y[i] + x[i]) | 0; +} + +// prettier-ignore +export function hchacha(s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array) { + const x = new Uint32Array([ + s[0], s[1], s[2], s[3], + k[0], k[1], k[2], k[3], + k[4], k[5], k[6], k[7], + i[0], i[1], i[2], i[3], + ]); + chachaRound(x, 20); + let oi = 0; + o32[oi++] = x[0]; o32[oi++] = x[1]; + o32[oi++] = x[2]; o32[oi++] = x[3]; + o32[oi++] = x[12]; o32[oi++] = x[13]; + o32[oi++] = x[14]; o32[oi++] = x[15]; +} + +/** + * salsa20, 12-byte nonce. + */ +export const salsa20 = /* @__PURE__ */ createCipher(salsaCore, { + allowShortKeys: true, + counterRight: true, +}); + +/** + * xsalsa20, 24-byte nonce. + */ +export const xsalsa20 = /* @__PURE__ */ createCipher(salsaCore, { + counterRight: true, + extendNonceFn: hsalsa, +}); + +/** + * chacha20 non-RFC, original version by djb. 8-byte nonce, 8-byte counter. + */ +export const chacha20orig = /* @__PURE__ */ createCipher(chachaCore, { + allowShortKeys: true, + counterRight: false, + counterLength: 8, +}); + +/** + * chacha20 RFC 8439 (IETF / TLS). 12-byte nonce, 4-byte counter. + */ +export const chacha20 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 4, +}); + +/** + * xchacha20 eXtended-nonce. https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha + */ +export const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 8, + extendNonceFn: hchacha, +}); + +/** + * 8-round chacha from the original paper. + */ +export const chacha8 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 4, + rounds: 8, +}); + +/** + * 12-round chacha from the original paper. + */ +export const chacha12 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 4, + rounds: 12, +}); + +const POW_2_130_5 = BigInt(2) ** BigInt(130) - BigInt(5); +const POW_2_128_1 = BigInt(2) ** BigInt(16 * 8) - BigInt(1); +const CLAMP_R = BigInt('0x0ffffffc0ffffffc0ffffffc0fffffff'); +const _0 = BigInt(0); +const _1 = BigInt(1); +// Can be speed-up using BigUint64Array, but would be more complicated +export function poly1305(msg: Uint8Array, key: Uint8Array): Uint8Array { + abytes(msg); + abytes(key); + let acc = _0; + const r = bytesToNumberLE(key.subarray(0, 16)) & CLAMP_R; + const s = bytesToNumberLE(key.subarray(16)); + // Process by 16 byte chunks + for (let i = 0; i < msg.length; i += 16) { + const m = msg.subarray(i, i + 16); + const n = bytesToNumberLE(m) | (_1 << BigInt(8 * m.length)); + acc = ((acc + n) * r) % POW_2_130_5; + } + const res = (acc + s) & POW_2_128_1; + return numberToBytesLE(res, 16); +} + +function computeTag( + fn: XorStream, + key: Uint8Array, + nonce: Uint8Array, + ciphertext: Uint8Array, + AAD?: Uint8Array +): Uint8Array { + const res = []; + if (AAD) { + res.push(AAD); + const leftover = AAD.length % 16; + if (leftover > 0) res.push(new Uint8Array(16 - leftover)); + } + res.push(ciphertext); + const leftover = ciphertext.length % 16; + if (leftover > 0) res.push(new Uint8Array(16 - leftover)); + // Lengths + const num = new Uint8Array(16); + const view = createView(num); + setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true); + setBigUint64(view, 8, BigInt(ciphertext.length), true); + res.push(num); + const authKey = fn(key, nonce, new Uint8Array(32)); + return poly1305(concatBytes(...res), authKey); +} + +/** + * xsalsa20-poly1305 eXtended-nonce (24 bytes) salsa. + */ +export const xsalsa20poly1305 = /* @__PURE__ */ wrapCipher( + { blockSize: 64, nonceLength: 24, tagLength: 16 }, + function xsalsa20poly1305(key: Uint8Array, nonce: Uint8Array) { + abytes(key); + abytes(nonce); + return { + encrypt: (plaintext: Uint8Array) => { + abytes(plaintext); + const m = concatBytes(new Uint8Array(32), plaintext); + const c = xsalsa20(key, nonce, m); + const authKey = c.subarray(0, 32); + const data = c.subarray(32); + const tag = poly1305(data, authKey); + return concatBytes(tag, data); + }, + decrypt: (ciphertext: Uint8Array) => { + abytes(ciphertext); + if (ciphertext.length < 16) throw new Error('encrypted data must be at least 16 bytes'); + const c = concatBytes(new Uint8Array(16), ciphertext); + const authKey = xsalsa20(key, nonce, new Uint8Array(32)); + const tag = poly1305(c.subarray(32), authKey); + if (!equalBytes(c.subarray(16, 32), tag)) throw new Error('invalid poly1305 tag'); + return xsalsa20(key, nonce, c).subarray(32); + }, + }; + } +); + +/** + * Alias to xsalsa20-poly1305 + */ +export function secretbox(key: Uint8Array, nonce: Uint8Array) { + const xs = xsalsa20poly1305(key, nonce); + return { seal: xs.encrypt, open: xs.decrypt }; +} + +export const _poly1305_aead = + (fn: XorStream) => + (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): Cipher => { + const tagLength = 16; + const keyLength = 32; + abytes(key, keyLength); + abytes(nonce); + return { + encrypt: (plaintext: Uint8Array) => { + abytes(plaintext); + const res = fn(key, nonce, plaintext, undefined, 1); + const tag = computeTag(fn, key, nonce, res, AAD); + return concatBytes(res, tag); + }, + decrypt: (ciphertext: Uint8Array) => { + abytes(ciphertext); + if (ciphertext.length < tagLength) + throw new Error(`encrypted data must be at least ${tagLength} bytes`); + const passedTag = ciphertext.subarray(-tagLength); + const data = ciphertext.subarray(0, -tagLength); + const tag = computeTag(fn, key, nonce, data, AAD); + if (!equalBytes(passedTag, tag)) throw new Error('invalid poly1305 tag'); + return fn(key, nonce, data, undefined, 1); + }, + }; + }; + +/** + * chacha20-poly1305 12-byte-nonce chacha. + */ +export const chacha20poly1305 = /* @__PURE__ */ wrapCipher( + { blockSize: 64, nonceLength: 12, tagLength: 16 }, + _poly1305_aead(chacha20) +); + +/** + * xchacha20-poly1305 eXtended-nonce (24 bytes) chacha. + * With 24-byte nonce, it's safe to use fill it with random (CSPRNG). + */ +export const xchacha20poly1305 = /* @__PURE__ */ wrapCipher( + { blockSize: 64, nonceLength: 24, tagLength: 16 }, + _poly1305_aead(xchacha20) +); diff --git a/node_modules/@noble/ciphers/src/_poly1305.ts b/node_modules/@noble/ciphers/src/_poly1305.ts new file mode 100644 index 0000000..7376cb9 --- /dev/null +++ b/node_modules/@noble/ciphers/src/_poly1305.ts @@ -0,0 +1,286 @@ +import { exists as aexists, bytes as abytes, output as aoutput } from './_assert.js'; +import { Input, toBytes, Hash } from './utils.js'; + +// Poly1305 is a fast and parallel secret-key message-authentication code. +// https://cr.yp.to/mac.html, https://cr.yp.to/mac/poly1305-20050329.pdf +// https://datatracker.ietf.org/doc/html/rfc8439 + +// Based on Public Domain poly1305-donna https://github.com/floodyberry/poly1305-donna +const u8to16 = (a: Uint8Array, i: number) => (a[i++] & 0xff) | ((a[i++] & 0xff) << 8); +class Poly1305 implements Hash { + readonly blockLen = 16; + readonly outputLen = 16; + private buffer = new Uint8Array(16); + private r = new Uint16Array(10); + private h = new Uint16Array(10); + private pad = new Uint16Array(8); + private pos = 0; + protected finished = false; + + constructor(key: Input) { + key = toBytes(key); + abytes(key, 32); + const t0 = u8to16(key, 0); + const t1 = u8to16(key, 2); + const t2 = u8to16(key, 4); + const t3 = u8to16(key, 6); + const t4 = u8to16(key, 8); + const t5 = u8to16(key, 10); + const t6 = u8to16(key, 12); + const t7 = u8to16(key, 14); + + // https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47 + this.r[0] = t0 & 0x1fff; + this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; + this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; + this.r[5] = (t4 >>> 1) & 0x1ffe; + this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; + this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + this.r[9] = (t7 >>> 5) & 0x007f; + for (let i = 0; i < 8; i++) this.pad[i] = u8to16(key, 16 + 2 * i); + } + + private process(data: Uint8Array, offset: number, isLast = false) { + const hibit = isLast ? 0 : 1 << 11; + const { h, r } = this; + const r0 = r[0]; + const r1 = r[1]; + const r2 = r[2]; + const r3 = r[3]; + const r4 = r[4]; + const r5 = r[5]; + const r6 = r[6]; + const r7 = r[7]; + const r8 = r[8]; + const r9 = r[9]; + + const t0 = u8to16(data, offset + 0); + const t1 = u8to16(data, offset + 2); + const t2 = u8to16(data, offset + 4); + const t3 = u8to16(data, offset + 6); + const t4 = u8to16(data, offset + 8); + const t5 = u8to16(data, offset + 10); + const t6 = u8to16(data, offset + 12); + const t7 = u8to16(data, offset + 14); + + let h0 = h[0] + (t0 & 0x1fff); + let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff); + let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff); + let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff); + let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff); + let h5 = h[5] + ((t4 >>> 1) & 0x1fff); + let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff); + let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff); + let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff); + let h9 = h[9] + ((t7 >>> 5) | hibit); + + let c = 0; + + let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6); + c = d0 >>> 13; + d0 &= 0x1fff; + d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1); + c += d0 >>> 13; + d0 &= 0x1fff; + + let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7); + c = d1 >>> 13; + d1 &= 0x1fff; + d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2); + c += d1 >>> 13; + d1 &= 0x1fff; + + let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8); + c = d2 >>> 13; + d2 &= 0x1fff; + d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3); + c += d2 >>> 13; + d2 &= 0x1fff; + + let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9); + c = d3 >>> 13; + d3 &= 0x1fff; + d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4); + c += d3 >>> 13; + d3 &= 0x1fff; + + let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0; + c = d4 >>> 13; + d4 &= 0x1fff; + d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5); + c += d4 >>> 13; + d4 &= 0x1fff; + + let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1; + c = d5 >>> 13; + d5 &= 0x1fff; + d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6); + c += d5 >>> 13; + d5 &= 0x1fff; + + let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2; + c = d6 >>> 13; + d6 &= 0x1fff; + d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7); + c += d6 >>> 13; + d6 &= 0x1fff; + + let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3; + c = d7 >>> 13; + d7 &= 0x1fff; + d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8); + c += d7 >>> 13; + d7 &= 0x1fff; + + let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4; + c = d8 >>> 13; + d8 &= 0x1fff; + d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9); + c += d8 >>> 13; + d8 &= 0x1fff; + + let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5; + c = d9 >>> 13; + d9 &= 0x1fff; + d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0; + c += d9 >>> 13; + d9 &= 0x1fff; + + c = ((c << 2) + c) | 0; + c = (c + d0) | 0; + d0 = c & 0x1fff; + c = c >>> 13; + d1 += c; + + h[0] = d0; + h[1] = d1; + h[2] = d2; + h[3] = d3; + h[4] = d4; + h[5] = d5; + h[6] = d6; + h[7] = d7; + h[8] = d8; + h[9] = d9; + } + + private finalize() { + const { h, pad } = this; + const g = new Uint16Array(10); + let c = h[1] >>> 13; + h[1] &= 0x1fff; + for (let i = 2; i < 10; i++) { + h[i] += c; + c = h[i] >>> 13; + h[i] &= 0x1fff; + } + h[0] += c * 5; + c = h[0] >>> 13; + h[0] &= 0x1fff; + h[1] += c; + c = h[1] >>> 13; + h[1] &= 0x1fff; + h[2] += c; + + g[0] = h[0] + 5; + c = g[0] >>> 13; + g[0] &= 0x1fff; + for (let i = 1; i < 10; i++) { + g[i] = h[i] + c; + c = g[i] >>> 13; + g[i] &= 0x1fff; + } + g[9] -= 1 << 13; + + let mask = (c ^ 1) - 1; + for (let i = 0; i < 10; i++) g[i] &= mask; + mask = ~mask; + for (let i = 0; i < 10; i++) h[i] = (h[i] & mask) | g[i]; + h[0] = (h[0] | (h[1] << 13)) & 0xffff; + h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff; + h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff; + h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff; + h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff; + h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff; + h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff; + h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff; + + let f = h[0] + pad[0]; + h[0] = f & 0xffff; + for (let i = 1; i < 8; i++) { + f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0; + h[i] = f & 0xffff; + } + } + update(data: Input): this { + aexists(this); + const { buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input + if (take === blockLen) { + for (; blockLen <= len - pos; pos += blockLen) this.process(data, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(buffer, 0, false); + this.pos = 0; + } + } + return this; + } + destroy() { + this.h.fill(0); + this.r.fill(0); + this.buffer.fill(0); + this.pad.fill(0); + } + digestInto(out: Uint8Array) { + aexists(this); + aoutput(out, this); + this.finished = true; + const { buffer, h } = this; + let { pos } = this; + if (pos) { + buffer[pos++] = 1; + // buffer.subarray(pos).fill(0); + for (; pos < 16; pos++) buffer[pos] = 0; + this.process(buffer, 0, true); + } + this.finalize(); + let opos = 0; + for (let i = 0; i < 8; i++) { + out[opos++] = h[i] >>> 0; + out[opos++] = h[i] >>> 8; + } + return out; + } + digest(): Uint8Array { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } +} + +export type CHash = ReturnType; +export function wrapConstructorWithKey>(hashCons: (key: Input) => Hash) { + const hashC = (msg: Input, key: Input): Uint8Array => hashCons(key).update(toBytes(msg)).digest(); + const tmp = hashCons(new Uint8Array(32)); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (key: Input) => hashCons(key); + return hashC; +} + +export const poly1305 = wrapConstructorWithKey((key) => new Poly1305(key)); diff --git a/node_modules/@noble/ciphers/src/_polyval.ts b/node_modules/@noble/ciphers/src/_polyval.ts new file mode 100644 index 0000000..9738685 --- /dev/null +++ b/node_modules/@noble/ciphers/src/_polyval.ts @@ -0,0 +1,248 @@ +import { createView, toBytes, Input, Hash, u32 } from './utils.js'; +import { bytes as abytes, exists as aexists, output as aoutput } from './_assert.js'; + +// GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV. +// Implemented in terms of GHash with conversion function for keys +// GCM GHASH from NIST SP800-38d, SIV from RFC 8452. +// https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf + +// GHASH modulo: x^128 + x^7 + x^2 + x + 1 +// POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1 + +const BLOCK_SIZE = 16; +// TODO: rewrite +// temporary padding buffer +const ZEROS16 = /* @__PURE__ */ new Uint8Array(16); +const ZEROS32 = u32(ZEROS16); +const POLY = 0xe1; // v = 2*v % POLY + +// v = 2*v % POLY +// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x +// We can multiply any number using montgomery ladder and this function (works as double, add is simple xor) +const mul2 = (s0: number, s1: number, s2: number, s3: number) => { + const hiBit = s3 & 1; + return { + s3: (s2 << 31) | (s3 >>> 1), + s2: (s1 << 31) | (s2 >>> 1), + s1: (s0 << 31) | (s1 >>> 1), + s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly + }; +}; + +const swapLE = (n: number) => + (((n >>> 0) & 0xff) << 24) | + (((n >>> 8) & 0xff) << 16) | + (((n >>> 16) & 0xff) << 8) | + ((n >>> 24) & 0xff) | + 0; + +/** + * `mulX_POLYVAL(ByteReverse(H))` from spec + * @param k mutated in place + */ +export function _toGHASHKey(k: Uint8Array): Uint8Array { + k.reverse(); + const hiBit = k[15] & 1; + // k >>= 1 + let carry = 0; + for (let i = 0; i < k.length; i++) { + const t = k[i]; + k[i] = (t >>> 1) | carry; + carry = (t & 1) << 7; + } + k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000; + return k; +} + +type Value = { s0: number; s1: number; s2: number; s3: number }; + +const estimateWindow = (bytes: number) => { + if (bytes > 64 * 1024) return 8; + if (bytes > 1024) return 4; + return 2; +}; + +class GHASH implements Hash { + readonly blockLen = BLOCK_SIZE; + readonly outputLen = BLOCK_SIZE; + protected s0 = 0; + protected s1 = 0; + protected s2 = 0; + protected s3 = 0; + protected finished = false; + protected t: Value[]; + private W: number; + private windowSize: number; + // We select bits per window adaptively based on expectedLength + constructor(key: Input, expectedLength?: number) { + key = toBytes(key); + abytes(key, 16); + const kView = createView(key); + let k0 = kView.getUint32(0, false); + let k1 = kView.getUint32(4, false); + let k2 = kView.getUint32(8, false); + let k3 = kView.getUint32(12, false); + // generate table of doubled keys (half of montgomery ladder) + const doubles: Value[] = []; + for (let i = 0; i < 128; i++) { + doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) }); + ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3)); + } + const W = estimateWindow(expectedLength || 1024); + if (![1, 2, 4, 8].includes(W)) + throw new Error(`ghash: wrong window size=${W}, should be 2, 4 or 8`); + this.W = W; + const bits = 128; // always 128 bits; + const windows = bits / W; + const windowSize = (this.windowSize = 2 ** W); + const items: Value[] = []; + // Create precompute table for window of W bits + for (let w = 0; w < windows; w++) { + // truth table: 00, 01, 10, 11 + for (let byte = 0; byte < windowSize; byte++) { + // prettier-ignore + let s0 = 0, s1 = 0, s2 = 0, s3 = 0; + for (let j = 0; j < W; j++) { + const bit = (byte >>> (W - j - 1)) & 1; + if (!bit) continue; + const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j]; + (s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3); + } + items.push({ s0, s1, s2, s3 }); + } + } + this.t = items; + } + protected _updateBlock(s0: number, s1: number, s2: number, s3: number) { + (s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3); + const { W, t, windowSize } = this; + // prettier-ignore + let o0 = 0, o1 = 0, o2 = 0, o3 = 0; + const mask = (1 << W) - 1; // 2**W will kill performance. + let w = 0; + for (const num of [s0, s1, s2, s3]) { + for (let bytePos = 0; bytePos < 4; bytePos++) { + const byte = (num >>> (8 * bytePos)) & 0xff; + for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) { + const bit = (byte >>> (W * bitPos)) & mask; + const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit]; + (o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3); + w += 1; + } + } + } + this.s0 = o0; + this.s1 = o1; + this.s2 = o2; + this.s3 = o3; + } + update(data: Input): this { + data = toBytes(data); + aexists(this); + const b32 = u32(data); + const blocks = Math.floor(data.length / BLOCK_SIZE); + const left = data.length % BLOCK_SIZE; + for (let i = 0; i < blocks; i++) { + this._updateBlock(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]); + } + if (left) { + ZEROS16.set(data.subarray(blocks * BLOCK_SIZE)); + this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]); + ZEROS32.fill(0); // clean tmp buffer + } + return this; + } + destroy() { + const { t } = this; + // clean precompute table + for (const elm of t) { + (elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0); + } + } + digestInto(out: Uint8Array) { + aexists(this); + aoutput(out, this); + this.finished = true; + const { s0, s1, s2, s3 } = this; + const o32 = u32(out); + o32[0] = s0; + o32[1] = s1; + o32[2] = s2; + o32[3] = s3; + return out; + } + digest(): Uint8Array { + const res = new Uint8Array(BLOCK_SIZE); + this.digestInto(res); + this.destroy(); + return res; + } +} + +class Polyval extends GHASH { + constructor(key: Input, expectedLength?: number) { + key = toBytes(key); + const ghKey = _toGHASHKey(key.slice()); + super(ghKey, expectedLength); + ghKey.fill(0); + } + update(data: Input): this { + data = toBytes(data); + aexists(this); + const b32 = u32(data); + const left = data.length % BLOCK_SIZE; + const blocks = Math.floor(data.length / BLOCK_SIZE); + for (let i = 0; i < blocks; i++) { + this._updateBlock( + swapLE(b32[i * 4 + 3]), + swapLE(b32[i * 4 + 2]), + swapLE(b32[i * 4 + 1]), + swapLE(b32[i * 4 + 0]) + ); + } + if (left) { + ZEROS16.set(data.subarray(blocks * BLOCK_SIZE)); + this._updateBlock( + swapLE(ZEROS32[3]), + swapLE(ZEROS32[2]), + swapLE(ZEROS32[1]), + swapLE(ZEROS32[0]) + ); + ZEROS32.fill(0); // clean tmp buffer + } + return this; + } + digestInto(out: Uint8Array) { + aexists(this); + aoutput(out, this); + this.finished = true; + // tmp ugly hack + const { s0, s1, s2, s3 } = this; + const o32 = u32(out); + o32[0] = s0; + o32[1] = s1; + o32[2] = s2; + o32[3] = s3; + return out.reverse(); + } +} + +export type CHash = ReturnType; +function wrapConstructorWithKey>( + hashCons: (key: Input, expectedLength?: number) => Hash +) { + const hashC = (msg: Input, key: Input): Uint8Array => + hashCons(key, msg.length).update(toBytes(msg)).digest(); + const tmp = hashCons(new Uint8Array(16), 0); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (key: Input, expectedLength?: number) => hashCons(key, expectedLength); + return hashC; +} + +export const ghash = wrapConstructorWithKey( + (key, expectedLength) => new GHASH(key, expectedLength) +); +export const polyval = wrapConstructorWithKey( + (key, expectedLength) => new Polyval(key, expectedLength) +); diff --git a/node_modules/@noble/ciphers/src/aes.ts b/node_modules/@noble/ciphers/src/aes.ts new file mode 100644 index 0000000..fe78b25 --- /dev/null +++ b/node_modules/@noble/ciphers/src/aes.ts @@ -0,0 +1,734 @@ +// prettier-ignore +import { + wrapCipher, Cipher, CipherWithOutput, + createView, setBigUint64, equalBytes, u32, u8, +} from './utils.js'; +import { ghash, polyval } from './_polyval.js'; +import { bytes as abytes } from './_assert.js'; + +/* +AES (Advanced Encryption Standard) aka Rijndael block cipher. + +Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round: +1. **S-box**, table substitution +2. **Shift rows**, cyclic shift left of all rows of data array +3. **Mix columns**, multiplying every column by fixed polynomial +4. **Add round key**, round_key xor i-th column of array + +Resources: +- FIPS-197 https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf +- Original proposal: https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf +*/ + +const BLOCK_SIZE = 16; +const BLOCK_SIZE32 = 4; +const EMPTY_BLOCK = new Uint8Array(BLOCK_SIZE); +const POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8 + +// TODO: remove multiplication, binary ops only +function mul2(n: number) { + return (n << 1) ^ (POLY & -(n >> 7)); +} + +function mul(a: number, b: number) { + let res = 0; + for (; b > 0; b >>= 1) { + // Montgomery ladder + res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time). + a = mul2(a); // a = 2*a + } + return res; +} + +// AES S-box is generated using finite field inversion, +// an affine transform, and xor of a constant 0x63. +const sbox = /* @__PURE__ */ (() => { + let t = new Uint8Array(256); + for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x)) t[i] = x; + const box = new Uint8Array(256); + box[0] = 0x63; // first elm + for (let i = 0; i < 255; i++) { + let x = t[255 - i]; + x |= x << 8; + box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff; + } + return box; +})(); + +// Inverted S-box +const invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j)); + +// Rotate u32 by 8 +const rotr32_8 = (n: number) => (n << 24) | (n >>> 8); +const rotl32_8 = (n: number) => (n << 8) | (n >>> 24); + +// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes: +// - LE instead of BE +// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23; +// so index is u16, instead of u8. This speeds up things, unexpectedly +function genTtable(sbox: Uint8Array, fn: (n: number) => number) { + if (sbox.length !== 256) throw new Error('Wrong sbox length'); + const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j])); + const T1 = T0.map(rotl32_8); + const T2 = T1.map(rotl32_8); + const T3 = T2.map(rotl32_8); + const T01 = new Uint32Array(256 * 256); + const T23 = new Uint32Array(256 * 256); + const sbox2 = new Uint16Array(256 * 256); + for (let i = 0; i < 256; i++) { + for (let j = 0; j < 256; j++) { + const idx = i * 256 + j; + T01[idx] = T0[i] ^ T1[j]; + T23[idx] = T2[i] ^ T3[j]; + sbox2[idx] = (sbox[i] << 8) | sbox[j]; + } + } + return { sbox, sbox2, T0, T1, T2, T3, T01, T23 }; +} + +const tableEncoding = /* @__PURE__ */ genTtable( + sbox, + (s: number) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2) +); +const tableDecoding = /* @__PURE__ */ genTtable( + invSbox, + (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14) +); + +const xPowers = /* @__PURE__ */ (() => { + const p = new Uint8Array(16); + for (let i = 0, x = 1; i < 16; i++, x = mul2(x)) p[i] = x; + return p; +})(); + +export function expandKeyLE(key: Uint8Array): Uint32Array { + abytes(key); + const len = key.length; + if (![16, 24, 32].includes(len)) + throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`); + const { sbox2 } = tableEncoding; + const k32 = u32(key); + const Nk = k32.length; + const subByte = (n: number) => applySbox(sbox2, n, n, n, n); + const xk = new Uint32Array(len + 28); // expanded key + xk.set(k32); + // 4.3.1 Key expansion + for (let i = Nk; i < xk.length; i++) { + let t = xk[i - 1]; + if (i % Nk === 0) t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1]; + else if (Nk > 6 && i % Nk === 4) t = subByte(t); + xk[i] = xk[i - Nk] ^ t; + } + return xk; +} + +export function expandKeyDecLE(key: Uint8Array): Uint32Array { + const encKey = expandKeyLE(key); + const xk = encKey.slice(); + const Nk = encKey.length; + const { sbox2 } = tableEncoding; + const { T0, T1, T2, T3 } = tableDecoding; + // Inverse key by chunks of 4 (rounds) + for (let i = 0; i < Nk; i += 4) { + for (let j = 0; j < 4; j++) xk[i + j] = encKey[Nk - i - 4 + j]; + } + encKey.fill(0); + // apply InvMixColumn except first & last round + for (let i = 4; i < Nk - 4; i++) { + const x = xk[i]; + const w = applySbox(sbox2, x, x, x, x); + xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24]; + } + return xk; +} + +// Apply tables +function apply0123( + T01: Uint32Array, + T23: Uint32Array, + s0: number, + s1: number, + s2: number, + s3: number +) { + return ( + T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^ + T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)] + ); +} + +function applySbox(sbox2: Uint16Array, s0: number, s1: number, s2: number, s3: number) { + return ( + sbox2[(s0 & 0xff) | (s1 & 0xff00)] | + (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16) + ); +} + +function encrypt(xk: Uint32Array, s0: number, s1: number, s2: number, s3: number) { + const { sbox2, T01, T23 } = tableEncoding; + let k = 0; + (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]); + const rounds = xk.length / 4 - 2; + for (let i = 0; i < rounds; i++) { + const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3); + const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0); + const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1); + const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2); + (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3); + } + // last round (without mixcolumns, so using SBOX2 table) + const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3); + const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0); + const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1); + const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; +} + +function decrypt(xk: Uint32Array, s0: number, s1: number, s2: number, s3: number) { + const { sbox2, T01, T23 } = tableDecoding; + let k = 0; + (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]); + const rounds = xk.length / 4 - 2; + for (let i = 0; i < rounds; i++) { + const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1); + const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2); + const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3); + const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0); + (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3); + } + // Last round + const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1); + const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2); + const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3); + const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; +} + +function getDst(len: number, dst?: Uint8Array) { + if (!dst) return new Uint8Array(len); + abytes(dst); + if (dst.length < len) + throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`); + return dst; +} + +// TODO: investigate merging with ctr32 +function ctrCounter(xk: Uint32Array, nonce: Uint8Array, src: Uint8Array, dst?: Uint8Array) { + abytes(nonce, BLOCK_SIZE); + abytes(src); + const srcLen = src.length; + dst = getDst(srcLen, dst); + const ctr = nonce; + const c32 = u32(ctr); + // Fill block (empty, ctr=0) + let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]); + const src32 = u32(src); + const dst32 = u32(dst); + // process blocks + for (let i = 0; i + 4 <= src32.length; i += 4) { + dst32[i + 0] = src32[i + 0] ^ s0; + dst32[i + 1] = src32[i + 1] ^ s1; + dst32[i + 2] = src32[i + 2] ^ s2; + dst32[i + 3] = src32[i + 3] ^ s3; + // Full 128 bit counter with wrap around + let carry = 1; + for (let i = ctr.length - 1; i >= 0; i--) { + carry = (carry + (ctr[i] & 0xff)) | 0; + ctr[i] = carry & 0xff; + carry >>>= 8; + } + ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3])); + } + // leftovers (less than block) + // It's possible to handle > u32 fast, but is it worth it? + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + const b32 = new Uint32Array([s0, s1, s2, s3]); + const buf = u8(b32); + for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos]; + } + return dst; +} + +// AES CTR with overflowing 32 bit counter +// It's possible to do 32le significantly simpler (and probably faster) by using u32. +// But, we need both, and perf bottleneck is in ghash anyway. +function ctr32( + xk: Uint32Array, + isLE: boolean, + nonce: Uint8Array, + src: Uint8Array, + dst?: Uint8Array +) { + abytes(nonce, BLOCK_SIZE); + abytes(src); + dst = getDst(src.length, dst); + const ctr = nonce; // write new value to nonce, so it can be re-used + const c32 = u32(ctr); + const view = createView(ctr); + const src32 = u32(src); + const dst32 = u32(dst); + const ctrPos = isLE ? 0 : 12; + const srcLen = src.length; + // Fill block (empty, ctr=0) + let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value + let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]); + // process blocks + for (let i = 0; i + 4 <= src32.length; i += 4) { + dst32[i + 0] = src32[i + 0] ^ s0; + dst32[i + 1] = src32[i + 1] ^ s1; + dst32[i + 2] = src32[i + 2] ^ s2; + dst32[i + 3] = src32[i + 3] ^ s3; + ctrNum = (ctrNum + 1) >>> 0; // u32 wrap + view.setUint32(ctrPos, ctrNum, isLE); + ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3])); + } + // leftovers (less than a block) + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + const b32 = new Uint32Array([s0, s1, s2, s3]); + const buf = u8(b32); + for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos]; + } + return dst; +} + +/** + * CTR: counter mode. Creates stream cipher. + * Requires good IV. Parallelizable. OK, but no MAC. + */ +export const ctr = wrapCipher( + { blockSize: 16, nonceLength: 16 }, + function ctr(key: Uint8Array, nonce: Uint8Array): CipherWithOutput { + abytes(key); + abytes(nonce, BLOCK_SIZE); + function processCtr(buf: Uint8Array, dst?: Uint8Array) { + const xk = expandKeyLE(key); + const n = nonce.slice(); + const out = ctrCounter(xk, n, buf, dst); + xk.fill(0); + n.fill(0); + return out; + } + return { + encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => processCtr(plaintext, dst), + decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => processCtr(ciphertext, dst), + }; + } +); + +function validateBlockDecrypt(data: Uint8Array) { + abytes(data); + if (data.length % BLOCK_SIZE !== 0) { + throw new Error( + `aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}` + ); + } +} + +function validateBlockEncrypt(plaintext: Uint8Array, pcks5: boolean, dst?: Uint8Array) { + let outLen = plaintext.length; + const remaining = outLen % BLOCK_SIZE; + if (!pcks5 && remaining !== 0) + throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding'); + const b = u32(plaintext); + if (pcks5) { + let left = BLOCK_SIZE - remaining; + if (!left) left = BLOCK_SIZE; // if no bytes left, create empty padding block + outLen = outLen + left; + } + const out = getDst(outLen, dst); + const o = u32(out); + return { b, o, out }; +} + +function validatePCKS(data: Uint8Array, pcks5: boolean) { + if (!pcks5) return data; + const len = data.length; + if (!len) throw new Error(`aes/pcks5: empty ciphertext not allowed`); + const lastByte = data[len - 1]; + if (lastByte <= 0 || lastByte > 16) throw new Error(`aes/pcks5: wrong padding byte: ${lastByte}`); + const out = data.subarray(0, -lastByte); + for (let i = 0; i < lastByte; i++) + if (data[len - i - 1] !== lastByte) throw new Error(`aes/pcks5: wrong padding`); + return out; +} + +function padPCKS(left: Uint8Array) { + const tmp = new Uint8Array(16); + const tmp32 = u32(tmp); + tmp.set(left); + const paddingByte = BLOCK_SIZE - left.length; + for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++) tmp[i] = paddingByte; + return tmp32; +} + +export type BlockOpts = { disablePadding?: boolean }; + +/** + * ECB: Electronic CodeBook. Simple deterministic replacement. + * Dangerous: always map x to y. See [AES Penguin](https://words.filippo.io/the-ecb-penguin/). + */ +export const ecb = wrapCipher( + { blockSize: 16 }, + function ecb(key: Uint8Array, opts: BlockOpts = {}): CipherWithOutput { + abytes(key); + const pcks5 = !opts.disablePadding; + return { + encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => { + abytes(plaintext); + const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst); + const xk = expandKeyLE(key); + let i = 0; + for (; i + 4 <= b.length; ) { + const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); + } + if (pcks5) { + const tmp32 = padPCKS(plaintext.subarray(i * 4)); + const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); + } + xk.fill(0); + return _out; + }, + decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => { + validateBlockDecrypt(ciphertext); + const xk = expandKeyDecLE(key); + const out = getDst(ciphertext.length, dst); + const b = u32(ciphertext); + const o = u32(out); + for (let i = 0; i + 4 <= b.length; ) { + const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); + } + xk.fill(0); + return validatePCKS(out, pcks5); + }, + }; + } +); + +/** + * CBC: Cipher-Block-Chaining. Key is previous round’s block. + * Fragile: needs proper padding. Unauthenticated: needs MAC. + */ +export const cbc = wrapCipher( + { blockSize: 16, nonceLength: 16 }, + function cbc(key: Uint8Array, iv: Uint8Array, opts: BlockOpts = {}): CipherWithOutput { + abytes(key); + abytes(iv, 16); + const pcks5 = !opts.disablePadding; + return { + encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => { + const xk = expandKeyLE(key); + const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst); + const n32 = u32(iv); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + let i = 0; + for (; i + 4 <= b.length; ) { + (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]); + ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3)); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); + } + if (pcks5) { + const tmp32 = padPCKS(plaintext.subarray(i * 4)); + (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]); + ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3)); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); + } + xk.fill(0); + return _out; + }, + decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => { + validateBlockDecrypt(ciphertext); + const xk = expandKeyDecLE(key); + const n32 = u32(iv); + const out = getDst(ciphertext.length, dst); + const b = u32(ciphertext); + const o = u32(out); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + for (let i = 0; i + 4 <= b.length; ) { + // prettier-ignore + const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3; + (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]); + const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3); + (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3); + } + xk.fill(0); + return validatePCKS(out, pcks5); + }, + }; + } +); + +/** + * CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output. + * Unauthenticated: needs MAC. + */ +export const cfb = wrapCipher( + { blockSize: 16, nonceLength: 16 }, + function cfb(key: Uint8Array, iv: Uint8Array): CipherWithOutput { + abytes(key); + abytes(iv, 16); + function processCfb(src: Uint8Array, isEncrypt: boolean, dst?: Uint8Array) { + const xk = expandKeyLE(key); + const srcLen = src.length; + dst = getDst(srcLen, dst); + const src32 = u32(src); + const dst32 = u32(dst); + const next32 = isEncrypt ? dst32 : src32; + const n32 = u32(iv); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + for (let i = 0; i + 4 <= src32.length; ) { + const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3); + dst32[i + 0] = src32[i + 0] ^ e0; + dst32[i + 1] = src32[i + 1] ^ e1; + dst32[i + 2] = src32[i + 2] ^ e2; + dst32[i + 3] = src32[i + 3] ^ e3; + (s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]); + } + // leftovers (less than block) + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3)); + const buf = u8(new Uint32Array([s0, s1, s2, s3])); + for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos]; + buf.fill(0); + } + xk.fill(0); + return dst; + } + return { + encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => processCfb(plaintext, true, dst), + decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => processCfb(ciphertext, false, dst), + }; + } +); + +// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen +function computeTag( + fn: typeof ghash, + isLE: boolean, + key: Uint8Array, + data: Uint8Array, + AAD?: Uint8Array +) { + const h = fn.create(key, data.length + (AAD?.length || 0)); + if (AAD) h.update(AAD); + h.update(data); + const num = new Uint8Array(16); + const view = createView(num); + if (AAD) setBigUint64(view, 0, BigInt(AAD.length * 8), isLE); + setBigUint64(view, 8, BigInt(data.length * 8), isLE); + h.update(num); + return h.digest(); +} + +/** + * GCM: Galois/Counter Mode. + * Good, modern version of CTR, parallel, with MAC. + * Be careful: MACs can be forged. + */ +export const gcm = wrapCipher( + { blockSize: 16, nonceLength: 12, tagLength: 16 }, + function gcm(key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): Cipher { + abytes(nonce); + // Nonce can be pretty much anything (even 1 byte). But smaller nonces less secure. + if (nonce.length === 0) throw new Error('aes/gcm: empty nonce'); + const tagLength = 16; + function _computeTag(authKey: Uint8Array, tagMask: Uint8Array, data: Uint8Array) { + const tag = computeTag(ghash, false, authKey, data, AAD); + for (let i = 0; i < tagMask.length; i++) tag[i] ^= tagMask[i]; + return tag; + } + function deriveKeys() { + const xk = expandKeyLE(key); + const authKey = EMPTY_BLOCK.slice(); + const counter = EMPTY_BLOCK.slice(); + ctr32(xk, false, counter, counter, authKey); + if (nonce.length === 12) { + counter.set(nonce); + } else { + // Spec (NIST 800-38d) supports variable size nonce. + // Not supported for now, but can be useful. + const nonceLen = EMPTY_BLOCK.slice(); + const view = createView(nonceLen); + setBigUint64(view, 8, BigInt(nonce.length * 8), false); + // ghash(nonce || u64be(0) || u64be(nonceLen*8)) + ghash.create(authKey).update(nonce).update(nonceLen).digestInto(counter); + } + const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK); + return { xk, authKey, counter, tagMask }; + } + return { + encrypt: (plaintext: Uint8Array) => { + abytes(plaintext); + const { xk, authKey, counter, tagMask } = deriveKeys(); + const out = new Uint8Array(plaintext.length + tagLength); + ctr32(xk, false, counter, plaintext, out); + const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength)); + out.set(tag, plaintext.length); + xk.fill(0); + return out; + }, + decrypt: (ciphertext: Uint8Array) => { + abytes(ciphertext); + if (ciphertext.length < tagLength) + throw new Error(`aes/gcm: ciphertext less than tagLen (${tagLength})`); + const { xk, authKey, counter, tagMask } = deriveKeys(); + const data = ciphertext.subarray(0, -tagLength); + const passedTag = ciphertext.subarray(-tagLength); + const tag = _computeTag(authKey, tagMask, data); + if (!equalBytes(tag, passedTag)) throw new Error('aes/gcm: invalid ghash tag'); + const out = ctr32(xk, false, counter, data); + authKey.fill(0); + tagMask.fill(0); + xk.fill(0); + return out; + }, + }; + } +); + +const limit = (name: string, min: number, max: number) => (value: number) => { + if (!Number.isSafeInteger(value) || min > value || value > max) + throw new Error(`${name}: invalid value=${value}, must be [${min}..${max}]`); +}; + +/** + * AES-GCM-SIV: classic AES-GCM with nonce-misuse resistance. + * Guarantees that, when a nonce is repeated, the only security loss is that identical + * plaintexts will produce identical ciphertexts. + * RFC 8452, https://datatracker.ietf.org/doc/html/rfc8452 + */ +export const siv = wrapCipher( + { blockSize: 16, nonceLength: 12, tagLength: 16 }, + function siv(key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): Cipher { + const tagLength = 16; + // From RFC 8452: Section 6 + const AAD_LIMIT = limit('AAD', 0, 2 ** 36); + const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36); + const NONCE_LIMIT = limit('nonce', 12, 12); + const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16); + abytes(nonce); + NONCE_LIMIT(nonce.length); + if (AAD) { + abytes(AAD); + AAD_LIMIT(AAD.length); + } + function deriveKeys() { + const len = key.length; + if (len !== 16 && len !== 24 && len !== 32) + throw new Error(`key length must be 16, 24 or 32 bytes, got: ${len} bytes`); + const xk = expandKeyLE(key); + const encKey = new Uint8Array(len); + const authKey = new Uint8Array(16); + const n32 = u32(nonce); + // prettier-ignore + let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2]; + let counter = 0; + for (const derivedKey of [authKey, encKey].map(u32)) { + const d32 = u32(derivedKey); + for (let i = 0; i < d32.length; i += 2) { + // aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ... + const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3); + d32[i + 0] = o0; + d32[i + 1] = o1; + s0 = ++counter; // increment counter inside state + } + } + xk.fill(0); + return { authKey, encKey: expandKeyLE(encKey) }; + } + function _computeTag(encKey: Uint32Array, authKey: Uint8Array, data: Uint8Array) { + const tag = computeTag(polyval, true, authKey, data, AAD); + // Compute the expected tag by XORing S_s and the nonce, clearing the + // most significant bit of the last byte and encrypting with the + // message-encryption key. + for (let i = 0; i < 12; i++) tag[i] ^= nonce[i]; + tag[15] &= 0x7f; // Clear the highest bit + // encrypt tag as block + const t32 = u32(tag); + // prettier-ignore + let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3]; + ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3)); + (t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3); + return tag; + } + // actual decrypt/encrypt of message. + function processSiv(encKey: Uint32Array, tag: Uint8Array, input: Uint8Array) { + let block = tag.slice(); + block[15] |= 0x80; // Force highest bit + return ctr32(encKey, true, block, input); + } + return { + encrypt: (plaintext: Uint8Array) => { + abytes(plaintext); + PLAIN_LIMIT(plaintext.length); + const { encKey, authKey } = deriveKeys(); + const tag = _computeTag(encKey, authKey, plaintext); + const out = new Uint8Array(plaintext.length + tagLength); + out.set(tag, plaintext.length); + out.set(processSiv(encKey, tag, plaintext)); + encKey.fill(0); + authKey.fill(0); + return out; + }, + decrypt: (ciphertext: Uint8Array) => { + abytes(ciphertext); + CIPHER_LIMIT(ciphertext.length); + const tag = ciphertext.subarray(-tagLength); + const { encKey, authKey } = deriveKeys(); + const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength)); + const expectedTag = _computeTag(encKey, authKey, plaintext); + encKey.fill(0); + authKey.fill(0); + if (!equalBytes(tag, expectedTag)) throw new Error('invalid polyval tag'); + return plaintext; + }, + }; + } +); + +function isBytes32(a: unknown): a is Uint8Array { + return ( + a != null && + typeof a === 'object' && + (a instanceof Uint32Array || a.constructor.name === 'Uint32Array') + ); +} + +function encryptBlock(xk: Uint32Array, block: Uint8Array) { + abytes(block, 16); + if (!isBytes32(xk)) throw new Error('_encryptBlock accepts result of expandKeyLE'); + const b32 = u32(block); + let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]); + (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3); + return block; +} + +function decryptBlock(xk: Uint32Array, block: Uint8Array) { + abytes(block, 16); + if (!isBytes32(xk)) throw new Error('_decryptBlock accepts result of expandKeyLE'); + const b32 = u32(block); + let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]); + (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3); + return block; +} + +// Highly unsafe private functions for implementing new modes or ciphers based on AES +// Can change at any time, no API guarantees +export const unsafe = { + expandKeyLE, + expandKeyDecLE, + encrypt, + decrypt, + encryptBlock, + decryptBlock, + ctrCounter, + ctr32, +}; diff --git a/node_modules/@noble/ciphers/src/chacha.ts b/node_modules/@noble/ciphers/src/chacha.ts new file mode 100644 index 0000000..bcd9ce6 --- /dev/null +++ b/node_modules/@noble/ciphers/src/chacha.ts @@ -0,0 +1,285 @@ +// prettier-ignore +import { + wrapCipher, CipherWithOutput, XorStream, createView, equalBytes, setBigUint64, +} from './utils.js'; +import { poly1305 } from './_poly1305.js'; +import { createCipher, rotl } from './_arx.js'; +import { bytes as abytes } from './_assert.js'; + +// ChaCha20 stream cipher was released in 2008. ChaCha aims to increase +// the diffusion per round, but had slightly less cryptanalysis. +// https://cr.yp.to/chacha.html, http://cr.yp.to/chacha/chacha-20080128.pdf + +/** + * ChaCha core function. + */ +// prettier-ignore +function chachaCore( + s: Uint32Array, k: Uint32Array, n: Uint32Array, out: Uint32Array, cnt: number, rounds = 20 +): void { + let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // "expa" "nd 3" "2-by" "te k" + y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key + y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key + y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Counter Nonce Nonce + // Save state to temporary variables + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, + x04 = y04, x05 = y05, x06 = y06, x07 = y07, + x08 = y08, x09 = y09, x10 = y10, x11 = y11, + x12 = y12, x13 = y13, x14 = y14, x15 = y15; + for (let r = 0; r < rounds; r += 2) { + x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16); + x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12); + x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8); + x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7); + + x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16); + x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12); + x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8); + x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7); + + x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16); + x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12); + x02 = (x02 + x06) | 0; x14 = rotl(x14 ^x02, 8); + x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7); + + x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16); + x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12); + x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8) + x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7); + + x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16); + x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12); + x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8); + x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7); + + x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16); + x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12); + x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8); + x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7); + + x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16); + x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12); + x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8); + x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7); + + x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16) + x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12); + x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8); + x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7); + } + // Write output + let oi = 0; + out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0; +} +/** + * hchacha helper method, used primarily in xchacha, to hash + * key and nonce into key' and nonce'. + * Same as chachaCore, but there doesn't seem to be a way to move the block + * out without 25% performance hit. + */ +// prettier-ignore +export function hchacha( + s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array +) { + let x00 = s[0], x01 = s[1], x02 = s[2], x03 = s[3], + x04 = k[0], x05 = k[1], x06 = k[2], x07 = k[3], + x08 = k[4], x09 = k[5], x10 = k[6], x11 = k[7], + x12 = i[0], x13 = i[1], x14 = i[2], x15 = i[3]; + for (let r = 0; r < 20; r += 2) { + x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16); + x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12); + x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8); + x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7); + + x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16); + x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12); + x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8); + x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7); + + x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16); + x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12); + x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 8); + x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7); + + x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16); + x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12); + x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8) + x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7); + + x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16); + x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12); + x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8); + x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7); + + x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16); + x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12); + x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8); + x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7); + + x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16); + x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12); + x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8); + x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7); + + x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16) + x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12); + x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8); + x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7); + } + let oi = 0; + o32[oi++] = x00; o32[oi++] = x01; + o32[oi++] = x02; o32[oi++] = x03; + o32[oi++] = x12; o32[oi++] = x13; + o32[oi++] = x14; o32[oi++] = x15; +} +/** + * Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter. + */ +export const chacha20orig = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 8, + allowShortKeys: true, +}); +/** + * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter. + * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance. + */ +export const chacha20 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 4, + allowShortKeys: false, +}); + +/** + * XChaCha eXtended-nonce ChaCha. 24-byte nonce. + * With 24-byte nonce, it's safe to use fill it with random (CSPRNG). + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha + */ +export const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 8, + extendNonceFn: hchacha, + allowShortKeys: false, +}); + +/** + * Reduced 8-round chacha, described in original paper. + */ +export const chacha8 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 4, + rounds: 8, +}); + +/** + * Reduced 12-round chacha, described in original paper. + */ +export const chacha12 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 4, + rounds: 12, +}); + +const ZEROS16 = /* @__PURE__ */ new Uint8Array(16); +// Pad to digest size with zeros +const updatePadded = (h: ReturnType, msg: Uint8Array) => { + h.update(msg); + const left = msg.length % 16; + if (left) h.update(ZEROS16.subarray(left)); +}; + +const ZEROS32 = /* @__PURE__ */ new Uint8Array(32); +function computeTag( + fn: XorStream, + key: Uint8Array, + nonce: Uint8Array, + data: Uint8Array, + AAD?: Uint8Array +): Uint8Array { + const authKey = fn(key, nonce, ZEROS32); + const h = poly1305.create(authKey); + if (AAD) updatePadded(h, AAD); + updatePadded(h, data); + const num = new Uint8Array(16); + const view = createView(num); + setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true); + setBigUint64(view, 8, BigInt(data.length), true); + h.update(num); + const res = h.digest(); + authKey.fill(0); + return res; +} + +/** + * AEAD algorithm from RFC 8439. + * Salsa20 and chacha (RFC 8439) use poly1305 differently. + * We could have composed them similar to: + * https://github.com/paulmillr/scure-base/blob/b266c73dde977b1dd7ef40ef7a23cc15aab526b3/index.ts#L250 + * But it's hard because of authKey: + * In salsa20, authKey changes position in salsa stream. + * In chacha, authKey can't be computed inside computeTag, it modifies the counter. + */ +export const _poly1305_aead = + (xorStream: XorStream) => + (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): CipherWithOutput => { + const tagLength = 16; + abytes(key, 32); + abytes(nonce); + return { + encrypt: (plaintext: Uint8Array, output?: Uint8Array) => { + const plength = plaintext.length; + const clength = plength + tagLength; + if (output) { + abytes(output, clength); + } else { + output = new Uint8Array(clength); + } + xorStream(key, nonce, plaintext, output, 1); + const tag = computeTag(xorStream, key, nonce, output.subarray(0, -tagLength), AAD); + output.set(tag, plength); // append tag + return output; + }, + decrypt: (ciphertext: Uint8Array, output?: Uint8Array) => { + const clength = ciphertext.length; + const plength = clength - tagLength; + if (clength < tagLength) + throw new Error(`encrypted data must be at least ${tagLength} bytes`); + if (output) { + abytes(output, plength); + } else { + output = new Uint8Array(plength); + } + const data = ciphertext.subarray(0, -tagLength); + const passedTag = ciphertext.subarray(-tagLength); + const tag = computeTag(xorStream, key, nonce, data, AAD); + if (!equalBytes(passedTag, tag)) throw new Error('invalid tag'); + xorStream(key, nonce, data, output, 1); + return output; + }, + }; + }; + +/** + * ChaCha20-Poly1305 from RFC 8439. + * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance. + */ +export const chacha20poly1305 = /* @__PURE__ */ wrapCipher( + { blockSize: 64, nonceLength: 12, tagLength: 16 }, + _poly1305_aead(chacha20) +); +/** + * XChaCha20-Poly1305 extended-nonce chacha. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha + * With 24-byte nonce, it's safe to use fill it with random (CSPRNG). + */ +export const xchacha20poly1305 = /* @__PURE__ */ wrapCipher( + { blockSize: 64, nonceLength: 24, tagLength: 16 }, + _poly1305_aead(xchacha20) +); diff --git a/node_modules/@noble/ciphers/src/crypto.ts b/node_modules/@noble/ciphers/src/crypto.ts new file mode 100644 index 0000000..2ada69a --- /dev/null +++ b/node_modules/@noble/ciphers/src/crypto.ts @@ -0,0 +1,15 @@ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +declare const globalThis: Record | undefined; +const cr = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; + +export function randomBytes(bytesLength = 32): Uint8Array { + if (cr && typeof cr.getRandomValues === 'function') + return cr.getRandomValues(new Uint8Array(bytesLength)); + throw new Error('crypto.getRandomValues must be defined'); +} + +export function getWebcryptoSubtle() { + if (cr && typeof cr.subtle === 'object' && cr.subtle != null) return cr.subtle; + throw new Error('crypto.subtle must be defined'); +} diff --git a/node_modules/@noble/ciphers/src/cryptoNode.ts b/node_modules/@noble/ciphers/src/cryptoNode.ts new file mode 100644 index 0000000..772f3b3 --- /dev/null +++ b/node_modules/@noble/ciphers/src/cryptoNode.ts @@ -0,0 +1,17 @@ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +// The file will throw on node.js 14 and earlier. +// @ts-ignore +import * as nc from 'node:crypto'; +const cr = nc && typeof nc === 'object' && 'webcrypto' in nc ? (nc.webcrypto as any) : undefined; + +export function randomBytes(bytesLength = 32): Uint8Array { + if (cr && typeof cr.getRandomValues === 'function') + return cr.getRandomValues(new Uint8Array(bytesLength)); + throw new Error('crypto.getRandomValues must be defined'); +} + +export function getWebcryptoSubtle() { + if (cr && typeof cr.subtle === 'object' && cr.subtle != null) return cr.subtle; + throw new Error('crypto.subtle must be defined'); +} diff --git a/node_modules/@noble/ciphers/src/ff1.ts b/node_modules/@noble/ciphers/src/ff1.ts new file mode 100644 index 0000000..1e3c579 --- /dev/null +++ b/node_modules/@noble/ciphers/src/ff1.ts @@ -0,0 +1,147 @@ +import { Cipher, bytesToNumberBE, numberToBytesBE } from './utils.js'; +import { unsafe } from './aes.js'; +// NOTE: no point in inlining encrypt instead of encryptBlock, since BigInt stuff will be slow +const { expandKeyLE, encryptBlock } = unsafe; + +// Format-preserving encryption algorithm (FPE-FF1) specified in NIST Special Publication 800-38G. +// https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf + +const BLOCK_LEN = 16; + +// Calculates a modulo b +function mod(a: number, b: number): number; +function mod(a: bigint, b: bigint): bigint; +function mod(a: any, b: any): number | bigint { + const result = a % b; + return result >= 0 ? result : b + result; +} + +function NUMradix(radix: number, data: number[]): bigint { + let res = BigInt(0); + for (let i of data) res = res * BigInt(radix) + BigInt(i); + return res; +} + +function getRound(radix: number, key: Uint8Array, tweak: Uint8Array, x: number[]) { + if (radix > 2 ** 16 - 1) throw new Error(`Invalid radix: ${radix}`); + // radix**minlen ≥ 100 + const minLen = Math.ceil(Math.log(100) / Math.log(radix)); + const maxLen = 2 ** 32 - 1; + // 2 ≤ minlen ≤ maxlen < 2**32 + if (2 > minLen || minLen > maxLen || maxLen >= 2 ** 32) + throw new Error('Invalid radix: 2 ≤ minlen ≤ maxlen < 2**32'); + if (x.length < minLen || x.length > maxLen) throw new Error('X is outside minLen..maxLen bounds'); + const u = Math.floor(x.length / 2); + const v = x.length - u; + const b = Math.ceil(Math.ceil(v * Math.log2(radix)) / 8); + const d = 4 * Math.ceil(b / 4) + 4; + const padding = mod(-tweak.length - b - 1, 16); + // P = [1]1 || [2]1 || [1]1 || [radix]3 || [10]1 || [u mod 256]1 || [n]4 || [t]4. + const P = new Uint8Array([1, 2, 1, 0, 0, 0, 10, u, 0, 0, 0, 0, 0, 0, 0, 0]); + const view = new DataView(P.buffer); + view.setUint16(4, radix, false); + view.setUint32(8, x.length, false); + view.setUint32(12, tweak.length, false); + // Q = T || [0](−t−b−1) mod 16 || [i]1 || [NUMradix(B)]b. + const PQ = new Uint8Array(P.length + tweak.length + padding + 1 + b); + PQ.set(P); + P.fill(0); + PQ.set(tweak, P.length); + const xk = expandKeyLE(key); + const round = (A: number[], B: number[], i: number, decrypt = false) => { + // Q = ... || [i]1 || [NUMradix(B)]b. + PQ[PQ.length - b - 1] = i; + if (b) PQ.set(numberToBytesBE(NUMradix(radix, B), b), PQ.length - b); + // PRF + let r = new Uint8Array(16); + for (let j = 0; j < PQ.length / BLOCK_LEN; j++) { + for (let i = 0; i < BLOCK_LEN; i++) r[i] ^= PQ[j * BLOCK_LEN + i]; + encryptBlock(xk, r); + } + // Let S be the first d bytes of the following string of ⎡d/16⎤ blocks: + // R || CIPHK(R ⊕[1]16) || CIPHK(R ⊕[2]16) ...CIPHK(R ⊕[⎡d / 16⎤ – 1]16). + let s = Array.from(r); + for (let j = 1; s.length < d; j++) { + const block = numberToBytesBE(BigInt(j), 16); + for (let k = 0; k < BLOCK_LEN; k++) block[k] ^= r[k]; + s.push(...Array.from(encryptBlock(xk, block))); + } + let y = bytesToNumberBE(Uint8Array.from(s.slice(0, d))); + s.fill(0); + if (decrypt) y = -y; + const m = i % 2 === 0 ? u : v; + let c = mod(NUMradix(radix, A) + y, BigInt(radix) ** BigInt(m)); + // STR(radix, m, c) + const C = Array(m).fill(0); + for (let i = 0; i < m; i++, c /= BigInt(radix)) C[m - 1 - i] = Number(c % BigInt(radix)); + A.fill(0); + A = B; + B = C; + return [A, B]; + }; + const destroy = () => { + xk.fill(0); + PQ.fill(0); + }; + return { u, round, destroy }; +} + +const EMPTY_BUF = new Uint8Array([]); + +export function FF1(radix: number, key: Uint8Array, tweak: Uint8Array = EMPTY_BUF) { + const PQ = getRound.bind(null, radix, key, tweak); + return { + encrypt(x: number[]) { + const { u, round, destroy } = PQ(x); + let [A, B] = [x.slice(0, u), x.slice(u)]; + for (let i = 0; i < 10; i++) [A, B] = round(A, B, i); + destroy(); + const res = A.concat(B); + A.fill(0); + B.fill(0); + return res; + }, + decrypt(x: number[]) { + const { u, round, destroy } = PQ(x); + // The FF1.Decrypt algorithm is similar to the FF1.Encrypt algorithm; + // the differences are in Step 6, where: + // 1) the order of the indices is reversed, + // 2) the roles of A and B are swapped + // 3) modular addition is replaced by modular subtraction, in Step 6vi. + let [B, A] = [x.slice(0, u), x.slice(u)]; + for (let i = 9; i >= 0; i--) [A, B] = round(A, B, i, true); + destroy(); + const res = B.concat(A); + A.fill(0); + B.fill(0); + return res; + }, + }; +} +// Binary string which encodes each byte in little-endian byte order +const binLE = { + encode(bytes: Uint8Array): number[] { + const x = []; + for (let i = 0; i < bytes.length; i++) { + for (let j = 0, tmp = bytes[i]; j < 8; j++, tmp >>= 1) x.push(tmp & 1); + } + return x; + }, + decode(b: number[]): Uint8Array { + if (b.length % 8) throw new Error('Invalid binary string'); + const res = new Uint8Array(b.length / 8); + for (let i = 0, j = 0; i < res.length; i++) { + res[i] = b[j++] | (b[j++] << 1) | (b[j++] << 2) | (b[j++] << 3); + res[i] |= (b[j++] << 4) | (b[j++] << 5) | (b[j++] << 6) | (b[j++] << 7); + } + return res; + }, +}; + +export function BinaryFF1(key: Uint8Array, tweak: Uint8Array = EMPTY_BUF): Cipher { + const ff1 = FF1(2, key, tweak); + return { + encrypt: (x: Uint8Array) => binLE.decode(ff1.encrypt(binLE.encode(x))), + decrypt: (x: Uint8Array) => binLE.decode(ff1.decrypt(binLE.encode(x))), + }; +} diff --git a/node_modules/@noble/ciphers/src/index.ts b/node_modules/@noble/ciphers/src/index.ts new file mode 100644 index 0000000..e1b6b61 --- /dev/null +++ b/node_modules/@noble/ciphers/src/index.ts @@ -0,0 +1 @@ +throw new Error('noble-ciphers have no entry-point: consult README for usage'); diff --git a/node_modules/@noble/ciphers/src/package.json b/node_modules/@noble/ciphers/src/package.json new file mode 100644 index 0000000..3dbc1ca --- /dev/null +++ b/node_modules/@noble/ciphers/src/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/@noble/ciphers/src/salsa.ts b/node_modules/@noble/ciphers/src/salsa.ts new file mode 100644 index 0000000..5cf5b92 --- /dev/null +++ b/node_modules/@noble/ciphers/src/salsa.ts @@ -0,0 +1,178 @@ +import { bytes as abytes } from './_assert.js'; +import { createCipher, rotl } from './_arx.js'; +import { poly1305 } from './_poly1305.js'; +import { wrapCipher, Cipher, equalBytes } from './utils.js'; + +// Salsa20 stream cipher was released in 2005. +// Salsa's goal was to implement AES replacement that does not rely on S-Boxes, +// which are hard to implement in a constant-time manner. +// https://cr.yp.to/snuffle.html, https://cr.yp.to/snuffle/salsafamily-20071225.pdf + +/** + * Salsa20 core function. + */ +// prettier-ignore +function salsaCore( + s: Uint32Array, k: Uint32Array, n: Uint32Array, out: Uint32Array, cnt: number, rounds = 20 +): void { + // Based on https://cr.yp.to/salsa20.html + let y00 = s[0], y01 = k[0], y02 = k[1], y03 = k[2], // "expa" Key Key Key + y04 = k[3], y05 = s[1], y06 = n[0], y07 = n[1], // Key "nd 3" Nonce Nonce + y08 = cnt, y09 = 0 , y10 = s[2], y11 = k[4], // Pos. Pos. "2-by" Key + y12 = k[5], y13 = k[6], y14 = k[7], y15 = s[3]; // Key Key Key "te k" + // Save state to temporary variables + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, + x04 = y04, x05 = y05, x06 = y06, x07 = y07, + x08 = y08, x09 = y09, x10 = y10, x11 = y11, + x12 = y12, x13 = y13, x14 = y14, x15 = y15; + for (let r = 0; r < rounds; r += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); x15 ^= rotl(x14 + x13 | 0, 18); + } + // Write output + let oi = 0; + out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0; +} + +/** + * hsalsa hashing function, used primarily in xsalsa, to hash + * key and nonce into key' and nonce'. + * Same as salsaCore, but there doesn't seem to be a way to move the block + * out without 25% performance hit. + */ +// prettier-ignore +export function hsalsa( + s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array +) { + let x00 = s[0], x01 = k[0], x02 = k[1], x03 = k[2], + x04 = k[3], x05 = s[1], x06 = i[0], x07 = i[1], + x08 = i[2], x09 = i[3], x10 = s[2], x11 = k[4], + x12 = k[5], x13 = k[6], x14 = k[7], x15 = s[3]; + for (let r = 0; r < 20; r += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); x15 ^= rotl(x14 + x13 | 0, 18); + } + let oi = 0; + o32[oi++] = x00; o32[oi++] = x05; + o32[oi++] = x10; o32[oi++] = x15; + o32[oi++] = x06; o32[oi++] = x07; + o32[oi++] = x08; o32[oi++] = x09; +} + +/** + * Salsa20 from original paper. + * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance. + */ +export const salsa20 = /* @__PURE__ */ createCipher(salsaCore, { + allowShortKeys: true, + counterRight: true, +}); + +/** + * xsalsa20 eXtended-nonce salsa. + * With 24-byte nonce, it's safe to use fill it with random (CSPRNG). + */ +export const xsalsa20 = /* @__PURE__ */ createCipher(salsaCore, { + counterRight: true, + extendNonceFn: hsalsa, +}); + +/** + * xsalsa20-poly1305 eXtended-nonce salsa. + * With 24-byte nonce, it's safe to use fill it with random (CSPRNG). + * Also known as secretbox from libsodium / nacl. + */ +export const xsalsa20poly1305 = /* @__PURE__ */ wrapCipher( + { blockSize: 64, nonceLength: 24, tagLength: 16 }, + (key: Uint8Array, nonce: Uint8Array): Cipher => { + const tagLength = 16; + abytes(key, 32); + abytes(nonce, 24); + return { + encrypt: (plaintext: Uint8Array, output?: Uint8Array) => { + abytes(plaintext); + // This is small optimization (calculate auth key with same call as encryption itself) makes it hard + // to separate tag calculation and encryption itself, since 32 byte is half-block of salsa (64 byte) + const clength = plaintext.length + 32; + if (output) { + abytes(output, clength); + } else { + output = new Uint8Array(clength); + } + output.set(plaintext, 32); + xsalsa20(key, nonce, output, output); + const authKey = output.subarray(0, 32); + const tag = poly1305(output.subarray(32), authKey); + // Clean auth key, even though JS provides no guarantees about memory cleaning + output.set(tag, tagLength); + output.subarray(0, tagLength).fill(0); + return output.subarray(tagLength); + }, + decrypt: (ciphertext: Uint8Array) => { + abytes(ciphertext); + const clength = ciphertext.length; + if (clength < tagLength) throw new Error('encrypted data should be at least 16 bytes'); + // Create new ciphertext array: + // auth tag auth tag from ciphertext ciphertext + // [bytes 0..16] [bytes 16..32] [bytes 32..] + // 16 instead of 32, because we already have 16 byte tag + const ciphertext_ = new Uint8Array(clength + tagLength); // alloc + ciphertext_.set(ciphertext, tagLength); + // Each xsalsa20 calls to hsalsa to calculate key, but seems not much perf difference + // Separate call to calculate authkey, since first bytes contains tag + const authKey = xsalsa20(key, nonce, new Uint8Array(32)); // alloc(32) + const tag = poly1305(ciphertext_.subarray(32), authKey); + if (!equalBytes(ciphertext_.subarray(16, 32), tag)) throw new Error('invalid tag'); + + const plaintext = xsalsa20(key, nonce, ciphertext_); // alloc + // Clean auth key, even though JS provides no guarantees about memory cleaning + plaintext.subarray(0, 32).fill(0); + authKey.fill(0); + return plaintext.subarray(32); + }, + }; + } +); + +/** + * Alias to xsalsa20poly1305, for compatibility with libsodium / nacl + */ +export function secretbox(key: Uint8Array, nonce: Uint8Array) { + const xs = xsalsa20poly1305(key, nonce); + return { seal: xs.encrypt, open: xs.decrypt }; +} diff --git a/node_modules/@noble/ciphers/src/utils.ts b/node_modules/@noble/ciphers/src/utils.ts new file mode 100644 index 0000000..08d0aff --- /dev/null +++ b/node_modules/@noble/ciphers/src/utils.ts @@ -0,0 +1,253 @@ +/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */ +import { bytes as abytes, isBytes } from './_assert.js'; +// prettier-ignore +export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | + Uint16Array | Int16Array | Uint32Array | Int32Array; + +// Cast array to different type +export const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +export const u16 = (arr: TypedArray) => + new Uint16Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 2)); +export const u32 = (arr: TypedArray) => + new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); + +// Cast array to view +export const createView = (arr: TypedArray) => + new DataView(arr.buffer, arr.byteOffset, arr.byteLength); + +// big-endian hardware is rare. Just in case someone still decides to run ciphers: +// early-throw an error because we don't support BE yet. +export const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!isLE) throw new Error('Non little-endian hardware is not supported'); + +// Array where index 0xf0 (240) is mapped to string 'f0' +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => + i.toString(16).padStart(2, '0') +); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export function bytesToHex(bytes: Uint8Array): string { + abytes(bytes); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} + +// We use optimized technique to convert hex string to byte array +const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 } as const; +function asciiToBase16(char: number): number | undefined { + if (char >= asciis._0 && char <= asciis._9) return char - asciis._0; + if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10); + if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10); + return; +} + +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export function hexToBytes(hex: string): Uint8Array { + if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex); + const hl = hex.length; + const al = hl / 2; + if (hl % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + hl); + const array = new Uint8Array(al); + for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { + const n1 = asciiToBase16(hex.charCodeAt(hi)); + const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); + if (n1 === undefined || n2 === undefined) { + const char = hex[hi] + hex[hi + 1]; + throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi); + } + array[ai] = n1 * 16 + n2; + } + return array; +} + +export function hexToNumber(hex: string): bigint { + if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex); + // Big Endian + return BigInt(hex === '' ? '0' : `0x${hex}`); +} + +// BE: Big Endian, LE: Little Endian +export function bytesToNumberBE(bytes: Uint8Array): bigint { + return hexToNumber(bytesToHex(bytes)); +} + +export function numberToBytesBE(n: number | bigint, len: number): Uint8Array { + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} + +// There is no setImmediate in browser and setTimeout is slow. +// call of async fn will return Promise, which will be fullfiled only on +// next scheduler queue processing step and this is exactly what we need. +export const nextTick = async () => {}; + +// Returns control to thread each 'tick' ms to avoid blocking +export async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) continue; + await nextTick(); + ts += diff; + } +} + +// Global symbols in both browsers and Node.js since v11 +// See https://github.com/microsoft/TypeScript/issues/31535 +declare const TextEncoder: any; +declare const TextDecoder: any; + +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export function utf8ToBytes(str: string): Uint8Array { + if (typeof str !== 'string') throw new Error(`string expected, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} + +/** + * @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc' + */ +export function bytesToUtf8(bytes: Uint8Array): string { + return new TextDecoder().decode(bytes); +} + +export type Input = Uint8Array | string; +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +export function toBytes(data: Input): Uint8Array { + if (typeof data === 'string') data = utf8ToBytes(data); + else if (isBytes(data)) data = data.slice(); + else throw new Error(`Uint8Array expected, got ${typeof data}`); + return data; +} + +/** + * Copies several Uint8Arrays into one. + */ +export function concatBytes(...arrays: Uint8Array[]): Uint8Array { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + abytes(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; +} + +type EmptyObj = {}; +export function checkOpts( + defaults: T1, + opts: T2 +): T1 & T2 { + if (opts == null || typeof opts !== 'object') throw new Error('options must be defined'); + const merged = Object.assign(defaults, opts); + return merged as T1 & T2; +} + +// Compares 2 u8a-s in kinda constant time +export function equalBytes(a: Uint8Array, b: Uint8Array) { + if (a.length !== b.length) return false; + let diff = 0; + for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i]; + return diff === 0; +} + +// For runtime check if class implements interface +export abstract class Hash> { + abstract blockLen: number; // Bytes per block + abstract outputLen: number; // Bytes in output + abstract update(buf: Input): this; + // Writes digest into buf + abstract digestInto(buf: Uint8Array): void; + abstract digest(): Uint8Array; + /** + * Resets internal state. Makes Hash instance unusable. + * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed + * by user, they will need to manually call `destroy()` when zeroing is necessary. + */ + abstract destroy(): void; +} + +// This will allow to re-use with composable things like packed & base encoders +// Also, we probably can make tags composable +export type Cipher = { + encrypt(plaintext: Uint8Array): Uint8Array; + decrypt(ciphertext: Uint8Array): Uint8Array; +}; + +export type AsyncCipher = { + encrypt(plaintext: Uint8Array): Promise; + decrypt(ciphertext: Uint8Array): Promise; +}; + +export type CipherWithOutput = Cipher & { + encrypt(plaintext: Uint8Array, output?: Uint8Array): Uint8Array; + decrypt(ciphertext: Uint8Array, output?: Uint8Array): Uint8Array; +}; + +// Params is outside return type, so it is accessible before calling constructor +// If function support multiple nonceLength's, we return best one +export type CipherParams = { blockSize: number; nonceLength?: number; tagLength?: number }; +export type CipherCons = (key: Uint8Array, ...args: T) => Cipher; +/** + * @__NO_SIDE_EFFECTS__ + */ +export const wrapCipher = , P extends CipherParams>( + params: P, + c: C +): C & P => { + Object.assign(c, params); + return c as C & P; +}; + +export type XorStream = ( + key: Uint8Array, + nonce: Uint8Array, + data: Uint8Array, + output?: Uint8Array, + counter?: number +) => Uint8Array; + +// Polyfill for Safari 14 +export function setBigUint64( + view: DataView, + byteOffset: number, + value: bigint, + isLE: boolean +): void { + if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} + +export function u64Lengths(ciphertext: Uint8Array, AAD?: Uint8Array) { + const num = new Uint8Array(16); + const view = createView(num); + setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true); + setBigUint64(view, 8, BigInt(ciphertext.length), true); + return num; +} diff --git a/node_modules/@noble/ciphers/src/webcrypto.ts b/node_modules/@noble/ciphers/src/webcrypto.ts new file mode 100644 index 0000000..c4a3ccb --- /dev/null +++ b/node_modules/@noble/ciphers/src/webcrypto.ts @@ -0,0 +1,125 @@ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.js on#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated, we can just drop the import. +// +// Use full path so that Node.js can rewrite it to `cryptoNode.js`. +import { randomBytes, getWebcryptoSubtle } from '@noble/ciphers/crypto'; +import { AsyncCipher, Cipher, concatBytes } from './utils.js'; +import { number, bytes as abytes } from './_assert.js'; + +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +export { randomBytes, getWebcryptoSubtle }; + +type RemoveNonceInner = ((...args: T) => Ret) extends ( + arg0: any, + arg1: any, + ...rest: infer R +) => any + ? (key: Uint8Array, ...args: R) => Ret + : never; + +type RemoveNonce any> = RemoveNonceInner, ReturnType>; +type CipherWithNonce = ((key: Uint8Array, nonce: Uint8Array, ...args: any[]) => Cipher) & { + nonceLength: number; +}; + +// Uses CSPRG for nonce, nonce injected in ciphertext +export function managedNonce(fn: T): RemoveNonce { + number(fn.nonceLength); + return ((key: Uint8Array, ...args: any[]): any => ({ + encrypt: (plaintext: Uint8Array, ...argsEnc: any[]) => { + const { nonceLength } = fn; + const nonce = randomBytes(nonceLength); + const ciphertext = (fn(key, nonce, ...args).encrypt as any)(plaintext, ...argsEnc); + const out = concatBytes(nonce, ciphertext); + ciphertext.fill(0); + return out; + }, + decrypt: (ciphertext: Uint8Array, ...argsDec: any[]) => { + const { nonceLength } = fn; + const nonce = ciphertext.subarray(0, nonceLength); + const data = ciphertext.subarray(nonceLength); + return (fn(key, nonce, ...args).decrypt as any)(data, ...argsDec); + }, + })) as RemoveNonce; +} + +// Overridable +export const utils = { + async encrypt(key: Uint8Array, keyParams: any, cryptParams: any, plaintext: Uint8Array) { + const cr = getWebcryptoSubtle(); + const iKey = await cr.importKey('raw', key, keyParams, true, ['encrypt']); + const ciphertext = await cr.encrypt(cryptParams, iKey, plaintext); + return new Uint8Array(ciphertext); + }, + async decrypt(key: Uint8Array, keyParams: any, cryptParams: any, ciphertext: Uint8Array) { + const cr = getWebcryptoSubtle(); + const iKey = await cr.importKey('raw', key, keyParams, true, ['decrypt']); + const plaintext = await cr.decrypt(cryptParams, iKey, ciphertext); + return new Uint8Array(plaintext); + }, +}; + +const mode = { + CBC: 'AES-CBC', + CTR: 'AES-CTR', + GCM: 'AES-GCM', +} as const; +type BlockMode = (typeof mode)[keyof typeof mode]; + +function getCryptParams(algo: BlockMode, nonce: Uint8Array, AAD?: Uint8Array) { + if (algo === mode.CBC) return { name: mode.CBC, iv: nonce }; + if (algo === mode.CTR) return { name: mode.CTR, counter: nonce, length: 64 }; + if (algo === mode.GCM) { + if (AAD) return { name: mode.GCM, iv: nonce, additionalData: AAD }; + else return { name: mode.GCM, iv: nonce }; + } + + throw new Error('unknown aes block mode'); +} + +function generate(algo: BlockMode) { + return (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): AsyncCipher => { + abytes(key); + abytes(nonce); + const keyParams = { name: algo, length: key.length * 8 }; + const cryptParams = getCryptParams(algo, nonce, AAD); + return { + // keyLength, + encrypt(plaintext: Uint8Array) { + abytes(plaintext); + return utils.encrypt(key, keyParams, cryptParams, plaintext); + }, + decrypt(ciphertext: Uint8Array) { + abytes(ciphertext); + return utils.decrypt(key, keyParams, cryptParams, ciphertext); + }, + }; + }; +} + +export const cbc = generate(mode.CBC); +export const ctr = generate(mode.CTR); +export const gcm = generate(mode.GCM); + +// // Type tests +// import { siv, gcm, ctr, ecb, cbc } from '../aes.js'; +// import { xsalsa20poly1305 } from '../salsa.js'; +// import { chacha20poly1305, xchacha20poly1305 } from '../chacha.js'; + +// const wsiv = managedNonce(siv); +// const wgcm = managedNonce(gcm); +// const wctr = managedNonce(ctr); +// const wcbc = managedNonce(cbc); +// const wsalsapoly = managedNonce(xsalsa20poly1305); +// const wchacha = managedNonce(chacha20poly1305); +// const wxchacha = managedNonce(xchacha20poly1305); + +// // should fail +// const wcbc2 = managedNonce(managedNonce(cbc)); +// const wecb = managedNonce(ecb); diff --git a/node_modules/@noble/ciphers/utils.d.ts b/node_modules/@noble/ciphers/utils.d.ts new file mode 100644 index 0000000..27590ec --- /dev/null +++ b/node_modules/@noble/ciphers/utils.d.ts @@ -0,0 +1,81 @@ +export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | Uint16Array | Int16Array | Uint32Array | Int32Array; +export declare const u8: (arr: TypedArray) => Uint8Array; +export declare const u16: (arr: TypedArray) => Uint16Array; +export declare const u32: (arr: TypedArray) => Uint32Array; +export declare const createView: (arr: TypedArray) => DataView; +export declare const isLE: boolean; +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export declare function bytesToHex(bytes: Uint8Array): string; +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export declare function hexToBytes(hex: string): Uint8Array; +export declare function hexToNumber(hex: string): bigint; +export declare function bytesToNumberBE(bytes: Uint8Array): bigint; +export declare function numberToBytesBE(n: number | bigint, len: number): Uint8Array; +export declare const nextTick: () => Promise; +export declare function asyncLoop(iters: number, tick: number, cb: (i: number) => void): Promise; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export declare function utf8ToBytes(str: string): Uint8Array; +/** + * @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc' + */ +export declare function bytesToUtf8(bytes: Uint8Array): string; +export type Input = Uint8Array | string; +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +export declare function toBytes(data: Input): Uint8Array; +/** + * Copies several Uint8Arrays into one. + */ +export declare function concatBytes(...arrays: Uint8Array[]): Uint8Array; +type EmptyObj = {}; +export declare function checkOpts(defaults: T1, opts: T2): T1 & T2; +export declare function equalBytes(a: Uint8Array, b: Uint8Array): boolean; +export declare abstract class Hash> { + abstract blockLen: number; + abstract outputLen: number; + abstract update(buf: Input): this; + abstract digestInto(buf: Uint8Array): void; + abstract digest(): Uint8Array; + /** + * Resets internal state. Makes Hash instance unusable. + * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed + * by user, they will need to manually call `destroy()` when zeroing is necessary. + */ + abstract destroy(): void; +} +export type Cipher = { + encrypt(plaintext: Uint8Array): Uint8Array; + decrypt(ciphertext: Uint8Array): Uint8Array; +}; +export type AsyncCipher = { + encrypt(plaintext: Uint8Array): Promise; + decrypt(ciphertext: Uint8Array): Promise; +}; +export type CipherWithOutput = Cipher & { + encrypt(plaintext: Uint8Array, output?: Uint8Array): Uint8Array; + decrypt(ciphertext: Uint8Array, output?: Uint8Array): Uint8Array; +}; +export type CipherParams = { + blockSize: number; + nonceLength?: number; + tagLength?: number; +}; +export type CipherCons = (key: Uint8Array, ...args: T) => Cipher; +/** + * @__NO_SIDE_EFFECTS__ + */ +export declare const wrapCipher: , P extends CipherParams>(params: P, c: C) => C & P; +export type XorStream = (key: Uint8Array, nonce: Uint8Array, data: Uint8Array, output?: Uint8Array, counter?: number) => Uint8Array; +export declare function setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void; +export declare function u64Lengths(ciphertext: Uint8Array, AAD?: Uint8Array): Uint8Array; +export {}; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/utils.d.ts.map b/node_modules/@noble/ciphers/utils.d.ts.map new file mode 100644 index 0000000..591539e --- /dev/null +++ b/node_modules/@noble/ciphers/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["src/utils.ts"],"names":[],"mappings":"AAGA,MAAM,MAAM,UAAU,GAAG,SAAS,GAAG,iBAAiB,GAAG,UAAU,GACjE,WAAW,GAAG,UAAU,GAAG,WAAW,GAAG,UAAU,CAAC;AAGtD,eAAO,MAAM,EAAE,QAAS,UAAU,eAA+D,CAAC;AAClG,eAAO,MAAM,GAAG,QAAS,UAAU,gBAC0C,CAAC;AAC9E,eAAO,MAAM,GAAG,QAAS,UAAU,gBAC0C,CAAC;AAG9E,eAAO,MAAM,UAAU,QAAS,UAAU,aACgB,CAAC;AAI3D,eAAO,MAAM,IAAI,SAAmE,CAAC;AAOrF;;GAEG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAQpD;AAWD;;GAEG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAgBlD;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAI/C;AAGD,wBAAgB,eAAe,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAEzD;AAED,wBAAgB,eAAe,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,UAAU,CAE3E;AAKD,eAAO,MAAM,QAAQ,qBAAiB,CAAC;AAGvC,wBAAsB,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,IAA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GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;IACpD,OAAO,CAAC,UAAU,EAAE,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;CACtD,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG;IACtC,OAAO,CAAC,SAAS,EAAE,UAAU,EAAE,MAAM,CAAC,EAAE,UAAU,GAAG,UAAU,CAAC;IAChE,OAAO,CAAC,UAAU,EAAE,UAAU,EAAE,MAAM,CAAC,EAAE,UAAU,GAAG,UAAU,CAAC;CAClE,CAAC;AAIF,MAAM,MAAM,YAAY,GAAG;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAC3F,MAAM,MAAM,UAAU,CAAC,CAAC,SAAS,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,IAAI,EAAE,CAAC,KAAK,MAAM,CAAC;AAClF;;GAEG;AACH,eAAO,MAAM,UAAU,+EAMtB,CAAC;AAEF,MAAM,MAAM,SAAS,GAAG,CACtB,GAAG,EAAE,UAAU,EACf,KAAK,EAAE,UAAU,EACjB,IAAI,EAAE,UAAU,EAChB,MAAM,CAAC,EAAE,UAAU,EACnB,OAAO,CAAC,EAAE,MAAM,KACb,UAAU,CAAC;AAGhB,wBAAgB,YAAY,CAC1B,IAAI,EAAE,QAAQ,EACd,UAAU,EAAE,MAAM,EAClB,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,OAAO,GACZ,IAAI,CAUN;AAED,wBAAgB,UAAU,CAAC,UAAU,EAAE,UAAU,EAAE,GAAG,CAAC,EAAE,UAAU,cAMlE"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/utils.js b/node_modules/@noble/ciphers/utils.js new file mode 100644 index 0000000..00cb4c2 --- /dev/null +++ b/node_modules/@noble/ciphers/utils.js @@ -0,0 +1,206 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.u64Lengths = exports.setBigUint64 = exports.wrapCipher = exports.Hash = exports.equalBytes = exports.checkOpts = exports.concatBytes = exports.toBytes = exports.bytesToUtf8 = exports.utf8ToBytes = exports.asyncLoop = exports.nextTick = exports.numberToBytesBE = exports.bytesToNumberBE = exports.hexToNumber = exports.hexToBytes = exports.bytesToHex = exports.isLE = exports.createView = exports.u32 = exports.u16 = exports.u8 = void 0; +/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */ +const _assert_js_1 = require("./_assert.js"); +// Cast array to different type +const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +exports.u8 = u8; +const u16 = (arr) => new Uint16Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 2)); +exports.u16 = u16; +const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +exports.u32 = u32; +// Cast array to view +const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +exports.createView = createView; +// big-endian hardware is rare. Just in case someone still decides to run ciphers: +// early-throw an error because we don't support BE yet. +exports.isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!exports.isLE) + throw new Error('Non little-endian hardware is not supported'); +// Array where index 0xf0 (240) is mapped to string 'f0' +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +function bytesToHex(bytes) { + (0, _assert_js_1.bytes)(bytes); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +exports.bytesToHex = bytesToHex; +// We use optimized technique to convert hex string to byte array +const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 }; +function asciiToBase16(char) { + if (char >= asciis._0 && char <= asciis._9) + return char - asciis._0; + if (char >= asciis._A && char <= asciis._F) + return char - (asciis._A - 10); + if (char >= asciis._a && char <= asciis._f) + return char - (asciis._a - 10); + return; +} +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const hl = hex.length; + const al = hl / 2; + if (hl % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + hl); + const array = new Uint8Array(al); + for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { + const n1 = asciiToBase16(hex.charCodeAt(hi)); + const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); + if (n1 === undefined || n2 === undefined) { + const char = hex[hi] + hex[hi + 1]; + throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi); + } + array[ai] = n1 * 16 + n2; + } + return array; +} +exports.hexToBytes = hexToBytes; +function hexToNumber(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + // Big Endian + return BigInt(hex === '' ? '0' : `0x${hex}`); +} +exports.hexToNumber = hexToNumber; +// BE: Big Endian, LE: Little Endian +function bytesToNumberBE(bytes) { + return hexToNumber(bytesToHex(bytes)); +} +exports.bytesToNumberBE = bytesToNumberBE; +function numberToBytesBE(n, len) { + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} +exports.numberToBytesBE = numberToBytesBE; +// There is no setImmediate in browser and setTimeout is slow. +// call of async fn will return Promise, which will be fullfiled only on +// next scheduler queue processing step and this is exactly what we need. +const nextTick = async () => { }; +exports.nextTick = nextTick; +// Returns control to thread each 'tick' ms to avoid blocking +async function asyncLoop(iters, tick, cb) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) + continue; + await (0, exports.nextTick)(); + ts += diff; + } +} +exports.asyncLoop = asyncLoop; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`string expected, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +exports.utf8ToBytes = utf8ToBytes; +/** + * @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc' + */ +function bytesToUtf8(bytes) { + return new TextDecoder().decode(bytes); +} +exports.bytesToUtf8 = bytesToUtf8; +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +function toBytes(data) { + if (typeof data === 'string') + data = utf8ToBytes(data); + else if ((0, _assert_js_1.isBytes)(data)) + data = data.slice(); + else + throw new Error(`Uint8Array expected, got ${typeof data}`); + return data; +} +exports.toBytes = toBytes; +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + (0, _assert_js_1.bytes)(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; +} +exports.concatBytes = concatBytes; +function checkOpts(defaults, opts) { + if (opts == null || typeof opts !== 'object') + throw new Error('options must be defined'); + const merged = Object.assign(defaults, opts); + return merged; +} +exports.checkOpts = checkOpts; +// Compares 2 u8a-s in kinda constant time +function equalBytes(a, b) { + if (a.length !== b.length) + return false; + let diff = 0; + for (let i = 0; i < a.length; i++) + diff |= a[i] ^ b[i]; + return diff === 0; +} +exports.equalBytes = equalBytes; +// For runtime check if class implements interface +class Hash { +} +exports.Hash = Hash; +/** + * @__NO_SIDE_EFFECTS__ + */ +const wrapCipher = (params, c) => { + Object.assign(c, params); + return c; +}; +exports.wrapCipher = wrapCipher; +// Polyfill for Safari 14 +function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +exports.setBigUint64 = setBigUint64; +function u64Lengths(ciphertext, AAD) { + const num = new Uint8Array(16); + const view = (0, exports.createView)(num); + setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true); + setBigUint64(view, 8, BigInt(ciphertext.length), true); + return num; +} +exports.u64Lengths = u64Lengths; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/utils.js.map b/node_modules/@noble/ciphers/utils.js.map new file mode 100644 index 0000000..78374b5 --- /dev/null +++ b/node_modules/@noble/ciphers/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["src/utils.ts"],"names":[],"mappings":";;;AAAA,uEAAuE;AACvE,6CAAwD;AAKxD,+BAA+B;AACxB,MAAM,EAAE,GAAG,CAAC,GAAe,EAAE,EAAE,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;AAArF,QAAA,EAAE,MAAmF;AAC3F,MAAM,GAAG,GAAG,CAAC,GAAe,EAAE,EAAE,CACrC,IAAI,WAAW,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,UAAU,GAAG,CAAC,CAAC,CAAC,CAAC;AADjE,QAAA,GAAG,OAC8D;AACvE,MAAM,GAAG,GAAG,CAAC,GAAe,EAAE,EAAE,CACrC,IAAI,WAAW,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,UAAU,GAAG,CAAC,CAAC,CAAC,CAA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AeC;AAED,SAAgB,UAAU,CAAC,UAAsB,EAAE,GAAgB;IACjE,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;IAC/B,MAAM,IAAI,GAAG,IAAA,kBAAU,EAAC,GAAG,CAAC,CAAC;IAC7B,YAAY,CAAC,IAAI,EAAE,CAAC,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;IAC1D,YAAY,CAAC,IAAI,EAAE,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC;IACvD,OAAO,GAAG,CAAC;AACb,CAAC;AAND,gCAMC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/webcrypto.d.ts b/node_modules/@noble/ciphers/webcrypto.d.ts new file mode 100644 index 0000000..44b34ba --- /dev/null +++ b/node_modules/@noble/ciphers/webcrypto.d.ts @@ -0,0 +1,20 @@ +import { randomBytes, getWebcryptoSubtle } from '@noble/ciphers/crypto'; +import { AsyncCipher, Cipher } from './utils.js'; +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +export { randomBytes, getWebcryptoSubtle }; +type RemoveNonceInner = ((...args: T) => Ret) extends (arg0: any, arg1: any, ...rest: infer R) => any ? (key: Uint8Array, ...args: R) => Ret : never; +type RemoveNonce any> = RemoveNonceInner, ReturnType>; +type CipherWithNonce = ((key: Uint8Array, nonce: Uint8Array, ...args: any[]) => Cipher) & { + nonceLength: number; +}; +export declare function managedNonce(fn: T): RemoveNonce; +export declare const utils: { + encrypt(key: Uint8Array, keyParams: any, cryptParams: any, plaintext: Uint8Array): Promise; + decrypt(key: Uint8Array, keyParams: any, cryptParams: any, ciphertext: Uint8Array): Promise; +}; +export declare const cbc: (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => AsyncCipher; +export declare const ctr: (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => AsyncCipher; +export declare const gcm: (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => AsyncCipher; +//# sourceMappingURL=webcrypto.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/webcrypto.d.ts.map b/node_modules/@noble/ciphers/webcrypto.d.ts.map new file mode 100644 index 0000000..8f5af2c --- /dev/null +++ b/node_modules/@noble/ciphers/webcrypto.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"webcrypto.d.ts","sourceRoot":"","sources":["src/webcrypto.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AACxE,OAAO,EAAE,WAAW,EAAE,MAAM,EAAe,MAAM,YAAY,CAAC;AAG9D;;GAEG;AACH,OAAO,EAAE,WAAW,EAAE,kBAAkB,EAAE,CAAC;AAE3C,KAAK,gBAAgB,CAAC,CAAC,SAAS,GAAG,EAAE,EAAE,GAAG,IAAI,CAAC,CAAC,GAAG,IAAI,EAAE,CAAC,KAAK,GAAG,CAAC,SAAS,CAC1E,IAAI,EAAE,GAAG,EACT,IAAI,EAAE,GAAG,EACT,GAAG,IAAI,EAAE,MAAM,CAAC,KACb,GAAG,GACJ,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,IAAI,EAAE,CAAC,KAAK,GAAG,GACpC,KAAK,CAAC;AAEV,KAAK,WAAW,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,KAAK,GAAG,IAAI,gBAAgB,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;AACnG,KAAK,eAAe,GAAG,CAAC,CAAC,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,MAAM,CAAC,GAAG;IACxF,WAAW,EAAE,MAAM,CAAC;CACrB,CAAC;AAGF,wBAAgB,YAAY,CAAC,CAAC,SAAS,eAAe,EAAE,EAAE,EAAE,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,CAkB7E;AAGD,eAAO,MAAM,KAAK;iBACG,UAAU,aAAa,GAAG,eAAe,GAAG,aAAa,UAAU;iBAMnE,UAAU,aAAa,GAAG,eAAe,GAAG,cAAc,UAAU;CAMxF,CAAC;AAwCF,eAAO,MAAM,GAAG,QAnBD,UAAU,SAAS,UAAU,QAAQ,UAAU,KAAG,WAmB5B,CAAC;AACtC,eAAO,MAAM,GAAG,QApBD,UAAU,SAAS,UAAU,QAAQ,UAAU,KAAG,WAoB5B,CAAC;AACtC,eAAO,MAAM,GAAG,QArBD,UAAU,SAAS,UAAU,QAAQ,UAAU,KAAG,WAqB5B,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/webcrypto.js b/node_modules/@noble/ciphers/webcrypto.js new file mode 100644 index 0000000..80911f3 --- /dev/null +++ b/node_modules/@noble/ciphers/webcrypto.js @@ -0,0 +1,107 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.gcm = exports.ctr = exports.cbc = exports.utils = exports.managedNonce = exports.getWebcryptoSubtle = exports.randomBytes = void 0; +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.js on#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated, we can just drop the import. +// +// Use full path so that Node.js can rewrite it to `cryptoNode.js`. +const crypto_1 = require("@noble/ciphers/crypto"); +Object.defineProperty(exports, "randomBytes", { enumerable: true, get: function () { return crypto_1.randomBytes; } }); +Object.defineProperty(exports, "getWebcryptoSubtle", { enumerable: true, get: function () { return crypto_1.getWebcryptoSubtle; } }); +const utils_js_1 = require("./utils.js"); +const _assert_js_1 = require("./_assert.js"); +// Uses CSPRG for nonce, nonce injected in ciphertext +function managedNonce(fn) { + (0, _assert_js_1.number)(fn.nonceLength); + return ((key, ...args) => ({ + encrypt: (plaintext, ...argsEnc) => { + const { nonceLength } = fn; + const nonce = (0, crypto_1.randomBytes)(nonceLength); + const ciphertext = fn(key, nonce, ...args).encrypt(plaintext, ...argsEnc); + const out = (0, utils_js_1.concatBytes)(nonce, ciphertext); + ciphertext.fill(0); + return out; + }, + decrypt: (ciphertext, ...argsDec) => { + const { nonceLength } = fn; + const nonce = ciphertext.subarray(0, nonceLength); + const data = ciphertext.subarray(nonceLength); + return fn(key, nonce, ...args).decrypt(data, ...argsDec); + }, + })); +} +exports.managedNonce = managedNonce; +// Overridable +exports.utils = { + async encrypt(key, keyParams, cryptParams, plaintext) { + const cr = (0, crypto_1.getWebcryptoSubtle)(); + const iKey = await cr.importKey('raw', key, keyParams, true, ['encrypt']); + const ciphertext = await cr.encrypt(cryptParams, iKey, plaintext); + return new Uint8Array(ciphertext); + }, + async decrypt(key, keyParams, cryptParams, ciphertext) { + const cr = (0, crypto_1.getWebcryptoSubtle)(); + const iKey = await cr.importKey('raw', key, keyParams, true, ['decrypt']); + const plaintext = await cr.decrypt(cryptParams, iKey, ciphertext); + return new Uint8Array(plaintext); + }, +}; +const mode = { + CBC: 'AES-CBC', + CTR: 'AES-CTR', + GCM: 'AES-GCM', +}; +function getCryptParams(algo, nonce, AAD) { + if (algo === mode.CBC) + return { name: mode.CBC, iv: nonce }; + if (algo === mode.CTR) + return { name: mode.CTR, counter: nonce, length: 64 }; + if (algo === mode.GCM) { + if (AAD) + return { name: mode.GCM, iv: nonce, additionalData: AAD }; + else + return { name: mode.GCM, iv: nonce }; + } + throw new Error('unknown aes block mode'); +} +function generate(algo) { + return (key, nonce, AAD) => { + (0, _assert_js_1.bytes)(key); + (0, _assert_js_1.bytes)(nonce); + const keyParams = { name: algo, length: key.length * 8 }; + const cryptParams = getCryptParams(algo, nonce, AAD); + return { + // keyLength, + encrypt(plaintext) { + (0, _assert_js_1.bytes)(plaintext); + return exports.utils.encrypt(key, keyParams, cryptParams, plaintext); + }, + decrypt(ciphertext) { + (0, _assert_js_1.bytes)(ciphertext); + return exports.utils.decrypt(key, keyParams, cryptParams, ciphertext); + }, + }; + }; +} +exports.cbc = generate(mode.CBC); +exports.ctr = generate(mode.CTR); +exports.gcm = generate(mode.GCM); +// // Type tests +// import { siv, gcm, ctr, ecb, cbc } from '../aes.js'; +// import { xsalsa20poly1305 } from '../salsa.js'; +// import { chacha20poly1305, xchacha20poly1305 } from '../chacha.js'; +// const wsiv = managedNonce(siv); +// const wgcm = managedNonce(gcm); +// const wctr = managedNonce(ctr); +// const wcbc = managedNonce(cbc); +// const wsalsapoly = managedNonce(xsalsa20poly1305); +// const wchacha = managedNonce(chacha20poly1305); +// const wxchacha = managedNonce(xchacha20poly1305); +// // should fail +// const wcbc2 = managedNonce(managedNonce(cbc)); +// const wecb = managedNonce(ecb); +//# sourceMappingURL=webcrypto.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/webcrypto.js.map b/node_modules/@noble/ciphers/webcrypto.js.map new file mode 100644 index 0000000..d749184 --- /dev/null +++ b/node_modules/@noble/ciphers/webcrypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"webcrypto.js","sourceRoot":"","sources":["src/webcrypto.ts"],"names":[],"mappings":";;;AAAA,oFAAoF;AACpF,sEAAsE;AACtE,mEAAmE;AACnE,8DAA8D;AAC9D,+DAA+D;AAC/D,8DAA8D;AAC9D,EAAE;AACF,mEAAmE;AACnE,kDAAwE;AAO/D,4FAPA,oBAAW,OAOA;AAAE,mGAPA,2BAAkB,OAOA;AANxC,yCAA8D;AAC9D,6CAAuD;AAoBvD,qDAAqD;AACrD,SAAgB,YAAY,CAA4B,EAAK;IAC3D,IAAA,mBAAM,EAAC,EAAE,CAAC,WAAW,CAAC,CAAC;IACvB,OAAO,CAAC,CAAC,GAAe,EAAE,GAAG,IAAW,EAAO,EAAE,CAAC,CAAC;QACjD,OAAO,EAAE,CAAC,SAAqB,EAAE,GAAG,OAAc,EAAE,EAAE;Y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file diff --git a/node_modules/@noble/curves/LICENSE b/node_modules/@noble/curves/LICENSE new file mode 100644 index 0000000..9297a04 --- /dev/null +++ b/node_modules/@noble/curves/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/@noble/curves/README.md b/node_modules/@noble/curves/README.md new file mode 100644 index 0000000..dfeaf76 --- /dev/null +++ b/node_modules/@noble/curves/README.md @@ -0,0 +1,1074 @@ +# noble-curves + +Audited & minimal JS implementation of elliptic curve cryptography. + +- 🔒 [**Audited**](#security) by an independent security firm +- 🔻 Tree-shaking-friendly: use only what's necessary, other code won't be included +- 🏎 Ultra-fast, hand-optimized for caveats of JS engines +- 🔍 Unique tests ensure correctness: property-based, cross-library and Wycheproof vectors, fuzzing +- ➰ Short Weierstrass, Edwards, Montgomery curves +- ✍️ ECDSA, EdDSA, Schnorr, BLS signature schemes, ECDH key agreement +- 🔖 SUF-CMA and SBS (non-repudiation) for ed25519, ed448 and others +- #️⃣ hash-to-curve for encoding or hashing an arbitrary string to an elliptic curve point +- 🧜‍♂️ Poseidon ZK-friendly hash + +### This library belongs to _noble_ crypto + +> **noble-crypto** — high-security, easily auditable set of contained cryptographic libraries and tools. + +- No dependencies, protection against supply chain attacks +- Auditable TypeScript / JS code +- Supported on all major platforms +- Releases are signed with PGP keys and built transparently with NPM provenance +- Check out [homepage](https://paulmillr.com/noble/) & all libraries: + [ciphers](https://github.com/paulmillr/noble-ciphers), + [curves](https://github.com/paulmillr/noble-curves), + [hashes](https://github.com/paulmillr/noble-hashes), + 4kb [secp256k1](https://github.com/paulmillr/noble-secp256k1) / + [ed25519](https://github.com/paulmillr/noble-ed25519) + +## Usage + +> npm install @noble/curves + +We support all major platforms and runtimes. +For [Deno](https://deno.land), ensure to use [npm specifier](https://deno.land/manual@v1.28.0/node/npm_specifiers). +For React Native, you may need a [polyfill for crypto.getRandomValues](https://github.com/LinusU/react-native-get-random-values). +If you don't like NPM, a standalone [noble-curves.js](https://github.com/paulmillr/noble-curves/releases) is also available. + +- [Implementations](#implementations) + - [ECDSA signature scheme](#ecdsa-signature-scheme) + - [ECDSA public key recovery & extra entropy](#ecdsa-public-key-recovery--extra-entropy) + - [ECDH (Elliptic Curve Diffie-Hellman)](#ecdh-elliptic-curve-diffie-hellman) + - [Schnorr signatures over secp256k1, BIP340](#schnorr-signatures-over-secp256k1-bip340) + - [ed25519, X25519, ristretto255](#ed25519-x25519-ristretto255) + - [ed448, X448, decaf448](#ed448-x448-decaf448) + - [bls12-381](#bls12-381) + - [All available imports](#all-available-imports) + - [Accessing a curve's variables](#accessing-a-curves-variables) +- [Abstract API](#abstract-api) + - [abstract/weierstrass: Short Weierstrass curve](#abstractweierstrass-short-weierstrass-curve) + - [abstract/edwards: Twisted Edwards curve](#abstractedwards-twisted-edwards-curve) + - [abstract/montgomery: Montgomery curve](#abstractmontgomery-montgomery-curve) + - [abstract/bls: Barreto-Lynn-Scott curves](#abstractbls-barreto-lynn-scott-curves) + - [abstract/hash-to-curve: Hashing strings to curve points](#abstracthash-to-curve-hashing-strings-to-curve-points) + - [abstract/poseidon: Poseidon hash](#abstractposeidon-poseidon-hash) + - [abstract/modular: Modular arithmetics utilities](#abstractmodular-modular-arithmetics-utilities) + - [Creating private keys from hashes](#creating-private-keys-from-hashes) + - [abstract/utils: Useful utilities](#abstractutils-useful-utilities) +- [Security](#security) +- [Speed](#speed) +- [Contributing & testing](#contributing--testing) +- [Upgrading](#upgrading) +- [Resources](#resources) + - [Demos](#demos) + - [Projects using curves](#projects-using-curves) +- [License](#license) + +### Implementations + +Implementations are utilizing [noble-hashes](https://github.com/paulmillr/noble-hashes). +[Abstract API](#abstract-api) doesn't depend on them: you can use a different hashing library. + +#### ECDSA signature scheme + +Generic example that works for all curves, shown for secp256k1: + +```ts +// import * from '@noble/curves'; // Error: use sub-imports, to ensure small app size +import { secp256k1 } from '@noble/curves/secp256k1'; // ESM and Common.js +// import { secp256k1 } from 'npm:@noble/curves@1.2.0/secp256k1'; // Deno +const priv = secp256k1.utils.randomPrivateKey(); +const pub = secp256k1.getPublicKey(priv); +const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa +const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available +const isValid = secp256k1.verify(sig, msg, pub) === true; + +// hex strings are also supported besides Uint8Arrays: +const privHex = '46c930bc7bb4db7f55da20798697421b98c4175a52c630294d75a84b9c126236'; +const pub2 = secp256k1.getPublicKey(privHex); +``` + +#### ECDSA public key recovery & extra entropy + +```ts +sig.recoverPublicKey(msg).toRawBytes(); // === pub; // public key recovery + +// extraEntropy https://moderncrypto.org/mail-archive/curves/2017/000925.html +const sigImprovedSecurity = secp256k1.sign(msg, priv, { extraEntropy: true }); +``` + +#### ECDH (Elliptic Curve Diffie-Hellman) + +```ts +// 1. The output includes parity byte. Strip it using shared.slice(1) +// 2. The output is not hashed. More secure way is sha256(shared) or hkdf(shared) +const someonesPub = secp256k1.getPublicKey(secp256k1.utils.randomPrivateKey()); +const shared = secp256k1.getSharedSecret(priv, someonesPub); +``` + +#### Schnorr signatures over secp256k1 (BIP340) + +```ts +import { schnorr } from '@noble/curves/secp256k1'; +const priv = schnorr.utils.randomPrivateKey(); +const pub = schnorr.getPublicKey(priv); +const msg = new TextEncoder().encode('hello'); +const sig = schnorr.sign(msg, priv); +const isValid = schnorr.verify(sig, msg, pub); +``` + +#### ed25519, X25519, ristretto255 + +```ts +import { ed25519 } from '@noble/curves/ed25519'; +const priv = ed25519.utils.randomPrivateKey(); +const pub = ed25519.getPublicKey(priv); +const msg = new TextEncoder().encode('hello'); +const sig = ed25519.sign(msg, priv); +ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215 +ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5 +``` + +Default `verify` behavior follows [ZIP215](https://zips.z.cash/zip-0215) and +[can be used in consensus-critical applications](https://hdevalence.ca/blog/2020-10-04-its-25519am). +It has SUF-CMA (strong unforgeability under chosen message attacks). +`zip215: false` option switches verification criteria to strict +[RFC8032](https://www.rfc-editor.org/rfc/rfc8032) / [FIPS 186-5](https://csrc.nist.gov/publications/detail/fips/186/5/final) +and additionally provides non-repudiation with SBS [(Strongly Binding Signatures)](https://eprint.iacr.org/2020/1244). + +X25519 follows [RFC7748](https://www.rfc-editor.org/rfc/rfc7748). + +```ts +// Variants from RFC8032: with context, prehashed +import { ed25519ctx, ed25519ph } from '@noble/curves/ed25519'; + +// ECDH using curve25519 aka x25519 +import { x25519 } from '@noble/curves/ed25519'; +const priv = 'a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4'; +const pub = 'e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c'; +x25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub); // aliases +x25519.getPublicKey(priv) === x25519.scalarMultBase(priv); +x25519.getPublicKey(x25519.utils.randomPrivateKey()); + +// ed25519 => x25519 conversion +import { edwardsToMontgomeryPub, edwardsToMontgomeryPriv } from '@noble/curves/ed25519'; +edwardsToMontgomeryPub(ed25519.getPublicKey(ed25519.utils.randomPrivateKey())); +edwardsToMontgomeryPriv(ed25519.utils.randomPrivateKey()); +``` + +ristretto255 follows [irtf draft](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448). + +```ts +// hash-to-curve, ristretto255 +import { utf8ToBytes } from '@noble/hashes/utils'; +import { sha512 } from '@noble/hashes/sha512'; +import { + hashToCurve, + encodeToCurve, + RistrettoPoint, + hashToRistretto255, +} from '@noble/curves/ed25519'; + +const msg = utf8ToBytes('Ristretto is traditionally a short shot of espresso coffee'); +hashToCurve(msg); + +const rp = RistrettoPoint.fromHex( + '6a493210f7499cd17fecb510ae0cea23a110e8d5b901f8acadd3095c73a3b919' +); +RistrettoPoint.BASE.multiply(2n).add(rp).subtract(RistrettoPoint.BASE).toRawBytes(); +RistrettoPoint.ZERO.equals(dp) === false; +// pre-hashed hash-to-curve +RistrettoPoint.hashToCurve(sha512(msg)); +// full hash-to-curve including domain separation tag +hashToRistretto255(msg, { DST: 'ristretto255_XMD:SHA-512_R255MAP_RO_' }); +``` + +#### ed448, X448, decaf448 + +```ts +import { ed448 } from '@noble/curves/ed448'; +const priv = ed448.utils.randomPrivateKey(); +const pub = ed448.getPublicKey(priv); +const msg = new TextEncoder().encode('whatsup'); +const sig = ed448.sign(msg, priv); +ed448.verify(sig, msg, pub); + +// Variants from RFC8032: prehashed +import { ed448ph } from '@noble/curves/ed448'; +``` + +ECDH using Curve448 aka X448, follows [RFC7748](https://www.rfc-editor.org/rfc/rfc7748). + +```ts +import { x448 } from '@noble/curves/ed448'; +x448.getSharedSecret(priv, pub) === x448.scalarMult(priv, pub); // aliases +x448.getPublicKey(priv) === x448.scalarMultBase(priv); + +// ed448 => x448 conversion +import { edwardsToMontgomeryPub } from '@noble/curves/ed448'; +edwardsToMontgomeryPub(ed448.getPublicKey(ed448.utils.randomPrivateKey())); +``` + +decaf448 follows [irtf draft](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448). + +```ts +import { utf8ToBytes } from '@noble/hashes/utils'; +import { shake256 } from '@noble/hashes/sha3'; +import { hashToCurve, encodeToCurve, DecafPoint, hashToDecaf448 } from '@noble/curves/ed448'; + +const msg = utf8ToBytes('Ristretto is traditionally a short shot of espresso coffee'); +hashToCurve(msg); + +const dp = DecafPoint.fromHex( + 'c898eb4f87f97c564c6fd61fc7e49689314a1f818ec85eeb3bd5514ac816d38778f69ef347a89fca817e66defdedce178c7cc709b2116e75' +); +DecafPoint.BASE.multiply(2n).add(dp).subtract(DecafPoint.BASE).toRawBytes(); +DecafPoint.ZERO.equals(dp) === false; +// pre-hashed hash-to-curve +DecafPoint.hashToCurve(shake256(msg, { dkLen: 112 })); +// full hash-to-curve including domain separation tag +hashToDecaf448(msg, { DST: 'decaf448_XOF:SHAKE256_D448MAP_RO_' }); +``` + +Same RFC7748 / RFC8032 / IRTF draft are followed. + +#### bls12-381 + +See [abstract/bls](#abstractbls-barreto-lynn-scott-curves). + +#### All available imports + +```typescript +import { secp256k1, schnorr } from '@noble/curves/secp256k1'; +import { ed25519, ed25519ph, ed25519ctx, x25519, RistrettoPoint } from '@noble/curves/ed25519'; +import { ed448, ed448ph, ed448ctx, x448 } from '@noble/curves/ed448'; +import { p256 } from '@noble/curves/p256'; +import { p384 } from '@noble/curves/p384'; +import { p521 } from '@noble/curves/p521'; +import { pallas, vesta } from '@noble/curves/pasta'; +import { bls12_381 } from '@noble/curves/bls12-381'; +import { bn254 } from '@noble/curves/bn254'; // also known as alt_bn128 +import { jubjub } from '@noble/curves/jubjub'; +import { bytesToHex, hexToBytes, concatBytes, utf8ToBytes } from '@noble/curves/abstract/utils'; +``` + +#### Accessing a curve's variables + +```ts +import { secp256k1 } from '@noble/curves/secp256k1'; +// Every curve has `CURVE` object that contains its parameters, field, and others +console.log(secp256k1.CURVE.p); // field modulus +console.log(secp256k1.CURVE.n); // curve order +console.log(secp256k1.CURVE.a, secp256k1.CURVE.b); // equation params +console.log(secp256k1.CURVE.Gx, secp256k1.CURVE.Gy); // base point coordinates +``` + +## Abstract API + +Abstract API allows to define custom curves. All arithmetics is done with JS +bigints over finite fields, which is defined from `modular` sub-module. For +scalar multiplication, we use +[precomputed tables with w-ary non-adjacent form (wNAF)](https://paulmillr.com/posts/noble-secp256k1-fast-ecc/). +Precomputes are enabled for weierstrass and edwards BASE points of a curve. You +could precompute any other point (e.g. for ECDH) using `utils.precompute()` +method: check out examples. + +### abstract/weierstrass: Short Weierstrass curve + +```ts +import { weierstrass } from '@noble/curves/abstract/weierstrass'; +import { Field } from '@noble/curves/abstract/modular'; // finite field for mod arithmetics +import { sha256 } from '@noble/hashes/sha256'; // 3rd-party sha256() of type utils.CHash +import { hmac } from '@noble/hashes/hmac'; // 3rd-party hmac() that will accept sha256() +import { concatBytes, randomBytes } from '@noble/hashes/utils'; // 3rd-party utilities +const secq256k1 = weierstrass({ + // secq256k1: cycle of secp256k1 with Fp/N flipped. + // https://personaelabs.org/posts/spartan-ecdsa + // https://zcash.github.io/halo2/background/curves.html#cycles-of-curves + a: 0n, + b: 7n, + Fp: Field(2n ** 256n - 432420386565659656852420866394968145599n), + n: 2n ** 256n - 2n ** 32n - 2n ** 9n - 2n ** 8n - 2n ** 7n - 2n ** 6n - 2n ** 4n - 1n, + Gx: 55066263022277343669578718895168534326250603453777594175500187360389116729240n, + Gy: 32670510020758816978083085130507043184471273380659243275938904335757337482424n, + hash: sha256, + hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(sha256, key, concatBytes(...msgs)), + randomBytes, +}); + +// Replace weierstrass() with weierstrassPoints() if you don't need ECDSA, hash, hmac, randomBytes +``` + +Short Weierstrass curve's formula is `y² = x³ + ax + b`. `weierstrass` +expects arguments `a`, `b`, field `Fp`, curve order `n`, cofactor `h` +and coordinates `Gx`, `Gy` of generator point. + +**`k` generation** is done deterministically, following +[RFC6979](https://www.rfc-editor.org/rfc/rfc6979). For this you will need +`hmac` & `hash`, which in our implementations is provided by noble-hashes. If +you're using different hashing library, make sure to wrap it in the following interface: + +```ts +type CHash = { + (message: Uint8Array): Uint8Array; + blockLen: number; + outputLen: number; + create(): any; +}; +``` + +**Message hash** is expected instead of message itself: + +- `sign(msgHash, privKey)` is default behavior, assuming you pre-hash msg with sha2, or other hash +- `sign(msg, privKey, {prehash: true})` option can be used if you want to pass the message itself + +**Weierstrass points:** + +1. Exported as `ProjectivePoint` +2. Represented in projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z) +3. Use complete exception-free formulas for addition and doubling +4. Can be decoded/encoded from/to Uint8Array / hex strings using + `ProjectivePoint.fromHex` and `ProjectivePoint#toRawBytes()` +5. Have `assertValidity()` which checks for being on-curve +6. Have `toAffine()` and `x` / `y` getters which convert to 2d xy affine coordinates + +```ts +// `weierstrassPoints()` returns `CURVE` and `ProjectivePoint` +// `weierstrass()` returns `CurveFn` +type SignOpts = { lowS?: boolean; prehash?: boolean; extraEntropy: boolean | Uint8Array }; +type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => SignatureType; + verify: ( + signature: Hex | SignatureType, + msgHash: Hex, + publicKey: Hex, + opts?: { lowS?: boolean; prehash?: boolean } + ) => boolean; + ProjectivePoint: ProjectivePointConstructor; + Signature: SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: PrivKey) => bigint; + isValidPrivateKey(key: PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: ProjPointType) => ProjPointType; + }; +}; + +// T is usually bigint, but can be something else like complex numbers in BLS curves +interface ProjPointType extends Group> { + readonly px: T; + readonly py: T; + readonly pz: T; + get x(): bigint; + get y(): bigint; + multiply(scalar: bigint): ProjPointType; + multiplyUnsafe(scalar: bigint): ProjPointType; + multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined; + toAffine(iz?: T): AffinePoint; + isTorsionFree(): boolean; + clearCofactor(): ProjPointType; + assertValidity(): void; + hasEvenY(): boolean; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; +} +// Static methods for 3d XYZ points +interface ProjConstructor extends GroupConstructor> { + new (x: T, y: T, z: T): ProjPointType; + fromAffine(p: AffinePoint): ProjPointType; + fromHex(hex: Hex): ProjPointType; + fromPrivateKey(privateKey: PrivKey): ProjPointType; +} +``` + +**ECDSA signatures** are represented by `Signature` instances and can be +described by the interface: + +```ts +interface SignatureType { + readonly r: bigint; + readonly s: bigint; + readonly recovery?: number; + assertValidity(): void; + addRecoveryBit(recovery: number): SignatureType; + hasHighS(): boolean; + normalizeS(): SignatureType; + recoverPublicKey(msgHash: Hex): ProjPointType; + toCompactRawBytes(): Uint8Array; + toCompactHex(): string; + // DER-encoded + toDERRawBytes(): Uint8Array; + toDERHex(): string; +} +type SignatureConstructor = { + new (r: bigint, s: bigint): SignatureType; + fromCompact(hex: Hex): SignatureType; + fromDER(hex: Hex): SignatureType; +}; +``` + +More examples: + +```typescript +// All curves expose same generic interface. +const priv = secq256k1.utils.randomPrivateKey(); +secq256k1.getPublicKey(priv); // Convert private key to public. +const sig = secq256k1.sign(msg, priv); // Sign msg with private key. +const sig2 = secq256k1.sign(msg, priv, { prehash: true }); // hash(msg) +secq256k1.verify(sig, msg, priv); // Verify if sig is correct. + +const Point = secq256k1.ProjectivePoint; +const point = Point.BASE; // Elliptic curve Point class and BASE point static var. +point.add(point).equals(point.double()); // add(), equals(), double() methods +point.subtract(point).equals(Point.ZERO); // subtract() method, ZERO static var +point.negate(); // Flips point over x/y coordinate. +point.multiply(31415n); // Multiplication of Point by scalar. + +point.assertValidity(); // Checks for being on-curve +point.toAffine(); // Converts to 2d affine xy coordinates + +secq256k1.CURVE.n; +secq256k1.CURVE.p; +secq256k1.CURVE.Fp.mod(); +secq256k1.CURVE.hash(); + +// precomputes +const fast = secq256k1.utils.precompute(8, Point.fromHex(someonesPubKey)); +fast.multiply(privKey); // much faster ECDH now +``` + +### abstract/edwards: Twisted Edwards curve + +```ts +import { twistedEdwards } from '@noble/curves/abstract/edwards'; +import { Field } from '@noble/curves/abstract/modular'; +import { sha512 } from '@noble/hashes/sha512'; +import { randomBytes } from '@noble/hashes/utils'; + +const Fp = Field(2n ** 255n - 19n); +const ed25519 = twistedEdwards({ + a: Fp.create(-1n), + d: Fp.div(-121665n, 121666n), // -121665n/121666n mod p + Fp: Fp, + n: 2n ** 252n + 27742317777372353535851937790883648493n, + h: 8n, + Gx: 15112221349535400772501151409588531511454012693041857206046113283949847762202n, + Gy: 46316835694926478169428394003475163141307993866256225615783033603165251855960n, + hash: sha512, + randomBytes, + adjustScalarBytes(bytes) { + // optional; but mandatory in ed25519 + bytes[0] &= 248; + bytes[31] &= 127; + bytes[31] |= 64; + return bytes; + }, +} as const); +``` + +Twisted Edwards curve's formula is `ax² + y² = 1 + dx²y²`. You must specify `a`, `d`, field `Fp`, order `n`, cofactor `h` +and coordinates `Gx`, `Gy` of generator point. + +For EdDSA signatures, `hash` param required. `adjustScalarBytes` which instructs how to change private scalars could be specified. + +**Edwards points:** + +1. Exported as `ExtendedPoint` +2. Represented in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z) +3. Use complete exception-free formulas for addition and doubling +4. Can be decoded/encoded from/to Uint8Array / hex strings using `ExtendedPoint.fromHex` and `ExtendedPoint#toRawBytes()` +5. Have `assertValidity()` which checks for being on-curve +6. Have `toAffine()` and `x` / `y` getters which convert to 2d xy affine coordinates +7. Have `isTorsionFree()`, `clearCofactor()` and `isSmallOrder()` utilities to handle torsions + +```ts +// `twistedEdwards()` returns `CurveFn` of following type: +type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: Hex) => Uint8Array; + sign: (message: Hex, privateKey: Hex, context?: Hex) => Uint8Array; + verify: (sig: SigType, message: Hex, publicKey: Hex, context?: Hex) => boolean; + ExtendedPoint: ExtPointConstructor; + utils: { + randomPrivateKey: () => Uint8Array; + getExtendedPublicKey: (key: PrivKey) => { + head: Uint8Array; + prefix: Uint8Array; + scalar: bigint; + point: PointType; + pointBytes: Uint8Array; + }; + }; +}; + +interface ExtPointType extends Group { + readonly ex: bigint; + readonly ey: bigint; + readonly ez: bigint; + readonly et: bigint; + get x(): bigint; + get y(): bigint; + assertValidity(): void; + multiply(scalar: bigint): ExtPointType; + multiplyUnsafe(scalar: bigint): ExtPointType; + isSmallOrder(): boolean; + isTorsionFree(): boolean; + clearCofactor(): ExtPointType; + toAffine(iz?: bigint): AffinePoint; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; +} +// Static methods of Extended Point with coordinates in X, Y, Z, T +interface ExtPointConstructor extends GroupConstructor { + new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType; + fromAffine(p: AffinePoint): ExtPointType; + fromHex(hex: Hex): ExtPointType; + fromPrivateKey(privateKey: Hex): ExtPointType; +} +``` + +### abstract/montgomery: Montgomery curve + +```typescript +import { montgomery } from '@noble/curves/abstract/montgomery'; +import { Field } from '@noble/curves/abstract/modular'; + +const x25519 = montgomery({ + a: 486662n, + Gu: 9n, + Fp: Field(2n ** 255n - 19n), + montgomeryBits: 255, + nByteLength: 32, + // Optional param + adjustScalarBytes(bytes) { + bytes[0] &= 248; + bytes[31] &= 127; + bytes[31] |= 64; + return bytes; + }, +}); +``` + +The module contains methods for x-only ECDH on Curve25519 / Curve448 from RFC7748. +Proper Elliptic Curve Points are not implemented yet. + +You must specify curve params `Fp`, `a`, `Gu` coordinate of u, `montgomeryBits` and `nByteLength`. + +### abstract/bls: Barreto-Lynn-Scott curves + +The module abstracts BLS (Barreto-Lynn-Scott) pairing-friendly elliptic curve construction. +They allow to construct [zk-SNARKs](https://z.cash/technology/zksnarks/) and +use aggregated, batch-verifiable +[threshold signatures](https://medium.com/snigirev.stepan/bls-signatures-better-than-schnorr-5a7fe30ea716), +using Boneh-Lynn-Shacham signature scheme. + +The module doesn't expose `CURVE` property: use `G1.CURVE`, `G2.CURVE` instead. + +Main methods and properties are: + +- `getPublicKey(privateKey)` +- `sign(message, privateKey)` +- `verify(signature, message, publicKey)` +- `aggregatePublicKeys(publicKeys)` +- `aggregateSignatures(signatures)` +- `G1` and `G2` curves containing `CURVE` and `ProjectivePoint` +- `Signature` property with `fromHex`, `toHex` methods +- `fields` containing `Fp`, `Fp2`, `Fp6`, `Fp12`, `Fr` + +Right now we only implement BLS12-381 (compatible with ETH and others), +but in theory defining BLS12-377, BLS24 should be straightforward. An example: + +```ts +import { bls12_381 as bls } from '@noble/curves/bls12-381'; +const privateKey = '67d53f170b908cabb9eb326c3c337762d59289a8fec79f7bc9254b584b73265c'; +const message = '64726e3da8'; +const publicKey = bls.getPublicKey(privateKey); +const signature = bls.sign(message, privateKey); +const isValid = bls.verify(signature, message, publicKey); +console.log({ publicKey, signature, isValid }); + +// Sign 1 msg with 3 keys +const privateKeys = [ + '18f020b98eb798752a50ed0563b079c125b0db5dd0b1060d1c1b47d4a193e1e4', + 'ed69a8c50cf8c9836be3b67c7eeff416612d45ba39a5c099d48fa668bf558c9c', + '16ae669f3be7a2121e17d0c68c05a8f3d6bef21ec0f2315f1d7aec12484e4cf5', +]; +const messages = ['d2', '0d98', '05caf3']; +const publicKeys = privateKeys.map(bls.getPublicKey); +const signatures2 = privateKeys.map((p) => bls.sign(message, p)); +const aggPubKey2 = bls.aggregatePublicKeys(publicKeys); +const aggSignature2 = bls.aggregateSignatures(signatures2); +const isValid2 = bls.verify(aggSignature2, message, aggPubKey2); +console.log({ signatures2, aggSignature2, isValid2 }); + +// Sign 3 msgs with 3 keys +const signatures3 = privateKeys.map((p, i) => bls.sign(messages[i], p)); +const aggSignature3 = bls.aggregateSignatures(signatures3); +const isValid3 = bls.verifyBatch(aggSignature3, messages, publicKeys); +console.log({ publicKeys, signatures3, aggSignature3, isValid3 }); + +// Pairings, with and without final exponentiation +// bls.pairing(PointG1, PointG2); +// bls.pairing(PointG1, PointG2, false); +// bls.fields.Fp12.finalExponentiate(bls.fields.Fp12.mul(eGS, ePHm)); + +// Others +// bls.G1.ProjectivePoint.BASE, bls.G2.ProjectivePoint.BASE +// bls.fields.Fp, bls.fields.Fp2, bls.fields.Fp12, bls.fields.Fr + +// hash-to-curve examples can be seen below +``` + +Full types: + +```ts +getPublicKey: (privateKey: PrivKey) => Uint8Array; +sign: { + (message: Hex, privateKey: PrivKey): Uint8Array; + (message: ProjPointType, privateKey: PrivKey): ProjPointType; +}; +verify: ( + signature: Hex | ProjPointType, + message: Hex | ProjPointType, + publicKey: Hex | ProjPointType +) => boolean; +verifyBatch: ( + signature: Hex | ProjPointType, + messages: (Hex | ProjPointType)[], + publicKeys: (Hex | ProjPointType)[] +) => boolean; +aggregatePublicKeys: { + (publicKeys: Hex[]): Uint8Array; + (publicKeys: ProjPointType[]): ProjPointType; +}; +aggregateSignatures: { + (signatures: Hex[]): Uint8Array; + (signatures: ProjPointType[]): ProjPointType; +}; +millerLoop: (ell: [Fp2, Fp2, Fp2][], g1: [Fp, Fp]) => Fp12; +pairing: (P: ProjPointType, Q: ProjPointType, withFinalExponent?: boolean) => Fp12; +G1: CurvePointsRes & ReturnType>; +G2: CurvePointsRes & ReturnType>; +Signature: SignatureCoder; +params: { + x: bigint; + r: bigint; + G1b: bigint; + G2b: Fp2; +}; +fields: { + Fp: IField; + Fp2: IField; + Fp6: IField; + Fp12: IField; + Fr: IField; +}; +utils: { + randomPrivateKey: () => Uint8Array; + calcPairingPrecomputes: (p: AffinePoint) => [Fp2, Fp2, Fp2][]; +}; +``` + +### abstract/hash-to-curve: Hashing strings to curve points + +The module allows to hash arbitrary strings to elliptic curve points. Implements [RFC 9380](https://www.rfc-editor.org/rfc/rfc9380). + +Every curve has exported `hashToCurve` and `encodeToCurve` methods. You should always prefer `hashToCurve` for security: + +```ts +import { hashToCurve, encodeToCurve } from '@noble/curves/secp256k1'; +import { randomBytes } from '@noble/hashes/utils'; +hashToCurve('0102abcd'); +console.log(hashToCurve(randomBytes())); +console.log(encodeToCurve(randomBytes())); + +import { bls12_381 } from '@noble/curves/bls12-381'; +bls12_381.G1.hashToCurve(randomBytes(), { DST: 'another' }); +bls12_381.G2.hashToCurve(randomBytes(), { DST: 'custom' }); +``` + +Low-level methods from the spec: + +```ts +// produces a uniformly random byte string using a cryptographic hash function H that outputs b bits. +function expand_message_xmd( + msg: Uint8Array, + DST: Uint8Array, + lenInBytes: number, + H: CHash // For CHash see abstract/weierstrass docs section +): Uint8Array; +// produces a uniformly random byte string using an extendable-output function (XOF) H. +function expand_message_xof( + msg: Uint8Array, + DST: Uint8Array, + lenInBytes: number, + k: number, + H: CHash +): Uint8Array; +// Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F +function hash_to_field(msg: Uint8Array, count: number, options: Opts): bigint[][]; + +/** + * * `DST` is a domain separation tag, defined in section 2.2.5 + * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m + * * `m` is extension degree (1 for prime fields) + * * `k` is the target security target in bits (e.g. 128), from section 5.1 + * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF) + * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props + */ +type UnicodeOrBytes = string | Uint8Array; +type Opts = { + DST: UnicodeOrBytes; + p: bigint; + m: number; + k: number; + expand?: 'xmd' | 'xof'; + hash: CHash; +}; +``` + +### abstract/poseidon: Poseidon hash + +Implements [Poseidon](https://www.poseidon-hash.info) ZK-friendly hash. + +There are many poseidon variants with different constants. +We don't provide them: you should construct them manually. +Check out [micro-starknet](https://github.com/paulmillr/micro-starknet) package for a proper example. + +```ts +import { poseidon } from '@noble/curves/abstract/poseidon'; + +type PoseidonOpts = { + Fp: Field; + t: number; + roundsFull: number; + roundsPartial: number; + sboxPower?: number; + reversePartialPowIdx?: boolean; + mds: bigint[][]; + roundConstants: bigint[][]; +}; +const instance = poseidon(opts: PoseidonOpts); +``` + +### abstract/modular: Modular arithmetics utilities + +```ts +import * as mod from '@noble/curves/abstract/modular'; +const fp = mod.Field(2n ** 255n - 19n); // Finite field over 2^255-19 +fp.mul(591n, 932n); // multiplication +fp.pow(481n, 11024858120n); // exponentiation +fp.div(5n, 17n); // division: 5/17 mod 2^255-19 == 5 * invert(17) +fp.sqrt(21n); // square root + +// Generic non-FP utils are also available +mod.mod(21n, 10n); // 21 mod 10 == 1n; fixed version of 21 % 10 +mod.invert(17n, 10n); // invert(17) mod 10; modular multiplicative inverse +mod.invertBatch([1n, 2n, 4n], 21n); // => [1n, 11n, 16n] in one inversion +``` + +Field operations are not constant-time: they are using JS bigints, see [security](#security). +The fact is mostly irrelevant, but the important method to keep in mind is `pow`, +which may leak exponent bits, when used naïvely. + +`mod.Field` is always **field over prime**. Non-prime fields aren't supported for now. +We don't test for prime-ness for speed and because algorithms are probabilistic anyway. +Initializing a non-prime field could make your app suspectible to +DoS (infilite loop) on Tonelli-Shanks square root calculation. + +Unlike `mod.invert`, `mod.invertBatch` won't throw on `0`: make sure to throw an error yourself. + +#### Creating private keys from hashes + +You can't simply make a 32-byte private key from a 32-byte hash. +Doing so will make the key [biased](https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/). + +To make the bias negligible, we follow [FIPS 186-5 A.2](https://csrc.nist.gov/publications/detail/fips/186/5/final) +and [RFC 9380](https://www.rfc-editor.org/rfc/rfc9380#section-5.2). +This means, for 32-byte key, we would need 48-byte hash to get 2^-128 bias, which matches curve security level. + +`hashToPrivateScalar()` that hashes to **private key** was created for this purpose. +Use [abstract/hash-to-curve](#abstracthash-to-curve-hashing-strings-to-curve-points) +if you need to hash to **public key**. + +```ts +import { p256 } from '@noble/curves/p256'; +import { sha256 } from '@noble/hashes/sha256'; +import { hkdf } from '@noble/hashes/hkdf'; +const someKey = new Uint8Array(32).fill(2); // Needs to actually be random, not .fill(2) +const derived = hkdf(sha256, someKey, undefined, 'application', 48); // 48 bytes for 32-byte priv +const validPrivateKey = mod.hashToPrivateScalar(derived, p256.CURVE.n); +``` + +### abstract/utils: Useful utilities + +```ts +import * as utils from '@noble/curves/abstract/utils'; + +utils.bytesToHex(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])); +utils.hexToBytes('deadbeef'); +utils.numberToHexUnpadded(123n); +utils.hexToNumber(); + +utils.bytesToNumberBE(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])); +utils.bytesToNumberLE(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])); +utils.numberToBytesBE(123n, 32); +utils.numberToBytesLE(123n, 64); + +utils.concatBytes(Uint8Array.from([0xde, 0xad]), Uint8Array.from([0xbe, 0xef])); +utils.nLength(255n); +utils.equalBytes(Uint8Array.from([0xde]), Uint8Array.from([0xde])); +``` + +## Security + +1. The library has been independently audited: + +- in Feb 2023 by [Trail of Bits](https://www.trailofbits.com): + [PDF](https://github.com/trailofbits/publications/blob/master/reviews/2023-01-ryanshea-noblecurveslibrary-securityreview.pdf). + The audit has been funded by [Ryan Shea](https://www.shea.io). + Audit scope was abstract modules `curve`, `hash-to-curve`, `modular`, `poseidon`, `utils`, `weierstrass`, + and top-level modules `_shortw_utils` and `secp256k1`. + See [changes since v0.7.3 audit](https://github.com/paulmillr/noble-curves/compare/0.7.3..main). + +2. The library has been fuzzed by [Guido Vranken's cryptofuzz](https://github.com/guidovranken/cryptofuzz). + You can run the fuzzer by yourself to check it. +3. [Timing attack](https://en.wikipedia.org/wiki/Timing_attack) considerations: + _JIT-compiler_ and _Garbage Collector_ make "constant time" extremely hard to + achieve in a scripting language. Which means _any other JS library can't have + constant-timeness_. Even statically typed Rust, a language without GC, + [makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security) + for some cases. If your goal is absolute security, don't use any JS lib — including bindings to native ones. + Use low-level libraries & languages. Nonetheless we're targetting algorithmic constant time. + +We consider infrastructure attacks like rogue NPM modules very important; +that's why it's crucial to minimize the amount of 3rd-party dependencies & native bindings. +If your app uses 500 dependencies, any dep could get hacked and you'll be +downloading malware with every `npm install`. Our goal is to minimize this attack vector. +As for devDependencies used by the library: + +- `@scure` base, bip32, bip39 (used in tests), micro-bmark (benchmark), micro-should (testing) + are developed by us and follow the same practices such as: minimal library size, auditability, + signed releases +- prettier (linter), fast-check (property-based testing), typescript versions + are locked and rarely updated. Every update is checked with `npm-diff`. + The packages are big, which makes it hard to audit their source code thoroughly and fully. +- They are only used if you clone the git repo and want to add some feature to it. End-users won't use them. + +As for key generation, we're deferring to built-in +[crypto.getRandomValues](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) +which is considered cryptographically secure (CSPRNG). + +## Speed + +Benchmark results on Apple M2 with node v20: + +``` +secp256k1 +init x 68 ops/sec @ 14ms/op +getPublicKey x 6,750 ops/sec @ 148μs/op +sign x 5,206 ops/sec @ 192μs/op +verify x 880 ops/sec @ 1ms/op +getSharedSecret x 536 ops/sec @ 1ms/op +recoverPublicKey x 852 ops/sec @ 1ms/op +schnorr.sign x 685 ops/sec @ 1ms/op +schnorr.verify x 908 ops/sec @ 1ms/op + +p256 +init x 38 ops/sec @ 26ms/op +getPublicKey x 6,530 ops/sec @ 153μs/op +sign x 5,074 ops/sec @ 197μs/op +verify x 626 ops/sec @ 1ms/op + +p384 +init x 17 ops/sec @ 57ms/op +getPublicKey x 2,883 ops/sec @ 346μs/op +sign x 2,358 ops/sec @ 424μs/op +verify x 245 ops/sec @ 4ms/op + +p521 +init x 9 ops/sec @ 109ms/op +getPublicKey x 1,516 ops/sec @ 659μs/op +sign x 1,271 ops/sec @ 786μs/op +verify x 123 ops/sec @ 8ms/op + +ed25519 +init x 54 ops/sec @ 18ms/op +getPublicKey x 10,269 ops/sec @ 97μs/op +sign x 5,110 ops/sec @ 195μs/op +verify x 1,049 ops/sec @ 952μs/op + +ed448 +init x 19 ops/sec @ 51ms/op +getPublicKey x 3,775 ops/sec @ 264μs/op +sign x 1,771 ops/sec @ 564μs/op +verify x 351 ops/sec @ 2ms/op + +ecdh +├─x25519 x 1,466 ops/sec @ 682μs/op +├─secp256k1 x 539 ops/sec @ 1ms/op +├─p256 x 511 ops/sec @ 1ms/op +├─p384 x 199 ops/sec @ 5ms/op +├─p521 x 103 ops/sec @ 9ms/op +└─x448 x 548 ops/sec @ 1ms/op + +bls12-381 +init x 36 ops/sec @ 27ms/op +getPublicKey 1-bit x 973 ops/sec @ 1ms/op +getPublicKey x 970 ops/sec @ 1ms/op +sign x 55 ops/sec @ 17ms/op +verify x 39 ops/sec @ 25ms/op +pairing x 106 ops/sec @ 9ms/op +aggregatePublicKeys/8 x 129 ops/sec @ 7ms/op +aggregatePublicKeys/32 x 34 ops/sec @ 28ms/op +aggregatePublicKeys/128 x 8 ops/sec @ 112ms/op +aggregatePublicKeys/512 x 2 ops/sec @ 446ms/op +aggregatePublicKeys/2048 x 0 ops/sec @ 1778ms/op +aggregateSignatures/8 x 50 ops/sec @ 19ms/op +aggregateSignatures/32 x 13 ops/sec @ 74ms/op +aggregateSignatures/128 x 3 ops/sec @ 296ms/op +aggregateSignatures/512 x 0 ops/sec @ 1180ms/op +aggregateSignatures/2048 x 0 ops/sec @ 4715ms/op + +hash-to-curve +hash_to_field x 91,600 ops/sec @ 10μs/op +secp256k1 x 2,373 ops/sec @ 421μs/op +p256 x 4,310 ops/sec @ 231μs/op +p384 x 1,664 ops/sec @ 600μs/op +p521 x 807 ops/sec @ 1ms/op +ed25519 x 3,088 ops/sec @ 323μs/op +ed448 x 1,247 ops/sec @ 801μs/op +``` + +## Contributing & testing + +1. Clone the repository +2. `npm install` to install build dependencies like TypeScript +3. `npm run build` to compile TypeScript code +4. `npm run test` will execute all main tests + +## Upgrading + +Previously, the library was split into single-feature packages +[noble-secp256k1](https://github.com/paulmillr/noble-secp256k1), +[noble-ed25519](https://github.com/paulmillr/noble-ed25519) and +[noble-bls12-381](https://github.com/paulmillr/noble-bls12-381). + +Curves continue their original work. The single-feature packages changed their +direction towards providing minimal 4kb implementations of cryptography, +which means they have less features. + +Upgrading from noble-secp256k1 2.0 or noble-ed25519 2.0: no changes, libraries are compatible. + +Upgrading from noble-secp256k1 1.7: + +- `getPublicKey` + - now produce 33-byte compressed signatures by default + - to use old behavior, which produced 65-byte uncompressed keys, set + argument `isCompressed` to `false`: `getPublicKey(priv, false)` +- `sign` + - is now sync; use `signAsync` for async version + - now returns `Signature` instance with `{ r, s, recovery }` properties + - `canonical` option was renamed to `lowS` + - `recovered` option has been removed because recovery bit is always returned now + - `der` option has been removed. There are 2 options: + 1. Use compact encoding: `fromCompact`, `toCompactRawBytes`, `toCompactHex`. + Compact encoding is simply a concatenation of 32-byte r and 32-byte s. + 2. If you must use DER encoding, switch to noble-curves (see above). +- `verify` + - `strict` option was renamed to `lowS` +- `getSharedSecret` + - now produce 33-byte compressed signatures by default + - to use old behavior, which produced 65-byte uncompressed keys, set + argument `isCompressed` to `false`: `getSharedSecret(a, b, false)` +- `recoverPublicKey(msg, sig, rec)` was changed to `sig.recoverPublicKey(msg)` +- `number` type for private keys have been removed: use `bigint` instead +- `Point` (2d xy) has been changed to `ProjectivePoint` (3d xyz) +- `utils` were split into `utils` (same api as in noble-curves) and + `etc` (`hmacSha256Sync` and others) + +Upgrading from [@noble/ed25519](https://github.com/paulmillr/noble-ed25519) 1.7: + +- Methods are now sync by default +- `bigint` is no longer allowed in `getPublicKey`, `sign`, `verify`. Reason: ed25519 is LE, can lead to bugs +- `Point` (2d xy) has been changed to `ExtendedPoint` (xyzt) +- `Signature` was removed: just use raw bytes or hex now +- `utils` were split into `utils` (same api as in noble-curves) and + `etc` (`sha512Sync` and others) +- `getSharedSecret` was moved to `x25519` module +- `toX25519` has been moved to `edwardsToMontgomeryPub` and `edwardsToMontgomeryPriv` methods + +Upgrading from [@noble/bls12-381](https://github.com/paulmillr/noble-bls12-381): + +- Methods and classes were renamed: + - PointG1 -> G1.Point, PointG2 -> G2.Point + - PointG2.fromSignature -> Signature.decode, PointG2.toSignature -> Signature.encode +- Fp2 ORDER was corrected + +## Resources + +- [Learning fast elliptic-curve cryptography](https://paulmillr.com/posts/noble-secp256k1-fast-ecc/) +- EdDSA + - [A Deep dive into Ed25519 Signatures](https://cendyne.dev/posts/2022-03-06-ed25519-signatures.html) + - [Ed25519 Deep Dive Addendum](https://cendyne.dev/posts/2022-09-11-ed25519-deep-dive-addendum.html) + - [It’s 255:19AM. Do you know what your validation criteria are?](https://hdevalence.ca/blog/2020-10-04-its-25519am) + - [Taming the many EdDSAs](https://csrc.nist.gov/csrc/media/Presentations/2023/crclub-2023-03-08/images-media/20230308-crypto-club-slides--taming-the-many-EdDSAs.pdf) + that describes concepts of Strong UnForgeability under Chosen Message Attacks and Strongly Binding Signatures + - [Cofactor Explained: Clearing Elliptic Curves’ dirty little secret](https://loup-vaillant.fr/tutorials/cofactor) + - [Surrounded by Elligators](https://loup-vaillant.fr/articles/implementing-elligator) +- Pairings and BLS + - [BLS signatures for busy people](https://gist.github.com/paulmillr/18b802ad219b1aee34d773d08ec26ca2) + - [BLS12-381 for the rest of us](https://hackmd.io/@benjaminion/bls12-381) + - [Key concepts of pairings](https://medium.com/@alonmuroch_65570/bls-signatures-part-2-key-concepts-of-pairings-27a8a9533d0c) + - Pairing over bls12-381: + [fields](https://research.nccgroup.com/2020/07/06/pairing-over-bls12-381-part-1-fields/), + [curves](https://research.nccgroup.com/2020/07/13/pairing-over-bls12-381-part-2-curves/), + [pairings](https://research.nccgroup.com/2020/08/13/pairing-over-bls12-381-part-3-pairing/) + - [Estimating the bit security of pairing-friendly curves](https://research.nccgroup.com/2022/02/03/estimating-the-bit-security-of-pairing-friendly-curves/) + +### Demos + +- [Elliptic Curve Calculator](https://paulmillr.com/noble): add / multiply points, sign messages +- [BLS threshold signatures](https://genthresh.com) + +### Projects using curves + +- HDkey libraries: [scure-bip32](https://github.com/paulmillr/scure-bip32), [bip32](https://github.com/bitcoinjs/bip32) +- Social networks: [nostr](https://github.com/nbd-wtf/nostr-tools), [bluesky](https://github.com/bluesky-social/atproto) +- Ethereum libraries: + - [ethereum-cryptography](https://github.com/ethereum/js-ethereum-cryptography) + - [micro-eth-signer](https://github.com/paulmillr/micro-eth-signer), + [ethers](https://github.com/ethers-io/ethers.js) (old noble), + [viem.sh](https://viem.sh), + [@ethereumjs](https://github.com/ethereumjs/ethereumjs-monorepo) + - [metamask's eth-sig-util](https://github.com/MetaMask/eth-sig-util) + - [gridplus lattice sdk](https://github.com/GridPlus/lattice-eth2-utils) +- Bitcoin libraries: + - [scure-btc-signer](https://github.com/paulmillr/scure-btc-signer) + - [tapscript](https://github.com/cmdruid/tapscript) +- Solana libraries: [micro-sol-signer](https://github.com/paulmillr/micro-sol-signer), [solana-web3.js](https://github.com/solana-labs/solana-web3.js) +- Other web3 stuff: + - [scure-starknet](https://github.com/paulmillr/scure-starknet) + - [aztec](https://github.com/AztecProtocol/aztec-packages) + - [polkadot.js](https://github.com/polkadot-js/common), [drand-client](https://github.com/drand/drand-client), [moneroj](https://github.com/beritani/moneroj), [tronlib](https://github.com/CoinSpace/tronlib) +- [protonmail](https://github.com/ProtonMail/WebClients) (old noble for now) +- [did-jwt](https://github.com/decentralized-identity/did-jwt), [hpke-js](https://github.com/dajiaji/hpke-js), + [js-libp2p-noise](https://github.com/ChainSafe/js-libp2p-noise) +- [ed25519-keygen](https://github.com/paulmillr/ed25519-keygen) SSH, PGP, TOR key generation +- [secp256k1 compatibility layer](https://github.com/ethereum/js-ethereum-cryptography/blob/2.0.0/src/secp256k1-compat.ts) + for users who want to switch from secp256k1-node or tiny-secp256k1. Allows to see which methods map to corresponding noble code. +- [BLS BBS signatures](https://github.com/Wind4Greg/BBS-Draft-Checks) following [draft-irtf-cfrg-bbs-signatures-latest](https://identity.foundation/bbs-signature/draft-irtf-cfrg-bbs-signatures.html) +- [KZG trusted setup ceremony](https://github.com/dsrvlabs/czg-keremony) +- See [full list of projects on GitHub](https://github.com/paulmillr/noble-curves/network/dependents). + +## License + +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller [(https://paulmillr.com)](https://paulmillr.com) + +See LICENSE file. diff --git a/node_modules/@noble/curves/_shortw_utils.d.ts b/node_modules/@noble/curves/_shortw_utils.d.ts new file mode 100644 index 0000000..3eb43a8 --- /dev/null +++ b/node_modules/@noble/curves/_shortw_utils.d.ts @@ -0,0 +1,62 @@ +import { randomBytes } from '@noble/hashes/utils'; +import { CurveType } from './abstract/weierstrass.js'; +import { CHash } from './abstract/utils.js'; +export declare function getHash(hash: CHash): { + hash: CHash; + hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => Uint8Array; + randomBytes: typeof randomBytes; +}; +type CurveDef = Readonly>; +export declare function createCurve(curveDef: CurveDef, defHash: CHash): Readonly<{ + create: (hash: CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType | undefined) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export {}; +//# sourceMappingURL=_shortw_utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/_shortw_utils.d.ts.map b/node_modules/@noble/curves/_shortw_utils.d.ts.map new file mode 100644 index 0000000..974f8da --- /dev/null +++ b/node_modules/@noble/curves/_shortw_utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"_shortw_utils.d.ts","sourceRoot":"","sources":["src/_shortw_utils.ts"],"names":[],"mappings":"AAEA,OAAO,EAAe,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAC/D,OAAO,EAAe,SAAS,EAAE,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAG5C,wBAAgB,OAAO,CAAC,IAAI,EAAE,KAAK;;gBAGnB,UAAU,WAAW,UAAU,EAAE;;EAGhD;AAED,KAAK,QAAQ,GAAG,QAAQ,CAAC,IAAI,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,aAAa,CAAC,CAAC,CAAC;AAC3E,wBAAgB,WAAW,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK;mBACtC,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAE5B"} \ No newline at end of file diff --git a/node_modules/@noble/curves/_shortw_utils.js b/node_modules/@noble/curves/_shortw_utils.js new file mode 100644 index 0000000..555de44 --- /dev/null +++ b/node_modules/@noble/curves/_shortw_utils.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createCurve = exports.getHash = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const hmac_1 = require("@noble/hashes/hmac"); +const utils_1 = require("@noble/hashes/utils"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +// connects noble-curves to noble-hashes +function getHash(hash) { + return { + hash, + hmac: (key, ...msgs) => (0, hmac_1.hmac)(hash, key, (0, utils_1.concatBytes)(...msgs)), + randomBytes: utils_1.randomBytes, + }; +} +exports.getHash = getHash; +function createCurve(curveDef, defHash) { + const create = (hash) => (0, weierstrass_js_1.weierstrass)({ ...curveDef, ...getHash(hash) }); + return Object.freeze({ ...create(defHash), create }); +} +exports.createCurve = createCurve; +//# sourceMappingURL=_shortw_utils.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/_shortw_utils.js.map b/node_modules/@noble/curves/_shortw_utils.js.map new file mode 100644 index 0000000..318dfda --- /dev/null +++ b/node_modules/@noble/curves/_shortw_utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_shortw_utils.js","sourceRoot":"","sources":["src/_shortw_utils.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,6CAA0C;AAC1C,+CAA+D;AAC/D,8DAAmE;AAGnE,wCAAwC;AACxC,SAAgB,OAAO,CAAC,IAAW;IACjC,OAAO;QACL,IAAI;QACJ,IAAI,EAAE,CAAC,GAAe,EAAE,GAAG,IAAkB,EAAE,EAAE,CAAC,IAAA,WAAI,EAAC,IAAI,EAAE,GAAG,EAAE,IAAA,mBAAW,EAAC,GAAG,IAAI,CAAC,CAAC;QACvF,WAAW,EAAX,mBAAW;KACZ,CAAC;AACJ,CAAC;AAND,0BAMC;AAGD,SAAgB,WAAW,CAAC,QAAkB,EAAE,OAAc;IAC5D,MAAM,MAAM,GAAG,CAAC,IAAW,EAAE,EAAE,CAAC,IAAA,4BAAW,EAAC,EAAE,GAAG,QAAQ,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAC/E,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,MAAM,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;AACvD,CAAC;AAHD,kCAGC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/bls.d.ts b/node_modules/@noble/curves/abstract/bls.d.ts new file mode 100644 index 0000000..f6f14ac --- /dev/null +++ b/node_modules/@noble/curves/abstract/bls.d.ts @@ -0,0 +1,103 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +/** + * BLS (Barreto-Lynn-Scott) family of pairing-friendly curves. + * Implements BLS (Boneh-Lynn-Shacham) signatures. + * Consists of two curves: G1 and G2: + * - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4. + * - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1 + * - Gt, created by bilinear (ate) pairing e(G1, G2), consists of p-th roots of unity in + * Fq^k where k is embedding degree. Only degree 12 is currently supported, 24 is not. + * Pairing is used to aggregate and verify signatures. + * We are using Fp for private keys (shorter) and Fp₂ for signatures (longer). + * Some projects may prefer to swap this relation, it is not supported for now. + */ +import { AffinePoint } from './curve.js'; +import { IField } from './modular.js'; +import { Hex, PrivKey, CHash } from './utils.js'; +import * as htf from './hash-to-curve.js'; +import { CurvePointsType, ProjPointType as ProjPointType, CurvePointsRes } from './weierstrass.js'; +type Fp = bigint; +export type SignatureCoder = { + fromHex(hex: Hex): ProjPointType; + toRawBytes(point: ProjPointType): Uint8Array; + toHex(point: ProjPointType): string; +}; +export type CurveType = { + G1: Omit, 'n'> & { + mapToCurve: htf.MapToCurve; + htfDefaults: htf.Opts; + }; + G2: Omit, 'n'> & { + Signature: SignatureCoder; + mapToCurve: htf.MapToCurve; + htfDefaults: htf.Opts; + }; + fields: { + Fp: IField; + Fr: IField; + Fp2: IField & { + reim: (num: Fp2) => { + re: bigint; + im: bigint; + }; + multiplyByB: (num: Fp2) => Fp2; + frobeniusMap(num: Fp2, power: number): Fp2; + }; + Fp6: IField; + Fp12: IField & { + frobeniusMap(num: Fp12, power: number): Fp12; + multiplyBy014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12; + conjugate(num: Fp12): Fp12; + finalExponentiate(num: Fp12): Fp12; + }; + }; + params: { + x: bigint; + r: bigint; + }; + htfDefaults: htf.Opts; + hash: CHash; + randomBytes: (bytesLength?: number) => Uint8Array; +}; +export type CurveFn = { + getPublicKey: (privateKey: PrivKey) => Uint8Array; + sign: { + (message: Hex, privateKey: PrivKey): Uint8Array; + (message: ProjPointType, privateKey: PrivKey): ProjPointType; + }; + verify: (signature: Hex | ProjPointType, message: Hex | ProjPointType, publicKey: Hex | ProjPointType) => boolean; + verifyBatch: (signature: Hex | ProjPointType, messages: (Hex | ProjPointType)[], publicKeys: (Hex | ProjPointType)[]) => boolean; + aggregatePublicKeys: { + (publicKeys: Hex[]): Uint8Array; + (publicKeys: ProjPointType[]): ProjPointType; + }; + aggregateSignatures: { + (signatures: Hex[]): Uint8Array; + (signatures: ProjPointType[]): ProjPointType; + }; + millerLoop: (ell: [Fp2, Fp2, Fp2][], g1: [Fp, Fp]) => Fp12; + pairing: (P: ProjPointType, Q: ProjPointType, withFinalExponent?: boolean) => Fp12; + G1: CurvePointsRes & ReturnType>; + G2: CurvePointsRes & ReturnType>; + Signature: SignatureCoder; + params: { + x: bigint; + r: bigint; + G1b: bigint; + G2b: Fp2; + }; + fields: { + Fp: IField; + Fp2: IField; + Fp6: IField; + Fp12: IField; + Fr: IField; + }; + utils: { + randomPrivateKey: () => Uint8Array; + calcPairingPrecomputes: (p: AffinePoint) => [Fp2, Fp2, Fp2][]; + }; +}; +export declare function bls(CURVE: CurveType): CurveFn; +export {}; +//# sourceMappingURL=bls.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/bls.d.ts.map b/node_modules/@noble/curves/abstract/bls.d.ts.map new file mode 100644 index 0000000..7f110e3 --- /dev/null +++ b/node_modules/@noble/curves/abstract/bls.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bls.d.ts","sourceRoot":"","sources":["../src/abstract/bls.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EAAE,MAAM,EAAoC,MAAM,cAAc,CAAC;AACxE,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,KAAK,EAA+B,MAAM,YAAY,CAAC;AAC9E,OAAO,KAAK,GAAG,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EACL,eAAe,EACf,aAAa,IAAI,aAAa,EAC9B,cAAc,EAEf,MAAM,kBAAkB,CAAC;AAE1B,KAAK,EAAE,GAAG,MAAM,CAAC;AAKjB,MAAM,MAAM,cAAc,CAAC,GAAG,IAAI;IAChC,OAAO,CAAC,GAAG,EAAE,GAAG,GAAG,aAAa,CAAC,GAAG,CAAC,CAAC;IACtC,UAAU,CAAC,KAAK,EAAE,aAAa,CAAC,GAAG,CAAC,GAAG,UAAU,CAAC;IAClD,KAAK,CAAC,KAAK,EAAE,aAAa,CAAC,GAAG,CAAC,GAAG,M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I,CAAC,CAAC;QACnB,EAAE,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;KACpB,CAAC;IACF,KAAK,EAAE;QACL,gBAAgB,EAAE,MAAM,UAAU,CAAC;QACnC,sBAAsB,EAAE,CAAC,CAAC,EAAE,WAAW,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,EAAE,CAAC;KACpE,CAAC;CACH,CAAC;AAEF,wBAAgB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAChC,KAAK,EAAE,SAAS,CAAC,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,GACnC,OAAO,CAAC,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAqR7B"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/bls.js b/node_modules/@noble/curves/abstract/bls.js new file mode 100644 index 0000000..a8bcfc5 --- /dev/null +++ b/node_modules/@noble/curves/abstract/bls.js @@ -0,0 +1,239 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bls = void 0; +const modular_js_1 = require("./modular.js"); +const utils_js_1 = require("./utils.js"); +const htf = require("./hash-to-curve.js"); +const weierstrass_js_1 = require("./weierstrass.js"); +// prettier-ignore +const _2n = BigInt(2), _3n = BigInt(3); +function bls(CURVE) { + // Fields are specific for curve, so for now we'll need to pass them with opts + const { Fp, Fr, Fp2, Fp6, Fp12 } = CURVE.fields; + const BLS_X_LEN = (0, utils_js_1.bitLen)(CURVE.params.x); + // Pre-compute coefficients for sparse multiplication + // Point addition and point double calculations is reused for coefficients + function calcPairingPrecomputes(p) { + const { x, y } = p; + // prettier-ignore + const Qx = x, Qy = y, Qz = Fp2.ONE; + // prettier-ignore + let Rx = Qx, Ry = Qy, Rz = Qz; + let ell_coeff = []; + for (let i = BLS_X_LEN - 2; i >= 0; i--) { + // Double + let t0 = Fp2.sqr(Ry); // Ry² + let t1 = Fp2.sqr(Rz); // Rz² + let t2 = Fp2.multiplyByB(Fp2.mul(t1, _3n)); // 3 * T1 * B + let t3 = Fp2.mul(t2, _3n); // 3 * T2 + let t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0); // (Ry + Rz)² - T1 - T0 + ell_coeff.push([ + Fp2.sub(t2, t0), + Fp2.mul(Fp2.sqr(Rx), _3n), + Fp2.neg(t4), // -T4 + ]); + Rx = Fp2.div(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), _2n); // ((T0 - T3) * Rx * Ry) / 2 + Ry = Fp2.sub(Fp2.sqr(Fp2.div(Fp2.add(t0, t3), _2n)), Fp2.mul(Fp2.sqr(t2), _3n)); // ((T0 + T3) / 2)² - 3 * T2² + Rz = Fp2.mul(t0, t4); // T0 * T4 + if ((0, utils_js_1.bitGet)(CURVE.params.x, i)) { + // Addition + let t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); // Ry - Qy * Rz + let t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz)); // Rx - Qx * Rz + ell_coeff.push([ + Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy)), + Fp2.neg(t0), + t1, // T1 + ]); + let t2 = Fp2.sqr(t1); // T1² + let t3 = Fp2.mul(t2, t1); // T2 * T1 + let t4 = Fp2.mul(t2, Rx); // T2 * Rx + let t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n)), Fp2.mul(Fp2.sqr(t0), Rz)); // T3 - 2 * T4 + T0² * Rz + Rx = Fp2.mul(t1, t5); // T1 * T5 + Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry)); // (T4 - T5) * T0 - T3 * Ry + Rz = Fp2.mul(Rz, t3); // Rz * T3 + } + } + return ell_coeff; + } + function millerLoop(ell, g1) { + const { x } = CURVE.params; + const Px = g1[0]; + const Py = g1[1]; + let f12 = Fp12.ONE; + for (let j = 0, i = BLS_X_LEN - 2; i >= 0; i--, j++) { + const E = ell[j]; + f12 = Fp12.multiplyBy014(f12, E[0], Fp2.mul(E[1], Px), Fp2.mul(E[2], Py)); + if ((0, utils_js_1.bitGet)(x, i)) { + j += 1; + const F = ell[j]; + f12 = Fp12.multiplyBy014(f12, F[0], Fp2.mul(F[1], Px), Fp2.mul(F[2], Py)); + } + if (i !== 0) + f12 = Fp12.sqr(f12); + } + return Fp12.conjugate(f12); + } + const utils = { + randomPrivateKey: () => { + const length = (0, modular_js_1.getMinHashLength)(Fr.ORDER); + return (0, modular_js_1.mapHashToField)(CURVE.randomBytes(length), Fr.ORDER); + }, + calcPairingPrecomputes, + }; + // Point on G1 curve: (x, y) + const G1_ = (0, weierstrass_js_1.weierstrassPoints)({ n: Fr.ORDER, ...CURVE.G1 }); + const G1 = Object.assign(G1_, htf.createHasher(G1_.ProjectivePoint, CURVE.G1.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G1.htfDefaults, + })); + function pairingPrecomputes(point) { + const p = point; + if (p._PPRECOMPUTES) + return p._PPRECOMPUTES; + p._PPRECOMPUTES = calcPairingPrecomputes(point.toAffine()); + return p._PPRECOMPUTES; + } + // TODO: export + // function clearPairingPrecomputes(point: G2) { + // const p = point as G2 & withPairingPrecomputes; + // p._PPRECOMPUTES = undefined; + // } + // Point on G2 curve (complex numbers): (x₁, x₂+i), (y₁, y₂+i) + const G2_ = (0, weierstrass_js_1.weierstrassPoints)({ n: Fr.ORDER, ...CURVE.G2 }); + const G2 = Object.assign(G2_, htf.createHasher(G2_.ProjectivePoint, CURVE.G2.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G2.htfDefaults, + })); + const { Signature } = CURVE.G2; + // Calculates bilinear pairing + function pairing(Q, P, withFinalExponent = true) { + if (Q.equals(G1.ProjectivePoint.ZERO) || P.equals(G2.ProjectivePoint.ZERO)) + throw new Error('pairing is not available for ZERO point'); + Q.assertValidity(); + P.assertValidity(); + // Performance: 9ms for millerLoop and ~14ms for exp. + const Qa = Q.toAffine(); + const looped = millerLoop(pairingPrecomputes(P), [Qa.x, Qa.y]); + return withFinalExponent ? Fp12.finalExponentiate(looped) : looped; + } + function normP1(point) { + return point instanceof G1.ProjectivePoint ? point : G1.ProjectivePoint.fromHex(point); + } + function normP2(point) { + return point instanceof G2.ProjectivePoint ? point : Signature.fromHex(point); + } + function normP2Hash(point, htfOpts) { + return point instanceof G2.ProjectivePoint + ? point + : G2.hashToCurve((0, utils_js_1.ensureBytes)('point', point), htfOpts); + } + // Multiplies generator by private key. + // P = pk x G + function getPublicKey(privateKey) { + return G1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true); + } + function sign(message, privateKey, htfOpts) { + const msgPoint = normP2Hash(message, htfOpts); + msgPoint.assertValidity(); + const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey)); + if (message instanceof G2.ProjectivePoint) + return sigPoint; + return Signature.toRawBytes(sigPoint); + } + // Checks if pairing of public key & hash is equal to pairing of generator & signature. + // e(P, H(m)) == e(G, S) + function verify(signature, message, publicKey, htfOpts) { + const P = normP1(publicKey); + const Hm = normP2Hash(message, htfOpts); + const G = G1.ProjectivePoint.BASE; + const S = normP2(signature); + // Instead of doing 2 exponentiations, we use property of billinear maps + // and do one exp after multiplying 2 points. + const ePHm = pairing(P.negate(), Hm, false); + const eGS = pairing(G, S, false); + const exp = Fp12.finalExponentiate(Fp12.mul(eGS, ePHm)); + return Fp12.eql(exp, Fp12.ONE); + } + function aggregatePublicKeys(publicKeys) { + if (!publicKeys.length) + throw new Error('Expected non-empty array'); + const agg = publicKeys.map(normP1).reduce((sum, p) => sum.add(p), G1.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (publicKeys[0] instanceof G1.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + // toRawBytes ensures point validity + return aggAffine.toRawBytes(true); + } + function aggregateSignatures(signatures) { + if (!signatures.length) + throw new Error('Expected non-empty array'); + const agg = signatures.map(normP2).reduce((sum, s) => sum.add(s), G2.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (signatures[0] instanceof G2.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + return Signature.toRawBytes(aggAffine); + } + // https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407 + // e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si)) + function verifyBatch(signature, messages, publicKeys, htfOpts) { + // @ts-ignore + // console.log('verifyBatch', bytesToHex(signature as any), messages, publicKeys.map(bytesToHex)); + if (!messages.length) + throw new Error('Expected non-empty messages array'); + if (publicKeys.length !== messages.length) + throw new Error('Pubkey count should equal msg count'); + const sig = normP2(signature); + const nMessages = messages.map((i) => normP2Hash(i, htfOpts)); + const nPublicKeys = publicKeys.map(normP1); + try { + const paired = []; + for (const message of new Set(nMessages)) { + const groupPublicKey = nMessages.reduce((groupPublicKey, subMessage, i) => subMessage === message ? groupPublicKey.add(nPublicKeys[i]) : groupPublicKey, G1.ProjectivePoint.ZERO); + // const msg = message instanceof PointG2 ? message : await PointG2.hashToCurve(message); + // Possible to batch pairing for same msg with different groupPublicKey here + paired.push(pairing(groupPublicKey, message, false)); + } + paired.push(pairing(G1.ProjectivePoint.BASE.negate(), sig, false)); + const product = paired.reduce((a, b) => Fp12.mul(a, b), Fp12.ONE); + const exp = Fp12.finalExponentiate(product); + return Fp12.eql(exp, Fp12.ONE); + } + catch { + return false; + } + } + G1.ProjectivePoint.BASE._setWindowSize(4); + return { + getPublicKey, + sign, + verify, + verifyBatch, + aggregatePublicKeys, + aggregateSignatures, + millerLoop, + pairing, + G1, + G2, + Signature, + fields: { + Fr, + Fp, + Fp2, + Fp6, + Fp12, + }, + params: { + x: CURVE.params.x, + r: CURVE.params.r, + G1b: CURVE.G1.b, + G2b: CURVE.G2.b, + }, + utils, + }; +} +exports.bls = bls; +//# sourceMappingURL=bls.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/bls.js.map b/node_modules/@noble/curves/abstract/bls.js.map new file mode 100644 index 0000000..520ab30 --- /dev/null +++ b/node_modules/@noble/curves/abstract/bls.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bls.js","sourceRoot":"","sources":["../src/abstract/bls.ts"],"names":[],"mappings":";;;AAcA,6CAAwE;AACxE,yCAA8E;AAC9E,0CAA0C;AAC1C,qDAK0B;AAI1B,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AA2FvC,SAAgB,GAAG,CACjB,KAAoC;IAEpC,8EAA8E;IAC9E,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC,MAAM,CAAC;IAChD,MAAM,SAAS,GAAG,IAAA,iBAAM,EAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IAEzC,qDAAqD;IACrD,0EAA0E;IAC1E,SAAS,sBAAsB,CAAC,CAAmB;QACjD,MAAM,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;QACnB,kBAAkB;QAClB,MAAM,EAAE,GAAG,CAAC,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,GAAG,GAAG,CAAC,GAAG,CAAC;QACnC,kBAAkB;QAClB,IAAI,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,EAAE,CAAC;QAC9B,IAAI,SAAS,GAAsB,EAAE,CAAC;QACtC,KAAK,IAAI,CAAC,GAAG,SAAS,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE;YACvC,SAAS;YACT,IAAI,EAAE,GAAG,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM;YAC5B,IAAI,EAAE,GAAG,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM;YAC5B,IAAI,EAAE,G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,KAAK,CAAC,MAAM,CAAC,CAAC;YACjB,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;YACjB,GAAG,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;YACf,GAAG,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;SAChB;QACD,KAAK;KACN,CAAC;AACJ,CAAC;AAvRD,kBAuRC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/curve.d.ts b/node_modules/@noble/curves/abstract/curve.d.ts new file mode 100644 index 0000000..9caf29c --- /dev/null +++ b/node_modules/@noble/curves/abstract/curve.d.ts @@ -0,0 +1,70 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { IField } from './modular.js'; +export type AffinePoint = { + x: T; + y: T; +} & { + z?: never; + t?: never; +}; +export interface Group> { + double(): T; + negate(): T; + add(other: T): T; + subtract(other: T): T; + equals(other: T): boolean; + multiply(scalar: bigint): T; +} +export type GroupConstructor = { + BASE: T; + ZERO: T; +}; +export type Mapper = (i: T[]) => T[]; +export declare function wNAF>(c: GroupConstructor, bits: number): { + constTimeNegate: (condition: boolean, item: T) => T; + unsafeLadder(elm: T, n: bigint): T; + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm: T, W: number): Group[]; + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W: number, precomputes: T[], n: bigint): { + p: T; + f: T; + }; + wNAFCached(P: T, precomputesMap: Map, n: bigint, transform: Mapper): { + p: T; + f: T; + }; +}; +export type BasicCurve = { + Fp: IField; + n: bigint; + nBitLength?: number; + nByteLength?: number; + h: bigint; + hEff?: bigint; + Gx: T; + Gy: T; + allowInfinityPoint?: boolean; +}; +export declare function validateBasic(curve: BasicCurve & T): Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; +} & BasicCurve & T & { + p: bigint; +}>; +//# sourceMappingURL=curve.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/curve.d.ts.map b/node_modules/@noble/curves/abstract/curve.d.ts.map new file mode 100644 index 0000000..fc52e87 --- /dev/null +++ b/node_modules/@noble/curves/abstract/curve.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"curve.d.ts","sourceRoot":"","sources":["../src/abstract/curve.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,OAAO,EAAE,MAAM,EAA0B,MAAM,cAAc,CAAC;AAK9D,MAAM,MAAM,WAAW,CAAC,CAAC,IAAI;IAC3B,CAAC,EAAE,CAAC,CAAC;IACL,CAAC,EAAE,CAAC,CAAC;CACN,GAAG;IAAE,CAAC,CAAC,EAAE,KAAK,CAAC;IAAC,CAAC,CAAC,EAAE,KAAK,CAAA;CAAE,CAAC;AAE7B,MAAM,WAAW,KAAK,CAAC,CAAC,SAAS,KAAK,CAAC,CAAC,CAAC;IACvC,MAAM,IAAI,CAAC,CAAC;IACZ,MAAM,IAAI,CAAC,CAAC;IACZ,GAAG,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC;IACjB,QAAQ,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC;IACtB,MAAM,CAAC,KAAK,EAAE,CAAC,GAAG,OAAO,CAAC;IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,CAAC,CAAC;CAC7B;AAED,MAAM,MAAM,gBAAgB,CAAC,CAAC,IAAI;IAChC,IAAI,EAAE,CAAC,CAAC;IACR,IAAI,EAAE,CAAC,CAAC;CACT,CAAC;AACF,MAAM,MAAM,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,CAAC,EAAE,CAAC;AAaxC,wBAAgB,IAAI,CAAC,CAAC,SAAS,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,gBAAgB,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM;iCACvC,OAAO,QAAQ,CAAC,KAAG,CAAC;sBAYpC,CAAC,KAAK,MAAM;IAW9B;;;;;;;;;OASG;0BACmB,CAAC,KAAK,MAAM,GAAG,MAAM,CAAC,CAAC,EAAE;IAkB/C;;;;;;OAMG;YACK,MAAM,eAAe,CAAC,EAAE,KAAK,MAAM;WAAQ,CAAC;WAAK,CAAC;;kBAsD5C,CAAC,kBAAkB,IAAI,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,MAAM,aAAa,OAAO,CAAC,CAAC,GAAG;QAAE,CAAC,EAAE,CAAC,CAAC;QAAC,CAAC,EAAE,CAAC,CAAA;KAAE;EAcjG;AAID,MAAM,MAAM,UAAU,CAAC,CAAC,IAAI;IAC1B,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC;IACd,CAAC,EAAE,MAAM,CAAC;IACV,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,CAAC,EAAE,MAAM,CAAC;IACV,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,EAAE,EAAE,CAAC,CAAC;IACN,EAAE,EAAE,CAAC,CAAC;IACN,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B,CAAC;AAEF,wBAAgB,aAAa,CAAC,EAAE,EAAE,CAAC,EAAE,KAAK,EAAE,UAAU,CAAC,EAAE,CAAC,GAAG,CAAC;;;;;GAqB7D"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/curve.js b/node_modules/@noble/curves/abstract/curve.js new file mode 100644 index 0000000..5a005bc --- /dev/null +++ b/node_modules/@noble/curves/abstract/curve.js @@ -0,0 +1,161 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateBasic = exports.wNAF = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Abelian group utilities +const modular_js_1 = require("./modular.js"); +const utils_js_1 = require("./utils.js"); +const _0n = BigInt(0); +const _1n = BigInt(1); +// Elliptic curve multiplication of Point by scalar. Fragile. +// Scalars should always be less than curve order: this should be checked inside of a curve itself. +// Creates precomputation tables for fast multiplication: +// - private scalar is split by fixed size windows of W bits +// - every window point is collected from window's table & added to accumulator +// - since windows are different, same point inside tables won't be accessed more than once per calc +// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar) +// - +1 window is neccessary for wNAF +// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication +// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow +// windows to be in different memory locations +function wNAF(c, bits) { + const constTimeNegate = (condition, item) => { + const neg = item.negate(); + return condition ? neg : item; + }; + const opts = (W) => { + const windows = Math.ceil(bits / W) + 1; // +1, because + const windowSize = 2 ** (W - 1); // -1 because we skip zero + return { windows, windowSize }; + }; + return { + constTimeNegate, + // non-const time multiplication ladder + unsafeLadder(elm, n) { + let p = c.ZERO; + let d = elm; + while (n > _0n) { + if (n & _1n) + p = p.add(d); + d = d.double(); + n >>= _1n; + } + return p; + }, + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm, W) { + const { windows, windowSize } = opts(W); + const points = []; + let p = elm; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + // =1, because we skip zero + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + }, + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W, precomputes, n) { + // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise + // But need to carefully remove other checks before wNAF. ORDER == bits here + const { windows, windowSize } = opts(W); + let p = c.ZERO; + let f = c.BASE; + const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc. + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + // Extract W bits. + let wbits = Number(n & mask); + // Shift number by W bits. + n >>= shiftBy; + // If the bits are bigger than max size, we'll split those. + // +224 => 256 - 32 + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n; + } + // This code was first written with assumption that 'f' and 'p' will never be infinity point: + // since each addition is multiplied by 2 ** W, it cannot cancel each other. However, + // there is negate now: it is possible that negated element from low value + // would be the same as high element, which will create carry into next window. + // It's not obvious how this can fail, but still worth investigating later. + // Check if we're onto Zero point. + // Add random point inside current window to f. + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + // The most important part for const-time getPublicKey + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } + else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ() + // Even if the variable is still unused, there are some checks which will + // throw an exception, so compiler needs to prove they won't happen, which is hard. + // At this point there is a way to F be infinity-point even if p is not, + // which makes it less const-time: around 1 bigint multiply. + return { p, f }; + }, + wNAFCached(P, precomputesMap, n, transform) { + // @ts-ignore + const W = P._WINDOW_SIZE || 1; + // Calculate precomputes on a first run, reuse them after + let comp = precomputesMap.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W); + if (W !== 1) { + precomputesMap.set(P, transform(comp)); + } + } + return this.wNAF(W, comp, n); + }, + }; +} +exports.wNAF = wNAF; +function validateBasic(curve) { + (0, modular_js_1.validateField)(curve.Fp); + (0, utils_js_1.validateObject)(curve, { + n: 'bigint', + h: 'bigint', + Gx: 'field', + Gy: 'field', + }, { + nBitLength: 'isSafeInteger', + nByteLength: 'isSafeInteger', + }); + // Set defaults + return Object.freeze({ + ...(0, modular_js_1.nLength)(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER }, + }); +} +exports.validateBasic = validateBasic; +//# sourceMappingURL=curve.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/curve.js.map b/node_modules/@noble/curves/abstract/curve.js.map new file mode 100644 index 0000000..dd6ca4b --- /dev/null +++ b/node_modules/@noble/curves/abstract/curve.js.map @@ -0,0 +1 @@ +{"version":3,"file":"curve.js","sourceRoot":"","sources":["../src/abstract/curve.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,0BAA0B;AAC1B,6CAA8D;AAC9D,yCAA4C;AAC5C,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAsBtB,6DAA6D;AAC7D,mGAAmG;AACnG,yDAAyD;AACzD,4DAA4D;AAC5D,+EAA+E;AAC/E,oGAAoG;AACpG,oGAAoG;AACpG,qCAAqC;AACrC,kGAAkG;AAClG,gGAAgG;AAChG,8CAA8C;AAC9C,SAAgB,IAAI,CAAqB,CAAsB,EAAE,IAAY;IAC3E,MAAM,eAAe,GAAG,CAAC,SAAkB,EAAE,IAAO,EAAK,EAAE;QACzD,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;QAC1B,OAAO,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;IAChC,CAAC,CAAC;IACF,MAAM,IAAI,GAAG,CAAC,CAAS,EAA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AC,EAAE,CAAC,CAAC;IACxB,IAAA,yBAAc,EACZ,KAAK,EACL;QACE,CAAC,EAAE,QAAQ;QACX,CAAC,EAAE,QAAQ;QACX,EAAE,EAAE,OAAO;QACX,EAAE,EAAE,OAAO;KACZ,EACD;QACE,UAAU,EAAE,eAAe;QAC3B,WAAW,EAAE,eAAe;KAC7B,CACF,CAAC;IACF,eAAe;IACf,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,GAAG,IAAA,oBAAO,EAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,UAAU,CAAC;QACrC,GAAG,KAAK;QACR,GAAG,EAAE,CAAC,EAAE,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE;KAChB,CAAC,CAAC;AACd,CAAC;AArBD,sCAqBC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/edwards.d.ts b/node_modules/@noble/curves/abstract/edwards.d.ts new file mode 100644 index 0000000..9c43c66 --- /dev/null +++ b/node_modules/@noble/curves/abstract/edwards.d.ts @@ -0,0 +1,89 @@ +import * as ut from './utils.js'; +import { FHash, Hex } from './utils.js'; +import { Group, GroupConstructor, BasicCurve, AffinePoint } from './curve.js'; +export type CurveType = BasicCurve & { + a: bigint; + d: bigint; + hash: FHash; + randomBytes: (bytesLength?: number) => Uint8Array; + adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; + domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; + uvRatio?: (u: bigint, v: bigint) => { + isValid: boolean; + value: bigint; + }; + prehash?: FHash; + mapToCurve?: (scalar: bigint[]) => AffinePoint; +}; +declare function validateOpts(curve: CurveType): Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly d: bigint; + readonly hash: ut.FHash; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + readonly adjustScalarBytes?: ((bytes: Uint8Array) => Uint8Array) | undefined; + readonly domain?: ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array) | undefined; + readonly uvRatio?: ((u: bigint, v: bigint) => { + isValid: boolean; + value: bigint; + }) | undefined; + readonly prehash?: ut.FHash | undefined; + readonly mapToCurve?: ((scalar: bigint[]) => AffinePoint) | undefined; + readonly p: bigint; +}>; +export interface ExtPointType extends Group { + readonly ex: bigint; + readonly ey: bigint; + readonly ez: bigint; + readonly et: bigint; + get x(): bigint; + get y(): bigint; + assertValidity(): void; + multiply(scalar: bigint): ExtPointType; + multiplyUnsafe(scalar: bigint): ExtPointType; + isSmallOrder(): boolean; + isTorsionFree(): boolean; + clearCofactor(): ExtPointType; + toAffine(iz?: bigint): AffinePoint; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; +} +export interface ExtPointConstructor extends GroupConstructor { + new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType; + fromAffine(p: AffinePoint): ExtPointType; + fromHex(hex: Hex): ExtPointType; + fromPrivateKey(privateKey: Hex): ExtPointType; +} +export type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: Hex) => Uint8Array; + sign: (message: Hex, privateKey: Hex, options?: { + context?: Hex; + }) => Uint8Array; + verify: (sig: Hex, message: Hex, publicKey: Hex, options?: { + context?: Hex; + zip215: boolean; + }) => boolean; + ExtendedPoint: ExtPointConstructor; + utils: { + randomPrivateKey: () => Uint8Array; + getExtendedPublicKey: (key: Hex) => { + head: Uint8Array; + prefix: Uint8Array; + scalar: bigint; + point: ExtPointType; + pointBytes: Uint8Array; + }; + }; +}; +export declare function twistedEdwards(curveDef: CurveType): CurveFn; +export {}; +//# sourceMappingURL=edwards.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/edwards.d.ts.map b/node_modules/@noble/curves/abstract/edwards.d.ts.map new file mode 100644 index 0000000..a32123f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G,CAAA;KAAE,KAAK,UAAU,CAAC;IACjF,MAAM,EAAE,CACN,GAAG,EAAE,GAAG,EACR,OAAO,EAAE,GAAG,EACZ,SAAS,EAAE,GAAG,EACd,OAAO,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,GAAG,CAAC;QAAC,MAAM,EAAE,OAAO,CAAA;KAAE,KACzC,OAAO,CAAC;IACb,aAAa,EAAE,mBAAmB,CAAC;IACnC,KAAK,EAAE;QACL,gBAAgB,EAAE,MAAM,UAAU,CAAC;QACnC,oBAAoB,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK;YAClC,IAAI,EAAE,UAAU,CAAC;YACjB,MAAM,EAAE,UAAU,CAAC;YACnB,MAAM,EAAE,MAAM,CAAC;YACf,KAAK,EAAE,YAAY,CAAC;YACpB,UAAU,EAAE,UAAU,CAAC;SACxB,CAAC;KACH,CAAC;CACH,CAAC;AAGF,wBAAgB,cAAc,CAAC,QAAQ,EAAE,SAAS,GAAG,OAAO,CA8Z3D"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/edwards.js b/node_modules/@noble/curves/abstract/edwards.js new file mode 100644 index 0000000..6dd4151 --- /dev/null +++ b/node_modules/@noble/curves/abstract/edwards.js @@ -0,0 +1,429 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.twistedEdwards = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y² +const modular_js_1 = require("./modular.js"); +const ut = require("./utils.js"); +const utils_js_1 = require("./utils.js"); +const curve_js_1 = require("./curve.js"); +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8); +// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex: +const VERIFY_DEFAULT = { zip215: true }; +function validateOpts(curve) { + const opts = (0, curve_js_1.validateBasic)(curve); + ut.validateObject(curve, { + hash: 'function', + a: 'bigint', + d: 'bigint', + randomBytes: 'function', + }, { + adjustScalarBytes: 'function', + domain: 'function', + uvRatio: 'function', + mapToCurve: 'function', + }); + // Set defaults + return Object.freeze({ ...opts }); +} +// It is not generic twisted curve for now, but ed25519/ed448 generic implementation +function twistedEdwards(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE; + const MASK = _2n << (BigInt(nByteLength * 8) - _1n); + const modP = Fp.create; // Function overrides + // sqrt(u/v) + const uvRatio = CURVE.uvRatio || + ((u, v) => { + try { + return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) }; + } + catch (e) { + return { isValid: false, value: _0n }; + } + }); + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP + const domain = CURVE.domain || + ((data, ctx, phflag) => { + if (ctx.length || phflag) + throw new Error('Contexts/pre-hash are not supported'); + return data; + }); // NOOP + const inBig = (n) => typeof n === 'bigint' && _0n < n; // n in [1..] + const inRange = (n, max) => inBig(n) && inBig(max) && n < max; // n in [1..max-1] + const in0MaskRange = (n) => n === _0n || inRange(n, MASK); // n in [0..MASK-1] + function assertInRange(n, max) { + // n in [1..max-1] + if (inRange(n, max)) + return n; + throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`); + } + function assertGE0(n) { + // n in [0..CURVE_ORDER-1] + return n === _0n ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group + } + const pointPrecomputes = new Map(); + function isPoint(other) { + if (!(other instanceof Point)) + throw new Error('ExtendedPoint expected'); + } + // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy). + // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates + class Point { + constructor(ex, ey, ez, et) { + this.ex = ex; + this.ey = ey; + this.ez = ez; + this.et = et; + if (!in0MaskRange(ex)) + throw new Error('x required'); + if (!in0MaskRange(ey)) + throw new Error('y required'); + if (!in0MaskRange(ez)) + throw new Error('z required'); + if (!in0MaskRange(et)) + throw new Error('t required'); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + static fromAffine(p) { + if (p instanceof Point) + throw new Error('extended point not allowed'); + const { x, y } = p || {}; + if (!in0MaskRange(x) || !in0MaskRange(y)) + throw new Error('invalid affine point'); + return new Point(x, y, _1n, modP(x * y)); + } + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.ez)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + // Not required for fromHex(), which always creates valid points. + // Could be useful for fromAffine(). + assertValidity() { + const { a, d } = CURVE; + if (this.is0()) + throw new Error('bad point: ZERO'); // TODO: optimize, with vars below? + // Equation in affine coordinates: ax² + y² = 1 + dx²y² + // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y² + const { ex: X, ey: Y, ez: Z, et: T } = this; + const X2 = modP(X * X); // X² + const Y2 = modP(Y * Y); // Y² + const Z2 = modP(Z * Z); // Z² + const Z4 = modP(Z2 * Z2); // Z⁴ + const aX2 = modP(X2 * a); // aX² + const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z² + const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y² + if (left !== right) + throw new Error('bad point: equation left != right (1)'); + // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T + const XY = modP(X * Y); + const ZT = modP(Z * T); + if (XY !== ZT) + throw new Error('bad point: equation left != right (2)'); + } + // Compare one point to another. + equals(other) { + isPoint(other); + const { ex: X1, ey: Y1, ez: Z1 } = this; + const { ex: X2, ey: Y2, ez: Z2 } = other; + const X1Z2 = modP(X1 * Z2); + const X2Z1 = modP(X2 * Z1); + const Y1Z2 = modP(Y1 * Z2); + const Y2Z1 = modP(Y2 * Z1); + return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; + } + is0() { + return this.equals(Point.ZERO); + } + negate() { + // Flips point sign to a negative one (-x, y in affine coords) + return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et)); + } + // Fast algo for doubling Extended Point. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd + // Cost: 4M + 4S + 1*a + 6add + 1*2. + double() { + const { a } = CURVE; + const { ex: X1, ey: Y1, ez: Z1 } = this; + const A = modP(X1 * X1); // A = X12 + const B = modP(Y1 * Y1); // B = Y12 + const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12 + const D = modP(a * A); // D = a*A + const x1y1 = X1 + Y1; + const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B + const G = D + B; // G = D+B + const F = G - C; // F = G-C + const H = D - B; // H = D-B + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + // Fast algo for adding 2 Extended Points. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd + // Cost: 9M + 1*a + 1*d + 7add. + add(other) { + isPoint(other); + const { a, d } = CURVE; + const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this; + const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other; + // Faster algo for adding 2 Extended Points when curve's a=-1. + // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4 + // Cost: 8M + 8add + 2*2. + // Note: It does not check whether the `other` point is valid. + if (a === BigInt(-1)) { + const A = modP((Y1 - X1) * (Y2 + X2)); + const B = modP((Y1 + X1) * (Y2 - X2)); + const F = modP(B - A); + if (F === _0n) + return this.double(); // Same point. Tests say it doesn't affect timing + const C = modP(Z1 * _2n * T2); + const D = modP(T1 * _2n * Z2); + const E = D + C; + const G = B + A; + const H = D - C; + const X3 = modP(E * F); + const Y3 = modP(G * H); + const T3 = modP(E * H); + const Z3 = modP(F * G); + return new Point(X3, Y3, Z3, T3); + } + const A = modP(X1 * X2); // A = X1*X2 + const B = modP(Y1 * Y2); // B = Y1*Y2 + const C = modP(T1 * d * T2); // C = T1*d*T2 + const D = modP(Z1 * Z2); // D = Z1*Z2 + const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B + const F = D - C; // F = D-C + const G = D + C; // G = D+C + const H = modP(B - a * A); // H = B-a*A + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + subtract(other) { + return this.add(other.negate()); + } + wNAF(n) { + return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ); + } + // Constant-time multiplication. + multiply(scalar) { + const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER)); + return Point.normalizeZ([p, f])[0]; + } + // Non-constant-time multiplication. Uses double-and-add algorithm. + // It's faster, but should only be used when you don't care about + // an exposed private key e.g. sig verification. + // Does NOT allow scalars higher than CURVE.n. + multiplyUnsafe(scalar) { + let n = assertGE0(scalar); // 0 <= scalar < CURVE.n + if (n === _0n) + return I; + if (this.equals(I) || n === _1n) + return this; + if (this.equals(G)) + return this.wNAF(n).p; + return wnaf.unsafeLadder(this, n); + } + // Checks if point is of small order. + // If you add something to small order point, you will have "dirty" + // point with torsion component. + // Multiplies point by cofactor and checks if the result is 0. + isSmallOrder() { + return this.multiplyUnsafe(cofactor).is0(); + } + // Multiplies point by curve order and checks if the result is 0. + // Returns `false` is the point is dirty. + isTorsionFree() { + return wnaf.unsafeLadder(this, CURVE_ORDER).is0(); + } + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + toAffine(iz) { + const { ex: x, ey: y, ez: z } = this; + const is0 = this.is0(); + if (iz == null) + iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily + const ax = modP(x * iz); + const ay = modP(y * iz); + const zz = modP(z * iz); + if (is0) + return { x: _0n, y: _1n }; + if (zz !== _1n) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + } + clearCofactor() { + const { h: cofactor } = CURVE; + if (cofactor === _1n) + return this; + return this.multiplyUnsafe(cofactor); + } + // Converts hash string or Uint8Array to Point. + // Uses algo from RFC8032 5.1.3. + static fromHex(hex, zip215 = false) { + const { d, a } = CURVE; + const len = Fp.BYTES; + hex = (0, utils_js_1.ensureBytes)('pointHex', hex, len); // copy hex to a new array + const normed = hex.slice(); // copy again, we'll manipulate it + const lastByte = hex[len - 1]; // select last byte + normed[len - 1] = lastByte & ~0x80; // clear last bit + const y = ut.bytesToNumberLE(normed); + if (y === _0n) { + // y=0 is allowed + } + else { + // RFC8032 prohibits >= p, but ZIP215 doesn't + if (zip215) + assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519) + else + assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519) + } + // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case: + // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a) + const y2 = modP(y * y); // denominator is always non-0 mod p. + const u = modP(y2 - _1n); // u = y² - 1 + const v = modP(d * y2 - a); // v = d y² + 1. + let { isValid, value: x } = uvRatio(u, v); // √(u/v) + if (!isValid) + throw new Error('Point.fromHex: invalid y coordinate'); + const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper + const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit + if (!zip215 && x === _0n && isLastByteOdd) + // if x=0 and x_0 = 1, fail + throw new Error('Point.fromHex: x=0 and x_0=1'); + if (isLastByteOdd !== isXOdd) + x = modP(-x); // if x_0 != x mod 2, set x = p-x + return Point.fromAffine({ x, y }); + } + static fromPrivateKey(privKey) { + return getExtendedPublicKey(privKey).point; + } + toRawBytes() { + const { x, y } = this.toAffine(); + const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y) + bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y + return bytes; // and use the last byte to encode sign of x + } + toHex() { + return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string. + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy)); + Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0 + const { BASE: G, ZERO: I } = Point; + const wnaf = (0, curve_js_1.wNAF)(Point, nByteLength * 8); + function modN(a) { + return (0, modular_js_1.mod)(a, CURVE_ORDER); + } + // Little-endian SHA512 with modulo n + function modN_LE(hash) { + return modN(ut.bytesToNumberLE(hash)); + } + /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */ + function getExtendedPublicKey(key) { + const len = nByteLength; + key = (0, utils_js_1.ensureBytes)('private key', key, len); + // Hash private key with curve's hash function to produce uniformingly random input + // Check byte lengths: ensure(64, h(ensure(32, key))) + const hashed = (0, utils_js_1.ensureBytes)('hashed private key', cHash(key), 2 * len); + const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE + const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6) + const scalar = modN_LE(head); // The actual private scalar + const point = G.multiply(scalar); // Point on Edwards curve aka public key + const pointBytes = point.toRawBytes(); // Uint8Array representation + return { head, prefix, scalar, point, pointBytes }; + } + // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared + function getPublicKey(privKey) { + return getExtendedPublicKey(privKey).pointBytes; + } + // int('LE', SHA512(dom2(F, C) || msgs)) mod N + function hashDomainToScalar(context = new Uint8Array(), ...msgs) { + const msg = ut.concatBytes(...msgs); + return modN_LE(cHash(domain(msg, (0, utils_js_1.ensureBytes)('context', context), !!prehash))); + } + /** Signs message with privateKey. RFC8032 5.1.6 */ + function sign(msg, privKey, options = {}) { + msg = (0, utils_js_1.ensureBytes)('message', msg); + if (prehash) + msg = prehash(msg); // for ed25519ph etc. + const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey); + const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M) + const R = G.multiply(r).toRawBytes(); // R = rG + const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M) + const s = modN(r + k * scalar); // S = (r + k * s) mod L + assertGE0(s); // 0 <= s < l + const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES)); + return (0, utils_js_1.ensureBytes)('result', res, nByteLength * 2); // 64-byte signature + } + const verifyOpts = VERIFY_DEFAULT; + function verify(sig, msg, publicKey, options = verifyOpts) { + const { context, zip215 } = options; + const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7. + sig = (0, utils_js_1.ensureBytes)('signature', sig, 2 * len); // An extended group equation is checked. + msg = (0, utils_js_1.ensureBytes)('message', msg); + if (prehash) + msg = prehash(msg); // for ed25519ph, etc + const s = ut.bytesToNumberLE(sig.slice(len, 2 * len)); + // zip215: true is good for consensus-critical apps and allows points < 2^256 + // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p + let A, R, SB; + try { + A = Point.fromHex(publicKey, zip215); + R = Point.fromHex(sig.slice(0, len), zip215); + SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside + } + catch (error) { + return false; + } + if (!zip215 && A.isSmallOrder()) + return false; + const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg); + const RkA = R.add(A.multiplyUnsafe(k)); + // [8][S]B = [8]R + [8][k]A' + return RkA.subtract(SB).clearCofactor().equals(Point.ZERO); + } + G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms. + const utils = { + getExtendedPublicKey, + // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1. + randomPrivateKey: () => randomBytes(Fp.BYTES), + /** + * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT + * values. This slows down first getPublicKey() by milliseconds (see Speed section), + * but allows to speed-up subsequent getPublicKey() calls up to 20x. + * @param windowSize 2, 4, 8, 16 + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; + }, + }; + return { + CURVE, + getPublicKey, + sign, + verify, + ExtendedPoint: Point, + utils, + }; +} +exports.twistedEdwards = twistedEdwards; +//# sourceMappingURL=edwards.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/edwards.js.map b/node_modules/@noble/curves/abstract/edwards.js.map new file mode 100644 index 0000000..73ac6d5 --- /dev/null +++ b/node_modules/@noble/curves/abstract/edwards.js.map @@ -0,0 +1 @@ +{"version":3,"file":"edwards.js","sourceRoot":"","sources":["../src/abstract/edwards.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,8DAA8D;AAC9D,6CAAmC;AACnC,iCAAiC;AACjC,yCAAqD;AACrD,yCAAmG;AAEnG,qEAAqE;AACrE,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAezE,8EAA8E;AAC9E,MAAM,cAAc,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;AAExC,SAAS,YAAY,CAAC,KAAgB;IACpC,MAAM,IAAI,GAAG,IAAA,wBAAa,EAAC,KAAK,CAAC,CAAC;IAClC,EAAE,CAAC,cAAc,CACf,KAAK,EACL;QACE,IAAI,EAAE,UAAU;QAChB,CAAC,EAAE,QAAQ;QACX,CAAC,EAAE,QAAQ;QACX,WA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C;IAC7D,CAAC;IAED,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,sEAAsE;IAE3F,MAAM,KAAK,GAAG;QACZ,oBAAoB;QACpB,6FAA6F;QAC7F,gBAAgB,EAAE,GAAe,EAAE,CAAC,WAAW,CAAC,EAAE,CAAC,KAAK,CAAC;QAEzD;;;;;WAKG;QACH,UAAU,CAAC,UAAU,GAAG,CAAC,EAAE,KAAK,GAAG,KAAK,CAAC,IAAI;YAC3C,KAAK,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC;YACjC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;YAC1B,OAAO,KAAK,CAAC;QACf,CAAC;KACF,CAAC;IAEF,OAAO;QACL,KAAK;QACL,YAAY;QACZ,IAAI;QACJ,MAAM;QACN,aAAa,EAAE,KAAK;QACpB,KAAK;KACN,CAAC;AACJ,CAAC;AA9ZD,wCA8ZC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/hash-to-curve.d.ts b/node_modules/@noble/curves/abstract/hash-to-curve.d.ts new file mode 100644 index 0000000..5720293 --- /dev/null +++ b/node_modules/@noble/curves/abstract/hash-to-curve.d.ts @@ -0,0 +1,57 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import type { Group, GroupConstructor, AffinePoint } from './curve.js'; +import { IField } from './modular.js'; +import { CHash } from './utils.js'; +/** + * * `DST` is a domain separation tag, defined in section 2.2.5 + * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m + * * `m` is extension degree (1 for prime fields) + * * `k` is the target security target in bits (e.g. 128), from section 5.1 + * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF) + * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props + */ +type UnicodeOrBytes = string | Uint8Array; +export type Opts = { + DST: UnicodeOrBytes; + p: bigint; + m: number; + k: number; + expand: 'xmd' | 'xof'; + hash: CHash; +}; +export declare function expand_message_xmd(msg: Uint8Array, DST: Uint8Array, lenInBytes: number, H: CHash): Uint8Array; +export declare function expand_message_xof(msg: Uint8Array, DST: Uint8Array, lenInBytes: number, k: number, H: CHash): Uint8Array; +/** + * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F + * https://www.rfc-editor.org/rfc/rfc9380#section-5.2 + * @param msg a byte string containing the message to hash + * @param count the number of elements of F to output + * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above + * @returns [u_0, ..., u_(count - 1)], a list of field elements. + */ +export declare function hash_to_field(msg: Uint8Array, count: number, options: Opts): bigint[][]; +export declare function isogenyMap>(field: F, map: [T[], T[], T[], T[]]): (x: T, y: T) => { + x: T; + y: T; +}; +export interface H2CPoint extends Group> { + add(rhs: H2CPoint): H2CPoint; + toAffine(iz?: bigint): AffinePoint; + clearCofactor(): H2CPoint; + assertValidity(): void; +} +export interface H2CPointConstructor extends GroupConstructor> { + fromAffine(ap: AffinePoint): H2CPoint; +} +export type MapToCurve = (scalar: bigint[]) => AffinePoint; +export type htfBasicOpts = { + DST: UnicodeOrBytes; +}; +export declare function createHasher(Point: H2CPointConstructor, mapToCurve: MapToCurve, def: Opts & { + encodeDST?: UnicodeOrBytes; +}): { + hashToCurve(msg: Uint8Array, options?: htfBasicOpts): H2CPoint; + encodeToCurve(msg: Uint8Array, options?: htfBasicOpts): H2CPoint; +}; +export {}; +//# sourceMappingURL=hash-to-curve.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/hash-to-curve.d.ts.map b/node_modules/@noble/curves/abstract/hash-to-curve.d.ts.map new file mode 100644 index 0000000..e74c0d7 --- /dev/null +++ b/node_modules/@noble/curves/abstract/hash-to-curve.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"hash-to-curve.d.ts","sourceRoot":"","sources":["../src/abstract/hash-to-curve.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,KAAK,EAAE,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GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;IACnC,QAAQ,CAAC,EAAE,CAAC,EAAE,MAAM,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC;IACtC,aAAa,IAAI,QAAQ,CAAC,CAAC,CAAC,CAAC;IAC7B,cAAc,IAAI,IAAI,CAAC;CACxB;AAED,MAAM,WAAW,mBAAmB,CAAC,CAAC,CAAE,SAAQ,gBAAgB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;IAC3E,UAAU,CAAC,EAAE,EAAE,WAAW,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;CAC7C;AAED,MAAM,MAAM,UAAU,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,WAAW,CAAC,CAAC,CAAC,CAAC;AAIjE,MAAM,MAAM,YAAY,GAAG;IAAE,GAAG,EAAE,cAAc,CAAA;CAAE,CAAC;AAEnD,wBAAgB,YAAY,CAAC,CAAC,EAC5B,KAAK,EAAE,mBAAmB,CAAC,CAAC,CAAC,EAC7B,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,EACzB,GAAG,EAAE,IAAI,GAAG;IAAE,SAAS,CAAC,EAAE,cAAc,CAAA;CAAE;qBAMvB,UAAU,YAAY,YAAY;uBAWhC,UAAU,YAAY,YAAY;EAOxD"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/hash-to-curve.js b/node_modules/@noble/curves/abstract/hash-to-curve.js new file mode 100644 index 0000000..aaab7c5 --- /dev/null +++ b/node_modules/@noble/curves/abstract/hash-to-curve.js @@ -0,0 +1,181 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createHasher = exports.isogenyMap = exports.hash_to_field = exports.expand_message_xof = exports.expand_message_xmd = void 0; +const modular_js_1 = require("./modular.js"); +const utils_js_1 = require("./utils.js"); +function validateDST(dst) { + if (dst instanceof Uint8Array) + return dst; + if (typeof dst === 'string') + return (0, utils_js_1.utf8ToBytes)(dst); + throw new Error('DST must be Uint8Array or string'); +} +// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE. +const os2ip = utils_js_1.bytesToNumberBE; +// Integer to Octet Stream (numberToBytesBE) +function i2osp(value, length) { + if (value < 0 || value >= 1 << (8 * length)) { + throw new Error(`bad I2OSP call: value=${value} length=${length}`); + } + const res = Array.from({ length }).fill(0); + for (let i = length - 1; i >= 0; i--) { + res[i] = value & 0xff; + value >>>= 8; + } + return new Uint8Array(res); +} +function strxor(a, b) { + const arr = new Uint8Array(a.length); + for (let i = 0; i < a.length; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} +function isBytes(item) { + if (!(item instanceof Uint8Array)) + throw new Error('Uint8Array expected'); +} +function isNum(item) { + if (!Number.isSafeInteger(item)) + throw new Error('number expected'); +} +// Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits +// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1 +function expand_message_xmd(msg, DST, lenInBytes, H) { + isBytes(msg); + isBytes(DST); + isNum(lenInBytes); + // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3 + if (DST.length > 255) + DST = H((0, utils_js_1.concatBytes)((0, utils_js_1.utf8ToBytes)('H2C-OVERSIZE-DST-'), DST)); + const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H; + const ell = Math.ceil(lenInBytes / b_in_bytes); + if (ell > 255) + throw new Error('Invalid xmd length'); + const DST_prime = (0, utils_js_1.concatBytes)(DST, i2osp(DST.length, 1)); + const Z_pad = i2osp(0, r_in_bytes); + const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str + const b = new Array(ell); + const b_0 = H((0, utils_js_1.concatBytes)(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); + b[0] = H((0, utils_js_1.concatBytes)(b_0, i2osp(1, 1), DST_prime)); + for (let i = 1; i <= ell; i++) { + const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime]; + b[i] = H((0, utils_js_1.concatBytes)(...args)); + } + const pseudo_random_bytes = (0, utils_js_1.concatBytes)(...b); + return pseudo_random_bytes.slice(0, lenInBytes); +} +exports.expand_message_xmd = expand_message_xmd; +// Produces a uniformly random byte string using an extendable-output function (XOF) H. +// 1. The collision resistance of H MUST be at least k bits. +// 2. H MUST be an XOF that has been proved indifferentiable from +// a random oracle under a reasonable cryptographic assumption. +// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2 +function expand_message_xof(msg, DST, lenInBytes, k, H) { + isBytes(msg); + isBytes(DST); + isNum(lenInBytes); + // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3 + // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8)); + if (DST.length > 255) { + const dkLen = Math.ceil((2 * k) / 8); + DST = H.create({ dkLen }).update((0, utils_js_1.utf8ToBytes)('H2C-OVERSIZE-DST-')).update(DST).digest(); + } + if (lenInBytes > 65535 || DST.length > 255) + throw new Error('expand_message_xof: invalid lenInBytes'); + return (H.create({ dkLen: lenInBytes }) + .update(msg) + .update(i2osp(lenInBytes, 2)) + // 2. DST_prime = DST || I2OSP(len(DST), 1) + .update(DST) + .update(i2osp(DST.length, 1)) + .digest()); +} +exports.expand_message_xof = expand_message_xof; +/** + * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F + * https://www.rfc-editor.org/rfc/rfc9380#section-5.2 + * @param msg a byte string containing the message to hash + * @param count the number of elements of F to output + * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above + * @returns [u_0, ..., u_(count - 1)], a list of field elements. + */ +function hash_to_field(msg, count, options) { + (0, utils_js_1.validateObject)(options, { + DST: 'stringOrUint8Array', + p: 'bigint', + m: 'isSafeInteger', + k: 'isSafeInteger', + hash: 'hash', + }); + const { p, k, m, hash, expand, DST: _DST } = options; + isBytes(msg); + isNum(count); + const DST = validateDST(_DST); + const log2p = p.toString(2).length; + const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above + const len_in_bytes = count * m * L; + let prb; // pseudo_random_bytes + if (expand === 'xmd') { + prb = expand_message_xmd(msg, DST, len_in_bytes, hash); + } + else if (expand === 'xof') { + prb = expand_message_xof(msg, DST, len_in_bytes, k, hash); + } + else if (expand === '_internal_pass') { + // for internal tests only + prb = msg; + } + else { + throw new Error('expand must be "xmd" or "xof"'); + } + const u = new Array(count); + for (let i = 0; i < count; i++) { + const e = new Array(m); + for (let j = 0; j < m; j++) { + const elm_offset = L * (j + i * m); + const tv = prb.subarray(elm_offset, elm_offset + L); + e[j] = (0, modular_js_1.mod)(os2ip(tv), p); + } + u[i] = e; + } + return u; +} +exports.hash_to_field = hash_to_field; +function isogenyMap(field, map) { + // Make same order as in spec + const COEFF = map.map((i) => Array.from(i).reverse()); + return (x, y) => { + const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i))); + x = field.div(xNum, xDen); // xNum / xDen + y = field.mul(y, field.div(yNum, yDen)); // y * (yNum / yDev) + return { x, y }; + }; +} +exports.isogenyMap = isogenyMap; +function createHasher(Point, mapToCurve, def) { + if (typeof mapToCurve !== 'function') + throw new Error('mapToCurve() must be defined'); + return { + // Encodes byte string to elliptic curve. + // hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 + hashToCurve(msg, options) { + const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options }); + const u0 = Point.fromAffine(mapToCurve(u[0])); + const u1 = Point.fromAffine(mapToCurve(u[1])); + const P = u0.add(u1).clearCofactor(); + P.assertValidity(); + return P; + }, + // Encodes byte string to elliptic curve. + // encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 + encodeToCurve(msg, options) { + const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options }); + const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor(); + P.assertValidity(); + return P; + }, + }; +} +exports.createHasher = createHasher; +//# sourceMappingURL=hash-to-curve.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/hash-to-curve.js.map b/node_modules/@noble/curves/abstract/hash-to-curve.js.map new file mode 100644 index 0000000..d59745d --- /dev/null +++ b/node_modules/@noble/curves/abstract/hash-to-curve.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hash-to-curve.js","sourceRoot":"","sources":["../src/abstract/hash-to-curve.ts"],"names":[],"mappings":";;;AAEA,6CAA2C;AAC3C,yCAA8F;AAoB9F,SAAS,WAAW,CAAC,GAAmB;IACtC,IAAI,GAAG,YAAY,UAAU;QAAE,OAAO,GAAG,CAAC;IAC1C,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,OAAO,IAAA,sBAAW,EAAC,GAAG,CAAC,CAAC;IACrD,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;AACtD,CAAC;AAED,6FAA6F;AAC7F,MAAM,KAAK,GAAG,0BAAe,CAAC;AAE9B,4CAA4C;AAC5C,SAAS,KAAK,CAAC,KAAa,EAAE,MAAc;IAC1C,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,MAAM,CAAC,EAAE;QAC3C,MAAM,IAAI,KAAK,CAAC,yBAAyB,KAAK,WAAW,MAAM,EAAE,CAAC,CAAC;KACpE;IACD,MAAM,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAa,CAAC;IACvD,KAAK,IAAI,CAAC,GAAG,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE;QACpC,GAAG,CAAC,CAAC,CAAC,GAAG,KAAK,GAAG,IAAI,CAAC;QACtB,KAAK,MAAM,CAAC,CAAC;KACd;IACD,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,MAAM,CAAC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AA3BD,oCA2BC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/modular.d.ts b/node_modules/@noble/curves/abstract/modular.d.ts new file mode 100644 index 0000000..42d4926 --- /dev/null +++ b/node_modules/@noble/curves/abstract/modular.d.ts @@ -0,0 +1,123 @@ +export declare function mod(a: bigint, b: bigint): bigint; +/** + * Efficiently raise num to power and do modular division. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + * @example + * pow(2n, 6n, 11n) // 64n % 11n == 9n + */ +export declare function pow(num: bigint, power: bigint, modulo: bigint): bigint; +export declare function pow2(x: bigint, power: bigint, modulo: bigint): bigint; +export declare function invert(number: bigint, modulo: bigint): bigint; +/** + * Tonelli-Shanks square root search algorithm. + * 1. https://eprint.iacr.org/2012/685.pdf (page 12) + * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks + * Will start an infinite loop if field order P is not prime. + * @param P field order + * @returns function that takes field Fp (created from P) and number n + */ +export declare function tonelliShanks(P: bigint): (Fp: IField, n: T) => T; +export declare function FpSqrt(P: bigint): (Fp: IField, n: T) => T; +export declare const isNegativeLE: (num: bigint, modulo: bigint) => boolean; +export interface IField { + ORDER: bigint; + BYTES: number; + BITS: number; + MASK: bigint; + ZERO: T; + ONE: T; + create: (num: T) => T; + isValid: (num: T) => boolean; + is0: (num: T) => boolean; + neg(num: T): T; + inv(num: T): T; + sqrt(num: T): T; + sqr(num: T): T; + eql(lhs: T, rhs: T): boolean; + add(lhs: T, rhs: T): T; + sub(lhs: T, rhs: T): T; + mul(lhs: T, rhs: T | bigint): T; + pow(lhs: T, power: bigint): T; + div(lhs: T, rhs: T | bigint): T; + addN(lhs: T, rhs: T): T; + subN(lhs: T, rhs: T): T; + mulN(lhs: T, rhs: T | bigint): T; + sqrN(num: T): T; + isOdd?(num: T): boolean; + pow(lhs: T, power: bigint): T; + invertBatch: (lst: T[]) => T[]; + toBytes(num: T): Uint8Array; + fromBytes(bytes: Uint8Array): T; + cmov(a: T, b: T, c: boolean): T; +} +export declare function validateField(field: IField): IField; +/** + * Same as `pow` but for Fp: non-constant-time. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + */ +export declare function FpPow(f: IField, num: T, power: bigint): T; +/** + * Efficiently invert an array of Field elements. + * `inv(0)` will return `undefined` here: make sure to throw an error. + */ +export declare function FpInvertBatch(f: IField, nums: T[]): T[]; +export declare function FpDiv(f: IField, lhs: T, rhs: T | bigint): T; +export declare function FpIsSquare(f: IField): (x: T) => boolean; +export declare function nLength(n: bigint, nBitLength?: number): { + nBitLength: number; + nByteLength: number; +}; +type FpField = IField & Required, 'isOdd'>>; +/** + * Initializes a finite field over prime. **Non-primes are not supported.** + * Do not init in loop: slow. Very fragile: always run a benchmark on a change. + * Major performance optimizations: + * * a) denormalized operations like mulN instead of mul + * * b) same object shape: never add or remove keys + * * c) Object.freeze + * @param ORDER prime positive bigint + * @param bitLen how many bits the field consumes + * @param isLE (def: false) if encoding / decoding should be in little-endian + * @param redef optional faster redefinitions of sqrt and other methods + */ +export declare function Field(ORDER: bigint, bitLen?: number, isLE?: boolean, redef?: Partial>): Readonly; +export declare function FpSqrtOdd(Fp: IField, elm: T): T; +export declare function FpSqrtEven(Fp: IField, elm: T): T; +/** + * "Constant-time" private key generation utility. + * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field). + * Which makes it slightly more biased, less secure. + * @deprecated use mapKeyToField instead + */ +export declare function hashToPrivateScalar(hash: string | Uint8Array, groupOrder: bigint, isLE?: boolean): bigint; +/** + * Returns total number of bytes consumed by the field element. + * For example, 32 bytes for usual 256-bit weierstrass curve. + * @param fieldOrder number of field elements, usually CURVE.n + * @returns byte length of field + */ +export declare function getFieldBytesLength(fieldOrder: bigint): number; +/** + * Returns minimal amount of bytes that can be safely reduced + * by field order. + * Should be 2^-128 for 128-bit curve such as P256. + * @param fieldOrder number of field elements, usually CURVE.n + * @returns byte length of target hash + */ +export declare function getMinHashLength(fieldOrder: bigint): number; +/** + * "Constant-time" private key generation utility. + * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF + * and convert them into private scalar, with the modulo bias being negligible. + * Needs at least 48 bytes of input for 32-byte private key. + * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ + * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final + * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5 + * @param hash hash output from SHA3 or a similar function + * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n) + * @param isLE interpret hash bytes as LE num + * @returns valid private scalar + */ +export declare function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE?: boolean): Uint8Array; +export {}; +//# sourceMappingURL=modular.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/modular.d.ts.map b/node_modules/@noble/curves/abstract/modular.d.ts.map new file mode 100644 index 0000000..5f1521e --- /dev/null +++ b/node_modules/@noble/curves/abstract/modular.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"modular.d.ts","sourceRoot":"","sources":["../src/abstract/modular.ts"],"names":[],"mappings":"AAmBA,wBAAgB,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAGhD;AACD;;;;;GAKG;AAEH,wBAAgB,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAUtE;AAGD,wBAAgB,IAAI,CAAC,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAOrE;AAGD,wBAAgB,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAsB7D;AAED;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,CAAC,EAAE,MAAM,iCAsDtC;AAED,wBAAgB,MAAM,CAAC,CAAC,EAAE,MAAM,iCA2D/B;AAGD,eAAO,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EAAE,MAAM,CAAC,CAAC,CAAC,OAE7B,CAAC,KAAG,OAAO,CAIvB;AAGD,wBAAgB,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM;;;EAKrD;AAED,KAAK,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC;AACxE;;;;;;;;;;;GAWG;AACH,wBAAgB,KAAK,CACnB,KAAK,EAAE,MAAM,EACb,MAAM,CAAC,EAAE,MAAM,EACf,IAAI,UAAQ,EACZ,KAAK,GAAE,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAM,GAClC,QAAQ,CAAC,OAAO,CAAC,CAkDnB;AAED,wBAAgB,SAAS,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,KAIjD;AAED,wBAAgB,UAAU,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,KAIlD;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,MAAM,GAAG,UAAU,EACzB,UAAU,EAAE,MAAM,EAClB,IAAI,UAAQ,GACX,MAAM,CAQR;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAI9D;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAG3D;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,UAAQ,GAAG,UAAU,CAW5F"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/modular.js b/node_modules/@noble/curves/abstract/modular.js new file mode 100644 index 0000000..8da4be4 --- /dev/null +++ b/node_modules/@noble/curves/abstract/modular.js @@ -0,0 +1,439 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.mapHashToField = exports.getMinHashLength = exports.getFieldBytesLength = exports.hashToPrivateScalar = exports.FpSqrtEven = exports.FpSqrtOdd = exports.Field = exports.nLength = exports.FpIsSquare = exports.FpDiv = exports.FpInvertBatch = exports.FpPow = exports.validateField = exports.isNegativeLE = exports.FpSqrt = exports.tonelliShanks = exports.invert = exports.pow2 = exports.pow = exports.mod = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Utilities for modular arithmetics and finite fields +const utils_js_1 = require("./utils.js"); +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); +// prettier-ignore +const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8); +// prettier-ignore +const _9n = BigInt(9), _16n = BigInt(16); +// Calculates a modulo b +function mod(a, b) { + const result = a % b; + return result >= _0n ? result : b + result; +} +exports.mod = mod; +/** + * Efficiently raise num to power and do modular division. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + * @example + * pow(2n, 6n, 11n) // 64n % 11n == 9n + */ +// TODO: use field version && remove +function pow(num, power, modulo) { + if (modulo <= _0n || power < _0n) + throw new Error('Expected power/modulo > 0'); + if (modulo === _1n) + return _0n; + let res = _1n; + while (power > _0n) { + if (power & _1n) + res = (res * num) % modulo; + num = (num * num) % modulo; + power >>= _1n; + } + return res; +} +exports.pow = pow; +// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4) +function pow2(x, power, modulo) { + let res = x; + while (power-- > _0n) { + res *= res; + res %= modulo; + } + return res; +} +exports.pow2 = pow2; +// Inverses number over modulo +function invert(number, modulo) { + if (number === _0n || modulo <= _0n) { + throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); + } + // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/ + // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower. + let a = mod(number, modulo); + let b = modulo; + // prettier-ignore + let x = _0n, y = _1n, u = _1n, v = _0n; + while (a !== _0n) { + // JIT applies optimization if those two lines follow each other + const q = b / a; + const r = b % a; + const m = x - u * q; + const n = y - v * q; + // prettier-ignore + b = a, a = r, x = u, y = v, u = m, v = n; + } + const gcd = b; + if (gcd !== _1n) + throw new Error('invert: does not exist'); + return mod(x, modulo); +} +exports.invert = invert; +/** + * Tonelli-Shanks square root search algorithm. + * 1. https://eprint.iacr.org/2012/685.pdf (page 12) + * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks + * Will start an infinite loop if field order P is not prime. + * @param P field order + * @returns function that takes field Fp (created from P) and number n + */ +function tonelliShanks(P) { + // Legendre constant: used to calculate Legendre symbol (a | p), + // which denotes the value of a^((p-1)/2) (mod p). + // (a | p) ≡ 1 if a is a square (mod p) + // (a | p) ≡ -1 if a is not a square (mod p) + // (a | p) ≡ 0 if a ≡ 0 (mod p) + const legendreC = (P - _1n) / _2n; + let Q, S, Z; + // Step 1: By factoring out powers of 2 from p - 1, + // find q and s such that p - 1 = q*(2^s) with q odd + for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++) + ; + // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq + for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++) + ; + // Fast-path + if (S === 1) { + const p1div4 = (P + _1n) / _4n; + return function tonelliFast(Fp, n) { + const root = Fp.pow(n, p1div4); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Slow-path + const Q1div2 = (Q + _1n) / _2n; + return function tonelliSlow(Fp, n) { + // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1 + if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) + throw new Error('Cannot find square root'); + let r = S; + // TODO: will fail at Fp2/etc + let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b + let x = Fp.pow(n, Q1div2); // first guess at the square root + let b = Fp.pow(n, Q); // first guess at the fudge factor + while (!Fp.eql(b, Fp.ONE)) { + if (Fp.eql(b, Fp.ZERO)) + return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0) + // Find m such b^(2^m)==1 + let m = 1; + for (let t2 = Fp.sqr(b); m < r; m++) { + if (Fp.eql(t2, Fp.ONE)) + break; + t2 = Fp.sqr(t2); // t2 *= t2 + } + // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow + const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1) + g = Fp.sqr(ge); // g = ge * ge + x = Fp.mul(x, ge); // x *= ge + b = Fp.mul(b, g); // b *= g + r = m; + } + return x; + }; +} +exports.tonelliShanks = tonelliShanks; +function FpSqrt(P) { + // NOTE: different algorithms can give different roots, it is up to user to decide which one they want. + // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve). + // P ≡ 3 (mod 4) + // √n = n^((P+1)/4) + if (P % _4n === _3n) { + // Not all roots possible! + // const ORDER = + // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn; + // const NUM = 72057594037927816n; + const p1div4 = (P + _1n) / _4n; + return function sqrt3mod4(Fp, n) { + const root = Fp.pow(n, p1div4); + // Throw if root**2 != n + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10) + if (P % _8n === _5n) { + const c1 = (P - _5n) / _8n; + return function sqrt5mod8(Fp, n) { + const n2 = Fp.mul(n, _2n); + const v = Fp.pow(n2, c1); + const nv = Fp.mul(n, v); + const i = Fp.mul(Fp.mul(nv, _2n), v); + const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // P ≡ 9 (mod 16) + if (P % _16n === _9n) { + // NOTE: tonelli is too slow for bls-Fp2 calculations even on start + // Means we cannot use sqrt for constants at all! + // + // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F + // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F + // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F + // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic + // sqrt = (x) => { + // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4 + // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1 + // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1 + // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1 + // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x + // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x + // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x + // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x + // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x + // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2 + // } + } + // Other cases: Tonelli-Shanks algorithm + return tonelliShanks(P); +} +exports.FpSqrt = FpSqrt; +// Little-endian check for first LE bit (last BE bit); +const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n; +exports.isNegativeLE = isNegativeLE; +// prettier-ignore +const FIELD_FIELDS = [ + 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr', + 'eql', 'add', 'sub', 'mul', 'pow', 'div', + 'addN', 'subN', 'mulN', 'sqrN' +]; +function validateField(field) { + const initial = { + ORDER: 'bigint', + MASK: 'bigint', + BYTES: 'isSafeInteger', + BITS: 'isSafeInteger', + }; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = 'function'; + return map; + }, initial); + return (0, utils_js_1.validateObject)(field, opts); +} +exports.validateField = validateField; +// Generic field functions +/** + * Same as `pow` but for Fp: non-constant-time. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + */ +function FpPow(f, num, power) { + // Should have same speed as pow for bigints + // TODO: benchmark! + if (power < _0n) + throw new Error('Expected power > 0'); + if (power === _0n) + return f.ONE; + if (power === _1n) + return num; + let p = f.ONE; + let d = num; + while (power > _0n) { + if (power & _1n) + p = f.mul(p, d); + d = f.sqr(d); + power >>= _1n; + } + return p; +} +exports.FpPow = FpPow; +/** + * Efficiently invert an array of Field elements. + * `inv(0)` will return `undefined` here: make sure to throw an error. + */ +function FpInvertBatch(f, nums) { + const tmp = new Array(nums.length); + // Walk from first to last, multiply them by each other MOD p + const lastMultiplied = nums.reduce((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = acc; + return f.mul(acc, num); + }, f.ONE); + // Invert last element + const inverted = f.inv(lastMultiplied); + // Walk from last to first, multiply them by inverted each other MOD p + nums.reduceRight((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = f.mul(acc, tmp[i]); + return f.mul(acc, num); + }, inverted); + return tmp; +} +exports.FpInvertBatch = FpInvertBatch; +function FpDiv(f, lhs, rhs) { + return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs)); +} +exports.FpDiv = FpDiv; +// This function returns True whenever the value x is a square in the field F. +function FpIsSquare(f) { + const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic + return (x) => { + const p = f.pow(x, legendreConst); + return f.eql(p, f.ZERO) || f.eql(p, f.ONE); + }; +} +exports.FpIsSquare = FpIsSquare; +// CURVE.n lengths +function nLength(n, nBitLength) { + // Bit size, byte size of CURVE.n + const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} +exports.nLength = nLength; +/** + * Initializes a finite field over prime. **Non-primes are not supported.** + * Do not init in loop: slow. Very fragile: always run a benchmark on a change. + * Major performance optimizations: + * * a) denormalized operations like mulN instead of mul + * * b) same object shape: never add or remove keys + * * c) Object.freeze + * @param ORDER prime positive bigint + * @param bitLen how many bits the field consumes + * @param isLE (def: false) if encoding / decoding should be in little-endian + * @param redef optional faster redefinitions of sqrt and other methods + */ +function Field(ORDER, bitLen, isLE = false, redef = {}) { + if (ORDER <= _0n) + throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen); + if (BYTES > 2048) + throw new Error('Field lengths over 2048 bytes are not supported'); + const sqrtP = FpSqrt(ORDER); + const f = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: (0, utils_js_1.bitMask)(BITS), + ZERO: _0n, + ONE: _1n, + create: (num) => mod(num, ORDER), + isValid: (num) => { + if (typeof num !== 'bigint') + throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); + return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible + }, + is0: (num) => num === _0n, + isOdd: (num) => (num & _1n) === _1n, + neg: (num) => mod(-num, ORDER), + eql: (lhs, rhs) => lhs === rhs, + sqr: (num) => mod(num * num, ORDER), + add: (lhs, rhs) => mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod(lhs * rhs, ORDER), + pow: (num, power) => FpPow(f, num, power), + div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), + // Same as above, but doesn't normalize + sqrN: (num) => num * num, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + inv: (num) => invert(num, ORDER), + sqrt: redef.sqrt || ((n) => sqrtP(f, n)), + invertBatch: (lst) => FpInvertBatch(f, lst), + // TODO: do we really need constant cmov? + // We don't have const-time bigints anyway, so probably will be not very useful + cmov: (a, b, c) => (c ? b : a), + toBytes: (num) => (isLE ? (0, utils_js_1.numberToBytesLE)(num, BYTES) : (0, utils_js_1.numberToBytesBE)(num, BYTES)), + fromBytes: (bytes) => { + if (bytes.length !== BYTES) + throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); + return isLE ? (0, utils_js_1.bytesToNumberLE)(bytes) : (0, utils_js_1.bytesToNumberBE)(bytes); + }, + }); + return Object.freeze(f); +} +exports.Field = Field; +function FpSqrtOdd(Fp, elm) { + if (!Fp.isOdd) + throw new Error(`Field doesn't have isOdd`); + const root = Fp.sqrt(elm); + return Fp.isOdd(root) ? root : Fp.neg(root); +} +exports.FpSqrtOdd = FpSqrtOdd; +function FpSqrtEven(Fp, elm) { + if (!Fp.isOdd) + throw new Error(`Field doesn't have isOdd`); + const root = Fp.sqrt(elm); + return Fp.isOdd(root) ? Fp.neg(root) : root; +} +exports.FpSqrtEven = FpSqrtEven; +/** + * "Constant-time" private key generation utility. + * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field). + * Which makes it slightly more biased, less secure. + * @deprecated use mapKeyToField instead + */ +function hashToPrivateScalar(hash, groupOrder, isLE = false) { + hash = (0, utils_js_1.ensureBytes)('privateHash', hash); + const hashLen = hash.length; + const minLen = nLength(groupOrder).nByteLength + 8; + if (minLen < 24 || hashLen < minLen || hashLen > 1024) + throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`); + const num = isLE ? (0, utils_js_1.bytesToNumberLE)(hash) : (0, utils_js_1.bytesToNumberBE)(hash); + return mod(num, groupOrder - _1n) + _1n; +} +exports.hashToPrivateScalar = hashToPrivateScalar; +/** + * Returns total number of bytes consumed by the field element. + * For example, 32 bytes for usual 256-bit weierstrass curve. + * @param fieldOrder number of field elements, usually CURVE.n + * @returns byte length of field + */ +function getFieldBytesLength(fieldOrder) { + if (typeof fieldOrder !== 'bigint') + throw new Error('field order must be bigint'); + const bitLength = fieldOrder.toString(2).length; + return Math.ceil(bitLength / 8); +} +exports.getFieldBytesLength = getFieldBytesLength; +/** + * Returns minimal amount of bytes that can be safely reduced + * by field order. + * Should be 2^-128 for 128-bit curve such as P256. + * @param fieldOrder number of field elements, usually CURVE.n + * @returns byte length of target hash + */ +function getMinHashLength(fieldOrder) { + const length = getFieldBytesLength(fieldOrder); + return length + Math.ceil(length / 2); +} +exports.getMinHashLength = getMinHashLength; +/** + * "Constant-time" private key generation utility. + * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF + * and convert them into private scalar, with the modulo bias being negligible. + * Needs at least 48 bytes of input for 32-byte private key. + * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ + * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final + * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5 + * @param hash hash output from SHA3 or a similar function + * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n) + * @param isLE interpret hash bytes as LE num + * @returns valid private scalar + */ +function mapHashToField(key, fieldOrder, isLE = false) { + const len = key.length; + const fieldLen = getFieldBytesLength(fieldOrder); + const minLen = getMinHashLength(fieldOrder); + // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings. + if (len < 16 || len < minLen || len > 1024) + throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`); + const num = isLE ? (0, utils_js_1.bytesToNumberBE)(key) : (0, utils_js_1.bytesToNumberLE)(key); + // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0 + const reduced = mod(num, fieldOrder - _1n) + _1n; + return isLE ? (0, utils_js_1.numberToBytesLE)(reduced, fieldLen) : (0, utils_js_1.numberToBytesBE)(reduced, fieldLen); +} +exports.mapHashToField = mapHashToField; +//# sourceMappingURL=modular.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/modular.js.map b/node_modules/@noble/curves/abstract/modular.js.map new file mode 100644 index 0000000..451c0e5 --- /dev/null +++ b/node_modules/@noble/curves/abstract/modular.js.map @@ -0,0 +1 @@ +{"version":3,"file":"modular.js","sourceRoot":"","sources":["../src/abstract/modular.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,sDAAsD;AACtD,yCAQoB;AACpB,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACzE,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACxD,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;AAEzC,wBAAwB;AACxB,SAAgB,GAAG,CAAC,CAAS,EAAE,CAAS;IACtC,MAAM,MAAM,GAAG,CAAC,GAAG,CAAC,CAAC;IACrB,OAAO,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC;AAC7C,CAAC;AAHD,kBAGC;AACD;;;;;GAKG;AACH,oCAAoC;AACpC,SAAgB,GAAG,CAAC,GAAW,EAAE,KAAa,EAAE,MAAc;IAC5D,IAAI,MAAM,IAAI,GAAG,IAAI,KAAK,GAAG,GAAG;QAAE,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAA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,0BAAe,EAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAA,0BAAe,EAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AACxF,CAAC;AAXD,wCAWC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/montgomery.d.ts b/node_modules/@noble/curves/abstract/montgomery.d.ts new file mode 100644 index 0000000..69e2bc4 --- /dev/null +++ b/node_modules/@noble/curves/abstract/montgomery.d.ts @@ -0,0 +1,26 @@ +type Hex = string | Uint8Array; +export type CurveType = { + P: bigint; + nByteLength: number; + adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; + domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; + a: bigint; + montgomeryBits: number; + powPminus2?: (x: bigint) => bigint; + xyToU?: (x: bigint, y: bigint) => bigint; + Gu: bigint; + randomBytes?: (bytesLength?: number) => Uint8Array; +}; +export type CurveFn = { + scalarMult: (scalar: Hex, u: Hex) => Uint8Array; + scalarMultBase: (scalar: Hex) => Uint8Array; + getSharedSecret: (privateKeyA: Hex, publicKeyB: Hex) => Uint8Array; + getPublicKey: (privateKey: Hex) => Uint8Array; + utils: { + randomPrivateKey: () => Uint8Array; + }; + GuBytes: Uint8Array; +}; +export declare function montgomery(curveDef: CurveType): CurveFn; +export {}; +//# sourceMappingURL=montgomery.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/montgomery.d.ts.map b/node_modules/@noble/curves/abstract/montgomery.d.ts.map new file mode 100644 index 0000000..a0d1c0b --- /dev/null +++ b/node_modules/@noble/curves/abstract/montgomery.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"montgomery.d.ts","sourceRoot":"","sources":["../src/abstract/montgomery.ts"],"names":[],"mappings":"AAMA,KAAK,GAAG,GAAG,MAAM,GAAG,UAAU,CAAC;AAE/B,MAAM,MAAM,SAAS,GAAG;IACtB,CAAC,EAAE,MAAM,CAAC;IACV,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,UAAU,CAAC;IACtD,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,UAAU,EAAE,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,KAAK,UAAU,CAAC;IAC5E,CAAC,EAAE,MAAM,CAAC;IACV,cAAc,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IACnC,KAAK,CAAC,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IACzC,EAAE,EAAE,MAAM,CAAC;IACX,WAAW,CAAC,EAAE,CAAC,WAAW,CAAC,EAAE,MAAM,KAAK,UAAU,CAAC;CACpD,CAAC;AACF,MAAM,MAAM,OAAO,GAAG;IACpB,UAAU,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,KAAK,UAAU,CAAC;IAChD,cAAc,EAAE,CAAC,MAAM,EAAE,GAAG,KAAK,UAAU,CAAC;IAC5C,eAAe,EAAE,CAAC,WAAW,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,KAAK,UAAU,CAAC;IACnE,YAAY,EAAE,CAAC,UAAU,EAAE,GAAG,KAAK,UAAU,CAAC;IAC9C,KAAK,EAAE;QAAE,gBAAgB,EAAE,MAAM,UAAU,CAAA;KAAE,CAAC;IAC9C,OAAO,EAAE,UAAU,CAAC;CACrB,CAAC;AAuBF,wBAAgB,UAAU,CAAC,QAAQ,EAAE,SAAS,GAAG,OAAO,CA0IvD"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/montgomery.js b/node_modules/@noble/curves/abstract/montgomery.js new file mode 100644 index 0000000..b43e43b --- /dev/null +++ b/node_modules/@noble/curves/abstract/montgomery.js @@ -0,0 +1,161 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.montgomery = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const modular_js_1 = require("./modular.js"); +const utils_js_1 = require("./utils.js"); +const _0n = BigInt(0); +const _1n = BigInt(1); +function validateOpts(curve) { + (0, utils_js_1.validateObject)(curve, { + a: 'bigint', + }, { + montgomeryBits: 'isSafeInteger', + nByteLength: 'isSafeInteger', + adjustScalarBytes: 'function', + domain: 'function', + powPminus2: 'function', + Gu: 'bigint', + }); + // Set defaults + return Object.freeze({ ...curve }); +} +// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748) +// Uses only one coordinate instead of two +function montgomery(curveDef) { + const CURVE = validateOpts(curveDef); + const { P } = CURVE; + const modP = (n) => (0, modular_js_1.mod)(n, P); + const montgomeryBits = CURVE.montgomeryBits; + const montgomeryBytes = Math.ceil(montgomeryBits / 8); + const fieldLen = CURVE.nByteLength; + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); + const powPminus2 = CURVE.powPminus2 || ((x) => (0, modular_js_1.pow)(x, P - BigInt(2), P)); + // cswap from RFC7748. But it is not from RFC7748! + /* + cswap(swap, x_2, x_3): + dummy = mask(swap) AND (x_2 XOR x_3) + x_2 = x_2 XOR dummy + x_3 = x_3 XOR dummy + Return (x_2, x_3) + Where mask(swap) is the all-1 or all-0 word of the same length as x_2 + and x_3, computed, e.g., as mask(swap) = 0 - swap. + */ + function cswap(swap, x_2, x_3) { + const dummy = modP(swap * (x_2 - x_3)); + x_2 = modP(x_2 - dummy); + x_3 = modP(x_3 + dummy); + return [x_2, x_3]; + } + // Accepts 0 as well + function assertFieldElement(n) { + if (typeof n === 'bigint' && _0n <= n && n < P) + return n; + throw new Error('Expected valid scalar 0 < scalar < CURVE.P'); + } + // x25519 from 4 + // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 + const a24 = (CURVE.a - BigInt(2)) / BigInt(4); + /** + * + * @param pointU u coordinate (x) on Montgomery Curve 25519 + * @param scalar by which the point would be multiplied + * @returns new Point on Montgomery curve + */ + function montgomeryLadder(pointU, scalar) { + const u = assertFieldElement(pointU); + // Section 5: Implementations MUST accept non-canonical values and process them as + // if they had been reduced modulo the field prime. + const k = assertFieldElement(scalar); + const x_1 = u; + let x_2 = _1n; + let z_2 = _0n; + let x_3 = u; + let z_3 = _1n; + let swap = _0n; + let sw; + for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) { + const k_t = (k >> t) & _1n; + swap ^= k_t; + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + swap = k_t; + const A = x_2 + z_2; + const AA = modP(A * A); + const B = x_2 - z_2; + const BB = modP(B * B); + const E = AA - BB; + const C = x_3 + z_3; + const D = x_3 - z_3; + const DA = modP(D * A); + const CB = modP(C * B); + const dacb = DA + CB; + const da_cb = DA - CB; + x_3 = modP(dacb * dacb); + z_3 = modP(x_1 * modP(da_cb * da_cb)); + x_2 = modP(AA * BB); + z_2 = modP(E * (AA + modP(a24 * E))); + } + // (x_2, x_3) = cswap(swap, x_2, x_3) + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + // (z_2, z_3) = cswap(swap, z_2, z_3) + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + // z_2^(p - 2) + const z2 = powPminus2(z_2); + // Return x_2 * (z_2^(p - 2)) + return modP(x_2 * z2); + } + function encodeUCoordinate(u) { + return (0, utils_js_1.numberToBytesLE)(modP(u), montgomeryBytes); + } + function decodeUCoordinate(uEnc) { + // Section 5: When receiving such an array, implementations of X25519 + // MUST mask the most significant bit in the final byte. + // This is very ugly way, but it works because fieldLen-1 is outside of bounds for X448, so this becomes NOOP + // fieldLen - scalaryBytes = 1 for X448 and = 0 for X25519 + const u = (0, utils_js_1.ensureBytes)('u coordinate', uEnc, montgomeryBytes); + // u[fieldLen-1] crashes QuickJS (TypeError: out-of-bound numeric index) + if (fieldLen === montgomeryBytes) + u[fieldLen - 1] &= 127; // 0b0111_1111 + return (0, utils_js_1.bytesToNumberLE)(u); + } + function decodeScalar(n) { + const bytes = (0, utils_js_1.ensureBytes)('scalar', n); + if (bytes.length !== montgomeryBytes && bytes.length !== fieldLen) + throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${bytes.length}`); + return (0, utils_js_1.bytesToNumberLE)(adjustScalarBytes(bytes)); + } + function scalarMult(scalar, u) { + const pointU = decodeUCoordinate(u); + const _scalar = decodeScalar(scalar); + const pu = montgomeryLadder(pointU, _scalar); + // The result was not contributory + // https://cr.yp.to/ecdh.html#validate + if (pu === _0n) + throw new Error('Invalid private or public key received'); + return encodeUCoordinate(pu); + } + // Computes public key from private. By doing scalar multiplication of base point. + const GuBytes = encodeUCoordinate(CURVE.Gu); + function scalarMultBase(scalar) { + return scalarMult(scalar, GuBytes); + } + return { + scalarMult, + scalarMultBase, + getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey), + getPublicKey: (privateKey) => scalarMultBase(privateKey), + utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) }, + GuBytes: GuBytes, + }; +} +exports.montgomery = montgomery; +//# sourceMappingURL=montgomery.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/montgomery.js.map b/node_modules/@noble/curves/abstract/montgomery.js.map new file mode 100644 index 0000000..1aa0c9e --- /dev/null +++ b/node_modules/@noble/curves/abstract/montgomery.js.map @@ -0,0 +1 @@ +{"version":3,"file":"montgomery.js","sourceRoot":"","sources":["../src/abstract/montgomery.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,6CAAwC;AACxC,yCAA2F;AAE3F,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAwBtB,SAAS,YAAY,CAAC,KAAgB;IACpC,IAAA,yBAAc,EACZ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AI,KAAK,CAAC,YAAY,eAAe,OAAO,QAAQ,eAAe,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;QAC3F,OAAO,IAAA,0BAAe,EAAC,iBAAiB,CAAC,KAAK,CAAC,CAAC,CAAC;IACnD,CAAC;IACD,SAAS,UAAU,CAAC,MAAW,EAAE,CAAM;QACrC,MAAM,MAAM,GAAG,iBAAiB,CAAC,CAAC,CAAC,CAAC;QACpC,MAAM,OAAO,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC;QACrC,MAAM,EAAE,GAAG,gBAAgB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAC7C,kCAAkC;QAClC,sCAAsC;QACtC,IAAI,EAAE,KAAK,GAAG;YAAE,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;QAC1E,OAAO,iBAAiB,CAAC,EAAE,CAAC,CAAC;IAC/B,CAAC;IACD,kFAAkF;IAClF,MAAM,OAAO,GAAG,iBAAiB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAC5C,SAAS,cAAc,CAAC,MAAW;QACjC,OAAO,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrC,CAAC;IAED,OAAO;QACL,UAAU;QACV,cAAc;QACd,eAAe,EAAE,CAAC,UAAe,EAAE,SAAc,EAAE,EAAE,CAAC,UAAU,CAAC,UAAU,EAAE,SAAS,CAAC;QACvF,YAAY,EAAE,CAAC,UAAe,EAAc,EAAE,CAAC,cAAc,CAAC,UAAU,CAAC;QACzE,KAAK,EAAE,EAAE,gBAAgB,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,WAAY,CAAC,KAAK,CAAC,WAAW,CAAC,EAAE;QACxE,OAAO,EAAE,OAAO;KACjB,CAAC;AACJ,CAAC;AA1ID,gCA0IC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/poseidon.d.ts b/node_modules/@noble/curves/abstract/poseidon.d.ts new file mode 100644 index 0000000..2f9ab81 --- /dev/null +++ b/node_modules/@noble/curves/abstract/poseidon.d.ts @@ -0,0 +1,30 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { IField } from './modular.js'; +export type PoseidonOpts = { + Fp: IField; + t: number; + roundsFull: number; + roundsPartial: number; + sboxPower?: number; + reversePartialPowIdx?: boolean; + mds: bigint[][]; + roundConstants: bigint[][]; +}; +export declare function validateOpts(opts: PoseidonOpts): Readonly<{ + rounds: number; + sboxFn: (n: bigint) => bigint; + roundConstants: bigint[][]; + mds: bigint[][]; + Fp: IField; + t: number; + roundsFull: number; + roundsPartial: number; + sboxPower?: number | undefined; + reversePartialPowIdx?: boolean | undefined; +}>; +export declare function splitConstants(rc: bigint[], t: number): bigint[][]; +export declare function poseidon(opts: PoseidonOpts): { + (values: bigint[]): bigint[]; + roundConstants: bigint[][]; +}; +//# sourceMappingURL=poseidon.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/poseidon.d.ts.map b/node_modules/@noble/curves/abstract/poseidon.d.ts.map new file mode 100644 index 0000000..8c0593d --- /dev/null +++ b/node_modules/@noble/curves/abstract/poseidon.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"poseidon.d.ts","sourceRoot":"","sources":["../src/abstract/poseidon.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,OAAO,EAAE,MAAM,EAAwB,MAAM,cAAc,CAAC;AAG5D,MAAM,MAAM,YAAY,GAAG;IACzB,EAAE,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;IACnB,CAAC,EAAE,MAAM,CAAC;IACV,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,GAAG,EAAE,MAAM,EAAE,EAAE,CAAC;IAChB,cAAc,EAAE,MAAM,EAAE,EAAE,CAAC;CAC5B,CAAC;AAEF,wBAAgB,YAAY,CAAC,IAAI,EAAE,YAAY;;gBA0C5B,MAAM;;;;;;;;;GAMxB;AAED,wBAAgB,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,cAarD;AAED,wBAAgB,QAAQ,CAAC,IAAI,EAAE,YAAY;aAcU,MAAM,EAAE;;EAsB5D"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/poseidon.js b/node_modules/@noble/curves/abstract/poseidon.js new file mode 100644 index 0000000..c10f971 --- /dev/null +++ b/node_modules/@noble/curves/abstract/poseidon.js @@ -0,0 +1,114 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.poseidon = exports.splitConstants = exports.validateOpts = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Poseidon Hash: https://eprint.iacr.org/2019/458.pdf, https://www.poseidon-hash.info +const modular_js_1 = require("./modular.js"); +function validateOpts(opts) { + const { Fp, mds, reversePartialPowIdx: rev, roundConstants: rc } = opts; + const { roundsFull, roundsPartial, sboxPower, t } = opts; + (0, modular_js_1.validateField)(Fp); + for (const i of ['t', 'roundsFull', 'roundsPartial']) { + if (typeof opts[i] !== 'number' || !Number.isSafeInteger(opts[i])) + throw new Error(`Poseidon: invalid param ${i}=${opts[i]} (${typeof opts[i]})`); + } + // MDS is TxT matrix + if (!Array.isArray(mds) || mds.length !== t) + throw new Error('Poseidon: wrong MDS matrix'); + const _mds = mds.map((mdsRow) => { + if (!Array.isArray(mdsRow) || mdsRow.length !== t) + throw new Error(`Poseidon MDS matrix row: ${mdsRow}`); + return mdsRow.map((i) => { + if (typeof i !== 'bigint') + throw new Error(`Poseidon MDS matrix value=${i}`); + return Fp.create(i); + }); + }); + if (rev !== undefined && typeof rev !== 'boolean') + throw new Error(`Poseidon: invalid param reversePartialPowIdx=${rev}`); + if (roundsFull % 2 !== 0) + throw new Error(`Poseidon roundsFull is not even: ${roundsFull}`); + const rounds = roundsFull + roundsPartial; + if (!Array.isArray(rc) || rc.length !== rounds) + throw new Error('Poseidon: wrong round constants'); + const roundConstants = rc.map((rc) => { + if (!Array.isArray(rc) || rc.length !== t) + throw new Error(`Poseidon wrong round constants: ${rc}`); + return rc.map((i) => { + if (typeof i !== 'bigint' || !Fp.isValid(i)) + throw new Error(`Poseidon wrong round constant=${i}`); + return Fp.create(i); + }); + }); + if (!sboxPower || ![3, 5, 7].includes(sboxPower)) + throw new Error(`Poseidon wrong sboxPower=${sboxPower}`); + const _sboxPower = BigInt(sboxPower); + let sboxFn = (n) => (0, modular_js_1.FpPow)(Fp, n, _sboxPower); + // Unwrapped sbox power for common cases (195->142μs) + if (sboxPower === 3) + sboxFn = (n) => Fp.mul(Fp.sqrN(n), n); + else if (sboxPower === 5) + sboxFn = (n) => Fp.mul(Fp.sqrN(Fp.sqrN(n)), n); + return Object.freeze({ ...opts, rounds, sboxFn, roundConstants, mds: _mds }); +} +exports.validateOpts = validateOpts; +function splitConstants(rc, t) { + if (typeof t !== 'number') + throw new Error('poseidonSplitConstants: wrong t'); + if (!Array.isArray(rc) || rc.length % t) + throw new Error('poseidonSplitConstants: wrong rc'); + const res = []; + let tmp = []; + for (let i = 0; i < rc.length; i++) { + tmp.push(rc[i]); + if (tmp.length === t) { + res.push(tmp); + tmp = []; + } + } + return res; +} +exports.splitConstants = splitConstants; +function poseidon(opts) { + const _opts = validateOpts(opts); + const { Fp, mds, roundConstants, rounds, roundsPartial, sboxFn, t } = _opts; + const halfRoundsFull = _opts.roundsFull / 2; + const partialIdx = _opts.reversePartialPowIdx ? t - 1 : 0; + const poseidonRound = (values, isFull, idx) => { + values = values.map((i, j) => Fp.add(i, roundConstants[idx][j])); + if (isFull) + values = values.map((i) => sboxFn(i)); + else + values[partialIdx] = sboxFn(values[partialIdx]); + // Matrix multiplication + values = mds.map((i) => i.reduce((acc, i, j) => Fp.add(acc, Fp.mulN(i, values[j])), Fp.ZERO)); + return values; + }; + const poseidonHash = function poseidonHash(values) { + if (!Array.isArray(values) || values.length !== t) + throw new Error(`Poseidon: wrong values (expected array of bigints with length ${t})`); + values = values.map((i) => { + if (typeof i !== 'bigint') + throw new Error(`Poseidon: wrong value=${i} (${typeof i})`); + return Fp.create(i); + }); + let round = 0; + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) + values = poseidonRound(values, true, round++); + // Apply r_p partial rounds. + for (let i = 0; i < roundsPartial; i++) + values = poseidonRound(values, false, round++); + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) + values = poseidonRound(values, true, round++); + if (round !== rounds) + throw new Error(`Poseidon: wrong number of rounds: last round=${round}, total=${rounds}`); + return values; + }; + // For verification in tests + poseidonHash.roundConstants = roundConstants; + return poseidonHash; +} +exports.poseidon = poseidon; +//# sourceMappingURL=poseidon.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/poseidon.js.map b/node_modules/@noble/curves/abstract/poseidon.js.map new file mode 100644 index 0000000..923cc06 --- /dev/null +++ b/node_modules/@noble/curves/abstract/poseidon.js.map @@ -0,0 +1 @@ +{"version":3,"file":"poseidon.js","sourceRoot":"","sources":["../src/abstract/poseidon.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,sFAAsF;AACtF,6CAA4D;AAc5D,SAAgB,YAAY,CAAC,IAAkB;IAC7C,MAAM,EAAE,EAAE,EAAE,GAAG,EAAE,oBAAoB,EAAE,GAAG,EAAE,cAAc,EAAE,EAAE,EAAE,GAAG,IAAI,CAAC;IACxE,MAAM,EAAE,UAAU,EAAE,aAAa,EAAE,SAAS,EAAE,CAAC,EAAE,GAAG,IAAI,CAAC;IAEzD,IAAA,0BAAa,EAAC,EAAE,CAAC,CAAC;IAClB,KAAK,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,YAAY,EAAE,eAAe,CAAU,EAAE;QAC7D,IAAI,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAC/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AC,CAAC,CAAC,CAAC;QACtB,CAAC,CAAC,CAAC;QACH,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,2BAA2B;QAC3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,cAAc,EAAE,CAAC,EAAE;YAAE,MAAM,GAAG,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;QACvF,4BAA4B;QAC5B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,aAAa,EAAE,CAAC,EAAE;YAAE,MAAM,GAAG,aAAa,CAAC,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;QACvF,2BAA2B;QAC3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,cAAc,EAAE,CAAC,EAAE;YAAE,MAAM,GAAG,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;QAEvF,IAAI,KAAK,KAAK,MAAM;YAClB,MAAM,IAAI,KAAK,CAAC,gDAAgD,KAAK,WAAW,MAAM,EAAE,CAAC,CAAC;QAC5F,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IACF,4BAA4B;IAC5B,YAAY,CAAC,cAAc,GAAG,cAAc,CAAC;IAC7C,OAAO,YAAY,CAAC;AACtB,CAAC;AApCD,4BAoCC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/utils.d.ts b/node_modules/@noble/curves/abstract/utils.d.ts new file mode 100644 index 0000000..f3fa253 --- /dev/null +++ b/node_modules/@noble/curves/abstract/utils.d.ts @@ -0,0 +1,92 @@ +export type Hex = Uint8Array | string; +export type PrivKey = Hex | bigint; +export type CHash = { + (message: Uint8Array | string): Uint8Array; + blockLen: number; + outputLen: number; + create(opts?: { + dkLen?: number; + }): any; +}; +export type FHash = (message: Uint8Array | string) => Uint8Array; +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export declare function bytesToHex(bytes: Uint8Array): string; +export declare function numberToHexUnpadded(num: number | bigint): string; +export declare function hexToNumber(hex: string): bigint; +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export declare function hexToBytes(hex: string): Uint8Array; +export declare function bytesToNumberBE(bytes: Uint8Array): bigint; +export declare function bytesToNumberLE(bytes: Uint8Array): bigint; +export declare function numberToBytesBE(n: number | bigint, len: number): Uint8Array; +export declare function numberToBytesLE(n: number | bigint, len: number): Uint8Array; +export declare function numberToVarBytesBE(n: number | bigint): Uint8Array; +/** + * Takes hex string or Uint8Array, converts to Uint8Array. + * Validates output length. + * Will throw error for other types. + * @param title descriptive title for an error e.g. 'private key' + * @param hex hex string or Uint8Array + * @param expectedLength optional, will compare to result array's length + * @returns + */ +export declare function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array; +/** + * Copies several Uint8Arrays into one. + */ +export declare function concatBytes(...arrays: Uint8Array[]): Uint8Array; +export declare function equalBytes(b1: Uint8Array, b2: Uint8Array): boolean; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export declare function utf8ToBytes(str: string): Uint8Array; +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + */ +export declare function bitLen(n: bigint): number; +/** + * Gets single bit at position. + * NOTE: first bit position is 0 (same as arrays) + * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` + */ +export declare function bitGet(n: bigint, pos: number): bigint; +/** + * Sets single bit at position. + */ +export declare const bitSet: (n: bigint, pos: number, value: boolean) => bigint; +/** + * Calculate mask for N bits. Not using ** operator with bigints because of old engines. + * Same as BigInt(`0b${Array(i).fill('1').join('')}`) + */ +export declare const bitMask: (n: number) => bigint; +type Pred = (v: Uint8Array) => T | undefined; +/** + * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + * @returns function that will call DRBG until 2nd arg returns something meaningful + * @example + * const drbg = createHmacDRBG(32, 32, hmac); + * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined + */ +export declare function createHmacDrbg(hashLen: number, qByteLen: number, hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array): (seed: Uint8Array, predicate: Pred) => T; +declare const validatorFns: { + readonly bigint: (val: any) => boolean; + readonly function: (val: any) => boolean; + readonly boolean: (val: any) => boolean; + readonly string: (val: any) => boolean; + readonly stringOrUint8Array: (val: any) => boolean; + readonly isSafeInteger: (val: any) => boolean; + readonly array: (val: any) => boolean; + readonly field: (val: any, object: any) => any; + readonly hash: (val: any) => boolean; +}; +type Validator = keyof typeof validatorFns; +type ValMap> = { + [K in keyof T]?: Validator; +}; +export declare function validateObject>(object: T, validators: ValMap, optValidators?: ValMap): T; +export {}; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/utils.d.ts.map b/node_modules/@noble/curves/abstract/utils.d.ts.map new file mode 100644 index 0000000..bc747ed --- /dev/null +++ b/node_modules/@noble/curves/abstract/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/abstract/utils.ts"],"names":[],"mappings":"AASA,MAAM,MAAM,GAAG,GAAG,UAAU,GAAG,MAAM,CAAC;AACtC,MAAM,MAAM,OAAO,GAAG,GAAG,GAAG,MAAM,CAAC;AACnC,MAAM,MAAM,KAAK,GAAG;IAClB,CAAC,OAAO,EAAE,UAAU,GAAG,MAAM,GAAG,UAAU,CAAC;IAC3C,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,IAAI,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,GAAG,CAAC;CACxC,CAAC;AACF,MAAM,MAAM,KAAK,GAAG,CAAC,OAAO,EAAE,UAAU,GAAG,MAAM,KAAK,UAAU,CAAC;AAKjE;;GAEG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,UAA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,WAE5D,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,OAAO,MAAO,MAAM,WAAiC,CAAC;AAMnE,KAAK,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,UAAU,KAAK,CAAC,GAAG,SAAS,CAAC;AAChD;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,CAAC,EAC9B,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,QAAQ,EAAE,UAAU,EAAE,KAAK,UAAU,GACjE,CAAC,IAAI,EAAE,UAAU,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CA4C7C;AAID,QAAA,MAAM,YAAY;2BACF,GAAG;6BACD,GAAG;4BACJ,GAAG;2BACJ,GAAG;uCACS,GAAG;kCACR,GAAG;0BACX,GAAG;0BACH,GAAG,UAAU,GAAG;yBACjB,GAAG;CACP,CAAC;AACX,KAAK,SAAS,GAAG,MAAM,OAAO,YAAY,CAAC;AAC3C,KAAK,MAAM,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI;KAAG,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,EAAE,SAAS;CAAE,CAAC;AAG5E,wBAAgB,cAAc,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAC1D,MAAM,EAAE,CAAC,EACT,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC,EACrB,aAAa,GAAE,MAAM,CAAC,CAAC,CAAM,KAkB9B"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/utils.js b/node_modules/@noble/curves/abstract/utils.js new file mode 100644 index 0000000..8a801ba --- /dev/null +++ b/node_modules/@noble/curves/abstract/utils.js @@ -0,0 +1,288 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateObject = exports.createHmacDrbg = exports.bitMask = exports.bitSet = exports.bitGet = exports.bitLen = exports.utf8ToBytes = exports.equalBytes = exports.concatBytes = exports.ensureBytes = exports.numberToVarBytesBE = exports.numberToBytesLE = exports.numberToBytesBE = exports.bytesToNumberLE = exports.bytesToNumberBE = exports.hexToBytes = exports.hexToNumber = exports.numberToHexUnpadded = exports.bytesToHex = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// 100 lines of code in the file are duplicated from noble-hashes (utils). +// This is OK: `abstract` directory does not use noble-hashes. +// User may opt-in into using different hashing library. This way, noble-hashes +// won't be included into their bundle. +const _0n = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +const u8a = (a) => a instanceof Uint8Array; +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +function bytesToHex(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +exports.bytesToHex = bytesToHex; +function numberToHexUnpadded(num) { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; +} +exports.numberToHexUnpadded = numberToHexUnpadded; +function hexToNumber(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + // Big Endian + return BigInt(hex === '' ? '0' : `0x${hex}`); +} +exports.hexToNumber = hexToNumber; +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} +exports.hexToBytes = hexToBytes; +// BE: Big Endian, LE: Little Endian +function bytesToNumberBE(bytes) { + return hexToNumber(bytesToHex(bytes)); +} +exports.bytesToNumberBE = bytesToNumberBE; +function bytesToNumberLE(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); +} +exports.bytesToNumberLE = bytesToNumberLE; +function numberToBytesBE(n, len) { + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} +exports.numberToBytesBE = numberToBytesBE; +function numberToBytesLE(n, len) { + return numberToBytesBE(n, len).reverse(); +} +exports.numberToBytesLE = numberToBytesLE; +// Unpadded, rarely used +function numberToVarBytesBE(n) { + return hexToBytes(numberToHexUnpadded(n)); +} +exports.numberToVarBytesBE = numberToVarBytesBE; +/** + * Takes hex string or Uint8Array, converts to Uint8Array. + * Validates output length. + * Will throw error for other types. + * @param title descriptive title for an error e.g. 'private key' + * @param hex hex string or Uint8Array + * @param expectedLength optional, will compare to result array's length + * @returns + */ +function ensureBytes(title, hex, expectedLength) { + let res; + if (typeof hex === 'string') { + try { + res = hexToBytes(hex); + } + catch (e) { + throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`); + } + } + else if (u8a(hex)) { + // Uint8Array.from() instead of hash.slice() because node.js Buffer + // is instance of Uint8Array, and its slice() creates **mutable** copy + res = Uint8Array.from(hex); + } + else { + throw new Error(`${title} must be hex string or Uint8Array`); + } + const len = res.length; + if (typeof expectedLength === 'number' && len !== expectedLength) + throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); + return res; +} +exports.ensureBytes = ensureBytes; +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) + throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} +exports.concatBytes = concatBytes; +function equalBytes(b1, b2) { + // We don't care about timing attacks here + if (b1.length !== b2.length) + return false; + for (let i = 0; i < b1.length; i++) + if (b1[i] !== b2[i]) + return false; + return true; +} +exports.equalBytes = equalBytes; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +exports.utf8ToBytes = utf8ToBytes; +// Bit operations +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + */ +function bitLen(n) { + let len; + for (len = 0; n > _0n; n >>= _1n, len += 1) + ; + return len; +} +exports.bitLen = bitLen; +/** + * Gets single bit at position. + * NOTE: first bit position is 0 (same as arrays) + * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` + */ +function bitGet(n, pos) { + return (n >> BigInt(pos)) & _1n; +} +exports.bitGet = bitGet; +/** + * Sets single bit at position. + */ +const bitSet = (n, pos, value) => { + return n | ((value ? _1n : _0n) << BigInt(pos)); +}; +exports.bitSet = bitSet; +/** + * Calculate mask for N bits. Not using ** operator with bigints because of old engines. + * Same as BigInt(`0b${Array(i).fill('1').join('')}`) + */ +const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n; +exports.bitMask = bitMask; +// DRBG +const u8n = (data) => new Uint8Array(data); // creates Uint8Array +const u8fr = (arr) => Uint8Array.from(arr); // another shortcut +/** + * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + * @returns function that will call DRBG until 2nd arg returns something meaningful + * @example + * const drbg = createHmacDRBG(32, 32, hmac); + * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined + */ +function createHmacDrbg(hashLen, qByteLen, hmacFn) { + if (typeof hashLen !== 'number' || hashLen < 2) + throw new Error('hashLen must be a number'); + if (typeof qByteLen !== 'number' || qByteLen < 2) + throw new Error('qByteLen must be a number'); + if (typeof hmacFn !== 'function') + throw new Error('hmacFn must be a function'); + // Step B, Step C: set hashLen to 8*ceil(hlen/8) + let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same + let i = 0; // Iterations counter, will throw when over 1000 + const reset = () => { + v.fill(1); + k.fill(0); + i = 0; + }; + const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values) + const reseed = (seed = u8n()) => { + // HMAC-DRBG reseed() function. Steps D-G + k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed) + v = h(); // v = hmac(k || v) + if (seed.length === 0) + return; + k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed) + v = h(); // v = hmac(k || v) + }; + const gen = () => { + // HMAC-DRBG generate() function + if (i++ >= 1000) + throw new Error('drbg: tried 1000 values'); + let len = 0; + const out = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes(...out); + }; + const genUntil = (seed, pred) => { + reset(); + reseed(seed); // Steps D-G + let res = undefined; // Step H: grind until k is in [1..n-1] + while (!(res = pred(gen()))) + reseed(); + reset(); + return res; + }; + return genUntil; +} +exports.createHmacDrbg = createHmacDrbg; +// Validating curves and fields +const validatorFns = { + bigint: (val) => typeof val === 'bigint', + function: (val) => typeof val === 'function', + boolean: (val) => typeof val === 'boolean', + string: (val) => typeof val === 'string', + stringOrUint8Array: (val) => typeof val === 'string' || val instanceof Uint8Array, + isSafeInteger: (val) => Number.isSafeInteger(val), + array: (val) => Array.isArray(val), + field: (val, object) => object.Fp.isValid(val), + hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen), +}; +// type Record = { [P in K]: T; } +function validateObject(object, validators, optValidators = {}) { + const checkField = (fieldName, type, isOptional) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== 'function') + throw new Error(`Invalid validator "${type}", expected function`); + const val = object[fieldName]; + if (isOptional && val === undefined) + return; + if (!checkVal(val, object)) { + throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); + } + }; + for (const [fieldName, type] of Object.entries(validators)) + checkField(fieldName, type, false); + for (const [fieldName, type] of Object.entries(optValidators)) + checkField(fieldName, type, true); + return object; +} +exports.validateObject = validateObject; +// validate type tests +// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 }; +// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok! +// // Should fail type-check +// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' }); +// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' }); +// const z3 = validateObject(o, { test: 'boolean', z: 'bug' }); +// const z4 = validateObject(o, { a: 'boolean', z: 'bug' }); +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/utils.js.map b/node_modules/@noble/curves/abstract/utils.js.map new file mode 100644 index 0000000..56f36c8 --- /dev/null +++ b/node_modules/@noble/curves/abstract/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/abstract/utils.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,0EAA0E;AAC1E,8DAA8D;AAC9D,+EAA+E;AAC/E,uCAAuC;AACvC,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,CAAC,CAAM,EAAmB,EAAE,CAAC,CAAC,YAAY,UAAU,CAAC;AAWjE,MAAM,KAAK,GAAG,eAAe,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CACjE,CAAC,CAAC,QAAQ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AAO,CAAC,aAAa,CAAC;QAAE,UAAU,CAAC,SAAS,EAAE,IAAK,EAAE,IAAI,CAAC,CAAC;IAClG,OAAO,MAAM,CAAC;AAChB,CAAC;AArBD,wCAqBC;AACD,sBAAsB;AACtB,uEAAuE;AACvE,gFAAgF;AAChF,4BAA4B;AAC5B,2DAA2D;AAC3D,qEAAqE;AACrE,+DAA+D;AAC/D,4DAA4D"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/weierstrass.d.ts b/node_modules/@noble/curves/abstract/weierstrass.d.ts new file mode 100644 index 0000000..9de89e2 --- /dev/null +++ b/node_modules/@noble/curves/abstract/weierstrass.d.ts @@ -0,0 +1,241 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import * as mod from './modular.js'; +import * as ut from './utils.js'; +import { CHash, Hex, PrivKey } from './utils.js'; +import { Group, GroupConstructor, BasicCurve, AffinePoint } from './curve.js'; +export type { AffinePoint }; +type HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; +type EndomorphismOpts = { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; +}; +export type BasicWCurve = BasicCurve & { + a: T; + b: T; + allowedPrivateKeyLengths?: readonly number[]; + wrapPrivateKey?: boolean; + endo?: EndomorphismOpts; + isTorsionFree?: (c: ProjConstructor, point: ProjPointType) => boolean; + clearCofactor?: (c: ProjConstructor, point: ProjPointType) => ProjPointType; +}; +type Entropy = Hex | true; +export type SignOpts = { + lowS?: boolean; + extraEntropy?: Entropy; + prehash?: boolean; +}; +export type VerOpts = { + lowS?: boolean; + prehash?: boolean; +}; +/** + * ### Design rationale for types + * + * * Interaction between classes from different curves should fail: + * `k256.Point.BASE.add(p256.Point.BASE)` + * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime + * * Different calls of `curve()` would return different classes - + * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve, + * it won't affect others + * + * TypeScript can't infer types for classes created inside a function. Classes is one instance of nominative types in TypeScript and interfaces only check for shape, so it's hard to create unique type for every function call. + * + * We can use generic types via some param, like curve opts, but that would: + * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params) + * which is hard to debug. + * 2. Params can be generic and we can't enforce them to be constant value: + * if somebody creates curve from non-constant params, + * it would be allowed to interact with other curves with non-constant params + * + * TODO: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol + */ +export interface ProjPointType extends Group> { + readonly px: T; + readonly py: T; + readonly pz: T; + get x(): T; + get y(): T; + multiply(scalar: bigint): ProjPointType; + toAffine(iz?: T): AffinePoint; + isTorsionFree(): boolean; + clearCofactor(): ProjPointType; + assertValidity(): void; + hasEvenY(): boolean; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; + multiplyUnsafe(scalar: bigint): ProjPointType; + multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined; + _setWindowSize(windowSize: number): void; +} +export interface ProjConstructor extends GroupConstructor> { + new (x: T, y: T, z: T): ProjPointType; + fromAffine(p: AffinePoint): ProjPointType; + fromHex(hex: Hex): ProjPointType; + fromPrivateKey(privateKey: PrivKey): ProjPointType; + normalizeZ(points: ProjPointType[]): ProjPointType[]; +} +export type CurvePointsType = BasicWCurve & { + fromBytes?: (bytes: Uint8Array) => AffinePoint; + toBytes?: (c: ProjConstructor, point: ProjPointType, isCompressed: boolean) => Uint8Array; +}; +export type CurvePointsRes = { + ProjectivePoint: ProjConstructor; + normPrivateKeyToScalar: (key: PrivKey) => bigint; + weierstrassEquation: (x: T) => T; + isWithinCurveOrder: (num: bigint) => boolean; +}; +export declare const DER: { + Err: { + new (m?: string): { + name: string; + message: string; + stack?: string | undefined; + }; + }; + _parseInt(data: Uint8Array): { + d: bigint; + l: Uint8Array; + }; + toSig(hex: string | Uint8Array): { + r: bigint; + s: bigint; + }; + hexFromSig(sig: { + r: bigint; + s: bigint; + }): string; +}; +export declare function weierstrassPoints(opts: CurvePointsType): { + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: mod.IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: T; + readonly Gy: T; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: T; + readonly b: T; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: EndomorphismOpts | undefined; + readonly isTorsionFree?: ((c: ProjConstructor, point: ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: ProjConstructor, point: ProjPointType) => ProjPointType) | undefined; + readonly fromBytes?: ((bytes: Uint8Array) => AffinePoint) | undefined; + readonly toBytes?: ((c: ProjConstructor, point: ProjPointType, isCompressed: boolean) => Uint8Array) | undefined; + readonly p: bigint; + }>; + ProjectivePoint: ProjConstructor; + normPrivateKeyToScalar: (key: PrivKey) => bigint; + weierstrassEquation: (x: T) => T; + isWithinCurveOrder: (num: bigint) => boolean; +}; +export interface SignatureType { + readonly r: bigint; + readonly s: bigint; + readonly recovery?: number; + assertValidity(): void; + addRecoveryBit(recovery: number): RecoveredSignatureType; + hasHighS(): boolean; + normalizeS(): SignatureType; + recoverPublicKey(msgHash: Hex): ProjPointType; + toCompactRawBytes(): Uint8Array; + toCompactHex(): string; + toDERRawBytes(isCompressed?: boolean): Uint8Array; + toDERHex(isCompressed?: boolean): string; +} +export type RecoveredSignatureType = SignatureType & { + readonly recovery: number; +}; +export type SignatureConstructor = { + new (r: bigint, s: bigint): SignatureType; + fromCompact(hex: Hex): SignatureType; + fromDER(hex: Hex): SignatureType; +}; +type SignatureLike = { + r: bigint; + s: bigint; +}; +export type PubKey = Hex | ProjPointType; +export type CurveType = BasicWCurve & { + hash: CHash; + hmac: HmacFnSync; + randomBytes: (bytesLength?: number) => Uint8Array; + lowS?: boolean; + bits2int?: (bytes: Uint8Array) => bigint; + bits2int_modN?: (bytes: Uint8Array) => bigint; +}; +declare function validateOpts(curve: CurveType): Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: mod.IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: EndomorphismOpts | undefined; + readonly isTorsionFree?: ((c: ProjConstructor, point: ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: ProjConstructor, point: ProjPointType) => ProjPointType) | undefined; + readonly hash: ut.CHash; + readonly hmac: HmacFnSync; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; +}>; +export type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType; + verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean; + ProjectivePoint: ProjConstructor; + Signature: SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: PrivKey) => bigint; + isValidPrivateKey(privateKey: PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: ProjPointType) => ProjPointType; + }; +}; +export declare function weierstrass(curveDef: CurveType): CurveFn; +/** + * Implementation of the Shallue and van de Woestijne method for any weierstrass curve. + * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular. + * b = True and y = sqrt(u / v) if (u / v) is square in F, and + * b = False and y = sqrt(Z * (u / v)) otherwise. + * @param Fp + * @param Z + * @returns + */ +export declare function SWUFpSqrtRatio(Fp: mod.IField, Z: T): (u: T, v: T) => { + isValid: boolean; + value: T; +}; +/** + * Simplified Shallue-van de Woestijne-Ulas Method + * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2 + */ +export declare function mapToCurveSimpleSWU(Fp: mod.IField, opts: { + A: T; + B: T; + Z: T; +}): (u: T) => { + x: T; + y: T; +}; +//# sourceMappingURL=weierstrass.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/weierstrass.d.ts.map b/node_modules/@noble/curves/abstract/weierstrass.d.ts.map new file mode 100644 index 0000000..3d15e49 --- /dev/null +++ b/node_modules/@noble/curves/abstract/weierstrass.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"weierstrass.d.ts","sourceRoot":"","sources":["../src/abstract/weierstrass.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AACjC,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,EAAe,MAAM,YAAY,CAAC;AAC9D,OAAO,EAAE,KAAK,EAAE,gBAAgB,EAAQ,UAAU,EAAiB,WAAW,EAAE,MAAM,YAAY,CAAC;AAEnG,YAAY,EAAE,WAAW,EAAE,CAAC;AAC5B,KAAK,UAAU,GAAG,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,QAAQ,EAAE,UAAU,EAAE,KAAK,UAAU,CAAC;AAC7E,KAAK,gBAAgB,GAAG;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK;QAAE,KAAK,EAAE,OAAO,CAAC;QAAC,EAAE,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,OAAO,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC;CACxF,CAAC;AACF,MAAM,MAAM,WAAW,CAAC,CAAC,IAAI,UAAU,CAAC,CAAC,CAAC,GA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AC,KAAG;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,CAAC,CAAA;CAAE,CAmD7D;AACD;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,EACnC,EAAE,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EACjB,IAAI,EAAE;IACJ,CAAC,EAAE,CAAC,CAAC;IACL,CAAC,EAAE,CAAC,CAAC;IACL,CAAC,EAAE,CAAC,CAAC;CACN,OASU,CAAC;OAAQ,CAAC;OAAK,CAAC;EA8B5B"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/weierstrass.js b/node_modules/@noble/curves/abstract/weierstrass.js new file mode 100644 index 0000000..b07585b --- /dev/null +++ b/node_modules/@noble/curves/abstract/weierstrass.js @@ -0,0 +1,1063 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.mapToCurveSimpleSWU = exports.SWUFpSqrtRatio = exports.weierstrass = exports.weierstrassPoints = exports.DER = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Short Weierstrass curve. The formula is: y² = x³ + ax + b +const mod = require("./modular.js"); +const ut = require("./utils.js"); +const utils_js_1 = require("./utils.js"); +const curve_js_1 = require("./curve.js"); +function validatePointOpts(curve) { + const opts = (0, curve_js_1.validateBasic)(curve); + ut.validateObject(opts, { + a: 'field', + b: 'field', + }, { + allowedPrivateKeyLengths: 'array', + wrapPrivateKey: 'boolean', + isTorsionFree: 'function', + clearCofactor: 'function', + allowInfinityPoint: 'boolean', + fromBytes: 'function', + toBytes: 'function', + }); + const { endo, Fp, a } = opts; + if (endo) { + if (!Fp.eql(a, Fp.ZERO)) { + throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0'); + } + if (typeof endo !== 'object' || + typeof endo.beta !== 'bigint' || + typeof endo.splitScalar !== 'function') { + throw new Error('Expected endomorphism with beta: bigint and splitScalar: function'); + } + } + return Object.freeze({ ...opts }); +} +// ASN.1 DER encoding utilities +const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; +exports.DER = { + // asn.1 DER encoding utils + Err: class DERErr extends Error { + constructor(m = '') { + super(m); + } + }, + _parseInt(data) { + const { Err: E } = exports.DER; + if (data.length < 2 || data[0] !== 0x02) + throw new E('Invalid signature integer tag'); + const len = data[1]; + const res = data.subarray(2, len + 2); + if (!len || res.length !== len) + throw new E('Invalid signature integer: wrong length'); + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + if (res[0] & 0b10000000) + throw new E('Invalid signature integer: negative'); + if (res[0] === 0x00 && !(res[1] & 0b10000000)) + throw new E('Invalid signature integer: unnecessary leading zero'); + return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left + }, + toSig(hex) { + // parse DER signature + const { Err: E } = exports.DER; + const data = typeof hex === 'string' ? h2b(hex) : hex; + if (!(data instanceof Uint8Array)) + throw new Error('ui8a expected'); + let l = data.length; + if (l < 2 || data[0] != 0x30) + throw new E('Invalid signature tag'); + if (data[1] !== l - 2) + throw new E('Invalid signature: incorrect length'); + const { d: r, l: sBytes } = exports.DER._parseInt(data.subarray(2)); + const { d: s, l: rBytesLeft } = exports.DER._parseInt(sBytes); + if (rBytesLeft.length) + throw new E('Invalid signature: left bytes after parsing'); + return { r, s }; + }, + hexFromSig(sig) { + // Add leading zero if first byte has negative bit enabled. More details in '_parseInt' + const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s); + const h = (num) => { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; + }; + const s = slice(h(sig.s)); + const r = slice(h(sig.r)); + const shl = s.length / 2; + const rhl = r.length / 2; + const sl = h(shl); + const rl = h(rhl); + return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`; + }, +}; +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4); +function weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ + const toBytes = CURVE.toBytes || + ((_c, point, _isCompressed) => { + const a = point.toAffine(); + return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y)); + }); + const fromBytes = CURVE.fromBytes || + ((bytes) => { + // const head = bytes[0]; + const tail = bytes.subarray(1); + // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported'); + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + }); + /** + * y² = x³ + ax + b: Short weierstrass curve formula + * @returns y² + */ + function weierstrassEquation(x) { + const { a, b } = CURVE; + const x2 = Fp.sqr(x); // x * x + const x3 = Fp.mul(x2, x); // x2 * x + return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b + } + // Validate whether the passed curve params are valid. + // We check if curve equation works for generator point. + // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381. + // ProjectivePoint class has not been initialized yet. + if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error('bad generator point: equation left != right'); + // Valid group elements reside in range 1..n-1 + function isWithinCurveOrder(num) { + return typeof num === 'bigint' && _0n < num && num < CURVE.n; + } + function assertGE(num) { + if (!isWithinCurveOrder(num)) + throw new Error('Expected valid bigint: 0 < bigint < curve.n'); + } + // Validates if priv key is valid and converts it to bigint. + // Supports options allowedPrivateKeyLengths and wrapPrivateKey. + function normPrivateKeyToScalar(key) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE; + if (lengths && typeof key !== 'bigint') { + if (key instanceof Uint8Array) + key = ut.bytesToHex(key); + // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes + if (typeof key !== 'string' || !lengths.includes(key.length)) + throw new Error('Invalid key'); + key = key.padStart(nByteLength * 2, '0'); + } + let num; + try { + num = + typeof key === 'bigint' + ? key + : ut.bytesToNumberBE((0, utils_js_1.ensureBytes)('private key', key, nByteLength)); + } + catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + } + if (wrapPrivateKey) + num = mod.mod(num, n); // disabled by default, enabled for BLS + assertGE(num); // num in range [1..N-1] + return num; + } + const pointPrecomputes = new Map(); + function assertPrjPoint(other) { + if (!(other instanceof Point)) + throw new Error('ProjectivePoint expected'); + } + /** + * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z) + * Default Point works in 2d / affine coordinates: (x, y) + * We're doing calculations in projective, because its operations don't require costly inversion. + */ + class Point { + constructor(px, py, pz) { + this.px = px; + this.py = py; + this.pz = pz; + if (px == null || !Fp.isValid(px)) + throw new Error('x required'); + if (py == null || !Fp.isValid(py)) + throw new Error('y required'); + if (pz == null || !Fp.isValid(pz)) + throw new Error('z required'); + } + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + static fromAffine(p) { + const { x, y } = p || {}; + if (!p || !Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('invalid affine point'); + if (p instanceof Point) + throw new Error('projective point not allowed'); + const is0 = (i) => Fp.eql(i, Fp.ZERO); + // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0) + if (is0(x) && is0(y)) + return Point.ZERO; + return new Point(x, y, Fp.ONE); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + /** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + */ + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex) { + const P = Point.fromAffine(fromBytes((0, utils_js_1.ensureBytes)('pointHex', hex))); + P.assertValidity(); + return P; + } + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey) { + return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + // A point on curve is valid if it conforms to equation. + assertValidity() { + if (this.is0()) { + // (0, 1, 0) aka ZERO is invalid in most contexts. + // In BLS, ZERO can be serialized, so we allow it. + // (0, 0, 0) is wrong representation of ZERO and is always invalid. + if (CURVE.allowInfinityPoint && !Fp.is0(this.py)) + return; + throw new Error('bad point: ZERO'); + } + // Some 3rd-party test vectors require different wording between here & `fromCompressedHex` + const { x, y } = this.toAffine(); + // Check if x, y are valid field elements + if (!Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('bad point: x or y not FE'); + const left = Fp.sqr(y); // y² + const right = weierstrassEquation(x); // x³ + ax + b + if (!Fp.eql(left, right)) + throw new Error('bad point: equation left != right'); + if (!this.isTorsionFree()) + throw new Error('bad point: not in prime-order subgroup'); + } + hasEvenY() { + const { y } = this.toAffine(); + if (Fp.isOdd) + return !Fp.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + /** + * Compare one point to another. + */ + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); + const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); + return U1 && U2; + } + /** + * Flips point to one corresponding to (x, -y) in Affine coordinates. + */ + negate() { + return new Point(this.px, Fp.neg(this.py), this.pz); + } + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a, b } = CURVE; + const b3 = Fp.mul(b, _3n); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + let t0 = Fp.mul(X1, X1); // step 1 + let t1 = Fp.mul(Y1, Y1); + let t2 = Fp.mul(Z1, Z1); + let t3 = Fp.mul(X1, Y1); + t3 = Fp.add(t3, t3); // step 5 + Z3 = Fp.mul(X1, Z1); + Z3 = Fp.add(Z3, Z3); + X3 = Fp.mul(a, Z3); + Y3 = Fp.mul(b3, t2); + Y3 = Fp.add(X3, Y3); // step 10 + X3 = Fp.sub(t1, Y3); + Y3 = Fp.add(t1, Y3); + Y3 = Fp.mul(X3, Y3); + X3 = Fp.mul(t3, X3); + Z3 = Fp.mul(b3, Z3); // step 15 + t2 = Fp.mul(a, t2); + t3 = Fp.sub(t0, t2); + t3 = Fp.mul(a, t3); + t3 = Fp.add(t3, Z3); + Z3 = Fp.add(t0, t0); // step 20 + t0 = Fp.add(Z3, t0); + t0 = Fp.add(t0, t2); + t0 = Fp.mul(t0, t3); + Y3 = Fp.add(Y3, t0); + t2 = Fp.mul(Y1, Z1); // step 25 + t2 = Fp.add(t2, t2); + t0 = Fp.mul(t2, t3); + X3 = Fp.sub(X3, t0); + Z3 = Fp.mul(t2, t1); + Z3 = Fp.add(Z3, Z3); // step 30 + Z3 = Fp.add(Z3, Z3); + return new Point(X3, Y3, Z3); + } + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + const a = CURVE.a; + const b3 = Fp.mul(CURVE.b, _3n); + let t0 = Fp.mul(X1, X2); // step 1 + let t1 = Fp.mul(Y1, Y2); + let t2 = Fp.mul(Z1, Z2); + let t3 = Fp.add(X1, Y1); + let t4 = Fp.add(X2, Y2); // step 5 + t3 = Fp.mul(t3, t4); + t4 = Fp.add(t0, t1); + t3 = Fp.sub(t3, t4); + t4 = Fp.add(X1, Z1); + let t5 = Fp.add(X2, Z2); // step 10 + t4 = Fp.mul(t4, t5); + t5 = Fp.add(t0, t2); + t4 = Fp.sub(t4, t5); + t5 = Fp.add(Y1, Z1); + X3 = Fp.add(Y2, Z2); // step 15 + t5 = Fp.mul(t5, X3); + X3 = Fp.add(t1, t2); + t5 = Fp.sub(t5, X3); + Z3 = Fp.mul(a, t4); + X3 = Fp.mul(b3, t2); // step 20 + Z3 = Fp.add(X3, Z3); + X3 = Fp.sub(t1, Z3); + Z3 = Fp.add(t1, Z3); + Y3 = Fp.mul(X3, Z3); + t1 = Fp.add(t0, t0); // step 25 + t1 = Fp.add(t1, t0); + t2 = Fp.mul(a, t2); + t4 = Fp.mul(b3, t4); + t1 = Fp.add(t1, t2); + t2 = Fp.sub(t0, t2); // step 30 + t2 = Fp.mul(a, t2); + t4 = Fp.add(t4, t2); + t0 = Fp.mul(t1, t4); + Y3 = Fp.add(Y3, t0); + t0 = Fp.mul(t5, t4); // step 35 + X3 = Fp.mul(t3, X3); + X3 = Fp.sub(X3, t0); + t0 = Fp.mul(t3, t1); + Z3 = Fp.mul(t5, Z3); + Z3 = Fp.add(Z3, t0); // step 40 + return new Point(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + is0() { + return this.equals(Point.ZERO); + } + wNAF(n) { + return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => { + const toInv = Fp.invertBatch(comp.map((p) => p.pz)); + return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + }); + } + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(n) { + const I = Point.ZERO; + if (n === _0n) + return I; + assertGE(n); // Will throw on 0 + if (n === _1n) + return this; + const { endo } = CURVE; + if (!endo) + return wnaf.unsafeLadder(this, n); + // Apply endomorphism + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let k1p = I; + let k2p = I; + let d = this; + while (k1 > _0n || k2 > _0n) { + if (k1 & _1n) + k1p = k1p.add(d); + if (k2 & _1n) + k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n; + k2 >>= _1n; + } + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar by which the point would be multiplied + * @returns New point + */ + multiply(scalar) { + assertGE(scalar); + let n = scalar; + let point, fake; // Fake point is used to const-time mult + const { endo } = CURVE; + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } + else { + const { p, f } = this.wNAF(n); + point = p; + fake = f; + } + // Normalize `z` for both points, but return only real one + return Point.normalizeZ([point, fake])[0]; + } + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q, a, b) { + const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes + const mul = (P, a // Select faster multiply() method + ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a)); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? undefined : sum; + } + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + toAffine(iz) { + const { px: x, py: y, pz: z } = this; + const is0 = this.is0(); + // If invZ was 0, we return zero point. However we still want to execute + // all operations, so we replace invZ with a random number, 1. + if (iz == null) + iz = is0 ? Fp.ONE : Fp.inv(z); + const ax = Fp.mul(x, iz); + const ay = Fp.mul(y, iz); + const zz = Fp.mul(z, iz); + if (is0) + return { x: Fp.ZERO, y: Fp.ZERO }; + if (!Fp.eql(zz, Fp.ONE)) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + } + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n) + return true; // No subgroups, always torsion-free + if (isTorsionFree) + return isTorsionFree(Point, this); + throw new Error('isTorsionFree() has not been declared for the elliptic curve'); + } + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n) + return this; // Fast-path + if (clearCofactor) + return clearCofactor(Point, this); + return this.multiplyUnsafe(CURVE.h); + } + toRawBytes(isCompressed = true) { + this.assertValidity(); + return toBytes(Point, this, isCompressed); + } + toHex(isCompressed = true) { + return ut.bytesToHex(this.toRawBytes(isCompressed)); + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); + Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = (0, curve_js_1.wNAF)(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + // Validate if generator point is on curve + return { + CURVE, + ProjectivePoint: Point, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + }; +} +exports.weierstrassPoints = weierstrassPoints; +function validateOpts(curve) { + const opts = (0, curve_js_1.validateBasic)(curve); + ut.validateObject(opts, { + hash: 'hash', + hmac: 'function', + randomBytes: 'function', + }, { + bits2int: 'function', + bits2int_modN: 'function', + lowS: 'boolean', + }); + return Object.freeze({ lowS: true, ...opts }); +} +function weierstrass(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32 + const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32 + function isValidFieldElement(num) { + return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE + } + function modN(a) { + return mod.mod(a, CURVE_ORDER); + } + function invN(a) { + return mod.invert(a, CURVE_ORDER); + } + const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({ + ...CURVE, + toBytes(_c, point, isCompressed) { + const a = point.toAffine(); + const x = Fp.toBytes(a.x); + const cat = ut.concatBytes; + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x); + } + else { + return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y)); + } + }, + fromBytes(bytes) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + // this.assertValidity() is done inside of fromHex + if (len === compressedLen && (head === 0x02 || head === 0x03)) { + const x = ut.bytesToNumberBE(tail); + if (!isValidFieldElement(x)) + throw new Error('Point is not on curve'); + const y2 = weierstrassEquation(x); // y² = x³ + ax + b + let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 + const isYOdd = (y & _1n) === _1n; + // ECDSA + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y = Fp.neg(y); + return { x, y }; + } + else if (len === uncompressedLen && head === 0x04) { + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + } + else { + throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); + } + }, + }); + const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number) { + const HALF = CURVE_ORDER >> _1n; + return number > HALF; + } + function normalizeS(s) { + return isBiggerThanHalfOrder(s) ? modN(-s) : s; + } + // slice bytes num + const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to)); + /** + * ECDSA signature with its (r, s) properties. Supports DER & compact representations. + */ + class Signature { + constructor(r, s, recovery) { + this.r = r; + this.s = s; + this.recovery = recovery; + this.assertValidity(); + } + // pair (bytes of r, bytes of s) + static fromCompact(hex) { + const l = CURVE.nByteLength; + hex = (0, utils_js_1.ensureBytes)('compactSignature', hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex) { + const { r, s } = exports.DER.toSig((0, utils_js_1.ensureBytes)('DER', hex)); + return new Signature(r, s); + } + assertValidity() { + // can use assertGE here + if (!isWithinCurveOrder(this.r)) + throw new Error('r must be 0 < r < CURVE.n'); + if (!isWithinCurveOrder(this.s)) + throw new Error('s must be 0 < s < CURVE.n'); + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(msgHash) { + const { r, s, recovery: rec } = this; + const h = bits2int_modN((0, utils_js_1.ensureBytes)('msgHash', msgHash)); // Truncate hash + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error('recovery id invalid'); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp.ORDER) + throw new Error('recovery id 2 or 3 invalid'); + const prefix = (rec & 1) === 0 ? '02' : '03'; + const R = Point.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); // r^-1 + const u1 = modN(-h * ir); // -hr^-1 + const u2 = modN(s * ir); // sr^-1 + const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1) + if (!Q) + throw new Error('point at infinify'); // unsafe is fine: no priv data leaked + Q.assertValidity(); + return Q; + } + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; + } + // DER-encoded + toDERRawBytes() { + return ut.hexToBytes(this.toDERHex()); + } + toDERHex() { + return exports.DER.hexFromSig({ r: this.r, s: this.s }); + } + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return ut.hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + const utils = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } + catch (error) { + return false; + } + }, + normPrivateKeyToScalar: normPrivateKeyToScalar, + /** + * Produces cryptographically secure private key from random of size + * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. + */ + randomPrivateKey: () => { + const length = mod.getMinHashLength(CURVE.n); + return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n); + }, + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here + return point; + }, + }; + /** + * Computes public key for a private key. Checks for validity of the private key. + * @param privateKey private key + * @param isCompressed whether to return compact (default), or full key + * @returns Public key, full when isCompressed=false; short when isCompressed=true + */ + function getPublicKey(privateKey, isCompressed = true) { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + /** + * Quick and dirty check for item being public key. Does not validate hex, or being on-curve. + */ + function isProbPub(item) { + const arr = item instanceof Uint8Array; + const str = typeof item === 'string'; + const len = (arr || str) && item.length; + if (arr) + return len === compressedLen || len === uncompressedLen; + if (str) + return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point) + return true; + return false; + } + /** + * ECDH (Elliptic Curve Diffie Hellman). + * Computes shared public key from private key and public key. + * Checks: 1) private key validity 2) shared key is on-curve. + * Does NOT hash the result. + * @param privateA private key + * @param publicB different public key + * @param isCompressed whether to return compact (default), or full key + * @returns shared public key + */ + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) + throw new Error('first arg must be private key'); + if (!isProbPub(publicB)) + throw new Error('second arg must be public key'); + const b = Point.fromHex(publicB); // check for being on-curve + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets. + // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int. + // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same. + // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors + const bits2int = CURVE.bits2int || + function (bytes) { + // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m) + // for some cases, since bytes.length * 8 is not actual bitLength. + const num = ut.bytesToNumberBE(bytes); // check for == u8 done here + const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits + return delta > 0 ? num >> BigInt(delta) : num; + }; + const bits2int_modN = CURVE.bits2int_modN || + function (bytes) { + return modN(bits2int(bytes)); // can't use bytesToNumberBE here + }; + // NOTE: pads output with zero as per spec + const ORDER_MASK = ut.bitMask(CURVE.nBitLength); + /** + * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. + */ + function int2octets(num) { + if (typeof num !== 'bigint') + throw new Error('bigint expected'); + if (!(_0n <= num && num < ORDER_MASK)) + throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); + // works with order, can have different size than numToField! + return ut.numberToBytesBE(num, CURVE.nByteLength); + } + // Steps A, D of RFC6979 3.2 + // Creates RFC6979 seed; converts msg/privKey to numbers. + // Used only in sign, not in verify. + // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521. + // Also it can be bigger for P224 + SHA256 + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (['recovered', 'canonical'].some((k) => k in opts)) + throw new Error('sign() legacy options not supported'); + const { hash, randomBytes } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default + if (lowS == null) + lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash + msgHash = (0, utils_js_1.ensureBytes)('msgHash', msgHash); + if (prehash) + msgHash = (0, utils_js_1.ensureBytes)('prehashed msgHash', hash(msgHash)); + // We can't later call bits2octets, since nested bits2int is broken for curves + // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call. + // const bits2octets = (bits) => int2octets(bits2int_modN(bits)) + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint + const seedArgs = [int2octets(d), int2octets(h1int)]; + // extraEntropy. RFC6979 3.6: additional k' (optional). + if (ent != null) { + // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') + const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is + seedArgs.push((0, utils_js_1.ensureBytes)('extraEntropy', e)); // check for being bytes + } + const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2 + const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash! + // Converts signature params into point w r/s, checks result for validity. + function k2sig(kBytes) { + // RFC 6979 Section 3.2, step 3: k = bits2int(T) + const k = bits2int(kBytes); // Cannot use fields methods, since it is group element + if (!isWithinCurveOrder(k)) + return; // Important: all mod() calls here must be done over N + const ik = invN(k); // k^-1 mod n + const q = Point.BASE.multiply(k).toAffine(); // q = Gk + const r = modN(q.x); // r = q.x mod n + if (r === _0n) + return; + // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to + // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it: + // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT + const s = modN(ik * modN(m + r * d)); // Not using blinding here + if (s === _0n) + return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n) + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); // if lowS was passed, ensure s is always + recovery ^= 1; // // in the bottom half of N + } + return new Signature(r, normS, recovery); // use normS, not s + } + return { seed, k2sig }; + } + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + /** + * Signs message hash with a private key. + * ``` + * sign(m, d, k) where + * (x, y) = G × k + * r = x mod n + * s = (m + dr)/k mod n + * ``` + * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`. + * @param privKey private key + * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg. + * @returns signature with recovery param + */ + function sign(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2. + const C = CURVE; + const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); // Steps B, C, D, E, F, G + } + // Enable precomputes. Slows down first publicKey computation by 20ms. + Point.BASE._setWindowSize(8); + // utils.precompute(8, ProjectivePoint.BASE) + /** + * Verifies a signature against message hash and public key. + * Rejects lowS signatures by default: to override, + * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf: + * + * ``` + * verify(r, s, h, P) where + * U1 = hs^-1 mod n + * U2 = rs^-1 mod n + * R = U1⋅G - U2⋅P + * mod(R.x, n) == r + * ``` + */ + function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { + const sg = signature; + msgHash = (0, utils_js_1.ensureBytes)('msgHash', msgHash); + publicKey = (0, utils_js_1.ensureBytes)('publicKey', publicKey); + if ('strict' in opts) + throw new Error('options.strict was renamed to lowS'); + const { lowS, prehash } = opts; + let _sig = undefined; + let P; + try { + if (typeof sg === 'string' || sg instanceof Uint8Array) { + // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length). + // Since DER can also be 2*nByteLength bytes, we check for it first. + try { + _sig = Signature.fromDER(sg); + } + catch (derError) { + if (!(derError instanceof exports.DER.Err)) + throw derError; + _sig = Signature.fromCompact(sg); + } + } + else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') { + const { r, s } = sg; + _sig = new Signature(r, s); + } + else { + throw new Error('PARSE'); + } + P = Point.fromHex(publicKey); + } + catch (error) { + if (error.message === 'PARSE') + throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; + } + if (lowS && _sig.hasHighS()) + return false; + if (prehash) + msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element + const is = invN(s); // s^-1 + const u1 = modN(h * is); // u1 = hs^-1 mod n + const u2 = modN(r * is); // u2 = rs^-1 mod n + const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P + if (!R) + return false; + const v = modN(R.x); + return v === r; + } + return { + CURVE, + getPublicKey, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point, + Signature, + utils, + }; +} +exports.weierstrass = weierstrass; +/** + * Implementation of the Shallue and van de Woestijne method for any weierstrass curve. + * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular. + * b = True and y = sqrt(u / v) if (u / v) is square in F, and + * b = False and y = sqrt(Z * (u / v)) otherwise. + * @param Fp + * @param Z + * @returns + */ +function SWUFpSqrtRatio(Fp, Z) { + // Generic implementation + const q = Fp.ORDER; + let l = _0n; + for (let o = q - _1n; o % _2n === _0n; o /= _2n) + l += _1n; + const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1. + // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<. + // 2n ** c1 == 2n << (c1-1) + const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n); + const _2n_pow_c1 = _2n_pow_c1_1 * _2n; + const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic + const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic + const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic + const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic + const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2 + const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2) + let sqrtRatio = (u, v) => { + let tv1 = c6; // 1. tv1 = c6 + let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4 + let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2 + tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v + let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3 + tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3 + tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2 + tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v + tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u + let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2 + tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5 + let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1 + tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7 + tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1 + tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR) + tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR) + // 17. for i in (c1, c1 - 1, ..., 2): + for (let i = c1; i > _1n; i--) { + let tv5 = i - _2n; // 18. tv5 = i - 2 + tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5 + let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5 + const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1 + tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1 + tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1 + tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1 + tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1) + tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1) + } + return { isValid: isQR, value: tv3 }; + }; + if (Fp.ORDER % _4n === _3n) { + // sqrt_ratio_3mod4(u, v) + const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic + const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z) + sqrtRatio = (u, v) => { + let tv1 = Fp.sqr(v); // 1. tv1 = v^2 + const tv2 = Fp.mul(u, v); // 2. tv2 = u * v + tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2 + let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1 + y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2 + const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2 + const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v + const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u + let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR) + return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2 + }; + } + // No curves uses that + // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8 + return sqrtRatio; +} +exports.SWUFpSqrtRatio = SWUFpSqrtRatio; +/** + * Simplified Shallue-van de Woestijne-Ulas Method + * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2 + */ +function mapToCurveSimpleSWU(Fp, opts) { + mod.validateField(Fp); + if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z)) + throw new Error('mapToCurveSimpleSWU: invalid opts'); + const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z); + if (!Fp.isOdd) + throw new Error('Fp.isOdd is not implemented!'); + // Input: u, an element of F. + // Output: (x, y), a point on E. + return (u) => { + // prettier-ignore + let tv1, tv2, tv3, tv4, tv5, tv6, x, y; + tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1 + tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2 + tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1 + tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1 + tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3 + tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0) + tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4 + tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2 + tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2 + tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6 + tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5 + tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3 + tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4 + tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6 + tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5 + x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3 + const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6) + y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1 + y = Fp.mul(y, value); // 20. y = y * y1 + x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square) + y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square) + const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y) + y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1) + x = Fp.div(x, tv4); // 25. x = x / tv4 + return { x, y }; + }; +} +exports.mapToCurveSimpleSWU = mapToCurveSimpleSWU; +//# sourceMappingURL=weierstrass.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/weierstrass.js.map b/node_modules/@noble/curves/abstract/weierstrass.js.map new file mode 100644 index 0000000..696074d --- /dev/null +++ b/node_modules/@noble/curves/abstract/weierstrass.js.map @@ -0,0 +1 @@ +{"version":3,"file":"weierstrass.js","sourceRoot":"","sources":["../src/abstract/weierstrass.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,4DAA4D;AAC5D,oCAAoC;AACpC,iCAAiC;AACjC,yCAA8D;AAC9D,yCAAmG;AAqFnG,SAAS,iBAAiB,CAAI,KAAyB;IACrD,MAAM,IAAI,GAAG,IAAA,wBAAa,EAAC,KAAK,CAAC,CAAC;IAClC,EAAE,CAAC,cAAc,CACf,IAAI,EACJ;QACE,CAAC,EAAE,OAAO;QACV,CAAC,EAAE,OAAO;KACX,EACD;QACE,wBAAwB,EAAE,OAAO;QACjC,cAAc,EAAE,SAAS;QACzB,aAAa,EAAE,UAAU;QACzB,aAAa,EAAE,UAAU;QACzB,kBAAkB,EAAE,SAAS;QAC7B,SAAS,EAAE,UAAU;QACrB,OAAO,EAAE,UAAU;KACpB,CACF,CAAC;IACF,MAAM,EAAE,IAAI,EAAE,E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,EAAE,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,sBAAsB;QAC5C,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,SAAS,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,iDAAiD;QACjG,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,qCAAqC;QACzD,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,mBAAmB;QACzC,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC,wCAAwC;QACtE,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,uCAAuC;QACvE,MAAM,EAAE,GAAG,EAAE,CAAC,KAAM,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,KAAM,CAAC,CAAC,CAAC,CAAC,CAAC,+BAA+B;QACzE,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,4BAA4B;QAC3D,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,oBAAoB;QACxC,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IAClB,CAAC,CAAC;AACJ,CAAC;AA7CD,kDA6CC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/bls12-381.d.ts b/node_modules/@noble/curves/bls12-381.d.ts new file mode 100644 index 0000000..0e71114 --- /dev/null +++ b/node_modules/@noble/curves/bls12-381.d.ts @@ -0,0 +1,68 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { CurveFn } from './abstract/bls.js'; +import * as mod from './abstract/modular.js'; +declare const Fp: Readonly & Required, "isOdd">>>; +type Fp = bigint; +type BigintTuple = [bigint, bigint]; +type Fp2 = { + c0: bigint; + c1: bigint; +}; +type Fp2Utils = { + fromBigTuple: (tuple: BigintTuple | bigint[]) => Fp2; + reim: (num: Fp2) => { + re: bigint; + im: bigint; + }; + mulByNonresidue: (num: Fp2) => Fp2; + multiplyByB: (num: Fp2) => Fp2; + frobeniusMap(num: Fp2, power: number): Fp2; +}; +declare const Fp2: mod.IField & Fp2Utils; +type BigintSix = [bigint, bigint, bigint, bigint, bigint, bigint]; +type Fp6 = { + c0: Fp2; + c1: Fp2; + c2: Fp2; +}; +type Fp6Utils = { + fromBigSix: (tuple: BigintSix) => Fp6; + mulByNonresidue: (num: Fp6) => Fp6; + frobeniusMap(num: Fp6, power: number): Fp6; + multiplyBy1(num: Fp6, b1: Fp2): Fp6; + multiplyBy01(num: Fp6, b0: Fp2, b1: Fp2): Fp6; + multiplyByFp2(lhs: Fp6, rhs: Fp2): Fp6; +}; +declare const Fp6: mod.IField & Fp6Utils; +type Fp12 = { + c0: Fp6; + c1: Fp6; +}; +type BigintTwelve = [ + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint +]; +type Fp12Utils = { + fromBigTwelve: (t: BigintTwelve) => Fp12; + frobeniusMap(num: Fp12, power: number): Fp12; + multiplyBy014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12; + multiplyByFp2(lhs: Fp12, rhs: Fp2): Fp12; + conjugate(num: Fp12): Fp12; + finalExponentiate(num: Fp12): Fp12; + _cyclotomicSquare(num: Fp12): Fp12; + _cyclotomicExp(num: Fp12, n: bigint): Fp12; +}; +declare const Fp12: mod.IField & Fp12Utils; +export declare const bls12_381: CurveFn; +export {}; +//# sourceMappingURL=bls12-381.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/bls12-381.d.ts.map b/node_modules/@noble/curves/bls12-381.d.ts.map new file mode 100644 index 0000000..01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G,IAAI,CAAC;IACzC,SAAS,CAAC,GAAG,EAAE,IAAI,GAAG,IAAI,CAAC;IAC3B,iBAAiB,CAAC,GAAG,EAAE,IAAI,GAAG,IAAI,CAAC;IACnC,iBAAiB,CAAC,GAAG,EAAE,IAAI,GAAG,IAAI,CAAC;IACnC,cAAc,CAAC,GAAG,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5C,CAAC;AAEF,QAAA,MAAM,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,SA6I9B,CAAC;AAkWF,eAAO,MAAM,SAAS,EAAE,OAAO,CAAC,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,CA2ShD,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/bls12-381.js b/node_modules/@noble/curves/bls12-381.js new file mode 100644 index 0000000..06766d4 --- /dev/null +++ b/node_modules/@noble/curves/bls12-381.js @@ -0,0 +1,1175 @@ +"use strict"; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bls12_381 = void 0; +// bls12-381 pairing-friendly Barreto-Lynn-Scott elliptic curve construction allows to: +// - Construct zk-SNARKs at the 128-bit security +// - Use threshold signatures, which allows a user to sign lots of messages with one signature and +// verify them swiftly in a batch, using Boneh-Lynn-Shacham signature scheme. +// +// The library uses G1 for public keys and G2 for signatures. Support for G1 signatures is planned. +// Compatible with Algorand, Chia, Dfinity, Ethereum, FIL, Zcash. Matches specs +// [pairing-curves-11](https://tools.ietf.org/html/draft-irtf-cfrg-pairing-friendly-curves-11), +// [bls-sigs-04](https:/cfrg-hash-to/tools.ietf.org/html/draft-irtf-cfrg-bls-signature-04), +// [hash-to-curve-12](https://tools.ietf.org/html/draft-irtf--curve-12). +// +// ### Summary +// 1. BLS Relies on Bilinear Pairing (expensive) +// 2. Private Keys: 32 bytes +// 3. Public Keys: 48 bytes: 381 bit affine x coordinate, encoded into 48 big-endian bytes. +// 4. Signatures: 96 bytes: two 381 bit integers (affine x coordinate), encoded into two 48 big-endian byte arrays. +// - The signature is a point on the G2 subgroup, which is defined over a finite field +// with elements twice as big as the G1 curve (G2 is over Fp2 rather than Fp. Fp2 is analogous to the complex numbers). +// 5. The 12 stands for the Embedding degree. +// +// ### Formulas +// - `P = pk x G` - public keys +// - `S = pk x H(m)` - signing +// - `e(P, H(m)) == e(G, S)` - verification using pairings +// - `e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))` - signature aggregation +// Filecoin uses little endian byte arrays for private keys - +// so ensure to reverse byte order if you'll use it with FIL. +const sha256_1 = require("@noble/hashes/sha256"); +const utils_1 = require("@noble/hashes/utils"); +const bls_js_1 = require("./abstract/bls.js"); +const mod = require("./abstract/modular.js"); +const utils_js_1 = require("./abstract/utils.js"); +// Types +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4); +// prettier-ignore +const _8n = BigInt(8), _16n = BigInt(16); +// CURVE FIELDS +// Finite field over p. +const Fp_raw = BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'); +const Fp = mod.Field(Fp_raw); +// Finite field over r. +// This particular field is not used anywhere in bls12-381, but it is still useful. +const Fr = mod.Field(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')); +const Fp2Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp.add(c0, r0), + c1: Fp.add(c1, r1), +}); +const Fp2Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp.sub(c0, r0), + c1: Fp.sub(c1, r1), +}); +const Fp2Multiply = ({ c0, c1 }, rhs) => { + if (typeof rhs === 'bigint') + return { c0: Fp.mul(c0, rhs), c1: Fp.mul(c1, rhs) }; + // (a+bi)(c+di) = (ac−bd) + (ad+bc)i + const { c0: r0, c1: r1 } = rhs; + let t1 = Fp.mul(c0, r0); // c0 * o0 + let t2 = Fp.mul(c1, r1); // c1 * o1 + // (T1 - T2) + ((c0 + c1) * (r0 + r1) - (T1 + T2))*i + const o0 = Fp.sub(t1, t2); + const o1 = Fp.sub(Fp.mul(Fp.add(c0, c1), Fp.add(r0, r1)), Fp.add(t1, t2)); + return { c0: o0, c1: o1 }; +}; +const Fp2Square = ({ c0, c1 }) => { + const a = Fp.add(c0, c1); + const b = Fp.sub(c0, c1); + const c = Fp.add(c0, c0); + return { c0: Fp.mul(a, b), c1: Fp.mul(c, c1) }; +}; +// G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1), +// where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where +// G² - 1 +// h2q +// NOTE: ORDER was wrong! +const FP2_ORDER = Fp_raw * Fp_raw; +const Fp2 = { + ORDER: FP2_ORDER, + BITS: (0, utils_js_1.bitLen)(FP2_ORDER), + BYTES: Math.ceil((0, utils_js_1.bitLen)(FP2_ORDER) / 8), + MASK: (0, utils_js_1.bitMask)((0, utils_js_1.bitLen)(FP2_ORDER)), + ZERO: { c0: Fp.ZERO, c1: Fp.ZERO }, + ONE: { c0: Fp.ONE, c1: Fp.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => typeof c0 === 'bigint' && typeof c1 === 'bigint', + is0: ({ c0, c1 }) => Fp.is0(c0) && Fp.is0(c1), + eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp.eql(c0, r0) && Fp.eql(c1, r1), + neg: ({ c0, c1 }) => ({ c0: Fp.neg(c0), c1: Fp.neg(c1) }), + pow: (num, power) => mod.FpPow(Fp2, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp2, nums), + // Normalized + add: Fp2Add, + sub: Fp2Subtract, + mul: Fp2Multiply, + sqr: Fp2Square, + // NonNormalized stuff + addN: Fp2Add, + subN: Fp2Subtract, + mulN: Fp2Multiply, + sqrN: Fp2Square, + // Why inversion for bigint inside Fp instead of Fp2? it is even used in that context? + div: (lhs, rhs) => Fp2.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp2.inv(rhs)), + inv: ({ c0: a, c1: b }) => { + // We wish to find the multiplicative inverse of a nonzero + // element a + bu in Fp2. We leverage an identity + // + // (a + bu)(a - bu) = a² + b² + // + // which holds because u² = -1. This can be rewritten as + // + // (a + bu)(a - bu)/(a² + b²) = 1 + // + // because a² + b² = 0 has no nonzero solutions for (a, b). + // This gives that (a - bu)/(a² + b²) is the inverse + // of (a + bu). Importantly, this can be computing using + // only a single inversion in Fp. + const factor = Fp.inv(Fp.create(a * a + b * b)); + return { c0: Fp.mul(factor, Fp.create(a)), c1: Fp.mul(factor, Fp.create(-b)) }; + }, + sqrt: (num) => { + if (Fp2.eql(num, Fp2.ZERO)) + return Fp2.ZERO; // Algo doesn't handles this case + // TODO: Optimize this line. It's extremely slow. + // Speeding this up would boost aggregateSignatures. + // https://eprint.iacr.org/2012/685.pdf applicable? + // https://github.com/zkcrypto/bls12_381/blob/080eaa74ec0e394377caa1ba302c8c121df08b07/src/fp2.rs#L250 + // https://github.com/supranational/blst/blob/aae0c7d70b799ac269ff5edf29d8191dbd357876/src/exp2.c#L1 + // Inspired by https://github.com/dalek-cryptography/curve25519-dalek/blob/17698df9d4c834204f83a3574143abacb4fc81a5/src/field.rs#L99 + const candidateSqrt = Fp2.pow(num, (Fp2.ORDER + _8n) / _16n); + const check = Fp2.div(Fp2.sqr(candidateSqrt), num); // candidateSqrt.square().div(this); + const R = FP2_ROOTS_OF_UNITY; + const divisor = [R[0], R[2], R[4], R[6]].find((r) => Fp2.eql(r, check)); + if (!divisor) + throw new Error('No root'); + const index = R.indexOf(divisor); + const root = R[index / 2]; + if (!root) + throw new Error('Invalid root'); + const x1 = Fp2.div(candidateSqrt, root); + const x2 = Fp2.neg(x1); + const { re: re1, im: im1 } = Fp2.reim(x1); + const { re: re2, im: im2 } = Fp2.reim(x2); + if (im1 > im2 || (im1 === im2 && re1 > re2)) + return x1; + return x2; + }, + // Same as sgn0_m_eq_2 in RFC 9380 + isOdd: (x) => { + const { re: x0, im: x1 } = Fp2.reim(x); + const sign_0 = x0 % _2n; + const zero_0 = x0 === _0n; + const sign_1 = x1 % _2n; + return BigInt(sign_0 || (zero_0 && sign_1)) == _1n; + }, + // Bytes util + fromBytes(b) { + if (b.length !== Fp2.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { c0: Fp.fromBytes(b.subarray(0, Fp.BYTES)), c1: Fp.fromBytes(b.subarray(Fp.BYTES)) }; + }, + toBytes: ({ c0, c1 }) => (0, utils_js_1.concatBytes)(Fp.toBytes(c0), Fp.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp.cmov(c0, r0, c), + c1: Fp.cmov(c1, r1, c), + }), + // Specific utils + // toString() { + // return `Fp2(${this.c0} + ${this.c1}×i)`; + // } + reim: ({ c0, c1 }) => ({ re: c0, im: c1 }), + // multiply by u + 1 + mulByNonresidue: ({ c0, c1 }) => ({ c0: Fp.sub(c0, c1), c1: Fp.add(c0, c1) }), + multiplyByB: ({ c0, c1 }) => { + let t0 = Fp.mul(c0, _4n); // 4 * c0 + let t1 = Fp.mul(c1, _4n); // 4 * c1 + // (T0-T1) + (T0+T1)*i + return { c0: Fp.sub(t0, t1), c1: Fp.add(t0, t1) }; + }, + fromBigTuple: (tuple) => { + if (tuple.length !== 2) + throw new Error('Invalid tuple'); + const fps = tuple.map((n) => Fp.create(n)); + return { c0: fps[0], c1: fps[1] }; + }, + frobeniusMap: ({ c0, c1 }, power) => ({ + c0, + c1: Fp.mul(c1, FP2_FROBENIUS_COEFFICIENTS[power % 2]), + }), +}; +// Finite extension field over irreducible polynominal. +// Fp(u) / (u² - β) where β = -1 +const FP2_FROBENIUS_COEFFICIENTS = [ + BigInt('0x1'), + BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'), +].map((item) => Fp.create(item)); +// For Fp2 roots of unity. +const rv1 = BigInt('0x6af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09'); +// const ev1 = +// BigInt('0x699be3b8c6870965e5bf892ad5d2cc7b0e85a117402dfd83b7f4a947e02d978498255a2aaec0ac627b5afbdf1bf1c90'); +// const ev2 = +// BigInt('0x8157cd83046453f5dd0972b6e3949e4288020b5b8a9cc99ca07e27089a2ce2436d965026adad3ef7baba37f2183e9b5'); +// const ev3 = +// BigInt('0xab1c2ffdd6c253ca155231eb3e71ba044fd562f6f72bc5bad5ec46a0b7a3b0247cf08ce6c6317f40edbc653a72dee17'); +// const ev4 = +// BigInt('0xaa404866706722864480885d68ad0ccac1967c7544b447873cc37e0181271e006df72162a3d3e0287bf597fbf7f8fc1'); +// Eighth roots of unity, used for computing square roots in Fp2. +// To verify or re-calculate: +// Array(8).fill(new Fp2([1n, 1n])).map((fp2, k) => fp2.pow(Fp2.ORDER * BigInt(k) / 8n)) +const FP2_ROOTS_OF_UNITY = [ + [_1n, _0n], + [rv1, -rv1], + [_0n, _1n], + [rv1, rv1], + [-_1n, _0n], + [-rv1, rv1], + [_0n, -_1n], + [-rv1, -rv1], +].map((pair) => Fp2.fromBigTuple(pair)); +const Fp6Add = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({ + c0: Fp2.add(c0, r0), + c1: Fp2.add(c1, r1), + c2: Fp2.add(c2, r2), +}); +const Fp6Subtract = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({ + c0: Fp2.sub(c0, r0), + c1: Fp2.sub(c1, r1), + c2: Fp2.sub(c2, r2), +}); +const Fp6Multiply = ({ c0, c1, c2 }, rhs) => { + if (typeof rhs === 'bigint') { + return { + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }; + } + const { c0: r0, c1: r1, c2: r2 } = rhs; + const t0 = Fp2.mul(c0, r0); // c0 * o0 + const t1 = Fp2.mul(c1, r1); // c1 * o1 + const t2 = Fp2.mul(c2, r2); // c2 * o2 + return { + // t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1) + c0: Fp2.add(t0, Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), Fp2.add(r1, r2)), Fp2.add(t1, t2)))), + // (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1) + c1: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c1), Fp2.add(r0, r1)), Fp2.add(t0, t1)), Fp2.mulByNonresidue(t2)), + // T1 + (c0 + c2) * (r0 + r2) - T0 + T2 + c2: Fp2.sub(Fp2.add(t1, Fp2.mul(Fp2.add(c0, c2), Fp2.add(r0, r2))), Fp2.add(t0, t2)), + }; +}; +const Fp6Square = ({ c0, c1, c2 }) => { + let t0 = Fp2.sqr(c0); // c0² + let t1 = Fp2.mul(Fp2.mul(c0, c1), _2n); // 2 * c0 * c1 + let t3 = Fp2.mul(Fp2.mul(c1, c2), _2n); // 2 * c1 * c2 + let t4 = Fp2.sqr(c2); // c2² + return { + c0: Fp2.add(Fp2.mulByNonresidue(t3), t0), + c1: Fp2.add(Fp2.mulByNonresidue(t4), t1), + // T1 + (c0 - c1 + c2)² + T3 - T0 - T4 + c2: Fp2.sub(Fp2.sub(Fp2.add(Fp2.add(t1, Fp2.sqr(Fp2.add(Fp2.sub(c0, c1), c2))), t3), t0), t4), + }; +}; +const Fp6 = { + ORDER: Fp2.ORDER, + BITS: 3 * Fp2.BITS, + BYTES: 3 * Fp2.BYTES, + MASK: (0, utils_js_1.bitMask)(3 * Fp2.BITS), + ZERO: { c0: Fp2.ZERO, c1: Fp2.ZERO, c2: Fp2.ZERO }, + ONE: { c0: Fp2.ONE, c1: Fp2.ZERO, c2: Fp2.ZERO }, + create: (num) => num, + isValid: ({ c0, c1, c2 }) => Fp2.isValid(c0) && Fp2.isValid(c1) && Fp2.isValid(c2), + is0: ({ c0, c1, c2 }) => Fp2.is0(c0) && Fp2.is0(c1) && Fp2.is0(c2), + neg: ({ c0, c1, c2 }) => ({ c0: Fp2.neg(c0), c1: Fp2.neg(c1), c2: Fp2.neg(c2) }), + eql: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => Fp2.eql(c0, r0) && Fp2.eql(c1, r1) && Fp2.eql(c2, r2), + sqrt: () => { + throw new Error('Not implemented'); + }, + // Do we need division by bigint at all? Should be done via order: + div: (lhs, rhs) => Fp6.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp6.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp6, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp6, nums), + // Normalized + add: Fp6Add, + sub: Fp6Subtract, + mul: Fp6Multiply, + sqr: Fp6Square, + // NonNormalized stuff + addN: Fp6Add, + subN: Fp6Subtract, + mulN: Fp6Multiply, + sqrN: Fp6Square, + inv: ({ c0, c1, c2 }) => { + let t0 = Fp2.sub(Fp2.sqr(c0), Fp2.mulByNonresidue(Fp2.mul(c2, c1))); // c0² - c2 * c1 * (u + 1) + let t1 = Fp2.sub(Fp2.mulByNonresidue(Fp2.sqr(c2)), Fp2.mul(c0, c1)); // c2² * (u + 1) - c0 * c1 + let t2 = Fp2.sub(Fp2.sqr(c1), Fp2.mul(c0, c2)); // c1² - c0 * c2 + // 1/(((c2 * T1 + c1 * T2) * v) + c0 * T0) + let t4 = Fp2.inv(Fp2.add(Fp2.mulByNonresidue(Fp2.add(Fp2.mul(c2, t1), Fp2.mul(c1, t2))), Fp2.mul(c0, t0))); + return { c0: Fp2.mul(t4, t0), c1: Fp2.mul(t4, t1), c2: Fp2.mul(t4, t2) }; + }, + // Bytes utils + fromBytes: (b) => { + if (b.length !== Fp6.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp2.fromBytes(b.subarray(0, Fp2.BYTES)), + c1: Fp2.fromBytes(b.subarray(Fp2.BYTES, 2 * Fp2.BYTES)), + c2: Fp2.fromBytes(b.subarray(2 * Fp2.BYTES)), + }; + }, + toBytes: ({ c0, c1, c2 }) => (0, utils_js_1.concatBytes)(Fp2.toBytes(c0), Fp2.toBytes(c1), Fp2.toBytes(c2)), + cmov: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }, c) => ({ + c0: Fp2.cmov(c0, r0, c), + c1: Fp2.cmov(c1, r1, c), + c2: Fp2.cmov(c2, r2, c), + }), + // Utils + // fromTriple(triple: [Fp2, Fp2, Fp2]) { + // return new Fp6(...triple); + // } + // toString() { + // return `Fp6(${this.c0} + ${this.c1} * v, ${this.c2} * v^2)`; + // } + fromBigSix: (t) => { + if (!Array.isArray(t) || t.length !== 6) + throw new Error('Invalid Fp6 usage'); + return { + c0: Fp2.fromBigTuple(t.slice(0, 2)), + c1: Fp2.fromBigTuple(t.slice(2, 4)), + c2: Fp2.fromBigTuple(t.slice(4, 6)), + }; + }, + frobeniusMap: ({ c0, c1, c2 }, power) => ({ + c0: Fp2.frobeniusMap(c0, power), + c1: Fp2.mul(Fp2.frobeniusMap(c1, power), FP6_FROBENIUS_COEFFICIENTS_1[power % 6]), + c2: Fp2.mul(Fp2.frobeniusMap(c2, power), FP6_FROBENIUS_COEFFICIENTS_2[power % 6]), + }), + mulByNonresidue: ({ c0, c1, c2 }) => ({ c0: Fp2.mulByNonresidue(c2), c1: c0, c2: c1 }), + // Sparse multiplication + multiplyBy1: ({ c0, c1, c2 }, b1) => ({ + c0: Fp2.mulByNonresidue(Fp2.mul(c2, b1)), + c1: Fp2.mul(c0, b1), + c2: Fp2.mul(c1, b1), + }), + // Sparse multiplication + multiplyBy01({ c0, c1, c2 }, b0, b1) { + let t0 = Fp2.mul(c0, b0); // c0 * b0 + let t1 = Fp2.mul(c1, b1); // c1 * b1 + return { + // ((c1 + c2) * b1 - T1) * (u + 1) + T0 + c0: Fp2.add(Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), b1), t1)), t0), + // (b0 + b1) * (c0 + c1) - T0 - T1 + c1: Fp2.sub(Fp2.sub(Fp2.mul(Fp2.add(b0, b1), Fp2.add(c0, c1)), t0), t1), + // (c0 + c2) * b0 - T0 + T1 + c2: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c2), b0), t0), t1), + }; + }, + multiplyByFp2: ({ c0, c1, c2 }, rhs) => ({ + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }), +}; +const FP6_FROBENIUS_COEFFICIENTS_1 = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt('0x0'), + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + BigInt('0x0'), + ], + [BigInt('0x0'), BigInt('0x1')], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + BigInt('0x0'), + ], + [ + BigInt('0x0'), + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + ], +].map((pair) => Fp2.fromBigTuple(pair)); +const FP6_FROBENIUS_COEFFICIENTS_2 = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad'), + BigInt('0x0'), + ], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + BigInt('0x0'), + ], + [ + BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'), + BigInt('0x0'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + BigInt('0x0'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff'), + BigInt('0x0'), + ], +].map((pair) => Fp2.fromBigTuple(pair)); +// The BLS parameter x for BLS12-381 +const BLS_X = BigInt('0xd201000000010000'); +const BLS_X_LEN = (0, utils_js_1.bitLen)(BLS_X); +const Fp12Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp6.add(c0, r0), + c1: Fp6.add(c1, r1), +}); +const Fp12Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp6.sub(c0, r0), + c1: Fp6.sub(c1, r1), +}); +const Fp12Multiply = ({ c0, c1 }, rhs) => { + if (typeof rhs === 'bigint') + return { c0: Fp6.mul(c0, rhs), c1: Fp6.mul(c1, rhs) }; + let { c0: r0, c1: r1 } = rhs; + let t1 = Fp6.mul(c0, r0); // c0 * r0 + let t2 = Fp6.mul(c1, r1); // c1 * r1 + return { + c0: Fp6.add(t1, Fp6.mulByNonresidue(t2)), + // (c0 + c1) * (r0 + r1) - (T1 + T2) + c1: Fp6.sub(Fp6.mul(Fp6.add(c0, c1), Fp6.add(r0, r1)), Fp6.add(t1, t2)), + }; +}; +const Fp12Square = ({ c0, c1 }) => { + let ab = Fp6.mul(c0, c1); // c0 * c1 + return { + // (c1 * v + c0) * (c0 + c1) - AB - AB * v + c0: Fp6.sub(Fp6.sub(Fp6.mul(Fp6.add(Fp6.mulByNonresidue(c1), c0), Fp6.add(c0, c1)), ab), Fp6.mulByNonresidue(ab)), + c1: Fp6.add(ab, ab), + }; // AB + AB +}; +function Fp4Square(a, b) { + const a2 = Fp2.sqr(a); + const b2 = Fp2.sqr(b); + return { + first: Fp2.add(Fp2.mulByNonresidue(b2), a2), + second: Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(a, b)), a2), b2), // (a + b)² - a² - b² + }; +} +const Fp12 = { + ORDER: Fp2.ORDER, + BITS: 2 * Fp2.BITS, + BYTES: 2 * Fp2.BYTES, + MASK: (0, utils_js_1.bitMask)(2 * Fp2.BITS), + ZERO: { c0: Fp6.ZERO, c1: Fp6.ZERO }, + ONE: { c0: Fp6.ONE, c1: Fp6.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => Fp6.isValid(c0) && Fp6.isValid(c1), + is0: ({ c0, c1 }) => Fp6.is0(c0) && Fp6.is0(c1), + neg: ({ c0, c1 }) => ({ c0: Fp6.neg(c0), c1: Fp6.neg(c1) }), + eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp6.eql(c0, r0) && Fp6.eql(c1, r1), + sqrt: () => { + throw new Error('Not implemented'); + }, + inv: ({ c0, c1 }) => { + let t = Fp6.inv(Fp6.sub(Fp6.sqr(c0), Fp6.mulByNonresidue(Fp6.sqr(c1)))); // 1 / (c0² - c1² * v) + return { c0: Fp6.mul(c0, t), c1: Fp6.neg(Fp6.mul(c1, t)) }; // ((C0 * T) * T) + (-C1 * T) * w + }, + div: (lhs, rhs) => Fp12.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp12.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp12, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp12, nums), + // Normalized + add: Fp12Add, + sub: Fp12Subtract, + mul: Fp12Multiply, + sqr: Fp12Square, + // NonNormalized stuff + addN: Fp12Add, + subN: Fp12Subtract, + mulN: Fp12Multiply, + sqrN: Fp12Square, + // Bytes utils + fromBytes: (b) => { + if (b.length !== Fp12.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp6.fromBytes(b.subarray(0, Fp6.BYTES)), + c1: Fp6.fromBytes(b.subarray(Fp6.BYTES)), + }; + }, + toBytes: ({ c0, c1 }) => (0, utils_js_1.concatBytes)(Fp6.toBytes(c0), Fp6.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp6.cmov(c0, r0, c), + c1: Fp6.cmov(c1, r1, c), + }), + // Utils + // toString() { + // return `Fp12(${this.c0} + ${this.c1} * w)`; + // }, + // fromTuple(c: [Fp6, Fp6]) { + // return new Fp12(...c); + // } + fromBigTwelve: (t) => ({ + c0: Fp6.fromBigSix(t.slice(0, 6)), + c1: Fp6.fromBigSix(t.slice(6, 12)), + }), + // Raises to q**i -th power + frobeniusMap(lhs, power) { + const r0 = Fp6.frobeniusMap(lhs.c0, power); + const { c0, c1, c2 } = Fp6.frobeniusMap(lhs.c1, power); + const coeff = FP12_FROBENIUS_COEFFICIENTS[power % 12]; + return { + c0: r0, + c1: Fp6.create({ + c0: Fp2.mul(c0, coeff), + c1: Fp2.mul(c1, coeff), + c2: Fp2.mul(c2, coeff), + }), + }; + }, + // Sparse multiplication + multiplyBy014: ({ c0, c1 }, o0, o1, o4) => { + let t0 = Fp6.multiplyBy01(c0, o0, o1); + let t1 = Fp6.multiplyBy1(c1, o4); + return { + c0: Fp6.add(Fp6.mulByNonresidue(t1), t0), + // (c1 + c0) * [o0, o1+o4] - T0 - T1 + c1: Fp6.sub(Fp6.sub(Fp6.multiplyBy01(Fp6.add(c1, c0), o0, Fp2.add(o1, o4)), t0), t1), + }; + }, + multiplyByFp2: ({ c0, c1 }, rhs) => ({ + c0: Fp6.multiplyByFp2(c0, rhs), + c1: Fp6.multiplyByFp2(c1, rhs), + }), + conjugate: ({ c0, c1 }) => ({ c0, c1: Fp6.neg(c1) }), + // A cyclotomic group is a subgroup of Fp^n defined by + // GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1} + // The result of any pairing is in a cyclotomic subgroup + // https://eprint.iacr.org/2009/565.pdf + _cyclotomicSquare: ({ c0, c1 }) => { + const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0; + const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1; + const { first: t3, second: t4 } = Fp4Square(c0c0, c1c1); + const { first: t5, second: t6 } = Fp4Square(c1c0, c0c2); + const { first: t7, second: t8 } = Fp4Square(c0c1, c1c2); + let t9 = Fp2.mulByNonresidue(t8); // T8 * (u + 1) + return { + c0: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.sub(t3, c0c0), _2n), t3), + c1: Fp2.add(Fp2.mul(Fp2.sub(t5, c0c1), _2n), t5), + c2: Fp2.add(Fp2.mul(Fp2.sub(t7, c0c2), _2n), t7), + }), + c1: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.add(t9, c1c0), _2n), t9), + c1: Fp2.add(Fp2.mul(Fp2.add(t4, c1c1), _2n), t4), + c2: Fp2.add(Fp2.mul(Fp2.add(t6, c1c2), _2n), t6), + }), + }; // 2 * (T6 + c1c2) + T6 + }, + _cyclotomicExp(num, n) { + let z = Fp12.ONE; + for (let i = BLS_X_LEN - 1; i >= 0; i--) { + z = Fp12._cyclotomicSquare(z); + if ((0, utils_js_1.bitGet)(n, i)) + z = Fp12.mul(z, num); + } + return z; + }, + // https://eprint.iacr.org/2010/354.pdf + // https://eprint.iacr.org/2009/565.pdf + finalExponentiate: (num) => { + const x = BLS_X; + // this^(q⁶) / this + const t0 = Fp12.div(Fp12.frobeniusMap(num, 6), num); + // t0^(q²) * t0 + const t1 = Fp12.mul(Fp12.frobeniusMap(t0, 2), t0); + const t2 = Fp12.conjugate(Fp12._cyclotomicExp(t1, x)); + const t3 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicSquare(t1)), t2); + const t4 = Fp12.conjugate(Fp12._cyclotomicExp(t3, x)); + const t5 = Fp12.conjugate(Fp12._cyclotomicExp(t4, x)); + const t6 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicExp(t5, x)), Fp12._cyclotomicSquare(t2)); + const t7 = Fp12.conjugate(Fp12._cyclotomicExp(t6, x)); + const t2_t5_pow_q2 = Fp12.frobeniusMap(Fp12.mul(t2, t5), 2); + const t4_t1_pow_q3 = Fp12.frobeniusMap(Fp12.mul(t4, t1), 3); + const t6_t1c_pow_q1 = Fp12.frobeniusMap(Fp12.mul(t6, Fp12.conjugate(t1)), 1); + const t7_t3c_t1 = Fp12.mul(Fp12.mul(t7, Fp12.conjugate(t3)), t1); + // (t2 * t5)^(q²) * (t4 * t1)^(q³) * (t6 * t1.conj)^(q^1) * t7 * t3.conj * t1 + return Fp12.mul(Fp12.mul(Fp12.mul(t2_t5_pow_q2, t4_t1_pow_q3), t6_t1c_pow_q1), t7_t3c_t1); + }, +}; +const FP12_FROBENIUS_COEFFICIENTS = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt('0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8'), + BigInt('0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff'), + BigInt('0x0'), + ], + [ + BigInt('0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2'), + BigInt('0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + BigInt('0x0'), + ], + [ + BigInt('0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995'), + BigInt('0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116'), + ], + [ + BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'), + BigInt('0x0'), + ], + [ + BigInt('0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3'), + BigInt('0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8'), + ], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + BigInt('0x0'), + ], + [ + BigInt('0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09'), + BigInt('0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2'), + ], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad'), + BigInt('0x0'), + ], + [ + BigInt('0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116'), + BigInt('0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995'), + ], +].map((n) => Fp2.fromBigTuple(n)); +// END OF CURVE FIELDS +// HashToCurve +// 3-isogeny map from E' to E https://www.rfc-editor.org/rfc/rfc9380#appendix-E.3 +const isogenyMapG2 = (0, hash_to_curve_js_1.isogenyMap)(Fp2, [ + // xNum + [ + [ + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + ], + [ + '0x0', + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d', + ], + [ + '0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1', + '0x0', + ], + ], + // xDen + [ + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63', + ], + [ + '0xc', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f', + ], + ['0x1', '0x0'], // LAST 1 + ], + // yNum + [ + [ + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + ], + [ + '0x0', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f', + ], + [ + '0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10', + '0x0', + ], + ], + // yDen + [ + [ + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + ], + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3', + ], + [ + '0x12', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99', + ], + ['0x1', '0x0'], // LAST 1 + ], +].map((i) => i.map((pair) => Fp2.fromBigTuple(pair.map(BigInt))))); +// 11-isogeny map from E' to E +const isogenyMapG1 = (0, hash_to_curve_js_1.isogenyMap)(Fp, [ + // xNum + [ + '0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7', + '0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb', + '0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0', + '0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861', + '0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9', + '0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983', + '0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84', + '0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e', + '0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317', + '0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e', + '0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b', + '0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229', + ], + // xDen + [ + '0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c', + '0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff', + '0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19', + '0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8', + '0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e', + '0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5', + '0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a', + '0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e', + '0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641', + '0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33', + '0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696', + '0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6', + '0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb', + '0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb', + '0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0', + '0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2', + '0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29', + '0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587', + '0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30', + '0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132', + '0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e', + '0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8', + '0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133', + '0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b', + '0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604', + ], + // yDen + [ + '0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1', + '0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d', + '0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2', + '0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416', + '0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d', + '0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac', + '0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c', + '0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9', + '0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a', + '0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55', + '0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8', + '0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092', + '0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc', + '0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7', + '0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], +].map((i) => i.map((j) => BigInt(j)))); +// SWU Map - Fp2 to G2': y² = x³ + 240i * x + 1012 + 1012i +const G2_SWU = (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp2, { + A: Fp2.create({ c0: Fp.create(_0n), c1: Fp.create(BigInt(240)) }), + B: Fp2.create({ c0: Fp.create(BigInt(1012)), c1: Fp.create(BigInt(1012)) }), + Z: Fp2.create({ c0: Fp.create(BigInt(-2)), c1: Fp.create(BigInt(-1)) }), // Z: -(2 + I) +}); +// Optimized SWU Map - Fp to G1 +const G1_SWU = (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, { + A: Fp.create(BigInt('0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d')), + B: Fp.create(BigInt('0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0')), + Z: Fp.create(BigInt(11)), +}); +// Endomorphisms (for fast cofactor clearing) +// Ψ(P) endomorphism +const ut_root = Fp6.create({ c0: Fp2.ZERO, c1: Fp2.ONE, c2: Fp2.ZERO }); +const wsq = Fp12.create({ c0: ut_root, c1: Fp6.ZERO }); +const wcu = Fp12.create({ c0: Fp6.ZERO, c1: ut_root }); +const [wsq_inv, wcu_inv] = Fp12.invertBatch([wsq, wcu]); +function psi(x, y) { + // Untwist Fp2->Fp12 && frobenius(1) && twist back + const x2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wsq_inv, x), 1), wsq).c0.c0; + const y2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wcu_inv, y), 1), wcu).c0.c0; + return [x2, y2]; +} +// Ψ endomorphism +function G2psi(c, P) { + const affine = P.toAffine(); + const p = psi(affine.x, affine.y); + return new c(p[0], p[1], Fp2.ONE); +} +// Ψ²(P) endomorphism +// 1 / F2(2)^((p-1)/3) in GF(p²) +const PSI2_C1 = BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'); +function psi2(x, y) { + return [Fp2.mul(x, PSI2_C1), Fp2.neg(y)]; +} +function G2psi2(c, P) { + const affine = P.toAffine(); + const p = psi2(affine.x, affine.y); + return new c(p[0], p[1], Fp2.ONE); +} +// Default hash_to_field options are for hash to G2. +// +// Parameter definitions are in section 5.3 of the spec unless otherwise noted. +// Parameter values come from section 8.8.2 of the spec. +// https://www.rfc-editor.org/rfc/rfc9380#section-8.8.2 +// +// Base field F is GF(p^m) +// p = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab +// m = 2 (or 1 for G1 see section 8.8.1) +// k = 128 +const htfDefaults = Object.freeze({ + // DST: a domain separation tag + // defined in section 2.2.5 + // Use utils.getDSTLabel(), utils.setDSTLabel(value) + DST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + encodeDST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + // p: the characteristic of F + // where F is a finite field of characteristic p and order q = p^m + p: Fp.ORDER, + // m: the extension degree of F, m >= 1 + // where F is a finite field of characteristic p and order q = p^m + m: 2, + // k: the target security level for the suite in bits + // defined in section 5.1 + k: 128, + // option to use a message that has already been processed by + // expand_message_xmd + expand: 'xmd', + // Hash functions for: expand_message_xmd is appropriate for use with a + // wide range of hash functions, including SHA-2, SHA-3, BLAKE2, and others. + // BBS+ uses blake2: https://github.com/hyperledger/aries-framework-go/issues/2247 + hash: sha256_1.sha256, +}); +// Encoding utils +// Point on G1 curve: (x, y) +const C_BIT_POS = Fp.BITS; // C_bit, compression bit for serialization flag +const I_BIT_POS = Fp.BITS + 1; // I_bit, point-at-infinity bit for serialization flag +const S_BIT_POS = Fp.BITS + 2; // S_bit, sign bit for serialization flag +// Compressed point of infinity +const COMPRESSED_ZERO = Fp.toBytes((0, utils_js_1.bitSet)((0, utils_js_1.bitSet)(_0n, I_BIT_POS, true), S_BIT_POS, true)); // set compressed & point-at-infinity bits +function signatureG2ToRawBytes(point) { + // NOTE: by some reasons it was missed in bls12-381, looks like bug + point.assertValidity(); + const len = Fp.BYTES; + if (point.equals(exports.bls12_381.G2.ProjectivePoint.ZERO)) + return (0, utils_js_1.concatBytes)(COMPRESSED_ZERO, (0, utils_js_1.numberToBytesBE)(_0n, len)); + const { x, y } = point.toAffine(); + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + const tmp = y1 > _0n ? y1 * _2n : y0 * _2n; + const aflag1 = Boolean((tmp / Fp.ORDER) & _1n); + const z1 = (0, utils_js_1.bitSet)((0, utils_js_1.bitSet)(x1, 381, aflag1), S_BIT_POS, true); + const z2 = x0; + return (0, utils_js_1.concatBytes)((0, utils_js_1.numberToBytesBE)(z1, len), (0, utils_js_1.numberToBytesBE)(z2, len)); +} +// To verify curve parameters, see pairing-friendly-curves spec: +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-11 +// Basic math is done over finite fields over p. +// More complicated math is done over polynominal extension fields. +// To simplify calculations in Fp12, we construct extension tower: +// Fp₁₂ = Fp₆² => Fp₂³ +// Fp(u) / (u² - β) where β = -1 +// Fp₂(v) / (v³ - ξ) where ξ = u + 1 +// Fp₆(w) / (w² - γ) where γ = v +// Here goes constants && point encoding format +exports.bls12_381 = (0, bls_js_1.bls)({ + // Fields + fields: { + Fp, + Fp2, + Fp6, + Fp12, + Fr, + }, + // G1 is the order-q subgroup of E1(Fp) : y² = x³ + 4, #E1(Fp) = h1q, where + // characteristic; z + (z⁴ - z² + 1)(z - 1)²/3 + G1: { + Fp, + // cofactor; (z - 1)²/3 + h: BigInt('0x396c8c005555e1568c00aaab0000aaab'), + // generator's coordinates + // x = 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507 + // y = 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569 + Gx: BigInt('0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb'), + Gy: BigInt('0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1'), + a: Fp.ZERO, + b: _4n, + htfDefaults: { ...htfDefaults, m: 1 }, + wrapPrivateKey: true, + allowInfinityPoint: true, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, point) => { + // φ endomorphism + const cubicRootOfUnityModP = BigInt('0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'); + const phi = new c(Fp.mul(point.px, cubicRootOfUnityModP), point.py, point.pz); + // todo: unroll + const xP = point.multiplyUnsafe(exports.bls12_381.params.x).negate(); // [x]P + const u2P = xP.multiplyUnsafe(exports.bls12_381.params.x); // [u2]P + return u2P.equals(phi); + // https://eprint.iacr.org/2019/814.pdf + // (z² − 1)/3 + // const c1 = BigInt('0x396c8c005555e1560000000055555555'); + // const P = this; + // const S = P.sigma(); + // const Q = S.double(); + // const S2 = S.sigma(); + // // [(z² − 1)/3](2σ(P) − P − σ²(P)) − σ²(P) = O + // const left = Q.subtract(P).subtract(S2).multiplyUnsafe(c1); + // const C = left.subtract(S2); + // return C.isZero(); + }, + // Clear cofactor of G1 + // https://eprint.iacr.org/2019/403 + clearCofactor: (_c, point) => { + // return this.multiplyUnsafe(CURVE.h); + return point.multiplyUnsafe(exports.bls12_381.params.x).add(point); // x*P + P + }, + mapToCurve: (scalars) => { + const { x, y } = G1_SWU(Fp.create(scalars[0])); + return isogenyMapG1(x, y); + }, + fromBytes: (bytes) => { + bytes = bytes.slice(); + if (bytes.length === 48) { + // TODO: Fp.bytes + const P = Fp.ORDER; + const compressedValue = (0, utils_js_1.bytesToNumberBE)(bytes); + const bflag = (0, utils_js_1.bitGet)(compressedValue, I_BIT_POS); + // Zero + if (bflag === _1n) + return { x: _0n, y: _0n }; + const x = Fp.create(compressedValue & Fp.MASK); + const right = Fp.add(Fp.pow(x, _3n), Fp.create(exports.bls12_381.params.G1b)); // y² = x³ + b + let y = Fp.sqrt(right); + if (!y) + throw new Error('Invalid compressed G1 point'); + const aflag = (0, utils_js_1.bitGet)(compressedValue, C_BIT_POS); + if ((y * _2n) / P !== aflag) + y = Fp.neg(y); + return { x: Fp.create(x), y: Fp.create(y) }; + } + else if (bytes.length === 96) { + // Check if the infinity flag is set + if ((bytes[0] & (1 << 6)) !== 0) + return exports.bls12_381.G1.ProjectivePoint.ZERO.toAffine(); + const x = (0, utils_js_1.bytesToNumberBE)(bytes.subarray(0, Fp.BYTES)); + const y = (0, utils_js_1.bytesToNumberBE)(bytes.subarray(Fp.BYTES)); + return { x: Fp.create(x), y: Fp.create(y) }; + } + else { + throw new Error('Invalid point G1, expected 48/96 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) + return COMPRESSED_ZERO.slice(); + const P = Fp.ORDER; + let num; + num = (0, utils_js_1.bitSet)(x, C_BIT_POS, Boolean((y * _2n) / P)); // set aflag + num = (0, utils_js_1.bitSet)(num, S_BIT_POS, true); + return (0, utils_js_1.numberToBytesBE)(num, Fp.BYTES); + } + else { + if (isZero) { + // 2x PUBLIC_KEY_LENGTH + const x = (0, utils_js_1.concatBytes)(new Uint8Array([0x40]), new Uint8Array(2 * Fp.BYTES - 1)); + return x; + } + else { + return (0, utils_js_1.concatBytes)((0, utils_js_1.numberToBytesBE)(x, Fp.BYTES), (0, utils_js_1.numberToBytesBE)(y, Fp.BYTES)); + } + } + }, + }, + // G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1), + // where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where + // G² - 1 + // h2q + G2: { + Fp: Fp2, + // cofactor + h: BigInt('0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5'), + Gx: Fp2.fromBigTuple([ + BigInt('0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8'), + BigInt('0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e'), + ]), + // y = + // 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582, + // 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905 + Gy: Fp2.fromBigTuple([ + BigInt('0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801'), + BigInt('0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be'), + ]), + a: Fp2.ZERO, + b: Fp2.fromBigTuple([_4n, _4n]), + hEff: BigInt('0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551'), + htfDefaults: { ...htfDefaults }, + wrapPrivateKey: true, + allowInfinityPoint: true, + mapToCurve: (scalars) => { + const { x, y } = G2_SWU(Fp2.fromBigTuple(scalars)); + return isogenyMapG2(x, y); + }, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, P) => { + return P.multiplyUnsafe(exports.bls12_381.params.x).negate().equals(G2psi(c, P)); // ψ(P) == [u](P) + // Older version: https://eprint.iacr.org/2019/814.pdf + // Ψ²(P) => Ψ³(P) => [z]Ψ³(P) where z = -x => [z]Ψ³(P) - Ψ²(P) + P == O + // return P.psi2().psi().mulNegX().subtract(psi2).add(P).isZero(); + }, + // Maps the point into the prime-order subgroup G2. + // clear_cofactor_bls12381_g2 from cfrg-hash-to-curve-11 + // https://eprint.iacr.org/2017/419.pdf + // prettier-ignore + clearCofactor: (c, P) => { + const x = exports.bls12_381.params.x; + let t1 = P.multiplyUnsafe(x).negate(); // [-x]P + let t2 = G2psi(c, P); // Ψ(P) + let t3 = P.double(); // 2P + t3 = G2psi2(c, t3); // Ψ²(2P) + t3 = t3.subtract(t2); // Ψ²(2P) - Ψ(P) + t2 = t1.add(t2); // [-x]P + Ψ(P) + t2 = t2.multiplyUnsafe(x).negate(); // [x²]P - [x]Ψ(P) + t3 = t3.add(t2); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + t3 = t3.subtract(t1); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P + const Q = t3.subtract(P); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P - 1P + return Q; // [x²-x-1]P + [x-1]Ψ(P) + Ψ²(2P) + }, + fromBytes: (bytes) => { + bytes = bytes.slice(); + const m_byte = bytes[0] & 0xe0; + if (m_byte === 0x20 || m_byte === 0x60 || m_byte === 0xe0) { + throw new Error('Invalid encoding flag: ' + m_byte); + } + const bitC = m_byte & 0x80; // compression bit + const bitI = m_byte & 0x40; // point at infinity bit + const bitS = m_byte & 0x20; // sign bit + const L = Fp.BYTES; + const slc = (b, from, to) => (0, utils_js_1.bytesToNumberBE)(b.slice(from, to)); + if (bytes.length === 96 && bitC) { + const b = exports.bls12_381.params.G2b; + const P = Fp.ORDER; + bytes[0] = bytes[0] & 0x1f; // clear flags + if (bitI) { + // check that all bytes are 0 + if (bytes.reduce((p, c) => (p !== 0 ? c + 1 : c), 0) > 0) { + throw new Error('Invalid compressed G2 point'); + } + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x_1 = slc(bytes, 0, L); + const x_0 = slc(bytes, L, 2 * L); + const x = Fp2.create({ c0: Fp.create(x_0), c1: Fp.create(x_1) }); + const right = Fp2.add(Fp2.pow(x, _3n), b); // y² = x³ + 4 * (u+1) = x³ + b + let y = Fp2.sqrt(right); + const Y_bit = y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P ? _1n : _0n; + y = bitS > 0 && Y_bit > 0 ? y : Fp2.neg(y); + return { x, y }; + } + else if (bytes.length === 192 && !bitC) { + // Check if the infinity flag is set + if ((bytes[0] & (1 << 6)) !== 0) { + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x1 = slc(bytes, 0, L); + const x0 = slc(bytes, L, 2 * L); + const y1 = slc(bytes, 2 * L, 3 * L); + const y0 = slc(bytes, 3 * L, 4 * L); + return { x: Fp2.fromBigTuple([x0, x1]), y: Fp2.fromBigTuple([y0, y1]) }; + } + else { + throw new Error('Invalid point G2, expected 96/192 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const { BYTES: len, ORDER: P } = Fp; + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) + return (0, utils_js_1.concatBytes)(COMPRESSED_ZERO, (0, utils_js_1.numberToBytesBE)(_0n, len)); + const flag = Boolean(y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P); + // set compressed & sign bits (looks like different offsets than for G1/Fp?) + let x_1 = (0, utils_js_1.bitSet)(x.c1, C_BIT_POS, flag); + x_1 = (0, utils_js_1.bitSet)(x_1, S_BIT_POS, true); + return (0, utils_js_1.concatBytes)((0, utils_js_1.numberToBytesBE)(x_1, len), (0, utils_js_1.numberToBytesBE)(x.c0, len)); + } + else { + if (isZero) + return (0, utils_js_1.concatBytes)(new Uint8Array([0x40]), new Uint8Array(4 * len - 1)); // bytes[0] |= 1 << 6; + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + return (0, utils_js_1.concatBytes)((0, utils_js_1.numberToBytesBE)(x1, len), (0, utils_js_1.numberToBytesBE)(x0, len), (0, utils_js_1.numberToBytesBE)(y1, len), (0, utils_js_1.numberToBytesBE)(y0, len)); + } + }, + Signature: { + // TODO: Optimize, it's very slow because of sqrt. + fromHex(hex) { + hex = (0, utils_js_1.ensureBytes)('signatureHex', hex); + const P = Fp.ORDER; + const half = hex.length / 2; + if (half !== 48 && half !== 96) + throw new Error('Invalid compressed signature length, must be 96 or 192'); + const z1 = (0, utils_js_1.bytesToNumberBE)(hex.slice(0, half)); + const z2 = (0, utils_js_1.bytesToNumberBE)(hex.slice(half)); + // Indicates the infinity point + const bflag1 = (0, utils_js_1.bitGet)(z1, I_BIT_POS); + if (bflag1 === _1n) + return exports.bls12_381.G2.ProjectivePoint.ZERO; + const x1 = Fp.create(z1 & Fp.MASK); + const x2 = Fp.create(z2); + const x = Fp2.create({ c0: x2, c1: x1 }); + const y2 = Fp2.add(Fp2.pow(x, _3n), exports.bls12_381.params.G2b); // y² = x³ + 4 + // The slow part + let y = Fp2.sqrt(y2); + if (!y) + throw new Error('Failed to find a square root'); + // Choose the y whose leftmost bit of the imaginary part is equal to the a_flag1 + // If y1 happens to be zero, then use the bit of y0 + const { re: y0, im: y1 } = Fp2.reim(y); + const aflag1 = (0, utils_js_1.bitGet)(z1, 381); + const isGreater = y1 > _0n && (y1 * _2n) / P !== aflag1; + const isZero = y1 === _0n && (y0 * _2n) / P !== aflag1; + if (isGreater || isZero) + y = Fp2.neg(y); + const point = exports.bls12_381.G2.ProjectivePoint.fromAffine({ x, y }); + point.assertValidity(); + return point; + }, + toRawBytes(point) { + return signatureG2ToRawBytes(point); + }, + toHex(point) { + return (0, utils_js_1.bytesToHex)(signatureG2ToRawBytes(point)); + }, + }, + }, + params: { + x: BLS_X, + r: Fr.ORDER, // order; z⁴ − z² + 1; CURVE.n from other curves + }, + htfDefaults, + hash: sha256_1.sha256, + randomBytes: utils_1.randomBytes, +}); +//# sourceMappingURL=bls12-381.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/bls12-381.js.map b/node_modules/@noble/curves/bls12-381.js.map new file mode 100644 index 0000000..fbed95a --- /dev/null +++ b/node_modules/@noble/curves/bls12-381.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bls12-381.js","sourceRoot":"","sources":["src/bls12-381.ts"],"names":[],"mappings":";AAAA,sEAAsE;;;AAEtE,uFAAuF;AACvF,gDAAgD;AAChD,kGAAkG;AAClG,+EAA+E;AAC/E,EAAE;AACF,mGAAmG;AACnG,+EAA+E;AAC/E,+FAA+F;AAC/F,2FAA2F;AAC3F,wEAAwE;AACxE,EAAE;AACF,cAAc;AACd,gDAAgD;AAChD,4BAA4B;AAC5B,2FAA2F;AAC3F,mHAAmH;AACnH,0FAA0F;AAC1F,2HAA2H;AAC3H,6CAA6C;AAC7C,EAAE;AACF,eAAe;AACf,+BAA+B;AAC/B,8BAA8B;AAC9B,0DAA0D;AAC1D,4EAA4E;AAC5E,6DAA6D;AAC7D,6DAA6D;AAC7D,iDAA8C;AAC9C,+CAAkD;AAClD,8CAAiD;AACjD,6CAA6C;AAC7C,kDAW6B;AAC7B,QAAQ;AACR,8DAKmC;AACnC,kEAAyD;AAEzD,qEAAqE;AACrE,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAC1F,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;AAEzC,eAAe;AACf,uBAAuB;AACvB,MAAM,MAAM,GAAG,MAAM,CACnB,oGAAoG,CACrG,CAAC;AACF,MAAM,EAAE,GAAG,GAAG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} \ No newline at end of file diff --git a/node_modules/@noble/curves/bn254.d.ts b/node_modules/@noble/curves/bn254.d.ts new file mode 100644 index 0000000..fd7064a --- /dev/null +++ b/node_modules/@noble/curves/bn254.d.ts @@ -0,0 +1,8 @@ +/** + * bn254 pairing-friendly curve. + * Previously known as alt_bn_128, when it had 128-bit security. + * Recent research shown it's weaker, the naming has been adjusted to its prime bit count. + * https://github.com/zcash/zcash/issues/2502 + */ +export declare const bn254: import("./abstract/weierstrass.js").CurveFn; +//# sourceMappingURL=bn254.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/bn254.d.ts.map b/node_modules/@noble/curves/bn254.d.ts.map new file mode 100644 index 0000000..572db18 --- /dev/null +++ b/node_modules/@noble/curves/bn254.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bn254.d.ts","sourceRoot":"","sources":["src/bn254.ts"],"names":[],"mappings":"AAKA;;;;;GAKG;AACH,eAAO,MAAM,KAAK,6CAShB,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/bn254.js b/node_modules/@noble/curves/bn254.js new file mode 100644 index 0000000..8b1c4b7 --- /dev/null +++ b/node_modules/@noble/curves/bn254.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bn254 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha256_1 = require("@noble/hashes/sha256"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const modular_js_1 = require("./abstract/modular.js"); +/** + * bn254 pairing-friendly curve. + * Previously known as alt_bn_128, when it had 128-bit security. + * Recent research shown it's weaker, the naming has been adjusted to its prime bit count. + * https://github.com/zcash/zcash/issues/2502 + */ +exports.bn254 = (0, weierstrass_js_1.weierstrass)({ + a: BigInt(0), + b: BigInt(3), + Fp: (0, modular_js_1.Field)(BigInt('0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47')), + n: BigInt('0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001'), + Gx: BigInt(1), + Gy: BigInt(2), + h: BigInt(1), + ...(0, _shortw_utils_js_1.getHash)(sha256_1.sha256), +}); +//# sourceMappingURL=bn254.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/bn254.js.map b/node_modules/@noble/curves/bn254.js.map new file mode 100644 index 0000000..a54fb58 --- /dev/null +++ b/node_modules/@noble/curves/bn254.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bn254.js","sourceRoot":"","sources":["src/bn254.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,iDAA8C;AAC9C,8DAAwD;AACxD,yDAA6C;AAC7C,sDAA8C;AAC9C;;;;;GAKG;AACU,QAAA,KAAK,GAAG,IAAA,4BAAW,EAAC;IAC/B,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE,EAAE,IAAA,kBAAK,EAAC,MAAM,CAAC,oEAAoE,CAAC,CAAC;IACvF,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,IAAA,0BAAO,EAAC,eAAM,CAAC;CACnB,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/ed25519.d.ts b/node_modules/@noble/curves/ed25519.d.ts new file mode 100644 index 0000000..08b1e89 --- /dev/null +++ b/node_modules/@noble/curves/ed25519.d.ts @@ -0,0 +1,76 @@ +import { ExtPointType } from './abstract/edwards.js'; +import { Hex } from './abstract/utils.js'; +import { htfBasicOpts } from './abstract/hash-to-curve.js'; +import { AffinePoint } from './abstract/curve.js'; +export declare const ED25519_TORSION_SUBGROUP: string[]; +export declare const ed25519: import("./abstract/edwards.js").CurveFn; +export declare const ed25519ctx: import("./abstract/edwards.js").CurveFn; +export declare const ed25519ph: import("./abstract/edwards.js").CurveFn; +export declare const x25519: import("./abstract/montgomery.js").CurveFn; +/** + * Converts ed25519 public key to x25519 public key. Uses formula: + * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)` + * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))` + * @example + * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey()); + * const aPriv = x25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub)) + */ +export declare function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array; +export declare const edwardsToMontgomery: typeof edwardsToMontgomeryPub; +/** + * Converts ed25519 secret key to x25519 secret key. + * @example + * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey()); + * const aPriv = ed25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub) + */ +export declare function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array; +export declare const hashToCurve: (msg: Uint8Array, options?: htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +type ExtendedPoint = ExtPointType; +/** + * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Ristretto was created to solve this. + * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +declare class RistPoint { + private readonly ep; + static BASE: RistPoint; + static ZERO: RistPoint; + constructor(ep: ExtendedPoint); + static fromAffine(ap: AffinePoint): RistPoint; + /** + * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://ristretto.group/formulas/elligator.html + * @param hex 64-byte output of a hash function + */ + static hashToCurve(hex: Hex): RistPoint; + /** + * Converts ristretto-encoded string to ristretto point. + * https://ristretto.group/formulas/decoding.html + * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding + */ + static fromHex(hex: Hex): RistPoint; + /** + * Encodes ristretto point to Uint8Array. + * https://ristretto.group/formulas/encoding.html + */ + toRawBytes(): Uint8Array; + toHex(): string; + toString(): string; + equals(other: RistPoint): boolean; + add(other: RistPoint): RistPoint; + subtract(other: RistPoint): RistPoint; + multiply(scalar: bigint): RistPoint; + multiplyUnsafe(scalar: bigint): RistPoint; +} +export declare const RistrettoPoint: typeof RistPoint; +export declare const hashToRistretto255: (msg: Uint8Array, options: htfBasicOpts) => RistPoint; +export declare const hash_to_ristretto255: (msg: Uint8Array, options: htfBasicOpts) => RistPoint; +export {}; +//# sourceMappingURL=ed25519.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/ed25519.d.ts.map b/node_modules/@noble/curves/ed25519.d.ts.map new file mode 100644 index 0000000..973b462 --- /dev/null +++ b/node_modules/@noble/curves/ed25519.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ed25519.d.ts","sourceRoot":"","sources":["src/ed25519.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,YAAY,EAAkB,MAAM,uBAAuB,CAAC;AAGrE,OAAO,EAKL,GAAG,EAEJ,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAgB,YAAY,EAAsB,MAAM,6BAA6B,CAAC;AAC7F,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAwElD,eAAO,MAAM,wBAAwB,UASpC,CAAC;AA6BF,eAAO,MAAM,OAAO,yCAAkD,CAAC;AAYvE,eAAO,MAAM,UAAU,yCAGrB,CAAC;AACH,eAAO,MAAM,SAAS,yCAIpB,CAAC;AAEH,eAAO,MAAM,MAAM,4CAeZ,CAAC;AAER;;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AC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/ed25519.js b/node_modules/@noble/curves/ed25519.js new file mode 100644 index 0000000..78554de --- /dev/null +++ b/node_modules/@noble/curves/ed25519.js @@ -0,0 +1,439 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hash_to_ristretto255 = exports.hashToRistretto255 = exports.RistrettoPoint = exports.encodeToCurve = exports.hashToCurve = exports.edwardsToMontgomeryPriv = exports.edwardsToMontgomery = exports.edwardsToMontgomeryPub = exports.x25519 = exports.ed25519ph = exports.ed25519ctx = exports.ed25519 = exports.ED25519_TORSION_SUBGROUP = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha512_1 = require("@noble/hashes/sha512"); +const utils_1 = require("@noble/hashes/utils"); +const edwards_js_1 = require("./abstract/edwards.js"); +const montgomery_js_1 = require("./abstract/montgomery.js"); +const modular_js_1 = require("./abstract/modular.js"); +const utils_js_1 = require("./abstract/utils.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +/** + * ed25519 Twisted Edwards curve with following addons: + * - X25519 ECDH + * - Ristretto cofactor elimination + * - Elligator hash-to-group / point indistinguishability + */ +const ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949'); +// √(-1) aka √(a) aka 2^((p-1)/4) +const ED25519_SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752'); +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _5n = BigInt(5); +// prettier-ignore +const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80); +function ed25519_pow_2_252_3(x) { + const P = ED25519_P; + const x2 = (x * x) % P; + const b2 = (x2 * x) % P; // x^3, 11 + const b4 = ((0, modular_js_1.pow2)(b2, _2n, P) * b2) % P; // x^15, 1111 + const b5 = ((0, modular_js_1.pow2)(b4, _1n, P) * x) % P; // x^31 + const b10 = ((0, modular_js_1.pow2)(b5, _5n, P) * b5) % P; + const b20 = ((0, modular_js_1.pow2)(b10, _10n, P) * b10) % P; + const b40 = ((0, modular_js_1.pow2)(b20, _20n, P) * b20) % P; + const b80 = ((0, modular_js_1.pow2)(b40, _40n, P) * b40) % P; + const b160 = ((0, modular_js_1.pow2)(b80, _80n, P) * b80) % P; + const b240 = ((0, modular_js_1.pow2)(b160, _80n, P) * b80) % P; + const b250 = ((0, modular_js_1.pow2)(b240, _10n, P) * b10) % P; + const pow_p_5_8 = ((0, modular_js_1.pow2)(b250, _2n, P) * x) % P; + // ^ To pow to (p+3)/8, multiply it by x. + return { pow_p_5_8, b2 }; +} +function adjustScalarBytes(bytes) { + // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar, + // set the three least significant bits of the first byte + bytes[0] &= 248; // 0b1111_1000 + // and the most significant bit of the last to zero, + bytes[31] &= 127; // 0b0111_1111 + // set the second most significant bit of the last byte to 1 + bytes[31] |= 64; // 0b0100_0000 + return bytes; +} +// sqrt(u/v) +function uvRatio(u, v) { + const P = ED25519_P; + const v3 = (0, modular_js_1.mod)(v * v * v, P); // v³ + const v7 = (0, modular_js_1.mod)(v3 * v3 * v, P); // v⁷ + // (p+3)/8 and (p-5)/8 + const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8; + let x = (0, modular_js_1.mod)(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8 + const vx2 = (0, modular_js_1.mod)(v * x * x, P); // vx² + const root1 = x; // First root candidate + const root2 = (0, modular_js_1.mod)(x * ED25519_SQRT_M1, P); // Second root candidate + const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root + const useRoot2 = vx2 === (0, modular_js_1.mod)(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4) + const noRoot = vx2 === (0, modular_js_1.mod)(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1) + if (useRoot1) + x = root1; + if (useRoot2 || noRoot) + x = root2; // We return root2 anyway, for const-time + if ((0, modular_js_1.isNegativeLE)(x, P)) + x = (0, modular_js_1.mod)(-x, P); + return { isValid: useRoot1 || useRoot2, value: x }; +} +// Just in case +exports.ED25519_TORSION_SUBGROUP = [ + '0100000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', + '0000000000000000000000000000000000000000000000000000000000000080', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05', + 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85', + '0000000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa', +]; +const Fp = (0, modular_js_1.Field)(ED25519_P, undefined, true); +const ed25519Defaults = { + // Param: a + a: BigInt(-1), + // d is equal to -121665/121666 over finite field. + // Negative number is P - number, and division is invert(number, P) + d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'), + // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n + Fp, + // Subgroup order: how many points curve has + // 2n**252n + 27742317777372353535851937790883648493n; + n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'), + // Cofactor + h: BigInt(8), + // Base point (x, y) aka generator point + Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'), + Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'), + hash: sha512_1.sha512, + randomBytes: utils_1.randomBytes, + adjustScalarBytes, + // dom2 + // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3. + // Constant-time, u/√v + uvRatio, +}; +exports.ed25519 = (0, edwards_js_1.twistedEdwards)(ed25519Defaults); +function ed25519_domain(data, ctx, phflag) { + if (ctx.length > 255) + throw new Error('Context is too big'); + return (0, utils_1.concatBytes)((0, utils_1.utf8ToBytes)('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); +} +exports.ed25519ctx = (0, edwards_js_1.twistedEdwards)({ + ...ed25519Defaults, + domain: ed25519_domain, +}); +exports.ed25519ph = (0, edwards_js_1.twistedEdwards)({ + ...ed25519Defaults, + domain: ed25519_domain, + prehash: sha512_1.sha512, +}); +exports.x25519 = (() => (0, montgomery_js_1.montgomery)({ + P: ED25519_P, + a: BigInt(486662), + montgomeryBits: 255, + nByteLength: 32, + Gu: BigInt(9), + powPminus2: (x) => { + const P = ED25519_P; + // x^(p-2) aka x^(2^255-21) + const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x); + return (0, modular_js_1.mod)((0, modular_js_1.pow2)(pow_p_5_8, BigInt(3), P) * b2, P); + }, + adjustScalarBytes, + randomBytes: utils_1.randomBytes, +}))(); +/** + * Converts ed25519 public key to x25519 public key. Uses formula: + * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)` + * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))` + * @example + * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey()); + * const aPriv = x25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub)) + */ +function edwardsToMontgomeryPub(edwardsPub) { + const { y } = exports.ed25519.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y))); +} +exports.edwardsToMontgomeryPub = edwardsToMontgomeryPub; +exports.edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated +/** + * Converts ed25519 secret key to x25519 secret key. + * @example + * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey()); + * const aPriv = ed25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub) + */ +function edwardsToMontgomeryPriv(edwardsPriv) { + const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32)); + return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32); +} +exports.edwardsToMontgomeryPriv = edwardsToMontgomeryPriv; +// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator) +// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since +// SageMath returns different root first and everything falls apart +const ELL2_C1 = (Fp.ORDER + BigInt(3)) / BigInt(8); // 1. c1 = (q + 3) / 8 # Integer arithmetic +const ELL2_C2 = Fp.pow(_2n, ELL2_C1); // 2. c2 = 2^c1 +const ELL2_C3 = Fp.sqrt(Fp.neg(Fp.ONE)); // 3. c3 = sqrt(-1) +const ELL2_C4 = (Fp.ORDER - BigInt(5)) / BigInt(8); // 4. c4 = (q - 5) / 8 # Integer arithmetic +const ELL2_J = BigInt(486662); +// prettier-ignore +function map_to_curve_elligator2_curve25519(u) { + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1 + let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not + let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2) + let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2 + tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4 + tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3 + tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3 + tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7 + let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8) + y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8) + let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3 + tv2 = Fp.sqr(y11); // 19. tv2 = y11^2 + tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd + let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1 + let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt + let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd + let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u + y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2 + let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3 + let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1) + tv2 = Fp.sqr(y21); // 28. tv2 = y21^2 + tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2 + let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt + tv2 = Fp.sqr(y1); // 32. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd + let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2 + let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4) + return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1) +} +const ELL2_C1_EDWARDS = (0, modular_js_1.FpSqrtEven)(Fp, Fp.neg(BigInt(486664))); // sgn0(c1) MUST equal 0 +function map_to_curve_elligator2_edwards25519(u) { + const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) = + // map_to_curve_elligator2_curve25519(u) + let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd + xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1 + let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM + let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd + let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d) + let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd + let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0 + xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e) + xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e) + yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e) + yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e) + const inv = Fp.invertBatch([xd, yd]); // batch division + return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd) +} +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.ed25519.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), { + DST: 'edwards25519_XMD:SHA-512_ELL2_RO_', + encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha512_1.sha512, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +function assertRstPoint(other) { + if (!(other instanceof RistPoint)) + throw new Error('RistrettoPoint expected'); +} +// √(-1) aka √(a) aka 2^((p-1)/4) +const SQRT_M1 = ED25519_SQRT_M1; +// √(ad - 1) +const SQRT_AD_MINUS_ONE = BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235'); +// 1 / √(a-d) +const INVSQRT_A_MINUS_D = BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578'); +// 1-d² +const ONE_MINUS_D_SQ = BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838'); +// (d-1)² +const D_MINUS_ONE_SQ = BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952'); +// Calculates 1/√(number) +const invertSqrt = (number) => uvRatio(_1n, number); +const MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const bytes255ToNumberLE = (bytes) => exports.ed25519.CURVE.Fp.create((0, utils_js_1.bytesToNumberLE)(bytes) & MAX_255B); +// Computes Elligator map for Ristretto +// https://ristretto.group/formulas/elligator.html +function calcElligatorRistrettoMap(r0) { + const { d } = exports.ed25519.CURVE; + const P = exports.ed25519.CURVE.Fp.ORDER; + const mod = exports.ed25519.CURVE.Fp.create; + const r = mod(SQRT_M1 * r0 * r0); // 1 + const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2 + let c = BigInt(-1); // 3 + const D = mod((c - d * r) * mod(r + d)); // 4 + let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5 + let s_ = mod(s * r0); // 6 + if (!(0, modular_js_1.isNegativeLE)(s_, P)) + s_ = mod(-s_); + if (!Ns_D_is_sq) + s = s_; // 7 + if (!Ns_D_is_sq) + c = r; // 8 + const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9 + const s2 = s * s; + const W0 = mod((s + s) * D); // 10 + const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11 + const W2 = mod(_1n - s2); // 12 + const W3 = mod(_1n + s2); // 13 + return new exports.ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2)); +} +/** + * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Ristretto was created to solve this. + * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +class RistPoint { + // Private property to discourage combining ExtendedPoint + RistrettoPoint + // Always use Ristretto encoding/decoding instead. + constructor(ep) { + this.ep = ep; + } + static fromAffine(ap) { + return new RistPoint(exports.ed25519.ExtendedPoint.fromAffine(ap)); + } + /** + * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://ristretto.group/formulas/elligator.html + * @param hex 64-byte output of a hash function + */ + static hashToCurve(hex) { + hex = (0, utils_js_1.ensureBytes)('ristrettoHash', hex, 64); + const r1 = bytes255ToNumberLE(hex.slice(0, 32)); + const R1 = calcElligatorRistrettoMap(r1); + const r2 = bytes255ToNumberLE(hex.slice(32, 64)); + const R2 = calcElligatorRistrettoMap(r2); + return new RistPoint(R1.add(R2)); + } + /** + * Converts ristretto-encoded string to ristretto point. + * https://ristretto.group/formulas/decoding.html + * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding + */ + static fromHex(hex) { + hex = (0, utils_js_1.ensureBytes)('ristrettoHex', hex, 32); + const { a, d } = exports.ed25519.CURVE; + const P = exports.ed25519.CURVE.Fp.ORDER; + const mod = exports.ed25519.CURVE.Fp.create; + const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint'; + const s = bytes255ToNumberLE(hex); + // 1. Check that s_bytes is the canonical encoding of a field element, or else abort. + // 3. Check that s is non-negative, or else abort + if (!(0, utils_js_1.equalBytes)((0, utils_js_1.numberToBytesLE)(s, 32), hex) || (0, modular_js_1.isNegativeLE)(s, P)) + throw new Error(emsg); + const s2 = mod(s * s); + const u1 = mod(_1n + a * s2); // 4 (a is -1) + const u2 = mod(_1n - a * s2); // 5 + const u1_2 = mod(u1 * u1); + const u2_2 = mod(u2 * u2); + const v = mod(a * d * u1_2 - u2_2); // 6 + const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7 + const Dx = mod(I * u2); // 8 + const Dy = mod(I * Dx * v); // 9 + let x = mod((s + s) * Dx); // 10 + if ((0, modular_js_1.isNegativeLE)(x, P)) + x = mod(-x); // 10 + const y = mod(u1 * Dy); // 11 + const t = mod(x * y); // 12 + if (!isValid || (0, modular_js_1.isNegativeLE)(t, P) || y === _0n) + throw new Error(emsg); + return new RistPoint(new exports.ed25519.ExtendedPoint(x, y, _1n, t)); + } + /** + * Encodes ristretto point to Uint8Array. + * https://ristretto.group/formulas/encoding.html + */ + toRawBytes() { + let { ex: x, ey: y, ez: z, et: t } = this.ep; + const P = exports.ed25519.CURVE.Fp.ORDER; + const mod = exports.ed25519.CURVE.Fp.create; + const u1 = mod(mod(z + y) * mod(z - y)); // 1 + const u2 = mod(x * y); // 2 + // Square root always exists + const u2sq = mod(u2 * u2); + const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3 + const D1 = mod(invsqrt * u1); // 4 + const D2 = mod(invsqrt * u2); // 5 + const zInv = mod(D1 * D2 * t); // 6 + let D; // 7 + if ((0, modular_js_1.isNegativeLE)(t * zInv, P)) { + let _x = mod(y * SQRT_M1); + let _y = mod(x * SQRT_M1); + x = _x; + y = _y; + D = mod(D1 * INVSQRT_A_MINUS_D); + } + else { + D = D2; // 8 + } + if ((0, modular_js_1.isNegativeLE)(x * zInv, P)) + y = mod(-y); // 9 + let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a)) + if ((0, modular_js_1.isNegativeLE)(s, P)) + s = mod(-s); + return (0, utils_js_1.numberToBytesLE)(s, 32); // 11 + } + toHex() { + return (0, utils_js_1.bytesToHex)(this.toRawBytes()); + } + toString() { + return this.toHex(); + } + // Compare one point to another. + equals(other) { + assertRstPoint(other); + const { ex: X1, ey: Y1 } = this.ep; + const { ex: X2, ey: Y2 } = other.ep; + const mod = exports.ed25519.CURVE.Fp.create; + // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2) + const one = mod(X1 * Y2) === mod(Y1 * X2); + const two = mod(Y1 * Y2) === mod(X1 * X2); + return one || two; + } + add(other) { + assertRstPoint(other); + return new RistPoint(this.ep.add(other.ep)); + } + subtract(other) { + assertRstPoint(other); + return new RistPoint(this.ep.subtract(other.ep)); + } + multiply(scalar) { + return new RistPoint(this.ep.multiply(scalar)); + } + multiplyUnsafe(scalar) { + return new RistPoint(this.ep.multiplyUnsafe(scalar)); + } +} +exports.RistrettoPoint = (() => { + if (!RistPoint.BASE) + RistPoint.BASE = new RistPoint(exports.ed25519.ExtendedPoint.BASE); + if (!RistPoint.ZERO) + RistPoint.ZERO = new RistPoint(exports.ed25519.ExtendedPoint.ZERO); + return RistPoint; +})(); +// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B +const hashToRistretto255 = (msg, options) => { + const d = options.DST; + const DST = typeof d === 'string' ? (0, utils_1.utf8ToBytes)(d) : d; + const uniform_bytes = (0, hash_to_curve_js_1.expand_message_xmd)(msg, DST, 64, sha512_1.sha512); + const P = RistPoint.hashToCurve(uniform_bytes); + return P; +}; +exports.hashToRistretto255 = hashToRistretto255; +exports.hash_to_ristretto255 = exports.hashToRistretto255; // legacy +//# sourceMappingURL=ed25519.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/ed25519.js.map b/node_modules/@noble/curves/ed25519.js.map new file mode 100644 index 0000000..af44c8d --- /dev/null +++ b/node_modules/@noble/curves/ed25519.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ed25519.js","sourceRoot":"","sources":["src/ed25519.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,iDAA8C;AAC9C,+CAA4E;AAC5E,sDAAqE;AACrE,4DAAsD;AACtD,sDAAmF;AACnF,kDAO6B;AAC7B,kEAA6F;AAG7F;;;;;GAKG;AAEH,MAAM,SAAS,GAAG,MAAM,CACtB,+EAA+E,CAChF,CAAC;AACF,iCAAiC;AACjC,MAAM,eAAe,GAAG,MAAM,CAC5B,+EAA+E,CAChF,CAAC;AAEF,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACzE,kBAAkB;AAClB,MAAM,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;AAEjF,SAAS,mBAAmB,CAAC,CAAS;IACpC,MAAM,CAAC,GAAG,SAAS,CAAC;IACpB,MAAM,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IACvB,MAAM,EAAE,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,UAAU;IACnC,MAAM,EAAE,GAAG,CAAC,IAAA,iBAAI,EAAC,EAAE,EAAE,GAAG,EAAE,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,aAAa;IACrD,MAAM,EAAE,GAAG,CAAC,IAAA,iBAAI,EAAC,EAAE,E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I,CAAC,EAAE,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAC;IACvD,CAAC;CACF;AACY,QAAA,cAAc,GAAmB,CAAC,GAAG,EAAE;IAClD,IAAI,CAAC,SAAS,CAAC,IAAI;QAAE,SAAS,CAAC,IAAI,GAAG,IAAI,SAAS,CAAC,eAAO,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;IAChF,IAAI,CAAC,SAAS,CAAC,IAAI;QAAE,SAAS,CAAC,IAAI,GAAG,IAAI,SAAS,CAAC,eAAO,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;IAChF,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC,EAAE,CAAC;AAEL,6EAA6E;AACtE,MAAM,kBAAkB,GAAG,CAAC,GAAe,EAAE,OAAqB,EAAE,EAAE;IAC3E,MAAM,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC;IACtB,MAAM,GAAG,GAAG,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAA,mBAAW,EAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACvD,MAAM,aAAa,GAAG,IAAA,qCAAkB,EAAC,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,eAAM,CAAC,CAAC;IAC/D,MAAM,CAAC,GAAG,SAAS,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC;IAC/C,OAAO,CAAC,CAAC;AACX,CAAC,CAAC;AANW,QAAA,kBAAkB,sBAM7B;AACW,QAAA,oBAAoB,GAAG,0BAAkB,CAAC,CAAC,SAAS"} \ No newline at end of file diff --git a/node_modules/@noble/curves/ed448.d.ts b/node_modules/@noble/curves/ed448.d.ts new file mode 100644 index 0000000..3523c71 --- /dev/null +++ b/node_modules/@noble/curves/ed448.d.ts @@ -0,0 +1,65 @@ +import { ExtPointType } from './abstract/edwards.js'; +import { htfBasicOpts } from './abstract/hash-to-curve.js'; +import { Hex } from './abstract/utils.js'; +import { AffinePoint } from './abstract/curve.js'; +export declare const ed448: import("./abstract/edwards.js").CurveFn; +export declare const ed448ph: import("./abstract/edwards.js").CurveFn; +export declare const x448: import("./abstract/montgomery.js").CurveFn; +/** + * Converts edwards448 public key to x448 public key. Uses formula: + * * `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)` + * * `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))` + * @example + * const aPub = ed448.getPublicKey(utils.randomPrivateKey()); + * x448.getSharedSecret(edwardsToMontgomery(aPub), edwardsToMontgomery(someonesPub)) + */ +export declare function edwardsToMontgomeryPub(edwardsPub: string | Uint8Array): Uint8Array; +export declare const edwardsToMontgomery: typeof edwardsToMontgomeryPub; +export declare const hashToCurve: (msg: Uint8Array, options?: htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +type ExtendedPoint = ExtPointType; +/** + * Each ed448/ExtendedPoint has 4 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Decaf was created to solve this. + * Decaf point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +declare class DcfPoint { + private readonly ep; + static BASE: DcfPoint; + static ZERO: DcfPoint; + constructor(ep: ExtendedPoint); + static fromAffine(ap: AffinePoint): DcfPoint; + /** + * Takes uniform output of 112-byte hash function like shake256 and converts it to `DecafPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2 + * @param hex 112-byte output of a hash function + */ + static hashToCurve(hex: Hex): DcfPoint; + /** + * Converts decaf-encoded string to decaf point. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-decode-2 + * @param hex Decaf-encoded 56 bytes. Not every 56-byte string is valid decaf encoding + */ + static fromHex(hex: Hex): DcfPoint; + /** + * Encodes decaf point to Uint8Array. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-encode-2 + */ + toRawBytes(): Uint8Array; + toHex(): string; + toString(): string; + equals(other: DcfPoint): boolean; + add(other: DcfPoint): DcfPoint; + subtract(other: DcfPoint): DcfPoint; + multiply(scalar: bigint): DcfPoint; + multiplyUnsafe(scalar: bigint): DcfPoint; +} +export declare const DecafPoint: typeof DcfPoint; +export declare const hashToDecaf448: (msg: Uint8Array, options: htfBasicOpts) => DcfPoint; +export declare const hash_to_decaf448: (msg: Uint8Array, options: htfBasicOpts) => DcfPoint; +export {}; +//# sourceMappingURL=ed448.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/ed448.d.ts.map b/node_modules/@noble/curves/ed448.d.ts.map new file mode 100644 index 0000000..caf0ca0 --- /dev/null +++ b/node_modules/@noble/curves/ed448.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ed448.d.ts","sourceRoot":"","sources":["src/ed448.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,YAAY,EAAkB,MAAM,uBAAuB,CAAC;AAGrE,OAAO,EAAgB,YAAY,EAAsB,MAAM,6BAA6B,CAAC;AAC7F,OAAO,EAKL,GAAG,EAEJ,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAqHlD,eAAO,MAAM,KAAK,yCAA4C,CAAC;AAE/D,eAAO,MAAM,OAAO,yCAAyE,CAAC;AAE9F,eAAO,MAAM,IAAI,4CAeV,CAAC;AAER;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,MAAM,GAAG,UAAU,GAAG,UAAU,CAIlF;AACD,eAAO,MAAM,mBAAmB,+BAAyB,CAAC;AA2F1D,eAAO,MAAM,WAAW,iHAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,iHAA8C,CAAC;AA2BzE,KAAK,aAAa,GAAG,YAAY,CAAC;AAiClC;;;;;;GAMG;AACH,cAAM,QAAQ;IAKA,OAAO,CAAC,QAAQ,CAAC,EAAE;IAJ/B,MAAM,CAAC,IAAI,EAAE,QAAQ,CAAC;IACtB,MAAM,CAAC,IAAI,EAAE,QAAQ,CAAC;gBAGO,EAAE,EAAE,aAAa;IAE9C,MAAM,CAAC,UAAU,CAAC,EAAE,EAAE,WAAW,CAAC,MAAM,CAAC;IAIzC;;;;;;OAMG;IACH,MAAM,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,GAAG,QAAQ;IAStC;;;;OAIG;IACH,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,GAAG,GAAG,QAAQ;IA8BlC;;;OAGG;IACH,UAAU,IAAI,UAAU;IAoBxB,KAAK,IAAI,MAAM;IAIf,QAAQ,IAAI,MAAM;IAMlB,MAAM,CAAC,KAAK,EAAE,QAAQ,GAAG,OAAO;IAShC,GAAG,CAAC,KAAK,EAAE,QAAQ,GAAG,QAAQ;IAK9B,QAAQ,CAAC,KAAK,EAAE,QAAQ,GAAG,QAAQ;IAKnC,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,QAAQ;IAIlC,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,QAAQ;CAGzC;AACD,eAAO,MAAM,UAAU,iBAMnB,CAAC;AAGL,eAAO,MAAM,cAAc,QAAS,UAAU,WAAW,YAAY,aAMpE,CAAC;AACF,eAAO,MAAM,gBAAgB,QAPO,UAAU,WAAW,YAAY,aAOvB,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/ed448.js b/node_modules/@noble/curves/ed448.js new file mode 100644 index 0000000..3eafbd5 --- /dev/null +++ b/node_modules/@noble/curves/ed448.js @@ -0,0 +1,397 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hash_to_decaf448 = exports.hashToDecaf448 = exports.DecafPoint = exports.encodeToCurve = exports.hashToCurve = exports.edwardsToMontgomery = exports.edwardsToMontgomeryPub = exports.x448 = exports.ed448ph = exports.ed448 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha3_1 = require("@noble/hashes/sha3"); +const utils_1 = require("@noble/hashes/utils"); +const edwards_js_1 = require("./abstract/edwards.js"); +const modular_js_1 = require("./abstract/modular.js"); +const montgomery_js_1 = require("./abstract/montgomery.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +const utils_js_1 = require("./abstract/utils.js"); +/** + * Edwards448 (not Ed448-Goldilocks) curve with following addons: + * - X448 ECDH + * - Decaf cofactor elimination + * - Elligator hash-to-group / point indistinguishability + * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2 + */ +const shake256_114 = (0, utils_1.wrapConstructor)(() => sha3_1.shake256.create({ dkLen: 114 })); +const shake256_64 = (0, utils_1.wrapConstructor)(() => sha3_1.shake256.create({ dkLen: 64 })); +const ed448P = BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439'); +// prettier-ignore +const _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4), _11n = BigInt(11); +// prettier-ignore +const _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223); +// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4. +// Used for efficient square root calculation. +// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1] +function ed448_pow_Pminus3div4(x) { + const P = ed448P; + const b2 = (x * x * x) % P; + const b3 = (b2 * b2 * x) % P; + const b6 = ((0, modular_js_1.pow2)(b3, _3n, P) * b3) % P; + const b9 = ((0, modular_js_1.pow2)(b6, _3n, P) * b3) % P; + const b11 = ((0, modular_js_1.pow2)(b9, _2n, P) * b2) % P; + const b22 = ((0, modular_js_1.pow2)(b11, _11n, P) * b11) % P; + const b44 = ((0, modular_js_1.pow2)(b22, _22n, P) * b22) % P; + const b88 = ((0, modular_js_1.pow2)(b44, _44n, P) * b44) % P; + const b176 = ((0, modular_js_1.pow2)(b88, _88n, P) * b88) % P; + const b220 = ((0, modular_js_1.pow2)(b176, _44n, P) * b44) % P; + const b222 = ((0, modular_js_1.pow2)(b220, _2n, P) * b2) % P; + const b223 = ((0, modular_js_1.pow2)(b222, _1n, P) * x) % P; + return ((0, modular_js_1.pow2)(b223, _223n, P) * b222) % P; +} +function adjustScalarBytes(bytes) { + // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, and the most + // significant bit of the last byte to 1. + bytes[0] &= 252; // 0b11111100 + // and the most significant bit of the last byte to 1. + bytes[55] |= 128; // 0b10000000 + // NOTE: is is NOOP for 56 bytes scalars (X25519/X448) + bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits) + return bytes; +} +// Constant-time ratio of u to v. Allows to combine inversion and square root u/√v. +// Uses algo from RFC8032 5.1.3. +function uvRatio(u, v) { + const P = ed448P; + // https://www.rfc-editor.org/rfc/rfc8032#section-5.2.3 + // To compute the square root of (u/v), the first step is to compute the + // candidate root x = (u/v)^((p+1)/4). This can be done using the + // following trick, to use a single modular powering for both the + // inversion of v and the square root: + // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p) + const u2v = (0, modular_js_1.mod)(u * u * v, P); // u²v + const u3v = (0, modular_js_1.mod)(u2v * u, P); // u³v + const u5v3 = (0, modular_js_1.mod)(u3v * u2v * v, P); // u⁵v³ + const root = ed448_pow_Pminus3div4(u5v3); + const x = (0, modular_js_1.mod)(u3v * root, P); + // Verify that root is exists + const x2 = (0, modular_js_1.mod)(x * x, P); // x² + // If vx² = u, the recovered x-coordinate is x. Otherwise, no + // square root exists, and the decoding fails. + return { isValid: (0, modular_js_1.mod)(x2 * v, P) === u, value: x }; +} +const Fp = (0, modular_js_1.Field)(ed448P, 456, true); +const ED448_DEF = { + // Param: a + a: BigInt(1), + // -39081. Negative number is P - number + d: BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358'), + // Finite field 𝔽p over which we'll do calculations; 2n**448n - 2n**224n - 1n + Fp, + // Subgroup order: how many points curve has; + // 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n + n: BigInt('181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779'), + nBitLength: 456, + // Cofactor + h: BigInt(4), + // Base point (x, y) aka generator point + Gx: BigInt('224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710'), + Gy: BigInt('298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660'), + // SHAKE256(dom4(phflag,context)||x, 114) + hash: shake256_114, + randomBytes: utils_1.randomBytes, + adjustScalarBytes, + // dom4 + domain: (data, ctx, phflag) => { + if (ctx.length > 255) + throw new Error(`Context is too big: ${ctx.length}`); + return (0, utils_1.concatBytes)((0, utils_1.utf8ToBytes)('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); + }, + uvRatio, +}; +exports.ed448 = (0, edwards_js_1.twistedEdwards)(ED448_DEF); +// NOTE: there is no ed448ctx, since ed448 supports ctx by default +exports.ed448ph = (0, edwards_js_1.twistedEdwards)({ ...ED448_DEF, prehash: shake256_64 }); +exports.x448 = (() => (0, montgomery_js_1.montgomery)({ + a: BigInt(156326), + montgomeryBits: 448, + nByteLength: 57, + P: ed448P, + Gu: BigInt(5), + powPminus2: (x) => { + const P = ed448P; + const Pminus3div4 = ed448_pow_Pminus3div4(x); + const Pminus3 = (0, modular_js_1.pow2)(Pminus3div4, BigInt(2), P); + return (0, modular_js_1.mod)(Pminus3 * x, P); // Pminus3 * x = Pminus2 + }, + adjustScalarBytes, + randomBytes: utils_1.randomBytes, +}))(); +/** + * Converts edwards448 public key to x448 public key. Uses formula: + * * `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)` + * * `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))` + * @example + * const aPub = ed448.getPublicKey(utils.randomPrivateKey()); + * x448.getSharedSecret(edwardsToMontgomery(aPub), edwardsToMontgomery(someonesPub)) + */ +function edwardsToMontgomeryPub(edwardsPub) { + const { y } = exports.ed448.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((y - _1n) * Fp.inv(y + _1n))); +} +exports.edwardsToMontgomeryPub = edwardsToMontgomeryPub; +exports.edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated +// Hash To Curve Elligator2 Map +const ELL2_C1 = (Fp.ORDER - BigInt(3)) / BigInt(4); // 1. c1 = (q - 3) / 4 # Integer arithmetic +const ELL2_J = BigInt(156326); +function map_to_curve_elligator2_curve448(u) { + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + let e1 = Fp.eql(tv1, Fp.ONE); // 2. e1 = tv1 == 1 + tv1 = Fp.cmov(tv1, Fp.ZERO, e1); // 3. tv1 = CMOV(tv1, 0, e1) # If Z * u^2 == -1, set tv1 = 0 + let xd = Fp.sub(Fp.ONE, tv1); // 4. xd = 1 - tv1 + let x1n = Fp.neg(ELL2_J); // 5. x1n = -J + let tv2 = Fp.sqr(xd); // 6. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 7. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, Fp.neg(ELL2_J)); // 8. gx1 = -J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 9. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 10. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 11. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 12. tv3 = gxd^2 + tv2 = Fp.mul(gx1, gxd); // 13. tv2 = gx1 * gxd # gx1 * gxd + tv3 = Fp.mul(tv3, tv2); // 14. tv3 = tv3 * tv2 # gx1 * gxd^3 + let y1 = Fp.pow(tv3, ELL2_C1); // 15. y1 = tv3^c1 # (gx1 * gxd^3)^((p - 3) / 4) + y1 = Fp.mul(y1, tv2); // 16. y1 = y1 * tv2 # gx1 * gxd * (gx1 * gxd^3)^((p - 3) / 4) + let x2n = Fp.mul(x1n, Fp.neg(tv1)); // 17. x2n = -tv1 * x1n # x2 = x2n / xd = -1 * u^2 * x1n / xd + let y2 = Fp.mul(y1, u); // 18. y2 = y1 * u + y2 = Fp.cmov(y2, Fp.ZERO, e1); // 19. y2 = CMOV(y2, 0, e1) + tv2 = Fp.sqr(y1); // 20. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 21. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx1); // 22. e2 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e2); // 23. xn = CMOV(x2n, x1n, e2) # If e2, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e2); // 24. y = CMOV(y2, y1, e2) # If e2, y = y1, else y = y2 + let e3 = Fp.isOdd(y); // 25. e3 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e2 !== e3); // 26. y = CMOV(y, -y, e2 XOR e3) + return { xn, xd, yn: y, yd: Fp.ONE }; // 27. return (xn, xd, y, 1) +} +function map_to_curve_elligator2_edwards448(u) { + let { xn, xd, yn, yd } = map_to_curve_elligator2_curve448(u); // 1. (xn, xd, yn, yd) = map_to_curve_elligator2_curve448(u) + let xn2 = Fp.sqr(xn); // 2. xn2 = xn^2 + let xd2 = Fp.sqr(xd); // 3. xd2 = xd^2 + let xd4 = Fp.sqr(xd2); // 4. xd4 = xd2^2 + let yn2 = Fp.sqr(yn); // 5. yn2 = yn^2 + let yd2 = Fp.sqr(yd); // 6. yd2 = yd^2 + let xEn = Fp.sub(xn2, xd2); // 7. xEn = xn2 - xd2 + let tv2 = Fp.sub(xEn, xd2); // 8. tv2 = xEn - xd2 + xEn = Fp.mul(xEn, xd2); // 9. xEn = xEn * xd2 + xEn = Fp.mul(xEn, yd); // 10. xEn = xEn * yd + xEn = Fp.mul(xEn, yn); // 11. xEn = xEn * yn + xEn = Fp.mul(xEn, _4n); // 12. xEn = xEn * 4 + tv2 = Fp.mul(tv2, xn2); // 13. tv2 = tv2 * xn2 + tv2 = Fp.mul(tv2, yd2); // 14. tv2 = tv2 * yd2 + let tv3 = Fp.mul(yn2, _4n); // 15. tv3 = 4 * yn2 + let tv1 = Fp.add(tv3, yd2); // 16. tv1 = tv3 + yd2 + tv1 = Fp.mul(tv1, xd4); // 17. tv1 = tv1 * xd4 + let xEd = Fp.add(tv1, tv2); // 18. xEd = tv1 + tv2 + tv2 = Fp.mul(tv2, xn); // 19. tv2 = tv2 * xn + let tv4 = Fp.mul(xn, xd4); // 20. tv4 = xn * xd4 + let yEn = Fp.sub(tv3, yd2); // 21. yEn = tv3 - yd2 + yEn = Fp.mul(yEn, tv4); // 22. yEn = yEn * tv4 + yEn = Fp.sub(yEn, tv2); // 23. yEn = yEn - tv2 + tv1 = Fp.add(xn2, xd2); // 24. tv1 = xn2 + xd2 + tv1 = Fp.mul(tv1, xd2); // 25. tv1 = tv1 * xd2 + tv1 = Fp.mul(tv1, xd); // 26. tv1 = tv1 * xd + tv1 = Fp.mul(tv1, yn2); // 27. tv1 = tv1 * yn2 + tv1 = Fp.mul(tv1, BigInt(-2)); // 28. tv1 = -2 * tv1 + let yEd = Fp.add(tv2, tv1); // 29. yEd = tv2 + tv1 + tv4 = Fp.mul(tv4, yd2); // 30. tv4 = tv4 * yd2 + yEd = Fp.add(yEd, tv4); // 31. yEd = yEd + tv4 + tv1 = Fp.mul(xEd, yEd); // 32. tv1 = xEd * yEd + let e = Fp.eql(tv1, Fp.ZERO); // 33. e = tv1 == 0 + xEn = Fp.cmov(xEn, Fp.ZERO, e); // 34. xEn = CMOV(xEn, 0, e) + xEd = Fp.cmov(xEd, Fp.ONE, e); // 35. xEd = CMOV(xEd, 1, e) + yEn = Fp.cmov(yEn, Fp.ONE, e); // 36. yEn = CMOV(yEn, 1, e) + yEd = Fp.cmov(yEd, Fp.ONE, e); // 37. yEd = CMOV(yEd, 1, e) + const inv = Fp.invertBatch([xEd, yEd]); // batch division + return { x: Fp.mul(xEn, inv[0]), y: Fp.mul(yEn, inv[1]) }; // 38. return (xEn, xEd, yEn, yEd) +} +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.ed448.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards448(scalars[0]), { + DST: 'edwards448_XOF:SHAKE256_ELL2_RO_', + encodeDST: 'edwards448_XOF:SHAKE256_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 224, + expand: 'xof', + hash: sha3_1.shake256, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +function assertDcfPoint(other) { + if (!(other instanceof DcfPoint)) + throw new Error('DecafPoint expected'); +} +// 1-d +const ONE_MINUS_D = BigInt('39082'); +// 1-2d +const ONE_MINUS_TWO_D = BigInt('78163'); +// √(-d) +const SQRT_MINUS_D = BigInt('98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214'); +// 1 / √(-d) +const INVSQRT_MINUS_D = BigInt('315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716'); +// Calculates 1/√(number) +const invertSqrt = (number) => uvRatio(_1n, number); +const MAX_448B = BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const bytes448ToNumberLE = (bytes) => exports.ed448.CURVE.Fp.create((0, utils_js_1.bytesToNumberLE)(bytes) & MAX_448B); +// Computes Elligator map for Decaf +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2 +function calcElligatorDecafMap(r0) { + const { d } = exports.ed448.CURVE; + const P = exports.ed448.CURVE.Fp.ORDER; + const mod = exports.ed448.CURVE.Fp.create; + const r = mod(-(r0 * r0)); // 1 + const u0 = mod(d * (r - _1n)); // 2 + const u1 = mod((u0 + _1n) * (u0 - r)); // 3 + const { isValid: was_square, value: v } = uvRatio(ONE_MINUS_TWO_D, mod((r + _1n) * u1)); // 4 + let v_prime = v; // 5 + if (!was_square) + v_prime = mod(r0 * v); + let sgn = _1n; // 6 + if (!was_square) + sgn = mod(-_1n); + const s = mod(v_prime * (r + _1n)); // 7 + let s_abs = s; + if ((0, modular_js_1.isNegativeLE)(s, P)) + s_abs = mod(-s); + const s2 = s * s; + const W0 = mod(s_abs * _2n); // 8 + const W1 = mod(s2 + _1n); // 9 + const W2 = mod(s2 - _1n); // 10 + const W3 = mod(v_prime * s * (r - _1n) * ONE_MINUS_TWO_D + sgn); // 11 + return new exports.ed448.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2)); +} +/** + * Each ed448/ExtendedPoint has 4 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Decaf was created to solve this. + * Decaf point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +class DcfPoint { + // Private property to discourage combining ExtendedPoint + DecafPoint + // Always use Decaf encoding/decoding instead. + constructor(ep) { + this.ep = ep; + } + static fromAffine(ap) { + return new DcfPoint(exports.ed448.ExtendedPoint.fromAffine(ap)); + } + /** + * Takes uniform output of 112-byte hash function like shake256 and converts it to `DecafPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2 + * @param hex 112-byte output of a hash function + */ + static hashToCurve(hex) { + hex = (0, utils_js_1.ensureBytes)('decafHash', hex, 112); + const r1 = bytes448ToNumberLE(hex.slice(0, 56)); + const R1 = calcElligatorDecafMap(r1); + const r2 = bytes448ToNumberLE(hex.slice(56, 112)); + const R2 = calcElligatorDecafMap(r2); + return new DcfPoint(R1.add(R2)); + } + /** + * Converts decaf-encoded string to decaf point. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-decode-2 + * @param hex Decaf-encoded 56 bytes. Not every 56-byte string is valid decaf encoding + */ + static fromHex(hex) { + hex = (0, utils_js_1.ensureBytes)('decafHex', hex, 56); + const { d } = exports.ed448.CURVE; + const P = exports.ed448.CURVE.Fp.ORDER; + const mod = exports.ed448.CURVE.Fp.create; + const emsg = 'DecafPoint.fromHex: the hex is not valid encoding of DecafPoint'; + const s = bytes448ToNumberLE(hex); + // 1. Check that s_bytes is the canonical encoding of a field element, or else abort. + // 2. Check that s is non-negative, or else abort + if (!(0, utils_js_1.equalBytes)((0, utils_js_1.numberToBytesLE)(s, 56), hex) || (0, modular_js_1.isNegativeLE)(s, P)) + throw new Error(emsg); + const s2 = mod(s * s); // 1 + const u1 = mod(_1n + s2); // 2 + const u1sq = mod(u1 * u1); + const u2 = mod(u1sq - _4n * d * s2); // 3 + const { isValid, value: invsqrt } = invertSqrt(mod(u2 * u1sq)); // 4 + let u3 = mod((s + s) * invsqrt * u1 * SQRT_MINUS_D); // 5 + if ((0, modular_js_1.isNegativeLE)(u3, P)) + u3 = mod(-u3); + const x = mod(u3 * invsqrt * u2 * INVSQRT_MINUS_D); // 6 + const y = mod((_1n - s2) * invsqrt * u1); // 7 + const t = mod(x * y); // 8 + if (!isValid) + throw new Error(emsg); + return new DcfPoint(new exports.ed448.ExtendedPoint(x, y, _1n, t)); + } + /** + * Encodes decaf point to Uint8Array. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-encode-2 + */ + toRawBytes() { + let { ex: x, ey: _y, ez: z, et: t } = this.ep; + const P = exports.ed448.CURVE.Fp.ORDER; + const mod = exports.ed448.CURVE.Fp.create; + const u1 = mod(mod(x + t) * mod(x - t)); // 1 + const x2 = mod(x * x); + const { value: invsqrt } = invertSqrt(mod(u1 * ONE_MINUS_D * x2)); // 2 + let ratio = mod(invsqrt * u1 * SQRT_MINUS_D); // 3 + if ((0, modular_js_1.isNegativeLE)(ratio, P)) + ratio = mod(-ratio); + const u2 = mod(INVSQRT_MINUS_D * ratio * z - t); // 4 + let s = mod(ONE_MINUS_D * invsqrt * x * u2); // 5 + if ((0, modular_js_1.isNegativeLE)(s, P)) + s = mod(-s); + return (0, utils_js_1.numberToBytesLE)(s, 56); + } + toHex() { + return (0, utils_js_1.bytesToHex)(this.toRawBytes()); + } + toString() { + return this.toHex(); + } + // Compare one point to another. + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-equals-2 + equals(other) { + assertDcfPoint(other); + const { ex: X1, ey: Y1 } = this.ep; + const { ex: X2, ey: Y2 } = other.ep; + const mod = exports.ed448.CURVE.Fp.create; + // (x1 * y2 == y1 * x2) + return mod(X1 * Y2) === mod(Y1 * X2); + } + add(other) { + assertDcfPoint(other); + return new DcfPoint(this.ep.add(other.ep)); + } + subtract(other) { + assertDcfPoint(other); + return new DcfPoint(this.ep.subtract(other.ep)); + } + multiply(scalar) { + return new DcfPoint(this.ep.multiply(scalar)); + } + multiplyUnsafe(scalar) { + return new DcfPoint(this.ep.multiplyUnsafe(scalar)); + } +} +exports.DecafPoint = (() => { + // decaf448 base point is ed448 base x 2 + // https://github.com/dalek-cryptography/curve25519-dalek/blob/59837c6ecff02b77b9d5ff84dbc239d0cf33ef90/vendor/ristretto.sage#L699 + if (!DcfPoint.BASE) + DcfPoint.BASE = new DcfPoint(exports.ed448.ExtendedPoint.BASE).multiply(_2n); + if (!DcfPoint.ZERO) + DcfPoint.ZERO = new DcfPoint(exports.ed448.ExtendedPoint.ZERO); + return DcfPoint; +})(); +// Hashing to decaf448. https://www.rfc-editor.org/rfc/rfc9380#appendix-C +const hashToDecaf448 = (msg, options) => { + const d = options.DST; + const DST = typeof d === 'string' ? (0, utils_1.utf8ToBytes)(d) : d; + const uniform_bytes = (0, hash_to_curve_js_1.expand_message_xof)(msg, DST, 112, 224, sha3_1.shake256); + const P = DcfPoint.hashToCurve(uniform_bytes); + return P; +}; +exports.hashToDecaf448 = hashToDecaf448; +exports.hash_to_decaf448 = exports.hashToDecaf448; // legacy +//# sourceMappingURL=ed448.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/ed448.js.map b/node_modules/@noble/curves/ed448.js.map new file mode 100644 index 0000000..7a939a4 --- /dev/null +++ b/node_modules/@noble/curves/ed448.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ed448.js","sourceRoot":"","sources":["src/ed448.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,6CAA8C;AAC9C,+CAA6F;AAC7F,sDAAqE;AACrE,sDAAuE;AACvE,4DAAsD;AACtD,kEAA6F;AAC7F,kDAO6B;AAG7B;;;;;;GAMG;AAEH,MAAM,YAAY,GAAG,IAAA,uBAAe,EAAC,GAAG,EAAE,CAAC,eAAQ,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;AAC5E,MAAM,WAAW,GAAG,IAAA,uBAAe,EAAC,GAAG,EAAE,CAAC,eAAQ,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC;AAC1E,MAAM,MAAM,GAAG,MAAM,CACnB,yIAAyI,CAC1I,CAAC;AAEF,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;AAC5F,kBAAkB;AAClB,MAAM,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,EAAE,IAAI,GAA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,CAAC;IACvD,MAAM,aAAa,GAAG,IAAA,qCAAkB,EAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,eAAQ,CAAC,CAAC;IACvE,MAAM,CAAC,GAAG,QAAQ,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC;IAC9C,OAAO,CAAC,CAAC;AACX,CAAC,CAAC;AANW,QAAA,cAAc,kBAMzB;AACW,QAAA,gBAAgB,GAAG,sBAAc,CAAC,CAAC,SAAS"} \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/_shortw_utils.js b/node_modules/@noble/curves/esm/_shortw_utils.js new file mode 100644 index 0000000..cc93e45 --- /dev/null +++ b/node_modules/@noble/curves/esm/_shortw_utils.js @@ -0,0 +1,17 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { hmac } from '@noble/hashes/hmac'; +import { concatBytes, randomBytes } from '@noble/hashes/utils'; +import { weierstrass } from './abstract/weierstrass.js'; +// connects noble-curves to noble-hashes +export function getHash(hash) { + return { + hash, + hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)), + randomBytes, + }; +} +export function createCurve(curveDef, defHash) { + const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) }); + return Object.freeze({ ...create(defHash), create }); +} +//# sourceMappingURL=_shortw_utils.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/_shortw_utils.js.map b/node_modules/@noble/curves/esm/_shortw_utils.js.map new file mode 100644 index 0000000..656ee45 --- /dev/null +++ b/node_modules/@noble/curves/esm/_shortw_utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_shortw_utils.js","sourceRoot":"","sources":["../src/_shortw_utils.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAa,MAAM,2BAA2B,CAAC;AAGnE,wCAAwC;AACxC,MAAM,UAAU,OAAO,CAAC,IAAW;IACjC,OAAO;QACL,IAAI;QACJ,IAAI,EAAE,CAAC,GAAe,EAAE,GAAG,IAAkB,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,EAAE,WAAW,CAAC,GAAG,IAAI,CAAC,CAAC;QACvF,WAAW;KACZ,CAAC;AACJ,CAAC;AAGD,MAAM,UAAU,WAAW,CAAC,QAAkB,EAAE,OAAc;IAC5D,MAAM,MAAM,GAAG,CAAC,IAAW,EAAE,EAAE,CAAC,WAAW,CAAC,EAAE,GAAG,QAAQ,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAC/E,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,MAAM,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;AACvD,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/abstract/bls.js b/node_modules/@noble/curves/esm/abstract/bls.js new file mode 100644 index 0000000..290d651 --- /dev/null +++ b/node_modules/@noble/curves/esm/abstract/bls.js @@ -0,0 +1,235 @@ +import { getMinHashLength, mapHashToField } from './modular.js'; +import { bitLen, bitGet, ensureBytes } from './utils.js'; +import * as htf from './hash-to-curve.js'; +import { weierstrassPoints, } from './weierstrass.js'; +// prettier-ignore +const _2n = BigInt(2), _3n = BigInt(3); +export function bls(CURVE) { + // Fields are specific for curve, so for now we'll need to pass them with opts + const { Fp, Fr, Fp2, Fp6, Fp12 } = CURVE.fields; + const BLS_X_LEN = bitLen(CURVE.params.x); + // Pre-compute coefficients for sparse multiplication + // Point addition and point double calculations is reused for coefficients + function calcPairingPrecomputes(p) { + const { x, y } = p; + // prettier-ignore + const Qx = x, Qy = y, Qz = Fp2.ONE; + // prettier-ignore + let Rx = Qx, Ry = Qy, Rz = Qz; + let ell_coeff = []; + for (let i = BLS_X_LEN - 2; i >= 0; i--) { + // Double + let t0 = Fp2.sqr(Ry); // Ry² + let t1 = Fp2.sqr(Rz); // Rz² + let t2 = Fp2.multiplyByB(Fp2.mul(t1, _3n)); // 3 * T1 * B + let t3 = Fp2.mul(t2, _3n); // 3 * T2 + let t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0); // (Ry + Rz)² - T1 - T0 + ell_coeff.push([ + Fp2.sub(t2, t0), + Fp2.mul(Fp2.sqr(Rx), _3n), + Fp2.neg(t4), // -T4 + ]); + Rx = Fp2.div(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), _2n); // ((T0 - T3) * Rx * Ry) / 2 + Ry = Fp2.sub(Fp2.sqr(Fp2.div(Fp2.add(t0, t3), _2n)), Fp2.mul(Fp2.sqr(t2), _3n)); // ((T0 + T3) / 2)² - 3 * T2² + Rz = Fp2.mul(t0, t4); // T0 * T4 + if (bitGet(CURVE.params.x, i)) { + // Addition + let t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); // Ry - Qy * Rz + let t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz)); // Rx - Qx * Rz + ell_coeff.push([ + Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy)), + Fp2.neg(t0), + t1, // T1 + ]); + let t2 = Fp2.sqr(t1); // T1² + let t3 = Fp2.mul(t2, t1); // T2 * T1 + let t4 = Fp2.mul(t2, Rx); // T2 * Rx + let t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n)), Fp2.mul(Fp2.sqr(t0), Rz)); // T3 - 2 * T4 + T0² * Rz + Rx = Fp2.mul(t1, t5); // T1 * T5 + Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry)); // (T4 - T5) * T0 - T3 * Ry + Rz = Fp2.mul(Rz, t3); // Rz * T3 + } + } + return ell_coeff; + } + function millerLoop(ell, g1) { + const { x } = CURVE.params; + const Px = g1[0]; + const Py = g1[1]; + let f12 = Fp12.ONE; + for (let j = 0, i = BLS_X_LEN - 2; i >= 0; i--, j++) { + const E = ell[j]; + f12 = Fp12.multiplyBy014(f12, E[0], Fp2.mul(E[1], Px), Fp2.mul(E[2], Py)); + if (bitGet(x, i)) { + j += 1; + const F = ell[j]; + f12 = Fp12.multiplyBy014(f12, F[0], Fp2.mul(F[1], Px), Fp2.mul(F[2], Py)); + } + if (i !== 0) + f12 = Fp12.sqr(f12); + } + return Fp12.conjugate(f12); + } + const utils = { + randomPrivateKey: () => { + const length = getMinHashLength(Fr.ORDER); + return mapHashToField(CURVE.randomBytes(length), Fr.ORDER); + }, + calcPairingPrecomputes, + }; + // Point on G1 curve: (x, y) + const G1_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G1 }); + const G1 = Object.assign(G1_, htf.createHasher(G1_.ProjectivePoint, CURVE.G1.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G1.htfDefaults, + })); + function pairingPrecomputes(point) { + const p = point; + if (p._PPRECOMPUTES) + return p._PPRECOMPUTES; + p._PPRECOMPUTES = calcPairingPrecomputes(point.toAffine()); + return p._PPRECOMPUTES; + } + // TODO: export + // function clearPairingPrecomputes(point: G2) { + // const p = point as G2 & withPairingPrecomputes; + // p._PPRECOMPUTES = undefined; + // } + // Point on G2 curve (complex numbers): (x₁, x₂+i), (y₁, y₂+i) + const G2_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G2 }); + const G2 = Object.assign(G2_, htf.createHasher(G2_.ProjectivePoint, CURVE.G2.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G2.htfDefaults, + })); + const { Signature } = CURVE.G2; + // Calculates bilinear pairing + function pairing(Q, P, withFinalExponent = true) { + if (Q.equals(G1.ProjectivePoint.ZERO) || P.equals(G2.ProjectivePoint.ZERO)) + throw new Error('pairing is not available for ZERO point'); + Q.assertValidity(); + P.assertValidity(); + // Performance: 9ms for millerLoop and ~14ms for exp. + const Qa = Q.toAffine(); + const looped = millerLoop(pairingPrecomputes(P), [Qa.x, Qa.y]); + return withFinalExponent ? Fp12.finalExponentiate(looped) : looped; + } + function normP1(point) { + return point instanceof G1.ProjectivePoint ? point : G1.ProjectivePoint.fromHex(point); + } + function normP2(point) { + return point instanceof G2.ProjectivePoint ? point : Signature.fromHex(point); + } + function normP2Hash(point, htfOpts) { + return point instanceof G2.ProjectivePoint + ? point + : G2.hashToCurve(ensureBytes('point', point), htfOpts); + } + // Multiplies generator by private key. + // P = pk x G + function getPublicKey(privateKey) { + return G1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true); + } + function sign(message, privateKey, htfOpts) { + const msgPoint = normP2Hash(message, htfOpts); + msgPoint.assertValidity(); + const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey)); + if (message instanceof G2.ProjectivePoint) + return sigPoint; + return Signature.toRawBytes(sigPoint); + } + // Checks if pairing of public key & hash is equal to pairing of generator & signature. + // e(P, H(m)) == e(G, S) + function verify(signature, message, publicKey, htfOpts) { + const P = normP1(publicKey); + const Hm = normP2Hash(message, htfOpts); + const G = G1.ProjectivePoint.BASE; + const S = normP2(signature); + // Instead of doing 2 exponentiations, we use property of billinear maps + // and do one exp after multiplying 2 points. + const ePHm = pairing(P.negate(), Hm, false); + const eGS = pairing(G, S, false); + const exp = Fp12.finalExponentiate(Fp12.mul(eGS, ePHm)); + return Fp12.eql(exp, Fp12.ONE); + } + function aggregatePublicKeys(publicKeys) { + if (!publicKeys.length) + throw new Error('Expected non-empty array'); + const agg = publicKeys.map(normP1).reduce((sum, p) => sum.add(p), G1.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (publicKeys[0] instanceof G1.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + // toRawBytes ensures point validity + return aggAffine.toRawBytes(true); + } + function aggregateSignatures(signatures) { + if (!signatures.length) + throw new Error('Expected non-empty array'); + const agg = signatures.map(normP2).reduce((sum, s) => sum.add(s), G2.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (signatures[0] instanceof G2.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + return Signature.toRawBytes(aggAffine); + } + // https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407 + // e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si)) + function verifyBatch(signature, messages, publicKeys, htfOpts) { + // @ts-ignore + // console.log('verifyBatch', bytesToHex(signature as any), messages, publicKeys.map(bytesToHex)); + if (!messages.length) + throw new Error('Expected non-empty messages array'); + if (publicKeys.length !== messages.length) + throw new Error('Pubkey count should equal msg count'); + const sig = normP2(signature); + const nMessages = messages.map((i) => normP2Hash(i, htfOpts)); + const nPublicKeys = publicKeys.map(normP1); + try { + const paired = []; + for (const message of new Set(nMessages)) { + const groupPublicKey = nMessages.reduce((groupPublicKey, subMessage, i) => subMessage === message ? groupPublicKey.add(nPublicKeys[i]) : groupPublicKey, G1.ProjectivePoint.ZERO); + // const msg = message instanceof PointG2 ? message : await PointG2.hashToCurve(message); + // Possible to batch pairing for same msg with different groupPublicKey here + paired.push(pairing(groupPublicKey, message, false)); + } + paired.push(pairing(G1.ProjectivePoint.BASE.negate(), sig, false)); + const product = paired.reduce((a, b) => Fp12.mul(a, b), Fp12.ONE); + const exp = Fp12.finalExponentiate(product); + return Fp12.eql(exp, Fp12.ONE); + } + catch { + return false; + } + } + G1.ProjectivePoint.BASE._setWindowSize(4); + return { + getPublicKey, + sign, + verify, + verifyBatch, + aggregatePublicKeys, + aggregateSignatures, + millerLoop, + pairing, + G1, + G2, + Signature, + fields: { + Fr, + Fp, + Fp2, + Fp6, + Fp12, + }, + params: { + x: CURVE.params.x, + r: CURVE.params.r, + G1b: CURVE.G1.b, + G2b: CURVE.G2.b, + }, + utils, + }; +} +//# sourceMappingURL=bls.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/abstract/bls.js.map b/node_modules/@noble/curves/esm/abstract/bls.js.map new file mode 100644 index 0000000..5c3b5d1 --- /dev/null +++ b/node_modules/@noble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AE;YACF,GAAG;YACH,GAAG;YACH,IAAI;SACL;QACD,MAAM,EAAE;YACN,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;YACjB,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;YACjB,GAAG,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;YACf,GAAG,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;SAChB;QACD,KAAK;KACN,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/abstract/curve.js b/node_modules/@noble/curves/esm/abstract/curve.js new file mode 100644 index 0000000..3454763 --- /dev/null +++ b/node_modules/@noble/curves/esm/abstract/curve.js @@ -0,0 +1,156 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Abelian group utilities +import { validateField, nLength } from './modular.js'; +import { validateObject } from './utils.js'; +const _0n = BigInt(0); +const _1n = BigInt(1); +// Elliptic curve multiplication of Point by scalar. Fragile. +// Scalars should always be less than curve order: this should be checked inside of a curve itself. +// Creates precomputation tables for fast multiplication: +// - private scalar is split by fixed size windows of W bits +// - every window point is collected from window's table & added to accumulator +// - since windows are different, same point inside tables won't be accessed more than once per calc +// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar) +// - +1 window is neccessary for wNAF +// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication +// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow +// windows to be in different memory locations +export function wNAF(c, bits) { + const constTimeNegate = (condition, item) => { + const neg = item.negate(); + return condition ? neg : item; + }; + const opts = (W) => { + const windows = Math.ceil(bits / W) + 1; // +1, because + const windowSize = 2 ** (W - 1); // -1 because we skip zero + return { windows, windowSize }; + }; + return { + constTimeNegate, + // non-const time multiplication ladder + unsafeLadder(elm, n) { + let p = c.ZERO; + let d = elm; + while (n > _0n) { + if (n & _1n) + p = p.add(d); + d = d.double(); + n >>= _1n; + } + return p; + }, + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm, W) { + const { windows, windowSize } = opts(W); + const points = []; + let p = elm; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + // =1, because we skip zero + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + }, + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W, precomputes, n) { + // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise + // But need to carefully remove other checks before wNAF. ORDER == bits here + const { windows, windowSize } = opts(W); + let p = c.ZERO; + let f = c.BASE; + const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc. + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + // Extract W bits. + let wbits = Number(n & mask); + // Shift number by W bits. + n >>= shiftBy; + // If the bits are bigger than max size, we'll split those. + // +224 => 256 - 32 + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n; + } + // This code was first written with assumption that 'f' and 'p' will never be infinity point: + // since each addition is multiplied by 2 ** W, it cannot cancel each other. However, + // there is negate now: it is possible that negated element from low value + // would be the same as high element, which will create carry into next window. + // It's not obvious how this can fail, but still worth investigating later. + // Check if we're onto Zero point. + // Add random point inside current window to f. + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + // The most important part for const-time getPublicKey + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } + else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ() + // Even if the variable is still unused, there are some checks which will + // throw an exception, so compiler needs to prove they won't happen, which is hard. + // At this point there is a way to F be infinity-point even if p is not, + // which makes it less const-time: around 1 bigint multiply. + return { p, f }; + }, + wNAFCached(P, precomputesMap, n, transform) { + // @ts-ignore + const W = P._WINDOW_SIZE || 1; + // Calculate precomputes on a first run, reuse them after + let comp = precomputesMap.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W); + if (W !== 1) { + precomputesMap.set(P, transform(comp)); + } + } + return this.wNAF(W, comp, n); + }, + }; +} +export function validateBasic(curve) { + validateField(curve.Fp); + validateObject(curve, { + n: 'bigint', + h: 'bigint', + Gx: 'field', + Gy: 'field', + }, { + nBitLength: 'isSafeInteger', + nByteLength: 'isSafeInteger', + }); + // Set defaults + return Object.freeze({ + ...nLength(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER }, + }); +} +//# sourceMappingURL=curve.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/abstract/curve.js.map b/node_modules/@noble/curves/esm/abstract/curve.js.map new file mode 100644 index 0000000..f0fbc7d --- /dev/null +++ b/node_modules/@noble/curves/esm/abstract/curve.js.map @@ -0,0 +1 @@ +{"version":3,"file":"curve.js","sourceRoot":"","sources":["../../src/abstract/curve.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,0BAA0B;AAC1B,OAAO,EAAU,aAAa,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAsBtB,6DAA6D;AAC7D,mGAAmG;AACnG,yDAAyD;AACzD,4DAA4D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gBACT,IAAI,GAAG,IAAI,CAAC,gBAAgB,CAAC,CAAC,EAAE,CAAC,CAAQ,CAAC;gBAC1C,IAAI,CAAC,KAAK,CAAC,EAAE;oBACX,cAAc,CAAC,GAAG,CAAC,CAAC,EAAE,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC;iBACxC;aACF;YACD,OAAO,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;QAC/B,CAAC;KACF,CAAC;AACJ,CAAC;AAgBD,MAAM,UAAU,aAAa,CAAQ,KAAyB;IAC5D,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACxB,cAAc,CACZ,KAAK,EACL;QACE,CAAC,EAAE,QAAQ;QACX,CAAC,EAAE,QAAQ;QACX,EAAE,EAAE,OAAO;QACX,EAAE,EAAE,OAAO;KACZ,EACD;QACE,UAAU,EAAE,eAAe;QAC3B,WAAW,EAAE,eAAe;KAC7B,CACF,CAAC;IACF,eAAe;IACf,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,UAAU,CAAC;QACrC,GAAG,KAAK;QACR,GAAG,EAAE,CAAC,EAAE,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE;KAChB,CAAC,CAAC;AACd,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/abstract/edwards.js b/node_modules/@noble/curves/esm/abstract/edwards.js new file mode 100644 index 0000000..de5123a --- /dev/null +++ b/node_modules/@noble/curves/esm/abstract/edwards.js @@ -0,0 +1,425 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y² +import { mod } from './modular.js'; +import * as ut from './utils.js'; +import { ensureBytes } from './utils.js'; +import { wNAF, validateBasic } from './curve.js'; +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8); +// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex: +const VERIFY_DEFAULT = { zip215: true }; +function validateOpts(curve) { + const opts = validateBasic(curve); + ut.validateObject(curve, { + hash: 'function', + a: 'bigint', + d: 'bigint', + randomBytes: 'function', + }, { + adjustScalarBytes: 'function', + domain: 'function', + uvRatio: 'function', + mapToCurve: 'function', + }); + // Set defaults + return Object.freeze({ ...opts }); +} +// It is not generic twisted curve for now, but ed25519/ed448 generic implementation +export function twistedEdwards(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE; + const MASK = _2n << (BigInt(nByteLength * 8) - _1n); + const modP = Fp.create; // Function overrides + // sqrt(u/v) + const uvRatio = CURVE.uvRatio || + ((u, v) => { + try { + return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) }; + } + catch (e) { + return { isValid: false, value: _0n }; + } + }); + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP + const domain = CURVE.domain || + ((data, ctx, phflag) => { + if (ctx.length || phflag) + throw new Error('Contexts/pre-hash are not supported'); + return data; + }); // NOOP + const inBig = (n) => typeof n === 'bigint' && _0n < n; // n in [1..] + const inRange = (n, max) => inBig(n) && inBig(max) && n < max; // n in [1..max-1] + const in0MaskRange = (n) => n === _0n || inRange(n, MASK); // n in [0..MASK-1] + function assertInRange(n, max) { + // n in [1..max-1] + if (inRange(n, max)) + return n; + throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`); + } + function assertGE0(n) { + // n in [0..CURVE_ORDER-1] + return n === _0n ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group + } + const pointPrecomputes = new Map(); + function isPoint(other) { + if (!(other instanceof Point)) + throw new Error('ExtendedPoint expected'); + } + // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy). + // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates + class Point { + constructor(ex, ey, ez, et) { + this.ex = ex; + this.ey = ey; + this.ez = ez; + this.et = et; + if (!in0MaskRange(ex)) + throw new Error('x required'); + if (!in0MaskRange(ey)) + throw new Error('y required'); + if (!in0MaskRange(ez)) + throw new Error('z required'); + if (!in0MaskRange(et)) + throw new Error('t required'); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + static fromAffine(p) { + if (p instanceof Point) + throw new Error('extended point not allowed'); + const { x, y } = p || {}; + if (!in0MaskRange(x) || !in0MaskRange(y)) + throw new Error('invalid affine point'); + return new Point(x, y, _1n, modP(x * y)); + } + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.ez)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + // Not required for fromHex(), which always creates valid points. + // Could be useful for fromAffine(). + assertValidity() { + const { a, d } = CURVE; + if (this.is0()) + throw new Error('bad point: ZERO'); // TODO: optimize, with vars below? + // Equation in affine coordinates: ax² + y² = 1 + dx²y² + // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y² + const { ex: X, ey: Y, ez: Z, et: T } = this; + const X2 = modP(X * X); // X² + const Y2 = modP(Y * Y); // Y² + const Z2 = modP(Z * Z); // Z² + const Z4 = modP(Z2 * Z2); // Z⁴ + const aX2 = modP(X2 * a); // aX² + const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z² + const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y² + if (left !== right) + throw new Error('bad point: equation left != right (1)'); + // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T + const XY = modP(X * Y); + const ZT = modP(Z * T); + if (XY !== ZT) + throw new Error('bad point: equation left != right (2)'); + } + // Compare one point to another. + equals(other) { + isPoint(other); + const { ex: X1, ey: Y1, ez: Z1 } = this; + const { ex: X2, ey: Y2, ez: Z2 } = other; + const X1Z2 = modP(X1 * Z2); + const X2Z1 = modP(X2 * Z1); + const Y1Z2 = modP(Y1 * Z2); + const Y2Z1 = modP(Y2 * Z1); + return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; + } + is0() { + return this.equals(Point.ZERO); + } + negate() { + // Flips point sign to a negative one (-x, y in affine coords) + return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et)); + } + // Fast algo for doubling Extended Point. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd + // Cost: 4M + 4S + 1*a + 6add + 1*2. + double() { + const { a } = CURVE; + const { ex: X1, ey: Y1, ez: Z1 } = this; + const A = modP(X1 * X1); // A = X12 + const B = modP(Y1 * Y1); // B = Y12 + const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12 + const D = modP(a * A); // D = a*A + const x1y1 = X1 + Y1; + const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B + const G = D + B; // G = D+B + const F = G - C; // F = G-C + const H = D - B; // H = D-B + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + // Fast algo for adding 2 Extended Points. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd + // Cost: 9M + 1*a + 1*d + 7add. + add(other) { + isPoint(other); + const { a, d } = CURVE; + const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this; + const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other; + // Faster algo for adding 2 Extended Points when curve's a=-1. + // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4 + // Cost: 8M + 8add + 2*2. + // Note: It does not check whether the `other` point is valid. + if (a === BigInt(-1)) { + const A = modP((Y1 - X1) * (Y2 + X2)); + const B = modP((Y1 + X1) * (Y2 - X2)); + const F = modP(B - A); + if (F === _0n) + return this.double(); // Same point. Tests say it doesn't affect timing + const C = modP(Z1 * _2n * T2); + const D = modP(T1 * _2n * Z2); + const E = D + C; + const G = B + A; + const H = D - C; + const X3 = modP(E * F); + const Y3 = modP(G * H); + const T3 = modP(E * H); + const Z3 = modP(F * G); + return new Point(X3, Y3, Z3, T3); + } + const A = modP(X1 * X2); // A = X1*X2 + const B = modP(Y1 * Y2); // B = Y1*Y2 + const C = modP(T1 * d * T2); // C = T1*d*T2 + const D = modP(Z1 * Z2); // D = Z1*Z2 + const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B + const F = D - C; // F = D-C + const G = D + C; // G = D+C + const H = modP(B - a * A); // H = B-a*A + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + subtract(other) { + return this.add(other.negate()); + } + wNAF(n) { + return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ); + } + // Constant-time multiplication. + multiply(scalar) { + const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER)); + return Point.normalizeZ([p, f])[0]; + } + // Non-constant-time multiplication. Uses double-and-add algorithm. + // It's faster, but should only be used when you don't care about + // an exposed private key e.g. sig verification. + // Does NOT allow scalars higher than CURVE.n. + multiplyUnsafe(scalar) { + let n = assertGE0(scalar); // 0 <= scalar < CURVE.n + if (n === _0n) + return I; + if (this.equals(I) || n === _1n) + return this; + if (this.equals(G)) + return this.wNAF(n).p; + return wnaf.unsafeLadder(this, n); + } + // Checks if point is of small order. + // If you add something to small order point, you will have "dirty" + // point with torsion component. + // Multiplies point by cofactor and checks if the result is 0. + isSmallOrder() { + return this.multiplyUnsafe(cofactor).is0(); + } + // Multiplies point by curve order and checks if the result is 0. + // Returns `false` is the point is dirty. + isTorsionFree() { + return wnaf.unsafeLadder(this, CURVE_ORDER).is0(); + } + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + toAffine(iz) { + const { ex: x, ey: y, ez: z } = this; + const is0 = this.is0(); + if (iz == null) + iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily + const ax = modP(x * iz); + const ay = modP(y * iz); + const zz = modP(z * iz); + if (is0) + return { x: _0n, y: _1n }; + if (zz !== _1n) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + } + clearCofactor() { + const { h: cofactor } = CURVE; + if (cofactor === _1n) + return this; + return this.multiplyUnsafe(cofactor); + } + // Converts hash string or Uint8Array to Point. + // Uses algo from RFC8032 5.1.3. + static fromHex(hex, zip215 = false) { + const { d, a } = CURVE; + const len = Fp.BYTES; + hex = ensureBytes('pointHex', hex, len); // copy hex to a new array + const normed = hex.slice(); // copy again, we'll manipulate it + const lastByte = hex[len - 1]; // select last byte + normed[len - 1] = lastByte & ~0x80; // clear last bit + const y = ut.bytesToNumberLE(normed); + if (y === _0n) { + // y=0 is allowed + } + else { + // RFC8032 prohibits >= p, but ZIP215 doesn't + if (zip215) + assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519) + else + assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519) + } + // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case: + // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a) + const y2 = modP(y * y); // denominator is always non-0 mod p. + const u = modP(y2 - _1n); // u = y² - 1 + const v = modP(d * y2 - a); // v = d y² + 1. + let { isValid, value: x } = uvRatio(u, v); // √(u/v) + if (!isValid) + throw new Error('Point.fromHex: invalid y coordinate'); + const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper + const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit + if (!zip215 && x === _0n && isLastByteOdd) + // if x=0 and x_0 = 1, fail + throw new Error('Point.fromHex: x=0 and x_0=1'); + if (isLastByteOdd !== isXOdd) + x = modP(-x); // if x_0 != x mod 2, set x = p-x + return Point.fromAffine({ x, y }); + } + static fromPrivateKey(privKey) { + return getExtendedPublicKey(privKey).point; + } + toRawBytes() { + const { x, y } = this.toAffine(); + const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y) + bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y + return bytes; // and use the last byte to encode sign of x + } + toHex() { + return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string. + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy)); + Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0 + const { BASE: G, ZERO: I } = Point; + const wnaf = wNAF(Point, nByteLength * 8); + function modN(a) { + return mod(a, CURVE_ORDER); + } + // Little-endian SHA512 with modulo n + function modN_LE(hash) { + return modN(ut.bytesToNumberLE(hash)); + } + /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */ + function getExtendedPublicKey(key) { + const len = nByteLength; + key = ensureBytes('private key', key, len); + // Hash private key with curve's hash function to produce uniformingly random input + // Check byte lengths: ensure(64, h(ensure(32, key))) + const hashed = ensureBytes('hashed private key', cHash(key), 2 * len); + const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE + const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6) + const scalar = modN_LE(head); // The actual private scalar + const point = G.multiply(scalar); // Point on Edwards curve aka public key + const pointBytes = point.toRawBytes(); // Uint8Array representation + return { head, prefix, scalar, point, pointBytes }; + } + // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared + function getPublicKey(privKey) { + return getExtendedPublicKey(privKey).pointBytes; + } + // int('LE', SHA512(dom2(F, C) || msgs)) mod N + function hashDomainToScalar(context = new Uint8Array(), ...msgs) { + const msg = ut.concatBytes(...msgs); + return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash))); + } + /** Signs message with privateKey. RFC8032 5.1.6 */ + function sign(msg, privKey, options = {}) { + msg = ensureBytes('message', msg); + if (prehash) + msg = prehash(msg); // for ed25519ph etc. + const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey); + const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M) + const R = G.multiply(r).toRawBytes(); // R = rG + const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M) + const s = modN(r + k * scalar); // S = (r + k * s) mod L + assertGE0(s); // 0 <= s < l + const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES)); + return ensureBytes('result', res, nByteLength * 2); // 64-byte signature + } + const verifyOpts = VERIFY_DEFAULT; + function verify(sig, msg, publicKey, options = verifyOpts) { + const { context, zip215 } = options; + const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7. + sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked. + msg = ensureBytes('message', msg); + if (prehash) + msg = prehash(msg); // for ed25519ph, etc + const s = ut.bytesToNumberLE(sig.slice(len, 2 * len)); + // zip215: true is good for consensus-critical apps and allows points < 2^256 + // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p + let A, R, SB; + try { + A = Point.fromHex(publicKey, zip215); + R = Point.fromHex(sig.slice(0, len), zip215); + SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside + } + catch (error) { + return false; + } + if (!zip215 && A.isSmallOrder()) + return false; + const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg); + const RkA = R.add(A.multiplyUnsafe(k)); + // [8][S]B = [8]R + [8][k]A' + return RkA.subtract(SB).clearCofactor().equals(Point.ZERO); + } + G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms. + const utils = { + getExtendedPublicKey, + // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1. + randomPrivateKey: () => randomBytes(Fp.BYTES), + /** + * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT + * values. This slows down first getPublicKey() by milliseconds (see Speed section), + * but allows to speed-up subsequent getPublicKey() calls up to 20x. + * @param windowSize 2, 4, 8, 16 + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; + }, + }; + return { + CURVE, + getPublicKey, + sign, + verify, + ExtendedPoint: Point, + utils, + }; +} +//# sourceMappingURL=edwards.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/abstract/edwards.js.map b/node_modules/@noble/curves/esm/abstract/edwards.js.map new file mode 100644 index 0000000..dda68a8 --- /dev/null +++ b/node_modules/@noble/curves/esm/abstract/edwards.js.map @@ -0,0 +1 @@ +{"version":3,"file":"edwards.js","sourceRoot":"","sources":["../../src/abstract/edwards.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,8DAA8D;AAC9D,OAAO,EAAE,GAAG,EAAE,MAAM,cAAc,CAAC;AACnC,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AACjC,OAAO,EAAE,WAAW,EAAc,MAAM,YAAY,CAAC;AACrD,OAAO,EAA2B,IAAI,EAAc,aAAa,EAAe,MAAM,YAAY,CAAC;AAEnG,qEAAqE;AACrE,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAezE,8EAA8E;AAC9E,MAAM,cAAc,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;AAExC,SAAS,YAAY,CAAC,KAAgB;IACpC,MAAM,IAAI,GAAG,aAAa,CAAC,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,CAAC,CAAC,aAAa,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC7D,CAAC;IAED,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,sEAAsE;IAE3F,MAAM,KAAK,GAAG;QACZ,oBAAoB;QACpB,6FAA6F;QAC7F,gBAAgB,EAAE,GAAe,EAAE,CAAC,WAAW,CAAC,EAAE,CAAC,KAAK,CAAC;QAEzD;;;;;WAKG;QACH,UAAU,CAAC,UAAU,GAAG,CAAC,EAAE,KAAK,GAAG,KAAK,CAAC,IAAI;YAC3C,KAAK,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC;YACjC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;YAC1B,OAAO,KAAK,CAAC;QACf,CAAC;KACF,CAAC;IAEF,OAAO;QACL,KAAK;QACL,YAAY;QACZ,IAAI;QACJ,MAAM;QACN,aAAa,EAAE,KAAK;QACpB,KAAK;KACN,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/abstract/hash-to-curve.js b/node_modules/@noble/curves/esm/abstract/hash-to-curve.js new file mode 100644 index 0000000..36a25b4 --- /dev/null +++ b/node_modules/@noble/curves/esm/abstract/hash-to-curve.js @@ -0,0 +1,173 @@ +import { mod } from './modular.js'; +import { bytesToNumberBE, concatBytes, utf8ToBytes, validateObject } from './utils.js'; +function validateDST(dst) { + if (dst instanceof Uint8Array) + return dst; + if (typeof dst === 'string') + return utf8ToBytes(dst); + throw new Error('DST must be Uint8Array or string'); +} +// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE. +const os2ip = bytesToNumberBE; +// Integer to Octet Stream (numberToBytesBE) +function i2osp(value, length) { + if (value < 0 || value >= 1 << (8 * length)) { + throw new Error(`bad I2OSP call: value=${value} length=${length}`); + } + const res = Array.from({ length }).fill(0); + for (let i = length - 1; i >= 0; i--) { + res[i] = value & 0xff; + value >>>= 8; + } + return new Uint8Array(res); +} +function strxor(a, b) { + const arr = new Uint8Array(a.length); + for (let i = 0; i < a.length; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} +function isBytes(item) { + if (!(item instanceof Uint8Array)) + throw new Error('Uint8Array expected'); +} +function isNum(item) { + if (!Number.isSafeInteger(item)) + throw new Error('number expected'); +} +// Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits +// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1 +export function expand_message_xmd(msg, DST, lenInBytes, H) { + isBytes(msg); + isBytes(DST); + isNum(lenInBytes); + // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3 + if (DST.length > 255) + DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST)); + const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H; + const ell = Math.ceil(lenInBytes / b_in_bytes); + if (ell > 255) + throw new Error('Invalid xmd length'); + const DST_prime = concatBytes(DST, i2osp(DST.length, 1)); + const Z_pad = i2osp(0, r_in_bytes); + const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str + const b = new Array(ell); + const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); + b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime)); + for (let i = 1; i <= ell; i++) { + const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime]; + b[i] = H(concatBytes(...args)); + } + const pseudo_random_bytes = concatBytes(...b); + return pseudo_random_bytes.slice(0, lenInBytes); +} +// Produces a uniformly random byte string using an extendable-output function (XOF) H. +// 1. The collision resistance of H MUST be at least k bits. +// 2. H MUST be an XOF that has been proved indifferentiable from +// a random oracle under a reasonable cryptographic assumption. +// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2 +export function expand_message_xof(msg, DST, lenInBytes, k, H) { + isBytes(msg); + isBytes(DST); + isNum(lenInBytes); + // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3 + // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8)); + if (DST.length > 255) { + const dkLen = Math.ceil((2 * k) / 8); + DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest(); + } + if (lenInBytes > 65535 || DST.length > 255) + throw new Error('expand_message_xof: invalid lenInBytes'); + return (H.create({ dkLen: lenInBytes }) + .update(msg) + .update(i2osp(lenInBytes, 2)) + // 2. DST_prime = DST || I2OSP(len(DST), 1) + .update(DST) + .update(i2osp(DST.length, 1)) + .digest()); +} +/** + * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F + * https://www.rfc-editor.org/rfc/rfc9380#section-5.2 + * @param msg a byte string containing the message to hash + * @param count the number of elements of F to output + * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above + * @returns [u_0, ..., u_(count - 1)], a list of field elements. + */ +export function hash_to_field(msg, count, options) { + validateObject(options, { + DST: 'stringOrUint8Array', + p: 'bigint', + m: 'isSafeInteger', + k: 'isSafeInteger', + hash: 'hash', + }); + const { p, k, m, hash, expand, DST: _DST } = options; + isBytes(msg); + isNum(count); + const DST = validateDST(_DST); + const log2p = p.toString(2).length; + const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above + const len_in_bytes = count * m * L; + let prb; // pseudo_random_bytes + if (expand === 'xmd') { + prb = expand_message_xmd(msg, DST, len_in_bytes, hash); + } + else if (expand === 'xof') { + prb = expand_message_xof(msg, DST, len_in_bytes, k, hash); + } + else if (expand === '_internal_pass') { + // for internal tests only + prb = msg; + } + else { + throw new Error('expand must be "xmd" or "xof"'); + } + const u = new Array(count); + for (let i = 0; i < count; i++) { + const e = new Array(m); + for (let j = 0; j < m; j++) { + const elm_offset = L * (j + i * m); + const tv = prb.subarray(elm_offset, elm_offset + L); + e[j] = mod(os2ip(tv), p); + } + u[i] = e; + } + return u; +} +export function isogenyMap(field, map) { + // Make same order as in spec + const COEFF = map.map((i) => Array.from(i).reverse()); + return (x, y) => { + const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i))); + x = field.div(xNum, xDen); // xNum / xDen + y = field.mul(y, field.div(yNum, yDen)); // y * (yNum / yDev) + return { x, y }; + }; +} +export function createHasher(Point, mapToCurve, def) { + if (typeof mapToCurve !== 'function') + throw new Error('mapToCurve() must be defined'); + return { + // Encodes byte string to elliptic curve. + // hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 + hashToCurve(msg, options) { + const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options }); + const u0 = Point.fromAffine(mapToCurve(u[0])); + const u1 = Point.fromAffine(mapToCurve(u[1])); + const P = u0.add(u1).clearCofactor(); + P.assertValidity(); + return P; + }, + // Encodes byte string to elliptic curve. + // encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 + encodeToCurve(msg, options) { + const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options }); + const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor(); + P.assertValidity(); + return P; + }, + }; +} +//# sourceMappingURL=hash-to-curve.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/abstract/hash-to-curve.js.map b/node_modules/@noble/curves/esm/abstract/hash-to-curve.js.map new file mode 100644 index 0000000..faee140 --- /dev/null +++ b/node_modules/@noble/curves/esm/abstract/hash-to-curve.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hash-to-curve.js","sourceRoot":"","sources":["../../src/abstract/hash-to-curve.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,GAAG,EAAU,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAS,WAAW,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAoB9F,SAAS,WAAW,CAAC,GAAmB;IACtC,IAAI,GAAG,YAAY,UAAU;QAAE,OAAO,GAAG,CAAC;IAC1C,IAAI,OAAO,GAAG,KAA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AAE,GAAG,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YAC9C,MAAM,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,aAAa,EAAE,CAAC;YACrC,CAAC,CAAC,cAAc,EAAE,CAAC;YACnB,OAAO,CAAC,CAAC;QACX,CAAC;QAED,yCAAyC;QACzC,wEAAwE;QACxE,aAAa,CAAC,GAAe,EAAE,OAAsB;YACnD,MAAM,CAAC,GAAG,aAAa,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE,GAAG,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,SAAS,EAAE,GAAG,OAAO,EAAU,CAAC,CAAC;YACpF,MAAM,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,aAAa,EAAE,CAAC;YAC7D,CAAC,CAAC,cAAc,EAAE,CAAC;YACnB,OAAO,CAAC,CAAC;QACX,CAAC;KACF,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/abstract/modular.js b/node_modules/@noble/curves/esm/abstract/modular.js new file mode 100644 index 0000000..ec835a3 --- /dev/null +++ b/node_modules/@noble/curves/esm/abstract/modular.js @@ -0,0 +1,416 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Utilities for modular arithmetics and finite fields +import { bitMask, numberToBytesBE, numberToBytesLE, bytesToNumberBE, bytesToNumberLE, ensureBytes, validateObject, } from './utils.js'; +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); +// prettier-ignore +const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8); +// prettier-ignore +const _9n = BigInt(9), _16n = BigInt(16); +// Calculates a modulo b +export function mod(a, b) { + const result = a % b; + return result >= _0n ? result : b + result; +} +/** + * Efficiently raise num to power and do modular division. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + * @example + * pow(2n, 6n, 11n) // 64n % 11n == 9n + */ +// TODO: use field version && remove +export function pow(num, power, modulo) { + if (modulo <= _0n || power < _0n) + throw new Error('Expected power/modulo > 0'); + if (modulo === _1n) + return _0n; + let res = _1n; + while (power > _0n) { + if (power & _1n) + res = (res * num) % modulo; + num = (num * num) % modulo; + power >>= _1n; + } + return res; +} +// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4) +export function pow2(x, power, modulo) { + let res = x; + while (power-- > _0n) { + res *= res; + res %= modulo; + } + return res; +} +// Inverses number over modulo +export function invert(number, modulo) { + if (number === _0n || modulo <= _0n) { + throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); + } + // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/ + // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower. + let a = mod(number, modulo); + let b = modulo; + // prettier-ignore + let x = _0n, y = _1n, u = _1n, v = _0n; + while (a !== _0n) { + // JIT applies optimization if those two lines follow each other + const q = b / a; + const r = b % a; + const m = x - u * q; + const n = y - v * q; + // prettier-ignore + b = a, a = r, x = u, y = v, u = m, v = n; + } + const gcd = b; + if (gcd !== _1n) + throw new Error('invert: does not exist'); + return mod(x, modulo); +} +/** + * Tonelli-Shanks square root search algorithm. + * 1. https://eprint.iacr.org/2012/685.pdf (page 12) + * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks + * Will start an infinite loop if field order P is not prime. + * @param P field order + * @returns function that takes field Fp (created from P) and number n + */ +export function tonelliShanks(P) { + // Legendre constant: used to calculate Legendre symbol (a | p), + // which denotes the value of a^((p-1)/2) (mod p). + // (a | p) ≡ 1 if a is a square (mod p) + // (a | p) ≡ -1 if a is not a square (mod p) + // (a | p) ≡ 0 if a ≡ 0 (mod p) + const legendreC = (P - _1n) / _2n; + let Q, S, Z; + // Step 1: By factoring out powers of 2 from p - 1, + // find q and s such that p - 1 = q*(2^s) with q odd + for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++) + ; + // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq + for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++) + ; + // Fast-path + if (S === 1) { + const p1div4 = (P + _1n) / _4n; + return function tonelliFast(Fp, n) { + const root = Fp.pow(n, p1div4); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Slow-path + const Q1div2 = (Q + _1n) / _2n; + return function tonelliSlow(Fp, n) { + // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1 + if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) + throw new Error('Cannot find square root'); + let r = S; + // TODO: will fail at Fp2/etc + let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b + let x = Fp.pow(n, Q1div2); // first guess at the square root + let b = Fp.pow(n, Q); // first guess at the fudge factor + while (!Fp.eql(b, Fp.ONE)) { + if (Fp.eql(b, Fp.ZERO)) + return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0) + // Find m such b^(2^m)==1 + let m = 1; + for (let t2 = Fp.sqr(b); m < r; m++) { + if (Fp.eql(t2, Fp.ONE)) + break; + t2 = Fp.sqr(t2); // t2 *= t2 + } + // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow + const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1) + g = Fp.sqr(ge); // g = ge * ge + x = Fp.mul(x, ge); // x *= ge + b = Fp.mul(b, g); // b *= g + r = m; + } + return x; + }; +} +export function FpSqrt(P) { + // NOTE: different algorithms can give different roots, it is up to user to decide which one they want. + // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve). + // P ≡ 3 (mod 4) + // √n = n^((P+1)/4) + if (P % _4n === _3n) { + // Not all roots possible! + // const ORDER = + // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn; + // const NUM = 72057594037927816n; + const p1div4 = (P + _1n) / _4n; + return function sqrt3mod4(Fp, n) { + const root = Fp.pow(n, p1div4); + // Throw if root**2 != n + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10) + if (P % _8n === _5n) { + const c1 = (P - _5n) / _8n; + return function sqrt5mod8(Fp, n) { + const n2 = Fp.mul(n, _2n); + const v = Fp.pow(n2, c1); + const nv = Fp.mul(n, v); + const i = Fp.mul(Fp.mul(nv, _2n), v); + const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // P ≡ 9 (mod 16) + if (P % _16n === _9n) { + // NOTE: tonelli is too slow for bls-Fp2 calculations even on start + // Means we cannot use sqrt for constants at all! + // + // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F + // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F + // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F + // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic + // sqrt = (x) => { + // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4 + // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1 + // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1 + // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1 + // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x + // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x + // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x + // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x + // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x + // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2 + // } + } + // Other cases: Tonelli-Shanks algorithm + return tonelliShanks(P); +} +// Little-endian check for first LE bit (last BE bit); +export const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n; +// prettier-ignore +const FIELD_FIELDS = [ + 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr', + 'eql', 'add', 'sub', 'mul', 'pow', 'div', + 'addN', 'subN', 'mulN', 'sqrN' +]; +export function validateField(field) { + const initial = { + ORDER: 'bigint', + MASK: 'bigint', + BYTES: 'isSafeInteger', + BITS: 'isSafeInteger', + }; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = 'function'; + return map; + }, initial); + return validateObject(field, opts); +} +// Generic field functions +/** + * Same as `pow` but for Fp: non-constant-time. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + */ +export function FpPow(f, num, power) { + // Should have same speed as pow for bigints + // TODO: benchmark! + if (power < _0n) + throw new Error('Expected power > 0'); + if (power === _0n) + return f.ONE; + if (power === _1n) + return num; + let p = f.ONE; + let d = num; + while (power > _0n) { + if (power & _1n) + p = f.mul(p, d); + d = f.sqr(d); + power >>= _1n; + } + return p; +} +/** + * Efficiently invert an array of Field elements. + * `inv(0)` will return `undefined` here: make sure to throw an error. + */ +export function FpInvertBatch(f, nums) { + const tmp = new Array(nums.length); + // Walk from first to last, multiply them by each other MOD p + const lastMultiplied = nums.reduce((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = acc; + return f.mul(acc, num); + }, f.ONE); + // Invert last element + const inverted = f.inv(lastMultiplied); + // Walk from last to first, multiply them by inverted each other MOD p + nums.reduceRight((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = f.mul(acc, tmp[i]); + return f.mul(acc, num); + }, inverted); + return tmp; +} +export function FpDiv(f, lhs, rhs) { + return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs)); +} +// This function returns True whenever the value x is a square in the field F. +export function FpIsSquare(f) { + const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic + return (x) => { + const p = f.pow(x, legendreConst); + return f.eql(p, f.ZERO) || f.eql(p, f.ONE); + }; +} +// CURVE.n lengths +export function nLength(n, nBitLength) { + // Bit size, byte size of CURVE.n + const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} +/** + * Initializes a finite field over prime. **Non-primes are not supported.** + * Do not init in loop: slow. Very fragile: always run a benchmark on a change. + * Major performance optimizations: + * * a) denormalized operations like mulN instead of mul + * * b) same object shape: never add or remove keys + * * c) Object.freeze + * @param ORDER prime positive bigint + * @param bitLen how many bits the field consumes + * @param isLE (def: false) if encoding / decoding should be in little-endian + * @param redef optional faster redefinitions of sqrt and other methods + */ +export function Field(ORDER, bitLen, isLE = false, redef = {}) { + if (ORDER <= _0n) + throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen); + if (BYTES > 2048) + throw new Error('Field lengths over 2048 bytes are not supported'); + const sqrtP = FpSqrt(ORDER); + const f = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: bitMask(BITS), + ZERO: _0n, + ONE: _1n, + create: (num) => mod(num, ORDER), + isValid: (num) => { + if (typeof num !== 'bigint') + throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); + return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible + }, + is0: (num) => num === _0n, + isOdd: (num) => (num & _1n) === _1n, + neg: (num) => mod(-num, ORDER), + eql: (lhs, rhs) => lhs === rhs, + sqr: (num) => mod(num * num, ORDER), + add: (lhs, rhs) => mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod(lhs * rhs, ORDER), + pow: (num, power) => FpPow(f, num, power), + div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), + // Same as above, but doesn't normalize + sqrN: (num) => num * num, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + inv: (num) => invert(num, ORDER), + sqrt: redef.sqrt || ((n) => sqrtP(f, n)), + invertBatch: (lst) => FpInvertBatch(f, lst), + // TODO: do we really need constant cmov? + // We don't have const-time bigints anyway, so probably will be not very useful + cmov: (a, b, c) => (c ? b : a), + toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)), + fromBytes: (bytes) => { + if (bytes.length !== BYTES) + throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); + return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); + }, + }); + return Object.freeze(f); +} +export function FpSqrtOdd(Fp, elm) { + if (!Fp.isOdd) + throw new Error(`Field doesn't have isOdd`); + const root = Fp.sqrt(elm); + return Fp.isOdd(root) ? root : Fp.neg(root); +} +export function FpSqrtEven(Fp, elm) { + if (!Fp.isOdd) + throw new Error(`Field doesn't have isOdd`); + const root = Fp.sqrt(elm); + return Fp.isOdd(root) ? Fp.neg(root) : root; +} +/** + * "Constant-time" private key generation utility. + * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field). + * Which makes it slightly more biased, less secure. + * @deprecated use mapKeyToField instead + */ +export function hashToPrivateScalar(hash, groupOrder, isLE = false) { + hash = ensureBytes('privateHash', hash); + const hashLen = hash.length; + const minLen = nLength(groupOrder).nByteLength + 8; + if (minLen < 24 || hashLen < minLen || hashLen > 1024) + throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`); + const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash); + return mod(num, groupOrder - _1n) + _1n; +} +/** + * Returns total number of bytes consumed by the field element. + * For example, 32 bytes for usual 256-bit weierstrass curve. + * @param fieldOrder number of field elements, usually CURVE.n + * @returns byte length of field + */ +export function getFieldBytesLength(fieldOrder) { + if (typeof fieldOrder !== 'bigint') + throw new Error('field order must be bigint'); + const bitLength = fieldOrder.toString(2).length; + return Math.ceil(bitLength / 8); +} +/** + * Returns minimal amount of bytes that can be safely reduced + * by field order. + * Should be 2^-128 for 128-bit curve such as P256. + * @param fieldOrder number of field elements, usually CURVE.n + * @returns byte length of target hash + */ +export function getMinHashLength(fieldOrder) { + const length = getFieldBytesLength(fieldOrder); + return length + Math.ceil(length / 2); +} +/** + * "Constant-time" private key generation utility. + * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF + * and convert them into private scalar, with the modulo bias being negligible. + * Needs at least 48 bytes of input for 32-byte private key. + * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ + * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final + * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5 + * @param hash hash output from SHA3 or a similar function + * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n) + * @param isLE interpret hash bytes as LE num + * @returns valid private scalar + */ +export function mapHashToField(key, fieldOrder, isLE = false) { + const len = key.length; + const fieldLen = getFieldBytesLength(fieldOrder); + const minLen = getMinHashLength(fieldOrder); + // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings. + if (len < 16 || len < minLen || len > 1024) + throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`); + const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key); + // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0 + const reduced = mod(num, fieldOrder - _1n) + _1n; + return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); +} +//# sourceMappingURL=modular.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/abstract/modular.js.map b/node_modules/@noble/curves/esm/abstract/modular.js.map new file mode 100644 index 0000000..0da524f --- /dev/null +++ b/node_modules/@noble/curves/esm/abstract/modular.js.map @@ -0,0 +1 @@ +{"version":3,"file":"modular.js","sourceRoot":"","sources":["../../src/abstract/modular.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,sDAAsD;AACtD,OAAO,EACL,OAAO,EACP,eAAe,EACf,eAAe,EACf,eAAe,EACf,eAAe,EACf,WAAW,EACX,cAAc,GACf,MAAM,YAAY,CAAC;AACpB,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACzE,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACxD,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;AAEzC,wBAAwB;AACxB,MAAM,UAAU,GAAG,CAAC,CAAS,EAAE,CAAS;IACtC,MAAM,MAAM,GAAG,CAAC,GAAG,CAAC,CAAC;IACrB,OAAO,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC;AAC7C,CAAC;AACD;;;;;GAKG;AACH,oCAAoC;AACpC,MAAM,UAAU,GAAG,CAAC,GAAW,EAAE,KAAa,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ble/curves/esm/abstract/montgomery.js b/node_modules/@noble/curves/esm/abstract/montgomery.js new file mode 100644 index 0000000..19a8b6e --- /dev/null +++ b/node_modules/@noble/curves/esm/abstract/montgomery.js @@ -0,0 +1,157 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { mod, pow } from './modular.js'; +import { bytesToNumberLE, ensureBytes, numberToBytesLE, validateObject } from './utils.js'; +const _0n = BigInt(0); +const _1n = BigInt(1); +function validateOpts(curve) { + validateObject(curve, { + a: 'bigint', + }, { + montgomeryBits: 'isSafeInteger', + nByteLength: 'isSafeInteger', + adjustScalarBytes: 'function', + domain: 'function', + powPminus2: 'function', + Gu: 'bigint', + }); + // Set defaults + return Object.freeze({ ...curve }); +} +// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748) +// Uses only one coordinate instead of two +export function montgomery(curveDef) { + const CURVE = validateOpts(curveDef); + const { P } = CURVE; + const modP = (n) => mod(n, P); + const montgomeryBits = CURVE.montgomeryBits; + const montgomeryBytes = Math.ceil(montgomeryBits / 8); + const fieldLen = CURVE.nByteLength; + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); + const powPminus2 = CURVE.powPminus2 || ((x) => pow(x, P - BigInt(2), P)); + // cswap from RFC7748. But it is not from RFC7748! + /* + cswap(swap, x_2, x_3): + dummy = mask(swap) AND (x_2 XOR x_3) + x_2 = x_2 XOR dummy + x_3 = x_3 XOR dummy + Return (x_2, x_3) + Where mask(swap) is the all-1 or all-0 word of the same length as x_2 + and x_3, computed, e.g., as mask(swap) = 0 - swap. + */ + function cswap(swap, x_2, x_3) { + const dummy = modP(swap * (x_2 - x_3)); + x_2 = modP(x_2 - dummy); + x_3 = modP(x_3 + dummy); + return [x_2, x_3]; + } + // Accepts 0 as well + function assertFieldElement(n) { + if (typeof n === 'bigint' && _0n <= n && n < P) + return n; + throw new Error('Expected valid scalar 0 < scalar < CURVE.P'); + } + // x25519 from 4 + // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 + const a24 = (CURVE.a - BigInt(2)) / BigInt(4); + /** + * + * @param pointU u coordinate (x) on Montgomery Curve 25519 + * @param scalar by which the point would be multiplied + * @returns new Point on Montgomery curve + */ + function montgomeryLadder(pointU, scalar) { + const u = assertFieldElement(pointU); + // Section 5: Implementations MUST accept non-canonical values and process them as + // if they had been reduced modulo the field prime. + const k = assertFieldElement(scalar); + const x_1 = u; + let x_2 = _1n; + let z_2 = _0n; + let x_3 = u; + let z_3 = _1n; + let swap = _0n; + let sw; + for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) { + const k_t = (k >> t) & _1n; + swap ^= k_t; + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + swap = k_t; + const A = x_2 + z_2; + const AA = modP(A * A); + const B = x_2 - z_2; + const BB = modP(B * B); + const E = AA - BB; + const C = x_3 + z_3; + const D = x_3 - z_3; + const DA = modP(D * A); + const CB = modP(C * B); + const dacb = DA + CB; + const da_cb = DA - CB; + x_3 = modP(dacb * dacb); + z_3 = modP(x_1 * modP(da_cb * da_cb)); + x_2 = modP(AA * BB); + z_2 = modP(E * (AA + modP(a24 * E))); + } + // (x_2, x_3) = cswap(swap, x_2, x_3) + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + // (z_2, z_3) = cswap(swap, z_2, z_3) + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + // z_2^(p - 2) + const z2 = powPminus2(z_2); + // Return x_2 * (z_2^(p - 2)) + return modP(x_2 * z2); + } + function encodeUCoordinate(u) { + return numberToBytesLE(modP(u), montgomeryBytes); + } + function decodeUCoordinate(uEnc) { + // Section 5: When receiving such an array, implementations of X25519 + // MUST mask the most significant bit in the final byte. + // This is very ugly way, but it works because fieldLen-1 is outside of bounds for X448, so this becomes NOOP + // fieldLen - scalaryBytes = 1 for X448 and = 0 for X25519 + const u = ensureBytes('u coordinate', uEnc, montgomeryBytes); + // u[fieldLen-1] crashes QuickJS (TypeError: out-of-bound numeric index) + if (fieldLen === montgomeryBytes) + u[fieldLen - 1] &= 127; // 0b0111_1111 + return bytesToNumberLE(u); + } + function decodeScalar(n) { + const bytes = ensureBytes('scalar', n); + if (bytes.length !== montgomeryBytes && bytes.length !== fieldLen) + throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${bytes.length}`); + return bytesToNumberLE(adjustScalarBytes(bytes)); + } + function scalarMult(scalar, u) { + const pointU = decodeUCoordinate(u); + const _scalar = decodeScalar(scalar); + const pu = montgomeryLadder(pointU, _scalar); + // The result was not contributory + // https://cr.yp.to/ecdh.html#validate + if (pu === _0n) + throw new Error('Invalid private or public key received'); + return encodeUCoordinate(pu); + } + // Computes public key from private. By doing scalar multiplication of base point. + const GuBytes = encodeUCoordinate(CURVE.Gu); + function scalarMultBase(scalar) { + return scalarMult(scalar, GuBytes); + } + return { + scalarMult, + scalarMultBase, + getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey), + getPublicKey: (privateKey) => scalarMultBase(privateKey), + utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) }, + GuBytes: GuBytes, + }; +} +//# sourceMappingURL=montgomery.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/abstract/montgomery.js.map b/node_modules/@noble/curves/esm/abstract/montgomery.js.map new file mode 100644 index 0000000..6bc1a06 --- /dev/null +++ b/node_modules/@noble/curves/esm/abstract/montgomery.js.map @@ -0,0 +1 @@ +{"version":3,"file":"montgomery.js","sourceRoot":"","sources":["../../src/abstract/montgomery.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,eAAe,EAAE,cAAc,EAAE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line at end of file diff --git a/node_modules/@noble/curves/esm/abstract/poseidon.js b/node_modules/@noble/curves/esm/abstract/poseidon.js new file mode 100644 index 0000000..79f69f5 --- /dev/null +++ b/node_modules/@noble/curves/esm/abstract/poseidon.js @@ -0,0 +1,108 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Poseidon Hash: https://eprint.iacr.org/2019/458.pdf, https://www.poseidon-hash.info +import { FpPow, validateField } from './modular.js'; +export function validateOpts(opts) { + const { Fp, mds, reversePartialPowIdx: rev, roundConstants: rc } = opts; + const { roundsFull, roundsPartial, sboxPower, t } = opts; + validateField(Fp); + for (const i of ['t', 'roundsFull', 'roundsPartial']) { + if (typeof opts[i] !== 'number' || !Number.isSafeInteger(opts[i])) + throw new Error(`Poseidon: invalid param ${i}=${opts[i]} (${typeof opts[i]})`); + } + // MDS is TxT matrix + if (!Array.isArray(mds) || mds.length !== t) + throw new Error('Poseidon: wrong MDS matrix'); + const _mds = mds.map((mdsRow) => { + if (!Array.isArray(mdsRow) || mdsRow.length !== t) + throw new Error(`Poseidon MDS matrix row: ${mdsRow}`); + return mdsRow.map((i) => { + if (typeof i !== 'bigint') + throw new Error(`Poseidon MDS matrix value=${i}`); + return Fp.create(i); + }); + }); + if (rev !== undefined && typeof rev !== 'boolean') + throw new Error(`Poseidon: invalid param reversePartialPowIdx=${rev}`); + if (roundsFull % 2 !== 0) + throw new Error(`Poseidon roundsFull is not even: ${roundsFull}`); + const rounds = roundsFull + roundsPartial; + if (!Array.isArray(rc) || rc.length !== rounds) + throw new Error('Poseidon: wrong round constants'); + const roundConstants = rc.map((rc) => { + if (!Array.isArray(rc) || rc.length !== t) + throw new Error(`Poseidon wrong round constants: ${rc}`); + return rc.map((i) => { + if (typeof i !== 'bigint' || !Fp.isValid(i)) + throw new Error(`Poseidon wrong round constant=${i}`); + return Fp.create(i); + }); + }); + if (!sboxPower || ![3, 5, 7].includes(sboxPower)) + throw new Error(`Poseidon wrong sboxPower=${sboxPower}`); + const _sboxPower = BigInt(sboxPower); + let sboxFn = (n) => FpPow(Fp, n, _sboxPower); + // Unwrapped sbox power for common cases (195->142μs) + if (sboxPower === 3) + sboxFn = (n) => Fp.mul(Fp.sqrN(n), n); + else if (sboxPower === 5) + sboxFn = (n) => Fp.mul(Fp.sqrN(Fp.sqrN(n)), n); + return Object.freeze({ ...opts, rounds, sboxFn, roundConstants, mds: _mds }); +} +export function splitConstants(rc, t) { + if (typeof t !== 'number') + throw new Error('poseidonSplitConstants: wrong t'); + if (!Array.isArray(rc) || rc.length % t) + throw new Error('poseidonSplitConstants: wrong rc'); + const res = []; + let tmp = []; + for (let i = 0; i < rc.length; i++) { + tmp.push(rc[i]); + if (tmp.length === t) { + res.push(tmp); + tmp = []; + } + } + return res; +} +export function poseidon(opts) { + const _opts = validateOpts(opts); + const { Fp, mds, roundConstants, rounds, roundsPartial, sboxFn, t } = _opts; + const halfRoundsFull = _opts.roundsFull / 2; + const partialIdx = _opts.reversePartialPowIdx ? t - 1 : 0; + const poseidonRound = (values, isFull, idx) => { + values = values.map((i, j) => Fp.add(i, roundConstants[idx][j])); + if (isFull) + values = values.map((i) => sboxFn(i)); + else + values[partialIdx] = sboxFn(values[partialIdx]); + // Matrix multiplication + values = mds.map((i) => i.reduce((acc, i, j) => Fp.add(acc, Fp.mulN(i, values[j])), Fp.ZERO)); + return values; + }; + const poseidonHash = function poseidonHash(values) { + if (!Array.isArray(values) || values.length !== t) + throw new Error(`Poseidon: wrong values (expected array of bigints with length ${t})`); + values = values.map((i) => { + if (typeof i !== 'bigint') + throw new Error(`Poseidon: wrong value=${i} (${typeof i})`); + return Fp.create(i); + }); + let round = 0; + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) + values = poseidonRound(values, true, round++); + // Apply r_p partial rounds. + for (let i = 0; i < roundsPartial; i++) + values = poseidonRound(values, false, round++); + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) + values = poseidonRound(values, true, round++); + if (round !== rounds) + throw new Error(`Poseidon: wrong number of rounds: last round=${round}, total=${rounds}`); + return values; + }; + // For verification in tests + poseidonHash.roundConstants = roundConstants; + return poseidonHash; +} +//# sourceMappingURL=poseidon.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/abstract/poseidon.js.map b/node_modules/@noble/curves/esm/abstract/poseidon.js.map new file mode 100644 index 0000000..2833829 --- /dev/null +++ b/node_modules/@noble/curves/esm/abstract/poseidon.js.map @@ -0,0 +1 @@ +{"version":3,"file":"poseidon.js","sourceRoot":"","sources":["../../src/abstract/poseidon.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,sFAAsF;AACtF,OAAO,EAAU,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAc5D,MAAM,UAAU,YAAY,CAAC,IAAkB;IAC7C,MAAM,EAAE,EAAE,EAAE,GAAG,EAAE,oBAAoB,EAAE,GAAG,EAAE,cAAc,EAAE,EAAE,EAAE,GAAG,IAAI,CAAC;IACxE,MAAM,EAAE,UAAU,EAAE,aAAa,EAAE,SAAS,EAAE,CAAC,EAAE,GAAG,IAAI,CAAC;IAEzD,aAAa,CAAC,EAAE,CAAC,CAAC;IAClB,KAAK,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,YAAY,EAAE,eAAe,CAAU,EAAE;QAC7D,IAAI,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAC/D,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,OAAO,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;KAClF;IAED,oBAAoB;IACpB,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;IAC3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AAG,aAAa,EAAE,CAAC,EAAE;YAAE,MAAM,GAAG,aAAa,CAAC,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;QACvF,2BAA2B;QAC3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,cAAc,EAAE,CAAC,EAAE;YAAE,MAAM,GAAG,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;QAEvF,IAAI,KAAK,KAAK,MAAM;YAClB,MAAM,IAAI,KAAK,CAAC,gDAAgD,KAAK,WAAW,MAAM,EAAE,CAAC,CAAC;QAC5F,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IACF,4BAA4B;IAC5B,YAAY,CAAC,cAAc,GAAG,cAAc,CAAC;IAC7C,OAAO,YAAY,CAAC;AACtB,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/abstract/utils.js b/node_modules/@noble/curves/esm/abstract/utils.js new file mode 100644 index 0000000..f420405 --- /dev/null +++ b/node_modules/@noble/curves/esm/abstract/utils.js @@ -0,0 +1,266 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// 100 lines of code in the file are duplicated from noble-hashes (utils). +// This is OK: `abstract` directory does not use noble-hashes. +// User may opt-in into using different hashing library. This way, noble-hashes +// won't be included into their bundle. +const _0n = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +const u8a = (a) => a instanceof Uint8Array; +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export function bytesToHex(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +export function numberToHexUnpadded(num) { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; +} +export function hexToNumber(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + // Big Endian + return BigInt(hex === '' ? '0' : `0x${hex}`); +} +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} +// BE: Big Endian, LE: Little Endian +export function bytesToNumberBE(bytes) { + return hexToNumber(bytesToHex(bytes)); +} +export function bytesToNumberLE(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); +} +export function numberToBytesBE(n, len) { + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} +export function numberToBytesLE(n, len) { + return numberToBytesBE(n, len).reverse(); +} +// Unpadded, rarely used +export function numberToVarBytesBE(n) { + return hexToBytes(numberToHexUnpadded(n)); +} +/** + * Takes hex string or Uint8Array, converts to Uint8Array. + * Validates output length. + * Will throw error for other types. + * @param title descriptive title for an error e.g. 'private key' + * @param hex hex string or Uint8Array + * @param expectedLength optional, will compare to result array's length + * @returns + */ +export function ensureBytes(title, hex, expectedLength) { + let res; + if (typeof hex === 'string') { + try { + res = hexToBytes(hex); + } + catch (e) { + throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`); + } + } + else if (u8a(hex)) { + // Uint8Array.from() instead of hash.slice() because node.js Buffer + // is instance of Uint8Array, and its slice() creates **mutable** copy + res = Uint8Array.from(hex); + } + else { + throw new Error(`${title} must be hex string or Uint8Array`); + } + const len = res.length; + if (typeof expectedLength === 'number' && len !== expectedLength) + throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); + return res; +} +/** + * Copies several Uint8Arrays into one. + */ +export function concatBytes(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) + throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} +export function equalBytes(b1, b2) { + // We don't care about timing attacks here + if (b1.length !== b2.length) + return false; + for (let i = 0; i < b1.length; i++) + if (b1[i] !== b2[i]) + return false; + return true; +} +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +// Bit operations +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + */ +export function bitLen(n) { + let len; + for (len = 0; n > _0n; n >>= _1n, len += 1) + ; + return len; +} +/** + * Gets single bit at position. + * NOTE: first bit position is 0 (same as arrays) + * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` + */ +export function bitGet(n, pos) { + return (n >> BigInt(pos)) & _1n; +} +/** + * Sets single bit at position. + */ +export const bitSet = (n, pos, value) => { + return n | ((value ? _1n : _0n) << BigInt(pos)); +}; +/** + * Calculate mask for N bits. Not using ** operator with bigints because of old engines. + * Same as BigInt(`0b${Array(i).fill('1').join('')}`) + */ +export const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n; +// DRBG +const u8n = (data) => new Uint8Array(data); // creates Uint8Array +const u8fr = (arr) => Uint8Array.from(arr); // another shortcut +/** + * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + * @returns function that will call DRBG until 2nd arg returns something meaningful + * @example + * const drbg = createHmacDRBG(32, 32, hmac); + * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined + */ +export function createHmacDrbg(hashLen, qByteLen, hmacFn) { + if (typeof hashLen !== 'number' || hashLen < 2) + throw new Error('hashLen must be a number'); + if (typeof qByteLen !== 'number' || qByteLen < 2) + throw new Error('qByteLen must be a number'); + if (typeof hmacFn !== 'function') + throw new Error('hmacFn must be a function'); + // Step B, Step C: set hashLen to 8*ceil(hlen/8) + let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same + let i = 0; // Iterations counter, will throw when over 1000 + const reset = () => { + v.fill(1); + k.fill(0); + i = 0; + }; + const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values) + const reseed = (seed = u8n()) => { + // HMAC-DRBG reseed() function. Steps D-G + k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed) + v = h(); // v = hmac(k || v) + if (seed.length === 0) + return; + k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed) + v = h(); // v = hmac(k || v) + }; + const gen = () => { + // HMAC-DRBG generate() function + if (i++ >= 1000) + throw new Error('drbg: tried 1000 values'); + let len = 0; + const out = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes(...out); + }; + const genUntil = (seed, pred) => { + reset(); + reseed(seed); // Steps D-G + let res = undefined; // Step H: grind until k is in [1..n-1] + while (!(res = pred(gen()))) + reseed(); + reset(); + return res; + }; + return genUntil; +} +// Validating curves and fields +const validatorFns = { + bigint: (val) => typeof val === 'bigint', + function: (val) => typeof val === 'function', + boolean: (val) => typeof val === 'boolean', + string: (val) => typeof val === 'string', + stringOrUint8Array: (val) => typeof val === 'string' || val instanceof Uint8Array, + isSafeInteger: (val) => Number.isSafeInteger(val), + array: (val) => Array.isArray(val), + field: (val, object) => object.Fp.isValid(val), + hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen), +}; +// type Record = { [P in K]: T; } +export function validateObject(object, validators, optValidators = {}) { + const checkField = (fieldName, type, isOptional) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== 'function') + throw new Error(`Invalid validator "${type}", expected function`); + const val = object[fieldName]; + if (isOptional && val === undefined) + return; + if (!checkVal(val, object)) { + throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); + } + }; + for (const [fieldName, type] of Object.entries(validators)) + checkField(fieldName, type, false); + for (const [fieldName, type] of Object.entries(optValidators)) + checkField(fieldName, type, true); + return object; +} +// validate type tests +// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 }; +// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok! +// // Should fail type-check +// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' }); +// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' }); +// const z3 = validateObject(o, { test: 'boolean', z: 'bug' }); +// const z4 = validateObject(o, { a: 'boolean', z: 'bug' }); +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/abstract/utils.js.map b/node_modules/@noble/curves/esm/abstract/utils.js.map new file mode 100644 index 0000000..f86d057 --- /dev/null +++ b/node_modules/@noble/curves/esm/abstract/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/abstract/utils.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,0EAA0E;AAC1E,8DAA8D;AAC9D,+EAA+E;AAC/E,uCAAuC;AACvC,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,CAAC,CAAM,EAAmB,EAAE,CAAC,CAAC,YAAY,UAAU,CAAC;AAWjE,MAAM,KAAK,GAAG,eAAe,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EA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CAAC;IAClG,OAAO,MAAM,CAAC;AAChB,CAAC;AACD,sBAAsB;AACtB,uEAAuE;AACvE,gFAAgF;AAChF,4BAA4B;AAC5B,2DAA2D;AAC3D,qEAAqE;AACrE,+DAA+D;AAC/D,4DAA4D"} \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/abstract/weierstrass.js b/node_modules/@noble/curves/esm/abstract/weierstrass.js new file mode 100644 index 0000000..5a66587 --- /dev/null +++ b/node_modules/@noble/curves/esm/abstract/weierstrass.js @@ -0,0 +1,1056 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Short Weierstrass curve. The formula is: y² = x³ + ax + b +import * as mod from './modular.js'; +import * as ut from './utils.js'; +import { ensureBytes } from './utils.js'; +import { wNAF, validateBasic } from './curve.js'; +function validatePointOpts(curve) { + const opts = validateBasic(curve); + ut.validateObject(opts, { + a: 'field', + b: 'field', + }, { + allowedPrivateKeyLengths: 'array', + wrapPrivateKey: 'boolean', + isTorsionFree: 'function', + clearCofactor: 'function', + allowInfinityPoint: 'boolean', + fromBytes: 'function', + toBytes: 'function', + }); + const { endo, Fp, a } = opts; + if (endo) { + if (!Fp.eql(a, Fp.ZERO)) { + throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0'); + } + if (typeof endo !== 'object' || + typeof endo.beta !== 'bigint' || + typeof endo.splitScalar !== 'function') { + throw new Error('Expected endomorphism with beta: bigint and splitScalar: function'); + } + } + return Object.freeze({ ...opts }); +} +// ASN.1 DER encoding utilities +const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; +export const DER = { + // asn.1 DER encoding utils + Err: class DERErr extends Error { + constructor(m = '') { + super(m); + } + }, + _parseInt(data) { + const { Err: E } = DER; + if (data.length < 2 || data[0] !== 0x02) + throw new E('Invalid signature integer tag'); + const len = data[1]; + const res = data.subarray(2, len + 2); + if (!len || res.length !== len) + throw new E('Invalid signature integer: wrong length'); + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + if (res[0] & 0b10000000) + throw new E('Invalid signature integer: negative'); + if (res[0] === 0x00 && !(res[1] & 0b10000000)) + throw new E('Invalid signature integer: unnecessary leading zero'); + return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left + }, + toSig(hex) { + // parse DER signature + const { Err: E } = DER; + const data = typeof hex === 'string' ? h2b(hex) : hex; + if (!(data instanceof Uint8Array)) + throw new Error('ui8a expected'); + let l = data.length; + if (l < 2 || data[0] != 0x30) + throw new E('Invalid signature tag'); + if (data[1] !== l - 2) + throw new E('Invalid signature: incorrect length'); + const { d: r, l: sBytes } = DER._parseInt(data.subarray(2)); + const { d: s, l: rBytesLeft } = DER._parseInt(sBytes); + if (rBytesLeft.length) + throw new E('Invalid signature: left bytes after parsing'); + return { r, s }; + }, + hexFromSig(sig) { + // Add leading zero if first byte has negative bit enabled. More details in '_parseInt' + const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s); + const h = (num) => { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; + }; + const s = slice(h(sig.s)); + const r = slice(h(sig.r)); + const shl = s.length / 2; + const rhl = r.length / 2; + const sl = h(shl); + const rl = h(rhl); + return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`; + }, +}; +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4); +export function weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ + const toBytes = CURVE.toBytes || + ((_c, point, _isCompressed) => { + const a = point.toAffine(); + return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y)); + }); + const fromBytes = CURVE.fromBytes || + ((bytes) => { + // const head = bytes[0]; + const tail = bytes.subarray(1); + // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported'); + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + }); + /** + * y² = x³ + ax + b: Short weierstrass curve formula + * @returns y² + */ + function weierstrassEquation(x) { + const { a, b } = CURVE; + const x2 = Fp.sqr(x); // x * x + const x3 = Fp.mul(x2, x); // x2 * x + return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b + } + // Validate whether the passed curve params are valid. + // We check if curve equation works for generator point. + // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381. + // ProjectivePoint class has not been initialized yet. + if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error('bad generator point: equation left != right'); + // Valid group elements reside in range 1..n-1 + function isWithinCurveOrder(num) { + return typeof num === 'bigint' && _0n < num && num < CURVE.n; + } + function assertGE(num) { + if (!isWithinCurveOrder(num)) + throw new Error('Expected valid bigint: 0 < bigint < curve.n'); + } + // Validates if priv key is valid and converts it to bigint. + // Supports options allowedPrivateKeyLengths and wrapPrivateKey. + function normPrivateKeyToScalar(key) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE; + if (lengths && typeof key !== 'bigint') { + if (key instanceof Uint8Array) + key = ut.bytesToHex(key); + // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes + if (typeof key !== 'string' || !lengths.includes(key.length)) + throw new Error('Invalid key'); + key = key.padStart(nByteLength * 2, '0'); + } + let num; + try { + num = + typeof key === 'bigint' + ? key + : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength)); + } + catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + } + if (wrapPrivateKey) + num = mod.mod(num, n); // disabled by default, enabled for BLS + assertGE(num); // num in range [1..N-1] + return num; + } + const pointPrecomputes = new Map(); + function assertPrjPoint(other) { + if (!(other instanceof Point)) + throw new Error('ProjectivePoint expected'); + } + /** + * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z) + * Default Point works in 2d / affine coordinates: (x, y) + * We're doing calculations in projective, because its operations don't require costly inversion. + */ + class Point { + constructor(px, py, pz) { + this.px = px; + this.py = py; + this.pz = pz; + if (px == null || !Fp.isValid(px)) + throw new Error('x required'); + if (py == null || !Fp.isValid(py)) + throw new Error('y required'); + if (pz == null || !Fp.isValid(pz)) + throw new Error('z required'); + } + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + static fromAffine(p) { + const { x, y } = p || {}; + if (!p || !Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('invalid affine point'); + if (p instanceof Point) + throw new Error('projective point not allowed'); + const is0 = (i) => Fp.eql(i, Fp.ZERO); + // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0) + if (is0(x) && is0(y)) + return Point.ZERO; + return new Point(x, y, Fp.ONE); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + /** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + */ + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex) { + const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex))); + P.assertValidity(); + return P; + } + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey) { + return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + // A point on curve is valid if it conforms to equation. + assertValidity() { + if (this.is0()) { + // (0, 1, 0) aka ZERO is invalid in most contexts. + // In BLS, ZERO can be serialized, so we allow it. + // (0, 0, 0) is wrong representation of ZERO and is always invalid. + if (CURVE.allowInfinityPoint && !Fp.is0(this.py)) + return; + throw new Error('bad point: ZERO'); + } + // Some 3rd-party test vectors require different wording between here & `fromCompressedHex` + const { x, y } = this.toAffine(); + // Check if x, y are valid field elements + if (!Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('bad point: x or y not FE'); + const left = Fp.sqr(y); // y² + const right = weierstrassEquation(x); // x³ + ax + b + if (!Fp.eql(left, right)) + throw new Error('bad point: equation left != right'); + if (!this.isTorsionFree()) + throw new Error('bad point: not in prime-order subgroup'); + } + hasEvenY() { + const { y } = this.toAffine(); + if (Fp.isOdd) + return !Fp.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + /** + * Compare one point to another. + */ + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); + const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); + return U1 && U2; + } + /** + * Flips point to one corresponding to (x, -y) in Affine coordinates. + */ + negate() { + return new Point(this.px, Fp.neg(this.py), this.pz); + } + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a, b } = CURVE; + const b3 = Fp.mul(b, _3n); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + let t0 = Fp.mul(X1, X1); // step 1 + let t1 = Fp.mul(Y1, Y1); + let t2 = Fp.mul(Z1, Z1); + let t3 = Fp.mul(X1, Y1); + t3 = Fp.add(t3, t3); // step 5 + Z3 = Fp.mul(X1, Z1); + Z3 = Fp.add(Z3, Z3); + X3 = Fp.mul(a, Z3); + Y3 = Fp.mul(b3, t2); + Y3 = Fp.add(X3, Y3); // step 10 + X3 = Fp.sub(t1, Y3); + Y3 = Fp.add(t1, Y3); + Y3 = Fp.mul(X3, Y3); + X3 = Fp.mul(t3, X3); + Z3 = Fp.mul(b3, Z3); // step 15 + t2 = Fp.mul(a, t2); + t3 = Fp.sub(t0, t2); + t3 = Fp.mul(a, t3); + t3 = Fp.add(t3, Z3); + Z3 = Fp.add(t0, t0); // step 20 + t0 = Fp.add(Z3, t0); + t0 = Fp.add(t0, t2); + t0 = Fp.mul(t0, t3); + Y3 = Fp.add(Y3, t0); + t2 = Fp.mul(Y1, Z1); // step 25 + t2 = Fp.add(t2, t2); + t0 = Fp.mul(t2, t3); + X3 = Fp.sub(X3, t0); + Z3 = Fp.mul(t2, t1); + Z3 = Fp.add(Z3, Z3); // step 30 + Z3 = Fp.add(Z3, Z3); + return new Point(X3, Y3, Z3); + } + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + const a = CURVE.a; + const b3 = Fp.mul(CURVE.b, _3n); + let t0 = Fp.mul(X1, X2); // step 1 + let t1 = Fp.mul(Y1, Y2); + let t2 = Fp.mul(Z1, Z2); + let t3 = Fp.add(X1, Y1); + let t4 = Fp.add(X2, Y2); // step 5 + t3 = Fp.mul(t3, t4); + t4 = Fp.add(t0, t1); + t3 = Fp.sub(t3, t4); + t4 = Fp.add(X1, Z1); + let t5 = Fp.add(X2, Z2); // step 10 + t4 = Fp.mul(t4, t5); + t5 = Fp.add(t0, t2); + t4 = Fp.sub(t4, t5); + t5 = Fp.add(Y1, Z1); + X3 = Fp.add(Y2, Z2); // step 15 + t5 = Fp.mul(t5, X3); + X3 = Fp.add(t1, t2); + t5 = Fp.sub(t5, X3); + Z3 = Fp.mul(a, t4); + X3 = Fp.mul(b3, t2); // step 20 + Z3 = Fp.add(X3, Z3); + X3 = Fp.sub(t1, Z3); + Z3 = Fp.add(t1, Z3); + Y3 = Fp.mul(X3, Z3); + t1 = Fp.add(t0, t0); // step 25 + t1 = Fp.add(t1, t0); + t2 = Fp.mul(a, t2); + t4 = Fp.mul(b3, t4); + t1 = Fp.add(t1, t2); + t2 = Fp.sub(t0, t2); // step 30 + t2 = Fp.mul(a, t2); + t4 = Fp.add(t4, t2); + t0 = Fp.mul(t1, t4); + Y3 = Fp.add(Y3, t0); + t0 = Fp.mul(t5, t4); // step 35 + X3 = Fp.mul(t3, X3); + X3 = Fp.sub(X3, t0); + t0 = Fp.mul(t3, t1); + Z3 = Fp.mul(t5, Z3); + Z3 = Fp.add(Z3, t0); // step 40 + return new Point(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + is0() { + return this.equals(Point.ZERO); + } + wNAF(n) { + return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => { + const toInv = Fp.invertBatch(comp.map((p) => p.pz)); + return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + }); + } + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(n) { + const I = Point.ZERO; + if (n === _0n) + return I; + assertGE(n); // Will throw on 0 + if (n === _1n) + return this; + const { endo } = CURVE; + if (!endo) + return wnaf.unsafeLadder(this, n); + // Apply endomorphism + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let k1p = I; + let k2p = I; + let d = this; + while (k1 > _0n || k2 > _0n) { + if (k1 & _1n) + k1p = k1p.add(d); + if (k2 & _1n) + k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n; + k2 >>= _1n; + } + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar by which the point would be multiplied + * @returns New point + */ + multiply(scalar) { + assertGE(scalar); + let n = scalar; + let point, fake; // Fake point is used to const-time mult + const { endo } = CURVE; + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } + else { + const { p, f } = this.wNAF(n); + point = p; + fake = f; + } + // Normalize `z` for both points, but return only real one + return Point.normalizeZ([point, fake])[0]; + } + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q, a, b) { + const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes + const mul = (P, a // Select faster multiply() method + ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a)); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? undefined : sum; + } + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + toAffine(iz) { + const { px: x, py: y, pz: z } = this; + const is0 = this.is0(); + // If invZ was 0, we return zero point. However we still want to execute + // all operations, so we replace invZ with a random number, 1. + if (iz == null) + iz = is0 ? Fp.ONE : Fp.inv(z); + const ax = Fp.mul(x, iz); + const ay = Fp.mul(y, iz); + const zz = Fp.mul(z, iz); + if (is0) + return { x: Fp.ZERO, y: Fp.ZERO }; + if (!Fp.eql(zz, Fp.ONE)) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + } + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n) + return true; // No subgroups, always torsion-free + if (isTorsionFree) + return isTorsionFree(Point, this); + throw new Error('isTorsionFree() has not been declared for the elliptic curve'); + } + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n) + return this; // Fast-path + if (clearCofactor) + return clearCofactor(Point, this); + return this.multiplyUnsafe(CURVE.h); + } + toRawBytes(isCompressed = true) { + this.assertValidity(); + return toBytes(Point, this, isCompressed); + } + toHex(isCompressed = true) { + return ut.bytesToHex(this.toRawBytes(isCompressed)); + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); + Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + // Validate if generator point is on curve + return { + CURVE, + ProjectivePoint: Point, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + }; +} +function validateOpts(curve) { + const opts = validateBasic(curve); + ut.validateObject(opts, { + hash: 'hash', + hmac: 'function', + randomBytes: 'function', + }, { + bits2int: 'function', + bits2int_modN: 'function', + lowS: 'boolean', + }); + return Object.freeze({ lowS: true, ...opts }); +} +export function weierstrass(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32 + const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32 + function isValidFieldElement(num) { + return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE + } + function modN(a) { + return mod.mod(a, CURVE_ORDER); + } + function invN(a) { + return mod.invert(a, CURVE_ORDER); + } + const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({ + ...CURVE, + toBytes(_c, point, isCompressed) { + const a = point.toAffine(); + const x = Fp.toBytes(a.x); + const cat = ut.concatBytes; + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x); + } + else { + return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y)); + } + }, + fromBytes(bytes) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + // this.assertValidity() is done inside of fromHex + if (len === compressedLen && (head === 0x02 || head === 0x03)) { + const x = ut.bytesToNumberBE(tail); + if (!isValidFieldElement(x)) + throw new Error('Point is not on curve'); + const y2 = weierstrassEquation(x); // y² = x³ + ax + b + let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 + const isYOdd = (y & _1n) === _1n; + // ECDSA + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y = Fp.neg(y); + return { x, y }; + } + else if (len === uncompressedLen && head === 0x04) { + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + } + else { + throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); + } + }, + }); + const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number) { + const HALF = CURVE_ORDER >> _1n; + return number > HALF; + } + function normalizeS(s) { + return isBiggerThanHalfOrder(s) ? modN(-s) : s; + } + // slice bytes num + const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to)); + /** + * ECDSA signature with its (r, s) properties. Supports DER & compact representations. + */ + class Signature { + constructor(r, s, recovery) { + this.r = r; + this.s = s; + this.recovery = recovery; + this.assertValidity(); + } + // pair (bytes of r, bytes of s) + static fromCompact(hex) { + const l = CURVE.nByteLength; + hex = ensureBytes('compactSignature', hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex) { + const { r, s } = DER.toSig(ensureBytes('DER', hex)); + return new Signature(r, s); + } + assertValidity() { + // can use assertGE here + if (!isWithinCurveOrder(this.r)) + throw new Error('r must be 0 < r < CURVE.n'); + if (!isWithinCurveOrder(this.s)) + throw new Error('s must be 0 < s < CURVE.n'); + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(msgHash) { + const { r, s, recovery: rec } = this; + const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error('recovery id invalid'); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp.ORDER) + throw new Error('recovery id 2 or 3 invalid'); + const prefix = (rec & 1) === 0 ? '02' : '03'; + const R = Point.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); // r^-1 + const u1 = modN(-h * ir); // -hr^-1 + const u2 = modN(s * ir); // sr^-1 + const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1) + if (!Q) + throw new Error('point at infinify'); // unsafe is fine: no priv data leaked + Q.assertValidity(); + return Q; + } + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; + } + // DER-encoded + toDERRawBytes() { + return ut.hexToBytes(this.toDERHex()); + } + toDERHex() { + return DER.hexFromSig({ r: this.r, s: this.s }); + } + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return ut.hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + const utils = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } + catch (error) { + return false; + } + }, + normPrivateKeyToScalar: normPrivateKeyToScalar, + /** + * Produces cryptographically secure private key from random of size + * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. + */ + randomPrivateKey: () => { + const length = mod.getMinHashLength(CURVE.n); + return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n); + }, + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here + return point; + }, + }; + /** + * Computes public key for a private key. Checks for validity of the private key. + * @param privateKey private key + * @param isCompressed whether to return compact (default), or full key + * @returns Public key, full when isCompressed=false; short when isCompressed=true + */ + function getPublicKey(privateKey, isCompressed = true) { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + /** + * Quick and dirty check for item being public key. Does not validate hex, or being on-curve. + */ + function isProbPub(item) { + const arr = item instanceof Uint8Array; + const str = typeof item === 'string'; + const len = (arr || str) && item.length; + if (arr) + return len === compressedLen || len === uncompressedLen; + if (str) + return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point) + return true; + return false; + } + /** + * ECDH (Elliptic Curve Diffie Hellman). + * Computes shared public key from private key and public key. + * Checks: 1) private key validity 2) shared key is on-curve. + * Does NOT hash the result. + * @param privateA private key + * @param publicB different public key + * @param isCompressed whether to return compact (default), or full key + * @returns shared public key + */ + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) + throw new Error('first arg must be private key'); + if (!isProbPub(publicB)) + throw new Error('second arg must be public key'); + const b = Point.fromHex(publicB); // check for being on-curve + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets. + // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int. + // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same. + // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors + const bits2int = CURVE.bits2int || + function (bytes) { + // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m) + // for some cases, since bytes.length * 8 is not actual bitLength. + const num = ut.bytesToNumberBE(bytes); // check for == u8 done here + const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits + return delta > 0 ? num >> BigInt(delta) : num; + }; + const bits2int_modN = CURVE.bits2int_modN || + function (bytes) { + return modN(bits2int(bytes)); // can't use bytesToNumberBE here + }; + // NOTE: pads output with zero as per spec + const ORDER_MASK = ut.bitMask(CURVE.nBitLength); + /** + * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. + */ + function int2octets(num) { + if (typeof num !== 'bigint') + throw new Error('bigint expected'); + if (!(_0n <= num && num < ORDER_MASK)) + throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); + // works with order, can have different size than numToField! + return ut.numberToBytesBE(num, CURVE.nByteLength); + } + // Steps A, D of RFC6979 3.2 + // Creates RFC6979 seed; converts msg/privKey to numbers. + // Used only in sign, not in verify. + // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521. + // Also it can be bigger for P224 + SHA256 + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (['recovered', 'canonical'].some((k) => k in opts)) + throw new Error('sign() legacy options not supported'); + const { hash, randomBytes } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default + if (lowS == null) + lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash + msgHash = ensureBytes('msgHash', msgHash); + if (prehash) + msgHash = ensureBytes('prehashed msgHash', hash(msgHash)); + // We can't later call bits2octets, since nested bits2int is broken for curves + // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call. + // const bits2octets = (bits) => int2octets(bits2int_modN(bits)) + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint + const seedArgs = [int2octets(d), int2octets(h1int)]; + // extraEntropy. RFC6979 3.6: additional k' (optional). + if (ent != null) { + // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') + const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is + seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes + } + const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2 + const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash! + // Converts signature params into point w r/s, checks result for validity. + function k2sig(kBytes) { + // RFC 6979 Section 3.2, step 3: k = bits2int(T) + const k = bits2int(kBytes); // Cannot use fields methods, since it is group element + if (!isWithinCurveOrder(k)) + return; // Important: all mod() calls here must be done over N + const ik = invN(k); // k^-1 mod n + const q = Point.BASE.multiply(k).toAffine(); // q = Gk + const r = modN(q.x); // r = q.x mod n + if (r === _0n) + return; + // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to + // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it: + // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT + const s = modN(ik * modN(m + r * d)); // Not using blinding here + if (s === _0n) + return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n) + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); // if lowS was passed, ensure s is always + recovery ^= 1; // // in the bottom half of N + } + return new Signature(r, normS, recovery); // use normS, not s + } + return { seed, k2sig }; + } + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + /** + * Signs message hash with a private key. + * ``` + * sign(m, d, k) where + * (x, y) = G × k + * r = x mod n + * s = (m + dr)/k mod n + * ``` + * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`. + * @param privKey private key + * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg. + * @returns signature with recovery param + */ + function sign(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2. + const C = CURVE; + const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); // Steps B, C, D, E, F, G + } + // Enable precomputes. Slows down first publicKey computation by 20ms. + Point.BASE._setWindowSize(8); + // utils.precompute(8, ProjectivePoint.BASE) + /** + * Verifies a signature against message hash and public key. + * Rejects lowS signatures by default: to override, + * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf: + * + * ``` + * verify(r, s, h, P) where + * U1 = hs^-1 mod n + * U2 = rs^-1 mod n + * R = U1⋅G - U2⋅P + * mod(R.x, n) == r + * ``` + */ + function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { + const sg = signature; + msgHash = ensureBytes('msgHash', msgHash); + publicKey = ensureBytes('publicKey', publicKey); + if ('strict' in opts) + throw new Error('options.strict was renamed to lowS'); + const { lowS, prehash } = opts; + let _sig = undefined; + let P; + try { + if (typeof sg === 'string' || sg instanceof Uint8Array) { + // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length). + // Since DER can also be 2*nByteLength bytes, we check for it first. + try { + _sig = Signature.fromDER(sg); + } + catch (derError) { + if (!(derError instanceof DER.Err)) + throw derError; + _sig = Signature.fromCompact(sg); + } + } + else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') { + const { r, s } = sg; + _sig = new Signature(r, s); + } + else { + throw new Error('PARSE'); + } + P = Point.fromHex(publicKey); + } + catch (error) { + if (error.message === 'PARSE') + throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; + } + if (lowS && _sig.hasHighS()) + return false; + if (prehash) + msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element + const is = invN(s); // s^-1 + const u1 = modN(h * is); // u1 = hs^-1 mod n + const u2 = modN(r * is); // u2 = rs^-1 mod n + const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P + if (!R) + return false; + const v = modN(R.x); + return v === r; + } + return { + CURVE, + getPublicKey, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point, + Signature, + utils, + }; +} +/** + * Implementation of the Shallue and van de Woestijne method for any weierstrass curve. + * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular. + * b = True and y = sqrt(u / v) if (u / v) is square in F, and + * b = False and y = sqrt(Z * (u / v)) otherwise. + * @param Fp + * @param Z + * @returns + */ +export function SWUFpSqrtRatio(Fp, Z) { + // Generic implementation + const q = Fp.ORDER; + let l = _0n; + for (let o = q - _1n; o % _2n === _0n; o /= _2n) + l += _1n; + const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1. + // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<. + // 2n ** c1 == 2n << (c1-1) + const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n); + const _2n_pow_c1 = _2n_pow_c1_1 * _2n; + const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic + const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic + const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic + const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic + const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2 + const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2) + let sqrtRatio = (u, v) => { + let tv1 = c6; // 1. tv1 = c6 + let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4 + let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2 + tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v + let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3 + tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3 + tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2 + tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v + tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u + let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2 + tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5 + let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1 + tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7 + tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1 + tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR) + tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR) + // 17. for i in (c1, c1 - 1, ..., 2): + for (let i = c1; i > _1n; i--) { + let tv5 = i - _2n; // 18. tv5 = i - 2 + tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5 + let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5 + const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1 + tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1 + tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1 + tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1 + tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1) + tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1) + } + return { isValid: isQR, value: tv3 }; + }; + if (Fp.ORDER % _4n === _3n) { + // sqrt_ratio_3mod4(u, v) + const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic + const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z) + sqrtRatio = (u, v) => { + let tv1 = Fp.sqr(v); // 1. tv1 = v^2 + const tv2 = Fp.mul(u, v); // 2. tv2 = u * v + tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2 + let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1 + y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2 + const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2 + const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v + const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u + let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR) + return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2 + }; + } + // No curves uses that + // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8 + return sqrtRatio; +} +/** + * Simplified Shallue-van de Woestijne-Ulas Method + * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2 + */ +export function mapToCurveSimpleSWU(Fp, opts) { + mod.validateField(Fp); + if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z)) + throw new Error('mapToCurveSimpleSWU: invalid opts'); + const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z); + if (!Fp.isOdd) + throw new Error('Fp.isOdd is not implemented!'); + // Input: u, an element of F. + // Output: (x, y), a point on E. + return (u) => { + // prettier-ignore + let tv1, tv2, tv3, tv4, tv5, tv6, x, y; + tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1 + tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2 + tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1 + tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1 + tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3 + tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0) + tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4 + tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2 + tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2 + tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6 + tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5 + tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3 + tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4 + tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6 + tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5 + x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3 + const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6) + y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1 + y = Fp.mul(y, value); // 20. y = y * y1 + x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square) + y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square) + const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y) + y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1) + x = Fp.div(x, tv4); // 25. x = x / tv4 + return { x, y }; + }; +} +//# sourceMappingURL=weierstrass.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/abstract/weierstrass.js.map b/node_modules/@noble/curves/esm/abstract/weierstrass.js.map new file mode 100644 index 0000000..457ede4 --- /dev/null +++ b/node_modules/@noble/curves/esm/abstract/weierstrass.js.map @@ -0,0 +1 @@ +{"version":3,"file":"weierstrass.js","sourceRoot":"","sources":["../../src/abstract/weierstrass.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,4DAA4D;AAC5D,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AACjC,OAAO,EAAuB,WAAW,EAAE,MAAM,YAAY,CAAC;AAC9D,OAAO,EAA2B,IAAI,EAAc,aAAa,EAAe,MAAM,YAAY,CAAC;AAqFnG,SAAS,iBAAiB,CAAI,KAAyB;IACrD,MAAM,IAAI,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC;IAClC,EAAE,CAAC,cAAc,CACf,IAAI,EACJ;QACE,CAAC,EAAE,OAAO;QACV,CAAC,EAAE,OAAO;KACX,EACD;QACE,wBAAwB,EAAE,OAAO;QACjC,cAAc,EAAE,SAAS;QACzB,aAAa,EAAE,UAAU;QACzB,aAAa,EAAE,UAAU;QACzB,kBAAkB,EAAE,SAAS;QAC7B,SAAS,EAAE,UAAU;QACrB,OAAO,EAAE,UAAU;KACpB,CACF,CAAC;IACF,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,EAAE,GAAG,IAAI,CAAC;IAC7B,IAAI,IAAI,EAAE;QACR,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE;YACvB,MAAM,IAAI,KAAK,CAAC,mEAAmE,CAAC,CAAC;SACtF;QACD,IACE,OAAO,IAAI,KAAK,QAAQ;YACxB,OAAO,IAAI,CAAC,IAAI,KAAK,QAAQ;YAC7B,OAAO,IAAI,CAAC,WAAW,KAAK,UAAU,EACtC;YACA,MAAM,IAAI,KAAK,CAAC,mEAAmE,CAAC,CAAC;SACtF;KACF;IACD,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,IAAI,EA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ACvE,MAAM,EAAE,GAAG,EAAE,CAAC,KAAM,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,KAAM,CAAC,CAAC,CAAC,CAAC,CAAC,+BAA+B;QACzE,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,4BAA4B;QAC3D,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,oBAAoB;QACxC,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IAClB,CAAC,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/bls12-381.js b/node_modules/@noble/curves/esm/bls12-381.js new file mode 100644 index 0000000..885c825 --- /dev/null +++ b/node_modules/@noble/curves/esm/bls12-381.js @@ -0,0 +1,1172 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// bls12-381 pairing-friendly Barreto-Lynn-Scott elliptic curve construction allows to: +// - Construct zk-SNARKs at the 128-bit security +// - Use threshold signatures, which allows a user to sign lots of messages with one signature and +// verify them swiftly in a batch, using Boneh-Lynn-Shacham signature scheme. +// +// The library uses G1 for public keys and G2 for signatures. Support for G1 signatures is planned. +// Compatible with Algorand, Chia, Dfinity, Ethereum, FIL, Zcash. Matches specs +// [pairing-curves-11](https://tools.ietf.org/html/draft-irtf-cfrg-pairing-friendly-curves-11), +// [bls-sigs-04](https:/cfrg-hash-to/tools.ietf.org/html/draft-irtf-cfrg-bls-signature-04), +// [hash-to-curve-12](https://tools.ietf.org/html/draft-irtf--curve-12). +// +// ### Summary +// 1. BLS Relies on Bilinear Pairing (expensive) +// 2. Private Keys: 32 bytes +// 3. Public Keys: 48 bytes: 381 bit affine x coordinate, encoded into 48 big-endian bytes. +// 4. Signatures: 96 bytes: two 381 bit integers (affine x coordinate), encoded into two 48 big-endian byte arrays. +// - The signature is a point on the G2 subgroup, which is defined over a finite field +// with elements twice as big as the G1 curve (G2 is over Fp2 rather than Fp. Fp2 is analogous to the complex numbers). +// 5. The 12 stands for the Embedding degree. +// +// ### Formulas +// - `P = pk x G` - public keys +// - `S = pk x H(m)` - signing +// - `e(P, H(m)) == e(G, S)` - verification using pairings +// - `e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))` - signature aggregation +// Filecoin uses little endian byte arrays for private keys - +// so ensure to reverse byte order if you'll use it with FIL. +import { sha256 } from '@noble/hashes/sha256'; +import { randomBytes } from '@noble/hashes/utils'; +import { bls } from './abstract/bls.js'; +import * as mod from './abstract/modular.js'; +import { concatBytes as concatB, ensureBytes, numberToBytesBE, bytesToNumberBE, bitLen, bitSet, bitGet, bitMask, bytesToHex, } from './abstract/utils.js'; +// Types +import { mapToCurveSimpleSWU, } from './abstract/weierstrass.js'; +import { isogenyMap } from './abstract/hash-to-curve.js'; +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4); +// prettier-ignore +const _8n = BigInt(8), _16n = BigInt(16); +// CURVE FIELDS +// Finite field over p. +const Fp_raw = BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'); +const Fp = mod.Field(Fp_raw); +// Finite field over r. +// This particular field is not used anywhere in bls12-381, but it is still useful. +const Fr = mod.Field(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')); +const Fp2Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp.add(c0, r0), + c1: Fp.add(c1, r1), +}); +const Fp2Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp.sub(c0, r0), + c1: Fp.sub(c1, r1), +}); +const Fp2Multiply = ({ c0, c1 }, rhs) => { + if (typeof rhs === 'bigint') + return { c0: Fp.mul(c0, rhs), c1: Fp.mul(c1, rhs) }; + // (a+bi)(c+di) = (ac−bd) + (ad+bc)i + const { c0: r0, c1: r1 } = rhs; + let t1 = Fp.mul(c0, r0); // c0 * o0 + let t2 = Fp.mul(c1, r1); // c1 * o1 + // (T1 - T2) + ((c0 + c1) * (r0 + r1) - (T1 + T2))*i + const o0 = Fp.sub(t1, t2); + const o1 = Fp.sub(Fp.mul(Fp.add(c0, c1), Fp.add(r0, r1)), Fp.add(t1, t2)); + return { c0: o0, c1: o1 }; +}; +const Fp2Square = ({ c0, c1 }) => { + const a = Fp.add(c0, c1); + const b = Fp.sub(c0, c1); + const c = Fp.add(c0, c0); + return { c0: Fp.mul(a, b), c1: Fp.mul(c, c1) }; +}; +// G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1), +// where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where +// G² - 1 +// h2q +// NOTE: ORDER was wrong! +const FP2_ORDER = Fp_raw * Fp_raw; +const Fp2 = { + ORDER: FP2_ORDER, + BITS: bitLen(FP2_ORDER), + BYTES: Math.ceil(bitLen(FP2_ORDER) / 8), + MASK: bitMask(bitLen(FP2_ORDER)), + ZERO: { c0: Fp.ZERO, c1: Fp.ZERO }, + ONE: { c0: Fp.ONE, c1: Fp.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => typeof c0 === 'bigint' && typeof c1 === 'bigint', + is0: ({ c0, c1 }) => Fp.is0(c0) && Fp.is0(c1), + eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp.eql(c0, r0) && Fp.eql(c1, r1), + neg: ({ c0, c1 }) => ({ c0: Fp.neg(c0), c1: Fp.neg(c1) }), + pow: (num, power) => mod.FpPow(Fp2, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp2, nums), + // Normalized + add: Fp2Add, + sub: Fp2Subtract, + mul: Fp2Multiply, + sqr: Fp2Square, + // NonNormalized stuff + addN: Fp2Add, + subN: Fp2Subtract, + mulN: Fp2Multiply, + sqrN: Fp2Square, + // Why inversion for bigint inside Fp instead of Fp2? it is even used in that context? + div: (lhs, rhs) => Fp2.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp2.inv(rhs)), + inv: ({ c0: a, c1: b }) => { + // We wish to find the multiplicative inverse of a nonzero + // element a + bu in Fp2. We leverage an identity + // + // (a + bu)(a - bu) = a² + b² + // + // which holds because u² = -1. This can be rewritten as + // + // (a + bu)(a - bu)/(a² + b²) = 1 + // + // because a² + b² = 0 has no nonzero solutions for (a, b). + // This gives that (a - bu)/(a² + b²) is the inverse + // of (a + bu). Importantly, this can be computing using + // only a single inversion in Fp. + const factor = Fp.inv(Fp.create(a * a + b * b)); + return { c0: Fp.mul(factor, Fp.create(a)), c1: Fp.mul(factor, Fp.create(-b)) }; + }, + sqrt: (num) => { + if (Fp2.eql(num, Fp2.ZERO)) + return Fp2.ZERO; // Algo doesn't handles this case + // TODO: Optimize this line. It's extremely slow. + // Speeding this up would boost aggregateSignatures. + // https://eprint.iacr.org/2012/685.pdf applicable? + // https://github.com/zkcrypto/bls12_381/blob/080eaa74ec0e394377caa1ba302c8c121df08b07/src/fp2.rs#L250 + // https://github.com/supranational/blst/blob/aae0c7d70b799ac269ff5edf29d8191dbd357876/src/exp2.c#L1 + // Inspired by https://github.com/dalek-cryptography/curve25519-dalek/blob/17698df9d4c834204f83a3574143abacb4fc81a5/src/field.rs#L99 + const candidateSqrt = Fp2.pow(num, (Fp2.ORDER + _8n) / _16n); + const check = Fp2.div(Fp2.sqr(candidateSqrt), num); // candidateSqrt.square().div(this); + const R = FP2_ROOTS_OF_UNITY; + const divisor = [R[0], R[2], R[4], R[6]].find((r) => Fp2.eql(r, check)); + if (!divisor) + throw new Error('No root'); + const index = R.indexOf(divisor); + const root = R[index / 2]; + if (!root) + throw new Error('Invalid root'); + const x1 = Fp2.div(candidateSqrt, root); + const x2 = Fp2.neg(x1); + const { re: re1, im: im1 } = Fp2.reim(x1); + const { re: re2, im: im2 } = Fp2.reim(x2); + if (im1 > im2 || (im1 === im2 && re1 > re2)) + return x1; + return x2; + }, + // Same as sgn0_m_eq_2 in RFC 9380 + isOdd: (x) => { + const { re: x0, im: x1 } = Fp2.reim(x); + const sign_0 = x0 % _2n; + const zero_0 = x0 === _0n; + const sign_1 = x1 % _2n; + return BigInt(sign_0 || (zero_0 && sign_1)) == _1n; + }, + // Bytes util + fromBytes(b) { + if (b.length !== Fp2.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { c0: Fp.fromBytes(b.subarray(0, Fp.BYTES)), c1: Fp.fromBytes(b.subarray(Fp.BYTES)) }; + }, + toBytes: ({ c0, c1 }) => concatB(Fp.toBytes(c0), Fp.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp.cmov(c0, r0, c), + c1: Fp.cmov(c1, r1, c), + }), + // Specific utils + // toString() { + // return `Fp2(${this.c0} + ${this.c1}×i)`; + // } + reim: ({ c0, c1 }) => ({ re: c0, im: c1 }), + // multiply by u + 1 + mulByNonresidue: ({ c0, c1 }) => ({ c0: Fp.sub(c0, c1), c1: Fp.add(c0, c1) }), + multiplyByB: ({ c0, c1 }) => { + let t0 = Fp.mul(c0, _4n); // 4 * c0 + let t1 = Fp.mul(c1, _4n); // 4 * c1 + // (T0-T1) + (T0+T1)*i + return { c0: Fp.sub(t0, t1), c1: Fp.add(t0, t1) }; + }, + fromBigTuple: (tuple) => { + if (tuple.length !== 2) + throw new Error('Invalid tuple'); + const fps = tuple.map((n) => Fp.create(n)); + return { c0: fps[0], c1: fps[1] }; + }, + frobeniusMap: ({ c0, c1 }, power) => ({ + c0, + c1: Fp.mul(c1, FP2_FROBENIUS_COEFFICIENTS[power % 2]), + }), +}; +// Finite extension field over irreducible polynominal. +// Fp(u) / (u² - β) where β = -1 +const FP2_FROBENIUS_COEFFICIENTS = [ + BigInt('0x1'), + BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'), +].map((item) => Fp.create(item)); +// For Fp2 roots of unity. +const rv1 = BigInt('0x6af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09'); +// const ev1 = +// BigInt('0x699be3b8c6870965e5bf892ad5d2cc7b0e85a117402dfd83b7f4a947e02d978498255a2aaec0ac627b5afbdf1bf1c90'); +// const ev2 = +// BigInt('0x8157cd83046453f5dd0972b6e3949e4288020b5b8a9cc99ca07e27089a2ce2436d965026adad3ef7baba37f2183e9b5'); +// const ev3 = +// BigInt('0xab1c2ffdd6c253ca155231eb3e71ba044fd562f6f72bc5bad5ec46a0b7a3b0247cf08ce6c6317f40edbc653a72dee17'); +// const ev4 = +// BigInt('0xaa404866706722864480885d68ad0ccac1967c7544b447873cc37e0181271e006df72162a3d3e0287bf597fbf7f8fc1'); +// Eighth roots of unity, used for computing square roots in Fp2. +// To verify or re-calculate: +// Array(8).fill(new Fp2([1n, 1n])).map((fp2, k) => fp2.pow(Fp2.ORDER * BigInt(k) / 8n)) +const FP2_ROOTS_OF_UNITY = [ + [_1n, _0n], + [rv1, -rv1], + [_0n, _1n], + [rv1, rv1], + [-_1n, _0n], + [-rv1, rv1], + [_0n, -_1n], + [-rv1, -rv1], +].map((pair) => Fp2.fromBigTuple(pair)); +const Fp6Add = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({ + c0: Fp2.add(c0, r0), + c1: Fp2.add(c1, r1), + c2: Fp2.add(c2, r2), +}); +const Fp6Subtract = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({ + c0: Fp2.sub(c0, r0), + c1: Fp2.sub(c1, r1), + c2: Fp2.sub(c2, r2), +}); +const Fp6Multiply = ({ c0, c1, c2 }, rhs) => { + if (typeof rhs === 'bigint') { + return { + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }; + } + const { c0: r0, c1: r1, c2: r2 } = rhs; + const t0 = Fp2.mul(c0, r0); // c0 * o0 + const t1 = Fp2.mul(c1, r1); // c1 * o1 + const t2 = Fp2.mul(c2, r2); // c2 * o2 + return { + // t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1) + c0: Fp2.add(t0, Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), Fp2.add(r1, r2)), Fp2.add(t1, t2)))), + // (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1) + c1: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c1), Fp2.add(r0, r1)), Fp2.add(t0, t1)), Fp2.mulByNonresidue(t2)), + // T1 + (c0 + c2) * (r0 + r2) - T0 + T2 + c2: Fp2.sub(Fp2.add(t1, Fp2.mul(Fp2.add(c0, c2), Fp2.add(r0, r2))), Fp2.add(t0, t2)), + }; +}; +const Fp6Square = ({ c0, c1, c2 }) => { + let t0 = Fp2.sqr(c0); // c0² + let t1 = Fp2.mul(Fp2.mul(c0, c1), _2n); // 2 * c0 * c1 + let t3 = Fp2.mul(Fp2.mul(c1, c2), _2n); // 2 * c1 * c2 + let t4 = Fp2.sqr(c2); // c2² + return { + c0: Fp2.add(Fp2.mulByNonresidue(t3), t0), + c1: Fp2.add(Fp2.mulByNonresidue(t4), t1), + // T1 + (c0 - c1 + c2)² + T3 - T0 - T4 + c2: Fp2.sub(Fp2.sub(Fp2.add(Fp2.add(t1, Fp2.sqr(Fp2.add(Fp2.sub(c0, c1), c2))), t3), t0), t4), + }; +}; +const Fp6 = { + ORDER: Fp2.ORDER, + BITS: 3 * Fp2.BITS, + BYTES: 3 * Fp2.BYTES, + MASK: bitMask(3 * Fp2.BITS), + ZERO: { c0: Fp2.ZERO, c1: Fp2.ZERO, c2: Fp2.ZERO }, + ONE: { c0: Fp2.ONE, c1: Fp2.ZERO, c2: Fp2.ZERO }, + create: (num) => num, + isValid: ({ c0, c1, c2 }) => Fp2.isValid(c0) && Fp2.isValid(c1) && Fp2.isValid(c2), + is0: ({ c0, c1, c2 }) => Fp2.is0(c0) && Fp2.is0(c1) && Fp2.is0(c2), + neg: ({ c0, c1, c2 }) => ({ c0: Fp2.neg(c0), c1: Fp2.neg(c1), c2: Fp2.neg(c2) }), + eql: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => Fp2.eql(c0, r0) && Fp2.eql(c1, r1) && Fp2.eql(c2, r2), + sqrt: () => { + throw new Error('Not implemented'); + }, + // Do we need division by bigint at all? Should be done via order: + div: (lhs, rhs) => Fp6.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp6.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp6, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp6, nums), + // Normalized + add: Fp6Add, + sub: Fp6Subtract, + mul: Fp6Multiply, + sqr: Fp6Square, + // NonNormalized stuff + addN: Fp6Add, + subN: Fp6Subtract, + mulN: Fp6Multiply, + sqrN: Fp6Square, + inv: ({ c0, c1, c2 }) => { + let t0 = Fp2.sub(Fp2.sqr(c0), Fp2.mulByNonresidue(Fp2.mul(c2, c1))); // c0² - c2 * c1 * (u + 1) + let t1 = Fp2.sub(Fp2.mulByNonresidue(Fp2.sqr(c2)), Fp2.mul(c0, c1)); // c2² * (u + 1) - c0 * c1 + let t2 = Fp2.sub(Fp2.sqr(c1), Fp2.mul(c0, c2)); // c1² - c0 * c2 + // 1/(((c2 * T1 + c1 * T2) * v) + c0 * T0) + let t4 = Fp2.inv(Fp2.add(Fp2.mulByNonresidue(Fp2.add(Fp2.mul(c2, t1), Fp2.mul(c1, t2))), Fp2.mul(c0, t0))); + return { c0: Fp2.mul(t4, t0), c1: Fp2.mul(t4, t1), c2: Fp2.mul(t4, t2) }; + }, + // Bytes utils + fromBytes: (b) => { + if (b.length !== Fp6.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp2.fromBytes(b.subarray(0, Fp2.BYTES)), + c1: Fp2.fromBytes(b.subarray(Fp2.BYTES, 2 * Fp2.BYTES)), + c2: Fp2.fromBytes(b.subarray(2 * Fp2.BYTES)), + }; + }, + toBytes: ({ c0, c1, c2 }) => concatB(Fp2.toBytes(c0), Fp2.toBytes(c1), Fp2.toBytes(c2)), + cmov: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }, c) => ({ + c0: Fp2.cmov(c0, r0, c), + c1: Fp2.cmov(c1, r1, c), + c2: Fp2.cmov(c2, r2, c), + }), + // Utils + // fromTriple(triple: [Fp2, Fp2, Fp2]) { + // return new Fp6(...triple); + // } + // toString() { + // return `Fp6(${this.c0} + ${this.c1} * v, ${this.c2} * v^2)`; + // } + fromBigSix: (t) => { + if (!Array.isArray(t) || t.length !== 6) + throw new Error('Invalid Fp6 usage'); + return { + c0: Fp2.fromBigTuple(t.slice(0, 2)), + c1: Fp2.fromBigTuple(t.slice(2, 4)), + c2: Fp2.fromBigTuple(t.slice(4, 6)), + }; + }, + frobeniusMap: ({ c0, c1, c2 }, power) => ({ + c0: Fp2.frobeniusMap(c0, power), + c1: Fp2.mul(Fp2.frobeniusMap(c1, power), FP6_FROBENIUS_COEFFICIENTS_1[power % 6]), + c2: Fp2.mul(Fp2.frobeniusMap(c2, power), FP6_FROBENIUS_COEFFICIENTS_2[power % 6]), + }), + mulByNonresidue: ({ c0, c1, c2 }) => ({ c0: Fp2.mulByNonresidue(c2), c1: c0, c2: c1 }), + // Sparse multiplication + multiplyBy1: ({ c0, c1, c2 }, b1) => ({ + c0: Fp2.mulByNonresidue(Fp2.mul(c2, b1)), + c1: Fp2.mul(c0, b1), + c2: Fp2.mul(c1, b1), + }), + // Sparse multiplication + multiplyBy01({ c0, c1, c2 }, b0, b1) { + let t0 = Fp2.mul(c0, b0); // c0 * b0 + let t1 = Fp2.mul(c1, b1); // c1 * b1 + return { + // ((c1 + c2) * b1 - T1) * (u + 1) + T0 + c0: Fp2.add(Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), b1), t1)), t0), + // (b0 + b1) * (c0 + c1) - T0 - T1 + c1: Fp2.sub(Fp2.sub(Fp2.mul(Fp2.add(b0, b1), Fp2.add(c0, c1)), t0), t1), + // (c0 + c2) * b0 - T0 + T1 + c2: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c2), b0), t0), t1), + }; + }, + multiplyByFp2: ({ c0, c1, c2 }, rhs) => ({ + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }), +}; +const FP6_FROBENIUS_COEFFICIENTS_1 = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt('0x0'), + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + BigInt('0x0'), + ], + [BigInt('0x0'), BigInt('0x1')], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + BigInt('0x0'), + ], + [ + BigInt('0x0'), + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + ], +].map((pair) => Fp2.fromBigTuple(pair)); +const FP6_FROBENIUS_COEFFICIENTS_2 = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad'), + BigInt('0x0'), + ], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + BigInt('0x0'), + ], + [ + BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'), + BigInt('0x0'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + BigInt('0x0'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff'), + BigInt('0x0'), + ], +].map((pair) => Fp2.fromBigTuple(pair)); +// The BLS parameter x for BLS12-381 +const BLS_X = BigInt('0xd201000000010000'); +const BLS_X_LEN = bitLen(BLS_X); +const Fp12Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp6.add(c0, r0), + c1: Fp6.add(c1, r1), +}); +const Fp12Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp6.sub(c0, r0), + c1: Fp6.sub(c1, r1), +}); +const Fp12Multiply = ({ c0, c1 }, rhs) => { + if (typeof rhs === 'bigint') + return { c0: Fp6.mul(c0, rhs), c1: Fp6.mul(c1, rhs) }; + let { c0: r0, c1: r1 } = rhs; + let t1 = Fp6.mul(c0, r0); // c0 * r0 + let t2 = Fp6.mul(c1, r1); // c1 * r1 + return { + c0: Fp6.add(t1, Fp6.mulByNonresidue(t2)), + // (c0 + c1) * (r0 + r1) - (T1 + T2) + c1: Fp6.sub(Fp6.mul(Fp6.add(c0, c1), Fp6.add(r0, r1)), Fp6.add(t1, t2)), + }; +}; +const Fp12Square = ({ c0, c1 }) => { + let ab = Fp6.mul(c0, c1); // c0 * c1 + return { + // (c1 * v + c0) * (c0 + c1) - AB - AB * v + c0: Fp6.sub(Fp6.sub(Fp6.mul(Fp6.add(Fp6.mulByNonresidue(c1), c0), Fp6.add(c0, c1)), ab), Fp6.mulByNonresidue(ab)), + c1: Fp6.add(ab, ab), + }; // AB + AB +}; +function Fp4Square(a, b) { + const a2 = Fp2.sqr(a); + const b2 = Fp2.sqr(b); + return { + first: Fp2.add(Fp2.mulByNonresidue(b2), a2), + second: Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(a, b)), a2), b2), // (a + b)² - a² - b² + }; +} +const Fp12 = { + ORDER: Fp2.ORDER, + BITS: 2 * Fp2.BITS, + BYTES: 2 * Fp2.BYTES, + MASK: bitMask(2 * Fp2.BITS), + ZERO: { c0: Fp6.ZERO, c1: Fp6.ZERO }, + ONE: { c0: Fp6.ONE, c1: Fp6.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => Fp6.isValid(c0) && Fp6.isValid(c1), + is0: ({ c0, c1 }) => Fp6.is0(c0) && Fp6.is0(c1), + neg: ({ c0, c1 }) => ({ c0: Fp6.neg(c0), c1: Fp6.neg(c1) }), + eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp6.eql(c0, r0) && Fp6.eql(c1, r1), + sqrt: () => { + throw new Error('Not implemented'); + }, + inv: ({ c0, c1 }) => { + let t = Fp6.inv(Fp6.sub(Fp6.sqr(c0), Fp6.mulByNonresidue(Fp6.sqr(c1)))); // 1 / (c0² - c1² * v) + return { c0: Fp6.mul(c0, t), c1: Fp6.neg(Fp6.mul(c1, t)) }; // ((C0 * T) * T) + (-C1 * T) * w + }, + div: (lhs, rhs) => Fp12.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp12.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp12, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp12, nums), + // Normalized + add: Fp12Add, + sub: Fp12Subtract, + mul: Fp12Multiply, + sqr: Fp12Square, + // NonNormalized stuff + addN: Fp12Add, + subN: Fp12Subtract, + mulN: Fp12Multiply, + sqrN: Fp12Square, + // Bytes utils + fromBytes: (b) => { + if (b.length !== Fp12.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp6.fromBytes(b.subarray(0, Fp6.BYTES)), + c1: Fp6.fromBytes(b.subarray(Fp6.BYTES)), + }; + }, + toBytes: ({ c0, c1 }) => concatB(Fp6.toBytes(c0), Fp6.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp6.cmov(c0, r0, c), + c1: Fp6.cmov(c1, r1, c), + }), + // Utils + // toString() { + // return `Fp12(${this.c0} + ${this.c1} * w)`; + // }, + // fromTuple(c: [Fp6, Fp6]) { + // return new Fp12(...c); + // } + fromBigTwelve: (t) => ({ + c0: Fp6.fromBigSix(t.slice(0, 6)), + c1: Fp6.fromBigSix(t.slice(6, 12)), + }), + // Raises to q**i -th power + frobeniusMap(lhs, power) { + const r0 = Fp6.frobeniusMap(lhs.c0, power); + const { c0, c1, c2 } = Fp6.frobeniusMap(lhs.c1, power); + const coeff = FP12_FROBENIUS_COEFFICIENTS[power % 12]; + return { + c0: r0, + c1: Fp6.create({ + c0: Fp2.mul(c0, coeff), + c1: Fp2.mul(c1, coeff), + c2: Fp2.mul(c2, coeff), + }), + }; + }, + // Sparse multiplication + multiplyBy014: ({ c0, c1 }, o0, o1, o4) => { + let t0 = Fp6.multiplyBy01(c0, o0, o1); + let t1 = Fp6.multiplyBy1(c1, o4); + return { + c0: Fp6.add(Fp6.mulByNonresidue(t1), t0), + // (c1 + c0) * [o0, o1+o4] - T0 - T1 + c1: Fp6.sub(Fp6.sub(Fp6.multiplyBy01(Fp6.add(c1, c0), o0, Fp2.add(o1, o4)), t0), t1), + }; + }, + multiplyByFp2: ({ c0, c1 }, rhs) => ({ + c0: Fp6.multiplyByFp2(c0, rhs), + c1: Fp6.multiplyByFp2(c1, rhs), + }), + conjugate: ({ c0, c1 }) => ({ c0, c1: Fp6.neg(c1) }), + // A cyclotomic group is a subgroup of Fp^n defined by + // GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1} + // The result of any pairing is in a cyclotomic subgroup + // https://eprint.iacr.org/2009/565.pdf + _cyclotomicSquare: ({ c0, c1 }) => { + const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0; + const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1; + const { first: t3, second: t4 } = Fp4Square(c0c0, c1c1); + const { first: t5, second: t6 } = Fp4Square(c1c0, c0c2); + const { first: t7, second: t8 } = Fp4Square(c0c1, c1c2); + let t9 = Fp2.mulByNonresidue(t8); // T8 * (u + 1) + return { + c0: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.sub(t3, c0c0), _2n), t3), + c1: Fp2.add(Fp2.mul(Fp2.sub(t5, c0c1), _2n), t5), + c2: Fp2.add(Fp2.mul(Fp2.sub(t7, c0c2), _2n), t7), + }), + c1: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.add(t9, c1c0), _2n), t9), + c1: Fp2.add(Fp2.mul(Fp2.add(t4, c1c1), _2n), t4), + c2: Fp2.add(Fp2.mul(Fp2.add(t6, c1c2), _2n), t6), + }), + }; // 2 * (T6 + c1c2) + T6 + }, + _cyclotomicExp(num, n) { + let z = Fp12.ONE; + for (let i = BLS_X_LEN - 1; i >= 0; i--) { + z = Fp12._cyclotomicSquare(z); + if (bitGet(n, i)) + z = Fp12.mul(z, num); + } + return z; + }, + // https://eprint.iacr.org/2010/354.pdf + // https://eprint.iacr.org/2009/565.pdf + finalExponentiate: (num) => { + const x = BLS_X; + // this^(q⁶) / this + const t0 = Fp12.div(Fp12.frobeniusMap(num, 6), num); + // t0^(q²) * t0 + const t1 = Fp12.mul(Fp12.frobeniusMap(t0, 2), t0); + const t2 = Fp12.conjugate(Fp12._cyclotomicExp(t1, x)); + const t3 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicSquare(t1)), t2); + const t4 = Fp12.conjugate(Fp12._cyclotomicExp(t3, x)); + const t5 = Fp12.conjugate(Fp12._cyclotomicExp(t4, x)); + const t6 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicExp(t5, x)), Fp12._cyclotomicSquare(t2)); + const t7 = Fp12.conjugate(Fp12._cyclotomicExp(t6, x)); + const t2_t5_pow_q2 = Fp12.frobeniusMap(Fp12.mul(t2, t5), 2); + const t4_t1_pow_q3 = Fp12.frobeniusMap(Fp12.mul(t4, t1), 3); + const t6_t1c_pow_q1 = Fp12.frobeniusMap(Fp12.mul(t6, Fp12.conjugate(t1)), 1); + const t7_t3c_t1 = Fp12.mul(Fp12.mul(t7, Fp12.conjugate(t3)), t1); + // (t2 * t5)^(q²) * (t4 * t1)^(q³) * (t6 * t1.conj)^(q^1) * t7 * t3.conj * t1 + return Fp12.mul(Fp12.mul(Fp12.mul(t2_t5_pow_q2, t4_t1_pow_q3), t6_t1c_pow_q1), t7_t3c_t1); + }, +}; +const FP12_FROBENIUS_COEFFICIENTS = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt('0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8'), + BigInt('0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff'), + BigInt('0x0'), + ], + [ + BigInt('0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2'), + BigInt('0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + BigInt('0x0'), + ], + [ + BigInt('0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995'), + BigInt('0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116'), + ], + [ + BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'), + BigInt('0x0'), + ], + [ + BigInt('0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3'), + BigInt('0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8'), + ], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + BigInt('0x0'), + ], + [ + BigInt('0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09'), + BigInt('0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2'), + ], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad'), + BigInt('0x0'), + ], + [ + BigInt('0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116'), + BigInt('0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995'), + ], +].map((n) => Fp2.fromBigTuple(n)); +// END OF CURVE FIELDS +// HashToCurve +// 3-isogeny map from E' to E https://www.rfc-editor.org/rfc/rfc9380#appendix-E.3 +const isogenyMapG2 = isogenyMap(Fp2, [ + // xNum + [ + [ + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + ], + [ + '0x0', + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d', + ], + [ + '0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1', + '0x0', + ], + ], + // xDen + [ + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63', + ], + [ + '0xc', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f', + ], + ['0x1', '0x0'], // LAST 1 + ], + // yNum + [ + [ + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + ], + [ + '0x0', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f', + ], + [ + '0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10', + '0x0', + ], + ], + // yDen + [ + [ + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + ], + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3', + ], + [ + '0x12', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99', + ], + ['0x1', '0x0'], // LAST 1 + ], +].map((i) => i.map((pair) => Fp2.fromBigTuple(pair.map(BigInt))))); +// 11-isogeny map from E' to E +const isogenyMapG1 = isogenyMap(Fp, [ + // xNum + [ + '0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7', + '0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb', + '0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0', + '0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861', + '0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9', + '0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983', + '0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84', + '0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e', + '0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317', + '0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e', + '0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b', + '0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229', + ], + // xDen + [ + '0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c', + '0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff', + '0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19', + '0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8', + '0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e', + '0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5', + '0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a', + '0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e', + '0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641', + '0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33', + '0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696', + '0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6', + '0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb', + '0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb', + '0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0', + '0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2', + '0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29', + '0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587', + '0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30', + '0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132', + '0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e', + '0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8', + '0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133', + '0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b', + '0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604', + ], + // yDen + [ + '0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1', + '0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d', + '0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2', + '0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416', + '0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d', + '0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac', + '0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c', + '0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9', + '0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a', + '0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55', + '0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8', + '0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092', + '0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc', + '0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7', + '0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], +].map((i) => i.map((j) => BigInt(j)))); +// SWU Map - Fp2 to G2': y² = x³ + 240i * x + 1012 + 1012i +const G2_SWU = mapToCurveSimpleSWU(Fp2, { + A: Fp2.create({ c0: Fp.create(_0n), c1: Fp.create(BigInt(240)) }), + B: Fp2.create({ c0: Fp.create(BigInt(1012)), c1: Fp.create(BigInt(1012)) }), + Z: Fp2.create({ c0: Fp.create(BigInt(-2)), c1: Fp.create(BigInt(-1)) }), // Z: -(2 + I) +}); +// Optimized SWU Map - Fp to G1 +const G1_SWU = mapToCurveSimpleSWU(Fp, { + A: Fp.create(BigInt('0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d')), + B: Fp.create(BigInt('0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0')), + Z: Fp.create(BigInt(11)), +}); +// Endomorphisms (for fast cofactor clearing) +// Ψ(P) endomorphism +const ut_root = Fp6.create({ c0: Fp2.ZERO, c1: Fp2.ONE, c2: Fp2.ZERO }); +const wsq = Fp12.create({ c0: ut_root, c1: Fp6.ZERO }); +const wcu = Fp12.create({ c0: Fp6.ZERO, c1: ut_root }); +const [wsq_inv, wcu_inv] = Fp12.invertBatch([wsq, wcu]); +function psi(x, y) { + // Untwist Fp2->Fp12 && frobenius(1) && twist back + const x2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wsq_inv, x), 1), wsq).c0.c0; + const y2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wcu_inv, y), 1), wcu).c0.c0; + return [x2, y2]; +} +// Ψ endomorphism +function G2psi(c, P) { + const affine = P.toAffine(); + const p = psi(affine.x, affine.y); + return new c(p[0], p[1], Fp2.ONE); +} +// Ψ²(P) endomorphism +// 1 / F2(2)^((p-1)/3) in GF(p²) +const PSI2_C1 = BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'); +function psi2(x, y) { + return [Fp2.mul(x, PSI2_C1), Fp2.neg(y)]; +} +function G2psi2(c, P) { + const affine = P.toAffine(); + const p = psi2(affine.x, affine.y); + return new c(p[0], p[1], Fp2.ONE); +} +// Default hash_to_field options are for hash to G2. +// +// Parameter definitions are in section 5.3 of the spec unless otherwise noted. +// Parameter values come from section 8.8.2 of the spec. +// https://www.rfc-editor.org/rfc/rfc9380#section-8.8.2 +// +// Base field F is GF(p^m) +// p = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab +// m = 2 (or 1 for G1 see section 8.8.1) +// k = 128 +const htfDefaults = Object.freeze({ + // DST: a domain separation tag + // defined in section 2.2.5 + // Use utils.getDSTLabel(), utils.setDSTLabel(value) + DST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + encodeDST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + // p: the characteristic of F + // where F is a finite field of characteristic p and order q = p^m + p: Fp.ORDER, + // m: the extension degree of F, m >= 1 + // where F is a finite field of characteristic p and order q = p^m + m: 2, + // k: the target security level for the suite in bits + // defined in section 5.1 + k: 128, + // option to use a message that has already been processed by + // expand_message_xmd + expand: 'xmd', + // Hash functions for: expand_message_xmd is appropriate for use with a + // wide range of hash functions, including SHA-2, SHA-3, BLAKE2, and others. + // BBS+ uses blake2: https://github.com/hyperledger/aries-framework-go/issues/2247 + hash: sha256, +}); +// Encoding utils +// Point on G1 curve: (x, y) +const C_BIT_POS = Fp.BITS; // C_bit, compression bit for serialization flag +const I_BIT_POS = Fp.BITS + 1; // I_bit, point-at-infinity bit for serialization flag +const S_BIT_POS = Fp.BITS + 2; // S_bit, sign bit for serialization flag +// Compressed point of infinity +const COMPRESSED_ZERO = Fp.toBytes(bitSet(bitSet(_0n, I_BIT_POS, true), S_BIT_POS, true)); // set compressed & point-at-infinity bits +function signatureG2ToRawBytes(point) { + // NOTE: by some reasons it was missed in bls12-381, looks like bug + point.assertValidity(); + const len = Fp.BYTES; + if (point.equals(bls12_381.G2.ProjectivePoint.ZERO)) + return concatB(COMPRESSED_ZERO, numberToBytesBE(_0n, len)); + const { x, y } = point.toAffine(); + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + const tmp = y1 > _0n ? y1 * _2n : y0 * _2n; + const aflag1 = Boolean((tmp / Fp.ORDER) & _1n); + const z1 = bitSet(bitSet(x1, 381, aflag1), S_BIT_POS, true); + const z2 = x0; + return concatB(numberToBytesBE(z1, len), numberToBytesBE(z2, len)); +} +// To verify curve parameters, see pairing-friendly-curves spec: +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-11 +// Basic math is done over finite fields over p. +// More complicated math is done over polynominal extension fields. +// To simplify calculations in Fp12, we construct extension tower: +// Fp₁₂ = Fp₆² => Fp₂³ +// Fp(u) / (u² - β) where β = -1 +// Fp₂(v) / (v³ - ξ) where ξ = u + 1 +// Fp₆(w) / (w² - γ) where γ = v +// Here goes constants && point encoding format +export const bls12_381 = bls({ + // Fields + fields: { + Fp, + Fp2, + Fp6, + Fp12, + Fr, + }, + // G1 is the order-q subgroup of E1(Fp) : y² = x³ + 4, #E1(Fp) = h1q, where + // characteristic; z + (z⁴ - z² + 1)(z - 1)²/3 + G1: { + Fp, + // cofactor; (z - 1)²/3 + h: BigInt('0x396c8c005555e1568c00aaab0000aaab'), + // generator's coordinates + // x = 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507 + // y = 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569 + Gx: BigInt('0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb'), + Gy: BigInt('0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1'), + a: Fp.ZERO, + b: _4n, + htfDefaults: { ...htfDefaults, m: 1 }, + wrapPrivateKey: true, + allowInfinityPoint: true, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, point) => { + // φ endomorphism + const cubicRootOfUnityModP = BigInt('0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'); + const phi = new c(Fp.mul(point.px, cubicRootOfUnityModP), point.py, point.pz); + // todo: unroll + const xP = point.multiplyUnsafe(bls12_381.params.x).negate(); // [x]P + const u2P = xP.multiplyUnsafe(bls12_381.params.x); // [u2]P + return u2P.equals(phi); + // https://eprint.iacr.org/2019/814.pdf + // (z² − 1)/3 + // const c1 = BigInt('0x396c8c005555e1560000000055555555'); + // const P = this; + // const S = P.sigma(); + // const Q = S.double(); + // const S2 = S.sigma(); + // // [(z² − 1)/3](2σ(P) − P − σ²(P)) − σ²(P) = O + // const left = Q.subtract(P).subtract(S2).multiplyUnsafe(c1); + // const C = left.subtract(S2); + // return C.isZero(); + }, + // Clear cofactor of G1 + // https://eprint.iacr.org/2019/403 + clearCofactor: (_c, point) => { + // return this.multiplyUnsafe(CURVE.h); + return point.multiplyUnsafe(bls12_381.params.x).add(point); // x*P + P + }, + mapToCurve: (scalars) => { + const { x, y } = G1_SWU(Fp.create(scalars[0])); + return isogenyMapG1(x, y); + }, + fromBytes: (bytes) => { + bytes = bytes.slice(); + if (bytes.length === 48) { + // TODO: Fp.bytes + const P = Fp.ORDER; + const compressedValue = bytesToNumberBE(bytes); + const bflag = bitGet(compressedValue, I_BIT_POS); + // Zero + if (bflag === _1n) + return { x: _0n, y: _0n }; + const x = Fp.create(compressedValue & Fp.MASK); + const right = Fp.add(Fp.pow(x, _3n), Fp.create(bls12_381.params.G1b)); // y² = x³ + b + let y = Fp.sqrt(right); + if (!y) + throw new Error('Invalid compressed G1 point'); + const aflag = bitGet(compressedValue, C_BIT_POS); + if ((y * _2n) / P !== aflag) + y = Fp.neg(y); + return { x: Fp.create(x), y: Fp.create(y) }; + } + else if (bytes.length === 96) { + // Check if the infinity flag is set + if ((bytes[0] & (1 << 6)) !== 0) + return bls12_381.G1.ProjectivePoint.ZERO.toAffine(); + const x = bytesToNumberBE(bytes.subarray(0, Fp.BYTES)); + const y = bytesToNumberBE(bytes.subarray(Fp.BYTES)); + return { x: Fp.create(x), y: Fp.create(y) }; + } + else { + throw new Error('Invalid point G1, expected 48/96 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) + return COMPRESSED_ZERO.slice(); + const P = Fp.ORDER; + let num; + num = bitSet(x, C_BIT_POS, Boolean((y * _2n) / P)); // set aflag + num = bitSet(num, S_BIT_POS, true); + return numberToBytesBE(num, Fp.BYTES); + } + else { + if (isZero) { + // 2x PUBLIC_KEY_LENGTH + const x = concatB(new Uint8Array([0x40]), new Uint8Array(2 * Fp.BYTES - 1)); + return x; + } + else { + return concatB(numberToBytesBE(x, Fp.BYTES), numberToBytesBE(y, Fp.BYTES)); + } + } + }, + }, + // G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1), + // where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where + // G² - 1 + // h2q + G2: { + Fp: Fp2, + // cofactor + h: BigInt('0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5'), + Gx: Fp2.fromBigTuple([ + BigInt('0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8'), + BigInt('0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e'), + ]), + // y = + // 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582, + // 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905 + Gy: Fp2.fromBigTuple([ + BigInt('0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801'), + BigInt('0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be'), + ]), + a: Fp2.ZERO, + b: Fp2.fromBigTuple([_4n, _4n]), + hEff: BigInt('0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551'), + htfDefaults: { ...htfDefaults }, + wrapPrivateKey: true, + allowInfinityPoint: true, + mapToCurve: (scalars) => { + const { x, y } = G2_SWU(Fp2.fromBigTuple(scalars)); + return isogenyMapG2(x, y); + }, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, P) => { + return P.multiplyUnsafe(bls12_381.params.x).negate().equals(G2psi(c, P)); // ψ(P) == [u](P) + // Older version: https://eprint.iacr.org/2019/814.pdf + // Ψ²(P) => Ψ³(P) => [z]Ψ³(P) where z = -x => [z]Ψ³(P) - Ψ²(P) + P == O + // return P.psi2().psi().mulNegX().subtract(psi2).add(P).isZero(); + }, + // Maps the point into the prime-order subgroup G2. + // clear_cofactor_bls12381_g2 from cfrg-hash-to-curve-11 + // https://eprint.iacr.org/2017/419.pdf + // prettier-ignore + clearCofactor: (c, P) => { + const x = bls12_381.params.x; + let t1 = P.multiplyUnsafe(x).negate(); // [-x]P + let t2 = G2psi(c, P); // Ψ(P) + let t3 = P.double(); // 2P + t3 = G2psi2(c, t3); // Ψ²(2P) + t3 = t3.subtract(t2); // Ψ²(2P) - Ψ(P) + t2 = t1.add(t2); // [-x]P + Ψ(P) + t2 = t2.multiplyUnsafe(x).negate(); // [x²]P - [x]Ψ(P) + t3 = t3.add(t2); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + t3 = t3.subtract(t1); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P + const Q = t3.subtract(P); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P - 1P + return Q; // [x²-x-1]P + [x-1]Ψ(P) + Ψ²(2P) + }, + fromBytes: (bytes) => { + bytes = bytes.slice(); + const m_byte = bytes[0] & 0xe0; + if (m_byte === 0x20 || m_byte === 0x60 || m_byte === 0xe0) { + throw new Error('Invalid encoding flag: ' + m_byte); + } + const bitC = m_byte & 0x80; // compression bit + const bitI = m_byte & 0x40; // point at infinity bit + const bitS = m_byte & 0x20; // sign bit + const L = Fp.BYTES; + const slc = (b, from, to) => bytesToNumberBE(b.slice(from, to)); + if (bytes.length === 96 && bitC) { + const b = bls12_381.params.G2b; + const P = Fp.ORDER; + bytes[0] = bytes[0] & 0x1f; // clear flags + if (bitI) { + // check that all bytes are 0 + if (bytes.reduce((p, c) => (p !== 0 ? c + 1 : c), 0) > 0) { + throw new Error('Invalid compressed G2 point'); + } + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x_1 = slc(bytes, 0, L); + const x_0 = slc(bytes, L, 2 * L); + const x = Fp2.create({ c0: Fp.create(x_0), c1: Fp.create(x_1) }); + const right = Fp2.add(Fp2.pow(x, _3n), b); // y² = x³ + 4 * (u+1) = x³ + b + let y = Fp2.sqrt(right); + const Y_bit = y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P ? _1n : _0n; + y = bitS > 0 && Y_bit > 0 ? y : Fp2.neg(y); + return { x, y }; + } + else if (bytes.length === 192 && !bitC) { + // Check if the infinity flag is set + if ((bytes[0] & (1 << 6)) !== 0) { + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x1 = slc(bytes, 0, L); + const x0 = slc(bytes, L, 2 * L); + const y1 = slc(bytes, 2 * L, 3 * L); + const y0 = slc(bytes, 3 * L, 4 * L); + return { x: Fp2.fromBigTuple([x0, x1]), y: Fp2.fromBigTuple([y0, y1]) }; + } + else { + throw new Error('Invalid point G2, expected 96/192 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const { BYTES: len, ORDER: P } = Fp; + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) + return concatB(COMPRESSED_ZERO, numberToBytesBE(_0n, len)); + const flag = Boolean(y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P); + // set compressed & sign bits (looks like different offsets than for G1/Fp?) + let x_1 = bitSet(x.c1, C_BIT_POS, flag); + x_1 = bitSet(x_1, S_BIT_POS, true); + return concatB(numberToBytesBE(x_1, len), numberToBytesBE(x.c0, len)); + } + else { + if (isZero) + return concatB(new Uint8Array([0x40]), new Uint8Array(4 * len - 1)); // bytes[0] |= 1 << 6; + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + return concatB(numberToBytesBE(x1, len), numberToBytesBE(x0, len), numberToBytesBE(y1, len), numberToBytesBE(y0, len)); + } + }, + Signature: { + // TODO: Optimize, it's very slow because of sqrt. + fromHex(hex) { + hex = ensureBytes('signatureHex', hex); + const P = Fp.ORDER; + const half = hex.length / 2; + if (half !== 48 && half !== 96) + throw new Error('Invalid compressed signature length, must be 96 or 192'); + const z1 = bytesToNumberBE(hex.slice(0, half)); + const z2 = bytesToNumberBE(hex.slice(half)); + // Indicates the infinity point + const bflag1 = bitGet(z1, I_BIT_POS); + if (bflag1 === _1n) + return bls12_381.G2.ProjectivePoint.ZERO; + const x1 = Fp.create(z1 & Fp.MASK); + const x2 = Fp.create(z2); + const x = Fp2.create({ c0: x2, c1: x1 }); + const y2 = Fp2.add(Fp2.pow(x, _3n), bls12_381.params.G2b); // y² = x³ + 4 + // The slow part + let y = Fp2.sqrt(y2); + if (!y) + throw new Error('Failed to find a square root'); + // Choose the y whose leftmost bit of the imaginary part is equal to the a_flag1 + // If y1 happens to be zero, then use the bit of y0 + const { re: y0, im: y1 } = Fp2.reim(y); + const aflag1 = bitGet(z1, 381); + const isGreater = y1 > _0n && (y1 * _2n) / P !== aflag1; + const isZero = y1 === _0n && (y0 * _2n) / P !== aflag1; + if (isGreater || isZero) + y = Fp2.neg(y); + const point = bls12_381.G2.ProjectivePoint.fromAffine({ x, y }); + point.assertValidity(); + return point; + }, + toRawBytes(point) { + return signatureG2ToRawBytes(point); + }, + toHex(point) { + return bytesToHex(signatureG2ToRawBytes(point)); + }, + }, + }, + params: { + x: BLS_X, + r: Fr.ORDER, // order; z⁴ − z² + 1; CURVE.n from other curves + }, + htfDefaults, + hash: sha256, + randomBytes, +}); +//# sourceMappingURL=bls12-381.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/bls12-381.js.map b/node_modules/@noble/curves/esm/bls12-381.js.map new file mode 100644 index 0000000..ed20a5d --- /dev/null +++ b/node_modules/@noble/curves/esm/bls12-381.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bls12-381.js","sourceRoot":"","sources":["../src/bls12-381.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,uFAAuF;AACvF,gDAAgD;AAChD,kGAAkG;AAClG,+EAA+E;AAC/E,EAAE;AACF,mGAAmG;AACnG,+EAA+E;AAC/E,+FAA+F;AAC/F,2FAA2F;AAC3F,wEAAwE;AACxE,EAAE;AACF,cAAc;AACd,gDAAgD;AAChD,4BAA4B;AAC5B,2FAA2F;AAC3F,mHAAmH;AACnH,0FAA0F;AAC1F,2HAA2H;AAC3H,6CAA6C;AAC7C,EAAE;AACF,eAAe;AACf,+BAA+B;AAC/B,8BAA8B;AAC9B,0DAA0D;AAC1D,4EAA4E;AAC5E,6DAA6D;AAC7D,6DAA6D;AAC7D,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,GAAG,EAAW,MAAM,mBAAmB,CAAC;AACjD,OAAO,KAAK,GAAG,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EACL,WAAW,IAAI,OAAO,EACtB,WAA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AAC;YACD,KAAK,CAAC,KAAyB;gBAC7B,OAAO,UAAU,CAAC,qBAAqB,CAAC,KAAK,CAAC,CAAC,CAAC;YAClD,CAAC;SACF;KACF;IACD,MAAM,EAAE;QACN,CAAC,EAAE,KAAK;QACR,CAAC,EAAE,EAAE,CAAC,KAAK,EAAE,gDAAgD;KAC9D;IACD,WAAW;IACX,IAAI,EAAE,MAAM;IACZ,WAAW;CACZ,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/bn254.js b/node_modules/@noble/curves/esm/bn254.js new file mode 100644 index 0000000..6b4f7c6 --- /dev/null +++ b/node_modules/@noble/curves/esm/bn254.js @@ -0,0 +1,22 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { weierstrass } from './abstract/weierstrass.js'; +import { getHash } from './_shortw_utils.js'; +import { Field } from './abstract/modular.js'; +/** + * bn254 pairing-friendly curve. + * Previously known as alt_bn_128, when it had 128-bit security. + * Recent research shown it's weaker, the naming has been adjusted to its prime bit count. + * https://github.com/zcash/zcash/issues/2502 + */ +export const bn254 = weierstrass({ + a: BigInt(0), + b: BigInt(3), + Fp: Field(BigInt('0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47')), + n: BigInt('0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001'), + Gx: BigInt(1), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); +//# sourceMappingURL=bn254.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/bn254.js.map b/node_modules/@noble/curves/esm/bn254.js.map new file mode 100644 index 0000000..e0ec023 --- /dev/null +++ b/node_modules/@noble/curves/esm/bn254.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bn254.js","sourceRoot":"","sources":["../src/bn254.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAC7C,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC9C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,KAAK,GAAG,WAAW,CAAC;IAC/B,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE,EAAE,KAAK,CAAC,MAAM,CAAC,oEAAoE,CAAC,CAAC;IACvF,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,OAAO,CAAC,MAAM,CAAC;CACnB,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/ed25519.js b/node_modules/@noble/curves/esm/ed25519.js new file mode 100644 index 0000000..ad84785 --- /dev/null +++ b/node_modules/@noble/curves/esm/ed25519.js @@ -0,0 +1,433 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha512 } from '@noble/hashes/sha512'; +import { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils'; +import { twistedEdwards } from './abstract/edwards.js'; +import { montgomery } from './abstract/montgomery.js'; +import { Field, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.js'; +import { bytesToHex, bytesToNumberLE, ensureBytes, equalBytes, numberToBytesLE, } from './abstract/utils.js'; +import { createHasher, expand_message_xmd } from './abstract/hash-to-curve.js'; +/** + * ed25519 Twisted Edwards curve with following addons: + * - X25519 ECDH + * - Ristretto cofactor elimination + * - Elligator hash-to-group / point indistinguishability + */ +const ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949'); +// √(-1) aka √(a) aka 2^((p-1)/4) +const ED25519_SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752'); +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _5n = BigInt(5); +// prettier-ignore +const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80); +function ed25519_pow_2_252_3(x) { + const P = ED25519_P; + const x2 = (x * x) % P; + const b2 = (x2 * x) % P; // x^3, 11 + const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111 + const b5 = (pow2(b4, _1n, P) * x) % P; // x^31 + const b10 = (pow2(b5, _5n, P) * b5) % P; + const b20 = (pow2(b10, _10n, P) * b10) % P; + const b40 = (pow2(b20, _20n, P) * b20) % P; + const b80 = (pow2(b40, _40n, P) * b40) % P; + const b160 = (pow2(b80, _80n, P) * b80) % P; + const b240 = (pow2(b160, _80n, P) * b80) % P; + const b250 = (pow2(b240, _10n, P) * b10) % P; + const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P; + // ^ To pow to (p+3)/8, multiply it by x. + return { pow_p_5_8, b2 }; +} +function adjustScalarBytes(bytes) { + // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar, + // set the three least significant bits of the first byte + bytes[0] &= 248; // 0b1111_1000 + // and the most significant bit of the last to zero, + bytes[31] &= 127; // 0b0111_1111 + // set the second most significant bit of the last byte to 1 + bytes[31] |= 64; // 0b0100_0000 + return bytes; +} +// sqrt(u/v) +function uvRatio(u, v) { + const P = ED25519_P; + const v3 = mod(v * v * v, P); // v³ + const v7 = mod(v3 * v3 * v, P); // v⁷ + // (p+3)/8 and (p-5)/8 + const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8; + let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8 + const vx2 = mod(v * x * x, P); // vx² + const root1 = x; // First root candidate + const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate + const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root + const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4) + const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1) + if (useRoot1) + x = root1; + if (useRoot2 || noRoot) + x = root2; // We return root2 anyway, for const-time + if (isNegativeLE(x, P)) + x = mod(-x, P); + return { isValid: useRoot1 || useRoot2, value: x }; +} +// Just in case +export const ED25519_TORSION_SUBGROUP = [ + '0100000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', + '0000000000000000000000000000000000000000000000000000000000000080', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05', + 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85', + '0000000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa', +]; +const Fp = Field(ED25519_P, undefined, true); +const ed25519Defaults = { + // Param: a + a: BigInt(-1), + // d is equal to -121665/121666 over finite field. + // Negative number is P - number, and division is invert(number, P) + d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'), + // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n + Fp, + // Subgroup order: how many points curve has + // 2n**252n + 27742317777372353535851937790883648493n; + n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'), + // Cofactor + h: BigInt(8), + // Base point (x, y) aka generator point + Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'), + Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'), + hash: sha512, + randomBytes, + adjustScalarBytes, + // dom2 + // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3. + // Constant-time, u/√v + uvRatio, +}; +export const ed25519 = /* @__PURE__ */ twistedEdwards(ed25519Defaults); +function ed25519_domain(data, ctx, phflag) { + if (ctx.length > 255) + throw new Error('Context is too big'); + return concatBytes(utf8ToBytes('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); +} +export const ed25519ctx = /* @__PURE__ */ twistedEdwards({ + ...ed25519Defaults, + domain: ed25519_domain, +}); +export const ed25519ph = /* @__PURE__ */ twistedEdwards({ + ...ed25519Defaults, + domain: ed25519_domain, + prehash: sha512, +}); +export const x25519 = /* @__PURE__ */ (() => montgomery({ + P: ED25519_P, + a: BigInt(486662), + montgomeryBits: 255, + nByteLength: 32, + Gu: BigInt(9), + powPminus2: (x) => { + const P = ED25519_P; + // x^(p-2) aka x^(2^255-21) + const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x); + return mod(pow2(pow_p_5_8, BigInt(3), P) * b2, P); + }, + adjustScalarBytes, + randomBytes, +}))(); +/** + * Converts ed25519 public key to x25519 public key. Uses formula: + * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)` + * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))` + * @example + * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey()); + * const aPriv = x25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub)) + */ +export function edwardsToMontgomeryPub(edwardsPub) { + const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y))); +} +export const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated +/** + * Converts ed25519 secret key to x25519 secret key. + * @example + * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey()); + * const aPriv = ed25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub) + */ +export function edwardsToMontgomeryPriv(edwardsPriv) { + const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32)); + return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32); +} +// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator) +// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since +// SageMath returns different root first and everything falls apart +const ELL2_C1 = (Fp.ORDER + BigInt(3)) / BigInt(8); // 1. c1 = (q + 3) / 8 # Integer arithmetic +const ELL2_C2 = Fp.pow(_2n, ELL2_C1); // 2. c2 = 2^c1 +const ELL2_C3 = Fp.sqrt(Fp.neg(Fp.ONE)); // 3. c3 = sqrt(-1) +const ELL2_C4 = (Fp.ORDER - BigInt(5)) / BigInt(8); // 4. c4 = (q - 5) / 8 # Integer arithmetic +const ELL2_J = BigInt(486662); +// prettier-ignore +function map_to_curve_elligator2_curve25519(u) { + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1 + let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not + let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2) + let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2 + tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4 + tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3 + tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3 + tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7 + let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8) + y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8) + let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3 + tv2 = Fp.sqr(y11); // 19. tv2 = y11^2 + tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd + let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1 + let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt + let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd + let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u + y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2 + let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3 + let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1) + tv2 = Fp.sqr(y21); // 28. tv2 = y21^2 + tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2 + let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt + tv2 = Fp.sqr(y1); // 32. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd + let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2 + let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4) + return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1) +} +const ELL2_C1_EDWARDS = FpSqrtEven(Fp, Fp.neg(BigInt(486664))); // sgn0(c1) MUST equal 0 +function map_to_curve_elligator2_edwards25519(u) { + const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) = + // map_to_curve_elligator2_curve25519(u) + let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd + xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1 + let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM + let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd + let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d) + let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd + let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0 + xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e) + xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e) + yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e) + yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e) + const inv = Fp.invertBatch([xd, yd]); // batch division + return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd) +} +const htf = /* @__PURE__ */ (() => createHasher(ed25519.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), { + DST: 'edwards25519_XMD:SHA-512_ELL2_RO_', + encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha512, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +function assertRstPoint(other) { + if (!(other instanceof RistPoint)) + throw new Error('RistrettoPoint expected'); +} +// √(-1) aka √(a) aka 2^((p-1)/4) +const SQRT_M1 = ED25519_SQRT_M1; +// √(ad - 1) +const SQRT_AD_MINUS_ONE = BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235'); +// 1 / √(a-d) +const INVSQRT_A_MINUS_D = BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578'); +// 1-d² +const ONE_MINUS_D_SQ = BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838'); +// (d-1)² +const D_MINUS_ONE_SQ = BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952'); +// Calculates 1/√(number) +const invertSqrt = (number) => uvRatio(_1n, number); +const MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const bytes255ToNumberLE = (bytes) => ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B); +// Computes Elligator map for Ristretto +// https://ristretto.group/formulas/elligator.html +function calcElligatorRistrettoMap(r0) { + const { d } = ed25519.CURVE; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const r = mod(SQRT_M1 * r0 * r0); // 1 + const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2 + let c = BigInt(-1); // 3 + const D = mod((c - d * r) * mod(r + d)); // 4 + let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5 + let s_ = mod(s * r0); // 6 + if (!isNegativeLE(s_, P)) + s_ = mod(-s_); + if (!Ns_D_is_sq) + s = s_; // 7 + if (!Ns_D_is_sq) + c = r; // 8 + const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9 + const s2 = s * s; + const W0 = mod((s + s) * D); // 10 + const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11 + const W2 = mod(_1n - s2); // 12 + const W3 = mod(_1n + s2); // 13 + return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2)); +} +/** + * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Ristretto was created to solve this. + * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +class RistPoint { + // Private property to discourage combining ExtendedPoint + RistrettoPoint + // Always use Ristretto encoding/decoding instead. + constructor(ep) { + this.ep = ep; + } + static fromAffine(ap) { + return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap)); + } + /** + * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://ristretto.group/formulas/elligator.html + * @param hex 64-byte output of a hash function + */ + static hashToCurve(hex) { + hex = ensureBytes('ristrettoHash', hex, 64); + const r1 = bytes255ToNumberLE(hex.slice(0, 32)); + const R1 = calcElligatorRistrettoMap(r1); + const r2 = bytes255ToNumberLE(hex.slice(32, 64)); + const R2 = calcElligatorRistrettoMap(r2); + return new RistPoint(R1.add(R2)); + } + /** + * Converts ristretto-encoded string to ristretto point. + * https://ristretto.group/formulas/decoding.html + * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding + */ + static fromHex(hex) { + hex = ensureBytes('ristrettoHex', hex, 32); + const { a, d } = ed25519.CURVE; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint'; + const s = bytes255ToNumberLE(hex); + // 1. Check that s_bytes is the canonical encoding of a field element, or else abort. + // 3. Check that s is non-negative, or else abort + if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P)) + throw new Error(emsg); + const s2 = mod(s * s); + const u1 = mod(_1n + a * s2); // 4 (a is -1) + const u2 = mod(_1n - a * s2); // 5 + const u1_2 = mod(u1 * u1); + const u2_2 = mod(u2 * u2); + const v = mod(a * d * u1_2 - u2_2); // 6 + const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7 + const Dx = mod(I * u2); // 8 + const Dy = mod(I * Dx * v); // 9 + let x = mod((s + s) * Dx); // 10 + if (isNegativeLE(x, P)) + x = mod(-x); // 10 + const y = mod(u1 * Dy); // 11 + const t = mod(x * y); // 12 + if (!isValid || isNegativeLE(t, P) || y === _0n) + throw new Error(emsg); + return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t)); + } + /** + * Encodes ristretto point to Uint8Array. + * https://ristretto.group/formulas/encoding.html + */ + toRawBytes() { + let { ex: x, ey: y, ez: z, et: t } = this.ep; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const u1 = mod(mod(z + y) * mod(z - y)); // 1 + const u2 = mod(x * y); // 2 + // Square root always exists + const u2sq = mod(u2 * u2); + const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3 + const D1 = mod(invsqrt * u1); // 4 + const D2 = mod(invsqrt * u2); // 5 + const zInv = mod(D1 * D2 * t); // 6 + let D; // 7 + if (isNegativeLE(t * zInv, P)) { + let _x = mod(y * SQRT_M1); + let _y = mod(x * SQRT_M1); + x = _x; + y = _y; + D = mod(D1 * INVSQRT_A_MINUS_D); + } + else { + D = D2; // 8 + } + if (isNegativeLE(x * zInv, P)) + y = mod(-y); // 9 + let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a)) + if (isNegativeLE(s, P)) + s = mod(-s); + return numberToBytesLE(s, 32); // 11 + } + toHex() { + return bytesToHex(this.toRawBytes()); + } + toString() { + return this.toHex(); + } + // Compare one point to another. + equals(other) { + assertRstPoint(other); + const { ex: X1, ey: Y1 } = this.ep; + const { ex: X2, ey: Y2 } = other.ep; + const mod = ed25519.CURVE.Fp.create; + // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2) + const one = mod(X1 * Y2) === mod(Y1 * X2); + const two = mod(Y1 * Y2) === mod(X1 * X2); + return one || two; + } + add(other) { + assertRstPoint(other); + return new RistPoint(this.ep.add(other.ep)); + } + subtract(other) { + assertRstPoint(other); + return new RistPoint(this.ep.subtract(other.ep)); + } + multiply(scalar) { + return new RistPoint(this.ep.multiply(scalar)); + } + multiplyUnsafe(scalar) { + return new RistPoint(this.ep.multiplyUnsafe(scalar)); + } +} +export const RistrettoPoint = /* @__PURE__ */ (() => { + if (!RistPoint.BASE) + RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE); + if (!RistPoint.ZERO) + RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO); + return RistPoint; +})(); +// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B +export const hashToRistretto255 = (msg, options) => { + const d = options.DST; + const DST = typeof d === 'string' ? utf8ToBytes(d) : d; + const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512); + const P = RistPoint.hashToCurve(uniform_bytes); + return P; +}; +export const hash_to_ristretto255 = hashToRistretto255; // legacy +//# sourceMappingURL=ed25519.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/ed25519.js.map b/node_modules/@noble/curves/esm/ed25519.js.map new file mode 100644 index 0000000..19410d9 --- /dev/null +++ b/node_modules/@noble/curves/esm/ed25519.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ed25519.js","sourceRoot":"","sources":["../src/ed25519.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,EAAgB,cAAc,EAA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I,CAAC,SAAS,CAAC,IAAI;QAAE,SAAS,CAAC,IAAI,GAAG,IAAI,SAAS,CAAC,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;IAChF,IAAI,CAAC,SAAS,CAAC,IAAI;QAAE,SAAS,CAAC,IAAI,GAAG,IAAI,SAAS,CAAC,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;IAChF,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC,EAAE,CAAC;AAEL,6EAA6E;AAC7E,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,GAAe,EAAE,OAAqB,EAAE,EAAE;IAC3E,MAAM,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC;IACtB,MAAM,GAAG,GAAG,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACvD,MAAM,aAAa,GAAG,kBAAkB,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,CAAC,CAAC;IAC/D,MAAM,CAAC,GAAG,SAAS,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC;IAC/C,OAAO,CAAC,CAAC;AACX,CAAC,CAAC;AACF,MAAM,CAAC,MAAM,oBAAoB,GAAG,kBAAkB,CAAC,CAAC,SAAS"} \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/ed448.js b/node_modules/@noble/curves/esm/ed448.js new file mode 100644 index 0000000..b582371 --- /dev/null +++ b/node_modules/@noble/curves/esm/ed448.js @@ -0,0 +1,392 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { shake256 } from '@noble/hashes/sha3'; +import { concatBytes, randomBytes, utf8ToBytes, wrapConstructor } from '@noble/hashes/utils'; +import { twistedEdwards } from './abstract/edwards.js'; +import { mod, pow2, Field, isNegativeLE } from './abstract/modular.js'; +import { montgomery } from './abstract/montgomery.js'; +import { createHasher, expand_message_xof } from './abstract/hash-to-curve.js'; +import { bytesToHex, bytesToNumberLE, ensureBytes, equalBytes, numberToBytesLE, } from './abstract/utils.js'; +/** + * Edwards448 (not Ed448-Goldilocks) curve with following addons: + * - X448 ECDH + * - Decaf cofactor elimination + * - Elligator hash-to-group / point indistinguishability + * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2 + */ +const shake256_114 = wrapConstructor(() => shake256.create({ dkLen: 114 })); +const shake256_64 = wrapConstructor(() => shake256.create({ dkLen: 64 })); +const ed448P = BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439'); +// prettier-ignore +const _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4), _11n = BigInt(11); +// prettier-ignore +const _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223); +// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4. +// Used for efficient square root calculation. +// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1] +function ed448_pow_Pminus3div4(x) { + const P = ed448P; + const b2 = (x * x * x) % P; + const b3 = (b2 * b2 * x) % P; + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b222 = (pow2(b220, _2n, P) * b2) % P; + const b223 = (pow2(b222, _1n, P) * x) % P; + return (pow2(b223, _223n, P) * b222) % P; +} +function adjustScalarBytes(bytes) { + // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, and the most + // significant bit of the last byte to 1. + bytes[0] &= 252; // 0b11111100 + // and the most significant bit of the last byte to 1. + bytes[55] |= 128; // 0b10000000 + // NOTE: is is NOOP for 56 bytes scalars (X25519/X448) + bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits) + return bytes; +} +// Constant-time ratio of u to v. Allows to combine inversion and square root u/√v. +// Uses algo from RFC8032 5.1.3. +function uvRatio(u, v) { + const P = ed448P; + // https://www.rfc-editor.org/rfc/rfc8032#section-5.2.3 + // To compute the square root of (u/v), the first step is to compute the + // candidate root x = (u/v)^((p+1)/4). This can be done using the + // following trick, to use a single modular powering for both the + // inversion of v and the square root: + // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p) + const u2v = mod(u * u * v, P); // u²v + const u3v = mod(u2v * u, P); // u³v + const u5v3 = mod(u3v * u2v * v, P); // u⁵v³ + const root = ed448_pow_Pminus3div4(u5v3); + const x = mod(u3v * root, P); + // Verify that root is exists + const x2 = mod(x * x, P); // x² + // If vx² = u, the recovered x-coordinate is x. Otherwise, no + // square root exists, and the decoding fails. + return { isValid: mod(x2 * v, P) === u, value: x }; +} +const Fp = Field(ed448P, 456, true); +const ED448_DEF = { + // Param: a + a: BigInt(1), + // -39081. Negative number is P - number + d: BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358'), + // Finite field 𝔽p over which we'll do calculations; 2n**448n - 2n**224n - 1n + Fp, + // Subgroup order: how many points curve has; + // 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n + n: BigInt('181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779'), + nBitLength: 456, + // Cofactor + h: BigInt(4), + // Base point (x, y) aka generator point + Gx: BigInt('224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710'), + Gy: BigInt('298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660'), + // SHAKE256(dom4(phflag,context)||x, 114) + hash: shake256_114, + randomBytes, + adjustScalarBytes, + // dom4 + domain: (data, ctx, phflag) => { + if (ctx.length > 255) + throw new Error(`Context is too big: ${ctx.length}`); + return concatBytes(utf8ToBytes('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); + }, + uvRatio, +}; +export const ed448 = /* @__PURE__ */ twistedEdwards(ED448_DEF); +// NOTE: there is no ed448ctx, since ed448 supports ctx by default +export const ed448ph = /* @__PURE__ */ twistedEdwards({ ...ED448_DEF, prehash: shake256_64 }); +export const x448 = /* @__PURE__ */ (() => montgomery({ + a: BigInt(156326), + montgomeryBits: 448, + nByteLength: 57, + P: ed448P, + Gu: BigInt(5), + powPminus2: (x) => { + const P = ed448P; + const Pminus3div4 = ed448_pow_Pminus3div4(x); + const Pminus3 = pow2(Pminus3div4, BigInt(2), P); + return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2 + }, + adjustScalarBytes, + randomBytes, +}))(); +/** + * Converts edwards448 public key to x448 public key. Uses formula: + * * `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)` + * * `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))` + * @example + * const aPub = ed448.getPublicKey(utils.randomPrivateKey()); + * x448.getSharedSecret(edwardsToMontgomery(aPub), edwardsToMontgomery(someonesPub)) + */ +export function edwardsToMontgomeryPub(edwardsPub) { + const { y } = ed448.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((y - _1n) * Fp.inv(y + _1n))); +} +export const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated +// Hash To Curve Elligator2 Map +const ELL2_C1 = (Fp.ORDER - BigInt(3)) / BigInt(4); // 1. c1 = (q - 3) / 4 # Integer arithmetic +const ELL2_J = BigInt(156326); +function map_to_curve_elligator2_curve448(u) { + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + let e1 = Fp.eql(tv1, Fp.ONE); // 2. e1 = tv1 == 1 + tv1 = Fp.cmov(tv1, Fp.ZERO, e1); // 3. tv1 = CMOV(tv1, 0, e1) # If Z * u^2 == -1, set tv1 = 0 + let xd = Fp.sub(Fp.ONE, tv1); // 4. xd = 1 - tv1 + let x1n = Fp.neg(ELL2_J); // 5. x1n = -J + let tv2 = Fp.sqr(xd); // 6. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 7. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, Fp.neg(ELL2_J)); // 8. gx1 = -J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 9. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 10. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 11. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 12. tv3 = gxd^2 + tv2 = Fp.mul(gx1, gxd); // 13. tv2 = gx1 * gxd # gx1 * gxd + tv3 = Fp.mul(tv3, tv2); // 14. tv3 = tv3 * tv2 # gx1 * gxd^3 + let y1 = Fp.pow(tv3, ELL2_C1); // 15. y1 = tv3^c1 # (gx1 * gxd^3)^((p - 3) / 4) + y1 = Fp.mul(y1, tv2); // 16. y1 = y1 * tv2 # gx1 * gxd * (gx1 * gxd^3)^((p - 3) / 4) + let x2n = Fp.mul(x1n, Fp.neg(tv1)); // 17. x2n = -tv1 * x1n # x2 = x2n / xd = -1 * u^2 * x1n / xd + let y2 = Fp.mul(y1, u); // 18. y2 = y1 * u + y2 = Fp.cmov(y2, Fp.ZERO, e1); // 19. y2 = CMOV(y2, 0, e1) + tv2 = Fp.sqr(y1); // 20. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 21. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx1); // 22. e2 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e2); // 23. xn = CMOV(x2n, x1n, e2) # If e2, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e2); // 24. y = CMOV(y2, y1, e2) # If e2, y = y1, else y = y2 + let e3 = Fp.isOdd(y); // 25. e3 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e2 !== e3); // 26. y = CMOV(y, -y, e2 XOR e3) + return { xn, xd, yn: y, yd: Fp.ONE }; // 27. return (xn, xd, y, 1) +} +function map_to_curve_elligator2_edwards448(u) { + let { xn, xd, yn, yd } = map_to_curve_elligator2_curve448(u); // 1. (xn, xd, yn, yd) = map_to_curve_elligator2_curve448(u) + let xn2 = Fp.sqr(xn); // 2. xn2 = xn^2 + let xd2 = Fp.sqr(xd); // 3. xd2 = xd^2 + let xd4 = Fp.sqr(xd2); // 4. xd4 = xd2^2 + let yn2 = Fp.sqr(yn); // 5. yn2 = yn^2 + let yd2 = Fp.sqr(yd); // 6. yd2 = yd^2 + let xEn = Fp.sub(xn2, xd2); // 7. xEn = xn2 - xd2 + let tv2 = Fp.sub(xEn, xd2); // 8. tv2 = xEn - xd2 + xEn = Fp.mul(xEn, xd2); // 9. xEn = xEn * xd2 + xEn = Fp.mul(xEn, yd); // 10. xEn = xEn * yd + xEn = Fp.mul(xEn, yn); // 11. xEn = xEn * yn + xEn = Fp.mul(xEn, _4n); // 12. xEn = xEn * 4 + tv2 = Fp.mul(tv2, xn2); // 13. tv2 = tv2 * xn2 + tv2 = Fp.mul(tv2, yd2); // 14. tv2 = tv2 * yd2 + let tv3 = Fp.mul(yn2, _4n); // 15. tv3 = 4 * yn2 + let tv1 = Fp.add(tv3, yd2); // 16. tv1 = tv3 + yd2 + tv1 = Fp.mul(tv1, xd4); // 17. tv1 = tv1 * xd4 + let xEd = Fp.add(tv1, tv2); // 18. xEd = tv1 + tv2 + tv2 = Fp.mul(tv2, xn); // 19. tv2 = tv2 * xn + let tv4 = Fp.mul(xn, xd4); // 20. tv4 = xn * xd4 + let yEn = Fp.sub(tv3, yd2); // 21. yEn = tv3 - yd2 + yEn = Fp.mul(yEn, tv4); // 22. yEn = yEn * tv4 + yEn = Fp.sub(yEn, tv2); // 23. yEn = yEn - tv2 + tv1 = Fp.add(xn2, xd2); // 24. tv1 = xn2 + xd2 + tv1 = Fp.mul(tv1, xd2); // 25. tv1 = tv1 * xd2 + tv1 = Fp.mul(tv1, xd); // 26. tv1 = tv1 * xd + tv1 = Fp.mul(tv1, yn2); // 27. tv1 = tv1 * yn2 + tv1 = Fp.mul(tv1, BigInt(-2)); // 28. tv1 = -2 * tv1 + let yEd = Fp.add(tv2, tv1); // 29. yEd = tv2 + tv1 + tv4 = Fp.mul(tv4, yd2); // 30. tv4 = tv4 * yd2 + yEd = Fp.add(yEd, tv4); // 31. yEd = yEd + tv4 + tv1 = Fp.mul(xEd, yEd); // 32. tv1 = xEd * yEd + let e = Fp.eql(tv1, Fp.ZERO); // 33. e = tv1 == 0 + xEn = Fp.cmov(xEn, Fp.ZERO, e); // 34. xEn = CMOV(xEn, 0, e) + xEd = Fp.cmov(xEd, Fp.ONE, e); // 35. xEd = CMOV(xEd, 1, e) + yEn = Fp.cmov(yEn, Fp.ONE, e); // 36. yEn = CMOV(yEn, 1, e) + yEd = Fp.cmov(yEd, Fp.ONE, e); // 37. yEd = CMOV(yEd, 1, e) + const inv = Fp.invertBatch([xEd, yEd]); // batch division + return { x: Fp.mul(xEn, inv[0]), y: Fp.mul(yEn, inv[1]) }; // 38. return (xEn, xEd, yEn, yEd) +} +const htf = /* @__PURE__ */ (() => createHasher(ed448.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards448(scalars[0]), { + DST: 'edwards448_XOF:SHAKE256_ELL2_RO_', + encodeDST: 'edwards448_XOF:SHAKE256_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 224, + expand: 'xof', + hash: shake256, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +function assertDcfPoint(other) { + if (!(other instanceof DcfPoint)) + throw new Error('DecafPoint expected'); +} +// 1-d +const ONE_MINUS_D = BigInt('39082'); +// 1-2d +const ONE_MINUS_TWO_D = BigInt('78163'); +// √(-d) +const SQRT_MINUS_D = BigInt('98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214'); +// 1 / √(-d) +const INVSQRT_MINUS_D = BigInt('315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716'); +// Calculates 1/√(number) +const invertSqrt = (number) => uvRatio(_1n, number); +const MAX_448B = BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const bytes448ToNumberLE = (bytes) => ed448.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_448B); +// Computes Elligator map for Decaf +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2 +function calcElligatorDecafMap(r0) { + const { d } = ed448.CURVE; + const P = ed448.CURVE.Fp.ORDER; + const mod = ed448.CURVE.Fp.create; + const r = mod(-(r0 * r0)); // 1 + const u0 = mod(d * (r - _1n)); // 2 + const u1 = mod((u0 + _1n) * (u0 - r)); // 3 + const { isValid: was_square, value: v } = uvRatio(ONE_MINUS_TWO_D, mod((r + _1n) * u1)); // 4 + let v_prime = v; // 5 + if (!was_square) + v_prime = mod(r0 * v); + let sgn = _1n; // 6 + if (!was_square) + sgn = mod(-_1n); + const s = mod(v_prime * (r + _1n)); // 7 + let s_abs = s; + if (isNegativeLE(s, P)) + s_abs = mod(-s); + const s2 = s * s; + const W0 = mod(s_abs * _2n); // 8 + const W1 = mod(s2 + _1n); // 9 + const W2 = mod(s2 - _1n); // 10 + const W3 = mod(v_prime * s * (r - _1n) * ONE_MINUS_TWO_D + sgn); // 11 + return new ed448.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2)); +} +/** + * Each ed448/ExtendedPoint has 4 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Decaf was created to solve this. + * Decaf point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +class DcfPoint { + // Private property to discourage combining ExtendedPoint + DecafPoint + // Always use Decaf encoding/decoding instead. + constructor(ep) { + this.ep = ep; + } + static fromAffine(ap) { + return new DcfPoint(ed448.ExtendedPoint.fromAffine(ap)); + } + /** + * Takes uniform output of 112-byte hash function like shake256 and converts it to `DecafPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2 + * @param hex 112-byte output of a hash function + */ + static hashToCurve(hex) { + hex = ensureBytes('decafHash', hex, 112); + const r1 = bytes448ToNumberLE(hex.slice(0, 56)); + const R1 = calcElligatorDecafMap(r1); + const r2 = bytes448ToNumberLE(hex.slice(56, 112)); + const R2 = calcElligatorDecafMap(r2); + return new DcfPoint(R1.add(R2)); + } + /** + * Converts decaf-encoded string to decaf point. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-decode-2 + * @param hex Decaf-encoded 56 bytes. Not every 56-byte string is valid decaf encoding + */ + static fromHex(hex) { + hex = ensureBytes('decafHex', hex, 56); + const { d } = ed448.CURVE; + const P = ed448.CURVE.Fp.ORDER; + const mod = ed448.CURVE.Fp.create; + const emsg = 'DecafPoint.fromHex: the hex is not valid encoding of DecafPoint'; + const s = bytes448ToNumberLE(hex); + // 1. Check that s_bytes is the canonical encoding of a field element, or else abort. + // 2. Check that s is non-negative, or else abort + if (!equalBytes(numberToBytesLE(s, 56), hex) || isNegativeLE(s, P)) + throw new Error(emsg); + const s2 = mod(s * s); // 1 + const u1 = mod(_1n + s2); // 2 + const u1sq = mod(u1 * u1); + const u2 = mod(u1sq - _4n * d * s2); // 3 + const { isValid, value: invsqrt } = invertSqrt(mod(u2 * u1sq)); // 4 + let u3 = mod((s + s) * invsqrt * u1 * SQRT_MINUS_D); // 5 + if (isNegativeLE(u3, P)) + u3 = mod(-u3); + const x = mod(u3 * invsqrt * u2 * INVSQRT_MINUS_D); // 6 + const y = mod((_1n - s2) * invsqrt * u1); // 7 + const t = mod(x * y); // 8 + if (!isValid) + throw new Error(emsg); + return new DcfPoint(new ed448.ExtendedPoint(x, y, _1n, t)); + } + /** + * Encodes decaf point to Uint8Array. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-encode-2 + */ + toRawBytes() { + let { ex: x, ey: _y, ez: z, et: t } = this.ep; + const P = ed448.CURVE.Fp.ORDER; + const mod = ed448.CURVE.Fp.create; + const u1 = mod(mod(x + t) * mod(x - t)); // 1 + const x2 = mod(x * x); + const { value: invsqrt } = invertSqrt(mod(u1 * ONE_MINUS_D * x2)); // 2 + let ratio = mod(invsqrt * u1 * SQRT_MINUS_D); // 3 + if (isNegativeLE(ratio, P)) + ratio = mod(-ratio); + const u2 = mod(INVSQRT_MINUS_D * ratio * z - t); // 4 + let s = mod(ONE_MINUS_D * invsqrt * x * u2); // 5 + if (isNegativeLE(s, P)) + s = mod(-s); + return numberToBytesLE(s, 56); + } + toHex() { + return bytesToHex(this.toRawBytes()); + } + toString() { + return this.toHex(); + } + // Compare one point to another. + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-equals-2 + equals(other) { + assertDcfPoint(other); + const { ex: X1, ey: Y1 } = this.ep; + const { ex: X2, ey: Y2 } = other.ep; + const mod = ed448.CURVE.Fp.create; + // (x1 * y2 == y1 * x2) + return mod(X1 * Y2) === mod(Y1 * X2); + } + add(other) { + assertDcfPoint(other); + return new DcfPoint(this.ep.add(other.ep)); + } + subtract(other) { + assertDcfPoint(other); + return new DcfPoint(this.ep.subtract(other.ep)); + } + multiply(scalar) { + return new DcfPoint(this.ep.multiply(scalar)); + } + multiplyUnsafe(scalar) { + return new DcfPoint(this.ep.multiplyUnsafe(scalar)); + } +} +export const DecafPoint = /* @__PURE__ */ (() => { + // decaf448 base point is ed448 base x 2 + // https://github.com/dalek-cryptography/curve25519-dalek/blob/59837c6ecff02b77b9d5ff84dbc239d0cf33ef90/vendor/ristretto.sage#L699 + if (!DcfPoint.BASE) + DcfPoint.BASE = new DcfPoint(ed448.ExtendedPoint.BASE).multiply(_2n); + if (!DcfPoint.ZERO) + DcfPoint.ZERO = new DcfPoint(ed448.ExtendedPoint.ZERO); + return DcfPoint; +})(); +// Hashing to decaf448. https://www.rfc-editor.org/rfc/rfc9380#appendix-C +export const hashToDecaf448 = (msg, options) => { + const d = options.DST; + const DST = typeof d === 'string' ? utf8ToBytes(d) : d; + const uniform_bytes = expand_message_xof(msg, DST, 112, 224, shake256); + const P = DcfPoint.hashToCurve(uniform_bytes); + return P; +}; +export const hash_to_decaf448 = hashToDecaf448; // legacy +//# sourceMappingURL=ed448.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/ed448.js.map b/node_modules/@noble/curves/esm/ed448.js.map new file mode 100644 index 0000000..833317b --- /dev/null +++ b/node_modules/@noble/curves/esm/ed448.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ed448.js","sourceRoot":"","sources":["../src/ed448.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAC7F,OAAO,EAAgB,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AACtD,OAAO,EAAE,YAAY,EAAgB,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAC7F,OAAO,EACL,UAAU,EACV,eAAe,EACf,WAAW,EACX,UAAU,EAEV,eAAe,GAChB,MAAM,qBAAqB,CAAC;AAG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AAG,IAAI,QAAQ,CAAC,KAAK,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;IACzF,IAAI,CAAC,QAAQ,CAAC,IAAI;QAAE,QAAQ,CAAC,IAAI,GAAG,IAAI,QAAQ,CAAC,KAAK,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;IAC3E,OAAO,QAAQ,CAAC;AAClB,CAAC,CAAC,EAAE,CAAC;AAEL,yEAAyE;AACzE,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,GAAe,EAAE,OAAqB,EAAE,EAAE;IACvE,MAAM,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC;IACtB,MAAM,GAAG,GAAG,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACvD,MAAM,aAAa,GAAG,kBAAkB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,QAAQ,CAAC,CAAC;IACvE,MAAM,CAAC,GAAG,QAAQ,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC;IAC9C,OAAO,CAAC,CAAC;AACX,CAAC,CAAC;AACF,MAAM,CAAC,MAAM,gBAAgB,GAAG,cAAc,CAAC,CAAC,SAAS"} \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/index.js b/node_modules/@noble/curves/esm/index.js new file mode 100644 index 0000000..ac4f223 --- /dev/null +++ b/node_modules/@noble/curves/esm/index.js @@ -0,0 +1,3 @@ +"use strict"; +throw new Error('Incorrect usage. Import submodules instead'); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/index.js.map b/node_modules/@noble/curves/esm/index.js.map new file mode 100644 index 0000000..b5117dc --- /dev/null +++ b/node_modules/@noble/curves/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/jubjub.js b/node_modules/@noble/curves/esm/jubjub.js new file mode 100644 index 0000000..1f2cc8e --- /dev/null +++ b/node_modules/@noble/curves/esm/jubjub.js @@ -0,0 +1,54 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha512 } from '@noble/hashes/sha512'; +import { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils'; +import { twistedEdwards } from './abstract/edwards.js'; +import { blake2s } from '@noble/hashes/blake2s'; +import { Field } from './abstract/modular.js'; +/** + * jubjub Twisted Edwards curve. + * https://neuromancer.sk/std/other/JubJub + * jubjub does not use EdDSA, so `hash`/sha512 params are passed because interface expects them. + */ +export const jubjub = /* @__PURE__ */ twistedEdwards({ + // Params: a, d + a: BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000'), + d: BigInt('0x2a9318e74bfa2b48f5fd9207e6bd7fd4292d7f6d37579d2601065fd6d6343eb1'), + // Finite field 𝔽p over which we'll do calculations + // Same value as bls12-381 Fr (not Fp) + Fp: Field(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')), + // Subgroup order: how many points curve has + n: BigInt('0xe7db4ea6533afa906673b0101343b00a6682093ccc81082d0970e5ed6f72cb7'), + // Cofactor + h: BigInt(8), + // Base point (x, y) aka generator point + Gx: BigInt('0x11dafe5d23e1218086a365b99fbf3d3be72f6afd7d1f72623e6b071492d1122b'), + Gy: BigInt('0x1d523cf1ddab1a1793132e78c866c0c33e26ba5cc220fed7cc3f870e59d292aa'), + hash: sha512, + randomBytes, +}); +const GH_FIRST_BLOCK = utf8ToBytes('096b36a5804bfacef1691e173c366a47ff5ba84a44f26ddd7e8d9f79d5b42df0'); +// Returns point at JubJub curve which is prime order and not zero +export function groupHash(tag, personalization) { + const h = blake2s.create({ personalization, dkLen: 32 }); + h.update(GH_FIRST_BLOCK); + h.update(tag); + // NOTE: returns ExtendedPoint, in case it will be multiplied later + let p = jubjub.ExtendedPoint.fromHex(h.digest()); + // NOTE: cannot replace with isSmallOrder, returns Point*8 + p = p.multiply(jubjub.CURVE.h); + if (p.equals(jubjub.ExtendedPoint.ZERO)) + throw new Error('Point has small order'); + return p; +} +export function findGroupHash(m, personalization) { + const tag = concatBytes(m, new Uint8Array([0])); + for (let i = 0; i < 256; i++) { + tag[tag.length - 1] = i; + try { + return groupHash(tag, personalization); + } + catch (e) { } + } + throw new Error('findGroupHash tag overflow'); +} +//# sourceMappingURL=jubjub.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/jubjub.js.map b/node_modules/@noble/curves/esm/jubjub.js.map new file mode 100644 index 0000000..e89b5c4 --- /dev/null +++ b/node_modules/@noble/curves/esm/jubjub.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jubjub.js","sourceRoot":"","sources":["../src/jubjub.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAChD,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAE9C;;;;GAIG;AAEH,MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,cAAc,CAAC;IACnD,eAAe;IACf,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,oDAAoD;IACpD,sCAAsC;IACtC,EAAE,EAAE,KAAK,CAAC,MAAM,CAAC,oEAAoE,CAAC,CAAC;IACvF,4CAA4C;IAC5C,CAAC,EAAE,MAAM,CAAC,mEAAmE,CAAC;IAC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,CAAC,GAAG,EAAE,eAAe,CAAC,CAAC;SACxC;QAAC,OAAO,CAAC,EAAE,GAAE;KACf;IACD,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;AAChD,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/p256.js b/node_modules/@noble/curves/esm/p256.js new file mode 100644 index 0000000..5e2e89e --- /dev/null +++ b/node_modules/@noble/curves/esm/p256.js @@ -0,0 +1,42 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { createCurve } from './_shortw_utils.js'; +import { sha256 } from '@noble/hashes/sha256'; +import { Field } from './abstract/modular.js'; +import { mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import { createHasher } from './abstract/hash-to-curve.js'; +// NIST secp256r1 aka p256 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256 +const Fp = Field(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff')); +const CURVE_A = Fp.create(BigInt('-3')); +const CURVE_B = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'); +// prettier-ignore +export const p256 = createCurve({ + a: CURVE_A, + b: CURVE_B, + Fp, + // Curve order, total count of valid points in the field + n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'), + // Base (generator) point (x, y) + Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'), + Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'), + h: BigInt(1), + lowS: false, +}, sha256); +export const secp256r1 = p256; +const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-10')), +}))(); +const htf = /* @__PURE__ */ (() => createHasher(secp256r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P256_XMD:SHA-256_SSWU_RO_', + encodeDST: 'P256_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +//# sourceMappingURL=p256.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/p256.js.map b/node_modules/@noble/curves/esm/p256.js.map new file mode 100644 index 0000000..1efec39 --- /dev/null +++ b/node_modules/@noble/curves/esm/p256.js.map @@ -0,0 +1 @@ +{"version":3,"file":"p256.js","sourceRoot":"","sources":["../src/p256.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC9C,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAE3D,0BAA0B;AAC1B,0EAA0E;AAE1E,MAAM,EAAE,GAAG,KAAK,CAAC,MAAM,CAAC,oEAAoE,CAAC,CAAC,CAAC;AAC/F,MAAM,OAAO,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AACxC,MAAM,OAAO,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAE7F,kBAAkB;AAClB,MAAM,CAAC,MAAM,IAAI,GAAG,WAAW,CAAC;IAC9B,CAAC,EAAE,OAAO;IACV,CAAC,EAAE,OAAO;IACV,EAAE;IACF,wDAAwD;IACxD,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,gCAAgC;IAChC,EAAE,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAChF,EAAE,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAChF,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,IAAI,EAAE,KAAK;CACH,EAAE,MAAM,CAAC,CAAC;AACpB,MAAM,CAAC,MAAM,SAAS,GAAG,IAAI,CAAC;AAE9B,MAAM,MAAM,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CACnC,mBAAmB,CAAC,EAAE,EAAE;IACtB,CAAC,EAAE,OAAO;IACV,CAAC,EAAE,OAAO;IACV,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;CAC5B,CAAC,CAAC,EAAE,CAAC;AAER,MAAM,GAAG,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAChC,YAAY,CAAC,SAAS,CAAC,eAAe,EAAE,CAAC,OAAiB,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE;IACjF,GAAG,EAAE,2BAA2B;IAChC,SAAS,EAAE,2BAA2B;IACtC,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,MAAM;CACb,CAAC,CAAC,EAAE,CAAC;AACR,MAAM,CAAC,MAAM,WAAW,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACrE,MAAM,CAAC,MAAM,aAAa,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/p384.js b/node_modules/@noble/curves/esm/p384.js new file mode 100644 index 0000000..21d9308 --- /dev/null +++ b/node_modules/@noble/curves/esm/p384.js @@ -0,0 +1,46 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { createCurve } from './_shortw_utils.js'; +import { sha384 } from '@noble/hashes/sha512'; +import { Field } from './abstract/modular.js'; +import { mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import { createHasher } from './abstract/hash-to-curve.js'; +// NIST secp384r1 aka p384 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-384 +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'); +const Fp = Field(P); +const CURVE_A = Fp.create(BigInt('-3')); +// prettier-ignore +const CURVE_B = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'); +// prettier-ignore +export const p384 = createCurve({ + a: CURVE_A, + b: CURVE_B, + Fp, + // Curve order, total count of valid points in the field. + n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'), + // Base (generator) point (x, y) + Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'), + Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'), + h: BigInt(1), + lowS: false, +}, sha384); +export const secp384r1 = p384; +const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-12')), +}))(); +const htf = /* @__PURE__ */ (() => createHasher(secp384r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P384_XMD:SHA-384_SSWU_RO_', + encodeDST: 'P384_XMD:SHA-384_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 192, + expand: 'xmd', + hash: sha384, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +//# sourceMappingURL=p384.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/p384.js.map b/node_modules/@noble/curves/esm/p384.js.map new file mode 100644 index 0000000..bf8b8ed --- /dev/null +++ b/node_modules/@noble/curves/esm/p384.js.map @@ -0,0 +1 @@ +{"version":3,"file":"p384.js","sourceRoot":"","sources":["../src/p384.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC9C,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAE3D,0BAA0B;AAC1B,0EAA0E;AAE1E,0CAA0C;AAC1C,kBAAkB;AAClB,MAAM,CAAC,GAAG,MAAM,CAAC,oGAAoG,CAAC,CAAC;AACvH,MAAM,EAAE,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AACpB,MAAM,OAAO,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AACxC,kBAAkB;AAClB,MAAM,OAAO,GAAG,MAAM,CAAC,oGAAoG,CAAC,CAAC;AAE7H,kBAAkB;AAClB,MAAM,CAAC,MAAM,IAAI,GAAG,WAAW,CAAC;IAC9B,CAAC,EAAE,OAAO;IACV,CAAC,EAAE,OAAO;IACV,EAAE;IACF,yDAAyD;IACzD,CAAC,EAAE,MAAM,CAAC,oGAAoG,CAAC;IAC/G,gCAAgC;IAChC,EAAE,EAAE,MAAM,CAAC,oGAAoG,CAAC;IAChH,EAAE,EAAE,MAAM,CAAC,oGAAoG,CAAC;IAChH,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,IAAI,EAAE,KAAK;CACH,EAAE,MAAM,CAAC,CAAC;AACpB,MAAM,CAAC,MAAM,SAAS,GAAG,IAAI,CAAC;AAE9B,MAAM,MAAM,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CACnC,mBAAmB,CAAC,EAAE,EAAE;IACtB,CAAC,EAAE,OAAO;IACV,CAAC,EAAE,OAAO;IACV,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;CAC5B,CAAC,CAAC,EAAE,CAAC;AAER,MAAM,GAAG,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAChC,YAAY,CAAC,SAAS,CAAC,eAAe,EAAE,CAAC,OAAiB,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE;IACjF,GAAG,EAAE,2BAA2B;IAChC,SAAS,EAAE,2BAA2B;IACtC,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,MAAM;CACb,CAAC,CAAC,EAAE,CAAC;AACR,MAAM,CAAC,MAAM,WAAW,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACrE,MAAM,CAAC,MAAM,aAAa,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/p521.js b/node_modules/@noble/curves/esm/p521.js new file mode 100644 index 0000000..0131155 --- /dev/null +++ b/node_modules/@noble/curves/esm/p521.js @@ -0,0 +1,53 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { createCurve } from './_shortw_utils.js'; +import { sha512 } from '@noble/hashes/sha512'; +import { Field } from './abstract/modular.js'; +import { mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import { createHasher } from './abstract/hash-to-curve.js'; +// NIST secp521r1 aka p521 +// Note that it's 521, which differs from 512 of its hash function. +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-521 +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const Fp = Field(P); +const CURVE = { + a: Fp.create(BigInt('-3')), + b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'), + Fp, + n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'), + Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'), + Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'), + h: BigInt(1), +}; +// prettier-ignore +export const p521 = createCurve({ + a: CURVE.a, + b: CURVE.b, + Fp, + // Curve order, total count of valid points in the field + n: CURVE.n, + Gx: CURVE.Gx, + Gy: CURVE.Gy, + h: CURVE.h, + lowS: false, + allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b +}, sha512); +export const secp521r1 = p521; +const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, { + A: CURVE.a, + B: CURVE.b, + Z: Fp.create(BigInt('-4')), +}))(); +const htf = /* @__PURE__ */ (() => createHasher(secp521r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P521_XMD:SHA-512_SSWU_RO_', + encodeDST: 'P521_XMD:SHA-512_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 256, + expand: 'xmd', + hash: sha512, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +//# sourceMappingURL=p521.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/p521.js.map b/node_modules/@noble/curves/esm/p521.js.map new file mode 100644 index 0000000..cd24eb5 --- /dev/null +++ b/node_modules/@noble/curves/esm/p521.js.map @@ -0,0 +1 @@ +{"version":3,"file":"p521.js","sourceRoot":"","sources":["../src/p521.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC9C,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAE3D,0BAA0B;AAC1B,mEAAmE;AACnE,0EAA0E;AAE1E,0CAA0C;AAC1C,kBAAkB;AAClB,MAAM,CAAC,GAAG,MAAM,CAAC,uIAAuI,CAAC,CAAC;AAC1J,MAAM,EAAE,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAEpB,MAAM,KAAK,GAAG;IACZ,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC1B,CAAC,EAAE,MAAM,CACP,wIAAwI,CACzI;IACD,EAAE;IACF,CAAC,EAAE,MAAM,CACP,wIAAwI,CACzI;IACD,EAAE,EAAE,MAAM,CACR,wIAAwI,CACzI;IACD,EAAE,EAAE,MAAM,CACR,wIAAwI,CACzI;IACD,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;CACb,CAAC;AAEF,kBAAkB;AAClB,MAAM,CAAC,MAAM,IAAI,GAAG,WAAW,CAAC;IAC9B,CAAC,EAAE,KAAK,CAAC,CAAC;IACV,CAAC,EAAE,KAAK,CAAC,CAAC;IACV,EAAE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/package.json b/node_modules/@noble/curves/esm/package.json new file mode 100644 index 0000000..7f1fc33 --- /dev/null +++ b/node_modules/@noble/curves/esm/package.json @@ -0,0 +1,4 @@ +{ + "type": "module", + "sideEffects": false +} diff --git a/node_modules/@noble/curves/esm/pasta.js b/node_modules/@noble/curves/esm/pasta.js new file mode 100644 index 0000000..fa5ca52 --- /dev/null +++ b/node_modules/@noble/curves/esm/pasta.js @@ -0,0 +1,30 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { weierstrass } from './abstract/weierstrass.js'; +import { getHash } from './_shortw_utils.js'; +import * as mod from './abstract/modular.js'; +export const p = BigInt('0x40000000000000000000000000000000224698fc094cf91b992d30ed00000001'); +export const q = BigInt('0x40000000000000000000000000000000224698fc0994a8dd8c46eb2100000001'); +// https://neuromancer.sk/std/other/Pallas +export const pallas = weierstrass({ + a: BigInt(0), + b: BigInt(5), + Fp: mod.Field(p), + n: q, + Gx: mod.mod(BigInt(-1), p), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); +// https://neuromancer.sk/std/other/Vesta +export const vesta = weierstrass({ + a: BigInt(0), + b: BigInt(5), + Fp: mod.Field(q), + n: p, + Gx: mod.mod(BigInt(-1), q), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); +//# sourceMappingURL=pasta.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/pasta.js.map b/node_modules/@noble/curves/esm/pasta.js.map new file mode 100644 index 0000000..4942dd2 --- /dev/null +++ b/node_modules/@noble/curves/esm/pasta.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pasta.js","sourceRoot":"","sources":["../src/pasta.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAC7C,OAAO,KAAK,GAAG,MAAM,uBAAuB,CAAC;AAE7C,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAC9F,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAE9F,0CAA0C;AAC1C,MAAM,CAAC,MAAM,MAAM,GAAG,WAAW,CAAC;IAChC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC;IAChB,CAAC,EAAE,CAAC;IACJ,EAAE,EAAE,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAC1B,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,OAAO,CAAC,MAAM,CAAC;CACnB,CAAC,CAAC;AACH,yCAAyC;AACzC,MAAM,CAAC,MAAM,KAAK,GAAG,WAAW,CAAC;IAC/B,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC;IAChB,CAAC,EAAE,CAAC;IACJ,EAAE,EAAE,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAC1B,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,OAAO,CAAC,MAAM,CAAC;CACnB,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/secp256k1.js b/node_modules/@noble/curves/esm/secp256k1.js new file mode 100644 index 0000000..eb36ebc --- /dev/null +++ b/node_modules/@noble/curves/esm/secp256k1.js @@ -0,0 +1,254 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { randomBytes } from '@noble/hashes/utils'; +import { Field, mod, pow2 } from './abstract/modular.js'; +import { mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import { bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE } from './abstract/utils.js'; +import { createHasher, isogenyMap } from './abstract/hash-to-curve.js'; +import { createCurve } from './_shortw_utils.js'; +const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'); +const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); +const _1n = BigInt(1); +const _2n = BigInt(2); +const divNearest = (a, b) => (a + b / _2n) / b; +/** + * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit. + * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00] + */ +function sqrtMod(y) { + const P = secp256k1P; + // prettier-ignore + const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + // prettier-ignore + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = (y * y * y) % P; // x^3, 11 + const b3 = (b2 * b2 * y) % P; // x^7 + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b223 = (pow2(b220, _3n, P) * b3) % P; + const t1 = (pow2(b223, _23n, P) * b22) % P; + const t2 = (pow2(t1, _6n, P) * b2) % P; + const root = pow2(t2, _2n, P); + if (!Fp.eql(Fp.sqr(root), y)) + throw new Error('Cannot find square root'); + return root; +} +const Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod }); +export const secp256k1 = createCurve({ + a: BigInt(0), + b: BigInt(7), + Fp, + n: secp256k1N, + // Base point (x, y) aka generator point + Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), + Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), + h: BigInt(1), + lowS: true, + /** + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 + */ + endo: { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + splitScalar: (k) => { + const n = secp256k1N; + const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); + const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); + const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); + const b2 = a1; + const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16) + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = mod(k - c1 * a1 - c2 * a2, n); + let k2 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) + k1 = n - k1; + if (k2neg) + k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error('splitScalar: Endomorphism failed, k=' + k); + } + return { k1neg, k1, k2neg, k2 }; + }, + }, +}, sha256); +// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code. +// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki +const _0n = BigInt(0); +const fe = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1P; +const ge = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1N; +/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */ +const TAGGED_HASH_PREFIXES = {}; +function taggedHash(tag, ...messages) { + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === undefined) { + const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + tagP = concatBytes(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return sha256(concatBytes(tagP, ...messages)); +} +// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03 +const pointToBytes = (point) => point.toRawBytes(true).slice(1); +const numTo32b = (n) => numberToBytesBE(n, 32); +const modP = (x) => mod(x, secp256k1P); +const modN = (x) => mod(x, secp256k1N); +const Point = secp256k1.ProjectivePoint; +const GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b); +// Calculate point, scalar and bytes +function schnorrGetExtPubKey(priv) { + let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey + let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside + const scalar = p.hasEvenY() ? d_ : modN(-d_); + return { scalar: scalar, bytes: pointToBytes(p) }; +} +/** + * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point. + * @returns valid point checked for being on-curve + */ +function lift_x(x) { + if (!fe(x)) + throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p. + const xx = modP(x * x); + const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p. + let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p. + if (y % _2n !== _0n) + y = modP(-y); // Return the unique point P such that x(P) = x and + const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise. + p.assertValidity(); + return p; +} +/** + * Create tagged hash, convert it to bigint, reduce modulo-n. + */ +function challenge(...args) { + return modN(bytesToNumberBE(taggedHash('BIP0340/challenge', ...args))); +} +/** + * Schnorr public key is just `x` coordinate of Point as per BIP340. + */ +function schnorrGetPublicKey(privateKey) { + return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G) +} +/** + * Creates Schnorr signature as per BIP340. Verifies itself before returning anything. + * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous. + */ +function schnorrSign(message, privateKey, auxRand = randomBytes(32)) { + const m = ensureBytes('message', message); + const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder + const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array + const t = numTo32b(d ^ bytesToNumberBE(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a) + const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m) + const k_ = modN(bytesToNumberBE(rand)); // Let k' = int(rand) mod n + if (k_ === _0n) + throw new Error('sign failed: k is zero'); // Fail if k' = 0. + const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G. + const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n. + const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n). + sig.set(rx, 0); + sig.set(numTo32b(modN(k + e * d)), 32); + // If Verify(bytes(P), m, sig) (see below) returns failure, abort + if (!schnorrVerify(sig, m, px)) + throw new Error('sign: Invalid signature produced'); + return sig; +} +/** + * Verifies Schnorr signature. + * Will swallow errors & return false except for initial type validation of arguments. + */ +function schnorrVerify(signature, message, publicKey) { + const sig = ensureBytes('signature', signature, 64); + const m = ensureBytes('message', message); + const pub = ensureBytes('publicKey', publicKey, 32); + try { + const P = lift_x(bytesToNumberBE(pub)); // P = lift_x(int(pk)); fail if that fails + const r = bytesToNumberBE(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p. + if (!fe(r)) + return false; + const s = bytesToNumberBE(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n. + if (!ge(s)) + return false; + const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n + const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P + if (!R || !R.hasEvenY() || R.toAffine().x !== r) + return false; // -eP == (n-e)P + return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r. + } + catch (error) { + return false; + } +} +export const schnorr = /* @__PURE__ */ (() => ({ + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + utils: { + randomPrivateKey: secp256k1.utils.randomPrivateKey, + lift_x, + pointToBytes, + numberToBytesBE, + bytesToNumberBE, + taggedHash, + mod, + }, +}))(); +const isoMap = /* @__PURE__ */ (() => isogenyMap(Fp, [ + // xNum + [ + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7', + '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581', + '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262', + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c', + ], + // xDen + [ + '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b', + '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c', + '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3', + '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931', + '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84', + ], + // yDen + [ + '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b', + '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573', + '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], +].map((i) => i.map((j) => BigInt(j)))))(); +const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, { + A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'), + B: BigInt('1771'), + Z: Fp.create(BigInt('-11')), +}))(); +const htf = /* @__PURE__ */ (() => createHasher(secp256k1.ProjectivePoint, (scalars) => { + const { x, y } = mapSWU(Fp.create(scalars[0])); + return isoMap(x, y); +}, { + DST: 'secp256k1_XMD:SHA-256_SSWU_RO_', + encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +//# sourceMappingURL=secp256k1.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/esm/secp256k1.js.map b/node_modules/@noble/curves/esm/secp256k1.js.map new file mode 100644 index 0000000..692678a --- /dev/null +++ b/node_modules/@noble/curves/esm/secp256k1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"secp256k1.js","sourceRoot":"","sources":["../src/secp256k1.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAA8B,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAE5F,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM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AAM,CAAC,MAAM,CAAC;IACjB,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;CAC5B,CAAC,CAAC,EAAE,CAAC;AACR,MAAM,GAAG,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAChC,YAAY,CACV,SAAS,CAAC,eAAe,EACzB,CAAC,OAAiB,EAAE,EAAE;IACpB,MAAM,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/C,OAAO,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AACtB,CAAC,EACD;IACE,GAAG,EAAE,gCAAgC;IACrC,SAAS,EAAE,gCAAgC;IAC3C,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,MAAM;CACb,CACF,CAAC,EAAE,CAAC;AACP,MAAM,CAAC,MAAM,WAAW,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACrE,MAAM,CAAC,MAAM,aAAa,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/index.d.ts b/node_modules/@noble/curves/index.d.ts new file mode 100644 index 0000000..f36479a --- /dev/null +++ b/node_modules/@noble/curves/index.d.ts @@ -0,0 +1 @@ +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/index.d.ts.map b/node_modules/@noble/curves/index.d.ts.map new file mode 100644 index 0000000..4e8c581 --- /dev/null +++ b/node_modules/@noble/curves/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@noble/curves/index.js b/node_modules/@noble/curves/index.js new file mode 100644 index 0000000..ac4f223 --- /dev/null +++ b/node_modules/@noble/curves/index.js @@ -0,0 +1,3 @@ +"use strict"; +throw new Error('Incorrect usage. Import submodules instead'); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/index.js.map b/node_modules/@noble/curves/index.js.map new file mode 100644 index 0000000..292b53a --- /dev/null +++ b/node_modules/@noble/curves/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":";AAAA,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/jubjub.d.ts b/node_modules/@noble/curves/jubjub.d.ts new file mode 100644 index 0000000..7d2c398 --- /dev/null +++ b/node_modules/@noble/curves/jubjub.d.ts @@ -0,0 +1,9 @@ +/** + * jubjub Twisted Edwards curve. + * https://neuromancer.sk/std/other/JubJub + * jubjub does not use EdDSA, so `hash`/sha512 params are passed because interface expects them. + */ +export declare const jubjub: import("./abstract/edwards.js").CurveFn; +export declare function groupHash(tag: Uint8Array, personalization: Uint8Array): import("./abstract/edwards.js").ExtPointType; +export declare function findGroupHash(m: Uint8Array, personalization: Uint8Array): import("./abstract/edwards.js").ExtPointType; +//# sourceMappingURL=jubjub.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/jubjub.d.ts.map b/node_modules/@noble/curves/jubjub.d.ts.map new file mode 100644 index 0000000..e79099d --- /dev/null +++ b/node_modules/@noble/curves/jubjub.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"jubjub.d.ts","sourceRoot":"","sources":["src/jubjub.ts"],"names":[],"mappings":"AAOA;;;;GAIG;AAEH,eAAO,MAAM,MAAM,yCAgBR,CAAC;AAOZ,wBAAgB,SAAS,CAAC,GAAG,EAAE,UAAU,EAAE,eAAe,EAAE,UAAU,gDAUrE;AAED,wBAAgB,aAAa,CAAC,CAAC,EAAE,UAAU,EAAE,eAAe,EAAE,UAAU,gDASvE"} \ No newline at end of file diff --git a/node_modules/@noble/curves/jubjub.js b/node_modules/@noble/curves/jubjub.js new file mode 100644 index 0000000..60c8329 --- /dev/null +++ b/node_modules/@noble/curves/jubjub.js @@ -0,0 +1,59 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.findGroupHash = exports.groupHash = exports.jubjub = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha512_1 = require("@noble/hashes/sha512"); +const utils_1 = require("@noble/hashes/utils"); +const edwards_js_1 = require("./abstract/edwards.js"); +const blake2s_1 = require("@noble/hashes/blake2s"); +const modular_js_1 = require("./abstract/modular.js"); +/** + * jubjub Twisted Edwards curve. + * https://neuromancer.sk/std/other/JubJub + * jubjub does not use EdDSA, so `hash`/sha512 params are passed because interface expects them. + */ +exports.jubjub = (0, edwards_js_1.twistedEdwards)({ + // Params: a, d + a: BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000'), + d: BigInt('0x2a9318e74bfa2b48f5fd9207e6bd7fd4292d7f6d37579d2601065fd6d6343eb1'), + // Finite field 𝔽p over which we'll do calculations + // Same value as bls12-381 Fr (not Fp) + Fp: (0, modular_js_1.Field)(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')), + // Subgroup order: how many points curve has + n: BigInt('0xe7db4ea6533afa906673b0101343b00a6682093ccc81082d0970e5ed6f72cb7'), + // Cofactor + h: BigInt(8), + // Base point (x, y) aka generator point + Gx: BigInt('0x11dafe5d23e1218086a365b99fbf3d3be72f6afd7d1f72623e6b071492d1122b'), + Gy: BigInt('0x1d523cf1ddab1a1793132e78c866c0c33e26ba5cc220fed7cc3f870e59d292aa'), + hash: sha512_1.sha512, + randomBytes: utils_1.randomBytes, +}); +const GH_FIRST_BLOCK = (0, utils_1.utf8ToBytes)('096b36a5804bfacef1691e173c366a47ff5ba84a44f26ddd7e8d9f79d5b42df0'); +// Returns point at JubJub curve which is prime order and not zero +function groupHash(tag, personalization) { + const h = blake2s_1.blake2s.create({ personalization, dkLen: 32 }); + h.update(GH_FIRST_BLOCK); + h.update(tag); + // NOTE: returns ExtendedPoint, in case it will be multiplied later + let p = exports.jubjub.ExtendedPoint.fromHex(h.digest()); + // NOTE: cannot replace with isSmallOrder, returns Point*8 + p = p.multiply(exports.jubjub.CURVE.h); + if (p.equals(exports.jubjub.ExtendedPoint.ZERO)) + throw new Error('Point has small order'); + return p; +} +exports.groupHash = groupHash; +function findGroupHash(m, personalization) { + const tag = (0, utils_1.concatBytes)(m, new Uint8Array([0])); + for (let i = 0; i < 256; i++) { + tag[tag.length - 1] = i; + try { + return groupHash(tag, personalization); + } + catch (e) { } + } + throw new Error('findGroupHash tag overflow'); +} +exports.findGroupHash = findGroupHash; +//# sourceMappingURL=jubjub.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/jubjub.js.map b/node_modules/@noble/curves/jubjub.js.map new file mode 100644 index 0000000..3cd9787 --- /dev/null +++ b/node_modules/@noble/curves/jubjub.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jubjub.js","sourceRoot":"","sources":["src/jubjub.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,iDAA8C;AAC9C,+CAA4E;AAC5E,sDAAuD;AACvD,mDAAgD;AAChD,sDAA8C;AAE9C;;;;GAIG;AAEU,QAAA,MAAM,GAAmB,IAAA,2BAAc,EAAC;IACnD,eAAe;IACf,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,oDAAoD;IACpD,sCAAsC;IACtC,EAAE,EAAE,IAAA,kBAAK,EAAC,MAAM,CAAC,oEAAoE,CAAC,CAAC;IACvF,4CAA4C;IAC5C,CAAC,EAAE,MAAM,CAAC,mEAAmE,CAAC;IAC9E,WAAW;IACX,CAAC,E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OAAO,SAAS,CAAC,GAAG,EAAE,eAAe,CAAC,CAAC;SACxC;QAAC,OAAO,CAAC,EAAE,GAAE;KACf;IACD,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;AAChD,CAAC;AATD,sCASC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/LICENSE b/node_modules/@noble/curves/node_modules/@noble/hashes/LICENSE new file mode 100644 index 0000000..9297a04 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/README.md b/node_modules/@noble/curves/node_modules/@noble/hashes/README.md new file mode 100644 index 0000000..6f71600 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/README.md @@ -0,0 +1,534 @@ +# noble-hashes + +Audited & minimal JS implementation of SHA2, SHA3, RIPEMD, BLAKE2/3, HMAC, HKDF, PBKDF2 & Scrypt. + +- 🔒 [**Audited**](#security) by an independent security firm +- 🔻 Tree-shaking-friendly: use only what's necessary, other code won't be included +- 🏎 Ultra-fast, hand-optimized for caveats of JS engines +- 🔍 Unique tests ensure correctness: chained tests, sliding window tests, DoS tests, fuzzing +- 🔁 No unrolled loops: makes it easier to verify and reduces source code size up to 5x +- 🐢 Scrypt supports `N: 2**22`, while other implementations are limited to `2**20` +- 🦘 SHA3 supports Keccak, TupleHash, KangarooTwelve and MarsupilamiFourteen +- 🪶 Just 3.4k lines / 17KB gzipped. SHA256-only is 240 lines / 3KB gzipped + +The library's initial development was funded by [Ethereum Foundation](https://ethereum.org/). + +### This library belongs to _noble_ crypto + +> **noble-crypto** — high-security, easily auditable set of contained cryptographic libraries and tools. + +- No dependencies, protection against supply chain attacks +- Auditable TypeScript / JS code +- Supported on all major platforms +- Releases are signed with PGP keys and built transparently with NPM provenance +- Check out [homepage](https://paulmillr.com/noble/) & all libraries: + [ciphers](https://github.com/paulmillr/noble-ciphers), + [curves](https://github.com/paulmillr/noble-curves), + [hashes](https://github.com/paulmillr/noble-hashes), + 4kb [secp256k1](https://github.com/paulmillr/noble-secp256k1) / + [ed25519](https://github.com/paulmillr/noble-ed25519) + +## Usage + +> npm install @noble/hashes + +We support all major platforms and runtimes. +For [Deno](https://deno.land), ensure to use [npm specifier](https://deno.land/manual@v1.28.0/node/npm_specifiers). +For React Native, you may need a [polyfill for getRandomValues](https://github.com/LinusU/react-native-get-random-values). +If you don't like NPM, a standalone [noble-hashes.js](https://github.com/paulmillr/noble-hashes/releases) is also available. + +```js +// import * from '@noble/hashes'; // Error: use sub-imports, to ensure small app size +import { sha256 } from '@noble/hashes/sha256'; // ECMAScript modules (ESM) and Common.js +// import { sha256 } from 'npm:@noble/hashes@1.3.0/sha256'; // Deno +console.log(sha256(new Uint8Array([1, 2, 3]))); // Uint8Array(32) [3, 144, 88, 198, 242...] +// you could also pass strings that will be UTF8-encoded to Uint8Array +console.log(sha256('abc')); // == sha256(new TextEncoder().encode('abc')) + +// sha384 is here, because it uses same internals as sha512 +import { sha512, sha512_256, sha384 } from '@noble/hashes/sha512'; +// prettier-ignore +import { + sha3_224, sha3_256, sha3_384, sha3_512, + keccak_224, keccak_256, keccak_384, keccak_512, + shake128, shake256 +} from '@noble/hashes/sha3'; +// prettier-ignore +import { + cshake128, cshake256, kmac128, kmac256, + k12, m14, + tuplehash256, parallelhash256, keccakprg +} from '@noble/hashes/sha3-addons'; +import { ripemd160 } from '@noble/hashes/ripemd160'; +import { blake3 } from '@noble/hashes/blake3'; +import { blake2b } from '@noble/hashes/blake2b'; +import { blake2s } from '@noble/hashes/blake2s'; +import { hmac } from '@noble/hashes/hmac'; +import { hkdf } from '@noble/hashes/hkdf'; +import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2'; +import { scrypt, scryptAsync } from '@noble/hashes/scrypt'; + +import { sha1 } from '@noble/hashes/sha1'; // legacy + +// small utility method that converts bytes to hex +import { bytesToHex as toHex } from '@noble/hashes/utils'; +console.log(toHex(sha256('abc'))); // ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad +``` + +## API + +All hash functions: + +- can be called directly, with `Uint8Array`. +- return `Uint8Array` +- can receive `string`, which is automatically converted to `Uint8Array` + via utf8 encoding **(not hex)** +- support hashing 4GB of data per update on 64-bit systems (unlimited with streaming) + +```ts +function hash(message: Uint8Array | string): Uint8Array; +hash(new Uint8Array([1, 3])); +hash('string') == hash(new TextEncoder().encode('string')); +``` + +All hash functions can be constructed via `hash.create()` method: + +- the result is `Hash` subclass instance, which has `update()` and `digest()` methods +- `digest()` finalizes the hash and makes it no longer usable + +```ts +hash + .create() + .update(new Uint8Array([1, 3])) + .digest(); +``` + +_Some_ hash functions can also receive `options` object, which can be either passed as a: + +- second argument to hash function: `blake3('abc', { key: 'd', dkLen: 32 })` +- first argument to class initializer: `blake3.create({ context: 'e', dkLen: 32 })` + +## Modules + +- [SHA2 (sha256, sha384, sha512, sha512_256)](#sha2-sha256-sha384-sha512-sha512_256) +- [SHA3 (FIPS, SHAKE, Keccak)](#sha3-fips-shake-keccak) +- [SHA3 Addons (cSHAKE, KMAC, KangarooTwelve, MarsupilamiFourteen)](#sha3-addons-cshake-kmac-tuplehash-parallelhash-kangarootwelve-marsupilamifourteen) +- [RIPEMD-160](#ripemd-160) +- [BLAKE2b, BLAKE2s](#blake2b-blake2s) +- [BLAKE3](#blake3) +- [SHA1 (legacy)](#sha1-legacy) +- [HMAC](#hmac) +- [HKDF](#hkdf) +- [PBKDF2](#pbkdf2) +- [Scrypt](#scrypt) +- [ESKDF](#eskdf) +- [utils](#utils) + +##### SHA2 (sha256, sha384, sha512, sha512_256) + +```typescript +import { sha256 } from '@noble/hashes/sha256'; +const h1a = sha256('abc'); +const h1b = sha256 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); +``` + +```typescript +import { sha512 } from '@noble/hashes/sha512'; +const h2a = sha512('abc'); +const h2b = sha512 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); + +// SHA512/256 variant +import { sha512_256 } from '@noble/hashes/sha512'; +const h3a = sha512_256('abc'); +const h3b = sha512_256 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); + +// SHA384 +import { sha384 } from '@noble/hashes/sha512'; +const h4a = sha384('abc'); +const h4b = sha384 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); +``` + +See [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and +[the paper on SHA512/256](https://eprint.iacr.org/2010/548.pdf). + +##### SHA3 (FIPS, SHAKE, Keccak) + +```typescript +import { + sha3_224, + sha3_256, + sha3_384, + sha3_512, + keccak_224, + keccak_256, + keccak_384, + keccak_512, + shake128, + shake256, +} from '@noble/hashes/sha3'; +const h5a = sha3_256('abc'); +const h5b = sha3_256 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); +const h6a = keccak_256('abc'); +const h7a = shake128('abc', { dkLen: 512 }); +const h7b = shake256('abc', { dkLen: 512 }); +``` + +See [FIPS PUB 202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf), +[Website](https://keccak.team/keccak.html). + +Check out [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub) + +##### SHA3 Addons (cSHAKE, KMAC, TupleHash, ParallelHash, KangarooTwelve, MarsupilamiFourteen) + +```typescript +import { + cshake128, + cshake256, + kmac128, + kmac256, + k12, + m14, + tuplehash128, + tuplehash256, + parallelhash128, + parallelhash256, + keccakprg, +} from '@noble/hashes/sha3-addons'; +const h7c = cshake128('abc', { personalization: 'def' }); +const h7d = cshake256('abc', { personalization: 'def' }); +const h7e = kmac128('key', 'message'); +const h7f = kmac256('key', 'message'); +const h7h = k12('abc'); +const h7g = m14('abc'); +const h7i = tuplehash128(['ab', 'c']); // tuplehash(['ab', 'c']) !== tuplehash(['a', 'bc']) !== tuplehash(['abc']) +// Same as k12/blake3, but without reduced number of rounds. Doesn't speedup anything due lack of SIMD and threading, +// added for compatibility. +const h7j = parallelhash128('abc', { blockLen: 8 }); +// pseudo-random generator, first argument is capacity. XKCP recommends 254 bits capacity for 128-bit security strength. +// * with a capacity of 254 bits. +const p = keccakprg(254); +p.feed('test'); +const rand1b = p.fetch(1); +``` + +- Full [NIST SP 800-185](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf): + cSHAKE, KMAC, TupleHash, ParallelHash + XOF variants +- 🦘 K12 ([KangarooTwelve Paper](https://keccak.team/files/KangarooTwelve.pdf), + [RFC Draft](https://www.ietf.org/archive/id/draft-irtf-cfrg-kangarootwelve-06.txt)) + and M14 aka MarsupilamiFourteen are basically parallel versions of Keccak with + reduced number of rounds (same as Blake3 and ParallelHash). +- [KeccakPRG](https://keccak.team/files/CSF-0.1.pdf): Pseudo-random generator based on Keccak + +##### RIPEMD-160 + +```typescript +import { ripemd160 } from '@noble/hashes/ripemd160'; +// function ripemd160(data: Uint8Array): Uint8Array; +const hash8 = ripemd160('abc'); +const hash9 = ripemd160() + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); +``` + +See [RFC 2286](https://datatracker.ietf.org/doc/html/rfc2286), +[Website](https://homes.esat.kuleuven.be/~bosselae/ripemd160.html) + +##### BLAKE2b, BLAKE2s + +```typescript +import { blake2b } from '@noble/hashes/blake2b'; +import { blake2s } from '@noble/hashes/blake2s'; +const h10a = blake2s('abc'); +const b2params = { key: new Uint8Array([1]), personalization: t, salt: t, dkLen: 32 }; +const h10b = blake2s('abc', b2params); +const h10c = blake2s + .create(b2params) + .update(Uint8Array.from([1, 2, 3])) + .digest(); +``` + +See [RFC 7693](https://datatracker.ietf.org/doc/html/rfc7693), [Website](https://www.blake2.net). + +##### BLAKE3 + +```typescript +import { blake3 } from '@noble/hashes/blake3'; +// All params are optional +const h11 = blake3('abc', { dkLen: 256, key: 'def', context: 'fji' }); +``` + +##### SHA1 (legacy) + +SHA1 was cryptographically broken, however, it was not broken for cases like HMAC. + +See [RFC4226 B.2](https://datatracker.ietf.org/doc/html/rfc4226#appendix-B.2). + +Don't use it for a new protocol. + +```typescript +import { sha1 } from '@noble/hashes/sha1'; +const h12 = sha1('def'); +``` + +##### HMAC + +```typescript +import { hmac } from '@noble/hashes/hmac'; +import { sha256 } from '@noble/hashes/sha256'; +const mac1 = hmac(sha256, 'key', 'message'); +const mac2 = hmac.create(sha256, Uint8Array.from([1, 2, 3])).update(Uint8Array.from([4, 5, 6])).digest(); +``` + +Matches [RFC 2104](https://datatracker.ietf.org/doc/html/rfc2104). + +##### HKDF + +```typescript +import { hkdf } from '@noble/hashes/hkdf'; +import { sha256 } from '@noble/hashes/sha256'; +import { randomBytes } from '@noble/hashes/utils'; +const inputKey = randomBytes(32); +const salt = randomBytes(32); +const info = 'abc'; +const dkLen = 32; +const hk1 = hkdf(sha256, inputKey, salt, info, dkLen); + +// == same as +import * as hkdf from '@noble/hashes/hkdf'; +import { sha256 } from '@noble/hashes/sha256'; +const prk = hkdf.extract(sha256, inputKey, salt); +const hk2 = hkdf.expand(sha256, prk, info, dkLen); +``` + +Matches [RFC 5869](https://datatracker.ietf.org/doc/html/rfc5869). + +##### PBKDF2 + +```typescript +import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2'; +import { sha256 } from '@noble/hashes/sha256'; +const pbkey1 = pbkdf2(sha256, 'password', 'salt', { c: 32, dkLen: 32 }); +const pbkey2 = await pbkdf2Async(sha256, 'password', 'salt', { c: 32, dkLen: 32 }); +const pbkey3 = await pbkdf2Async(sha256, Uint8Array.from([1, 2, 3]), Uint8Array.from([4, 5, 6]), { + c: 32, + dkLen: 32, +}); +``` + +Matches [RFC 2898](https://datatracker.ietf.org/doc/html/rfc2898). + +##### Scrypt + +```typescript +import { scrypt, scryptAsync } from '@noble/hashes/scrypt'; +const scr1 = scrypt('password', 'salt', { N: 2 ** 16, r: 8, p: 1, dkLen: 32 }); +const scr2 = await scryptAsync('password', 'salt', { N: 2 ** 16, r: 8, p: 1, dkLen: 32 }); +const scr3 = await scryptAsync(Uint8Array.from([1, 2, 3]), Uint8Array.from([4, 5, 6]), { + N: 2 ** 22, + r: 8, + p: 1, + dkLen: 32, + onProgress(percentage) { + console.log('progress', percentage); + }, + maxmem: 2 ** 32 + 128 * 8 * 1, // N * r * p * 128 + (128*r*p) +}); +``` + +Conforms to [RFC 7914](https://datatracker.ietf.org/doc/html/rfc7914), +[Website](https://www.tarsnap.com/scrypt.html) + +- `N, r, p` are work factors. To understand them, see [the blog post](https://blog.filippo.io/the-scrypt-parameters/). +- `dkLen` is the length of output bytes +- It is common to use N from `2**10` to `2**22` and `{r: 8, p: 1, dkLen: 32}` +- `onProgress` can be used with async version of the function to report progress to a user. + +Memory usage of scrypt is calculated with the formula `N * r * p * 128 + (128 * r * p)`, +which means `{N: 2 ** 22, r: 8, p: 1}` will use 4GB + 1KB of memory. To prevent +DoS, we limit scrypt to `1GB + 1KB` of RAM used, which corresponds to +`{N: 2 ** 20, r: 8, p: 1}`. If you want to use higher values, increase +`maxmem` using the formula above. + +_Note:_ noble supports `2**22` (4GB RAM) which is the highest amount amongst JS +libs. Many other implementations don't support it. We cannot support `2**23`, +because there is a limitation in JS engines that makes allocating +arrays bigger than 4GB impossible, but we're looking into other possible solutions. + +##### Argon2 + +Experimental Argon2 RFC 9106 implementation. It may be removed at any time. + +```ts +import { argon2d, argon2i, argon2id } from '@noble/hashes/argon2'; +const result = argon2id('password', 'salt', { t: 2, m: 65536, p: 1 }); +``` + +##### ESKDF + +A tiny stretched KDF for various applications like AES key-gen. Takes >= 2 seconds to execute. + +Takes following params: + +- `username` - username, email, or identifier, min: 8 characters, should have enough entropy +- `password` - min: 8 characters, should have enough entropy + +Produces ESKDF instance that has `deriveChildKey(protocol, accountId[, options])` function. + +- `protocol` - 3-15 character protocol name +- `accountId` - numeric identifier of account +- `options` - `keyLength: 32` with specified key length (default is 32), + or `modulus: 2n ** 221n - 17n` with specified modulus. It will fetch modulus + 64 bits of + data, execute modular division. The result will have negligible bias as per FIPS 186 B.4.1. + Can be used to generate, for example, elliptic curve keys. + +Takes username and password, then takes protocol name and account id. + +```typescript +import { eskdf } from '@noble/hashes/eskdf'; +const kdf = await eskdf('example@university', 'beginning-new-example'); +console.log(kdf.fingerprint); +const key1 = kdf.deriveChildKey('aes', 0); +const key2 = kdf.deriveChildKey('aes', 0, { keyLength: 16 }); +const ecc1 = kdf.deriveChildKey('ecc', 0, { modulus: 2n ** 252n - 27742317777372353535851937790883648493n }) +kdf.expire(); +``` + +##### utils + +```typescript +import { bytesToHex as toHex, randomBytes } from '@noble/hashes/utils'; +console.log(toHex(randomBytes(32))); +``` + +- `bytesToHex` will convert `Uint8Array` to a hex string +- `randomBytes(bytes)` will produce cryptographically secure random `Uint8Array` of length `bytes` + +## Security + +Noble is production-ready. + +1. The library has been audited in Jan 2022 by an independent security firm + cure53: [PDF](https://cure53.de/pentest-report_hashing-libs.pdf). + No vulnerabilities have been found. The audit has been funded by + [Ethereum Foundation](https://ethereum.org/en/) with help of [Nomic Labs](https://nomiclabs.io). + Modules `blake3`, `sha3-addons`, `sha1` and `argon2` have not been audited. + See [changes since audit](https://github.com/paulmillr/noble-hashes/compare/1.0.0..main). +2. The library has been fuzzed by [Guido Vranken's cryptofuzz](https://github.com/guidovranken/cryptofuzz). + You can run the fuzzer by yourself to check it. +3. [Timing attack](https://en.wikipedia.org/wiki/Timing_attack) considerations: + _JIT-compiler_ and _Garbage Collector_ make "constant time" extremely hard to + achieve in a scripting language. Which means _any other JS library can't have constant-timeness_. + Even statically typed Rust, a language without GC, + [makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security) + for some cases. If your goal is absolute security, don't use any JS lib — including + bindings to native ones. Use low-level libraries & languages. Nonetheless we're + targetting algorithmic constant time. +4. Memory dump considerations: the library shares state buffers between hash + function calls. The buffers are zeroed-out after each call. However, if an attacker + can read application memory, you are doomed in any case: + - At some point, input will be a string and strings are immutable in JS: + there is no way to overwrite them with zeros. For example: deriving + key from `scrypt(password, salt)` where password and salt are strings + - Input from a file will stay in file buffers + - Input / output will be re-used multiple times in application which means + it could stay in memory + - `await anything()` will always write all internal variables (including numbers) + to memory. With async functions / Promises there are no guarantees when the code + chunk would be executed. Which means attacker can have plenty of time to read data from memory + - There is no way to guarantee anything about zeroing sensitive data without + complex tests-suite which will dump process memory and verify that there is + no sensitive data left. For JS it means testing all browsers (incl. mobile), + which is complex. And of course it will be useless without using the same + test-suite in the actual application that consumes the library + +We consider infrastructure attacks like rogue NPM modules very important; that's +why it's crucial to minimize the amount of 3rd-party dependencies & native bindings. +If your app uses 500 dependencies, any dep could get hacked and you'll be downloading +malware with every `npm install`. Our goal is to minimize this attack vector. + +## Speed + +Benchmarks measured on Apple M1 with macOS 12. +Note that PBKDF2 and Scrypt are tested with extremely high work factor. +To run benchmarks, execute `npm run bench:install` and then `npm run bench` + +``` +SHA256 32B x 1,219,512 ops/sec @ 820ns/op ± 2.58% (min: 625ns, max: 4ms) +SHA384 32B x 512,032 ops/sec @ 1μs/op +SHA512 32B x 509,943 ops/sec @ 1μs/op +SHA3-256, keccak256, shake256 32B x 199,600 ops/sec @ 5μs/op +Kangaroo12 32B x 336,360 ops/sec @ 2μs/op +Marsupilami14 32B x 298,418 ops/sec @ 3μs/op +BLAKE2b 32B x 379,794 ops/sec @ 2μs/op +BLAKE2s 32B x 515,995 ops/sec @ 1μs/op ± 1.07% (min: 1μs, max: 4ms) +BLAKE3 32B x 588,235 ops/sec @ 1μs/op ± 1.36% (min: 1μs, max: 5ms) +RIPEMD160 32B x 1,140,250 ops/sec @ 877ns/op ± 3.12% (min: 708ns, max: 6ms) +HMAC-SHA256 32B x 377,358 ops/sec @ 2μs/op + +HKDF-SHA256 32B x 108,377 ops/sec @ 9μs/op +PBKDF2-HMAC-SHA256 262144 x 3 ops/sec @ 326ms/op +PBKDF2-HMAC-SHA512 262144 x 1 ops/sec @ 970ms/op +Scrypt r: 8, p: 1, n: 262144 x 1 ops/sec @ 616ms/op +``` + +Compare to native node.js implementation that uses C bindings instead of pure-js code: + +``` +SHA256 32B node x 1,302,083 ops/sec @ 768ns/op ± 10.54% (min: 416ns, max: 7ms) +SHA384 32B node x 975,609 ops/sec @ 1μs/op ± 11.32% (min: 625ns, max: 8ms) +SHA512 32B node x 983,284 ops/sec @ 1μs/op ± 11.24% (min: 625ns, max: 8ms) +SHA3-256 32B node x 910,746 ops/sec @ 1μs/op ± 12.19% (min: 666ns, max: 10ms) +keccak, k12, m14 are not implemented +BLAKE2b 32B node x 967,117 ops/sec @ 1μs/op ± 11.26% (min: 625ns, max: 9ms) +BLAKE2s 32B node x 1,055,966 ops/sec @ 947ns/op ± 11.07% (min: 583ns, max: 7ms) +BLAKE3 is not implemented +RIPEMD160 32B node x 1,002,004 ops/sec @ 998ns/op ± 10.66% (min: 625ns, max: 7ms) +HMAC-SHA256 32B node x 919,963 ops/sec @ 1μs/op ± 6.13% (min: 833ns, max: 5ms) +HKDF-SHA256 32 node x 369,276 ops/sec @ 2μs/op ± 13.59% (min: 1μs, max: 9ms) +PBKDF2-HMAC-SHA256 262144 node x 25 ops/sec @ 39ms/op +PBKDF2-HMAC-SHA512 262144 node x 7 ops/sec @ 132ms/op +Scrypt r: 8, p: 1, n: 262144 node x 1 ops/sec @ 523ms/op +``` + +It is possible to [make this library 4x+ faster](./benchmark/README.md) by +_doing code generation of full loop unrolls_. We've decided against it. Reasons: + +- the library must be auditable, with minimum amount of code, and zero dependencies +- most method invocations with the lib are going to be something like hashing 32b to 64kb of data +- hashing big inputs is 10x faster with low-level languages, which means you should probably pick 'em instead + +The current performance is good enough when compared to other projects; SHA256 takes only 900 nanoseconds to run. + +## Contributing & testing + +1. Clone the repository +2. `npm install` to install build dependencies like TypeScript +3. `npm run build` to compile TypeScript code +4. `npm run test` will execute all main tests. See [our approach to testing](./test/README.md) +5. `npm run test:dos` will test against DoS; by measuring function complexity. **Takes ~20 minutes** +6. `npm run test:big` will execute hashing on 4GB inputs, + scrypt with 1024 different `N, r, p` combinations, etc. **Takes several hours**. Using 8-32+ core CPU helps. + +## License + +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller [(https://paulmillr.com)](https://paulmillr.com) + +See LICENSE file. diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/_assert.d.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/_assert.d.ts new file mode 100644 index 0000000..32a720b --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/_assert.d.ts @@ -0,0 +1,22 @@ +declare function number(n: number): void; +declare function bool(b: boolean): void; +declare function bytes(b: Uint8Array | undefined, ...lengths: number[]): void; +type Hash = { + (data: Uint8Array): Uint8Array; + blockLen: number; + outputLen: number; + create: any; +}; +declare function hash(hash: Hash): void; +declare function exists(instance: any, checkFinished?: boolean): void; +declare function output(out: any, instance: any): void; +export { number, bool, bytes, hash, exists, output }; +declare const assert: { + number: typeof number; + bool: typeof bool; + bytes: typeof bytes; + hash: typeof hash; + exists: typeof exists; + output: typeof output; +}; +export default assert; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/_assert.js b/node_modules/@noble/curves/node_modules/@noble/hashes/_assert.js new file mode 100644 index 0000000..920cdd9 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/_assert.js @@ -0,0 +1,45 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.output = exports.exists = exports.hash = exports.bytes = exports.bool = exports.number = void 0; +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); +} +exports.number = number; +function bool(b) { + if (typeof b !== 'boolean') + throw new Error(`Expected boolean, not ${b}`); +} +exports.bool = bool; +function bytes(b, ...lengths) { + if (!(b instanceof Uint8Array)) + throw new Error('Expected Uint8Array'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} +exports.bytes = bytes; +function hash(hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(hash.outputLen); + number(hash.blockLen); +} +exports.hash = hash; +function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +exports.exists = exists; +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} +exports.output = output; +const assert = { number, bool, bytes, hash, exists, output }; +exports.default = assert; +//# sourceMappingURL=_assert.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/_assert.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/_assert.js.map new file mode 100644 index 0000000..f3cc515 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/_assert.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_assert.js","sourceRoot":"","sources":["src/_assert.ts"],"names":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AK,CAAC,uCAAuC,CAAC,CAAC;AACnG,CAAC;AASmC,wBAAM;AAR1C,SAAS,MAAM,CAAC,GAAQ,EAAE,QAAa;IACrC,KAAK,CAAC,GAAG,CAAC,CAAC;IACX,MAAM,GAAG,GAAG,QAAQ,CAAC,SAAS,CAAC;IAC/B,IAAI,GAAG,CAAC,MAAM,GAAG,GAAG,EAAE;QACpB,MAAM,IAAI,KAAK,CAAC,yDAAyD,GAAG,EAAE,CAAC,CAAC;KACjF;AACH,CAAC;AAE2C,wBAAM;AAElD,MAAM,MAAM,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAC7D,kBAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/_blake2.d.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/_blake2.d.ts new file mode 100644 index 0000000..352b978 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/_blake2.d.ts @@ -0,0 +1,27 @@ +import { Hash, Input } from './utils.js'; +export declare const SIGMA: Uint8Array; +export type BlakeOpts = { + dkLen?: number; + key?: Input; + salt?: Input; + personalization?: Input; +}; +export declare abstract class BLAKE2> extends Hash { + readonly blockLen: number; + outputLen: number; + protected abstract compress(msg: Uint32Array, offset: number, isLast: boolean): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected buffer: Uint8Array; + protected buffer32: Uint32Array; + protected length: number; + protected pos: number; + protected finished: boolean; + protected destroyed: boolean; + constructor(blockLen: number, outputLen: number, opts: BlakeOpts | undefined, keyLen: number, saltLen: number, persLen: number); + update(data: Input): this; + digestInto(out: Uint8Array): void; + digest(): Uint8Array; + _cloneInto(to?: T): T; +} diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/_blake2.js b/node_modules/@noble/curves/node_modules/@noble/hashes/_blake2.js new file mode 100644 index 0000000..9a5a45d --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/_blake2.js @@ -0,0 +1,112 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BLAKE2 = exports.SIGMA = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +// Blake is based on ChaCha permutation. +// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. +// prettier-ignore +exports.SIGMA = new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, +]); +class BLAKE2 extends utils_js_1.Hash { + constructor(blockLen, outputLen, opts = {}, keyLen, saltLen, persLen) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.length = 0; + this.pos = 0; + this.finished = false; + this.destroyed = false; + (0, _assert_js_1.number)(blockLen); + (0, _assert_js_1.number)(outputLen); + (0, _assert_js_1.number)(keyLen); + if (outputLen < 0 || outputLen > keyLen) + throw new Error('outputLen bigger than keyLen'); + if (opts.key !== undefined && (opts.key.length < 1 || opts.key.length > keyLen)) + throw new Error(`key must be up 1..${keyLen} byte long or undefined`); + if (opts.salt !== undefined && opts.salt.length !== saltLen) + throw new Error(`salt must be ${saltLen} byte long or undefined`); + if (opts.personalization !== undefined && opts.personalization.length !== persLen) + throw new Error(`personalization must be ${persLen} byte long or undefined`); + this.buffer32 = (0, utils_js_1.u32)((this.buffer = new Uint8Array(blockLen))); + } + update(data) { + (0, _assert_js_1.exists)(this); + // Main difference with other hashes: there is flag for last block, + // so we cannot process current block before we know that there + // is the next one. This significantly complicates logic and reduces ability + // to do zero-copy processing + const { blockLen, buffer, buffer32 } = this; + data = (0, utils_js_1.toBytes)(data); + const len = data.length; + const offset = data.byteOffset; + const buf = data.buffer; + for (let pos = 0; pos < len;) { + // If buffer is full and we still have input (don't process last block, same as blake2s) + if (this.pos === blockLen) { + this.compress(buffer32, 0, false); + this.pos = 0; + } + const take = Math.min(blockLen - this.pos, len - pos); + const dataOffset = offset + pos; + // full block && aligned to 4 bytes && not last in input + if (take === blockLen && !(dataOffset % 4) && pos + take < len) { + const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4)); + for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) { + this.length += blockLen; + this.compress(data32, pos32, false); + } + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + this.length += take; + pos += take; + } + return this; + } + digestInto(out) { + (0, _assert_js_1.exists)(this); + (0, _assert_js_1.output)(out, this); + const { pos, buffer32 } = this; + this.finished = true; + // Padding + this.buffer.subarray(pos).fill(0); + this.compress(buffer32, 0, true); + const out32 = (0, utils_js_1.u32)(out); + this.get().forEach((v, i) => (out32[i] = v)); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + const { buffer, length, finished, destroyed, outputLen, pos } = this; + to || (to = new this.constructor({ dkLen: outputLen })); + to.set(...this.get()); + to.length = length; + to.finished = finished; + to.destroyed = destroyed; + to.outputLen = outputLen; + to.buffer.set(buffer); + to.pos = pos; + return to; + } +} +exports.BLAKE2 = BLAKE2; +//# sourceMappingURL=_blake2.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/_blake2.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/_blake2.js.map new file mode 100644 index 0000000..85cf0b6 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/_blake2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_blake2.js","sourceRoot":"","sources":["src/_blake2.ts"],"names":[],"mappings":";;;AAAA,6CAAsD;AACtD,yCAAuD;AAEvD,wCAAwC;AAExC,gGAAgG;AAChG,kBAAkB;AACL,QAAA,KAAK,GAAmB,IAAI,UAAU,CAAC;IAClD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;IACpD,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,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modules/@noble/curves/node_modules/@noble/hashes/_sha2.d.ts new file mode 100644 index 0000000..883788f --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/_sha2.d.ts @@ -0,0 +1,23 @@ +import { Hash, Input } from './utils.js'; +export declare abstract class SHA2> extends Hash { + readonly blockLen: number; + outputLen: number; + readonly padOffset: number; + readonly isLE: boolean; + protected abstract process(buf: DataView, offset: number): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected abstract roundClean(): void; + protected buffer: Uint8Array; + protected view: DataView; + protected finished: boolean; + protected length: number; + protected pos: number; + protected destroyed: boolean; + constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean); + update(data: Input): this; + digestInto(out: Uint8Array): void; + digest(): Uint8Array; + _cloneInto(to?: T): T; +} diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/_sha2.js b/node_modules/@noble/curves/node_modules/@noble/hashes/_sha2.js new file mode 100644 index 0000000..7a45349 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/_sha2.js @@ -0,0 +1,118 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SHA2 = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +// Polyfill for Safari 14 +function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +// Base SHA2 class (RFC 6234) +class SHA2 extends utils_js_1.Hash { + constructor(blockLen, outputLen, padOffset, isLE) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = (0, utils_js_1.createView)(this.buffer); + } + update(data) { + (0, _assert_js_1.exists)(this); + const { view, buffer, blockLen } = this; + data = (0, utils_js_1.toBytes)(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input, cast it to view and process + if (take === blockLen) { + const dataView = (0, utils_js_1.createView)(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + (0, _assert_js_1.exists)(this); + (0, _assert_js_1.output)(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + this.buffer.subarray(pos).fill(0); + // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) + buffer[i] = 0; + // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = (0, utils_js_1.createView)(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + if (len % 4) + throw new Error('_sha2: outputLen should be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } +} +exports.SHA2 = SHA2; +//# sourceMappingURL=_sha2.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/_sha2.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/_sha2.js.map new file mode 100644 index 0000000..9c9c8eb --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/_sha2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_sha2.js","sourceRoot":"","sources":["src/_sha2.ts"],"names":[],"mappings":";;;AAAA,6CAA8C;AAC9C,yCAA8D;AAE9D,yBAAyB;AACzB,SAAS,YAAY,CAAC,IAAc,EAAE,UAAkB,EAAE,KAAa,EAAE,IAAa;IACpF,IAAI,OAAO,IAAI,CAAC,YAAY,KAAK,UAAU;QAAE,OAAO,IAAI,CAAC,YAAY,CAAC,UAAU,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;IAC/F,MAAM,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;IACxB,MAAM,QAAQ,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;IACpC,MAAM,EAAE,GAAG,MAAM,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,GAAG,QAAQ,CAAC,CAAC;IAC9C,MAAM,EAAE,GAAG,MAAM,CAAC,KAAK,GAAG,QAAQ,CAAC,CAAC;IACpC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACvB,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACvB,IAAI,CAAC,SAAS,CAAC,UAAU,GAAG,CAAC,EAAE,EA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O,EAAE,CAAC;QACf,OAAO,GAAG,CAAC;IACb,CAAC;IACD,UAAU,CAAC,EAAM;QACf,EAAE,KAAF,EAAE,GAAK,IAAK,IAAI,CAAC,WAAmB,EAAO,EAAC;QAC5C,EAAE,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;QACtB,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;QACpE,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC;QACnB,EAAE,CAAC,GAAG,GAAG,GAAG,CAAC;QACb,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACvB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,IAAI,MAAM,GAAG,QAAQ;YAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC7C,OAAO,EAAE,CAAC;IACZ,CAAC;CACF;AApGD,oBAoGC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/_u64.d.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/_u64.d.ts new file mode 100644 index 0000000..59fd1c2 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/_u64.d.ts @@ -0,0 +1,54 @@ +declare function fromBig(n: bigint, le?: boolean): { + h: number; + l: number; +}; +declare function split(lst: bigint[], le?: boolean): Uint32Array[]; +declare const toBig: (h: number, l: number) => bigint; +declare const shrSH: (h: number, _l: number, s: number) => number; +declare const shrSL: (h: number, l: number, s: number) => number; +declare const rotrSH: (h: number, l: number, s: number) => number; +declare const rotrSL: (h: number, l: number, s: number) => number; +declare const rotrBH: (h: number, l: number, s: number) => number; +declare const rotrBL: (h: number, l: number, s: number) => number; +declare const rotr32H: (_h: number, l: number) => number; +declare const rotr32L: (h: number, _l: number) => number; +declare const rotlSH: (h: number, l: number, s: number) => number; +declare const rotlSL: (h: number, l: number, s: number) => number; +declare const rotlBH: (h: number, l: number, s: number) => number; +declare const rotlBL: (h: number, l: number, s: number) => number; +declare function add(Ah: number, Al: number, Bh: number, Bl: number): { + h: number; + l: number; +}; +declare const add3L: (Al: number, Bl: number, Cl: number) => number; +declare const add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; +declare const add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; +declare const add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; +declare const add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; +declare const add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; +export { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, }; +declare const u64: { + fromBig: typeof fromBig; + split: typeof split; + toBig: (h: number, l: number) => bigint; + shrSH: (h: number, _l: number, s: number) => number; + shrSL: (h: number, l: number, s: number) => number; + rotrSH: (h: number, l: number, s: number) => number; + rotrSL: (h: number, l: number, s: number) => number; + rotrBH: (h: number, l: number, s: number) => number; + rotrBL: (h: number, l: number, s: number) => number; + rotr32H: (_h: number, l: number) => number; + rotr32L: (h: number, _l: number) => number; + rotlSH: (h: number, l: number, s: number) => number; + rotlSL: (h: number, l: number, s: number) => number; + rotlBH: (h: number, l: number, s: number) => number; + rotlBL: (h: number, l: number, s: number) => number; + add: typeof add; + add3L: (Al: number, Bl: number, Cl: number) => number; + add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; + add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; + add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; + add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; + add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; +}; +export default u64; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/_u64.js b/node_modules/@noble/curves/node_modules/@noble/hashes/_u64.js new file mode 100644 index 0000000..c5080f0 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/_u64.js @@ -0,0 +1,85 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +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; +const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n = /* @__PURE__ */ BigInt(32); +// We are not using BigUint64Array, because they are extremely slow as per 2022 +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +exports.fromBig = fromBig; +function split(lst, le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +exports.split = split; +const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +exports.toBig = toBig; +// for Shift in [0, 32) +const shrSH = (h, _l, s) => h >>> s; +exports.shrSH = shrSH; +const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +exports.shrSL = shrSL; +// Right rotate for Shift in [1, 32) +const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); +exports.rotrSH = rotrSH; +const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +exports.rotrSL = rotrSL; +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); +exports.rotrBH = rotrBH; +const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); +exports.rotrBL = rotrBL; +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (_h, l) => l; +exports.rotr32H = rotr32H; +const rotr32L = (h, _l) => h; +exports.rotr32L = rotr32L; +// Left rotate for Shift in [1, 32) +const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); +exports.rotlSH = rotlSH; +const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); +exports.rotlSL = rotlSL; +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); +exports.rotlBH = rotlBH; +const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); +exports.rotlBL = rotlBL; +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +exports.add = add; +// Addition with more than 2 elements +const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +exports.add3L = add3L; +const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +exports.add3H = add3H; +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +exports.add4L = add4L; +const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +exports.add4H = add4H; +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +exports.add5L = add5L; +const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; +exports.add5H = add5H; +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +exports.default = u64; +//# sourceMappingURL=_u64.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/_u64.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/_u64.js.map new file mode 100644 index 0000000..6116a39 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/_u64.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_u64.js","sourceRoot":"","sources":["src/_u64.ts"],"names":[],"mappings":";;;AAAA,MAAM,UAAU,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC;AACvD,MAAM,IAAI,GAAG,eAAe,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;AAExC,+EAA+E;AAC/E,SAAS,OAAO,CAAC,CAAS,EAAE,EAAE,GAAG,KAAK;IACpC,IAAI,EAAE;QAAE,OAAO,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,GAAG,UAAU,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,GAAG,UAAU,CAAC,EAAE,CAAC;IAClF,OAAO,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,GAAG,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,GAAG,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;AACpF,CAAC;AAqDC,0BAAO;AAnDT,SAAS,KAAK,CAAC,GAAa,EAAE,EAAE,GAAG,KAAK;IACtC,IAAI,EAAE,GAAG,IAAI,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACrC,IAAI,EAAE,GAAG,IAAI,WAAW,CAAC,GAAG,CAAC,MAAM,CAA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MAAM;IAC9B,OAAO,EAAE,OAAO;IAChB,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9B,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK;CAC9C,CAAC;AACF,kBAAe,GAAG,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/argon2.d.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/argon2.d.ts new file mode 100644 index 0000000..15b6486 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/argon2.d.ts @@ -0,0 +1,16 @@ +import { Input } from './utils.js'; +export type ArgonOpts = { + t: number; + m: number; + p: number; + version?: number; + key?: Input; + personalization?: Input; + dkLen?: number; + asyncTick?: number; + maxmem?: number; + onProgress?: (progress: number) => void; +}; +export declare const argon2d: (password: Input, salt: Input, opts: ArgonOpts) => Uint8Array; +export declare const argon2i: (password: Input, salt: Input, opts: ArgonOpts) => Uint8Array; +export declare const argon2id: (password: Input, salt: Input, opts: ArgonOpts) => Uint8Array; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/argon2.js b/node_modules/@noble/curves/node_modules/@noble/hashes/argon2.js new file mode 100644 index 0000000..2754f8c --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/argon2.js @@ -0,0 +1,303 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.argon2id = exports.argon2i = exports.argon2d = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +const blake2b_js_1 = require("./blake2b.js"); +const _u64_js_1 = require("./_u64.js"); +const ARGON2_SYNC_POINTS = 4; +const toBytesOptional = (buf) => (buf !== undefined ? (0, utils_js_1.toBytes)(buf) : new Uint8Array([])); +function mul(a, b) { + const aL = a & 0xffff; + const aH = a >>> 16; + const bL = b & 0xffff; + const bH = b >>> 16; + const ll = Math.imul(aL, bL); + const hl = Math.imul(aH, bL); + const lh = Math.imul(aL, bH); + const hh = Math.imul(aH, bH); + const BUF = ((ll >>> 16) + (hl & 0xffff) + lh) | 0; + const h = ((hl >>> 16) + (BUF >>> 16) + hh) | 0; + return { h, l: (BUF << 16) | (ll & 0xffff) }; +} +function relPos(areaSize, relativePos) { + // areaSize - 1 - ((areaSize * ((relativePos ** 2) >>> 32)) >>> 32) + return areaSize - 1 - mul(areaSize, mul(relativePos, relativePos).h).h; +} +function mul2(a, b) { + // 2 * a * b (via shifts) + const { h, l } = mul(a, b); + return { h: ((h << 1) | (l >>> 31)) & 4294967295, l: (l << 1) & 4294967295 }; +} +function blamka(Ah, Al, Bh, Bl) { + const { h: Ch, l: Cl } = mul2(Al, Bl); + // A + B + (2 * A * B) + const Rll = (0, _u64_js_1.add3L)(Al, Bl, Cl); + return { h: (0, _u64_js_1.add3H)(Rll, Ah, Bh, Ch), l: Rll | 0 }; +} +// Temporary block buffer +const BUF = new Uint32Array(256); +function G(a, b, c, d) { + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: (0, _u64_js_1.rotr32H)(Dh, Dl), Dl: (0, _u64_js_1.rotr32L)(Dh, Dl) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: (0, _u64_js_1.rotrSH)(Bh, Bl, 24), Bl: (0, _u64_js_1.rotrSL)(Bh, Bl, 24) }); + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: (0, _u64_js_1.rotrSH)(Dh, Dl, 16), Dl: (0, _u64_js_1.rotrSL)(Dh, Dl, 16) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: (0, _u64_js_1.rotrBH)(Bh, Bl, 63), Bl: (0, _u64_js_1.rotrBL)(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +// prettier-ignore +function P(v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15) { + G(v00, v04, v08, v12); + G(v01, v05, v09, v13); + G(v02, v06, v10, v14); + G(v03, v07, v11, v15); + G(v00, v05, v10, v15); + G(v01, v06, v11, v12); + G(v02, v07, v08, v13); + G(v03, v04, v09, v14); +} +function block(x, xPos, yPos, outPos, needXor) { + for (let i = 0; i < 256; i++) + BUF[i] = x[xPos + i] ^ x[yPos + i]; + // columns + for (let i = 0; i < 128; i += 16) { + // prettier-ignore + P(i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15); + } + // rows + for (let i = 0; i < 16; i += 2) { + // prettier-ignore + P(i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113); + } + if (needXor) + for (let i = 0; i < 256; i++) + x[outPos + i] ^= BUF[i] ^ x[xPos + i] ^ x[yPos + i]; + else + for (let i = 0; i < 256; i++) + x[outPos + i] = BUF[i] ^ x[xPos + i] ^ x[yPos + i]; +} +// Variable-Length Hash Function H' +function Hp(A, dkLen) { + const A8 = (0, utils_js_1.u8)(A); + const T = new Uint32Array(1); + const T8 = (0, utils_js_1.u8)(T); + T[0] = dkLen; + // Fast path + if (dkLen <= 64) + return blake2b_js_1.blake2b.create({ dkLen }).update(T8).update(A8).digest(); + const out = new Uint8Array(dkLen); + let V = blake2b_js_1.blake2b.create({}).update(T8).update(A8).digest(); + let pos = 0; + // First block + out.set(V.subarray(0, 32)); + pos += 32; + // Rest blocks + for (; dkLen - pos > 64; pos += 32) + out.set((V = (0, blake2b_js_1.blake2b)(V)).subarray(0, 32), pos); + // Last block + out.set((0, blake2b_js_1.blake2b)(V, { dkLen: dkLen - pos }), pos); + return (0, utils_js_1.u32)(out); +} +function indexAlpha(r, s, laneLen, segmentLen, index, randL, sameLane = false) { + let area; + if (0 == r) { + if (0 == s) + area = index - 1; + else if (sameLane) + area = s * segmentLen + index - 1; + else + area = s * segmentLen + (index == 0 ? -1 : 0); + } + else if (sameLane) + area = laneLen - segmentLen + index - 1; + else + area = laneLen - segmentLen + (index == 0 ? -1 : 0); + const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0; + const rel = relPos(area, randL); + // NOTE: check about overflows here + // absPos = (startPos + relPos) % laneLength; + return (startPos + rel) % laneLen; +} +function argon2Init(type, password, salt, opts) { + password = (0, utils_js_1.toBytes)(password); + salt = (0, utils_js_1.toBytes)(salt); + let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress } = { + ...opts, + version: opts.version || 0x13, + dkLen: opts.dkLen || 32, + maxmem: 2 ** 32, + }; + // Validation + (0, _assert_js_1.number)(p); + (0, _assert_js_1.number)(dkLen); + (0, _assert_js_1.number)(m); + (0, _assert_js_1.number)(t); + (0, _assert_js_1.number)(version); + if (dkLen < 4 || dkLen >= 2 ** 32) + throw new Error('Argon2: dkLen should be at least 4 bytes'); + if (p < 1 || p >= 2 ** 32) + throw new Error('Argon2: p (parallelism) should be at least 1'); + if (t < 1 || t >= 2 ** 32) + throw new Error('Argon2: t (iterations) should be at least 1'); + if (m < 8 * p) + throw new Error(`Argon2: memory should be at least 8*p bytes`); + if (version !== 16 && version !== 19) + throw new Error(`Argon2: unknown version=${version}`); + password = (0, utils_js_1.toBytes)(password); + if (password.length < 0 || password.length >= 2 ** 32) + throw new Error('Argon2: password should be less than 4 GB'); + salt = (0, utils_js_1.toBytes)(salt); + if (salt.length < 8) + throw new Error('Argon2: salt should be at least 8 bytes'); + key = toBytesOptional(key); + personalization = toBytesOptional(personalization); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + // Params + const lanes = p; + // m' = 4 * p * floor (m / 4p) + const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p)); + //q = m' / p columns + const laneLen = Math.floor(mP / p); + const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS); + // H0 + const h = blake2b_js_1.blake2b.create({}); + const BUF = new Uint32Array(1); + const BUF8 = (0, utils_js_1.u8)(BUF); + for (const i of [p, dkLen, m, t, version, type]) { + if (i < 0 || i >= 2 ** 32) + throw new Error(`Argon2: wrong parameter=${i}, expected uint32`); + BUF[0] = i; + h.update(BUF8); + } + for (let i of [password, salt, key, personalization]) { + BUF[0] = i.length; + h.update(BUF8).update(i); + } + const H0 = new Uint32Array(18); + const H0_8 = (0, utils_js_1.u8)(H0); + h.digestInto(H0_8); + // 256 u32 = 1024 (BLOCK_SIZE) + const memUsed = mP * 256; + if (memUsed < 0 || memUsed >= 2 ** 32 || memUsed > maxmem) { + throw new Error(`Argon2: wrong params (memUsed=${memUsed} maxmem=${maxmem}), should be less than 2**32`); + } + const B = new Uint32Array(memUsed); + // Fill first blocks + for (let l = 0; l < p; l++) { + const i = 256 * laneLen * l; + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + H0[17] = l; + H0[16] = 0; + B.set(Hp(H0, 1024), i); + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + H0[16] = 1; + B.set(Hp(H0, 1024), i + 256); + } + let perBlock = () => { }; + if (onProgress) { + const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlock / 10000), 1); + let blockCnt = 0; + perBlock = () => { + blockCnt++; + if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock)) + onProgress(blockCnt / totalBlock); + }; + } + return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock }; +} +function argon2Output(B, p, laneLen, dkLen) { + const B_final = new Uint32Array(256); + for (let l = 0; l < p; l++) + for (let j = 0; j < 256; j++) + B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j]; + return (0, utils_js_1.u8)(Hp(B_final, dkLen)); +} +function processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor) { + if (offset % laneLen) + prev = offset - 1; + let randL, randH; + if (dataIndependent) { + if (index % 128 === 0) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + randL = address[2 * (index % 128)]; + randH = address[2 * (index % 128) + 1]; + } + else { + const T = 256 * prev; + randL = B[T]; + randH = B[T + 1]; + } + // address block + const refLane = r === 0 && s === 0 ? l : randH % lanes; + const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l); + const refBlock = laneLen * refLane + refPos; + // B[i][j] = G(B[i][j-1], B[l][z]) + block(B, 256 * prev, 256 * refBlock, offset * 256, needXor); +} +function argon2(type, password, salt, opts) { + const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init(type, password, salt, opts); + // Pre-loop setup + // [address, input, zero_block] format so we can pass single U32 to block function + const address = new Uint32Array(3 * 256); + address[256 + 6] = mP; + address[256 + 8] = t; + address[256 + 10] = type; + for (let r = 0; r < t; r++) { + const needXor = r !== 0 && version === 0x13; + address[256 + 0] = r; + for (let s = 0; s < ARGON2_SYNC_POINTS; s++) { + address[256 + 4] = s; + const dataIndependent = type == 1 /* Types.Argon2i */ || (type == 2 /* Types.Argon2id */ && r === 0 && s < 2); + for (let l = 0; l < p; l++) { + address[256 + 2] = l; + address[256 + 12] = 0; + let startPos = 0; + if (r === 0 && s === 0) { + startPos = 2; + if (dataIndependent) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + } + // current block postion + let offset = l * laneLen + s * segmentLen + startPos; + // previous block position + let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1; + for (let index = startPos; index < segmentLen; index++, offset++, prev++) { + perBlock(); + processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor); + } + } + } + } + return argon2Output(B, p, laneLen, dkLen); +} +const argon2d = (password, salt, opts) => argon2(0 /* Types.Argond2d */, password, salt, opts); +exports.argon2d = argon2d; +const argon2i = (password, salt, opts) => argon2(1 /* Types.Argon2i */, password, salt, opts); +exports.argon2i = argon2i; +const argon2id = (password, salt, opts) => argon2(2 /* Types.Argon2id */, password, salt, opts); +exports.argon2id = argon2id; +//# sourceMappingURL=argon2.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/argon2.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/argon2.js.map new file mode 100644 index 0000000..a88b252 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/argon2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"argon2.js","sourceRoot":"","sources":["src/argon2.ts"],"names":[],"mappings":";;;AAAA,6CAAsD;AACtD,yCAAqD;AACrD,6CAAuC;AACvC,uCAA2F;AAS3F,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAE7B,MAAM,eAAe,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,CAAC,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,IAAA,kBAAO,EAAC,GAAG,CAAC,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EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AADlC,QAAA,QAAQ,YAC0B"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/blake2b.d.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/blake2b.d.ts new file mode 100644 index 0000000..7a78c6b --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/blake2b.d.ts @@ -0,0 +1,53 @@ +import { BLAKE2, BlakeOpts } from './_blake2.js'; +declare class BLAKE2b extends BLAKE2 { + private v0l; + private v0h; + private v1l; + private v1h; + private v2l; + private v2h; + private v3l; + private v3h; + private v4l; + private v4h; + private v5l; + private v5h; + private v6l; + private v6h; + private v7l; + private v7h; + constructor(opts?: BlakeOpts); + protected get(): [ + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number + ]; + protected set(v0l: number, v0h: number, v1l: number, v1h: number, v2l: number, v2h: number, v3l: number, v3h: number, v4l: number, v4h: number, v5l: number, v5h: number, v6l: number, v6h: number, v7l: number, v7h: number): void; + protected compress(msg: Uint32Array, offset: number, isLast: boolean): void; + destroy(): void; +} +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export declare const blake2b: { + (msg: import("./utils.js").Input, opts?: BlakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: BlakeOpts): import("./utils.js").Hash; +}; +export {}; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/blake2b.js b/node_modules/@noble/curves/node_modules/@noble/hashes/blake2b.js new file mode 100644 index 0000000..9d41df5 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/blake2b.js @@ -0,0 +1,192 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.blake2b = void 0; +const _blake2_js_1 = require("./_blake2.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// Same as SHA-512 but LE +// prettier-ignore +const IV = /* @__PURE__ */ new Uint32Array([ + 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, + 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19 +]); +// Temporary buffer +const BUF = /* @__PURE__ */ new Uint32Array(32); +// Mixing function G splitted in two halfs +function G1(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = _u64_js_1.default.add3L(Al, Bl, Xl); + Ah = _u64_js_1.default.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 32) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: _u64_js_1.default.rotr32H(Dh, Dl), Dl: _u64_js_1.default.rotr32L(Dh, Dl) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = _u64_js_1.default.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 24) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: _u64_js_1.default.rotrSH(Bh, Bl, 24), Bl: _u64_js_1.default.rotrSL(Bh, Bl, 24) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +function G2(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = _u64_js_1.default.add3L(Al, Bl, Xl); + Ah = _u64_js_1.default.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 16) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: _u64_js_1.default.rotrSH(Dh, Dl, 16), Dl: _u64_js_1.default.rotrSL(Dh, Dl, 16) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = _u64_js_1.default.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 63) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: _u64_js_1.default.rotrBH(Bh, Bl, 63), Bl: _u64_js_1.default.rotrBL(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +class BLAKE2b extends _blake2_js_1.BLAKE2 { + constructor(opts = {}) { + super(128, opts.dkLen === undefined ? 64 : opts.dkLen, opts, 64, 16, 16); + // Same as SHA-512, but LE + this.v0l = IV[0] | 0; + this.v0h = IV[1] | 0; + this.v1l = IV[2] | 0; + this.v1h = IV[3] | 0; + this.v2l = IV[4] | 0; + this.v2h = IV[5] | 0; + this.v3l = IV[6] | 0; + this.v3h = IV[7] | 0; + this.v4l = IV[8] | 0; + this.v4h = IV[9] | 0; + this.v5l = IV[10] | 0; + this.v5h = IV[11] | 0; + this.v6l = IV[12] | 0; + this.v6h = IV[13] | 0; + this.v7l = IV[14] | 0; + this.v7h = IV[15] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.salt)); + this.v4l ^= salt[0]; + this.v4h ^= salt[1]; + this.v5l ^= salt[2]; + this.v5h ^= salt[3]; + } + if (opts.personalization) { + const pers = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.personalization)); + this.v6l ^= pers[0]; + this.v6h ^= pers[1]; + this.v7l ^= pers[2]; + this.v7h ^= pers[3]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set((0, utils_js_1.toBytes)(opts.key)); + this.update(tmp); + } + } + // prettier-ignore + get() { + let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + compress(msg, offset, isLast) { + this.get().forEach((v, i) => (BUF[i] = v)); // First half from state. + BUF.set(IV, 16); // Second half from IV. + let { h, l } = _u64_js_1.default.fromBig(BigInt(this.length)); + BUF[24] = IV[8] ^ l; // Low word of the offset. + BUF[25] = IV[9] ^ h; // High word. + // Invert all bits for last block + if (isLast) { + BUF[28] = ~BUF[28]; + BUF[29] = ~BUF[29]; + } + let j = 0; + const s = _blake2_js_1.SIGMA; + for (let i = 0; i < 12; i++) { + G1(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G2(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G1(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G2(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G1(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G2(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G1(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G2(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G1(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G2(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G1(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G2(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G1(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G2(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G1(3, 4, 9, 14, msg, offset + 2 * s[j++]); + G2(3, 4, 9, 14, msg, offset + 2 * s[j++]); + } + this.v0l ^= BUF[0] ^ BUF[16]; + this.v0h ^= BUF[1] ^ BUF[17]; + this.v1l ^= BUF[2] ^ BUF[18]; + this.v1h ^= BUF[3] ^ BUF[19]; + this.v2l ^= BUF[4] ^ BUF[20]; + this.v2h ^= BUF[5] ^ BUF[21]; + this.v3l ^= BUF[6] ^ BUF[22]; + this.v3h ^= BUF[7] ^ BUF[23]; + this.v4l ^= BUF[8] ^ BUF[24]; + this.v4h ^= BUF[9] ^ BUF[25]; + this.v5l ^= BUF[10] ^ BUF[26]; + this.v5h ^= BUF[11] ^ BUF[27]; + this.v6l ^= BUF[12] ^ BUF[28]; + this.v6h ^= BUF[13] ^ BUF[29]; + this.v7l ^= BUF[14] ^ BUF[30]; + this.v7h ^= BUF[15] ^ BUF[31]; + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +exports.blake2b = (0, utils_js_1.wrapConstructorWithOpts)((opts) => new BLAKE2b(opts)); +//# sourceMappingURL=blake2b.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/blake2b.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/blake2b.js.map new file mode 100644 index 0000000..4e936fb --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/blake2b.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2b.js","sourceRoot":"","sources":["src/blake2b.ts"],"names":[],"mappings":";;;AAAA,6CAAwD;AACxD,uCAA4B;AAC5B,yCAAmE;AAEnE,yBAAyB;AACzB,kBAAkB;AAClB,MAAM,EAAE,GAAG,eAAe,CAAC,IAAI,WAAW,CAAC;IACzC,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;IAC9F,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;CAC/F,CAAC,CAAC;AACH,mBAAmB;AACnB,MAAM,GAAG,GAAG,eAAe,CAAC,IAAI,WAAW,CAAC,EAAE,CAAC,CAAC;AAEhD,0CAA0C;AAC1C,SAAS,EAAE,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS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IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,CAAC;QAC9B,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,CAAC;QAC9B,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,CAAC;QAC9B,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,CAAC;QAC9B,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,CAAC;QAC9B,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACd,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACtB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC3D,CAAC;CACF;AAED;;;;GAIG;AACU,QAAA,OAAO,GAAmB,IAAA,kCAAuB,EAC5D,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAC5B,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/blake2s.d.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/blake2s.d.ts new file mode 100644 index 0000000..d9dd59b --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/blake2s.d.ts @@ -0,0 +1,47 @@ +import { BLAKE2, BlakeOpts } from './_blake2.js'; +export declare const IV: Uint32Array; +export declare function compress(s: Uint8Array, offset: number, msg: Uint32Array, rounds: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number): { + v0: number; + v1: number; + v2: number; + v3: number; + v4: number; + v5: number; + v6: number; + v7: number; + v8: number; + v9: number; + v10: number; + v11: number; + v12: number; + v13: number; + v14: number; + v15: number; +}; +declare class BLAKE2s extends BLAKE2 { + private v0; + private v1; + private v2; + private v3; + private v4; + private v5; + private v6; + private v7; + constructor(opts?: BlakeOpts); + protected get(): [number, number, number, number, number, number, number, number]; + protected set(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number): void; + protected compress(msg: Uint32Array, offset: number, isLast: boolean): void; + destroy(): void; +} +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export declare const blake2s: { + (msg: import("./utils.js").Input, opts?: BlakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: BlakeOpts): import("./utils.js").Hash; +}; +export {}; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/blake2s.js b/node_modules/@noble/curves/node_modules/@noble/hashes/blake2s.js new file mode 100644 index 0000000..ace7513 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/blake2s.js @@ -0,0 +1,122 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.blake2s = exports.compress = exports.IV = void 0; +const _blake2_js_1 = require("./_blake2.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19) +// same as SHA-256 +// prettier-ignore +exports.IV = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]); +// Mixing function G splitted in two halfs +function G1(a, b, c, d, x) { + a = (a + b + x) | 0; + d = (0, utils_js_1.rotr)(d ^ a, 16); + c = (c + d) | 0; + b = (0, utils_js_1.rotr)(b ^ c, 12); + return { a, b, c, d }; +} +function G2(a, b, c, d, x) { + a = (a + b + x) | 0; + d = (0, utils_js_1.rotr)(d ^ a, 8); + c = (c + d) | 0; + b = (0, utils_js_1.rotr)(b ^ c, 7); + return { a, b, c, d }; +} +// prettier-ignore +function compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) { + let j = 0; + for (let i = 0; i < rounds; i++) { + ({ a: v0, b: v4, c: v8, d: v12 } = G1(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v0, b: v4, c: v8, d: v12 } = G2(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G1(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G2(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G1(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G2(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G1(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G2(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G1(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G2(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G1(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G2(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G1(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G2(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G1(v3, v4, v9, v14, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G2(v3, v4, v9, v14, msg[offset + s[j++]])); + } + return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; +} +exports.compress = compress; +class BLAKE2s extends _blake2_js_1.BLAKE2 { + constructor(opts = {}) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, opts, 32, 8, 8); + // Internal state, same as SHA-256 + this.v0 = exports.IV[0] | 0; + this.v1 = exports.IV[1] | 0; + this.v2 = exports.IV[2] | 0; + this.v3 = exports.IV[3] | 0; + this.v4 = exports.IV[4] | 0; + this.v5 = exports.IV[5] | 0; + this.v6 = exports.IV[6] | 0; + this.v7 = exports.IV[7] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.salt)); + this.v4 ^= salt[0]; + this.v5 ^= salt[1]; + } + if (opts.personalization) { + const pers = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.personalization)); + this.v6 ^= pers[0]; + this.v7 ^= pers[1]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set((0, utils_js_1.toBytes)(opts.key)); + this.update(tmp); + } + } + get() { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + set(v0, v1, v2, v3, v4, v5, v6, v7) { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + compress(msg, offset, isLast) { + const { h, l } = (0, _u64_js_1.fromBig)(BigInt(this.length)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(_blake2_js_1.SIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, exports.IV[0], exports.IV[1], exports.IV[2], exports.IV[3], l ^ exports.IV[4], h ^ exports.IV[5], isLast ? ~exports.IV[6] : exports.IV[6], exports.IV[7]); + this.v0 ^= v0 ^ v8; + this.v1 ^= v1 ^ v9; + this.v2 ^= v2 ^ v10; + this.v3 ^= v3 ^ v11; + this.v4 ^= v4 ^ v12; + this.v5 ^= v5 ^ v13; + this.v6 ^= v6 ^ v14; + this.v7 ^= v7 ^ v15; + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +exports.blake2s = (0, utils_js_1.wrapConstructorWithOpts)((opts) => new BLAKE2s(opts)); +//# sourceMappingURL=blake2s.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/blake2s.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/blake2s.js.map new file mode 100644 index 0000000..ac692b3 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/blake2s.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2s.js","sourceRoot":"","sources":["src/blake2s.ts"],"names":[],"mappings":";;;AAAA,6CAAwD;AACxD,uCAAoC;AACpC,yCAAyE;AAEzE,iBAAiB;AACjB,yFAAyF;AACzF,kBAAkB;AAClB,kBAAkB;AACL,QAAA,EAAE,GAAkB,IAAI,WAAW,CAAC,CAAC,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAA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E,IAAI,EAAE,GAAG,GAAG,CAAC;IACtB,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACtB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IACnC,CAAC;CACF;AAED;;;;GAIG;AACU,QAAA,OAAO,GAAmB,IAAA,kCAAuB,EAC5D,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAC5B,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/blake3.d.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/blake3.d.ts new file mode 100644 index 0000000..13894cf --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/blake3.d.ts @@ -0,0 +1,46 @@ +import { BLAKE2 } from './_blake2.js'; +import { Input, HashXOF } from './utils.js'; +export type Blake3Opts = { + dkLen?: number; + key?: Input; + context?: Input; +}; +declare class BLAKE3 extends BLAKE2 implements HashXOF { + private IV; + private flags; + private state; + private chunkPos; + private chunksDone; + private stack; + private posOut; + private bufferOut32; + private bufferOut; + private chunkOut; + private enableXOF; + constructor(opts?: Blake3Opts, flags?: number); + protected get(): never[]; + protected set(): void; + private b2Compress; + protected compress(buf: Uint32Array, bufPos?: number, isLast?: boolean): void; + _cloneInto(to?: BLAKE3): BLAKE3; + destroy(): void; + private b2CompressOut; + protected finish(): void; + private writeInto; + xofInto(out: Uint8Array): Uint8Array; + xof(bytes: number): Uint8Array; + digestInto(out: Uint8Array): Uint8Array; + digest(): Uint8Array; +} +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +export declare const blake3: { + (msg: Input, opts?: Blake3Opts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: Blake3Opts): HashXOF; +}; +export {}; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/blake3.js b/node_modules/@noble/curves/node_modules/@noble/hashes/blake3.js new file mode 100644 index 0000000..3c339f5 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/blake3.js @@ -0,0 +1,229 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.blake3 = void 0; +const _assert_js_1 = require("./_assert.js"); +const _u64_js_1 = require("./_u64.js"); +const _blake2_js_1 = require("./_blake2.js"); +const blake2s_js_1 = require("./blake2s.js"); +const utils_js_1 = require("./utils.js"); +const SIGMA = /* @__PURE__ */ (() => { + const Id = Array.from({ length: 16 }, (_, i) => i); + const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]); + const res = []; + for (let i = 0, v = Id; i < 7; i++, v = permute(v)) + res.push(...v); + return Uint8Array.from(res); +})(); +// Why is this so slow? It should be 6x faster than blake2b. +// - There is only 30% reduction in number of rounds from blake2s +// - This function uses tree mode to achive parallelisation via SIMD and threading, +// however in JS we don't have threads and SIMD, so we get only overhead from tree structure +// - It is possible to speed it up via Web Workers, hovewer it will make code singnificantly more +// complicated, which we are trying to avoid, since this library is intended to be used +// for cryptographic purposes. Also, parallelization happens only on chunk level (1024 bytes), +// which won't really benefit small inputs. +class BLAKE3 extends _blake2_js_1.BLAKE2 { + constructor(opts = {}, flags = 0) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, {}, Number.MAX_SAFE_INTEGER, 0, 0); + this.flags = 0 | 0; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + this.stack = []; + // Output + this.posOut = 0; + this.bufferOut32 = new Uint32Array(16); + this.chunkOut = 0; // index of output chunk + this.enableXOF = true; + this.outputLen = opts.dkLen === undefined ? 32 : opts.dkLen; + (0, _assert_js_1.number)(this.outputLen); + if (opts.key !== undefined && opts.context !== undefined) + throw new Error('Blake3: only key or context can be specified at same time'); + else if (opts.key !== undefined) { + const key = (0, utils_js_1.toBytes)(opts.key).slice(); + if (key.length !== 32) + throw new Error('Blake3: key should be 32 byte'); + this.IV = (0, utils_js_1.u32)(key); + this.flags = flags | 16 /* Flags.KEYED_HASH */; + } + else if (opts.context !== undefined) { + const context_key = new BLAKE3({ dkLen: 32 }, 32 /* Flags.DERIVE_KEY_CONTEXT */) + .update(opts.context) + .digest(); + this.IV = (0, utils_js_1.u32)(context_key); + this.flags = flags | 64 /* Flags.DERIVE_KEY_MATERIAL */; + } + else { + this.IV = blake2s_js_1.IV.slice(); + this.flags = flags; + } + this.state = this.IV.slice(); + this.bufferOut = (0, utils_js_1.u8)(this.bufferOut32); + } + // Unused + get() { + return []; + } + set() { } + b2Compress(counter, flags, buf, bufPos = 0) { + const { state: s, pos } = this; + const { h, l } = (0, _u64_js_1.fromBig)(BigInt(counter), true); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = (0, blake2s_js_1.compress)(SIGMA, bufPos, buf, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], blake2s_js_1.IV[0], blake2s_js_1.IV[1], blake2s_js_1.IV[2], blake2s_js_1.IV[3], h, l, pos, flags); + s[0] = v0 ^ v8; + s[1] = v1 ^ v9; + s[2] = v2 ^ v10; + s[3] = v3 ^ v11; + s[4] = v4 ^ v12; + s[5] = v5 ^ v13; + s[6] = v6 ^ v14; + s[7] = v7 ^ v15; + } + compress(buf, bufPos = 0, isLast = false) { + // Compress last block + let flags = this.flags; + if (!this.chunkPos) + flags |= 1 /* Flags.CHUNK_START */; + if (this.chunkPos === 15 || isLast) + flags |= 2 /* Flags.CHUNK_END */; + if (!isLast) + this.pos = this.blockLen; + this.b2Compress(this.chunksDone, flags, buf, bufPos); + this.chunkPos += 1; + // If current block is last in chunk (16 blocks), then compress chunks + if (this.chunkPos === 16 || isLast) { + let chunk = this.state; + this.state = this.IV.slice(); + // If not the last one, compress only when there are trailing zeros in chunk counter + // chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed. + // 1 (001) - leaf not finished (just push current chunk to stack) + // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back) + // 3 (011) - last leaf not finished + // 4 (100) - leafs finished at depth=1 and depth=2 + for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) { + if (!(last = this.stack.pop())) + break; + this.buffer32.set(last, 0); + this.buffer32.set(chunk, 8); + this.pos = this.blockLen; + this.b2Compress(0, this.flags | 4 /* Flags.PARENT */, this.buffer32, 0); + chunk = this.state; + this.state = this.IV.slice(); + } + this.chunksDone++; + this.chunkPos = 0; + this.stack.push(chunk); + } + this.pos = 0; + } + _cloneInto(to) { + to = super._cloneInto(to); + const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this; + to.state.set(state.slice()); + to.stack = stack.map((i) => Uint32Array.from(i)); + to.IV.set(IV); + to.flags = flags; + to.chunkPos = chunkPos; + to.chunksDone = chunksDone; + to.posOut = posOut; + to.chunkOut = chunkOut; + to.enableXOF = this.enableXOF; + to.bufferOut32.set(this.bufferOut32); + return to; + } + destroy() { + this.destroyed = true; + this.state.fill(0); + this.buffer32.fill(0); + this.IV.fill(0); + this.bufferOut32.fill(0); + for (let i of this.stack) + i.fill(0); + } + // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8) + b2CompressOut() { + const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this; + const { h, l } = (0, _u64_js_1.fromBig)(BigInt(this.chunkOut++)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = (0, blake2s_js_1.compress)(SIGMA, 0, buffer32, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], blake2s_js_1.IV[0], blake2s_js_1.IV[1], blake2s_js_1.IV[2], blake2s_js_1.IV[3], l, h, pos, flags); + out32[0] = v0 ^ v8; + out32[1] = v1 ^ v9; + out32[2] = v2 ^ v10; + out32[3] = v3 ^ v11; + out32[4] = v4 ^ v12; + out32[5] = v5 ^ v13; + out32[6] = v6 ^ v14; + out32[7] = v7 ^ v15; + out32[8] = s[0] ^ v8; + out32[9] = s[1] ^ v9; + out32[10] = s[2] ^ v10; + out32[11] = s[3] ^ v11; + out32[12] = s[4] ^ v12; + out32[13] = s[5] ^ v13; + out32[14] = s[6] ^ v14; + out32[15] = s[7] ^ v15; + this.posOut = 0; + } + finish() { + if (this.finished) + return; + this.finished = true; + // Padding + this.buffer.fill(0, this.pos); + // Process last chunk + let flags = this.flags | 8 /* Flags.ROOT */; + if (this.stack.length) { + flags |= 4 /* Flags.PARENT */; + this.compress(this.buffer32, 0, true); + this.chunksDone = 0; + this.pos = this.blockLen; + } + else { + flags |= (!this.chunkPos ? 1 /* Flags.CHUNK_START */ : 0) | 2 /* Flags.CHUNK_END */; + } + this.flags = flags; + this.b2CompressOut(); + } + writeInto(out) { + (0, _assert_js_1.exists)(this, false); + (0, _assert_js_1.bytes)(out); + this.finish(); + const { blockLen, bufferOut } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.b2CompressOut(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + if (!this.enableXOF) + throw new Error('XOF is not possible after digest call'); + return this.writeInto(out); + } + xof(bytes) { + (0, _assert_js_1.number)(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + (0, _assert_js_1.output)(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.enableXOF = false; + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } +} +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +exports.blake3 = (0, utils_js_1.wrapXOFConstructorWithOpts)((opts) => new BLAKE3(opts)); +//# sourceMappingURL=blake3.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/blake3.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/blake3.js.map new file mode 100644 index 0000000..7ed8fd6 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/blake3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake3.js","sourceRoot":"","sources":["src/blake3.ts"],"names":[],"mappings":";;;AAAA,6CAA6D;AAC7D,uCAAoC;AACpC,6CAAsC;AACtC,6CAA4C;AAC5C,yCAA0F;AAe1F,MAAM,KAAK,GAAe,eAAe,CAAC,CAAC,GAAG,EAAE;IAC9C,MAAM,EAAE,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;IACnD,MAAM,OAAO,GAAG,CAAC,GAAa,EAAE,EAAE,CAChC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAC5E,MAAM,GAAG,GAAa,EAAE,CAAC;IACzB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;QAAE,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IACnE,OAAO,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC9B,CAAC,CAAC,EA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/curves/node_modules/@noble/hashes/crypto.d.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/crypto.d.ts new file mode 100644 index 0000000..cebbcd1 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/crypto.d.ts @@ -0,0 +1 @@ +export declare const crypto: any; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/crypto.js b/node_modules/@noble/curves/node_modules/@noble/hashes/crypto.js new file mode 100644 index 0000000..8226391 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/crypto.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.crypto = void 0; +exports.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; +//# sourceMappingURL=crypto.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/crypto.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/crypto.js.map new file mode 100644 index 0000000..9f794e2 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/crypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.js","sourceRoot":"","sources":["src/crypto.ts"],"names":[],"mappings":";;;AAGa,QAAA,MAAM,GACjB,OAAO,UAAU,KAAK,QAAQ,IAAI,QAAQ,IAAI,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/cryptoNode.d.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/cryptoNode.d.ts new file mode 100644 index 0000000..cebbcd1 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/cryptoNode.d.ts @@ -0,0 +1 @@ +export declare const crypto: any; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/cryptoNode.js b/node_modules/@noble/curves/node_modules/@noble/hashes/cryptoNode.js new file mode 100644 index 0000000..a88676d --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/cryptoNode.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.crypto = void 0; +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +// The file will throw on node.js 14 and earlier. +// @ts-ignore +const nc = require("node:crypto"); +exports.crypto = nc && typeof nc === 'object' && 'webcrypto' in nc ? nc.webcrypto : undefined; +//# sourceMappingURL=cryptoNode.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/cryptoNode.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/cryptoNode.js.map new file mode 100644 index 0000000..9287d27 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/cryptoNode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cryptoNode.js","sourceRoot":"","sources":["src/cryptoNode.ts"],"names":[],"mappings":";;;AAAA,oFAAoF;AACpF,4BAA4B;AAC5B,iDAAiD;AACjD,aAAa;AACb,kCAAkC;AACrB,QAAA,MAAM,GACjB,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,WAAW,IAAI,EAAE,CAAC,CAAC,CAAE,EAAE,CAAC,SAAiB,CAAC,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/eskdf.d.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/eskdf.d.ts new file mode 100644 index 0000000..f0fc54d --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/eskdf.d.ts @@ -0,0 +1,46 @@ +export declare function scrypt(password: string, salt: string): Uint8Array; +export declare function pbkdf2(password: string, salt: string): Uint8Array; +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +export declare function deriveMainSeed(username: string, password: string): Uint8Array; +type AccountID = number | string; +type OptsLength = { + keyLength: number; +}; +type OptsMod = { + modulus: bigint; +}; +type KeyOpts = undefined | OptsLength | OptsMod; +type ESKDF = Promise Uint8Array; + /** + * Deletes the main seed from eskdf instance + */ + expire: () => void; + /** + * Account fingerprint + */ + fingerprint: string; +}>>; +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +export declare function eskdf(username: string, password: string): ESKDF; +export {}; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/eskdf.js b/node_modules/@noble/curves/node_modules/@noble/hashes/eskdf.js new file mode 100644 index 0000000..bc622b6 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/eskdf.js @@ -0,0 +1,162 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.eskdf = exports.deriveMainSeed = exports.pbkdf2 = exports.scrypt = void 0; +const _assert_js_1 = require("./_assert.js"); +const hkdf_js_1 = require("./hkdf.js"); +const sha256_js_1 = require("./sha256.js"); +const pbkdf2_js_1 = require("./pbkdf2.js"); +const scrypt_js_1 = require("./scrypt.js"); +const utils_js_1 = require("./utils.js"); +// A tiny KDF for various applications like AES key-gen. +// Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure". +// Which is good enough: assume sha2-256 retained preimage resistance. +const SCRYPT_FACTOR = 2 ** 19; +const PBKDF2_FACTOR = 2 ** 17; +// Scrypt KDF +function scrypt(password, salt) { + return (0, scrypt_js_1.scrypt)(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 }); +} +exports.scrypt = scrypt; +// PBKDF2-HMAC-SHA256 +function pbkdf2(password, salt) { + return (0, pbkdf2_js_1.pbkdf2)(sha256_js_1.sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 }); +} +exports.pbkdf2 = pbkdf2; +// Combines two 32-byte byte arrays +function xor32(a, b) { + (0, _assert_js_1.bytes)(a, 32); + (0, _assert_js_1.bytes)(b, 32); + const arr = new Uint8Array(32); + for (let i = 0; i < 32; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} +function strHasLength(str, min, max) { + return typeof str === 'string' && str.length >= min && str.length <= max; +} +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +function deriveMainSeed(username, password) { + if (!strHasLength(username, 8, 255)) + throw new Error('invalid username'); + if (!strHasLength(password, 8, 255)) + throw new Error('invalid password'); + const scr = scrypt(password + '\u{1}', username + '\u{1}'); + const pbk = pbkdf2(password + '\u{2}', username + '\u{2}'); + const res = xor32(scr, pbk); + scr.fill(0); + pbk.fill(0); + return res; +} +exports.deriveMainSeed = deriveMainSeed; +/** + * Converts protocol & accountId pair to HKDF salt & info params. + */ +function getSaltInfo(protocol, accountId = 0) { + // Note that length here also repeats two lines below + // We do an additional length check here to reduce the scope of DoS attacks + if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) { + throw new Error('invalid protocol'); + } + // Allow string account ids for some protocols + const allowsStr = /^password\d{0,3}|ssh|tor|file$/.test(protocol); + let salt; // Extract salt. Default is undefined. + if (typeof accountId === 'string') { + if (!allowsStr) + throw new Error('accountId must be a number'); + if (!strHasLength(accountId, 1, 255)) + throw new Error('accountId must be valid string'); + salt = (0, utils_js_1.toBytes)(accountId); + } + else if (Number.isSafeInteger(accountId)) { + if (accountId < 0 || accountId > 2 ** 32 - 1) + throw new Error('invalid accountId'); + // Convert to Big Endian Uint32 + salt = new Uint8Array(4); + (0, utils_js_1.createView)(salt).setUint32(0, accountId, false); + } + else { + throw new Error(`accountId must be a number${allowsStr ? ' or string' : ''}`); + } + const info = (0, utils_js_1.toBytes)(protocol); + return { salt, info }; +} +function countBytes(num) { + if (typeof num !== 'bigint' || num <= BigInt(128)) + throw new Error('invalid number'); + return Math.ceil(num.toString(2).length / 8); +} +/** + * Parses keyLength and modulus options to extract length of result key. + * If modulus is used, adds 64 bits to it as per FIPS 186 B.4.1 to combat modulo bias. + */ +function getKeyLength(options) { + if (!options || typeof options !== 'object') + return 32; + const hasLen = 'keyLength' in options; + const hasMod = 'modulus' in options; + if (hasLen && hasMod) + throw new Error('cannot combine keyLength and modulus options'); + if (!hasLen && !hasMod) + throw new Error('must have either keyLength or modulus option'); + // FIPS 186 B.4.1 requires at least 64 more bits + const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength; + if (!(typeof l === 'number' && l >= 16 && l <= 8192)) + throw new Error('invalid keyLength'); + return l; +} +/** + * Converts key to bigint and divides it by modulus. Big Endian. + * Implements FIPS 186 B.4.1, which removes 0 and modulo bias from output. + */ +function modReduceKey(key, modulus) { + const _1 = BigInt(1); + const num = BigInt('0x' + (0, utils_js_1.bytesToHex)(key)); // check for ui8a, then bytesToNumber() + const res = (num % (modulus - _1)) + _1; // Remove 0 from output + if (res < _1) + throw new Error('expected positive number'); // Guard against bad values + const len = key.length - 8; // FIPS requires 64 more bits = 8 bytes + const hex = res.toString(16).padStart(len * 2, '0'); // numberToHex() + const bytes = (0, utils_js_1.hexToBytes)(hex); + if (bytes.length !== len) + throw new Error('invalid length of result key'); + return bytes; +} +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +async function eskdf(username, password) { + // We are using closure + object instead of class because + // we want to make `seed` non-accessible for any external function. + let seed = deriveMainSeed(username, password); + function deriveCK(protocol, accountId = 0, options) { + (0, _assert_js_1.bytes)(seed, 32); + const { salt, info } = getSaltInfo(protocol, accountId); // validate protocol & accountId + const keyLength = getKeyLength(options); // validate options + const key = (0, hkdf_js_1.hkdf)(sha256_js_1.sha256, seed, salt, info, keyLength); + // Modulus has already been validated + return options && 'modulus' in options ? modReduceKey(key, options.modulus) : key; + } + function expire() { + if (seed) + seed.fill(1); + seed = undefined; + } + // prettier-ignore + const fingerprint = Array.from(deriveCK('fingerprint', 0)) + .slice(0, 6) + .map((char) => char.toString(16).padStart(2, '0').toUpperCase()) + .join(':'); + return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint }); +} +exports.eskdf = eskdf; +//# sourceMappingURL=eskdf.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/eskdf.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/eskdf.js.map new file mode 100644 index 0000000..70c49e9 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/eskdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eskdf.js","sourceRoot":"","sources":["src/eskdf.ts"],"names":[],"mappings":";;;AAAA,6CAAoD;AACpD,uCAAiC;AACjC,2CAAqC;AACrC,2CAAgD;AAChD,2CAAgD;AAChD,yCAAyE;AAEzE,wDAAwD;AACxD,gFAAgF;AAChF,sEAAsE;AAEtE,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,CAAC;AAC9B,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,CAAC;AAE9B,aAAa;AACb,SAAgB,MAAM,CAAC,QAAgB,EAAE,IAAY;IACnD,OAAO,IAAA,kBAAO,EAAC,QAAQ,EAAE,IAAI,EAAE,EAAE,CAAC,EAAE,aAAa,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;AAC9E,CAAC;AAFD,wBAEC;AAED,qBAAqB;AACrB,SAAgB,MAAM,CAAC,QAAgB,EAAE,IAAY;IACnD,OAAO,IAAA,kBAAO,EAAC,kBAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,CAAC,EAAE,aAAa,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;AAC1E,CAAC;AAFD,wBAEC;AAED,mCAAmC;AACnC,SAAS,KAAK,CAAC,CAAa,EAAE,CAAa;IACzC,IAAA,kBAAW,EAAC,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AI,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC;QACvD,qCAAqC;QACrC,OAAO,OAAO,IAAI,SAAS,IAAI,OAAO,CAAC,CAAC,CAAC,YAAY,CAAC,GAAG,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;IACpF,CAAC;IACD,SAAS,MAAM;QACb,IAAI,IAAI;YAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACvB,IAAI,GAAG,SAAS,CAAC;IACnB,CAAC;IACD,kBAAkB;IAClB,MAAM,WAAW,GAAG,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC;SACvD,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;SACX,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC;SAC/D,IAAI,CAAC,GAAG,CAAC,CAAC;IACb,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC,CAAC;AAC1E,CAAC;AAvBD,sBAuBC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_assert.js b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_assert.js new file mode 100644 index 0000000..4259cea --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_assert.js @@ -0,0 +1,37 @@ +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); +} +function bool(b) { + if (typeof b !== 'boolean') + throw new Error(`Expected boolean, not ${b}`); +} +function bytes(b, ...lengths) { + if (!(b instanceof Uint8Array)) + throw new Error('Expected Uint8Array'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} +function hash(hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(hash.outputLen); + number(hash.blockLen); +} +function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} +export { number, bool, bytes, hash, exists, output }; +const assert = { number, bool, bytes, hash, exists, output }; +export default assert; +//# sourceMappingURL=_assert.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_assert.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_assert.js.map new file mode 100644 index 0000000..d8f294f --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_assert.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_assert.js","sourceRoot":"","sources":["../src/_assert.ts"],"names":[],"mappings":"AAAA,SAAS,MAAM,CAAC,CAAS;IACvB,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,EAAE,CAAC,CAAC;AACzF,CAAC;AAED,SAAS,IAAI,CAAC,CAAU;IACtB,IAAI,OAAO,CAAC,KAAK,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,EAAE,CAAC,CAAC;AAC5E,CAAC;AAED,SAAS,KAAK,CAAC,CAAyB,EAAE,GAAG,OAAiB;IAC5D,IAAI,CAAC,CAAC,CAAC,YAAY,UAAU,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;IACvE,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC;QACnD,MAAM,IAAI,KAAK,CAAC,iCAAiC,OAAO,mBAAmB,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC;AAC3F,CAAC;AAQD,SAAS,IAAI,CAAC,IAAU;IACtB,IAAI,OAAO,IAAI,KAAK,UAAU,IAAI,OAAO,IAAI,CAAC,MAAM,KAAK,UAAU;QACjE,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IACrE,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACvB,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AACxB,CAAC;AAED,SAAS,MAAM,CAAC,QAAa,EAAE,aAAa,GAAG,IAAI;IACjD,IAAI,QAAQ,CAAC,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;IAC5E,IAAI,aAAa,IAAI,QAAQ,CAAC,QAAQ;QAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;AACnG,CAAC;AACD,SAAS,MAAM,CAAC,GAAQ,EAAE,QAAa;IACrC,KAAK,CAAC,GAAG,CAAC,CAAC;IACX,MAAM,GAAG,GAAG,QAAQ,CAAC,SAAS,CAAC;IAC/B,IAAI,GAAG,CAAC,MAAM,GAAG,GAAG,EAAE;QACpB,MAAM,IAAI,KAAK,CAAC,yDAAyD,GAAG,EAAE,CAAC,CAAC;KACjF;AACH,CAAC;AAED,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAErD,MAAM,MAAM,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAC7D,eAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_blake2.js b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_blake2.js new file mode 100644 index 0000000..948e01b --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_blake2.js @@ -0,0 +1,108 @@ +import { number, exists, output } from './_assert.js'; +import { Hash, toBytes, u32 } from './utils.js'; +// Blake is based on ChaCha permutation. +// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. +// prettier-ignore +export const SIGMA = /* @__PURE__ */ new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, +]); +export class BLAKE2 extends Hash { + constructor(blockLen, outputLen, opts = {}, keyLen, saltLen, persLen) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.length = 0; + this.pos = 0; + this.finished = false; + this.destroyed = false; + number(blockLen); + number(outputLen); + number(keyLen); + if (outputLen < 0 || outputLen > keyLen) + throw new Error('outputLen bigger than keyLen'); + if (opts.key !== undefined && (opts.key.length < 1 || opts.key.length > keyLen)) + throw new Error(`key must be up 1..${keyLen} byte long or undefined`); + if (opts.salt !== undefined && opts.salt.length !== saltLen) + throw new Error(`salt must be ${saltLen} byte long or undefined`); + if (opts.personalization !== undefined && opts.personalization.length !== persLen) + throw new Error(`personalization must be ${persLen} byte long or undefined`); + this.buffer32 = u32((this.buffer = new Uint8Array(blockLen))); + } + update(data) { + exists(this); + // Main difference with other hashes: there is flag for last block, + // so we cannot process current block before we know that there + // is the next one. This significantly complicates logic and reduces ability + // to do zero-copy processing + const { blockLen, buffer, buffer32 } = this; + data = toBytes(data); + const len = data.length; + const offset = data.byteOffset; + const buf = data.buffer; + for (let pos = 0; pos < len;) { + // If buffer is full and we still have input (don't process last block, same as blake2s) + if (this.pos === blockLen) { + this.compress(buffer32, 0, false); + this.pos = 0; + } + const take = Math.min(blockLen - this.pos, len - pos); + const dataOffset = offset + pos; + // full block && aligned to 4 bytes && not last in input + if (take === blockLen && !(dataOffset % 4) && pos + take < len) { + const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4)); + for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) { + this.length += blockLen; + this.compress(data32, pos32, false); + } + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + this.length += take; + pos += take; + } + return this; + } + digestInto(out) { + exists(this); + output(out, this); + const { pos, buffer32 } = this; + this.finished = true; + // Padding + this.buffer.subarray(pos).fill(0); + this.compress(buffer32, 0, true); + const out32 = u32(out); + this.get().forEach((v, i) => (out32[i] = v)); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + const { buffer, length, finished, destroyed, outputLen, pos } = this; + to || (to = new this.constructor({ dkLen: outputLen })); + to.set(...this.get()); + to.length = length; + to.finished = finished; + to.destroyed = destroyed; + to.outputLen = outputLen; + to.buffer.set(buffer); + to.pos = pos; + return to; + } +} +//# sourceMappingURL=_blake2.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_blake2.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_blake2.js.map new file mode 100644 index 0000000..4222d07 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_blake2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_blake2.js","sourceRoot":"","sources":["../src/_blake2.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,IAAI,EAAS,OAAO,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AAEvD,wCAAwC;AAExC,gGAAgG;AAChG,kBAAkB;AAClB,MAAM,CAAC,MAAM,KAAK,GAAG,eAAe,CAAC,IAAI,UAAU,CAAC;IAClD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;IACpD,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE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vB,IAAI,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IAC/C,CAAC;IACD,MAAM;QACJ,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;QACnC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QACxB,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;QACvC,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,OAAO,GAAG,CAAC;IACb,CAAC;IACD,UAAU,CAAC,EAAM;QACf,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;QACrE,EAAE,KAAF,EAAE,GAAK,IAAK,IAAI,CAAC,WAAmB,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,CAAM,EAAC;QAChE,EAAE,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;QACtB,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC;QACnB,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACvB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACtB,EAAE,CAAC,GAAG,GAAG,GAAG,CAAC;QACb,OAAO,EAAE,CAAC;IACZ,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_sha2.js b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_sha2.js new file mode 100644 index 0000000..cd26ea4 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_sha2.js @@ -0,0 +1,114 @@ +import { exists, output } from './_assert.js'; +import { Hash, createView, toBytes } from './utils.js'; +// Polyfill for Safari 14 +function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +// Base SHA2 class (RFC 6234) +export class SHA2 extends Hash { + constructor(blockLen, outputLen, padOffset, isLE) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + exists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input, cast it to view and process + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + exists(this); + output(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + this.buffer.subarray(pos).fill(0); + // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) + buffer[i] = 0; + // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + if (len % 4) + throw new Error('_sha2: outputLen should be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } +} +//# sourceMappingURL=_sha2.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_sha2.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_sha2.js.map new file mode 100644 index 0000000..1675e44 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_sha2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_sha2.js","sourceRoot":"","sources":["../src/_sha2.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,IAAI,EAAE,UAAU,EAAS,OAAO,EAAE,MAAM,YAAY,CAAC;AAE9D,yBAAyB;AACzB,SAAS,YAAY,CAAC,IAAc,EAAE,UAAkB,EAAE,KAAa,EAAE,IAAa;IACpF,IAAI,OAAO,IAAI,CAAC,YAAY,KAAK,UAAU;QAAE,OAAO,IAAI,CAAC,YAAY,CAAC,UAAU,EAAE,KAAK,EAAE,IAAI,CA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AE,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;QACjF,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,EAAE,CAAC,EAAE;YAAE,KAAK,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;IAC1E,CAAC;IACD,MAAM;QACJ,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;QACnC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QACxB,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;QACvC,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,OAAO,GAAG,CAAC;IACb,CAAC;IACD,UAAU,CAAC,EAAM;QACf,EAAE,KAAF,EAAE,GAAK,IAAK,IAAI,CAAC,WAAmB,EAAO,EAAC;QAC5C,EAAE,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;QACtB,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;QACpE,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC;QACnB,EAAE,CAAC,GAAG,GAAG,GAAG,CAAC;QACb,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACvB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,IAAI,MAAM,GAAG,QAAQ;YAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC7C,OAAO,EAAE,CAAC;IACZ,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_u64.js b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_u64.js new file mode 100644 index 0000000..66cce47 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_u64.js @@ -0,0 +1,62 @@ +const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n = /* @__PURE__ */ BigInt(32); +// We are not using BigUint64Array, because they are extremely slow as per 2022 +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +function split(lst, le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +// for Shift in [0, 32) +const shrSH = (h, _l, s) => h >>> s; +const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in [1, 32) +const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); +const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); +const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (_h, l) => l; +const rotr32L = (h, _l) => h; +// Left rotate for Shift in [1, 32) +const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); +const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); +const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +// Addition with more than 2 elements +const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; +// prettier-ignore +export { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, }; +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +export default u64; +//# sourceMappingURL=_u64.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_u64.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_u64.js.map new file mode 100644 index 0000000..b2339ed --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_u64.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_u64.js","sourceRoot":"","sources":["../src/_u64.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC;AACvD,MAAM,IAAI,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,EAAU,EAAE,EAAU,EAAE,EAAE,CACxF,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;AAEvD,kBAAkB;AAClB,OAAO,EACL,OAAO,EAAE,KAAK,EAAE,KAAK,EACrB,KAAK,EAAE,KAAK,EACZ,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAC9B,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAC9B,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,GAC9C,CAAC;AACF,kBAAkB;AAClB,MAAM,GAAG,GAAG;IACV,OAAO,EAAE,KAAK,EAAE,KAAK;IACrB,KAAK,EAAE,KAAK;IACZ,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9B,OAAO,EAAE,OAAO;IAChB,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9B,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK;CAC9C,CAAC;AACF,eAAe,GAAG,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/argon2.js b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/argon2.js new file mode 100644 index 0000000..1e5a6b0 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/argon2.js @@ -0,0 +1,297 @@ +import { number as assertNumber } from './_assert.js'; +import { toBytes, u8, u32 } from './utils.js'; +import { blake2b } from './blake2b.js'; +import { add3H, add3L, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL } from './_u64.js'; +const ARGON2_SYNC_POINTS = 4; +const toBytesOptional = (buf) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); +function mul(a, b) { + const aL = a & 0xffff; + const aH = a >>> 16; + const bL = b & 0xffff; + const bH = b >>> 16; + const ll = Math.imul(aL, bL); + const hl = Math.imul(aH, bL); + const lh = Math.imul(aL, bH); + const hh = Math.imul(aH, bH); + const BUF = ((ll >>> 16) + (hl & 0xffff) + lh) | 0; + const h = ((hl >>> 16) + (BUF >>> 16) + hh) | 0; + return { h, l: (BUF << 16) | (ll & 0xffff) }; +} +function relPos(areaSize, relativePos) { + // areaSize - 1 - ((areaSize * ((relativePos ** 2) >>> 32)) >>> 32) + return areaSize - 1 - mul(areaSize, mul(relativePos, relativePos).h).h; +} +function mul2(a, b) { + // 2 * a * b (via shifts) + const { h, l } = mul(a, b); + return { h: ((h << 1) | (l >>> 31)) & 4294967295, l: (l << 1) & 4294967295 }; +} +function blamka(Ah, Al, Bh, Bl) { + const { h: Ch, l: Cl } = mul2(Al, Bl); + // A + B + (2 * A * B) + const Rll = add3L(Al, Bl, Cl); + return { h: add3H(Rll, Ah, Bh, Ch), l: Rll | 0 }; +} +// Temporary block buffer +const BUF = new Uint32Array(256); +function G(a, b, c, d) { + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: rotr32H(Dh, Dl), Dl: rotr32L(Dh, Dl) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: rotrSH(Bh, Bl, 24), Bl: rotrSL(Bh, Bl, 24) }); + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: rotrSH(Dh, Dl, 16), Dl: rotrSL(Dh, Dl, 16) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: rotrBH(Bh, Bl, 63), Bl: rotrBL(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +// prettier-ignore +function P(v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15) { + G(v00, v04, v08, v12); + G(v01, v05, v09, v13); + G(v02, v06, v10, v14); + G(v03, v07, v11, v15); + G(v00, v05, v10, v15); + G(v01, v06, v11, v12); + G(v02, v07, v08, v13); + G(v03, v04, v09, v14); +} +function block(x, xPos, yPos, outPos, needXor) { + for (let i = 0; i < 256; i++) + BUF[i] = x[xPos + i] ^ x[yPos + i]; + // columns + for (let i = 0; i < 128; i += 16) { + // prettier-ignore + P(i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15); + } + // rows + for (let i = 0; i < 16; i += 2) { + // prettier-ignore + P(i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113); + } + if (needXor) + for (let i = 0; i < 256; i++) + x[outPos + i] ^= BUF[i] ^ x[xPos + i] ^ x[yPos + i]; + else + for (let i = 0; i < 256; i++) + x[outPos + i] = BUF[i] ^ x[xPos + i] ^ x[yPos + i]; +} +// Variable-Length Hash Function H' +function Hp(A, dkLen) { + const A8 = u8(A); + const T = new Uint32Array(1); + const T8 = u8(T); + T[0] = dkLen; + // Fast path + if (dkLen <= 64) + return blake2b.create({ dkLen }).update(T8).update(A8).digest(); + const out = new Uint8Array(dkLen); + let V = blake2b.create({}).update(T8).update(A8).digest(); + let pos = 0; + // First block + out.set(V.subarray(0, 32)); + pos += 32; + // Rest blocks + for (; dkLen - pos > 64; pos += 32) + out.set((V = blake2b(V)).subarray(0, 32), pos); + // Last block + out.set(blake2b(V, { dkLen: dkLen - pos }), pos); + return u32(out); +} +function indexAlpha(r, s, laneLen, segmentLen, index, randL, sameLane = false) { + let area; + if (0 == r) { + if (0 == s) + area = index - 1; + else if (sameLane) + area = s * segmentLen + index - 1; + else + area = s * segmentLen + (index == 0 ? -1 : 0); + } + else if (sameLane) + area = laneLen - segmentLen + index - 1; + else + area = laneLen - segmentLen + (index == 0 ? -1 : 0); + const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0; + const rel = relPos(area, randL); + // NOTE: check about overflows here + // absPos = (startPos + relPos) % laneLength; + return (startPos + rel) % laneLen; +} +function argon2Init(type, password, salt, opts) { + password = toBytes(password); + salt = toBytes(salt); + let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress } = { + ...opts, + version: opts.version || 0x13, + dkLen: opts.dkLen || 32, + maxmem: 2 ** 32, + }; + // Validation + assertNumber(p); + assertNumber(dkLen); + assertNumber(m); + assertNumber(t); + assertNumber(version); + if (dkLen < 4 || dkLen >= 2 ** 32) + throw new Error('Argon2: dkLen should be at least 4 bytes'); + if (p < 1 || p >= 2 ** 32) + throw new Error('Argon2: p (parallelism) should be at least 1'); + if (t < 1 || t >= 2 ** 32) + throw new Error('Argon2: t (iterations) should be at least 1'); + if (m < 8 * p) + throw new Error(`Argon2: memory should be at least 8*p bytes`); + if (version !== 16 && version !== 19) + throw new Error(`Argon2: unknown version=${version}`); + password = toBytes(password); + if (password.length < 0 || password.length >= 2 ** 32) + throw new Error('Argon2: password should be less than 4 GB'); + salt = toBytes(salt); + if (salt.length < 8) + throw new Error('Argon2: salt should be at least 8 bytes'); + key = toBytesOptional(key); + personalization = toBytesOptional(personalization); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + // Params + const lanes = p; + // m' = 4 * p * floor (m / 4p) + const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p)); + //q = m' / p columns + const laneLen = Math.floor(mP / p); + const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS); + // H0 + const h = blake2b.create({}); + const BUF = new Uint32Array(1); + const BUF8 = u8(BUF); + for (const i of [p, dkLen, m, t, version, type]) { + if (i < 0 || i >= 2 ** 32) + throw new Error(`Argon2: wrong parameter=${i}, expected uint32`); + BUF[0] = i; + h.update(BUF8); + } + for (let i of [password, salt, key, personalization]) { + BUF[0] = i.length; + h.update(BUF8).update(i); + } + const H0 = new Uint32Array(18); + const H0_8 = u8(H0); + h.digestInto(H0_8); + // 256 u32 = 1024 (BLOCK_SIZE) + const memUsed = mP * 256; + if (memUsed < 0 || memUsed >= 2 ** 32 || memUsed > maxmem) { + throw new Error(`Argon2: wrong params (memUsed=${memUsed} maxmem=${maxmem}), should be less than 2**32`); + } + const B = new Uint32Array(memUsed); + // Fill first blocks + for (let l = 0; l < p; l++) { + const i = 256 * laneLen * l; + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + H0[17] = l; + H0[16] = 0; + B.set(Hp(H0, 1024), i); + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + H0[16] = 1; + B.set(Hp(H0, 1024), i + 256); + } + let perBlock = () => { }; + if (onProgress) { + const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlock / 10000), 1); + let blockCnt = 0; + perBlock = () => { + blockCnt++; + if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock)) + onProgress(blockCnt / totalBlock); + }; + } + return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock }; +} +function argon2Output(B, p, laneLen, dkLen) { + const B_final = new Uint32Array(256); + for (let l = 0; l < p; l++) + for (let j = 0; j < 256; j++) + B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j]; + return u8(Hp(B_final, dkLen)); +} +function processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor) { + if (offset % laneLen) + prev = offset - 1; + let randL, randH; + if (dataIndependent) { + if (index % 128 === 0) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + randL = address[2 * (index % 128)]; + randH = address[2 * (index % 128) + 1]; + } + else { + const T = 256 * prev; + randL = B[T]; + randH = B[T + 1]; + } + // address block + const refLane = r === 0 && s === 0 ? l : randH % lanes; + const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l); + const refBlock = laneLen * refLane + refPos; + // B[i][j] = G(B[i][j-1], B[l][z]) + block(B, 256 * prev, 256 * refBlock, offset * 256, needXor); +} +function argon2(type, password, salt, opts) { + const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init(type, password, salt, opts); + // Pre-loop setup + // [address, input, zero_block] format so we can pass single U32 to block function + const address = new Uint32Array(3 * 256); + address[256 + 6] = mP; + address[256 + 8] = t; + address[256 + 10] = type; + for (let r = 0; r < t; r++) { + const needXor = r !== 0 && version === 0x13; + address[256 + 0] = r; + for (let s = 0; s < ARGON2_SYNC_POINTS; s++) { + address[256 + 4] = s; + const dataIndependent = type == 1 /* Types.Argon2i */ || (type == 2 /* Types.Argon2id */ && r === 0 && s < 2); + for (let l = 0; l < p; l++) { + address[256 + 2] = l; + address[256 + 12] = 0; + let startPos = 0; + if (r === 0 && s === 0) { + startPos = 2; + if (dataIndependent) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + } + // current block postion + let offset = l * laneLen + s * segmentLen + startPos; + // previous block position + let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1; + for (let index = startPos; index < segmentLen; index++, offset++, prev++) { + perBlock(); + processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor); + } + } + } + } + return argon2Output(B, p, laneLen, dkLen); +} +export const argon2d = (password, salt, opts) => argon2(0 /* Types.Argond2d */, password, salt, opts); +export const argon2i = (password, salt, opts) => argon2(1 /* Types.Argon2i */, password, salt, opts); +export const argon2id = (password, salt, opts) => argon2(2 /* Types.Argon2id */, password, salt, opts); +//# sourceMappingURL=argon2.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/argon2.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/argon2.js.map new file mode 100644 index 0000000..267eb62 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/argon2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"argon2.js","sourceRoot":"","sources":["../src/argon2.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAS,OAAO,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAS3F,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAE7B,MAAM,eAAe,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,CAAC,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,UAAU,CAAC,E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,CAAC;gBACrD,0BAA0B;gBAC1B,IAAI,IAAI,GAAG,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,OAAO,GAAG,CAAC,CAAC;gBAChE,KAAK,IAAI,KAAK,GAAG,QAAQ,EAAE,KAAK,GAAG,UAAU,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,EAAE;oBACxE,QAAQ,EAAE,CAAC;oBACX,YAAY,CACV,CAAC,EACD,OAAO,EACP,CAAC,EACD,CAAC,EACD,CAAC,EACD,KAAK,EACL,OAAO,EACP,UAAU,EACV,KAAK,EACL,MAAM,EACN,IAAI,EACJ,eAAe,EACf,OAAO,CACR,CAAC;iBACH;aACF;SACF;KACF;IACD,OAAO,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;AAC5C,CAAC;AAED,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACvE,MAAM,yBAAiB,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAC/C,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACvE,MAAM,wBAAgB,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAC9C,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACxE,MAAM,yBAAiB,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake2b.js b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake2b.js new file mode 100644 index 0000000..29cecc5 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake2b.js @@ -0,0 +1,189 @@ +import { BLAKE2, SIGMA } from './_blake2.js'; +import u64 from './_u64.js'; +import { toBytes, u32, wrapConstructorWithOpts } from './utils.js'; +// Same as SHA-512 but LE +// prettier-ignore +const IV = /* @__PURE__ */ new Uint32Array([ + 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, + 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19 +]); +// Temporary buffer +const BUF = /* @__PURE__ */ new Uint32Array(32); +// Mixing function G splitted in two halfs +function G1(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 32) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 24) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +function G2(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 16) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 63) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +class BLAKE2b extends BLAKE2 { + constructor(opts = {}) { + super(128, opts.dkLen === undefined ? 64 : opts.dkLen, opts, 64, 16, 16); + // Same as SHA-512, but LE + this.v0l = IV[0] | 0; + this.v0h = IV[1] | 0; + this.v1l = IV[2] | 0; + this.v1h = IV[3] | 0; + this.v2l = IV[4] | 0; + this.v2h = IV[5] | 0; + this.v3l = IV[6] | 0; + this.v3h = IV[7] | 0; + this.v4l = IV[8] | 0; + this.v4h = IV[9] | 0; + this.v5l = IV[10] | 0; + this.v5h = IV[11] | 0; + this.v6l = IV[12] | 0; + this.v6h = IV[13] | 0; + this.v7l = IV[14] | 0; + this.v7h = IV[15] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4l ^= salt[0]; + this.v4h ^= salt[1]; + this.v5l ^= salt[2]; + this.v5h ^= salt[3]; + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6l ^= pers[0]; + this.v6h ^= pers[1]; + this.v7l ^= pers[2]; + this.v7h ^= pers[3]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + // prettier-ignore + get() { + let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + compress(msg, offset, isLast) { + this.get().forEach((v, i) => (BUF[i] = v)); // First half from state. + BUF.set(IV, 16); // Second half from IV. + let { h, l } = u64.fromBig(BigInt(this.length)); + BUF[24] = IV[8] ^ l; // Low word of the offset. + BUF[25] = IV[9] ^ h; // High word. + // Invert all bits for last block + if (isLast) { + BUF[28] = ~BUF[28]; + BUF[29] = ~BUF[29]; + } + let j = 0; + const s = SIGMA; + for (let i = 0; i < 12; i++) { + G1(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G2(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G1(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G2(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G1(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G2(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G1(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G2(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G1(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G2(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G1(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G2(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G1(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G2(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G1(3, 4, 9, 14, msg, offset + 2 * s[j++]); + G2(3, 4, 9, 14, msg, offset + 2 * s[j++]); + } + this.v0l ^= BUF[0] ^ BUF[16]; + this.v0h ^= BUF[1] ^ BUF[17]; + this.v1l ^= BUF[2] ^ BUF[18]; + this.v1h ^= BUF[3] ^ BUF[19]; + this.v2l ^= BUF[4] ^ BUF[20]; + this.v2h ^= BUF[5] ^ BUF[21]; + this.v3l ^= BUF[6] ^ BUF[22]; + this.v3h ^= BUF[7] ^ BUF[23]; + this.v4l ^= BUF[8] ^ BUF[24]; + this.v4h ^= BUF[9] ^ BUF[25]; + this.v5l ^= BUF[10] ^ BUF[26]; + this.v5h ^= BUF[11] ^ BUF[27]; + this.v6l ^= BUF[12] ^ BUF[28]; + this.v6h ^= BUF[13] ^ BUF[29]; + this.v7l ^= BUF[14] ^ BUF[30]; + this.v7h ^= BUF[15] ^ BUF[31]; + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2b = /* @__PURE__ */ wrapConstructorWithOpts((opts) => new BLAKE2b(opts)); +//# sourceMappingURL=blake2b.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake2b.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake2b.js.map new file mode 100644 index 0000000..a448786 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake2b.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2b.js","sourceRoot":"","sources":["../src/blake2b.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAa,KAAK,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,GAAG,MAAM,WAAW,CAAC;AAC5B,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AAEnE,yBAAyB;AACzB,kBAAkB;AAClB,MAAM,EAAE,GAAG,eAAe,CAAC,IAAI,WAAW,CAAC;IACzC,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;IAC9F,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;CAC/F,CAAC,CAAC;AACH,mBAAmB;AACnB,MAAM,GAAG,GAAG,eAAe,CAAC,IAAI,WAAW,CAAC,EAAE,CAAC,CAAC;AAEhD,0CAA0C;AAC1C,SAAS,EAAE,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CA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G,GAAG,CAAC,EAAE,CAAC,CAAC;QAC9B,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,CAAC;QAC9B,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,CAAC;QAC9B,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,CAAC;QAC9B,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,CAAC;QAC9B,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACd,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACtB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC3D,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,eAAe,CAAC,uBAAuB,CAC5D,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAC5B,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake2s.js b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake2s.js new file mode 100644 index 0000000..5c64991 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake2s.js @@ -0,0 +1,118 @@ +import { BLAKE2, SIGMA } from './_blake2.js'; +import { fromBig } from './_u64.js'; +import { rotr, toBytes, wrapConstructorWithOpts, u32 } from './utils.js'; +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19) +// same as SHA-256 +// prettier-ignore +export const IV = /* @__PURE__ */ new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]); +// Mixing function G splitted in two halfs +function G1(a, b, c, d, x) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 16); + c = (c + d) | 0; + b = rotr(b ^ c, 12); + return { a, b, c, d }; +} +function G2(a, b, c, d, x) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 8); + c = (c + d) | 0; + b = rotr(b ^ c, 7); + return { a, b, c, d }; +} +// prettier-ignore +export function compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) { + let j = 0; + for (let i = 0; i < rounds; i++) { + ({ a: v0, b: v4, c: v8, d: v12 } = G1(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v0, b: v4, c: v8, d: v12 } = G2(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G1(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G2(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G1(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G2(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G1(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G2(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G1(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G2(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G1(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G2(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G1(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G2(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G1(v3, v4, v9, v14, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G2(v3, v4, v9, v14, msg[offset + s[j++]])); + } + return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; +} +class BLAKE2s extends BLAKE2 { + constructor(opts = {}) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, opts, 32, 8, 8); + // Internal state, same as SHA-256 + this.v0 = IV[0] | 0; + this.v1 = IV[1] | 0; + this.v2 = IV[2] | 0; + this.v3 = IV[3] | 0; + this.v4 = IV[4] | 0; + this.v5 = IV[5] | 0; + this.v6 = IV[6] | 0; + this.v7 = IV[7] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4 ^= salt[0]; + this.v5 ^= salt[1]; + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6 ^= pers[0]; + this.v7 ^= pers[1]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + get() { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + set(v0, v1, v2, v3, v4, v5, v6, v7) { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + compress(msg, offset, isLast) { + const { h, l } = fromBig(BigInt(this.length)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(SIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, IV[0], IV[1], IV[2], IV[3], l ^ IV[4], h ^ IV[5], isLast ? ~IV[6] : IV[6], IV[7]); + this.v0 ^= v0 ^ v8; + this.v1 ^= v1 ^ v9; + this.v2 ^= v2 ^ v10; + this.v3 ^= v3 ^ v11; + this.v4 ^= v4 ^ v12; + this.v5 ^= v5 ^ v13; + this.v6 ^= v6 ^ v14; + this.v7 ^= v7 ^ v15; + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2s = /* @__PURE__ */ wrapConstructorWithOpts((opts) => new BLAKE2s(opts)); +//# sourceMappingURL=blake2s.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake2s.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake2s.js.map new file mode 100644 index 0000000..44cce78 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake2s.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2s.js","sourceRoot":"","sources":["../src/blake2s.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAa,KAAK,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,uBAAuB,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC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GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;IACtB,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACtB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IACnC,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,eAAe,CAAC,uBAAuB,CAC5D,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAC5B,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake3.js b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake3.js new file mode 100644 index 0000000..af92963 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake3.js @@ -0,0 +1,226 @@ +import { bytes, exists, number, output } from './_assert.js'; +import { fromBig } from './_u64.js'; +import { BLAKE2 } from './_blake2.js'; +import { compress, IV } from './blake2s.js'; +import { u8, u32, toBytes, wrapXOFConstructorWithOpts } from './utils.js'; +const SIGMA = /* @__PURE__ */ (() => { + const Id = Array.from({ length: 16 }, (_, i) => i); + const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]); + const res = []; + for (let i = 0, v = Id; i < 7; i++, v = permute(v)) + res.push(...v); + return Uint8Array.from(res); +})(); +// Why is this so slow? It should be 6x faster than blake2b. +// - There is only 30% reduction in number of rounds from blake2s +// - This function uses tree mode to achive parallelisation via SIMD and threading, +// however in JS we don't have threads and SIMD, so we get only overhead from tree structure +// - It is possible to speed it up via Web Workers, hovewer it will make code singnificantly more +// complicated, which we are trying to avoid, since this library is intended to be used +// for cryptographic purposes. Also, parallelization happens only on chunk level (1024 bytes), +// which won't really benefit small inputs. +class BLAKE3 extends BLAKE2 { + constructor(opts = {}, flags = 0) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, {}, Number.MAX_SAFE_INTEGER, 0, 0); + this.flags = 0 | 0; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + this.stack = []; + // Output + this.posOut = 0; + this.bufferOut32 = new Uint32Array(16); + this.chunkOut = 0; // index of output chunk + this.enableXOF = true; + this.outputLen = opts.dkLen === undefined ? 32 : opts.dkLen; + number(this.outputLen); + if (opts.key !== undefined && opts.context !== undefined) + throw new Error('Blake3: only key or context can be specified at same time'); + else if (opts.key !== undefined) { + const key = toBytes(opts.key).slice(); + if (key.length !== 32) + throw new Error('Blake3: key should be 32 byte'); + this.IV = u32(key); + this.flags = flags | 16 /* Flags.KEYED_HASH */; + } + else if (opts.context !== undefined) { + const context_key = new BLAKE3({ dkLen: 32 }, 32 /* Flags.DERIVE_KEY_CONTEXT */) + .update(opts.context) + .digest(); + this.IV = u32(context_key); + this.flags = flags | 64 /* Flags.DERIVE_KEY_MATERIAL */; + } + else { + this.IV = IV.slice(); + this.flags = flags; + } + this.state = this.IV.slice(); + this.bufferOut = u8(this.bufferOut32); + } + // Unused + get() { + return []; + } + set() { } + b2Compress(counter, flags, buf, bufPos = 0) { + const { state: s, pos } = this; + const { h, l } = fromBig(BigInt(counter), true); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(SIGMA, bufPos, buf, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], IV[0], IV[1], IV[2], IV[3], h, l, pos, flags); + s[0] = v0 ^ v8; + s[1] = v1 ^ v9; + s[2] = v2 ^ v10; + s[3] = v3 ^ v11; + s[4] = v4 ^ v12; + s[5] = v5 ^ v13; + s[6] = v6 ^ v14; + s[7] = v7 ^ v15; + } + compress(buf, bufPos = 0, isLast = false) { + // Compress last block + let flags = this.flags; + if (!this.chunkPos) + flags |= 1 /* Flags.CHUNK_START */; + if (this.chunkPos === 15 || isLast) + flags |= 2 /* Flags.CHUNK_END */; + if (!isLast) + this.pos = this.blockLen; + this.b2Compress(this.chunksDone, flags, buf, bufPos); + this.chunkPos += 1; + // If current block is last in chunk (16 blocks), then compress chunks + if (this.chunkPos === 16 || isLast) { + let chunk = this.state; + this.state = this.IV.slice(); + // If not the last one, compress only when there are trailing zeros in chunk counter + // chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed. + // 1 (001) - leaf not finished (just push current chunk to stack) + // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back) + // 3 (011) - last leaf not finished + // 4 (100) - leafs finished at depth=1 and depth=2 + for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) { + if (!(last = this.stack.pop())) + break; + this.buffer32.set(last, 0); + this.buffer32.set(chunk, 8); + this.pos = this.blockLen; + this.b2Compress(0, this.flags | 4 /* Flags.PARENT */, this.buffer32, 0); + chunk = this.state; + this.state = this.IV.slice(); + } + this.chunksDone++; + this.chunkPos = 0; + this.stack.push(chunk); + } + this.pos = 0; + } + _cloneInto(to) { + to = super._cloneInto(to); + const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this; + to.state.set(state.slice()); + to.stack = stack.map((i) => Uint32Array.from(i)); + to.IV.set(IV); + to.flags = flags; + to.chunkPos = chunkPos; + to.chunksDone = chunksDone; + to.posOut = posOut; + to.chunkOut = chunkOut; + to.enableXOF = this.enableXOF; + to.bufferOut32.set(this.bufferOut32); + return to; + } + destroy() { + this.destroyed = true; + this.state.fill(0); + this.buffer32.fill(0); + this.IV.fill(0); + this.bufferOut32.fill(0); + for (let i of this.stack) + i.fill(0); + } + // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8) + b2CompressOut() { + const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this; + const { h, l } = fromBig(BigInt(this.chunkOut++)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(SIGMA, 0, buffer32, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], IV[0], IV[1], IV[2], IV[3], l, h, pos, flags); + out32[0] = v0 ^ v8; + out32[1] = v1 ^ v9; + out32[2] = v2 ^ v10; + out32[3] = v3 ^ v11; + out32[4] = v4 ^ v12; + out32[5] = v5 ^ v13; + out32[6] = v6 ^ v14; + out32[7] = v7 ^ v15; + out32[8] = s[0] ^ v8; + out32[9] = s[1] ^ v9; + out32[10] = s[2] ^ v10; + out32[11] = s[3] ^ v11; + out32[12] = s[4] ^ v12; + out32[13] = s[5] ^ v13; + out32[14] = s[6] ^ v14; + out32[15] = s[7] ^ v15; + this.posOut = 0; + } + finish() { + if (this.finished) + return; + this.finished = true; + // Padding + this.buffer.fill(0, this.pos); + // Process last chunk + let flags = this.flags | 8 /* Flags.ROOT */; + if (this.stack.length) { + flags |= 4 /* Flags.PARENT */; + this.compress(this.buffer32, 0, true); + this.chunksDone = 0; + this.pos = this.blockLen; + } + else { + flags |= (!this.chunkPos ? 1 /* Flags.CHUNK_START */ : 0) | 2 /* Flags.CHUNK_END */; + } + this.flags = flags; + this.b2CompressOut(); + } + writeInto(out) { + exists(this, false); + bytes(out); + this.finish(); + const { blockLen, bufferOut } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.b2CompressOut(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + if (!this.enableXOF) + throw new Error('XOF is not possible after digest call'); + return this.writeInto(out); + } + xof(bytes) { + number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + output(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.enableXOF = false; + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } +} +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +export const blake3 = /* @__PURE__ */ wrapXOFConstructorWithOpts((opts) => new BLAKE3(opts)); +//# sourceMappingURL=blake3.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake3.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake3.js.map new file mode 100644 index 0000000..50f489b --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/blake3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake3.js","sourceRoot":"","sources":["../src/blake3.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC7D,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAS,EAAE,EAAE,GAAG,EAAE,OAAO,EAAW,0BAA0B,EAAE,MAAM,YAAY,CAAC;AAe1F,MAAM,KAAK,GAAe,eAAe,CAAC,CAAC,GAAG,EAAE;IAC9C,MAAM,EAAE,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;IACnD,MAAM,OAAO,GAAG,CAAC,GAAa,EAAE,EAAE,CAChC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAA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AAC,CAAC;QACpB,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,OAAO,GAAG,CAAC;IACb,CAAC;IACD,MAAM;QACJ,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IACzD,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,0BAA0B,CAC9D,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,CAC3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/crypto.js b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/crypto.js new file mode 100644 index 0000000..8d499a0 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/crypto.js @@ -0,0 +1,2 @@ +export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; +//# sourceMappingURL=crypto.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/crypto.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/crypto.js.map new file mode 100644 index 0000000..4b4fd3d --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/crypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.js","sourceRoot":"","sources":["../src/crypto.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,MAAM,MAAM,GACjB,OAAO,UAAU,KAAK,QAAQ,IAAI,QAAQ,IAAI,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/cryptoNode.js b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/cryptoNode.js new file mode 100644 index 0000000..241f1da --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/cryptoNode.js @@ -0,0 +1,7 @@ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +// The file will throw on node.js 14 and earlier. +// @ts-ignore +import * as nc from 'node:crypto'; +export const crypto = nc && typeof nc === 'object' && 'webcrypto' in nc ? nc.webcrypto : undefined; +//# sourceMappingURL=cryptoNode.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/cryptoNode.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/cryptoNode.js.map new file mode 100644 index 0000000..f7ab75e --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/cryptoNode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cryptoNode.js","sourceRoot":"","sources":["../src/cryptoNode.ts"],"names":[],"mappings":"AAAA,oFAAoF;AACpF,4BAA4B;AAC5B,iDAAiD;AACjD,aAAa;AACb,OAAO,KAAK,EAAE,MAAM,aAAa,CAAC;AAClC,MAAM,CAAC,MAAM,MAAM,GACjB,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,WAAW,IAAI,EAAE,CAAC,CAAC,CAAE,EAAE,CAAC,SAAiB,CAAC,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/eskdf.js b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/eskdf.js new file mode 100644 index 0000000..13253eb --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/eskdf.js @@ -0,0 +1,155 @@ +import { bytes as assertBytes } from './_assert.js'; +import { hkdf } from './hkdf.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 as _pbkdf2 } from './pbkdf2.js'; +import { scrypt as _scrypt } from './scrypt.js'; +import { bytesToHex, createView, hexToBytes, toBytes } from './utils.js'; +// A tiny KDF for various applications like AES key-gen. +// Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure". +// Which is good enough: assume sha2-256 retained preimage resistance. +const SCRYPT_FACTOR = 2 ** 19; +const PBKDF2_FACTOR = 2 ** 17; +// Scrypt KDF +export function scrypt(password, salt) { + return _scrypt(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 }); +} +// PBKDF2-HMAC-SHA256 +export function pbkdf2(password, salt) { + return _pbkdf2(sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 }); +} +// Combines two 32-byte byte arrays +function xor32(a, b) { + assertBytes(a, 32); + assertBytes(b, 32); + const arr = new Uint8Array(32); + for (let i = 0; i < 32; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} +function strHasLength(str, min, max) { + return typeof str === 'string' && str.length >= min && str.length <= max; +} +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +export function deriveMainSeed(username, password) { + if (!strHasLength(username, 8, 255)) + throw new Error('invalid username'); + if (!strHasLength(password, 8, 255)) + throw new Error('invalid password'); + const scr = scrypt(password + '\u{1}', username + '\u{1}'); + const pbk = pbkdf2(password + '\u{2}', username + '\u{2}'); + const res = xor32(scr, pbk); + scr.fill(0); + pbk.fill(0); + return res; +} +/** + * Converts protocol & accountId pair to HKDF salt & info params. + */ +function getSaltInfo(protocol, accountId = 0) { + // Note that length here also repeats two lines below + // We do an additional length check here to reduce the scope of DoS attacks + if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) { + throw new Error('invalid protocol'); + } + // Allow string account ids for some protocols + const allowsStr = /^password\d{0,3}|ssh|tor|file$/.test(protocol); + let salt; // Extract salt. Default is undefined. + if (typeof accountId === 'string') { + if (!allowsStr) + throw new Error('accountId must be a number'); + if (!strHasLength(accountId, 1, 255)) + throw new Error('accountId must be valid string'); + salt = toBytes(accountId); + } + else if (Number.isSafeInteger(accountId)) { + if (accountId < 0 || accountId > 2 ** 32 - 1) + throw new Error('invalid accountId'); + // Convert to Big Endian Uint32 + salt = new Uint8Array(4); + createView(salt).setUint32(0, accountId, false); + } + else { + throw new Error(`accountId must be a number${allowsStr ? ' or string' : ''}`); + } + const info = toBytes(protocol); + return { salt, info }; +} +function countBytes(num) { + if (typeof num !== 'bigint' || num <= BigInt(128)) + throw new Error('invalid number'); + return Math.ceil(num.toString(2).length / 8); +} +/** + * Parses keyLength and modulus options to extract length of result key. + * If modulus is used, adds 64 bits to it as per FIPS 186 B.4.1 to combat modulo bias. + */ +function getKeyLength(options) { + if (!options || typeof options !== 'object') + return 32; + const hasLen = 'keyLength' in options; + const hasMod = 'modulus' in options; + if (hasLen && hasMod) + throw new Error('cannot combine keyLength and modulus options'); + if (!hasLen && !hasMod) + throw new Error('must have either keyLength or modulus option'); + // FIPS 186 B.4.1 requires at least 64 more bits + const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength; + if (!(typeof l === 'number' && l >= 16 && l <= 8192)) + throw new Error('invalid keyLength'); + return l; +} +/** + * Converts key to bigint and divides it by modulus. Big Endian. + * Implements FIPS 186 B.4.1, which removes 0 and modulo bias from output. + */ +function modReduceKey(key, modulus) { + const _1 = BigInt(1); + const num = BigInt('0x' + bytesToHex(key)); // check for ui8a, then bytesToNumber() + const res = (num % (modulus - _1)) + _1; // Remove 0 from output + if (res < _1) + throw new Error('expected positive number'); // Guard against bad values + const len = key.length - 8; // FIPS requires 64 more bits = 8 bytes + const hex = res.toString(16).padStart(len * 2, '0'); // numberToHex() + const bytes = hexToBytes(hex); + if (bytes.length !== len) + throw new Error('invalid length of result key'); + return bytes; +} +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +export async function eskdf(username, password) { + // We are using closure + object instead of class because + // we want to make `seed` non-accessible for any external function. + let seed = deriveMainSeed(username, password); + function deriveCK(protocol, accountId = 0, options) { + assertBytes(seed, 32); + const { salt, info } = getSaltInfo(protocol, accountId); // validate protocol & accountId + const keyLength = getKeyLength(options); // validate options + const key = hkdf(sha256, seed, salt, info, keyLength); + // Modulus has already been validated + return options && 'modulus' in options ? modReduceKey(key, options.modulus) : key; + } + function expire() { + if (seed) + seed.fill(1); + seed = undefined; + } + // prettier-ignore + const fingerprint = Array.from(deriveCK('fingerprint', 0)) + .slice(0, 6) + .map((char) => char.toString(16).padStart(2, '0').toUpperCase()) + .join(':'); + return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint }); +} +//# sourceMappingURL=eskdf.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/eskdf.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/eskdf.js.map new file mode 100644 index 0000000..f53eebe --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/eskdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eskdf.js","sourceRoot":"","sources":["../src/eskdf.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,IAAI,WAAW,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,MAAM,IAAI,OAAO,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,MAAM,IAAI,OAAO,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAEzE,wDAAwD;AACxD,gFAAgF;AAChF,sEAAsE;AAEtE,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,CAAC;AAC9B,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,CAAC;AAE9B,aAAa;AACb,MAAM,UAAU,MAAM,CAAC,QAAgB,EAAE,IAAY;IACnD,OAAO,OAAO,CAAC,QAAQ,EAAE,IAAI,EAAE,EAAE,CAAC,EAAE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,CAAC,QAAgB,EAAE,YAAuB,CAAC,EAAE,OAAiB;QAC7E,WAAW,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QACtB,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,WAAW,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC,CAAC,gCAAgC;QACzF,MAAM,SAAS,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC,mBAAmB;QAC5D,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,EAAE,IAAK,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC;QACvD,qCAAqC;QACrC,OAAO,OAAO,IAAI,SAAS,IAAI,OAAO,CAAC,CAAC,CAAC,YAAY,CAAC,GAAG,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;IACpF,CAAC;IACD,SAAS,MAAM;QACb,IAAI,IAAI;YAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACvB,IAAI,GAAG,SAAS,CAAC;IACnB,CAAC;IACD,kBAAkB;IAClB,MAAM,WAAW,GAAG,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC;SACvD,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;SACX,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC;SAC/D,IAAI,CAAC,GAAG,CAAC,CAAC;IACb,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC,CAAC;AAC1E,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/hkdf.js b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/hkdf.js new file mode 100644 index 0000000..8fbdac8 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/hkdf.js @@ -0,0 +1,72 @@ +import { hash as assertHash, number as assertNumber } from './_assert.js'; +import { toBytes } from './utils.js'; +import { hmac } from './hmac.js'; +// HKDF (RFC 5869) +// https://soatok.blog/2021/11/17/understanding-hkdf/ +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +export function extract(hash, ikm, salt) { + assertHash(hash); + // NOTE: some libraries treat zero-length array as 'not provided'; + // we don't, since we have undefined as 'not provided' + // https://github.com/RustCrypto/KDFs/issues/15 + if (salt === undefined) + salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros + return hmac(hash, toBytes(salt), toBytes(ikm)); +} +// HKDF-Expand(PRK, info, L) -> OKM +const HKDF_COUNTER = /* @__PURE__ */ new Uint8Array([0]); +const EMPTY_BUFFER = /* @__PURE__ */ new Uint8Array(); +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +export function expand(hash, prk, info, length = 32) { + assertHash(hash); + assertNumber(length); + if (length > 255 * hash.outputLen) + throw new Error('Length should be <= 255*HashLen'); + const blocks = Math.ceil(length / hash.outputLen); + if (info === undefined) + info = EMPTY_BUFFER; + // first L(ength) octets of T + const okm = new Uint8Array(blocks * hash.outputLen); + // Re-use HMAC instance between blocks + const HMAC = hmac.create(hash, prk); + const HMACTmp = HMAC._cloneInto(); + const T = new Uint8Array(HMAC.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + // T(0) = empty string (zero length) + // T(N) = HMAC-Hash(PRK, T(N-1) | info | N) + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T) + .update(info) + .update(HKDF_COUNTER) + .digestInto(T); + okm.set(T, hash.outputLen * counter); + HMAC._cloneInto(HMACTmp); + } + HMAC.destroy(); + HMACTmp.destroy(); + T.fill(0); + HKDF_COUNTER.fill(0); + return okm.slice(0, length); +} +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +export const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length); +//# sourceMappingURL=hkdf.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/hkdf.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/hkdf.js.map new file mode 100644 index 0000000..868bdb5 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/hkdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hkdf.js","sourceRoot":"","sources":["../src/hkdf.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,IAAI,UAAU,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AAC1E,OAAO,EAAgB,OAAO,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,kBAAkB;AAClB,qDAAqD;AAErD;;;;;;;GAOG;AACH,MAAM,UAAU,OAAO,CAAC,IAAW,EAAE,GAAU,EAAE,IAAY;IAC3D,UAAU,CAAC,IAAI,CAAC,CAAC;IACjB,kEAAkE;IAClE,sDAAsD;IACtD,+CAA+C;IAC/C,IAAI,IAAI,KAAK,SAAS;QAAE,IAAI,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,0DAA0D;IACzH,OAAO,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;AACjD,CAAC;AAED,mCAAmC;AACnC,MAAM,YAAY,GAAG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AC,CAAC;QACjB,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,CAAC;QACrC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;KAC1B;IACD,IAAI,CAAC,OAAO,EAAE,CAAC;IACf,OAAO,CAAC,OAAO,EAAE,CAAC;IAClB,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACV,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACrB,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;AAC9B,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG,CAClB,IAAW,EACX,GAAU,EACV,IAAuB,EACvB,IAAuB,EACvB,MAAc,EACd,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/hmac.js b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/hmac.js new file mode 100644 index 0000000..520f776 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/hmac.js @@ -0,0 +1,77 @@ +import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js'; +import { Hash, toBytes } from './utils.js'; +// HMAC (RFC 2104) +export class HMAC extends Hash { + constructor(hash, _key) { + super(); + this.finished = false; + this.destroyed = false; + assertHash(hash); + const key = toBytes(_key); + this.iHash = hash.create(); + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash.create(); + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + assertExists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + assertExists(this); + assertBytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +export const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); +hmac.create = (hash, key) => new HMAC(hash, key); +//# sourceMappingURL=hmac.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/hmac.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/hmac.js.map new file mode 100644 index 0000000..e04539d --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/hmac.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hmac.js","sourceRoot":"","sources":["../src/hmac.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,IAAI,UAAU,EAAE,KAAK,IAAI,WAAW,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AAChG,OAAO,E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,IAAI,CAAC;QACxE,EAAE,GAAG,EAAU,CAAC;QAChB,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACvB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACvB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,EAAE,CAAC,KAAK,GAAG,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;QACtC,EAAE,CAAC,KAAK,GAAG,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;QACtC,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;QACrB,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;IACvB,CAAC;CACF;AAED;;;;;GAKG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG,CAAC,IAAW,EAAE,GAAU,EAAE,OAAc,EAAc,EAAE,CAC1E,IAAI,IAAI,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC;AACpD,IAAI,CAAC,MAAM,GAAG,CAAC,IAAW,EAAE,GAAU,EAAE,EAAE,CAAC,IAAI,IAAI,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/index.js b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/index.js new file mode 100644 index 0000000..2299d7f --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/index.js @@ -0,0 +1,3 @@ +"use strict"; +throw new Error('noble-hashes have no entry-point: consult README for usage'); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/index.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/index.js.map new file mode 100644 index 0000000..90172aa --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA,MAAM,IAAI,KAAK,CAAC,4DAA4D,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/package.json b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/package.json new file mode 100644 index 0000000..f42e46b --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/package.json @@ -0,0 +1,10 @@ +{ + "type": "module", + "sideEffects": false, + "browser": { + "node:crypto": false + }, + "node": { + "./crypto": "./esm/cryptoNode.js" + } +} diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/pbkdf2.js b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/pbkdf2.js new file mode 100644 index 0000000..3f0c11f --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/pbkdf2.js @@ -0,0 +1,86 @@ +import { hash as assertHash, number as assertNumber } from './_assert.js'; +import { hmac } from './hmac.js'; +import { createView, toBytes, checkOpts, asyncLoop } from './utils.js'; +// Common prologue and epilogue for sync/async functions +function pbkdf2Init(hash, _password, _salt, _opts) { + assertHash(hash); + const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + assertNumber(c); + assertNumber(dkLen); + assertNumber(asyncTick); + if (c < 1) + throw new Error('PBKDF2: iterations (c) should be >= 1'); + const password = toBytes(_password); + const salt = toBytes(_salt); + // DK = PBKDF2(PRF, Password, Salt, c, dkLen); + const DK = new Uint8Array(dkLen); + // U1 = PRF(Password, Salt + INT_32_BE(i)) + const PRF = hmac.create(hash, password); + const PRFSalt = PRF._cloneInto().update(salt); + return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; +} +function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) + prfW.destroy(); + u.fill(0); + return DK; +} +/** + * PBKDF2-HMAC: RFC 2898 key derivation function + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated + * @param salt - cryptographic salt + * @param opts - {c, dkLen} where c is work factor and dkLen is output message size + */ +export function pbkdf2(hash, password, salt, opts) { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + for (let ui = 1; ui < c; ui++) { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +export async function pbkdf2Async(hash, password, salt, opts) { + const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + await asyncLoop(c - 1, asyncTick, () => { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + }); + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +//# sourceMappingURL=pbkdf2.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/pbkdf2.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/pbkdf2.js.map new file mode 100644 index 0000000..b404934 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/pbkdf2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pbkdf2.js","sourceRoot":"","sources":["../src/pbkdf2.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,IAAI,UAAU,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AAC1E,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAsB,UAAU,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAQ3F,wDAAwD;AACxD,SAAS,UAAU,CAAC,IAAW,EAAE,SAAgB,EAAE,KAAY,EAAE,KAAgB;IAC/E,UAAU,CAAC,IAAI,CAAC,CAAC;IACjB,MAAM,IAAI,GAAG,SAAS,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IAC5D,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;IACrC,YAAY,CAAC,CAAC,CAAC,CAAC;IAChB,YAAY,CAAC,KAAK,CAAC,CAAC;IACpB,YAAY,CAAC,SAAS,CAAC,CAAC;IACxB,IAAI,CAAC,GAAG,CAAC;QA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G,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,EAAE;gBAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;QACpD,CAAC,CAAC,CAAC;KACJ;IACD,OAAO,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AACjD,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/ripemd160.js b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/ripemd160.js new file mode 100644 index 0000000..1e23958 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/ripemd160.js @@ -0,0 +1,104 @@ +import { SHA2 } from './_sha2.js'; +import { wrapConstructor } from './utils.js'; +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = /* @__PURE__ */ Uint8Array.from({ length: 16 }, (_, i) => i); +const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) + for (let j of [idxL, idxR]) + j.push(j[i].map((k) => Rho[k])); +const shifts = /* @__PURE__ */ [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => new Uint8Array(i)); +const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +const Kl = /* @__PURE__ */ new Uint32Array([ + 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e, +]); +const Kr = /* @__PURE__ */ new Uint32Array([ + 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000, +]); +// The rotate left (circular left shift) operation for uint32 +const rotl = (word, shift) => (word << shift) | (word >>> (32 - shift)); +// It's called f() in spec. +function f(group, x, y, z) { + if (group === 0) + return x ^ y ^ z; + else if (group === 1) + return (x & y) | (~x & z); + else if (group === 2) + return (x | ~y) ^ z; + else if (group === 3) + return (x & z) | (y & ~z); + else + return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const BUF = /* @__PURE__ */ new Uint32Array(16); +export class RIPEMD160 extends SHA2 { + constructor() { + super(64, 20, 8, true); + this.h0 = 0x67452301 | 0; + this.h1 = 0xefcdab89 | 0; + this.h2 = 0x98badcfe | 0; + this.h3 = 0x10325476 | 0; + this.h4 = 0xc3d2e1f0 | 0; + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + BUF[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0); + } + roundClean() { + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +export const ripemd160 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160()); +//# sourceMappingURL=ripemd160.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/ripemd160.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/ripemd160.js.map new file mode 100644 index 0000000..7964756 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/ripemd160.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ripemd160.js","sourceRoot":"","sources":["../src/ripemd160.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C,0DAA0D;AAC1D,6EAA6E;AAC7E,MAAM,GAAG,GAAG,eAAe,CAAC,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAA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AC,GAAG,EAAE,CAAC,IAAI,SAAS,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/scrypt.js b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/scrypt.js new file mode 100644 index 0000000..37012f5 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/scrypt.js @@ -0,0 +1,218 @@ +import { number as assertNumber } from './_assert.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 } from './pbkdf2.js'; +import { asyncLoop, checkOpts, u32 } from './utils.js'; +// RFC 7914 Scrypt KDF +// Left rotate for uint32 +const rotl = (a, b) => (a << b) | (a >>> (32 - b)); +// The main Scrypt loop: uses Salsa extensively. +// Six versions of the function were tried, this is the fastest one. +// prettier-ignore +function XorAndSalsa(prev, pi, input, ii, out, oi) { + // Based on https://cr.yp.to/salsa20.html + // Xor blocks + let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; + let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; + let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; + let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; + let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; + let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; + let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; + let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; + // Save state to temporary variables (salsa) + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; + // Main loop (salsa) + for (let i = 0; i < 8; i += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); + x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); + x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); + x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); + x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); + x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); + x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); + x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); + x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); + x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); + x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); + x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); + x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); + x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); + x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); + x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); + x15 ^= rotl(x14 + x13 | 0, 18); + } + // Write output (salsa) + out[oi++] = (y00 + x00) | 0; + out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; + out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; + out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; + out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; + out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; + out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; + out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; + out[oi++] = (y15 + x15) | 0; +} +function BlockMix(input, ii, out, oi, r) { + // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks) + let head = oi + 0; + let tail = oi + 16 * r; + for (let i = 0; i < 16; i++) + out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1] + for (let i = 0; i < r; i++, head += 16, ii += 16) { + // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1 + XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1]) + if (i > 0) + tail += 16; // First iteration overwrites tmp value in tail + XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i]) + } +} +// Common prologue and epilogue for sync/async functions +function scryptInit(password, salt, _opts) { + // Maxmem - 1GB+1KB by default + const opts = checkOpts({ + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024, + }, _opts); + const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; + assertNumber(N); + assertNumber(r); + assertNumber(p); + assertNumber(dkLen); + assertNumber(asyncTick); + assertNumber(maxmem); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + const blockSize = 128 * r; + const blockSize32 = blockSize / 4; + if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) { + // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function + // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future. + throw new Error('Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32'); + } + if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) { + throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)'); + } + if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) { + throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32'); + } + const memUsed = blockSize * (N + p); + if (memUsed > maxmem) { + throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`); + } + // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor) + // Since it has only one iteration there is no reason to use async variant + const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p }); + const B32 = u32(B); + // Re-used between parallel iterations. Array(iterations) of B + const V = u32(new Uint8Array(blockSize * N)); + const tmp = u32(new Uint8Array(blockSize)); + let blockMixCb = () => { }; + if (onProgress) { + const totalBlockMix = 2 * N * p; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1); + let blockMixCnt = 0; + blockMixCb = () => { + blockMixCnt++; + if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) + onProgress(blockMixCnt / totalBlockMix); + }; + } + return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick }; +} +function scryptOutput(password, dkLen, B, V, tmp) { + const res = pbkdf2(sha256, password, B, { c: 1, dkLen }); + B.fill(0); + V.fill(0); + tmp.fill(0); + return res; +} +/** + * Scrypt KDF from RFC 7914. + * @param password - pass + * @param salt - salt + * @param opts - parameters + * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + * @returns Derived key + */ +export function scrypt(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + for (let i = 0, pos = 0; i < N - 1; i++) { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + } + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + for (let i = 0; i < N; i++) { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + } + } + return scryptOutput(password, dkLen, B, V, tmp); +} +/** + * Scrypt KDF from RFC 7914. + */ +export async function scryptAsync(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + let pos = 0; + await asyncLoop(N - 1, asyncTick, () => { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + }); + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + await asyncLoop(N, asyncTick, () => { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + }); + } + return scryptOutput(password, dkLen, B, V, tmp); +} +//# sourceMappingURL=scrypt.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/scrypt.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/scrypt.js.map new file mode 100644 index 0000000..0fa6c1f --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/scrypt.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scrypt.js","sourceRoot":"","sources":["../src/scrypt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,SAAS,EAAE,SAAS,EAAS,GAAG,EAAE,MAAM,YAAY,CAAC;AAE9D,sBAAsB;AAEtB,yBAAyB;AACzB,MAAM,IAAI,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;AAEnE,gDAAgD;AAChD,oEAAoE;AACpE,kBAAkB;AAClB,SAAS,WAAW,CAClB,IAAiB,EACjB,EAAU,EACV,KAAkB,EAClB,EAAU,EACV,GAAgB,EAChB,EAAU;IAEV,yCAAyC;IACzC,aAAa;IACb,IAAI,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;IACnE,IAAI,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;IACnE,IAAI,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAA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AAE,CAAC;QACf,CAAC,CAAC,CAAC;QACH,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,WAAW,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,uBAAuB;QACvE,UAAU,EAAE,CAAC;QACb,MAAM,SAAS,CAAC,CAAC,EAAE,SAAS,EAAE,GAAG,EAAE;YACjC,kDAAkD;YAClD,MAAM,CAAC,GAAG,GAAG,CAAC,EAAE,GAAG,WAAW,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,gCAAgC;YAC1E,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,WAAW,EAAE,CAAC,EAAE;gBAAE,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,WAAW,GAAG,CAAC,CAAC,CAAC,CAAC,iBAAiB;YACtG,QAAQ,CAAC,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,yBAAyB;YACvD,UAAU,EAAE,CAAC;QACf,CAAC,CAAC,CAAC;KACJ;IACD,OAAO,YAAY,CAAC,QAAQ,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;AAClD,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha1.js b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha1.js new file mode 100644 index 0000000..563bff5 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha1.js @@ -0,0 +1,87 @@ +import { SHA2 } from './_sha2.js'; +import { wrapConstructor } from './utils.js'; +// SHA1 was cryptographically broken. +// It is still widely used in legacy apps. Don't use it for a new protocol. +// RFC 3174 +const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +// Initial state +const IV = /* @__PURE__ */ new Uint32Array([ + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0, +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = /* @__PURE__ */ new Uint32Array(80); +class SHA1 extends SHA2 { + constructor() { + super(64, 20, 8, false); + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + } + get() { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + set(A, B, C, D, E) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } + else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } + else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } + else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +export const sha1 = /* @__PURE__ */ wrapConstructor(() => new SHA1()); +//# sourceMappingURL=sha1.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha1.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha1.js.map new file mode 100644 index 0000000..55249de --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha1.js","sourceRoot":"","sources":["../src/sha1.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C,qCAAqC;AACrC,2EAA2E;AAE3E,WAAW;AACX,MAAM,IAAI,GAAG,CAAC,IAAY,EAAE,KAAa,EAAE,EAAE,CAAC,CAAC,IAAI,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,KAAK,CAAC,EAAE,GAAG,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;AAChG,oBAAoB;AACpB,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AACpE,oDAAoD;AACpD,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAE7E,gBAAgB;AAChB,MAAM,EAAE,GAAG,eAAe,CAAC,IAAI,WAAW,CAAC;IACzC,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;CAC3D,CAAC,CAAC;AAEH,4DAA4D;AAC5D,mDAAmD;AACnD,MAAM,MAAM,GAAG,eAAe,CAAC,IAAI,WAAW,CAAC,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CAAC;YACN,CAAC,GAAG,CAAC,CAAC;YACN,CAAC,GAAG,IAAI,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YAChB,CAAC,GAAG,CAAC,CAAC;YACN,CAAC,GAAG,CAAC,CAAC;SACP;QACD,qDAAqD;QACrD,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC1B,CAAC;IACS,UAAU;QAClB,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACjB,CAAC;IACD,OAAO;QACL,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QACxB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACtB,CAAC;CACF;AAED,MAAM,CAAC,MAAM,IAAI,GAAG,eAAe,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha256.js b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha256.js new file mode 100644 index 0000000..e92203c --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha256.js @@ -0,0 +1,126 @@ +import { SHA2 } from './_sha2.js'; +import { rotr, wrapConstructor } from './utils.js'; +// SHA2-256 need to try 2^128 hashes to execute birthday attack. +// BTC network is doing 2^67 hashes/sec as per early 2023. +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = /* @__PURE__ */ new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); +// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): +// prettier-ignore +const IV = /* @__PURE__ */ new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = /* @__PURE__ */ new Uint32Array(64); +class SHA256 extends SHA2 { + constructor() { + super(64, 32, 8, false); + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + this.F = IV[5] | 0; + this.G = IV[6] | 0; + this.H = IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + constructor() { + super(); + this.A = 0xc1059ed8 | 0; + this.B = 0x367cd507 | 0; + this.C = 0x3070dd17 | 0; + this.D = 0xf70e5939 | 0; + this.E = 0xffc00b31 | 0; + this.F = 0x68581511 | 0; + this.G = 0x64f98fa7 | 0; + this.H = 0xbefa4fa4 | 0; + this.outputLen = 28; + } +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +export const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); +export const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224()); +//# sourceMappingURL=sha256.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha256.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha256.js.map new file mode 100644 index 0000000..0236fa8 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha256.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha256.js","sourceRoot":"","sources":["../src/sha256.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAEnD,gEAAgE;AAChE,0DAA0D;AAE1D,oBAAoB;AACpB,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AACpE,oDAAoD;AACpD,MAA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AAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QAGjB,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;IACtB,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC;AAC1E,MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha3-addons.js b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha3-addons.js new file mode 100644 index 0000000..449b3a3 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha3-addons.js @@ -0,0 +1,347 @@ +import { number as assertNumber } from './_assert.js'; +import { toBytes, wrapConstructorWithOpts, u32 } from './utils.js'; +import { Keccak } from './sha3.js'; +// cSHAKE && KMAC (NIST SP800-185) +function leftEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.unshift(res.length); + return new Uint8Array(res); +} +function rightEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +function chooseLen(opts, outputLen) { + return opts.dkLen === undefined ? outputLen : opts.dkLen; +} +const toBytesOptional = (buf) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); +// NOTE: second modulo is necessary since we don't need to add padding if current element takes whole block +const getPadding = (len, block) => new Uint8Array((block - (len % block)) % block); +// Personalization +function cshakePers(hash, opts = {}) { + if (!opts || (!opts.personalization && !opts.NISTfn)) + return hash; + // Encode and pad inplace to avoid unneccesary memory copies/slices (so we don't need to zero them later) + // bytepad(encode_string(N) || encode_string(S), 168) + const blockLenBytes = leftEncode(hash.blockLen); + const fn = toBytesOptional(opts.NISTfn); + const fnLen = leftEncode(8 * fn.length); // length in bits + const pers = toBytesOptional(opts.personalization); + const persLen = leftEncode(8 * pers.length); // length in bits + if (!fn.length && !pers.length) + return hash; + hash.suffix = 0x04; + hash.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers); + let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length; + hash.update(getPadding(totalLen, hash.blockLen)); + return hash; +} +const gencShake = (suffix, blockLen, outputLen) => wrapConstructorWithOpts((opts = {}) => cshakePers(new Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts)); +export const cshake128 = /* @__PURE__ */ (() => gencShake(0x1f, 168, 128 / 8))(); +export const cshake256 = /* @__PURE__ */ (() => gencShake(0x1f, 136, 256 / 8))(); +class KMAC extends Keccak { + constructor(blockLen, outputLen, enableXOF, key, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'KMAC', personalization: opts.personalization }); + key = toBytes(key); + // 1. newX = bytepad(encode_string(K), 168) || X || right_encode(L). + const blockLenBytes = leftEncode(this.blockLen); + const keyLen = leftEncode(8 * key.length); + this.update(blockLenBytes).update(keyLen).update(key); + const totalLen = blockLenBytes.length + keyLen.length + key.length; + this.update(getPadding(totalLen, this.blockLen)); + } + finish() { + if (!this.finished) + this.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + // Force "to" to be instance of KMAC instead of Sha3. + if (!to) { + to = Object.create(Object.getPrototypeOf(this), {}); + to.state = this.state.slice(); + to.blockLen = this.blockLen; + to.state32 = u32(to.state); + } + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genKmac(blockLen, outputLen, xof = false) { + const kmac = (key, message, opts) => kmac.create(key, opts).update(message).digest(); + kmac.create = (key, opts = {}) => new KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts); + return kmac; +} +export const kmac128 = /* @__PURE__ */ (() => genKmac(168, 128 / 8))(); +export const kmac256 = /* @__PURE__ */ (() => genKmac(136, 256 / 8))(); +export const kmac128xof = /* @__PURE__ */ (() => genKmac(168, 128 / 8, true))(); +export const kmac256xof = /* @__PURE__ */ (() => genKmac(136, 256 / 8, true))(); +// TupleHash +// Usage: tuple(['ab', 'cd']) != tuple(['a', 'bcd']) +class TupleHash extends Keccak { + constructor(blockLen, outputLen, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'TupleHash', personalization: opts.personalization }); + // Change update after cshake processed + this.update = (data) => { + data = toBytes(data); + super.update(leftEncode(data.length * 8)); + super.update(data); + return this; + }; + } + finish() { + if (!this.finished) + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new TupleHash(this.blockLen, this.outputLen, this.enableXOF)); + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genTuple(blockLen, outputLen, xof = false) { + const tuple = (messages, opts) => { + const h = tuple.create(opts); + for (const msg of messages) + h.update(msg); + return h.digest(); + }; + tuple.create = (opts = {}) => new TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts); + return tuple; +} +export const tuplehash128 = /* @__PURE__ */ (() => genTuple(168, 128 / 8))(); +export const tuplehash256 = /* @__PURE__ */ (() => genTuple(136, 256 / 8))(); +export const tuplehash128xof = /* @__PURE__ */ (() => genTuple(168, 128 / 8, true))(); +export const tuplehash256xof = /* @__PURE__ */ (() => genTuple(136, 256 / 8, true))(); +class ParallelHash extends Keccak { + constructor(blockLen, outputLen, leafCons, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + this.leafCons = leafCons; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + cshakePers(this, { NISTfn: 'ParallelHash', personalization: opts.personalization }); + let { blockLen: B } = opts; + B || (B = 8); + assertNumber(B); + this.chunkLen = B; + super.update(leftEncode(B)); + // Change update after cshake processed + this.update = (data) => { + data = toBytes(data); + const { chunkLen, leafCons } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen || !this.leafHash) { + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + this.leafHash = leafCons(); + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + this.leafHash.update(data.subarray(pos, pos + take)); + this.chunkPos += take; + pos += take; + } + return this; + }; + } + finish() { + if (this.finished) + return; + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + super.update(rightEncode(this.chunksDone)); + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF)); + if (this.leafHash) + to.leafHash = this.leafHash._cloneInto(to.leafHash); + to.chunkPos = this.chunkPos; + to.chunkLen = this.chunkLen; + to.chunksDone = this.chunksDone; + return super._cloneInto(to); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + } + clone() { + return this._cloneInto(); + } +} +function genPrl(blockLen, outputLen, leaf, xof = false) { + const parallel = (message, opts) => parallel.create(opts).update(message).digest(); + parallel.create = (opts = {}) => new ParallelHash(blockLen, chooseLen(opts, outputLen), () => leaf.create({ dkLen: 2 * outputLen }), xof, opts); + return parallel; +} +export const parallelhash128 = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128))(); +export const parallelhash256 = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256))(); +export const parallelhash128xof = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128, true))(); +export const parallelhash256xof = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256, true))(); +// Kangaroo +// Same as NIST rightEncode, but returns [0] for zero string +function rightEncodeK12(n) { + const res = []; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +const EMPTY = new Uint8Array([]); +class KangarooTwelve extends Keccak { + constructor(blockLen, leafLen, outputLen, rounds, opts) { + super(blockLen, 0x07, outputLen, true, rounds); + this.leafLen = leafLen; + this.chunkLen = 8192; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + const { personalization } = opts; + this.personalization = toBytesOptional(personalization); + } + update(data) { + data = toBytes(data); + const { chunkLen, blockLen, leafLen, rounds } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen) { + if (this.leafHash) + super.update(this.leafHash.digest()); + else { + this.suffix = 0x06; // Its safe to change suffix here since its used only in digest() + super.update(new Uint8Array([3, 0, 0, 0, 0, 0, 0, 0])); + } + this.leafHash = new Keccak(blockLen, 0x0b, leafLen, false, rounds); + this.chunksDone++; + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + const chunk = data.subarray(pos, pos + take); + if (this.leafHash) + this.leafHash.update(chunk); + else + super.update(chunk); + this.chunkPos += take; + pos += take; + } + return this; + } + finish() { + if (this.finished) + return; + const { personalization } = this; + this.update(personalization).update(rightEncodeK12(personalization.length)); + // Leaf hash + if (this.leafHash) { + super.update(this.leafHash.digest()); + super.update(rightEncodeK12(this.chunksDone)); + super.update(new Uint8Array([0xff, 0xff])); + } + super.finish.call(this); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + // We cannot zero personalization buffer since it is user provided and we don't want to mutate user input + this.personalization = EMPTY; + } + _cloneInto(to) { + const { blockLen, leafLen, leafHash, outputLen, rounds } = this; + to || (to = new KangarooTwelve(blockLen, leafLen, outputLen, rounds, {})); + super._cloneInto(to); + if (leafHash) + to.leafHash = leafHash._cloneInto(to.leafHash); + to.personalization.set(this.personalization); + to.leafLen = this.leafLen; + to.chunkPos = this.chunkPos; + to.chunksDone = this.chunksDone; + return to; + } + clone() { + return this._cloneInto(); + } +} +// Default to 32 bytes, so it can be used without opts +export const k12 = /* @__PURE__ */ (() => wrapConstructorWithOpts((opts = {}) => new KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts)))(); +// MarsupilamiFourteen +export const m14 = /* @__PURE__ */ (() => wrapConstructorWithOpts((opts = {}) => new KangarooTwelve(136, 64, chooseLen(opts, 64), 14, opts)))(); +// https://keccak.team/files/CSF-0.1.pdf +// + https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG +class KeccakPRG extends Keccak { + constructor(capacity) { + assertNumber(capacity); + // Rho should be full bytes + if (capacity < 0 || capacity > 1600 - 10 || (1600 - capacity - 2) % 8) + throw new Error('KeccakPRG: Invalid capacity'); + // blockLen = rho in bytes + super((1600 - capacity - 2) / 8, 0, 0, true); + this.rate = 1600 - capacity; + this.posOut = Math.floor((this.rate + 7) / 8); + } + keccak() { + // Duplex padding + this.state[this.pos] ^= 0x01; + this.state[this.blockLen] ^= 0x02; // Rho is full bytes + super.keccak(); + this.pos = 0; + this.posOut = 0; + } + update(data) { + super.update(data); + this.posOut = this.blockLen; + return this; + } + feed(data) { + return this.update(data); + } + finish() { } + digestInto(_out) { + throw new Error('KeccakPRG: digest is not allowed, please use .fetch instead.'); + } + fetch(bytes) { + return this.xof(bytes); + } + // Ensure irreversibility (even if state leaked previous outputs cannot be computed) + forget() { + if (this.rate < 1600 / 2 + 1) + throw new Error('KeccakPRG: rate too low to use forget'); + this.keccak(); + for (let i = 0; i < this.blockLen; i++) + this.state[i] = 0; + this.pos = this.blockLen; + this.keccak(); + this.posOut = this.blockLen; + } + _cloneInto(to) { + const { rate } = this; + to || (to = new KeccakPRG(1600 - rate)); + super._cloneInto(to); + to.rate = rate; + return to; + } + clone() { + return this._cloneInto(); + } +} +export const keccakprg = (capacity = 254) => new KeccakPRG(capacity); +//# sourceMappingURL=sha3-addons.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha3-addons.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha3-addons.js.map new file mode 100644 index 0000000..7600a9a --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha3-addons.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3-addons.js","sourceRoot":"","sources":["../src/sha3-addons.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAS,OAAO,EAAE,uBAAuB,EAAE,GAAG,EAAiB,MAAM,YAAY,CAAC;AACzF,OAAO,EAAE,MAAM,EAAa,MAAM,WAAW,CAAC;AAC9C,kCAAkC;AAClC,SAAS,UAAU,CAAC,CAAS;IAC3B,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IACvB,CAAC,KAAK,CAAC,CAAC;IACR,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC;QAAE,GAAG,CAAC,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IAC7C,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACxB,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,WAAW,CAAC,CAAS;IAC5B,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IACvB,CAAC,KAAK,CAAC,CAAC;IACR,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC;QAAE,GAAG,CAAC,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IAC7C,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACrB,OAAO,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QACvF,IAAI,CAAC,MAAM,EAAE,CAAC;QACd,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC,EAAE;YAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QAC1D,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC;QACzB,IAAI,CAAC,MAAM,EAAE,CAAC;QACd,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC;IAC9B,CAAC;IACD,UAAU,CAAC,EAAc;QACvB,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;QACtB,EAAE,KAAF,EAAE,GAAK,IAAI,SAAS,CAAC,IAAI,GAAG,IAAI,CAAC,EAAC;QAClC,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;QACrB,EAAE,CAAC,IAAI,GAAG,IAAI,CAAC;QACf,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,KAAK;QACH,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC;IAC3B,CAAC;CACF;AAED,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,QAAQ,GAAG,GAAG,EAAE,EAAE,CAAC,IAAI,SAAS,CAAC,QAAQ,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha3.js b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha3.js new file mode 100644 index 0000000..0879d36 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha3.js @@ -0,0 +1,208 @@ +import { bytes, exists, number, output } from './_assert.js'; +import { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.js'; +import { Hash, u32, toBytes, wrapConstructor, wrapXOFConstructorWithOpts, } from './utils.js'; +// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. +// It's called a sponge function. +// Various per round constants calculations +const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []]; +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); +const _2n = /* @__PURE__ */ BigInt(2); +const _7n = /* @__PURE__ */ BigInt(7); +const _256n = /* @__PURE__ */ BigInt(256); +const _0x71n = /* @__PURE__ */ BigInt(0x71); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) + t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); +// Left rotation (without 0, 32, 64) +const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s)); +const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s)); +// Same as keccakf1600, but allows to skip some rounds +export function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) + B[x] = s[y + x]; + for (let x = 0; x < 10; x++) + s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} +export class Keccak extends Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + // Can be passed from user as dkLen + number(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + update(data) { + exists(this); + const { blockLen, state } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + writeInto(out) { + exists(this, false); + bytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) + throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes) { + number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + output(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} +const gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); +export const sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +export const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8); +export const sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8); +export const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8); +export const keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +export const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8); +export const keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8); +export const keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8); +const genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)); +export const shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8); +export const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8); +//# sourceMappingURL=sha3.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha3.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha3.js.map new file mode 100644 index 0000000..32d5b16 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3.js","sourceRoot":"","sources":["../src/sha3.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC7D,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAClE,OAAO,EACL,IAAI,EACJ,GAAG,EAEH,OAAO,EACP,eAAe,EACf,0BAA0B,GAE3B,MAAM,YAAY,CAAC;AAEpB,oGAAoG;AACpG,iCAAiC;AAEjC,2CAA2C;AAC3C,MAAM,CAAC,OAAO,EAAE,SAAS,EAAE,UAAU,CAAC,GAAmC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;AACtF,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,KAAK,GAAG,eAAe,CAAC,MAAM,CAAC,GAAG,C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G,CAAC,CAAC,CAAC;AAClE;;;GAGG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,eAAe,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;AAClE,MAAM,CAAC,MAAM,UAAU,GAAG,eAAe,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;AAClE,MAAM,CAAC,MAAM,UAAU,GAAG,eAAe,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;AAIjE,MAAM,QAAQ,GAAG,CAAC,MAAc,EAAE,QAAgB,EAAE,SAAiB,EAAE,EAAE,CACvE,0BAA0B,CACxB,CAAC,OAAkB,EAAE,EAAE,EAAE,CACvB,IAAI,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,CACxF,CAAC;AAEJ,MAAM,CAAC,MAAM,QAAQ,GAAG,eAAe,CAAC,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;AACrE,MAAM,CAAC,MAAM,QAAQ,GAAG,eAAe,CAAC,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha512.js b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha512.js new file mode 100644 index 0000000..f938b6d --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha512.js @@ -0,0 +1,231 @@ +import { SHA2 } from './_sha2.js'; +import u64 from './_u64.js'; +import { wrapConstructor } from './utils.js'; +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))))(); +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); +const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); +export class SHA512 extends SHA2 { + constructor() { + super(128, 64, 16, false); + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x6a09e667 | 0; + this.Al = 0xf3bcc908 | 0; + this.Bh = 0xbb67ae85 | 0; + this.Bl = 0x84caa73b | 0; + this.Ch = 0x3c6ef372 | 0; + this.Cl = 0xfe94f82b | 0; + this.Dh = 0xa54ff53a | 0; + this.Dl = 0x5f1d36f1 | 0; + this.Eh = 0x510e527f | 0; + this.El = 0xade682d1 | 0; + this.Fh = 0x9b05688c | 0; + this.Fl = 0x2b3e6c1f | 0; + this.Gh = 0x1f83d9ab | 0; + this.Gl = 0xfb41bd6b | 0; + this.Hh = 0x5be0cd19 | 0; + this.Hl = 0x137e2179 | 0; + } + // prettier-ignore + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); + const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); + const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); + const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); + const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = u64.add3L(T1l, sigma0l, MAJl); + Ah = u64.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +class SHA512_224 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x8c3d37c8 | 0; + this.Al = 0x19544da2 | 0; + this.Bh = 0x73e19966 | 0; + this.Bl = 0x89dcd4d6 | 0; + this.Ch = 0x1dfab7ae | 0; + this.Cl = 0x32ff9c82 | 0; + this.Dh = 0x679dd514 | 0; + this.Dl = 0x582f9fcf | 0; + this.Eh = 0x0f6d2b69 | 0; + this.El = 0x7bd44da8 | 0; + this.Fh = 0x77e36f73 | 0; + this.Fl = 0x04c48942 | 0; + this.Gh = 0x3f9d85a8 | 0; + this.Gl = 0x6a1d36c8 | 0; + this.Hh = 0x1112e6ad | 0; + this.Hl = 0x91d692a1 | 0; + this.outputLen = 28; + } +} +class SHA512_256 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x22312194 | 0; + this.Al = 0xfc2bf72c | 0; + this.Bh = 0x9f555fa3 | 0; + this.Bl = 0xc84c64c2 | 0; + this.Ch = 0x2393b86b | 0; + this.Cl = 0x6f53b151 | 0; + this.Dh = 0x96387719 | 0; + this.Dl = 0x5940eabd | 0; + this.Eh = 0x96283ee2 | 0; + this.El = 0xa88effe3 | 0; + this.Fh = 0xbe5e1e25 | 0; + this.Fl = 0x53863992 | 0; + this.Gh = 0x2b0199fc | 0; + this.Gl = 0x2c85b8aa | 0; + this.Hh = 0x0eb72ddc | 0; + this.Hl = 0x81c52ca2 | 0; + this.outputLen = 32; + } +} +class SHA384 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0xcbbb9d5d | 0; + this.Al = 0xc1059ed8 | 0; + this.Bh = 0x629a292a | 0; + this.Bl = 0x367cd507 | 0; + this.Ch = 0x9159015a | 0; + this.Cl = 0x3070dd17 | 0; + this.Dh = 0x152fecd8 | 0; + this.Dl = 0xf70e5939 | 0; + this.Eh = 0x67332667 | 0; + this.El = 0xffc00b31 | 0; + this.Fh = 0x8eb44a87 | 0; + this.Fl = 0x68581511 | 0; + this.Gh = 0xdb0c2e0d | 0; + this.Gl = 0x64f98fa7 | 0; + this.Hh = 0x47b5481d | 0; + this.Hl = 0xbefa4fa4 | 0; + this.outputLen = 48; + } +} +export const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512()); +export const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224()); +export const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256()); +export const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384()); +//# sourceMappingURL=sha512.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha512.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha512.js.map new file mode 100644 index 0000000..4c9e3e6 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha512.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha512.js","sourceRoot":"","sources":["../src/sha512.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,GAAG,MAAM,WAAW,CAAC;AAC5B,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C,0GAA0G;AAC1G,kBAAkB;AAClB,MAAM,CAAC,SAAS,EAAE,SAAS,CAAC,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC;IAC9D,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oB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,IAAI,UAAU,EAAE,CAAC,CAAC;AAClF,MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js new file mode 100644 index 0000000..80c0949 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js @@ -0,0 +1,154 @@ +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated, we can just drop the import. +import { crypto } from '@noble/hashes/crypto'; +const u8a = (a) => a instanceof Uint8Array; +// Cast array to different type +export const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +export const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +// Cast array to view +export const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +// The rotate right (circular right shift) operation for uint32 +export const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); +// big-endian hardware is rare. Just in case someone still decides to run hashes: +// early-throw an error because we don't support BE yet. +export const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!isLE) + throw new Error('Non little-endian hardware is not supported'); +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export function bytesToHex(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} +// There is no setImmediate in browser and setTimeout is slow. +// call of async fn will return Promise, which will be fullfiled only on +// next scheduler queue processing step and this is exactly what we need. +export const nextTick = async () => { }; +// Returns control to thread each 'tick' ms to avoid blocking +export async function asyncLoop(iters, tick, cb) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) + continue; + await nextTick(); + ts += diff; + } +} +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +export function toBytes(data) { + if (typeof data === 'string') + data = utf8ToBytes(data); + if (!u8a(data)) + throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; +} +/** + * Copies several Uint8Arrays into one. + */ +export function concatBytes(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) + throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} +// For runtime check if class implements interface +export class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +const toStr = {}.toString; +export function checkOpts(defaults, opts) { + if (opts !== undefined && toStr.call(opts) !== '[object Object]') + throw new Error('Options should be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged; +} +export function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +export function wrapConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +export function wrapXOFConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +export function randomBytes(bytesLength = 32) { + if (crypto && typeof crypto.getRandomValues === 'function') { + return crypto.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error('crypto.getRandomValues must be defined'); +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js.map new file mode 100644 index 0000000..19d87a9 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,oFAAoF;AACpF,sEAAsE;AACtE,kEAAkE;AAClE,8DAA8D;AAC9D,+DAA+D;AAC/D,8D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QAAQ,GAAG,GAAG,CAAC,QAAQ,CAAC;IAC9B,KAAK,CAAC,MAAM,GAAG,CAAC,IAAO,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC3C,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,WAAW,CAAC,WAAW,GAAG,EAAE;IAC1C,IAAI,MAAM,IAAI,OAAO,MAAM,CAAC,eAAe,KAAK,UAAU,EAAE;QAC1D,OAAO,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC;KAC5D;IACD,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAC5D,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/hkdf.d.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/hkdf.d.ts new file mode 100644 index 0000000..e1d683b --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/hkdf.d.ts @@ -0,0 +1,26 @@ +import { CHash, Input } from './utils.js'; +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +export declare function extract(hash: CHash, ikm: Input, salt?: Input): Uint8Array; +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +export declare function expand(hash: CHash, prk: Input, info?: Input, length?: number): Uint8Array; +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +export declare const hkdf: (hash: CHash, ikm: Input, salt: Input | undefined, info: Input | undefined, length: number) => Uint8Array; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/hkdf.js b/node_modules/@noble/curves/node_modules/@noble/hashes/hkdf.js new file mode 100644 index 0000000..021b68e --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/hkdf.js @@ -0,0 +1,78 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hkdf = exports.expand = exports.extract = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +const hmac_js_1 = require("./hmac.js"); +// HKDF (RFC 5869) +// https://soatok.blog/2021/11/17/understanding-hkdf/ +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +function extract(hash, ikm, salt) { + (0, _assert_js_1.hash)(hash); + // NOTE: some libraries treat zero-length array as 'not provided'; + // we don't, since we have undefined as 'not provided' + // https://github.com/RustCrypto/KDFs/issues/15 + if (salt === undefined) + salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros + return (0, hmac_js_1.hmac)(hash, (0, utils_js_1.toBytes)(salt), (0, utils_js_1.toBytes)(ikm)); +} +exports.extract = extract; +// HKDF-Expand(PRK, info, L) -> OKM +const HKDF_COUNTER = /* @__PURE__ */ new Uint8Array([0]); +const EMPTY_BUFFER = /* @__PURE__ */ new Uint8Array(); +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +function expand(hash, prk, info, length = 32) { + (0, _assert_js_1.hash)(hash); + (0, _assert_js_1.number)(length); + if (length > 255 * hash.outputLen) + throw new Error('Length should be <= 255*HashLen'); + const blocks = Math.ceil(length / hash.outputLen); + if (info === undefined) + info = EMPTY_BUFFER; + // first L(ength) octets of T + const okm = new Uint8Array(blocks * hash.outputLen); + // Re-use HMAC instance between blocks + const HMAC = hmac_js_1.hmac.create(hash, prk); + const HMACTmp = HMAC._cloneInto(); + const T = new Uint8Array(HMAC.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + // T(0) = empty string (zero length) + // T(N) = HMAC-Hash(PRK, T(N-1) | info | N) + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T) + .update(info) + .update(HKDF_COUNTER) + .digestInto(T); + okm.set(T, hash.outputLen * counter); + HMAC._cloneInto(HMACTmp); + } + HMAC.destroy(); + HMACTmp.destroy(); + T.fill(0); + HKDF_COUNTER.fill(0); + return okm.slice(0, length); +} +exports.expand = expand; +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length); +exports.hkdf = hkdf; +//# sourceMappingURL=hkdf.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/hkdf.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/hkdf.js.map new file mode 100644 index 0000000..7790e7c --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/hkdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hkdf.js","sourceRoot":"","sources":["src/hkdf.ts"],"names":[],"mappings":";;;AAAA,6CAA0E;AAC1E,yCAAmD;AACnD,uCAAiC;AAEjC,kBAAkB;AAClB,qDAAqD;AAErD;;;;;;;GAOG;AACH,SAAgB,OAAO,CAAC,IAAW,EAAE,GAAU,EAAE,IAAY;IAC3D,IAAA,iBAAU,EAAC,IAAI,CAAC,CAAC;IACjB,kEAAkE;IAClE,sDAAsD;IACtD,+CAA+C;IAC/C,IAAI,IAAI,KAAK,SAAS;QAAE,IAAI,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,0DAA0D;IACzH,OAAO,IAAA,cAAI,EAAC,IAAI,EAAE,IAAA,kBAAO,EAAC,IAAI,CAA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AAY,CAAC,CAAC,CAAC,CAAC,CAAC;aAC7C,MAAM,CAAC,IAAI,CAAC;aACZ,MAAM,CAAC,YAAY,CAAC;aACpB,UAAU,CAAC,CAAC,CAAC,CAAC;QACjB,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,CAAC;QACrC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;KAC1B;IACD,IAAI,CAAC,OAAO,EAAE,CAAC;IACf,OAAO,CAAC,OAAO,EAAE,CAAC;IAClB,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACV,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACrB,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;AAC9B,CAAC;AA5BD,wBA4BC;AAED;;;;;;;GAOG;AACI,MAAM,IAAI,GAAG,CAClB,IAAW,EACX,GAAU,EACV,IAAuB,EACvB,IAAuB,EACvB,MAAc,EACd,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAN7C,QAAA,IAAI,QAMyC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/hmac.d.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/hmac.d.ts new file mode 100644 index 0000000..63db656 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/hmac.d.ts @@ -0,0 +1,25 @@ +import { Hash, CHash, Input } from './utils.js'; +export declare class HMAC> extends Hash> { + oHash: T; + iHash: T; + blockLen: number; + outputLen: number; + private finished; + private destroyed; + constructor(hash: CHash, _key: Input); + update(buf: Input): this; + digestInto(out: Uint8Array): void; + digest(): Uint8Array; + _cloneInto(to?: HMAC): HMAC; + destroy(): void; +} +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +export declare const hmac: { + (hash: CHash, key: Input, message: Input): Uint8Array; + create(hash: CHash, key: Input): HMAC; +}; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/hmac.js b/node_modules/@noble/curves/node_modules/@noble/hashes/hmac.js new file mode 100644 index 0000000..0fc2d02 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/hmac.js @@ -0,0 +1,82 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hmac = exports.HMAC = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +// HMAC (RFC 2104) +class HMAC extends utils_js_1.Hash { + constructor(hash, _key) { + super(); + this.finished = false; + this.destroyed = false; + (0, _assert_js_1.hash)(hash); + const key = (0, utils_js_1.toBytes)(_key); + this.iHash = hash.create(); + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash.create(); + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + (0, _assert_js_1.exists)(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + (0, _assert_js_1.exists)(this); + (0, _assert_js_1.bytes)(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} +exports.HMAC = HMAC; +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); +exports.hmac = hmac; +exports.hmac.create = (hash, key) => new HMAC(hash, key); +//# sourceMappingURL=hmac.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/hmac.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/hmac.js.map new file mode 100644 index 0000000..798c5fa --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/hmac.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hmac.js","sourceRoot":"","sources":["src/hmac.ts"],"names":[],"mappings":";;;AAAA,6CAAgG;AAChG,yCAAyD;AACzD,kBAAkB;AAClB,MAAa,IAAwB,SAAQ,eAAa;IAQxD,YAAY,IAAW,EAAE,IAAW;QAClC,KAAK,EAAE,CAAC;QAJF,aAAQ,GAAG,KAAK,CAAC;QACjB,cAAS,GAAG,KAAK,CAAC;QAIxB,IAAA,iBAAU,EAAC,IAAI,CAAC,CAAC;QACjB,MAAM,GAAG,GAAG,IAAA,kBAAO,EAAC,IAAI,CAAC,CAAC;QAC1B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,MAAM,EAAO,CAAC;QAChC,IAAI,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,KAAK,UAAU;YACzC,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;QACzE,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC;Q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AI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;IACvB,CAAC;CACF;AAnED,oBAmEC;AAED;;;;;GAKG;AACI,MAAM,IAAI,GAAG,CAAC,IAAW,EAAE,GAAU,EAAE,OAAc,EAAc,EAAE,CAC1E,IAAI,IAAI,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC;AADvC,QAAA,IAAI,QACmC;AACpD,YAAI,CAAC,MAAM,GAAG,CAAC,IAAW,EAAE,GAAU,EAAE,EAAE,CAAC,IAAI,IAAI,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/index.d.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/index.d.ts new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/index.js b/node_modules/@noble/curves/node_modules/@noble/hashes/index.js new file mode 100644 index 0000000..2299d7f --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/index.js @@ -0,0 +1,3 @@ +"use strict"; +throw new Error('noble-hashes have no entry-point: consult README for usage'); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/index.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/index.js.map new file mode 100644 index 0000000..b71bae6 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":";AAAA,MAAM,IAAI,KAAK,CAAC,4DAA4D,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/package.json b/node_modules/@noble/curves/node_modules/@noble/hashes/package.json new file mode 100644 index 0000000..9a668d3 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/package.json @@ -0,0 +1,174 @@ +{ + "name": "@noble/hashes", + "version": "1.3.2", + "description": "Audited & minimal 0-dependency JS implementation of SHA2, SHA3, RIPEMD, BLAKE2/3, HMAC, HKDF, PBKDF2, Scrypt", + "files": [ + "/*.js", + "/*.d.ts", + "/*.js.map", + "esm", + "src/*.ts" + ], + "scripts": { + "bench": "node benchmark/index.js noble", + "bench:all": "node benchmark/index.js", + "bench:install": "cd benchmark && npm install && cd ../../", + "build": "npm run build:clean; tsc && tsc -p tsconfig.esm.json", + "build:release": "cd build; npm i; npm run build", + "build:clean": "rm *.{js,d.ts,js.map} esm/*.{js,js.map} 2> /dev/null", + "lint": "prettier --check 'src/**/*.{js,ts}' 'test/**/*.{js,ts}'", + "format": "prettier --write 'src/**/*.{js,ts}' 'test/**/*.{js,ts}'", + "test": "node test/index.js", + "test:dos": "node test/slow-dos.test.js", + "test:big": "node test/slow-big.test.js" + }, + "author": "Paul Miller (https://paulmillr.com)", + "homepage": "https://paulmillr.com/noble/", + "repository": { + "type": "git", + "url": "https://github.com/paulmillr/noble-hashes.git" + }, + "license": "MIT", + "sideEffects": false, + "browser": { + "node:crypto": false, + "./crypto": "./crypto.js" + }, + "devDependencies": { + "micro-bmark": "0.3.1", + "micro-should": "0.4.0", + "prettier": "2.8.4", + "typescript": "5.0.2" + }, + "engines": { + "node": ">= 16" + }, + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./esm/index.js", + "default": "./index.js" + }, + "./crypto": { + "types": "./crypto.d.ts", + "node": { + "import": "./esm/cryptoNode.js", + "default": "./cryptoNode.js" + }, + "import": "./esm/crypto.js", + "default": "./crypto.js" + }, + "./_assert": { + "types": "./_assert.d.ts", + "import": "./esm/_assert.js", + "default": "./_assert.js" + }, + "./_sha2": { + "types": "./_sha2.d.ts", + "import": "./esm/_sha2.js", + "default": "./_sha2.js" + }, + "./argon2": { + "types": "./argon2.d.ts", + "import": "./esm/argon2.js", + "default": "./argon2.js" + }, + "./blake2b": { + "types": "./blake2b.d.ts", + "import": "./esm/blake2b.js", + "default": "./blake2b.js" + }, + "./blake2s": { + "types": "./blake2s.d.ts", + "import": "./esm/blake2s.js", + "default": "./blake2s.js" + }, + "./blake3": { + "types": "./blake3.d.ts", + "import": "./esm/blake3.js", + "default": "./blake3.js" + }, + "./eskdf": { + "types": "./eskdf.d.ts", + "import": "./esm/eskdf.js", + "default": "./eskdf.js" + }, + "./hkdf": { + "types": "./hkdf.d.ts", + "import": "./esm/hkdf.js", + "default": "./hkdf.js" + }, + "./hmac": { + "types": "./hmac.d.ts", + "import": "./esm/hmac.js", + "default": "./hmac.js" + }, + "./pbkdf2": { + "types": "./pbkdf2.d.ts", + "import": "./esm/pbkdf2.js", + "default": "./pbkdf2.js" + }, + "./ripemd160": { + "types": "./ripemd160.d.ts", + "import": "./esm/ripemd160.js", + "default": "./ripemd160.js" + }, + "./scrypt": { + "types": "./scrypt.d.ts", + "import": "./esm/scrypt.js", + "default": "./scrypt.js" + }, + "./sha1": { + "types": "./sha1.d.ts", + "import": "./esm/sha1.js", + "default": "./sha1.js" + }, + "./sha3-addons": { + "types": "./sha3-addons.d.ts", + "import": "./esm/sha3-addons.js", + "default": "./sha3-addons.js" + }, + "./sha3": { + "types": "./sha3.d.ts", + "import": "./esm/sha3.js", + "default": "./sha3.js" + }, + "./sha256": { + "types": "./sha256.d.ts", + "import": "./esm/sha256.js", + "default": "./sha256.js" + }, + "./sha512": { + "types": "./sha512.d.ts", + "import": "./esm/sha512.js", + "default": "./sha512.js" + }, + "./utils": { + "types": "./utils.d.ts", + "import": "./esm/utils.js", + "default": "./utils.js" + } + }, + "keywords": [ + "sha", + "sha2", + "sha3", + "sha256", + "sha512", + "keccak", + "kangarootwelve", + "ripemd160", + "blake2", + "blake3", + "hmac", + "hkdf", + "pbkdf2", + "scrypt", + "kdf", + "hash", + "cryptography", + "security", + "noble" + ], + "funding": "https://paulmillr.com/funding/" +} diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/pbkdf2.d.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/pbkdf2.d.ts new file mode 100644 index 0000000..42f691c --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/pbkdf2.d.ts @@ -0,0 +1,15 @@ +import { CHash, Input } from './utils.js'; +export type Pbkdf2Opt = { + c: number; + dkLen?: number; + asyncTick?: number; +}; +/** + * PBKDF2-HMAC: RFC 2898 key derivation function + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated + * @param salt - cryptographic salt + * @param opts - {c, dkLen} where c is work factor and dkLen is output message size + */ +export declare function pbkdf2(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt): Uint8Array; +export declare function pbkdf2Async(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt): Promise; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/pbkdf2.js b/node_modules/@noble/curves/node_modules/@noble/hashes/pbkdf2.js new file mode 100644 index 0000000..a667178 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/pbkdf2.js @@ -0,0 +1,91 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.pbkdf2Async = exports.pbkdf2 = void 0; +const _assert_js_1 = require("./_assert.js"); +const hmac_js_1 = require("./hmac.js"); +const utils_js_1 = require("./utils.js"); +// Common prologue and epilogue for sync/async functions +function pbkdf2Init(hash, _password, _salt, _opts) { + (0, _assert_js_1.hash)(hash); + const opts = (0, utils_js_1.checkOpts)({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + (0, _assert_js_1.number)(c); + (0, _assert_js_1.number)(dkLen); + (0, _assert_js_1.number)(asyncTick); + if (c < 1) + throw new Error('PBKDF2: iterations (c) should be >= 1'); + const password = (0, utils_js_1.toBytes)(_password); + const salt = (0, utils_js_1.toBytes)(_salt); + // DK = PBKDF2(PRF, Password, Salt, c, dkLen); + const DK = new Uint8Array(dkLen); + // U1 = PRF(Password, Salt + INT_32_BE(i)) + const PRF = hmac_js_1.hmac.create(hash, password); + const PRFSalt = PRF._cloneInto().update(salt); + return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; +} +function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) + prfW.destroy(); + u.fill(0); + return DK; +} +/** + * PBKDF2-HMAC: RFC 2898 key derivation function + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated + * @param salt - cryptographic salt + * @param opts - {c, dkLen} where c is work factor and dkLen is output message size + */ +function pbkdf2(hash, password, salt, opts) { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = (0, utils_js_1.createView)(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + for (let ui = 1; ui < c; ui++) { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +exports.pbkdf2 = pbkdf2; +async function pbkdf2Async(hash, password, salt, opts) { + const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = (0, utils_js_1.createView)(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + await (0, utils_js_1.asyncLoop)(c - 1, asyncTick, () => { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + }); + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +exports.pbkdf2Async = pbkdf2Async; +//# sourceMappingURL=pbkdf2.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/pbkdf2.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/pbkdf2.js.map new file mode 100644 index 0000000..a8f30b0 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/pbkdf2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pbkdf2.js","sourceRoot":"","sources":["src/pbkdf2.ts"],"names":[],"mappings":";;;AAAA,6CAA0E;AAC1E,uCAAiC;AACjC,yCAA2F;AAQ3F,wDAAwD;AACxD,SAAS,UAAU,CAAC,IAAW,EAAE,SAAgB,EAAE,KAAY,EAAE,KAAgB;IAC/E,IAAA,iBAAU,EAAC,IAAI,CAAC,CAAC;IACjB,MAAM,IAAI,GAAG,IAAA,oBAAS,EAAC,EAAE,KAAK,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IAC5D,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;IACrC,IAAA,mBAAY,EAAC,CAAC,CAAC,CAAC;IAChB,IAAA,mBAAY,EAAC,KAAK,CAAC,CAAC;IACpB,IAAA,mBAAY,EAAC,SAAS,CAAC,CAAC;IACxB,IAAI,CAAC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AAC,CAAC,CAAC,CAAC;YAC7C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,EAAE;gBAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;QACpD,CAAC,CAAC,CAAC;KACJ;IACD,OAAO,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AACjD,CAAC;AAtBD,kCAsBC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/ripemd160.d.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/ripemd160.d.ts new file mode 100644 index 0000000..92e662f --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/ripemd160.d.ts @@ -0,0 +1,24 @@ +import { SHA2 } from './_sha2.js'; +export declare class RIPEMD160 extends SHA2 { + private h0; + private h1; + private h2; + private h3; + private h4; + constructor(); + protected get(): [number, number, number, number, number]; + protected set(h0: number, h1: number, h2: number, h3: number, h4: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +export declare const ripemd160: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/ripemd160.js b/node_modules/@noble/curves/node_modules/@noble/hashes/ripemd160.js new file mode 100644 index 0000000..7d6e057 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/ripemd160.js @@ -0,0 +1,108 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ripemd160 = exports.RIPEMD160 = void 0; +const _sha2_js_1 = require("./_sha2.js"); +const utils_js_1 = require("./utils.js"); +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = /* @__PURE__ */ Uint8Array.from({ length: 16 }, (_, i) => i); +const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) + for (let j of [idxL, idxR]) + j.push(j[i].map((k) => Rho[k])); +const shifts = /* @__PURE__ */ [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => new Uint8Array(i)); +const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +const Kl = /* @__PURE__ */ new Uint32Array([ + 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e, +]); +const Kr = /* @__PURE__ */ new Uint32Array([ + 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000, +]); +// The rotate left (circular left shift) operation for uint32 +const rotl = (word, shift) => (word << shift) | (word >>> (32 - shift)); +// It's called f() in spec. +function f(group, x, y, z) { + if (group === 0) + return x ^ y ^ z; + else if (group === 1) + return (x & y) | (~x & z); + else if (group === 2) + return (x | ~y) ^ z; + else if (group === 3) + return (x & z) | (y & ~z); + else + return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const BUF = /* @__PURE__ */ new Uint32Array(16); +class RIPEMD160 extends _sha2_js_1.SHA2 { + constructor() { + super(64, 20, 8, true); + this.h0 = 0x67452301 | 0; + this.h1 = 0xefcdab89 | 0; + this.h2 = 0x98badcfe | 0; + this.h3 = 0x10325476 | 0; + this.h4 = 0xc3d2e1f0 | 0; + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + BUF[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0); + } + roundClean() { + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} +exports.RIPEMD160 = RIPEMD160; +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +exports.ripemd160 = (0, utils_js_1.wrapConstructor)(() => new RIPEMD160()); +//# sourceMappingURL=ripemd160.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/ripemd160.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/ripemd160.js.map new file mode 100644 index 0000000..396a517 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/ripemd160.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ripemd160.js","sourceRoot":"","sources":["src/ripemd160.ts"],"names":[],"mappings":";;;AAAA,yCAAkC;AAClC,yCAA6C;AAE7C,0DAA0D;AAC1D,6EAA6E;AAC7E,MAAM,GAAG,GAAG,eAAe,CAAC,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;AACnG,MAAM,EAAE,GAAG,eAAe,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;AACxE,MAAM,EAAE,GAAG,eAAe,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC;AAC3D,IAAI,IAAI,GAAG,CAAC,EAAE,CAAC,CAAC;AAChB,IAAI,IAAI,GAAG,CAAC,EAAE,CAAC,CAAC;AAChB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAA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EACvB,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,EACvB,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,EACvB,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CACxB,CAAC;IACJ,CAAC;IACS,UAAU;QAClB,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACd,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACpB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC1B,CAAC;CACF;AAhED,8BAgEC;AAED;;;GAGG;AACU,QAAA,SAAS,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,SAAS,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/scrypt.d.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/scrypt.d.ts new file mode 100644 index 0000000..82485b3 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/scrypt.d.ts @@ -0,0 +1,29 @@ +import { Input } from './utils.js'; +export type ScryptOpts = { + N: number; + r: number; + p: number; + dkLen?: number; + asyncTick?: number; + maxmem?: number; + onProgress?: (progress: number) => void; +}; +/** + * Scrypt KDF from RFC 7914. + * @param password - pass + * @param salt - salt + * @param opts - parameters + * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + * @returns Derived key + */ +export declare function scrypt(password: Input, salt: Input, opts: ScryptOpts): Uint8Array; +/** + * Scrypt KDF from RFC 7914. + */ +export declare function scryptAsync(password: Input, salt: Input, opts: ScryptOpts): Promise; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/scrypt.js b/node_modules/@noble/curves/node_modules/@noble/hashes/scrypt.js new file mode 100644 index 0000000..2f118db --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/scrypt.js @@ -0,0 +1,223 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.scryptAsync = exports.scrypt = void 0; +const _assert_js_1 = require("./_assert.js"); +const sha256_js_1 = require("./sha256.js"); +const pbkdf2_js_1 = require("./pbkdf2.js"); +const utils_js_1 = require("./utils.js"); +// RFC 7914 Scrypt KDF +// Left rotate for uint32 +const rotl = (a, b) => (a << b) | (a >>> (32 - b)); +// The main Scrypt loop: uses Salsa extensively. +// Six versions of the function were tried, this is the fastest one. +// prettier-ignore +function XorAndSalsa(prev, pi, input, ii, out, oi) { + // Based on https://cr.yp.to/salsa20.html + // Xor blocks + let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; + let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; + let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; + let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; + let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; + let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; + let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; + let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; + // Save state to temporary variables (salsa) + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; + // Main loop (salsa) + for (let i = 0; i < 8; i += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); + x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); + x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); + x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); + x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); + x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); + x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); + x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); + x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); + x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); + x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); + x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); + x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); + x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); + x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); + x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); + x15 ^= rotl(x14 + x13 | 0, 18); + } + // Write output (salsa) + out[oi++] = (y00 + x00) | 0; + out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; + out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; + out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; + out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; + out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; + out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; + out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; + out[oi++] = (y15 + x15) | 0; +} +function BlockMix(input, ii, out, oi, r) { + // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks) + let head = oi + 0; + let tail = oi + 16 * r; + for (let i = 0; i < 16; i++) + out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1] + for (let i = 0; i < r; i++, head += 16, ii += 16) { + // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1 + XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1]) + if (i > 0) + tail += 16; // First iteration overwrites tmp value in tail + XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i]) + } +} +// Common prologue and epilogue for sync/async functions +function scryptInit(password, salt, _opts) { + // Maxmem - 1GB+1KB by default + const opts = (0, utils_js_1.checkOpts)({ + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024, + }, _opts); + const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; + (0, _assert_js_1.number)(N); + (0, _assert_js_1.number)(r); + (0, _assert_js_1.number)(p); + (0, _assert_js_1.number)(dkLen); + (0, _assert_js_1.number)(asyncTick); + (0, _assert_js_1.number)(maxmem); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + const blockSize = 128 * r; + const blockSize32 = blockSize / 4; + if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) { + // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function + // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future. + throw new Error('Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32'); + } + if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) { + throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)'); + } + if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) { + throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32'); + } + const memUsed = blockSize * (N + p); + if (memUsed > maxmem) { + throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`); + } + // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor) + // Since it has only one iteration there is no reason to use async variant + const B = (0, pbkdf2_js_1.pbkdf2)(sha256_js_1.sha256, password, salt, { c: 1, dkLen: blockSize * p }); + const B32 = (0, utils_js_1.u32)(B); + // Re-used between parallel iterations. Array(iterations) of B + const V = (0, utils_js_1.u32)(new Uint8Array(blockSize * N)); + const tmp = (0, utils_js_1.u32)(new Uint8Array(blockSize)); + let blockMixCb = () => { }; + if (onProgress) { + const totalBlockMix = 2 * N * p; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1); + let blockMixCnt = 0; + blockMixCb = () => { + blockMixCnt++; + if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) + onProgress(blockMixCnt / totalBlockMix); + }; + } + return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick }; +} +function scryptOutput(password, dkLen, B, V, tmp) { + const res = (0, pbkdf2_js_1.pbkdf2)(sha256_js_1.sha256, password, B, { c: 1, dkLen }); + B.fill(0); + V.fill(0); + tmp.fill(0); + return res; +} +/** + * Scrypt KDF from RFC 7914. + * @param password - pass + * @param salt - salt + * @param opts - parameters + * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + * @returns Derived key + */ +function scrypt(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + for (let i = 0, pos = 0; i < N - 1; i++) { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + } + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + for (let i = 0; i < N; i++) { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + } + } + return scryptOutput(password, dkLen, B, V, tmp); +} +exports.scrypt = scrypt; +/** + * Scrypt KDF from RFC 7914. + */ +async function scryptAsync(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + let pos = 0; + await (0, utils_js_1.asyncLoop)(N - 1, asyncTick, () => { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + }); + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + await (0, utils_js_1.asyncLoop)(N, asyncTick, () => { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + }); + } + return scryptOutput(password, dkLen, B, V, tmp); +} +exports.scryptAsync = scryptAsync; +//# sourceMappingURL=scrypt.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/scrypt.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/scrypt.js.map new file mode 100644 index 0000000..873dc15 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/scrypt.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scrypt.js","sourceRoot":"","sources":["src/scrypt.ts"],"names":[],"mappings":";;;AAAA,6CAAsD;AACtD,2CAAqC;AACrC,2CAAqC;AACrC,yCAA8D;AAE9D,sBAAsB;AAEtB,yBAAyB;AACzB,MAAM,IAAI,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;AAEnE,gDAAgD;AAChD,oEAAoE;AACpE,kBAAkB;AAClB,SAAS,WAAW,CAClB,IAAiB,EACjB,EAAU,EACV,KAAkB,EAClB,EAAU,EACV,GAAgB,EAChB,EAAU;IAEV,yCAAyC;IACzC,aAAa;IACb,IAAI,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;IACnE,IAAI,GAAG,GAAG,IAAI,CAA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d.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/sha1.d.ts new file mode 100644 index 0000000..d9cb132 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/sha1.d.ts @@ -0,0 +1,21 @@ +import { SHA2 } from './_sha2.js'; +declare class SHA1 extends SHA2 { + private A; + private B; + private C; + private D; + private E; + constructor(); + protected get(): [number, number, number, number, number]; + protected set(A: number, B: number, C: number, D: number, E: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +export declare const sha1: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export {}; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/sha1.js b/node_modules/@noble/curves/node_modules/@noble/hashes/sha1.js new file mode 100644 index 0000000..10c6953 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/sha1.js @@ -0,0 +1,90 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha1 = void 0; +const _sha2_js_1 = require("./_sha2.js"); +const utils_js_1 = require("./utils.js"); +// SHA1 was cryptographically broken. +// It is still widely used in legacy apps. Don't use it for a new protocol. +// RFC 3174 +const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +// Initial state +const IV = /* @__PURE__ */ new Uint32Array([ + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0, +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = /* @__PURE__ */ new Uint32Array(80); +class SHA1 extends _sha2_js_1.SHA2 { + constructor() { + super(64, 20, 8, false); + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + } + get() { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + set(A, B, C, D, E) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } + else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } + else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } + else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +exports.sha1 = (0, utils_js_1.wrapConstructor)(() => new SHA1()); +//# sourceMappingURL=sha1.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/sha1.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/sha1.js.map new file mode 100644 index 0000000..4b0ccbd --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/sha1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha1.js","sourceRoot":"","sources":["src/sha1.ts"],"names":[],"mappings":";;;AAAA,yCAAkC;AAClC,yCAA6C;AAE7C,qCAAqC;AACrC,2EAA2E;AAE3E,WAAW;AACX,MAAM,IAAI,GAAG,CAAC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G,CAAC,CAAC;QACrB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC1B,CAAC;IACS,UAAU;QAClB,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACjB,CAAC;IACD,OAAO;QACL,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QACxB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACtB,CAAC;CACF;AAEY,QAAA,IAAI,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/sha256.d.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/sha256.d.ts new file mode 100644 index 0000000..3e1491d --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/sha256.d.ts @@ -0,0 +1,34 @@ +import { SHA2 } from './_sha2.js'; +declare class SHA256 extends SHA2 { + A: number; + B: number; + C: number; + D: number; + E: number; + F: number; + G: number; + H: number; + constructor(); + protected get(): [number, number, number, number, number, number, number, number]; + protected set(A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +export declare const sha256: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha224: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export {}; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/sha256.js b/node_modules/@noble/curves/node_modules/@noble/hashes/sha256.js new file mode 100644 index 0000000..24fe574 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/sha256.js @@ -0,0 +1,129 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha224 = exports.sha256 = void 0; +const _sha2_js_1 = require("./_sha2.js"); +const utils_js_1 = require("./utils.js"); +// SHA2-256 need to try 2^128 hashes to execute birthday attack. +// BTC network is doing 2^67 hashes/sec as per early 2023. +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = /* @__PURE__ */ new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); +// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): +// prettier-ignore +const IV = /* @__PURE__ */ new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = /* @__PURE__ */ new Uint32Array(64); +class SHA256 extends _sha2_js_1.SHA2 { + constructor() { + super(64, 32, 8, false); + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + this.F = IV[5] | 0; + this.G = IV[6] | 0; + this.H = IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = (0, utils_js_1.rotr)(W15, 7) ^ (0, utils_js_1.rotr)(W15, 18) ^ (W15 >>> 3); + const s1 = (0, utils_js_1.rotr)(W2, 17) ^ (0, utils_js_1.rotr)(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = (0, utils_js_1.rotr)(E, 6) ^ (0, utils_js_1.rotr)(E, 11) ^ (0, utils_js_1.rotr)(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = (0, utils_js_1.rotr)(A, 2) ^ (0, utils_js_1.rotr)(A, 13) ^ (0, utils_js_1.rotr)(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + constructor() { + super(); + this.A = 0xc1059ed8 | 0; + this.B = 0x367cd507 | 0; + this.C = 0x3070dd17 | 0; + this.D = 0xf70e5939 | 0; + this.E = 0xffc00b31 | 0; + this.F = 0x68581511 | 0; + this.G = 0x64f98fa7 | 0; + this.H = 0xbefa4fa4 | 0; + this.outputLen = 28; + } +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +exports.sha256 = (0, utils_js_1.wrapConstructor)(() => new SHA256()); +exports.sha224 = (0, utils_js_1.wrapConstructor)(() => new SHA224()); +//# sourceMappingURL=sha256.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/sha256.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/sha256.js.map new file mode 100644 index 0000000..a2fd853 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/sha256.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha256.js","sourceRoot":"","sources":["src/sha256.ts"],"names":[],"mappings":";;;AAAA,yCAAkC;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AAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QACjC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACtB,CAAC;CACF;AACD,4EAA4E;AAC5E,MAAM,MAAO,SAAQ,MAAM;IASzB;QACE,KAAK,EAAE,CAAC;QATV,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QAGjB,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;IACtB,CAAC;CACF;AAED;;;GAGG;AACU,QAAA,MAAM,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC;AAC7D,QAAA,MAAM,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/sha3-addons.d.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/sha3-addons.d.ts new file mode 100644 index 0000000..cf7c3a0 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/sha3-addons.d.ts @@ -0,0 +1,138 @@ +import { Input, Hash, HashXOF } from './utils.js'; +import { Keccak, ShakeOpts } from './sha3.js'; +export type cShakeOpts = ShakeOpts & { + personalization?: Input; + NISTfn?: Input; +}; +export declare const cshake128: { + (msg: Input, opts?: cShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: cShakeOpts): Hash; +}; +export declare const cshake256: { + (msg: Input, opts?: cShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: cShakeOpts): Hash; +}; +declare class KMAC extends Keccak implements HashXOF { + constructor(blockLen: number, outputLen: number, enableXOF: boolean, key: Input, opts?: cShakeOpts); + protected finish(): void; + _cloneInto(to?: KMAC): KMAC; + clone(): KMAC; +} +export declare const kmac128: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +export declare const kmac256: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +export declare const kmac128xof: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +export declare const kmac256xof: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +declare class TupleHash extends Keccak implements HashXOF { + constructor(blockLen: number, outputLen: number, enableXOF: boolean, opts?: cShakeOpts); + protected finish(): void; + _cloneInto(to?: TupleHash): TupleHash; + clone(): TupleHash; +} +export declare const tuplehash128: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +export declare const tuplehash256: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +export declare const tuplehash128xof: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +export declare const tuplehash256xof: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +type ParallelOpts = cShakeOpts & { + blockLen?: number; +}; +declare class ParallelHash extends Keccak implements HashXOF { + protected leafCons: () => Hash; + private leafHash?; + private chunkPos; + private chunksDone; + private chunkLen; + constructor(blockLen: number, outputLen: number, leafCons: () => Hash, enableXOF: boolean, opts?: ParallelOpts); + protected finish(): void; + _cloneInto(to?: ParallelHash): ParallelHash; + destroy(): void; + clone(): ParallelHash; +} +export declare const parallelhash128: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export declare const parallelhash256: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export declare const parallelhash128xof: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export declare const parallelhash256xof: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export type KangarooOpts = { + dkLen?: number; + personalization?: Input; +}; +declare class KangarooTwelve extends Keccak implements HashXOF { + protected leafLen: number; + readonly chunkLen = 8192; + private leafHash?; + private personalization; + private chunkPos; + private chunksDone; + constructor(blockLen: number, leafLen: number, outputLen: number, rounds: number, opts: KangarooOpts); + update(data: Input): this; + protected finish(): void; + destroy(): void; + _cloneInto(to?: KangarooTwelve): KangarooTwelve; + clone(): KangarooTwelve; +} +export declare const k12: { + (msg: Input, opts?: KangarooOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: KangarooOpts): Hash; +}; +export declare const m14: { + (msg: Input, opts?: KangarooOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: KangarooOpts): Hash; +}; +declare class KeccakPRG extends Keccak { + protected rate: number; + constructor(capacity: number); + keccak(): void; + update(data: Input): this; + feed(data: Input): this; + protected finish(): void; + digestInto(_out: Uint8Array): Uint8Array; + fetch(bytes: number): Uint8Array; + forget(): void; + _cloneInto(to?: KeccakPRG): KeccakPRG; + clone(): KeccakPRG; +} +export declare const keccakprg: (capacity?: number) => KeccakPRG; +export {}; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/sha3-addons.js b/node_modules/@noble/curves/node_modules/@noble/hashes/sha3-addons.js new file mode 100644 index 0000000..e5317b1 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/sha3-addons.js @@ -0,0 +1,351 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.keccakprg = exports.m14 = exports.k12 = exports.parallelhash256xof = exports.parallelhash128xof = exports.parallelhash256 = exports.parallelhash128 = exports.tuplehash256xof = exports.tuplehash128xof = exports.tuplehash256 = exports.tuplehash128 = exports.kmac256xof = exports.kmac128xof = exports.kmac256 = exports.kmac128 = exports.cshake256 = exports.cshake128 = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +const sha3_js_1 = require("./sha3.js"); +// cSHAKE && KMAC (NIST SP800-185) +function leftEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.unshift(res.length); + return new Uint8Array(res); +} +function rightEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +function chooseLen(opts, outputLen) { + return opts.dkLen === undefined ? outputLen : opts.dkLen; +} +const toBytesOptional = (buf) => (buf !== undefined ? (0, utils_js_1.toBytes)(buf) : new Uint8Array([])); +// NOTE: second modulo is necessary since we don't need to add padding if current element takes whole block +const getPadding = (len, block) => new Uint8Array((block - (len % block)) % block); +// Personalization +function cshakePers(hash, opts = {}) { + if (!opts || (!opts.personalization && !opts.NISTfn)) + return hash; + // Encode and pad inplace to avoid unneccesary memory copies/slices (so we don't need to zero them later) + // bytepad(encode_string(N) || encode_string(S), 168) + const blockLenBytes = leftEncode(hash.blockLen); + const fn = toBytesOptional(opts.NISTfn); + const fnLen = leftEncode(8 * fn.length); // length in bits + const pers = toBytesOptional(opts.personalization); + const persLen = leftEncode(8 * pers.length); // length in bits + if (!fn.length && !pers.length) + return hash; + hash.suffix = 0x04; + hash.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers); + let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length; + hash.update(getPadding(totalLen, hash.blockLen)); + return hash; +} +const gencShake = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapConstructorWithOpts)((opts = {}) => cshakePers(new sha3_js_1.Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts)); +exports.cshake128 = (() => gencShake(0x1f, 168, 128 / 8))(); +exports.cshake256 = (() => gencShake(0x1f, 136, 256 / 8))(); +class KMAC extends sha3_js_1.Keccak { + constructor(blockLen, outputLen, enableXOF, key, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'KMAC', personalization: opts.personalization }); + key = (0, utils_js_1.toBytes)(key); + // 1. newX = bytepad(encode_string(K), 168) || X || right_encode(L). + const blockLenBytes = leftEncode(this.blockLen); + const keyLen = leftEncode(8 * key.length); + this.update(blockLenBytes).update(keyLen).update(key); + const totalLen = blockLenBytes.length + keyLen.length + key.length; + this.update(getPadding(totalLen, this.blockLen)); + } + finish() { + if (!this.finished) + this.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + // Force "to" to be instance of KMAC instead of Sha3. + if (!to) { + to = Object.create(Object.getPrototypeOf(this), {}); + to.state = this.state.slice(); + to.blockLen = this.blockLen; + to.state32 = (0, utils_js_1.u32)(to.state); + } + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genKmac(blockLen, outputLen, xof = false) { + const kmac = (key, message, opts) => kmac.create(key, opts).update(message).digest(); + kmac.create = (key, opts = {}) => new KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts); + return kmac; +} +exports.kmac128 = (() => genKmac(168, 128 / 8))(); +exports.kmac256 = (() => genKmac(136, 256 / 8))(); +exports.kmac128xof = (() => genKmac(168, 128 / 8, true))(); +exports.kmac256xof = (() => genKmac(136, 256 / 8, true))(); +// TupleHash +// Usage: tuple(['ab', 'cd']) != tuple(['a', 'bcd']) +class TupleHash extends sha3_js_1.Keccak { + constructor(blockLen, outputLen, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'TupleHash', personalization: opts.personalization }); + // Change update after cshake processed + this.update = (data) => { + data = (0, utils_js_1.toBytes)(data); + super.update(leftEncode(data.length * 8)); + super.update(data); + return this; + }; + } + finish() { + if (!this.finished) + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new TupleHash(this.blockLen, this.outputLen, this.enableXOF)); + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genTuple(blockLen, outputLen, xof = false) { + const tuple = (messages, opts) => { + const h = tuple.create(opts); + for (const msg of messages) + h.update(msg); + return h.digest(); + }; + tuple.create = (opts = {}) => new TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts); + return tuple; +} +exports.tuplehash128 = (() => genTuple(168, 128 / 8))(); +exports.tuplehash256 = (() => genTuple(136, 256 / 8))(); +exports.tuplehash128xof = (() => genTuple(168, 128 / 8, true))(); +exports.tuplehash256xof = (() => genTuple(136, 256 / 8, true))(); +class ParallelHash extends sha3_js_1.Keccak { + constructor(blockLen, outputLen, leafCons, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + this.leafCons = leafCons; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + cshakePers(this, { NISTfn: 'ParallelHash', personalization: opts.personalization }); + let { blockLen: B } = opts; + B || (B = 8); + (0, _assert_js_1.number)(B); + this.chunkLen = B; + super.update(leftEncode(B)); + // Change update after cshake processed + this.update = (data) => { + data = (0, utils_js_1.toBytes)(data); + const { chunkLen, leafCons } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen || !this.leafHash) { + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + this.leafHash = leafCons(); + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + this.leafHash.update(data.subarray(pos, pos + take)); + this.chunkPos += take; + pos += take; + } + return this; + }; + } + finish() { + if (this.finished) + return; + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + super.update(rightEncode(this.chunksDone)); + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF)); + if (this.leafHash) + to.leafHash = this.leafHash._cloneInto(to.leafHash); + to.chunkPos = this.chunkPos; + to.chunkLen = this.chunkLen; + to.chunksDone = this.chunksDone; + return super._cloneInto(to); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + } + clone() { + return this._cloneInto(); + } +} +function genPrl(blockLen, outputLen, leaf, xof = false) { + const parallel = (message, opts) => parallel.create(opts).update(message).digest(); + parallel.create = (opts = {}) => new ParallelHash(blockLen, chooseLen(opts, outputLen), () => leaf.create({ dkLen: 2 * outputLen }), xof, opts); + return parallel; +} +exports.parallelhash128 = (() => genPrl(168, 128 / 8, exports.cshake128))(); +exports.parallelhash256 = (() => genPrl(136, 256 / 8, exports.cshake256))(); +exports.parallelhash128xof = (() => genPrl(168, 128 / 8, exports.cshake128, true))(); +exports.parallelhash256xof = (() => genPrl(136, 256 / 8, exports.cshake256, true))(); +// Kangaroo +// Same as NIST rightEncode, but returns [0] for zero string +function rightEncodeK12(n) { + const res = []; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +const EMPTY = new Uint8Array([]); +class KangarooTwelve extends sha3_js_1.Keccak { + constructor(blockLen, leafLen, outputLen, rounds, opts) { + super(blockLen, 0x07, outputLen, true, rounds); + this.leafLen = leafLen; + this.chunkLen = 8192; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + const { personalization } = opts; + this.personalization = toBytesOptional(personalization); + } + update(data) { + data = (0, utils_js_1.toBytes)(data); + const { chunkLen, blockLen, leafLen, rounds } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen) { + if (this.leafHash) + super.update(this.leafHash.digest()); + else { + this.suffix = 0x06; // Its safe to change suffix here since its used only in digest() + super.update(new Uint8Array([3, 0, 0, 0, 0, 0, 0, 0])); + } + this.leafHash = new sha3_js_1.Keccak(blockLen, 0x0b, leafLen, false, rounds); + this.chunksDone++; + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + const chunk = data.subarray(pos, pos + take); + if (this.leafHash) + this.leafHash.update(chunk); + else + super.update(chunk); + this.chunkPos += take; + pos += take; + } + return this; + } + finish() { + if (this.finished) + return; + const { personalization } = this; + this.update(personalization).update(rightEncodeK12(personalization.length)); + // Leaf hash + if (this.leafHash) { + super.update(this.leafHash.digest()); + super.update(rightEncodeK12(this.chunksDone)); + super.update(new Uint8Array([0xff, 0xff])); + } + super.finish.call(this); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + // We cannot zero personalization buffer since it is user provided and we don't want to mutate user input + this.personalization = EMPTY; + } + _cloneInto(to) { + const { blockLen, leafLen, leafHash, outputLen, rounds } = this; + to || (to = new KangarooTwelve(blockLen, leafLen, outputLen, rounds, {})); + super._cloneInto(to); + if (leafHash) + to.leafHash = leafHash._cloneInto(to.leafHash); + to.personalization.set(this.personalization); + to.leafLen = this.leafLen; + to.chunkPos = this.chunkPos; + to.chunksDone = this.chunksDone; + return to; + } + clone() { + return this._cloneInto(); + } +} +// Default to 32 bytes, so it can be used without opts +exports.k12 = (() => (0, utils_js_1.wrapConstructorWithOpts)((opts = {}) => new KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts)))(); +// MarsupilamiFourteen +exports.m14 = (() => (0, utils_js_1.wrapConstructorWithOpts)((opts = {}) => new KangarooTwelve(136, 64, chooseLen(opts, 64), 14, opts)))(); +// https://keccak.team/files/CSF-0.1.pdf +// + https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG +class KeccakPRG extends sha3_js_1.Keccak { + constructor(capacity) { + (0, _assert_js_1.number)(capacity); + // Rho should be full bytes + if (capacity < 0 || capacity > 1600 - 10 || (1600 - capacity - 2) % 8) + throw new Error('KeccakPRG: Invalid capacity'); + // blockLen = rho in bytes + super((1600 - capacity - 2) / 8, 0, 0, true); + this.rate = 1600 - capacity; + this.posOut = Math.floor((this.rate + 7) / 8); + } + keccak() { + // Duplex padding + this.state[this.pos] ^= 0x01; + this.state[this.blockLen] ^= 0x02; // Rho is full bytes + super.keccak(); + this.pos = 0; + this.posOut = 0; + } + update(data) { + super.update(data); + this.posOut = this.blockLen; + return this; + } + feed(data) { + return this.update(data); + } + finish() { } + digestInto(_out) { + throw new Error('KeccakPRG: digest is not allowed, please use .fetch instead.'); + } + fetch(bytes) { + return this.xof(bytes); + } + // Ensure irreversibility (even if state leaked previous outputs cannot be computed) + forget() { + if (this.rate < 1600 / 2 + 1) + throw new Error('KeccakPRG: rate too low to use forget'); + this.keccak(); + for (let i = 0; i < this.blockLen; i++) + this.state[i] = 0; + this.pos = this.blockLen; + this.keccak(); + this.posOut = this.blockLen; + } + _cloneInto(to) { + const { rate } = this; + to || (to = new KeccakPRG(1600 - rate)); + super._cloneInto(to); + to.rate = rate; + return to; + } + clone() { + return this._cloneInto(); + } +} +const keccakprg = (capacity = 254) => new KeccakPRG(capacity); +exports.keccakprg = keccakprg; +//# sourceMappingURL=sha3-addons.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/sha3-addons.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/sha3-addons.js.map new file mode 100644 index 0000000..7232b4f --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/sha3-addons.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3-addons.js","sourceRoot":"","sources":["src/sha3-addons.ts"],"names":[],"mappings":";;;AAAA,6CAAsD;AACtD,yCAAyF;AACzF,uCAA8C;AAC9C,kCAAkC;AAClC,SAAS,UAAU,CAAC,CAAS;IAC3B,MAAM,GAAG,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/curves/node_modules/@noble/hashes/sha3.d.ts new file mode 100644 index 0000000..2107cf6 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/sha3.d.ts @@ -0,0 +1,97 @@ +import { Hash, Input, HashXOF } from './utils.js'; +export declare function keccakP(s: Uint32Array, rounds?: number): void; +export declare class Keccak extends Hash implements HashXOF { + blockLen: number; + suffix: number; + outputLen: number; + protected enableXOF: boolean; + protected rounds: number; + protected state: Uint8Array; + protected pos: number; + protected posOut: number; + protected finished: boolean; + protected state32: Uint32Array; + protected destroyed: boolean; + constructor(blockLen: number, suffix: number, outputLen: number, enableXOF?: boolean, rounds?: number); + protected keccak(): void; + update(data: Input): this; + protected finish(): void; + protected writeInto(out: Uint8Array): Uint8Array; + xofInto(out: Uint8Array): Uint8Array; + xof(bytes: number): Uint8Array; + digestInto(out: Uint8Array): Uint8Array; + digest(): Uint8Array; + destroy(): void; + _cloneInto(to?: Keccak): Keccak; +} +export declare const sha3_224: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +export declare const sha3_256: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const sha3_384: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const sha3_512: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const keccak_224: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +export declare const keccak_256: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const keccak_384: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const keccak_512: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export type ShakeOpts = { + dkLen?: number; +}; +export declare const shake128: { + (msg: Input, opts?: ShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: ShakeOpts): HashXOF>; +}; +export declare const shake256: { + (msg: Input, opts?: ShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: ShakeOpts): HashXOF>; +}; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/sha3.js b/node_modules/@noble/curves/node_modules/@noble/hashes/sha3.js new file mode 100644 index 0000000..e1b7530 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/sha3.js @@ -0,0 +1,213 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.shake256 = exports.shake128 = exports.keccak_512 = exports.keccak_384 = exports.keccak_256 = exports.keccak_224 = exports.sha3_512 = exports.sha3_384 = exports.sha3_256 = exports.sha3_224 = exports.Keccak = exports.keccakP = void 0; +const _assert_js_1 = require("./_assert.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. +// It's called a sponge function. +// Various per round constants calculations +const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []]; +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); +const _2n = /* @__PURE__ */ BigInt(2); +const _7n = /* @__PURE__ */ BigInt(7); +const _256n = /* @__PURE__ */ BigInt(256); +const _0x71n = /* @__PURE__ */ BigInt(0x71); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) + t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ (0, _u64_js_1.split)(_SHA3_IOTA, true); +// Left rotation (without 0, 32, 64) +const rotlH = (h, l, s) => (s > 32 ? (0, _u64_js_1.rotlBH)(h, l, s) : (0, _u64_js_1.rotlSH)(h, l, s)); +const rotlL = (h, l, s) => (s > 32 ? (0, _u64_js_1.rotlBL)(h, l, s) : (0, _u64_js_1.rotlSL)(h, l, s)); +// Same as keccakf1600, but allows to skip some rounds +function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) + B[x] = s[y + x]; + for (let x = 0; x < 10; x++) + s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} +exports.keccakP = keccakP; +class Keccak extends utils_js_1.Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + // Can be passed from user as dkLen + (0, _assert_js_1.number)(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = (0, utils_js_1.u32)(this.state); + } + keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + update(data) { + (0, _assert_js_1.exists)(this); + const { blockLen, state } = this; + data = (0, utils_js_1.toBytes)(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + writeInto(out) { + (0, _assert_js_1.exists)(this, false); + (0, _assert_js_1.bytes)(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) + throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes) { + (0, _assert_js_1.number)(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + (0, _assert_js_1.output)(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} +exports.Keccak = Keccak; +const gen = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapConstructor)(() => new Keccak(blockLen, suffix, outputLen)); +exports.sha3_224 = gen(0x06, 144, 224 / 8); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +exports.sha3_256 = gen(0x06, 136, 256 / 8); +exports.sha3_384 = gen(0x06, 104, 384 / 8); +exports.sha3_512 = gen(0x06, 72, 512 / 8); +exports.keccak_224 = gen(0x01, 144, 224 / 8); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +exports.keccak_256 = gen(0x01, 136, 256 / 8); +exports.keccak_384 = gen(0x01, 104, 384 / 8); +exports.keccak_512 = gen(0x01, 72, 512 / 8); +const genShake = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapXOFConstructorWithOpts)((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)); +exports.shake128 = genShake(0x1f, 168, 128 / 8); +exports.shake256 = genShake(0x1f, 136, 256 / 8); +//# sourceMappingURL=sha3.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/sha3.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/sha3.js.map new file mode 100644 index 0000000..fd68950 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/sha3.js.map @@ -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AAmB,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;AACxD,QAAA,QAAQ,GAAmB,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/sha512.d.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/sha512.d.ts new file mode 100644 index 0000000..b8ba9b0 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/sha512.d.ts @@ -0,0 +1,66 @@ +import { SHA2 } from './_sha2.js'; +export declare class SHA512 extends SHA2 { + Ah: number; + Al: number; + Bh: number; + Bl: number; + Ch: number; + Cl: number; + Dh: number; + Dl: number; + Eh: number; + El: number; + Fh: number; + Fl: number; + Gh: number; + Gl: number; + Hh: number; + Hl: number; + constructor(); + protected get(): [ + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number + ]; + protected set(Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number, Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +export declare const sha512: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha512_224: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha512_256: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha384: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/sha512.js b/node_modules/@noble/curves/node_modules/@noble/hashes/sha512.js new file mode 100644 index 0000000..1d3482a --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/sha512.js @@ -0,0 +1,235 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha384 = exports.sha512_256 = exports.sha512_224 = exports.sha512 = exports.SHA512 = void 0; +const _sha2_js_1 = require("./_sha2.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => _u64_js_1.default.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))))(); +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); +const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); +class SHA512 extends _sha2_js_1.SHA2 { + constructor() { + super(128, 64, 16, false); + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x6a09e667 | 0; + this.Al = 0xf3bcc908 | 0; + this.Bh = 0xbb67ae85 | 0; + this.Bl = 0x84caa73b | 0; + this.Ch = 0x3c6ef372 | 0; + this.Cl = 0xfe94f82b | 0; + this.Dh = 0xa54ff53a | 0; + this.Dl = 0x5f1d36f1 | 0; + this.Eh = 0x510e527f | 0; + this.El = 0xade682d1 | 0; + this.Fh = 0x9b05688c | 0; + this.Fl = 0x2b3e6c1f | 0; + this.Gh = 0x1f83d9ab | 0; + this.Gl = 0xfb41bd6b | 0; + this.Hh = 0x5be0cd19 | 0; + this.Hl = 0x137e2179 | 0; + } + // prettier-ignore + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = _u64_js_1.default.rotrSH(W15h, W15l, 1) ^ _u64_js_1.default.rotrSH(W15h, W15l, 8) ^ _u64_js_1.default.shrSH(W15h, W15l, 7); + const s0l = _u64_js_1.default.rotrSL(W15h, W15l, 1) ^ _u64_js_1.default.rotrSL(W15h, W15l, 8) ^ _u64_js_1.default.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = _u64_js_1.default.rotrSH(W2h, W2l, 19) ^ _u64_js_1.default.rotrBH(W2h, W2l, 61) ^ _u64_js_1.default.shrSH(W2h, W2l, 6); + const s1l = _u64_js_1.default.rotrSL(W2h, W2l, 19) ^ _u64_js_1.default.rotrBL(W2h, W2l, 61) ^ _u64_js_1.default.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = _u64_js_1.default.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = _u64_js_1.default.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = _u64_js_1.default.rotrSH(Eh, El, 14) ^ _u64_js_1.default.rotrSH(Eh, El, 18) ^ _u64_js_1.default.rotrBH(Eh, El, 41); + const sigma1l = _u64_js_1.default.rotrSL(Eh, El, 14) ^ _u64_js_1.default.rotrSL(Eh, El, 18) ^ _u64_js_1.default.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = _u64_js_1.default.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = _u64_js_1.default.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = _u64_js_1.default.rotrSH(Ah, Al, 28) ^ _u64_js_1.default.rotrBH(Ah, Al, 34) ^ _u64_js_1.default.rotrBH(Ah, Al, 39); + const sigma0l = _u64_js_1.default.rotrSL(Ah, Al, 28) ^ _u64_js_1.default.rotrBL(Ah, Al, 34) ^ _u64_js_1.default.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = _u64_js_1.default.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = _u64_js_1.default.add3L(T1l, sigma0l, MAJl); + Ah = _u64_js_1.default.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = _u64_js_1.default.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = _u64_js_1.default.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = _u64_js_1.default.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = _u64_js_1.default.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = _u64_js_1.default.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = _u64_js_1.default.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = _u64_js_1.default.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = _u64_js_1.default.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +exports.SHA512 = SHA512; +class SHA512_224 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x8c3d37c8 | 0; + this.Al = 0x19544da2 | 0; + this.Bh = 0x73e19966 | 0; + this.Bl = 0x89dcd4d6 | 0; + this.Ch = 0x1dfab7ae | 0; + this.Cl = 0x32ff9c82 | 0; + this.Dh = 0x679dd514 | 0; + this.Dl = 0x582f9fcf | 0; + this.Eh = 0x0f6d2b69 | 0; + this.El = 0x7bd44da8 | 0; + this.Fh = 0x77e36f73 | 0; + this.Fl = 0x04c48942 | 0; + this.Gh = 0x3f9d85a8 | 0; + this.Gl = 0x6a1d36c8 | 0; + this.Hh = 0x1112e6ad | 0; + this.Hl = 0x91d692a1 | 0; + this.outputLen = 28; + } +} +class SHA512_256 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x22312194 | 0; + this.Al = 0xfc2bf72c | 0; + this.Bh = 0x9f555fa3 | 0; + this.Bl = 0xc84c64c2 | 0; + this.Ch = 0x2393b86b | 0; + this.Cl = 0x6f53b151 | 0; + this.Dh = 0x96387719 | 0; + this.Dl = 0x5940eabd | 0; + this.Eh = 0x96283ee2 | 0; + this.El = 0xa88effe3 | 0; + this.Fh = 0xbe5e1e25 | 0; + this.Fl = 0x53863992 | 0; + this.Gh = 0x2b0199fc | 0; + this.Gl = 0x2c85b8aa | 0; + this.Hh = 0x0eb72ddc | 0; + this.Hl = 0x81c52ca2 | 0; + this.outputLen = 32; + } +} +class SHA384 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0xcbbb9d5d | 0; + this.Al = 0xc1059ed8 | 0; + this.Bh = 0x629a292a | 0; + this.Bl = 0x367cd507 | 0; + this.Ch = 0x9159015a | 0; + this.Cl = 0x3070dd17 | 0; + this.Dh = 0x152fecd8 | 0; + this.Dl = 0xf70e5939 | 0; + this.Eh = 0x67332667 | 0; + this.El = 0xffc00b31 | 0; + this.Fh = 0x8eb44a87 | 0; + this.Fl = 0x68581511 | 0; + this.Gh = 0xdb0c2e0d | 0; + this.Gl = 0x64f98fa7 | 0; + this.Hh = 0x47b5481d | 0; + this.Hl = 0xbefa4fa4 | 0; + this.outputLen = 48; + } +} +exports.sha512 = (0, utils_js_1.wrapConstructor)(() => new SHA512()); +exports.sha512_224 = (0, utils_js_1.wrapConstructor)(() => new SHA512_224()); +exports.sha512_256 = (0, utils_js_1.wrapConstructor)(() => new SHA512_256()); +exports.sha384 = (0, utils_js_1.wrapConstructor)(() => new SHA384()); +//# sourceMappingURL=sha512.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/sha512.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/sha512.js.map new file mode 100644 index 0000000..700a8e7 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/sha512.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha512.js","sourceRoot":"","sources":["src/sha512.ts"],"names":[],"mappings":";;;AAAA,yCAAkC;AAClC,uCAA4B;AAC5B,yCAA6C;AAE7C,0GAA0G;AAC1G,kBAAkB;AAClB,MAAM,CAAC,SAAS,EAAE,SAAS,CAAC,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,iBAAG,CAAC,KAAK,CAAC;IAC9D,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,E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GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QAIlB,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;IACtB,CAAC;CACF;AAEY,QAAA,MAAM,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC;AAC7D,QAAA,UAAU,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,CAAC;AACrE,QAAA,UAAU,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,CAAC;AACrE,QAAA,MAAM,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/src/_assert.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/src/_assert.ts new file mode 100644 index 0000000..11d28ea --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/src/_assert.ts @@ -0,0 +1,43 @@ +function number(n: number) { + if (!Number.isSafeInteger(n) || n < 0) throw new Error(`Wrong positive integer: ${n}`); +} + +function bool(b: boolean) { + if (typeof b !== 'boolean') throw new Error(`Expected boolean, not ${b}`); +} + +function bytes(b: Uint8Array | undefined, ...lengths: number[]) { + if (!(b instanceof Uint8Array)) throw new Error('Expected Uint8Array'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} + +type Hash = { + (data: Uint8Array): Uint8Array; + blockLen: number; + outputLen: number; + create: any; +}; +function hash(hash: Hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(hash.outputLen); + number(hash.blockLen); +} + +function exists(instance: any, checkFinished = true) { + if (instance.destroyed) throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called'); +} +function output(out: any, instance: any) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} + +export { number, bool, bytes, hash, exists, output }; + +const assert = { number, bool, bytes, hash, exists, output }; +export default assert; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/src/_blake2.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/src/_blake2.ts new file mode 100644 index 0000000..6aa4a74 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/src/_blake2.ts @@ -0,0 +1,128 @@ +import { number, exists, output } from './_assert.js'; +import { Hash, Input, toBytes, u32 } from './utils.js'; + +// Blake is based on ChaCha permutation. + +// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. +// prettier-ignore +export const SIGMA = /* @__PURE__ */ new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, +]); + +export type BlakeOpts = { + dkLen?: number; + key?: Input; + salt?: Input; + personalization?: Input; +}; + +export abstract class BLAKE2> extends Hash { + protected abstract compress(msg: Uint32Array, offset: number, isLast: boolean): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected buffer: Uint8Array; + protected buffer32: Uint32Array; + protected length: number = 0; + protected pos: number = 0; + protected finished = false; + protected destroyed = false; + + constructor( + readonly blockLen: number, + public outputLen: number, + opts: BlakeOpts = {}, + keyLen: number, + saltLen: number, + persLen: number + ) { + super(); + number(blockLen); + number(outputLen); + number(keyLen); + if (outputLen < 0 || outputLen > keyLen) throw new Error('outputLen bigger than keyLen'); + if (opts.key !== undefined && (opts.key.length < 1 || opts.key.length > keyLen)) + throw new Error(`key must be up 1..${keyLen} byte long or undefined`); + if (opts.salt !== undefined && opts.salt.length !== saltLen) + throw new Error(`salt must be ${saltLen} byte long or undefined`); + if (opts.personalization !== undefined && opts.personalization.length !== persLen) + throw new Error(`personalization must be ${persLen} byte long or undefined`); + this.buffer32 = u32((this.buffer = new Uint8Array(blockLen))); + } + update(data: Input) { + exists(this); + // Main difference with other hashes: there is flag for last block, + // so we cannot process current block before we know that there + // is the next one. This significantly complicates logic and reduces ability + // to do zero-copy processing + const { blockLen, buffer, buffer32 } = this; + data = toBytes(data); + const len = data.length; + const offset = data.byteOffset; + const buf = data.buffer; + for (let pos = 0; pos < len; ) { + // If buffer is full and we still have input (don't process last block, same as blake2s) + if (this.pos === blockLen) { + this.compress(buffer32, 0, false); + this.pos = 0; + } + const take = Math.min(blockLen - this.pos, len - pos); + const dataOffset = offset + pos; + // full block && aligned to 4 bytes && not last in input + if (take === blockLen && !(dataOffset % 4) && pos + take < len) { + const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4)); + for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) { + this.length += blockLen; + this.compress(data32, pos32, false); + } + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + this.length += take; + pos += take; + } + return this; + } + digestInto(out: Uint8Array) { + exists(this); + output(out, this); + const { pos, buffer32 } = this; + this.finished = true; + // Padding + this.buffer.subarray(pos).fill(0); + this.compress(buffer32, 0, true); + const out32 = u32(out); + this.get().forEach((v, i) => (out32[i] = v)); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to?: T): T { + const { buffer, length, finished, destroyed, outputLen, pos } = this; + to ||= new (this.constructor as any)({ dkLen: outputLen }) as T; + to.set(...this.get()); + to.length = length; + to.finished = finished; + to.destroyed = destroyed; + to.outputLen = outputLen; + to.buffer.set(buffer); + to.pos = pos; + return to; + } +} diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/src/_sha2.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/src/_sha2.ts new file mode 100644 index 0000000..bd99103 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/src/_sha2.ts @@ -0,0 +1,118 @@ +import { exists, output } from './_assert.js'; +import { Hash, createView, Input, toBytes } from './utils.js'; + +// Polyfill for Safari 14 +function setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void { + if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} + +// Base SHA2 class (RFC 6234) +export abstract class SHA2> extends Hash { + protected abstract process(buf: DataView, offset: number): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected abstract roundClean(): void; + // For partial updates less than block size + protected buffer: Uint8Array; + protected view: DataView; + protected finished = false; + protected length = 0; + protected pos = 0; + protected destroyed = false; + + constructor( + readonly blockLen: number, + public outputLen: number, + readonly padOffset: number, + readonly isLE: boolean + ) { + super(); + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data: Input): this { + exists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input, cast it to view and process + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out: Uint8Array) { + exists(this); + output(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + this.buffer.subarray(pos).fill(0); + // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) buffer[i] = 0; + // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to?: T): T { + to ||= new (this.constructor as any)() as T; + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) to.buffer.set(buffer); + return to; + } +} diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/src/_u64.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/src/_u64.ts new file mode 100644 index 0000000..efc55b4 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/src/_u64.ts @@ -0,0 +1,77 @@ +const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n = /* @__PURE__ */ BigInt(32); + +// We are not using BigUint64Array, because they are extremely slow as per 2022 +function fromBig(n: bigint, le = false) { + if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} + +function split(lst: bigint[], le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} + +const toBig = (h: number, l: number) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +// for Shift in [0, 32) +const shrSH = (h: number, _l: number, s: number) => h >>> s; +const shrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in [1, 32) +const rotrSH = (h: number, l: number, s: number) => (h >>> s) | (l << (32 - s)); +const rotrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h: number, l: number, s: number) => (h << (64 - s)) | (l >>> (s - 32)); +const rotrBL = (h: number, l: number, s: number) => (h >>> (s - 32)) | (l << (64 - s)); +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (_h: number, l: number) => l; +const rotr32L = (h: number, _l: number) => h; +// Left rotate for Shift in [1, 32) +const rotlSH = (h: number, l: number, s: number) => (h << s) | (l >>> (32 - s)); +const rotlSL = (h: number, l: number, s: number) => (l << s) | (h >>> (32 - s)); +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h: number, l: number, s: number) => (l << (s - 32)) | (h >>> (64 - s)); +const rotlBL = (h: number, l: number, s: number) => (h << (s - 32)) | (l >>> (64 - s)); + +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +function add(Ah: number, Al: number, Bh: number, Bl: number) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +// Addition with more than 2 elements +const add3L = (Al: number, Bl: number, Cl: number) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +const add3H = (low: number, Ah: number, Bh: number, Ch: number) => + (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +const add4L = (Al: number, Bl: number, Cl: number, Dl: number) => + (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +const add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => + (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +const add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number) => + (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +const add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => + (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; + +// prettier-ignore +export { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +export default u64; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/src/argon2.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/src/argon2.ts new file mode 100644 index 0000000..d727b0f --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/src/argon2.ts @@ -0,0 +1,374 @@ +import { number as assertNumber } from './_assert.js'; +import { Input, toBytes, u8, u32 } from './utils.js'; +import { blake2b } from './blake2b.js'; +import { add3H, add3L, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL } from './_u64.js'; + +// Experimental Argon2 RFC 9106 implementation. It may be removed at any time. +const enum Types { + Argond2d = 0, + Argon2i = 1, + Argon2id = 2, +} + +const ARGON2_SYNC_POINTS = 4; + +const toBytesOptional = (buf?: Input) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); + +function mul(a: number, b: number) { + const aL = a & 0xffff; + const aH = a >>> 16; + const bL = b & 0xffff; + const bH = b >>> 16; + const ll = Math.imul(aL, bL); + const hl = Math.imul(aH, bL); + const lh = Math.imul(aL, bH); + const hh = Math.imul(aH, bH); + const BUF = ((ll >>> 16) + (hl & 0xffff) + lh) | 0; + const h = ((hl >>> 16) + (BUF >>> 16) + hh) | 0; + return { h, l: (BUF << 16) | (ll & 0xffff) }; +} + +function relPos(areaSize: number, relativePos: number) { + // areaSize - 1 - ((areaSize * ((relativePos ** 2) >>> 32)) >>> 32) + return areaSize - 1 - mul(areaSize, mul(relativePos, relativePos).h).h; +} + +function mul2(a: number, b: number) { + // 2 * a * b (via shifts) + const { h, l } = mul(a, b); + return { h: ((h << 1) | (l >>> 31)) & 0xffff_ffff, l: (l << 1) & 0xffff_ffff }; +} + +function blamka(Ah: number, Al: number, Bh: number, Bl: number) { + const { h: Ch, l: Cl } = mul2(Al, Bl); + // A + B + (2 * A * B) + const Rll = add3L(Al, Bl, Cl); + return { h: add3H(Rll, Ah, Bh, Ch), l: Rll | 0 }; +} + +// Temporary block buffer +const BUF = new Uint32Array(256); + +function G(a: number, b: number, c: number, d: number) { + let Al = BUF[2*a], Ah = BUF[2*a + 1]; // prettier-ignore + let Bl = BUF[2*b], Bh = BUF[2*b + 1]; // prettier-ignore + let Cl = BUF[2*c], Ch = BUF[2*c + 1]; // prettier-ignore + let Dl = BUF[2*d], Dh = BUF[2*d + 1]; // prettier-ignore + + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: rotr32H(Dh, Dl), Dl: rotr32L(Dh, Dl) }); + + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: rotrSH(Bh, Bl, 24), Bl: rotrSL(Bh, Bl, 24) }); + + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: rotrSH(Dh, Dl, 16), Dl: rotrSL(Dh, Dl, 16) }); + + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: rotrBH(Bh, Bl, 63), Bl: rotrBL(Bh, Bl, 63) }); + + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} + +// prettier-ignore +function P( + v00: number, v01: number, v02: number, v03: number, v04: number, v05: number, v06: number, v07: number, + v08: number, v09: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, +) { + G(v00, v04, v08, v12); + G(v01, v05, v09, v13); + G(v02, v06, v10, v14); + G(v03, v07, v11, v15); + G(v00, v05, v10, v15); + G(v01, v06, v11, v12); + G(v02, v07, v08, v13); + G(v03, v04, v09, v14); +} + +function block(x: Uint32Array, xPos: number, yPos: number, outPos: number, needXor: boolean) { + for (let i = 0; i < 256; i++) BUF[i] = x[xPos + i] ^ x[yPos + i]; + + // columns + for (let i = 0; i < 128; i += 16) { + // prettier-ignore + P( + i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, + i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15 + ); + } + // rows + for (let i = 0; i < 16; i += 2) { + // prettier-ignore + P( + i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, + i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113 + ); + } + + if (needXor) for (let i = 0; i < 256; i++) x[outPos + i] ^= BUF[i] ^ x[xPos + i] ^ x[yPos + i]; + else for (let i = 0; i < 256; i++) x[outPos + i] = BUF[i] ^ x[xPos + i] ^ x[yPos + i]; +} + +// Variable-Length Hash Function H' +function Hp(A: Uint32Array, dkLen: number) { + const A8 = u8(A); + const T = new Uint32Array(1); + const T8 = u8(T); + T[0] = dkLen; + // Fast path + if (dkLen <= 64) return blake2b.create({ dkLen }).update(T8).update(A8).digest(); + const out = new Uint8Array(dkLen); + let V = blake2b.create({}).update(T8).update(A8).digest(); + let pos = 0; + // First block + out.set(V.subarray(0, 32)); + pos += 32; + // Rest blocks + for (; dkLen - pos > 64; pos += 32) out.set((V = blake2b(V)).subarray(0, 32), pos); + // Last block + out.set(blake2b(V, { dkLen: dkLen - pos }), pos); + return u32(out); +} + +function indexAlpha( + r: number, + s: number, + laneLen: number, + segmentLen: number, + index: number, + randL: number, + sameLane: boolean = false +) { + let area; + if (0 == r) { + if (0 == s) area = index - 1; + else if (sameLane) area = s * segmentLen + index - 1; + else area = s * segmentLen + (index == 0 ? -1 : 0); + } else if (sameLane) area = laneLen - segmentLen + index - 1; + else area = laneLen - segmentLen + (index == 0 ? -1 : 0); + const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0; + const rel = relPos(area, randL); + // NOTE: check about overflows here + // absPos = (startPos + relPos) % laneLength; + return (startPos + rel) % laneLen; +} + +// RFC 9106 +export type ArgonOpts = { + t: number; // Time cost, iterations count + m: number; // Memory cost (in KB) + p: number; // Parallelization parameter + version?: number; // Default: 0x13 (19) + key?: Input; // Optional key + personalization?: Input; // Optional arbitrary extra data + dkLen?: number; // Desired number of returned bytes + asyncTick?: number; // Maximum time in ms for which async function can block execution + maxmem?: number; + onProgress?: (progress: number) => void; +}; + +function argon2Init(type: Types, password: Input, salt: Input, opts: ArgonOpts) { + password = toBytes(password); + salt = toBytes(salt); + let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress } = { + ...opts, + version: opts.version || 0x13, + dkLen: opts.dkLen || 32, + maxmem: 2 ** 32, + }; + // Validation + assertNumber(p); + assertNumber(dkLen); + assertNumber(m); + assertNumber(t); + assertNumber(version); + if (dkLen < 4 || dkLen >= 2 ** 32) throw new Error('Argon2: dkLen should be at least 4 bytes'); + if (p < 1 || p >= 2 ** 32) throw new Error('Argon2: p (parallelism) should be at least 1'); + if (t < 1 || t >= 2 ** 32) throw new Error('Argon2: t (iterations) should be at least 1'); + if (m < 8 * p) throw new Error(`Argon2: memory should be at least 8*p bytes`); + if (version !== 16 && version !== 19) throw new Error(`Argon2: unknown version=${version}`); + password = toBytes(password); + if (password.length < 0 || password.length >= 2 ** 32) + throw new Error('Argon2: password should be less than 4 GB'); + salt = toBytes(salt); + if (salt.length < 8) throw new Error('Argon2: salt should be at least 8 bytes'); + key = toBytesOptional(key); + personalization = toBytesOptional(personalization); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + // Params + const lanes = p; + // m' = 4 * p * floor (m / 4p) + const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p)); + //q = m' / p columns + const laneLen = Math.floor(mP / p); + const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS); + // H0 + const h = blake2b.create({}); + const BUF = new Uint32Array(1); + const BUF8 = u8(BUF); + for (const i of [p, dkLen, m, t, version, type]) { + if (i < 0 || i >= 2 ** 32) throw new Error(`Argon2: wrong parameter=${i}, expected uint32`); + BUF[0] = i; + h.update(BUF8); + } + for (let i of [password, salt, key, personalization]) { + BUF[0] = i.length; + h.update(BUF8).update(i); + } + const H0 = new Uint32Array(18); + const H0_8 = u8(H0); + h.digestInto(H0_8); + + // 256 u32 = 1024 (BLOCK_SIZE) + const memUsed = mP * 256; + if (memUsed < 0 || memUsed >= 2 ** 32 || memUsed > maxmem) { + throw new Error( + `Argon2: wrong params (memUsed=${memUsed} maxmem=${maxmem}), should be less than 2**32` + ); + } + const B = new Uint32Array(memUsed); + // Fill first blocks + for (let l = 0; l < p; l++) { + const i = 256 * laneLen * l; + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + H0[17] = l; + H0[16] = 0; + B.set(Hp(H0, 1024), i); + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + H0[16] = 1; + B.set(Hp(H0, 1024), i + 256); + } + let perBlock = () => {}; + if (onProgress) { + const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlock / 10000), 1); + let blockCnt = 0; + perBlock = () => { + blockCnt++; + if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock)) + onProgress(blockCnt / totalBlock); + }; + } + return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock }; +} + +function argon2Output(B: Uint32Array, p: number, laneLen: number, dkLen: number) { + const B_final = new Uint32Array(256); + for (let l = 0; l < p; l++) + for (let j = 0; j < 256; j++) B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j]; + return u8(Hp(B_final, dkLen)); +} + +function processBlock( + B: Uint32Array, + address: Uint32Array, + l: number, + r: number, + s: number, + index: number, + laneLen: number, + segmentLen: number, + lanes: number, + offset: number, + prev: number, + dataIndependent: boolean, + needXor: boolean +) { + if (offset % laneLen) prev = offset - 1; + let randL, randH; + if (dataIndependent) { + if (index % 128 === 0) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + randL = address[2 * (index % 128)]; + randH = address[2 * (index % 128) + 1]; + } else { + const T = 256 * prev; + randL = B[T]; + randH = B[T + 1]; + } + // address block + const refLane = r === 0 && s === 0 ? l : randH % lanes; + const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l); + const refBlock = laneLen * refLane + refPos; + // B[i][j] = G(B[i][j-1], B[l][z]) + block(B, 256 * prev, 256 * refBlock, offset * 256, needXor); +} + +function argon2(type: Types, password: Input, salt: Input, opts: ArgonOpts) { + const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init( + type, + password, + salt, + opts + ); + // Pre-loop setup + // [address, input, zero_block] format so we can pass single U32 to block function + const address = new Uint32Array(3 * 256); + address[256 + 6] = mP; + address[256 + 8] = t; + address[256 + 10] = type; + for (let r = 0; r < t; r++) { + const needXor = r !== 0 && version === 0x13; + address[256 + 0] = r; + for (let s = 0; s < ARGON2_SYNC_POINTS; s++) { + address[256 + 4] = s; + const dataIndependent = type == Types.Argon2i || (type == Types.Argon2id && r === 0 && s < 2); + for (let l = 0; l < p; l++) { + address[256 + 2] = l; + address[256 + 12] = 0; + let startPos = 0; + if (r === 0 && s === 0) { + startPos = 2; + if (dataIndependent) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + } + // current block postion + let offset = l * laneLen + s * segmentLen + startPos; + // previous block position + let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1; + for (let index = startPos; index < segmentLen; index++, offset++, prev++) { + perBlock(); + processBlock( + B, + address, + l, + r, + s, + index, + laneLen, + segmentLen, + lanes, + offset, + prev, + dataIndependent, + needXor + ); + } + } + } + } + return argon2Output(B, p, laneLen, dkLen); +} + +export const argon2d = (password: Input, salt: Input, opts: ArgonOpts) => + argon2(Types.Argond2d, password, salt, opts); +export const argon2i = (password: Input, salt: Input, opts: ArgonOpts) => + argon2(Types.Argon2i, password, salt, opts); +export const argon2id = (password: Input, salt: Input, opts: ArgonOpts) => + argon2(Types.Argon2id, password, salt, opts); diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/src/blake2b.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/src/blake2b.ts new file mode 100644 index 0000000..5784742 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/src/blake2b.ts @@ -0,0 +1,205 @@ +import { BLAKE2, BlakeOpts, SIGMA } from './_blake2.js'; +import u64 from './_u64.js'; +import { toBytes, u32, wrapConstructorWithOpts } from './utils.js'; + +// Same as SHA-512 but LE +// prettier-ignore +const IV = /* @__PURE__ */ new Uint32Array([ + 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, + 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19 +]); +// Temporary buffer +const BUF = /* @__PURE__ */ new Uint32Array(32); + +// Mixing function G splitted in two halfs +function G1(a: number, b: number, c: number, d: number, msg: Uint32Array, x: number) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 32) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 24) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} + +function G2(a: number, b: number, c: number, d: number, msg: Uint32Array, x: number) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 16) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 63) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} + +class BLAKE2b extends BLAKE2 { + // Same as SHA-512, but LE + private v0l = IV[0] | 0; + private v0h = IV[1] | 0; + private v1l = IV[2] | 0; + private v1h = IV[3] | 0; + private v2l = IV[4] | 0; + private v2h = IV[5] | 0; + private v3l = IV[6] | 0; + private v3h = IV[7] | 0; + private v4l = IV[8] | 0; + private v4h = IV[9] | 0; + private v5l = IV[10] | 0; + private v5h = IV[11] | 0; + private v6l = IV[12] | 0; + private v6h = IV[13] | 0; + private v7l = IV[14] | 0; + private v7h = IV[15] | 0; + + constructor(opts: BlakeOpts = {}) { + super(128, opts.dkLen === undefined ? 64 : opts.dkLen, opts, 64, 16, 16); + const keyLength = opts.key ? opts.key.length : 0; + this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4l ^= salt[0]; + this.v4h ^= salt[1]; + this.v5l ^= salt[2]; + this.v5h ^= salt[3]; + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6l ^= pers[0]; + this.v6h ^= pers[1]; + this.v7l ^= pers[2]; + this.v7h ^= pers[3]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + // prettier-ignore + protected get(): [ + number, number, number, number, number, number, number, number, + number, number, number, number, number, number, number, number + ] { + let {v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h} = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + protected set( + v0l: number, v0h: number, v1l: number, v1h: number, + v2l: number, v2h: number, v3l: number, v3h: number, + v4l: number, v4h: number, v5l: number, v5h: number, + v6l: number, v6h: number, v7l: number, v7h: number + ) { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + protected compress(msg: Uint32Array, offset: number, isLast: boolean) { + this.get().forEach((v, i) => (BUF[i] = v)); // First half from state. + BUF.set(IV, 16); // Second half from IV. + let { h, l } = u64.fromBig(BigInt(this.length)); + BUF[24] = IV[8] ^ l; // Low word of the offset. + BUF[25] = IV[9] ^ h; // High word. + // Invert all bits for last block + if (isLast) { + BUF[28] = ~BUF[28]; + BUF[29] = ~BUF[29]; + } + let j = 0; + const s = SIGMA; + for (let i = 0; i < 12; i++) { + G1(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G2(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G1(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G2(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G1(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G2(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G1(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G2(3, 7, 11, 15, msg, offset + 2 * s[j++]); + + G1(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G2(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G1(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G2(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G1(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G2(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G1(3, 4, 9, 14, msg, offset + 2 * s[j++]); + G2(3, 4, 9, 14, msg, offset + 2 * s[j++]); + } + this.v0l ^= BUF[0] ^ BUF[16]; + this.v0h ^= BUF[1] ^ BUF[17]; + this.v1l ^= BUF[2] ^ BUF[18]; + this.v1h ^= BUF[3] ^ BUF[19]; + this.v2l ^= BUF[4] ^ BUF[20]; + this.v2h ^= BUF[5] ^ BUF[21]; + this.v3l ^= BUF[6] ^ BUF[22]; + this.v3h ^= BUF[7] ^ BUF[23]; + this.v4l ^= BUF[8] ^ BUF[24]; + this.v4h ^= BUF[9] ^ BUF[25]; + this.v5l ^= BUF[10] ^ BUF[26]; + this.v5h ^= BUF[11] ^ BUF[27]; + this.v6l ^= BUF[12] ^ BUF[28]; + this.v6h ^= BUF[13] ^ BUF[29]; + this.v7l ^= BUF[14] ^ BUF[30]; + this.v7h ^= BUF[15] ^ BUF[31]; + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} + +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2b = /* @__PURE__ */ wrapConstructorWithOpts( + (opts) => new BLAKE2b(opts) +); diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/src/blake2s.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/src/blake2s.ts new file mode 100644 index 0000000..a609886 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/src/blake2s.ts @@ -0,0 +1,136 @@ +import { BLAKE2, BlakeOpts, SIGMA } from './_blake2.js'; +import { fromBig } from './_u64.js'; +import { rotr, toBytes, wrapConstructorWithOpts, u32 } from './utils.js'; + +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19) +// same as SHA-256 +// prettier-ignore +export const IV = /* @__PURE__ */new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]); + +// Mixing function G splitted in two halfs +function G1(a: number, b: number, c: number, d: number, x: number) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 16); + c = (c + d) | 0; + b = rotr(b ^ c, 12); + return { a, b, c, d }; +} + +function G2(a: number, b: number, c: number, d: number, x: number) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 8); + c = (c + d) | 0; + b = rotr(b ^ c, 7); + return { a, b, c, d }; +} +// prettier-ignore +export function compress(s: Uint8Array, offset: number, msg: Uint32Array, rounds: number, + v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, + v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, +) { + let j = 0; + for (let i = 0; i < rounds; i++) { + ({ a: v0, b: v4, c: v8, d: v12 } = G1(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v0, b: v4, c: v8, d: v12 } = G2(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G1(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G2(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G1(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G2(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G1(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G2(v3, v7, v11, v15, msg[offset + s[j++]])); + + ({ a: v0, b: v5, c: v10, d: v15 } = G1(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G2(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G1(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G2(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G1(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G2(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G1(v3, v4, v9, v14, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G2(v3, v4, v9, v14, msg[offset + s[j++]])); + } + return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; +} + +class BLAKE2s extends BLAKE2 { + // Internal state, same as SHA-256 + private v0 = IV[0] | 0; + private v1 = IV[1] | 0; + private v2 = IV[2] | 0; + private v3 = IV[3] | 0; + private v4 = IV[4] | 0; + private v5 = IV[5] | 0; + private v6 = IV[6] | 0; + private v7 = IV[7] | 0; + + constructor(opts: BlakeOpts = {}) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, opts, 32, 8, 8); + const keyLength = opts.key ? opts.key.length : 0; + this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4 ^= salt[0]; + this.v5 ^= salt[1]; + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6 ^= pers[0]; + this.v7 ^= pers[1]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + protected get(): [number, number, number, number, number, number, number, number] { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + protected set( + v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number + ) { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + protected compress(msg: Uint32Array, offset: number, isLast: boolean) { + const { h, l } = fromBig(BigInt(this.length)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = + compress( + SIGMA, offset, msg, 10, + this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, + IV[0], IV[1], IV[2], IV[3], l ^ IV[4], h ^ IV[5], isLast ? ~IV[6] : IV[6], IV[7] + ); + this.v0 ^= v0 ^ v8; + this.v1 ^= v1 ^ v9; + this.v2 ^= v2 ^ v10; + this.v3 ^= v3 ^ v11; + this.v4 ^= v4 ^ v12; + this.v5 ^= v5 ^ v13; + this.v6 ^= v6 ^ v14; + this.v7 ^= v7 ^ v15; + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } +} + +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2s = /* @__PURE__ */ wrapConstructorWithOpts( + (opts) => new BLAKE2s(opts) +); diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/src/blake3.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/src/blake3.ts new file mode 100644 index 0000000..01d7d54 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/src/blake3.ts @@ -0,0 +1,250 @@ +import { bytes, exists, number, output } from './_assert.js'; +import { fromBig } from './_u64.js'; +import { BLAKE2 } from './_blake2.js'; +import { compress, IV } from './blake2s.js'; +import { Input, u8, u32, toBytes, HashXOF, wrapXOFConstructorWithOpts } from './utils.js'; + +// Blake3 is single-option Blake2 with reduced security (round count). + +// Flag bitset +const enum Flags { + CHUNK_START = 1 << 0, + CHUNK_END = 1 << 1, + PARENT = 1 << 2, + ROOT = 1 << 3, + KEYED_HASH = 1 << 4, + DERIVE_KEY_CONTEXT = 1 << 5, + DERIVE_KEY_MATERIAL = 1 << 6, +} + +const SIGMA: Uint8Array = /* @__PURE__ */ (() => { + const Id = Array.from({ length: 16 }, (_, i) => i); + const permute = (arr: number[]) => + [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]); + const res: number[] = []; + for (let i = 0, v = Id; i < 7; i++, v = permute(v)) res.push(...v); + return Uint8Array.from(res); +})(); + +// - key: is 256-bit key +// - context: string should be hardcoded, globally unique, and application - specific. +// A good default format for the context string is "[application] [commit timestamp] [purpose]" +// - Only one of 'key' (keyed mode) or 'context' (derive key mode) can be used at same time +export type Blake3Opts = { dkLen?: number; key?: Input; context?: Input }; + +// Why is this so slow? It should be 6x faster than blake2b. +// - There is only 30% reduction in number of rounds from blake2s +// - This function uses tree mode to achive parallelisation via SIMD and threading, +// however in JS we don't have threads and SIMD, so we get only overhead from tree structure +// - It is possible to speed it up via Web Workers, hovewer it will make code singnificantly more +// complicated, which we are trying to avoid, since this library is intended to be used +// for cryptographic purposes. Also, parallelization happens only on chunk level (1024 bytes), +// which won't really benefit small inputs. +class BLAKE3 extends BLAKE2 implements HashXOF { + private IV: Uint32Array; + private flags = 0 | 0; + private state: Uint32Array; + private chunkPos = 0; // Position of current block in chunk + private chunksDone = 0; // How many chunks we already have + private stack: Uint32Array[] = []; + // Output + private posOut = 0; + private bufferOut32 = new Uint32Array(16); + private bufferOut: Uint8Array; + private chunkOut = 0; // index of output chunk + private enableXOF = true; + + constructor(opts: Blake3Opts = {}, flags = 0) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, {}, Number.MAX_SAFE_INTEGER, 0, 0); + this.outputLen = opts.dkLen === undefined ? 32 : opts.dkLen; + number(this.outputLen); + if (opts.key !== undefined && opts.context !== undefined) + throw new Error('Blake3: only key or context can be specified at same time'); + else if (opts.key !== undefined) { + const key = toBytes(opts.key).slice(); + if (key.length !== 32) throw new Error('Blake3: key should be 32 byte'); + this.IV = u32(key); + this.flags = flags | Flags.KEYED_HASH; + } else if (opts.context !== undefined) { + const context_key = new BLAKE3({ dkLen: 32 }, Flags.DERIVE_KEY_CONTEXT) + .update(opts.context) + .digest(); + this.IV = u32(context_key); + this.flags = flags | Flags.DERIVE_KEY_MATERIAL; + } else { + this.IV = IV.slice(); + this.flags = flags; + } + this.state = this.IV.slice(); + this.bufferOut = u8(this.bufferOut32); + } + // Unused + protected get() { + return []; + } + protected set() {} + private b2Compress(counter: number, flags: number, buf: Uint32Array, bufPos: number = 0) { + const { state: s, pos } = this; + const { h, l } = fromBig(BigInt(counter), true); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = + compress( + SIGMA, bufPos, buf, 7, + s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], + IV[0], IV[1], IV[2], IV[3], h, l, pos, flags + ); + s[0] = v0 ^ v8; + s[1] = v1 ^ v9; + s[2] = v2 ^ v10; + s[3] = v3 ^ v11; + s[4] = v4 ^ v12; + s[5] = v5 ^ v13; + s[6] = v6 ^ v14; + s[7] = v7 ^ v15; + } + protected compress(buf: Uint32Array, bufPos: number = 0, isLast: boolean = false) { + // Compress last block + let flags = this.flags; + if (!this.chunkPos) flags |= Flags.CHUNK_START; + if (this.chunkPos === 15 || isLast) flags |= Flags.CHUNK_END; + if (!isLast) this.pos = this.blockLen; + this.b2Compress(this.chunksDone, flags, buf, bufPos); + this.chunkPos += 1; + // If current block is last in chunk (16 blocks), then compress chunks + if (this.chunkPos === 16 || isLast) { + let chunk = this.state; + this.state = this.IV.slice(); + // If not the last one, compress only when there are trailing zeros in chunk counter + // chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed. + // 1 (001) - leaf not finished (just push current chunk to stack) + // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back) + // 3 (011) - last leaf not finished + // 4 (100) - leafs finished at depth=1 and depth=2 + for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) { + if (!(last = this.stack.pop())) break; + this.buffer32.set(last, 0); + this.buffer32.set(chunk, 8); + this.pos = this.blockLen; + this.b2Compress(0, this.flags | Flags.PARENT, this.buffer32, 0); + chunk = this.state; + this.state = this.IV.slice(); + } + this.chunksDone++; + this.chunkPos = 0; + this.stack.push(chunk); + } + this.pos = 0; + } + _cloneInto(to?: BLAKE3): BLAKE3 { + to = super._cloneInto(to) as BLAKE3; + const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this; + to.state.set(state.slice()); + to.stack = stack.map((i) => Uint32Array.from(i)); + to.IV.set(IV); + to.flags = flags; + to.chunkPos = chunkPos; + to.chunksDone = chunksDone; + to.posOut = posOut; + to.chunkOut = chunkOut; + to.enableXOF = this.enableXOF; + to.bufferOut32.set(this.bufferOut32); + return to; + } + destroy() { + this.destroyed = true; + this.state.fill(0); + this.buffer32.fill(0); + this.IV.fill(0); + this.bufferOut32.fill(0); + for (let i of this.stack) i.fill(0); + } + // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8) + private b2CompressOut() { + const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this; + const { h, l } = fromBig(BigInt(this.chunkOut++)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = + compress( + SIGMA, 0, buffer32, 7, + s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], + IV[0], IV[1], IV[2], IV[3], l, h, pos, flags + ); + out32[0] = v0 ^ v8; + out32[1] = v1 ^ v9; + out32[2] = v2 ^ v10; + out32[3] = v3 ^ v11; + out32[4] = v4 ^ v12; + out32[5] = v5 ^ v13; + out32[6] = v6 ^ v14; + out32[7] = v7 ^ v15; + out32[8] = s[0] ^ v8; + out32[9] = s[1] ^ v9; + out32[10] = s[2] ^ v10; + out32[11] = s[3] ^ v11; + out32[12] = s[4] ^ v12; + out32[13] = s[5] ^ v13; + out32[14] = s[6] ^ v14; + out32[15] = s[7] ^ v15; + this.posOut = 0; + } + protected finish() { + if (this.finished) return; + this.finished = true; + // Padding + this.buffer.fill(0, this.pos); + // Process last chunk + let flags = this.flags | Flags.ROOT; + if (this.stack.length) { + flags |= Flags.PARENT; + this.compress(this.buffer32, 0, true); + this.chunksDone = 0; + this.pos = this.blockLen; + } else { + flags |= (!this.chunkPos ? Flags.CHUNK_START : 0) | Flags.CHUNK_END; + } + this.flags = flags; + this.b2CompressOut(); + } + private writeInto(out: Uint8Array) { + exists(this, false); + bytes(out); + this.finish(); + const { blockLen, bufferOut } = this; + for (let pos = 0, len = out.length; pos < len; ) { + if (this.posOut >= blockLen) this.b2CompressOut(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out: Uint8Array): Uint8Array { + if (!this.enableXOF) throw new Error('XOF is not possible after digest call'); + return this.writeInto(out); + } + xof(bytes: number): Uint8Array { + number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out: Uint8Array) { + output(out, this); + if (this.finished) throw new Error('digest() was already called'); + this.enableXOF = false; + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } +} + +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +export const blake3 = /* @__PURE__ */ wrapXOFConstructorWithOpts( + (opts) => new BLAKE3(opts) +); diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/src/crypto.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/src/crypto.ts new file mode 100644 index 0000000..eaea6be --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/src/crypto.ts @@ -0,0 +1,5 @@ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +declare const globalThis: Record | undefined; +export const crypto = + typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/src/cryptoNode.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/src/cryptoNode.ts new file mode 100644 index 0000000..6fdba9e --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/src/cryptoNode.ts @@ -0,0 +1,7 @@ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +// The file will throw on node.js 14 and earlier. +// @ts-ignore +import * as nc from 'node:crypto'; +export const crypto = + nc && typeof nc === 'object' && 'webcrypto' in nc ? (nc.webcrypto as any) : undefined; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/src/eskdf.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/src/eskdf.ts new file mode 100644 index 0000000..b4c224b --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/src/eskdf.ts @@ -0,0 +1,183 @@ +import { bytes as assertBytes } from './_assert.js'; +import { hkdf } from './hkdf.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 as _pbkdf2 } from './pbkdf2.js'; +import { scrypt as _scrypt } from './scrypt.js'; +import { bytesToHex, createView, hexToBytes, toBytes } from './utils.js'; + +// A tiny KDF for various applications like AES key-gen. +// Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure". +// Which is good enough: assume sha2-256 retained preimage resistance. + +const SCRYPT_FACTOR = 2 ** 19; +const PBKDF2_FACTOR = 2 ** 17; + +// Scrypt KDF +export function scrypt(password: string, salt: string): Uint8Array { + return _scrypt(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 }); +} + +// PBKDF2-HMAC-SHA256 +export function pbkdf2(password: string, salt: string): Uint8Array { + return _pbkdf2(sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 }); +} + +// Combines two 32-byte byte arrays +function xor32(a: Uint8Array, b: Uint8Array): Uint8Array { + assertBytes(a, 32); + assertBytes(b, 32); + const arr = new Uint8Array(32); + for (let i = 0; i < 32; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} + +function strHasLength(str: string, min: number, max: number): boolean { + return typeof str === 'string' && str.length >= min && str.length <= max; +} + +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +export function deriveMainSeed(username: string, password: string): Uint8Array { + if (!strHasLength(username, 8, 255)) throw new Error('invalid username'); + if (!strHasLength(password, 8, 255)) throw new Error('invalid password'); + const scr = scrypt(password + '\u{1}', username + '\u{1}'); + const pbk = pbkdf2(password + '\u{2}', username + '\u{2}'); + const res = xor32(scr, pbk); + scr.fill(0); + pbk.fill(0); + return res; +} + +type AccountID = number | string; + +/** + * Converts protocol & accountId pair to HKDF salt & info params. + */ +function getSaltInfo(protocol: string, accountId: AccountID = 0) { + // Note that length here also repeats two lines below + // We do an additional length check here to reduce the scope of DoS attacks + if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) { + throw new Error('invalid protocol'); + } + + // Allow string account ids for some protocols + const allowsStr = /^password\d{0,3}|ssh|tor|file$/.test(protocol); + let salt: Uint8Array; // Extract salt. Default is undefined. + if (typeof accountId === 'string') { + if (!allowsStr) throw new Error('accountId must be a number'); + if (!strHasLength(accountId, 1, 255)) throw new Error('accountId must be valid string'); + salt = toBytes(accountId); + } else if (Number.isSafeInteger(accountId)) { + if (accountId < 0 || accountId > 2 ** 32 - 1) throw new Error('invalid accountId'); + // Convert to Big Endian Uint32 + salt = new Uint8Array(4); + createView(salt).setUint32(0, accountId, false); + } else { + throw new Error(`accountId must be a number${allowsStr ? ' or string' : ''}`); + } + const info = toBytes(protocol); + return { salt, info }; +} + +type OptsLength = { keyLength: number }; +type OptsMod = { modulus: bigint }; +type KeyOpts = undefined | OptsLength | OptsMod; + +function countBytes(num: bigint): number { + if (typeof num !== 'bigint' || num <= BigInt(128)) throw new Error('invalid number'); + return Math.ceil(num.toString(2).length / 8); +} + +/** + * Parses keyLength and modulus options to extract length of result key. + * If modulus is used, adds 64 bits to it as per FIPS 186 B.4.1 to combat modulo bias. + */ +function getKeyLength(options: KeyOpts): number { + if (!options || typeof options !== 'object') return 32; + const hasLen = 'keyLength' in options; + const hasMod = 'modulus' in options; + if (hasLen && hasMod) throw new Error('cannot combine keyLength and modulus options'); + if (!hasLen && !hasMod) throw new Error('must have either keyLength or modulus option'); + // FIPS 186 B.4.1 requires at least 64 more bits + const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength; + if (!(typeof l === 'number' && l >= 16 && l <= 8192)) throw new Error('invalid keyLength'); + return l; +} + +/** + * Converts key to bigint and divides it by modulus. Big Endian. + * Implements FIPS 186 B.4.1, which removes 0 and modulo bias from output. + */ +function modReduceKey(key: Uint8Array, modulus: bigint): Uint8Array { + const _1 = BigInt(1); + const num = BigInt('0x' + bytesToHex(key)); // check for ui8a, then bytesToNumber() + const res = (num % (modulus - _1)) + _1; // Remove 0 from output + if (res < _1) throw new Error('expected positive number'); // Guard against bad values + const len = key.length - 8; // FIPS requires 64 more bits = 8 bytes + const hex = res.toString(16).padStart(len * 2, '0'); // numberToHex() + const bytes = hexToBytes(hex); + if (bytes.length !== len) throw new Error('invalid length of result key'); + return bytes; +} + +// We are not using classes because constructor cannot be async +type ESKDF = Promise< + Readonly<{ + /** + * Derives a child key. Child key will not be associated with any + * other child key because of properties of underlying KDF. + * + * @param protocol - 3-15 character protocol name + * @param accountId - numeric identifier of account + * @param options - `keyLength: 64` or `modulus: 41920438n` + * @example deriveChildKey('aes', 0) + */ + deriveChildKey: (protocol: string, accountId: AccountID, options?: KeyOpts) => Uint8Array; + /** + * Deletes the main seed from eskdf instance + */ + expire: () => void; + /** + * Account fingerprint + */ + fingerprint: string; + }> +>; + +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +export async function eskdf(username: string, password: string): ESKDF { + // We are using closure + object instead of class because + // we want to make `seed` non-accessible for any external function. + let seed: Uint8Array | undefined = deriveMainSeed(username, password); + + function deriveCK(protocol: string, accountId: AccountID = 0, options?: KeyOpts): Uint8Array { + assertBytes(seed, 32); + const { salt, info } = getSaltInfo(protocol, accountId); // validate protocol & accountId + const keyLength = getKeyLength(options); // validate options + const key = hkdf(sha256, seed!, salt, info, keyLength); + // Modulus has already been validated + return options && 'modulus' in options ? modReduceKey(key, options.modulus) : key; + } + function expire() { + if (seed) seed.fill(1); + seed = undefined; + } + // prettier-ignore + const fingerprint = Array.from(deriveCK('fingerprint', 0)) + .slice(0, 6) + .map((char) => char.toString(16).padStart(2, '0').toUpperCase()) + .join(':'); + return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint }); +} diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/src/hkdf.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/src/hkdf.ts new file mode 100644 index 0000000..6d880d1 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/src/hkdf.ts @@ -0,0 +1,79 @@ +import { hash as assertHash, number as assertNumber } from './_assert.js'; +import { CHash, Input, toBytes } from './utils.js'; +import { hmac } from './hmac.js'; + +// HKDF (RFC 5869) +// https://soatok.blog/2021/11/17/understanding-hkdf/ + +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +export function extract(hash: CHash, ikm: Input, salt?: Input) { + assertHash(hash); + // NOTE: some libraries treat zero-length array as 'not provided'; + // we don't, since we have undefined as 'not provided' + // https://github.com/RustCrypto/KDFs/issues/15 + if (salt === undefined) salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros + return hmac(hash, toBytes(salt), toBytes(ikm)); +} + +// HKDF-Expand(PRK, info, L) -> OKM +const HKDF_COUNTER = /* @__PURE__ */ new Uint8Array([0]); +const EMPTY_BUFFER = /* @__PURE__ */ new Uint8Array(); + +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +export function expand(hash: CHash, prk: Input, info?: Input, length: number = 32) { + assertHash(hash); + assertNumber(length); + if (length > 255 * hash.outputLen) throw new Error('Length should be <= 255*HashLen'); + const blocks = Math.ceil(length / hash.outputLen); + if (info === undefined) info = EMPTY_BUFFER; + // first L(ength) octets of T + const okm = new Uint8Array(blocks * hash.outputLen); + // Re-use HMAC instance between blocks + const HMAC = hmac.create(hash, prk); + const HMACTmp = HMAC._cloneInto(); + const T = new Uint8Array(HMAC.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + // T(0) = empty string (zero length) + // T(N) = HMAC-Hash(PRK, T(N-1) | info | N) + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T) + .update(info) + .update(HKDF_COUNTER) + .digestInto(T); + okm.set(T, hash.outputLen * counter); + HMAC._cloneInto(HMACTmp); + } + HMAC.destroy(); + HMACTmp.destroy(); + T.fill(0); + HKDF_COUNTER.fill(0); + return okm.slice(0, length); +} + +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +export const hkdf = ( + hash: CHash, + ikm: Input, + salt: Input | undefined, + info: Input | undefined, + length: number +) => expand(hash, extract(hash, ikm, salt), info, length); diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/src/hmac.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/src/hmac.ts new file mode 100644 index 0000000..bebf4b3 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/src/hmac.ts @@ -0,0 +1,81 @@ +import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js'; +import { Hash, CHash, Input, toBytes } from './utils.js'; +// HMAC (RFC 2104) +export class HMAC> extends Hash> { + oHash: T; + iHash: T; + blockLen: number; + outputLen: number; + private finished = false; + private destroyed = false; + + constructor(hash: CHash, _key: Input) { + super(); + assertHash(hash); + const key = toBytes(_key); + this.iHash = hash.create() as T; + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash.create() as T; + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf: Input) { + assertExists(this); + this.iHash.update(buf); + return this; + } + digestInto(out: Uint8Array) { + assertExists(this); + assertBytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to?: HMAC): HMAC { + // Create new instance without calling constructor since key already in state and we don't know it. + to ||= Object.create(Object.getPrototypeOf(this), {}); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to as this; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} + +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +export const hmac = (hash: CHash, key: Input, message: Input): Uint8Array => + new HMAC(hash, key).update(message).digest(); +hmac.create = (hash: CHash, key: Input) => new HMAC(hash, key); diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/src/index.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/src/index.ts new file mode 100644 index 0000000..1505776 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/src/index.ts @@ -0,0 +1 @@ +throw new Error('noble-hashes have no entry-point: consult README for usage'); diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/src/pbkdf2.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/src/pbkdf2.ts new file mode 100644 index 0000000..b5f7e6a --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/src/pbkdf2.ts @@ -0,0 +1,97 @@ +import { hash as assertHash, number as assertNumber } from './_assert.js'; +import { hmac } from './hmac.js'; +import { Hash, CHash, Input, createView, toBytes, checkOpts, asyncLoop } from './utils.js'; + +// PBKDF (RFC 2898) +export type Pbkdf2Opt = { + c: number; // Iterations + dkLen?: number; // Desired key length in bytes (Intended output length in octets of the derived key + asyncTick?: number; // Maximum time in ms for which async function can block execution +}; +// Common prologue and epilogue for sync/async functions +function pbkdf2Init(hash: CHash, _password: Input, _salt: Input, _opts: Pbkdf2Opt) { + assertHash(hash); + const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + assertNumber(c); + assertNumber(dkLen); + assertNumber(asyncTick); + if (c < 1) throw new Error('PBKDF2: iterations (c) should be >= 1'); + const password = toBytes(_password); + const salt = toBytes(_salt); + // DK = PBKDF2(PRF, Password, Salt, c, dkLen); + const DK = new Uint8Array(dkLen); + // U1 = PRF(Password, Salt + INT_32_BE(i)) + const PRF = hmac.create(hash, password); + const PRFSalt = PRF._cloneInto().update(salt); + return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; +} + +function pbkdf2Output>( + PRF: Hash, + PRFSalt: Hash, + DK: Uint8Array, + prfW: Hash, + u: Uint8Array +) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) prfW.destroy(); + u.fill(0); + return DK; +} + +/** + * PBKDF2-HMAC: RFC 2898 key derivation function + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated + * @param salt - cryptographic salt + * @param opts - {c, dkLen} where c is work factor and dkLen is output message size + */ +export function pbkdf2(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt) { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW: any; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + for (let ui = 1; ui < c; ui++) { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} + +export async function pbkdf2Async(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt) { + const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW: any; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + await asyncLoop(c - 1, asyncTick, () => { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i]; + }); + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/src/ripemd160.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/src/ripemd160.ts new file mode 100644 index 0000000..5f32380 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/src/ripemd160.ts @@ -0,0 +1,110 @@ +import { SHA2 } from './_sha2.js'; +import { wrapConstructor } from './utils.js'; + +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = /* @__PURE__ */ Uint8Array.from({ length: 16 }, (_, i) => i); +const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) for (let j of [idxL, idxR]) j.push(j[i].map((k) => Rho[k])); + +const shifts = /* @__PURE__ */ [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => new Uint8Array(i)); +const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +const Kl = /* @__PURE__ */ new Uint32Array([ + 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e, +]); +const Kr = /* @__PURE__ */ new Uint32Array([ + 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000, +]); +// The rotate left (circular left shift) operation for uint32 +const rotl = (word: number, shift: number) => (word << shift) | (word >>> (32 - shift)); +// It's called f() in spec. +function f(group: number, x: number, y: number, z: number): number { + if (group === 0) return x ^ y ^ z; + else if (group === 1) return (x & y) | (~x & z); + else if (group === 2) return (x | ~y) ^ z; + else if (group === 3) return (x & z) | (y & ~z); + else return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const BUF = /* @__PURE__ */ new Uint32Array(16); +export class RIPEMD160 extends SHA2 { + private h0 = 0x67452301 | 0; + private h1 = 0xefcdab89 | 0; + private h2 = 0x98badcfe | 0; + private h3 = 0x10325476 | 0; + private h4 = 0xc3d2e1f0 | 0; + + constructor() { + super(64, 20, 8, true); + } + protected get(): [number, number, number, number, number] { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + protected set(h0: number, h1: number, h2: number, h3: number, h4: number) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + protected process(view: DataView, offset: number): void { + for (let i = 0; i < 16; i++, offset += 4) BUF[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, + bl = this.h1 | 0, br = bl, + cl = this.h2 | 0, cr = cl, + dl = this.h3 | 0, dr = dl, + el = this.h4 | 0, er = el; + + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + this.set( + (this.h1 + cl + dr) | 0, + (this.h2 + dl + er) | 0, + (this.h3 + el + ar) | 0, + (this.h4 + al + br) | 0, + (this.h0 + bl + cr) | 0 + ); + } + protected roundClean() { + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} + +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +export const ripemd160 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160()); diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/src/scrypt.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/src/scrypt.ts new file mode 100644 index 0000000..85b68d8 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/src/scrypt.ts @@ -0,0 +1,240 @@ +import { number as assertNumber } from './_assert.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 } from './pbkdf2.js'; +import { asyncLoop, checkOpts, Input, u32 } from './utils.js'; + +// RFC 7914 Scrypt KDF + +// Left rotate for uint32 +const rotl = (a: number, b: number) => (a << b) | (a >>> (32 - b)); + +// The main Scrypt loop: uses Salsa extensively. +// Six versions of the function were tried, this is the fastest one. +// prettier-ignore +function XorAndSalsa( + prev: Uint32Array, + pi: number, + input: Uint32Array, + ii: number, + out: Uint32Array, + oi: number +) { + // Based on https://cr.yp.to/salsa20.html + // Xor blocks + let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; + let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; + let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; + let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; + let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; + let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; + let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; + let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; + // Save state to temporary variables (salsa) + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, + x04 = y04, x05 = y05, x06 = y06, x07 = y07, + x08 = y08, x09 = y09, x10 = y10, x11 = y11, + x12 = y12, x13 = y13, x14 = y14, x15 = y15; + // Main loop (salsa) + for (let i = 0; i < 8; i += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); x15 ^= rotl(x14 + x13 | 0, 18); + } + // Write output (salsa) + out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0; +} + +function BlockMix(input: Uint32Array, ii: number, out: Uint32Array, oi: number, r: number) { + // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks) + let head = oi + 0; + let tail = oi + 16 * r; + for (let i = 0; i < 16; i++) out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1] + for (let i = 0; i < r; i++, head += 16, ii += 16) { + // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1 + XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1]) + if (i > 0) tail += 16; // First iteration overwrites tmp value in tail + XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i]) + } +} + +export type ScryptOpts = { + N: number; // cost factor + r: number; // block size + p: number; // parallelization + dkLen?: number; // key length + asyncTick?: number; // block execution max time + maxmem?: number; + onProgress?: (progress: number) => void; +}; + +// Common prologue and epilogue for sync/async functions +function scryptInit(password: Input, salt: Input, _opts?: ScryptOpts) { + // Maxmem - 1GB+1KB by default + const opts = checkOpts( + { + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024, + }, + _opts + ); + const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; + assertNumber(N); + assertNumber(r); + assertNumber(p); + assertNumber(dkLen); + assertNumber(asyncTick); + assertNumber(maxmem); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + const blockSize = 128 * r; + const blockSize32 = blockSize / 4; + if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) { + // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function + // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future. + throw new Error( + 'Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32' + ); + } + if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) { + throw new Error( + 'Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)' + ); + } + if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) { + throw new Error( + 'Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32' + ); + } + const memUsed = blockSize * (N + p); + if (memUsed > maxmem) { + throw new Error( + `Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)` + ); + } + // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor) + // Since it has only one iteration there is no reason to use async variant + const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p }); + const B32 = u32(B); + // Re-used between parallel iterations. Array(iterations) of B + const V = u32(new Uint8Array(blockSize * N)); + const tmp = u32(new Uint8Array(blockSize)); + let blockMixCb = () => {}; + if (onProgress) { + const totalBlockMix = 2 * N * p; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1); + let blockMixCnt = 0; + blockMixCb = () => { + blockMixCnt++; + if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) + onProgress(blockMixCnt / totalBlockMix); + }; + } + return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick }; +} + +function scryptOutput( + password: Input, + dkLen: number, + B: Uint8Array, + V: Uint32Array, + tmp: Uint32Array +) { + const res = pbkdf2(sha256, password, B, { c: 1, dkLen }); + B.fill(0); + V.fill(0); + tmp.fill(0); + return res; +} + +/** + * Scrypt KDF from RFC 7914. + * @param password - pass + * @param salt - salt + * @param opts - parameters + * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + * @returns Derived key + */ +export function scrypt(password: Input, salt: Input, opts: ScryptOpts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit( + password, + salt, + opts + ); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) V[i] = B32[Pi + i]; // V[0] = B[i] + for (let i = 0, pos = 0; i < N - 1; i++) { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + } + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + for (let i = 0; i < N; i++) { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + } + } + return scryptOutput(password, dkLen, B, V, tmp); +} + +/** + * Scrypt KDF from RFC 7914. + */ +export async function scryptAsync(password: Input, salt: Input, opts: ScryptOpts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit( + password, + salt, + opts + ); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) V[i] = B32[Pi + i]; // V[0] = B[i] + let pos = 0; + await asyncLoop(N - 1, asyncTick, () => { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + }); + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + await asyncLoop(N, asyncTick, () => { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + }); + } + return scryptOutput(password, dkLen, B, V, tmp); +} diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/src/sha1.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/src/sha1.ts new file mode 100644 index 0000000..1fec224 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/src/sha1.ts @@ -0,0 +1,88 @@ +import { SHA2 } from './_sha2.js'; +import { wrapConstructor } from './utils.js'; + +// SHA1 was cryptographically broken. +// It is still widely used in legacy apps. Don't use it for a new protocol. + +// RFC 3174 +const rotl = (word: number, shift: number) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +// Choice: a ? b : c +const Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c); + +// Initial state +const IV = /* @__PURE__ */ new Uint32Array([ + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0, +]); + +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = /* @__PURE__ */ new Uint32Array(80); +class SHA1 extends SHA2 { + private A = IV[0] | 0; + private B = IV[1] | 0; + private C = IV[2] | 0; + private D = IV[3] | 0; + private E = IV[4] | 0; + + constructor() { + super(64, 20, 8, false); + } + protected get(): [number, number, number, number, number] { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + protected set(A: number, B: number, C: number, D: number, E: number) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + protected process(view: DataView, offset: number): void { + for (let i = 0; i < 16; i++, offset += 4) SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + protected roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} + +export const sha1 = /* @__PURE__ */ wrapConstructor(() => new SHA1()); diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/src/sha256.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/src/sha256.ts new file mode 100644 index 0000000..6f88b9a --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/src/sha256.ts @@ -0,0 +1,133 @@ +import { SHA2 } from './_sha2.js'; +import { rotr, wrapConstructor } from './utils.js'; + +// SHA2-256 need to try 2^128 hashes to execute birthday attack. +// BTC network is doing 2^67 hashes/sec as per early 2023. + +// Choice: a ? b : c +const Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c); + +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = /* @__PURE__ */new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); + +// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): +// prettier-ignore +const IV = /* @__PURE__ */new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); + +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = /* @__PURE__ */ new Uint32Array(64); +class SHA256 extends SHA2 { + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + A = IV[0] | 0; + B = IV[1] | 0; + C = IV[2] | 0; + D = IV[3] | 0; + E = IV[4] | 0; + F = IV[5] | 0; + G = IV[6] | 0; + H = IV[7] | 0; + + constructor() { + super(64, 32, 8, false); + } + protected get(): [number, number, number, number, number, number, number, number] { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + protected set( + A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number + ) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + protected process(view: DataView, offset: number): void { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + protected roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + A = 0xc1059ed8 | 0; + B = 0x367cd507 | 0; + C = 0x3070dd17 | 0; + D = 0xf70e5939 | 0; + E = 0xffc00b31 | 0; + F = 0x68581511 | 0; + G = 0x64f98fa7 | 0; + H = 0xbefa4fa4 | 0; + constructor() { + super(); + this.outputLen = 28; + } +} + +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +export const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); +export const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224()); diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/src/sha3-addons.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/src/sha3-addons.ts new file mode 100644 index 0000000..1d5fbf9 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/src/sha3-addons.ts @@ -0,0 +1,398 @@ +import { number as assertNumber } from './_assert.js'; +import { Input, toBytes, wrapConstructorWithOpts, u32, Hash, HashXOF } from './utils.js'; +import { Keccak, ShakeOpts } from './sha3.js'; +// cSHAKE && KMAC (NIST SP800-185) +function leftEncode(n: number): Uint8Array { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) res.unshift(n & 0xff); + res.unshift(res.length); + return new Uint8Array(res); +} + +function rightEncode(n: number): Uint8Array { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} + +function chooseLen(opts: ShakeOpts, outputLen: number): number { + return opts.dkLen === undefined ? outputLen : opts.dkLen; +} + +const toBytesOptional = (buf?: Input) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); +// NOTE: second modulo is necessary since we don't need to add padding if current element takes whole block +const getPadding = (len: number, block: number) => new Uint8Array((block - (len % block)) % block); +export type cShakeOpts = ShakeOpts & { personalization?: Input; NISTfn?: Input }; + +// Personalization +function cshakePers(hash: Keccak, opts: cShakeOpts = {}): Keccak { + if (!opts || (!opts.personalization && !opts.NISTfn)) return hash; + // Encode and pad inplace to avoid unneccesary memory copies/slices (so we don't need to zero them later) + // bytepad(encode_string(N) || encode_string(S), 168) + const blockLenBytes = leftEncode(hash.blockLen); + const fn = toBytesOptional(opts.NISTfn); + const fnLen = leftEncode(8 * fn.length); // length in bits + const pers = toBytesOptional(opts.personalization); + const persLen = leftEncode(8 * pers.length); // length in bits + if (!fn.length && !pers.length) return hash; + hash.suffix = 0x04; + hash.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers); + let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length; + hash.update(getPadding(totalLen, hash.blockLen)); + return hash; +} + +const gencShake = (suffix: number, blockLen: number, outputLen: number) => + wrapConstructorWithOpts((opts: cShakeOpts = {}) => + cshakePers(new Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts) + ); + +export const cshake128 = /* @__PURE__ */ (() => gencShake(0x1f, 168, 128 / 8))(); +export const cshake256 = /* @__PURE__ */ (() => gencShake(0x1f, 136, 256 / 8))(); + +class KMAC extends Keccak implements HashXOF { + constructor( + blockLen: number, + outputLen: number, + enableXOF: boolean, + key: Input, + opts: cShakeOpts = {} + ) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'KMAC', personalization: opts.personalization }); + key = toBytes(key); + // 1. newX = bytepad(encode_string(K), 168) || X || right_encode(L). + const blockLenBytes = leftEncode(this.blockLen); + const keyLen = leftEncode(8 * key.length); + this.update(blockLenBytes).update(keyLen).update(key); + const totalLen = blockLenBytes.length + keyLen.length + key.length; + this.update(getPadding(totalLen, this.blockLen)); + } + protected finish() { + if (!this.finished) this.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to?: KMAC): KMAC { + // Create new instance without calling constructor since key already in state and we don't know it. + // Force "to" to be instance of KMAC instead of Sha3. + if (!to) { + to = Object.create(Object.getPrototypeOf(this), {}) as KMAC; + to.state = this.state.slice(); + to.blockLen = this.blockLen; + to.state32 = u32(to.state); + } + return super._cloneInto(to) as KMAC; + } + clone(): KMAC { + return this._cloneInto(); + } +} + +function genKmac(blockLen: number, outputLen: number, xof = false) { + const kmac = (key: Input, message: Input, opts?: cShakeOpts): Uint8Array => + kmac.create(key, opts).update(message).digest(); + kmac.create = (key: Input, opts: cShakeOpts = {}) => + new KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts); + return kmac; +} + +export const kmac128 = /* @__PURE__ */ (() => genKmac(168, 128 / 8))(); +export const kmac256 = /* @__PURE__ */ (() => genKmac(136, 256 / 8))(); +export const kmac128xof = /* @__PURE__ */ (() => genKmac(168, 128 / 8, true))(); +export const kmac256xof = /* @__PURE__ */ (() => genKmac(136, 256 / 8, true))(); + +// TupleHash +// Usage: tuple(['ab', 'cd']) != tuple(['a', 'bcd']) +class TupleHash extends Keccak implements HashXOF { + constructor(blockLen: number, outputLen: number, enableXOF: boolean, opts: cShakeOpts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'TupleHash', personalization: opts.personalization }); + // Change update after cshake processed + this.update = (data: Input) => { + data = toBytes(data); + super.update(leftEncode(data.length * 8)); + super.update(data); + return this; + }; + } + protected finish() { + if (!this.finished) super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to?: TupleHash): TupleHash { + to ||= new TupleHash(this.blockLen, this.outputLen, this.enableXOF); + return super._cloneInto(to) as TupleHash; + } + clone(): TupleHash { + return this._cloneInto(); + } +} + +function genTuple(blockLen: number, outputLen: number, xof = false) { + const tuple = (messages: Input[], opts?: cShakeOpts): Uint8Array => { + const h = tuple.create(opts); + for (const msg of messages) h.update(msg); + return h.digest(); + }; + tuple.create = (opts: cShakeOpts = {}) => + new TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts); + return tuple; +} + +export const tuplehash128 = /* @__PURE__ */ (() => genTuple(168, 128 / 8))(); +export const tuplehash256 = /* @__PURE__ */ (() => genTuple(136, 256 / 8))(); +export const tuplehash128xof = /* @__PURE__ */ (() => genTuple(168, 128 / 8, true))(); +export const tuplehash256xof = /* @__PURE__ */ (() => genTuple(136, 256 / 8, true))(); + +// ParallelHash (same as K12/M14, but without speedup for inputs less 8kb, reduced number of rounds and more simple) +type ParallelOpts = cShakeOpts & { blockLen?: number }; + +class ParallelHash extends Keccak implements HashXOF { + private leafHash?: Hash; + private chunkPos = 0; // Position of current block in chunk + private chunksDone = 0; // How many chunks we already have + private chunkLen: number; + constructor( + blockLen: number, + outputLen: number, + protected leafCons: () => Hash, + enableXOF: boolean, + opts: ParallelOpts = {} + ) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'ParallelHash', personalization: opts.personalization }); + let { blockLen: B } = opts; + B ||= 8; + assertNumber(B); + this.chunkLen = B; + super.update(leftEncode(B)); + // Change update after cshake processed + this.update = (data: Input) => { + data = toBytes(data); + const { chunkLen, leafCons } = this; + for (let pos = 0, len = data.length; pos < len; ) { + if (this.chunkPos == chunkLen || !this.leafHash) { + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + this.leafHash = leafCons(); + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + this.leafHash.update(data.subarray(pos, pos + take)); + this.chunkPos += take; + pos += take; + } + return this; + }; + } + protected finish() { + if (this.finished) return; + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + super.update(rightEncode(this.chunksDone)); + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to?: ParallelHash): ParallelHash { + to ||= new ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF); + if (this.leafHash) to.leafHash = this.leafHash._cloneInto(to.leafHash as Keccak); + to.chunkPos = this.chunkPos; + to.chunkLen = this.chunkLen; + to.chunksDone = this.chunksDone; + return super._cloneInto(to) as ParallelHash; + } + destroy() { + super.destroy.call(this); + if (this.leafHash) this.leafHash.destroy(); + } + clone(): ParallelHash { + return this._cloneInto(); + } +} + +function genPrl( + blockLen: number, + outputLen: number, + leaf: ReturnType, + xof = false +) { + const parallel = (message: Input, opts?: ParallelOpts): Uint8Array => + parallel.create(opts).update(message).digest(); + parallel.create = (opts: ParallelOpts = {}) => + new ParallelHash( + blockLen, + chooseLen(opts, outputLen), + () => leaf.create({ dkLen: 2 * outputLen }), + xof, + opts + ); + return parallel; +} + +export const parallelhash128 = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128))(); +export const parallelhash256 = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256))(); +export const parallelhash128xof = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128, true))(); +export const parallelhash256xof = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256, true))(); + +// Kangaroo +// Same as NIST rightEncode, but returns [0] for zero string +function rightEncodeK12(n: number): Uint8Array { + const res = []; + for (; n > 0; n >>= 8) res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} + +export type KangarooOpts = { dkLen?: number; personalization?: Input }; +const EMPTY = new Uint8Array([]); + +class KangarooTwelve extends Keccak implements HashXOF { + readonly chunkLen = 8192; + private leafHash?: Keccak; + private personalization: Uint8Array; + private chunkPos = 0; // Position of current block in chunk + private chunksDone = 0; // How many chunks we already have + constructor( + blockLen: number, + protected leafLen: number, + outputLen: number, + rounds: number, + opts: KangarooOpts + ) { + super(blockLen, 0x07, outputLen, true, rounds); + const { personalization } = opts; + this.personalization = toBytesOptional(personalization); + } + update(data: Input) { + data = toBytes(data); + const { chunkLen, blockLen, leafLen, rounds } = this; + for (let pos = 0, len = data.length; pos < len; ) { + if (this.chunkPos == chunkLen) { + if (this.leafHash) super.update(this.leafHash.digest()); + else { + this.suffix = 0x06; // Its safe to change suffix here since its used only in digest() + super.update(new Uint8Array([3, 0, 0, 0, 0, 0, 0, 0])); + } + this.leafHash = new Keccak(blockLen, 0x0b, leafLen, false, rounds); + this.chunksDone++; + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + const chunk = data.subarray(pos, pos + take); + if (this.leafHash) this.leafHash.update(chunk); + else super.update(chunk); + this.chunkPos += take; + pos += take; + } + return this; + } + protected finish() { + if (this.finished) return; + const { personalization } = this; + this.update(personalization).update(rightEncodeK12(personalization.length)); + // Leaf hash + if (this.leafHash) { + super.update(this.leafHash.digest()); + super.update(rightEncodeK12(this.chunksDone)); + super.update(new Uint8Array([0xff, 0xff])); + } + super.finish.call(this); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) this.leafHash.destroy(); + // We cannot zero personalization buffer since it is user provided and we don't want to mutate user input + this.personalization = EMPTY; + } + _cloneInto(to?: KangarooTwelve): KangarooTwelve { + const { blockLen, leafLen, leafHash, outputLen, rounds } = this; + to ||= new KangarooTwelve(blockLen, leafLen, outputLen, rounds, {}); + super._cloneInto(to); + if (leafHash) to.leafHash = leafHash._cloneInto(to.leafHash); + to.personalization.set(this.personalization); + to.leafLen = this.leafLen; + to.chunkPos = this.chunkPos; + to.chunksDone = this.chunksDone; + return to; + } + clone(): KangarooTwelve { + return this._cloneInto(); + } +} +// Default to 32 bytes, so it can be used without opts +export const k12 = /* @__PURE__ */ (() => + wrapConstructorWithOpts( + (opts: KangarooOpts = {}) => new KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts) + ))(); +// MarsupilamiFourteen +export const m14 = /* @__PURE__ */ (() => + wrapConstructorWithOpts( + (opts: KangarooOpts = {}) => new KangarooTwelve(136, 64, chooseLen(opts, 64), 14, opts) + ))(); + +// https://keccak.team/files/CSF-0.1.pdf +// + https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG +class KeccakPRG extends Keccak { + protected rate: number; + constructor(capacity: number) { + assertNumber(capacity); + // Rho should be full bytes + if (capacity < 0 || capacity > 1600 - 10 || (1600 - capacity - 2) % 8) + throw new Error('KeccakPRG: Invalid capacity'); + // blockLen = rho in bytes + super((1600 - capacity - 2) / 8, 0, 0, true); + this.rate = 1600 - capacity; + this.posOut = Math.floor((this.rate + 7) / 8); + } + keccak() { + // Duplex padding + this.state[this.pos] ^= 0x01; + this.state[this.blockLen] ^= 0x02; // Rho is full bytes + super.keccak(); + this.pos = 0; + this.posOut = 0; + } + update(data: Input) { + super.update(data); + this.posOut = this.blockLen; + return this; + } + feed(data: Input) { + return this.update(data); + } + protected finish() {} + digestInto(_out: Uint8Array): Uint8Array { + throw new Error('KeccakPRG: digest is not allowed, please use .fetch instead.'); + } + fetch(bytes: number): Uint8Array { + return this.xof(bytes); + } + // Ensure irreversibility (even if state leaked previous outputs cannot be computed) + forget() { + if (this.rate < 1600 / 2 + 1) throw new Error('KeccakPRG: rate too low to use forget'); + this.keccak(); + for (let i = 0; i < this.blockLen; i++) this.state[i] = 0; + this.pos = this.blockLen; + this.keccak(); + this.posOut = this.blockLen; + } + _cloneInto(to?: KeccakPRG): KeccakPRG { + const { rate } = this; + to ||= new KeccakPRG(1600 - rate); + super._cloneInto(to); + to.rate = rate; + return to; + } + clone(): KeccakPRG { + return this._cloneInto(); + } +} + +export const keccakprg = (capacity = 254) => new KeccakPRG(capacity); diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/src/sha3.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/src/sha3.ts new file mode 100644 index 0000000..c730b06 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/src/sha3.ts @@ -0,0 +1,223 @@ +import { bytes, exists, number, output } from './_assert.js'; +import { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.js'; +import { + Hash, + u32, + Input, + toBytes, + wrapConstructor, + wrapXOFConstructorWithOpts, + HashXOF, +} from './utils.js'; + +// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. +// It's called a sponge function. + +// Various per round constants calculations +const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA]: [number[], number[], bigint[]] = [[], [], []]; +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); +const _2n = /* @__PURE__ */ BigInt(2); +const _7n = /* @__PURE__ */ BigInt(7); +const _256n = /* @__PURE__ */ BigInt(256); +const _0x71n = /* @__PURE__ */ BigInt(0x71); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); + +// Left rotation (without 0, 32, 64) +const rotlH = (h: number, l: number, s: number) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s)); +const rotlL = (h: number, l: number, s: number) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s)); + +// Same as keccakf1600, but allows to skip some rounds +export function keccakP(s: Uint32Array, rounds: number = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) B[x] = s[y + x]; + for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} + +export class Keccak extends Hash implements HashXOF { + protected state: Uint8Array; + protected pos = 0; + protected posOut = 0; + protected finished = false; + protected state32: Uint32Array; + protected destroyed = false; + // NOTE: we accept arguments in bytes instead of bits here. + constructor( + public blockLen: number, + public suffix: number, + public outputLen: number, + protected enableXOF = false, + protected rounds: number = 24 + ) { + super(); + // Can be passed from user as dkLen + number(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + protected keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + update(data: Input) { + exists(this); + const { blockLen, state } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) this.keccak(); + } + return this; + } + protected finish() { + if (this.finished) return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + protected writeInto(out: Uint8Array): Uint8Array { + exists(this, false); + bytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len; ) { + if (this.posOut >= blockLen) this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out: Uint8Array): Uint8Array { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes: number): Uint8Array { + number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out: Uint8Array) { + output(out, this); + if (this.finished) throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to?: Keccak): Keccak { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} + +const gen = (suffix: number, blockLen: number, outputLen: number) => + wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); + +export const sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +export const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8); +export const sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8); +export const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8); +export const keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +export const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8); +export const keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8); +export const keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8); + +export type ShakeOpts = { dkLen?: number }; + +const genShake = (suffix: number, blockLen: number, outputLen: number) => + wrapXOFConstructorWithOpts, ShakeOpts>( + (opts: ShakeOpts = {}) => + new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true) + ); + +export const shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8); +export const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8); diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/src/sha512.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/src/sha512.ts new file mode 100644 index 0000000..27b7ac5 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/src/sha512.ts @@ -0,0 +1,246 @@ +import { SHA2 } from './_sha2.js'; +import u64 from './_u64.js'; +import { wrapConstructor } from './utils.js'; + +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))))(); + +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); +const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); +export class SHA512 extends SHA2 { + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + Ah = 0x6a09e667 | 0; + Al = 0xf3bcc908 | 0; + Bh = 0xbb67ae85 | 0; + Bl = 0x84caa73b | 0; + Ch = 0x3c6ef372 | 0; + Cl = 0xfe94f82b | 0; + Dh = 0xa54ff53a | 0; + Dl = 0x5f1d36f1 | 0; + Eh = 0x510e527f | 0; + El = 0xade682d1 | 0; + Fh = 0x9b05688c | 0; + Fl = 0x2b3e6c1f | 0; + Gh = 0x1f83d9ab | 0; + Gl = 0xfb41bd6b | 0; + Hh = 0x5be0cd19 | 0; + Hl = 0x137e2179 | 0; + + constructor() { + super(128, 64, 16, false); + } + // prettier-ignore + protected get(): [ + number, number, number, number, number, number, number, number, + number, number, number, number, number, number, number, number + ] { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + protected set( + Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number, + Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number + ) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + protected process(view: DataView, offset: number) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); + const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); + const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); + const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); + const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = u64.add3L(T1l, sigma0l, MAJl); + Ah = u64.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + protected roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} + +class SHA512_224 extends SHA512 { + // h -- high 32 bits, l -- low 32 bits + Ah = 0x8c3d37c8 | 0; + Al = 0x19544da2 | 0; + Bh = 0x73e19966 | 0; + Bl = 0x89dcd4d6 | 0; + Ch = 0x1dfab7ae | 0; + Cl = 0x32ff9c82 | 0; + Dh = 0x679dd514 | 0; + Dl = 0x582f9fcf | 0; + Eh = 0x0f6d2b69 | 0; + El = 0x7bd44da8 | 0; + Fh = 0x77e36f73 | 0; + Fl = 0x04c48942 | 0; + Gh = 0x3f9d85a8 | 0; + Gl = 0x6a1d36c8 | 0; + Hh = 0x1112e6ad | 0; + Hl = 0x91d692a1 | 0; + + constructor() { + super(); + this.outputLen = 28; + } +} + +class SHA512_256 extends SHA512 { + // h -- high 32 bits, l -- low 32 bits + Ah = 0x22312194 | 0; + Al = 0xfc2bf72c | 0; + Bh = 0x9f555fa3 | 0; + Bl = 0xc84c64c2 | 0; + Ch = 0x2393b86b | 0; + Cl = 0x6f53b151 | 0; + Dh = 0x96387719 | 0; + Dl = 0x5940eabd | 0; + Eh = 0x96283ee2 | 0; + El = 0xa88effe3 | 0; + Fh = 0xbe5e1e25 | 0; + Fl = 0x53863992 | 0; + Gh = 0x2b0199fc | 0; + Gl = 0x2c85b8aa | 0; + Hh = 0x0eb72ddc | 0; + Hl = 0x81c52ca2 | 0; + + constructor() { + super(); + this.outputLen = 32; + } +} + +class SHA384 extends SHA512 { + // h -- high 32 bits, l -- low 32 bits + Ah = 0xcbbb9d5d | 0; + Al = 0xc1059ed8 | 0; + Bh = 0x629a292a | 0; + Bl = 0x367cd507 | 0; + Ch = 0x9159015a | 0; + Cl = 0x3070dd17 | 0; + Dh = 0x152fecd8 | 0; + Dl = 0xf70e5939 | 0; + Eh = 0x67332667 | 0; + El = 0xffc00b31 | 0; + Fh = 0x8eb44a87 | 0; + Fl = 0x68581511 | 0; + Gh = 0xdb0c2e0d | 0; + Gl = 0x64f98fa7 | 0; + Hh = 0x47b5481d | 0; + Hl = 0xbefa4fa4 | 0; + + constructor() { + super(); + this.outputLen = 48; + } +} + +export const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512()); +export const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224()); +export const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256()); +export const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384()); diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/src/utils.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/src/utils.ts new file mode 100644 index 0000000..81e5256 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/src/utils.ts @@ -0,0 +1,215 @@ +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated, we can just drop the import. +import { crypto } from '@noble/hashes/crypto'; + +// prettier-ignore +export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | + Uint16Array | Int16Array | Uint32Array | Int32Array; + +const u8a = (a: any): a is Uint8Array => a instanceof Uint8Array; +// Cast array to different type +export const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +export const u32 = (arr: TypedArray) => + new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); + +// Cast array to view +export const createView = (arr: TypedArray) => + new DataView(arr.buffer, arr.byteOffset, arr.byteLength); + +// The rotate right (circular right shift) operation for uint32 +export const rotr = (word: number, shift: number) => (word << (32 - shift)) | (word >>> shift); + +// big-endian hardware is rare. Just in case someone still decides to run hashes: +// early-throw an error because we don't support BE yet. +export const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!isLE) throw new Error('Non little-endian hardware is not supported'); + +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => + i.toString(16).padStart(2, '0') +); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export function bytesToHex(bytes: Uint8Array): string { + if (!u8a(bytes)) throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} + +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export function hexToBytes(hex: string): Uint8Array { + if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} + +// There is no setImmediate in browser and setTimeout is slow. +// call of async fn will return Promise, which will be fullfiled only on +// next scheduler queue processing step and this is exactly what we need. +export const nextTick = async () => {}; + +// Returns control to thread each 'tick' ms to avoid blocking +export async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) continue; + await nextTick(); + ts += diff; + } +} + +// Global symbols in both browsers and Node.js since v11 +// See https://github.com/microsoft/TypeScript/issues/31535 +declare const TextEncoder: any; + +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export function utf8ToBytes(str: string): Uint8Array { + if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} + +export type Input = Uint8Array | string; +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +export function toBytes(data: Input): Uint8Array { + if (typeof data === 'string') data = utf8ToBytes(data); + if (!u8a(data)) throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; +} + +/** + * Copies several Uint8Arrays into one. + */ +export function concatBytes(...arrays: Uint8Array[]): Uint8Array { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} + +// For runtime check if class implements interface +export abstract class Hash> { + abstract blockLen: number; // Bytes per block + abstract outputLen: number; // Bytes in output + abstract update(buf: Input): this; + // Writes digest into buf + abstract digestInto(buf: Uint8Array): void; + abstract digest(): Uint8Array; + /** + * Resets internal state. Makes Hash instance unusable. + * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed + * by user, they will need to manually call `destroy()` when zeroing is necessary. + */ + abstract destroy(): void; + /** + * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()` + * when no options are passed. + * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal + * buffers are overwritten => causes buffer overwrite which is used for digest in some cases. + * There are no guarantees for clean-up because it's impossible in JS. + */ + abstract _cloneInto(to?: T): T; + // Safe version that clones internal state + clone(): T { + return this._cloneInto(); + } +} + +/** + * XOF: streaming API to read digest in chunks. + * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name. + * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot + * destroy state, next call can require more bytes. + */ +export type HashXOF> = Hash & { + xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream + xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf +}; + +const toStr = {}.toString; +type EmptyObj = {}; +export function checkOpts( + defaults: T1, + opts?: T2 +): T1 & T2 { + if (opts !== undefined && toStr.call(opts) !== '[object Object]') + throw new Error('Options should be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged as T1 & T2; +} + +export type CHash = ReturnType; + +export function wrapConstructor>(hashCons: () => Hash) { + const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} + +export function wrapConstructorWithOpts, T extends Object>( + hashCons: (opts?: T) => Hash +) { + const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({} as T); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts: T) => hashCons(opts); + return hashC; +} + +export function wrapXOFConstructorWithOpts, T extends Object>( + hashCons: (opts?: T) => HashXOF +) { + const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({} as T); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts: T) => hashCons(opts); + return hashC; +} + +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +export function randomBytes(bytesLength = 32): Uint8Array { + if (crypto && typeof crypto.getRandomValues === 'function') { + return crypto.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error('crypto.getRandomValues must be defined'); +} diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/utils.d.ts b/node_modules/@noble/curves/node_modules/@noble/hashes/utils.d.ts new file mode 100644 index 0000000..a0017e4 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/utils.d.ts @@ -0,0 +1,90 @@ +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | Uint16Array | Int16Array | Uint32Array | Int32Array; +export declare const u8: (arr: TypedArray) => Uint8Array; +export declare const u32: (arr: TypedArray) => Uint32Array; +export declare const createView: (arr: TypedArray) => DataView; +export declare const rotr: (word: number, shift: number) => number; +export declare const isLE: boolean; +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export declare function bytesToHex(bytes: Uint8Array): string; +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export declare function hexToBytes(hex: string): Uint8Array; +export declare const nextTick: () => Promise; +export declare function asyncLoop(iters: number, tick: number, cb: (i: number) => void): Promise; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export declare function utf8ToBytes(str: string): Uint8Array; +export type Input = Uint8Array | string; +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +export declare function toBytes(data: Input): Uint8Array; +/** + * Copies several Uint8Arrays into one. + */ +export declare function concatBytes(...arrays: Uint8Array[]): Uint8Array; +export declare abstract class Hash> { + abstract blockLen: number; + abstract outputLen: number; + abstract update(buf: Input): this; + abstract digestInto(buf: Uint8Array): void; + abstract digest(): Uint8Array; + /** + * Resets internal state. Makes Hash instance unusable. + * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed + * by user, they will need to manually call `destroy()` when zeroing is necessary. + */ + abstract destroy(): void; + /** + * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()` + * when no options are passed. + * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal + * buffers are overwritten => causes buffer overwrite which is used for digest in some cases. + * There are no guarantees for clean-up because it's impossible in JS. + */ + abstract _cloneInto(to?: T): T; + clone(): T; +} +/** + * XOF: streaming API to read digest in chunks. + * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name. + * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot + * destroy state, next call can require more bytes. + */ +export type HashXOF> = Hash & { + xof(bytes: number): Uint8Array; + xofInto(buf: Uint8Array): Uint8Array; +}; +type EmptyObj = {}; +export declare function checkOpts(defaults: T1, opts?: T2): T1 & T2; +export type CHash = ReturnType; +export declare function wrapConstructor>(hashCons: () => Hash): { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare function wrapConstructorWithOpts, T extends Object>(hashCons: (opts?: T) => Hash): { + (msg: Input, opts?: T): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: T): Hash; +}; +export declare function wrapXOFConstructorWithOpts, T extends Object>(hashCons: (opts?: T) => HashXOF): { + (msg: Input, opts?: T): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: T): HashXOF; +}; +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +export declare function randomBytes(bytesLength?: number): Uint8Array; +export {}; diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/utils.js b/node_modules/@noble/curves/node_modules/@noble/hashes/utils.js new file mode 100644 index 0000000..2ffcbbe --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/utils.js @@ -0,0 +1,174 @@ +"use strict"; +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +Object.defineProperty(exports, "__esModule", { value: true }); +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; +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated, we can just drop the import. +const crypto_1 = require("@noble/hashes/crypto"); +const u8a = (a) => a instanceof Uint8Array; +// Cast array to different type +const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +exports.u8 = u8; +const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +exports.u32 = u32; +// Cast array to view +const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +exports.createView = createView; +// The rotate right (circular right shift) operation for uint32 +const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); +exports.rotr = rotr; +// big-endian hardware is rare. Just in case someone still decides to run hashes: +// early-throw an error because we don't support BE yet. +exports.isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!exports.isLE) + throw new Error('Non little-endian hardware is not supported'); +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +function bytesToHex(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +exports.bytesToHex = bytesToHex; +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} +exports.hexToBytes = hexToBytes; +// There is no setImmediate in browser and setTimeout is slow. +// call of async fn will return Promise, which will be fullfiled only on +// next scheduler queue processing step and this is exactly what we need. +const nextTick = async () => { }; +exports.nextTick = nextTick; +// Returns control to thread each 'tick' ms to avoid blocking +async function asyncLoop(iters, tick, cb) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) + continue; + await (0, exports.nextTick)(); + ts += diff; + } +} +exports.asyncLoop = asyncLoop; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +exports.utf8ToBytes = utf8ToBytes; +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +function toBytes(data) { + if (typeof data === 'string') + data = utf8ToBytes(data); + if (!u8a(data)) + throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; +} +exports.toBytes = toBytes; +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) + throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} +exports.concatBytes = concatBytes; +// For runtime check if class implements interface +class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +exports.Hash = Hash; +const toStr = {}.toString; +function checkOpts(defaults, opts) { + if (opts !== undefined && toStr.call(opts) !== '[object Object]') + throw new Error('Options should be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged; +} +exports.checkOpts = checkOpts; +function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +exports.wrapConstructor = wrapConstructor; +function wrapConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +exports.wrapConstructorWithOpts = wrapConstructorWithOpts; +function wrapXOFConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +exports.wrapXOFConstructorWithOpts = wrapXOFConstructorWithOpts; +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +function randomBytes(bytesLength = 32) { + if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') { + return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error('crypto.getRandomValues must be defined'); +} +exports.randomBytes = randomBytes; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/node_modules/@noble/hashes/utils.js.map b/node_modules/@noble/curves/node_modules/@noble/hashes/utils.js.map new file mode 100644 index 0000000..4fc2171 --- /dev/null +++ b/node_modules/@noble/curves/node_modules/@noble/hashes/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["src/utils.ts"],"names":[],"mappings":";AAAA,sEAAsE;;;AAEtE,oFAAoF;AACpF,sEAAsE;AACtE,kEAAkE;AAClE,8DAA8D;AAC9D,+DAA+D;AAC/D,8DAA8D;AAC9D,iDAA8C;AAM9C,MAAM,GAAG,GAAG,CAAC,CAAM,EAAmB,EAAE,CAAC,CAAC,YAAY,UAAU,CAAC;AACjE,+BAA+B;AACxB,MAAM,EAAE,GAAG,CAAC,GAAe,EAAE,EAAE,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;AAArF,Q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;;GAEG;AACH,SAAgB,WAAW,CAAC,WAAW,GAAG,EAAE;IAC1C,IAAI,eAAM,IAAI,OAAO,eAAM,CAAC,eAAe,KAAK,UAAU,EAAE;QAC1D,OAAO,eAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC;KAC5D;IACD,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAC5D,CAAC;AALD,kCAKC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/p256.d.ts b/node_modules/@noble/curves/p256.d.ts new file mode 100644 index 0000000..cf8c0d6 --- /dev/null +++ b/node_modules/@noble/curves/p256.d.ts @@ -0,0 +1,105 @@ +export declare const p256: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType | undefined) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const secp256r1: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType | undefined) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const hashToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +//# sourceMappingURL=p256.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/p256.d.ts.map b/node_modules/@noble/curves/p256.d.ts.map new file mode 100644 index 0000000..d16f812 --- /dev/null +++ b/node_modules/@noble/curves/p256.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"p256.d.ts","sourceRoot":"","sources":["src/p256.ts"],"names":[],"mappings":"AAeA,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAWE,CAAC;AACpB,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAO,CAAC;AAmB9B,eAAO,MAAM,WAAW,uJAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,uJAA8C,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/p256.js b/node_modules/@noble/curves/p256.js new file mode 100644 index 0000000..1e7e809 --- /dev/null +++ b/node_modules/@noble/curves/p256.js @@ -0,0 +1,45 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeToCurve = exports.hashToCurve = exports.secp256r1 = exports.p256 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const sha256_1 = require("@noble/hashes/sha256"); +const modular_js_1 = require("./abstract/modular.js"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +// NIST secp256r1 aka p256 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256 +const Fp = (0, modular_js_1.Field)(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff')); +const CURVE_A = Fp.create(BigInt('-3')); +const CURVE_B = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'); +// prettier-ignore +exports.p256 = (0, _shortw_utils_js_1.createCurve)({ + a: CURVE_A, + b: CURVE_B, + Fp, + // Curve order, total count of valid points in the field + n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'), + // Base (generator) point (x, y) + Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'), + Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'), + h: BigInt(1), + lowS: false, +}, sha256_1.sha256); +exports.secp256r1 = exports.p256; +const mapSWU = /* @__PURE__ */ (() => (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-10')), +}))(); +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.secp256r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P256_XMD:SHA-256_SSWU_RO_', + encodeDST: 'P256_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256_1.sha256, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +//# sourceMappingURL=p256.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/p256.js.map b/node_modules/@noble/curves/p256.js.map new file mode 100644 index 0000000..0459df9 --- /dev/null +++ b/node_modules/@noble/curves/p256.js.map @@ -0,0 +1 @@ +{"version":3,"file":"p256.js","sourceRoot":"","sources":["src/p256.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,yDAAiD;AACjD,iDAA8C;AAC9C,sDAA8C;AAC9C,8DAAgE;AAChE,kEAA2D;AAE3D,0BAA0B;AAC1B,0EAA0E;AAE1E,MAAM,EAAE,GAAG,IAAA,kBAAK,EAAC,MAAM,CAAC,oEAAoE,CAAC,CAAC,CAAC;AAC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GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACxD,QAAA,aAAa,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/p384.d.ts b/node_modules/@noble/curves/p384.d.ts new file mode 100644 index 0000000..0be4254 --- /dev/null +++ b/node_modules/@noble/curves/p384.d.ts @@ -0,0 +1,105 @@ +export declare const p384: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType | undefined) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const secp384r1: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType | undefined) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const hashToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +//# sourceMappingURL=p384.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/p384.d.ts.map b/node_modules/@noble/curves/p384.d.ts.map new file mode 100644 index 0000000..547746d --- /dev/null +++ b/node_modules/@noble/curves/p384.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"p384.d.ts","sourceRoot":"","sources":["src/p384.ts"],"names":[],"mappings":"AAmBA,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAWE,CAAC;AACpB,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAO,CAAC;AAmB9B,eAAO,MAAM,WAAW,uJAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,uJAA8C,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/p384.js b/node_modules/@noble/curves/p384.js new file mode 100644 index 0000000..d3a472b --- /dev/null +++ b/node_modules/@noble/curves/p384.js @@ -0,0 +1,49 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeToCurve = exports.hashToCurve = exports.secp384r1 = exports.p384 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const sha512_1 = require("@noble/hashes/sha512"); +const modular_js_1 = require("./abstract/modular.js"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +// NIST secp384r1 aka p384 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-384 +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'); +const Fp = (0, modular_js_1.Field)(P); +const CURVE_A = Fp.create(BigInt('-3')); +// prettier-ignore +const CURVE_B = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'); +// prettier-ignore +exports.p384 = (0, _shortw_utils_js_1.createCurve)({ + a: CURVE_A, + b: CURVE_B, + Fp, + // Curve order, total count of valid points in the field. + n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'), + // Base (generator) point (x, y) + Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'), + Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'), + h: BigInt(1), + lowS: false, +}, sha512_1.sha384); +exports.secp384r1 = exports.p384; +const mapSWU = /* @__PURE__ */ (() => (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-12')), +}))(); +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.secp384r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P384_XMD:SHA-384_SSWU_RO_', + encodeDST: 'P384_XMD:SHA-384_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 192, + expand: 'xmd', + hash: sha512_1.sha384, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +//# sourceMappingURL=p384.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/p384.js.map b/node_modules/@noble/curves/p384.js.map new file mode 100644 index 0000000..6816f0d --- /dev/null +++ b/node_modules/@noble/curves/p384.js.map @@ -0,0 +1 @@ +{"version":3,"file":"p384.js","sourceRoot":"","sources":["src/p384.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,yDAAiD;AACjD,iDAA8C;AAC9C,sDAA8C;AAC9C,8DAAgE;AAChE,kEAA2D;AAE3D,0BAA0B;AAC1B,0EAA0E;AAE1E,0CAA0C;AAC1C,kBAAkB;AAClB,MAAM,CAAC,GAAG,MAAM,CAAC,oGAAoG,CAAC,CAAC;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;CACb,CAAC,CAAC,EAAE,CAAC;AACK,QAAA,WAAW,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACxD,QAAA,aAAa,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/p521.d.ts b/node_modules/@noble/curves/p521.d.ts new file mode 100644 index 0000000..47cca46 --- /dev/null +++ b/node_modules/@noble/curves/p521.d.ts @@ -0,0 +1,105 @@ +export declare const p521: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType | undefined) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const secp521r1: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType | undefined) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const hashToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +//# sourceMappingURL=p521.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/p521.d.ts.map b/node_modules/@noble/curves/p521.d.ts.map new file mode 100644 index 0000000..1c3cdaa --- /dev/null +++ b/node_modules/@noble/curves/p521.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"p521.d.ts","sourceRoot":"","sources":["src/p521.ts"],"names":[],"mappings":"AAmCA,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAWE,CAAC;AACpB,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAO,CAAC;AAmB9B,eAAO,MAAM,WAAW,uJAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,uJAA8C,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/p521.js b/node_modules/@noble/curves/p521.js new file mode 100644 index 0000000..c1c0e22 --- /dev/null +++ b/node_modules/@noble/curves/p521.js @@ -0,0 +1,56 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeToCurve = exports.hashToCurve = exports.secp521r1 = exports.p521 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const sha512_1 = require("@noble/hashes/sha512"); +const modular_js_1 = require("./abstract/modular.js"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +// NIST secp521r1 aka p521 +// Note that it's 521, which differs from 512 of its hash function. +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-521 +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const Fp = (0, modular_js_1.Field)(P); +const CURVE = { + a: Fp.create(BigInt('-3')), + b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'), + Fp, + n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'), + Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'), + Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'), + h: BigInt(1), +}; +// prettier-ignore +exports.p521 = (0, _shortw_utils_js_1.createCurve)({ + a: CURVE.a, + b: CURVE.b, + Fp, + // Curve order, total count of valid points in the field + n: CURVE.n, + Gx: CURVE.Gx, + Gy: CURVE.Gy, + h: CURVE.h, + lowS: false, + allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b +}, sha512_1.sha512); +exports.secp521r1 = exports.p521; +const mapSWU = /* @__PURE__ */ (() => (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, { + A: CURVE.a, + B: CURVE.b, + Z: Fp.create(BigInt('-4')), +}))(); +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.secp521r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P521_XMD:SHA-512_SSWU_RO_', + encodeDST: 'P521_XMD:SHA-512_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 256, + expand: 'xmd', + hash: sha512_1.sha512, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +//# sourceMappingURL=p521.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/p521.js.map b/node_modules/@noble/curves/p521.js.map new file mode 100644 index 0000000..f79e5f0 --- /dev/null +++ b/node_modules/@noble/curves/p521.js.map @@ -0,0 +1 @@ +{"version":3,"file":"p521.js","sourceRoot":"","sources":["src/p521.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,yDAAiD;AACjD,iDAA8C;AAC9C,sDAA8C;AAC9C,8DAAgE;AAChE,kEAA2D;AAE3D,0BAA0B;AAC1B,mEAAmE;AACnE,0EAA0E;AAE1E,0CAA0C;AAC1C,kBAAkB;AAClB,MAAM,CAAC,GAAG,MAAM,CAAC,uIAAuI,CAAC,CAAC;AAC1J,MAAM,EAAE,GAAG,IAAA,kBAAK,EAAC,CAAC,CAAC,CAAC;AAEpB,MAAM,KAAK,GAAG;IACZ,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC1B,CAAC,EAAE,MAAM,CACP,wIAAwI,CACzI;IACD,EAAE;IACF,CAAC,EAAE,MAAM,CACP,wIAAwI,CACzI;IACD,EAAE,EAAE,MAAM,CACR,wIAAwI,CACzI;IACD,EAAE,EAAE,MAAM,CACR,wIAAwI,CACzI;IACD,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;CACb,CAAC;AAEF,kBAAkB;AACL,QAAA,IAAI,GAAG,IAAA,8BAAW,EAAC;IAC9B,CAAC,EAAE,KAAK,CAAC,CAAC;IACV,CAAC,EAAE,KAAK,CAAC,CAAC;IACV,EAAE;IACF,wDAAwD;IACxD,CAAC,EAAE,KAAK,CAAC,CAAC;IACV,EAAE,EAAE,KAAK,CAAC,EAAE;IACZ,EAAE,EAAE,KAAK,CAAC,EAAE;IACZ,CAAC,EAAE,KAAK,CAAC,CAAC;IACV,IAAI,EAAE,KAAK;IACX,wBAAwB,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,mDAAmD;CACrF,EAAE,eAAM,CAAC,CAAC;AACP,QAAA,SAAS,GAAG,YAAI,CAAC;AAE9B,MAAM,MAAM,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CACnC,IAAA,oCAAmB,EAAC,EAAE,EAAE;IACtB,CAAC,EAAE,KAAK,CAAC,CAAC;IACV,CAAC,EAAE,KAAK,CAAC,CAAC;IACV,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;CAC3B,CAAC,CAAC,EAAE,CAAC;AAER,MAAM,GAAG,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAChC,IAAA,+BAAY,EAAC,iBAAS,CAAC,eAAe,EAAE,CAAC,OAAiB,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE;IACjF,GAAG,EAAE,2BAA2B;IAChC,SAAS,EAAE,2BAA2B;IACtC,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,eAAM;CACb,CAAC,CAAC,EAAE,CAAC;AACK,QAAA,WAAW,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACxD,QAAA,aAAa,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/package.json b/node_modules/@noble/curves/package.json new file mode 100644 index 0000000..38cf3da --- /dev/null +++ b/node_modules/@noble/curves/package.json @@ -0,0 +1,181 @@ +{ + "name": "@noble/curves", + "version": "1.2.0", + "description": "Audited & minimal JS implementation of elliptic curve cryptography", + "files": [ + "abstract", + "esm", + "src", + "*.js", + "*.js.map", + "*.d.ts", + "*.d.ts.map" + ], + "scripts": { + "bench": "cd benchmark; node secp256k1.js; node curves.js; node ecdh.js; node hash-to-curve.js; node modular.js; node bls.js; node ristretto255.js; node decaf448.js", + "build": "tsc && tsc -p tsconfig.esm.json", + "build:release": "rollup -c rollup.config.js", + "build:clean": "rm *.{js,d.ts,d.ts.map,js.map} esm/*.{js,d.ts,d.ts.map,js.map} 2> /dev/null", + "lint": "prettier --check 'src/**/*.{js,ts}' 'test/*.js'", + "format": "prettier --write 'src/**/*.{js,ts}' 'test/*.js'", + "test": "node test/index.test.js" + }, + "author": "Paul Miller (https://paulmillr.com)", + "homepage": "https://paulmillr.com/noble/", + "repository": { + "type": "git", + "url": "https://github.com/paulmillr/noble-curves.git" + }, + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.3.2" + }, + "devDependencies": { + "fast-check": "3.0.0", + "micro-bmark": "0.3.1", + "micro-should": "0.4.0", + "prettier": "2.8.4", + "typescript": "5.0.2" + }, + "sideEffects": false, + "main": "index.js", + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./esm/index.js", + "default": "./index.js" + }, + "./abstract/edwards": { + "types": "./abstract/edwards.d.ts", + "import": "./esm/abstract/edwards.js", + "default": "./abstract/edwards.js" + }, + "./abstract/modular": { + "types": "./abstract/modular.d.ts", + "import": "./esm/abstract/modular.js", + "default": "./abstract/modular.js" + }, + "./abstract/montgomery": { + "types": "./abstract/montgomery.d.ts", + "import": "./esm/abstract/montgomery.js", + "default": "./abstract/montgomery.js" + }, + "./abstract/weierstrass": { + "types": "./abstract/weierstrass.d.ts", + "import": "./esm/abstract/weierstrass.js", + "default": "./abstract/weierstrass.js" + }, + "./abstract/bls": { + "types": "./abstract/bls.d.ts", + "import": "./esm/abstract/bls.js", + "default": "./abstract/bls.js" + }, + "./abstract/hash-to-curve": { + "types": "./abstract/hash-to-curve.d.ts", + "import": "./esm/abstract/hash-to-curve.js", + "default": "./abstract/hash-to-curve.js" + }, + "./abstract/curve": { + "types": "./abstract/curve.d.ts", + "import": "./esm/abstract/curve.js", + "default": "./abstract/curve.js" + }, + "./abstract/utils": { + "types": "./abstract/utils.d.ts", + "import": "./esm/abstract/utils.js", + "default": "./abstract/utils.js" + }, + "./abstract/poseidon": { + "types": "./abstract/poseidon.d.ts", + "import": "./esm/abstract/poseidon.js", + "default": "./abstract/poseidon.js" + }, + "./_shortw_utils": { + "types": "./_shortw_utils.d.ts", + "import": "./esm/_shortw_utils.js", + "default": "./_shortw_utils.js" + }, + "./bls12-381": { + "types": "./bls12-381.d.ts", + "import": "./esm/bls12-381.js", + "default": "./bls12-381.js" + }, + "./bn254": { + "types": "./bn254.d.ts", + "import": "./esm/bn254.js", + "default": "./bn254.js" + }, + "./ed25519": { + "types": "./ed25519.d.ts", + "import": "./esm/ed25519.js", + "default": "./ed25519.js" + }, + "./ed448": { + "types": "./ed448.d.ts", + "import": "./esm/ed448.js", + "default": "./ed448.js" + }, + "./index": { + "types": "./index.d.ts", + "import": "./esm/index.js", + "default": "./index.js" + }, + "./jubjub": { + "types": "./jubjub.d.ts", + "import": "./esm/jubjub.js", + "default": "./jubjub.js" + }, + "./p256": { + "types": "./p256.d.ts", + "import": "./esm/p256.js", + "default": "./p256.js" + }, + "./p384": { + "types": "./p384.d.ts", + "import": "./esm/p384.js", + "default": "./p384.js" + }, + "./p521": { + "types": "./p521.d.ts", + "import": "./esm/p521.js", + "default": "./p521.js" + }, + "./pasta": { + "types": "./pasta.d.ts", + "import": "./esm/pasta.js", + "default": "./pasta.js" + }, + "./secp256k1": { + "types": "./secp256k1.d.ts", + "import": "./esm/secp256k1.js", + "default": "./secp256k1.js" + } + }, + "keywords": [ + "elliptic", + "curve", + "cryptography", + "weierstrass", + "montgomery", + "edwards", + "p256", + "p384", + "p521", + "secp256r1", + "secp256k1", + "ed25519", + "ed448", + "x25519", + "ed25519", + "bls12-381", + "bn254", + "pasta", + "bls", + "noble", + "ecc", + "ecdsa", + "eddsa", + "schnorr" + ], + "funding": "https://paulmillr.com/funding/" +} \ No newline at end of file diff --git a/node_modules/@noble/curves/pasta.d.ts b/node_modules/@noble/curves/pasta.d.ts new file mode 100644 index 0000000..9e1f4ed --- /dev/null +++ b/node_modules/@noble/curves/pasta.d.ts @@ -0,0 +1,5 @@ +export declare const p: bigint; +export declare const q: bigint; +export declare const pallas: import("./abstract/weierstrass.js").CurveFn; +export declare const vesta: import("./abstract/weierstrass.js").CurveFn; +//# sourceMappingURL=pasta.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/pasta.d.ts.map b/node_modules/@noble/curves/pasta.d.ts.map new file mode 100644 index 0000000..d4e6dd5 --- /dev/null +++ b/node_modules/@noble/curves/pasta.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"pasta.d.ts","sourceRoot":"","sources":["src/pasta.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,CAAC,QAA+E,CAAC;AAC9F,eAAO,MAAM,CAAC,QAA+E,CAAC;AAG9F,eAAO,MAAM,MAAM,6CASjB,CAAC;AAEH,eAAO,MAAM,KAAK,6CAShB,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/pasta.js b/node_modules/@noble/curves/pasta.js new file mode 100644 index 0000000..c3bee21 --- /dev/null +++ b/node_modules/@noble/curves/pasta.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.vesta = exports.pallas = exports.q = exports.p = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha256_1 = require("@noble/hashes/sha256"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const mod = require("./abstract/modular.js"); +exports.p = BigInt('0x40000000000000000000000000000000224698fc094cf91b992d30ed00000001'); +exports.q = BigInt('0x40000000000000000000000000000000224698fc0994a8dd8c46eb2100000001'); +// https://neuromancer.sk/std/other/Pallas +exports.pallas = (0, weierstrass_js_1.weierstrass)({ + a: BigInt(0), + b: BigInt(5), + Fp: mod.Field(exports.p), + n: exports.q, + Gx: mod.mod(BigInt(-1), exports.p), + Gy: BigInt(2), + h: BigInt(1), + ...(0, _shortw_utils_js_1.getHash)(sha256_1.sha256), +}); +// https://neuromancer.sk/std/other/Vesta +exports.vesta = (0, weierstrass_js_1.weierstrass)({ + a: BigInt(0), + b: BigInt(5), + Fp: mod.Field(exports.q), + n: exports.p, + Gx: mod.mod(BigInt(-1), exports.q), + Gy: BigInt(2), + h: BigInt(1), + ...(0, _shortw_utils_js_1.getHash)(sha256_1.sha256), +}); +//# sourceMappingURL=pasta.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/pasta.js.map b/node_modules/@noble/curves/pasta.js.map new file mode 100644 index 0000000..5ea530c --- /dev/null +++ b/node_modules/@noble/curves/pasta.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pasta.js","sourceRoot":"","sources":["src/pasta.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,iDAA8C;AAC9C,8DAAwD;AACxD,yDAA6C;AAC7C,6CAA6C;AAEhC,QAAA,CAAC,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AACjF,QAAA,CAAC,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAE9F,0CAA0C;AAC7B,QAAA,MAAM,GAAG,IAAA,4BAAW,EAAC;IAChC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,SAAC,CAAC;IAChB,CAAC,EAAE,SAAC;IACJ,EAAE,EAAE,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,SAAC,CAAC;IAC1B,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,IAAA,0BAAO,EAAC,eAAM,CAAC;CACnB,CAAC,CAAC;AACH,yCAAyC;AAC5B,QAAA,KAAK,GAAG,IAAA,4BAAW,EAAC;IAC/B,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,SAAC,CAAC;IAChB,CAAC,EAAE,SAAC;IACJ,EAAE,EAAE,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,SAAC,CAAC;IAC1B,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,IAAA,0BAAO,EAAC,eAAM,CAAC;CACnB,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/secp256k1.d.ts b/node_modules/@noble/curves/secp256k1.d.ts new file mode 100644 index 0000000..b94df77 --- /dev/null +++ b/node_modules/@noble/curves/secp256k1.d.ts @@ -0,0 +1,93 @@ +import { mod } from './abstract/modular.js'; +import { ProjPointType as PointType } from './abstract/weierstrass.js'; +import type { Hex, PrivKey } from './abstract/utils.js'; +import { bytesToNumberBE, numberToBytesBE } from './abstract/utils.js'; +export declare const secp256k1: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: PointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: PointType) => PointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: Hex, privKey: PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: Hex | { + r: bigint; + s: bigint; + }, msgHash: Hex, publicKey: Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: PrivKey) => bigint; + isValidPrivateKey(privateKey: PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: PointType | undefined) => PointType; + }; +}>; +declare function taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array; +/** + * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point. + * @returns valid point checked for being on-curve + */ +declare function lift_x(x: bigint): PointType; +/** + * Schnorr public key is just `x` coordinate of Point as per BIP340. + */ +declare function schnorrGetPublicKey(privateKey: Hex): Uint8Array; +/** + * Creates Schnorr signature as per BIP340. Verifies itself before returning anything. + * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous. + */ +declare function schnorrSign(message: Hex, privateKey: PrivKey, auxRand?: Hex): Uint8Array; +/** + * Verifies Schnorr signature. + * Will swallow errors & return false except for initial type validation of arguments. + */ +declare function schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean; +export declare const schnorr: { + getPublicKey: typeof schnorrGetPublicKey; + sign: typeof schnorrSign; + verify: typeof schnorrVerify; + utils: { + randomPrivateKey: () => Uint8Array; + lift_x: typeof lift_x; + pointToBytes: (point: PointType) => Uint8Array; + numberToBytesBE: typeof numberToBytesBE; + bytesToNumberBE: typeof bytesToNumberBE; + taggedHash: typeof taggedHash; + mod: typeof mod; + }; +}; +export declare const hashToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +export {}; +//# sourceMappingURL=secp256k1.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/secp256k1.d.ts.map b/node_modules/@noble/curves/secp256k1.d.ts.map new file mode 100644 index 0000000..c6ddafc --- /dev/null +++ b/node_modules/@noble/curves/secp256k1.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"secp256k1.d.ts","sourceRoot":"","sources":["src/secp256k1.ts"],"names":[],"mappings":"AAGA,OAAO,EAAS,GAAG,EAAQ,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,aAAa,IAAI,SAAS,EAAuB,MAAM,2BAA2B,CAAC;AAC5F,OAAO,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,eAAe,EAA4B,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAwCjG,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA2CrB,CAAC;AASF,iBAAS,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,QAAQ,EAAE,UAAU,EAAE,GAAG,UAAU,CAQtE;AAkBD;;;GAGG;AACH,iBAAS,MAAM,CAAC,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC,MAAM,CAAC,CAS5C;AAQD;;GAEG;AACH,iBAAS,mBAAmB,CAAC,UAAU,EAAE,GAAG,GAAG,UAAU,CAExD;AAED;;;GAGG;AACH,iBAAS,WAAW,CAClB,OAAO,EAAE,GAAG,EACZ,UAAU,EAAE,OAAO,EACnB,OAAO,GAAE,GAAqB,GAC7B,UAAU,CAgBZ;AAED;;;GAGG;AACH,iBAAS,aAAa,CAAC,SAAS,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,GAAG,OAAO,CAiB5E;AAED,eAAO,MAAM,OAAO;;;;;;;8BA5FS,UAAU,MAAM,CAAC;;;;;;CAyGzC,CAAC;AA0DN,eAAO,MAAM,WAAW,uJAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,uJAA8C,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/secp256k1.js b/node_modules/@noble/curves/secp256k1.js new file mode 100644 index 0000000..463edcc --- /dev/null +++ b/node_modules/@noble/curves/secp256k1.js @@ -0,0 +1,257 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeToCurve = exports.hashToCurve = exports.schnorr = exports.secp256k1 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha256_1 = require("@noble/hashes/sha256"); +const utils_1 = require("@noble/hashes/utils"); +const modular_js_1 = require("./abstract/modular.js"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const utils_js_1 = require("./abstract/utils.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'); +const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); +const _1n = BigInt(1); +const _2n = BigInt(2); +const divNearest = (a, b) => (a + b / _2n) / b; +/** + * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit. + * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00] + */ +function sqrtMod(y) { + const P = secp256k1P; + // prettier-ignore + const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + // prettier-ignore + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = (y * y * y) % P; // x^3, 11 + const b3 = (b2 * b2 * y) % P; // x^7 + const b6 = ((0, modular_js_1.pow2)(b3, _3n, P) * b3) % P; + const b9 = ((0, modular_js_1.pow2)(b6, _3n, P) * b3) % P; + const b11 = ((0, modular_js_1.pow2)(b9, _2n, P) * b2) % P; + const b22 = ((0, modular_js_1.pow2)(b11, _11n, P) * b11) % P; + const b44 = ((0, modular_js_1.pow2)(b22, _22n, P) * b22) % P; + const b88 = ((0, modular_js_1.pow2)(b44, _44n, P) * b44) % P; + const b176 = ((0, modular_js_1.pow2)(b88, _88n, P) * b88) % P; + const b220 = ((0, modular_js_1.pow2)(b176, _44n, P) * b44) % P; + const b223 = ((0, modular_js_1.pow2)(b220, _3n, P) * b3) % P; + const t1 = ((0, modular_js_1.pow2)(b223, _23n, P) * b22) % P; + const t2 = ((0, modular_js_1.pow2)(t1, _6n, P) * b2) % P; + const root = (0, modular_js_1.pow2)(t2, _2n, P); + if (!Fp.eql(Fp.sqr(root), y)) + throw new Error('Cannot find square root'); + return root; +} +const Fp = (0, modular_js_1.Field)(secp256k1P, undefined, undefined, { sqrt: sqrtMod }); +exports.secp256k1 = (0, _shortw_utils_js_1.createCurve)({ + a: BigInt(0), + b: BigInt(7), + Fp, + n: secp256k1N, + // Base point (x, y) aka generator point + Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), + Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), + h: BigInt(1), + lowS: true, + /** + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 + */ + endo: { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + splitScalar: (k) => { + const n = secp256k1N; + const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); + const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); + const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); + const b2 = a1; + const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16) + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = (0, modular_js_1.mod)(k - c1 * a1 - c2 * a2, n); + let k2 = (0, modular_js_1.mod)(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) + k1 = n - k1; + if (k2neg) + k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error('splitScalar: Endomorphism failed, k=' + k); + } + return { k1neg, k1, k2neg, k2 }; + }, + }, +}, sha256_1.sha256); +// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code. +// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki +const _0n = BigInt(0); +const fe = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1P; +const ge = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1N; +/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */ +const TAGGED_HASH_PREFIXES = {}; +function taggedHash(tag, ...messages) { + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === undefined) { + const tagH = (0, sha256_1.sha256)(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + tagP = (0, utils_js_1.concatBytes)(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return (0, sha256_1.sha256)((0, utils_js_1.concatBytes)(tagP, ...messages)); +} +// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03 +const pointToBytes = (point) => point.toRawBytes(true).slice(1); +const numTo32b = (n) => (0, utils_js_1.numberToBytesBE)(n, 32); +const modP = (x) => (0, modular_js_1.mod)(x, secp256k1P); +const modN = (x) => (0, modular_js_1.mod)(x, secp256k1N); +const Point = exports.secp256k1.ProjectivePoint; +const GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b); +// Calculate point, scalar and bytes +function schnorrGetExtPubKey(priv) { + let d_ = exports.secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey + let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside + const scalar = p.hasEvenY() ? d_ : modN(-d_); + return { scalar: scalar, bytes: pointToBytes(p) }; +} +/** + * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point. + * @returns valid point checked for being on-curve + */ +function lift_x(x) { + if (!fe(x)) + throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p. + const xx = modP(x * x); + const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p. + let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p. + if (y % _2n !== _0n) + y = modP(-y); // Return the unique point P such that x(P) = x and + const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise. + p.assertValidity(); + return p; +} +/** + * Create tagged hash, convert it to bigint, reduce modulo-n. + */ +function challenge(...args) { + return modN((0, utils_js_1.bytesToNumberBE)(taggedHash('BIP0340/challenge', ...args))); +} +/** + * Schnorr public key is just `x` coordinate of Point as per BIP340. + */ +function schnorrGetPublicKey(privateKey) { + return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G) +} +/** + * Creates Schnorr signature as per BIP340. Verifies itself before returning anything. + * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous. + */ +function schnorrSign(message, privateKey, auxRand = (0, utils_1.randomBytes)(32)) { + const m = (0, utils_js_1.ensureBytes)('message', message); + const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder + const a = (0, utils_js_1.ensureBytes)('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array + const t = numTo32b(d ^ (0, utils_js_1.bytesToNumberBE)(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a) + const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m) + const k_ = modN((0, utils_js_1.bytesToNumberBE)(rand)); // Let k' = int(rand) mod n + if (k_ === _0n) + throw new Error('sign failed: k is zero'); // Fail if k' = 0. + const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G. + const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n. + const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n). + sig.set(rx, 0); + sig.set(numTo32b(modN(k + e * d)), 32); + // If Verify(bytes(P), m, sig) (see below) returns failure, abort + if (!schnorrVerify(sig, m, px)) + throw new Error('sign: Invalid signature produced'); + return sig; +} +/** + * Verifies Schnorr signature. + * Will swallow errors & return false except for initial type validation of arguments. + */ +function schnorrVerify(signature, message, publicKey) { + const sig = (0, utils_js_1.ensureBytes)('signature', signature, 64); + const m = (0, utils_js_1.ensureBytes)('message', message); + const pub = (0, utils_js_1.ensureBytes)('publicKey', publicKey, 32); + try { + const P = lift_x((0, utils_js_1.bytesToNumberBE)(pub)); // P = lift_x(int(pk)); fail if that fails + const r = (0, utils_js_1.bytesToNumberBE)(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p. + if (!fe(r)) + return false; + const s = (0, utils_js_1.bytesToNumberBE)(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n. + if (!ge(s)) + return false; + const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n + const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P + if (!R || !R.hasEvenY() || R.toAffine().x !== r) + return false; // -eP == (n-e)P + return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r. + } + catch (error) { + return false; + } +} +exports.schnorr = (() => ({ + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + utils: { + randomPrivateKey: exports.secp256k1.utils.randomPrivateKey, + lift_x, + pointToBytes, + numberToBytesBE: utils_js_1.numberToBytesBE, + bytesToNumberBE: utils_js_1.bytesToNumberBE, + taggedHash, + mod: modular_js_1.mod, + }, +}))(); +const isoMap = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.isogenyMap)(Fp, [ + // xNum + [ + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7', + '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581', + '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262', + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c', + ], + // xDen + [ + '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b', + '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c', + '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3', + '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931', + '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84', + ], + // yDen + [ + '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b', + '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573', + '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], +].map((i) => i.map((j) => BigInt(j)))))(); +const mapSWU = /* @__PURE__ */ (() => (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, { + A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'), + B: BigInt('1771'), + Z: Fp.create(BigInt('-11')), +}))(); +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.secp256k1.ProjectivePoint, (scalars) => { + const { x, y } = mapSWU(Fp.create(scalars[0])); + return isoMap(x, y); +}, { + DST: 'secp256k1_XMD:SHA-256_SSWU_RO_', + encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256_1.sha256, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +//# sourceMappingURL=secp256k1.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/secp256k1.js.map b/node_modules/@noble/curves/secp256k1.js.map new file mode 100644 index 0000000..4d76de2 --- /dev/null +++ b/node_modules/@noble/curves/secp256k1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"secp256k1.js","sourceRoot":"","sources":["src/secp256k1.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,iDAA8C;AAC9C,+CAAkD;AAClD,sDAAyD;AACzD,8DAA4F;AAE5F,kDAAiG;AACjG,kEAAuE;AACvE,yDAAiD;AAEjD,MAAM,UAAU,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAChG,MAAM,UAAU,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAChG,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,UAAU,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;AAE/D;;;GAGG;AACH,SAAS,OAA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OAAiB,EAAE,EAAE;IACpB,MAAM,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/C,OAAO,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AACtB,CAAC,EACD;IACE,GAAG,EAAE,gCAAgC;IACrC,SAAS,EAAE,gCAAgC;IAC3C,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,eAAM;CACb,CACF,CAAC,EAAE,CAAC;AACM,QAAA,WAAW,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACxD,QAAA,aAAa,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/src/_shortw_utils.ts b/node_modules/@noble/curves/src/_shortw_utils.ts new file mode 100644 index 0000000..3ae5ca4 --- /dev/null +++ b/node_modules/@noble/curves/src/_shortw_utils.ts @@ -0,0 +1,20 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { hmac } from '@noble/hashes/hmac'; +import { concatBytes, randomBytes } from '@noble/hashes/utils'; +import { weierstrass, CurveType } from './abstract/weierstrass.js'; +import { CHash } from './abstract/utils.js'; + +// connects noble-curves to noble-hashes +export function getHash(hash: CHash) { + return { + hash, + hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(hash, key, concatBytes(...msgs)), + randomBytes, + }; +} +// Same API as @noble/hashes, with ability to create curve with custom hash +type CurveDef = Readonly>; +export function createCurve(curveDef: CurveDef, defHash: CHash) { + const create = (hash: CHash) => weierstrass({ ...curveDef, ...getHash(hash) }); + return Object.freeze({ ...create(defHash), create }); +} diff --git a/node_modules/@noble/curves/src/abstract/bls.ts b/node_modules/@noble/curves/src/abstract/bls.ts new file mode 100644 index 0000000..ba4b6b0 --- /dev/null +++ b/node_modules/@noble/curves/src/abstract/bls.ts @@ -0,0 +1,398 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +/** + * BLS (Barreto-Lynn-Scott) family of pairing-friendly curves. + * Implements BLS (Boneh-Lynn-Shacham) signatures. + * Consists of two curves: G1 and G2: + * - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4. + * - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1 + * - Gt, created by bilinear (ate) pairing e(G1, G2), consists of p-th roots of unity in + * Fq^k where k is embedding degree. Only degree 12 is currently supported, 24 is not. + * Pairing is used to aggregate and verify signatures. + * We are using Fp for private keys (shorter) and Fp₂ for signatures (longer). + * Some projects may prefer to swap this relation, it is not supported for now. + */ +import { AffinePoint } from './curve.js'; +import { IField, getMinHashLength, mapHashToField } from './modular.js'; +import { Hex, PrivKey, CHash, bitLen, bitGet, ensureBytes } from './utils.js'; +import * as htf from './hash-to-curve.js'; +import { + CurvePointsType, + ProjPointType as ProjPointType, + CurvePointsRes, + weierstrassPoints, +} from './weierstrass.js'; + +type Fp = bigint; // Can be different field? + +// prettier-ignore +const _2n = BigInt(2), _3n = BigInt(3); + +export type SignatureCoder = { + fromHex(hex: Hex): ProjPointType; + toRawBytes(point: ProjPointType): Uint8Array; + toHex(point: ProjPointType): string; +}; + +export type CurveType = { + G1: Omit, 'n'> & { + mapToCurve: htf.MapToCurve; + htfDefaults: htf.Opts; + }; + G2: Omit, 'n'> & { + Signature: SignatureCoder; + mapToCurve: htf.MapToCurve; + htfDefaults: htf.Opts; + }; + fields: { + Fp: IField; + Fr: IField; + Fp2: IField & { + reim: (num: Fp2) => { re: bigint; im: bigint }; + multiplyByB: (num: Fp2) => Fp2; + frobeniusMap(num: Fp2, power: number): Fp2; + }; + Fp6: IField; + Fp12: IField & { + frobeniusMap(num: Fp12, power: number): Fp12; + multiplyBy014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12; + conjugate(num: Fp12): Fp12; + finalExponentiate(num: Fp12): Fp12; + }; + }; + params: { + x: bigint; + r: bigint; + }; + htfDefaults: htf.Opts; + hash: CHash; // Because we need outputLen for DRBG + randomBytes: (bytesLength?: number) => Uint8Array; +}; + +export type CurveFn = { + getPublicKey: (privateKey: PrivKey) => Uint8Array; + sign: { + (message: Hex, privateKey: PrivKey): Uint8Array; + (message: ProjPointType, privateKey: PrivKey): ProjPointType; + }; + verify: ( + signature: Hex | ProjPointType, + message: Hex | ProjPointType, + publicKey: Hex | ProjPointType + ) => boolean; + verifyBatch: ( + signature: Hex | ProjPointType, + messages: (Hex | ProjPointType)[], + publicKeys: (Hex | ProjPointType)[] + ) => boolean; + aggregatePublicKeys: { + (publicKeys: Hex[]): Uint8Array; + (publicKeys: ProjPointType[]): ProjPointType; + }; + aggregateSignatures: { + (signatures: Hex[]): Uint8Array; + (signatures: ProjPointType[]): ProjPointType; + }; + millerLoop: (ell: [Fp2, Fp2, Fp2][], g1: [Fp, Fp]) => Fp12; + pairing: (P: ProjPointType, Q: ProjPointType, withFinalExponent?: boolean) => Fp12; + G1: CurvePointsRes & ReturnType>; + G2: CurvePointsRes & ReturnType>; + Signature: SignatureCoder; + params: { + x: bigint; + r: bigint; + G1b: bigint; + G2b: Fp2; + }; + fields: { + Fp: IField; + Fp2: IField; + Fp6: IField; + Fp12: IField; + Fr: IField; + }; + utils: { + randomPrivateKey: () => Uint8Array; + calcPairingPrecomputes: (p: AffinePoint) => [Fp2, Fp2, Fp2][]; + }; +}; + +export function bls( + CURVE: CurveType +): CurveFn { + // Fields are specific for curve, so for now we'll need to pass them with opts + const { Fp, Fr, Fp2, Fp6, Fp12 } = CURVE.fields; + const BLS_X_LEN = bitLen(CURVE.params.x); + + // Pre-compute coefficients for sparse multiplication + // Point addition and point double calculations is reused for coefficients + function calcPairingPrecomputes(p: AffinePoint) { + const { x, y } = p; + // prettier-ignore + const Qx = x, Qy = y, Qz = Fp2.ONE; + // prettier-ignore + let Rx = Qx, Ry = Qy, Rz = Qz; + let ell_coeff: [Fp2, Fp2, Fp2][] = []; + for (let i = BLS_X_LEN - 2; i >= 0; i--) { + // Double + let t0 = Fp2.sqr(Ry); // Ry² + let t1 = Fp2.sqr(Rz); // Rz² + let t2 = Fp2.multiplyByB(Fp2.mul(t1, _3n)); // 3 * T1 * B + let t3 = Fp2.mul(t2, _3n); // 3 * T2 + let t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0); // (Ry + Rz)² - T1 - T0 + ell_coeff.push([ + Fp2.sub(t2, t0), // T2 - T0 + Fp2.mul(Fp2.sqr(Rx), _3n), // 3 * Rx² + Fp2.neg(t4), // -T4 + ]); + Rx = Fp2.div(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), _2n); // ((T0 - T3) * Rx * Ry) / 2 + Ry = Fp2.sub(Fp2.sqr(Fp2.div(Fp2.add(t0, t3), _2n)), Fp2.mul(Fp2.sqr(t2), _3n)); // ((T0 + T3) / 2)² - 3 * T2² + Rz = Fp2.mul(t0, t4); // T0 * T4 + if (bitGet(CURVE.params.x, i)) { + // Addition + let t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); // Ry - Qy * Rz + let t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz)); // Rx - Qx * Rz + ell_coeff.push([ + Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy)), // T0 * Qx - T1 * Qy + Fp2.neg(t0), // -T0 + t1, // T1 + ]); + let t2 = Fp2.sqr(t1); // T1² + let t3 = Fp2.mul(t2, t1); // T2 * T1 + let t4 = Fp2.mul(t2, Rx); // T2 * Rx + let t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n)), Fp2.mul(Fp2.sqr(t0), Rz)); // T3 - 2 * T4 + T0² * Rz + Rx = Fp2.mul(t1, t5); // T1 * T5 + Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry)); // (T4 - T5) * T0 - T3 * Ry + Rz = Fp2.mul(Rz, t3); // Rz * T3 + } + } + return ell_coeff; + } + + function millerLoop(ell: [Fp2, Fp2, Fp2][], g1: [Fp, Fp]): Fp12 { + const { x } = CURVE.params; + const Px = g1[0]; + const Py = g1[1]; + let f12 = Fp12.ONE; + for (let j = 0, i = BLS_X_LEN - 2; i >= 0; i--, j++) { + const E = ell[j]; + f12 = Fp12.multiplyBy014(f12, E[0], Fp2.mul(E[1], Px), Fp2.mul(E[2], Py)); + if (bitGet(x, i)) { + j += 1; + const F = ell[j]; + f12 = Fp12.multiplyBy014(f12, F[0], Fp2.mul(F[1], Px), Fp2.mul(F[2], Py)); + } + if (i !== 0) f12 = Fp12.sqr(f12); + } + return Fp12.conjugate(f12); + } + + const utils = { + randomPrivateKey: (): Uint8Array => { + const length = getMinHashLength(Fr.ORDER); + return mapHashToField(CURVE.randomBytes(length), Fr.ORDER); + }, + calcPairingPrecomputes, + }; + + // Point on G1 curve: (x, y) + const G1_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G1 }); + const G1 = Object.assign( + G1_, + htf.createHasher(G1_.ProjectivePoint, CURVE.G1.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G1.htfDefaults, + }) + ); + + // Sparse multiplication against precomputed coefficients + // TODO: replace with weakmap? + type withPairingPrecomputes = { _PPRECOMPUTES: [Fp2, Fp2, Fp2][] | undefined }; + function pairingPrecomputes(point: G2): [Fp2, Fp2, Fp2][] { + const p = point as G2 & withPairingPrecomputes; + if (p._PPRECOMPUTES) return p._PPRECOMPUTES; + p._PPRECOMPUTES = calcPairingPrecomputes(point.toAffine()); + return p._PPRECOMPUTES; + } + + // TODO: export + // function clearPairingPrecomputes(point: G2) { + // const p = point as G2 & withPairingPrecomputes; + // p._PPRECOMPUTES = undefined; + // } + + // Point on G2 curve (complex numbers): (x₁, x₂+i), (y₁, y₂+i) + const G2_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G2 }); + const G2 = Object.assign( + G2_, + htf.createHasher(G2_.ProjectivePoint as htf.H2CPointConstructor, CURVE.G2.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G2.htfDefaults, + }) + ); + + const { Signature } = CURVE.G2; + + // Calculates bilinear pairing + function pairing(Q: G1, P: G2, withFinalExponent: boolean = true): Fp12 { + if (Q.equals(G1.ProjectivePoint.ZERO) || P.equals(G2.ProjectivePoint.ZERO)) + throw new Error('pairing is not available for ZERO point'); + Q.assertValidity(); + P.assertValidity(); + // Performance: 9ms for millerLoop and ~14ms for exp. + const Qa = Q.toAffine(); + const looped = millerLoop(pairingPrecomputes(P), [Qa.x, Qa.y]); + return withFinalExponent ? Fp12.finalExponentiate(looped) : looped; + } + type G1 = typeof G1.ProjectivePoint.BASE; + type G2 = typeof G2.ProjectivePoint.BASE; + + type G1Hex = Hex | G1; + type G2Hex = Hex | G2; + function normP1(point: G1Hex): G1 { + return point instanceof G1.ProjectivePoint ? (point as G1) : G1.ProjectivePoint.fromHex(point); + } + function normP2(point: G2Hex): G2 { + return point instanceof G2.ProjectivePoint ? point : Signature.fromHex(point); + } + function normP2Hash(point: G2Hex, htfOpts?: htf.htfBasicOpts): G2 { + return point instanceof G2.ProjectivePoint + ? point + : (G2.hashToCurve(ensureBytes('point', point), htfOpts) as G2); + } + + // Multiplies generator by private key. + // P = pk x G + function getPublicKey(privateKey: PrivKey): Uint8Array { + return G1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true); + } + + // Executes `hashToCurve` on the message and then multiplies the result by private key. + // S = pk x H(m) + function sign(message: Hex, privateKey: PrivKey, htfOpts?: htf.htfBasicOpts): Uint8Array; + function sign(message: G2, privateKey: PrivKey, htfOpts?: htf.htfBasicOpts): G2; + function sign(message: G2Hex, privateKey: PrivKey, htfOpts?: htf.htfBasicOpts): Uint8Array | G2 { + const msgPoint = normP2Hash(message, htfOpts); + msgPoint.assertValidity(); + const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey)); + if (message instanceof G2.ProjectivePoint) return sigPoint; + return Signature.toRawBytes(sigPoint); + } + + // Checks if pairing of public key & hash is equal to pairing of generator & signature. + // e(P, H(m)) == e(G, S) + function verify( + signature: G2Hex, + message: G2Hex, + publicKey: G1Hex, + htfOpts?: htf.htfBasicOpts + ): boolean { + const P = normP1(publicKey); + const Hm = normP2Hash(message, htfOpts); + const G = G1.ProjectivePoint.BASE; + const S = normP2(signature); + // Instead of doing 2 exponentiations, we use property of billinear maps + // and do one exp after multiplying 2 points. + const ePHm = pairing(P.negate(), Hm, false); + const eGS = pairing(G, S, false); + const exp = Fp12.finalExponentiate(Fp12.mul(eGS, ePHm)); + return Fp12.eql(exp, Fp12.ONE); + } + + // Adds a bunch of public key points together. + // pk1 + pk2 + pk3 = pkA + function aggregatePublicKeys(publicKeys: Hex[]): Uint8Array; + function aggregatePublicKeys(publicKeys: G1[]): G1; + function aggregatePublicKeys(publicKeys: G1Hex[]): Uint8Array | G1 { + if (!publicKeys.length) throw new Error('Expected non-empty array'); + const agg = publicKeys.map(normP1).reduce((sum, p) => sum.add(p), G1.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (publicKeys[0] instanceof G1.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + // toRawBytes ensures point validity + return aggAffine.toRawBytes(true); + } + + // Adds a bunch of signature points together. + function aggregateSignatures(signatures: Hex[]): Uint8Array; + function aggregateSignatures(signatures: G2[]): G2; + function aggregateSignatures(signatures: G2Hex[]): Uint8Array | G2 { + if (!signatures.length) throw new Error('Expected non-empty array'); + const agg = signatures.map(normP2).reduce((sum, s) => sum.add(s), G2.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (signatures[0] instanceof G2.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + return Signature.toRawBytes(aggAffine); + } + + // https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407 + // e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si)) + function verifyBatch( + signature: G2Hex, + messages: G2Hex[], + publicKeys: G1Hex[], + htfOpts?: htf.htfBasicOpts + ): boolean { + // @ts-ignore + // console.log('verifyBatch', bytesToHex(signature as any), messages, publicKeys.map(bytesToHex)); + + if (!messages.length) throw new Error('Expected non-empty messages array'); + if (publicKeys.length !== messages.length) + throw new Error('Pubkey count should equal msg count'); + const sig = normP2(signature); + const nMessages = messages.map((i) => normP2Hash(i, htfOpts)); + const nPublicKeys = publicKeys.map(normP1); + try { + const paired = []; + for (const message of new Set(nMessages)) { + const groupPublicKey = nMessages.reduce( + (groupPublicKey, subMessage, i) => + subMessage === message ? groupPublicKey.add(nPublicKeys[i]) : groupPublicKey, + G1.ProjectivePoint.ZERO + ); + // const msg = message instanceof PointG2 ? message : await PointG2.hashToCurve(message); + // Possible to batch pairing for same msg with different groupPublicKey here + paired.push(pairing(groupPublicKey, message, false)); + } + paired.push(pairing(G1.ProjectivePoint.BASE.negate(), sig, false)); + const product = paired.reduce((a, b) => Fp12.mul(a, b), Fp12.ONE); + const exp = Fp12.finalExponentiate(product); + return Fp12.eql(exp, Fp12.ONE); + } catch { + return false; + } + } + + G1.ProjectivePoint.BASE._setWindowSize(4); + + return { + getPublicKey, + sign, + verify, + verifyBatch, + aggregatePublicKeys, + aggregateSignatures, + millerLoop, + pairing, + G1, + G2, + Signature, + fields: { + Fr, + Fp, + Fp2, + Fp6, + Fp12, + }, + params: { + x: CURVE.params.x, + r: CURVE.params.r, + G1b: CURVE.G1.b, + G2b: CURVE.G2.b, + }, + utils, + }; +} diff --git a/node_modules/@noble/curves/src/abstract/curve.ts b/node_modules/@noble/curves/src/abstract/curve.ts new file mode 100644 index 0000000..2876377 --- /dev/null +++ b/node_modules/@noble/curves/src/abstract/curve.ts @@ -0,0 +1,203 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Abelian group utilities +import { IField, validateField, nLength } from './modular.js'; +import { validateObject } from './utils.js'; +const _0n = BigInt(0); +const _1n = BigInt(1); + +export type AffinePoint = { + x: T; + y: T; +} & { z?: never; t?: never }; + +export interface Group> { + double(): T; + negate(): T; + add(other: T): T; + subtract(other: T): T; + equals(other: T): boolean; + multiply(scalar: bigint): T; +} + +export type GroupConstructor = { + BASE: T; + ZERO: T; +}; +export type Mapper = (i: T[]) => T[]; + +// Elliptic curve multiplication of Point by scalar. Fragile. +// Scalars should always be less than curve order: this should be checked inside of a curve itself. +// Creates precomputation tables for fast multiplication: +// - private scalar is split by fixed size windows of W bits +// - every window point is collected from window's table & added to accumulator +// - since windows are different, same point inside tables won't be accessed more than once per calc +// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar) +// - +1 window is neccessary for wNAF +// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication +// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow +// windows to be in different memory locations +export function wNAF>(c: GroupConstructor, bits: number) { + const constTimeNegate = (condition: boolean, item: T): T => { + const neg = item.negate(); + return condition ? neg : item; + }; + const opts = (W: number) => { + const windows = Math.ceil(bits / W) + 1; // +1, because + const windowSize = 2 ** (W - 1); // -1 because we skip zero + return { windows, windowSize }; + }; + return { + constTimeNegate, + // non-const time multiplication ladder + unsafeLadder(elm: T, n: bigint) { + let p = c.ZERO; + let d: T = elm; + while (n > _0n) { + if (n & _1n) p = p.add(d); + d = d.double(); + n >>= _1n; + } + return p; + }, + + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm: T, W: number): Group[] { + const { windows, windowSize } = opts(W); + const points: T[] = []; + let p: T = elm; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + // =1, because we skip zero + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + }, + + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T } { + // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise + // But need to carefully remove other checks before wNAF. ORDER == bits here + const { windows, windowSize } = opts(W); + + let p = c.ZERO; + let f = c.BASE; + + const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc. + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + // Extract W bits. + let wbits = Number(n & mask); + + // Shift number by W bits. + n >>= shiftBy; + + // If the bits are bigger than max size, we'll split those. + // +224 => 256 - 32 + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n; + } + + // This code was first written with assumption that 'f' and 'p' will never be infinity point: + // since each addition is multiplied by 2 ** W, it cannot cancel each other. However, + // there is negate now: it is possible that negated element from low value + // would be the same as high element, which will create carry into next window. + // It's not obvious how this can fail, but still worth investigating later. + + // Check if we're onto Zero point. + // Add random point inside current window to f. + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + // The most important part for const-time getPublicKey + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ() + // Even if the variable is still unused, there are some checks which will + // throw an exception, so compiler needs to prove they won't happen, which is hard. + // At this point there is a way to F be infinity-point even if p is not, + // which makes it less const-time: around 1 bigint multiply. + return { p, f }; + }, + + wNAFCached(P: T, precomputesMap: Map, n: bigint, transform: Mapper): { p: T; f: T } { + // @ts-ignore + const W: number = P._WINDOW_SIZE || 1; + // Calculate precomputes on a first run, reuse them after + let comp = precomputesMap.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W) as T[]; + if (W !== 1) { + precomputesMap.set(P, transform(comp)); + } + } + return this.wNAF(W, comp, n); + }, + }; +} + +// Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok. +// Though generator can be different (Fp2 / Fp6 for BLS). +export type BasicCurve = { + Fp: IField; // Field over which we'll do calculations (Fp) + n: bigint; // Curve order, total count of valid points in the field + nBitLength?: number; // bit length of curve order + nByteLength?: number; // byte length of curve order + h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation + hEff?: bigint; // Number to multiply to clear cofactor + Gx: T; // base point X coordinate + Gy: T; // base point Y coordinate + allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey +}; + +export function validateBasic(curve: BasicCurve & T) { + validateField(curve.Fp); + validateObject( + curve, + { + n: 'bigint', + h: 'bigint', + Gx: 'field', + Gy: 'field', + }, + { + nBitLength: 'isSafeInteger', + nByteLength: 'isSafeInteger', + } + ); + // Set defaults + return Object.freeze({ + ...nLength(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER }, + } as const); +} diff --git a/node_modules/@noble/curves/src/abstract/edwards.ts b/node_modules/@noble/curves/src/abstract/edwards.ts new file mode 100644 index 0000000..9124f66 --- /dev/null +++ b/node_modules/@noble/curves/src/abstract/edwards.ts @@ -0,0 +1,513 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y² +import { mod } from './modular.js'; +import * as ut from './utils.js'; +import { ensureBytes, FHash, Hex } from './utils.js'; +import { Group, GroupConstructor, wNAF, BasicCurve, validateBasic, AffinePoint } from './curve.js'; + +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8); + +// Edwards curves must declare params a & d. +export type CurveType = BasicCurve & { + a: bigint; // curve param a + d: bigint; // curve param d + hash: FHash; // Hashing + randomBytes: (bytesLength?: number) => Uint8Array; // CSPRNG + adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; // clears bits to get valid field elemtn + domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; // Used for hashing + uvRatio?: (u: bigint, v: bigint) => { isValid: boolean; value: bigint }; // Ratio √(u/v) + prehash?: FHash; // RFC 8032 pre-hashing of messages to sign() / verify() + mapToCurve?: (scalar: bigint[]) => AffinePoint; // for hash-to-curve standard +}; + +// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex: +const VERIFY_DEFAULT = { zip215: true }; + +function validateOpts(curve: CurveType) { + const opts = validateBasic(curve); + ut.validateObject( + curve, + { + hash: 'function', + a: 'bigint', + d: 'bigint', + randomBytes: 'function', + }, + { + adjustScalarBytes: 'function', + domain: 'function', + uvRatio: 'function', + mapToCurve: 'function', + } + ); + // Set defaults + return Object.freeze({ ...opts } as const); +} + +// Instance of Extended Point with coordinates in X, Y, Z, T +export interface ExtPointType extends Group { + readonly ex: bigint; + readonly ey: bigint; + readonly ez: bigint; + readonly et: bigint; + get x(): bigint; + get y(): bigint; + assertValidity(): void; + multiply(scalar: bigint): ExtPointType; + multiplyUnsafe(scalar: bigint): ExtPointType; + isSmallOrder(): boolean; + isTorsionFree(): boolean; + clearCofactor(): ExtPointType; + toAffine(iz?: bigint): AffinePoint; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; +} +// Static methods of Extended Point with coordinates in X, Y, Z, T +export interface ExtPointConstructor extends GroupConstructor { + new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType; + fromAffine(p: AffinePoint): ExtPointType; + fromHex(hex: Hex): ExtPointType; + fromPrivateKey(privateKey: Hex): ExtPointType; +} + +export type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: Hex) => Uint8Array; + sign: (message: Hex, privateKey: Hex, options?: { context?: Hex }) => Uint8Array; + verify: ( + sig: Hex, + message: Hex, + publicKey: Hex, + options?: { context?: Hex; zip215: boolean } + ) => boolean; + ExtendedPoint: ExtPointConstructor; + utils: { + randomPrivateKey: () => Uint8Array; + getExtendedPublicKey: (key: Hex) => { + head: Uint8Array; + prefix: Uint8Array; + scalar: bigint; + point: ExtPointType; + pointBytes: Uint8Array; + }; + }; +}; + +// It is not generic twisted curve for now, but ed25519/ed448 generic implementation +export function twistedEdwards(curveDef: CurveType): CurveFn { + const CURVE = validateOpts(curveDef) as ReturnType; + const { + Fp, + n: CURVE_ORDER, + prehash: prehash, + hash: cHash, + randomBytes, + nByteLength, + h: cofactor, + } = CURVE; + const MASK = _2n << (BigInt(nByteLength * 8) - _1n); + const modP = Fp.create; // Function overrides + + // sqrt(u/v) + const uvRatio = + CURVE.uvRatio || + ((u: bigint, v: bigint) => { + try { + return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) }; + } catch (e) { + return { isValid: false, value: _0n }; + } + }); + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes); // NOOP + const domain = + CURVE.domain || + ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => { + if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported'); + return data; + }); // NOOP + const inBig = (n: bigint) => typeof n === 'bigint' && _0n < n; // n in [1..] + const inRange = (n: bigint, max: bigint) => inBig(n) && inBig(max) && n < max; // n in [1..max-1] + const in0MaskRange = (n: bigint) => n === _0n || inRange(n, MASK); // n in [0..MASK-1] + function assertInRange(n: bigint, max: bigint) { + // n in [1..max-1] + if (inRange(n, max)) return n; + throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`); + } + function assertGE0(n: bigint) { + // n in [0..CURVE_ORDER-1] + return n === _0n ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group + } + const pointPrecomputes = new Map(); + function isPoint(other: unknown) { + if (!(other instanceof Point)) throw new Error('ExtendedPoint expected'); + } + // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy). + // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates + class Point implements ExtPointType { + static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy)); + static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0 + + constructor( + readonly ex: bigint, + readonly ey: bigint, + readonly ez: bigint, + readonly et: bigint + ) { + if (!in0MaskRange(ex)) throw new Error('x required'); + if (!in0MaskRange(ey)) throw new Error('y required'); + if (!in0MaskRange(ez)) throw new Error('z required'); + if (!in0MaskRange(et)) throw new Error('t required'); + } + + get x(): bigint { + return this.toAffine().x; + } + get y(): bigint { + return this.toAffine().y; + } + + static fromAffine(p: AffinePoint): Point { + if (p instanceof Point) throw new Error('extended point not allowed'); + const { x, y } = p || {}; + if (!in0MaskRange(x) || !in0MaskRange(y)) throw new Error('invalid affine point'); + return new Point(x, y, _1n, modP(x * y)); + } + static normalizeZ(points: Point[]): Point[] { + const toInv = Fp.invertBatch(points.map((p) => p.ez)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + + // We calculate precomputes for elliptic curve point multiplication + // using windowed method. This specifies window size and + // stores precomputed values. Usually only base point would be precomputed. + _WINDOW_SIZE?: number; + + // "Private method", don't use it directly + _setWindowSize(windowSize: number) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + // Not required for fromHex(), which always creates valid points. + // Could be useful for fromAffine(). + assertValidity(): void { + const { a, d } = CURVE; + if (this.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below? + // Equation in affine coordinates: ax² + y² = 1 + dx²y² + // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y² + const { ex: X, ey: Y, ez: Z, et: T } = this; + const X2 = modP(X * X); // X² + const Y2 = modP(Y * Y); // Y² + const Z2 = modP(Z * Z); // Z² + const Z4 = modP(Z2 * Z2); // Z⁴ + const aX2 = modP(X2 * a); // aX² + const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z² + const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y² + if (left !== right) throw new Error('bad point: equation left != right (1)'); + // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T + const XY = modP(X * Y); + const ZT = modP(Z * T); + if (XY !== ZT) throw new Error('bad point: equation left != right (2)'); + } + + // Compare one point to another. + equals(other: Point): boolean { + isPoint(other); + const { ex: X1, ey: Y1, ez: Z1 } = this; + const { ex: X2, ey: Y2, ez: Z2 } = other; + const X1Z2 = modP(X1 * Z2); + const X2Z1 = modP(X2 * Z1); + const Y1Z2 = modP(Y1 * Z2); + const Y2Z1 = modP(Y2 * Z1); + return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; + } + + protected is0(): boolean { + return this.equals(Point.ZERO); + } + + negate(): Point { + // Flips point sign to a negative one (-x, y in affine coords) + return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et)); + } + + // Fast algo for doubling Extended Point. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd + // Cost: 4M + 4S + 1*a + 6add + 1*2. + double(): Point { + const { a } = CURVE; + const { ex: X1, ey: Y1, ez: Z1 } = this; + const A = modP(X1 * X1); // A = X12 + const B = modP(Y1 * Y1); // B = Y12 + const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12 + const D = modP(a * A); // D = a*A + const x1y1 = X1 + Y1; + const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B + const G = D + B; // G = D+B + const F = G - C; // F = G-C + const H = D - B; // H = D-B + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + + // Fast algo for adding 2 Extended Points. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd + // Cost: 9M + 1*a + 1*d + 7add. + add(other: Point) { + isPoint(other); + const { a, d } = CURVE; + const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this; + const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other; + // Faster algo for adding 2 Extended Points when curve's a=-1. + // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4 + // Cost: 8M + 8add + 2*2. + // Note: It does not check whether the `other` point is valid. + if (a === BigInt(-1)) { + const A = modP((Y1 - X1) * (Y2 + X2)); + const B = modP((Y1 + X1) * (Y2 - X2)); + const F = modP(B - A); + if (F === _0n) return this.double(); // Same point. Tests say it doesn't affect timing + const C = modP(Z1 * _2n * T2); + const D = modP(T1 * _2n * Z2); + const E = D + C; + const G = B + A; + const H = D - C; + const X3 = modP(E * F); + const Y3 = modP(G * H); + const T3 = modP(E * H); + const Z3 = modP(F * G); + return new Point(X3, Y3, Z3, T3); + } + const A = modP(X1 * X2); // A = X1*X2 + const B = modP(Y1 * Y2); // B = Y1*Y2 + const C = modP(T1 * d * T2); // C = T1*d*T2 + const D = modP(Z1 * Z2); // D = Z1*Z2 + const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B + const F = D - C; // F = D-C + const G = D + C; // G = D+C + const H = modP(B - a * A); // H = B-a*A + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + + return new Point(X3, Y3, Z3, T3); + } + + subtract(other: Point): Point { + return this.add(other.negate()); + } + + private wNAF(n: bigint): { p: Point; f: Point } { + return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ); + } + + // Constant-time multiplication. + multiply(scalar: bigint): Point { + const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER)); + return Point.normalizeZ([p, f])[0]; + } + + // Non-constant-time multiplication. Uses double-and-add algorithm. + // It's faster, but should only be used when you don't care about + // an exposed private key e.g. sig verification. + // Does NOT allow scalars higher than CURVE.n. + multiplyUnsafe(scalar: bigint): Point { + let n = assertGE0(scalar); // 0 <= scalar < CURVE.n + if (n === _0n) return I; + if (this.equals(I) || n === _1n) return this; + if (this.equals(G)) return this.wNAF(n).p; + return wnaf.unsafeLadder(this, n); + } + + // Checks if point is of small order. + // If you add something to small order point, you will have "dirty" + // point with torsion component. + // Multiplies point by cofactor and checks if the result is 0. + isSmallOrder(): boolean { + return this.multiplyUnsafe(cofactor).is0(); + } + + // Multiplies point by curve order and checks if the result is 0. + // Returns `false` is the point is dirty. + isTorsionFree(): boolean { + return wnaf.unsafeLadder(this, CURVE_ORDER).is0(); + } + + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + toAffine(iz?: bigint): AffinePoint { + const { ex: x, ey: y, ez: z } = this; + const is0 = this.is0(); + if (iz == null) iz = is0 ? _8n : (Fp.inv(z) as bigint); // 8 was chosen arbitrarily + const ax = modP(x * iz); + const ay = modP(y * iz); + const zz = modP(z * iz); + if (is0) return { x: _0n, y: _1n }; + if (zz !== _1n) throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + } + + clearCofactor(): Point { + const { h: cofactor } = CURVE; + if (cofactor === _1n) return this; + return this.multiplyUnsafe(cofactor); + } + + // Converts hash string or Uint8Array to Point. + // Uses algo from RFC8032 5.1.3. + static fromHex(hex: Hex, zip215 = false): Point { + const { d, a } = CURVE; + const len = Fp.BYTES; + hex = ensureBytes('pointHex', hex, len); // copy hex to a new array + const normed = hex.slice(); // copy again, we'll manipulate it + const lastByte = hex[len - 1]; // select last byte + normed[len - 1] = lastByte & ~0x80; // clear last bit + const y = ut.bytesToNumberLE(normed); + if (y === _0n) { + // y=0 is allowed + } else { + // RFC8032 prohibits >= p, but ZIP215 doesn't + if (zip215) assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519) + else assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519) + } + + // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case: + // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a) + const y2 = modP(y * y); // denominator is always non-0 mod p. + const u = modP(y2 - _1n); // u = y² - 1 + const v = modP(d * y2 - a); // v = d y² + 1. + let { isValid, value: x } = uvRatio(u, v); // √(u/v) + if (!isValid) throw new Error('Point.fromHex: invalid y coordinate'); + const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper + const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit + if (!zip215 && x === _0n && isLastByteOdd) + // if x=0 and x_0 = 1, fail + throw new Error('Point.fromHex: x=0 and x_0=1'); + if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x + return Point.fromAffine({ x, y }); + } + static fromPrivateKey(privKey: Hex) { + return getExtendedPublicKey(privKey).point; + } + toRawBytes(): Uint8Array { + const { x, y } = this.toAffine(); + const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y) + bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y + return bytes; // and use the last byte to encode sign of x + } + toHex(): string { + return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string. + } + } + const { BASE: G, ZERO: I } = Point; + const wnaf = wNAF(Point, nByteLength * 8); + + function modN(a: bigint) { + return mod(a, CURVE_ORDER); + } + // Little-endian SHA512 with modulo n + function modN_LE(hash: Uint8Array): bigint { + return modN(ut.bytesToNumberLE(hash)); + } + + /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */ + function getExtendedPublicKey(key: Hex) { + const len = nByteLength; + key = ensureBytes('private key', key, len); + // Hash private key with curve's hash function to produce uniformingly random input + // Check byte lengths: ensure(64, h(ensure(32, key))) + const hashed = ensureBytes('hashed private key', cHash(key), 2 * len); + const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE + const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6) + const scalar = modN_LE(head); // The actual private scalar + const point = G.multiply(scalar); // Point on Edwards curve aka public key + const pointBytes = point.toRawBytes(); // Uint8Array representation + return { head, prefix, scalar, point, pointBytes }; + } + + // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared + function getPublicKey(privKey: Hex): Uint8Array { + return getExtendedPublicKey(privKey).pointBytes; + } + + // int('LE', SHA512(dom2(F, C) || msgs)) mod N + function hashDomainToScalar(context: Hex = new Uint8Array(), ...msgs: Uint8Array[]) { + const msg = ut.concatBytes(...msgs); + return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash))); + } + + /** Signs message with privateKey. RFC8032 5.1.6 */ + function sign(msg: Hex, privKey: Hex, options: { context?: Hex } = {}): Uint8Array { + msg = ensureBytes('message', msg); + if (prehash) msg = prehash(msg); // for ed25519ph etc. + const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey); + const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M) + const R = G.multiply(r).toRawBytes(); // R = rG + const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M) + const s = modN(r + k * scalar); // S = (r + k * s) mod L + assertGE0(s); // 0 <= s < l + const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES)); + return ensureBytes('result', res, nByteLength * 2); // 64-byte signature + } + + const verifyOpts: { context?: Hex; zip215?: boolean } = VERIFY_DEFAULT; + function verify(sig: Hex, msg: Hex, publicKey: Hex, options = verifyOpts): boolean { + const { context, zip215 } = options; + const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7. + sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked. + msg = ensureBytes('message', msg); + if (prehash) msg = prehash(msg); // for ed25519ph, etc + + const s = ut.bytesToNumberLE(sig.slice(len, 2 * len)); + // zip215: true is good for consensus-critical apps and allows points < 2^256 + // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p + let A, R, SB; + try { + A = Point.fromHex(publicKey, zip215); + R = Point.fromHex(sig.slice(0, len), zip215); + SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside + } catch (error) { + return false; + } + if (!zip215 && A.isSmallOrder()) return false; + + const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg); + const RkA = R.add(A.multiplyUnsafe(k)); + // [8][S]B = [8]R + [8][k]A' + return RkA.subtract(SB).clearCofactor().equals(Point.ZERO); + } + + G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms. + + const utils = { + getExtendedPublicKey, + // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1. + randomPrivateKey: (): Uint8Array => randomBytes(Fp.BYTES), + + /** + * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT + * values. This slows down first getPublicKey() by milliseconds (see Speed section), + * but allows to speed-up subsequent getPublicKey() calls up to 20x. + * @param windowSize 2, 4, 8, 16 + */ + precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; + }, + }; + + return { + CURVE, + getPublicKey, + sign, + verify, + ExtendedPoint: Point, + utils, + }; +} diff --git a/node_modules/@noble/curves/src/abstract/hash-to-curve.ts b/node_modules/@noble/curves/src/abstract/hash-to-curve.ts new file mode 100644 index 0000000..64d7db4 --- /dev/null +++ b/node_modules/@noble/curves/src/abstract/hash-to-curve.ts @@ -0,0 +1,229 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import type { Group, GroupConstructor, AffinePoint } from './curve.js'; +import { mod, IField } from './modular.js'; +import { bytesToNumberBE, CHash, concatBytes, utf8ToBytes, validateObject } from './utils.js'; + +/** + * * `DST` is a domain separation tag, defined in section 2.2.5 + * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m + * * `m` is extension degree (1 for prime fields) + * * `k` is the target security target in bits (e.g. 128), from section 5.1 + * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF) + * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props + */ +type UnicodeOrBytes = string | Uint8Array; +export type Opts = { + DST: UnicodeOrBytes; + p: bigint; + m: number; + k: number; + expand: 'xmd' | 'xof'; + hash: CHash; +}; + +function validateDST(dst: UnicodeOrBytes): Uint8Array { + if (dst instanceof Uint8Array) return dst; + if (typeof dst === 'string') return utf8ToBytes(dst); + throw new Error('DST must be Uint8Array or string'); +} + +// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE. +const os2ip = bytesToNumberBE; + +// Integer to Octet Stream (numberToBytesBE) +function i2osp(value: number, length: number): Uint8Array { + if (value < 0 || value >= 1 << (8 * length)) { + throw new Error(`bad I2OSP call: value=${value} length=${length}`); + } + const res = Array.from({ length }).fill(0) as number[]; + for (let i = length - 1; i >= 0; i--) { + res[i] = value & 0xff; + value >>>= 8; + } + return new Uint8Array(res); +} + +function strxor(a: Uint8Array, b: Uint8Array): Uint8Array { + const arr = new Uint8Array(a.length); + for (let i = 0; i < a.length; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} + +function isBytes(item: unknown): void { + if (!(item instanceof Uint8Array)) throw new Error('Uint8Array expected'); +} +function isNum(item: unknown): void { + if (!Number.isSafeInteger(item)) throw new Error('number expected'); +} + +// Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits +// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1 +export function expand_message_xmd( + msg: Uint8Array, + DST: Uint8Array, + lenInBytes: number, + H: CHash +): Uint8Array { + isBytes(msg); + isBytes(DST); + isNum(lenInBytes); + // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3 + if (DST.length > 255) DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST)); + const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H; + const ell = Math.ceil(lenInBytes / b_in_bytes); + if (ell > 255) throw new Error('Invalid xmd length'); + const DST_prime = concatBytes(DST, i2osp(DST.length, 1)); + const Z_pad = i2osp(0, r_in_bytes); + const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str + const b = new Array(ell); + const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); + b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime)); + for (let i = 1; i <= ell; i++) { + const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime]; + b[i] = H(concatBytes(...args)); + } + const pseudo_random_bytes = concatBytes(...b); + return pseudo_random_bytes.slice(0, lenInBytes); +} + +// Produces a uniformly random byte string using an extendable-output function (XOF) H. +// 1. The collision resistance of H MUST be at least k bits. +// 2. H MUST be an XOF that has been proved indifferentiable from +// a random oracle under a reasonable cryptographic assumption. +// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2 +export function expand_message_xof( + msg: Uint8Array, + DST: Uint8Array, + lenInBytes: number, + k: number, + H: CHash +): Uint8Array { + isBytes(msg); + isBytes(DST); + isNum(lenInBytes); + // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3 + // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8)); + if (DST.length > 255) { + const dkLen = Math.ceil((2 * k) / 8); + DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest(); + } + if (lenInBytes > 65535 || DST.length > 255) + throw new Error('expand_message_xof: invalid lenInBytes'); + return ( + H.create({ dkLen: lenInBytes }) + .update(msg) + .update(i2osp(lenInBytes, 2)) + // 2. DST_prime = DST || I2OSP(len(DST), 1) + .update(DST) + .update(i2osp(DST.length, 1)) + .digest() + ); +} + +/** + * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F + * https://www.rfc-editor.org/rfc/rfc9380#section-5.2 + * @param msg a byte string containing the message to hash + * @param count the number of elements of F to output + * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above + * @returns [u_0, ..., u_(count - 1)], a list of field elements. + */ +export function hash_to_field(msg: Uint8Array, count: number, options: Opts): bigint[][] { + validateObject(options, { + DST: 'stringOrUint8Array', + p: 'bigint', + m: 'isSafeInteger', + k: 'isSafeInteger', + hash: 'hash', + }); + const { p, k, m, hash, expand, DST: _DST } = options; + isBytes(msg); + isNum(count); + const DST = validateDST(_DST); + const log2p = p.toString(2).length; + const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above + const len_in_bytes = count * m * L; + let prb; // pseudo_random_bytes + if (expand === 'xmd') { + prb = expand_message_xmd(msg, DST, len_in_bytes, hash); + } else if (expand === 'xof') { + prb = expand_message_xof(msg, DST, len_in_bytes, k, hash); + } else if (expand === '_internal_pass') { + // for internal tests only + prb = msg; + } else { + throw new Error('expand must be "xmd" or "xof"'); + } + const u = new Array(count); + for (let i = 0; i < count; i++) { + const e = new Array(m); + for (let j = 0; j < m; j++) { + const elm_offset = L * (j + i * m); + const tv = prb.subarray(elm_offset, elm_offset + L); + e[j] = mod(os2ip(tv), p); + } + u[i] = e; + } + return u; +} + +export function isogenyMap>(field: F, map: [T[], T[], T[], T[]]) { + // Make same order as in spec + const COEFF = map.map((i) => Array.from(i).reverse()); + return (x: T, y: T) => { + const [xNum, xDen, yNum, yDen] = COEFF.map((val) => + val.reduce((acc, i) => field.add(field.mul(acc, x), i)) + ); + x = field.div(xNum, xDen); // xNum / xDen + y = field.mul(y, field.div(yNum, yDen)); // y * (yNum / yDev) + return { x, y }; + }; +} + +export interface H2CPoint extends Group> { + add(rhs: H2CPoint): H2CPoint; + toAffine(iz?: bigint): AffinePoint; + clearCofactor(): H2CPoint; + assertValidity(): void; +} + +export interface H2CPointConstructor extends GroupConstructor> { + fromAffine(ap: AffinePoint): H2CPoint; +} + +export type MapToCurve = (scalar: bigint[]) => AffinePoint; + +// Separated from initialization opts, so users won't accidentally change per-curve parameters +// (changing DST is ok!) +export type htfBasicOpts = { DST: UnicodeOrBytes }; + +export function createHasher( + Point: H2CPointConstructor, + mapToCurve: MapToCurve, + def: Opts & { encodeDST?: UnicodeOrBytes } +) { + if (typeof mapToCurve !== 'function') throw new Error('mapToCurve() must be defined'); + return { + // Encodes byte string to elliptic curve. + // hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 + hashToCurve(msg: Uint8Array, options?: htfBasicOpts) { + const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options } as Opts); + const u0 = Point.fromAffine(mapToCurve(u[0])); + const u1 = Point.fromAffine(mapToCurve(u[1])); + const P = u0.add(u1).clearCofactor(); + P.assertValidity(); + return P; + }, + + // Encodes byte string to elliptic curve. + // encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 + encodeToCurve(msg: Uint8Array, options?: htfBasicOpts) { + const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options } as Opts); + const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor(); + P.assertValidity(); + return P; + }, + }; +} diff --git a/node_modules/@noble/curves/src/abstract/modular.ts b/node_modules/@noble/curves/src/abstract/modular.ts new file mode 100644 index 0000000..ddafcd9 --- /dev/null +++ b/node_modules/@noble/curves/src/abstract/modular.ts @@ -0,0 +1,484 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Utilities for modular arithmetics and finite fields +import { + bitMask, + numberToBytesBE, + numberToBytesLE, + bytesToNumberBE, + bytesToNumberLE, + ensureBytes, + validateObject, +} from './utils.js'; +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); +// prettier-ignore +const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8); +// prettier-ignore +const _9n = BigInt(9), _16n = BigInt(16); + +// Calculates a modulo b +export function mod(a: bigint, b: bigint): bigint { + const result = a % b; + return result >= _0n ? result : b + result; +} +/** + * Efficiently raise num to power and do modular division. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + * @example + * pow(2n, 6n, 11n) // 64n % 11n == 9n + */ +// TODO: use field version && remove +export function pow(num: bigint, power: bigint, modulo: bigint): bigint { + if (modulo <= _0n || power < _0n) throw new Error('Expected power/modulo > 0'); + if (modulo === _1n) return _0n; + let res = _1n; + while (power > _0n) { + if (power & _1n) res = (res * num) % modulo; + num = (num * num) % modulo; + power >>= _1n; + } + return res; +} + +// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4) +export function pow2(x: bigint, power: bigint, modulo: bigint): bigint { + let res = x; + while (power-- > _0n) { + res *= res; + res %= modulo; + } + return res; +} + +// Inverses number over modulo +export function invert(number: bigint, modulo: bigint): bigint { + if (number === _0n || modulo <= _0n) { + throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); + } + // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/ + // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower. + let a = mod(number, modulo); + let b = modulo; + // prettier-ignore + let x = _0n, y = _1n, u = _1n, v = _0n; + while (a !== _0n) { + // JIT applies optimization if those two lines follow each other + const q = b / a; + const r = b % a; + const m = x - u * q; + const n = y - v * q; + // prettier-ignore + b = a, a = r, x = u, y = v, u = m, v = n; + } + const gcd = b; + if (gcd !== _1n) throw new Error('invert: does not exist'); + return mod(x, modulo); +} + +/** + * Tonelli-Shanks square root search algorithm. + * 1. https://eprint.iacr.org/2012/685.pdf (page 12) + * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks + * Will start an infinite loop if field order P is not prime. + * @param P field order + * @returns function that takes field Fp (created from P) and number n + */ +export function tonelliShanks(P: bigint) { + // Legendre constant: used to calculate Legendre symbol (a | p), + // which denotes the value of a^((p-1)/2) (mod p). + // (a | p) ≡ 1 if a is a square (mod p) + // (a | p) ≡ -1 if a is not a square (mod p) + // (a | p) ≡ 0 if a ≡ 0 (mod p) + const legendreC = (P - _1n) / _2n; + + let Q: bigint, S: number, Z: bigint; + // Step 1: By factoring out powers of 2 from p - 1, + // find q and s such that p - 1 = q*(2^s) with q odd + for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++); + + // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq + for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++); + + // Fast-path + if (S === 1) { + const p1div4 = (P + _1n) / _4n; + return function tonelliFast(Fp: IField, n: T) { + const root = Fp.pow(n, p1div4); + if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root'); + return root; + }; + } + + // Slow-path + const Q1div2 = (Q + _1n) / _2n; + return function tonelliSlow(Fp: IField, n: T): T { + // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1 + if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) throw new Error('Cannot find square root'); + let r = S; + // TODO: will fail at Fp2/etc + let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b + let x = Fp.pow(n, Q1div2); // first guess at the square root + let b = Fp.pow(n, Q); // first guess at the fudge factor + + while (!Fp.eql(b, Fp.ONE)) { + if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0) + // Find m such b^(2^m)==1 + let m = 1; + for (let t2 = Fp.sqr(b); m < r; m++) { + if (Fp.eql(t2, Fp.ONE)) break; + t2 = Fp.sqr(t2); // t2 *= t2 + } + // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow + const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1) + g = Fp.sqr(ge); // g = ge * ge + x = Fp.mul(x, ge); // x *= ge + b = Fp.mul(b, g); // b *= g + r = m; + } + return x; + }; +} + +export function FpSqrt(P: bigint) { + // NOTE: different algorithms can give different roots, it is up to user to decide which one they want. + // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve). + + // P ≡ 3 (mod 4) + // √n = n^((P+1)/4) + if (P % _4n === _3n) { + // Not all roots possible! + // const ORDER = + // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn; + // const NUM = 72057594037927816n; + const p1div4 = (P + _1n) / _4n; + return function sqrt3mod4(Fp: IField, n: T) { + const root = Fp.pow(n, p1div4); + // Throw if root**2 != n + if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root'); + return root; + }; + } + + // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10) + if (P % _8n === _5n) { + const c1 = (P - _5n) / _8n; + return function sqrt5mod8(Fp: IField, n: T) { + const n2 = Fp.mul(n, _2n); + const v = Fp.pow(n2, c1); + const nv = Fp.mul(n, v); + const i = Fp.mul(Fp.mul(nv, _2n), v); + const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); + if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root'); + return root; + }; + } + + // P ≡ 9 (mod 16) + if (P % _16n === _9n) { + // NOTE: tonelli is too slow for bls-Fp2 calculations even on start + // Means we cannot use sqrt for constants at all! + // + // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F + // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F + // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F + // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic + // sqrt = (x) => { + // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4 + // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1 + // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1 + // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1 + // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x + // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x + // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x + // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x + // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x + // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2 + // } + } + + // Other cases: Tonelli-Shanks algorithm + return tonelliShanks(P); +} + +// Little-endian check for first LE bit (last BE bit); +export const isNegativeLE = (num: bigint, modulo: bigint) => (mod(num, modulo) & _1n) === _1n; + +// Field is not always over prime: for example, Fp2 has ORDER(q)=p^m +export interface IField { + ORDER: bigint; + BYTES: number; + BITS: number; + MASK: bigint; + ZERO: T; + ONE: T; + // 1-arg + create: (num: T) => T; + isValid: (num: T) => boolean; + is0: (num: T) => boolean; + neg(num: T): T; + inv(num: T): T; + sqrt(num: T): T; + sqr(num: T): T; + // 2-args + eql(lhs: T, rhs: T): boolean; + add(lhs: T, rhs: T): T; + sub(lhs: T, rhs: T): T; + mul(lhs: T, rhs: T | bigint): T; + pow(lhs: T, power: bigint): T; + div(lhs: T, rhs: T | bigint): T; + // N for NonNormalized (for now) + addN(lhs: T, rhs: T): T; + subN(lhs: T, rhs: T): T; + mulN(lhs: T, rhs: T | bigint): T; + sqrN(num: T): T; + + // Optional + // Should be same as sgn0 function in + // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1). + // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway. + isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2 + // legendre?(num: T): T; + pow(lhs: T, power: bigint): T; + invertBatch: (lst: T[]) => T[]; + toBytes(num: T): Uint8Array; + fromBytes(bytes: Uint8Array): T; + // If c is False, CMOV returns a, otherwise it returns b. + cmov(a: T, b: T, c: boolean): T; +} +// prettier-ignore +const FIELD_FIELDS = [ + 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr', + 'eql', 'add', 'sub', 'mul', 'pow', 'div', + 'addN', 'subN', 'mulN', 'sqrN' +] as const; +export function validateField(field: IField) { + const initial = { + ORDER: 'bigint', + MASK: 'bigint', + BYTES: 'isSafeInteger', + BITS: 'isSafeInteger', + } as Record; + const opts = FIELD_FIELDS.reduce((map, val: string) => { + map[val] = 'function'; + return map; + }, initial); + return validateObject(field, opts); +} + +// Generic field functions + +/** + * Same as `pow` but for Fp: non-constant-time. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + */ +export function FpPow(f: IField, num: T, power: bigint): T { + // Should have same speed as pow for bigints + // TODO: benchmark! + if (power < _0n) throw new Error('Expected power > 0'); + if (power === _0n) return f.ONE; + if (power === _1n) return num; + let p = f.ONE; + let d = num; + while (power > _0n) { + if (power & _1n) p = f.mul(p, d); + d = f.sqr(d); + power >>= _1n; + } + return p; +} + +/** + * Efficiently invert an array of Field elements. + * `inv(0)` will return `undefined` here: make sure to throw an error. + */ +export function FpInvertBatch(f: IField, nums: T[]): T[] { + const tmp = new Array(nums.length); + // Walk from first to last, multiply them by each other MOD p + const lastMultiplied = nums.reduce((acc, num, i) => { + if (f.is0(num)) return acc; + tmp[i] = acc; + return f.mul(acc, num); + }, f.ONE); + // Invert last element + const inverted = f.inv(lastMultiplied); + // Walk from last to first, multiply them by inverted each other MOD p + nums.reduceRight((acc, num, i) => { + if (f.is0(num)) return acc; + tmp[i] = f.mul(acc, tmp[i]); + return f.mul(acc, num); + }, inverted); + return tmp; +} + +export function FpDiv(f: IField, lhs: T, rhs: T | bigint): T { + return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs)); +} + +// This function returns True whenever the value x is a square in the field F. +export function FpIsSquare(f: IField) { + const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic + return (x: T): boolean => { + const p = f.pow(x, legendreConst); + return f.eql(p, f.ZERO) || f.eql(p, f.ONE); + }; +} + +// CURVE.n lengths +export function nLength(n: bigint, nBitLength?: number) { + // Bit size, byte size of CURVE.n + const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} + +type FpField = IField & Required, 'isOdd'>>; +/** + * Initializes a finite field over prime. **Non-primes are not supported.** + * Do not init in loop: slow. Very fragile: always run a benchmark on a change. + * Major performance optimizations: + * * a) denormalized operations like mulN instead of mul + * * b) same object shape: never add or remove keys + * * c) Object.freeze + * @param ORDER prime positive bigint + * @param bitLen how many bits the field consumes + * @param isLE (def: false) if encoding / decoding should be in little-endian + * @param redef optional faster redefinitions of sqrt and other methods + */ +export function Field( + ORDER: bigint, + bitLen?: number, + isLE = false, + redef: Partial> = {} +): Readonly { + if (ORDER <= _0n) throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen); + if (BYTES > 2048) throw new Error('Field lengths over 2048 bytes are not supported'); + const sqrtP = FpSqrt(ORDER); + const f: Readonly = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: bitMask(BITS), + ZERO: _0n, + ONE: _1n, + create: (num) => mod(num, ORDER), + isValid: (num) => { + if (typeof num !== 'bigint') + throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); + return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible + }, + is0: (num) => num === _0n, + isOdd: (num) => (num & _1n) === _1n, + neg: (num) => mod(-num, ORDER), + eql: (lhs, rhs) => lhs === rhs, + + sqr: (num) => mod(num * num, ORDER), + add: (lhs, rhs) => mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod(lhs * rhs, ORDER), + pow: (num, power) => FpPow(f, num, power), + div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), + + // Same as above, but doesn't normalize + sqrN: (num) => num * num, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + + inv: (num) => invert(num, ORDER), + sqrt: redef.sqrt || ((n) => sqrtP(f, n)), + invertBatch: (lst) => FpInvertBatch(f, lst), + // TODO: do we really need constant cmov? + // We don't have const-time bigints anyway, so probably will be not very useful + cmov: (a, b, c) => (c ? b : a), + toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)), + fromBytes: (bytes) => { + if (bytes.length !== BYTES) + throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); + return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); + }, + } as FpField); + return Object.freeze(f); +} + +export function FpSqrtOdd(Fp: IField, elm: T) { + if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`); + const root = Fp.sqrt(elm); + return Fp.isOdd(root) ? root : Fp.neg(root); +} + +export function FpSqrtEven(Fp: IField, elm: T) { + if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`); + const root = Fp.sqrt(elm); + return Fp.isOdd(root) ? Fp.neg(root) : root; +} + +/** + * "Constant-time" private key generation utility. + * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field). + * Which makes it slightly more biased, less secure. + * @deprecated use mapKeyToField instead + */ +export function hashToPrivateScalar( + hash: string | Uint8Array, + groupOrder: bigint, + isLE = false +): bigint { + hash = ensureBytes('privateHash', hash); + const hashLen = hash.length; + const minLen = nLength(groupOrder).nByteLength + 8; + if (minLen < 24 || hashLen < minLen || hashLen > 1024) + throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`); + const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash); + return mod(num, groupOrder - _1n) + _1n; +} + +/** + * Returns total number of bytes consumed by the field element. + * For example, 32 bytes for usual 256-bit weierstrass curve. + * @param fieldOrder number of field elements, usually CURVE.n + * @returns byte length of field + */ +export function getFieldBytesLength(fieldOrder: bigint): number { + if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint'); + const bitLength = fieldOrder.toString(2).length; + return Math.ceil(bitLength / 8); +} + +/** + * Returns minimal amount of bytes that can be safely reduced + * by field order. + * Should be 2^-128 for 128-bit curve such as P256. + * @param fieldOrder number of field elements, usually CURVE.n + * @returns byte length of target hash + */ +export function getMinHashLength(fieldOrder: bigint): number { + const length = getFieldBytesLength(fieldOrder); + return length + Math.ceil(length / 2); +} + +/** + * "Constant-time" private key generation utility. + * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF + * and convert them into private scalar, with the modulo bias being negligible. + * Needs at least 48 bytes of input for 32-byte private key. + * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ + * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final + * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5 + * @param hash hash output from SHA3 or a similar function + * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n) + * @param isLE interpret hash bytes as LE num + * @returns valid private scalar + */ +export function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array { + const len = key.length; + const fieldLen = getFieldBytesLength(fieldOrder); + const minLen = getMinHashLength(fieldOrder); + // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings. + if (len < 16 || len < minLen || len > 1024) + throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`); + const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key); + // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0 + const reduced = mod(num, fieldOrder - _1n) + _1n; + return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); +} diff --git a/node_modules/@noble/curves/src/abstract/montgomery.ts b/node_modules/@noble/curves/src/abstract/montgomery.ts new file mode 100644 index 0000000..64d1b53 --- /dev/null +++ b/node_modules/@noble/curves/src/abstract/montgomery.ts @@ -0,0 +1,189 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { mod, pow } from './modular.js'; +import { bytesToNumberLE, ensureBytes, numberToBytesLE, validateObject } from './utils.js'; + +const _0n = BigInt(0); +const _1n = BigInt(1); +type Hex = string | Uint8Array; + +export type CurveType = { + P: bigint; // finite field prime + nByteLength: number; + adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; + domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; + a: bigint; + montgomeryBits: number; + powPminus2?: (x: bigint) => bigint; + xyToU?: (x: bigint, y: bigint) => bigint; + Gu: bigint; + randomBytes?: (bytesLength?: number) => Uint8Array; +}; +export type CurveFn = { + scalarMult: (scalar: Hex, u: Hex) => Uint8Array; + scalarMultBase: (scalar: Hex) => Uint8Array; + getSharedSecret: (privateKeyA: Hex, publicKeyB: Hex) => Uint8Array; + getPublicKey: (privateKey: Hex) => Uint8Array; + utils: { randomPrivateKey: () => Uint8Array }; + GuBytes: Uint8Array; +}; + +function validateOpts(curve: CurveType) { + validateObject( + curve, + { + a: 'bigint', + }, + { + montgomeryBits: 'isSafeInteger', + nByteLength: 'isSafeInteger', + adjustScalarBytes: 'function', + domain: 'function', + powPminus2: 'function', + Gu: 'bigint', + } + ); + // Set defaults + return Object.freeze({ ...curve } as const); +} + +// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748) +// Uses only one coordinate instead of two +export function montgomery(curveDef: CurveType): CurveFn { + const CURVE = validateOpts(curveDef); + const { P } = CURVE; + const modP = (n: bigint) => mod(n, P); + const montgomeryBits = CURVE.montgomeryBits; + const montgomeryBytes = Math.ceil(montgomeryBits / 8); + const fieldLen = CURVE.nByteLength; + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes); + const powPminus2 = CURVE.powPminus2 || ((x: bigint) => pow(x, P - BigInt(2), P)); + + // cswap from RFC7748. But it is not from RFC7748! + /* + cswap(swap, x_2, x_3): + dummy = mask(swap) AND (x_2 XOR x_3) + x_2 = x_2 XOR dummy + x_3 = x_3 XOR dummy + Return (x_2, x_3) + Where mask(swap) is the all-1 or all-0 word of the same length as x_2 + and x_3, computed, e.g., as mask(swap) = 0 - swap. + */ + function cswap(swap: bigint, x_2: bigint, x_3: bigint): [bigint, bigint] { + const dummy = modP(swap * (x_2 - x_3)); + x_2 = modP(x_2 - dummy); + x_3 = modP(x_3 + dummy); + return [x_2, x_3]; + } + + // Accepts 0 as well + function assertFieldElement(n: bigint): bigint { + if (typeof n === 'bigint' && _0n <= n && n < P) return n; + throw new Error('Expected valid scalar 0 < scalar < CURVE.P'); + } + + // x25519 from 4 + // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 + const a24 = (CURVE.a - BigInt(2)) / BigInt(4); + /** + * + * @param pointU u coordinate (x) on Montgomery Curve 25519 + * @param scalar by which the point would be multiplied + * @returns new Point on Montgomery curve + */ + function montgomeryLadder(pointU: bigint, scalar: bigint): bigint { + const u = assertFieldElement(pointU); + // Section 5: Implementations MUST accept non-canonical values and process them as + // if they had been reduced modulo the field prime. + const k = assertFieldElement(scalar); + const x_1 = u; + let x_2 = _1n; + let z_2 = _0n; + let x_3 = u; + let z_3 = _1n; + let swap = _0n; + let sw: [bigint, bigint]; + for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) { + const k_t = (k >> t) & _1n; + swap ^= k_t; + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + swap = k_t; + + const A = x_2 + z_2; + const AA = modP(A * A); + const B = x_2 - z_2; + const BB = modP(B * B); + const E = AA - BB; + const C = x_3 + z_3; + const D = x_3 - z_3; + const DA = modP(D * A); + const CB = modP(C * B); + const dacb = DA + CB; + const da_cb = DA - CB; + x_3 = modP(dacb * dacb); + z_3 = modP(x_1 * modP(da_cb * da_cb)); + x_2 = modP(AA * BB); + z_2 = modP(E * (AA + modP(a24 * E))); + } + // (x_2, x_3) = cswap(swap, x_2, x_3) + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + // (z_2, z_3) = cswap(swap, z_2, z_3) + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + // z_2^(p - 2) + const z2 = powPminus2(z_2); + // Return x_2 * (z_2^(p - 2)) + return modP(x_2 * z2); + } + + function encodeUCoordinate(u: bigint): Uint8Array { + return numberToBytesLE(modP(u), montgomeryBytes); + } + + function decodeUCoordinate(uEnc: Hex): bigint { + // Section 5: When receiving such an array, implementations of X25519 + // MUST mask the most significant bit in the final byte. + // This is very ugly way, but it works because fieldLen-1 is outside of bounds for X448, so this becomes NOOP + // fieldLen - scalaryBytes = 1 for X448 and = 0 for X25519 + const u = ensureBytes('u coordinate', uEnc, montgomeryBytes); + // u[fieldLen-1] crashes QuickJS (TypeError: out-of-bound numeric index) + if (fieldLen === montgomeryBytes) u[fieldLen - 1] &= 127; // 0b0111_1111 + return bytesToNumberLE(u); + } + function decodeScalar(n: Hex): bigint { + const bytes = ensureBytes('scalar', n); + if (bytes.length !== montgomeryBytes && bytes.length !== fieldLen) + throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${bytes.length}`); + return bytesToNumberLE(adjustScalarBytes(bytes)); + } + function scalarMult(scalar: Hex, u: Hex): Uint8Array { + const pointU = decodeUCoordinate(u); + const _scalar = decodeScalar(scalar); + const pu = montgomeryLadder(pointU, _scalar); + // The result was not contributory + // https://cr.yp.to/ecdh.html#validate + if (pu === _0n) throw new Error('Invalid private or public key received'); + return encodeUCoordinate(pu); + } + // Computes public key from private. By doing scalar multiplication of base point. + const GuBytes = encodeUCoordinate(CURVE.Gu); + function scalarMultBase(scalar: Hex): Uint8Array { + return scalarMult(scalar, GuBytes); + } + + return { + scalarMult, + scalarMultBase, + getSharedSecret: (privateKey: Hex, publicKey: Hex) => scalarMult(privateKey, publicKey), + getPublicKey: (privateKey: Hex): Uint8Array => scalarMultBase(privateKey), + utils: { randomPrivateKey: () => CURVE.randomBytes!(CURVE.nByteLength) }, + GuBytes: GuBytes, + }; +} diff --git a/node_modules/@noble/curves/src/abstract/poseidon.ts b/node_modules/@noble/curves/src/abstract/poseidon.ts new file mode 100644 index 0000000..a2a218a --- /dev/null +++ b/node_modules/@noble/curves/src/abstract/poseidon.ts @@ -0,0 +1,118 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Poseidon Hash: https://eprint.iacr.org/2019/458.pdf, https://www.poseidon-hash.info +import { IField, FpPow, validateField } from './modular.js'; +// We don't provide any constants, since different implementations use different constants. +// For reference constants see './test/poseidon.test.js'. +export type PoseidonOpts = { + Fp: IField; + t: number; + roundsFull: number; + roundsPartial: number; + sboxPower?: number; + reversePartialPowIdx?: boolean; // Hack for stark + mds: bigint[][]; + roundConstants: bigint[][]; +}; + +export function validateOpts(opts: PoseidonOpts) { + const { Fp, mds, reversePartialPowIdx: rev, roundConstants: rc } = opts; + const { roundsFull, roundsPartial, sboxPower, t } = opts; + + validateField(Fp); + for (const i of ['t', 'roundsFull', 'roundsPartial'] as const) { + if (typeof opts[i] !== 'number' || !Number.isSafeInteger(opts[i])) + throw new Error(`Poseidon: invalid param ${i}=${opts[i]} (${typeof opts[i]})`); + } + + // MDS is TxT matrix + if (!Array.isArray(mds) || mds.length !== t) throw new Error('Poseidon: wrong MDS matrix'); + const _mds = mds.map((mdsRow) => { + if (!Array.isArray(mdsRow) || mdsRow.length !== t) + throw new Error(`Poseidon MDS matrix row: ${mdsRow}`); + return mdsRow.map((i) => { + if (typeof i !== 'bigint') throw new Error(`Poseidon MDS matrix value=${i}`); + return Fp.create(i); + }); + }); + + if (rev !== undefined && typeof rev !== 'boolean') + throw new Error(`Poseidon: invalid param reversePartialPowIdx=${rev}`); + + if (roundsFull % 2 !== 0) throw new Error(`Poseidon roundsFull is not even: ${roundsFull}`); + const rounds = roundsFull + roundsPartial; + + if (!Array.isArray(rc) || rc.length !== rounds) + throw new Error('Poseidon: wrong round constants'); + const roundConstants = rc.map((rc) => { + if (!Array.isArray(rc) || rc.length !== t) + throw new Error(`Poseidon wrong round constants: ${rc}`); + return rc.map((i) => { + if (typeof i !== 'bigint' || !Fp.isValid(i)) + throw new Error(`Poseidon wrong round constant=${i}`); + return Fp.create(i); + }); + }); + + if (!sboxPower || ![3, 5, 7].includes(sboxPower)) + throw new Error(`Poseidon wrong sboxPower=${sboxPower}`); + const _sboxPower = BigInt(sboxPower); + let sboxFn = (n: bigint) => FpPow(Fp, n, _sboxPower); + // Unwrapped sbox power for common cases (195->142μs) + if (sboxPower === 3) sboxFn = (n: bigint) => Fp.mul(Fp.sqrN(n), n); + else if (sboxPower === 5) sboxFn = (n: bigint) => Fp.mul(Fp.sqrN(Fp.sqrN(n)), n); + + return Object.freeze({ ...opts, rounds, sboxFn, roundConstants, mds: _mds }); +} + +export function splitConstants(rc: bigint[], t: number) { + if (typeof t !== 'number') throw new Error('poseidonSplitConstants: wrong t'); + if (!Array.isArray(rc) || rc.length % t) throw new Error('poseidonSplitConstants: wrong rc'); + const res = []; + let tmp = []; + for (let i = 0; i < rc.length; i++) { + tmp.push(rc[i]); + if (tmp.length === t) { + res.push(tmp); + tmp = []; + } + } + return res; +} + +export function poseidon(opts: PoseidonOpts) { + const _opts = validateOpts(opts); + const { Fp, mds, roundConstants, rounds, roundsPartial, sboxFn, t } = _opts; + const halfRoundsFull = _opts.roundsFull / 2; + const partialIdx = _opts.reversePartialPowIdx ? t - 1 : 0; + const poseidonRound = (values: bigint[], isFull: boolean, idx: number) => { + values = values.map((i, j) => Fp.add(i, roundConstants[idx][j])); + + if (isFull) values = values.map((i) => sboxFn(i)); + else values[partialIdx] = sboxFn(values[partialIdx]); + // Matrix multiplication + values = mds.map((i) => i.reduce((acc, i, j) => Fp.add(acc, Fp.mulN(i, values[j])), Fp.ZERO)); + return values; + }; + const poseidonHash = function poseidonHash(values: bigint[]) { + if (!Array.isArray(values) || values.length !== t) + throw new Error(`Poseidon: wrong values (expected array of bigints with length ${t})`); + values = values.map((i) => { + if (typeof i !== 'bigint') throw new Error(`Poseidon: wrong value=${i} (${typeof i})`); + return Fp.create(i); + }); + let round = 0; + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) values = poseidonRound(values, true, round++); + // Apply r_p partial rounds. + for (let i = 0; i < roundsPartial; i++) values = poseidonRound(values, false, round++); + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) values = poseidonRound(values, true, round++); + + if (round !== rounds) + throw new Error(`Poseidon: wrong number of rounds: last round=${round}, total=${rounds}`); + return values; + }; + // For verification in tests + poseidonHash.roundConstants = roundConstants; + return poseidonHash; +} diff --git a/node_modules/@noble/curves/src/abstract/utils.ts b/node_modules/@noble/curves/src/abstract/utils.ts new file mode 100644 index 0000000..ff5b0c4 --- /dev/null +++ b/node_modules/@noble/curves/src/abstract/utils.ts @@ -0,0 +1,290 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// 100 lines of code in the file are duplicated from noble-hashes (utils). +// This is OK: `abstract` directory does not use noble-hashes. +// User may opt-in into using different hashing library. This way, noble-hashes +// won't be included into their bundle. +const _0n = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +const u8a = (a: any): a is Uint8Array => a instanceof Uint8Array; +export type Hex = Uint8Array | string; // hex strings are accepted for simplicity +export type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve +export type CHash = { + (message: Uint8Array | string): Uint8Array; + blockLen: number; + outputLen: number; + create(opts?: { dkLen?: number }): any; // For shake +}; +export type FHash = (message: Uint8Array | string) => Uint8Array; + +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => + i.toString(16).padStart(2, '0') +); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export function bytesToHex(bytes: Uint8Array): string { + if (!u8a(bytes)) throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} + +export function numberToHexUnpadded(num: number | bigint): string { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; +} + +export function hexToNumber(hex: string): bigint { + if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex); + // Big Endian + return BigInt(hex === '' ? '0' : `0x${hex}`); +} + +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export function hexToBytes(hex: string): Uint8Array { + if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} + +// BE: Big Endian, LE: Little Endian +export function bytesToNumberBE(bytes: Uint8Array): bigint { + return hexToNumber(bytesToHex(bytes)); +} +export function bytesToNumberLE(bytes: Uint8Array): bigint { + if (!u8a(bytes)) throw new Error('Uint8Array expected'); + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); +} + +export function numberToBytesBE(n: number | bigint, len: number): Uint8Array { + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} +export function numberToBytesLE(n: number | bigint, len: number): Uint8Array { + return numberToBytesBE(n, len).reverse(); +} +// Unpadded, rarely used +export function numberToVarBytesBE(n: number | bigint): Uint8Array { + return hexToBytes(numberToHexUnpadded(n)); +} + +/** + * Takes hex string or Uint8Array, converts to Uint8Array. + * Validates output length. + * Will throw error for other types. + * @param title descriptive title for an error e.g. 'private key' + * @param hex hex string or Uint8Array + * @param expectedLength optional, will compare to result array's length + * @returns + */ +export function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array { + let res: Uint8Array; + if (typeof hex === 'string') { + try { + res = hexToBytes(hex); + } catch (e) { + throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`); + } + } else if (u8a(hex)) { + // Uint8Array.from() instead of hash.slice() because node.js Buffer + // is instance of Uint8Array, and its slice() creates **mutable** copy + res = Uint8Array.from(hex); + } else { + throw new Error(`${title} must be hex string or Uint8Array`); + } + const len = res.length; + if (typeof expectedLength === 'number' && len !== expectedLength) + throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); + return res; +} + +/** + * Copies several Uint8Arrays into one. + */ +export function concatBytes(...arrays: Uint8Array[]): Uint8Array { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} + +export function equalBytes(b1: Uint8Array, b2: Uint8Array) { + // We don't care about timing attacks here + if (b1.length !== b2.length) return false; + for (let i = 0; i < b1.length; i++) if (b1[i] !== b2[i]) return false; + return true; +} + +// Global symbols in both browsers and Node.js since v11 +// See https://github.com/microsoft/TypeScript/issues/31535 +declare const TextEncoder: any; + +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export function utf8ToBytes(str: string): Uint8Array { + if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} + +// Bit operations + +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + */ +export function bitLen(n: bigint) { + let len; + for (len = 0; n > _0n; n >>= _1n, len += 1); + return len; +} + +/** + * Gets single bit at position. + * NOTE: first bit position is 0 (same as arrays) + * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` + */ +export function bitGet(n: bigint, pos: number) { + return (n >> BigInt(pos)) & _1n; +} + +/** + * Sets single bit at position. + */ +export const bitSet = (n: bigint, pos: number, value: boolean) => { + return n | ((value ? _1n : _0n) << BigInt(pos)); +}; + +/** + * Calculate mask for N bits. Not using ** operator with bigints because of old engines. + * Same as BigInt(`0b${Array(i).fill('1').join('')}`) + */ +export const bitMask = (n: number) => (_2n << BigInt(n - 1)) - _1n; + +// DRBG + +const u8n = (data?: any) => new Uint8Array(data); // creates Uint8Array +const u8fr = (arr: any) => Uint8Array.from(arr); // another shortcut +type Pred = (v: Uint8Array) => T | undefined; +/** + * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + * @returns function that will call DRBG until 2nd arg returns something meaningful + * @example + * const drbg = createHmacDRBG(32, 32, hmac); + * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined + */ +export function createHmacDrbg( + hashLen: number, + qByteLen: number, + hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array +): (seed: Uint8Array, predicate: Pred) => T { + if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number'); + if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number'); + if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function'); + // Step B, Step C: set hashLen to 8*ceil(hlen/8) + let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same + let i = 0; // Iterations counter, will throw when over 1000 + const reset = () => { + v.fill(1); + k.fill(0); + i = 0; + }; + const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values) + const reseed = (seed = u8n()) => { + // HMAC-DRBG reseed() function. Steps D-G + k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed) + v = h(); // v = hmac(k || v) + if (seed.length === 0) return; + k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed) + v = h(); // v = hmac(k || v) + }; + const gen = () => { + // HMAC-DRBG generate() function + if (i++ >= 1000) throw new Error('drbg: tried 1000 values'); + let len = 0; + const out: Uint8Array[] = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes(...out); + }; + const genUntil = (seed: Uint8Array, pred: Pred): T => { + reset(); + reseed(seed); // Steps D-G + let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1] + while (!(res = pred(gen()))) reseed(); + reset(); + return res; + }; + return genUntil; +} + +// Validating curves and fields + +const validatorFns = { + bigint: (val: any) => typeof val === 'bigint', + function: (val: any) => typeof val === 'function', + boolean: (val: any) => typeof val === 'boolean', + string: (val: any) => typeof val === 'string', + stringOrUint8Array: (val: any) => typeof val === 'string' || val instanceof Uint8Array, + isSafeInteger: (val: any) => Number.isSafeInteger(val), + array: (val: any) => Array.isArray(val), + field: (val: any, object: any) => (object as any).Fp.isValid(val), + hash: (val: any) => typeof val === 'function' && Number.isSafeInteger(val.outputLen), +} as const; +type Validator = keyof typeof validatorFns; +type ValMap> = { [K in keyof T]?: Validator }; +// type Record = { [P in K]: T; } + +export function validateObject>( + object: T, + validators: ValMap, + optValidators: ValMap = {} +) { + const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== 'function') + throw new Error(`Invalid validator "${type}", expected function`); + + const val = object[fieldName as keyof typeof object]; + if (isOptional && val === undefined) return; + if (!checkVal(val, object)) { + throw new Error( + `Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}` + ); + } + }; + for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false); + for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true); + return object; +} +// validate type tests +// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 }; +// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok! +// // Should fail type-check +// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' }); +// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' }); +// const z3 = validateObject(o, { test: 'boolean', z: 'bug' }); +// const z4 = validateObject(o, { a: 'boolean', z: 'bug' }); diff --git a/node_modules/@noble/curves/src/abstract/weierstrass.ts b/node_modules/@noble/curves/src/abstract/weierstrass.ts new file mode 100644 index 0000000..82e7d42 --- /dev/null +++ b/node_modules/@noble/curves/src/abstract/weierstrass.ts @@ -0,0 +1,1222 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Short Weierstrass curve. The formula is: y² = x³ + ax + b +import * as mod from './modular.js'; +import * as ut from './utils.js'; +import { CHash, Hex, PrivKey, ensureBytes } from './utils.js'; +import { Group, GroupConstructor, wNAF, BasicCurve, validateBasic, AffinePoint } from './curve.js'; + +export type { AffinePoint }; +type HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; +type EndomorphismOpts = { + beta: bigint; + splitScalar: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint }; +}; +export type BasicWCurve = BasicCurve & { + // Params: a, b + a: T; + b: T; + + // Optional params + allowedPrivateKeyLengths?: readonly number[]; // for P521 + wrapPrivateKey?: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n + endo?: EndomorphismOpts; // Endomorphism options for Koblitz curves + // When a cofactor != 1, there can be an effective methods to: + // 1. Determine whether a point is torsion-free + isTorsionFree?: (c: ProjConstructor, point: ProjPointType) => boolean; + // 2. Clear torsion component + clearCofactor?: (c: ProjConstructor, point: ProjPointType) => ProjPointType; +}; + +type Entropy = Hex | true; +export type SignOpts = { lowS?: boolean; extraEntropy?: Entropy; prehash?: boolean }; +export type VerOpts = { lowS?: boolean; prehash?: boolean }; + +/** + * ### Design rationale for types + * + * * Interaction between classes from different curves should fail: + * `k256.Point.BASE.add(p256.Point.BASE)` + * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime + * * Different calls of `curve()` would return different classes - + * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve, + * it won't affect others + * + * TypeScript can't infer types for classes created inside a function. Classes is one instance of nominative types in TypeScript and interfaces only check for shape, so it's hard to create unique type for every function call. + * + * We can use generic types via some param, like curve opts, but that would: + * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params) + * which is hard to debug. + * 2. Params can be generic and we can't enforce them to be constant value: + * if somebody creates curve from non-constant params, + * it would be allowed to interact with other curves with non-constant params + * + * TODO: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol + */ + +// Instance for 3d XYZ points +export interface ProjPointType extends Group> { + readonly px: T; + readonly py: T; + readonly pz: T; + get x(): T; + get y(): T; + multiply(scalar: bigint): ProjPointType; + toAffine(iz?: T): AffinePoint; + isTorsionFree(): boolean; + clearCofactor(): ProjPointType; + assertValidity(): void; + hasEvenY(): boolean; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; + + multiplyUnsafe(scalar: bigint): ProjPointType; + multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined; + _setWindowSize(windowSize: number): void; +} +// Static methods for 3d XYZ points +export interface ProjConstructor extends GroupConstructor> { + new (x: T, y: T, z: T): ProjPointType; + fromAffine(p: AffinePoint): ProjPointType; + fromHex(hex: Hex): ProjPointType; + fromPrivateKey(privateKey: PrivKey): ProjPointType; + normalizeZ(points: ProjPointType[]): ProjPointType[]; +} + +export type CurvePointsType = BasicWCurve & { + // Bytes + fromBytes?: (bytes: Uint8Array) => AffinePoint; + toBytes?: (c: ProjConstructor, point: ProjPointType, isCompressed: boolean) => Uint8Array; +}; + +function validatePointOpts(curve: CurvePointsType) { + const opts = validateBasic(curve); + ut.validateObject( + opts, + { + a: 'field', + b: 'field', + }, + { + allowedPrivateKeyLengths: 'array', + wrapPrivateKey: 'boolean', + isTorsionFree: 'function', + clearCofactor: 'function', + allowInfinityPoint: 'boolean', + fromBytes: 'function', + toBytes: 'function', + } + ); + const { endo, Fp, a } = opts; + if (endo) { + if (!Fp.eql(a, Fp.ZERO)) { + throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0'); + } + if ( + typeof endo !== 'object' || + typeof endo.beta !== 'bigint' || + typeof endo.splitScalar !== 'function' + ) { + throw new Error('Expected endomorphism with beta: bigint and splitScalar: function'); + } + } + return Object.freeze({ ...opts } as const); +} + +export type CurvePointsRes = { + ProjectivePoint: ProjConstructor; + normPrivateKeyToScalar: (key: PrivKey) => bigint; + weierstrassEquation: (x: T) => T; + isWithinCurveOrder: (num: bigint) => boolean; +}; + +// ASN.1 DER encoding utilities +const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; +export const DER = { + // asn.1 DER encoding utils + Err: class DERErr extends Error { + constructor(m = '') { + super(m); + } + }, + _parseInt(data: Uint8Array): { d: bigint; l: Uint8Array } { + const { Err: E } = DER; + if (data.length < 2 || data[0] !== 0x02) throw new E('Invalid signature integer tag'); + const len = data[1]; + const res = data.subarray(2, len + 2); + if (!len || res.length !== len) throw new E('Invalid signature integer: wrong length'); + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + if (res[0] & 0b10000000) throw new E('Invalid signature integer: negative'); + if (res[0] === 0x00 && !(res[1] & 0b10000000)) + throw new E('Invalid signature integer: unnecessary leading zero'); + return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left + }, + toSig(hex: string | Uint8Array): { r: bigint; s: bigint } { + // parse DER signature + const { Err: E } = DER; + const data = typeof hex === 'string' ? h2b(hex) : hex; + if (!(data instanceof Uint8Array)) throw new Error('ui8a expected'); + let l = data.length; + if (l < 2 || data[0] != 0x30) throw new E('Invalid signature tag'); + if (data[1] !== l - 2) throw new E('Invalid signature: incorrect length'); + const { d: r, l: sBytes } = DER._parseInt(data.subarray(2)); + const { d: s, l: rBytesLeft } = DER._parseInt(sBytes); + if (rBytesLeft.length) throw new E('Invalid signature: left bytes after parsing'); + return { r, s }; + }, + hexFromSig(sig: { r: bigint; s: bigint }): string { + // Add leading zero if first byte has negative bit enabled. More details in '_parseInt' + const slice = (s: string): string => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s); + const h = (num: number | bigint) => { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; + }; + const s = slice(h(sig.s)); + const r = slice(h(sig.r)); + const shl = s.length / 2; + const rhl = r.length / 2; + const sl = h(shl); + const rl = h(rhl); + return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`; + }, +}; + +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4); + +export function weierstrassPoints(opts: CurvePointsType) { + const CURVE = validatePointOpts(opts); + const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ + + const toBytes = + CURVE.toBytes || + ((_c: ProjConstructor, point: ProjPointType, _isCompressed: boolean) => { + const a = point.toAffine(); + return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y)); + }); + const fromBytes = + CURVE.fromBytes || + ((bytes: Uint8Array) => { + // const head = bytes[0]; + const tail = bytes.subarray(1); + // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported'); + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + }); + + /** + * y² = x³ + ax + b: Short weierstrass curve formula + * @returns y² + */ + function weierstrassEquation(x: T): T { + const { a, b } = CURVE; + const x2 = Fp.sqr(x); // x * x + const x3 = Fp.mul(x2, x); // x2 * x + return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b + } + // Validate whether the passed curve params are valid. + // We check if curve equation works for generator point. + // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381. + // ProjectivePoint class has not been initialized yet. + if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error('bad generator point: equation left != right'); + + // Valid group elements reside in range 1..n-1 + function isWithinCurveOrder(num: bigint): boolean { + return typeof num === 'bigint' && _0n < num && num < CURVE.n; + } + function assertGE(num: bigint) { + if (!isWithinCurveOrder(num)) throw new Error('Expected valid bigint: 0 < bigint < curve.n'); + } + // Validates if priv key is valid and converts it to bigint. + // Supports options allowedPrivateKeyLengths and wrapPrivateKey. + function normPrivateKeyToScalar(key: PrivKey): bigint { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE; + if (lengths && typeof key !== 'bigint') { + if (key instanceof Uint8Array) key = ut.bytesToHex(key); + // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes + if (typeof key !== 'string' || !lengths.includes(key.length)) throw new Error('Invalid key'); + key = key.padStart(nByteLength * 2, '0'); + } + let num: bigint; + try { + num = + typeof key === 'bigint' + ? key + : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength)); + } catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + } + if (wrapPrivateKey) num = mod.mod(num, n); // disabled by default, enabled for BLS + assertGE(num); // num in range [1..N-1] + return num; + } + + const pointPrecomputes = new Map(); + function assertPrjPoint(other: unknown) { + if (!(other instanceof Point)) throw new Error('ProjectivePoint expected'); + } + /** + * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z) + * Default Point works in 2d / affine coordinates: (x, y) + * We're doing calculations in projective, because its operations don't require costly inversion. + */ + class Point implements ProjPointType { + static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); + static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); + + constructor(readonly px: T, readonly py: T, readonly pz: T) { + if (px == null || !Fp.isValid(px)) throw new Error('x required'); + if (py == null || !Fp.isValid(py)) throw new Error('y required'); + if (pz == null || !Fp.isValid(pz)) throw new Error('z required'); + } + + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + static fromAffine(p: AffinePoint): Point { + const { x, y } = p || {}; + if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point'); + if (p instanceof Point) throw new Error('projective point not allowed'); + const is0 = (i: T) => Fp.eql(i, Fp.ZERO); + // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0) + if (is0(x) && is0(y)) return Point.ZERO; + return new Point(x, y, Fp.ONE); + } + + get x(): T { + return this.toAffine().x; + } + get y(): T { + return this.toAffine().y; + } + + /** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + */ + static normalizeZ(points: Point[]): Point[] { + const toInv = Fp.invertBatch(points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex: Hex): Point { + const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex))); + P.assertValidity(); + return P; + } + + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey: PrivKey) { + return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + + // We calculate precomputes for elliptic curve point multiplication + // using windowed method. This specifies window size and + // stores precomputed values. Usually only base point would be precomputed. + _WINDOW_SIZE?: number; + + // "Private method", don't use it directly + _setWindowSize(windowSize: number) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + + // A point on curve is valid if it conforms to equation. + assertValidity(): void { + if (this.is0()) { + // (0, 1, 0) aka ZERO is invalid in most contexts. + // In BLS, ZERO can be serialized, so we allow it. + // (0, 0, 0) is wrong representation of ZERO and is always invalid. + if (CURVE.allowInfinityPoint && !Fp.is0(this.py)) return; + throw new Error('bad point: ZERO'); + } + // Some 3rd-party test vectors require different wording between here & `fromCompressedHex` + const { x, y } = this.toAffine(); + // Check if x, y are valid field elements + if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not FE'); + const left = Fp.sqr(y); // y² + const right = weierstrassEquation(x); // x³ + ax + b + if (!Fp.eql(left, right)) throw new Error('bad point: equation left != right'); + if (!this.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup'); + } + hasEvenY(): boolean { + const { y } = this.toAffine(); + if (Fp.isOdd) return !Fp.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + + /** + * Compare one point to another. + */ + equals(other: Point): boolean { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); + const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); + return U1 && U2; + } + + /** + * Flips point to one corresponding to (x, -y) in Affine coordinates. + */ + negate(): Point { + return new Point(this.px, Fp.neg(this.py), this.pz); + } + + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a, b } = CURVE; + const b3 = Fp.mul(b, _3n); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + let t0 = Fp.mul(X1, X1); // step 1 + let t1 = Fp.mul(Y1, Y1); + let t2 = Fp.mul(Z1, Z1); + let t3 = Fp.mul(X1, Y1); + t3 = Fp.add(t3, t3); // step 5 + Z3 = Fp.mul(X1, Z1); + Z3 = Fp.add(Z3, Z3); + X3 = Fp.mul(a, Z3); + Y3 = Fp.mul(b3, t2); + Y3 = Fp.add(X3, Y3); // step 10 + X3 = Fp.sub(t1, Y3); + Y3 = Fp.add(t1, Y3); + Y3 = Fp.mul(X3, Y3); + X3 = Fp.mul(t3, X3); + Z3 = Fp.mul(b3, Z3); // step 15 + t2 = Fp.mul(a, t2); + t3 = Fp.sub(t0, t2); + t3 = Fp.mul(a, t3); + t3 = Fp.add(t3, Z3); + Z3 = Fp.add(t0, t0); // step 20 + t0 = Fp.add(Z3, t0); + t0 = Fp.add(t0, t2); + t0 = Fp.mul(t0, t3); + Y3 = Fp.add(Y3, t0); + t2 = Fp.mul(Y1, Z1); // step 25 + t2 = Fp.add(t2, t2); + t0 = Fp.mul(t2, t3); + X3 = Fp.sub(X3, t0); + Z3 = Fp.mul(t2, t1); + Z3 = Fp.add(Z3, Z3); // step 30 + Z3 = Fp.add(Z3, Z3); + return new Point(X3, Y3, Z3); + } + + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other: Point): Point { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + const a = CURVE.a; + const b3 = Fp.mul(CURVE.b, _3n); + let t0 = Fp.mul(X1, X2); // step 1 + let t1 = Fp.mul(Y1, Y2); + let t2 = Fp.mul(Z1, Z2); + let t3 = Fp.add(X1, Y1); + let t4 = Fp.add(X2, Y2); // step 5 + t3 = Fp.mul(t3, t4); + t4 = Fp.add(t0, t1); + t3 = Fp.sub(t3, t4); + t4 = Fp.add(X1, Z1); + let t5 = Fp.add(X2, Z2); // step 10 + t4 = Fp.mul(t4, t5); + t5 = Fp.add(t0, t2); + t4 = Fp.sub(t4, t5); + t5 = Fp.add(Y1, Z1); + X3 = Fp.add(Y2, Z2); // step 15 + t5 = Fp.mul(t5, X3); + X3 = Fp.add(t1, t2); + t5 = Fp.sub(t5, X3); + Z3 = Fp.mul(a, t4); + X3 = Fp.mul(b3, t2); // step 20 + Z3 = Fp.add(X3, Z3); + X3 = Fp.sub(t1, Z3); + Z3 = Fp.add(t1, Z3); + Y3 = Fp.mul(X3, Z3); + t1 = Fp.add(t0, t0); // step 25 + t1 = Fp.add(t1, t0); + t2 = Fp.mul(a, t2); + t4 = Fp.mul(b3, t4); + t1 = Fp.add(t1, t2); + t2 = Fp.sub(t0, t2); // step 30 + t2 = Fp.mul(a, t2); + t4 = Fp.add(t4, t2); + t0 = Fp.mul(t1, t4); + Y3 = Fp.add(Y3, t0); + t0 = Fp.mul(t5, t4); // step 35 + X3 = Fp.mul(t3, X3); + X3 = Fp.sub(X3, t0); + t0 = Fp.mul(t3, t1); + Z3 = Fp.mul(t5, Z3); + Z3 = Fp.add(Z3, t0); // step 40 + return new Point(X3, Y3, Z3); + } + + subtract(other: Point) { + return this.add(other.negate()); + } + + private is0() { + return this.equals(Point.ZERO); + } + private wNAF(n: bigint): { p: Point; f: Point } { + return wnaf.wNAFCached(this, pointPrecomputes, n, (comp: Point[]) => { + const toInv = Fp.invertBatch(comp.map((p) => p.pz)); + return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + }); + } + + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(n: bigint): Point { + const I = Point.ZERO; + if (n === _0n) return I; + assertGE(n); // Will throw on 0 + if (n === _1n) return this; + const { endo } = CURVE; + if (!endo) return wnaf.unsafeLadder(this, n); + + // Apply endomorphism + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let k1p = I; + let k2p = I; + let d: Point = this; + while (k1 > _0n || k2 > _0n) { + if (k1 & _1n) k1p = k1p.add(d); + if (k2 & _1n) k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n; + k2 >>= _1n; + } + if (k1neg) k1p = k1p.negate(); + if (k2neg) k2p = k2p.negate(); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar by which the point would be multiplied + * @returns New point + */ + multiply(scalar: bigint): Point { + assertGE(scalar); + let n = scalar; + let point: Point, fake: Point; // Fake point is used to const-time mult + const { endo } = CURVE; + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } else { + const { p, f } = this.wNAF(n); + point = p; + fake = f; + } + // Normalize `z` for both points, but return only real one + return Point.normalizeZ([point, fake])[0]; + } + + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q: Point, a: bigint, b: bigint): Point | undefined { + const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes + const mul = ( + P: Point, + a: bigint // Select faster multiply() method + ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a)); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? undefined : sum; + } + + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + toAffine(iz?: T): AffinePoint { + const { px: x, py: y, pz: z } = this; + const is0 = this.is0(); + // If invZ was 0, we return zero point. However we still want to execute + // all operations, so we replace invZ with a random number, 1. + if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(z); + const ax = Fp.mul(x, iz); + const ay = Fp.mul(y, iz); + const zz = Fp.mul(z, iz); + if (is0) return { x: Fp.ZERO, y: Fp.ZERO }; + if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + } + isTorsionFree(): boolean { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n) return true; // No subgroups, always torsion-free + if (isTorsionFree) return isTorsionFree(Point, this); + throw new Error('isTorsionFree() has not been declared for the elliptic curve'); + } + clearCofactor(): Point { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n) return this; // Fast-path + if (clearCofactor) return clearCofactor(Point, this) as Point; + return this.multiplyUnsafe(CURVE.h); + } + + toRawBytes(isCompressed = true): Uint8Array { + this.assertValidity(); + return toBytes(Point, this, isCompressed); + } + + toHex(isCompressed = true): string { + return ut.bytesToHex(this.toRawBytes(isCompressed)); + } + } + const _bits = CURVE.nBitLength; + const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + // Validate if generator point is on curve + return { + CURVE, + ProjectivePoint: Point as ProjConstructor, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + }; +} + +// Instance +export interface SignatureType { + readonly r: bigint; + readonly s: bigint; + readonly recovery?: number; + assertValidity(): void; + addRecoveryBit(recovery: number): RecoveredSignatureType; + hasHighS(): boolean; + normalizeS(): SignatureType; + recoverPublicKey(msgHash: Hex): ProjPointType; + toCompactRawBytes(): Uint8Array; + toCompactHex(): string; + // DER-encoded + toDERRawBytes(isCompressed?: boolean): Uint8Array; + toDERHex(isCompressed?: boolean): string; +} +export type RecoveredSignatureType = SignatureType & { + readonly recovery: number; +}; +// Static methods +export type SignatureConstructor = { + new (r: bigint, s: bigint): SignatureType; + fromCompact(hex: Hex): SignatureType; + fromDER(hex: Hex): SignatureType; +}; +type SignatureLike = { r: bigint; s: bigint }; + +export type PubKey = Hex | ProjPointType; + +export type CurveType = BasicWCurve & { + hash: CHash; // CHash not FHash because we need outputLen for DRBG + hmac: HmacFnSync; + randomBytes: (bytesLength?: number) => Uint8Array; + lowS?: boolean; + bits2int?: (bytes: Uint8Array) => bigint; + bits2int_modN?: (bytes: Uint8Array) => bigint; +}; + +function validateOpts(curve: CurveType) { + const opts = validateBasic(curve); + ut.validateObject( + opts, + { + hash: 'hash', + hmac: 'function', + randomBytes: 'function', + }, + { + bits2int: 'function', + bits2int_modN: 'function', + lowS: 'boolean', + } + ); + return Object.freeze({ lowS: true, ...opts } as const); +} + +export type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType; + verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean; + ProjectivePoint: ProjConstructor; + Signature: SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: PrivKey) => bigint; + isValidPrivateKey(privateKey: PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: ProjPointType) => ProjPointType; + }; +}; + +export function weierstrass(curveDef: CurveType): CurveFn { + const CURVE = validateOpts(curveDef) as ReturnType; + const { Fp, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32 + const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32 + + function isValidFieldElement(num: bigint): boolean { + return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE + } + function modN(a: bigint) { + return mod.mod(a, CURVE_ORDER); + } + function invN(a: bigint) { + return mod.invert(a, CURVE_ORDER); + } + + const { + ProjectivePoint: Point, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + } = weierstrassPoints({ + ...CURVE, + toBytes(_c, point, isCompressed: boolean): Uint8Array { + const a = point.toAffine(); + const x = Fp.toBytes(a.x); + const cat = ut.concatBytes; + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x); + } else { + return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y)); + } + }, + fromBytes(bytes: Uint8Array) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + // this.assertValidity() is done inside of fromHex + if (len === compressedLen && (head === 0x02 || head === 0x03)) { + const x = ut.bytesToNumberBE(tail); + if (!isValidFieldElement(x)) throw new Error('Point is not on curve'); + const y2 = weierstrassEquation(x); // y² = x³ + ax + b + let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 + const isYOdd = (y & _1n) === _1n; + // ECDSA + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) y = Fp.neg(y); + return { x, y }; + } else if (len === uncompressedLen && head === 0x04) { + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + } else { + throw new Error( + `Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes` + ); + } + }, + }); + const numToNByteStr = (num: bigint): string => + ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength)); + + function isBiggerThanHalfOrder(number: bigint) { + const HALF = CURVE_ORDER >> _1n; + return number > HALF; + } + + function normalizeS(s: bigint) { + return isBiggerThanHalfOrder(s) ? modN(-s) : s; + } + // slice bytes num + const slcNum = (b: Uint8Array, from: number, to: number) => ut.bytesToNumberBE(b.slice(from, to)); + + /** + * ECDSA signature with its (r, s) properties. Supports DER & compact representations. + */ + class Signature implements SignatureType { + constructor(readonly r: bigint, readonly s: bigint, readonly recovery?: number) { + this.assertValidity(); + } + + // pair (bytes of r, bytes of s) + static fromCompact(hex: Hex) { + const l = CURVE.nByteLength; + hex = ensureBytes('compactSignature', hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex: Hex) { + const { r, s } = DER.toSig(ensureBytes('DER', hex)); + return new Signature(r, s); + } + + assertValidity(): void { + // can use assertGE here + if (!isWithinCurveOrder(this.r)) throw new Error('r must be 0 < r < CURVE.n'); + if (!isWithinCurveOrder(this.s)) throw new Error('s must be 0 < s < CURVE.n'); + } + + addRecoveryBit(recovery: number): RecoveredSignature { + return new Signature(this.r, this.s, recovery) as RecoveredSignature; + } + + recoverPublicKey(msgHash: Hex): typeof Point.BASE { + const { r, s, recovery: rec } = this; + const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash + if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error('recovery id invalid'); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp.ORDER) throw new Error('recovery id 2 or 3 invalid'); + const prefix = (rec & 1) === 0 ? '02' : '03'; + const R = Point.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); // r^-1 + const u1 = modN(-h * ir); // -hr^-1 + const u2 = modN(s * ir); // sr^-1 + const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1) + if (!Q) throw new Error('point at infinify'); // unsafe is fine: no priv data leaked + Q.assertValidity(); + return Q; + } + + // Signatures should be low-s, to prevent malleability. + hasHighS(): boolean { + return isBiggerThanHalfOrder(this.s); + } + + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; + } + + // DER-encoded + toDERRawBytes() { + return ut.hexToBytes(this.toDERHex()); + } + toDERHex() { + return DER.hexFromSig({ r: this.r, s: this.s }); + } + + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return ut.hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + type RecoveredSignature = Signature & { recovery: number }; + + const utils = { + isValidPrivateKey(privateKey: PrivKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } catch (error) { + return false; + } + }, + normPrivateKeyToScalar: normPrivateKeyToScalar, + + /** + * Produces cryptographically secure private key from random of size + * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. + */ + randomPrivateKey: (): Uint8Array => { + const length = mod.getMinHashLength(CURVE.n); + return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n); + }, + + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here + return point; + }, + }; + + /** + * Computes public key for a private key. Checks for validity of the private key. + * @param privateKey private key + * @param isCompressed whether to return compact (default), or full key + * @returns Public key, full when isCompressed=false; short when isCompressed=true + */ + function getPublicKey(privateKey: PrivKey, isCompressed = true): Uint8Array { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + + /** + * Quick and dirty check for item being public key. Does not validate hex, or being on-curve. + */ + function isProbPub(item: PrivKey | PubKey): boolean { + const arr = item instanceof Uint8Array; + const str = typeof item === 'string'; + const len = (arr || str) && (item as Hex).length; + if (arr) return len === compressedLen || len === uncompressedLen; + if (str) return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point) return true; + return false; + } + + /** + * ECDH (Elliptic Curve Diffie Hellman). + * Computes shared public key from private key and public key. + * Checks: 1) private key validity 2) shared key is on-curve. + * Does NOT hash the result. + * @param privateA private key + * @param publicB different public key + * @param isCompressed whether to return compact (default), or full key + * @returns shared public key + */ + function getSharedSecret(privateA: PrivKey, publicB: Hex, isCompressed = true): Uint8Array { + if (isProbPub(privateA)) throw new Error('first arg must be private key'); + if (!isProbPub(publicB)) throw new Error('second arg must be public key'); + const b = Point.fromHex(publicB); // check for being on-curve + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + + // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets. + // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int. + // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same. + // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors + const bits2int = + CURVE.bits2int || + function (bytes: Uint8Array): bigint { + // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m) + // for some cases, since bytes.length * 8 is not actual bitLength. + const num = ut.bytesToNumberBE(bytes); // check for == u8 done here + const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits + return delta > 0 ? num >> BigInt(delta) : num; + }; + const bits2int_modN = + CURVE.bits2int_modN || + function (bytes: Uint8Array): bigint { + return modN(bits2int(bytes)); // can't use bytesToNumberBE here + }; + // NOTE: pads output with zero as per spec + const ORDER_MASK = ut.bitMask(CURVE.nBitLength); + /** + * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. + */ + function int2octets(num: bigint): Uint8Array { + if (typeof num !== 'bigint') throw new Error('bigint expected'); + if (!(_0n <= num && num < ORDER_MASK)) + throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); + // works with order, can have different size than numToField! + return ut.numberToBytesBE(num, CURVE.nByteLength); + } + + // Steps A, D of RFC6979 3.2 + // Creates RFC6979 seed; converts msg/privKey to numbers. + // Used only in sign, not in verify. + // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521. + // Also it can be bigger for P224 + SHA256 + function prepSig(msgHash: Hex, privateKey: PrivKey, opts = defaultSigOpts) { + if (['recovered', 'canonical'].some((k) => k in opts)) + throw new Error('sign() legacy options not supported'); + const { hash, randomBytes } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default + if (lowS == null) lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash + msgHash = ensureBytes('msgHash', msgHash); + if (prehash) msgHash = ensureBytes('prehashed msgHash', hash(msgHash)); + + // We can't later call bits2octets, since nested bits2int is broken for curves + // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call. + // const bits2octets = (bits) => int2octets(bits2int_modN(bits)) + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint + const seedArgs = [int2octets(d), int2octets(h1int)]; + // extraEntropy. RFC6979 3.6: additional k' (optional). + if (ent != null) { + // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') + const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is + seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes + } + const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2 + const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash! + // Converts signature params into point w r/s, checks result for validity. + function k2sig(kBytes: Uint8Array): RecoveredSignature | undefined { + // RFC 6979 Section 3.2, step 3: k = bits2int(T) + const k = bits2int(kBytes); // Cannot use fields methods, since it is group element + if (!isWithinCurveOrder(k)) return; // Important: all mod() calls here must be done over N + const ik = invN(k); // k^-1 mod n + const q = Point.BASE.multiply(k).toAffine(); // q = Gk + const r = modN(q.x); // r = q.x mod n + if (r === _0n) return; + // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to + // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it: + // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT + const s = modN(ik * modN(m + r * d)); // Not using blinding here + if (s === _0n) return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n) + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); // if lowS was passed, ensure s is always + recovery ^= 1; // // in the bottom half of N + } + return new Signature(r, normS, recovery) as RecoveredSignature; // use normS, not s + } + return { seed, k2sig }; + } + const defaultSigOpts: SignOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts: VerOpts = { lowS: CURVE.lowS, prehash: false }; + + /** + * Signs message hash with a private key. + * ``` + * sign(m, d, k) where + * (x, y) = G × k + * r = x mod n + * s = (m + dr)/k mod n + * ``` + * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`. + * @param privKey private key + * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg. + * @returns signature with recovery param + */ + function sign(msgHash: Hex, privKey: PrivKey, opts = defaultSigOpts): RecoveredSignature { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2. + const C = CURVE; + const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); // Steps B, C, D, E, F, G + } + + // Enable precomputes. Slows down first publicKey computation by 20ms. + Point.BASE._setWindowSize(8); + // utils.precompute(8, ProjectivePoint.BASE) + + /** + * Verifies a signature against message hash and public key. + * Rejects lowS signatures by default: to override, + * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf: + * + * ``` + * verify(r, s, h, P) where + * U1 = hs^-1 mod n + * U2 = rs^-1 mod n + * R = U1⋅G - U2⋅P + * mod(R.x, n) == r + * ``` + */ + function verify( + signature: Hex | SignatureLike, + msgHash: Hex, + publicKey: Hex, + opts = defaultVerOpts + ): boolean { + const sg = signature; + msgHash = ensureBytes('msgHash', msgHash); + publicKey = ensureBytes('publicKey', publicKey); + if ('strict' in opts) throw new Error('options.strict was renamed to lowS'); + const { lowS, prehash } = opts; + + let _sig: Signature | undefined = undefined; + let P: ProjPointType; + try { + if (typeof sg === 'string' || sg instanceof Uint8Array) { + // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length). + // Since DER can also be 2*nByteLength bytes, we check for it first. + try { + _sig = Signature.fromDER(sg); + } catch (derError) { + if (!(derError instanceof DER.Err)) throw derError; + _sig = Signature.fromCompact(sg); + } + } else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') { + const { r, s } = sg; + _sig = new Signature(r, s); + } else { + throw new Error('PARSE'); + } + P = Point.fromHex(publicKey); + } catch (error) { + if ((error as Error).message === 'PARSE') + throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; + } + if (lowS && _sig.hasHighS()) return false; + if (prehash) msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element + const is = invN(s); // s^-1 + const u1 = modN(h * is); // u1 = hs^-1 mod n + const u2 = modN(r * is); // u2 = rs^-1 mod n + const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P + if (!R) return false; + const v = modN(R.x); + return v === r; + } + return { + CURVE, + getPublicKey, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point, + Signature, + utils, + }; +} + +/** + * Implementation of the Shallue and van de Woestijne method for any weierstrass curve. + * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular. + * b = True and y = sqrt(u / v) if (u / v) is square in F, and + * b = False and y = sqrt(Z * (u / v)) otherwise. + * @param Fp + * @param Z + * @returns + */ +export function SWUFpSqrtRatio(Fp: mod.IField, Z: T) { + // Generic implementation + const q = Fp.ORDER; + let l = _0n; + for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n; + const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1. + // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<. + // 2n ** c1 == 2n << (c1-1) + const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n); + const _2n_pow_c1 = _2n_pow_c1_1 * _2n; + const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic + const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic + const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic + const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic + const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2 + const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2) + let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => { + let tv1 = c6; // 1. tv1 = c6 + let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4 + let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2 + tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v + let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3 + tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3 + tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2 + tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v + tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u + let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2 + tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5 + let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1 + tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7 + tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1 + tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR) + tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR) + // 17. for i in (c1, c1 - 1, ..., 2): + for (let i = c1; i > _1n; i--) { + let tv5 = i - _2n; // 18. tv5 = i - 2 + tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5 + let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5 + const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1 + tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1 + tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1 + tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1 + tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1) + tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1) + } + return { isValid: isQR, value: tv3 }; + }; + if (Fp.ORDER % _4n === _3n) { + // sqrt_ratio_3mod4(u, v) + const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic + const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z) + sqrtRatio = (u: T, v: T) => { + let tv1 = Fp.sqr(v); // 1. tv1 = v^2 + const tv2 = Fp.mul(u, v); // 2. tv2 = u * v + tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2 + let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1 + y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2 + const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2 + const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v + const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u + let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR) + return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2 + }; + } + // No curves uses that + // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8 + return sqrtRatio; +} +/** + * Simplified Shallue-van de Woestijne-Ulas Method + * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2 + */ +export function mapToCurveSimpleSWU( + Fp: mod.IField, + opts: { + A: T; + B: T; + Z: T; + } +) { + mod.validateField(Fp); + if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z)) + throw new Error('mapToCurveSimpleSWU: invalid opts'); + const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z); + if (!Fp.isOdd) throw new Error('Fp.isOdd is not implemented!'); + // Input: u, an element of F. + // Output: (x, y), a point on E. + return (u: T): { x: T; y: T } => { + // prettier-ignore + let tv1, tv2, tv3, tv4, tv5, tv6, x, y; + tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1 + tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2 + tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1 + tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1 + tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3 + tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0) + tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4 + tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2 + tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2 + tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6 + tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5 + tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3 + tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4 + tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6 + tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5 + x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3 + const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6) + y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1 + y = Fp.mul(y, value); // 20. y = y * y1 + x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square) + y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square) + const e1 = Fp.isOdd!(u) === Fp.isOdd!(y); // 23. e1 = sgn0(u) == sgn0(y) + y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1) + x = Fp.div(x, tv4); // 25. x = x / tv4 + return { x, y }; + }; +} diff --git a/node_modules/@noble/curves/src/bls12-381.ts b/node_modules/@noble/curves/src/bls12-381.ts new file mode 100644 index 0000000..a98d72b --- /dev/null +++ b/node_modules/@noble/curves/src/bls12-381.ts @@ -0,0 +1,1350 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + +// bls12-381 pairing-friendly Barreto-Lynn-Scott elliptic curve construction allows to: +// - Construct zk-SNARKs at the 128-bit security +// - Use threshold signatures, which allows a user to sign lots of messages with one signature and +// verify them swiftly in a batch, using Boneh-Lynn-Shacham signature scheme. +// +// The library uses G1 for public keys and G2 for signatures. Support for G1 signatures is planned. +// Compatible with Algorand, Chia, Dfinity, Ethereum, FIL, Zcash. Matches specs +// [pairing-curves-11](https://tools.ietf.org/html/draft-irtf-cfrg-pairing-friendly-curves-11), +// [bls-sigs-04](https:/cfrg-hash-to/tools.ietf.org/html/draft-irtf-cfrg-bls-signature-04), +// [hash-to-curve-12](https://tools.ietf.org/html/draft-irtf--curve-12). +// +// ### Summary +// 1. BLS Relies on Bilinear Pairing (expensive) +// 2. Private Keys: 32 bytes +// 3. Public Keys: 48 bytes: 381 bit affine x coordinate, encoded into 48 big-endian bytes. +// 4. Signatures: 96 bytes: two 381 bit integers (affine x coordinate), encoded into two 48 big-endian byte arrays. +// - The signature is a point on the G2 subgroup, which is defined over a finite field +// with elements twice as big as the G1 curve (G2 is over Fp2 rather than Fp. Fp2 is analogous to the complex numbers). +// 5. The 12 stands for the Embedding degree. +// +// ### Formulas +// - `P = pk x G` - public keys +// - `S = pk x H(m)` - signing +// - `e(P, H(m)) == e(G, S)` - verification using pairings +// - `e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))` - signature aggregation +// Filecoin uses little endian byte arrays for private keys - +// so ensure to reverse byte order if you'll use it with FIL. +import { sha256 } from '@noble/hashes/sha256'; +import { randomBytes } from '@noble/hashes/utils'; +import { bls, CurveFn } from './abstract/bls.js'; +import * as mod from './abstract/modular.js'; +import { + concatBytes as concatB, + ensureBytes, + numberToBytesBE, + bytesToNumberBE, + bitLen, + bitSet, + bitGet, + Hex, + bitMask, + bytesToHex, +} from './abstract/utils.js'; +// Types +import { + ProjPointType, + ProjConstructor, + mapToCurveSimpleSWU, + AffinePoint, +} from './abstract/weierstrass.js'; +import { isogenyMap } from './abstract/hash-to-curve.js'; + +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4); +// prettier-ignore +const _8n = BigInt(8), _16n = BigInt(16); + +// CURVE FIELDS +// Finite field over p. +const Fp_raw = BigInt( + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab' +); +const Fp = mod.Field(Fp_raw); +type Fp = bigint; +// Finite field over r. +// This particular field is not used anywhere in bls12-381, but it is still useful. +const Fr = mod.Field(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')); + +// Fp₂ over complex plane +type BigintTuple = [bigint, bigint]; +type Fp2 = { c0: bigint; c1: bigint }; +const Fp2Add = ({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2) => ({ + c0: Fp.add(c0, r0), + c1: Fp.add(c1, r1), +}); +const Fp2Subtract = ({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2) => ({ + c0: Fp.sub(c0, r0), + c1: Fp.sub(c1, r1), +}); +const Fp2Multiply = ({ c0, c1 }: Fp2, rhs: Fp2) => { + if (typeof rhs === 'bigint') return { c0: Fp.mul(c0, rhs), c1: Fp.mul(c1, rhs) }; + // (a+bi)(c+di) = (ac−bd) + (ad+bc)i + const { c0: r0, c1: r1 } = rhs; + let t1 = Fp.mul(c0, r0); // c0 * o0 + let t2 = Fp.mul(c1, r1); // c1 * o1 + // (T1 - T2) + ((c0 + c1) * (r0 + r1) - (T1 + T2))*i + const o0 = Fp.sub(t1, t2); + const o1 = Fp.sub(Fp.mul(Fp.add(c0, c1), Fp.add(r0, r1)), Fp.add(t1, t2)); + return { c0: o0, c1: o1 }; +}; +const Fp2Square = ({ c0, c1 }: Fp2) => { + const a = Fp.add(c0, c1); + const b = Fp.sub(c0, c1); + const c = Fp.add(c0, c0); + return { c0: Fp.mul(a, b), c1: Fp.mul(c, c1) }; +}; +type Fp2Utils = { + fromBigTuple: (tuple: BigintTuple | bigint[]) => Fp2; + reim: (num: Fp2) => { re: bigint; im: bigint }; + mulByNonresidue: (num: Fp2) => Fp2; + multiplyByB: (num: Fp2) => Fp2; + frobeniusMap(num: Fp2, power: number): Fp2; +}; +// G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1), +// where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where +// G² - 1 +// h2q +// NOTE: ORDER was wrong! +const FP2_ORDER = Fp_raw * Fp_raw; + +const Fp2: mod.IField & Fp2Utils = { + ORDER: FP2_ORDER, + BITS: bitLen(FP2_ORDER), + BYTES: Math.ceil(bitLen(FP2_ORDER) / 8), + MASK: bitMask(bitLen(FP2_ORDER)), + ZERO: { c0: Fp.ZERO, c1: Fp.ZERO }, + ONE: { c0: Fp.ONE, c1: Fp.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => typeof c0 === 'bigint' && typeof c1 === 'bigint', + is0: ({ c0, c1 }) => Fp.is0(c0) && Fp.is0(c1), + eql: ({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2) => Fp.eql(c0, r0) && Fp.eql(c1, r1), + neg: ({ c0, c1 }) => ({ c0: Fp.neg(c0), c1: Fp.neg(c1) }), + pow: (num, power) => mod.FpPow(Fp2, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp2, nums), + // Normalized + add: Fp2Add, + sub: Fp2Subtract, + mul: Fp2Multiply, + sqr: Fp2Square, + // NonNormalized stuff + addN: Fp2Add, + subN: Fp2Subtract, + mulN: Fp2Multiply, + sqrN: Fp2Square, + // Why inversion for bigint inside Fp instead of Fp2? it is even used in that context? + div: (lhs, rhs) => Fp2.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp2.inv(rhs)), + inv: ({ c0: a, c1: b }) => { + // We wish to find the multiplicative inverse of a nonzero + // element a + bu in Fp2. We leverage an identity + // + // (a + bu)(a - bu) = a² + b² + // + // which holds because u² = -1. This can be rewritten as + // + // (a + bu)(a - bu)/(a² + b²) = 1 + // + // because a² + b² = 0 has no nonzero solutions for (a, b). + // This gives that (a - bu)/(a² + b²) is the inverse + // of (a + bu). Importantly, this can be computing using + // only a single inversion in Fp. + const factor = Fp.inv(Fp.create(a * a + b * b)); + return { c0: Fp.mul(factor, Fp.create(a)), c1: Fp.mul(factor, Fp.create(-b)) }; + }, + sqrt: (num) => { + if (Fp2.eql(num, Fp2.ZERO)) return Fp2.ZERO; // Algo doesn't handles this case + // TODO: Optimize this line. It's extremely slow. + // Speeding this up would boost aggregateSignatures. + // https://eprint.iacr.org/2012/685.pdf applicable? + // https://github.com/zkcrypto/bls12_381/blob/080eaa74ec0e394377caa1ba302c8c121df08b07/src/fp2.rs#L250 + // https://github.com/supranational/blst/blob/aae0c7d70b799ac269ff5edf29d8191dbd357876/src/exp2.c#L1 + // Inspired by https://github.com/dalek-cryptography/curve25519-dalek/blob/17698df9d4c834204f83a3574143abacb4fc81a5/src/field.rs#L99 + const candidateSqrt = Fp2.pow(num, (Fp2.ORDER + _8n) / _16n); + const check = Fp2.div(Fp2.sqr(candidateSqrt), num); // candidateSqrt.square().div(this); + const R = FP2_ROOTS_OF_UNITY; + const divisor = [R[0], R[2], R[4], R[6]].find((r) => Fp2.eql(r, check)); + if (!divisor) throw new Error('No root'); + const index = R.indexOf(divisor); + const root = R[index / 2]; + if (!root) throw new Error('Invalid root'); + const x1 = Fp2.div(candidateSqrt, root); + const x2 = Fp2.neg(x1); + const { re: re1, im: im1 } = Fp2.reim(x1); + const { re: re2, im: im2 } = Fp2.reim(x2); + if (im1 > im2 || (im1 === im2 && re1 > re2)) return x1; + return x2; + }, + // Same as sgn0_m_eq_2 in RFC 9380 + isOdd: (x: Fp2) => { + const { re: x0, im: x1 } = Fp2.reim(x); + const sign_0 = x0 % _2n; + const zero_0 = x0 === _0n; + const sign_1 = x1 % _2n; + return BigInt(sign_0 || (zero_0 && sign_1)) == _1n; + }, + // Bytes util + fromBytes(b: Uint8Array): Fp2 { + if (b.length !== Fp2.BYTES) throw new Error(`fromBytes wrong length=${b.length}`); + return { c0: Fp.fromBytes(b.subarray(0, Fp.BYTES)), c1: Fp.fromBytes(b.subarray(Fp.BYTES)) }; + }, + toBytes: ({ c0, c1 }) => concatB(Fp.toBytes(c0), Fp.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp.cmov(c0, r0, c), + c1: Fp.cmov(c1, r1, c), + }), + // Specific utils + // toString() { + // return `Fp2(${this.c0} + ${this.c1}×i)`; + // } + reim: ({ c0, c1 }) => ({ re: c0, im: c1 }), + // multiply by u + 1 + mulByNonresidue: ({ c0, c1 }) => ({ c0: Fp.sub(c0, c1), c1: Fp.add(c0, c1) }), + multiplyByB: ({ c0, c1 }) => { + let t0 = Fp.mul(c0, _4n); // 4 * c0 + let t1 = Fp.mul(c1, _4n); // 4 * c1 + // (T0-T1) + (T0+T1)*i + return { c0: Fp.sub(t0, t1), c1: Fp.add(t0, t1) }; + }, + fromBigTuple: (tuple: BigintTuple | bigint[]) => { + if (tuple.length !== 2) throw new Error('Invalid tuple'); + const fps = tuple.map((n) => Fp.create(n)) as [Fp, Fp]; + return { c0: fps[0], c1: fps[1] }; + }, + frobeniusMap: ({ c0, c1 }, power: number): Fp2 => ({ + c0, + c1: Fp.mul(c1, FP2_FROBENIUS_COEFFICIENTS[power % 2]), + }), +}; +// Finite extension field over irreducible polynominal. +// Fp(u) / (u² - β) where β = -1 +const FP2_FROBENIUS_COEFFICIENTS = [ + BigInt('0x1'), + BigInt( + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa' + ), +].map((item) => Fp.create(item)); + +// For Fp2 roots of unity. +const rv1 = BigInt( + '0x6af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09' +); +// const ev1 = +// BigInt('0x699be3b8c6870965e5bf892ad5d2cc7b0e85a117402dfd83b7f4a947e02d978498255a2aaec0ac627b5afbdf1bf1c90'); +// const ev2 = +// BigInt('0x8157cd83046453f5dd0972b6e3949e4288020b5b8a9cc99ca07e27089a2ce2436d965026adad3ef7baba37f2183e9b5'); +// const ev3 = +// BigInt('0xab1c2ffdd6c253ca155231eb3e71ba044fd562f6f72bc5bad5ec46a0b7a3b0247cf08ce6c6317f40edbc653a72dee17'); +// const ev4 = +// BigInt('0xaa404866706722864480885d68ad0ccac1967c7544b447873cc37e0181271e006df72162a3d3e0287bf597fbf7f8fc1'); + +// Eighth roots of unity, used for computing square roots in Fp2. +// To verify or re-calculate: +// Array(8).fill(new Fp2([1n, 1n])).map((fp2, k) => fp2.pow(Fp2.ORDER * BigInt(k) / 8n)) +const FP2_ROOTS_OF_UNITY = [ + [_1n, _0n], + [rv1, -rv1], + [_0n, _1n], + [rv1, rv1], + [-_1n, _0n], + [-rv1, rv1], + [_0n, -_1n], + [-rv1, -rv1], +].map((pair) => Fp2.fromBigTuple(pair)); +// eta values, used for computing sqrt(g(X1(t))) +// const FP2_ETAs = [ +// [ev1, ev2], +// [-ev2, ev1], +// [ev3, ev4], +// [-ev4, ev3], +// ].map((pair) => Fp2.fromBigTuple(pair)); + +// Finite extension field over irreducible polynominal. +// Fp2(v) / (v³ - ξ) where ξ = u + 1 +type BigintSix = [bigint, bigint, bigint, bigint, bigint, bigint]; +type Fp6 = { c0: Fp2; c1: Fp2; c2: Fp2 }; +const Fp6Add = ({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6) => ({ + c0: Fp2.add(c0, r0), + c1: Fp2.add(c1, r1), + c2: Fp2.add(c2, r2), +}); +const Fp6Subtract = ({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6) => ({ + c0: Fp2.sub(c0, r0), + c1: Fp2.sub(c1, r1), + c2: Fp2.sub(c2, r2), +}); +const Fp6Multiply = ({ c0, c1, c2 }: Fp6, rhs: Fp6 | bigint) => { + if (typeof rhs === 'bigint') { + return { + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }; + } + const { c0: r0, c1: r1, c2: r2 } = rhs; + const t0 = Fp2.mul(c0, r0); // c0 * o0 + const t1 = Fp2.mul(c1, r1); // c1 * o1 + const t2 = Fp2.mul(c2, r2); // c2 * o2 + return { + // t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1) + c0: Fp2.add( + t0, + Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), Fp2.add(r1, r2)), Fp2.add(t1, t2))) + ), + // (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1) + c1: Fp2.add( + Fp2.sub(Fp2.mul(Fp2.add(c0, c1), Fp2.add(r0, r1)), Fp2.add(t0, t1)), + Fp2.mulByNonresidue(t2) + ), + // T1 + (c0 + c2) * (r0 + r2) - T0 + T2 + c2: Fp2.sub(Fp2.add(t1, Fp2.mul(Fp2.add(c0, c2), Fp2.add(r0, r2))), Fp2.add(t0, t2)), + }; +}; +const Fp6Square = ({ c0, c1, c2 }: Fp6) => { + let t0 = Fp2.sqr(c0); // c0² + let t1 = Fp2.mul(Fp2.mul(c0, c1), _2n); // 2 * c0 * c1 + let t3 = Fp2.mul(Fp2.mul(c1, c2), _2n); // 2 * c1 * c2 + let t4 = Fp2.sqr(c2); // c2² + return { + c0: Fp2.add(Fp2.mulByNonresidue(t3), t0), // T3 * (u + 1) + T0 + c1: Fp2.add(Fp2.mulByNonresidue(t4), t1), // T4 * (u + 1) + T1 + // T1 + (c0 - c1 + c2)² + T3 - T0 - T4 + c2: Fp2.sub(Fp2.sub(Fp2.add(Fp2.add(t1, Fp2.sqr(Fp2.add(Fp2.sub(c0, c1), c2))), t3), t0), t4), + }; +}; +type Fp6Utils = { + fromBigSix: (tuple: BigintSix) => Fp6; + mulByNonresidue: (num: Fp6) => Fp6; + frobeniusMap(num: Fp6, power: number): Fp6; + multiplyBy1(num: Fp6, b1: Fp2): Fp6; + multiplyBy01(num: Fp6, b0: Fp2, b1: Fp2): Fp6; + multiplyByFp2(lhs: Fp6, rhs: Fp2): Fp6; +}; + +const Fp6: mod.IField & Fp6Utils = { + ORDER: Fp2.ORDER, // TODO: unused, but need to verify + BITS: 3 * Fp2.BITS, + BYTES: 3 * Fp2.BYTES, + MASK: bitMask(3 * Fp2.BITS), + ZERO: { c0: Fp2.ZERO, c1: Fp2.ZERO, c2: Fp2.ZERO }, + ONE: { c0: Fp2.ONE, c1: Fp2.ZERO, c2: Fp2.ZERO }, + create: (num) => num, + isValid: ({ c0, c1, c2 }) => Fp2.isValid(c0) && Fp2.isValid(c1) && Fp2.isValid(c2), + is0: ({ c0, c1, c2 }) => Fp2.is0(c0) && Fp2.is0(c1) && Fp2.is0(c2), + neg: ({ c0, c1, c2 }) => ({ c0: Fp2.neg(c0), c1: Fp2.neg(c1), c2: Fp2.neg(c2) }), + eql: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => + Fp2.eql(c0, r0) && Fp2.eql(c1, r1) && Fp2.eql(c2, r2), + sqrt: () => { + throw new Error('Not implemented'); + }, + // Do we need division by bigint at all? Should be done via order: + div: (lhs, rhs) => Fp6.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp6.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp6, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp6, nums), + // Normalized + add: Fp6Add, + sub: Fp6Subtract, + mul: Fp6Multiply, + sqr: Fp6Square, + // NonNormalized stuff + addN: Fp6Add, + subN: Fp6Subtract, + mulN: Fp6Multiply, + sqrN: Fp6Square, + + inv: ({ c0, c1, c2 }) => { + let t0 = Fp2.sub(Fp2.sqr(c0), Fp2.mulByNonresidue(Fp2.mul(c2, c1))); // c0² - c2 * c1 * (u + 1) + let t1 = Fp2.sub(Fp2.mulByNonresidue(Fp2.sqr(c2)), Fp2.mul(c0, c1)); // c2² * (u + 1) - c0 * c1 + let t2 = Fp2.sub(Fp2.sqr(c1), Fp2.mul(c0, c2)); // c1² - c0 * c2 + // 1/(((c2 * T1 + c1 * T2) * v) + c0 * T0) + let t4 = Fp2.inv( + Fp2.add(Fp2.mulByNonresidue(Fp2.add(Fp2.mul(c2, t1), Fp2.mul(c1, t2))), Fp2.mul(c0, t0)) + ); + return { c0: Fp2.mul(t4, t0), c1: Fp2.mul(t4, t1), c2: Fp2.mul(t4, t2) }; + }, + // Bytes utils + fromBytes: (b: Uint8Array): Fp6 => { + if (b.length !== Fp6.BYTES) throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp2.fromBytes(b.subarray(0, Fp2.BYTES)), + c1: Fp2.fromBytes(b.subarray(Fp2.BYTES, 2 * Fp2.BYTES)), + c2: Fp2.fromBytes(b.subarray(2 * Fp2.BYTES)), + }; + }, + toBytes: ({ c0, c1, c2 }): Uint8Array => + concatB(Fp2.toBytes(c0), Fp2.toBytes(c1), Fp2.toBytes(c2)), + cmov: ({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6, c) => ({ + c0: Fp2.cmov(c0, r0, c), + c1: Fp2.cmov(c1, r1, c), + c2: Fp2.cmov(c2, r2, c), + }), + // Utils + // fromTriple(triple: [Fp2, Fp2, Fp2]) { + // return new Fp6(...triple); + // } + // toString() { + // return `Fp6(${this.c0} + ${this.c1} * v, ${this.c2} * v^2)`; + // } + fromBigSix: (t: BigintSix): Fp6 => { + if (!Array.isArray(t) || t.length !== 6) throw new Error('Invalid Fp6 usage'); + return { + c0: Fp2.fromBigTuple(t.slice(0, 2)), + c1: Fp2.fromBigTuple(t.slice(2, 4)), + c2: Fp2.fromBigTuple(t.slice(4, 6)), + }; + }, + frobeniusMap: ({ c0, c1, c2 }, power: number) => ({ + c0: Fp2.frobeniusMap(c0, power), + c1: Fp2.mul(Fp2.frobeniusMap(c1, power), FP6_FROBENIUS_COEFFICIENTS_1[power % 6]), + c2: Fp2.mul(Fp2.frobeniusMap(c2, power), FP6_FROBENIUS_COEFFICIENTS_2[power % 6]), + }), + mulByNonresidue: ({ c0, c1, c2 }) => ({ c0: Fp2.mulByNonresidue(c2), c1: c0, c2: c1 }), + + // Sparse multiplication + multiplyBy1: ({ c0, c1, c2 }, b1: Fp2): Fp6 => ({ + c0: Fp2.mulByNonresidue(Fp2.mul(c2, b1)), + c1: Fp2.mul(c0, b1), + c2: Fp2.mul(c1, b1), + }), + // Sparse multiplication + multiplyBy01({ c0, c1, c2 }, b0: Fp2, b1: Fp2): Fp6 { + let t0 = Fp2.mul(c0, b0); // c0 * b0 + let t1 = Fp2.mul(c1, b1); // c1 * b1 + return { + // ((c1 + c2) * b1 - T1) * (u + 1) + T0 + c0: Fp2.add(Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), b1), t1)), t0), + // (b0 + b1) * (c0 + c1) - T0 - T1 + c1: Fp2.sub(Fp2.sub(Fp2.mul(Fp2.add(b0, b1), Fp2.add(c0, c1)), t0), t1), + // (c0 + c2) * b0 - T0 + T1 + c2: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c2), b0), t0), t1), + }; + }, + + multiplyByFp2: ({ c0, c1, c2 }, rhs: Fp2): Fp6 => ({ + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }), +}; + +const FP6_FROBENIUS_COEFFICIENTS_1 = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt('0x0'), + BigInt( + '0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac' + ), + ], + [ + BigInt( + '0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe' + ), + BigInt('0x0'), + ], + [BigInt('0x0'), BigInt('0x1')], + [ + BigInt( + '0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac' + ), + BigInt('0x0'), + ], + [ + BigInt('0x0'), + BigInt( + '0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe' + ), + ], +].map((pair) => Fp2.fromBigTuple(pair)); +const FP6_FROBENIUS_COEFFICIENTS_2 = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt( + '0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff' + ), + BigInt('0x0'), + ], +].map((pair) => Fp2.fromBigTuple(pair)); + +// Finite extension field over irreducible polynominal. +// Fp₁₂ = Fp₆² => Fp₂³ +// Fp₆(w) / (w² - γ) where γ = v +type Fp12 = { c0: Fp6; c1: Fp6 }; +// The BLS parameter x for BLS12-381 +const BLS_X = BigInt('0xd201000000010000'); +const BLS_X_LEN = bitLen(BLS_X); + +// prettier-ignore +type BigintTwelve = [ + bigint, bigint, bigint, bigint, bigint, bigint, + bigint, bigint, bigint, bigint, bigint, bigint + ]; +const Fp12Add = ({ c0, c1 }: Fp12, { c0: r0, c1: r1 }: Fp12) => ({ + c0: Fp6.add(c0, r0), + c1: Fp6.add(c1, r1), +}); +const Fp12Subtract = ({ c0, c1 }: Fp12, { c0: r0, c1: r1 }: Fp12) => ({ + c0: Fp6.sub(c0, r0), + c1: Fp6.sub(c1, r1), +}); +const Fp12Multiply = ({ c0, c1 }: Fp12, rhs: Fp12 | bigint) => { + if (typeof rhs === 'bigint') return { c0: Fp6.mul(c0, rhs), c1: Fp6.mul(c1, rhs) }; + let { c0: r0, c1: r1 } = rhs; + let t1 = Fp6.mul(c0, r0); // c0 * r0 + let t2 = Fp6.mul(c1, r1); // c1 * r1 + return { + c0: Fp6.add(t1, Fp6.mulByNonresidue(t2)), // T1 + T2 * v + // (c0 + c1) * (r0 + r1) - (T1 + T2) + c1: Fp6.sub(Fp6.mul(Fp6.add(c0, c1), Fp6.add(r0, r1)), Fp6.add(t1, t2)), + }; +}; +const Fp12Square = ({ c0, c1 }: Fp12) => { + let ab = Fp6.mul(c0, c1); // c0 * c1 + return { + // (c1 * v + c0) * (c0 + c1) - AB - AB * v + c0: Fp6.sub( + Fp6.sub(Fp6.mul(Fp6.add(Fp6.mulByNonresidue(c1), c0), Fp6.add(c0, c1)), ab), + Fp6.mulByNonresidue(ab) + ), + c1: Fp6.add(ab, ab), + }; // AB + AB +}; +function Fp4Square(a: Fp2, b: Fp2): { first: Fp2; second: Fp2 } { + const a2 = Fp2.sqr(a); + const b2 = Fp2.sqr(b); + return { + first: Fp2.add(Fp2.mulByNonresidue(b2), a2), // b² * Nonresidue + a² + second: Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(a, b)), a2), b2), // (a + b)² - a² - b² + }; +} +type Fp12Utils = { + fromBigTwelve: (t: BigintTwelve) => Fp12; + frobeniusMap(num: Fp12, power: number): Fp12; + multiplyBy014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12; + multiplyByFp2(lhs: Fp12, rhs: Fp2): Fp12; + conjugate(num: Fp12): Fp12; + finalExponentiate(num: Fp12): Fp12; + _cyclotomicSquare(num: Fp12): Fp12; + _cyclotomicExp(num: Fp12, n: bigint): Fp12; +}; + +const Fp12: mod.IField & Fp12Utils = { + ORDER: Fp2.ORDER, // TODO: unused, but need to verify + BITS: 2 * Fp2.BITS, + BYTES: 2 * Fp2.BYTES, + MASK: bitMask(2 * Fp2.BITS), + ZERO: { c0: Fp6.ZERO, c1: Fp6.ZERO }, + ONE: { c0: Fp6.ONE, c1: Fp6.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => Fp6.isValid(c0) && Fp6.isValid(c1), + is0: ({ c0, c1 }) => Fp6.is0(c0) && Fp6.is0(c1), + neg: ({ c0, c1 }) => ({ c0: Fp6.neg(c0), c1: Fp6.neg(c1) }), + eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp6.eql(c0, r0) && Fp6.eql(c1, r1), + sqrt: () => { + throw new Error('Not implemented'); + }, + inv: ({ c0, c1 }) => { + let t = Fp6.inv(Fp6.sub(Fp6.sqr(c0), Fp6.mulByNonresidue(Fp6.sqr(c1)))); // 1 / (c0² - c1² * v) + return { c0: Fp6.mul(c0, t), c1: Fp6.neg(Fp6.mul(c1, t)) }; // ((C0 * T) * T) + (-C1 * T) * w + }, + div: (lhs, rhs) => + Fp12.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp12.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp12, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp12, nums), + // Normalized + add: Fp12Add, + sub: Fp12Subtract, + mul: Fp12Multiply, + sqr: Fp12Square, + // NonNormalized stuff + addN: Fp12Add, + subN: Fp12Subtract, + mulN: Fp12Multiply, + sqrN: Fp12Square, + + // Bytes utils + fromBytes: (b: Uint8Array): Fp12 => { + if (b.length !== Fp12.BYTES) throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp6.fromBytes(b.subarray(0, Fp6.BYTES)), + c1: Fp6.fromBytes(b.subarray(Fp6.BYTES)), + }; + }, + toBytes: ({ c0, c1 }): Uint8Array => concatB(Fp6.toBytes(c0), Fp6.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp6.cmov(c0, r0, c), + c1: Fp6.cmov(c1, r1, c), + }), + // Utils + // toString() { + // return `Fp12(${this.c0} + ${this.c1} * w)`; + // }, + // fromTuple(c: [Fp6, Fp6]) { + // return new Fp12(...c); + // } + fromBigTwelve: (t: BigintTwelve): Fp12 => ({ + c0: Fp6.fromBigSix(t.slice(0, 6) as BigintSix), + c1: Fp6.fromBigSix(t.slice(6, 12) as BigintSix), + }), + // Raises to q**i -th power + frobeniusMap(lhs, power: number) { + const r0 = Fp6.frobeniusMap(lhs.c0, power); + const { c0, c1, c2 } = Fp6.frobeniusMap(lhs.c1, power); + const coeff = FP12_FROBENIUS_COEFFICIENTS[power % 12]; + return { + c0: r0, + c1: Fp6.create({ + c0: Fp2.mul(c0, coeff), + c1: Fp2.mul(c1, coeff), + c2: Fp2.mul(c2, coeff), + }), + }; + }, + // Sparse multiplication + multiplyBy014: ({ c0, c1 }, o0: Fp2, o1: Fp2, o4: Fp2) => { + let t0 = Fp6.multiplyBy01(c0, o0, o1); + let t1 = Fp6.multiplyBy1(c1, o4); + return { + c0: Fp6.add(Fp6.mulByNonresidue(t1), t0), // T1 * v + T0 + // (c1 + c0) * [o0, o1+o4] - T0 - T1 + c1: Fp6.sub(Fp6.sub(Fp6.multiplyBy01(Fp6.add(c1, c0), o0, Fp2.add(o1, o4)), t0), t1), + }; + }, + multiplyByFp2: ({ c0, c1 }, rhs: Fp2): Fp12 => ({ + c0: Fp6.multiplyByFp2(c0, rhs), + c1: Fp6.multiplyByFp2(c1, rhs), + }), + conjugate: ({ c0, c1 }): Fp12 => ({ c0, c1: Fp6.neg(c1) }), + + // A cyclotomic group is a subgroup of Fp^n defined by + // GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1} + // The result of any pairing is in a cyclotomic subgroup + // https://eprint.iacr.org/2009/565.pdf + _cyclotomicSquare: ({ c0, c1 }): Fp12 => { + const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0; + const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1; + const { first: t3, second: t4 } = Fp4Square(c0c0, c1c1); + const { first: t5, second: t6 } = Fp4Square(c1c0, c0c2); + const { first: t7, second: t8 } = Fp4Square(c0c1, c1c2); + let t9 = Fp2.mulByNonresidue(t8); // T8 * (u + 1) + return { + c0: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.sub(t3, c0c0), _2n), t3), // 2 * (T3 - c0c0) + T3 + c1: Fp2.add(Fp2.mul(Fp2.sub(t5, c0c1), _2n), t5), // 2 * (T5 - c0c1) + T5 + c2: Fp2.add(Fp2.mul(Fp2.sub(t7, c0c2), _2n), t7), + }), // 2 * (T7 - c0c2) + T7 + c1: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.add(t9, c1c0), _2n), t9), // 2 * (T9 + c1c0) + T9 + c1: Fp2.add(Fp2.mul(Fp2.add(t4, c1c1), _2n), t4), // 2 * (T4 + c1c1) + T4 + c2: Fp2.add(Fp2.mul(Fp2.add(t6, c1c2), _2n), t6), + }), + }; // 2 * (T6 + c1c2) + T6 + }, + _cyclotomicExp(num, n) { + let z = Fp12.ONE; + for (let i = BLS_X_LEN - 1; i >= 0; i--) { + z = Fp12._cyclotomicSquare(z); + if (bitGet(n, i)) z = Fp12.mul(z, num); + } + return z; + }, + // https://eprint.iacr.org/2010/354.pdf + // https://eprint.iacr.org/2009/565.pdf + finalExponentiate: (num) => { + const x = BLS_X; + // this^(q⁶) / this + const t0 = Fp12.div(Fp12.frobeniusMap(num, 6), num); + // t0^(q²) * t0 + const t1 = Fp12.mul(Fp12.frobeniusMap(t0, 2), t0); + const t2 = Fp12.conjugate(Fp12._cyclotomicExp(t1, x)); + const t3 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicSquare(t1)), t2); + const t4 = Fp12.conjugate(Fp12._cyclotomicExp(t3, x)); + const t5 = Fp12.conjugate(Fp12._cyclotomicExp(t4, x)); + const t6 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicExp(t5, x)), Fp12._cyclotomicSquare(t2)); + const t7 = Fp12.conjugate(Fp12._cyclotomicExp(t6, x)); + const t2_t5_pow_q2 = Fp12.frobeniusMap(Fp12.mul(t2, t5), 2); + const t4_t1_pow_q3 = Fp12.frobeniusMap(Fp12.mul(t4, t1), 3); + const t6_t1c_pow_q1 = Fp12.frobeniusMap(Fp12.mul(t6, Fp12.conjugate(t1)), 1); + const t7_t3c_t1 = Fp12.mul(Fp12.mul(t7, Fp12.conjugate(t3)), t1); + // (t2 * t5)^(q²) * (t4 * t1)^(q³) * (t6 * t1.conj)^(q^1) * t7 * t3.conj * t1 + return Fp12.mul(Fp12.mul(Fp12.mul(t2_t5_pow_q2, t4_t1_pow_q3), t6_t1c_pow_q1), t7_t3c_t1); + }, +}; +const FP12_FROBENIUS_COEFFICIENTS = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt( + '0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8' + ), + BigInt( + '0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3' + ), + ], + [ + BigInt( + '0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2' + ), + BigInt( + '0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09' + ), + ], + [ + BigInt( + '0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995' + ), + BigInt( + '0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116' + ), + ], + [ + BigInt( + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3' + ), + BigInt( + '0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8' + ), + ], + [ + BigInt( + '0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09' + ), + BigInt( + '0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2' + ), + ], + [ + BigInt( + '0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116' + ), + BigInt( + '0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995' + ), + ], +].map((n) => Fp2.fromBigTuple(n)); +// END OF CURVE FIELDS + +// HashToCurve + +// 3-isogeny map from E' to E https://www.rfc-editor.org/rfc/rfc9380#appendix-E.3 +const isogenyMapG2 = isogenyMap( + Fp2, + [ + // xNum + [ + [ + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + ], + [ + '0x0', + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d', + ], + [ + '0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1', + '0x0', + ], + ], + // xDen + [ + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63', + ], + [ + '0xc', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f', + ], + ['0x1', '0x0'], // LAST 1 + ], + // yNum + [ + [ + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + ], + [ + '0x0', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f', + ], + [ + '0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10', + '0x0', + ], + ], + // yDen + [ + [ + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + ], + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3', + ], + [ + '0x12', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99', + ], + ['0x1', '0x0'], // LAST 1 + ], + ].map((i) => i.map((pair) => Fp2.fromBigTuple(pair.map(BigInt)))) as [Fp2[], Fp2[], Fp2[], Fp2[]] +); +// 11-isogeny map from E' to E +const isogenyMapG1 = isogenyMap( + Fp, + [ + // xNum + [ + '0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7', + '0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb', + '0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0', + '0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861', + '0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9', + '0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983', + '0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84', + '0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e', + '0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317', + '0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e', + '0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b', + '0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229', + ], + // xDen + [ + '0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c', + '0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff', + '0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19', + '0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8', + '0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e', + '0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5', + '0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a', + '0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e', + '0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641', + '0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33', + '0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696', + '0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6', + '0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb', + '0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb', + '0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0', + '0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2', + '0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29', + '0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587', + '0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30', + '0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132', + '0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e', + '0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8', + '0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133', + '0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b', + '0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604', + ], + // yDen + [ + '0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1', + '0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d', + '0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2', + '0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416', + '0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d', + '0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac', + '0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c', + '0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9', + '0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a', + '0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55', + '0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8', + '0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092', + '0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc', + '0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7', + '0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + ].map((i) => i.map((j) => BigInt(j))) as [Fp[], Fp[], Fp[], Fp[]] +); + +// SWU Map - Fp2 to G2': y² = x³ + 240i * x + 1012 + 1012i +const G2_SWU = mapToCurveSimpleSWU(Fp2, { + A: Fp2.create({ c0: Fp.create(_0n), c1: Fp.create(BigInt(240)) }), // A' = 240 * I + B: Fp2.create({ c0: Fp.create(BigInt(1012)), c1: Fp.create(BigInt(1012)) }), // B' = 1012 * (1 + I) + Z: Fp2.create({ c0: Fp.create(BigInt(-2)), c1: Fp.create(BigInt(-1)) }), // Z: -(2 + I) +}); +// Optimized SWU Map - Fp to G1 +const G1_SWU = mapToCurveSimpleSWU(Fp, { + A: Fp.create( + BigInt( + '0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d' + ) + ), + B: Fp.create( + BigInt( + '0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0' + ) + ), + Z: Fp.create(BigInt(11)), +}); + +// Endomorphisms (for fast cofactor clearing) +// Ψ(P) endomorphism +const ut_root = Fp6.create({ c0: Fp2.ZERO, c1: Fp2.ONE, c2: Fp2.ZERO }); +const wsq = Fp12.create({ c0: ut_root, c1: Fp6.ZERO }); +const wcu = Fp12.create({ c0: Fp6.ZERO, c1: ut_root }); +const [wsq_inv, wcu_inv] = Fp12.invertBatch([wsq, wcu]); +function psi(x: Fp2, y: Fp2): [Fp2, Fp2] { + // Untwist Fp2->Fp12 && frobenius(1) && twist back + const x2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wsq_inv, x), 1), wsq).c0.c0; + const y2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wcu_inv, y), 1), wcu).c0.c0; + return [x2, y2]; +} +// Ψ endomorphism +function G2psi(c: ProjConstructor, P: ProjPointType) { + const affine = P.toAffine(); + const p = psi(affine.x, affine.y); + return new c(p[0], p[1], Fp2.ONE); +} +// Ψ²(P) endomorphism +// 1 / F2(2)^((p-1)/3) in GF(p²) +const PSI2_C1 = BigInt( + '0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac' +); + +function psi2(x: Fp2, y: Fp2): [Fp2, Fp2] { + return [Fp2.mul(x, PSI2_C1), Fp2.neg(y)]; +} +function G2psi2(c: ProjConstructor, P: ProjPointType) { + const affine = P.toAffine(); + const p = psi2(affine.x, affine.y); + return new c(p[0], p[1], Fp2.ONE); +} + +// Default hash_to_field options are for hash to G2. +// +// Parameter definitions are in section 5.3 of the spec unless otherwise noted. +// Parameter values come from section 8.8.2 of the spec. +// https://www.rfc-editor.org/rfc/rfc9380#section-8.8.2 +// +// Base field F is GF(p^m) +// p = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab +// m = 2 (or 1 for G1 see section 8.8.1) +// k = 128 +const htfDefaults = Object.freeze({ + // DST: a domain separation tag + // defined in section 2.2.5 + // Use utils.getDSTLabel(), utils.setDSTLabel(value) + DST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + encodeDST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + // p: the characteristic of F + // where F is a finite field of characteristic p and order q = p^m + p: Fp.ORDER, + // m: the extension degree of F, m >= 1 + // where F is a finite field of characteristic p and order q = p^m + m: 2, + // k: the target security level for the suite in bits + // defined in section 5.1 + k: 128, + // option to use a message that has already been processed by + // expand_message_xmd + expand: 'xmd', + // Hash functions for: expand_message_xmd is appropriate for use with a + // wide range of hash functions, including SHA-2, SHA-3, BLAKE2, and others. + // BBS+ uses blake2: https://github.com/hyperledger/aries-framework-go/issues/2247 + hash: sha256, +} as const); + +// Encoding utils +// Point on G1 curve: (x, y) +const C_BIT_POS = Fp.BITS; // C_bit, compression bit for serialization flag +const I_BIT_POS = Fp.BITS + 1; // I_bit, point-at-infinity bit for serialization flag +const S_BIT_POS = Fp.BITS + 2; // S_bit, sign bit for serialization flag +// Compressed point of infinity +const COMPRESSED_ZERO = Fp.toBytes(bitSet(bitSet(_0n, I_BIT_POS, true), S_BIT_POS, true)); // set compressed & point-at-infinity bits + +function signatureG2ToRawBytes(point: ProjPointType) { + // NOTE: by some reasons it was missed in bls12-381, looks like bug + point.assertValidity(); + const len = Fp.BYTES; + if (point.equals(bls12_381.G2.ProjectivePoint.ZERO)) + return concatB(COMPRESSED_ZERO, numberToBytesBE(_0n, len)); + const { x, y } = point.toAffine(); + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + const tmp = y1 > _0n ? y1 * _2n : y0 * _2n; + const aflag1 = Boolean((tmp / Fp.ORDER) & _1n); + const z1 = bitSet(bitSet(x1, 381, aflag1), S_BIT_POS, true); + const z2 = x0; + return concatB(numberToBytesBE(z1, len), numberToBytesBE(z2, len)); +} + +// To verify curve parameters, see pairing-friendly-curves spec: +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-11 +// Basic math is done over finite fields over p. +// More complicated math is done over polynominal extension fields. +// To simplify calculations in Fp12, we construct extension tower: +// Fp₁₂ = Fp₆² => Fp₂³ +// Fp(u) / (u² - β) where β = -1 +// Fp₂(v) / (v³ - ξ) where ξ = u + 1 +// Fp₆(w) / (w² - γ) where γ = v +// Here goes constants && point encoding format +export const bls12_381: CurveFn = bls({ + // Fields + fields: { + Fp, + Fp2, + Fp6, + Fp12, + Fr, + }, + // G1 is the order-q subgroup of E1(Fp) : y² = x³ + 4, #E1(Fp) = h1q, where + // characteristic; z + (z⁴ - z² + 1)(z - 1)²/3 + G1: { + Fp, + // cofactor; (z - 1)²/3 + h: BigInt('0x396c8c005555e1568c00aaab0000aaab'), + // generator's coordinates + // x = 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507 + // y = 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569 + Gx: BigInt( + '0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb' + ), + Gy: BigInt( + '0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1' + ), + a: Fp.ZERO, + b: _4n, + htfDefaults: { ...htfDefaults, m: 1 }, + wrapPrivateKey: true, + allowInfinityPoint: true, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, point): boolean => { + // φ endomorphism + const cubicRootOfUnityModP = BigInt( + '0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe' + ); + const phi = new c(Fp.mul(point.px, cubicRootOfUnityModP), point.py, point.pz); + + // todo: unroll + const xP = point.multiplyUnsafe(bls12_381.params.x).negate(); // [x]P + const u2P = xP.multiplyUnsafe(bls12_381.params.x); // [u2]P + return u2P.equals(phi); + + // https://eprint.iacr.org/2019/814.pdf + // (z² − 1)/3 + // const c1 = BigInt('0x396c8c005555e1560000000055555555'); + // const P = this; + // const S = P.sigma(); + // const Q = S.double(); + // const S2 = S.sigma(); + // // [(z² − 1)/3](2σ(P) − P − σ²(P)) − σ²(P) = O + // const left = Q.subtract(P).subtract(S2).multiplyUnsafe(c1); + // const C = left.subtract(S2); + // return C.isZero(); + }, + // Clear cofactor of G1 + // https://eprint.iacr.org/2019/403 + clearCofactor: (_c, point) => { + // return this.multiplyUnsafe(CURVE.h); + return point.multiplyUnsafe(bls12_381.params.x).add(point); // x*P + P + }, + mapToCurve: (scalars: bigint[]) => { + const { x, y } = G1_SWU(Fp.create(scalars[0])); + return isogenyMapG1(x, y); + }, + fromBytes: (bytes: Uint8Array): AffinePoint => { + bytes = bytes.slice(); + if (bytes.length === 48) { + // TODO: Fp.bytes + const P = Fp.ORDER; + const compressedValue = bytesToNumberBE(bytes); + const bflag = bitGet(compressedValue, I_BIT_POS); + // Zero + if (bflag === _1n) return { x: _0n, y: _0n }; + const x = Fp.create(compressedValue & Fp.MASK); + const right = Fp.add(Fp.pow(x, _3n), Fp.create(bls12_381.params.G1b)); // y² = x³ + b + let y = Fp.sqrt(right); + if (!y) throw new Error('Invalid compressed G1 point'); + const aflag = bitGet(compressedValue, C_BIT_POS); + if ((y * _2n) / P !== aflag) y = Fp.neg(y); + return { x: Fp.create(x), y: Fp.create(y) }; + } else if (bytes.length === 96) { + // Check if the infinity flag is set + if ((bytes[0] & (1 << 6)) !== 0) return bls12_381.G1.ProjectivePoint.ZERO.toAffine(); + const x = bytesToNumberBE(bytes.subarray(0, Fp.BYTES)); + const y = bytesToNumberBE(bytes.subarray(Fp.BYTES)); + return { x: Fp.create(x), y: Fp.create(y) }; + } else { + throw new Error('Invalid point G1, expected 48/96 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) return COMPRESSED_ZERO.slice(); + const P = Fp.ORDER; + let num; + num = bitSet(x, C_BIT_POS, Boolean((y * _2n) / P)); // set aflag + num = bitSet(num, S_BIT_POS, true); + return numberToBytesBE(num, Fp.BYTES); + } else { + if (isZero) { + // 2x PUBLIC_KEY_LENGTH + const x = concatB(new Uint8Array([0x40]), new Uint8Array(2 * Fp.BYTES - 1)); + return x; + } else { + return concatB(numberToBytesBE(x, Fp.BYTES), numberToBytesBE(y, Fp.BYTES)); + } + } + }, + }, + // G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1), + // where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where + // G² - 1 + // h2q + G2: { + Fp: Fp2, + // cofactor + h: BigInt( + '0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5' + ), + Gx: Fp2.fromBigTuple([ + BigInt( + '0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8' + ), + BigInt( + '0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e' + ), + ]), + // y = + // 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582, + // 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905 + Gy: Fp2.fromBigTuple([ + BigInt( + '0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801' + ), + BigInt( + '0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be' + ), + ]), + a: Fp2.ZERO, + b: Fp2.fromBigTuple([_4n, _4n]), + hEff: BigInt( + '0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551' + ), + htfDefaults: { ...htfDefaults }, + wrapPrivateKey: true, + allowInfinityPoint: true, + mapToCurve: (scalars: bigint[]) => { + const { x, y } = G2_SWU(Fp2.fromBigTuple(scalars)); + return isogenyMapG2(x, y); + }, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, P): boolean => { + return P.multiplyUnsafe(bls12_381.params.x).negate().equals(G2psi(c, P)); // ψ(P) == [u](P) + // Older version: https://eprint.iacr.org/2019/814.pdf + // Ψ²(P) => Ψ³(P) => [z]Ψ³(P) where z = -x => [z]Ψ³(P) - Ψ²(P) + P == O + // return P.psi2().psi().mulNegX().subtract(psi2).add(P).isZero(); + }, + // Maps the point into the prime-order subgroup G2. + // clear_cofactor_bls12381_g2 from cfrg-hash-to-curve-11 + // https://eprint.iacr.org/2017/419.pdf + // prettier-ignore + clearCofactor: (c, P) => { + const x = bls12_381.params.x; + let t1 = P.multiplyUnsafe(x).negate(); // [-x]P + let t2 = G2psi(c, P); // Ψ(P) + let t3 = P.double(); // 2P + t3 = G2psi2(c, t3); // Ψ²(2P) + t3 = t3.subtract(t2); // Ψ²(2P) - Ψ(P) + t2 = t1.add(t2); // [-x]P + Ψ(P) + t2 = t2.multiplyUnsafe(x).negate(); // [x²]P - [x]Ψ(P) + t3 = t3.add(t2); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + t3 = t3.subtract(t1); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P + const Q = t3.subtract(P); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P - 1P + return Q; // [x²-x-1]P + [x-1]Ψ(P) + Ψ²(2P) + }, + fromBytes: (bytes: Uint8Array): AffinePoint => { + bytes = bytes.slice(); + const m_byte = bytes[0] & 0xe0; + if (m_byte === 0x20 || m_byte === 0x60 || m_byte === 0xe0) { + throw new Error('Invalid encoding flag: ' + m_byte); + } + const bitC = m_byte & 0x80; // compression bit + const bitI = m_byte & 0x40; // point at infinity bit + const bitS = m_byte & 0x20; // sign bit + const L = Fp.BYTES; + const slc = (b: Uint8Array, from: number, to?: number) => bytesToNumberBE(b.slice(from, to)); + if (bytes.length === 96 && bitC) { + const b = bls12_381.params.G2b; + const P = Fp.ORDER; + + bytes[0] = bytes[0] & 0x1f; // clear flags + if (bitI) { + // check that all bytes are 0 + if (bytes.reduce((p, c) => (p !== 0 ? c + 1 : c), 0) > 0) { + throw new Error('Invalid compressed G2 point'); + } + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x_1 = slc(bytes, 0, L); + const x_0 = slc(bytes, L, 2 * L); + const x = Fp2.create({ c0: Fp.create(x_0), c1: Fp.create(x_1) }); + const right = Fp2.add(Fp2.pow(x, _3n), b); // y² = x³ + 4 * (u+1) = x³ + b + let y = Fp2.sqrt(right); + const Y_bit = y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P ? _1n : _0n; + y = bitS > 0 && Y_bit > 0 ? y : Fp2.neg(y); + return { x, y }; + } else if (bytes.length === 192 && !bitC) { + // Check if the infinity flag is set + if ((bytes[0] & (1 << 6)) !== 0) { + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x1 = slc(bytes, 0, L); + const x0 = slc(bytes, L, 2 * L); + const y1 = slc(bytes, 2 * L, 3 * L); + const y0 = slc(bytes, 3 * L, 4 * L); + return { x: Fp2.fromBigTuple([x0, x1]), y: Fp2.fromBigTuple([y0, y1]) }; + } else { + throw new Error('Invalid point G2, expected 96/192 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const { BYTES: len, ORDER: P } = Fp; + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) return concatB(COMPRESSED_ZERO, numberToBytesBE(_0n, len)); + const flag = Boolean(y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P); + // set compressed & sign bits (looks like different offsets than for G1/Fp?) + let x_1 = bitSet(x.c1, C_BIT_POS, flag); + x_1 = bitSet(x_1, S_BIT_POS, true); + return concatB(numberToBytesBE(x_1, len), numberToBytesBE(x.c0, len)); + } else { + if (isZero) return concatB(new Uint8Array([0x40]), new Uint8Array(4 * len - 1)); // bytes[0] |= 1 << 6; + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + return concatB( + numberToBytesBE(x1, len), + numberToBytesBE(x0, len), + numberToBytesBE(y1, len), + numberToBytesBE(y0, len) + ); + } + }, + Signature: { + // TODO: Optimize, it's very slow because of sqrt. + fromHex(hex: Hex): ProjPointType { + hex = ensureBytes('signatureHex', hex); + const P = Fp.ORDER; + const half = hex.length / 2; + if (half !== 48 && half !== 96) + throw new Error('Invalid compressed signature length, must be 96 or 192'); + const z1 = bytesToNumberBE(hex.slice(0, half)); + const z2 = bytesToNumberBE(hex.slice(half)); + // Indicates the infinity point + const bflag1 = bitGet(z1, I_BIT_POS); + if (bflag1 === _1n) return bls12_381.G2.ProjectivePoint.ZERO; + + const x1 = Fp.create(z1 & Fp.MASK); + const x2 = Fp.create(z2); + const x = Fp2.create({ c0: x2, c1: x1 }); + const y2 = Fp2.add(Fp2.pow(x, _3n), bls12_381.params.G2b); // y² = x³ + 4 + // The slow part + let y = Fp2.sqrt(y2); + if (!y) throw new Error('Failed to find a square root'); + + // Choose the y whose leftmost bit of the imaginary part is equal to the a_flag1 + // If y1 happens to be zero, then use the bit of y0 + const { re: y0, im: y1 } = Fp2.reim(y); + const aflag1 = bitGet(z1, 381); + const isGreater = y1 > _0n && (y1 * _2n) / P !== aflag1; + const isZero = y1 === _0n && (y0 * _2n) / P !== aflag1; + if (isGreater || isZero) y = Fp2.neg(y); + const point = bls12_381.G2.ProjectivePoint.fromAffine({ x, y }); + point.assertValidity(); + return point; + }, + toRawBytes(point: ProjPointType) { + return signatureG2ToRawBytes(point); + }, + toHex(point: ProjPointType) { + return bytesToHex(signatureG2ToRawBytes(point)); + }, + }, + }, + params: { + x: BLS_X, // The BLS parameter x for BLS12-381 + r: Fr.ORDER, // order; z⁴ − z² + 1; CURVE.n from other curves + }, + htfDefaults, + hash: sha256, + randomBytes, +}); diff --git a/node_modules/@noble/curves/src/bn254.ts b/node_modules/@noble/curves/src/bn254.ts new file mode 100644 index 0000000..64ccfe0 --- /dev/null +++ b/node_modules/@noble/curves/src/bn254.ts @@ -0,0 +1,21 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { weierstrass } from './abstract/weierstrass.js'; +import { getHash } from './_shortw_utils.js'; +import { Field } from './abstract/modular.js'; +/** + * bn254 pairing-friendly curve. + * Previously known as alt_bn_128, when it had 128-bit security. + * Recent research shown it's weaker, the naming has been adjusted to its prime bit count. + * https://github.com/zcash/zcash/issues/2502 + */ +export const bn254 = weierstrass({ + a: BigInt(0), + b: BigInt(3), + Fp: Field(BigInt('0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47')), + n: BigInt('0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001'), + Gx: BigInt(1), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); diff --git a/node_modules/@noble/curves/src/ed25519.ts b/node_modules/@noble/curves/src/ed25519.ts new file mode 100644 index 0000000..896f4ee --- /dev/null +++ b/node_modules/@noble/curves/src/ed25519.ts @@ -0,0 +1,489 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha512 } from '@noble/hashes/sha512'; +import { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils'; +import { ExtPointType, twistedEdwards } from './abstract/edwards.js'; +import { montgomery } from './abstract/montgomery.js'; +import { Field, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.js'; +import { + bytesToHex, + bytesToNumberLE, + ensureBytes, + equalBytes, + Hex, + numberToBytesLE, +} from './abstract/utils.js'; +import { createHasher, htfBasicOpts, expand_message_xmd } from './abstract/hash-to-curve.js'; +import { AffinePoint } from './abstract/curve.js'; + +/** + * ed25519 Twisted Edwards curve with following addons: + * - X25519 ECDH + * - Ristretto cofactor elimination + * - Elligator hash-to-group / point indistinguishability + */ + +const ED25519_P = BigInt( + '57896044618658097711785492504343953926634992332820282019728792003956564819949' +); +// √(-1) aka √(a) aka 2^((p-1)/4) +const ED25519_SQRT_M1 = BigInt( + '19681161376707505956807079304988542015446066515923890162744021073123829784752' +); + +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _5n = BigInt(5); +// prettier-ignore +const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80); + +function ed25519_pow_2_252_3(x: bigint) { + const P = ED25519_P; + const x2 = (x * x) % P; + const b2 = (x2 * x) % P; // x^3, 11 + const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111 + const b5 = (pow2(b4, _1n, P) * x) % P; // x^31 + const b10 = (pow2(b5, _5n, P) * b5) % P; + const b20 = (pow2(b10, _10n, P) * b10) % P; + const b40 = (pow2(b20, _20n, P) * b20) % P; + const b80 = (pow2(b40, _40n, P) * b40) % P; + const b160 = (pow2(b80, _80n, P) * b80) % P; + const b240 = (pow2(b160, _80n, P) * b80) % P; + const b250 = (pow2(b240, _10n, P) * b10) % P; + const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P; + // ^ To pow to (p+3)/8, multiply it by x. + return { pow_p_5_8, b2 }; +} + +function adjustScalarBytes(bytes: Uint8Array): Uint8Array { + // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar, + // set the three least significant bits of the first byte + bytes[0] &= 248; // 0b1111_1000 + // and the most significant bit of the last to zero, + bytes[31] &= 127; // 0b0111_1111 + // set the second most significant bit of the last byte to 1 + bytes[31] |= 64; // 0b0100_0000 + return bytes; +} + +// sqrt(u/v) +function uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } { + const P = ED25519_P; + const v3 = mod(v * v * v, P); // v³ + const v7 = mod(v3 * v3 * v, P); // v⁷ + // (p+3)/8 and (p-5)/8 + const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8; + let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8 + const vx2 = mod(v * x * x, P); // vx² + const root1 = x; // First root candidate + const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate + const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root + const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4) + const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1) + if (useRoot1) x = root1; + if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time + if (isNegativeLE(x, P)) x = mod(-x, P); + return { isValid: useRoot1 || useRoot2, value: x }; +} + +// Just in case +export const ED25519_TORSION_SUBGROUP = [ + '0100000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', + '0000000000000000000000000000000000000000000000000000000000000080', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05', + 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85', + '0000000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa', +]; + +const Fp = Field(ED25519_P, undefined, true); + +const ed25519Defaults = { + // Param: a + a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster + // d is equal to -121665/121666 over finite field. + // Negative number is P - number, and division is invert(number, P) + d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'), + // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n + Fp, + // Subgroup order: how many points curve has + // 2n**252n + 27742317777372353535851937790883648493n; + n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'), + // Cofactor + h: BigInt(8), + // Base point (x, y) aka generator point + Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'), + Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'), + hash: sha512, + randomBytes, + adjustScalarBytes, + // dom2 + // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3. + // Constant-time, u/√v + uvRatio, +} as const; + +export const ed25519 = /* @__PURE__ */ twistedEdwards(ed25519Defaults); + +function ed25519_domain(data: Uint8Array, ctx: Uint8Array, phflag: boolean) { + if (ctx.length > 255) throw new Error('Context is too big'); + return concatBytes( + utf8ToBytes('SigEd25519 no Ed25519 collisions'), + new Uint8Array([phflag ? 1 : 0, ctx.length]), + ctx, + data + ); +} + +export const ed25519ctx = /* @__PURE__ */ twistedEdwards({ + ...ed25519Defaults, + domain: ed25519_domain, +}); +export const ed25519ph = /* @__PURE__ */ twistedEdwards({ + ...ed25519Defaults, + domain: ed25519_domain, + prehash: sha512, +}); + +export const x25519 = /* @__PURE__ */ (() => + montgomery({ + P: ED25519_P, + a: BigInt(486662), + montgomeryBits: 255, // n is 253 bits + nByteLength: 32, + Gu: BigInt(9), + powPminus2: (x: bigint): bigint => { + const P = ED25519_P; + // x^(p-2) aka x^(2^255-21) + const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x); + return mod(pow2(pow_p_5_8, BigInt(3), P) * b2, P); + }, + adjustScalarBytes, + randomBytes, + }))(); + +/** + * Converts ed25519 public key to x25519 public key. Uses formula: + * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)` + * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))` + * @example + * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey()); + * const aPriv = x25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub)) + */ +export function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array { + const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y))); +} +export const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated + +/** + * Converts ed25519 secret key to x25519 secret key. + * @example + * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey()); + * const aPriv = ed25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub) + */ +export function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array { + const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32)); + return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32); +} + +// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator) +// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since +// SageMath returns different root first and everything falls apart + +const ELL2_C1 = (Fp.ORDER + BigInt(3)) / BigInt(8); // 1. c1 = (q + 3) / 8 # Integer arithmetic + +const ELL2_C2 = Fp.pow(_2n, ELL2_C1); // 2. c2 = 2^c1 +const ELL2_C3 = Fp.sqrt(Fp.neg(Fp.ONE)); // 3. c3 = sqrt(-1) +const ELL2_C4 = (Fp.ORDER - BigInt(5)) / BigInt(8); // 4. c4 = (q - 5) / 8 # Integer arithmetic +const ELL2_J = BigInt(486662); + +// prettier-ignore +function map_to_curve_elligator2_curve25519(u: bigint) { + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1 + let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not + let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2) + let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2 + tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4 + tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3 + tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3 + tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7 + let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8) + y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8) + let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3 + tv2 = Fp.sqr(y11); // 19. tv2 = y11^2 + tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd + let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1 + let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt + let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd + let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u + y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2 + let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3 + let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1) + tv2 = Fp.sqr(y21); // 28. tv2 = y21^2 + tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2 + let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt + tv2 = Fp.sqr(y1); // 32. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd + let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2 + let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4) + return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1) +} + +const ELL2_C1_EDWARDS = FpSqrtEven(Fp, Fp.neg(BigInt(486664))); // sgn0(c1) MUST equal 0 +function map_to_curve_elligator2_edwards25519(u: bigint) { + const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) = + // map_to_curve_elligator2_curve25519(u) + let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd + xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1 + let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM + let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd + let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d) + let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd + let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0 + xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e) + xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e) + yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e) + yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e) + + const inv = Fp.invertBatch([xd, yd]); // batch division + return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd) +} + +const htf = /* @__PURE__ */ (() => + createHasher( + ed25519.ExtendedPoint, + (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]), + { + DST: 'edwards25519_XMD:SHA-512_ELL2_RO_', + encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha512, + } + ))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); + +function assertRstPoint(other: unknown) { + if (!(other instanceof RistPoint)) throw new Error('RistrettoPoint expected'); +} + +// √(-1) aka √(a) aka 2^((p-1)/4) +const SQRT_M1 = ED25519_SQRT_M1; +// √(ad - 1) +const SQRT_AD_MINUS_ONE = BigInt( + '25063068953384623474111414158702152701244531502492656460079210482610430750235' +); +// 1 / √(a-d) +const INVSQRT_A_MINUS_D = BigInt( + '54469307008909316920995813868745141605393597292927456921205312896311721017578' +); +// 1-d² +const ONE_MINUS_D_SQ = BigInt( + '1159843021668779879193775521855586647937357759715417654439879720876111806838' +); +// (d-1)² +const D_MINUS_ONE_SQ = BigInt( + '40440834346308536858101042469323190826248399146238708352240133220865137265952' +); +// Calculates 1/√(number) +const invertSqrt = (number: bigint) => uvRatio(_1n, number); + +const MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const bytes255ToNumberLE = (bytes: Uint8Array) => + ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B); + +type ExtendedPoint = ExtPointType; + +// Computes Elligator map for Ristretto +// https://ristretto.group/formulas/elligator.html +function calcElligatorRistrettoMap(r0: bigint): ExtendedPoint { + const { d } = ed25519.CURVE; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const r = mod(SQRT_M1 * r0 * r0); // 1 + const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2 + let c = BigInt(-1); // 3 + const D = mod((c - d * r) * mod(r + d)); // 4 + let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5 + let s_ = mod(s * r0); // 6 + if (!isNegativeLE(s_, P)) s_ = mod(-s_); + if (!Ns_D_is_sq) s = s_; // 7 + if (!Ns_D_is_sq) c = r; // 8 + const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9 + const s2 = s * s; + const W0 = mod((s + s) * D); // 10 + const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11 + const W2 = mod(_1n - s2); // 12 + const W3 = mod(_1n + s2); // 13 + return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2)); +} + +/** + * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Ristretto was created to solve this. + * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +class RistPoint { + static BASE: RistPoint; + static ZERO: RistPoint; + // Private property to discourage combining ExtendedPoint + RistrettoPoint + // Always use Ristretto encoding/decoding instead. + constructor(private readonly ep: ExtendedPoint) {} + + static fromAffine(ap: AffinePoint) { + return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap)); + } + + /** + * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://ristretto.group/formulas/elligator.html + * @param hex 64-byte output of a hash function + */ + static hashToCurve(hex: Hex): RistPoint { + hex = ensureBytes('ristrettoHash', hex, 64); + const r1 = bytes255ToNumberLE(hex.slice(0, 32)); + const R1 = calcElligatorRistrettoMap(r1); + const r2 = bytes255ToNumberLE(hex.slice(32, 64)); + const R2 = calcElligatorRistrettoMap(r2); + return new RistPoint(R1.add(R2)); + } + + /** + * Converts ristretto-encoded string to ristretto point. + * https://ristretto.group/formulas/decoding.html + * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding + */ + static fromHex(hex: Hex): RistPoint { + hex = ensureBytes('ristrettoHex', hex, 32); + const { a, d } = ed25519.CURVE; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint'; + const s = bytes255ToNumberLE(hex); + // 1. Check that s_bytes is the canonical encoding of a field element, or else abort. + // 3. Check that s is non-negative, or else abort + if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P)) throw new Error(emsg); + const s2 = mod(s * s); + const u1 = mod(_1n + a * s2); // 4 (a is -1) + const u2 = mod(_1n - a * s2); // 5 + const u1_2 = mod(u1 * u1); + const u2_2 = mod(u2 * u2); + const v = mod(a * d * u1_2 - u2_2); // 6 + const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7 + const Dx = mod(I * u2); // 8 + const Dy = mod(I * Dx * v); // 9 + let x = mod((s + s) * Dx); // 10 + if (isNegativeLE(x, P)) x = mod(-x); // 10 + const y = mod(u1 * Dy); // 11 + const t = mod(x * y); // 12 + if (!isValid || isNegativeLE(t, P) || y === _0n) throw new Error(emsg); + return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t)); + } + + /** + * Encodes ristretto point to Uint8Array. + * https://ristretto.group/formulas/encoding.html + */ + toRawBytes(): Uint8Array { + let { ex: x, ey: y, ez: z, et: t } = this.ep; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const u1 = mod(mod(z + y) * mod(z - y)); // 1 + const u2 = mod(x * y); // 2 + // Square root always exists + const u2sq = mod(u2 * u2); + const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3 + const D1 = mod(invsqrt * u1); // 4 + const D2 = mod(invsqrt * u2); // 5 + const zInv = mod(D1 * D2 * t); // 6 + let D: bigint; // 7 + if (isNegativeLE(t * zInv, P)) { + let _x = mod(y * SQRT_M1); + let _y = mod(x * SQRT_M1); + x = _x; + y = _y; + D = mod(D1 * INVSQRT_A_MINUS_D); + } else { + D = D2; // 8 + } + if (isNegativeLE(x * zInv, P)) y = mod(-y); // 9 + let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a)) + if (isNegativeLE(s, P)) s = mod(-s); + return numberToBytesLE(s, 32); // 11 + } + + toHex(): string { + return bytesToHex(this.toRawBytes()); + } + + toString(): string { + return this.toHex(); + } + + // Compare one point to another. + equals(other: RistPoint): boolean { + assertRstPoint(other); + const { ex: X1, ey: Y1 } = this.ep; + const { ex: X2, ey: Y2 } = other.ep; + const mod = ed25519.CURVE.Fp.create; + // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2) + const one = mod(X1 * Y2) === mod(Y1 * X2); + const two = mod(Y1 * Y2) === mod(X1 * X2); + return one || two; + } + + add(other: RistPoint): RistPoint { + assertRstPoint(other); + return new RistPoint(this.ep.add(other.ep)); + } + + subtract(other: RistPoint): RistPoint { + assertRstPoint(other); + return new RistPoint(this.ep.subtract(other.ep)); + } + + multiply(scalar: bigint): RistPoint { + return new RistPoint(this.ep.multiply(scalar)); + } + + multiplyUnsafe(scalar: bigint): RistPoint { + return new RistPoint(this.ep.multiplyUnsafe(scalar)); + } +} +export const RistrettoPoint = /* @__PURE__ */ (() => { + if (!RistPoint.BASE) RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE); + if (!RistPoint.ZERO) RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO); + return RistPoint; +})(); + +// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B +export const hashToRistretto255 = (msg: Uint8Array, options: htfBasicOpts) => { + const d = options.DST; + const DST = typeof d === 'string' ? utf8ToBytes(d) : d; + const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512); + const P = RistPoint.hashToCurve(uniform_bytes); + return P; +}; +export const hash_to_ristretto255 = hashToRistretto255; // legacy diff --git a/node_modules/@noble/curves/src/ed448.ts b/node_modules/@noble/curves/src/ed448.ts new file mode 100644 index 0000000..0e5477a --- /dev/null +++ b/node_modules/@noble/curves/src/ed448.ts @@ -0,0 +1,465 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { shake256 } from '@noble/hashes/sha3'; +import { concatBytes, randomBytes, utf8ToBytes, wrapConstructor } from '@noble/hashes/utils'; +import { ExtPointType, twistedEdwards } from './abstract/edwards.js'; +import { mod, pow2, Field, isNegativeLE } from './abstract/modular.js'; +import { montgomery } from './abstract/montgomery.js'; +import { createHasher, htfBasicOpts, expand_message_xof } from './abstract/hash-to-curve.js'; +import { + bytesToHex, + bytesToNumberLE, + ensureBytes, + equalBytes, + Hex, + numberToBytesLE, +} from './abstract/utils.js'; +import { AffinePoint } from './abstract/curve.js'; + +/** + * Edwards448 (not Ed448-Goldilocks) curve with following addons: + * - X448 ECDH + * - Decaf cofactor elimination + * - Elligator hash-to-group / point indistinguishability + * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2 + */ + +const shake256_114 = wrapConstructor(() => shake256.create({ dkLen: 114 })); +const shake256_64 = wrapConstructor(() => shake256.create({ dkLen: 64 })); +const ed448P = BigInt( + '726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439' +); + +// prettier-ignore +const _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4), _11n = BigInt(11); +// prettier-ignore +const _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223); + +// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4. +// Used for efficient square root calculation. +// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1] +function ed448_pow_Pminus3div4(x: bigint): bigint { + const P = ed448P; + const b2 = (x * x * x) % P; + const b3 = (b2 * b2 * x) % P; + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b222 = (pow2(b220, _2n, P) * b2) % P; + const b223 = (pow2(b222, _1n, P) * x) % P; + return (pow2(b223, _223n, P) * b222) % P; +} + +function adjustScalarBytes(bytes: Uint8Array): Uint8Array { + // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, and the most + // significant bit of the last byte to 1. + bytes[0] &= 252; // 0b11111100 + // and the most significant bit of the last byte to 1. + bytes[55] |= 128; // 0b10000000 + // NOTE: is is NOOP for 56 bytes scalars (X25519/X448) + bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits) + return bytes; +} + +// Constant-time ratio of u to v. Allows to combine inversion and square root u/√v. +// Uses algo from RFC8032 5.1.3. +function uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } { + const P = ed448P; + // https://www.rfc-editor.org/rfc/rfc8032#section-5.2.3 + // To compute the square root of (u/v), the first step is to compute the + // candidate root x = (u/v)^((p+1)/4). This can be done using the + // following trick, to use a single modular powering for both the + // inversion of v and the square root: + // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p) + const u2v = mod(u * u * v, P); // u²v + const u3v = mod(u2v * u, P); // u³v + const u5v3 = mod(u3v * u2v * v, P); // u⁵v³ + const root = ed448_pow_Pminus3div4(u5v3); + const x = mod(u3v * root, P); + // Verify that root is exists + const x2 = mod(x * x, P); // x² + // If vx² = u, the recovered x-coordinate is x. Otherwise, no + // square root exists, and the decoding fails. + return { isValid: mod(x2 * v, P) === u, value: x }; +} + +const Fp = Field(ed448P, 456, true); + +const ED448_DEF = { + // Param: a + a: BigInt(1), + // -39081. Negative number is P - number + d: BigInt( + '726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358' + ), + // Finite field 𝔽p over which we'll do calculations; 2n**448n - 2n**224n - 1n + Fp, + // Subgroup order: how many points curve has; + // 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n + n: BigInt( + '181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779' + ), + nBitLength: 456, + // Cofactor + h: BigInt(4), + // Base point (x, y) aka generator point + Gx: BigInt( + '224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710' + ), + Gy: BigInt( + '298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660' + ), + // SHAKE256(dom4(phflag,context)||x, 114) + hash: shake256_114, + randomBytes, + adjustScalarBytes, + // dom4 + domain: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => { + if (ctx.length > 255) throw new Error(`Context is too big: ${ctx.length}`); + return concatBytes( + utf8ToBytes('SigEd448'), + new Uint8Array([phflag ? 1 : 0, ctx.length]), + ctx, + data + ); + }, + uvRatio, +} as const; + +export const ed448 = /* @__PURE__ */ twistedEdwards(ED448_DEF); +// NOTE: there is no ed448ctx, since ed448 supports ctx by default +export const ed448ph = /* @__PURE__ */ twistedEdwards({ ...ED448_DEF, prehash: shake256_64 }); + +export const x448 = /* @__PURE__ */ (() => + montgomery({ + a: BigInt(156326), + montgomeryBits: 448, + nByteLength: 57, + P: ed448P, + Gu: BigInt(5), + powPminus2: (x: bigint): bigint => { + const P = ed448P; + const Pminus3div4 = ed448_pow_Pminus3div4(x); + const Pminus3 = pow2(Pminus3div4, BigInt(2), P); + return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2 + }, + adjustScalarBytes, + randomBytes, + }))(); + +/** + * Converts edwards448 public key to x448 public key. Uses formula: + * * `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)` + * * `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))` + * @example + * const aPub = ed448.getPublicKey(utils.randomPrivateKey()); + * x448.getSharedSecret(edwardsToMontgomery(aPub), edwardsToMontgomery(someonesPub)) + */ +export function edwardsToMontgomeryPub(edwardsPub: string | Uint8Array): Uint8Array { + const { y } = ed448.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((y - _1n) * Fp.inv(y + _1n))); +} +export const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated + +// Hash To Curve Elligator2 Map +const ELL2_C1 = (Fp.ORDER - BigInt(3)) / BigInt(4); // 1. c1 = (q - 3) / 4 # Integer arithmetic +const ELL2_J = BigInt(156326); +function map_to_curve_elligator2_curve448(u: bigint) { + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + let e1 = Fp.eql(tv1, Fp.ONE); // 2. e1 = tv1 == 1 + tv1 = Fp.cmov(tv1, Fp.ZERO, e1); // 3. tv1 = CMOV(tv1, 0, e1) # If Z * u^2 == -1, set tv1 = 0 + let xd = Fp.sub(Fp.ONE, tv1); // 4. xd = 1 - tv1 + let x1n = Fp.neg(ELL2_J); // 5. x1n = -J + let tv2 = Fp.sqr(xd); // 6. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 7. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, Fp.neg(ELL2_J)); // 8. gx1 = -J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 9. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 10. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 11. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 12. tv3 = gxd^2 + tv2 = Fp.mul(gx1, gxd); // 13. tv2 = gx1 * gxd # gx1 * gxd + tv3 = Fp.mul(tv3, tv2); // 14. tv3 = tv3 * tv2 # gx1 * gxd^3 + let y1 = Fp.pow(tv3, ELL2_C1); // 15. y1 = tv3^c1 # (gx1 * gxd^3)^((p - 3) / 4) + y1 = Fp.mul(y1, tv2); // 16. y1 = y1 * tv2 # gx1 * gxd * (gx1 * gxd^3)^((p - 3) / 4) + let x2n = Fp.mul(x1n, Fp.neg(tv1)); // 17. x2n = -tv1 * x1n # x2 = x2n / xd = -1 * u^2 * x1n / xd + let y2 = Fp.mul(y1, u); // 18. y2 = y1 * u + y2 = Fp.cmov(y2, Fp.ZERO, e1); // 19. y2 = CMOV(y2, 0, e1) + tv2 = Fp.sqr(y1); // 20. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 21. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx1); // 22. e2 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e2); // 23. xn = CMOV(x2n, x1n, e2) # If e2, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e2); // 24. y = CMOV(y2, y1, e2) # If e2, y = y1, else y = y2 + let e3 = Fp.isOdd(y); // 25. e3 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e2 !== e3); // 26. y = CMOV(y, -y, e2 XOR e3) + return { xn, xd, yn: y, yd: Fp.ONE }; // 27. return (xn, xd, y, 1) +} +function map_to_curve_elligator2_edwards448(u: bigint) { + let { xn, xd, yn, yd } = map_to_curve_elligator2_curve448(u); // 1. (xn, xd, yn, yd) = map_to_curve_elligator2_curve448(u) + let xn2 = Fp.sqr(xn); // 2. xn2 = xn^2 + let xd2 = Fp.sqr(xd); // 3. xd2 = xd^2 + let xd4 = Fp.sqr(xd2); // 4. xd4 = xd2^2 + let yn2 = Fp.sqr(yn); // 5. yn2 = yn^2 + let yd2 = Fp.sqr(yd); // 6. yd2 = yd^2 + let xEn = Fp.sub(xn2, xd2); // 7. xEn = xn2 - xd2 + let tv2 = Fp.sub(xEn, xd2); // 8. tv2 = xEn - xd2 + xEn = Fp.mul(xEn, xd2); // 9. xEn = xEn * xd2 + xEn = Fp.mul(xEn, yd); // 10. xEn = xEn * yd + xEn = Fp.mul(xEn, yn); // 11. xEn = xEn * yn + xEn = Fp.mul(xEn, _4n); // 12. xEn = xEn * 4 + tv2 = Fp.mul(tv2, xn2); // 13. tv2 = tv2 * xn2 + tv2 = Fp.mul(tv2, yd2); // 14. tv2 = tv2 * yd2 + let tv3 = Fp.mul(yn2, _4n); // 15. tv3 = 4 * yn2 + let tv1 = Fp.add(tv3, yd2); // 16. tv1 = tv3 + yd2 + tv1 = Fp.mul(tv1, xd4); // 17. tv1 = tv1 * xd4 + let xEd = Fp.add(tv1, tv2); // 18. xEd = tv1 + tv2 + tv2 = Fp.mul(tv2, xn); // 19. tv2 = tv2 * xn + let tv4 = Fp.mul(xn, xd4); // 20. tv4 = xn * xd4 + let yEn = Fp.sub(tv3, yd2); // 21. yEn = tv3 - yd2 + yEn = Fp.mul(yEn, tv4); // 22. yEn = yEn * tv4 + yEn = Fp.sub(yEn, tv2); // 23. yEn = yEn - tv2 + tv1 = Fp.add(xn2, xd2); // 24. tv1 = xn2 + xd2 + tv1 = Fp.mul(tv1, xd2); // 25. tv1 = tv1 * xd2 + tv1 = Fp.mul(tv1, xd); // 26. tv1 = tv1 * xd + tv1 = Fp.mul(tv1, yn2); // 27. tv1 = tv1 * yn2 + tv1 = Fp.mul(tv1, BigInt(-2)); // 28. tv1 = -2 * tv1 + let yEd = Fp.add(tv2, tv1); // 29. yEd = tv2 + tv1 + tv4 = Fp.mul(tv4, yd2); // 30. tv4 = tv4 * yd2 + yEd = Fp.add(yEd, tv4); // 31. yEd = yEd + tv4 + tv1 = Fp.mul(xEd, yEd); // 32. tv1 = xEd * yEd + let e = Fp.eql(tv1, Fp.ZERO); // 33. e = tv1 == 0 + xEn = Fp.cmov(xEn, Fp.ZERO, e); // 34. xEn = CMOV(xEn, 0, e) + xEd = Fp.cmov(xEd, Fp.ONE, e); // 35. xEd = CMOV(xEd, 1, e) + yEn = Fp.cmov(yEn, Fp.ONE, e); // 36. yEn = CMOV(yEn, 1, e) + yEd = Fp.cmov(yEd, Fp.ONE, e); // 37. yEd = CMOV(yEd, 1, e) + + const inv = Fp.invertBatch([xEd, yEd]); // batch division + return { x: Fp.mul(xEn, inv[0]), y: Fp.mul(yEn, inv[1]) }; // 38. return (xEn, xEd, yEn, yEd) +} + +const htf = /* @__PURE__ */ (() => + createHasher( + ed448.ExtendedPoint, + (scalars: bigint[]) => map_to_curve_elligator2_edwards448(scalars[0]), + { + DST: 'edwards448_XOF:SHAKE256_ELL2_RO_', + encodeDST: 'edwards448_XOF:SHAKE256_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 224, + expand: 'xof', + hash: shake256, + } + ))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); + +function assertDcfPoint(other: unknown) { + if (!(other instanceof DcfPoint)) throw new Error('DecafPoint expected'); +} + +// 1-d +const ONE_MINUS_D = BigInt('39082'); +// 1-2d +const ONE_MINUS_TWO_D = BigInt('78163'); +// √(-d) +const SQRT_MINUS_D = BigInt( + '98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214' +); +// 1 / √(-d) +const INVSQRT_MINUS_D = BigInt( + '315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716' +); +// Calculates 1/√(number) +const invertSqrt = (number: bigint) => uvRatio(_1n, number); + +const MAX_448B = BigInt( + '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff' +); +const bytes448ToNumberLE = (bytes: Uint8Array) => + ed448.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_448B); + +type ExtendedPoint = ExtPointType; + +// Computes Elligator map for Decaf +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2 +function calcElligatorDecafMap(r0: bigint): ExtendedPoint { + const { d } = ed448.CURVE; + const P = ed448.CURVE.Fp.ORDER; + const mod = ed448.CURVE.Fp.create; + + const r = mod(-(r0 * r0)); // 1 + const u0 = mod(d * (r - _1n)); // 2 + const u1 = mod((u0 + _1n) * (u0 - r)); // 3 + + const { isValid: was_square, value: v } = uvRatio(ONE_MINUS_TWO_D, mod((r + _1n) * u1)); // 4 + + let v_prime = v; // 5 + if (!was_square) v_prime = mod(r0 * v); + + let sgn = _1n; // 6 + if (!was_square) sgn = mod(-_1n); + + const s = mod(v_prime * (r + _1n)); // 7 + let s_abs = s; + if (isNegativeLE(s, P)) s_abs = mod(-s); + + const s2 = s * s; + const W0 = mod(s_abs * _2n); // 8 + const W1 = mod(s2 + _1n); // 9 + const W2 = mod(s2 - _1n); // 10 + const W3 = mod(v_prime * s * (r - _1n) * ONE_MINUS_TWO_D + sgn); // 11 + return new ed448.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2)); +} + +/** + * Each ed448/ExtendedPoint has 4 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Decaf was created to solve this. + * Decaf point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +class DcfPoint { + static BASE: DcfPoint; + static ZERO: DcfPoint; + // Private property to discourage combining ExtendedPoint + DecafPoint + // Always use Decaf encoding/decoding instead. + constructor(private readonly ep: ExtendedPoint) {} + + static fromAffine(ap: AffinePoint) { + return new DcfPoint(ed448.ExtendedPoint.fromAffine(ap)); + } + + /** + * Takes uniform output of 112-byte hash function like shake256 and converts it to `DecafPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2 + * @param hex 112-byte output of a hash function + */ + static hashToCurve(hex: Hex): DcfPoint { + hex = ensureBytes('decafHash', hex, 112); + const r1 = bytes448ToNumberLE(hex.slice(0, 56)); + const R1 = calcElligatorDecafMap(r1); + const r2 = bytes448ToNumberLE(hex.slice(56, 112)); + const R2 = calcElligatorDecafMap(r2); + return new DcfPoint(R1.add(R2)); + } + + /** + * Converts decaf-encoded string to decaf point. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-decode-2 + * @param hex Decaf-encoded 56 bytes. Not every 56-byte string is valid decaf encoding + */ + static fromHex(hex: Hex): DcfPoint { + hex = ensureBytes('decafHex', hex, 56); + const { d } = ed448.CURVE; + const P = ed448.CURVE.Fp.ORDER; + const mod = ed448.CURVE.Fp.create; + const emsg = 'DecafPoint.fromHex: the hex is not valid encoding of DecafPoint'; + const s = bytes448ToNumberLE(hex); + + // 1. Check that s_bytes is the canonical encoding of a field element, or else abort. + // 2. Check that s is non-negative, or else abort + if (!equalBytes(numberToBytesLE(s, 56), hex) || isNegativeLE(s, P)) throw new Error(emsg); + + const s2 = mod(s * s); // 1 + const u1 = mod(_1n + s2); // 2 + const u1sq = mod(u1 * u1); + const u2 = mod(u1sq - _4n * d * s2); // 3 + + const { isValid, value: invsqrt } = invertSqrt(mod(u2 * u1sq)); // 4 + + let u3 = mod((s + s) * invsqrt * u1 * SQRT_MINUS_D); // 5 + if (isNegativeLE(u3, P)) u3 = mod(-u3); + + const x = mod(u3 * invsqrt * u2 * INVSQRT_MINUS_D); // 6 + const y = mod((_1n - s2) * invsqrt * u1); // 7 + const t = mod(x * y); // 8 + + if (!isValid) throw new Error(emsg); + return new DcfPoint(new ed448.ExtendedPoint(x, y, _1n, t)); + } + + /** + * Encodes decaf point to Uint8Array. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-encode-2 + */ + toRawBytes(): Uint8Array { + let { ex: x, ey: _y, ez: z, et: t } = this.ep; + const P = ed448.CURVE.Fp.ORDER; + const mod = ed448.CURVE.Fp.create; + + const u1 = mod(mod(x + t) * mod(x - t)); // 1 + const x2 = mod(x * x); + const { value: invsqrt } = invertSqrt(mod(u1 * ONE_MINUS_D * x2)); // 2 + + let ratio = mod(invsqrt * u1 * SQRT_MINUS_D); // 3 + if (isNegativeLE(ratio, P)) ratio = mod(-ratio); + + const u2 = mod(INVSQRT_MINUS_D * ratio * z - t); // 4 + + let s = mod(ONE_MINUS_D * invsqrt * x * u2); // 5 + if (isNegativeLE(s, P)) s = mod(-s); + + return numberToBytesLE(s, 56); + } + + toHex(): string { + return bytesToHex(this.toRawBytes()); + } + + toString(): string { + return this.toHex(); + } + + // Compare one point to another. + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-equals-2 + equals(other: DcfPoint): boolean { + assertDcfPoint(other); + const { ex: X1, ey: Y1 } = this.ep; + const { ex: X2, ey: Y2 } = other.ep; + const mod = ed448.CURVE.Fp.create; + // (x1 * y2 == y1 * x2) + return mod(X1 * Y2) === mod(Y1 * X2); + } + + add(other: DcfPoint): DcfPoint { + assertDcfPoint(other); + return new DcfPoint(this.ep.add(other.ep)); + } + + subtract(other: DcfPoint): DcfPoint { + assertDcfPoint(other); + return new DcfPoint(this.ep.subtract(other.ep)); + } + + multiply(scalar: bigint): DcfPoint { + return new DcfPoint(this.ep.multiply(scalar)); + } + + multiplyUnsafe(scalar: bigint): DcfPoint { + return new DcfPoint(this.ep.multiplyUnsafe(scalar)); + } +} +export const DecafPoint = /* @__PURE__ */ (() => { + // decaf448 base point is ed448 base x 2 + // https://github.com/dalek-cryptography/curve25519-dalek/blob/59837c6ecff02b77b9d5ff84dbc239d0cf33ef90/vendor/ristretto.sage#L699 + if (!DcfPoint.BASE) DcfPoint.BASE = new DcfPoint(ed448.ExtendedPoint.BASE).multiply(_2n); + if (!DcfPoint.ZERO) DcfPoint.ZERO = new DcfPoint(ed448.ExtendedPoint.ZERO); + return DcfPoint; +})(); + +// Hashing to decaf448. https://www.rfc-editor.org/rfc/rfc9380#appendix-C +export const hashToDecaf448 = (msg: Uint8Array, options: htfBasicOpts) => { + const d = options.DST; + const DST = typeof d === 'string' ? utf8ToBytes(d) : d; + const uniform_bytes = expand_message_xof(msg, DST, 112, 224, shake256); + const P = DcfPoint.hashToCurve(uniform_bytes); + return P; +}; +export const hash_to_decaf448 = hashToDecaf448; // legacy diff --git a/node_modules/@noble/curves/src/index.ts b/node_modules/@noble/curves/src/index.ts new file mode 100644 index 0000000..0ffab52 --- /dev/null +++ b/node_modules/@noble/curves/src/index.ts @@ -0,0 +1 @@ +throw new Error('Incorrect usage. Import submodules instead'); diff --git a/node_modules/@noble/curves/src/jubjub.ts b/node_modules/@noble/curves/src/jubjub.ts new file mode 100644 index 0000000..a600d3a --- /dev/null +++ b/node_modules/@noble/curves/src/jubjub.ts @@ -0,0 +1,58 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha512 } from '@noble/hashes/sha512'; +import { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils'; +import { twistedEdwards } from './abstract/edwards.js'; +import { blake2s } from '@noble/hashes/blake2s'; +import { Field } from './abstract/modular.js'; + +/** + * jubjub Twisted Edwards curve. + * https://neuromancer.sk/std/other/JubJub + * jubjub does not use EdDSA, so `hash`/sha512 params are passed because interface expects them. + */ + +export const jubjub = /* @__PURE__ */ twistedEdwards({ + // Params: a, d + a: BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000'), + d: BigInt('0x2a9318e74bfa2b48f5fd9207e6bd7fd4292d7f6d37579d2601065fd6d6343eb1'), + // Finite field 𝔽p over which we'll do calculations + // Same value as bls12-381 Fr (not Fp) + Fp: Field(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')), + // Subgroup order: how many points curve has + n: BigInt('0xe7db4ea6533afa906673b0101343b00a6682093ccc81082d0970e5ed6f72cb7'), + // Cofactor + h: BigInt(8), + // Base point (x, y) aka generator point + Gx: BigInt('0x11dafe5d23e1218086a365b99fbf3d3be72f6afd7d1f72623e6b071492d1122b'), + Gy: BigInt('0x1d523cf1ddab1a1793132e78c866c0c33e26ba5cc220fed7cc3f870e59d292aa'), + hash: sha512, + randomBytes, +} as const); + +const GH_FIRST_BLOCK = utf8ToBytes( + '096b36a5804bfacef1691e173c366a47ff5ba84a44f26ddd7e8d9f79d5b42df0' +); + +// Returns point at JubJub curve which is prime order and not zero +export function groupHash(tag: Uint8Array, personalization: Uint8Array) { + const h = blake2s.create({ personalization, dkLen: 32 }); + h.update(GH_FIRST_BLOCK); + h.update(tag); + // NOTE: returns ExtendedPoint, in case it will be multiplied later + let p = jubjub.ExtendedPoint.fromHex(h.digest()); + // NOTE: cannot replace with isSmallOrder, returns Point*8 + p = p.multiply(jubjub.CURVE.h); + if (p.equals(jubjub.ExtendedPoint.ZERO)) throw new Error('Point has small order'); + return p; +} + +export function findGroupHash(m: Uint8Array, personalization: Uint8Array) { + const tag = concatBytes(m, new Uint8Array([0])); + for (let i = 0; i < 256; i++) { + tag[tag.length - 1] = i; + try { + return groupHash(tag, personalization); + } catch (e) {} + } + throw new Error('findGroupHash tag overflow'); +} diff --git a/node_modules/@noble/curves/src/p256.ts b/node_modules/@noble/curves/src/p256.ts new file mode 100644 index 0000000..164c470 --- /dev/null +++ b/node_modules/@noble/curves/src/p256.ts @@ -0,0 +1,48 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { createCurve } from './_shortw_utils.js'; +import { sha256 } from '@noble/hashes/sha256'; +import { Field } from './abstract/modular.js'; +import { mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import { createHasher } from './abstract/hash-to-curve.js'; + +// NIST secp256r1 aka p256 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256 + +const Fp = Field(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff')); +const CURVE_A = Fp.create(BigInt('-3')); +const CURVE_B = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'); + +// prettier-ignore +export const p256 = createCurve({ + a: CURVE_A, // Equation params: a, b + b: CURVE_B, + Fp, // Field: 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n + // Curve order, total count of valid points in the field + n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'), + // Base (generator) point (x, y) + Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'), + Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'), + h: BigInt(1), + lowS: false, +} as const, sha256); +export const secp256r1 = p256; + +const mapSWU = /* @__PURE__ */ (() => + mapToCurveSimpleSWU(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-10')), + }))(); + +const htf = /* @__PURE__ */ (() => + createHasher(secp256r1.ProjectivePoint, (scalars: bigint[]) => mapSWU(scalars[0]), { + DST: 'P256_XMD:SHA-256_SSWU_RO_', + encodeDST: 'P256_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256, + }))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); diff --git a/node_modules/@noble/curves/src/p384.ts b/node_modules/@noble/curves/src/p384.ts new file mode 100644 index 0000000..436de9b --- /dev/null +++ b/node_modules/@noble/curves/src/p384.ts @@ -0,0 +1,52 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { createCurve } from './_shortw_utils.js'; +import { sha384 } from '@noble/hashes/sha512'; +import { Field } from './abstract/modular.js'; +import { mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import { createHasher } from './abstract/hash-to-curve.js'; + +// NIST secp384r1 aka p384 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-384 + +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'); +const Fp = Field(P); +const CURVE_A = Fp.create(BigInt('-3')); +// prettier-ignore +const CURVE_B = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'); + +// prettier-ignore +export const p384 = createCurve({ + a: CURVE_A, // Equation params: a, b + b: CURVE_B, + Fp, // Field: 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n + // Curve order, total count of valid points in the field. + n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'), + // Base (generator) point (x, y) + Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'), + Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'), + h: BigInt(1), + lowS: false, +} as const, sha384); +export const secp384r1 = p384; + +const mapSWU = /* @__PURE__ */ (() => + mapToCurveSimpleSWU(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-12')), + }))(); + +const htf = /* @__PURE__ */ (() => + createHasher(secp384r1.ProjectivePoint, (scalars: bigint[]) => mapSWU(scalars[0]), { + DST: 'P384_XMD:SHA-384_SSWU_RO_', + encodeDST: 'P384_XMD:SHA-384_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 192, + expand: 'xmd', + hash: sha384, + }))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); diff --git a/node_modules/@noble/curves/src/p521.ts b/node_modules/@noble/curves/src/p521.ts new file mode 100644 index 0000000..cc9fbbc --- /dev/null +++ b/node_modules/@noble/curves/src/p521.ts @@ -0,0 +1,68 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { createCurve } from './_shortw_utils.js'; +import { sha512 } from '@noble/hashes/sha512'; +import { Field } from './abstract/modular.js'; +import { mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import { createHasher } from './abstract/hash-to-curve.js'; + +// NIST secp521r1 aka p521 +// Note that it's 521, which differs from 512 of its hash function. +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-521 + +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const Fp = Field(P); + +const CURVE = { + a: Fp.create(BigInt('-3')), + b: BigInt( + '0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00' + ), + Fp, + n: BigInt( + '0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409' + ), + Gx: BigInt( + '0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66' + ), + Gy: BigInt( + '0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650' + ), + h: BigInt(1), +}; + +// prettier-ignore +export const p521 = createCurve({ + a: CURVE.a, // Equation params: a, b + b: CURVE.b, + Fp, // Field: 2n**521n - 1n + // Curve order, total count of valid points in the field + n: CURVE.n, + Gx: CURVE.Gx, // Base point (x, y) aka generator point + Gy: CURVE.Gy, + h: CURVE.h, + lowS: false, + allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b +} as const, sha512); +export const secp521r1 = p521; + +const mapSWU = /* @__PURE__ */ (() => + mapToCurveSimpleSWU(Fp, { + A: CURVE.a, + B: CURVE.b, + Z: Fp.create(BigInt('-4')), + }))(); + +const htf = /* @__PURE__ */ (() => + createHasher(secp521r1.ProjectivePoint, (scalars: bigint[]) => mapSWU(scalars[0]), { + DST: 'P521_XMD:SHA-512_SSWU_RO_', + encodeDST: 'P521_XMD:SHA-512_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 256, + expand: 'xmd', + hash: sha512, + }))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); diff --git a/node_modules/@noble/curves/src/pasta.ts b/node_modules/@noble/curves/src/pasta.ts new file mode 100644 index 0000000..faed89e --- /dev/null +++ b/node_modules/@noble/curves/src/pasta.ts @@ -0,0 +1,31 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { weierstrass } from './abstract/weierstrass.js'; +import { getHash } from './_shortw_utils.js'; +import * as mod from './abstract/modular.js'; + +export const p = BigInt('0x40000000000000000000000000000000224698fc094cf91b992d30ed00000001'); +export const q = BigInt('0x40000000000000000000000000000000224698fc0994a8dd8c46eb2100000001'); + +// https://neuromancer.sk/std/other/Pallas +export const pallas = weierstrass({ + a: BigInt(0), + b: BigInt(5), + Fp: mod.Field(p), + n: q, + Gx: mod.mod(BigInt(-1), p), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); +// https://neuromancer.sk/std/other/Vesta +export const vesta = weierstrass({ + a: BigInt(0), + b: BigInt(5), + Fp: mod.Field(q), + n: p, + Gx: mod.mod(BigInt(-1), q), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); diff --git a/node_modules/@noble/curves/src/secp256k1.ts b/node_modules/@noble/curves/src/secp256k1.ts new file mode 100644 index 0000000..7119222 --- /dev/null +++ b/node_modules/@noble/curves/src/secp256k1.ts @@ -0,0 +1,274 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { randomBytes } from '@noble/hashes/utils'; +import { Field, mod, pow2 } from './abstract/modular.js'; +import { ProjPointType as PointType, mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import type { Hex, PrivKey } from './abstract/utils.js'; +import { bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE } from './abstract/utils.js'; +import { createHasher, isogenyMap } from './abstract/hash-to-curve.js'; +import { createCurve } from './_shortw_utils.js'; + +const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'); +const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); +const _1n = BigInt(1); +const _2n = BigInt(2); +const divNearest = (a: bigint, b: bigint) => (a + b / _2n) / b; + +/** + * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit. + * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00] + */ +function sqrtMod(y: bigint): bigint { + const P = secp256k1P; + // prettier-ignore + const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + // prettier-ignore + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = (y * y * y) % P; // x^3, 11 + const b3 = (b2 * b2 * y) % P; // x^7 + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b223 = (pow2(b220, _3n, P) * b3) % P; + const t1 = (pow2(b223, _23n, P) * b22) % P; + const t2 = (pow2(t1, _6n, P) * b2) % P; + const root = pow2(t2, _2n, P); + if (!Fp.eql(Fp.sqr(root), y)) throw new Error('Cannot find square root'); + return root; +} + +const Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod }); + +export const secp256k1 = createCurve( + { + a: BigInt(0), // equation params: a, b + b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975 + Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n + n: secp256k1N, // Curve order, total count of valid points in the field + // Base point (x, y) aka generator point + Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), + Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), + h: BigInt(1), // Cofactor + lowS: true, // Allow only low-S signatures by default in sign() and verify() + /** + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 + */ + endo: { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + splitScalar: (k: bigint) => { + const n = secp256k1N; + const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); + const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); + const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); + const b2 = a1; + const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16) + + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = mod(k - c1 * a1 - c2 * a2, n); + let k2 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) k1 = n - k1; + if (k2neg) k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error('splitScalar: Endomorphism failed, k=' + k); + } + return { k1neg, k1, k2neg, k2 }; + }, + }, + }, + sha256 +); + +// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code. +// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki +const _0n = BigInt(0); +const fe = (x: bigint) => typeof x === 'bigint' && _0n < x && x < secp256k1P; +const ge = (x: bigint) => typeof x === 'bigint' && _0n < x && x < secp256k1N; +/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */ +const TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {}; +function taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array { + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === undefined) { + const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + tagP = concatBytes(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return sha256(concatBytes(tagP, ...messages)); +} + +// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03 +const pointToBytes = (point: PointType) => point.toRawBytes(true).slice(1); +const numTo32b = (n: bigint) => numberToBytesBE(n, 32); +const modP = (x: bigint) => mod(x, secp256k1P); +const modN = (x: bigint) => mod(x, secp256k1N); +const Point = secp256k1.ProjectivePoint; +const GmulAdd = (Q: PointType, a: bigint, b: bigint) => + Point.BASE.multiplyAndAddUnsafe(Q, a, b); + +// Calculate point, scalar and bytes +function schnorrGetExtPubKey(priv: PrivKey) { + let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey + let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside + const scalar = p.hasEvenY() ? d_ : modN(-d_); + return { scalar: scalar, bytes: pointToBytes(p) }; +} +/** + * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point. + * @returns valid point checked for being on-curve + */ +function lift_x(x: bigint): PointType { + if (!fe(x)) throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p. + const xx = modP(x * x); + const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p. + let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p. + if (y % _2n !== _0n) y = modP(-y); // Return the unique point P such that x(P) = x and + const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise. + p.assertValidity(); + return p; +} +/** + * Create tagged hash, convert it to bigint, reduce modulo-n. + */ +function challenge(...args: Uint8Array[]): bigint { + return modN(bytesToNumberBE(taggedHash('BIP0340/challenge', ...args))); +} + +/** + * Schnorr public key is just `x` coordinate of Point as per BIP340. + */ +function schnorrGetPublicKey(privateKey: Hex): Uint8Array { + return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G) +} + +/** + * Creates Schnorr signature as per BIP340. Verifies itself before returning anything. + * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous. + */ +function schnorrSign( + message: Hex, + privateKey: PrivKey, + auxRand: Hex = randomBytes(32) +): Uint8Array { + const m = ensureBytes('message', message); + const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder + const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array + const t = numTo32b(d ^ bytesToNumberBE(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a) + const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m) + const k_ = modN(bytesToNumberBE(rand)); // Let k' = int(rand) mod n + if (k_ === _0n) throw new Error('sign failed: k is zero'); // Fail if k' = 0. + const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G. + const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n. + const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n). + sig.set(rx, 0); + sig.set(numTo32b(modN(k + e * d)), 32); + // If Verify(bytes(P), m, sig) (see below) returns failure, abort + if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced'); + return sig; +} + +/** + * Verifies Schnorr signature. + * Will swallow errors & return false except for initial type validation of arguments. + */ +function schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean { + const sig = ensureBytes('signature', signature, 64); + const m = ensureBytes('message', message); + const pub = ensureBytes('publicKey', publicKey, 32); + try { + const P = lift_x(bytesToNumberBE(pub)); // P = lift_x(int(pk)); fail if that fails + const r = bytesToNumberBE(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p. + if (!fe(r)) return false; + const s = bytesToNumberBE(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n. + if (!ge(s)) return false; + const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n + const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P + if (!R || !R.hasEvenY() || R.toAffine().x !== r) return false; // -eP == (n-e)P + return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r. + } catch (error) { + return false; + } +} + +export const schnorr = /* @__PURE__ */ (() => ({ + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + utils: { + randomPrivateKey: secp256k1.utils.randomPrivateKey, + lift_x, + pointToBytes, + numberToBytesBE, + bytesToNumberBE, + taggedHash, + mod, + }, +}))(); + +const isoMap = /* @__PURE__ */ (() => + isogenyMap( + Fp, + [ + // xNum + [ + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7', + '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581', + '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262', + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c', + ], + // xDen + [ + '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b', + '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c', + '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3', + '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931', + '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84', + ], + // yDen + [ + '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b', + '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573', + '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + ].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]] + ))(); +const mapSWU = /* @__PURE__ */ (() => + mapToCurveSimpleSWU(Fp, { + A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'), + B: BigInt('1771'), + Z: Fp.create(BigInt('-11')), + }))(); +const htf = /* @__PURE__ */ (() => + createHasher( + secp256k1.ProjectivePoint, + (scalars: bigint[]) => { + const { x, y } = mapSWU(Fp.create(scalars[0])); + return isoMap(x, y); + }, + { + DST: 'secp256k1_XMD:SHA-256_SSWU_RO_', + encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256, + } + ))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); diff --git a/node_modules/@noble/hashes/LICENSE b/node_modules/@noble/hashes/LICENSE new file mode 100644 index 0000000..9297a04 --- /dev/null +++ b/node_modules/@noble/hashes/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/@noble/hashes/README.md b/node_modules/@noble/hashes/README.md new file mode 100644 index 0000000..83f6dd8 --- /dev/null +++ b/node_modules/@noble/hashes/README.md @@ -0,0 +1,536 @@ +# noble-hashes + +Audited & minimal JS implementation of SHA2, SHA3, RIPEMD, BLAKE2/3, HMAC, HKDF, PBKDF2 & Scrypt. + +- 🔒 [**Audited**](#security) by an independent security firm +- 🔻 Tree-shaking-friendly: use only what's necessary, other code won't be included +- 🏎 Ultra-fast, hand-optimized for caveats of JS engines +- 🔍 Unique tests ensure correctness: chained tests, sliding window tests, DoS tests, fuzzing +- 🔁 No unrolled loops: makes it easier to verify and reduces source code size up to 5x +- 🐢 Scrypt supports `N: 2**22`, while other implementations are limited to `2**20` +- 🦘 SHA3 supports Keccak, TupleHash, KangarooTwelve and MarsupilamiFourteen +- 🪶 Just 3.4k lines / 17KB gzipped. SHA256-only is 240 lines / 3KB gzipped + +The library's initial development was funded by [Ethereum Foundation](https://ethereum.org/). + +### This library belongs to _noble_ crypto + +> **noble-crypto** — high-security, easily auditable set of contained cryptographic libraries and tools. + +- No dependencies, protection against supply chain attacks +- Auditable TypeScript / JS code +- Supported in all major browsers and stable node.js versions +- All releases are signed with PGP keys +- Check out [homepage](https://paulmillr.com/noble/) & all libraries: + [curves](https://github.com/paulmillr/noble-curves) + (4kb versions [secp256k1](https://github.com/paulmillr/noble-secp256k1), + [ed25519](https://github.com/paulmillr/noble-ed25519)), + [hashes](https://github.com/paulmillr/noble-hashes) + +## Usage + +> npm install @noble/hashes + +We support all major platforms and runtimes. +For [Deno](https://deno.land), ensure to use [npm specifier](https://deno.land/manual@v1.28.0/node/npm_specifiers). +For React Native, you may need a [polyfill for getRandomValues](https://github.com/LinusU/react-native-get-random-values). +If you don't like NPM, a standalone [noble-hashes.js](https://github.com/paulmillr/noble-hashes/releases) is also available. + +The library is tree-shaking-friendly and does not expose root entry point as +`@noble/hashes`. Instead, you need to import specific primitives. +This is done to ensure small size of your apps. + +```js +import { sha256 } from '@noble/hashes/sha256'; // ECMAScript modules (ESM) and Common.js +// import { sha256 } from 'npm:@noble/hashes@1.3.0/sha256'; // Deno +console.log(sha256(new Uint8Array([1, 2, 3]))); // Uint8Array(32) [3, 144, 88, 198, 242...] +// you could also pass strings that will be UTF8-encoded to Uint8Array +console.log(sha256('abc')); // == sha256(new TextEncoder().encode('abc')) + +// sha384 is here, because it uses same internals as sha512 +import { sha512, sha512_256, sha384 } from '@noble/hashes/sha512'; +// prettier-ignore +import { + sha3_224, sha3_256, sha3_384, sha3_512, + keccak_224, keccak_256, keccak_384, keccak_512, + shake128, shake256 +} from '@noble/hashes/sha3'; +// prettier-ignore +import { + cshake128, cshake256, kmac128, kmac256, + k12, m14, + tuplehash256, parallelhash256, keccakprg +} from '@noble/hashes/sha3-addons'; +import { ripemd160 } from '@noble/hashes/ripemd160'; +import { blake3 } from '@noble/hashes/blake3'; +import { blake2b } from '@noble/hashes/blake2b'; +import { blake2s } from '@noble/hashes/blake2s'; +import { hmac } from '@noble/hashes/hmac'; +import { hkdf } from '@noble/hashes/hkdf'; +import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2'; +import { scrypt, scryptAsync } from '@noble/hashes/scrypt'; + +import { sha1 } from '@noble/hashes/sha1'; // legacy + +// small utility method that converts bytes to hex +import { bytesToHex as toHex } from '@noble/hashes/utils'; +console.log(toHex(sha256('abc'))); // ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad +``` + +## API + +All hash functions: + +- can be called directly, with `Uint8Array`. +- return `Uint8Array` +- can receive `string`, which is automatically converted to `Uint8Array` + via utf8 encoding **(not hex)** +- support hashing 4GB of data per update on 64-bit systems (unlimited with streaming) + +```ts +function hash(message: Uint8Array | string): Uint8Array; +hash(new Uint8Array([1, 3])); +hash('string') == hash(new TextEncoder().encode('string')); +``` + +All hash functions can be constructed via `hash.create()` method: + +- the result is `Hash` subclass instance, which has `update()` and `digest()` methods +- `digest()` finalizes the hash and makes it no longer usable + +```ts +hash + .create() + .update(new Uint8Array([1, 3])) + .digest(); +``` + +_Some_ hash functions can also receive `options` object, which can be either passed as a: + +- second argument to hash function: `blake3('abc', { key: 'd', dkLen: 32 })` +- first argument to class initializer: `blake3.create({ context: 'e', dkLen: 32 })` + +## Modules + +- [SHA2 (sha256, sha384, sha512, sha512_256)](#sha2-sha256-sha384-sha512-sha512_256) +- [SHA3 (FIPS, SHAKE, Keccak)](#sha3-fips-shake-keccak) +- [SHA3 Addons (cSHAKE, KMAC, KangarooTwelve, MarsupilamiFourteen)](#sha3-addons-cshake-kmac-tuplehash-parallelhash-kangarootwelve-marsupilamifourteen) +- [RIPEMD-160](#ripemd-160) +- [BLAKE2b, BLAKE2s](#blake2b-blake2s) +- [BLAKE3](#blake3) +- [SHA1 (legacy)](#sha1-legacy) +- [HMAC](#hmac) +- [HKDF](#hkdf) +- [PBKDF2](#pbkdf2) +- [Scrypt](#scrypt) +- [ESKDF](#eskdf) +- [utils](#utils) + +##### SHA2 (sha256, sha384, sha512, sha512_256) + +```typescript +import { sha256 } from '@noble/hashes/sha256'; +const h1a = sha256('abc'); +const h1b = sha256 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); +``` + +```typescript +import { sha512 } from '@noble/hashes/sha512'; +const h2a = sha512('abc'); +const h2b = sha512 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); + +// SHA512/256 variant +import { sha512_256 } from '@noble/hashes/sha512'; +const h3a = sha512_256('abc'); +const h3b = sha512_256 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); + +// SHA384 +import { sha384 } from '@noble/hashes/sha512'; +const h4a = sha384('abc'); +const h4b = sha384 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); +``` + +See [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and +[the paper on SHA512/256](https://eprint.iacr.org/2010/548.pdf). + +##### SHA3 (FIPS, SHAKE, Keccak) + +```typescript +import { + sha3_224, + sha3_256, + sha3_384, + sha3_512, + keccak_224, + keccak_256, + keccak_384, + keccak_512, + shake128, + shake256, +} from '@noble/hashes/sha3'; +const h5a = sha3_256('abc'); +const h5b = sha3_256 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); +const h6a = keccak_256('abc'); +const h7a = shake128('abc', { dkLen: 512 }); +const h7b = shake256('abc', { dkLen: 512 }); +``` + +See [FIPS PUB 202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf), +[Website](https://keccak.team/keccak.html). + +Check out [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub) + +##### SHA3 Addons (cSHAKE, KMAC, TupleHash, ParallelHash, KangarooTwelve, MarsupilamiFourteen) + +```typescript +import { + cshake128, + cshake256, + kmac128, + kmac256, + k12, + m14, + tuplehash128, + tuplehash256, + parallelhash128, + parallelhash256, + keccakprg, +} from '@noble/hashes/sha3-addons'; +const h7c = cshake128('abc', { personalization: 'def' }); +const h7d = cshake256('abc', { personalization: 'def' }); +const h7e = kmac128('key', 'message'); +const h7f = kmac256('key', 'message'); +const h7h = k12('abc'); +const h7g = m14('abc'); +const h7i = tuplehash128(['ab', 'c']); // tuplehash(['ab', 'c']) !== tuplehash(['a', 'bc']) !== tuplehash(['abc']) +// Same as k12/blake3, but without reduced number of rounds. Doesn't speedup anything due lack of SIMD and threading, +// added for compatibility. +const h7j = parallelhash128('abc', { blockLen: 8 }); +// pseudo-random generator, first argument is capacity. XKCP recommends 254 bits capacity for 128-bit security strength. +// * with a capacity of 254 bits. +const p = keccakprg(254); +p.feed('test'); +const rand1b = p.fetch(1); +``` + +- Full [NIST SP 800-185](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf): + cSHAKE, KMAC, TupleHash, ParallelHash + XOF variants +- 🦘 K12 ([KangarooTwelve Paper](https://keccak.team/files/KangarooTwelve.pdf), + [RFC Draft](https://www.ietf.org/archive/id/draft-irtf-cfrg-kangarootwelve-06.txt)) + and M14 aka MarsupilamiFourteen are basically parallel versions of Keccak with + reduced number of rounds (same as Blake3 and ParallelHash). +- [KeccakPRG](https://keccak.team/files/CSF-0.1.pdf): Pseudo-random generator based on Keccak + +##### RIPEMD-160 + +```typescript +import { ripemd160 } from '@noble/hashes/ripemd160'; +// function ripemd160(data: Uint8Array): Uint8Array; +const hash8 = ripemd160('abc'); +const hash9 = ripemd160() + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); +``` + +See [RFC 2286](https://datatracker.ietf.org/doc/html/rfc2286), +[Website](https://homes.esat.kuleuven.be/~bosselae/ripemd160.html) + +##### BLAKE2b, BLAKE2s + +```typescript +import { blake2b } from '@noble/hashes/blake2b'; +import { blake2s } from '@noble/hashes/blake2s'; +const h10a = blake2s('abc'); +const b2params = { key: new Uint8Array([1]), personalization: t, salt: t, dkLen: 32 }; +const h10b = blake2s('abc', b2params); +const h10c = blake2s + .create(b2params) + .update(Uint8Array.from([1, 2, 3])) + .digest(); +``` + +See [RFC 7693](https://datatracker.ietf.org/doc/html/rfc7693), [Website](https://www.blake2.net). + +##### BLAKE3 + +```typescript +import { blake3 } from '@noble/hashes/blake3'; +// All params are optional +const h11 = blake3('abc', { dkLen: 256, key: 'def', context: 'fji' }); +``` + +##### SHA1 (legacy) + +SHA1 was cryptographically broken, however, it was not broken for cases like HMAC. + +See [RFC4226 B.2](https://datatracker.ietf.org/doc/html/rfc4226#appendix-B.2). + +Don't use it for a new protocol. + +```typescript +import { sha1 } from '@noble/hashes/sha1'; +const h12 = sha1('def'); +``` + +##### HMAC + +```typescript +import { hmac } from '@noble/hashes/hmac'; +import { sha256 } from '@noble/hashes/sha256'; +const mac1 = hmac(sha256, 'key', 'message'); +const mac2 = hmac.create(sha256, Uint8Array.from([1, 2, 3])).update(Uint8Array.from([4, 5, 6])).digest(); +``` + +Matches [RFC 2104](https://datatracker.ietf.org/doc/html/rfc2104). + +##### HKDF + +```typescript +import { hkdf } from '@noble/hashes/hkdf'; +import { sha256 } from '@noble/hashes/sha256'; +import { randomBytes } from '@noble/hashes/utils'; +const inputKey = randomBytes(32); +const salt = randomBytes(32); +const info = 'abc'; +const dkLen = 32; +const hk1 = hkdf(sha256, inputKey, salt, info, dkLen); + +// == same as +import * as hkdf from '@noble/hashes/hkdf'; +import { sha256 } from '@noble/hashes/sha256'; +const prk = hkdf.extract(sha256, inputKey, salt); +const hk2 = hkdf.expand(sha256, prk, info, dkLen); +``` + +Matches [RFC 5869](https://datatracker.ietf.org/doc/html/rfc5869). + +##### PBKDF2 + +```typescript +import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2'; +import { sha256 } from '@noble/hashes/sha256'; +const pbkey1 = pbkdf2(sha256, 'password', 'salt', { c: 32, dkLen: 32 }); +const pbkey2 = await pbkdf2Async(sha256, 'password', 'salt', { c: 32, dkLen: 32 }); +const pbkey3 = await pbkdf2Async(sha256, Uint8Array.from([1, 2, 3]), Uint8Array.from([4, 5, 6]), { + c: 32, + dkLen: 32, +}); +``` + +Matches [RFC 2898](https://datatracker.ietf.org/doc/html/rfc2898). + +##### Scrypt + +```typescript +import { scrypt, scryptAsync } from '@noble/hashes/scrypt'; +const scr1 = scrypt('password', 'salt', { N: 2 ** 16, r: 8, p: 1, dkLen: 32 }); +const scr2 = await scryptAsync('password', 'salt', { N: 2 ** 16, r: 8, p: 1, dkLen: 32 }); +const scr3 = await scryptAsync(Uint8Array.from([1, 2, 3]), Uint8Array.from([4, 5, 6]), { + N: 2 ** 22, + r: 8, + p: 1, + dkLen: 32, + onProgress(percentage) { + console.log('progress', percentage); + }, + maxmem: 2 ** 32 + 128 * 8 * 1, // N * r * p * 128 + (128*r*p) +}); +``` + +Conforms to [RFC 7914](https://datatracker.ietf.org/doc/html/rfc7914), +[Website](https://www.tarsnap.com/scrypt.html) + +- `N, r, p` are work factors. To understand them, see [the blog post](https://blog.filippo.io/the-scrypt-parameters/). +- `dkLen` is the length of output bytes +- It is common to use N from `2**10` to `2**22` and `{r: 8, p: 1, dkLen: 32}` +- `onProgress` can be used with async version of the function to report progress to a user. + +Memory usage of scrypt is calculated with the formula `N * r * p * 128 + (128 * r * p)`, +which means `{N: 2 ** 22, r: 8, p: 1}` will use 4GB + 1KB of memory. To prevent +DoS, we limit scrypt to `1GB + 1KB` of RAM used, which corresponds to +`{N: 2 ** 20, r: 8, p: 1}`. If you want to use higher values, increase +`maxmem` using the formula above. + +_Note:_ noble supports `2**22` (4GB RAM) which is the highest amount amongst JS +libs. Many other implementations don't support it. We cannot support `2**23`, +because there is a limitation in JS engines that makes allocating +arrays bigger than 4GB impossible, but we're looking into other possible solutions. + +##### Argon2 + +Experimental Argon2 RFC 9106 implementation. It may be removed at any time. + +```ts +import { argon2d, argon2i, argon2id } from '@noble/hashes/argon2'; +const result = argon2id('password', 'salt', { t: 2, m: 65536, p: 1 }); +``` + +##### ESKDF + +A tiny stretched KDF for various applications like AES key-gen. Takes >= 2 seconds to execute. + +Takes following params: + +- `username` - username, email, or identifier, min: 8 characters, should have enough entropy +- `password` - min: 8 characters, should have enough entropy + +Produces ESKDF instance that has `deriveChildKey(protocol, accountId[, options])` function. + +- `protocol` - 3-15 character protocol name +- `accountId` - numeric identifier of account +- `options` - `keyLength: 32` with specified key length (default is 32), + or `modulus: 2n ** 221n - 17n` with specified modulus. It will fetch modulus + 64 bits of + data, execute modular division. The result will have negligible bias as per FIPS 186 B.4.1. + Can be used to generate, for example, elliptic curve keys. + +Takes username and password, then takes protocol name and account id. + +```typescript +import { eskdf } from '@noble/hashes/eskdf'; +const kdf = await eskdf('example@university', 'beginning-new-example'); +console.log(kdf.fingerprint); +const key1 = kdf.deriveChildKey('aes', 0); +const key2 = kdf.deriveChildKey('aes', 0, { keyLength: 16 }); +const ecc1 = kdf.deriveChildKey('ecc', 0, { modulus: 2n ** 252n - 27742317777372353535851937790883648493n }) +kdf.expire(); +``` + +##### utils + +```typescript +import { bytesToHex as toHex, randomBytes } from '@noble/hashes/utils'; +console.log(toHex(randomBytes(32))); +``` + +- `bytesToHex` will convert `Uint8Array` to a hex string +- `randomBytes(bytes)` will produce cryptographically secure random `Uint8Array` of length `bytes` + +## Security + +Noble is production-ready. + +1. The library has been audited in Jan 2022 by an independent security firm + cure53: [PDF](https://cure53.de/pentest-report_hashing-libs.pdf). + No vulnerabilities have been found. The audit has been funded by + [Ethereum Foundation](https://ethereum.org/en/) with help of [Nomic Labs](https://nomiclabs.io). + Modules `blake3`, `sha3-addons`, `sha1` and `argon2` have not been audited. + See [changes since audit](https://github.com/paulmillr/noble-hashes/compare/1.0.0..main). +2. The library has been fuzzed by [Guido Vranken's cryptofuzz](https://github.com/guidovranken/cryptofuzz). + You can run the fuzzer by yourself to check it. +3. [Timing attack](https://en.wikipedia.org/wiki/Timing_attack) considerations: + _JIT-compiler_ and _Garbage Collector_ make "constant time" extremely hard to + achieve in a scripting language. Which means _any other JS library can't have constant-timeness_. + Even statically typed Rust, a language without GC, + [makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security) + for some cases. If your goal is absolute security, don't use any JS lib — including + bindings to native ones. Use low-level libraries & languages. Nonetheless we're + targetting algorithmic constant time. +4. Memory dump considerations: the library shares state buffers between hash + function calls. The buffers are zeroed-out after each call. However, if an attacker + can read application memory, you are doomed in any case: + - At some point, input will be a string and strings are immutable in JS: + there is no way to overwrite them with zeros. For example: deriving + key from `scrypt(password, salt)` where password and salt are strings + - Input from a file will stay in file buffers + - Input / output will be re-used multiple times in application which means + it could stay in memory + - `await anything()` will always write all internal variables (including numbers) + to memory. With async functions / Promises there are no guarantees when the code + chunk would be executed. Which means attacker can have plenty of time to read data from memory + - There is no way to guarantee anything about zeroing sensitive data without + complex tests-suite which will dump process memory and verify that there is + no sensitive data left. For JS it means testing all browsers (incl. mobile), + which is complex. And of course it will be useless without using the same + test-suite in the actual application that consumes the library + +We consider infrastructure attacks like rogue NPM modules very important; that's +why it's crucial to minimize the amount of 3rd-party dependencies & native bindings. +If your app uses 500 dependencies, any dep could get hacked and you'll be downloading +malware with every `npm install`. Our goal is to minimize this attack vector. + +## Speed + +Benchmarks measured on Apple M1 with macOS 12. +Note that PBKDF2 and Scrypt are tested with extremely high work factor. +To run benchmarks, execute `npm run bench:install` and then `npm run bench` + +``` +SHA256 32B x 1,219,512 ops/sec @ 820ns/op ± 2.58% (min: 625ns, max: 4ms) +SHA384 32B x 512,032 ops/sec @ 1μs/op +SHA512 32B x 509,943 ops/sec @ 1μs/op +SHA3-256, keccak256, shake256 32B x 199,600 ops/sec @ 5μs/op +Kangaroo12 32B x 336,360 ops/sec @ 2μs/op +Marsupilami14 32B x 298,418 ops/sec @ 3μs/op +BLAKE2b 32B x 379,794 ops/sec @ 2μs/op +BLAKE2s 32B x 515,995 ops/sec @ 1μs/op ± 1.07% (min: 1μs, max: 4ms) +BLAKE3 32B x 588,235 ops/sec @ 1μs/op ± 1.36% (min: 1μs, max: 5ms) +RIPEMD160 32B x 1,140,250 ops/sec @ 877ns/op ± 3.12% (min: 708ns, max: 6ms) +HMAC-SHA256 32B x 377,358 ops/sec @ 2μs/op + +HKDF-SHA256 32B x 108,377 ops/sec @ 9μs/op +PBKDF2-HMAC-SHA256 262144 x 3 ops/sec @ 326ms/op +PBKDF2-HMAC-SHA512 262144 x 1 ops/sec @ 970ms/op +Scrypt r: 8, p: 1, n: 262144 x 1 ops/sec @ 616ms/op +``` + +Compare to native node.js implementation that uses C bindings instead of pure-js code: + +``` +SHA256 32B node x 1,302,083 ops/sec @ 768ns/op ± 10.54% (min: 416ns, max: 7ms) +SHA384 32B node x 975,609 ops/sec @ 1μs/op ± 11.32% (min: 625ns, max: 8ms) +SHA512 32B node x 983,284 ops/sec @ 1μs/op ± 11.24% (min: 625ns, max: 8ms) +SHA3-256 32B node x 910,746 ops/sec @ 1μs/op ± 12.19% (min: 666ns, max: 10ms) +keccak, k12, m14 are not implemented +BLAKE2b 32B node x 967,117 ops/sec @ 1μs/op ± 11.26% (min: 625ns, max: 9ms) +BLAKE2s 32B node x 1,055,966 ops/sec @ 947ns/op ± 11.07% (min: 583ns, max: 7ms) +BLAKE3 is not implemented +RIPEMD160 32B node x 1,002,004 ops/sec @ 998ns/op ± 10.66% (min: 625ns, max: 7ms) +HMAC-SHA256 32B node x 919,963 ops/sec @ 1μs/op ± 6.13% (min: 833ns, max: 5ms) +HKDF-SHA256 32 node x 369,276 ops/sec @ 2μs/op ± 13.59% (min: 1μs, max: 9ms) +PBKDF2-HMAC-SHA256 262144 node x 25 ops/sec @ 39ms/op +PBKDF2-HMAC-SHA512 262144 node x 7 ops/sec @ 132ms/op +Scrypt r: 8, p: 1, n: 262144 node x 1 ops/sec @ 523ms/op +``` + +It is possible to [make this library 4x+ faster](./benchmark/README.md) by +_doing code generation of full loop unrolls_. We've decided against it. Reasons: + +- the library must be auditable, with minimum amount of code, and zero dependencies +- most method invocations with the lib are going to be something like hashing 32b to 64kb of data +- hashing big inputs is 10x faster with low-level languages, which means you should probably pick 'em instead + +The current performance is good enough when compared to other projects; SHA256 takes only 900 nanoseconds to run. + +## Contributing & testing + +1. Clone the repository +2. `npm install` to install build dependencies like TypeScript +3. `npm run build` to compile TypeScript code +4. `npm run test` will execute all main tests. See [our approach to testing](./test/README.md) +5. `npm run test:dos` will test against DoS; by measuring function complexity. **Takes ~20 minutes** +6. `npm run test:big` will execute hashing on 4GB inputs, + scrypt with 1024 different `N, r, p` combinations, etc. **Takes several hours**. Using 8-32+ core CPU helps. + +## License + +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller [(https://paulmillr.com)](https://paulmillr.com) + +See LICENSE file. diff --git a/node_modules/@noble/hashes/_assert.d.ts b/node_modules/@noble/hashes/_assert.d.ts new file mode 100644 index 0000000..b71d8e4 --- /dev/null +++ b/node_modules/@noble/hashes/_assert.d.ts @@ -0,0 +1,21 @@ +export declare function number(n: number): void; +export declare function bool(b: boolean): void; +export declare function bytes(b: Uint8Array | undefined, ...lengths: number[]): void; +type Hash = { + (data: Uint8Array): Uint8Array; + blockLen: number; + outputLen: number; + create: any; +}; +export declare function hash(hash: Hash): void; +export declare function exists(instance: any, checkFinished?: boolean): void; +export declare function output(out: any, instance: any): void; +declare const assert: { + number: typeof number; + bool: typeof bool; + bytes: typeof bytes; + hash: typeof hash; + exists: typeof exists; + output: typeof output; +}; +export default assert; diff --git a/node_modules/@noble/hashes/_assert.js b/node_modules/@noble/hashes/_assert.js new file mode 100644 index 0000000..acf3491 --- /dev/null +++ b/node_modules/@noble/hashes/_assert.js @@ -0,0 +1,52 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.output = exports.exists = exports.hash = exports.bytes = exports.bool = exports.number = void 0; +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); +} +exports.number = number; +function bool(b) { + if (typeof b !== 'boolean') + throw new Error(`Expected boolean, not ${b}`); +} +exports.bool = bool; +function bytes(b, ...lengths) { + if (!(b instanceof Uint8Array)) + throw new Error('Expected Uint8Array'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} +exports.bytes = bytes; +function hash(hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(hash.outputLen); + number(hash.blockLen); +} +exports.hash = hash; +function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +exports.exists = exists; +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} +exports.output = output; +const assert = { + number, + bool, + bytes, + hash, + exists, + output, +}; +exports.default = assert; +//# sourceMappingURL=_assert.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/_assert.js.map b/node_modules/@noble/hashes/_assert.js.map new file mode 100644 index 0000000..94ac2c1 --- /dev/null +++ b/node_modules/@noble/hashes/_assert.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_assert.js","sourceRoot":"","sources":["src/_assert.ts"],"names":[],"mappings":";;;AAAA,SAAgB,MAAM,CAAC,CAAS;IAC9B,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,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,CAAC,CAAC;IACX,MAAM,GAAG,GAAG,QAAQ,CAAC,SAAS,CAAC;IAC/B,IAAI,GAAG,CAAC,MAAM,GAAG,GAAG,EAAE;QACpB,MAAM,IAAI,KAAK,CAAC,yDAAyD,GAAG,EAAE,CAAC,CAAC;KACjF;AACH,CAAC;AAND,wBAMC;AAED,MAAM,MAAM,GAAG;IACb,MAAM;IACN,IAAI;IACJ,KAAK;IACL,IAAI;IACJ,MAAM;IACN,MAAM;CACP,CAAC;AAEF,kBAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/_blake2.d.ts b/node_modules/@noble/hashes/_blake2.d.ts new file mode 100644 index 0000000..352b978 --- /dev/null +++ b/node_modules/@noble/hashes/_blake2.d.ts @@ -0,0 +1,27 @@ +import { Hash, Input } from './utils.js'; +export declare const SIGMA: Uint8Array; +export type BlakeOpts = { + dkLen?: number; + key?: Input; + salt?: Input; + personalization?: Input; +}; +export declare abstract class BLAKE2> extends Hash { + readonly blockLen: number; + outputLen: number; + protected abstract compress(msg: Uint32Array, offset: number, isLast: boolean): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected buffer: Uint8Array; + protected buffer32: Uint32Array; + protected length: number; + protected pos: number; + protected finished: boolean; + protected destroyed: boolean; + constructor(blockLen: number, outputLen: number, opts: BlakeOpts | undefined, keyLen: number, saltLen: number, persLen: number); + update(data: Input): this; + digestInto(out: Uint8Array): void; + digest(): Uint8Array; + _cloneInto(to?: T): T; +} diff --git a/node_modules/@noble/hashes/_blake2.js b/node_modules/@noble/hashes/_blake2.js new file mode 100644 index 0000000..bf5dd93 --- /dev/null +++ b/node_modules/@noble/hashes/_blake2.js @@ -0,0 +1,111 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BLAKE2 = exports.SIGMA = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. +// prettier-ignore +exports.SIGMA = new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, +]); +class BLAKE2 extends utils_js_1.Hash { + constructor(blockLen, outputLen, opts = {}, keyLen, saltLen, persLen) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.length = 0; + this.pos = 0; + this.finished = false; + this.destroyed = false; + _assert_js_1.default.number(blockLen); + _assert_js_1.default.number(outputLen); + _assert_js_1.default.number(keyLen); + if (outputLen < 0 || outputLen > keyLen) + throw new Error('outputLen bigger than keyLen'); + if (opts.key !== undefined && (opts.key.length < 1 || opts.key.length > keyLen)) + throw new Error(`key must be up 1..${keyLen} byte long or undefined`); + if (opts.salt !== undefined && opts.salt.length !== saltLen) + throw new Error(`salt must be ${saltLen} byte long or undefined`); + if (opts.personalization !== undefined && opts.personalization.length !== persLen) + throw new Error(`personalization must be ${persLen} byte long or undefined`); + this.buffer32 = (0, utils_js_1.u32)((this.buffer = new Uint8Array(blockLen))); + } + update(data) { + _assert_js_1.default.exists(this); + // Main difference with other hashes: there is flag for last block, + // so we cannot process current block before we know that there + // is the next one. This significantly complicates logic and reduces ability + // to do zero-copy processing + const { blockLen, buffer, buffer32 } = this; + data = (0, utils_js_1.toBytes)(data); + const len = data.length; + const offset = data.byteOffset; + const buf = data.buffer; + for (let pos = 0; pos < len;) { + // If buffer is full and we still have input (don't process last block, same as blake2s) + if (this.pos === blockLen) { + this.compress(buffer32, 0, false); + this.pos = 0; + } + const take = Math.min(blockLen - this.pos, len - pos); + const dataOffset = offset + pos; + // full block && aligned to 4 bytes && not last in input + if (take === blockLen && !(dataOffset % 4) && pos + take < len) { + const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4)); + for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) { + this.length += blockLen; + this.compress(data32, pos32, false); + } + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + this.length += take; + pos += take; + } + return this; + } + digestInto(out) { + _assert_js_1.default.exists(this); + _assert_js_1.default.output(out, this); + const { pos, buffer32 } = this; + this.finished = true; + // Padding + this.buffer.subarray(pos).fill(0); + this.compress(buffer32, 0, true); + const out32 = (0, utils_js_1.u32)(out); + this.get().forEach((v, i) => (out32[i] = v)); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + const { buffer, length, finished, destroyed, outputLen, pos } = this; + to || (to = new this.constructor({ dkLen: outputLen })); + to.set(...this.get()); + to.length = length; + to.finished = finished; + to.destroyed = destroyed; + to.outputLen = outputLen; + to.buffer.set(buffer); + to.pos = pos; + return to; + } +} +exports.BLAKE2 = BLAKE2; +//# sourceMappingURL=_blake2.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/_blake2.js.map b/node_modules/@noble/hashes/_blake2.js.map new file mode 100644 index 0000000..88ca9c0 --- /dev/null +++ b/node_modules/@noble/hashes/_blake2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_blake2.js","sourceRoot":"","sources":["src/_blake2.ts"],"names":[],"mappings":";;;AAAA,6CAAkC;AAClC,yCAAuD;AACvD,gGAAgG;AAChG,kBAAkB;AACL,QAAA,KAAK,GAAG,IAAI,UAAU,CAAC;IAClC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;IACpD,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE;IACpD,CAAC,EAAE,E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;QACJ,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;QACnC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QACxB,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;QACvC,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,OAAO,GAAG,CAAC;IACb,CAAC;IACD,UAAU,CAAC,EAAM;QACf,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;QACrE,EAAE,KAAF,EAAE,GAAK,IAAK,IAAI,CAAC,WAAmB,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,CAAM,EAAC;QAChE,EAAE,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;QACtB,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC;QACnB,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACvB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACtB,EAAE,CAAC,GAAG,GAAG,GAAG,CAAC;QACb,OAAO,EAAE,CAAC;IACZ,CAAC;CACF;AAlGD,wBAkGC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/_sha2.d.ts b/node_modules/@noble/hashes/_sha2.d.ts new file mode 100644 index 0000000..883788f --- /dev/null +++ b/node_modules/@noble/hashes/_sha2.d.ts @@ -0,0 +1,23 @@ +import { Hash, Input } from './utils.js'; +export declare abstract class SHA2> extends Hash { + readonly blockLen: number; + outputLen: number; + readonly padOffset: number; + readonly isLE: boolean; + protected abstract process(buf: DataView, offset: number): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected abstract roundClean(): void; + protected buffer: Uint8Array; + protected view: DataView; + protected finished: boolean; + protected length: number; + protected pos: number; + protected destroyed: boolean; + constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean); + update(data: Input): this; + digestInto(out: Uint8Array): void; + digest(): Uint8Array; + _cloneInto(to?: T): T; +} diff --git a/node_modules/@noble/hashes/_sha2.js b/node_modules/@noble/hashes/_sha2.js new file mode 100644 index 0000000..398d446 --- /dev/null +++ b/node_modules/@noble/hashes/_sha2.js @@ -0,0 +1,118 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SHA2 = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +// Polyfill for Safari 14 +function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +// Base SHA2 class (RFC 6234) +class SHA2 extends utils_js_1.Hash { + constructor(blockLen, outputLen, padOffset, isLE) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = (0, utils_js_1.createView)(this.buffer); + } + update(data) { + _assert_js_1.default.exists(this); + const { view, buffer, blockLen } = this; + data = (0, utils_js_1.toBytes)(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input, cast it to view and process + if (take === blockLen) { + const dataView = (0, utils_js_1.createView)(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + _assert_js_1.default.exists(this); + _assert_js_1.default.output(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + this.buffer.subarray(pos).fill(0); + // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) + buffer[i] = 0; + // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = (0, utils_js_1.createView)(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + if (len % 4) + throw new Error('_sha2: outputLen should be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } +} +exports.SHA2 = SHA2; +//# sourceMappingURL=_sha2.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/_sha2.js.map b/node_modules/@noble/hashes/_sha2.js.map new file mode 100644 index 0000000..cae147e --- /dev/null +++ b/node_modules/@noble/hashes/_sha2.js.map @@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G,CAAC;QACb,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACvB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,IAAI,MAAM,GAAG,QAAQ;YAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC7C,OAAO,EAAE,CAAC;IACZ,CAAC;CACF;AApGD,oBAoGC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/_u64.d.ts b/node_modules/@noble/hashes/_u64.d.ts new file mode 100644 index 0000000..9ac94f8 --- /dev/null +++ b/node_modules/@noble/hashes/_u64.d.ts @@ -0,0 +1,35 @@ +export declare function fromBig(n: bigint, le?: boolean): { + h: number; + l: number; +}; +export declare function split(lst: bigint[], le?: boolean): Uint32Array[]; +export declare const toBig: (h: number, l: number) => bigint; +export declare function add(Ah: number, Al: number, Bh: number, Bl: number): { + h: number; + l: number; +}; +declare const u64: { + fromBig: typeof fromBig; + split: typeof split; + toBig: (h: number, l: number) => bigint; + shrSH: (h: number, l: number, s: number) => number; + shrSL: (h: number, l: number, s: number) => number; + rotrSH: (h: number, l: number, s: number) => number; + rotrSL: (h: number, l: number, s: number) => number; + rotrBH: (h: number, l: number, s: number) => number; + rotrBL: (h: number, l: number, s: number) => number; + rotr32H: (h: number, l: number) => number; + rotr32L: (h: number, l: number) => number; + rotlSH: (h: number, l: number, s: number) => number; + rotlSL: (h: number, l: number, s: number) => number; + rotlBH: (h: number, l: number, s: number) => number; + rotlBL: (h: number, l: number, s: number) => number; + add: typeof add; + add3L: (Al: number, Bl: number, Cl: number) => number; + add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; + add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; + add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; + add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; + add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; +}; +export default u64; diff --git a/node_modules/@noble/hashes/_u64.js b/node_modules/@noble/hashes/_u64.js new file mode 100644 index 0000000..2e1936d --- /dev/null +++ b/node_modules/@noble/hashes/_u64.js @@ -0,0 +1,68 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.add = exports.toBig = exports.split = exports.fromBig = void 0; +const U32_MASK64 = BigInt(2 ** 32 - 1); +const _32n = BigInt(32); +// We are not using BigUint64Array, because they are extremely slow as per 2022 +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +exports.fromBig = fromBig; +function split(lst, le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +exports.split = split; +const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +exports.toBig = toBig; +// for Shift in [0, 32) +const shrSH = (h, l, s) => h >>> s; +const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in [1, 32) +const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); +const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); +const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (h, l) => l; +const rotr32L = (h, l) => h; +// Left rotate for Shift in [1, 32) +const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); +const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); +const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +// Removing "export" has 5% perf penalty -_- +function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +exports.add = add; +// Addition with more than 2 elements +const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; +// prettier-ignore +const u64 = { + fromBig, split, toBig: exports.toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +exports.default = u64; +//# sourceMappingURL=_u64.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/_u64.js.map b/node_modules/@noble/hashes/_u64.js.map new file mode 100644 index 0000000..aa363e0 --- /dev/null +++ b/node_modules/@noble/hashes/_u64.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_u64.js","sourceRoot":"","sources":["src/_u64.ts"],"names":[],"mappings":";;;AAAA,MAAM,UAAU,GAAG,MAAM,CAAC,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC;AACvC,MAAM,IAAI,GAAG,MAAM,CAAC,EAAE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,CAAC,GAAW,EAAE,EAAU,EAAE,EAAU,EAAE,EAAU,EAAE,EAAU,EAAE,EAAU,EAAE,EAAE,CACxF,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;AAEvD,kBAAkB;AAClB,MAAM,GAAG,GAAG;IACV,OAAO,EAAE,KAAK,EAAE,KAAK,EAAL,aAAK;IACrB,KAAK,EAAE,KAAK;IACZ,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9B,OAAO,EAAE,OAAO;IAChB,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9B,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK;CAC9C,CAAC;AACF,kBAAe,GAAG,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/argon2.d.ts b/node_modules/@noble/hashes/argon2.d.ts new file mode 100644 index 0000000..15b6486 --- /dev/null +++ b/node_modules/@noble/hashes/argon2.d.ts @@ -0,0 +1,16 @@ +import { Input } from './utils.js'; +export type ArgonOpts = { + t: number; + m: number; + p: number; + version?: number; + key?: Input; + personalization?: Input; + dkLen?: number; + asyncTick?: number; + maxmem?: number; + onProgress?: (progress: number) => void; +}; +export declare const argon2d: (password: Input, salt: Input, opts: ArgonOpts) => Uint8Array; +export declare const argon2i: (password: Input, salt: Input, opts: ArgonOpts) => Uint8Array; +export declare const argon2id: (password: Input, salt: Input, opts: ArgonOpts) => Uint8Array; diff --git a/node_modules/@noble/hashes/argon2.js b/node_modules/@noble/hashes/argon2.js new file mode 100644 index 0000000..cf480c9 --- /dev/null +++ b/node_modules/@noble/hashes/argon2.js @@ -0,0 +1,310 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.argon2id = exports.argon2i = exports.argon2d = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +const blake2b_js_1 = require("./blake2b.js"); +const _u64_js_1 = require("./_u64.js"); +// Experimental Argon2 RFC 9106 implementation. It may be removed at any time. +var Types; +(function (Types) { + Types[Types["Argond2d"] = 0] = "Argond2d"; + Types[Types["Argon2i"] = 1] = "Argon2i"; + Types[Types["Argon2id"] = 2] = "Argon2id"; +})(Types || (Types = {})); +const ARGON2_SYNC_POINTS = 4; +const toBytesOptional = (buf) => (buf !== undefined ? (0, utils_js_1.toBytes)(buf) : new Uint8Array([])); +function mul(a, b) { + const aL = a & 0xffff; + const aH = a >>> 16; + const bL = b & 0xffff; + const bH = b >>> 16; + const ll = Math.imul(aL, bL); + const hl = Math.imul(aH, bL); + const lh = Math.imul(aL, bH); + const hh = Math.imul(aH, bH); + const BUF = ((ll >>> 16) + (hl & 0xffff) + lh) | 0; + const h = ((hl >>> 16) + (BUF >>> 16) + hh) | 0; + return { h, l: (BUF << 16) | (ll & 0xffff) }; +} +function relPos(areaSize, relativePos) { + // areaSize - 1 - ((areaSize * ((relativePos ** 2) >>> 32)) >>> 32) + return areaSize - 1 - mul(areaSize, mul(relativePos, relativePos).h).h; +} +function mul2(a, b) { + // 2 * a * b (via shifts) + const { h, l } = mul(a, b); + return { h: ((h << 1) | (l >>> 31)) & 4294967295, l: (l << 1) & 4294967295 }; +} +function blamka(Ah, Al, Bh, Bl) { + const { h: Ch, l: Cl } = mul2(Al, Bl); + // A + B + (2 * A * B) + const Rll = _u64_js_1.default.add3L(Al, Bl, Cl); + return { h: _u64_js_1.default.add3H(Rll, Ah, Bh, Ch), l: Rll | 0 }; +} +// Temporary block buffer +const BUF = new Uint32Array(256); +function G(a, b, c, d) { + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: _u64_js_1.default.rotr32H(Dh, Dl), Dl: _u64_js_1.default.rotr32L(Dh, Dl) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: _u64_js_1.default.rotrSH(Bh, Bl, 24), Bl: _u64_js_1.default.rotrSL(Bh, Bl, 24) }); + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: _u64_js_1.default.rotrSH(Dh, Dl, 16), Dl: _u64_js_1.default.rotrSL(Dh, Dl, 16) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: _u64_js_1.default.rotrBH(Bh, Bl, 63), Bl: _u64_js_1.default.rotrBL(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +// prettier-ignore +function P(v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15) { + G(v00, v04, v08, v12); + G(v01, v05, v09, v13); + G(v02, v06, v10, v14); + G(v03, v07, v11, v15); + G(v00, v05, v10, v15); + G(v01, v06, v11, v12); + G(v02, v07, v08, v13); + G(v03, v04, v09, v14); +} +function block(x, xPos, yPos, outPos, needXor) { + for (let i = 0; i < 256; i++) + BUF[i] = x[xPos + i] ^ x[yPos + i]; + // columns + for (let i = 0; i < 128; i += 16) { + // prettier-ignore + P(i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15); + } + // rows + for (let i = 0; i < 16; i += 2) { + // prettier-ignore + P(i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113); + } + if (needXor) + for (let i = 0; i < 256; i++) + x[outPos + i] ^= BUF[i] ^ x[xPos + i] ^ x[yPos + i]; + else + for (let i = 0; i < 256; i++) + x[outPos + i] = BUF[i] ^ x[xPos + i] ^ x[yPos + i]; +} +// Variable-Length Hash Function H' +function Hp(A, dkLen) { + const A8 = (0, utils_js_1.u8)(A); + const T = new Uint32Array(1); + const T8 = (0, utils_js_1.u8)(T); + T[0] = dkLen; + // Fast path + if (dkLen <= 64) + return blake2b_js_1.blake2b.create({ dkLen }).update(T8).update(A8).digest(); + const out = new Uint8Array(dkLen); + let V = blake2b_js_1.blake2b.create({}).update(T8).update(A8).digest(); + let pos = 0; + // First block + out.set(V.subarray(0, 32)); + pos += 32; + // Rest blocks + for (; dkLen - pos > 64; pos += 32) + out.set((V = (0, blake2b_js_1.blake2b)(V)).subarray(0, 32), pos); + // Last block + out.set((0, blake2b_js_1.blake2b)(V, { dkLen: dkLen - pos }), pos); + return (0, utils_js_1.u32)(out); +} +function indexAlpha(r, s, laneLen, segmentLen, index, randL, sameLane = false) { + let area; + if (0 == r) { + if (0 == s) + area = index - 1; + else if (sameLane) + area = s * segmentLen + index - 1; + else + area = s * segmentLen + (index == 0 ? -1 : 0); + } + else if (sameLane) + area = laneLen - segmentLen + index - 1; + else + area = laneLen - segmentLen + (index == 0 ? -1 : 0); + const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0; + const rel = relPos(area, randL); + // NOTE: check about overflows here + // absPos = (startPos + relPos) % laneLength; + return (startPos + rel) % laneLen; +} +function argon2Init(type, password, salt, opts) { + password = (0, utils_js_1.toBytes)(password); + salt = (0, utils_js_1.toBytes)(salt); + let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress } = { + ...opts, + version: opts.version || 0x13, + dkLen: opts.dkLen || 32, + maxmem: 2 ** 32, + }; + // Validation + _assert_js_1.default.number(p); + _assert_js_1.default.number(dkLen); + _assert_js_1.default.number(m); + _assert_js_1.default.number(t); + _assert_js_1.default.number(version); + if (dkLen < 4 || dkLen >= 2 ** 32) + throw new Error('Argon2: dkLen should be at least 4 bytes'); + if (dkLen < 1 || p >= 2 ** 32) + throw new Error('Argon2: p (paralllelism) should be at least 1'); + if (dkLen < 1 || p >= 2 ** 32) + throw new Error('Argon2: t (iterations) should be at least 1'); + if (m < 8 * p) + throw new Error(`Argon2: memory should be at least 8*p bytes`); + if (version !== 16 && version !== 19) + throw new Error(`Argon2: unknown version=${version}`); + password = (0, utils_js_1.toBytes)(password); + if (password.length < 0 || password.length >= 2 ** 32) + throw new Error('Argon2: password should be less than 4 GB'); + salt = (0, utils_js_1.toBytes)(salt); + if (salt.length < 8) + throw new Error('Argon2: salt should be at least 8 bytes'); + key = toBytesOptional(key); + personalization = toBytesOptional(personalization); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + // Params + const lanes = p; + // m' = 4 * p * floor (m / 4p) + const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p)); + //q = m' / p columns + const laneLen = Math.floor(mP / p); + const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS); + // H0 + const h = blake2b_js_1.blake2b.create({}); + const BUF = new Uint32Array(1); + const BUF8 = (0, utils_js_1.u8)(BUF); + for (const i of [p, dkLen, m, t, version, type]) { + if (i < 0 || i >= 2 ** 32) + throw new Error(`Argon2: wrong parameter=${i}, expected uint32`); + BUF[0] = i; + h.update(BUF8); + } + for (let i of [password, salt, key, personalization]) { + BUF[0] = i.length; + h.update(BUF8).update(i); + } + const H0 = new Uint32Array(18); + const H0_8 = (0, utils_js_1.u8)(H0); + h.digestInto(H0_8); + // 256 u32 = 1024 (BLOCK_SIZE) + const memUsed = mP * 256; + if (memUsed < 0 || memUsed >= 2 ** 32 || memUsed > maxmem) { + throw new Error(`Argon2: wrong params (memUsed=${memUsed} maxmem=${maxmem}), should be less than 2**32`); + } + const B = new Uint32Array(memUsed); + // Fill first blocks + for (let l = 0; l < p; l++) { + const i = 256 * laneLen * l; + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + H0[17] = l; + H0[16] = 0; + B.set(Hp(H0, 1024), i); + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + H0[16] = 1; + B.set(Hp(H0, 1024), i + 256); + } + let perBlock = () => { }; + if (onProgress) { + const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlock / 10000), 1); + let blockCnt = 0; + perBlock = () => { + blockCnt++; + if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock)) + onProgress(blockCnt / totalBlock); + }; + } + return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock }; +} +function argon2Output(B, p, laneLen, dkLen) { + const B_final = new Uint32Array(256); + for (let l = 0; l < p; l++) + for (let j = 0; j < 256; j++) + B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j]; + return (0, utils_js_1.u8)(Hp(B_final, dkLen)); +} +function processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor) { + if (offset % laneLen) + prev = offset - 1; + let randL, randH; + if (dataIndependent) { + if (index % 128 === 0) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + randL = address[2 * (index % 128)]; + randH = address[2 * (index % 128) + 1]; + } + else { + const T = 256 * prev; + randL = B[T]; + randH = B[T + 1]; + } + // address block + const refLane = r === 0 && s === 0 ? l : randH % lanes; + const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l); + const refBlock = laneLen * refLane + refPos; + // B[i][j] = G(B[i][j-1], B[l][z]) + block(B, 256 * prev, 256 * refBlock, offset * 256, needXor); +} +function argon2(type, password, salt, opts) { + const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init(type, password, salt, opts); + // Pre-loop setup + // [address, input, zero_block] format so we can pass single U32 to block function + const address = new Uint32Array(3 * 256); + address[256 + 6] = mP; + address[256 + 8] = t; + address[256 + 10] = type; + for (let r = 0; r < t; r++) { + const needXor = r !== 0 && version === 0x13; + address[256 + 0] = r; + for (let s = 0; s < ARGON2_SYNC_POINTS; s++) { + address[256 + 4] = s; + const dataIndependent = type == Types.Argon2i || (type == Types.Argon2id && r === 0 && s < 2); + for (let l = 0; l < p; l++) { + address[256 + 2] = l; + address[256 + 12] = 0; + let startPos = 0; + if (r === 0 && s === 0) { + startPos = 2; + if (dataIndependent) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + } + // current block postion + let offset = l * laneLen + s * segmentLen + startPos; + // previous block position + let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1; + for (let index = startPos; index < segmentLen; index++, offset++, prev++) { + perBlock(); + processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor); + } + } + } + } + return argon2Output(B, p, laneLen, dkLen); +} +const argon2d = (password, salt, opts) => argon2(Types.Argond2d, password, salt, opts); +exports.argon2d = argon2d; +const argon2i = (password, salt, opts) => argon2(Types.Argon2i, password, salt, opts); +exports.argon2i = argon2i; +const argon2id = (password, salt, opts) => argon2(Types.Argon2id, password, salt, opts); +exports.argon2id = argon2id; +//# sourceMappingURL=argon2.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/argon2.js.map b/node_modules/@noble/hashes/argon2.js.map new file mode 100644 index 0000000..ca36172 --- /dev/null +++ b/node_modules/@noble/hashes/argon2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"argon2.js","sourceRoot":"","sources":["src/argon2.ts"],"names":[],"mappings":";;;AAAA,6CAAkC;AAClC,yCAAqD;AACrD,6CAAuC;AACvC,uCAA4B;AAE5B,8EAA8E;AAC9E,IAAK,KAIJ;AAJD,WAAK,KAAK;IACR,yCAAY,CAAA;IACZ,uCAAW,CAAA;IACX,yCAAY,CAAA;AACd,CAAC,EAJI,KAAK,KAAL,KAAK,QAIT;AAED,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAE7B,MAAM,eAAe,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,CAAC,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC;AAEjG,SAAS,GAAG,CAAC,CAAS,EAAE,CAAS;IAC/B,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,CAAC;IACtB,MAAM,EAAE,GAAG,CAAC,KAAK,EAAE,CAAC;IACpB,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,CAAC;IACtB,MAAM,EAAE,GAAG,CAAC,KAAK,EAAE,CAAC;IACpB,MAAM,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IAC7B,MAAM,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IAC7B,MAAM,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IAC7B,MAAM,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IAC7B,MAAM,GAAG,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,EAAE,GAAG,MAAM,CAA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CAAC,EACD,CAAC,EACD,KAAK,EACL,OAAO,EACP,UAAU,EACV,KAAK,EACL,MAAM,EACN,IAAI,EACJ,eAAe,EACf,OAAO,CACR,CAAC;iBACH;aACF;SACF;KACF;IACD,OAAO,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;AAC5C,CAAC;AAEM,MAAM,OAAO,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACvE,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AADlC,QAAA,OAAO,WAC2B;AACxC,MAAM,OAAO,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACvE,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AADjC,QAAA,OAAO,WAC0B;AACvC,MAAM,QAAQ,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACxE,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AADlC,QAAA,QAAQ,YAC0B"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/blake2b.d.ts b/node_modules/@noble/hashes/blake2b.d.ts new file mode 100644 index 0000000..7a78c6b --- /dev/null +++ b/node_modules/@noble/hashes/blake2b.d.ts @@ -0,0 +1,53 @@ +import { BLAKE2, BlakeOpts } from './_blake2.js'; +declare class BLAKE2b extends BLAKE2 { + private v0l; + private v0h; + private v1l; + private v1h; + private v2l; + private v2h; + private v3l; + private v3h; + private v4l; + private v4h; + private v5l; + private v5h; + private v6l; + private v6h; + private v7l; + private v7h; + constructor(opts?: BlakeOpts); + protected get(): [ + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number + ]; + protected set(v0l: number, v0h: number, v1l: number, v1h: number, v2l: number, v2h: number, v3l: number, v3h: number, v4l: number, v4h: number, v5l: number, v5h: number, v6l: number, v6h: number, v7l: number, v7h: number): void; + protected compress(msg: Uint32Array, offset: number, isLast: boolean): void; + destroy(): void; +} +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export declare const blake2b: { + (msg: import("./utils.js").Input, opts?: BlakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: BlakeOpts): import("./utils.js").Hash; +}; +export {}; diff --git a/node_modules/@noble/hashes/blake2b.js b/node_modules/@noble/hashes/blake2b.js new file mode 100644 index 0000000..a25abda --- /dev/null +++ b/node_modules/@noble/hashes/blake2b.js @@ -0,0 +1,192 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.blake2b = void 0; +const _blake2_js_1 = require("./_blake2.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// Same as SHA-512 but LE +// prettier-ignore +const IV = new Uint32Array([ + 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, + 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19 +]); +// Temporary buffer +const BUF = new Uint32Array(32); +// Mixing function G splitted in two halfs +function G1(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = _u64_js_1.default.add3L(Al, Bl, Xl); + Ah = _u64_js_1.default.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 32) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: _u64_js_1.default.rotr32H(Dh, Dl), Dl: _u64_js_1.default.rotr32L(Dh, Dl) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = _u64_js_1.default.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 24) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: _u64_js_1.default.rotrSH(Bh, Bl, 24), Bl: _u64_js_1.default.rotrSL(Bh, Bl, 24) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +function G2(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = _u64_js_1.default.add3L(Al, Bl, Xl); + Ah = _u64_js_1.default.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 16) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: _u64_js_1.default.rotrSH(Dh, Dl, 16), Dl: _u64_js_1.default.rotrSL(Dh, Dl, 16) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = _u64_js_1.default.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 63) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: _u64_js_1.default.rotrBH(Bh, Bl, 63), Bl: _u64_js_1.default.rotrBL(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +class BLAKE2b extends _blake2_js_1.BLAKE2 { + constructor(opts = {}) { + super(128, opts.dkLen === undefined ? 64 : opts.dkLen, opts, 64, 16, 16); + // Same as SHA-512, but LE + this.v0l = IV[0] | 0; + this.v0h = IV[1] | 0; + this.v1l = IV[2] | 0; + this.v1h = IV[3] | 0; + this.v2l = IV[4] | 0; + this.v2h = IV[5] | 0; + this.v3l = IV[6] | 0; + this.v3h = IV[7] | 0; + this.v4l = IV[8] | 0; + this.v4h = IV[9] | 0; + this.v5l = IV[10] | 0; + this.v5h = IV[11] | 0; + this.v6l = IV[12] | 0; + this.v6h = IV[13] | 0; + this.v7l = IV[14] | 0; + this.v7h = IV[15] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.salt)); + this.v4l ^= salt[0]; + this.v4h ^= salt[1]; + this.v5l ^= salt[2]; + this.v5h ^= salt[3]; + } + if (opts.personalization) { + const pers = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.personalization)); + this.v6l ^= pers[0]; + this.v6h ^= pers[1]; + this.v7l ^= pers[2]; + this.v7h ^= pers[3]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set((0, utils_js_1.toBytes)(opts.key)); + this.update(tmp); + } + } + // prettier-ignore + get() { + let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + compress(msg, offset, isLast) { + this.get().forEach((v, i) => (BUF[i] = v)); // First half from state. + BUF.set(IV, 16); // Second half from IV. + let { h, l } = _u64_js_1.default.fromBig(BigInt(this.length)); + BUF[24] = IV[8] ^ l; // Low word of the offset. + BUF[25] = IV[9] ^ h; // High word. + // Invert all bits for last block + if (isLast) { + BUF[28] = ~BUF[28]; + BUF[29] = ~BUF[29]; + } + let j = 0; + const s = _blake2_js_1.SIGMA; + for (let i = 0; i < 12; i++) { + G1(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G2(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G1(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G2(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G1(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G2(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G1(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G2(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G1(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G2(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G1(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G2(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G1(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G2(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G1(3, 4, 9, 14, msg, offset + 2 * s[j++]); + G2(3, 4, 9, 14, msg, offset + 2 * s[j++]); + } + this.v0l ^= BUF[0] ^ BUF[16]; + this.v0h ^= BUF[1] ^ BUF[17]; + this.v1l ^= BUF[2] ^ BUF[18]; + this.v1h ^= BUF[3] ^ BUF[19]; + this.v2l ^= BUF[4] ^ BUF[20]; + this.v2h ^= BUF[5] ^ BUF[21]; + this.v3l ^= BUF[6] ^ BUF[22]; + this.v3h ^= BUF[7] ^ BUF[23]; + this.v4l ^= BUF[8] ^ BUF[24]; + this.v4h ^= BUF[9] ^ BUF[25]; + this.v5l ^= BUF[10] ^ BUF[26]; + this.v5h ^= BUF[11] ^ BUF[27]; + this.v6l ^= BUF[12] ^ BUF[28]; + this.v6h ^= BUF[13] ^ BUF[29]; + this.v7l ^= BUF[14] ^ BUF[30]; + this.v7h ^= BUF[15] ^ BUF[31]; + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +exports.blake2b = (0, utils_js_1.wrapConstructorWithOpts)((opts) => new BLAKE2b(opts)); +//# sourceMappingURL=blake2b.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/blake2b.js.map b/node_modules/@noble/hashes/blake2b.js.map new file mode 100644 index 0000000..6cb986b --- /dev/null +++ b/node_modules/@noble/hashes/blake2b.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2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AE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC3D,CAAC;CACF;AAED;;;;GAIG;AACU,QAAA,OAAO,GAAG,IAAA,kCAAuB,EAAqB,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/blake2s.d.ts b/node_modules/@noble/hashes/blake2s.d.ts new file mode 100644 index 0000000..d9dd59b --- /dev/null +++ b/node_modules/@noble/hashes/blake2s.d.ts @@ -0,0 +1,47 @@ +import { BLAKE2, BlakeOpts } from './_blake2.js'; +export declare const IV: Uint32Array; +export declare function compress(s: Uint8Array, offset: number, msg: Uint32Array, rounds: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number): { + v0: number; + v1: number; + v2: number; + v3: number; + v4: number; + v5: number; + v6: number; + v7: number; + v8: number; + v9: number; + v10: number; + v11: number; + v12: number; + v13: number; + v14: number; + v15: number; +}; +declare class BLAKE2s extends BLAKE2 { + private v0; + private v1; + private v2; + private v3; + private v4; + private v5; + private v6; + private v7; + constructor(opts?: BlakeOpts); + protected get(): [number, number, number, number, number, number, number, number]; + protected set(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number): void; + protected compress(msg: Uint32Array, offset: number, isLast: boolean): void; + destroy(): void; +} +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export declare const blake2s: { + (msg: import("./utils.js").Input, opts?: BlakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: BlakeOpts): import("./utils.js").Hash; +}; +export {}; diff --git a/node_modules/@noble/hashes/blake2s.js b/node_modules/@noble/hashes/blake2s.js new file mode 100644 index 0000000..30bf033 --- /dev/null +++ b/node_modules/@noble/hashes/blake2s.js @@ -0,0 +1,124 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.blake2s = exports.compress = exports.IV = void 0; +const _blake2_js_1 = require("./_blake2.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19) +// same as SHA-256 +// prettier-ignore +exports.IV = new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Mixing function G splitted in two halfs +function G1(a, b, c, d, x) { + a = (a + b + x) | 0; + d = (0, utils_js_1.rotr)(d ^ a, 16); + c = (c + d) | 0; + b = (0, utils_js_1.rotr)(b ^ c, 12); + return { a, b, c, d }; +} +function G2(a, b, c, d, x) { + a = (a + b + x) | 0; + d = (0, utils_js_1.rotr)(d ^ a, 8); + c = (c + d) | 0; + b = (0, utils_js_1.rotr)(b ^ c, 7); + return { a, b, c, d }; +} +// prettier-ignore +function compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) { + let j = 0; + for (let i = 0; i < rounds; i++) { + ({ a: v0, b: v4, c: v8, d: v12 } = G1(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v0, b: v4, c: v8, d: v12 } = G2(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G1(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G2(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G1(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G2(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G1(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G2(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G1(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G2(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G1(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G2(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G1(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G2(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G1(v3, v4, v9, v14, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G2(v3, v4, v9, v14, msg[offset + s[j++]])); + } + return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; +} +exports.compress = compress; +class BLAKE2s extends _blake2_js_1.BLAKE2 { + constructor(opts = {}) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, opts, 32, 8, 8); + // Internal state, same as SHA-256 + this.v0 = exports.IV[0] | 0; + this.v1 = exports.IV[1] | 0; + this.v2 = exports.IV[2] | 0; + this.v3 = exports.IV[3] | 0; + this.v4 = exports.IV[4] | 0; + this.v5 = exports.IV[5] | 0; + this.v6 = exports.IV[6] | 0; + this.v7 = exports.IV[7] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.salt)); + this.v4 ^= salt[0]; + this.v5 ^= salt[1]; + } + if (opts.personalization) { + const pers = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.personalization)); + this.v6 ^= pers[0]; + this.v7 ^= pers[1]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set((0, utils_js_1.toBytes)(opts.key)); + this.update(tmp); + } + } + get() { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + set(v0, v1, v2, v3, v4, v5, v6, v7) { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + compress(msg, offset, isLast) { + const { h, l } = _u64_js_1.default.fromBig(BigInt(this.length)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(_blake2_js_1.SIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, exports.IV[0], exports.IV[1], exports.IV[2], exports.IV[3], l ^ exports.IV[4], h ^ exports.IV[5], isLast ? ~exports.IV[6] : exports.IV[6], exports.IV[7]); + this.v0 ^= v0 ^ v8; + this.v1 ^= v1 ^ v9; + this.v2 ^= v2 ^ v10; + this.v3 ^= v3 ^ v11; + this.v4 ^= v4 ^ v12; + this.v5 ^= v5 ^ v13; + this.v6 ^= v6 ^ v14; + this.v7 ^= v7 ^ v15; + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +exports.blake2s = (0, utils_js_1.wrapConstructorWithOpts)((opts) => new BLAKE2s(opts)); +//# sourceMappingURL=blake2s.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/blake2s.js.map b/node_modules/@noble/hashes/blake2s.js.map new file mode 100644 index 0000000..ce187f2 --- /dev/null +++ b/node_modules/@noble/hashes/blake2s.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2s.js","sourceRoot":"","sources":["src/blake2s.ts"],"names":[],"mappings":";;;AAAA,6CAAwD;AACxD,uCAA4B;AAC5B,yCAAyE;AAEzE,iBAAiB;AACjB,yFAAyF;AACzF,kBAAkB;AAClB,kBAAkB;AACL,QAAA,EAAE,GAAG,IAAI,WAAW,CAAC;IAChC,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;CAC/F,CAAC,CAAC;AAEH,0CAA0C;AAC1C,SAAS,EAAE,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS;IAC/D,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IACpB,CAAC,GAAG,IAAA,eAAI,EAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;IACpB,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IAChB,CAAC,GAAG,IAAA,eAAI,EAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;IACpB,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;AACxB,CAAC;AAED,SAAS,EAAE,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS;IAC/D,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IACpB,CAAC,GAAG,IAAA,eAAI,EAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;IACnB,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,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F,CAAC;QACJ,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC;QACnB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC;QACnB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;IACtB,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACtB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IACnC,CAAC;CACF;AAED;;;;GAIG;AACU,QAAA,OAAO,GAAG,IAAA,kCAAuB,EAAqB,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/blake3.d.ts b/node_modules/@noble/hashes/blake3.d.ts new file mode 100644 index 0000000..13894cf --- /dev/null +++ b/node_modules/@noble/hashes/blake3.d.ts @@ -0,0 +1,46 @@ +import { BLAKE2 } from './_blake2.js'; +import { Input, HashXOF } from './utils.js'; +export type Blake3Opts = { + dkLen?: number; + key?: Input; + context?: Input; +}; +declare class BLAKE3 extends BLAKE2 implements HashXOF { + private IV; + private flags; + private state; + private chunkPos; + private chunksDone; + private stack; + private posOut; + private bufferOut32; + private bufferOut; + private chunkOut; + private enableXOF; + constructor(opts?: Blake3Opts, flags?: number); + protected get(): never[]; + protected set(): void; + private b2Compress; + protected compress(buf: Uint32Array, bufPos?: number, isLast?: boolean): void; + _cloneInto(to?: BLAKE3): BLAKE3; + destroy(): void; + private b2CompressOut; + protected finish(): void; + private writeInto; + xofInto(out: Uint8Array): Uint8Array; + xof(bytes: number): Uint8Array; + digestInto(out: Uint8Array): Uint8Array; + digest(): Uint8Array; +} +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +export declare const blake3: { + (msg: Input, opts?: Blake3Opts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: Blake3Opts): HashXOF; +}; +export {}; diff --git a/node_modules/@noble/hashes/blake3.js b/node_modules/@noble/hashes/blake3.js new file mode 100644 index 0000000..52689eb --- /dev/null +++ b/node_modules/@noble/hashes/blake3.js @@ -0,0 +1,240 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.blake3 = void 0; +const _assert_js_1 = require("./_assert.js"); +const _u64_js_1 = require("./_u64.js"); +const _blake2_js_1 = require("./_blake2.js"); +const blake2s_js_1 = require("./blake2s.js"); +const utils_js_1 = require("./utils.js"); +// Flag bitset +var Flags; +(function (Flags) { + Flags[Flags["CHUNK_START"] = 1] = "CHUNK_START"; + Flags[Flags["CHUNK_END"] = 2] = "CHUNK_END"; + Flags[Flags["PARENT"] = 4] = "PARENT"; + Flags[Flags["ROOT"] = 8] = "ROOT"; + Flags[Flags["KEYED_HASH"] = 16] = "KEYED_HASH"; + Flags[Flags["DERIVE_KEY_CONTEXT"] = 32] = "DERIVE_KEY_CONTEXT"; + Flags[Flags["DERIVE_KEY_MATERIAL"] = 64] = "DERIVE_KEY_MATERIAL"; +})(Flags || (Flags = {})); +const SIGMA = (() => { + const Id = Array.from({ length: 16 }, (_, i) => i); + const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]); + const res = []; + for (let i = 0, v = Id; i < 7; i++, v = permute(v)) + res.push(...v); + return Uint8Array.from(res); +})(); +// Why is this so slow? It should be 6x faster than blake2b. +// - There is only 30% reduction in number of rounds from blake2s +// - This function uses tree mode to achive parallelisation via SIMD and threading, +// however in JS we don't have threads and SIMD, so we get only overhead from tree structure +// - It is possible to speed it up via Web Workers, hovewer it will make code singnificantly more +// complicated, which we are trying to avoid, since this library is intended to be used +// for cryptographic purposes. Also, parallelization happens only on chunk level (1024 bytes), +// which won't really benefit small inputs. +class BLAKE3 extends _blake2_js_1.BLAKE2 { + constructor(opts = {}, flags = 0) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, {}, Number.MAX_SAFE_INTEGER, 0, 0); + this.flags = 0 | 0; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + this.stack = []; + // Output + this.posOut = 0; + this.bufferOut32 = new Uint32Array(16); + this.chunkOut = 0; // index of output chunk + this.enableXOF = true; + this.outputLen = opts.dkLen === undefined ? 32 : opts.dkLen; + _assert_js_1.default.number(this.outputLen); + if (opts.key !== undefined && opts.context !== undefined) + throw new Error('Blake3: only key or context can be specified at same time'); + else if (opts.key !== undefined) { + const key = (0, utils_js_1.toBytes)(opts.key).slice(); + if (key.length !== 32) + throw new Error('Blake3: key should be 32 byte'); + this.IV = (0, utils_js_1.u32)(key); + this.flags = flags | Flags.KEYED_HASH; + } + else if (opts.context !== undefined) { + const context_key = new BLAKE3({ dkLen: 32 }, Flags.DERIVE_KEY_CONTEXT) + .update(opts.context) + .digest(); + this.IV = (0, utils_js_1.u32)(context_key); + this.flags = flags | Flags.DERIVE_KEY_MATERIAL; + } + else { + this.IV = blake2s_js_1.IV.slice(); + this.flags = flags; + } + this.state = this.IV.slice(); + this.bufferOut = (0, utils_js_1.u8)(this.bufferOut32); + } + // Unused + get() { + return []; + } + set() { } + b2Compress(counter, flags, buf, bufPos = 0) { + const { state: s, pos } = this; + const { h, l } = _u64_js_1.default.fromBig(BigInt(counter), true); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = (0, blake2s_js_1.compress)(SIGMA, bufPos, buf, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], blake2s_js_1.IV[0], blake2s_js_1.IV[1], blake2s_js_1.IV[2], blake2s_js_1.IV[3], h, l, pos, flags); + s[0] = v0 ^ v8; + s[1] = v1 ^ v9; + s[2] = v2 ^ v10; + s[3] = v3 ^ v11; + s[4] = v4 ^ v12; + s[5] = v5 ^ v13; + s[6] = v6 ^ v14; + s[7] = v7 ^ v15; + } + compress(buf, bufPos = 0, isLast = false) { + // Compress last block + let flags = this.flags; + if (!this.chunkPos) + flags |= Flags.CHUNK_START; + if (this.chunkPos === 15 || isLast) + flags |= Flags.CHUNK_END; + if (!isLast) + this.pos = this.blockLen; + this.b2Compress(this.chunksDone, flags, buf, bufPos); + this.chunkPos += 1; + // If current block is last in chunk (16 blocks), then compress chunks + if (this.chunkPos === 16 || isLast) { + let chunk = this.state; + this.state = this.IV.slice(); + // If not the last one, compress only when there are trailing zeros in chunk counter + // chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed. + // 1 (001) - leaf not finished (just push current chunk to stack) + // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back) + // 3 (011) - last leaf not finished + // 4 (100) - leafs finished at depth=1 and depth=2 + for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) { + if (!(last = this.stack.pop())) + break; + this.buffer32.set(last, 0); + this.buffer32.set(chunk, 8); + this.pos = this.blockLen; + this.b2Compress(0, this.flags | Flags.PARENT, this.buffer32, 0); + chunk = this.state; + this.state = this.IV.slice(); + } + this.chunksDone++; + this.chunkPos = 0; + this.stack.push(chunk); + } + this.pos = 0; + } + _cloneInto(to) { + to = super._cloneInto(to); + const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this; + to.state.set(state.slice()); + to.stack = stack.map((i) => Uint32Array.from(i)); + to.IV.set(IV); + to.flags = flags; + to.chunkPos = chunkPos; + to.chunksDone = chunksDone; + to.posOut = posOut; + to.chunkOut = chunkOut; + to.enableXOF = this.enableXOF; + to.bufferOut32.set(this.bufferOut32); + return to; + } + destroy() { + this.destroyed = true; + this.state.fill(0); + this.buffer32.fill(0); + this.IV.fill(0); + this.bufferOut32.fill(0); + for (let i of this.stack) + i.fill(0); + } + // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8) + b2CompressOut() { + const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this; + const { h, l } = _u64_js_1.default.fromBig(BigInt(this.chunkOut++)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = (0, blake2s_js_1.compress)(SIGMA, 0, buffer32, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], blake2s_js_1.IV[0], blake2s_js_1.IV[1], blake2s_js_1.IV[2], blake2s_js_1.IV[3], l, h, pos, flags); + out32[0] = v0 ^ v8; + out32[1] = v1 ^ v9; + out32[2] = v2 ^ v10; + out32[3] = v3 ^ v11; + out32[4] = v4 ^ v12; + out32[5] = v5 ^ v13; + out32[6] = v6 ^ v14; + out32[7] = v7 ^ v15; + out32[8] = s[0] ^ v8; + out32[9] = s[1] ^ v9; + out32[10] = s[2] ^ v10; + out32[11] = s[3] ^ v11; + out32[12] = s[4] ^ v12; + out32[13] = s[5] ^ v13; + out32[14] = s[6] ^ v14; + out32[15] = s[7] ^ v15; + this.posOut = 0; + } + finish() { + if (this.finished) + return; + this.finished = true; + // Padding + this.buffer.fill(0, this.pos); + // Process last chunk + let flags = this.flags | Flags.ROOT; + if (this.stack.length) { + flags |= Flags.PARENT; + this.compress(this.buffer32, 0, true); + this.chunksDone = 0; + this.pos = this.blockLen; + } + else { + flags |= (!this.chunkPos ? Flags.CHUNK_START : 0) | Flags.CHUNK_END; + } + this.flags = flags; + this.b2CompressOut(); + } + writeInto(out) { + _assert_js_1.default.exists(this, false); + _assert_js_1.default.bytes(out); + this.finish(); + const { blockLen, bufferOut } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.b2CompressOut(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + if (!this.enableXOF) + throw new Error('XOF is not possible after digest call'); + return this.writeInto(out); + } + xof(bytes) { + _assert_js_1.default.number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + _assert_js_1.default.output(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.enableXOF = false; + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } +} +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +exports.blake3 = (0, utils_js_1.wrapXOFConstructorWithOpts)((opts) => new BLAKE3(opts)); +//# sourceMappingURL=blake3.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/blake3.js.map b/node_modules/@noble/hashes/blake3.js.map new file mode 100644 index 0000000..c7f09ac --- /dev/null +++ b/node_modules/@noble/hashes/blake3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake3.js","sourceRoot":"","sources":["src/blake3.ts"],"names":[],"mappings":";;;AAAA,6CAAkC;AAClC,uCAA4B;AAC5B,6CAAsC;AACtC,6CAA4C;AAC5C,yCAA0F;AAE1F,cAAc;AACd,IAAK,KAQJ;AARD,WAAK,KAAK;IACR,+CAAoB,CAAA;IACpB,2CAAkB,CAAA;IAClB,qCAAe,CAAA;IACf,iCAAa,CAAA;IACb,8CAAmB,CAAA;IACnB,8DAA2B,CAAA;IAC3B,gEAA4B,CAAA;AAC9B,CAAC,EARI,KAAK,KAAL,KAAK,QAQT;AAED,MAAM,KAAK,GAAe,CAAC,GAAG,EAAE;IAC9B,MAAM,EAAE,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE,M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C;IACb,CAAC;IACD,OAAO,CAAC,GAAe;QACrB,IAAI,CAAC,IAAI,CAAC,SAAS;YAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;QAC9E,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;IAC7B,CAAC;IACD,GAAG,CAAC,KAAa;QACf,oBAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACrB,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;IAC7C,CAAC;IACD,UAAU,CAAC,GAAe;QACxB,oBAAM,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QACzB,IAAI,IAAI,CAAC,QAAQ;YAAE,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;QAClE,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;QACvB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;QACpB,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,OAAO,GAAG,CAAC;IACb,CAAC;IACD,MAAM;QACJ,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IACzD,CAAC;CACF;AAED;;;;GAIG;AACU,QAAA,MAAM,GAAG,IAAA,qCAA0B,EAAqB,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/crypto.d.ts b/node_modules/@noble/hashes/crypto.d.ts new file mode 100644 index 0000000..cebbcd1 --- /dev/null +++ b/node_modules/@noble/hashes/crypto.d.ts @@ -0,0 +1 @@ +export declare const crypto: any; diff --git a/node_modules/@noble/hashes/crypto.js b/node_modules/@noble/hashes/crypto.js new file mode 100644 index 0000000..8226391 --- /dev/null +++ b/node_modules/@noble/hashes/crypto.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.crypto = void 0; +exports.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; +//# sourceMappingURL=crypto.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/crypto.js.map b/node_modules/@noble/hashes/crypto.js.map new file mode 100644 index 0000000..9f794e2 --- /dev/null +++ b/node_modules/@noble/hashes/crypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.js","sourceRoot":"","sources":["src/crypto.ts"],"names":[],"mappings":";;;AAGa,QAAA,MAAM,GACjB,OAAO,UAAU,KAAK,QAAQ,IAAI,QAAQ,IAAI,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/cryptoNode.d.ts b/node_modules/@noble/hashes/cryptoNode.d.ts new file mode 100644 index 0000000..cebbcd1 --- /dev/null +++ b/node_modules/@noble/hashes/cryptoNode.d.ts @@ -0,0 +1 @@ +export declare const crypto: any; diff --git a/node_modules/@noble/hashes/cryptoNode.js b/node_modules/@noble/hashes/cryptoNode.js new file mode 100644 index 0000000..a88676d --- /dev/null +++ b/node_modules/@noble/hashes/cryptoNode.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.crypto = void 0; +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +// The file will throw on node.js 14 and earlier. +// @ts-ignore +const nc = require("node:crypto"); +exports.crypto = nc && typeof nc === 'object' && 'webcrypto' in nc ? nc.webcrypto : undefined; +//# sourceMappingURL=cryptoNode.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/cryptoNode.js.map b/node_modules/@noble/hashes/cryptoNode.js.map new file mode 100644 index 0000000..9287d27 --- /dev/null +++ b/node_modules/@noble/hashes/cryptoNode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cryptoNode.js","sourceRoot":"","sources":["src/cryptoNode.ts"],"names":[],"mappings":";;;AAAA,oFAAoF;AACpF,4BAA4B;AAC5B,iDAAiD;AACjD,aAAa;AACb,kCAAkC;AACrB,QAAA,MAAM,GACjB,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,WAAW,IAAI,EAAE,CAAC,CAAC,CAAE,EAAE,CAAC,SAAiB,CAAC,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/eskdf.d.ts b/node_modules/@noble/hashes/eskdf.d.ts new file mode 100644 index 0000000..f0fc54d --- /dev/null +++ b/node_modules/@noble/hashes/eskdf.d.ts @@ -0,0 +1,46 @@ +export declare function scrypt(password: string, salt: string): Uint8Array; +export declare function pbkdf2(password: string, salt: string): Uint8Array; +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +export declare function deriveMainSeed(username: string, password: string): Uint8Array; +type AccountID = number | string; +type OptsLength = { + keyLength: number; +}; +type OptsMod = { + modulus: bigint; +}; +type KeyOpts = undefined | OptsLength | OptsMod; +type ESKDF = Promise Uint8Array; + /** + * Deletes the main seed from eskdf instance + */ + expire: () => void; + /** + * Account fingerprint + */ + fingerprint: string; +}>>; +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +export declare function eskdf(username: string, password: string): ESKDF; +export {}; diff --git a/node_modules/@noble/hashes/eskdf.js b/node_modules/@noble/hashes/eskdf.js new file mode 100644 index 0000000..bc622b6 --- /dev/null +++ b/node_modules/@noble/hashes/eskdf.js @@ -0,0 +1,162 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.eskdf = exports.deriveMainSeed = exports.pbkdf2 = exports.scrypt = void 0; +const _assert_js_1 = require("./_assert.js"); +const hkdf_js_1 = require("./hkdf.js"); +const sha256_js_1 = require("./sha256.js"); +const pbkdf2_js_1 = require("./pbkdf2.js"); +const scrypt_js_1 = require("./scrypt.js"); +const utils_js_1 = require("./utils.js"); +// A tiny KDF for various applications like AES key-gen. +// Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure". +// Which is good enough: assume sha2-256 retained preimage resistance. +const SCRYPT_FACTOR = 2 ** 19; +const PBKDF2_FACTOR = 2 ** 17; +// Scrypt KDF +function scrypt(password, salt) { + return (0, scrypt_js_1.scrypt)(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 }); +} +exports.scrypt = scrypt; +// PBKDF2-HMAC-SHA256 +function pbkdf2(password, salt) { + return (0, pbkdf2_js_1.pbkdf2)(sha256_js_1.sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 }); +} +exports.pbkdf2 = pbkdf2; +// Combines two 32-byte byte arrays +function xor32(a, b) { + (0, _assert_js_1.bytes)(a, 32); + (0, _assert_js_1.bytes)(b, 32); + const arr = new Uint8Array(32); + for (let i = 0; i < 32; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} +function strHasLength(str, min, max) { + return typeof str === 'string' && str.length >= min && str.length <= max; +} +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +function deriveMainSeed(username, password) { + if (!strHasLength(username, 8, 255)) + throw new Error('invalid username'); + if (!strHasLength(password, 8, 255)) + throw new Error('invalid password'); + const scr = scrypt(password + '\u{1}', username + '\u{1}'); + const pbk = pbkdf2(password + '\u{2}', username + '\u{2}'); + const res = xor32(scr, pbk); + scr.fill(0); + pbk.fill(0); + return res; +} +exports.deriveMainSeed = deriveMainSeed; +/** + * Converts protocol & accountId pair to HKDF salt & info params. + */ +function getSaltInfo(protocol, accountId = 0) { + // Note that length here also repeats two lines below + // We do an additional length check here to reduce the scope of DoS attacks + if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) { + throw new Error('invalid protocol'); + } + // Allow string account ids for some protocols + const allowsStr = /^password\d{0,3}|ssh|tor|file$/.test(protocol); + let salt; // Extract salt. Default is undefined. + if (typeof accountId === 'string') { + if (!allowsStr) + throw new Error('accountId must be a number'); + if (!strHasLength(accountId, 1, 255)) + throw new Error('accountId must be valid string'); + salt = (0, utils_js_1.toBytes)(accountId); + } + else if (Number.isSafeInteger(accountId)) { + if (accountId < 0 || accountId > 2 ** 32 - 1) + throw new Error('invalid accountId'); + // Convert to Big Endian Uint32 + salt = new Uint8Array(4); + (0, utils_js_1.createView)(salt).setUint32(0, accountId, false); + } + else { + throw new Error(`accountId must be a number${allowsStr ? ' or string' : ''}`); + } + const info = (0, utils_js_1.toBytes)(protocol); + return { salt, info }; +} +function countBytes(num) { + if (typeof num !== 'bigint' || num <= BigInt(128)) + throw new Error('invalid number'); + return Math.ceil(num.toString(2).length / 8); +} +/** + * Parses keyLength and modulus options to extract length of result key. + * If modulus is used, adds 64 bits to it as per FIPS 186 B.4.1 to combat modulo bias. + */ +function getKeyLength(options) { + if (!options || typeof options !== 'object') + return 32; + const hasLen = 'keyLength' in options; + const hasMod = 'modulus' in options; + if (hasLen && hasMod) + throw new Error('cannot combine keyLength and modulus options'); + if (!hasLen && !hasMod) + throw new Error('must have either keyLength or modulus option'); + // FIPS 186 B.4.1 requires at least 64 more bits + const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength; + if (!(typeof l === 'number' && l >= 16 && l <= 8192)) + throw new Error('invalid keyLength'); + return l; +} +/** + * Converts key to bigint and divides it by modulus. Big Endian. + * Implements FIPS 186 B.4.1, which removes 0 and modulo bias from output. + */ +function modReduceKey(key, modulus) { + const _1 = BigInt(1); + const num = BigInt('0x' + (0, utils_js_1.bytesToHex)(key)); // check for ui8a, then bytesToNumber() + const res = (num % (modulus - _1)) + _1; // Remove 0 from output + if (res < _1) + throw new Error('expected positive number'); // Guard against bad values + const len = key.length - 8; // FIPS requires 64 more bits = 8 bytes + const hex = res.toString(16).padStart(len * 2, '0'); // numberToHex() + const bytes = (0, utils_js_1.hexToBytes)(hex); + if (bytes.length !== len) + throw new Error('invalid length of result key'); + return bytes; +} +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +async function eskdf(username, password) { + // We are using closure + object instead of class because + // we want to make `seed` non-accessible for any external function. + let seed = deriveMainSeed(username, password); + function deriveCK(protocol, accountId = 0, options) { + (0, _assert_js_1.bytes)(seed, 32); + const { salt, info } = getSaltInfo(protocol, accountId); // validate protocol & accountId + const keyLength = getKeyLength(options); // validate options + const key = (0, hkdf_js_1.hkdf)(sha256_js_1.sha256, seed, salt, info, keyLength); + // Modulus has already been validated + return options && 'modulus' in options ? modReduceKey(key, options.modulus) : key; + } + function expire() { + if (seed) + seed.fill(1); + seed = undefined; + } + // prettier-ignore + const fingerprint = Array.from(deriveCK('fingerprint', 0)) + .slice(0, 6) + .map((char) => char.toString(16).padStart(2, '0').toUpperCase()) + .join(':'); + return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint }); +} +exports.eskdf = eskdf; +//# sourceMappingURL=eskdf.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/eskdf.js.map b/node_modules/@noble/hashes/eskdf.js.map new file mode 100644 index 0000000..70c49e9 --- /dev/null +++ b/node_modules/@noble/hashes/eskdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eskdf.js","sourceRoot":"","sources":["src/eskdf.ts"],"names":[],"mappings":";;;AAAA,6CAAoD;AACpD,uCAAiC;AACjC,2CAAqC;AACrC,2CAAgD;AAChD,2CAAgD;AAChD,yCAAyE;AAEzE,wDAAwD;AACxD,gFAAgF;AAChF,sEAAsE;AAEtE,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,CAAC;AAC9B,MAAM,aAAa,GAAG,CAAC,IAAI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IACb,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC,CAAC;AAC1E,CAAC;AAvBD,sBAuBC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/_assert.js b/node_modules/@noble/hashes/esm/_assert.js new file mode 100644 index 0000000..73a5c37 --- /dev/null +++ b/node_modules/@noble/hashes/esm/_assert.js @@ -0,0 +1,43 @@ +export function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); +} +export function bool(b) { + if (typeof b !== 'boolean') + throw new Error(`Expected boolean, not ${b}`); +} +export function bytes(b, ...lengths) { + if (!(b instanceof Uint8Array)) + throw new Error('Expected Uint8Array'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} +export function hash(hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(hash.outputLen); + number(hash.blockLen); +} +export function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +export function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} +const assert = { + number, + bool, + bytes, + hash, + exists, + output, +}; +export default assert; +//# sourceMappingURL=_assert.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/_assert.js.map b/node_modules/@noble/hashes/esm/_assert.js.map new file mode 100644 index 0000000..b36620a --- /dev/null +++ b/node_modules/@noble/hashes/esm/_assert.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_assert.js","sourceRoot":"","sources":["../src/_assert.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,MAAM,CAAC,CAAS;IAC9B,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,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,GAAG,QAAQ,CAAC,SAAS,CAAC;IAC/B,IAAI,GAAG,CAAC,MAAM,GAAG,GAAG,EAAE;QACpB,MAAM,IAAI,KAAK,CAAC,yDAAyD,GAAG,EAAE,CAAC,CAAC;KACjF;AACH,CAAC;AAED,MAAM,MAAM,GAAG;IACb,MAAM;IACN,IAAI;IACJ,KAAK;IACL,IAAI;IACJ,MAAM;IACN,MAAM;CACP,CAAC;AAEF,eAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/_blake2.js b/node_modules/@noble/hashes/esm/_blake2.js new file mode 100644 index 0000000..42b621f --- /dev/null +++ b/node_modules/@noble/hashes/esm/_blake2.js @@ -0,0 +1,107 @@ +import assert from './_assert.js'; +import { Hash, toBytes, u32 } from './utils.js'; +// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. +// prettier-ignore +export const SIGMA = new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, +]); +export class BLAKE2 extends Hash { + constructor(blockLen, outputLen, opts = {}, keyLen, saltLen, persLen) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.length = 0; + this.pos = 0; + this.finished = false; + this.destroyed = false; + assert.number(blockLen); + assert.number(outputLen); + assert.number(keyLen); + if (outputLen < 0 || outputLen > keyLen) + throw new Error('outputLen bigger than keyLen'); + if (opts.key !== undefined && (opts.key.length < 1 || opts.key.length > keyLen)) + throw new Error(`key must be up 1..${keyLen} byte long or undefined`); + if (opts.salt !== undefined && opts.salt.length !== saltLen) + throw new Error(`salt must be ${saltLen} byte long or undefined`); + if (opts.personalization !== undefined && opts.personalization.length !== persLen) + throw new Error(`personalization must be ${persLen} byte long or undefined`); + this.buffer32 = u32((this.buffer = new Uint8Array(blockLen))); + } + update(data) { + assert.exists(this); + // Main difference with other hashes: there is flag for last block, + // so we cannot process current block before we know that there + // is the next one. This significantly complicates logic and reduces ability + // to do zero-copy processing + const { blockLen, buffer, buffer32 } = this; + data = toBytes(data); + const len = data.length; + const offset = data.byteOffset; + const buf = data.buffer; + for (let pos = 0; pos < len;) { + // If buffer is full and we still have input (don't process last block, same as blake2s) + if (this.pos === blockLen) { + this.compress(buffer32, 0, false); + this.pos = 0; + } + const take = Math.min(blockLen - this.pos, len - pos); + const dataOffset = offset + pos; + // full block && aligned to 4 bytes && not last in input + if (take === blockLen && !(dataOffset % 4) && pos + take < len) { + const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4)); + for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) { + this.length += blockLen; + this.compress(data32, pos32, false); + } + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + this.length += take; + pos += take; + } + return this; + } + digestInto(out) { + assert.exists(this); + assert.output(out, this); + const { pos, buffer32 } = this; + this.finished = true; + // Padding + this.buffer.subarray(pos).fill(0); + this.compress(buffer32, 0, true); + const out32 = u32(out); + this.get().forEach((v, i) => (out32[i] = v)); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + const { buffer, length, finished, destroyed, outputLen, pos } = this; + to || (to = new this.constructor({ dkLen: outputLen })); + to.set(...this.get()); + to.length = length; + to.finished = finished; + to.destroyed = destroyed; + to.outputLen = outputLen; + to.buffer.set(buffer); + to.pos = pos; + return to; + } +} +//# sourceMappingURL=_blake2.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/_blake2.js.map b/node_modules/@noble/hashes/esm/_blake2.js.map new file mode 100644 index 0000000..5fafed2 --- /dev/null +++ b/node_modules/@noble/hashes/esm/_blake2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_blake2.js","sourceRoot":"","sources":["../src/_blake2.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,EAAE,IAAI,EAAS,OAAO,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AACvD,gGAAgG;AAChG,kBAAkB;AAClB,MAAM,CAAC,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC;IAClC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;IACpD,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAA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AE,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACtB,EAAE,CAAC,GAAG,GAAG,GAAG,CAAC;QACb,OAAO,EAAE,CAAC;IACZ,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/_sha2.js b/node_modules/@noble/hashes/esm/_sha2.js new file mode 100644 index 0000000..4d1bf27 --- /dev/null +++ b/node_modules/@noble/hashes/esm/_sha2.js @@ -0,0 +1,114 @@ +import assert from './_assert.js'; +import { Hash, createView, toBytes } from './utils.js'; +// Polyfill for Safari 14 +function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +// Base SHA2 class (RFC 6234) +export class SHA2 extends Hash { + constructor(blockLen, outputLen, padOffset, isLE) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + assert.exists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input, cast it to view and process + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + assert.exists(this); + assert.output(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + this.buffer.subarray(pos).fill(0); + // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) + buffer[i] = 0; + // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + if (len % 4) + throw new Error('_sha2: outputLen should be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } +} +//# sourceMappingURL=_sha2.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/_sha2.js.map b/node_modules/@noble/hashes/esm/_sha2.js.map new file mode 100644 index 0000000..c9a4b7e --- /dev/null +++ b/node_modules/@noble/hashes/esm/_sha2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_sha2.js","sourceRoot":"","sources":["../src/_sha2.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,UAAU,EAAS,OAAO,EAAE,MAA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Q;YAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC7C,OAAO,EAAE,CAAC;IACZ,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/_u64.js b/node_modules/@noble/hashes/esm/_u64.js new file mode 100644 index 0000000..40c88ac --- /dev/null +++ b/node_modules/@noble/hashes/esm/_u64.js @@ -0,0 +1,61 @@ +const U32_MASK64 = BigInt(2 ** 32 - 1); +const _32n = BigInt(32); +// We are not using BigUint64Array, because they are extremely slow as per 2022 +export function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +export function split(lst, le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +export const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +// for Shift in [0, 32) +const shrSH = (h, l, s) => h >>> s; +const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in [1, 32) +const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); +const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); +const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (h, l) => l; +const rotr32L = (h, l) => h; +// Left rotate for Shift in [1, 32) +const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); +const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); +const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +// Removing "export" has 5% perf penalty -_- +export function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +// Addition with more than 2 elements +const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +export default u64; +//# sourceMappingURL=_u64.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/_u64.js.map b/node_modules/@noble/hashes/esm/_u64.js.map new file mode 100644 index 0000000..8baa59c --- /dev/null +++ b/node_modules/@noble/hashes/esm/_u64.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_u64.js","sourceRoot":"","sources":["../src/_u64.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,GAAG,MAAM,CAAC,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC;AACvC,MAAM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AW,EAAE,EAAU,EAAE,EAAU,EAAE,EAAU,EAAE,EAAU,EAAE,EAAU,EAAE,EAAE,CACxF,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;AAEvD,kBAAkB;AAClB,MAAM,GAAG,GAAG;IACV,OAAO,EAAE,KAAK,EAAE,KAAK;IACrB,KAAK,EAAE,KAAK;IACZ,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9B,OAAO,EAAE,OAAO;IAChB,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9B,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK;CAC9C,CAAC;AACF,eAAe,GAAG,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/argon2.js b/node_modules/@noble/hashes/esm/argon2.js new file mode 100644 index 0000000..73f8385 --- /dev/null +++ b/node_modules/@noble/hashes/esm/argon2.js @@ -0,0 +1,304 @@ +import assert from './_assert.js'; +import { toBytes, u8, u32 } from './utils.js'; +import { blake2b } from './blake2b.js'; +import u64 from './_u64.js'; +// Experimental Argon2 RFC 9106 implementation. It may be removed at any time. +var Types; +(function (Types) { + Types[Types["Argond2d"] = 0] = "Argond2d"; + Types[Types["Argon2i"] = 1] = "Argon2i"; + Types[Types["Argon2id"] = 2] = "Argon2id"; +})(Types || (Types = {})); +const ARGON2_SYNC_POINTS = 4; +const toBytesOptional = (buf) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); +function mul(a, b) { + const aL = a & 0xffff; + const aH = a >>> 16; + const bL = b & 0xffff; + const bH = b >>> 16; + const ll = Math.imul(aL, bL); + const hl = Math.imul(aH, bL); + const lh = Math.imul(aL, bH); + const hh = Math.imul(aH, bH); + const BUF = ((ll >>> 16) + (hl & 0xffff) + lh) | 0; + const h = ((hl >>> 16) + (BUF >>> 16) + hh) | 0; + return { h, l: (BUF << 16) | (ll & 0xffff) }; +} +function relPos(areaSize, relativePos) { + // areaSize - 1 - ((areaSize * ((relativePos ** 2) >>> 32)) >>> 32) + return areaSize - 1 - mul(areaSize, mul(relativePos, relativePos).h).h; +} +function mul2(a, b) { + // 2 * a * b (via shifts) + const { h, l } = mul(a, b); + return { h: ((h << 1) | (l >>> 31)) & 4294967295, l: (l << 1) & 4294967295 }; +} +function blamka(Ah, Al, Bh, Bl) { + const { h: Ch, l: Cl } = mul2(Al, Bl); + // A + B + (2 * A * B) + const Rll = u64.add3L(Al, Bl, Cl); + return { h: u64.add3H(Rll, Ah, Bh, Ch), l: Rll | 0 }; +} +// Temporary block buffer +const BUF = new Uint32Array(256); +function G(a, b, c, d) { + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) }); + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +// prettier-ignore +function P(v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15) { + G(v00, v04, v08, v12); + G(v01, v05, v09, v13); + G(v02, v06, v10, v14); + G(v03, v07, v11, v15); + G(v00, v05, v10, v15); + G(v01, v06, v11, v12); + G(v02, v07, v08, v13); + G(v03, v04, v09, v14); +} +function block(x, xPos, yPos, outPos, needXor) { + for (let i = 0; i < 256; i++) + BUF[i] = x[xPos + i] ^ x[yPos + i]; + // columns + for (let i = 0; i < 128; i += 16) { + // prettier-ignore + P(i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15); + } + // rows + for (let i = 0; i < 16; i += 2) { + // prettier-ignore + P(i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113); + } + if (needXor) + for (let i = 0; i < 256; i++) + x[outPos + i] ^= BUF[i] ^ x[xPos + i] ^ x[yPos + i]; + else + for (let i = 0; i < 256; i++) + x[outPos + i] = BUF[i] ^ x[xPos + i] ^ x[yPos + i]; +} +// Variable-Length Hash Function H' +function Hp(A, dkLen) { + const A8 = u8(A); + const T = new Uint32Array(1); + const T8 = u8(T); + T[0] = dkLen; + // Fast path + if (dkLen <= 64) + return blake2b.create({ dkLen }).update(T8).update(A8).digest(); + const out = new Uint8Array(dkLen); + let V = blake2b.create({}).update(T8).update(A8).digest(); + let pos = 0; + // First block + out.set(V.subarray(0, 32)); + pos += 32; + // Rest blocks + for (; dkLen - pos > 64; pos += 32) + out.set((V = blake2b(V)).subarray(0, 32), pos); + // Last block + out.set(blake2b(V, { dkLen: dkLen - pos }), pos); + return u32(out); +} +function indexAlpha(r, s, laneLen, segmentLen, index, randL, sameLane = false) { + let area; + if (0 == r) { + if (0 == s) + area = index - 1; + else if (sameLane) + area = s * segmentLen + index - 1; + else + area = s * segmentLen + (index == 0 ? -1 : 0); + } + else if (sameLane) + area = laneLen - segmentLen + index - 1; + else + area = laneLen - segmentLen + (index == 0 ? -1 : 0); + const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0; + const rel = relPos(area, randL); + // NOTE: check about overflows here + // absPos = (startPos + relPos) % laneLength; + return (startPos + rel) % laneLen; +} +function argon2Init(type, password, salt, opts) { + password = toBytes(password); + salt = toBytes(salt); + let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress } = { + ...opts, + version: opts.version || 0x13, + dkLen: opts.dkLen || 32, + maxmem: 2 ** 32, + }; + // Validation + assert.number(p); + assert.number(dkLen); + assert.number(m); + assert.number(t); + assert.number(version); + if (dkLen < 4 || dkLen >= 2 ** 32) + throw new Error('Argon2: dkLen should be at least 4 bytes'); + if (dkLen < 1 || p >= 2 ** 32) + throw new Error('Argon2: p (paralllelism) should be at least 1'); + if (dkLen < 1 || p >= 2 ** 32) + throw new Error('Argon2: t (iterations) should be at least 1'); + if (m < 8 * p) + throw new Error(`Argon2: memory should be at least 8*p bytes`); + if (version !== 16 && version !== 19) + throw new Error(`Argon2: unknown version=${version}`); + password = toBytes(password); + if (password.length < 0 || password.length >= 2 ** 32) + throw new Error('Argon2: password should be less than 4 GB'); + salt = toBytes(salt); + if (salt.length < 8) + throw new Error('Argon2: salt should be at least 8 bytes'); + key = toBytesOptional(key); + personalization = toBytesOptional(personalization); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + // Params + const lanes = p; + // m' = 4 * p * floor (m / 4p) + const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p)); + //q = m' / p columns + const laneLen = Math.floor(mP / p); + const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS); + // H0 + const h = blake2b.create({}); + const BUF = new Uint32Array(1); + const BUF8 = u8(BUF); + for (const i of [p, dkLen, m, t, version, type]) { + if (i < 0 || i >= 2 ** 32) + throw new Error(`Argon2: wrong parameter=${i}, expected uint32`); + BUF[0] = i; + h.update(BUF8); + } + for (let i of [password, salt, key, personalization]) { + BUF[0] = i.length; + h.update(BUF8).update(i); + } + const H0 = new Uint32Array(18); + const H0_8 = u8(H0); + h.digestInto(H0_8); + // 256 u32 = 1024 (BLOCK_SIZE) + const memUsed = mP * 256; + if (memUsed < 0 || memUsed >= 2 ** 32 || memUsed > maxmem) { + throw new Error(`Argon2: wrong params (memUsed=${memUsed} maxmem=${maxmem}), should be less than 2**32`); + } + const B = new Uint32Array(memUsed); + // Fill first blocks + for (let l = 0; l < p; l++) { + const i = 256 * laneLen * l; + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + H0[17] = l; + H0[16] = 0; + B.set(Hp(H0, 1024), i); + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + H0[16] = 1; + B.set(Hp(H0, 1024), i + 256); + } + let perBlock = () => { }; + if (onProgress) { + const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlock / 10000), 1); + let blockCnt = 0; + perBlock = () => { + blockCnt++; + if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock)) + onProgress(blockCnt / totalBlock); + }; + } + return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock }; +} +function argon2Output(B, p, laneLen, dkLen) { + const B_final = new Uint32Array(256); + for (let l = 0; l < p; l++) + for (let j = 0; j < 256; j++) + B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j]; + return u8(Hp(B_final, dkLen)); +} +function processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor) { + if (offset % laneLen) + prev = offset - 1; + let randL, randH; + if (dataIndependent) { + if (index % 128 === 0) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + randL = address[2 * (index % 128)]; + randH = address[2 * (index % 128) + 1]; + } + else { + const T = 256 * prev; + randL = B[T]; + randH = B[T + 1]; + } + // address block + const refLane = r === 0 && s === 0 ? l : randH % lanes; + const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l); + const refBlock = laneLen * refLane + refPos; + // B[i][j] = G(B[i][j-1], B[l][z]) + block(B, 256 * prev, 256 * refBlock, offset * 256, needXor); +} +function argon2(type, password, salt, opts) { + const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init(type, password, salt, opts); + // Pre-loop setup + // [address, input, zero_block] format so we can pass single U32 to block function + const address = new Uint32Array(3 * 256); + address[256 + 6] = mP; + address[256 + 8] = t; + address[256 + 10] = type; + for (let r = 0; r < t; r++) { + const needXor = r !== 0 && version === 0x13; + address[256 + 0] = r; + for (let s = 0; s < ARGON2_SYNC_POINTS; s++) { + address[256 + 4] = s; + const dataIndependent = type == Types.Argon2i || (type == Types.Argon2id && r === 0 && s < 2); + for (let l = 0; l < p; l++) { + address[256 + 2] = l; + address[256 + 12] = 0; + let startPos = 0; + if (r === 0 && s === 0) { + startPos = 2; + if (dataIndependent) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + } + // current block postion + let offset = l * laneLen + s * segmentLen + startPos; + // previous block position + let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1; + for (let index = startPos; index < segmentLen; index++, offset++, prev++) { + perBlock(); + processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor); + } + } + } + } + return argon2Output(B, p, laneLen, dkLen); +} +export const argon2d = (password, salt, opts) => argon2(Types.Argond2d, password, salt, opts); +export const argon2i = (password, salt, opts) => argon2(Types.Argon2i, password, salt, opts); +export const argon2id = (password, salt, opts) => argon2(Types.Argon2id, password, salt, opts); +//# sourceMappingURL=argon2.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/argon2.js.map b/node_modules/@noble/hashes/esm/argon2.js.map new file mode 100644 index 0000000..2a46f5a --- /dev/null +++ b/node_modules/@noble/hashes/esm/argon2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"argon2.js","sourceRoot":"","sources":["../src/argon2.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,EAAS,OAAO,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,GAAG,MAAM,WAAW,CAAC;AAE5B,8EAA8E;AAC9E,IAAK,KAIJ;AAJD,WAAK,KAAK;IACR,yCAAY,CAAA;IACZ,uCAAW,CAAA;IACX,yCAAY,CAAA;AACd,CAAC,EAJI,KAAK,KAAL,KAAK,QAIT;AAED,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAE7B,MAAM,eAAe,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,CAAC,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC;AAEjG,SAAS,GAAG,CAAC,CAAS,EAAE,CAAS;IAC/B,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,CAAC;IACtB,MAAM,EAAE,GAAG,CAAC,KAAK,EAAE,CAAC;IACpB,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,CAAC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AQ,CAAC;gBACrD,0BAA0B;gBAC1B,IAAI,IAAI,GAAG,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,OAAO,GAAG,CAAC,CAAC;gBAChE,KAAK,IAAI,KAAK,GAAG,QAAQ,EAAE,KAAK,GAAG,UAAU,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,EAAE;oBACxE,QAAQ,EAAE,CAAC;oBACX,YAAY,CACV,CAAC,EACD,OAAO,EACP,CAAC,EACD,CAAC,EACD,CAAC,EACD,KAAK,EACL,OAAO,EACP,UAAU,EACV,KAAK,EACL,MAAM,EACN,IAAI,EACJ,eAAe,EACf,OAAO,CACR,CAAC;iBACH;aACF;SACF;KACF;IACD,OAAO,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;AAC5C,CAAC;AAED,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACvE,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAC/C,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACvE,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAC9C,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACxE,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/blake2b.js b/node_modules/@noble/hashes/esm/blake2b.js new file mode 100644 index 0000000..a52871c --- /dev/null +++ b/node_modules/@noble/hashes/esm/blake2b.js @@ -0,0 +1,189 @@ +import { BLAKE2, SIGMA } from './_blake2.js'; +import u64 from './_u64.js'; +import { toBytes, u32, wrapConstructorWithOpts } from './utils.js'; +// Same as SHA-512 but LE +// prettier-ignore +const IV = new Uint32Array([ + 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, + 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19 +]); +// Temporary buffer +const BUF = new Uint32Array(32); +// Mixing function G splitted in two halfs +function G1(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 32) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 24) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +function G2(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 16) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 63) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +class BLAKE2b extends BLAKE2 { + constructor(opts = {}) { + super(128, opts.dkLen === undefined ? 64 : opts.dkLen, opts, 64, 16, 16); + // Same as SHA-512, but LE + this.v0l = IV[0] | 0; + this.v0h = IV[1] | 0; + this.v1l = IV[2] | 0; + this.v1h = IV[3] | 0; + this.v2l = IV[4] | 0; + this.v2h = IV[5] | 0; + this.v3l = IV[6] | 0; + this.v3h = IV[7] | 0; + this.v4l = IV[8] | 0; + this.v4h = IV[9] | 0; + this.v5l = IV[10] | 0; + this.v5h = IV[11] | 0; + this.v6l = IV[12] | 0; + this.v6h = IV[13] | 0; + this.v7l = IV[14] | 0; + this.v7h = IV[15] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4l ^= salt[0]; + this.v4h ^= salt[1]; + this.v5l ^= salt[2]; + this.v5h ^= salt[3]; + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6l ^= pers[0]; + this.v6h ^= pers[1]; + this.v7l ^= pers[2]; + this.v7h ^= pers[3]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + // prettier-ignore + get() { + let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + compress(msg, offset, isLast) { + this.get().forEach((v, i) => (BUF[i] = v)); // First half from state. + BUF.set(IV, 16); // Second half from IV. + let { h, l } = u64.fromBig(BigInt(this.length)); + BUF[24] = IV[8] ^ l; // Low word of the offset. + BUF[25] = IV[9] ^ h; // High word. + // Invert all bits for last block + if (isLast) { + BUF[28] = ~BUF[28]; + BUF[29] = ~BUF[29]; + } + let j = 0; + const s = SIGMA; + for (let i = 0; i < 12; i++) { + G1(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G2(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G1(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G2(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G1(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G2(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G1(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G2(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G1(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G2(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G1(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G2(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G1(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G2(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G1(3, 4, 9, 14, msg, offset + 2 * s[j++]); + G2(3, 4, 9, 14, msg, offset + 2 * s[j++]); + } + this.v0l ^= BUF[0] ^ BUF[16]; + this.v0h ^= BUF[1] ^ BUF[17]; + this.v1l ^= BUF[2] ^ BUF[18]; + this.v1h ^= BUF[3] ^ BUF[19]; + this.v2l ^= BUF[4] ^ BUF[20]; + this.v2h ^= BUF[5] ^ BUF[21]; + this.v3l ^= BUF[6] ^ BUF[22]; + this.v3h ^= BUF[7] ^ BUF[23]; + this.v4l ^= BUF[8] ^ BUF[24]; + this.v4h ^= BUF[9] ^ BUF[25]; + this.v5l ^= BUF[10] ^ BUF[26]; + this.v5h ^= BUF[11] ^ BUF[27]; + this.v6l ^= BUF[12] ^ BUF[28]; + this.v6h ^= BUF[13] ^ BUF[29]; + this.v7l ^= BUF[14] ^ BUF[30]; + this.v7h ^= BUF[15] ^ BUF[31]; + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2b = wrapConstructorWithOpts((opts) => new BLAKE2b(opts)); +//# sourceMappingURL=blake2b.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/blake2b.js.map b/node_modules/@noble/hashes/esm/blake2b.js.map new file mode 100644 index 0000000..5b5e5fa --- /dev/null +++ b/node_modules/@noble/hashes/esm/blake2b.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2b.js","sourceRoot":"","sources":["../src/blake2b.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAa,KAAK,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,GAAG,MAAM,WAAW,CAAC;AAC5B,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AAEnE,yBAAyB;AACzB,kBAAkB;AAClB,MAAM,EAAE,GAAG,IAAI,WAAW,CAAC;IACzB,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;IAC9F,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;CAC/F,CAAC,CAAC;AACH,mBAAmB;AACnB,MAAM,GAAG,GAAG,IAAI,WAAW,CAAC,EAAE,CAAC,CAAC;AAEhC,0CAA0C;AAC1C,SAAS,EAAE,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,GAAgB,EAAE,CAAS;IACjF,qBAAqB;IACrB,MAAM,EAAE,GAAG,GAAG,CAAC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AE,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,CAAC;QAC9B,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,CAAC;QAC9B,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,CAAC;QAC9B,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,CAAC;QAC9B,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACd,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACtB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC3D,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,uBAAuB,CAAqB,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/blake2s.js b/node_modules/@noble/hashes/esm/blake2s.js new file mode 100644 index 0000000..ca92ef7 --- /dev/null +++ b/node_modules/@noble/hashes/esm/blake2s.js @@ -0,0 +1,120 @@ +import { BLAKE2, SIGMA } from './_blake2.js'; +import u64 from './_u64.js'; +import { rotr, toBytes, wrapConstructorWithOpts, u32 } from './utils.js'; +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19) +// same as SHA-256 +// prettier-ignore +export const IV = new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Mixing function G splitted in two halfs +function G1(a, b, c, d, x) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 16); + c = (c + d) | 0; + b = rotr(b ^ c, 12); + return { a, b, c, d }; +} +function G2(a, b, c, d, x) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 8); + c = (c + d) | 0; + b = rotr(b ^ c, 7); + return { a, b, c, d }; +} +// prettier-ignore +export function compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) { + let j = 0; + for (let i = 0; i < rounds; i++) { + ({ a: v0, b: v4, c: v8, d: v12 } = G1(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v0, b: v4, c: v8, d: v12 } = G2(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G1(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G2(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G1(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G2(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G1(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G2(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G1(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G2(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G1(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G2(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G1(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G2(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G1(v3, v4, v9, v14, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G2(v3, v4, v9, v14, msg[offset + s[j++]])); + } + return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; +} +class BLAKE2s extends BLAKE2 { + constructor(opts = {}) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, opts, 32, 8, 8); + // Internal state, same as SHA-256 + this.v0 = IV[0] | 0; + this.v1 = IV[1] | 0; + this.v2 = IV[2] | 0; + this.v3 = IV[3] | 0; + this.v4 = IV[4] | 0; + this.v5 = IV[5] | 0; + this.v6 = IV[6] | 0; + this.v7 = IV[7] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4 ^= salt[0]; + this.v5 ^= salt[1]; + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6 ^= pers[0]; + this.v7 ^= pers[1]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + get() { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + set(v0, v1, v2, v3, v4, v5, v6, v7) { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + compress(msg, offset, isLast) { + const { h, l } = u64.fromBig(BigInt(this.length)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(SIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, IV[0], IV[1], IV[2], IV[3], l ^ IV[4], h ^ IV[5], isLast ? ~IV[6] : IV[6], IV[7]); + this.v0 ^= v0 ^ v8; + this.v1 ^= v1 ^ v9; + this.v2 ^= v2 ^ v10; + this.v3 ^= v3 ^ v11; + this.v4 ^= v4 ^ v12; + this.v5 ^= v5 ^ v13; + this.v6 ^= v6 ^ v14; + this.v7 ^= v7 ^ v15; + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2s = wrapConstructorWithOpts((opts) => new BLAKE2s(opts)); +//# sourceMappingURL=blake2s.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/blake2s.js.map b/node_modules/@noble/hashes/esm/blake2s.js.map new file mode 100644 index 0000000..47e74b1 --- /dev/null +++ b/node_modules/@noble/hashes/esm/blake2s.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2s.js","sourceRoot":"","sources":["../src/blake2s.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAa,KAAK,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,GAAG,MAAM,WAAW,CAAC;AAC5B,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,uBAAuB,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AAEzE,iBAAiB;AACjB,yFAAyF;AACzF,kBAAkB;AAClB,kBAAkB;AAClB,MAAM,CAAC,MAAM,EAAE,GAAG,IAAI,WAAW,CAAC;IAChC,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,U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QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACtB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IACnC,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,uBAAuB,CAAqB,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/blake3.js b/node_modules/@noble/hashes/esm/blake3.js new file mode 100644 index 0000000..0e59be8 --- /dev/null +++ b/node_modules/@noble/hashes/esm/blake3.js @@ -0,0 +1,237 @@ +import assert from './_assert.js'; +import u64 from './_u64.js'; +import { BLAKE2 } from './_blake2.js'; +import { compress, IV } from './blake2s.js'; +import { u8, u32, toBytes, wrapXOFConstructorWithOpts } from './utils.js'; +// Flag bitset +var Flags; +(function (Flags) { + Flags[Flags["CHUNK_START"] = 1] = "CHUNK_START"; + Flags[Flags["CHUNK_END"] = 2] = "CHUNK_END"; + Flags[Flags["PARENT"] = 4] = "PARENT"; + Flags[Flags["ROOT"] = 8] = "ROOT"; + Flags[Flags["KEYED_HASH"] = 16] = "KEYED_HASH"; + Flags[Flags["DERIVE_KEY_CONTEXT"] = 32] = "DERIVE_KEY_CONTEXT"; + Flags[Flags["DERIVE_KEY_MATERIAL"] = 64] = "DERIVE_KEY_MATERIAL"; +})(Flags || (Flags = {})); +const SIGMA = (() => { + const Id = Array.from({ length: 16 }, (_, i) => i); + const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]); + const res = []; + for (let i = 0, v = Id; i < 7; i++, v = permute(v)) + res.push(...v); + return Uint8Array.from(res); +})(); +// Why is this so slow? It should be 6x faster than blake2b. +// - There is only 30% reduction in number of rounds from blake2s +// - This function uses tree mode to achive parallelisation via SIMD and threading, +// however in JS we don't have threads and SIMD, so we get only overhead from tree structure +// - It is possible to speed it up via Web Workers, hovewer it will make code singnificantly more +// complicated, which we are trying to avoid, since this library is intended to be used +// for cryptographic purposes. Also, parallelization happens only on chunk level (1024 bytes), +// which won't really benefit small inputs. +class BLAKE3 extends BLAKE2 { + constructor(opts = {}, flags = 0) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, {}, Number.MAX_SAFE_INTEGER, 0, 0); + this.flags = 0 | 0; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + this.stack = []; + // Output + this.posOut = 0; + this.bufferOut32 = new Uint32Array(16); + this.chunkOut = 0; // index of output chunk + this.enableXOF = true; + this.outputLen = opts.dkLen === undefined ? 32 : opts.dkLen; + assert.number(this.outputLen); + if (opts.key !== undefined && opts.context !== undefined) + throw new Error('Blake3: only key or context can be specified at same time'); + else if (opts.key !== undefined) { + const key = toBytes(opts.key).slice(); + if (key.length !== 32) + throw new Error('Blake3: key should be 32 byte'); + this.IV = u32(key); + this.flags = flags | Flags.KEYED_HASH; + } + else if (opts.context !== undefined) { + const context_key = new BLAKE3({ dkLen: 32 }, Flags.DERIVE_KEY_CONTEXT) + .update(opts.context) + .digest(); + this.IV = u32(context_key); + this.flags = flags | Flags.DERIVE_KEY_MATERIAL; + } + else { + this.IV = IV.slice(); + this.flags = flags; + } + this.state = this.IV.slice(); + this.bufferOut = u8(this.bufferOut32); + } + // Unused + get() { + return []; + } + set() { } + b2Compress(counter, flags, buf, bufPos = 0) { + const { state: s, pos } = this; + const { h, l } = u64.fromBig(BigInt(counter), true); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(SIGMA, bufPos, buf, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], IV[0], IV[1], IV[2], IV[3], h, l, pos, flags); + s[0] = v0 ^ v8; + s[1] = v1 ^ v9; + s[2] = v2 ^ v10; + s[3] = v3 ^ v11; + s[4] = v4 ^ v12; + s[5] = v5 ^ v13; + s[6] = v6 ^ v14; + s[7] = v7 ^ v15; + } + compress(buf, bufPos = 0, isLast = false) { + // Compress last block + let flags = this.flags; + if (!this.chunkPos) + flags |= Flags.CHUNK_START; + if (this.chunkPos === 15 || isLast) + flags |= Flags.CHUNK_END; + if (!isLast) + this.pos = this.blockLen; + this.b2Compress(this.chunksDone, flags, buf, bufPos); + this.chunkPos += 1; + // If current block is last in chunk (16 blocks), then compress chunks + if (this.chunkPos === 16 || isLast) { + let chunk = this.state; + this.state = this.IV.slice(); + // If not the last one, compress only when there are trailing zeros in chunk counter + // chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed. + // 1 (001) - leaf not finished (just push current chunk to stack) + // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back) + // 3 (011) - last leaf not finished + // 4 (100) - leafs finished at depth=1 and depth=2 + for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) { + if (!(last = this.stack.pop())) + break; + this.buffer32.set(last, 0); + this.buffer32.set(chunk, 8); + this.pos = this.blockLen; + this.b2Compress(0, this.flags | Flags.PARENT, this.buffer32, 0); + chunk = this.state; + this.state = this.IV.slice(); + } + this.chunksDone++; + this.chunkPos = 0; + this.stack.push(chunk); + } + this.pos = 0; + } + _cloneInto(to) { + to = super._cloneInto(to); + const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this; + to.state.set(state.slice()); + to.stack = stack.map((i) => Uint32Array.from(i)); + to.IV.set(IV); + to.flags = flags; + to.chunkPos = chunkPos; + to.chunksDone = chunksDone; + to.posOut = posOut; + to.chunkOut = chunkOut; + to.enableXOF = this.enableXOF; + to.bufferOut32.set(this.bufferOut32); + return to; + } + destroy() { + this.destroyed = true; + this.state.fill(0); + this.buffer32.fill(0); + this.IV.fill(0); + this.bufferOut32.fill(0); + for (let i of this.stack) + i.fill(0); + } + // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8) + b2CompressOut() { + const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this; + const { h, l } = u64.fromBig(BigInt(this.chunkOut++)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(SIGMA, 0, buffer32, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], IV[0], IV[1], IV[2], IV[3], l, h, pos, flags); + out32[0] = v0 ^ v8; + out32[1] = v1 ^ v9; + out32[2] = v2 ^ v10; + out32[3] = v3 ^ v11; + out32[4] = v4 ^ v12; + out32[5] = v5 ^ v13; + out32[6] = v6 ^ v14; + out32[7] = v7 ^ v15; + out32[8] = s[0] ^ v8; + out32[9] = s[1] ^ v9; + out32[10] = s[2] ^ v10; + out32[11] = s[3] ^ v11; + out32[12] = s[4] ^ v12; + out32[13] = s[5] ^ v13; + out32[14] = s[6] ^ v14; + out32[15] = s[7] ^ v15; + this.posOut = 0; + } + finish() { + if (this.finished) + return; + this.finished = true; + // Padding + this.buffer.fill(0, this.pos); + // Process last chunk + let flags = this.flags | Flags.ROOT; + if (this.stack.length) { + flags |= Flags.PARENT; + this.compress(this.buffer32, 0, true); + this.chunksDone = 0; + this.pos = this.blockLen; + } + else { + flags |= (!this.chunkPos ? Flags.CHUNK_START : 0) | Flags.CHUNK_END; + } + this.flags = flags; + this.b2CompressOut(); + } + writeInto(out) { + assert.exists(this, false); + assert.bytes(out); + this.finish(); + const { blockLen, bufferOut } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.b2CompressOut(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + if (!this.enableXOF) + throw new Error('XOF is not possible after digest call'); + return this.writeInto(out); + } + xof(bytes) { + assert.number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + assert.output(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.enableXOF = false; + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } +} +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +export const blake3 = wrapXOFConstructorWithOpts((opts) => new BLAKE3(opts)); +//# sourceMappingURL=blake3.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/blake3.js.map b/node_modules/@noble/hashes/esm/blake3.js.map new file mode 100644 index 0000000..f08f0fb --- /dev/null +++ b/node_modules/@noble/hashes/esm/blake3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake3.js","sourceRoot":"","sources":["../src/blake3.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,GAAG,MAAM,WAAW,CAAC;AAC5B,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAS,EAAE,EAAE,GAAG,EAAE,OAAO,EAAW,0BAA0B,EAAE,MAAM,YAAY,CAAC;AAE1F,cAAc;AACd,IAAK,KAQJ;AARD,WAAK,KAAK;IACR,+CAAoB,CAAA;IACpB,2CAAkB,CAAA;IAClB,qCAAe,CAAA;IACf,iCAAa,CAAA;IACb,8CAAmB,CAAA;IACnB,8DAA2B,CAAA;IAC3B,gEAA4B,CAAA;AAC9B,CAAC,EARI,KAAK,KAAL,KAAK,QAQT;AAED,MAAM,KAAK,GAAe,CAAC,GAAG,EAAE;IAC9B,MAAM,EAAE,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;IACnD,MAAM,OAAO,GAAG,CAAC,GAAa,EAAE,EAAE,CAChC,CAAC,CAAC,EAAE,CAAC,EA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f,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACrB,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;IAC7C,CAAC;IACD,UAAU,CAAC,GAAe;QACxB,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QACzB,IAAI,IAAI,CAAC,QAAQ;YAAE,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;QAClE,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;QACvB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;QACpB,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,OAAO,GAAG,CAAC;IACb,CAAC;IACD,MAAM;QACJ,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IACzD,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,0BAA0B,CAAqB,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/crypto.js b/node_modules/@noble/hashes/esm/crypto.js new file mode 100644 index 0000000..8d499a0 --- /dev/null +++ b/node_modules/@noble/hashes/esm/crypto.js @@ -0,0 +1,2 @@ +export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; +//# sourceMappingURL=crypto.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/crypto.js.map b/node_modules/@noble/hashes/esm/crypto.js.map new file mode 100644 index 0000000..4b4fd3d --- /dev/null +++ b/node_modules/@noble/hashes/esm/crypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.js","sourceRoot":"","sources":["../src/crypto.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,MAAM,MAAM,GACjB,OAAO,UAAU,KAAK,QAAQ,IAAI,QAAQ,IAAI,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/cryptoNode.js b/node_modules/@noble/hashes/esm/cryptoNode.js new file mode 100644 index 0000000..241f1da --- /dev/null +++ b/node_modules/@noble/hashes/esm/cryptoNode.js @@ -0,0 +1,7 @@ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +// The file will throw on node.js 14 and earlier. +// @ts-ignore +import * as nc from 'node:crypto'; +export const crypto = nc && typeof nc === 'object' && 'webcrypto' in nc ? nc.webcrypto : undefined; +//# sourceMappingURL=cryptoNode.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/cryptoNode.js.map b/node_modules/@noble/hashes/esm/cryptoNode.js.map new file mode 100644 index 0000000..f7ab75e --- /dev/null +++ b/node_modules/@noble/hashes/esm/cryptoNode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cryptoNode.js","sourceRoot":"","sources":["../src/cryptoNode.ts"],"names":[],"mappings":"AAAA,oFAAoF;AACpF,4BAA4B;AAC5B,iDAAiD;AACjD,aAAa;AACb,OAAO,KAAK,EAAE,MAAM,aAAa,CAAC;AAClC,MAAM,CAAC,MAAM,MAAM,GACjB,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,WAAW,IAAI,EAAE,CAAC,CAAC,CAAE,EAAE,CAAC,SAAiB,CAAC,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/eskdf.js b/node_modules/@noble/hashes/esm/eskdf.js new file mode 100644 index 0000000..13253eb --- /dev/null +++ b/node_modules/@noble/hashes/esm/eskdf.js @@ -0,0 +1,155 @@ +import { bytes as assertBytes } from './_assert.js'; +import { hkdf } from './hkdf.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 as _pbkdf2 } from './pbkdf2.js'; +import { scrypt as _scrypt } from './scrypt.js'; +import { bytesToHex, createView, hexToBytes, toBytes } from './utils.js'; +// A tiny KDF for various applications like AES key-gen. +// Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure". +// Which is good enough: assume sha2-256 retained preimage resistance. +const SCRYPT_FACTOR = 2 ** 19; +const PBKDF2_FACTOR = 2 ** 17; +// Scrypt KDF +export function scrypt(password, salt) { + return _scrypt(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 }); +} +// PBKDF2-HMAC-SHA256 +export function pbkdf2(password, salt) { + return _pbkdf2(sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 }); +} +// Combines two 32-byte byte arrays +function xor32(a, b) { + assertBytes(a, 32); + assertBytes(b, 32); + const arr = new Uint8Array(32); + for (let i = 0; i < 32; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} +function strHasLength(str, min, max) { + return typeof str === 'string' && str.length >= min && str.length <= max; +} +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +export function deriveMainSeed(username, password) { + if (!strHasLength(username, 8, 255)) + throw new Error('invalid username'); + if (!strHasLength(password, 8, 255)) + throw new Error('invalid password'); + const scr = scrypt(password + '\u{1}', username + '\u{1}'); + const pbk = pbkdf2(password + '\u{2}', username + '\u{2}'); + const res = xor32(scr, pbk); + scr.fill(0); + pbk.fill(0); + return res; +} +/** + * Converts protocol & accountId pair to HKDF salt & info params. + */ +function getSaltInfo(protocol, accountId = 0) { + // Note that length here also repeats two lines below + // We do an additional length check here to reduce the scope of DoS attacks + if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) { + throw new Error('invalid protocol'); + } + // Allow string account ids for some protocols + const allowsStr = /^password\d{0,3}|ssh|tor|file$/.test(protocol); + let salt; // Extract salt. Default is undefined. + if (typeof accountId === 'string') { + if (!allowsStr) + throw new Error('accountId must be a number'); + if (!strHasLength(accountId, 1, 255)) + throw new Error('accountId must be valid string'); + salt = toBytes(accountId); + } + else if (Number.isSafeInteger(accountId)) { + if (accountId < 0 || accountId > 2 ** 32 - 1) + throw new Error('invalid accountId'); + // Convert to Big Endian Uint32 + salt = new Uint8Array(4); + createView(salt).setUint32(0, accountId, false); + } + else { + throw new Error(`accountId must be a number${allowsStr ? ' or string' : ''}`); + } + const info = toBytes(protocol); + return { salt, info }; +} +function countBytes(num) { + if (typeof num !== 'bigint' || num <= BigInt(128)) + throw new Error('invalid number'); + return Math.ceil(num.toString(2).length / 8); +} +/** + * Parses keyLength and modulus options to extract length of result key. + * If modulus is used, adds 64 bits to it as per FIPS 186 B.4.1 to combat modulo bias. + */ +function getKeyLength(options) { + if (!options || typeof options !== 'object') + return 32; + const hasLen = 'keyLength' in options; + const hasMod = 'modulus' in options; + if (hasLen && hasMod) + throw new Error('cannot combine keyLength and modulus options'); + if (!hasLen && !hasMod) + throw new Error('must have either keyLength or modulus option'); + // FIPS 186 B.4.1 requires at least 64 more bits + const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength; + if (!(typeof l === 'number' && l >= 16 && l <= 8192)) + throw new Error('invalid keyLength'); + return l; +} +/** + * Converts key to bigint and divides it by modulus. Big Endian. + * Implements FIPS 186 B.4.1, which removes 0 and modulo bias from output. + */ +function modReduceKey(key, modulus) { + const _1 = BigInt(1); + const num = BigInt('0x' + bytesToHex(key)); // check for ui8a, then bytesToNumber() + const res = (num % (modulus - _1)) + _1; // Remove 0 from output + if (res < _1) + throw new Error('expected positive number'); // Guard against bad values + const len = key.length - 8; // FIPS requires 64 more bits = 8 bytes + const hex = res.toString(16).padStart(len * 2, '0'); // numberToHex() + const bytes = hexToBytes(hex); + if (bytes.length !== len) + throw new Error('invalid length of result key'); + return bytes; +} +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +export async function eskdf(username, password) { + // We are using closure + object instead of class because + // we want to make `seed` non-accessible for any external function. + let seed = deriveMainSeed(username, password); + function deriveCK(protocol, accountId = 0, options) { + assertBytes(seed, 32); + const { salt, info } = getSaltInfo(protocol, accountId); // validate protocol & accountId + const keyLength = getKeyLength(options); // validate options + const key = hkdf(sha256, seed, salt, info, keyLength); + // Modulus has already been validated + return options && 'modulus' in options ? modReduceKey(key, options.modulus) : key; + } + function expire() { + if (seed) + seed.fill(1); + seed = undefined; + } + // prettier-ignore + const fingerprint = Array.from(deriveCK('fingerprint', 0)) + .slice(0, 6) + .map((char) => char.toString(16).padStart(2, '0').toUpperCase()) + .join(':'); + return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint }); +} +//# sourceMappingURL=eskdf.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/eskdf.js.map b/node_modules/@noble/hashes/esm/eskdf.js.map new file mode 100644 index 0000000..f53eebe --- /dev/null +++ b/node_modules/@noble/hashes/esm/eskdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eskdf.js","sourceRoot":"","sources":["../src/eskdf.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,IAAI,WAAW,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,MAAM,IAAI,OAAO,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,MAAM,IAAI,OAAO,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAEzE,wDAAwD;AACxD,gFAAgF;AAChF,sEAAsE;AAEtE,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,CAAC;AAC9B,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,CAAC;AAE9B,aAAa;AACb,MA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of file diff --git a/node_modules/@noble/hashes/esm/hkdf.js b/node_modules/@noble/hashes/esm/hkdf.js new file mode 100644 index 0000000..d3a46e4 --- /dev/null +++ b/node_modules/@noble/hashes/esm/hkdf.js @@ -0,0 +1,72 @@ +import assert from './_assert.js'; +import { toBytes } from './utils.js'; +import { hmac } from './hmac.js'; +// HKDF (RFC 5869) +// https://soatok.blog/2021/11/17/understanding-hkdf/ +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +export function extract(hash, ikm, salt) { + assert.hash(hash); + // NOTE: some libraries treat zero-length array as 'not provided'; + // we don't, since we have undefined as 'not provided' + // https://github.com/RustCrypto/KDFs/issues/15 + if (salt === undefined) + salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros + return hmac(hash, toBytes(salt), toBytes(ikm)); +} +// HKDF-Expand(PRK, info, L) -> OKM +const HKDF_COUNTER = new Uint8Array([0]); +const EMPTY_BUFFER = new Uint8Array(); +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +export function expand(hash, prk, info, length = 32) { + assert.hash(hash); + assert.number(length); + if (length > 255 * hash.outputLen) + throw new Error('Length should be <= 255*HashLen'); + const blocks = Math.ceil(length / hash.outputLen); + if (info === undefined) + info = EMPTY_BUFFER; + // first L(ength) octets of T + const okm = new Uint8Array(blocks * hash.outputLen); + // Re-use HMAC instance between blocks + const HMAC = hmac.create(hash, prk); + const HMACTmp = HMAC._cloneInto(); + const T = new Uint8Array(HMAC.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + // T(0) = empty string (zero length) + // T(N) = HMAC-Hash(PRK, T(N-1) | info | N) + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T) + .update(info) + .update(HKDF_COUNTER) + .digestInto(T); + okm.set(T, hash.outputLen * counter); + HMAC._cloneInto(HMACTmp); + } + HMAC.destroy(); + HMACTmp.destroy(); + T.fill(0); + HKDF_COUNTER.fill(0); + return okm.slice(0, length); +} +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +export const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length); +//# sourceMappingURL=hkdf.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/hkdf.js.map b/node_modules/@noble/hashes/esm/hkdf.js.map new file mode 100644 index 0000000..6e80029 --- /dev/null +++ b/node_modules/@noble/hashes/esm/hkdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hkdf.js","sourceRoot":"","sources":["../src/hkdf.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,EAAgB,OAAO,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,kBAAkB;AAClB,qDAAqD;AAErD;;;;;;;GAOG;AACH,MAAM,UAAU,OAAO,CAAC,IAAW,EAAE,GAAU,EAAE,IAAY;IAC3D,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAClB,kEAAkE;IAClE,sDAAsD;IACtD,+CAA+C;IAC/C,IAAI,IAAI,KAAK,SAAS;QAAE,IAAI,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,0DAA0D;IACzH,OAAO,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;AACjD,CAAC;AAED,mCAAmC;AACnC,MAAM,YAAY,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACzC,MAAM,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C,SAAS,GAAG,OAAO,CAAC,CAAC;QACrC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;KAC1B;IACD,IAAI,CAAC,OAAO,EAAE,CAAC;IACf,OAAO,CAAC,OAAO,EAAE,CAAC;IAClB,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACV,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACrB,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;AAC9B,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG,CAClB,IAAW,EACX,GAAU,EACV,IAAuB,EACvB,IAAuB,EACvB,MAAc,EACd,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/hmac.js b/node_modules/@noble/hashes/esm/hmac.js new file mode 100644 index 0000000..36ae4f4 --- /dev/null +++ b/node_modules/@noble/hashes/esm/hmac.js @@ -0,0 +1,77 @@ +import assert from './_assert.js'; +import { Hash, toBytes } from './utils.js'; +// HMAC (RFC 2104) +export class HMAC extends Hash { + constructor(hash, _key) { + super(); + this.finished = false; + this.destroyed = false; + assert.hash(hash); + const key = toBytes(_key); + this.iHash = hash.create(); + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash.create(); + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + assert.exists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + assert.exists(this); + assert.bytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +export const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); +hmac.create = (hash, key) => new HMAC(hash, key); +//# sourceMappingURL=hmac.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/hmac.js.map b/node_modules/@noble/hashes/esm/hmac.js.map new file mode 100644 index 0000000..e580ae4 --- /dev/null +++ b/node_modules/@noble/hashes/esm/hmac.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hmac.js","sourceRoot":"","sources":["../src/hmac.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,EAAE,IAAI,EAAgB,OAAO,EAAE,MAAM,YAAY,CAAC;AACzD,kBAAkB;AAClB,MAAM,OAAO,IAAwB,SAAQ,IAAa;IAQxD,YAAY,IAAW,EAAE,IAAW;QAClC,KAAK,EAAE,CAAC;QAJF,aAAQ,GAAG,KAAK,CAAC;QACjB,cAAS,GAAG,KAAK,CAAC;QAIxB,MAAM,CAAC,IA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,SAAS,GAAG,SAAS,CAAC;QACzB,EAAE,CAAC,KAAK,GAAG,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;QACtC,EAAE,CAAC,KAAK,GAAG,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;QACtC,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;QACrB,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;IACvB,CAAC;CACF;AAED;;;;;GAKG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG,CAAC,IAAW,EAAE,GAAU,EAAE,OAAc,EAAc,EAAE,CAC1E,IAAI,IAAI,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC;AACpD,IAAI,CAAC,MAAM,GAAG,CAAC,IAAW,EAAE,GAAU,EAAE,EAAE,CAAC,IAAI,IAAI,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/index.js b/node_modules/@noble/hashes/esm/index.js new file mode 100644 index 0000000..2299d7f --- /dev/null +++ b/node_modules/@noble/hashes/esm/index.js @@ -0,0 +1,3 @@ +"use strict"; +throw new Error('noble-hashes have no entry-point: consult README for usage'); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/index.js.map b/node_modules/@noble/hashes/esm/index.js.map new file mode 100644 index 0000000..90172aa --- /dev/null +++ b/node_modules/@noble/hashes/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA,MAAM,IAAI,KAAK,CAAC,4DAA4D,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/package.json b/node_modules/@noble/hashes/esm/package.json new file mode 100644 index 0000000..cf1903a --- /dev/null +++ b/node_modules/@noble/hashes/esm/package.json @@ -0,0 +1,9 @@ +{ + "type": "module", + "browser": { + "node:crypto": false + }, + "node": { + "./crypto": "./esm/cryptoNode.js" + } +} diff --git a/node_modules/@noble/hashes/esm/pbkdf2.js b/node_modules/@noble/hashes/esm/pbkdf2.js new file mode 100644 index 0000000..fe68436 --- /dev/null +++ b/node_modules/@noble/hashes/esm/pbkdf2.js @@ -0,0 +1,86 @@ +import assert from './_assert.js'; +import { hmac } from './hmac.js'; +import { createView, toBytes, checkOpts, asyncLoop } from './utils.js'; +// Common prologue and epilogue for sync/async functions +function pbkdf2Init(hash, _password, _salt, _opts) { + assert.hash(hash); + const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + assert.number(c); + assert.number(dkLen); + assert.number(asyncTick); + if (c < 1) + throw new Error('PBKDF2: iterations (c) should be >= 1'); + const password = toBytes(_password); + const salt = toBytes(_salt); + // DK = PBKDF2(PRF, Password, Salt, c, dkLen); + const DK = new Uint8Array(dkLen); + // U1 = PRF(Password, Salt + INT_32_BE(i)) + const PRF = hmac.create(hash, password); + const PRFSalt = PRF._cloneInto().update(salt); + return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; +} +function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) + prfW.destroy(); + u.fill(0); + return DK; +} +/** + * PBKDF2-HMAC: RFC 2898 key derivation function + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated + * @param salt - cryptographic salt + * @param opts - {c, dkLen} where c is work factor and dkLen is output message size + */ +export function pbkdf2(hash, password, salt, opts) { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + for (let ui = 1; ui < c; ui++) { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +export async function pbkdf2Async(hash, password, salt, opts) { + const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + await asyncLoop(c - 1, asyncTick, (i) => { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + }); + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +//# sourceMappingURL=pbkdf2.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/pbkdf2.js.map b/node_modules/@noble/hashes/esm/pbkdf2.js.map new file mode 100644 index 0000000..1710c5c --- /dev/null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AE,GAAG,GAAG,CAAC,EAAE,GAAG,GAAG,KAAK,EAAE,EAAE,EAAE,EAAE,GAAG,IAAI,GAAG,CAAC,SAAS,EAAE;QACjE,+BAA+B;QAC/B,MAAM,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,GAAG,EAAE,GAAG,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC;QACjD,IAAI,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;QAC5B,6CAA6C;QAC7C,0CAA0C;QAC1C,CAAC,IAAI,GAAG,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC5D,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;QACjC,MAAM,SAAS,CAAC,CAAC,GAAG,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,EAAE,EAAE;YACtC,2BAA2B;YAC3B,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;YAC7C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,EAAE;gBAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;QACpD,CAAC,CAAC,CAAC;KACJ;IACD,OAAO,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AACjD,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/ripemd160.js b/node_modules/@noble/hashes/esm/ripemd160.js new file mode 100644 index 0000000..fcf1f5e --- /dev/null +++ b/node_modules/@noble/hashes/esm/ripemd160.js @@ -0,0 +1,100 @@ +import { SHA2 } from './_sha2.js'; +import { wrapConstructor } from './utils.js'; +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = Uint8Array.from({ length: 16 }, (_, i) => i); +const Pi = Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) + for (let j of [idxL, idxR]) + j.push(j[i].map((k) => Rho[k])); +const shifts = [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => new Uint8Array(i)); +const shiftsL = idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +const Kl = new Uint32Array([0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]); +const Kr = new Uint32Array([0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]); +// The rotate left (circular left shift) operation for uint32 +const rotl = (word, shift) => (word << shift) | (word >>> (32 - shift)); +// It's called f() in spec. +function f(group, x, y, z) { + if (group === 0) + return x ^ y ^ z; + else if (group === 1) + return (x & y) | (~x & z); + else if (group === 2) + return (x | ~y) ^ z; + else if (group === 3) + return (x & z) | (y & ~z); + else + return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const BUF = new Uint32Array(16); +export class RIPEMD160 extends SHA2 { + constructor() { + super(64, 20, 8, true); + this.h0 = 0x67452301 | 0; + this.h1 = 0xefcdab89 | 0; + this.h2 = 0x98badcfe | 0; + this.h3 = 0x10325476 | 0; + this.h4 = 0xc3d2e1f0 | 0; + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + BUF[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0); + } + roundClean() { + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +export const ripemd160 = wrapConstructor(() => new RIPEMD160()); +//# sourceMappingURL=ripemd160.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/ripemd160.js.map b/node_modules/@noble/hashes/esm/ripemd160.js.map new file mode 100644 index 0000000..bb6ab0f --- /dev/null +++ b/node_modules/@noble/hashes/esm/ripemd160.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ripemd160.js","sourceRoot":"","sources":["../src/ripemd160.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C,0DAA0D;AAC1D,6EAA6E;AAC7E,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;AACnF,MAAM,EAAE,GAAG,UAAU,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;AACxD,MAAM,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC;AAC3C,IAAI,IAAI,GAAG,CAAC,EAAE,CAAC,CAAC;AAChB,IAAI,IAAI,GAAG,CAAC,EAAE,CAAC,CAAC;AAChB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE;IAAE,KAAK,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC;QAAE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AAG,CAAC,EACvB,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CACxB,CAAC;IACJ,CAAC;IACS,UAAU;QAClB,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACd,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACpB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC1B,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,SAAS,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/scrypt.js b/node_modules/@noble/hashes/esm/scrypt.js new file mode 100644 index 0000000..204d41a --- /dev/null +++ b/node_modules/@noble/hashes/esm/scrypt.js @@ -0,0 +1,218 @@ +import assert from './_assert.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 } from './pbkdf2.js'; +import { asyncLoop, checkOpts, u32 } from './utils.js'; +// RFC 7914 Scrypt KDF +// Left rotate for uint32 +const rotl = (a, b) => (a << b) | (a >>> (32 - b)); +// The main Scrypt loop: uses Salsa extensively. +// Six versions of the function were tried, this is the fastest one. +// prettier-ignore +function XorAndSalsa(prev, pi, input, ii, out, oi) { + // Based on https://cr.yp.to/salsa20.html + // Xor blocks + let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; + let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; + let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; + let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; + let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; + let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; + let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; + let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; + // Save state to temporary variables (salsa) + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; + // Main loop (salsa) + for (let i = 0; i < 8; i += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); + x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); + x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); + x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); + x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); + x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); + x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); + x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); + x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); + x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); + x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); + x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); + x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); + x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); + x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); + x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); + x15 ^= rotl(x14 + x13 | 0, 18); + } + // Write output (salsa) + out[oi++] = (y00 + x00) | 0; + out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; + out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; + out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; + out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; + out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; + out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; + out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; + out[oi++] = (y15 + x15) | 0; +} +function BlockMix(input, ii, out, oi, r) { + // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks) + let head = oi + 0; + let tail = oi + 16 * r; + for (let i = 0; i < 16; i++) + out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1] + for (let i = 0; i < r; i++, head += 16, ii += 16) { + // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1 + XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1]) + if (i > 0) + tail += 16; // First iteration overwrites tmp value in tail + XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i]) + } +} +// Common prologue and epilogue for sync/async functions +function scryptInit(password, salt, _opts) { + // Maxmem - 1GB+1KB by default + const opts = checkOpts({ + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024, + }, _opts); + const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; + assert.number(N); + assert.number(r); + assert.number(p); + assert.number(dkLen); + assert.number(asyncTick); + assert.number(maxmem); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + const blockSize = 128 * r; + const blockSize32 = blockSize / 4; + if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) { + // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function + // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future. + throw new Error('Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32'); + } + if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) { + throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)'); + } + if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) { + throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32'); + } + const memUsed = blockSize * (N + p); + if (memUsed > maxmem) { + throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`); + } + // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor) + // Since it has only one iteration there is no reason to use async variant + const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p }); + const B32 = u32(B); + // Re-used between parallel iterations. Array(iterations) of B + const V = u32(new Uint8Array(blockSize * N)); + const tmp = u32(new Uint8Array(blockSize)); + let blockMixCb = () => { }; + if (onProgress) { + const totalBlockMix = 2 * N * p; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1); + let blockMixCnt = 0; + blockMixCb = () => { + blockMixCnt++; + if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) + onProgress(blockMixCnt / totalBlockMix); + }; + } + return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick }; +} +function scryptOutput(password, dkLen, B, V, tmp) { + const res = pbkdf2(sha256, password, B, { c: 1, dkLen }); + B.fill(0); + V.fill(0); + tmp.fill(0); + return res; +} +/** + * Scrypt KDF from RFC 7914. + * @param password - pass + * @param salt - salt + * @param opts - parameters + * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + * @returns Derived key + */ +export function scrypt(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + for (let i = 0, pos = 0; i < N - 1; i++) { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + } + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + for (let i = 0; i < N; i++) { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + } + } + return scryptOutput(password, dkLen, B, V, tmp); +} +/** + * Scrypt KDF from RFC 7914. + */ +export async function scryptAsync(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + let pos = 0; + await asyncLoop(N - 1, asyncTick, (i) => { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + }); + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + await asyncLoop(N, asyncTick, (i) => { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + }); + } + return scryptOutput(password, dkLen, B, V, tmp); +} +//# sourceMappingURL=scrypt.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/scrypt.js.map b/node_modules/@noble/hashes/esm/scrypt.js.map new file mode 100644 index 0000000..d944f4c --- /dev/null +++ b/node_modules/@noble/hashes/esm/scrypt.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scrypt.js","sourceRoot":"","sources":["../src/scrypt.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,SAAS,EAAE,SAAS,EAAS,GAAG,EAAE,MAAM,YAAY,CAAC;AAE9D,sBAAsB;AAEtB,yBAAyB;AACzB,MAAM,IAAI,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;AAEnE,gDAAgD;AAChD,oEAAoE;AACpE,kBAAkB;AAClB,SAAS,WAAW,CAClB,IAAiB,EACjB,EAAU,EACV,KAAkB,EAClB,EAAU,EACV,GAAgB,EAChB,EAAU;IAEV,yCAAyC;IACzC,aAAa;IACb,IAAI,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,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AC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;AAClD,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/sha1.js b/node_modules/@noble/hashes/esm/sha1.js new file mode 100644 index 0000000..f0691b0 --- /dev/null +++ b/node_modules/@noble/hashes/esm/sha1.js @@ -0,0 +1,85 @@ +import { SHA2 } from './_sha2.js'; +import { wrapConstructor } from './utils.js'; +// SHA1 was cryptographically broken. +// It is still widely used in legacy apps. Don't use it for a new protocol. +// RFC 3174 +const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +// Initial state +const IV = new Uint32Array([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = new Uint32Array(80); +class SHA1 extends SHA2 { + constructor() { + super(64, 20, 8, false); + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + } + get() { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + set(A, B, C, D, E) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } + else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } + else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } + else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +export const sha1 = wrapConstructor(() => new SHA1()); +//# sourceMappingURL=sha1.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/sha1.js.map b/node_modules/@noble/hashes/esm/sha1.js.map new file mode 100644 index 0000000..dbf3cd3 --- /dev/null +++ b/node_modules/@noble/hashes/esm/sha1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha1.js","sourceRoot":"","sources":["../src/sha1.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C,qCAAqC;AACrC,2EAA2E;AAE3E,WAAW;AACX,MAAM,IAAI,GAAG,CAAC,IAAY,EAAE,KAAa,EAAE,EAAE,CAAC,CAAC,IAAI,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,KAAK,CAAC,EAAE,GAAG,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;AAChG,oBAAoB;AACpB,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AACpE,oDAAoD;AACpD,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,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AI,GAAG,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/sha256.js b/node_modules/@noble/hashes/esm/sha256.js new file mode 100644 index 0000000..841917e --- /dev/null +++ b/node_modules/@noble/hashes/esm/sha256.js @@ -0,0 +1,124 @@ +import { SHA2 } from './_sha2.js'; +import { rotr, wrapConstructor } from './utils.js'; +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); +// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): +// prettier-ignore +const IV = new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = new Uint32Array(64); +class SHA256 extends SHA2 { + constructor() { + super(64, 32, 8, false); + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + this.F = IV[5] | 0; + this.G = IV[6] | 0; + this.H = IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + constructor() { + super(); + this.A = 0xc1059ed8 | 0; + this.B = 0x367cd507 | 0; + this.C = 0x3070dd17 | 0; + this.D = 0xf70e5939 | 0; + this.E = 0xffc00b31 | 0; + this.F = 0x68581511 | 0; + this.G = 0x64f98fa7 | 0; + this.H = 0xbefa4fa4 | 0; + this.outputLen = 28; + } +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +export const sha256 = wrapConstructor(() => new SHA256()); +export const sha224 = wrapConstructor(() => new SHA224()); +//# sourceMappingURL=sha256.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/sha256.js.map b/node_modules/@noble/hashes/esm/sha256.js.map new file mode 100644 index 0000000..a986797 --- /dev/null +++ b/node_modules/@noble/hashes/esm/sha256.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha256.js","sourceRoot":"","sources":["../src/sha256.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAEnD,oBAAoB;AACpB,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AACpE,oD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C,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QAGjB,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;IACtB,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC;AAC1D,MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/sha3-addons.js b/node_modules/@noble/hashes/esm/sha3-addons.js new file mode 100644 index 0000000..cb1a2a8 --- /dev/null +++ b/node_modules/@noble/hashes/esm/sha3-addons.js @@ -0,0 +1,347 @@ +import { number as assertNumber } from './_assert.js'; +import { toBytes, wrapConstructorWithOpts, u32 } from './utils.js'; +import { Keccak } from './sha3.js'; +// cSHAKE && KMAC (NIST SP800-185) +function leftEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.unshift(res.length); + return new Uint8Array(res); +} +function rightEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +function chooseLen(opts, outputLen) { + return opts.dkLen === undefined ? outputLen : opts.dkLen; +} +const toBytesOptional = (buf) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); +// NOTE: second modulo is necessary since we don't need to add padding if current element takes whole block +const getPadding = (len, block) => new Uint8Array((block - (len % block)) % block); +// Personalization +function cshakePers(hash, opts = {}) { + if (!opts || (!opts.personalization && !opts.NISTfn)) + return hash; + // Encode and pad inplace to avoid unneccesary memory copies/slices (so we don't need to zero them later) + // bytepad(encode_string(N) || encode_string(S), 168) + const blockLenBytes = leftEncode(hash.blockLen); + const fn = toBytesOptional(opts.NISTfn); + const fnLen = leftEncode(8 * fn.length); // length in bits + const pers = toBytesOptional(opts.personalization); + const persLen = leftEncode(8 * pers.length); // length in bits + if (!fn.length && !pers.length) + return hash; + hash.suffix = 0x04; + hash.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers); + let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length; + hash.update(getPadding(totalLen, hash.blockLen)); + return hash; +} +const gencShake = (suffix, blockLen, outputLen) => wrapConstructorWithOpts((opts = {}) => cshakePers(new Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts)); +export const cshake128 = /* @__PURE__ */ (() => gencShake(0x1f, 168, 128 / 8))(); +export const cshake256 = /* @__PURE__ */ (() => gencShake(0x1f, 136, 256 / 8))(); +class KMAC extends Keccak { + constructor(blockLen, outputLen, enableXOF, key, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'KMAC', personalization: opts.personalization }); + key = toBytes(key); + // 1. newX = bytepad(encode_string(K), 168) || X || right_encode(L). + const blockLenBytes = leftEncode(this.blockLen); + const keyLen = leftEncode(8 * key.length); + this.update(blockLenBytes).update(keyLen).update(key); + const totalLen = blockLenBytes.length + keyLen.length + key.length; + this.update(getPadding(totalLen, this.blockLen)); + } + finish() { + if (!this.finished) + this.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + // Force "to" to be instance of KMAC instead of Sha3. + if (!to) { + to = Object.create(Object.getPrototypeOf(this), {}); + to.state = this.state.slice(); + to.blockLen = this.blockLen; + to.state32 = u32(to.state); + } + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genKmac(blockLen, outputLen, xof = false) { + const kmac = (key, message, opts) => kmac.create(key, opts).update(message).digest(); + kmac.create = (key, opts = {}) => new KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts); + return kmac; +} +export const kmac128 = /* @__PURE__ */ (() => genKmac(168, 128 / 8))(); +export const kmac256 = /* @__PURE__ */ (() => genKmac(136, 256 / 8))(); +export const kmac128xof = /* @__PURE__ */ (() => genKmac(168, 128 / 8, true))(); +export const kmac256xof = /* @__PURE__ */ (() => genKmac(136, 256 / 8, true))(); +// TupleHash +// Usage: tuple(['ab', 'cd']) != tuple(['a', 'bcd']) +class TupleHash extends Keccak { + constructor(blockLen, outputLen, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'TupleHash', personalization: opts.personalization }); + // Change update after cshake processed + this.update = (data) => { + data = toBytes(data); + super.update(leftEncode(data.length * 8)); + super.update(data); + return this; + }; + } + finish() { + if (!this.finished) + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new TupleHash(this.blockLen, this.outputLen, this.enableXOF)); + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genTuple(blockLen, outputLen, xof = false) { + const tuple = (messages, opts) => { + const h = tuple.create(opts); + for (const msg of messages) + h.update(msg); + return h.digest(); + }; + tuple.create = (opts = {}) => new TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts); + return tuple; +} +export const tuplehash128 = /* @__PURE__ */ (() => genTuple(168, 128 / 8))(); +export const tuplehash256 = /* @__PURE__ */ (() => genTuple(136, 256 / 8))(); +export const tuplehash128xof = /* @__PURE__ */ (() => genTuple(168, 128 / 8, true))(); +export const tuplehash256xof = /* @__PURE__ */ (() => genTuple(136, 256 / 8, true))(); +class ParallelHash extends Keccak { + constructor(blockLen, outputLen, leafCons, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + this.leafCons = leafCons; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + cshakePers(this, { NISTfn: 'ParallelHash', personalization: opts.personalization }); + let { blockLen: B } = opts; + B || (B = 8); + assertNumber(B); + this.chunkLen = B; + super.update(leftEncode(B)); + // Change update after cshake processed + this.update = (data) => { + data = toBytes(data); + const { chunkLen, leafCons } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen || !this.leafHash) { + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + this.leafHash = leafCons(); + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + this.leafHash.update(data.subarray(pos, pos + take)); + this.chunkPos += take; + pos += take; + } + return this; + }; + } + finish() { + if (this.finished) + return; + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + super.update(rightEncode(this.chunksDone)); + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF)); + if (this.leafHash) + to.leafHash = this.leafHash._cloneInto(to.leafHash); + to.chunkPos = this.chunkPos; + to.chunkLen = this.chunkLen; + to.chunksDone = this.chunksDone; + return super._cloneInto(to); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + } + clone() { + return this._cloneInto(); + } +} +function genPrl(blockLen, outputLen, leaf, xof = false) { + const parallel = (message, opts) => parallel.create(opts).update(message).digest(); + parallel.create = (opts = {}) => new ParallelHash(blockLen, chooseLen(opts, outputLen), () => leaf.create({ dkLen: 2 * outputLen }), xof, opts); + return parallel; +} +export const parallelhash128 = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128))(); +export const parallelhash256 = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256))(); +export const parallelhash128xof = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128, true))(); +export const parallelhash256xof = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256, true))(); +// Kangaroo +// Same as NIST rightEncode, but returns [0] for zero string +function rightEncodeK12(n) { + const res = []; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +const EMPTY = new Uint8Array([]); +class KangarooTwelve extends Keccak { + constructor(blockLen, leafLen, outputLen, rounds, opts) { + super(blockLen, 0x07, outputLen, true, rounds); + this.leafLen = leafLen; + this.chunkLen = 8192; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + const { personalization } = opts; + this.personalization = toBytesOptional(personalization); + } + update(data) { + data = toBytes(data); + const { chunkLen, blockLen, leafLen, rounds } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen) { + if (this.leafHash) + super.update(this.leafHash.digest()); + else { + this.suffix = 0x06; // Its safe to change suffix here since its used only in digest() + super.update(new Uint8Array([3, 0, 0, 0, 0, 0, 0, 0])); + } + this.leafHash = new Keccak(blockLen, 0x0b, leafLen, false, rounds); + this.chunksDone++; + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + const chunk = data.subarray(pos, pos + take); + if (this.leafHash) + this.leafHash.update(chunk); + else + super.update(chunk); + this.chunkPos += take; + pos += take; + } + return this; + } + finish() { + if (this.finished) + return; + const { personalization } = this; + this.update(personalization).update(rightEncodeK12(personalization.length)); + // Leaf hash + if (this.leafHash) { + super.update(this.leafHash.digest()); + super.update(rightEncodeK12(this.chunksDone)); + super.update(new Uint8Array([0xff, 0xff])); + } + super.finish.call(this); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + // We cannot zero personalization buffer since it is user provided and we don't want to mutate user input + this.personalization = EMPTY; + } + _cloneInto(to) { + const { blockLen, leafLen, leafHash, outputLen, rounds } = this; + to || (to = new KangarooTwelve(blockLen, leafLen, outputLen, rounds, {})); + super._cloneInto(to); + if (leafHash) + to.leafHash = leafHash._cloneInto(to.leafHash); + to.personalization.set(this.personalization); + to.leafLen = this.leafLen; + to.chunkPos = this.chunkPos; + to.chunksDone = this.chunksDone; + return to; + } + clone() { + return this._cloneInto(); + } +} +// Default to 32 bytes, so it can be used without opts +export const k12 = /* @__PURE__ */ (() => wrapConstructorWithOpts((opts = {}) => new KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts)))(); +// MarsupilamiFourteen +export const m14 = /* @__PURE__ */ (() => wrapConstructorWithOpts((opts = {}) => new KangarooTwelve(136, 64, chooseLen(opts, 64), 14, opts)))(); +// https://keccak.team/files/CSF-0.1.pdf +// + https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG +class KeccakPRG extends Keccak { + constructor(capacity) { + assertNumber(capacity); + // Rho should be full bytes + if (capacity < 0 || capacity > 1600 - 10 || (1600 - capacity - 2) % 8) + throw new Error('KeccakPRG: Invalid capacity'); + // blockLen = rho in bytes + super((1600 - capacity - 2) / 8, 0, 0, true); + this.rate = 1600 - capacity; + this.posOut = Math.floor((this.rate + 7) / 8); + } + keccak() { + // Duplex padding + this.state[this.pos] ^= 0x01; + this.state[this.blockLen] ^= 0x02; // Rho is full bytes + super.keccak(); + this.pos = 0; + this.posOut = 0; + } + update(data) { + super.update(data); + this.posOut = this.blockLen; + return this; + } + feed(data) { + return this.update(data); + } + finish() { } + digestInto(out) { + throw new Error('KeccakPRG: digest is not allowed, please use .fetch instead.'); + } + fetch(bytes) { + return this.xof(bytes); + } + // Ensure irreversibility (even if state leaked previous outputs cannot be computed) + forget() { + if (this.rate < 1600 / 2 + 1) + throw new Error('KeccakPRG: rate too low to use forget'); + this.keccak(); + for (let i = 0; i < this.blockLen; i++) + this.state[i] = 0; + this.pos = this.blockLen; + this.keccak(); + this.posOut = this.blockLen; + } + _cloneInto(to) { + const { rate } = this; + to || (to = new KeccakPRG(1600 - rate)); + super._cloneInto(to); + to.rate = rate; + return to; + } + clone() { + return this._cloneInto(); + } +} +export const keccakprg = (capacity = 254) => new KeccakPRG(capacity); +//# sourceMappingURL=sha3-addons.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/sha3-addons.js.map b/node_modules/@noble/hashes/esm/sha3-addons.js.map new file mode 100644 index 0000000..3393dec --- /dev/null +++ b/node_modules/@noble/hashes/esm/sha3-addons.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3-addons.js","sourceRoot":"","sources":["../src/sha3-addons.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAS,OAAO,EAAE,uBAAuB,EAAE,GAAG,EAAiB,MAAM,YAAY,CAAC;AACzF,OAAO,EAAE,MAAM,EAAa,MAAM,WAAW,CAAC;AAC9C,kCAAkC;AAClC,SAAS,UAAU,CAAC,CAAS;IAC3B,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IACvB,CAAC,KAAK,CAAC,CAAC;IACR,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC;QAAE,GAAG,CAAC,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IAC7C,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACxB,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,WAAW,CAAC,CAAS;IAC5B,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IACvB,CAAC,KAAK,CAAC,CAAC;IACR,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC;QAAE,GAAG,CAAC,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IAC7C,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACrB,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,SAAS,CAAC,IAAe,EAAE,SAAiB;IACnD,OAAO,IAAI,CAAC,KAAK,KAAK,SAA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IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QAC1D,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC;QACzB,IAAI,CAAC,MAAM,EAAE,CAAC;QACd,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC;IAC9B,CAAC;IACD,UAAU,CAAC,EAAc;QACvB,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;QACtB,EAAE,KAAF,EAAE,GAAK,IAAI,SAAS,CAAC,IAAI,GAAG,IAAI,CAAC,EAAC;QAClC,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;QACrB,EAAE,CAAC,IAAI,GAAG,IAAI,CAAC;QACf,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,KAAK;QACH,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC;IAC3B,CAAC;CACF;AAED,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,QAAQ,GAAG,GAAG,EAAE,EAAE,CAAC,IAAI,SAAS,CAAC,QAAQ,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/sha3.js b/node_modules/@noble/hashes/esm/sha3.js new file mode 100644 index 0000000..710eca4 --- /dev/null +++ b/node_modules/@noble/hashes/esm/sha3.js @@ -0,0 +1,206 @@ +import assert from './_assert.js'; +import u64 from './_u64.js'; +import { Hash, u32, toBytes, wrapConstructor, wrapXOFConstructorWithOpts, } from './utils.js'; +// Various per round constants calculations +const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []]; +const _0n = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +const _7n = BigInt(7); +const _256n = BigInt(256); +const _0x71n = BigInt(0x71); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) + t ^= _1n << ((_1n << BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = u64.split(_SHA3_IOTA, true); +// Left rotation (without 0, 32, 64) +const rotlH = (h, l, s) => s > 32 ? u64.rotlBH(h, l, s) : u64.rotlSH(h, l, s); +const rotlL = (h, l, s) => s > 32 ? u64.rotlBL(h, l, s) : u64.rotlSL(h, l, s); +// Same as keccakf1600, but allows to skip some rounds +export function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) + B[x] = s[y + x]; + for (let x = 0; x < 10; x++) + s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} +export class Keccak extends Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + // Can be passed from user as dkLen + assert.number(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + update(data) { + assert.exists(this); + const { blockLen, state } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + writeInto(out) { + assert.exists(this, false); + assert.bytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) + throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes) { + assert.number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + assert.output(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} +const gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); +export const sha3_224 = gen(0x06, 144, 224 / 8); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +export const sha3_256 = gen(0x06, 136, 256 / 8); +export const sha3_384 = gen(0x06, 104, 384 / 8); +export const sha3_512 = gen(0x06, 72, 512 / 8); +export const keccak_224 = gen(0x01, 144, 224 / 8); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +export const keccak_256 = gen(0x01, 136, 256 / 8); +export const keccak_384 = gen(0x01, 104, 384 / 8); +export const keccak_512 = gen(0x01, 72, 512 / 8); +const genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)); +export const shake128 = genShake(0x1f, 168, 128 / 8); +export const shake256 = genShake(0x1f, 136, 256 / 8); +//# sourceMappingURL=sha3.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/sha3.js.map b/node_modules/@noble/hashes/esm/sha3.js.map new file mode 100644 index 0000000..e64e81e --- /dev/null +++ b/node_modules/@noble/hashes/esm/sha3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3.js","sourceRoot":"","sources":["../src/sha3.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC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,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;AACrD,MAAM,CAAC,MAAM,QAAQ,GAAG,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/sha512.js b/node_modules/@noble/hashes/esm/sha512.js new file mode 100644 index 0000000..aaec7e4 --- /dev/null +++ b/node_modules/@noble/hashes/esm/sha512.js @@ -0,0 +1,231 @@ +import { SHA2 } from './_sha2.js'; +import u64 from './_u64.js'; +import { wrapConstructor } from './utils.js'; +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = u64.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))); +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = new Uint32Array(80); +const SHA512_W_L = new Uint32Array(80); +export class SHA512 extends SHA2 { + constructor() { + super(128, 64, 16, false); + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x6a09e667 | 0; + this.Al = 0xf3bcc908 | 0; + this.Bh = 0xbb67ae85 | 0; + this.Bl = 0x84caa73b | 0; + this.Ch = 0x3c6ef372 | 0; + this.Cl = 0xfe94f82b | 0; + this.Dh = 0xa54ff53a | 0; + this.Dl = 0x5f1d36f1 | 0; + this.Eh = 0x510e527f | 0; + this.El = 0xade682d1 | 0; + this.Fh = 0x9b05688c | 0; + this.Fl = 0x2b3e6c1f | 0; + this.Gh = 0x1f83d9ab | 0; + this.Gl = 0xfb41bd6b | 0; + this.Hh = 0x5be0cd19 | 0; + this.Hl = 0x137e2179 | 0; + } + // prettier-ignore + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); + const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); + const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); + const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); + const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = u64.add3L(T1l, sigma0l, MAJl); + Ah = u64.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +class SHA512_224 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x8c3d37c8 | 0; + this.Al = 0x19544da2 | 0; + this.Bh = 0x73e19966 | 0; + this.Bl = 0x89dcd4d6 | 0; + this.Ch = 0x1dfab7ae | 0; + this.Cl = 0x32ff9c82 | 0; + this.Dh = 0x679dd514 | 0; + this.Dl = 0x582f9fcf | 0; + this.Eh = 0x0f6d2b69 | 0; + this.El = 0x7bd44da8 | 0; + this.Fh = 0x77e36f73 | 0; + this.Fl = 0x04c48942 | 0; + this.Gh = 0x3f9d85a8 | 0; + this.Gl = 0x6a1d36c8 | 0; + this.Hh = 0x1112e6ad | 0; + this.Hl = 0x91d692a1 | 0; + this.outputLen = 28; + } +} +class SHA512_256 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x22312194 | 0; + this.Al = 0xfc2bf72c | 0; + this.Bh = 0x9f555fa3 | 0; + this.Bl = 0xc84c64c2 | 0; + this.Ch = 0x2393b86b | 0; + this.Cl = 0x6f53b151 | 0; + this.Dh = 0x96387719 | 0; + this.Dl = 0x5940eabd | 0; + this.Eh = 0x96283ee2 | 0; + this.El = 0xa88effe3 | 0; + this.Fh = 0xbe5e1e25 | 0; + this.Fl = 0x53863992 | 0; + this.Gh = 0x2b0199fc | 0; + this.Gl = 0x2c85b8aa | 0; + this.Hh = 0x0eb72ddc | 0; + this.Hl = 0x81c52ca2 | 0; + this.outputLen = 32; + } +} +class SHA384 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0xcbbb9d5d | 0; + this.Al = 0xc1059ed8 | 0; + this.Bh = 0x629a292a | 0; + this.Bl = 0x367cd507 | 0; + this.Ch = 0x9159015a | 0; + this.Cl = 0x3070dd17 | 0; + this.Dh = 0x152fecd8 | 0; + this.Dl = 0xf70e5939 | 0; + this.Eh = 0x67332667 | 0; + this.El = 0xffc00b31 | 0; + this.Fh = 0x8eb44a87 | 0; + this.Fl = 0x68581511 | 0; + this.Gh = 0xdb0c2e0d | 0; + this.Gl = 0x64f98fa7 | 0; + this.Hh = 0x47b5481d | 0; + this.Hl = 0xbefa4fa4 | 0; + this.outputLen = 48; + } +} +export const sha512 = wrapConstructor(() => new SHA512()); +export const sha512_224 = wrapConstructor(() => new SHA512_224()); +export const sha512_256 = wrapConstructor(() => new SHA512_256()); +export const sha384 = wrapConstructor(() => new SHA384()); +//# sourceMappingURL=sha512.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/sha512.js.map b/node_modules/@noble/hashes/esm/sha512.js.map new file mode 100644 index 0000000..e06ea23 --- /dev/null +++ b/node_modules/@noble/hashes/esm/sha512.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha512.js","sourceRoot":"","sources":["../src/sha512.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,GAAG,MAAM,WAAW,CAAC;AAC5B,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C,0GAA0G;AAC1G,kBAAkB;AAClB,MAAM,CAAC,SAAS,EAAE,SAAS,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC;IACvC,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,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E,CAAC,CAAC;AAC1D,MAAM,CAAC,MAAM,UAAU,GAAG,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,CAAC;AAClE,MAAM,CAAC,MAAM,UAAU,GAAG,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,CAAC;AAClE,MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/utils.js b/node_modules/@noble/hashes/esm/utils.js new file mode 100644 index 0000000..59e86f5 --- /dev/null +++ b/node_modules/@noble/hashes/esm/utils.js @@ -0,0 +1,155 @@ +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated, we can just drop the import. +import { crypto } from '@noble/hashes/crypto'; +const u8a = (a) => a instanceof Uint8Array; +// Cast array to different type +export const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +export const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +// Cast array to view +export const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +// The rotate right (circular right shift) operation for uint32 +export const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); +// big-endian hardware is rare. Just in case someone still decides to run hashes: +// early-throw an error because we don't support BE yet. +export const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!isLE) + throw new Error('Non little-endian hardware is not supported'); +const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export function bytesToHex(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} +// There is no setImmediate in browser and setTimeout is slow. +// call of async fn will return Promise, which will be fullfiled only on +// next scheduler queue processing step and this is exactly what we need. +export const nextTick = async () => { }; +// Returns control to thread each 'tick' ms to avoid blocking +export async function asyncLoop(iters, tick, cb) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) + continue; + await nextTick(); + ts += diff; + } +} +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +export function toBytes(data) { + if (typeof data === 'string') + data = utf8ToBytes(data); + if (!u8a(data)) + throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; +} +/** + * Copies several Uint8Arrays into one. + */ +export function concatBytes(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) + throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} +// For runtime check if class implements interface +export class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +// Check if object doens't have custom constructor (like Uint8Array/Array) +const isPlainObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object; +export function checkOpts(defaults, opts) { + if (opts !== undefined && (typeof opts !== 'object' || !isPlainObject(opts))) + throw new Error('Options should be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged; +} +export function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +export function wrapConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +export function wrapXOFConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +export function randomBytes(bytesLength = 32) { + if (crypto && typeof crypto.getRandomValues === 'function') { + return crypto.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error('crypto.getRandomValues must be defined'); +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/esm/utils.js.map b/node_modules/@noble/hashes/esm/utils.js.map new file mode 100644 index 0000000..82e3954 --- /dev/null +++ b/node_modules/@noble/hashes/esm/utils.js.map @@ -0,0 +1 @@ +{"version":3,"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QAAkC;IAElC,MAAM,KAAK,GAAG,CAAC,GAAU,EAAE,IAAQ,EAAc,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;IACjG,MAAM,GAAG,GAAG,QAAQ,CAAC,EAAO,CAAC,CAAC;IAC9B,KAAK,CAAC,SAAS,GAAG,GAAG,CAAC,SAAS,CAAC;IAChC,KAAK,CAAC,QAAQ,GAAG,GAAG,CAAC,QAAQ,CAAC;IAC9B,KAAK,CAAC,MAAM,GAAG,CAAC,IAAO,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC3C,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,WAAW,CAAC,WAAW,GAAG,EAAE;IAC1C,IAAI,MAAM,IAAI,OAAO,MAAM,CAAC,eAAe,KAAK,UAAU,EAAE;QAC1D,OAAO,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC;KAC5D;IACD,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAC5D,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/hkdf.d.ts b/node_modules/@noble/hashes/hkdf.d.ts new file mode 100644 index 0000000..e1d683b --- /dev/null +++ b/node_modules/@noble/hashes/hkdf.d.ts @@ -0,0 +1,26 @@ +import { CHash, Input } from './utils.js'; +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +export declare function extract(hash: CHash, ikm: Input, salt?: Input): Uint8Array; +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +export declare function expand(hash: CHash, prk: Input, info?: Input, length?: number): Uint8Array; +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +export declare const hkdf: (hash: CHash, ikm: Input, salt: Input | undefined, info: Input | undefined, length: number) => Uint8Array; diff --git a/node_modules/@noble/hashes/hkdf.js b/node_modules/@noble/hashes/hkdf.js new file mode 100644 index 0000000..66dc8ba --- /dev/null +++ b/node_modules/@noble/hashes/hkdf.js @@ -0,0 +1,78 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hkdf = exports.expand = exports.extract = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +const hmac_js_1 = require("./hmac.js"); +// HKDF (RFC 5869) +// https://soatok.blog/2021/11/17/understanding-hkdf/ +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +function extract(hash, ikm, salt) { + _assert_js_1.default.hash(hash); + // NOTE: some libraries treat zero-length array as 'not provided'; + // we don't, since we have undefined as 'not provided' + // https://github.com/RustCrypto/KDFs/issues/15 + if (salt === undefined) + salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros + return (0, hmac_js_1.hmac)(hash, (0, utils_js_1.toBytes)(salt), (0, utils_js_1.toBytes)(ikm)); +} +exports.extract = extract; +// HKDF-Expand(PRK, info, L) -> OKM +const HKDF_COUNTER = new Uint8Array([0]); +const EMPTY_BUFFER = new Uint8Array(); +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +function expand(hash, prk, info, length = 32) { + _assert_js_1.default.hash(hash); + _assert_js_1.default.number(length); + if (length > 255 * hash.outputLen) + throw new Error('Length should be <= 255*HashLen'); + const blocks = Math.ceil(length / hash.outputLen); + if (info === undefined) + info = EMPTY_BUFFER; + // first L(ength) octets of T + const okm = new Uint8Array(blocks * hash.outputLen); + // Re-use HMAC instance between blocks + const HMAC = hmac_js_1.hmac.create(hash, prk); + const HMACTmp = HMAC._cloneInto(); + const T = new Uint8Array(HMAC.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + // T(0) = empty string (zero length) + // T(N) = HMAC-Hash(PRK, T(N-1) | info | N) + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T) + .update(info) + .update(HKDF_COUNTER) + .digestInto(T); + okm.set(T, hash.outputLen * counter); + HMAC._cloneInto(HMACTmp); + } + HMAC.destroy(); + HMACTmp.destroy(); + T.fill(0); + HKDF_COUNTER.fill(0); + return okm.slice(0, length); +} +exports.expand = expand; +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length); +exports.hkdf = hkdf; +//# sourceMappingURL=hkdf.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/hkdf.js.map b/node_modules/@noble/hashes/hkdf.js.map new file mode 100644 index 0000000..998a82f --- /dev/null +++ b/node_modules/@noble/hashes/hkdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hkdf.js","sourceRoot":"","sources":["src/hkdf.ts"],"names":[],"mappings":";;;AAAA,6CAAkC;AAClC,yCAAmD;AACnD,uCAAiC;AAEjC,kBAAkB;AAClB,qDAAqD;AAErD;;;;;;;GAOG;AACH,SAAgB,OAAO,CAAC,IAAW,EAAE,GAAU,EAAE,IAAY;IAC3D,oBAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAClB,kEAAkE;IAClE,sDAAsD;IACtD,+CAA+C;IAC/C,IAAI,IAAI,KAAK,SAAS;QAAE,IA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C,GAAG,OAAO,GAAG,CAAC,CAAC;QAC9B,oCAAoC;QACpC,2CAA2C;QAC3C,OAAO,CAAC,MAAM,CAAC,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC;aAC7C,MAAM,CAAC,IAAI,CAAC;aACZ,MAAM,CAAC,YAAY,CAAC;aACpB,UAAU,CAAC,CAAC,CAAC,CAAC;QACjB,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,CAAC;QACrC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;KAC1B;IACD,IAAI,CAAC,OAAO,EAAE,CAAC;IACf,OAAO,CAAC,OAAO,EAAE,CAAC;IAClB,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACV,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACrB,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;AAC9B,CAAC;AA5BD,wBA4BC;AAED;;;;;;;GAOG;AACI,MAAM,IAAI,GAAG,CAClB,IAAW,EACX,GAAU,EACV,IAAuB,EACvB,IAAuB,EACvB,MAAc,EACd,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAN7C,QAAA,IAAI,QAMyC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/hmac.d.ts b/node_modules/@noble/hashes/hmac.d.ts new file mode 100644 index 0000000..63db656 --- /dev/null +++ b/node_modules/@noble/hashes/hmac.d.ts @@ -0,0 +1,25 @@ +import { Hash, CHash, Input } from './utils.js'; +export declare class HMAC> extends Hash> { + oHash: T; + iHash: T; + blockLen: number; + outputLen: number; + private finished; + private destroyed; + constructor(hash: CHash, _key: Input); + update(buf: Input): this; + digestInto(out: Uint8Array): void; + digest(): Uint8Array; + _cloneInto(to?: HMAC): HMAC; + destroy(): void; +} +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +export declare const hmac: { + (hash: CHash, key: Input, message: Input): Uint8Array; + create(hash: CHash, key: Input): HMAC; +}; diff --git a/node_modules/@noble/hashes/hmac.js b/node_modules/@noble/hashes/hmac.js new file mode 100644 index 0000000..4b2998e --- /dev/null +++ b/node_modules/@noble/hashes/hmac.js @@ -0,0 +1,82 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hmac = exports.HMAC = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +// HMAC (RFC 2104) +class HMAC extends utils_js_1.Hash { + constructor(hash, _key) { + super(); + this.finished = false; + this.destroyed = false; + _assert_js_1.default.hash(hash); + const key = (0, utils_js_1.toBytes)(_key); + this.iHash = hash.create(); + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash.create(); + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + _assert_js_1.default.exists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + _assert_js_1.default.exists(this); + _assert_js_1.default.bytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} +exports.HMAC = HMAC; +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); +exports.hmac = hmac; +exports.hmac.create = (hash, key) => new HMAC(hash, key); +//# sourceMappingURL=hmac.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/hmac.js.map b/node_modules/@noble/hashes/hmac.js.map new file mode 100644 index 0000000..a417288 --- /dev/null +++ b/node_modules/@noble/hashes/hmac.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hmac.js","sourceRoot":"","sources":["src/hmac.ts"],"names":[],"mappings":";;;AAAA,6CAAkC;AAClC,yCAAyD;AACzD,kBAAkB;AAClB,MAAa,IAAwB,SAAQ,eAAa;IAQxD,YAAY,IAAW,EAAE,IAAW;QAClC,KAAK,EAAE,CAAC;QAJF,aAAQ,GAAG,KAAK,CAAC;QACjB,cAAS,GAAG,KAAK,CAAC;QAIxB,oBAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAClB,MAAM,GAAG,GAAG,IAAA,kBAAO,EAAC,IAAI,CAAC,CAAC;QAC1B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,MAAM,EAAO,CAAC;QAChC,IAAI,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,KAAK,UAAU;YACzC,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;QACzE,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC;QACpC,I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AC;QACrB,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;IACvB,CAAC;CACF;AAnED,oBAmEC;AAED;;;;;GAKG;AACI,MAAM,IAAI,GAAG,CAAC,IAAW,EAAE,GAAU,EAAE,OAAc,EAAc,EAAE,CAC1E,IAAI,IAAI,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC;AADvC,QAAA,IAAI,QACmC;AACpD,YAAI,CAAC,MAAM,GAAG,CAAC,IAAW,EAAE,GAAU,EAAE,EAAE,CAAC,IAAI,IAAI,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/index.d.ts b/node_modules/@noble/hashes/index.d.ts new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/@noble/hashes/index.js b/node_modules/@noble/hashes/index.js new file mode 100644 index 0000000..2299d7f --- /dev/null +++ b/node_modules/@noble/hashes/index.js @@ -0,0 +1,3 @@ +"use strict"; +throw new Error('noble-hashes have no entry-point: consult README for usage'); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/index.js.map b/node_modules/@noble/hashes/index.js.map new file mode 100644 index 0000000..b71bae6 --- /dev/null +++ b/node_modules/@noble/hashes/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":";AAAA,MAAM,IAAI,KAAK,CAAC,4DAA4D,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/package.json b/node_modules/@noble/hashes/package.json new file mode 100644 index 0000000..b8fd0f0 --- /dev/null +++ b/node_modules/@noble/hashes/package.json @@ -0,0 +1,173 @@ +{ + "name": "@noble/hashes", + "version": "1.3.1", + "description": "Audited & minimal 0-dependency JS implementation of SHA2, SHA3, RIPEMD, BLAKE2/3, HMAC, HKDF, PBKDF2, Scrypt", + "files": [ + "/*.js", + "/*.d.ts", + "/*.js.map", + "esm", + "src/*.ts" + ], + "scripts": { + "bench": "node benchmark/index.js noble", + "bench:all": "node benchmark/index.js", + "bench:install": "cd benchmark && npm install && cd ../../", + "build": "npm run build:clean; tsc && tsc -p tsconfig.esm.json", + "build:release": "cd build; npm i; npm run build", + "build:clean": "rm *.{js,d.ts,js.map} esm/*.{js,js.map} 2> /dev/null", + "lint": "prettier --check 'src/**/*.{js,ts}' 'test/**/*.{js,ts}'", + "format": "prettier --write 'src/**/*.{js,ts}' 'test/**/*.{js,ts}'", + "test": "node test/index.js", + "test:dos": "node test/slow-dos.test.js", + "test:big": "node test/slow-big.test.js" + }, + "author": "Paul Miller (https://paulmillr.com)", + "homepage": "https://paulmillr.com/noble/", + "repository": { + "type": "git", + "url": "https://github.com/paulmillr/noble-hashes.git" + }, + "license": "MIT", + "browser": { + "node:crypto": false, + "./crypto": "./crypto.js" + }, + "devDependencies": { + "micro-bmark": "0.3.1", + "micro-should": "0.4.0", + "prettier": "2.8.4", + "typescript": "5.0.2" + }, + "engines": { + "node": ">= 16" + }, + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./esm/index.js", + "default": "./index.js" + }, + "./crypto": { + "types": "./crypto.d.ts", + "node": { + "import": "./esm/cryptoNode.js", + "default": "./cryptoNode.js" + }, + "import": "./esm/crypto.js", + "default": "./crypto.js" + }, + "./_assert": { + "types": "./_assert.d.ts", + "import": "./esm/_assert.js", + "default": "./_assert.js" + }, + "./_sha2": { + "types": "./_sha2.d.ts", + "import": "./esm/_sha2.js", + "default": "./_sha2.js" + }, + "./argon2": { + "types": "./argon2.d.ts", + "import": "./esm/argon2.js", + "default": "./argon2.js" + }, + "./blake2b": { + "types": "./blake2b.d.ts", + "import": "./esm/blake2b.js", + "default": "./blake2b.js" + }, + "./blake2s": { + "types": "./blake2s.d.ts", + "import": "./esm/blake2s.js", + "default": "./blake2s.js" + }, + "./blake3": { + "types": "./blake3.d.ts", + "import": "./esm/blake3.js", + "default": "./blake3.js" + }, + "./eskdf": { + "types": "./eskdf.d.ts", + "import": "./esm/eskdf.js", + "default": "./eskdf.js" + }, + "./hkdf": { + "types": "./hkdf.d.ts", + "import": "./esm/hkdf.js", + "default": "./hkdf.js" + }, + "./hmac": { + "types": "./hmac.d.ts", + "import": "./esm/hmac.js", + "default": "./hmac.js" + }, + "./pbkdf2": { + "types": "./pbkdf2.d.ts", + "import": "./esm/pbkdf2.js", + "default": "./pbkdf2.js" + }, + "./ripemd160": { + "types": "./ripemd160.d.ts", + "import": "./esm/ripemd160.js", + "default": "./ripemd160.js" + }, + "./scrypt": { + "types": "./scrypt.d.ts", + "import": "./esm/scrypt.js", + "default": "./scrypt.js" + }, + "./sha1": { + "types": "./sha1.d.ts", + "import": "./esm/sha1.js", + "default": "./sha1.js" + }, + "./sha3-addons": { + "types": "./sha3-addons.d.ts", + "import": "./esm/sha3-addons.js", + "default": "./sha3-addons.js" + }, + "./sha3": { + "types": "./sha3.d.ts", + "import": "./esm/sha3.js", + "default": "./sha3.js" + }, + "./sha256": { + "types": "./sha256.d.ts", + "import": "./esm/sha256.js", + "default": "./sha256.js" + }, + "./sha512": { + "types": "./sha512.d.ts", + "import": "./esm/sha512.js", + "default": "./sha512.js" + }, + "./utils": { + "types": "./utils.d.ts", + "import": "./esm/utils.js", + "default": "./utils.js" + } + }, + "keywords": [ + "sha", + "sha2", + "sha3", + "sha256", + "sha512", + "keccak", + "kangarootwelve", + "ripemd160", + "blake2", + "blake3", + "hmac", + "hkdf", + "pbkdf2", + "scrypt", + "kdf", + "hash", + "cryptography", + "security", + "noble" + ], + "funding": "https://paulmillr.com/funding/" +} diff --git a/node_modules/@noble/hashes/pbkdf2.d.ts b/node_modules/@noble/hashes/pbkdf2.d.ts new file mode 100644 index 0000000..42f691c --- /dev/null +++ b/node_modules/@noble/hashes/pbkdf2.d.ts @@ -0,0 +1,15 @@ +import { CHash, Input } from './utils.js'; +export type Pbkdf2Opt = { + c: number; + dkLen?: number; + asyncTick?: number; +}; +/** + * PBKDF2-HMAC: RFC 2898 key derivation function + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated + * @param salt - cryptographic salt + * @param opts - {c, dkLen} where c is work factor and dkLen is output message size + */ +export declare function pbkdf2(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt): Uint8Array; +export declare function pbkdf2Async(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt): Promise; diff --git a/node_modules/@noble/hashes/pbkdf2.js b/node_modules/@noble/hashes/pbkdf2.js new file mode 100644 index 0000000..fc20a33 --- /dev/null +++ b/node_modules/@noble/hashes/pbkdf2.js @@ -0,0 +1,91 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.pbkdf2Async = exports.pbkdf2 = void 0; +const _assert_js_1 = require("./_assert.js"); +const hmac_js_1 = require("./hmac.js"); +const utils_js_1 = require("./utils.js"); +// Common prologue and epilogue for sync/async functions +function pbkdf2Init(hash, _password, _salt, _opts) { + _assert_js_1.default.hash(hash); + const opts = (0, utils_js_1.checkOpts)({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + _assert_js_1.default.number(c); + _assert_js_1.default.number(dkLen); + _assert_js_1.default.number(asyncTick); + if (c < 1) + throw new Error('PBKDF2: iterations (c) should be >= 1'); + const password = (0, utils_js_1.toBytes)(_password); + const salt = (0, utils_js_1.toBytes)(_salt); + // DK = PBKDF2(PRF, Password, Salt, c, dkLen); + const DK = new Uint8Array(dkLen); + // U1 = PRF(Password, Salt + INT_32_BE(i)) + const PRF = hmac_js_1.hmac.create(hash, password); + const PRFSalt = PRF._cloneInto().update(salt); + return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; +} +function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) + prfW.destroy(); + u.fill(0); + return DK; +} +/** + * PBKDF2-HMAC: RFC 2898 key derivation function + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated + * @param salt - cryptographic salt + * @param opts - {c, dkLen} where c is work factor and dkLen is output message size + */ +function pbkdf2(hash, password, salt, opts) { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = (0, utils_js_1.createView)(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + for (let ui = 1; ui < c; ui++) { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +exports.pbkdf2 = pbkdf2; +async function pbkdf2Async(hash, password, salt, opts) { + const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = (0, utils_js_1.createView)(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + await (0, utils_js_1.asyncLoop)(c - 1, asyncTick, (i) => { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + }); + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +exports.pbkdf2Async = pbkdf2Async; +//# sourceMappingURL=pbkdf2.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/pbkdf2.js.map b/node_modules/@noble/hashes/pbkdf2.js.map new file mode 100644 index 0000000..6af49d8 --- /dev/null +++ b/node_modules/@noble/hashes/pbkdf2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pbkdf2.js","sourceRoot":"","sources":["src/pbkdf2.ts"],"names":[],"mappings":";;;AAAA,6CAAkC;AAClC,uCAAiC;AACjC,yCAA2F;AAQ3F,wDAAwD;AACxD,SAAS,UAAU,CAAC,IAAW,EAAE,SAAgB,EAAE,KAAY,EAAE,KAAgB;IAC/E,oBAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAClB,MAAM,IAAI,GAAG,IAAA,oBAAS,EAAC,EAAE,KAAK,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IAC5D,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;IACrC,oBAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IACjB,oBAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACrB,oBAAM,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IACzB,IAAI,CAAC,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;IACpE,MAAM,QAAQ,GAAG,IAAA,kBAAO,EAAC,SAAS,CAAC,CAAC;IACpC,MAAM,IAAI,GAAG,IAAA,kBAAO,EAAC,KAAK,CAAC,CAAC;IAC5B,8CAA8C;IAC9C,MAAM,EAAE,GAAG,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;IACjC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,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AACjD,CAAC;AAtBD,kCAsBC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/ripemd160.d.ts b/node_modules/@noble/hashes/ripemd160.d.ts new file mode 100644 index 0000000..92e662f --- /dev/null +++ b/node_modules/@noble/hashes/ripemd160.d.ts @@ -0,0 +1,24 @@ +import { SHA2 } from './_sha2.js'; +export declare class RIPEMD160 extends SHA2 { + private h0; + private h1; + private h2; + private h3; + private h4; + constructor(); + protected get(): [number, number, number, number, number]; + protected set(h0: number, h1: number, h2: number, h3: number, h4: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +export declare const ripemd160: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; diff --git a/node_modules/@noble/hashes/ripemd160.js b/node_modules/@noble/hashes/ripemd160.js new file mode 100644 index 0000000..2f702ba --- /dev/null +++ b/node_modules/@noble/hashes/ripemd160.js @@ -0,0 +1,104 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ripemd160 = exports.RIPEMD160 = void 0; +const _sha2_js_1 = require("./_sha2.js"); +const utils_js_1 = require("./utils.js"); +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = Uint8Array.from({ length: 16 }, (_, i) => i); +const Pi = Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) + for (let j of [idxL, idxR]) + j.push(j[i].map((k) => Rho[k])); +const shifts = [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => new Uint8Array(i)); +const shiftsL = idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +const Kl = new Uint32Array([0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]); +const Kr = new Uint32Array([0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]); +// The rotate left (circular left shift) operation for uint32 +const rotl = (word, shift) => (word << shift) | (word >>> (32 - shift)); +// It's called f() in spec. +function f(group, x, y, z) { + if (group === 0) + return x ^ y ^ z; + else if (group === 1) + return (x & y) | (~x & z); + else if (group === 2) + return (x | ~y) ^ z; + else if (group === 3) + return (x & z) | (y & ~z); + else + return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const BUF = new Uint32Array(16); +class RIPEMD160 extends _sha2_js_1.SHA2 { + constructor() { + super(64, 20, 8, true); + this.h0 = 0x67452301 | 0; + this.h1 = 0xefcdab89 | 0; + this.h2 = 0x98badcfe | 0; + this.h3 = 0x10325476 | 0; + this.h4 = 0xc3d2e1f0 | 0; + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + BUF[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0); + } + roundClean() { + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} +exports.RIPEMD160 = RIPEMD160; +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +exports.ripemd160 = (0, utils_js_1.wrapConstructor)(() => new RIPEMD160()); +//# sourceMappingURL=ripemd160.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/ripemd160.js.map b/node_modules/@noble/hashes/ripemd160.js.map new file mode 100644 index 0000000..90c597d --- /dev/null +++ b/node_modules/@noble/hashes/ripemd160.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ripemd160.js","sourceRoot":"","sources":["src/ripemd160.ts"],"names":[],"mappings":";;;AAAA,yCAAkC;AAClC,yCAA6C;AAE7C,0DAA0D;AAC1D,6EAA6E;AAC7E,MAAM,GAAG,GAAG,IAAI,UAAU,CA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I,SAAS,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/scrypt.d.ts b/node_modules/@noble/hashes/scrypt.d.ts new file mode 100644 index 0000000..82485b3 --- /dev/null +++ b/node_modules/@noble/hashes/scrypt.d.ts @@ -0,0 +1,29 @@ +import { Input } from './utils.js'; +export type ScryptOpts = { + N: number; + r: number; + p: number; + dkLen?: number; + asyncTick?: number; + maxmem?: number; + onProgress?: (progress: number) => void; +}; +/** + * Scrypt KDF from RFC 7914. + * @param password - pass + * @param salt - salt + * @param opts - parameters + * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + * @returns Derived key + */ +export declare function scrypt(password: Input, salt: Input, opts: ScryptOpts): Uint8Array; +/** + * Scrypt KDF from RFC 7914. + */ +export declare function scryptAsync(password: Input, salt: Input, opts: ScryptOpts): Promise; diff --git a/node_modules/@noble/hashes/scrypt.js b/node_modules/@noble/hashes/scrypt.js new file mode 100644 index 0000000..b28c8d8 --- /dev/null +++ b/node_modules/@noble/hashes/scrypt.js @@ -0,0 +1,223 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.scryptAsync = exports.scrypt = void 0; +const _assert_js_1 = require("./_assert.js"); +const sha256_js_1 = require("./sha256.js"); +const pbkdf2_js_1 = require("./pbkdf2.js"); +const utils_js_1 = require("./utils.js"); +// RFC 7914 Scrypt KDF +// Left rotate for uint32 +const rotl = (a, b) => (a << b) | (a >>> (32 - b)); +// The main Scrypt loop: uses Salsa extensively. +// Six versions of the function were tried, this is the fastest one. +// prettier-ignore +function XorAndSalsa(prev, pi, input, ii, out, oi) { + // Based on https://cr.yp.to/salsa20.html + // Xor blocks + let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; + let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; + let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; + let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; + let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; + let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; + let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; + let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; + // Save state to temporary variables (salsa) + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; + // Main loop (salsa) + for (let i = 0; i < 8; i += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); + x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); + x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); + x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); + x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); + x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); + x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); + x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); + x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); + x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); + x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); + x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); + x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); + x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); + x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); + x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); + x15 ^= rotl(x14 + x13 | 0, 18); + } + // Write output (salsa) + out[oi++] = (y00 + x00) | 0; + out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; + out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; + out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; + out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; + out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; + out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; + out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; + out[oi++] = (y15 + x15) | 0; +} +function BlockMix(input, ii, out, oi, r) { + // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks) + let head = oi + 0; + let tail = oi + 16 * r; + for (let i = 0; i < 16; i++) + out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1] + for (let i = 0; i < r; i++, head += 16, ii += 16) { + // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1 + XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1]) + if (i > 0) + tail += 16; // First iteration overwrites tmp value in tail + XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i]) + } +} +// Common prologue and epilogue for sync/async functions +function scryptInit(password, salt, _opts) { + // Maxmem - 1GB+1KB by default + const opts = (0, utils_js_1.checkOpts)({ + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024, + }, _opts); + const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; + _assert_js_1.default.number(N); + _assert_js_1.default.number(r); + _assert_js_1.default.number(p); + _assert_js_1.default.number(dkLen); + _assert_js_1.default.number(asyncTick); + _assert_js_1.default.number(maxmem); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + const blockSize = 128 * r; + const blockSize32 = blockSize / 4; + if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) { + // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function + // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future. + throw new Error('Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32'); + } + if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) { + throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)'); + } + if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) { + throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32'); + } + const memUsed = blockSize * (N + p); + if (memUsed > maxmem) { + throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`); + } + // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor) + // Since it has only one iteration there is no reason to use async variant + const B = (0, pbkdf2_js_1.pbkdf2)(sha256_js_1.sha256, password, salt, { c: 1, dkLen: blockSize * p }); + const B32 = (0, utils_js_1.u32)(B); + // Re-used between parallel iterations. Array(iterations) of B + const V = (0, utils_js_1.u32)(new Uint8Array(blockSize * N)); + const tmp = (0, utils_js_1.u32)(new Uint8Array(blockSize)); + let blockMixCb = () => { }; + if (onProgress) { + const totalBlockMix = 2 * N * p; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1); + let blockMixCnt = 0; + blockMixCb = () => { + blockMixCnt++; + if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) + onProgress(blockMixCnt / totalBlockMix); + }; + } + return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick }; +} +function scryptOutput(password, dkLen, B, V, tmp) { + const res = (0, pbkdf2_js_1.pbkdf2)(sha256_js_1.sha256, password, B, { c: 1, dkLen }); + B.fill(0); + V.fill(0); + tmp.fill(0); + return res; +} +/** + * Scrypt KDF from RFC 7914. + * @param password - pass + * @param salt - salt + * @param opts - parameters + * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + * @returns Derived key + */ +function scrypt(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + for (let i = 0, pos = 0; i < N - 1; i++) { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + } + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + for (let i = 0; i < N; i++) { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + } + } + return scryptOutput(password, dkLen, B, V, tmp); +} +exports.scrypt = scrypt; +/** + * Scrypt KDF from RFC 7914. + */ +async function scryptAsync(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + let pos = 0; + await (0, utils_js_1.asyncLoop)(N - 1, asyncTick, (i) => { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + }); + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + await (0, utils_js_1.asyncLoop)(N, asyncTick, (i) => { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + }); + } + return scryptOutput(password, dkLen, B, V, tmp); +} +exports.scryptAsync = scryptAsync; +//# sourceMappingURL=scrypt.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/scrypt.js.map b/node_modules/@noble/hashes/scrypt.js.map new file mode 100644 index 0000000..5be0b8c --- /dev/null +++ b/node_modules/@noble/hashes/scrypt.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scrypt.js","sourceRoot":"","sources":["src/scrypt.ts"],"names":[],"mappings":";;;AAAA,6CAAkC;AAClC,2CAAqC;AACrC,2CAAqC;AACrC,yCAA8D;AAE9D,sBAAsB;AAEtB,yBAAyB;AACzB,MAAM,IAAI,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAA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,GAAG,CAAC,EAAE,CAAC,GAAG,WAAW,EAAE,CAAC,EAAE;gBAAE,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,WAAW,GAAG,CAAC,CAAC,CAAC,CAAC,iBAAiB;YACtG,QAAQ,CAAC,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,yBAAyB;YACvD,UAAU,EAAE,CAAC;QACf,CAAC,CAAC,CAAC;KACJ;IACD,OAAO,YAAY,CAAC,QAAQ,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;AAClD,CAAC;AAzBD,kCAyBC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/sha1.d.ts b/node_modules/@noble/hashes/sha1.d.ts new file mode 100644 index 0000000..d9cb132 --- /dev/null +++ b/node_modules/@noble/hashes/sha1.d.ts @@ -0,0 +1,21 @@ +import { SHA2 } from './_sha2.js'; +declare class SHA1 extends SHA2 { + private A; + private B; + private C; + private D; + private E; + constructor(); + protected get(): [number, number, number, number, number]; + protected set(A: number, B: number, C: number, D: number, E: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +export declare const sha1: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export {}; diff --git a/node_modules/@noble/hashes/sha1.js b/node_modules/@noble/hashes/sha1.js new file mode 100644 index 0000000..8eff8bb --- /dev/null +++ b/node_modules/@noble/hashes/sha1.js @@ -0,0 +1,88 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha1 = void 0; +const _sha2_js_1 = require("./_sha2.js"); +const utils_js_1 = require("./utils.js"); +// SHA1 was cryptographically broken. +// It is still widely used in legacy apps. Don't use it for a new protocol. +// RFC 3174 +const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +// Initial state +const IV = new Uint32Array([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = new Uint32Array(80); +class SHA1 extends _sha2_js_1.SHA2 { + constructor() { + super(64, 20, 8, false); + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + } + get() { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + set(A, B, C, D, E) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } + else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } + else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } + else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +exports.sha1 = (0, utils_js_1.wrapConstructor)(() => new SHA1()); +//# sourceMappingURL=sha1.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/sha1.js.map b/node_modules/@noble/hashes/sha1.js.map new file mode 100644 index 0000000..c099ccb --- /dev/null +++ b/node_modules/@noble/hashes/sha1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha1.js","sourceRoot":"","sources":["src/sha1.ts"],"names":[],"mappings":";;;AAAA,yCAAkC;AAClC,yCAA6C;AAE7C,qCAAqC;AACrC,2EAA2E;AAE3E,WAAW;AACX,MAAM,IAAI,GAAG,CAAC,IAAY,EAAE,KAAa,EAAE,EAAE,CAAC,CAAC,IAAI,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,KAAK,CAAC,EAAE,GAAG,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;AAChG,oBAAoB;AACpB,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AACpE,oDAAoD;AACpD,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAE7E,gBAAgB;AAChB,MAAM,EAAE,GAAG,IAAI,WAAW,CAAC,CAAC,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC;AAEzF,4DAA4D;AAC5D,mDAAmD;AACnD,MAAM,MAAM,GAAG,IAAI,WAAW,CAAC,EAAE,CAAC,CAAC;AACnC,MAAM,IAAK,SAAQ,eAAU;IAO3B;QACE,KAAK,CAAC,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC;Q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CAAC,GAAG,CAAC,CAAC;SACP;QACD,qDAAqD;QACrD,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC1B,CAAC;IACS,UAAU;QAClB,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACjB,CAAC;IACD,OAAO;QACL,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QACxB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACtB,CAAC;CACF;AAEY,QAAA,IAAI,GAAG,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/sha256.d.ts b/node_modules/@noble/hashes/sha256.d.ts new file mode 100644 index 0000000..3e1491d --- /dev/null +++ b/node_modules/@noble/hashes/sha256.d.ts @@ -0,0 +1,34 @@ +import { SHA2 } from './_sha2.js'; +declare class SHA256 extends SHA2 { + A: number; + B: number; + C: number; + D: number; + E: number; + F: number; + G: number; + H: number; + constructor(); + protected get(): [number, number, number, number, number, number, number, number]; + protected set(A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +export declare const sha256: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha224: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export {}; diff --git a/node_modules/@noble/hashes/sha256.js b/node_modules/@noble/hashes/sha256.js new file mode 100644 index 0000000..7f897a4 --- /dev/null +++ b/node_modules/@noble/hashes/sha256.js @@ -0,0 +1,127 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha224 = exports.sha256 = void 0; +const _sha2_js_1 = require("./_sha2.js"); +const utils_js_1 = require("./utils.js"); +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); +// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): +// prettier-ignore +const IV = new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = new Uint32Array(64); +class SHA256 extends _sha2_js_1.SHA2 { + constructor() { + super(64, 32, 8, false); + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + this.F = IV[5] | 0; + this.G = IV[6] | 0; + this.H = IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = (0, utils_js_1.rotr)(W15, 7) ^ (0, utils_js_1.rotr)(W15, 18) ^ (W15 >>> 3); + const s1 = (0, utils_js_1.rotr)(W2, 17) ^ (0, utils_js_1.rotr)(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = (0, utils_js_1.rotr)(E, 6) ^ (0, utils_js_1.rotr)(E, 11) ^ (0, utils_js_1.rotr)(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = (0, utils_js_1.rotr)(A, 2) ^ (0, utils_js_1.rotr)(A, 13) ^ (0, utils_js_1.rotr)(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + constructor() { + super(); + this.A = 0xc1059ed8 | 0; + this.B = 0x367cd507 | 0; + this.C = 0x3070dd17 | 0; + this.D = 0xf70e5939 | 0; + this.E = 0xffc00b31 | 0; + this.F = 0x68581511 | 0; + this.G = 0x64f98fa7 | 0; + this.H = 0xbefa4fa4 | 0; + this.outputLen = 28; + } +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +exports.sha256 = (0, utils_js_1.wrapConstructor)(() => new SHA256()); +exports.sha224 = (0, utils_js_1.wrapConstructor)(() => new SHA224()); +//# sourceMappingURL=sha256.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/sha256.js.map b/node_modules/@noble/hashes/sha256.js.map new file mode 100644 index 0000000..28623a9 --- /dev/null +++ b/node_modules/@noble/hashes/s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AAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QACjC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACtB,CAAC;CACF;AACD,4EAA4E;AAC5E,MAAM,MAAO,SAAQ,MAAM;IASzB;QACE,KAAK,EAAE,CAAC;QATV,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QAGjB,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;IACtB,CAAC;CACF;AAED;;;GAGG;AACU,QAAA,MAAM,GAAG,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC;AAC7C,QAAA,MAAM,GAAG,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/sha3-addons.d.ts b/node_modules/@noble/hashes/sha3-addons.d.ts new file mode 100644 index 0000000..f6ae900 --- /dev/null +++ b/node_modules/@noble/hashes/sha3-addons.d.ts @@ -0,0 +1,138 @@ +import { Input, Hash, HashXOF } from './utils.js'; +import { Keccak, ShakeOpts } from './sha3.js'; +export type cShakeOpts = ShakeOpts & { + personalization?: Input; + NISTfn?: Input; +}; +export declare const cshake128: { + (msg: Input, opts?: cShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: cShakeOpts): Hash; +}; +export declare const cshake256: { + (msg: Input, opts?: cShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: cShakeOpts): Hash; +}; +declare class KMAC extends Keccak implements HashXOF { + constructor(blockLen: number, outputLen: number, enableXOF: boolean, key: Input, opts?: cShakeOpts); + protected finish(): void; + _cloneInto(to?: KMAC): KMAC; + clone(): KMAC; +} +export declare const kmac128: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +export declare const kmac256: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +export declare const kmac128xof: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +export declare const kmac256xof: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +declare class TupleHash extends Keccak implements HashXOF { + constructor(blockLen: number, outputLen: number, enableXOF: boolean, opts?: cShakeOpts); + protected finish(): void; + _cloneInto(to?: TupleHash): TupleHash; + clone(): TupleHash; +} +export declare const tuplehash128: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +export declare const tuplehash256: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +export declare const tuplehash128xof: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +export declare const tuplehash256xof: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +type ParallelOpts = cShakeOpts & { + blockLen?: number; +}; +declare class ParallelHash extends Keccak implements HashXOF { + protected leafCons: () => Hash; + private leafHash?; + private chunkPos; + private chunksDone; + private chunkLen; + constructor(blockLen: number, outputLen: number, leafCons: () => Hash, enableXOF: boolean, opts?: ParallelOpts); + protected finish(): void; + _cloneInto(to?: ParallelHash): ParallelHash; + destroy(): void; + clone(): ParallelHash; +} +export declare const parallelhash128: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export declare const parallelhash256: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export declare const parallelhash128xof: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export declare const parallelhash256xof: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export type KangarooOpts = { + dkLen?: number; + personalization?: Input; +}; +declare class KangarooTwelve extends Keccak implements HashXOF { + protected leafLen: number; + readonly chunkLen = 8192; + private leafHash?; + private personalization; + private chunkPos; + private chunksDone; + constructor(blockLen: number, leafLen: number, outputLen: number, rounds: number, opts: KangarooOpts); + update(data: Input): this; + protected finish(): void; + destroy(): void; + _cloneInto(to?: KangarooTwelve): KangarooTwelve; + clone(): KangarooTwelve; +} +export declare const k12: { + (msg: Input, opts?: KangarooOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: KangarooOpts): Hash; +}; +export declare const m14: { + (msg: Input, opts?: KangarooOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: KangarooOpts): Hash; +}; +declare class KeccakPRG extends Keccak { + protected rate: number; + constructor(capacity: number); + keccak(): void; + update(data: Input): this; + feed(data: Input): this; + protected finish(): void; + digestInto(out: Uint8Array): Uint8Array; + fetch(bytes: number): Uint8Array; + forget(): void; + _cloneInto(to?: KeccakPRG): KeccakPRG; + clone(): KeccakPRG; +} +export declare const keccakprg: (capacity?: number) => KeccakPRG; +export {}; diff --git a/node_modules/@noble/hashes/sha3-addons.js b/node_modules/@noble/hashes/sha3-addons.js new file mode 100644 index 0000000..1ac012d --- /dev/null +++ b/node_modules/@noble/hashes/sha3-addons.js @@ -0,0 +1,351 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.keccakprg = exports.m14 = exports.k12 = exports.parallelhash256xof = exports.parallelhash128xof = exports.parallelhash256 = exports.parallelhash128 = exports.tuplehash256xof = exports.tuplehash128xof = exports.tuplehash256 = exports.tuplehash128 = exports.kmac256xof = exports.kmac128xof = exports.kmac256 = exports.kmac128 = exports.cshake256 = exports.cshake128 = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +const sha3_js_1 = require("./sha3.js"); +// cSHAKE && KMAC (NIST SP800-185) +function leftEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.unshift(res.length); + return new Uint8Array(res); +} +function rightEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +function chooseLen(opts, outputLen) { + return opts.dkLen === undefined ? outputLen : opts.dkLen; +} +const toBytesOptional = (buf) => (buf !== undefined ? (0, utils_js_1.toBytes)(buf) : new Uint8Array([])); +// NOTE: second modulo is necessary since we don't need to add padding if current element takes whole block +const getPadding = (len, block) => new Uint8Array((block - (len % block)) % block); +// Personalization +function cshakePers(hash, opts = {}) { + if (!opts || (!opts.personalization && !opts.NISTfn)) + return hash; + // Encode and pad inplace to avoid unneccesary memory copies/slices (so we don't need to zero them later) + // bytepad(encode_string(N) || encode_string(S), 168) + const blockLenBytes = leftEncode(hash.blockLen); + const fn = toBytesOptional(opts.NISTfn); + const fnLen = leftEncode(8 * fn.length); // length in bits + const pers = toBytesOptional(opts.personalization); + const persLen = leftEncode(8 * pers.length); // length in bits + if (!fn.length && !pers.length) + return hash; + hash.suffix = 0x04; + hash.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers); + let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length; + hash.update(getPadding(totalLen, hash.blockLen)); + return hash; +} +const gencShake = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapConstructorWithOpts)((opts = {}) => cshakePers(new sha3_js_1.Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts)); +exports.cshake128 = (() => gencShake(0x1f, 168, 128 / 8))(); +exports.cshake256 = (() => gencShake(0x1f, 136, 256 / 8))(); +class KMAC extends sha3_js_1.Keccak { + constructor(blockLen, outputLen, enableXOF, key, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'KMAC', personalization: opts.personalization }); + key = (0, utils_js_1.toBytes)(key); + // 1. newX = bytepad(encode_string(K), 168) || X || right_encode(L). + const blockLenBytes = leftEncode(this.blockLen); + const keyLen = leftEncode(8 * key.length); + this.update(blockLenBytes).update(keyLen).update(key); + const totalLen = blockLenBytes.length + keyLen.length + key.length; + this.update(getPadding(totalLen, this.blockLen)); + } + finish() { + if (!this.finished) + this.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + // Force "to" to be instance of KMAC instead of Sha3. + if (!to) { + to = Object.create(Object.getPrototypeOf(this), {}); + to.state = this.state.slice(); + to.blockLen = this.blockLen; + to.state32 = (0, utils_js_1.u32)(to.state); + } + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genKmac(blockLen, outputLen, xof = false) { + const kmac = (key, message, opts) => kmac.create(key, opts).update(message).digest(); + kmac.create = (key, opts = {}) => new KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts); + return kmac; +} +exports.kmac128 = (() => genKmac(168, 128 / 8))(); +exports.kmac256 = (() => genKmac(136, 256 / 8))(); +exports.kmac128xof = (() => genKmac(168, 128 / 8, true))(); +exports.kmac256xof = (() => genKmac(136, 256 / 8, true))(); +// TupleHash +// Usage: tuple(['ab', 'cd']) != tuple(['a', 'bcd']) +class TupleHash extends sha3_js_1.Keccak { + constructor(blockLen, outputLen, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'TupleHash', personalization: opts.personalization }); + // Change update after cshake processed + this.update = (data) => { + data = (0, utils_js_1.toBytes)(data); + super.update(leftEncode(data.length * 8)); + super.update(data); + return this; + }; + } + finish() { + if (!this.finished) + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new TupleHash(this.blockLen, this.outputLen, this.enableXOF)); + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genTuple(blockLen, outputLen, xof = false) { + const tuple = (messages, opts) => { + const h = tuple.create(opts); + for (const msg of messages) + h.update(msg); + return h.digest(); + }; + tuple.create = (opts = {}) => new TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts); + return tuple; +} +exports.tuplehash128 = (() => genTuple(168, 128 / 8))(); +exports.tuplehash256 = (() => genTuple(136, 256 / 8))(); +exports.tuplehash128xof = (() => genTuple(168, 128 / 8, true))(); +exports.tuplehash256xof = (() => genTuple(136, 256 / 8, true))(); +class ParallelHash extends sha3_js_1.Keccak { + constructor(blockLen, outputLen, leafCons, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + this.leafCons = leafCons; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + cshakePers(this, { NISTfn: 'ParallelHash', personalization: opts.personalization }); + let { blockLen: B } = opts; + B || (B = 8); + (0, _assert_js_1.number)(B); + this.chunkLen = B; + super.update(leftEncode(B)); + // Change update after cshake processed + this.update = (data) => { + data = (0, utils_js_1.toBytes)(data); + const { chunkLen, leafCons } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen || !this.leafHash) { + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + this.leafHash = leafCons(); + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + this.leafHash.update(data.subarray(pos, pos + take)); + this.chunkPos += take; + pos += take; + } + return this; + }; + } + finish() { + if (this.finished) + return; + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + super.update(rightEncode(this.chunksDone)); + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF)); + if (this.leafHash) + to.leafHash = this.leafHash._cloneInto(to.leafHash); + to.chunkPos = this.chunkPos; + to.chunkLen = this.chunkLen; + to.chunksDone = this.chunksDone; + return super._cloneInto(to); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + } + clone() { + return this._cloneInto(); + } +} +function genPrl(blockLen, outputLen, leaf, xof = false) { + const parallel = (message, opts) => parallel.create(opts).update(message).digest(); + parallel.create = (opts = {}) => new ParallelHash(blockLen, chooseLen(opts, outputLen), () => leaf.create({ dkLen: 2 * outputLen }), xof, opts); + return parallel; +} +exports.parallelhash128 = (() => genPrl(168, 128 / 8, exports.cshake128))(); +exports.parallelhash256 = (() => genPrl(136, 256 / 8, exports.cshake256))(); +exports.parallelhash128xof = (() => genPrl(168, 128 / 8, exports.cshake128, true))(); +exports.parallelhash256xof = (() => genPrl(136, 256 / 8, exports.cshake256, true))(); +// Kangaroo +// Same as NIST rightEncode, but returns [0] for zero string +function rightEncodeK12(n) { + const res = []; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +const EMPTY = new Uint8Array([]); +class KangarooTwelve extends sha3_js_1.Keccak { + constructor(blockLen, leafLen, outputLen, rounds, opts) { + super(blockLen, 0x07, outputLen, true, rounds); + this.leafLen = leafLen; + this.chunkLen = 8192; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + const { personalization } = opts; + this.personalization = toBytesOptional(personalization); + } + update(data) { + data = (0, utils_js_1.toBytes)(data); + const { chunkLen, blockLen, leafLen, rounds } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen) { + if (this.leafHash) + super.update(this.leafHash.digest()); + else { + this.suffix = 0x06; // Its safe to change suffix here since its used only in digest() + super.update(new Uint8Array([3, 0, 0, 0, 0, 0, 0, 0])); + } + this.leafHash = new sha3_js_1.Keccak(blockLen, 0x0b, leafLen, false, rounds); + this.chunksDone++; + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + const chunk = data.subarray(pos, pos + take); + if (this.leafHash) + this.leafHash.update(chunk); + else + super.update(chunk); + this.chunkPos += take; + pos += take; + } + return this; + } + finish() { + if (this.finished) + return; + const { personalization } = this; + this.update(personalization).update(rightEncodeK12(personalization.length)); + // Leaf hash + if (this.leafHash) { + super.update(this.leafHash.digest()); + super.update(rightEncodeK12(this.chunksDone)); + super.update(new Uint8Array([0xff, 0xff])); + } + super.finish.call(this); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + // We cannot zero personalization buffer since it is user provided and we don't want to mutate user input + this.personalization = EMPTY; + } + _cloneInto(to) { + const { blockLen, leafLen, leafHash, outputLen, rounds } = this; + to || (to = new KangarooTwelve(blockLen, leafLen, outputLen, rounds, {})); + super._cloneInto(to); + if (leafHash) + to.leafHash = leafHash._cloneInto(to.leafHash); + to.personalization.set(this.personalization); + to.leafLen = this.leafLen; + to.chunkPos = this.chunkPos; + to.chunksDone = this.chunksDone; + return to; + } + clone() { + return this._cloneInto(); + } +} +// Default to 32 bytes, so it can be used without opts +exports.k12 = (() => (0, utils_js_1.wrapConstructorWithOpts)((opts = {}) => new KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts)))(); +// MarsupilamiFourteen +exports.m14 = (() => (0, utils_js_1.wrapConstructorWithOpts)((opts = {}) => new KangarooTwelve(136, 64, chooseLen(opts, 64), 14, opts)))(); +// https://keccak.team/files/CSF-0.1.pdf +// + https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG +class KeccakPRG extends sha3_js_1.Keccak { + constructor(capacity) { + (0, _assert_js_1.number)(capacity); + // Rho should be full bytes + if (capacity < 0 || capacity > 1600 - 10 || (1600 - capacity - 2) % 8) + throw new Error('KeccakPRG: Invalid capacity'); + // blockLen = rho in bytes + super((1600 - capacity - 2) / 8, 0, 0, true); + this.rate = 1600 - capacity; + this.posOut = Math.floor((this.rate + 7) / 8); + } + keccak() { + // Duplex padding + this.state[this.pos] ^= 0x01; + this.state[this.blockLen] ^= 0x02; // Rho is full bytes + super.keccak(); + this.pos = 0; + this.posOut = 0; + } + update(data) { + super.update(data); + this.posOut = this.blockLen; + return this; + } + feed(data) { + return this.update(data); + } + finish() { } + digestInto(out) { + throw new Error('KeccakPRG: digest is not allowed, please use .fetch instead.'); + } + fetch(bytes) { + return this.xof(bytes); + } + // Ensure irreversibility (even if state leaked previous outputs cannot be computed) + forget() { + if (this.rate < 1600 / 2 + 1) + throw new Error('KeccakPRG: rate too low to use forget'); + this.keccak(); + for (let i = 0; i < this.blockLen; i++) + this.state[i] = 0; + this.pos = this.blockLen; + this.keccak(); + this.posOut = this.blockLen; + } + _cloneInto(to) { + const { rate } = this; + to || (to = new KeccakPRG(1600 - rate)); + super._cloneInto(to); + to.rate = rate; + return to; + } + clone() { + return this._cloneInto(); + } +} +const keccakprg = (capacity = 254) => new KeccakPRG(capacity); +exports.keccakprg = keccakprg; +//# sourceMappingURL=sha3-addons.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/sha3-addons.js.map b/node_modules/@noble/hashes/sha3-addons.js.map new file mode 100644 index 0000000..406aeaa --- /dev/null +++ b/node_modules/@noble/hashes/sha3-addons.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3-addons.js","sourceRoot":"","sources":["src/sha3-addons.ts"],"names":[],"mappings":";;;AAAA,6CAAsD;AACtD,yCAAyF;AACzF,uCAA8C;AAC9C,kCAAkC;AAClC,SAAS,UAAU,CAAC,CAAS;IAC3B,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IACvB,CAAC,KAAK,CAAC,CAAC;IACR,OAAO,CAAC,GAAG,CAAC,E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AAC;IACD,KAAK,CAAC,KAAa;QACjB,OAAO,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACzB,CAAC;IACD,oFAAoF;IACpF,MAAM;QACJ,IAAI,IAAI,CAAC,IAAI,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;QACvF,IAAI,CAAC,MAAM,EAAE,CAAC;QACd,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC,EAAE;YAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QAC1D,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC;QACzB,IAAI,CAAC,MAAM,EAAE,CAAC;QACd,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC;IAC9B,CAAC;IACD,UAAU,CAAC,EAAc;QACvB,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;QACtB,EAAE,KAAF,EAAE,GAAK,IAAI,SAAS,CAAC,IAAI,GAAG,IAAI,CAAC,EAAC;QAClC,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;QACrB,EAAE,CAAC,IAAI,GAAG,IAAI,CAAC;QACf,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,KAAK;QACH,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC;IAC3B,CAAC;CACF;AAEM,MAAM,SAAS,GAAG,CAAC,QAAQ,GAAG,GAAG,EAAE,EAAE,CAAC,IAAI,SAAS,CAAC,QAAQ,CAAC,CAAC;AAAxD,QAAA,SAAS,aAA+C"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/sha3.d.ts b/node_modules/@noble/hashes/sha3.d.ts new file mode 100644 index 0000000..2107cf6 --- /dev/null +++ b/node_modules/@noble/hashes/sha3.d.ts @@ -0,0 +1,97 @@ +import { Hash, Input, HashXOF } from './utils.js'; +export declare function keccakP(s: Uint32Array, rounds?: number): void; +export declare class Keccak extends Hash implements HashXOF { + blockLen: number; + suffix: number; + outputLen: number; + protected enableXOF: boolean; + protected rounds: number; + protected state: Uint8Array; + protected pos: number; + protected posOut: number; + protected finished: boolean; + protected state32: Uint32Array; + protected destroyed: boolean; + constructor(blockLen: number, suffix: number, outputLen: number, enableXOF?: boolean, rounds?: number); + protected keccak(): void; + update(data: Input): this; + protected finish(): void; + protected writeInto(out: Uint8Array): Uint8Array; + xofInto(out: Uint8Array): Uint8Array; + xof(bytes: number): Uint8Array; + digestInto(out: Uint8Array): Uint8Array; + digest(): Uint8Array; + destroy(): void; + _cloneInto(to?: Keccak): Keccak; +} +export declare const sha3_224: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +export declare const sha3_256: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const sha3_384: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const sha3_512: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const keccak_224: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +export declare const keccak_256: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const keccak_384: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const keccak_512: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export type ShakeOpts = { + dkLen?: number; +}; +export declare const shake128: { + (msg: Input, opts?: ShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: ShakeOpts): HashXOF>; +}; +export declare const shake256: { + (msg: Input, opts?: ShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: ShakeOpts): HashXOF>; +}; diff --git a/node_modules/@noble/hashes/sha3.js b/node_modules/@noble/hashes/sha3.js new file mode 100644 index 0000000..7c2779f --- /dev/null +++ b/node_modules/@noble/hashes/sha3.js @@ -0,0 +1,211 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.shake256 = exports.shake128 = exports.keccak_512 = exports.keccak_384 = exports.keccak_256 = exports.keccak_224 = exports.sha3_512 = exports.sha3_384 = exports.sha3_256 = exports.sha3_224 = exports.Keccak = exports.keccakP = void 0; +const _assert_js_1 = require("./_assert.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// Various per round constants calculations +const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []]; +const _0n = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +const _7n = BigInt(7); +const _256n = BigInt(256); +const _0x71n = BigInt(0x71); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) + t ^= _1n << ((_1n << BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = _u64_js_1.default.split(_SHA3_IOTA, true); +// Left rotation (without 0, 32, 64) +const rotlH = (h, l, s) => s > 32 ? _u64_js_1.default.rotlBH(h, l, s) : _u64_js_1.default.rotlSH(h, l, s); +const rotlL = (h, l, s) => s > 32 ? _u64_js_1.default.rotlBL(h, l, s) : _u64_js_1.default.rotlSL(h, l, s); +// Same as keccakf1600, but allows to skip some rounds +function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) + B[x] = s[y + x]; + for (let x = 0; x < 10; x++) + s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} +exports.keccakP = keccakP; +class Keccak extends utils_js_1.Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + // Can be passed from user as dkLen + _assert_js_1.default.number(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = (0, utils_js_1.u32)(this.state); + } + keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + update(data) { + _assert_js_1.default.exists(this); + const { blockLen, state } = this; + data = (0, utils_js_1.toBytes)(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + writeInto(out) { + _assert_js_1.default.exists(this, false); + _assert_js_1.default.bytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) + throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes) { + _assert_js_1.default.number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + _assert_js_1.default.output(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} +exports.Keccak = Keccak; +const gen = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapConstructor)(() => new Keccak(blockLen, suffix, outputLen)); +exports.sha3_224 = gen(0x06, 144, 224 / 8); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +exports.sha3_256 = gen(0x06, 136, 256 / 8); +exports.sha3_384 = gen(0x06, 104, 384 / 8); +exports.sha3_512 = gen(0x06, 72, 512 / 8); +exports.keccak_224 = gen(0x01, 144, 224 / 8); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +exports.keccak_256 = gen(0x01, 136, 256 / 8); +exports.keccak_384 = gen(0x01, 104, 384 / 8); +exports.keccak_512 = gen(0x01, 72, 512 / 8); +const genShake = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapXOFConstructorWithOpts)((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)); +exports.shake128 = genShake(0x1f, 168, 128 / 8); +exports.shake256 = genShake(0x1f, 136, 256 / 8); +//# sourceMappingURL=sha3.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/sha3.js.map b/node_modules/@noble/hashes/sha3.js.map new file mode 100644 index 0000000..829c658 --- /dev/null +++ b/node_modules/@noble/hashes/sha3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3.js","sourceRoot":"","sources":["src/sha3.ts"],"names":[],"mappings":";;;AAAA,6CAAkC;AAClC,uCAA4B;AAC5B,yCAQoB;AAEpB,2CAA2C;AAC3C,MAAM,CAAC,OAAO,EAAE,SAAS,EAAE,UAAU,CAAC,GAAmC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;AACtF,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,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CAAC,CAAC,CAAC;AAClC,QAAA,UAAU,GAAG,GAAG,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;AAClD;;;GAGG;AACU,QAAA,UAAU,GAAG,GAAG,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;AACrC,QAAA,UAAU,GAAG,GAAG,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;AACrC,QAAA,UAAU,GAAG,GAAG,CAAC,IAAI,EAAE,EAAE,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;AAIjD,MAAM,QAAQ,GAAG,CAAC,MAAc,EAAE,QAAgB,EAAE,SAAiB,EAAE,EAAE,CACvE,IAAA,qCAA0B,EACxB,CAAC,OAAkB,EAAE,EAAE,EAAE,CACvB,IAAI,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,CACxF,CAAC;AAES,QAAA,QAAQ,GAAG,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;AACxC,QAAA,QAAQ,GAAG,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/sha512.d.ts b/node_modules/@noble/hashes/sha512.d.ts new file mode 100644 index 0000000..b8ba9b0 --- /dev/null +++ b/node_modules/@noble/hashes/sha512.d.ts @@ -0,0 +1,66 @@ +import { SHA2 } from './_sha2.js'; +export declare class SHA512 extends SHA2 { + Ah: number; + Al: number; + Bh: number; + Bl: number; + Ch: number; + Cl: number; + Dh: number; + Dl: number; + Eh: number; + El: number; + Fh: number; + Fl: number; + Gh: number; + Gl: number; + Hh: number; + Hl: number; + constructor(); + protected get(): [ + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number + ]; + protected set(Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number, Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +export declare const sha512: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha512_224: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha512_256: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha384: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; diff --git a/node_modules/@noble/hashes/sha512.js b/node_modules/@noble/hashes/sha512.js new file mode 100644 index 0000000..951a314 --- /dev/null +++ b/node_modules/@noble/hashes/sha512.js @@ -0,0 +1,235 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha384 = exports.sha512_256 = exports.sha512_224 = exports.sha512 = exports.SHA512 = void 0; +const _sha2_js_1 = require("./_sha2.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = _u64_js_1.default.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))); +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = new Uint32Array(80); +const SHA512_W_L = new Uint32Array(80); +class SHA512 extends _sha2_js_1.SHA2 { + constructor() { + super(128, 64, 16, false); + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x6a09e667 | 0; + this.Al = 0xf3bcc908 | 0; + this.Bh = 0xbb67ae85 | 0; + this.Bl = 0x84caa73b | 0; + this.Ch = 0x3c6ef372 | 0; + this.Cl = 0xfe94f82b | 0; + this.Dh = 0xa54ff53a | 0; + this.Dl = 0x5f1d36f1 | 0; + this.Eh = 0x510e527f | 0; + this.El = 0xade682d1 | 0; + this.Fh = 0x9b05688c | 0; + this.Fl = 0x2b3e6c1f | 0; + this.Gh = 0x1f83d9ab | 0; + this.Gl = 0xfb41bd6b | 0; + this.Hh = 0x5be0cd19 | 0; + this.Hl = 0x137e2179 | 0; + } + // prettier-ignore + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = _u64_js_1.default.rotrSH(W15h, W15l, 1) ^ _u64_js_1.default.rotrSH(W15h, W15l, 8) ^ _u64_js_1.default.shrSH(W15h, W15l, 7); + const s0l = _u64_js_1.default.rotrSL(W15h, W15l, 1) ^ _u64_js_1.default.rotrSL(W15h, W15l, 8) ^ _u64_js_1.default.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = _u64_js_1.default.rotrSH(W2h, W2l, 19) ^ _u64_js_1.default.rotrBH(W2h, W2l, 61) ^ _u64_js_1.default.shrSH(W2h, W2l, 6); + const s1l = _u64_js_1.default.rotrSL(W2h, W2l, 19) ^ _u64_js_1.default.rotrBL(W2h, W2l, 61) ^ _u64_js_1.default.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = _u64_js_1.default.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = _u64_js_1.default.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = _u64_js_1.default.rotrSH(Eh, El, 14) ^ _u64_js_1.default.rotrSH(Eh, El, 18) ^ _u64_js_1.default.rotrBH(Eh, El, 41); + const sigma1l = _u64_js_1.default.rotrSL(Eh, El, 14) ^ _u64_js_1.default.rotrSL(Eh, El, 18) ^ _u64_js_1.default.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = _u64_js_1.default.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = _u64_js_1.default.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = _u64_js_1.default.rotrSH(Ah, Al, 28) ^ _u64_js_1.default.rotrBH(Ah, Al, 34) ^ _u64_js_1.default.rotrBH(Ah, Al, 39); + const sigma0l = _u64_js_1.default.rotrSL(Ah, Al, 28) ^ _u64_js_1.default.rotrBL(Ah, Al, 34) ^ _u64_js_1.default.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = _u64_js_1.default.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = _u64_js_1.default.add3L(T1l, sigma0l, MAJl); + Ah = _u64_js_1.default.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = _u64_js_1.default.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = _u64_js_1.default.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = _u64_js_1.default.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = _u64_js_1.default.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = _u64_js_1.default.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = _u64_js_1.default.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = _u64_js_1.default.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = _u64_js_1.default.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +exports.SHA512 = SHA512; +class SHA512_224 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x8c3d37c8 | 0; + this.Al = 0x19544da2 | 0; + this.Bh = 0x73e19966 | 0; + this.Bl = 0x89dcd4d6 | 0; + this.Ch = 0x1dfab7ae | 0; + this.Cl = 0x32ff9c82 | 0; + this.Dh = 0x679dd514 | 0; + this.Dl = 0x582f9fcf | 0; + this.Eh = 0x0f6d2b69 | 0; + this.El = 0x7bd44da8 | 0; + this.Fh = 0x77e36f73 | 0; + this.Fl = 0x04c48942 | 0; + this.Gh = 0x3f9d85a8 | 0; + this.Gl = 0x6a1d36c8 | 0; + this.Hh = 0x1112e6ad | 0; + this.Hl = 0x91d692a1 | 0; + this.outputLen = 28; + } +} +class SHA512_256 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x22312194 | 0; + this.Al = 0xfc2bf72c | 0; + this.Bh = 0x9f555fa3 | 0; + this.Bl = 0xc84c64c2 | 0; + this.Ch = 0x2393b86b | 0; + this.Cl = 0x6f53b151 | 0; + this.Dh = 0x96387719 | 0; + this.Dl = 0x5940eabd | 0; + this.Eh = 0x96283ee2 | 0; + this.El = 0xa88effe3 | 0; + this.Fh = 0xbe5e1e25 | 0; + this.Fl = 0x53863992 | 0; + this.Gh = 0x2b0199fc | 0; + this.Gl = 0x2c85b8aa | 0; + this.Hh = 0x0eb72ddc | 0; + this.Hl = 0x81c52ca2 | 0; + this.outputLen = 32; + } +} +class SHA384 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0xcbbb9d5d | 0; + this.Al = 0xc1059ed8 | 0; + this.Bh = 0x629a292a | 0; + this.Bl = 0x367cd507 | 0; + this.Ch = 0x9159015a | 0; + this.Cl = 0x3070dd17 | 0; + this.Dh = 0x152fecd8 | 0; + this.Dl = 0xf70e5939 | 0; + this.Eh = 0x67332667 | 0; + this.El = 0xffc00b31 | 0; + this.Fh = 0x8eb44a87 | 0; + this.Fl = 0x68581511 | 0; + this.Gh = 0xdb0c2e0d | 0; + this.Gl = 0x64f98fa7 | 0; + this.Hh = 0x47b5481d | 0; + this.Hl = 0xbefa4fa4 | 0; + this.outputLen = 48; + } +} +exports.sha512 = (0, utils_js_1.wrapConstructor)(() => new SHA512()); +exports.sha512_224 = (0, utils_js_1.wrapConstructor)(() => new SHA512_224()); +exports.sha512_256 = (0, utils_js_1.wrapConstructor)(() => new SHA512_256()); +exports.sha384 = (0, utils_js_1.wrapConstructor)(() => new SHA384()); +//# sourceMappingURL=sha512.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/sha512.js.map b/node_modules/@noble/hashes/sha512.js.map new file mode 100644 index 0000000..5f5cee4 --- /dev/null +++ b/node_modules/@noble/hashes/sha512.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha512.js","sourceRoot":"","sources":["src/sha512.ts"],"names":[],"mappings":";;;AAAA,yCAAkC;AAClC,uCAA4B;AAC5B,yCAA6C;AAE7C,0GAA0G;AAC1G,kBAAkB;AAClB,MAAM,CAAC,SAAS,EAAE,SAAS,CAAC,GAAG,iBAAG,CAAC,KAAK,CAAC;IACvC,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAA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.ts new file mode 100644 index 0000000..492c925 --- /dev/null +++ b/node_modules/@noble/hashes/src/_assert.ts @@ -0,0 +1,49 @@ +export function number(n: number) { + if (!Number.isSafeInteger(n) || n < 0) throw new Error(`Wrong positive integer: ${n}`); +} + +export function bool(b: boolean) { + if (typeof b !== 'boolean') throw new Error(`Expected boolean, not ${b}`); +} + +export function bytes(b: Uint8Array | undefined, ...lengths: number[]) { + if (!(b instanceof Uint8Array)) throw new Error('Expected Uint8Array'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} + +type Hash = { + (data: Uint8Array): Uint8Array; + blockLen: number; + outputLen: number; + create: any; +}; +export function hash(hash: Hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(hash.outputLen); + number(hash.blockLen); +} + +export function exists(instance: any, checkFinished = true) { + if (instance.destroyed) throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called'); +} +export function output(out: any, instance: any) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} + +const assert = { + number, + bool, + bytes, + hash, + exists, + output, +}; + +export default assert; diff --git a/node_modules/@noble/hashes/src/_blake2.ts b/node_modules/@noble/hashes/src/_blake2.ts new file mode 100644 index 0000000..7adabeb --- /dev/null +++ b/node_modules/@noble/hashes/src/_blake2.ts @@ -0,0 +1,125 @@ +import assert from './_assert.js'; +import { Hash, Input, toBytes, u32 } from './utils.js'; +// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. +// prettier-ignore +export const SIGMA = new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, +]); + +export type BlakeOpts = { + dkLen?: number; + key?: Input; + salt?: Input; + personalization?: Input; +}; + +export abstract class BLAKE2> extends Hash { + protected abstract compress(msg: Uint32Array, offset: number, isLast: boolean): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected buffer: Uint8Array; + protected buffer32: Uint32Array; + protected length: number = 0; + protected pos: number = 0; + protected finished = false; + protected destroyed = false; + + constructor( + readonly blockLen: number, + public outputLen: number, + opts: BlakeOpts = {}, + keyLen: number, + saltLen: number, + persLen: number + ) { + super(); + assert.number(blockLen); + assert.number(outputLen); + assert.number(keyLen); + if (outputLen < 0 || outputLen > keyLen) throw new Error('outputLen bigger than keyLen'); + if (opts.key !== undefined && (opts.key.length < 1 || opts.key.length > keyLen)) + throw new Error(`key must be up 1..${keyLen} byte long or undefined`); + if (opts.salt !== undefined && opts.salt.length !== saltLen) + throw new Error(`salt must be ${saltLen} byte long or undefined`); + if (opts.personalization !== undefined && opts.personalization.length !== persLen) + throw new Error(`personalization must be ${persLen} byte long or undefined`); + this.buffer32 = u32((this.buffer = new Uint8Array(blockLen))); + } + update(data: Input) { + assert.exists(this); + // Main difference with other hashes: there is flag for last block, + // so we cannot process current block before we know that there + // is the next one. This significantly complicates logic and reduces ability + // to do zero-copy processing + const { blockLen, buffer, buffer32 } = this; + data = toBytes(data); + const len = data.length; + const offset = data.byteOffset; + const buf = data.buffer; + for (let pos = 0; pos < len; ) { + // If buffer is full and we still have input (don't process last block, same as blake2s) + if (this.pos === blockLen) { + this.compress(buffer32, 0, false); + this.pos = 0; + } + const take = Math.min(blockLen - this.pos, len - pos); + const dataOffset = offset + pos; + // full block && aligned to 4 bytes && not last in input + if (take === blockLen && !(dataOffset % 4) && pos + take < len) { + const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4)); + for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) { + this.length += blockLen; + this.compress(data32, pos32, false); + } + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + this.length += take; + pos += take; + } + return this; + } + digestInto(out: Uint8Array) { + assert.exists(this); + assert.output(out, this); + const { pos, buffer32 } = this; + this.finished = true; + // Padding + this.buffer.subarray(pos).fill(0); + this.compress(buffer32, 0, true); + const out32 = u32(out); + this.get().forEach((v, i) => (out32[i] = v)); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to?: T): T { + const { buffer, length, finished, destroyed, outputLen, pos } = this; + to ||= new (this.constructor as any)({ dkLen: outputLen }) as T; + to.set(...this.get()); + to.length = length; + to.finished = finished; + to.destroyed = destroyed; + to.outputLen = outputLen; + to.buffer.set(buffer); + to.pos = pos; + return to; + } +} diff --git a/node_modules/@noble/hashes/src/_sha2.ts b/node_modules/@noble/hashes/src/_sha2.ts new file mode 100644 index 0000000..15f8f63 --- /dev/null +++ b/node_modules/@noble/hashes/src/_sha2.ts @@ -0,0 +1,118 @@ +import assert from './_assert.js'; +import { Hash, createView, Input, toBytes } from './utils.js'; + +// Polyfill for Safari 14 +function setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void { + if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} + +// Base SHA2 class (RFC 6234) +export abstract class SHA2> extends Hash { + protected abstract process(buf: DataView, offset: number): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected abstract roundClean(): void; + // For partial updates less than block size + protected buffer: Uint8Array; + protected view: DataView; + protected finished = false; + protected length = 0; + protected pos = 0; + protected destroyed = false; + + constructor( + readonly blockLen: number, + public outputLen: number, + readonly padOffset: number, + readonly isLE: boolean + ) { + super(); + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data: Input): this { + assert.exists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input, cast it to view and process + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out: Uint8Array) { + assert.exists(this); + assert.output(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + this.buffer.subarray(pos).fill(0); + // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) buffer[i] = 0; + // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to?: T): T { + to ||= new (this.constructor as any)() as T; + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) to.buffer.set(buffer); + return to; + } +} diff --git a/node_modules/@noble/hashes/src/_u64.ts b/node_modules/@noble/hashes/src/_u64.ts new file mode 100644 index 0000000..368de54 --- /dev/null +++ b/node_modules/@noble/hashes/src/_u64.ts @@ -0,0 +1,69 @@ +const U32_MASK64 = BigInt(2 ** 32 - 1); +const _32n = BigInt(32); + +// We are not using BigUint64Array, because they are extremely slow as per 2022 +export function fromBig(n: bigint, le = false) { + if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} + +export function split(lst: bigint[], le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} + +export const toBig = (h: number, l: number) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +// for Shift in [0, 32) +const shrSH = (h: number, l: number, s: number) => h >>> s; +const shrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in [1, 32) +const rotrSH = (h: number, l: number, s: number) => (h >>> s) | (l << (32 - s)); +const rotrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h: number, l: number, s: number) => (h << (64 - s)) | (l >>> (s - 32)); +const rotrBL = (h: number, l: number, s: number) => (h >>> (s - 32)) | (l << (64 - s)); +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (h: number, l: number) => l; +const rotr32L = (h: number, l: number) => h; +// Left rotate for Shift in [1, 32) +const rotlSH = (h: number, l: number, s: number) => (h << s) | (l >>> (32 - s)); +const rotlSL = (h: number, l: number, s: number) => (l << s) | (h >>> (32 - s)); +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h: number, l: number, s: number) => (l << (s - 32)) | (h >>> (64 - s)); +const rotlBL = (h: number, l: number, s: number) => (h << (s - 32)) | (l >>> (64 - s)); + +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +// Removing "export" has 5% perf penalty -_- +export function add(Ah: number, Al: number, Bh: number, Bl: number) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +// Addition with more than 2 elements +const add3L = (Al: number, Bl: number, Cl: number) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +const add3H = (low: number, Ah: number, Bh: number, Ch: number) => + (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +const add4L = (Al: number, Bl: number, Cl: number, Dl: number) => + (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +const add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => + (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +const add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number) => + (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +const add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => + (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; + +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +export default u64; diff --git a/node_modules/@noble/hashes/src/argon2.ts b/node_modules/@noble/hashes/src/argon2.ts new file mode 100644 index 0000000..27852bb --- /dev/null +++ b/node_modules/@noble/hashes/src/argon2.ts @@ -0,0 +1,374 @@ +import assert from './_assert.js'; +import { Input, toBytes, u8, u32 } from './utils.js'; +import { blake2b } from './blake2b.js'; +import u64 from './_u64.js'; + +// Experimental Argon2 RFC 9106 implementation. It may be removed at any time. +enum Types { + Argond2d = 0, + Argon2i = 1, + Argon2id = 2, +} + +const ARGON2_SYNC_POINTS = 4; + +const toBytesOptional = (buf?: Input) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); + +function mul(a: number, b: number) { + const aL = a & 0xffff; + const aH = a >>> 16; + const bL = b & 0xffff; + const bH = b >>> 16; + const ll = Math.imul(aL, bL); + const hl = Math.imul(aH, bL); + const lh = Math.imul(aL, bH); + const hh = Math.imul(aH, bH); + const BUF = ((ll >>> 16) + (hl & 0xffff) + lh) | 0; + const h = ((hl >>> 16) + (BUF >>> 16) + hh) | 0; + return { h, l: (BUF << 16) | (ll & 0xffff) }; +} + +function relPos(areaSize: number, relativePos: number) { + // areaSize - 1 - ((areaSize * ((relativePos ** 2) >>> 32)) >>> 32) + return areaSize - 1 - mul(areaSize, mul(relativePos, relativePos).h).h; +} + +function mul2(a: number, b: number) { + // 2 * a * b (via shifts) + const { h, l } = mul(a, b); + return { h: ((h << 1) | (l >>> 31)) & 0xffff_ffff, l: (l << 1) & 0xffff_ffff }; +} + +function blamka(Ah: number, Al: number, Bh: number, Bl: number) { + const { h: Ch, l: Cl } = mul2(Al, Bl); + // A + B + (2 * A * B) + const Rll = u64.add3L(Al, Bl, Cl); + return { h: u64.add3H(Rll, Ah, Bh, Ch), l: Rll | 0 }; +} + +// Temporary block buffer +const BUF = new Uint32Array(256); + +function G(a: number, b: number, c: number, d: number) { + let Al = BUF[2*a], Ah = BUF[2*a + 1]; // prettier-ignore + let Bl = BUF[2*b], Bh = BUF[2*b + 1]; // prettier-ignore + let Cl = BUF[2*c], Ch = BUF[2*c + 1]; // prettier-ignore + let Dl = BUF[2*d], Dh = BUF[2*d + 1]; // prettier-ignore + + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) }); + + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) }); + + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) }); + + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) }); + + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} + +// prettier-ignore +function P( + v00: number, v01: number, v02: number, v03: number, v04: number, v05: number, v06: number, v07: number, + v08: number, v09: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, +) { + G(v00, v04, v08, v12); + G(v01, v05, v09, v13); + G(v02, v06, v10, v14); + G(v03, v07, v11, v15); + G(v00, v05, v10, v15); + G(v01, v06, v11, v12); + G(v02, v07, v08, v13); + G(v03, v04, v09, v14); +} + +function block(x: Uint32Array, xPos: number, yPos: number, outPos: number, needXor: boolean) { + for (let i = 0; i < 256; i++) BUF[i] = x[xPos + i] ^ x[yPos + i]; + + // columns + for (let i = 0; i < 128; i += 16) { + // prettier-ignore + P( + i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, + i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15 + ); + } + // rows + for (let i = 0; i < 16; i += 2) { + // prettier-ignore + P( + i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, + i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113 + ); + } + + if (needXor) for (let i = 0; i < 256; i++) x[outPos + i] ^= BUF[i] ^ x[xPos + i] ^ x[yPos + i]; + else for (let i = 0; i < 256; i++) x[outPos + i] = BUF[i] ^ x[xPos + i] ^ x[yPos + i]; +} + +// Variable-Length Hash Function H' +function Hp(A: Uint32Array, dkLen: number) { + const A8 = u8(A); + const T = new Uint32Array(1); + const T8 = u8(T); + T[0] = dkLen; + // Fast path + if (dkLen <= 64) return blake2b.create({ dkLen }).update(T8).update(A8).digest(); + const out = new Uint8Array(dkLen); + let V = blake2b.create({}).update(T8).update(A8).digest(); + let pos = 0; + // First block + out.set(V.subarray(0, 32)); + pos += 32; + // Rest blocks + for (; dkLen - pos > 64; pos += 32) out.set((V = blake2b(V)).subarray(0, 32), pos); + // Last block + out.set(blake2b(V, { dkLen: dkLen - pos }), pos); + return u32(out); +} + +function indexAlpha( + r: number, + s: number, + laneLen: number, + segmentLen: number, + index: number, + randL: number, + sameLane: boolean = false +) { + let area; + if (0 == r) { + if (0 == s) area = index - 1; + else if (sameLane) area = s * segmentLen + index - 1; + else area = s * segmentLen + (index == 0 ? -1 : 0); + } else if (sameLane) area = laneLen - segmentLen + index - 1; + else area = laneLen - segmentLen + (index == 0 ? -1 : 0); + const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0; + const rel = relPos(area, randL); + // NOTE: check about overflows here + // absPos = (startPos + relPos) % laneLength; + return (startPos + rel) % laneLen; +} + +// RFC 9106 +export type ArgonOpts = { + t: number; // Time cost, iterations count + m: number; // Memory cost (in KB) + p: number; // Parallelization parameter + version?: number; // Default: 0x13 (19) + key?: Input; // Optional key + personalization?: Input; // Optional arbitrary extra data + dkLen?: number; // Desired number of returned bytes + asyncTick?: number; // Maximum time in ms for which async function can block execution + maxmem?: number; + onProgress?: (progress: number) => void; +}; + +function argon2Init(type: Types, password: Input, salt: Input, opts: ArgonOpts) { + password = toBytes(password); + salt = toBytes(salt); + let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress } = { + ...opts, + version: opts.version || 0x13, + dkLen: opts.dkLen || 32, + maxmem: 2 ** 32, + }; + // Validation + assert.number(p); + assert.number(dkLen); + assert.number(m); + assert.number(t); + assert.number(version); + if (dkLen < 4 || dkLen >= 2 ** 32) throw new Error('Argon2: dkLen should be at least 4 bytes'); + if (dkLen < 1 || p >= 2 ** 32) throw new Error('Argon2: p (paralllelism) should be at least 1'); + if (dkLen < 1 || p >= 2 ** 32) throw new Error('Argon2: t (iterations) should be at least 1'); + if (m < 8 * p) throw new Error(`Argon2: memory should be at least 8*p bytes`); + if (version !== 16 && version !== 19) throw new Error(`Argon2: unknown version=${version}`); + password = toBytes(password); + if (password.length < 0 || password.length >= 2 ** 32) + throw new Error('Argon2: password should be less than 4 GB'); + salt = toBytes(salt); + if (salt.length < 8) throw new Error('Argon2: salt should be at least 8 bytes'); + key = toBytesOptional(key); + personalization = toBytesOptional(personalization); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + // Params + const lanes = p; + // m' = 4 * p * floor (m / 4p) + const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p)); + //q = m' / p columns + const laneLen = Math.floor(mP / p); + const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS); + // H0 + const h = blake2b.create({}); + const BUF = new Uint32Array(1); + const BUF8 = u8(BUF); + for (const i of [p, dkLen, m, t, version, type]) { + if (i < 0 || i >= 2 ** 32) throw new Error(`Argon2: wrong parameter=${i}, expected uint32`); + BUF[0] = i; + h.update(BUF8); + } + for (let i of [password, salt, key, personalization]) { + BUF[0] = i.length; + h.update(BUF8).update(i); + } + const H0 = new Uint32Array(18); + const H0_8 = u8(H0); + h.digestInto(H0_8); + + // 256 u32 = 1024 (BLOCK_SIZE) + const memUsed = mP * 256; + if (memUsed < 0 || memUsed >= 2 ** 32 || memUsed > maxmem) { + throw new Error( + `Argon2: wrong params (memUsed=${memUsed} maxmem=${maxmem}), should be less than 2**32` + ); + } + const B = new Uint32Array(memUsed); + // Fill first blocks + for (let l = 0; l < p; l++) { + const i = 256 * laneLen * l; + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + H0[17] = l; + H0[16] = 0; + B.set(Hp(H0, 1024), i); + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + H0[16] = 1; + B.set(Hp(H0, 1024), i + 256); + } + let perBlock = () => {}; + if (onProgress) { + const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlock / 10000), 1); + let blockCnt = 0; + perBlock = () => { + blockCnt++; + if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock)) + onProgress(blockCnt / totalBlock); + }; + } + return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock }; +} + +function argon2Output(B: Uint32Array, p: number, laneLen: number, dkLen: number) { + const B_final = new Uint32Array(256); + for (let l = 0; l < p; l++) + for (let j = 0; j < 256; j++) B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j]; + return u8(Hp(B_final, dkLen)); +} + +function processBlock( + B: Uint32Array, + address: Uint32Array, + l: number, + r: number, + s: number, + index: number, + laneLen: number, + segmentLen: number, + lanes: number, + offset: number, + prev: number, + dataIndependent: boolean, + needXor: boolean +) { + if (offset % laneLen) prev = offset - 1; + let randL, randH; + if (dataIndependent) { + if (index % 128 === 0) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + randL = address[2 * (index % 128)]; + randH = address[2 * (index % 128) + 1]; + } else { + const T = 256 * prev; + randL = B[T]; + randH = B[T + 1]; + } + // address block + const refLane = r === 0 && s === 0 ? l : randH % lanes; + const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l); + const refBlock = laneLen * refLane + refPos; + // B[i][j] = G(B[i][j-1], B[l][z]) + block(B, 256 * prev, 256 * refBlock, offset * 256, needXor); +} + +function argon2(type: Types, password: Input, salt: Input, opts: ArgonOpts) { + const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init( + type, + password, + salt, + opts + ); + // Pre-loop setup + // [address, input, zero_block] format so we can pass single U32 to block function + const address = new Uint32Array(3 * 256); + address[256 + 6] = mP; + address[256 + 8] = t; + address[256 + 10] = type; + for (let r = 0; r < t; r++) { + const needXor = r !== 0 && version === 0x13; + address[256 + 0] = r; + for (let s = 0; s < ARGON2_SYNC_POINTS; s++) { + address[256 + 4] = s; + const dataIndependent = type == Types.Argon2i || (type == Types.Argon2id && r === 0 && s < 2); + for (let l = 0; l < p; l++) { + address[256 + 2] = l; + address[256 + 12] = 0; + let startPos = 0; + if (r === 0 && s === 0) { + startPos = 2; + if (dataIndependent) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + } + // current block postion + let offset = l * laneLen + s * segmentLen + startPos; + // previous block position + let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1; + for (let index = startPos; index < segmentLen; index++, offset++, prev++) { + perBlock(); + processBlock( + B, + address, + l, + r, + s, + index, + laneLen, + segmentLen, + lanes, + offset, + prev, + dataIndependent, + needXor + ); + } + } + } + } + return argon2Output(B, p, laneLen, dkLen); +} + +export const argon2d = (password: Input, salt: Input, opts: ArgonOpts) => + argon2(Types.Argond2d, password, salt, opts); +export const argon2i = (password: Input, salt: Input, opts: ArgonOpts) => + argon2(Types.Argon2i, password, salt, opts); +export const argon2id = (password: Input, salt: Input, opts: ArgonOpts) => + argon2(Types.Argon2id, password, salt, opts); diff --git a/node_modules/@noble/hashes/src/blake2b.ts b/node_modules/@noble/hashes/src/blake2b.ts new file mode 100644 index 0000000..e2c6e98 --- /dev/null +++ b/node_modules/@noble/hashes/src/blake2b.ts @@ -0,0 +1,203 @@ +import { BLAKE2, BlakeOpts, SIGMA } from './_blake2.js'; +import u64 from './_u64.js'; +import { toBytes, u32, wrapConstructorWithOpts } from './utils.js'; + +// Same as SHA-512 but LE +// prettier-ignore +const IV = new Uint32Array([ + 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, + 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19 +]); +// Temporary buffer +const BUF = new Uint32Array(32); + +// Mixing function G splitted in two halfs +function G1(a: number, b: number, c: number, d: number, msg: Uint32Array, x: number) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 32) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 24) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} + +function G2(a: number, b: number, c: number, d: number, msg: Uint32Array, x: number) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 16) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 63) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} + +class BLAKE2b extends BLAKE2 { + // Same as SHA-512, but LE + private v0l = IV[0] | 0; + private v0h = IV[1] | 0; + private v1l = IV[2] | 0; + private v1h = IV[3] | 0; + private v2l = IV[4] | 0; + private v2h = IV[5] | 0; + private v3l = IV[6] | 0; + private v3h = IV[7] | 0; + private v4l = IV[8] | 0; + private v4h = IV[9] | 0; + private v5l = IV[10] | 0; + private v5h = IV[11] | 0; + private v6l = IV[12] | 0; + private v6h = IV[13] | 0; + private v7l = IV[14] | 0; + private v7h = IV[15] | 0; + + constructor(opts: BlakeOpts = {}) { + super(128, opts.dkLen === undefined ? 64 : opts.dkLen, opts, 64, 16, 16); + const keyLength = opts.key ? opts.key.length : 0; + this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4l ^= salt[0]; + this.v4h ^= salt[1]; + this.v5l ^= salt[2]; + this.v5h ^= salt[3]; + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6l ^= pers[0]; + this.v6h ^= pers[1]; + this.v7l ^= pers[2]; + this.v7h ^= pers[3]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + // prettier-ignore + protected get(): [ + number, number, number, number, number, number, number, number, + number, number, number, number, number, number, number, number + ] { + let {v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h} = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + protected set( + v0l: number, v0h: number, v1l: number, v1h: number, + v2l: number, v2h: number, v3l: number, v3h: number, + v4l: number, v4h: number, v5l: number, v5h: number, + v6l: number, v6h: number, v7l: number, v7h: number + ) { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + protected compress(msg: Uint32Array, offset: number, isLast: boolean) { + this.get().forEach((v, i) => (BUF[i] = v)); // First half from state. + BUF.set(IV, 16); // Second half from IV. + let { h, l } = u64.fromBig(BigInt(this.length)); + BUF[24] = IV[8] ^ l; // Low word of the offset. + BUF[25] = IV[9] ^ h; // High word. + // Invert all bits for last block + if (isLast) { + BUF[28] = ~BUF[28]; + BUF[29] = ~BUF[29]; + } + let j = 0; + const s = SIGMA; + for (let i = 0; i < 12; i++) { + G1(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G2(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G1(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G2(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G1(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G2(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G1(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G2(3, 7, 11, 15, msg, offset + 2 * s[j++]); + + G1(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G2(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G1(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G2(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G1(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G2(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G1(3, 4, 9, 14, msg, offset + 2 * s[j++]); + G2(3, 4, 9, 14, msg, offset + 2 * s[j++]); + } + this.v0l ^= BUF[0] ^ BUF[16]; + this.v0h ^= BUF[1] ^ BUF[17]; + this.v1l ^= BUF[2] ^ BUF[18]; + this.v1h ^= BUF[3] ^ BUF[19]; + this.v2l ^= BUF[4] ^ BUF[20]; + this.v2h ^= BUF[5] ^ BUF[21]; + this.v3l ^= BUF[6] ^ BUF[22]; + this.v3h ^= BUF[7] ^ BUF[23]; + this.v4l ^= BUF[8] ^ BUF[24]; + this.v4h ^= BUF[9] ^ BUF[25]; + this.v5l ^= BUF[10] ^ BUF[26]; + this.v5h ^= BUF[11] ^ BUF[27]; + this.v6l ^= BUF[12] ^ BUF[28]; + this.v6h ^= BUF[13] ^ BUF[29]; + this.v7l ^= BUF[14] ^ BUF[30]; + this.v7h ^= BUF[15] ^ BUF[31]; + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} + +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2b = wrapConstructorWithOpts((opts) => new BLAKE2b(opts)); diff --git a/node_modules/@noble/hashes/src/blake2s.ts b/node_modules/@noble/hashes/src/blake2s.ts new file mode 100644 index 0000000..f5824d4 --- /dev/null +++ b/node_modules/@noble/hashes/src/blake2s.ts @@ -0,0 +1,136 @@ +import { BLAKE2, BlakeOpts, SIGMA } from './_blake2.js'; +import u64 from './_u64.js'; +import { rotr, toBytes, wrapConstructorWithOpts, u32 } from './utils.js'; + +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19) +// same as SHA-256 +// prettier-ignore +export const IV = new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); + +// Mixing function G splitted in two halfs +function G1(a: number, b: number, c: number, d: number, x: number) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 16); + c = (c + d) | 0; + b = rotr(b ^ c, 12); + return { a, b, c, d }; +} + +function G2(a: number, b: number, c: number, d: number, x: number) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 8); + c = (c + d) | 0; + b = rotr(b ^ c, 7); + return { a, b, c, d }; +} +// prettier-ignore +export function compress(s: Uint8Array, offset: number, msg: Uint32Array, rounds: number, + v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, + v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, +) { + let j = 0; + for (let i = 0; i < rounds; i++) { + ({ a: v0, b: v4, c: v8, d: v12 } = G1(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v0, b: v4, c: v8, d: v12 } = G2(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G1(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G2(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G1(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G2(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G1(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G2(v3, v7, v11, v15, msg[offset + s[j++]])); + + ({ a: v0, b: v5, c: v10, d: v15 } = G1(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G2(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G1(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G2(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G1(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G2(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G1(v3, v4, v9, v14, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G2(v3, v4, v9, v14, msg[offset + s[j++]])); + } + return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; +} + +class BLAKE2s extends BLAKE2 { + // Internal state, same as SHA-256 + private v0 = IV[0] | 0; + private v1 = IV[1] | 0; + private v2 = IV[2] | 0; + private v3 = IV[3] | 0; + private v4 = IV[4] | 0; + private v5 = IV[5] | 0; + private v6 = IV[6] | 0; + private v7 = IV[7] | 0; + + constructor(opts: BlakeOpts = {}) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, opts, 32, 8, 8); + const keyLength = opts.key ? opts.key.length : 0; + this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4 ^= salt[0]; + this.v5 ^= salt[1]; + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6 ^= pers[0]; + this.v7 ^= pers[1]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + protected get(): [number, number, number, number, number, number, number, number] { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + protected set( + v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number + ) { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + protected compress(msg: Uint32Array, offset: number, isLast: boolean) { + const { h, l } = u64.fromBig(BigInt(this.length)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = + compress( + SIGMA, offset, msg, 10, + this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, + IV[0], IV[1], IV[2], IV[3], l ^ IV[4], h ^ IV[5], isLast ? ~IV[6] : IV[6], IV[7] + ); + this.v0 ^= v0 ^ v8; + this.v1 ^= v1 ^ v9; + this.v2 ^= v2 ^ v10; + this.v3 ^= v3 ^ v11; + this.v4 ^= v4 ^ v12; + this.v5 ^= v5 ^ v13; + this.v6 ^= v6 ^ v14; + this.v7 ^= v7 ^ v15; + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } +} + +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2s = wrapConstructorWithOpts((opts) => new BLAKE2s(opts)); diff --git a/node_modules/@noble/hashes/src/blake3.ts b/node_modules/@noble/hashes/src/blake3.ts new file mode 100644 index 0000000..873d0da --- /dev/null +++ b/node_modules/@noble/hashes/src/blake3.ts @@ -0,0 +1,246 @@ +import assert from './_assert.js'; +import u64 from './_u64.js'; +import { BLAKE2 } from './_blake2.js'; +import { compress, IV } from './blake2s.js'; +import { Input, u8, u32, toBytes, HashXOF, wrapXOFConstructorWithOpts } from './utils.js'; + +// Flag bitset +enum Flags { + CHUNK_START = 1 << 0, + CHUNK_END = 1 << 1, + PARENT = 1 << 2, + ROOT = 1 << 3, + KEYED_HASH = 1 << 4, + DERIVE_KEY_CONTEXT = 1 << 5, + DERIVE_KEY_MATERIAL = 1 << 6, +} + +const SIGMA: Uint8Array = (() => { + const Id = Array.from({ length: 16 }, (_, i) => i); + const permute = (arr: number[]) => + [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]); + const res: number[] = []; + for (let i = 0, v = Id; i < 7; i++, v = permute(v)) res.push(...v); + return Uint8Array.from(res); +})(); + +// - key: is 256-bit key +// - context: string should be hardcoded, globally unique, and application - specific. +// A good default format for the context string is "[application] [commit timestamp] [purpose]" +// - Only one of 'key' (keyed mode) or 'context' (derive key mode) can be used at same time +export type Blake3Opts = { dkLen?: number; key?: Input; context?: Input }; + +// Why is this so slow? It should be 6x faster than blake2b. +// - There is only 30% reduction in number of rounds from blake2s +// - This function uses tree mode to achive parallelisation via SIMD and threading, +// however in JS we don't have threads and SIMD, so we get only overhead from tree structure +// - It is possible to speed it up via Web Workers, hovewer it will make code singnificantly more +// complicated, which we are trying to avoid, since this library is intended to be used +// for cryptographic purposes. Also, parallelization happens only on chunk level (1024 bytes), +// which won't really benefit small inputs. +class BLAKE3 extends BLAKE2 implements HashXOF { + private IV: Uint32Array; + private flags = 0 | 0; + private state: Uint32Array; + private chunkPos = 0; // Position of current block in chunk + private chunksDone = 0; // How many chunks we already have + private stack: Uint32Array[] = []; + // Output + private posOut = 0; + private bufferOut32 = new Uint32Array(16); + private bufferOut: Uint8Array; + private chunkOut = 0; // index of output chunk + private enableXOF = true; + + constructor(opts: Blake3Opts = {}, flags = 0) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, {}, Number.MAX_SAFE_INTEGER, 0, 0); + this.outputLen = opts.dkLen === undefined ? 32 : opts.dkLen; + assert.number(this.outputLen); + if (opts.key !== undefined && opts.context !== undefined) + throw new Error('Blake3: only key or context can be specified at same time'); + else if (opts.key !== undefined) { + const key = toBytes(opts.key).slice(); + if (key.length !== 32) throw new Error('Blake3: key should be 32 byte'); + this.IV = u32(key); + this.flags = flags | Flags.KEYED_HASH; + } else if (opts.context !== undefined) { + const context_key = new BLAKE3({ dkLen: 32 }, Flags.DERIVE_KEY_CONTEXT) + .update(opts.context) + .digest(); + this.IV = u32(context_key); + this.flags = flags | Flags.DERIVE_KEY_MATERIAL; + } else { + this.IV = IV.slice(); + this.flags = flags; + } + this.state = this.IV.slice(); + this.bufferOut = u8(this.bufferOut32); + } + // Unused + protected get() { + return []; + } + protected set() {} + private b2Compress(counter: number, flags: number, buf: Uint32Array, bufPos: number = 0) { + const { state: s, pos } = this; + const { h, l } = u64.fromBig(BigInt(counter), true); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = + compress( + SIGMA, bufPos, buf, 7, + s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], + IV[0], IV[1], IV[2], IV[3], h, l, pos, flags + ); + s[0] = v0 ^ v8; + s[1] = v1 ^ v9; + s[2] = v2 ^ v10; + s[3] = v3 ^ v11; + s[4] = v4 ^ v12; + s[5] = v5 ^ v13; + s[6] = v6 ^ v14; + s[7] = v7 ^ v15; + } + protected compress(buf: Uint32Array, bufPos: number = 0, isLast: boolean = false) { + // Compress last block + let flags = this.flags; + if (!this.chunkPos) flags |= Flags.CHUNK_START; + if (this.chunkPos === 15 || isLast) flags |= Flags.CHUNK_END; + if (!isLast) this.pos = this.blockLen; + this.b2Compress(this.chunksDone, flags, buf, bufPos); + this.chunkPos += 1; + // If current block is last in chunk (16 blocks), then compress chunks + if (this.chunkPos === 16 || isLast) { + let chunk = this.state; + this.state = this.IV.slice(); + // If not the last one, compress only when there are trailing zeros in chunk counter + // chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed. + // 1 (001) - leaf not finished (just push current chunk to stack) + // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back) + // 3 (011) - last leaf not finished + // 4 (100) - leafs finished at depth=1 and depth=2 + for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) { + if (!(last = this.stack.pop())) break; + this.buffer32.set(last, 0); + this.buffer32.set(chunk, 8); + this.pos = this.blockLen; + this.b2Compress(0, this.flags | Flags.PARENT, this.buffer32, 0); + chunk = this.state; + this.state = this.IV.slice(); + } + this.chunksDone++; + this.chunkPos = 0; + this.stack.push(chunk); + } + this.pos = 0; + } + _cloneInto(to?: BLAKE3): BLAKE3 { + to = super._cloneInto(to) as BLAKE3; + const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this; + to.state.set(state.slice()); + to.stack = stack.map((i) => Uint32Array.from(i)); + to.IV.set(IV); + to.flags = flags; + to.chunkPos = chunkPos; + to.chunksDone = chunksDone; + to.posOut = posOut; + to.chunkOut = chunkOut; + to.enableXOF = this.enableXOF; + to.bufferOut32.set(this.bufferOut32); + return to; + } + destroy() { + this.destroyed = true; + this.state.fill(0); + this.buffer32.fill(0); + this.IV.fill(0); + this.bufferOut32.fill(0); + for (let i of this.stack) i.fill(0); + } + // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8) + private b2CompressOut() { + const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this; + const { h, l } = u64.fromBig(BigInt(this.chunkOut++)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = + compress( + SIGMA, 0, buffer32, 7, + s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], + IV[0], IV[1], IV[2], IV[3], l, h, pos, flags + ); + out32[0] = v0 ^ v8; + out32[1] = v1 ^ v9; + out32[2] = v2 ^ v10; + out32[3] = v3 ^ v11; + out32[4] = v4 ^ v12; + out32[5] = v5 ^ v13; + out32[6] = v6 ^ v14; + out32[7] = v7 ^ v15; + out32[8] = s[0] ^ v8; + out32[9] = s[1] ^ v9; + out32[10] = s[2] ^ v10; + out32[11] = s[3] ^ v11; + out32[12] = s[4] ^ v12; + out32[13] = s[5] ^ v13; + out32[14] = s[6] ^ v14; + out32[15] = s[7] ^ v15; + this.posOut = 0; + } + protected finish() { + if (this.finished) return; + this.finished = true; + // Padding + this.buffer.fill(0, this.pos); + // Process last chunk + let flags = this.flags | Flags.ROOT; + if (this.stack.length) { + flags |= Flags.PARENT; + this.compress(this.buffer32, 0, true); + this.chunksDone = 0; + this.pos = this.blockLen; + } else { + flags |= (!this.chunkPos ? Flags.CHUNK_START : 0) | Flags.CHUNK_END; + } + this.flags = flags; + this.b2CompressOut(); + } + private writeInto(out: Uint8Array) { + assert.exists(this, false); + assert.bytes(out); + this.finish(); + const { blockLen, bufferOut } = this; + for (let pos = 0, len = out.length; pos < len; ) { + if (this.posOut >= blockLen) this.b2CompressOut(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out: Uint8Array): Uint8Array { + if (!this.enableXOF) throw new Error('XOF is not possible after digest call'); + return this.writeInto(out); + } + xof(bytes: number): Uint8Array { + assert.number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out: Uint8Array) { + assert.output(out, this); + if (this.finished) throw new Error('digest() was already called'); + this.enableXOF = false; + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } +} + +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +export const blake3 = wrapXOFConstructorWithOpts((opts) => new BLAKE3(opts)); diff --git a/node_modules/@noble/hashes/src/crypto.ts b/node_modules/@noble/hashes/src/crypto.ts new file mode 100644 index 0000000..eaea6be --- /dev/null +++ b/node_modules/@noble/hashes/src/crypto.ts @@ -0,0 +1,5 @@ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +declare const globalThis: Record | undefined; +export const crypto = + typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; diff --git a/node_modules/@noble/hashes/src/cryptoNode.ts b/node_modules/@noble/hashes/src/cryptoNode.ts new file mode 100644 index 0000000..6fdba9e --- /dev/null +++ b/node_modules/@noble/hashes/src/cryptoNode.ts @@ -0,0 +1,7 @@ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +// The file will throw on node.js 14 and earlier. +// @ts-ignore +import * as nc from 'node:crypto'; +export const crypto = + nc && typeof nc === 'object' && 'webcrypto' in nc ? (nc.webcrypto as any) : undefined; diff --git a/node_modules/@noble/hashes/src/eskdf.ts b/node_modules/@noble/hashes/src/eskdf.ts new file mode 100644 index 0000000..b4c224b --- /dev/null +++ b/node_modules/@noble/hashes/src/eskdf.ts @@ -0,0 +1,183 @@ +import { bytes as assertBytes } from './_assert.js'; +import { hkdf } from './hkdf.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 as _pbkdf2 } from './pbkdf2.js'; +import { scrypt as _scrypt } from './scrypt.js'; +import { bytesToHex, createView, hexToBytes, toBytes } from './utils.js'; + +// A tiny KDF for various applications like AES key-gen. +// Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure". +// Which is good enough: assume sha2-256 retained preimage resistance. + +const SCRYPT_FACTOR = 2 ** 19; +const PBKDF2_FACTOR = 2 ** 17; + +// Scrypt KDF +export function scrypt(password: string, salt: string): Uint8Array { + return _scrypt(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 }); +} + +// PBKDF2-HMAC-SHA256 +export function pbkdf2(password: string, salt: string): Uint8Array { + return _pbkdf2(sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 }); +} + +// Combines two 32-byte byte arrays +function xor32(a: Uint8Array, b: Uint8Array): Uint8Array { + assertBytes(a, 32); + assertBytes(b, 32); + const arr = new Uint8Array(32); + for (let i = 0; i < 32; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} + +function strHasLength(str: string, min: number, max: number): boolean { + return typeof str === 'string' && str.length >= min && str.length <= max; +} + +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +export function deriveMainSeed(username: string, password: string): Uint8Array { + if (!strHasLength(username, 8, 255)) throw new Error('invalid username'); + if (!strHasLength(password, 8, 255)) throw new Error('invalid password'); + const scr = scrypt(password + '\u{1}', username + '\u{1}'); + const pbk = pbkdf2(password + '\u{2}', username + '\u{2}'); + const res = xor32(scr, pbk); + scr.fill(0); + pbk.fill(0); + return res; +} + +type AccountID = number | string; + +/** + * Converts protocol & accountId pair to HKDF salt & info params. + */ +function getSaltInfo(protocol: string, accountId: AccountID = 0) { + // Note that length here also repeats two lines below + // We do an additional length check here to reduce the scope of DoS attacks + if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) { + throw new Error('invalid protocol'); + } + + // Allow string account ids for some protocols + const allowsStr = /^password\d{0,3}|ssh|tor|file$/.test(protocol); + let salt: Uint8Array; // Extract salt. Default is undefined. + if (typeof accountId === 'string') { + if (!allowsStr) throw new Error('accountId must be a number'); + if (!strHasLength(accountId, 1, 255)) throw new Error('accountId must be valid string'); + salt = toBytes(accountId); + } else if (Number.isSafeInteger(accountId)) { + if (accountId < 0 || accountId > 2 ** 32 - 1) throw new Error('invalid accountId'); + // Convert to Big Endian Uint32 + salt = new Uint8Array(4); + createView(salt).setUint32(0, accountId, false); + } else { + throw new Error(`accountId must be a number${allowsStr ? ' or string' : ''}`); + } + const info = toBytes(protocol); + return { salt, info }; +} + +type OptsLength = { keyLength: number }; +type OptsMod = { modulus: bigint }; +type KeyOpts = undefined | OptsLength | OptsMod; + +function countBytes(num: bigint): number { + if (typeof num !== 'bigint' || num <= BigInt(128)) throw new Error('invalid number'); + return Math.ceil(num.toString(2).length / 8); +} + +/** + * Parses keyLength and modulus options to extract length of result key. + * If modulus is used, adds 64 bits to it as per FIPS 186 B.4.1 to combat modulo bias. + */ +function getKeyLength(options: KeyOpts): number { + if (!options || typeof options !== 'object') return 32; + const hasLen = 'keyLength' in options; + const hasMod = 'modulus' in options; + if (hasLen && hasMod) throw new Error('cannot combine keyLength and modulus options'); + if (!hasLen && !hasMod) throw new Error('must have either keyLength or modulus option'); + // FIPS 186 B.4.1 requires at least 64 more bits + const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength; + if (!(typeof l === 'number' && l >= 16 && l <= 8192)) throw new Error('invalid keyLength'); + return l; +} + +/** + * Converts key to bigint and divides it by modulus. Big Endian. + * Implements FIPS 186 B.4.1, which removes 0 and modulo bias from output. + */ +function modReduceKey(key: Uint8Array, modulus: bigint): Uint8Array { + const _1 = BigInt(1); + const num = BigInt('0x' + bytesToHex(key)); // check for ui8a, then bytesToNumber() + const res = (num % (modulus - _1)) + _1; // Remove 0 from output + if (res < _1) throw new Error('expected positive number'); // Guard against bad values + const len = key.length - 8; // FIPS requires 64 more bits = 8 bytes + const hex = res.toString(16).padStart(len * 2, '0'); // numberToHex() + const bytes = hexToBytes(hex); + if (bytes.length !== len) throw new Error('invalid length of result key'); + return bytes; +} + +// We are not using classes because constructor cannot be async +type ESKDF = Promise< + Readonly<{ + /** + * Derives a child key. Child key will not be associated with any + * other child key because of properties of underlying KDF. + * + * @param protocol - 3-15 character protocol name + * @param accountId - numeric identifier of account + * @param options - `keyLength: 64` or `modulus: 41920438n` + * @example deriveChildKey('aes', 0) + */ + deriveChildKey: (protocol: string, accountId: AccountID, options?: KeyOpts) => Uint8Array; + /** + * Deletes the main seed from eskdf instance + */ + expire: () => void; + /** + * Account fingerprint + */ + fingerprint: string; + }> +>; + +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +export async function eskdf(username: string, password: string): ESKDF { + // We are using closure + object instead of class because + // we want to make `seed` non-accessible for any external function. + let seed: Uint8Array | undefined = deriveMainSeed(username, password); + + function deriveCK(protocol: string, accountId: AccountID = 0, options?: KeyOpts): Uint8Array { + assertBytes(seed, 32); + const { salt, info } = getSaltInfo(protocol, accountId); // validate protocol & accountId + const keyLength = getKeyLength(options); // validate options + const key = hkdf(sha256, seed!, salt, info, keyLength); + // Modulus has already been validated + return options && 'modulus' in options ? modReduceKey(key, options.modulus) : key; + } + function expire() { + if (seed) seed.fill(1); + seed = undefined; + } + // prettier-ignore + const fingerprint = Array.from(deriveCK('fingerprint', 0)) + .slice(0, 6) + .map((char) => char.toString(16).padStart(2, '0').toUpperCase()) + .join(':'); + return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint }); +} diff --git a/node_modules/@noble/hashes/src/hkdf.ts b/node_modules/@noble/hashes/src/hkdf.ts new file mode 100644 index 0000000..2605898 --- /dev/null +++ b/node_modules/@noble/hashes/src/hkdf.ts @@ -0,0 +1,79 @@ +import assert from './_assert.js'; +import { CHash, Input, toBytes } from './utils.js'; +import { hmac } from './hmac.js'; + +// HKDF (RFC 5869) +// https://soatok.blog/2021/11/17/understanding-hkdf/ + +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +export function extract(hash: CHash, ikm: Input, salt?: Input) { + assert.hash(hash); + // NOTE: some libraries treat zero-length array as 'not provided'; + // we don't, since we have undefined as 'not provided' + // https://github.com/RustCrypto/KDFs/issues/15 + if (salt === undefined) salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros + return hmac(hash, toBytes(salt), toBytes(ikm)); +} + +// HKDF-Expand(PRK, info, L) -> OKM +const HKDF_COUNTER = new Uint8Array([0]); +const EMPTY_BUFFER = new Uint8Array(); + +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +export function expand(hash: CHash, prk: Input, info?: Input, length: number = 32) { + assert.hash(hash); + assert.number(length); + if (length > 255 * hash.outputLen) throw new Error('Length should be <= 255*HashLen'); + const blocks = Math.ceil(length / hash.outputLen); + if (info === undefined) info = EMPTY_BUFFER; + // first L(ength) octets of T + const okm = new Uint8Array(blocks * hash.outputLen); + // Re-use HMAC instance between blocks + const HMAC = hmac.create(hash, prk); + const HMACTmp = HMAC._cloneInto(); + const T = new Uint8Array(HMAC.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + // T(0) = empty string (zero length) + // T(N) = HMAC-Hash(PRK, T(N-1) | info | N) + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T) + .update(info) + .update(HKDF_COUNTER) + .digestInto(T); + okm.set(T, hash.outputLen * counter); + HMAC._cloneInto(HMACTmp); + } + HMAC.destroy(); + HMACTmp.destroy(); + T.fill(0); + HKDF_COUNTER.fill(0); + return okm.slice(0, length); +} + +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +export const hkdf = ( + hash: CHash, + ikm: Input, + salt: Input | undefined, + info: Input | undefined, + length: number +) => expand(hash, extract(hash, ikm, salt), info, length); diff --git a/node_modules/@noble/hashes/src/hmac.ts b/node_modules/@noble/hashes/src/hmac.ts new file mode 100644 index 0000000..1efd2b7 --- /dev/null +++ b/node_modules/@noble/hashes/src/hmac.ts @@ -0,0 +1,81 @@ +import assert from './_assert.js'; +import { Hash, CHash, Input, toBytes } from './utils.js'; +// HMAC (RFC 2104) +export class HMAC> extends Hash> { + oHash: T; + iHash: T; + blockLen: number; + outputLen: number; + private finished = false; + private destroyed = false; + + constructor(hash: CHash, _key: Input) { + super(); + assert.hash(hash); + const key = toBytes(_key); + this.iHash = hash.create() as T; + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash.create() as T; + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf: Input) { + assert.exists(this); + this.iHash.update(buf); + return this; + } + digestInto(out: Uint8Array) { + assert.exists(this); + assert.bytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to?: HMAC): HMAC { + // Create new instance without calling constructor since key already in state and we don't know it. + to ||= Object.create(Object.getPrototypeOf(this), {}); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to as this; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} + +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +export const hmac = (hash: CHash, key: Input, message: Input): Uint8Array => + new HMAC(hash, key).update(message).digest(); +hmac.create = (hash: CHash, key: Input) => new HMAC(hash, key); diff --git a/node_modules/@noble/hashes/src/index.ts b/node_modules/@noble/hashes/src/index.ts new file mode 100644 index 0000000..1505776 --- /dev/null +++ b/node_modules/@noble/hashes/src/index.ts @@ -0,0 +1 @@ +throw new Error('noble-hashes have no entry-point: consult README for usage'); diff --git a/node_modules/@noble/hashes/src/pbkdf2.ts b/node_modules/@noble/hashes/src/pbkdf2.ts new file mode 100644 index 0000000..2a46476 --- /dev/null +++ b/node_modules/@noble/hashes/src/pbkdf2.ts @@ -0,0 +1,97 @@ +import assert from './_assert.js'; +import { hmac } from './hmac.js'; +import { Hash, CHash, Input, createView, toBytes, checkOpts, asyncLoop } from './utils.js'; + +// PBKDF (RFC 2898) +export type Pbkdf2Opt = { + c: number; // Iterations + dkLen?: number; // Desired key length in bytes (Intended output length in octets of the derived key + asyncTick?: number; // Maximum time in ms for which async function can block execution +}; +// Common prologue and epilogue for sync/async functions +function pbkdf2Init(hash: CHash, _password: Input, _salt: Input, _opts: Pbkdf2Opt) { + assert.hash(hash); + const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + assert.number(c); + assert.number(dkLen); + assert.number(asyncTick); + if (c < 1) throw new Error('PBKDF2: iterations (c) should be >= 1'); + const password = toBytes(_password); + const salt = toBytes(_salt); + // DK = PBKDF2(PRF, Password, Salt, c, dkLen); + const DK = new Uint8Array(dkLen); + // U1 = PRF(Password, Salt + INT_32_BE(i)) + const PRF = hmac.create(hash, password); + const PRFSalt = PRF._cloneInto().update(salt); + return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; +} + +function pbkdf2Output>( + PRF: Hash, + PRFSalt: Hash, + DK: Uint8Array, + prfW: Hash, + u: Uint8Array +) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) prfW.destroy(); + u.fill(0); + return DK; +} + +/** + * PBKDF2-HMAC: RFC 2898 key derivation function + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated + * @param salt - cryptographic salt + * @param opts - {c, dkLen} where c is work factor and dkLen is output message size + */ +export function pbkdf2(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt) { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW: any; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + for (let ui = 1; ui < c; ui++) { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} + +export async function pbkdf2Async(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt) { + const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW: any; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + await asyncLoop(c - 1, asyncTick, (i) => { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i]; + }); + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} diff --git a/node_modules/@noble/hashes/src/ripemd160.ts b/node_modules/@noble/hashes/src/ripemd160.ts new file mode 100644 index 0000000..dff071a --- /dev/null +++ b/node_modules/@noble/hashes/src/ripemd160.ts @@ -0,0 +1,108 @@ +import { SHA2 } from './_sha2.js'; +import { wrapConstructor } from './utils.js'; + +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = Uint8Array.from({ length: 16 }, (_, i) => i); +const Pi = Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) for (let j of [idxL, idxR]) j.push(j[i].map((k) => Rho[k])); + +const shifts = [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => new Uint8Array(i)); + +const shiftsL = idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = idxR.map((idx, i) => idx.map((j) => shifts[i][j])); + +const Kl = new Uint32Array([0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]); +const Kr = new Uint32Array([0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]); +// The rotate left (circular left shift) operation for uint32 +const rotl = (word: number, shift: number) => (word << shift) | (word >>> (32 - shift)); +// It's called f() in spec. +function f(group: number, x: number, y: number, z: number): number { + if (group === 0) return x ^ y ^ z; + else if (group === 1) return (x & y) | (~x & z); + else if (group === 2) return (x | ~y) ^ z; + else if (group === 3) return (x & z) | (y & ~z); + else return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const BUF = new Uint32Array(16); +export class RIPEMD160 extends SHA2 { + private h0 = 0x67452301 | 0; + private h1 = 0xefcdab89 | 0; + private h2 = 0x98badcfe | 0; + private h3 = 0x10325476 | 0; + private h4 = 0xc3d2e1f0 | 0; + + constructor() { + super(64, 20, 8, true); + } + protected get(): [number, number, number, number, number] { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + protected set(h0: number, h1: number, h2: number, h3: number, h4: number) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + protected process(view: DataView, offset: number): void { + for (let i = 0; i < 16; i++, offset += 4) BUF[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, + bl = this.h1 | 0, br = bl, + cl = this.h2 | 0, cr = cl, + dl = this.h3 | 0, dr = dl, + el = this.h4 | 0, er = el; + + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + this.set( + (this.h1 + cl + dr) | 0, + (this.h2 + dl + er) | 0, + (this.h3 + el + ar) | 0, + (this.h4 + al + br) | 0, + (this.h0 + bl + cr) | 0 + ); + } + protected roundClean() { + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} + +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +export const ripemd160 = wrapConstructor(() => new RIPEMD160()); diff --git a/node_modules/@noble/hashes/src/scrypt.ts b/node_modules/@noble/hashes/src/scrypt.ts new file mode 100644 index 0000000..f11b2b5 --- /dev/null +++ b/node_modules/@noble/hashes/src/scrypt.ts @@ -0,0 +1,240 @@ +import assert from './_assert.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 } from './pbkdf2.js'; +import { asyncLoop, checkOpts, Input, u32 } from './utils.js'; + +// RFC 7914 Scrypt KDF + +// Left rotate for uint32 +const rotl = (a: number, b: number) => (a << b) | (a >>> (32 - b)); + +// The main Scrypt loop: uses Salsa extensively. +// Six versions of the function were tried, this is the fastest one. +// prettier-ignore +function XorAndSalsa( + prev: Uint32Array, + pi: number, + input: Uint32Array, + ii: number, + out: Uint32Array, + oi: number +) { + // Based on https://cr.yp.to/salsa20.html + // Xor blocks + let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; + let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; + let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; + let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; + let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; + let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; + let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; + let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; + // Save state to temporary variables (salsa) + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, + x04 = y04, x05 = y05, x06 = y06, x07 = y07, + x08 = y08, x09 = y09, x10 = y10, x11 = y11, + x12 = y12, x13 = y13, x14 = y14, x15 = y15; + // Main loop (salsa) + for (let i = 0; i < 8; i += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); x15 ^= rotl(x14 + x13 | 0, 18); + } + // Write output (salsa) + out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0; +} + +function BlockMix(input: Uint32Array, ii: number, out: Uint32Array, oi: number, r: number) { + // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks) + let head = oi + 0; + let tail = oi + 16 * r; + for (let i = 0; i < 16; i++) out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1] + for (let i = 0; i < r; i++, head += 16, ii += 16) { + // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1 + XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1]) + if (i > 0) tail += 16; // First iteration overwrites tmp value in tail + XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i]) + } +} + +export type ScryptOpts = { + N: number; // cost factor + r: number; // block size + p: number; // parallelization + dkLen?: number; // key length + asyncTick?: number; // block execution max time + maxmem?: number; + onProgress?: (progress: number) => void; +}; + +// Common prologue and epilogue for sync/async functions +function scryptInit(password: Input, salt: Input, _opts?: ScryptOpts) { + // Maxmem - 1GB+1KB by default + const opts = checkOpts( + { + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024, + }, + _opts + ); + const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; + assert.number(N); + assert.number(r); + assert.number(p); + assert.number(dkLen); + assert.number(asyncTick); + assert.number(maxmem); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + const blockSize = 128 * r; + const blockSize32 = blockSize / 4; + if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) { + // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function + // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future. + throw new Error( + 'Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32' + ); + } + if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) { + throw new Error( + 'Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)' + ); + } + if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) { + throw new Error( + 'Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32' + ); + } + const memUsed = blockSize * (N + p); + if (memUsed > maxmem) { + throw new Error( + `Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)` + ); + } + // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor) + // Since it has only one iteration there is no reason to use async variant + const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p }); + const B32 = u32(B); + // Re-used between parallel iterations. Array(iterations) of B + const V = u32(new Uint8Array(blockSize * N)); + const tmp = u32(new Uint8Array(blockSize)); + let blockMixCb = () => {}; + if (onProgress) { + const totalBlockMix = 2 * N * p; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1); + let blockMixCnt = 0; + blockMixCb = () => { + blockMixCnt++; + if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) + onProgress(blockMixCnt / totalBlockMix); + }; + } + return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick }; +} + +function scryptOutput( + password: Input, + dkLen: number, + B: Uint8Array, + V: Uint32Array, + tmp: Uint32Array +) { + const res = pbkdf2(sha256, password, B, { c: 1, dkLen }); + B.fill(0); + V.fill(0); + tmp.fill(0); + return res; +} + +/** + * Scrypt KDF from RFC 7914. + * @param password - pass + * @param salt - salt + * @param opts - parameters + * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + * @returns Derived key + */ +export function scrypt(password: Input, salt: Input, opts: ScryptOpts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit( + password, + salt, + opts + ); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) V[i] = B32[Pi + i]; // V[0] = B[i] + for (let i = 0, pos = 0; i < N - 1; i++) { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + } + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + for (let i = 0; i < N; i++) { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + } + } + return scryptOutput(password, dkLen, B, V, tmp); +} + +/** + * Scrypt KDF from RFC 7914. + */ +export async function scryptAsync(password: Input, salt: Input, opts: ScryptOpts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit( + password, + salt, + opts + ); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) V[i] = B32[Pi + i]; // V[0] = B[i] + let pos = 0; + await asyncLoop(N - 1, asyncTick, (i) => { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + }); + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + await asyncLoop(N, asyncTick, (i) => { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + }); + } + return scryptOutput(password, dkLen, B, V, tmp); +} diff --git a/node_modules/@noble/hashes/src/sha1.ts b/node_modules/@noble/hashes/src/sha1.ts new file mode 100644 index 0000000..80b3686 --- /dev/null +++ b/node_modules/@noble/hashes/src/sha1.ts @@ -0,0 +1,86 @@ +import { SHA2 } from './_sha2.js'; +import { wrapConstructor } from './utils.js'; + +// SHA1 was cryptographically broken. +// It is still widely used in legacy apps. Don't use it for a new protocol. + +// RFC 3174 +const rotl = (word: number, shift: number) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +// Choice: a ? b : c +const Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c); + +// Initial state +const IV = new Uint32Array([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]); + +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = new Uint32Array(80); +class SHA1 extends SHA2 { + private A = IV[0] | 0; + private B = IV[1] | 0; + private C = IV[2] | 0; + private D = IV[3] | 0; + private E = IV[4] | 0; + + constructor() { + super(64, 20, 8, false); + } + protected get(): [number, number, number, number, number] { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + protected set(A: number, B: number, C: number, D: number, E: number) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + protected process(view: DataView, offset: number): void { + for (let i = 0; i < 16; i++, offset += 4) SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + protected roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} + +export const sha1 = wrapConstructor(() => new SHA1()); diff --git a/node_modules/@noble/hashes/src/sha256.ts b/node_modules/@noble/hashes/src/sha256.ts new file mode 100644 index 0000000..76fdd11 --- /dev/null +++ b/node_modules/@noble/hashes/src/sha256.ts @@ -0,0 +1,130 @@ +import { SHA2 } from './_sha2.js'; +import { rotr, wrapConstructor } from './utils.js'; + +// Choice: a ? b : c +const Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c); + +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); + +// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): +// prettier-ignore +const IV = new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); + +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = new Uint32Array(64); +class SHA256 extends SHA2 { + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + A = IV[0] | 0; + B = IV[1] | 0; + C = IV[2] | 0; + D = IV[3] | 0; + E = IV[4] | 0; + F = IV[5] | 0; + G = IV[6] | 0; + H = IV[7] | 0; + + constructor() { + super(64, 32, 8, false); + } + protected get(): [number, number, number, number, number, number, number, number] { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + protected set( + A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number + ) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + protected process(view: DataView, offset: number): void { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + protected roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + A = 0xc1059ed8 | 0; + B = 0x367cd507 | 0; + C = 0x3070dd17 | 0; + D = 0xf70e5939 | 0; + E = 0xffc00b31 | 0; + F = 0x68581511 | 0; + G = 0x64f98fa7 | 0; + H = 0xbefa4fa4 | 0; + constructor() { + super(); + this.outputLen = 28; + } +} + +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +export const sha256 = wrapConstructor(() => new SHA256()); +export const sha224 = wrapConstructor(() => new SHA224()); diff --git a/node_modules/@noble/hashes/src/sha3-addons.ts b/node_modules/@noble/hashes/src/sha3-addons.ts new file mode 100644 index 0000000..1015250 --- /dev/null +++ b/node_modules/@noble/hashes/src/sha3-addons.ts @@ -0,0 +1,398 @@ +import { number as assertNumber } from './_assert.js'; +import { Input, toBytes, wrapConstructorWithOpts, u32, Hash, HashXOF } from './utils.js'; +import { Keccak, ShakeOpts } from './sha3.js'; +// cSHAKE && KMAC (NIST SP800-185) +function leftEncode(n: number): Uint8Array { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) res.unshift(n & 0xff); + res.unshift(res.length); + return new Uint8Array(res); +} + +function rightEncode(n: number): Uint8Array { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} + +function chooseLen(opts: ShakeOpts, outputLen: number): number { + return opts.dkLen === undefined ? outputLen : opts.dkLen; +} + +const toBytesOptional = (buf?: Input) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); +// NOTE: second modulo is necessary since we don't need to add padding if current element takes whole block +const getPadding = (len: number, block: number) => new Uint8Array((block - (len % block)) % block); +export type cShakeOpts = ShakeOpts & { personalization?: Input; NISTfn?: Input }; + +// Personalization +function cshakePers(hash: Keccak, opts: cShakeOpts = {}): Keccak { + if (!opts || (!opts.personalization && !opts.NISTfn)) return hash; + // Encode and pad inplace to avoid unneccesary memory copies/slices (so we don't need to zero them later) + // bytepad(encode_string(N) || encode_string(S), 168) + const blockLenBytes = leftEncode(hash.blockLen); + const fn = toBytesOptional(opts.NISTfn); + const fnLen = leftEncode(8 * fn.length); // length in bits + const pers = toBytesOptional(opts.personalization); + const persLen = leftEncode(8 * pers.length); // length in bits + if (!fn.length && !pers.length) return hash; + hash.suffix = 0x04; + hash.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers); + let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length; + hash.update(getPadding(totalLen, hash.blockLen)); + return hash; +} + +const gencShake = (suffix: number, blockLen: number, outputLen: number) => + wrapConstructorWithOpts((opts: cShakeOpts = {}) => + cshakePers(new Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts) + ); + +export const cshake128 = /* @__PURE__ */ (() => gencShake(0x1f, 168, 128 / 8))(); +export const cshake256 = /* @__PURE__ */ (() => gencShake(0x1f, 136, 256 / 8))(); + +class KMAC extends Keccak implements HashXOF { + constructor( + blockLen: number, + outputLen: number, + enableXOF: boolean, + key: Input, + opts: cShakeOpts = {} + ) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'KMAC', personalization: opts.personalization }); + key = toBytes(key); + // 1. newX = bytepad(encode_string(K), 168) || X || right_encode(L). + const blockLenBytes = leftEncode(this.blockLen); + const keyLen = leftEncode(8 * key.length); + this.update(blockLenBytes).update(keyLen).update(key); + const totalLen = blockLenBytes.length + keyLen.length + key.length; + this.update(getPadding(totalLen, this.blockLen)); + } + protected finish() { + if (!this.finished) this.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to?: KMAC): KMAC { + // Create new instance without calling constructor since key already in state and we don't know it. + // Force "to" to be instance of KMAC instead of Sha3. + if (!to) { + to = Object.create(Object.getPrototypeOf(this), {}) as KMAC; + to.state = this.state.slice(); + to.blockLen = this.blockLen; + to.state32 = u32(to.state); + } + return super._cloneInto(to) as KMAC; + } + clone(): KMAC { + return this._cloneInto(); + } +} + +function genKmac(blockLen: number, outputLen: number, xof = false) { + const kmac = (key: Input, message: Input, opts?: cShakeOpts): Uint8Array => + kmac.create(key, opts).update(message).digest(); + kmac.create = (key: Input, opts: cShakeOpts = {}) => + new KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts); + return kmac; +} + +export const kmac128 = /* @__PURE__ */ (() => genKmac(168, 128 / 8))(); +export const kmac256 = /* @__PURE__ */ (() => genKmac(136, 256 / 8))(); +export const kmac128xof = /* @__PURE__ */ (() => genKmac(168, 128 / 8, true))(); +export const kmac256xof = /* @__PURE__ */ (() => genKmac(136, 256 / 8, true))(); + +// TupleHash +// Usage: tuple(['ab', 'cd']) != tuple(['a', 'bcd']) +class TupleHash extends Keccak implements HashXOF { + constructor(blockLen: number, outputLen: number, enableXOF: boolean, opts: cShakeOpts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'TupleHash', personalization: opts.personalization }); + // Change update after cshake processed + this.update = (data: Input) => { + data = toBytes(data); + super.update(leftEncode(data.length * 8)); + super.update(data); + return this; + }; + } + protected finish() { + if (!this.finished) super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to?: TupleHash): TupleHash { + to ||= new TupleHash(this.blockLen, this.outputLen, this.enableXOF); + return super._cloneInto(to) as TupleHash; + } + clone(): TupleHash { + return this._cloneInto(); + } +} + +function genTuple(blockLen: number, outputLen: number, xof = false) { + const tuple = (messages: Input[], opts?: cShakeOpts): Uint8Array => { + const h = tuple.create(opts); + for (const msg of messages) h.update(msg); + return h.digest(); + }; + tuple.create = (opts: cShakeOpts = {}) => + new TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts); + return tuple; +} + +export const tuplehash128 = /* @__PURE__ */ (() => genTuple(168, 128 / 8))(); +export const tuplehash256 = /* @__PURE__ */ (() => genTuple(136, 256 / 8))(); +export const tuplehash128xof = /* @__PURE__ */ (() => genTuple(168, 128 / 8, true))(); +export const tuplehash256xof = /* @__PURE__ */ (() => genTuple(136, 256 / 8, true))(); + +// ParallelHash (same as K12/M14, but without speedup for inputs less 8kb, reduced number of rounds and more simple) +type ParallelOpts = cShakeOpts & { blockLen?: number }; + +class ParallelHash extends Keccak implements HashXOF { + private leafHash?: Hash; + private chunkPos = 0; // Position of current block in chunk + private chunksDone = 0; // How many chunks we already have + private chunkLen: number; + constructor( + blockLen: number, + outputLen: number, + protected leafCons: () => Hash, + enableXOF: boolean, + opts: ParallelOpts = {} + ) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'ParallelHash', personalization: opts.personalization }); + let { blockLen: B } = opts; + B ||= 8; + assertNumber(B); + this.chunkLen = B; + super.update(leftEncode(B)); + // Change update after cshake processed + this.update = (data: Input) => { + data = toBytes(data); + const { chunkLen, leafCons } = this; + for (let pos = 0, len = data.length; pos < len; ) { + if (this.chunkPos == chunkLen || !this.leafHash) { + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + this.leafHash = leafCons(); + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + this.leafHash.update(data.subarray(pos, pos + take)); + this.chunkPos += take; + pos += take; + } + return this; + }; + } + protected finish() { + if (this.finished) return; + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + super.update(rightEncode(this.chunksDone)); + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to?: ParallelHash): ParallelHash { + to ||= new ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF); + if (this.leafHash) to.leafHash = this.leafHash._cloneInto(to.leafHash as Keccak); + to.chunkPos = this.chunkPos; + to.chunkLen = this.chunkLen; + to.chunksDone = this.chunksDone; + return super._cloneInto(to) as ParallelHash; + } + destroy() { + super.destroy.call(this); + if (this.leafHash) this.leafHash.destroy(); + } + clone(): ParallelHash { + return this._cloneInto(); + } +} + +function genPrl( + blockLen: number, + outputLen: number, + leaf: ReturnType, + xof = false +) { + const parallel = (message: Input, opts?: ParallelOpts): Uint8Array => + parallel.create(opts).update(message).digest(); + parallel.create = (opts: ParallelOpts = {}) => + new ParallelHash( + blockLen, + chooseLen(opts, outputLen), + () => leaf.create({ dkLen: 2 * outputLen }), + xof, + opts + ); + return parallel; +} + +export const parallelhash128 = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128))(); +export const parallelhash256 = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256))(); +export const parallelhash128xof = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128, true))(); +export const parallelhash256xof = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256, true))(); + +// Kangaroo +// Same as NIST rightEncode, but returns [0] for zero string +function rightEncodeK12(n: number): Uint8Array { + const res = []; + for (; n > 0; n >>= 8) res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} + +export type KangarooOpts = { dkLen?: number; personalization?: Input }; +const EMPTY = new Uint8Array([]); + +class KangarooTwelve extends Keccak implements HashXOF { + readonly chunkLen = 8192; + private leafHash?: Keccak; + private personalization: Uint8Array; + private chunkPos = 0; // Position of current block in chunk + private chunksDone = 0; // How many chunks we already have + constructor( + blockLen: number, + protected leafLen: number, + outputLen: number, + rounds: number, + opts: KangarooOpts + ) { + super(blockLen, 0x07, outputLen, true, rounds); + const { personalization } = opts; + this.personalization = toBytesOptional(personalization); + } + update(data: Input) { + data = toBytes(data); + const { chunkLen, blockLen, leafLen, rounds } = this; + for (let pos = 0, len = data.length; pos < len; ) { + if (this.chunkPos == chunkLen) { + if (this.leafHash) super.update(this.leafHash.digest()); + else { + this.suffix = 0x06; // Its safe to change suffix here since its used only in digest() + super.update(new Uint8Array([3, 0, 0, 0, 0, 0, 0, 0])); + } + this.leafHash = new Keccak(blockLen, 0x0b, leafLen, false, rounds); + this.chunksDone++; + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + const chunk = data.subarray(pos, pos + take); + if (this.leafHash) this.leafHash.update(chunk); + else super.update(chunk); + this.chunkPos += take; + pos += take; + } + return this; + } + protected finish() { + if (this.finished) return; + const { personalization } = this; + this.update(personalization).update(rightEncodeK12(personalization.length)); + // Leaf hash + if (this.leafHash) { + super.update(this.leafHash.digest()); + super.update(rightEncodeK12(this.chunksDone)); + super.update(new Uint8Array([0xff, 0xff])); + } + super.finish.call(this); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) this.leafHash.destroy(); + // We cannot zero personalization buffer since it is user provided and we don't want to mutate user input + this.personalization = EMPTY; + } + _cloneInto(to?: KangarooTwelve): KangarooTwelve { + const { blockLen, leafLen, leafHash, outputLen, rounds } = this; + to ||= new KangarooTwelve(blockLen, leafLen, outputLen, rounds, {}); + super._cloneInto(to); + if (leafHash) to.leafHash = leafHash._cloneInto(to.leafHash); + to.personalization.set(this.personalization); + to.leafLen = this.leafLen; + to.chunkPos = this.chunkPos; + to.chunksDone = this.chunksDone; + return to; + } + clone(): KangarooTwelve { + return this._cloneInto(); + } +} +// Default to 32 bytes, so it can be used without opts +export const k12 = /* @__PURE__ */ (() => + wrapConstructorWithOpts( + (opts: KangarooOpts = {}) => new KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts) + ))(); +// MarsupilamiFourteen +export const m14 = /* @__PURE__ */ (() => + wrapConstructorWithOpts( + (opts: KangarooOpts = {}) => new KangarooTwelve(136, 64, chooseLen(opts, 64), 14, opts) + ))(); + +// https://keccak.team/files/CSF-0.1.pdf +// + https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG +class KeccakPRG extends Keccak { + protected rate: number; + constructor(capacity: number) { + assertNumber(capacity); + // Rho should be full bytes + if (capacity < 0 || capacity > 1600 - 10 || (1600 - capacity - 2) % 8) + throw new Error('KeccakPRG: Invalid capacity'); + // blockLen = rho in bytes + super((1600 - capacity - 2) / 8, 0, 0, true); + this.rate = 1600 - capacity; + this.posOut = Math.floor((this.rate + 7) / 8); + } + keccak() { + // Duplex padding + this.state[this.pos] ^= 0x01; + this.state[this.blockLen] ^= 0x02; // Rho is full bytes + super.keccak(); + this.pos = 0; + this.posOut = 0; + } + update(data: Input) { + super.update(data); + this.posOut = this.blockLen; + return this; + } + feed(data: Input) { + return this.update(data); + } + protected finish() {} + digestInto(out: Uint8Array): Uint8Array { + throw new Error('KeccakPRG: digest is not allowed, please use .fetch instead.'); + } + fetch(bytes: number): Uint8Array { + return this.xof(bytes); + } + // Ensure irreversibility (even if state leaked previous outputs cannot be computed) + forget() { + if (this.rate < 1600 / 2 + 1) throw new Error('KeccakPRG: rate too low to use forget'); + this.keccak(); + for (let i = 0; i < this.blockLen; i++) this.state[i] = 0; + this.pos = this.blockLen; + this.keccak(); + this.posOut = this.blockLen; + } + _cloneInto(to?: KeccakPRG): KeccakPRG { + const { rate } = this; + to ||= new KeccakPRG(1600 - rate); + super._cloneInto(to); + to.rate = rate; + return to; + } + clone(): KeccakPRG { + return this._cloneInto(); + } +} + +export const keccakprg = (capacity = 254) => new KeccakPRG(capacity); diff --git a/node_modules/@noble/hashes/src/sha3.ts b/node_modules/@noble/hashes/src/sha3.ts new file mode 100644 index 0000000..6f1b937 --- /dev/null +++ b/node_modules/@noble/hashes/src/sha3.ts @@ -0,0 +1,222 @@ +import assert from './_assert.js'; +import u64 from './_u64.js'; +import { + Hash, + u32, + Input, + toBytes, + wrapConstructor, + wrapXOFConstructorWithOpts, + HashXOF, +} from './utils.js'; + +// Various per round constants calculations +const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA]: [number[], number[], bigint[]] = [[], [], []]; +const _0n = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +const _7n = BigInt(7); +const _256n = BigInt(256); +const _0x71n = BigInt(0x71); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) t ^= _1n << ((_1n << BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = u64.split(_SHA3_IOTA, true); + +// Left rotation (without 0, 32, 64) +const rotlH = (h: number, l: number, s: number) => + s > 32 ? u64.rotlBH(h, l, s) : u64.rotlSH(h, l, s); +const rotlL = (h: number, l: number, s: number) => + s > 32 ? u64.rotlBL(h, l, s) : u64.rotlSL(h, l, s); + +// Same as keccakf1600, but allows to skip some rounds +export function keccakP(s: Uint32Array, rounds: number = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) B[x] = s[y + x]; + for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} + +export class Keccak extends Hash implements HashXOF { + protected state: Uint8Array; + protected pos = 0; + protected posOut = 0; + protected finished = false; + protected state32: Uint32Array; + protected destroyed = false; + // NOTE: we accept arguments in bytes instead of bits here. + constructor( + public blockLen: number, + public suffix: number, + public outputLen: number, + protected enableXOF = false, + protected rounds: number = 24 + ) { + super(); + // Can be passed from user as dkLen + assert.number(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + protected keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + update(data: Input) { + assert.exists(this); + const { blockLen, state } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) this.keccak(); + } + return this; + } + protected finish() { + if (this.finished) return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + protected writeInto(out: Uint8Array): Uint8Array { + assert.exists(this, false); + assert.bytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len; ) { + if (this.posOut >= blockLen) this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out: Uint8Array): Uint8Array { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes: number): Uint8Array { + assert.number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out: Uint8Array) { + assert.output(out, this); + if (this.finished) throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to?: Keccak): Keccak { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} + +const gen = (suffix: number, blockLen: number, outputLen: number) => + wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); + +export const sha3_224 = gen(0x06, 144, 224 / 8); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +export const sha3_256 = gen(0x06, 136, 256 / 8); +export const sha3_384 = gen(0x06, 104, 384 / 8); +export const sha3_512 = gen(0x06, 72, 512 / 8); +export const keccak_224 = gen(0x01, 144, 224 / 8); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +export const keccak_256 = gen(0x01, 136, 256 / 8); +export const keccak_384 = gen(0x01, 104, 384 / 8); +export const keccak_512 = gen(0x01, 72, 512 / 8); + +export type ShakeOpts = { dkLen?: number }; + +const genShake = (suffix: number, blockLen: number, outputLen: number) => + wrapXOFConstructorWithOpts, ShakeOpts>( + (opts: ShakeOpts = {}) => + new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true) + ); + +export const shake128 = genShake(0x1f, 168, 128 / 8); +export const shake256 = genShake(0x1f, 136, 256 / 8); diff --git a/node_modules/@noble/hashes/src/sha512.ts b/node_modules/@noble/hashes/src/sha512.ts new file mode 100644 index 0000000..fd6484e --- /dev/null +++ b/node_modules/@noble/hashes/src/sha512.ts @@ -0,0 +1,247 @@ +import { SHA2 } from './_sha2.js'; +import u64 from './_u64.js'; +import { wrapConstructor } from './utils.js'; + +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = u64.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))); + +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = new Uint32Array(80); +const SHA512_W_L = new Uint32Array(80); + +export class SHA512 extends SHA2 { + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + Ah = 0x6a09e667 | 0; + Al = 0xf3bcc908 | 0; + Bh = 0xbb67ae85 | 0; + Bl = 0x84caa73b | 0; + Ch = 0x3c6ef372 | 0; + Cl = 0xfe94f82b | 0; + Dh = 0xa54ff53a | 0; + Dl = 0x5f1d36f1 | 0; + Eh = 0x510e527f | 0; + El = 0xade682d1 | 0; + Fh = 0x9b05688c | 0; + Fl = 0x2b3e6c1f | 0; + Gh = 0x1f83d9ab | 0; + Gl = 0xfb41bd6b | 0; + Hh = 0x5be0cd19 | 0; + Hl = 0x137e2179 | 0; + + constructor() { + super(128, 64, 16, false); + } + // prettier-ignore + protected get(): [ + number, number, number, number, number, number, number, number, + number, number, number, number, number, number, number, number + ] { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + protected set( + Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number, + Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number + ) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + protected process(view: DataView, offset: number) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); + const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); + const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); + const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); + const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = u64.add3L(T1l, sigma0l, MAJl); + Ah = u64.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + protected roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} + +class SHA512_224 extends SHA512 { + // h -- high 32 bits, l -- low 32 bits + Ah = 0x8c3d37c8 | 0; + Al = 0x19544da2 | 0; + Bh = 0x73e19966 | 0; + Bl = 0x89dcd4d6 | 0; + Ch = 0x1dfab7ae | 0; + Cl = 0x32ff9c82 | 0; + Dh = 0x679dd514 | 0; + Dl = 0x582f9fcf | 0; + Eh = 0x0f6d2b69 | 0; + El = 0x7bd44da8 | 0; + Fh = 0x77e36f73 | 0; + Fl = 0x04c48942 | 0; + Gh = 0x3f9d85a8 | 0; + Gl = 0x6a1d36c8 | 0; + Hh = 0x1112e6ad | 0; + Hl = 0x91d692a1 | 0; + + constructor() { + super(); + this.outputLen = 28; + } +} + +class SHA512_256 extends SHA512 { + // h -- high 32 bits, l -- low 32 bits + Ah = 0x22312194 | 0; + Al = 0xfc2bf72c | 0; + Bh = 0x9f555fa3 | 0; + Bl = 0xc84c64c2 | 0; + Ch = 0x2393b86b | 0; + Cl = 0x6f53b151 | 0; + Dh = 0x96387719 | 0; + Dl = 0x5940eabd | 0; + Eh = 0x96283ee2 | 0; + El = 0xa88effe3 | 0; + Fh = 0xbe5e1e25 | 0; + Fl = 0x53863992 | 0; + Gh = 0x2b0199fc | 0; + Gl = 0x2c85b8aa | 0; + Hh = 0x0eb72ddc | 0; + Hl = 0x81c52ca2 | 0; + + constructor() { + super(); + this.outputLen = 32; + } +} + +class SHA384 extends SHA512 { + // h -- high 32 bits, l -- low 32 bits + Ah = 0xcbbb9d5d | 0; + Al = 0xc1059ed8 | 0; + Bh = 0x629a292a | 0; + Bl = 0x367cd507 | 0; + Ch = 0x9159015a | 0; + Cl = 0x3070dd17 | 0; + Dh = 0x152fecd8 | 0; + Dl = 0xf70e5939 | 0; + Eh = 0x67332667 | 0; + El = 0xffc00b31 | 0; + Fh = 0x8eb44a87 | 0; + Fl = 0x68581511 | 0; + Gh = 0xdb0c2e0d | 0; + Gl = 0x64f98fa7 | 0; + Hh = 0x47b5481d | 0; + Hl = 0xbefa4fa4 | 0; + + constructor() { + super(); + this.outputLen = 48; + } +} + +export const sha512 = wrapConstructor(() => new SHA512()); +export const sha512_224 = wrapConstructor(() => new SHA512_224()); +export const sha512_256 = wrapConstructor(() => new SHA512_256()); +export const sha384 = wrapConstructor(() => new SHA384()); diff --git a/node_modules/@noble/hashes/src/utils.ts b/node_modules/@noble/hashes/src/utils.ts new file mode 100644 index 0000000..ce0d84d --- /dev/null +++ b/node_modules/@noble/hashes/src/utils.ts @@ -0,0 +1,216 @@ +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated, we can just drop the import. +import { crypto } from '@noble/hashes/crypto'; + +// prettier-ignore +export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | + Uint16Array | Int16Array | Uint32Array | Int32Array; + +const u8a = (a: any): a is Uint8Array => a instanceof Uint8Array; +// Cast array to different type +export const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +export const u32 = (arr: TypedArray) => + new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); + +// Cast array to view +export const createView = (arr: TypedArray) => + new DataView(arr.buffer, arr.byteOffset, arr.byteLength); + +// The rotate right (circular right shift) operation for uint32 +export const rotr = (word: number, shift: number) => (word << (32 - shift)) | (word >>> shift); + +// big-endian hardware is rare. Just in case someone still decides to run hashes: +// early-throw an error because we don't support BE yet. +export const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!isLE) throw new Error('Non little-endian hardware is not supported'); + +const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export function bytesToHex(bytes: Uint8Array): string { + if (!u8a(bytes)) throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} + +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export function hexToBytes(hex: string): Uint8Array { + if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} + +// There is no setImmediate in browser and setTimeout is slow. +// call of async fn will return Promise, which will be fullfiled only on +// next scheduler queue processing step and this is exactly what we need. +export const nextTick = async () => {}; + +// Returns control to thread each 'tick' ms to avoid blocking +export async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) continue; + await nextTick(); + ts += diff; + } +} + +// Global symbols in both browsers and Node.js since v11 +// See https://github.com/microsoft/TypeScript/issues/31535 +declare const TextEncoder: any; + +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export function utf8ToBytes(str: string): Uint8Array { + if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} + +export type Input = Uint8Array | string; +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +export function toBytes(data: Input): Uint8Array { + if (typeof data === 'string') data = utf8ToBytes(data); + if (!u8a(data)) throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; +} + +/** + * Copies several Uint8Arrays into one. + */ +export function concatBytes(...arrays: Uint8Array[]): Uint8Array { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} + +// For runtime check if class implements interface +export abstract class Hash> { + abstract blockLen: number; // Bytes per block + abstract outputLen: number; // Bytes in output + abstract update(buf: Input): this; + // Writes digest into buf + abstract digestInto(buf: Uint8Array): void; + abstract digest(): Uint8Array; + /** + * Resets internal state. Makes Hash instance unusable. + * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed + * by user, they will need to manually call `destroy()` when zeroing is necessary. + */ + abstract destroy(): void; + /** + * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()` + * when no options are passed. + * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal + * buffers are overwritten => causes buffer overwrite which is used for digest in some cases. + * There are no guarantees for clean-up because it's impossible in JS. + */ + abstract _cloneInto(to?: T): T; + // Safe version that clones internal state + clone(): T { + return this._cloneInto(); + } +} + +/** + * XOF: streaming API to read digest in chunks. + * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name. + * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot + * destroy state, next call can require more bytes. + */ +export type HashXOF> = Hash & { + xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream + xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf +}; + +// Check if object doens't have custom constructor (like Uint8Array/Array) +const isPlainObject = (obj: any) => + Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object; + +type EmptyObj = {}; +export function checkOpts( + defaults: T1, + opts?: T2 +): T1 & T2 { + if (opts !== undefined && (typeof opts !== 'object' || !isPlainObject(opts))) + throw new Error('Options should be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged as T1 & T2; +} + +export type CHash = ReturnType; + +export function wrapConstructor>(hashCons: () => Hash) { + const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} + +export function wrapConstructorWithOpts, T extends Object>( + hashCons: (opts?: T) => Hash +) { + const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({} as T); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts: T) => hashCons(opts); + return hashC; +} + +export function wrapXOFConstructorWithOpts, T extends Object>( + hashCons: (opts?: T) => HashXOF +) { + const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({} as T); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts: T) => hashCons(opts); + return hashC; +} + +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +export function randomBytes(bytesLength = 32): Uint8Array { + if (crypto && typeof crypto.getRandomValues === 'function') { + return crypto.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error('crypto.getRandomValues must be defined'); +} diff --git a/node_modules/@noble/hashes/utils.d.ts b/node_modules/@noble/hashes/utils.d.ts new file mode 100644 index 0000000..a0017e4 --- /dev/null +++ b/node_modules/@noble/hashes/utils.d.ts @@ -0,0 +1,90 @@ +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | Uint16Array | Int16Array | Uint32Array | Int32Array; +export declare const u8: (arr: TypedArray) => Uint8Array; +export declare const u32: (arr: TypedArray) => Uint32Array; +export declare const createView: (arr: TypedArray) => DataView; +export declare const rotr: (word: number, shift: number) => number; +export declare const isLE: boolean; +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export declare function bytesToHex(bytes: Uint8Array): string; +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export declare function hexToBytes(hex: string): Uint8Array; +export declare const nextTick: () => Promise; +export declare function asyncLoop(iters: number, tick: number, cb: (i: number) => void): Promise; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export declare function utf8ToBytes(str: string): Uint8Array; +export type Input = Uint8Array | string; +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +export declare function toBytes(data: Input): Uint8Array; +/** + * Copies several Uint8Arrays into one. + */ +export declare function concatBytes(...arrays: Uint8Array[]): Uint8Array; +export declare abstract class Hash> { + abstract blockLen: number; + abstract outputLen: number; + abstract update(buf: Input): this; + abstract digestInto(buf: Uint8Array): void; + abstract digest(): Uint8Array; + /** + * Resets internal state. Makes Hash instance unusable. + * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed + * by user, they will need to manually call `destroy()` when zeroing is necessary. + */ + abstract destroy(): void; + /** + * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()` + * when no options are passed. + * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal + * buffers are overwritten => causes buffer overwrite which is used for digest in some cases. + * There are no guarantees for clean-up because it's impossible in JS. + */ + abstract _cloneInto(to?: T): T; + clone(): T; +} +/** + * XOF: streaming API to read digest in chunks. + * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name. + * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot + * destroy state, next call can require more bytes. + */ +export type HashXOF> = Hash & { + xof(bytes: number): Uint8Array; + xofInto(buf: Uint8Array): Uint8Array; +}; +type EmptyObj = {}; +export declare function checkOpts(defaults: T1, opts?: T2): T1 & T2; +export type CHash = ReturnType; +export declare function wrapConstructor>(hashCons: () => Hash): { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare function wrapConstructorWithOpts, T extends Object>(hashCons: (opts?: T) => Hash): { + (msg: Input, opts?: T): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: T): Hash; +}; +export declare function wrapXOFConstructorWithOpts, T extends Object>(hashCons: (opts?: T) => HashXOF): { + (msg: Input, opts?: T): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: T): HashXOF; +}; +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +export declare function randomBytes(bytesLength?: number): Uint8Array; +export {}; diff --git a/node_modules/@noble/hashes/utils.js b/node_modules/@noble/hashes/utils.js new file mode 100644 index 0000000..ffd37be --- /dev/null +++ b/node_modules/@noble/hashes/utils.js @@ -0,0 +1,175 @@ +"use strict"; +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +Object.defineProperty(exports, "__esModule", { value: true }); +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; +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated, we can just drop the import. +const crypto_1 = require("@noble/hashes/crypto"); +const u8a = (a) => a instanceof Uint8Array; +// Cast array to different type +const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +exports.u8 = u8; +const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +exports.u32 = u32; +// Cast array to view +const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +exports.createView = createView; +// The rotate right (circular right shift) operation for uint32 +const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); +exports.rotr = rotr; +// big-endian hardware is rare. Just in case someone still decides to run hashes: +// early-throw an error because we don't support BE yet. +exports.isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!exports.isLE) + throw new Error('Non little-endian hardware is not supported'); +const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +function bytesToHex(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +exports.bytesToHex = bytesToHex; +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} +exports.hexToBytes = hexToBytes; +// There is no setImmediate in browser and setTimeout is slow. +// call of async fn will return Promise, which will be fullfiled only on +// next scheduler queue processing step and this is exactly what we need. +const nextTick = async () => { }; +exports.nextTick = nextTick; +// Returns control to thread each 'tick' ms to avoid blocking +async function asyncLoop(iters, tick, cb) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) + continue; + await (0, exports.nextTick)(); + ts += diff; + } +} +exports.asyncLoop = asyncLoop; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +exports.utf8ToBytes = utf8ToBytes; +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +function toBytes(data) { + if (typeof data === 'string') + data = utf8ToBytes(data); + if (!u8a(data)) + throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; +} +exports.toBytes = toBytes; +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) + throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} +exports.concatBytes = concatBytes; +// For runtime check if class implements interface +class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +exports.Hash = Hash; +// Check if object doens't have custom constructor (like Uint8Array/Array) +const isPlainObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object; +function checkOpts(defaults, opts) { + if (opts !== undefined && (typeof opts !== 'object' || !isPlainObject(opts))) + throw new Error('Options should be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged; +} +exports.checkOpts = checkOpts; +function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +exports.wrapConstructor = wrapConstructor; +function wrapConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +exports.wrapConstructorWithOpts = wrapConstructorWithOpts; +function wrapXOFConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +exports.wrapXOFConstructorWithOpts = wrapXOFConstructorWithOpts; +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +function randomBytes(bytesLength = 32) { + if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') { + return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error('crypto.getRandomValues must be defined'); +} +exports.randomBytes = randomBytes; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/utils.js.map b/node_modules/@noble/hashes/utils.js.map new file mode 100644 index 0000000..b789568 --- /dev/null +++ b/node_modules/@noble/hashes/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["src/utils.ts"],"names":[],"mappings":";AAAA,sEAAsE;;;AAEtE,oFAAoF;AACpF,sEAAsE;AACtE,kEAAkE;AAClE,8DAA8D;AAC9D,+DAA+D;AAC/D,8DAA8D;AAC9D,iDAA8C;AAM9C,MAAM,GAAG,GAAG,CAAC,CAAM,EAAmB,EAAE,CAAC,CAAC,YAAY,UAAU,CAAC;AACjE,+BAA+B;AACxB,MAAM,EAAE,GAAG,CAAC,GAAe,EAAE,EAAE,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;AAArF,QAAA,EAAE,MAAmF;AAC3F,MAAM,GAAG,GAAG,CAAC,GAAe,EAAE,EAAE,CACrC,IAAI,WAAW,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,UAAU,GAAG,CAAC,CAAC,CAAC,CAAC;AADjE,QAAA,GAAG,OAC8D;AAE9E,qBAAqB;AACd,MAAM,UAAU,GAAG,CAAC,GAAe,EAAE,EAAE,CAC5C,IAAI,QAAQ,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;AAD9C,QAAA,UAAU,cACoC;AAE3D,+D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end of file diff --git a/node_modules/@scure/base/LICENSE b/node_modules/@scure/base/LICENSE new file mode 100644 index 0000000..5b91e4c --- /dev/null +++ b/node_modules/@scure/base/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/@scure/base/README.md b/node_modules/@scure/base/README.md new file mode 100644 index 0000000..9e3dbb3 --- /dev/null +++ b/node_modules/@scure/base/README.md @@ -0,0 +1,147 @@ +# scure-base + +Secure, [audited](#security) and 0-dep implementation of bech32, base64, base58, base32 & base16. + +Written in [functional style](#design-rationale), uses chaining, has unique tests which ensure correctness. + +Matches following specs: + +- Bech32, Bech32m: [BIP173](https://en.bitcoin.it/wiki/BIP_0173), [BIP350](https://en.bitcoin.it/wiki/BIP_0350) +- Base16, Base32, Base32Hex, Base64, Base64Url: [RFC 4648](https://datatracker.ietf.org/doc/html/rfc4648) (aka RFC 3548) +- [Base58](https://www.ietf.org/archive/id/draft-msporny-base58-03.txt), [Base58check](https://en.bitcoin.it/wiki/Base58Check_encoding), [Base32 Crockford](https://www.crockford.com/base32.html) + +### This library belongs to *scure* + +> **scure** — secure audited packages for every use case. + +- Independent security audits +- All releases are signed with PGP keys +- Check out all libraries: + [base](https://github.com/paulmillr/scure-base), + [bip32](https://github.com/paulmillr/scure-bip32), + [bip39](https://github.com/paulmillr/scure-bip39) + +## Usage + +> npm install @scure/base + +Or + +> yarn add @scure/base + +```js +const { base16, base32, base64, base58 } = require('@scure/base'); +// Flavors +const { base58xmr, base58xrp, base32hex, base32crockford, base64url } = require('@scure/base'); + +const data = Uint8Array.from([1, 2, 3]); +base64.decode(base64.encode(data)); + +// Everything has the same API except for bech32 and base58check +base32.encode(data); +base16.encode(data); +base32hex.encode(data); + +// bech32 +const { bech32, bech32m } = require('@scure/base'); +const words = bech32.toWords(data); +const be = bech32.encode('prefix', words); +const { prefix, words } = bech32.decode(be); +bech32m.encode('prefix', words); + +// base58check is special-case +// you need to pass sha256() function that returns Uint8Array +const { base58check } = require('@scure/base'); +base58check(sha256).encode(data); + +// Alternative API +const { str, bytes } = require('@scure/base'); +const encoded = str('base64', data); +const data = bytes('base64', encoded); +``` + +## Design rationale + +The code may feel unnecessarily complicated; but actually it's much easier to reason about. +Any encoding library consists of two functions: + +``` +encode(A) -> B +decode(B) -> A + where X = decode(encode(X)) + # encode(decode(X)) can be !== X! + # because decoding can normalize input + +e.g. +base58checksum = { + encode(): { + // checksum + // radix conversion + // alphabet + }, + decode(): { + // alphabet + // radix conversion + // checksum + } +} +``` + +But instead of creating two big functions for each specific case, +we create them from tiny composamble building blocks: + +``` +base58checksum = chain(checksum(), radix(), alphabet()) +``` + +Which is the same as chain/pipe/sequence function in Functional Programming, +but significantly more useful since it enforces same order of execution of encode/decode. +Basically you only define encode (in declarative way) and get correct decode for free. +So, instead of reasoning about two big functions you need only reason about primitives and encode chain. +The design revealed obvious bug in older version of the lib, +where xmr version of base58 had errors in decode's block processing. + +Besides base-encodings, we can reuse the same approach with any encode/decode function +(`bytes2number`, `bytes2u32`, etc). +For example, you can easily encode entropy to mnemonic (BIP-39): + +```ts +export function getCoder(wordlist: string[]) { + if (!Array.isArray(wordlist) || wordlist.length !== 2 ** 11 || typeof wordlist[0] !== 'string') { + throw new Error('Worlist: expected array of 2048 strings'); + } + return mbc.chain(mbu.checksum(1, checksum), mbu.radix2(11, true), mbu.alphabet(wordlist)); +} +``` + +## base58 is O(n^2) and radixes + +`Uint8Array` is represented as big-endian number: + +``` +[1, 2, 3, 4, 5] -> 1*(256**4) + 2*(256**3) 3*(256**2) + 4*(256**1) + 5*(256**0) +where 256 = 2**8 (8 bits per byte) +``` + +which is then converted to a number in another radix/base (16/32/58/64, etc). + +However, generic conversion between bases has [quadratic O(n^2) time complexity](https://cs.stackexchange.com/q/21799). + +Which means base58 has quadratic time complexity too. Use base58 only when you have small +constant sized input, because variable length sized input from user can cause DoS. + +On the other hand, if both bases are power of same number (like `2**8 <-> 2**64`), +there is linear algorithm. For now we have implementation for power-of-two bases only (radix2). + +## Security + +The library has been audited by Cure53 on Jan 5, 2022. Check out the audit [PDF](./audit/2022-01-05-cure53-audit-nbl2.pdf) & [URL](https://cure53.de/pentest-report_hashing-libs.pdf). See [changes since audit](https://github.com/paulmillr/scure-base/compare/1.0.0..main). + +1. The library was initially developed for [js-ethereum-cryptography](https://github.com/ethereum/js-ethereum-cryptography) +2. At commit [ae00e6d7](https://github.com/ethereum/js-ethereum-cryptography/commit/ae00e6d7d24fb3c76a1c7fe10039f6ecd120b77e), it + was extracted to a separate package called `micro-base` +3. After the audit we've decided to use NPM namespace for security. Since `@micro` namespace was taken, we've renamed the package to `@scure/base` + +## License + +MIT (c) Paul Miller [(https://paulmillr.com)](https://paulmillr.com), see LICENSE file. diff --git a/node_modules/@scure/base/lib/esm/index.js b/node_modules/@scure/base/lib/esm/index.js new file mode 100644 index 0000000..df3d966 --- /dev/null +++ b/node_modules/@scure/base/lib/esm/index.js @@ -0,0 +1,394 @@ +/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +export function assertNumber(n) { + if (!Number.isSafeInteger(n)) + throw new Error(`Wrong integer: ${n}`); +} +function chain(...args) { + const wrap = (a, b) => (c) => a(b(c)); + const encode = Array.from(args) + .reverse() + .reduce((acc, i) => (acc ? wrap(acc, i.encode) : i.encode), undefined); + const decode = args.reduce((acc, i) => (acc ? wrap(acc, i.decode) : i.decode), undefined); + return { encode, decode }; +} +function alphabet(alphabet) { + return { + encode: (digits) => { + if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) + throw new Error('alphabet.encode input should be an array of numbers'); + return digits.map((i) => { + assertNumber(i); + if (i < 0 || i >= alphabet.length) + throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet.length})`); + return alphabet[i]; + }); + }, + decode: (input) => { + if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string')) + throw new Error('alphabet.decode input should be array of strings'); + return input.map((letter) => { + if (typeof letter !== 'string') + throw new Error(`alphabet.decode: not string element=${letter}`); + const index = alphabet.indexOf(letter); + if (index === -1) + throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet}`); + return index; + }); + }, + }; +} +function join(separator = '') { + if (typeof separator !== 'string') + throw new Error('join separator should be string'); + return { + encode: (from) => { + if (!Array.isArray(from) || (from.length && typeof from[0] !== 'string')) + throw new Error('join.encode input should be array of strings'); + for (let i of from) + if (typeof i !== 'string') + throw new Error(`join.encode: non-string input=${i}`); + return from.join(separator); + }, + decode: (to) => { + if (typeof to !== 'string') + throw new Error('join.decode input should be string'); + return to.split(separator); + }, + }; +} +function padding(bits, chr = '=') { + assertNumber(bits); + if (typeof chr !== 'string') + throw new Error('padding chr should be string'); + return { + encode(data) { + if (!Array.isArray(data) || (data.length && typeof data[0] !== 'string')) + throw new Error('padding.encode input should be array of strings'); + for (let i of data) + if (typeof i !== 'string') + throw new Error(`padding.encode: non-string input=${i}`); + while ((data.length * bits) % 8) + data.push(chr); + return data; + }, + decode(input) { + if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string')) + throw new Error('padding.encode input should be array of strings'); + for (let i of input) + if (typeof i !== 'string') + throw new Error(`padding.decode: non-string input=${i}`); + let end = input.length; + if ((end * bits) % 8) + throw new Error('Invalid padding: string should have whole number of bytes'); + for (; end > 0 && input[end - 1] === chr; end--) { + if (!(((end - 1) * bits) % 8)) + throw new Error('Invalid padding: string has too much padding'); + } + return input.slice(0, end); + }, + }; +} +function normalize(fn) { + if (typeof fn !== 'function') + throw new Error('normalize fn should be function'); + return { encode: (from) => from, decode: (to) => fn(to) }; +} +function convertRadix(data, from, to) { + if (from < 2) + throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`); + if (to < 2) + throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`); + if (!Array.isArray(data)) + throw new Error('convertRadix: data should be array'); + if (!data.length) + return []; + let pos = 0; + const res = []; + const digits = Array.from(data); + digits.forEach((d) => { + assertNumber(d); + if (d < 0 || d >= from) + throw new Error(`Wrong integer: ${d}`); + }); + while (true) { + let carry = 0; + let done = true; + for (let i = pos; i < digits.length; i++) { + const digit = digits[i]; + const digitBase = from * carry + digit; + if (!Number.isSafeInteger(digitBase) || + (from * carry) / from !== carry || + digitBase - digit !== from * carry) { + throw new Error('convertRadix: carry overflow'); + } + carry = digitBase % to; + digits[i] = Math.floor(digitBase / to); + if (!Number.isSafeInteger(digits[i]) || digits[i] * to + carry !== digitBase) + throw new Error('convertRadix: carry overflow'); + if (!done) + continue; + else if (!digits[i]) + pos = i; + else + done = false; + } + res.push(carry); + if (done) + break; + } + for (let i = 0; i < data.length - 1 && data[i] === 0; i++) + res.push(0); + return res.reverse(); +} +const gcd = (a, b) => (!b ? a : gcd(b, a % b)); +const radix2carry = (from, to) => from + (to - gcd(from, to)); +function convertRadix2(data, from, to, padding) { + if (!Array.isArray(data)) + throw new Error('convertRadix2: data should be array'); + if (from <= 0 || from > 32) + throw new Error(`convertRadix2: wrong from=${from}`); + if (to <= 0 || to > 32) + throw new Error(`convertRadix2: wrong to=${to}`); + if (radix2carry(from, to) > 32) { + throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`); + } + let carry = 0; + let pos = 0; + const mask = 2 ** to - 1; + const res = []; + for (const n of data) { + assertNumber(n); + if (n >= 2 ** from) + throw new Error(`convertRadix2: invalid data word=${n} from=${from}`); + carry = (carry << from) | n; + if (pos + from > 32) + throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`); + pos += from; + for (; pos >= to; pos -= to) + res.push(((carry >> (pos - to)) & mask) >>> 0); + carry &= 2 ** pos - 1; + } + carry = (carry << (to - pos)) & mask; + if (!padding && pos >= from) + throw new Error('Excess padding'); + if (!padding && carry) + throw new Error(`Non-zero padding: ${carry}`); + if (padding && pos > 0) + res.push(carry >>> 0); + return res; +} +function radix(num) { + assertNumber(num); + return { + encode: (bytes) => { + if (!(bytes instanceof Uint8Array)) + throw new Error('radix.encode input should be Uint8Array'); + return convertRadix(Array.from(bytes), 2 ** 8, num); + }, + decode: (digits) => { + if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) + throw new Error('radix.decode input should be array of strings'); + return Uint8Array.from(convertRadix(digits, num, 2 ** 8)); + }, + }; +} +function radix2(bits, revPadding = false) { + assertNumber(bits); + if (bits <= 0 || bits > 32) + throw new Error('radix2: bits should be in (0..32]'); + if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32) + throw new Error('radix2: carry overflow'); + return { + encode: (bytes) => { + if (!(bytes instanceof Uint8Array)) + throw new Error('radix2.encode input should be Uint8Array'); + return convertRadix2(Array.from(bytes), 8, bits, !revPadding); + }, + decode: (digits) => { + if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) + throw new Error('radix2.decode input should be array of strings'); + return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding)); + }, + }; +} +function unsafeWrapper(fn) { + if (typeof fn !== 'function') + throw new Error('unsafeWrapper fn should be function'); + return function (...args) { + try { + return fn.apply(null, args); + } + catch (e) { } + }; +} +function checksum(len, fn) { + assertNumber(len); + if (typeof fn !== 'function') + throw new Error('checksum fn should be function'); + return { + encode(data) { + if (!(data instanceof Uint8Array)) + throw new Error('checksum.encode: input should be Uint8Array'); + const checksum = fn(data).slice(0, len); + const res = new Uint8Array(data.length + len); + res.set(data); + res.set(checksum, data.length); + return res; + }, + decode(data) { + if (!(data instanceof Uint8Array)) + throw new Error('checksum.decode: input should be Uint8Array'); + const payload = data.slice(0, -len); + const newChecksum = fn(payload).slice(0, len); + const oldChecksum = data.slice(-len); + for (let i = 0; i < len; i++) + if (newChecksum[i] !== oldChecksum[i]) + throw new Error('Invalid checksum'); + return payload; + }, + }; +} +export const utils = { alphabet, chain, checksum, radix, radix2, join, padding }; +export const base16 = chain(radix2(4), alphabet('0123456789ABCDEF'), join('')); +export const base32 = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join('')); +export const base32hex = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join('')); +export const base32crockford = chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))); +export const base64 = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join('')); +export const base64url = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join('')); +const genBase58 = (abc) => chain(radix(58), alphabet(abc), join('')); +export const base58 = genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'); +export const base58flickr = genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'); +export const base58xrp = genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'); +const XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11]; +export const base58xmr = { + encode(data) { + let res = ''; + for (let i = 0; i < data.length; i += 8) { + const block = data.subarray(i, i + 8); + res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1'); + } + return res; + }, + decode(str) { + let res = []; + for (let i = 0; i < str.length; i += 11) { + const slice = str.slice(i, i + 11); + const blockLen = XMR_BLOCK_LEN.indexOf(slice.length); + const block = base58.decode(slice); + for (let j = 0; j < block.length - blockLen; j++) { + if (block[j] !== 0) + throw new Error('base58xmr: wrong padding'); + } + res = res.concat(Array.from(block.slice(block.length - blockLen))); + } + return Uint8Array.from(res); + }, +}; +export const base58check = (sha256) => chain(checksum(4, (data) => sha256(sha256(data))), base58); +const BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join('')); +const POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]; +function bech32Polymod(pre) { + const b = pre >> 25; + let chk = (pre & 0x1ffffff) << 5; + for (let i = 0; i < POLYMOD_GENERATORS.length; i++) { + if (((b >> i) & 1) === 1) + chk ^= POLYMOD_GENERATORS[i]; + } + return chk; +} +function bechChecksum(prefix, words, encodingConst = 1) { + const len = prefix.length; + let chk = 1; + for (let i = 0; i < len; i++) { + const c = prefix.charCodeAt(i); + if (c < 33 || c > 126) + throw new Error(`Invalid prefix (${prefix})`); + chk = bech32Polymod(chk) ^ (c >> 5); + } + chk = bech32Polymod(chk); + for (let i = 0; i < len; i++) + chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f); + for (let v of words) + chk = bech32Polymod(chk) ^ v; + for (let i = 0; i < 6; i++) + chk = bech32Polymod(chk); + chk ^= encodingConst; + return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false)); +} +function genBech32(encoding) { + const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3; + const _words = radix2(5); + const fromWords = _words.decode; + const toWords = _words.encode; + const fromWordsUnsafe = unsafeWrapper(fromWords); + function encode(prefix, words, limit = 90) { + if (typeof prefix !== 'string') + throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`); + if (!Array.isArray(words) || (words.length && typeof words[0] !== 'number')) + throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`); + const actualLength = prefix.length + 7 + words.length; + if (limit !== false && actualLength > limit) + throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`); + prefix = prefix.toLowerCase(); + return `${prefix}1${BECH_ALPHABET.encode(words)}${bechChecksum(prefix, words, ENCODING_CONST)}`; + } + function decode(str, limit = 90) { + if (typeof str !== 'string') + throw new Error(`bech32.decode input should be string, not ${typeof str}`); + if (str.length < 8 || (limit !== false && str.length > limit)) + throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`); + const lowered = str.toLowerCase(); + if (str !== lowered && str !== str.toUpperCase()) + throw new Error(`String must be lowercase or uppercase`); + str = lowered; + const sepIndex = str.lastIndexOf('1'); + if (sepIndex === 0 || sepIndex === -1) + throw new Error(`Letter "1" must be present between prefix and data only`); + const prefix = str.slice(0, sepIndex); + const _words = str.slice(sepIndex + 1); + if (_words.length < 6) + throw new Error('Data must be at least 6 characters long'); + const words = BECH_ALPHABET.decode(_words).slice(0, -6); + const sum = bechChecksum(prefix, words, ENCODING_CONST); + if (!_words.endsWith(sum)) + throw new Error(`Invalid checksum in ${str}: expected "${sum}"`); + return { prefix, words }; + } + const decodeUnsafe = unsafeWrapper(decode); + function decodeToBytes(str) { + const { prefix, words } = decode(str, false); + return { prefix, words, bytes: fromWords(words) }; + } + return { encode, decode, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords }; +} +export const bech32 = genBech32('bech32'); +export const bech32m = genBech32('bech32m'); +export const utf8 = { + encode: (data) => new TextDecoder().decode(data), + decode: (str) => new TextEncoder().encode(str), +}; +export const hex = chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => { + if (typeof s !== 'string' || s.length % 2) + throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`); + return s.toLowerCase(); +})); +const CODERS = { + utf8, hex, base16, base32, base64, base64url, base58, base58xmr +}; +const coderTypeError = `Invalid encoding type. Available types: ${Object.keys(CODERS).join(', ')}`; +export const bytesToString = (type, bytes) => { + if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) + throw new TypeError(coderTypeError); + if (!(bytes instanceof Uint8Array)) + throw new TypeError('bytesToString() expects Uint8Array'); + return CODERS[type].encode(bytes); +}; +export const str = bytesToString; +export const stringToBytes = (type, str) => { + if (!CODERS.hasOwnProperty(type)) + throw new TypeError(coderTypeError); + if (typeof str !== 'string') + throw new TypeError('stringToBytes() expects string'); + return CODERS[type].decode(str); +}; +export const bytes = stringToBytes; diff --git a/node_modules/@scure/base/lib/esm/package.json b/node_modules/@scure/base/lib/esm/package.json new file mode 100644 index 0000000..5ffd980 --- /dev/null +++ b/node_modules/@scure/base/lib/esm/package.json @@ -0,0 +1 @@ +{ "type": "module" } diff --git a/node_modules/@scure/base/lib/index.d.ts b/node_modules/@scure/base/lib/index.d.ts new file mode 100644 index 0000000..5e46141 --- /dev/null +++ b/node_modules/@scure/base/lib/index.d.ts @@ -0,0 +1,92 @@ +/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +export declare function assertNumber(n: number): void; +export interface Coder { + encode(from: F): T; + decode(to: T): F; +} +export interface BytesCoder extends Coder { + encode: (data: Uint8Array) => string; + decode: (str: string) => Uint8Array; +} +declare type Chain = [Coder, ...Coder[]]; +declare type Input = F extends Coder ? T : never; +declare type Output = F extends Coder ? T : never; +declare type First = T extends [infer U, ...any[]] ? U : never; +declare type Last = T extends [...any[], infer U] ? U : never; +declare type Tail = T extends [any, ...infer U] ? U : never; +declare type AsChain> = { + [K in keyof C]: Coder, Input>; +}; +declare function chain>(...args: T): Coder>, Output>>; +declare type Alphabet = string[] | string; +declare function alphabet(alphabet: Alphabet): Coder; +declare function join(separator?: string): Coder; +declare function padding(bits: number, chr?: string): Coder; +declare function radix(num: number): Coder; +declare function radix2(bits: number, revPadding?: boolean): Coder; +declare function checksum(len: number, fn: (data: Uint8Array) => Uint8Array): Coder; +export declare const utils: { + alphabet: typeof alphabet; + chain: typeof chain; + checksum: typeof checksum; + radix: typeof radix; + radix2: typeof radix2; + join: typeof join; + padding: typeof padding; +}; +export declare const base16: BytesCoder; +export declare const base32: BytesCoder; +export declare const base32hex: BytesCoder; +export declare const base32crockford: BytesCoder; +export declare const base64: BytesCoder; +export declare const base64url: BytesCoder; +export declare const base58: BytesCoder; +export declare const base58flickr: BytesCoder; +export declare const base58xrp: BytesCoder; +export declare const base58xmr: BytesCoder; +export declare const base58check: (sha256: (data: Uint8Array) => Uint8Array) => BytesCoder; +export interface Bech32Decoded { + prefix: string; + words: number[]; +} +export interface Bech32DecodedWithArray { + prefix: string; + words: number[]; + bytes: Uint8Array; +} +export declare const bech32: { + encode: (prefix: string, words: number[] | Uint8Array, limit?: number | false) => string; + decode: (str: string, limit?: number | false) => Bech32Decoded; + decodeToBytes: (str: string) => Bech32DecodedWithArray; + decodeUnsafe: (str: string, limit?: number | false | undefined) => Bech32Decoded | undefined; + fromWords: (to: number[]) => Uint8Array; + fromWordsUnsafe: (to: number[]) => Uint8Array | undefined; + toWords: (from: Uint8Array) => number[]; +}; +export declare const bech32m: { + encode: (prefix: string, words: number[] | Uint8Array, limit?: number | false) => string; + decode: (str: string, limit?: number | false) => Bech32Decoded; + decodeToBytes: (str: string) => Bech32DecodedWithArray; + decodeUnsafe: (str: string, limit?: number | false | undefined) => Bech32Decoded | undefined; + fromWords: (to: number[]) => Uint8Array; + fromWordsUnsafe: (to: number[]) => Uint8Array | undefined; + toWords: (from: Uint8Array) => number[]; +}; +export declare const utf8: BytesCoder; +export declare const hex: BytesCoder; +declare const CODERS: { + utf8: BytesCoder; + hex: BytesCoder; + base16: BytesCoder; + base32: BytesCoder; + base64: BytesCoder; + base64url: BytesCoder; + base58: BytesCoder; + base58xmr: BytesCoder; +}; +declare type CoderType = keyof typeof CODERS; +export declare const bytesToString: (type: CoderType, bytes: Uint8Array) => string; +export declare const str: (type: CoderType, bytes: Uint8Array) => string; +export declare const stringToBytes: (type: CoderType, str: string) => Uint8Array; +export declare const bytes: (type: CoderType, str: string) => Uint8Array; +export {}; diff --git a/node_modules/@scure/base/lib/index.js b/node_modules/@scure/base/lib/index.js new file mode 100644 index 0000000..083320c --- /dev/null +++ b/node_modules/@scure/base/lib/index.js @@ -0,0 +1,401 @@ +"use strict"; +/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bytes = exports.stringToBytes = exports.str = exports.bytesToString = exports.hex = exports.utf8 = exports.bech32m = exports.bech32 = exports.base58check = exports.base58xmr = exports.base58xrp = exports.base58flickr = exports.base58 = exports.base64url = exports.base64 = exports.base32crockford = exports.base32hex = exports.base32 = exports.base16 = exports.utils = exports.assertNumber = void 0; +function assertNumber(n) { + if (!Number.isSafeInteger(n)) + throw new Error(`Wrong integer: ${n}`); +} +exports.assertNumber = assertNumber; +function chain(...args) { + const wrap = (a, b) => (c) => a(b(c)); + const encode = Array.from(args) + .reverse() + .reduce((acc, i) => (acc ? wrap(acc, i.encode) : i.encode), undefined); + const decode = args.reduce((acc, i) => (acc ? wrap(acc, i.decode) : i.decode), undefined); + return { encode, decode }; +} +function alphabet(alphabet) { + return { + encode: (digits) => { + if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) + throw new Error('alphabet.encode input should be an array of numbers'); + return digits.map((i) => { + assertNumber(i); + if (i < 0 || i >= alphabet.length) + throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet.length})`); + return alphabet[i]; + }); + }, + decode: (input) => { + if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string')) + throw new Error('alphabet.decode input should be array of strings'); + return input.map((letter) => { + if (typeof letter !== 'string') + throw new Error(`alphabet.decode: not string element=${letter}`); + const index = alphabet.indexOf(letter); + if (index === -1) + throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet}`); + return index; + }); + }, + }; +} +function join(separator = '') { + if (typeof separator !== 'string') + throw new Error('join separator should be string'); + return { + encode: (from) => { + if (!Array.isArray(from) || (from.length && typeof from[0] !== 'string')) + throw new Error('join.encode input should be array of strings'); + for (let i of from) + if (typeof i !== 'string') + throw new Error(`join.encode: non-string input=${i}`); + return from.join(separator); + }, + decode: (to) => { + if (typeof to !== 'string') + throw new Error('join.decode input should be string'); + return to.split(separator); + }, + }; +} +function padding(bits, chr = '=') { + assertNumber(bits); + if (typeof chr !== 'string') + throw new Error('padding chr should be string'); + return { + encode(data) { + if (!Array.isArray(data) || (data.length && typeof data[0] !== 'string')) + throw new Error('padding.encode input should be array of strings'); + for (let i of data) + if (typeof i !== 'string') + throw new Error(`padding.encode: non-string input=${i}`); + while ((data.length * bits) % 8) + data.push(chr); + return data; + }, + decode(input) { + if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string')) + throw new Error('padding.encode input should be array of strings'); + for (let i of input) + if (typeof i !== 'string') + throw new Error(`padding.decode: non-string input=${i}`); + let end = input.length; + if ((end * bits) % 8) + throw new Error('Invalid padding: string should have whole number of bytes'); + for (; end > 0 && input[end - 1] === chr; end--) { + if (!(((end - 1) * bits) % 8)) + throw new Error('Invalid padding: string has too much padding'); + } + return input.slice(0, end); + }, + }; +} +function normalize(fn) { + if (typeof fn !== 'function') + throw new Error('normalize fn should be function'); + return { encode: (from) => from, decode: (to) => fn(to) }; +} +function convertRadix(data, from, to) { + if (from < 2) + throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`); + if (to < 2) + throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`); + if (!Array.isArray(data)) + throw new Error('convertRadix: data should be array'); + if (!data.length) + return []; + let pos = 0; + const res = []; + const digits = Array.from(data); + digits.forEach((d) => { + assertNumber(d); + if (d < 0 || d >= from) + throw new Error(`Wrong integer: ${d}`); + }); + while (true) { + let carry = 0; + let done = true; + for (let i = pos; i < digits.length; i++) { + const digit = digits[i]; + const digitBase = from * carry + digit; + if (!Number.isSafeInteger(digitBase) || + (from * carry) / from !== carry || + digitBase - digit !== from * carry) { + throw new Error('convertRadix: carry overflow'); + } + carry = digitBase % to; + digits[i] = Math.floor(digitBase / to); + if (!Number.isSafeInteger(digits[i]) || digits[i] * to + carry !== digitBase) + throw new Error('convertRadix: carry overflow'); + if (!done) + continue; + else if (!digits[i]) + pos = i; + else + done = false; + } + res.push(carry); + if (done) + break; + } + for (let i = 0; i < data.length - 1 && data[i] === 0; i++) + res.push(0); + return res.reverse(); +} +const gcd = (a, b) => (!b ? a : gcd(b, a % b)); +const radix2carry = (from, to) => from + (to - gcd(from, to)); +function convertRadix2(data, from, to, padding) { + if (!Array.isArray(data)) + throw new Error('convertRadix2: data should be array'); + if (from <= 0 || from > 32) + throw new Error(`convertRadix2: wrong from=${from}`); + if (to <= 0 || to > 32) + throw new Error(`convertRadix2: wrong to=${to}`); + if (radix2carry(from, to) > 32) { + throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`); + } + let carry = 0; + let pos = 0; + const mask = 2 ** to - 1; + const res = []; + for (const n of data) { + assertNumber(n); + if (n >= 2 ** from) + throw new Error(`convertRadix2: invalid data word=${n} from=${from}`); + carry = (carry << from) | n; + if (pos + from > 32) + throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`); + pos += from; + for (; pos >= to; pos -= to) + res.push(((carry >> (pos - to)) & mask) >>> 0); + carry &= 2 ** pos - 1; + } + carry = (carry << (to - pos)) & mask; + if (!padding && pos >= from) + throw new Error('Excess padding'); + if (!padding && carry) + throw new Error(`Non-zero padding: ${carry}`); + if (padding && pos > 0) + res.push(carry >>> 0); + return res; +} +function radix(num) { + assertNumber(num); + return { + encode: (bytes) => { + if (!(bytes instanceof Uint8Array)) + throw new Error('radix.encode input should be Uint8Array'); + return convertRadix(Array.from(bytes), 2 ** 8, num); + }, + decode: (digits) => { + if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) + throw new Error('radix.decode input should be array of strings'); + return Uint8Array.from(convertRadix(digits, num, 2 ** 8)); + }, + }; +} +function radix2(bits, revPadding = false) { + assertNumber(bits); + if (bits <= 0 || bits > 32) + throw new Error('radix2: bits should be in (0..32]'); + if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32) + throw new Error('radix2: carry overflow'); + return { + encode: (bytes) => { + if (!(bytes instanceof Uint8Array)) + throw new Error('radix2.encode input should be Uint8Array'); + return convertRadix2(Array.from(bytes), 8, bits, !revPadding); + }, + decode: (digits) => { + if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) + throw new Error('radix2.decode input should be array of strings'); + return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding)); + }, + }; +} +function unsafeWrapper(fn) { + if (typeof fn !== 'function') + throw new Error('unsafeWrapper fn should be function'); + return function (...args) { + try { + return fn.apply(null, args); + } + catch (e) { } + }; +} +function checksum(len, fn) { + assertNumber(len); + if (typeof fn !== 'function') + throw new Error('checksum fn should be function'); + return { + encode(data) { + if (!(data instanceof Uint8Array)) + throw new Error('checksum.encode: input should be Uint8Array'); + const checksum = fn(data).slice(0, len); + const res = new Uint8Array(data.length + len); + res.set(data); + res.set(checksum, data.length); + return res; + }, + decode(data) { + if (!(data instanceof Uint8Array)) + throw new Error('checksum.decode: input should be Uint8Array'); + const payload = data.slice(0, -len); + const newChecksum = fn(payload).slice(0, len); + const oldChecksum = data.slice(-len); + for (let i = 0; i < len; i++) + if (newChecksum[i] !== oldChecksum[i]) + throw new Error('Invalid checksum'); + return payload; + }, + }; +} +exports.utils = { alphabet, chain, checksum, radix, radix2, join, padding }; +exports.base16 = chain(radix2(4), alphabet('0123456789ABCDEF'), join('')); +exports.base32 = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join('')); +exports.base32hex = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join('')); +exports.base32crockford = chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))); +exports.base64 = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join('')); +exports.base64url = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join('')); +const genBase58 = (abc) => chain(radix(58), alphabet(abc), join('')); +exports.base58 = genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'); +exports.base58flickr = genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'); +exports.base58xrp = genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'); +const XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11]; +exports.base58xmr = { + encode(data) { + let res = ''; + for (let i = 0; i < data.length; i += 8) { + const block = data.subarray(i, i + 8); + res += exports.base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1'); + } + return res; + }, + decode(str) { + let res = []; + for (let i = 0; i < str.length; i += 11) { + const slice = str.slice(i, i + 11); + const blockLen = XMR_BLOCK_LEN.indexOf(slice.length); + const block = exports.base58.decode(slice); + for (let j = 0; j < block.length - blockLen; j++) { + if (block[j] !== 0) + throw new Error('base58xmr: wrong padding'); + } + res = res.concat(Array.from(block.slice(block.length - blockLen))); + } + return Uint8Array.from(res); + }, +}; +const base58check = (sha256) => chain(checksum(4, (data) => sha256(sha256(data))), exports.base58); +exports.base58check = base58check; +const BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join('')); +const POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]; +function bech32Polymod(pre) { + const b = pre >> 25; + let chk = (pre & 0x1ffffff) << 5; + for (let i = 0; i < POLYMOD_GENERATORS.length; i++) { + if (((b >> i) & 1) === 1) + chk ^= POLYMOD_GENERATORS[i]; + } + return chk; +} +function bechChecksum(prefix, words, encodingConst = 1) { + const len = prefix.length; + let chk = 1; + for (let i = 0; i < len; i++) { + const c = prefix.charCodeAt(i); + if (c < 33 || c > 126) + throw new Error(`Invalid prefix (${prefix})`); + chk = bech32Polymod(chk) ^ (c >> 5); + } + chk = bech32Polymod(chk); + for (let i = 0; i < len; i++) + chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f); + for (let v of words) + chk = bech32Polymod(chk) ^ v; + for (let i = 0; i < 6; i++) + chk = bech32Polymod(chk); + chk ^= encodingConst; + return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false)); +} +function genBech32(encoding) { + const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3; + const _words = radix2(5); + const fromWords = _words.decode; + const toWords = _words.encode; + const fromWordsUnsafe = unsafeWrapper(fromWords); + function encode(prefix, words, limit = 90) { + if (typeof prefix !== 'string') + throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`); + if (!Array.isArray(words) || (words.length && typeof words[0] !== 'number')) + throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`); + const actualLength = prefix.length + 7 + words.length; + if (limit !== false && actualLength > limit) + throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`); + prefix = prefix.toLowerCase(); + return `${prefix}1${BECH_ALPHABET.encode(words)}${bechChecksum(prefix, words, ENCODING_CONST)}`; + } + function decode(str, limit = 90) { + if (typeof str !== 'string') + throw new Error(`bech32.decode input should be string, not ${typeof str}`); + if (str.length < 8 || (limit !== false && str.length > limit)) + throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`); + const lowered = str.toLowerCase(); + if (str !== lowered && str !== str.toUpperCase()) + throw new Error(`String must be lowercase or uppercase`); + str = lowered; + const sepIndex = str.lastIndexOf('1'); + if (sepIndex === 0 || sepIndex === -1) + throw new Error(`Letter "1" must be present between prefix and data only`); + const prefix = str.slice(0, sepIndex); + const _words = str.slice(sepIndex + 1); + if (_words.length < 6) + throw new Error('Data must be at least 6 characters long'); + const words = BECH_ALPHABET.decode(_words).slice(0, -6); + const sum = bechChecksum(prefix, words, ENCODING_CONST); + if (!_words.endsWith(sum)) + throw new Error(`Invalid checksum in ${str}: expected "${sum}"`); + return { prefix, words }; + } + const decodeUnsafe = unsafeWrapper(decode); + function decodeToBytes(str) { + const { prefix, words } = decode(str, false); + return { prefix, words, bytes: fromWords(words) }; + } + return { encode, decode, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords }; +} +exports.bech32 = genBech32('bech32'); +exports.bech32m = genBech32('bech32m'); +exports.utf8 = { + encode: (data) => new TextDecoder().decode(data), + decode: (str) => new TextEncoder().encode(str), +}; +exports.hex = chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => { + if (typeof s !== 'string' || s.length % 2) + throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`); + return s.toLowerCase(); +})); +const CODERS = { + utf8: exports.utf8, hex: exports.hex, base16: exports.base16, base32: exports.base32, base64: exports.base64, base64url: exports.base64url, base58: exports.base58, base58xmr: exports.base58xmr +}; +const coderTypeError = `Invalid encoding type. Available types: ${Object.keys(CODERS).join(', ')}`; +const bytesToString = (type, bytes) => { + if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) + throw new TypeError(coderTypeError); + if (!(bytes instanceof Uint8Array)) + throw new TypeError('bytesToString() expects Uint8Array'); + return CODERS[type].encode(bytes); +}; +exports.bytesToString = bytesToString; +exports.str = exports.bytesToString; +const stringToBytes = (type, str) => { + if (!CODERS.hasOwnProperty(type)) + throw new TypeError(coderTypeError); + if (typeof str !== 'string') + throw new TypeError('stringToBytes() expects string'); + return CODERS[type].decode(str); +}; +exports.stringToBytes = stringToBytes; +exports.bytes = exports.stringToBytes; diff --git a/node_modules/@scure/base/package.json b/node_modules/@scure/base/package.json new file mode 100644 index 0000000..beb4dfc --- /dev/null +++ b/node_modules/@scure/base/package.json @@ -0,0 +1,60 @@ +{ + "name": "@scure/base", + "version": "1.1.1", + "description": "Secure, audited & 0-dep implementation of bech32, base64, base58, base32 & base16", + "files": [ + "lib/index.js", + "lib/esm/index.js", + "lib/esm/package.json", + "lib/index.d.ts" + ], + "main": "lib/index.js", + "module": "lib/esm/index.js", + "types": "lib/index.d.ts", + "exports": { + ".": { + "import": "./lib/esm/index.js", + "default": "./lib/index.js" + }, + "./index.d.ts": "./lib/index.d.ts" + }, + "scripts": { + "bench": "node test/benchmark/index.js", + "build": "tsc -d && tsc -p tsconfig.esm.json", + "lint": "prettier --check index.ts", + "test": "node test/index.js" + }, + "author": "Paul Miller (https://paulmillr.com)", + "license": "MIT", + "homepage": "https://github.com/paulmillr/scure-base", + "repository": { + "type": "git", + "url": "git+https://github.com/paulmillr/scure-base.git" + }, + "devDependencies": { + "micro-should": "0.2.0", + "prettier": "2.6.2", + "typescript": "4.7.3" + }, + "keywords": [ + "bech32", + "bech32m", + "base64", + "base58", + "base32", + "base16", + "rfc4648", + "rfc3548", + "crockford", + "encode", + "encoder", + "base-x", + "base" + ], + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ] +} diff --git a/node_modules/@scure/bip32/LICENSE b/node_modules/@scure/bip32/LICENSE new file mode 100644 index 0000000..68222b8 --- /dev/null +++ b/node_modules/@scure/bip32/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/@scure/bip32/README.md b/node_modules/@scure/bip32/README.md new file mode 100644 index 0000000..ea5bfbb --- /dev/null +++ b/node_modules/@scure/bip32/README.md @@ -0,0 +1,107 @@ +# scure-bip32 + +Secure, [audited](#security) & minimal implementation of BIP32 hierarchical deterministic (HD) wallets over secp256k1. + +Compared to popular `hdkey` package, scure-bip32: + +- Supports ESM and common.js +- Is 418KB all-bundled instead of 5.9MB +- Uses 3 dependencies instead of 24 +- Had an external security [audit](#security) by Cure53 + +Check out [scure-bip39](https://github.com/paulmillr/scure-bip39) if you need mnemonic phrases. See [ed25519-keygen](https://github.com/paulmillr/ed25519-keygen) if you need SLIP-0010/BIP32 ed25519 hdkey implementation. + +### This library belongs to *scure* + +> **scure** — secure, independently audited packages for every use case. + +- Audited by a third-party +- Releases are signed with PGP keys and built transparently with NPM provenance +- Check out all libraries: + [base](https://github.com/paulmillr/scure-base), + [bip32](https://github.com/paulmillr/scure-bip32), + [bip39](https://github.com/paulmillr/scure-bip39), + [btc-signer](https://github.com/paulmillr/scure-btc-signer) + +## Usage + +> npm install @scure/bip32 + +This module exports a single class `HDKey`, which should be used like this: + +```ts +const { HDKey } = require("@scure/bip32"); +const hdkey1 = HDKey.fromMasterSeed(seed); +const hdkey2 = HDKey.fromExtendedKey(base58key); +const hdkey3 = HDKey.fromJSON({ xpriv: string }); + +// props +[hdkey1.depth, hdkey1.index, hdkey1.chainCode]; +console.log(hdkey2.privateKey, hdkey2.publicKey); +console.log(hdkey3.derive("m/0/2147483647'/1")); +const sig = hdkey3.sign(hash); +hdkey3.verify(hash, sig); +``` + +Note: `chainCode` property is essentially a private part +of a secret "master" key, it should be guarded from unauthorized access. + +The full API is: + +```ts +class HDKey { + public static HARDENED_OFFSET: number; + public static fromMasterSeed(seed: Uint8Array, versions: Versions): HDKey; + public static fromExtendedKey(base58key: string, versions: Versions): HDKey; + public static fromJSON(json: { xpriv: string }): HDKey; + + readonly versions: Versions; + readonly depth: number = 0; + readonly index: number = 0; + readonly chainCode: Uint8Array | null = null; + readonly parentFingerprint: number = 0; + + get fingerprint(): number; + get identifier(): Uint8Array | undefined; + get pubKeyHash(): Uint8Array | undefined; + get privateKey(): Uint8Array | null; + get publicKey(): Uint8Array | null; + get privateExtendedKey(): string; + get publicExtendedKey(): string; + + derive(path: string): HDKey; + deriveChild(index: number): HDKey; + sign(hash: Uint8Array): Uint8Array; + verify(hash: Uint8Array, signature: Uint8Array): boolean; + wipePrivateData(): this; +} + +interface Versions { + private: number; + public: number; +} +``` + +The `hdkey` submodule provides a library for keys derivation according to +[BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki). + +It has almost the exact same API than the version `1.x` of +[`hdkey` from cryptocoinjs](https://github.com/cryptocoinjs/hdkey), +but it's backed by this package's primitives, and has built-in TypeScript types. +Its only difference is that it has to be be used with a named import. +The implementation is [loosely based on hdkey, which has MIT License](#LICENSE). + +## Security + +The library has been audited by Cure53 on Jan 5, 2022. Check out the audit [PDF](./audit/2022-01-05-cure53-audit-nbl2.pdf) & [URL](https://cure53.de/pentest-report_hashing-libs.pdf). See [changes since audit](https://github.com/paulmillr/scure-bip32/compare/1.0.1..main). + +1. The library was initially developed for [js-ethereum-cryptography](https://github.com/ethereum/js-ethereum-cryptography) +2. At commit [ae00e6d7](https://github.com/ethereum/js-ethereum-cryptography/commit/ae00e6d7d24fb3c76a1c7fe10039f6ecd120b77e), it + was extracted to a separate package called `micro-bip32` +3. After the audit we've decided to use NPM namespace for security. Since `@micro` namespace was taken, we've renamed the package to `@scure/bip32` + +## License + +[MIT License](./LICENSE) + +Copyright (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) diff --git a/node_modules/@scure/bip32/index.ts b/node_modules/@scure/bip32/index.ts new file mode 100644 index 0000000..d0496ef --- /dev/null +++ b/node_modules/@scure/bip32/index.ts @@ -0,0 +1,307 @@ +/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */ +import { hmac } from '@noble/hashes/hmac'; +import { ripemd160 } from '@noble/hashes/ripemd160'; +import { sha256 } from '@noble/hashes/sha256'; +import { sha512 } from '@noble/hashes/sha512'; +import { bytes as assertBytes } from '@noble/hashes/_assert'; +import { bytesToHex, concatBytes, createView, hexToBytes, utf8ToBytes } from '@noble/hashes/utils'; +import { secp256k1 as secp } from '@noble/curves/secp256k1'; +import { mod } from '@noble/curves/abstract/modular'; +import { base58check as base58checker } from '@scure/base'; + +const Point = secp.ProjectivePoint; +const base58check = base58checker(sha256); + +function bytesToNumber(bytes: Uint8Array): bigint { + return BigInt(`0x${bytesToHex(bytes)}`); +} + +function numberToBytes(num: bigint): Uint8Array { + return hexToBytes(num.toString(16).padStart(64, '0')); +} + +const MASTER_SECRET = utf8ToBytes('Bitcoin seed'); +// Bitcoin hardcoded by default +const BITCOIN_VERSIONS: Versions = { private: 0x0488ade4, public: 0x0488b21e }; +export const HARDENED_OFFSET: number = 0x80000000; + +export interface Versions { + private: number; + public: number; +} + +const hash160 = (data: Uint8Array) => ripemd160(sha256(data)); +const fromU32 = (data: Uint8Array) => createView(data).getUint32(0, false); +const toU32 = (n: number) => { + if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) { + throw new Error(`Invalid number=${n}. Should be from 0 to 2 ** 32 - 1`); + } + const buf = new Uint8Array(4); + createView(buf).setUint32(0, n, false); + return buf; +}; + +interface HDKeyOpt { + versions: Versions; + depth?: number; + index?: number; + parentFingerprint?: number; + chainCode: Uint8Array; + publicKey?: Uint8Array; + privateKey?: Uint8Array | bigint; +} + +export class HDKey { + get fingerprint(): number { + if (!this.pubHash) { + throw new Error('No publicKey set!'); + } + return fromU32(this.pubHash); + } + get identifier(): Uint8Array | undefined { + return this.pubHash; + } + get pubKeyHash(): Uint8Array | undefined { + return this.pubHash; + } + get privateKey(): Uint8Array | null { + return this.privKeyBytes || null; + } + get publicKey(): Uint8Array | null { + return this.pubKey || null; + } + get privateExtendedKey(): string { + const priv = this.privateKey; + if (!priv) { + throw new Error('No private key'); + } + return base58check.encode( + this.serialize(this.versions.private, concatBytes(new Uint8Array([0]), priv)) + ); + } + get publicExtendedKey(): string { + if (!this.pubKey) { + throw new Error('No public key'); + } + return base58check.encode(this.serialize(this.versions.public, this.pubKey)); + } + + public static fromMasterSeed(seed: Uint8Array, versions: Versions = BITCOIN_VERSIONS): HDKey { + assertBytes(seed); + if (8 * seed.length < 128 || 8 * seed.length > 512) { + throw new Error( + `HDKey: wrong seed length=${seed.length}. Should be between 128 and 512 bits; 256 bits is advised)` + ); + } + const I = hmac(sha512, MASTER_SECRET, seed); + return new HDKey({ + versions, + chainCode: I.slice(32), + privateKey: I.slice(0, 32), + }); + } + + public static fromExtendedKey(base58key: string, versions: Versions = BITCOIN_VERSIONS): HDKey { + // => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33) + const keyBuffer: Uint8Array = base58check.decode(base58key); + const keyView = createView(keyBuffer); + const version = keyView.getUint32(0, false); + const opt = { + versions, + depth: keyBuffer[4], + parentFingerprint: keyView.getUint32(5, false), + index: keyView.getUint32(9, false), + chainCode: keyBuffer.slice(13, 45), + }; + const key = keyBuffer.slice(45); + const isPriv = key[0] === 0; + if (version !== versions[isPriv ? 'private' : 'public']) { + throw new Error('Version mismatch'); + } + if (isPriv) { + return new HDKey({ ...opt, privateKey: key.slice(1) }); + } else { + return new HDKey({ ...opt, publicKey: key }); + } + } + + public static fromJSON(json: { xpriv: string }): HDKey { + return HDKey.fromExtendedKey(json.xpriv); + } + public readonly versions: Versions; + public readonly depth: number = 0; + public readonly index: number = 0; + public readonly chainCode: Uint8Array | null = null; + public readonly parentFingerprint: number = 0; + private privKey?: bigint; + private privKeyBytes?: Uint8Array; + private pubKey?: Uint8Array; + private pubHash: Uint8Array | undefined; + + constructor(opt: HDKeyOpt) { + if (!opt || typeof opt !== 'object') { + throw new Error('HDKey.constructor must not be called directly'); + } + this.versions = opt.versions || BITCOIN_VERSIONS; + this.depth = opt.depth || 0; + this.chainCode = opt.chainCode; + this.index = opt.index || 0; + this.parentFingerprint = opt.parentFingerprint || 0; + if (!this.depth) { + if (this.parentFingerprint || this.index) { + throw new Error('HDKey: zero depth with non-zero index/parent fingerprint'); + } + } + if (opt.publicKey && opt.privateKey) { + throw new Error('HDKey: publicKey and privateKey at same time.'); + } + if (opt.privateKey) { + if (!secp.utils.isValidPrivateKey(opt.privateKey)) { + throw new Error('Invalid private key'); + } + this.privKey = + typeof opt.privateKey === 'bigint' ? opt.privateKey : bytesToNumber(opt.privateKey); + this.privKeyBytes = numberToBytes(this.privKey); + this.pubKey = secp.getPublicKey(opt.privateKey, true); + } else if (opt.publicKey) { + this.pubKey = Point.fromHex(opt.publicKey).toRawBytes(true); // force compressed point + } else { + throw new Error('HDKey: no public or private key provided'); + } + this.pubHash = hash160(this.pubKey); + } + + public derive(path: string): HDKey { + if (!/^[mM]'?/.test(path)) { + throw new Error('Path must start with "m" or "M"'); + } + if (/^[mM]'?$/.test(path)) { + return this; + } + const parts = path.replace(/^[mM]'?\//, '').split('/'); + // tslint:disable-next-line + let child: HDKey = this; + for (const c of parts) { + const m = /^(\d+)('?)$/.exec(c); + if (!m || m.length !== 3) { + throw new Error(`Invalid child index: ${c}`); + } + let idx = +m[1]; + if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) { + throw new Error('Invalid index'); + } + // hardened key + if (m[2] === "'") { + idx += HARDENED_OFFSET; + } + child = child.deriveChild(idx); + } + return child; + } + + public deriveChild(index: number): HDKey { + if (!this.pubKey || !this.chainCode) { + throw new Error('No publicKey or chainCode set'); + } + let data = toU32(index); + if (index >= HARDENED_OFFSET) { + // Hardened + const priv = this.privateKey; + if (!priv) { + throw new Error('Could not derive hardened child key'); + } + // Hardened child: 0x00 || ser256(kpar) || ser32(index) + data = concatBytes(new Uint8Array([0]), priv, data); + } else { + // Normal child: serP(point(kpar)) || ser32(index) + data = concatBytes(this.pubKey, data); + } + const I = hmac(sha512, this.chainCode, data); + const childTweak = bytesToNumber(I.slice(0, 32)); + const chainCode = I.slice(32); + if (!secp.utils.isValidPrivateKey(childTweak)) { + throw new Error('Tweak bigger than curve order'); + } + const opt: HDKeyOpt = { + versions: this.versions, + chainCode, + depth: this.depth + 1, + parentFingerprint: this.fingerprint, + index, + }; + try { + // Private parent key -> private child key + if (this.privateKey) { + const added = mod(this.privKey! + childTweak, secp.CURVE.n); + if (!secp.utils.isValidPrivateKey(added)) { + throw new Error('The tweak was out of range or the resulted private key is invalid'); + } + opt.privateKey = added; + } else { + const added = Point.fromHex(this.pubKey).add(Point.fromPrivateKey(childTweak)); + // Cryptographically impossible: hmac-sha512 preimage would need to be found + if (added.equals(Point.ZERO)) { + throw new Error('The tweak was equal to negative P, which made the result key invalid'); + } + opt.publicKey = added.toRawBytes(true); + } + return new HDKey(opt); + } catch (err) { + return this.deriveChild(index + 1); + } + } + + public sign(hash: Uint8Array): Uint8Array { + if (!this.privateKey) { + throw new Error('No privateKey set!'); + } + assertBytes(hash, 32); + return secp.sign(hash, this.privKey!).toCompactRawBytes(); + } + + public verify(hash: Uint8Array, signature: Uint8Array): boolean { + assertBytes(hash, 32); + assertBytes(signature, 64); + if (!this.publicKey) { + throw new Error('No publicKey set!'); + } + let sig; + try { + sig = secp.Signature.fromCompact(signature); + } catch (error) { + return false; + } + return secp.verify(sig, hash, this.publicKey); + } + + public wipePrivateData(): this { + this.privKey = undefined; + if (this.privKeyBytes) { + this.privKeyBytes.fill(0); + this.privKeyBytes = undefined; + } + return this; + } + public toJSON(): { xpriv: string; xpub: string } { + return { + xpriv: this.privateExtendedKey, + xpub: this.publicExtendedKey, + }; + } + + private serialize(version: number, key: Uint8Array) { + if (!this.chainCode) { + throw new Error('No chainCode set'); + } + assertBytes(key, 33); + // version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33) + return concatBytes( + toU32(version), + new Uint8Array([this.depth]), + toU32(this.parentFingerprint), + toU32(this.index), + this.chainCode, + key + ); + } +} diff --git a/node_modules/@scure/bip32/lib/esm/index.js b/node_modules/@scure/bip32/lib/esm/index.js new file mode 100644 index 0000000..a5e768b --- /dev/null +++ b/node_modules/@scure/bip32/lib/esm/index.js @@ -0,0 +1,257 @@ +import { hmac } from '@noble/hashes/hmac'; +import { ripemd160 } from '@noble/hashes/ripemd160'; +import { sha256 } from '@noble/hashes/sha256'; +import { sha512 } from '@noble/hashes/sha512'; +import { bytes as assertBytes } from '@noble/hashes/_assert'; +import { bytesToHex, concatBytes, createView, hexToBytes, utf8ToBytes } from '@noble/hashes/utils'; +import { secp256k1 as secp } from '@noble/curves/secp256k1'; +import { mod } from '@noble/curves/abstract/modular'; +import { base58check as base58checker } from '@scure/base'; +const Point = secp.ProjectivePoint; +const base58check = base58checker(sha256); +function bytesToNumber(bytes) { + return BigInt(`0x${bytesToHex(bytes)}`); +} +function numberToBytes(num) { + return hexToBytes(num.toString(16).padStart(64, '0')); +} +const MASTER_SECRET = utf8ToBytes('Bitcoin seed'); +const BITCOIN_VERSIONS = { private: 0x0488ade4, public: 0x0488b21e }; +export const HARDENED_OFFSET = 0x80000000; +const hash160 = (data) => ripemd160(sha256(data)); +const fromU32 = (data) => createView(data).getUint32(0, false); +const toU32 = (n) => { + if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) { + throw new Error(`Invalid number=${n}. Should be from 0 to 2 ** 32 - 1`); + } + const buf = new Uint8Array(4); + createView(buf).setUint32(0, n, false); + return buf; +}; +export class HDKey { + get fingerprint() { + if (!this.pubHash) { + throw new Error('No publicKey set!'); + } + return fromU32(this.pubHash); + } + get identifier() { + return this.pubHash; + } + get pubKeyHash() { + return this.pubHash; + } + get privateKey() { + return this.privKeyBytes || null; + } + get publicKey() { + return this.pubKey || null; + } + get privateExtendedKey() { + const priv = this.privateKey; + if (!priv) { + throw new Error('No private key'); + } + return base58check.encode(this.serialize(this.versions.private, concatBytes(new Uint8Array([0]), priv))); + } + get publicExtendedKey() { + if (!this.pubKey) { + throw new Error('No public key'); + } + return base58check.encode(this.serialize(this.versions.public, this.pubKey)); + } + static fromMasterSeed(seed, versions = BITCOIN_VERSIONS) { + assertBytes(seed); + if (8 * seed.length < 128 || 8 * seed.length > 512) { + throw new Error(`HDKey: wrong seed length=${seed.length}. Should be between 128 and 512 bits; 256 bits is advised)`); + } + const I = hmac(sha512, MASTER_SECRET, seed); + return new HDKey({ + versions, + chainCode: I.slice(32), + privateKey: I.slice(0, 32), + }); + } + static fromExtendedKey(base58key, versions = BITCOIN_VERSIONS) { + const keyBuffer = base58check.decode(base58key); + const keyView = createView(keyBuffer); + const version = keyView.getUint32(0, false); + const opt = { + versions, + depth: keyBuffer[4], + parentFingerprint: keyView.getUint32(5, false), + index: keyView.getUint32(9, false), + chainCode: keyBuffer.slice(13, 45), + }; + const key = keyBuffer.slice(45); + const isPriv = key[0] === 0; + if (version !== versions[isPriv ? 'private' : 'public']) { + throw new Error('Version mismatch'); + } + if (isPriv) { + return new HDKey({ ...opt, privateKey: key.slice(1) }); + } + else { + return new HDKey({ ...opt, publicKey: key }); + } + } + static fromJSON(json) { + return HDKey.fromExtendedKey(json.xpriv); + } + constructor(opt) { + this.depth = 0; + this.index = 0; + this.chainCode = null; + this.parentFingerprint = 0; + if (!opt || typeof opt !== 'object') { + throw new Error('HDKey.constructor must not be called directly'); + } + this.versions = opt.versions || BITCOIN_VERSIONS; + this.depth = opt.depth || 0; + this.chainCode = opt.chainCode; + this.index = opt.index || 0; + this.parentFingerprint = opt.parentFingerprint || 0; + if (!this.depth) { + if (this.parentFingerprint || this.index) { + throw new Error('HDKey: zero depth with non-zero index/parent fingerprint'); + } + } + if (opt.publicKey && opt.privateKey) { + throw new Error('HDKey: publicKey and privateKey at same time.'); + } + if (opt.privateKey) { + if (!secp.utils.isValidPrivateKey(opt.privateKey)) { + throw new Error('Invalid private key'); + } + this.privKey = + typeof opt.privateKey === 'bigint' ? opt.privateKey : bytesToNumber(opt.privateKey); + this.privKeyBytes = numberToBytes(this.privKey); + this.pubKey = secp.getPublicKey(opt.privateKey, true); + } + else if (opt.publicKey) { + this.pubKey = Point.fromHex(opt.publicKey).toRawBytes(true); + } + else { + throw new Error('HDKey: no public or private key provided'); + } + this.pubHash = hash160(this.pubKey); + } + derive(path) { + if (!/^[mM]'?/.test(path)) { + throw new Error('Path must start with "m" or "M"'); + } + if (/^[mM]'?$/.test(path)) { + return this; + } + const parts = path.replace(/^[mM]'?\//, '').split('/'); + let child = this; + for (const c of parts) { + const m = /^(\d+)('?)$/.exec(c); + if (!m || m.length !== 3) { + throw new Error(`Invalid child index: ${c}`); + } + let idx = +m[1]; + if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) { + throw new Error('Invalid index'); + } + if (m[2] === "'") { + idx += HARDENED_OFFSET; + } + child = child.deriveChild(idx); + } + return child; + } + deriveChild(index) { + if (!this.pubKey || !this.chainCode) { + throw new Error('No publicKey or chainCode set'); + } + let data = toU32(index); + if (index >= HARDENED_OFFSET) { + const priv = this.privateKey; + if (!priv) { + throw new Error('Could not derive hardened child key'); + } + data = concatBytes(new Uint8Array([0]), priv, data); + } + else { + data = concatBytes(this.pubKey, data); + } + const I = hmac(sha512, this.chainCode, data); + const childTweak = bytesToNumber(I.slice(0, 32)); + const chainCode = I.slice(32); + if (!secp.utils.isValidPrivateKey(childTweak)) { + throw new Error('Tweak bigger than curve order'); + } + const opt = { + versions: this.versions, + chainCode, + depth: this.depth + 1, + parentFingerprint: this.fingerprint, + index, + }; + try { + if (this.privateKey) { + const added = mod(this.privKey + childTweak, secp.CURVE.n); + if (!secp.utils.isValidPrivateKey(added)) { + throw new Error('The tweak was out of range or the resulted private key is invalid'); + } + opt.privateKey = added; + } + else { + const added = Point.fromHex(this.pubKey).add(Point.fromPrivateKey(childTweak)); + if (added.equals(Point.ZERO)) { + throw new Error('The tweak was equal to negative P, which made the result key invalid'); + } + opt.publicKey = added.toRawBytes(true); + } + return new HDKey(opt); + } + catch (err) { + return this.deriveChild(index + 1); + } + } + sign(hash) { + if (!this.privateKey) { + throw new Error('No privateKey set!'); + } + assertBytes(hash, 32); + return secp.sign(hash, this.privKey).toCompactRawBytes(); + } + verify(hash, signature) { + assertBytes(hash, 32); + assertBytes(signature, 64); + if (!this.publicKey) { + throw new Error('No publicKey set!'); + } + let sig; + try { + sig = secp.Signature.fromCompact(signature); + } + catch (error) { + return false; + } + return secp.verify(sig, hash, this.publicKey); + } + wipePrivateData() { + this.privKey = undefined; + if (this.privKeyBytes) { + this.privKeyBytes.fill(0); + this.privKeyBytes = undefined; + } + return this; + } + toJSON() { + return { + xpriv: this.privateExtendedKey, + xpub: this.publicExtendedKey, + }; + } + serialize(version, key) { + if (!this.chainCode) { + throw new Error('No chainCode set'); + } + assertBytes(key, 33); + return concatBytes(toU32(version), new Uint8Array([this.depth]), toU32(this.parentFingerprint), toU32(this.index), this.chainCode, key); + } +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/lib/esm/index.js.map b/node_modules/@scure/bip32/lib/esm/index.js.map new file mode 100644 index 0000000..a764a14 --- /dev/null +++ b/node_modules/@scure/bip32/lib/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC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AC;QACR,IAAI;YACF,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC;SAC7C;QAAC,OAAO,KAAK,EAAE;YACd,OAAO,KAAK,CAAC;SACd;QACD,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;IAChD,CAAC;IAEM,eAAe;QACpB,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC;QACzB,IAAI,IAAI,CAAC,YAAY,EAAE;YACrB,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAC1B,IAAI,CAAC,YAAY,GAAG,SAAS,CAAC;SAC/B;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IACM,MAAM;QACX,OAAO;YACL,KAAK,EAAE,IAAI,CAAC,kBAAkB;YAC9B,IAAI,EAAE,IAAI,CAAC,iBAAiB;SAC7B,CAAC;IACJ,CAAC;IAEO,SAAS,CAAC,OAAe,EAAE,GAAe;QAChD,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;YACnB,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;SACrC;QACD,WAAW,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;QAErB,OAAO,WAAW,CAChB,KAAK,CAAC,OAAO,CAAC,EACd,IAAI,UAAU,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAC5B,KAAK,CAAC,IAAI,CAAC,iBAAiB,CAAC,EAC7B,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,EACjB,IAAI,CAAC,SAAS,EACd,GAAG,CACJ,CAAC;IACJ,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/lib/esm/package.json b/node_modules/@scure/bip32/lib/esm/package.json new file mode 100644 index 0000000..e8309c4 --- /dev/null +++ b/node_modules/@scure/bip32/lib/esm/package.json @@ -0,0 +1,6 @@ +{ + "type": "module", + "browser": { + "crypto": false + } +} \ No newline at end of file diff --git a/node_modules/@scure/bip32/lib/index.d.ts b/node_modules/@scure/bip32/lib/index.d.ts new file mode 100644 index 0000000..753367b --- /dev/null +++ b/node_modules/@scure/bip32/lib/index.d.ts @@ -0,0 +1,49 @@ +export declare const HARDENED_OFFSET: number; +export interface Versions { + private: number; + public: number; +} +interface HDKeyOpt { + versions: Versions; + depth?: number; + index?: number; + parentFingerprint?: number; + chainCode: Uint8Array; + publicKey?: Uint8Array; + privateKey?: Uint8Array | bigint; +} +export declare class HDKey { + get fingerprint(): number; + get identifier(): Uint8Array | undefined; + get pubKeyHash(): Uint8Array | undefined; + get privateKey(): Uint8Array | null; + get publicKey(): Uint8Array | null; + get privateExtendedKey(): string; + get publicExtendedKey(): string; + static fromMasterSeed(seed: Uint8Array, versions?: Versions): HDKey; + static fromExtendedKey(base58key: string, versions?: Versions): HDKey; + static fromJSON(json: { + xpriv: string; + }): HDKey; + readonly versions: Versions; + readonly depth: number; + readonly index: number; + readonly chainCode: Uint8Array | null; + readonly parentFingerprint: number; + private privKey?; + private privKeyBytes?; + private pubKey?; + private pubHash; + constructor(opt: HDKeyOpt); + derive(path: string): HDKey; + deriveChild(index: number): HDKey; + sign(hash: Uint8Array): Uint8Array; + verify(hash: Uint8Array, signature: Uint8Array): boolean; + wipePrivateData(): this; + toJSON(): { + xpriv: string; + xpub: string; + }; + private serialize; +} +export {}; diff --git a/node_modules/@scure/bip32/lib/index.js b/node_modules/@scure/bip32/lib/index.js new file mode 100644 index 0000000..04722bd --- /dev/null +++ b/node_modules/@scure/bip32/lib/index.js @@ -0,0 +1,261 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.HDKey = exports.HARDENED_OFFSET = void 0; +const hmac_1 = require("@noble/hashes/hmac"); +const ripemd160_1 = require("@noble/hashes/ripemd160"); +const sha256_1 = require("@noble/hashes/sha256"); +const sha512_1 = require("@noble/hashes/sha512"); +const _assert_1 = require("@noble/hashes/_assert"); +const utils_1 = require("@noble/hashes/utils"); +const secp256k1_1 = require("@noble/curves/secp256k1"); +const modular_1 = require("@noble/curves/abstract/modular"); +const base_1 = require("@scure/base"); +const Point = secp256k1_1.secp256k1.ProjectivePoint; +const base58check = (0, base_1.base58check)(sha256_1.sha256); +function bytesToNumber(bytes) { + return BigInt(`0x${(0, utils_1.bytesToHex)(bytes)}`); +} +function numberToBytes(num) { + return (0, utils_1.hexToBytes)(num.toString(16).padStart(64, '0')); +} +const MASTER_SECRET = (0, utils_1.utf8ToBytes)('Bitcoin seed'); +const BITCOIN_VERSIONS = { private: 0x0488ade4, public: 0x0488b21e }; +exports.HARDENED_OFFSET = 0x80000000; +const hash160 = (data) => (0, ripemd160_1.ripemd160)((0, sha256_1.sha256)(data)); +const fromU32 = (data) => (0, utils_1.createView)(data).getUint32(0, false); +const toU32 = (n) => { + if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) { + throw new Error(`Invalid number=${n}. Should be from 0 to 2 ** 32 - 1`); + } + const buf = new Uint8Array(4); + (0, utils_1.createView)(buf).setUint32(0, n, false); + return buf; +}; +class HDKey { + get fingerprint() { + if (!this.pubHash) { + throw new Error('No publicKey set!'); + } + return fromU32(this.pubHash); + } + get identifier() { + return this.pubHash; + } + get pubKeyHash() { + return this.pubHash; + } + get privateKey() { + return this.privKeyBytes || null; + } + get publicKey() { + return this.pubKey || null; + } + get privateExtendedKey() { + const priv = this.privateKey; + if (!priv) { + throw new Error('No private key'); + } + return base58check.encode(this.serialize(this.versions.private, (0, utils_1.concatBytes)(new Uint8Array([0]), priv))); + } + get publicExtendedKey() { + if (!this.pubKey) { + throw new Error('No public key'); + } + return base58check.encode(this.serialize(this.versions.public, this.pubKey)); + } + static fromMasterSeed(seed, versions = BITCOIN_VERSIONS) { + (0, _assert_1.bytes)(seed); + if (8 * seed.length < 128 || 8 * seed.length > 512) { + throw new Error(`HDKey: wrong seed length=${seed.length}. Should be between 128 and 512 bits; 256 bits is advised)`); + } + const I = (0, hmac_1.hmac)(sha512_1.sha512, MASTER_SECRET, seed); + return new HDKey({ + versions, + chainCode: I.slice(32), + privateKey: I.slice(0, 32), + }); + } + static fromExtendedKey(base58key, versions = BITCOIN_VERSIONS) { + const keyBuffer = base58check.decode(base58key); + const keyView = (0, utils_1.createView)(keyBuffer); + const version = keyView.getUint32(0, false); + const opt = { + versions, + depth: keyBuffer[4], + parentFingerprint: keyView.getUint32(5, false), + index: keyView.getUint32(9, false), + chainCode: keyBuffer.slice(13, 45), + }; + const key = keyBuffer.slice(45); + const isPriv = key[0] === 0; + if (version !== versions[isPriv ? 'private' : 'public']) { + throw new Error('Version mismatch'); + } + if (isPriv) { + return new HDKey({ ...opt, privateKey: key.slice(1) }); + } + else { + return new HDKey({ ...opt, publicKey: key }); + } + } + static fromJSON(json) { + return HDKey.fromExtendedKey(json.xpriv); + } + constructor(opt) { + this.depth = 0; + this.index = 0; + this.chainCode = null; + this.parentFingerprint = 0; + if (!opt || typeof opt !== 'object') { + throw new Error('HDKey.constructor must not be called directly'); + } + this.versions = opt.versions || BITCOIN_VERSIONS; + this.depth = opt.depth || 0; + this.chainCode = opt.chainCode; + this.index = opt.index || 0; + this.parentFingerprint = opt.parentFingerprint || 0; + if (!this.depth) { + if (this.parentFingerprint || this.index) { + throw new Error('HDKey: zero depth with non-zero index/parent fingerprint'); + } + } + if (opt.publicKey && opt.privateKey) { + throw new Error('HDKey: publicKey and privateKey at same time.'); + } + if (opt.privateKey) { + if (!secp256k1_1.secp256k1.utils.isValidPrivateKey(opt.privateKey)) { + throw new Error('Invalid private key'); + } + this.privKey = + typeof opt.privateKey === 'bigint' ? opt.privateKey : bytesToNumber(opt.privateKey); + this.privKeyBytes = numberToBytes(this.privKey); + this.pubKey = secp256k1_1.secp256k1.getPublicKey(opt.privateKey, true); + } + else if (opt.publicKey) { + this.pubKey = Point.fromHex(opt.publicKey).toRawBytes(true); + } + else { + throw new Error('HDKey: no public or private key provided'); + } + this.pubHash = hash160(this.pubKey); + } + derive(path) { + if (!/^[mM]'?/.test(path)) { + throw new Error('Path must start with "m" or "M"'); + } + if (/^[mM]'?$/.test(path)) { + return this; + } + const parts = path.replace(/^[mM]'?\//, '').split('/'); + let child = this; + for (const c of parts) { + const m = /^(\d+)('?)$/.exec(c); + if (!m || m.length !== 3) { + throw new Error(`Invalid child index: ${c}`); + } + let idx = +m[1]; + if (!Number.isSafeInteger(idx) || idx >= exports.HARDENED_OFFSET) { + throw new Error('Invalid index'); + } + if (m[2] === "'") { + idx += exports.HARDENED_OFFSET; + } + child = child.deriveChild(idx); + } + return child; + } + deriveChild(index) { + if (!this.pubKey || !this.chainCode) { + throw new Error('No publicKey or chainCode set'); + } + let data = toU32(index); + if (index >= exports.HARDENED_OFFSET) { + const priv = this.privateKey; + if (!priv) { + throw new Error('Could not derive hardened child key'); + } + data = (0, utils_1.concatBytes)(new Uint8Array([0]), priv, data); + } + else { + data = (0, utils_1.concatBytes)(this.pubKey, data); + } + const I = (0, hmac_1.hmac)(sha512_1.sha512, this.chainCode, data); + const childTweak = bytesToNumber(I.slice(0, 32)); + const chainCode = I.slice(32); + if (!secp256k1_1.secp256k1.utils.isValidPrivateKey(childTweak)) { + throw new Error('Tweak bigger than curve order'); + } + const opt = { + versions: this.versions, + chainCode, + depth: this.depth + 1, + parentFingerprint: this.fingerprint, + index, + }; + try { + if (this.privateKey) { + const added = (0, modular_1.mod)(this.privKey + childTweak, secp256k1_1.secp256k1.CURVE.n); + if (!secp256k1_1.secp256k1.utils.isValidPrivateKey(added)) { + throw new Error('The tweak was out of range or the resulted private key is invalid'); + } + opt.privateKey = added; + } + else { + const added = Point.fromHex(this.pubKey).add(Point.fromPrivateKey(childTweak)); + if (added.equals(Point.ZERO)) { + throw new Error('The tweak was equal to negative P, which made the result key invalid'); + } + opt.publicKey = added.toRawBytes(true); + } + return new HDKey(opt); + } + catch (err) { + return this.deriveChild(index + 1); + } + } + sign(hash) { + if (!this.privateKey) { + throw new Error('No privateKey set!'); + } + (0, _assert_1.bytes)(hash, 32); + return secp256k1_1.secp256k1.sign(hash, this.privKey).toCompactRawBytes(); + } + verify(hash, signature) { + (0, _assert_1.bytes)(hash, 32); + (0, _assert_1.bytes)(signature, 64); + if (!this.publicKey) { + throw new Error('No publicKey set!'); + } + let sig; + try { + sig = secp256k1_1.secp256k1.Signature.fromCompact(signature); + } + catch (error) { + return false; + } + return secp256k1_1.secp256k1.verify(sig, hash, this.publicKey); + } + wipePrivateData() { + this.privKey = undefined; + if (this.privKeyBytes) { + this.privKeyBytes.fill(0); + this.privKeyBytes = undefined; + } + return this; + } + toJSON() { + return { + xpriv: this.privateExtendedKey, + xpub: this.publicExtendedKey, + }; + } + serialize(version, key) { + if (!this.chainCode) { + throw new Error('No chainCode set'); + } + (0, _assert_1.bytes)(key, 33); + return (0, utils_1.concatBytes)(toU32(version), new Uint8Array([this.depth]), toU32(this.parentFingerprint), toU32(this.index), this.chainCode, key); + } +} +exports.HDKey = HDKey; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/lib/index.js.map b/node_modules/@scure/bip32/lib/index.js.map new file mode 100644 index 0000000..81026d4 --- /dev/null +++ b/node_modules/@scure/bip32/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":";;;AACA,6CAA0C;AAC1C,uDAAoD;AACpD,iDAA8C;AAC9C,iDAA8C;AAC9C,mDAA6D;AAC7D,+CAAmG;AACnG,uDAA4D;AAC5D,4DAAqD;AACrD,sCAA2D;AAE3D,MAAM,KAAK,GAAG,qBAAI,CAAC,eAAe,CAAC;AACnC,MAAM,WAAW,GAAG,IAAA,kBAAa,EAAC,eAAM,CAAC,CAAC;AAE1C,SAAS,aAAa,CAAC,KAAiB;IACtC,OAAO,MAAM,CAAC,KAAK,IAAA,kBAAU,EAAC,KAAK,CAAC,EAAE,CAAC,CAAC;AAC1C,CAAC;AAED,SAAS,aAAa,CAAC,GAAW;IAChC,OAAO,IAAA,kBAAU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C,IAAI,CAAC,SAAS,EAAE;YACnB,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;SACrC;QACD,IAAA,eAAW,EAAC,GAAG,EAAE,EAAE,CAAC,CAAC;QAErB,OAAO,IAAA,mBAAW,EAChB,KAAK,CAAC,OAAO,CAAC,EACd,IAAI,UAAU,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAC5B,KAAK,CAAC,IAAI,CAAC,iBAAiB,CAAC,EAC7B,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,EACjB,IAAI,CAAC,SAAS,EACd,GAAG,CACJ,CAAC;IACJ,CAAC;CACF;AA7PD,sBA6PC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/LICENSE b/node_modules/@scure/bip32/node_modules/@noble/curves/LICENSE new file mode 100644 index 0000000..9297a04 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/README.md b/node_modules/@scure/bip32/node_modules/@noble/curves/README.md new file mode 100644 index 0000000..a5d14f4 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/README.md @@ -0,0 +1,971 @@ +# noble-curves + +Audited & minimal JS implementation of elliptic curve cryptography. + +- 🔒 [**Audited**](#security) by an independent security firm +- 🔻 Tree-shaking-friendly: use only what's necessary, other code won't be included +- 🏎 Ultra-fast, hand-optimized for caveats of JS engines +- 🔍 Unique tests ensure correctness: property-based, cross-library and Wycheproof vectors, fuzzing +- ➰ Short Weierstrass, Edwards, Montgomery curves +- ✍️ ECDSA, EdDSA, Schnorr, BLS signature schemes, ECDH key agreement +- 🔖 SUF-CMA and SBS (non-repudiation) for ed25519, ed448 and others +- #️⃣ Hash-to-curve + for encoding or hashing an arbitrary string to an elliptic curve point +- 🧜‍♂️ Poseidon ZK-friendly hash + +Check out [Upgrading](#upgrading) if you've previously used single-feature noble +packages. See [Resources](#resources) for articles and real-world software that uses curves. + +### This library belongs to _noble_ crypto + +> **noble-crypto** — high-security, easily auditable set of contained cryptographic libraries and tools. + +- No dependencies, protection against supply chain attacks +- Auditable TypeScript / JS code +- Supported in all major browsers and stable node.js versions +- All releases are signed with PGP keys +- Check out [homepage](https://paulmillr.com/noble/) & all libraries: + [curves](https://github.com/paulmillr/noble-curves) + (4kb versions [secp256k1](https://github.com/paulmillr/noble-secp256k1), + [ed25519](https://github.com/paulmillr/noble-ed25519)), + [hashes](https://github.com/paulmillr/noble-hashes) + +## Usage + +> npm install @noble/curves + +We support all major platforms and runtimes. +For [Deno](https://deno.land), ensure to use [npm specifier](https://deno.land/manual@v1.28.0/node/npm_specifiers). +For React Native, you may need a [polyfill for crypto.getRandomValues](https://github.com/LinusU/react-native-get-random-values). +If you don't like NPM, a standalone [noble-curves.js](https://github.com/paulmillr/noble-curves/releases) is also available. + +The library is tree-shaking-friendly and does not expose root entry point as +`@noble/curves`. Instead, you need to import specific primitives. +This is done to ensure small size of your apps. + +The package consists of two parts: + +* [Implementations](#implementations), utilizing one dependency [noble-hashes](https://github.com/paulmillr/noble-hashes), + providing ready-to-use: + - NIST curves secp256r1 / p256, secp384r1 / p384, secp521r1 / p521 + - SECG curve secp256k1 + - ed25519 / curve25519 / x25519 / ristretto255, edwards448 / curve448 / x448 + - pairing-friendly curves bls12-381, bn254 + - [pasta](https://electriccoin.co/blog/the-pasta-curves-for-halo-2-and-beyond/) curves +2. [Abstract](#abstract-api), zero-dependency elliptic curve algorithms + +### Implementations + +#### Generic example for all curves, secp256k1 + +```ts +// Each curve has similar methods +import { secp256k1 } from '@noble/curves/secp256k1'; // ESM and Common.js +// import { secp256k1 } from 'npm:@noble/curves@1.2.0/secp256k1'; // Deno +const priv = secp256k1.utils.randomPrivateKey(); +const pub = secp256k1.getPublicKey(priv); +const msg = new Uint8Array(32).fill(1); +const sig = secp256k1.sign(msg, priv); +const isValid = secp256k1.verify(sig, msg, pub) === true; + +// hex strings are also supported besides Uint8Arrays: +const privHex = '46c930bc7bb4db7f55da20798697421b98c4175a52c630294d75a84b9c126236'; +const pub2 = secp256k1.getPublicKey(privHex); +``` + +#### All imports + +```typescript +import { secp256k1, schnorr } from '@noble/curves/secp256k1'; +import { ed25519, ed25519ph, ed25519ctx, x25519, RistrettoPoint } from '@noble/curves/ed25519'; +import { ed448, ed448ph, ed448ctx, x448 } from '@noble/curves/ed448'; +import { p256 } from '@noble/curves/p256'; +import { p384 } from '@noble/curves/p384'; +import { p521 } from '@noble/curves/p521'; +import { pallas, vesta } from '@noble/curves/pasta'; +import { bls12_381 } from '@noble/curves/bls12-381'; +import { bn254 } from '@noble/curves/bn254'; +import { jubjub } from '@noble/curves/jubjub'; +``` + +#### ECDSA public key recovery & ECDH + +```ts +// extraEntropy https://moderncrypto.org/mail-archive/curves/2017/000925.html +const sigImprovedSecurity = secp256k1.sign(msg, priv, { extraEntropy: true }); +sig.recoverPublicKey(msg) === pub; // public key recovery +const someonesPub = secp256k1.getPublicKey(secp256k1.utils.randomPrivateKey()); +const shared = secp256k1.getSharedSecret(priv, someonesPub); // ECDH +``` + +#### Schnorr signatures over secp256k1 (BIP340) + +```ts +import { schnorr } from '@noble/curves/secp256k1'; +const priv = schnorr.utils.randomPrivateKey(); +const pub = schnorr.getPublicKey(priv); +const msg = new TextEncoder().encode('hello'); +const sig = schnorr.sign(msg, priv); +const isValid = schnorr.verify(sig, msg, pub); +``` + +#### ed25519, X25519, ristretto255 + +```ts +import { ed25519 } from '@noble/curves/ed25519'; +const priv = ed25519.utils.randomPrivateKey(); +const pub = ed25519.getPublicKey(priv); +const msg = new TextEncoder().encode('hello'); +const sig = ed25519.sign(msg, priv); +ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215 +ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5 +``` + +Default `verify` behavior follows [ZIP215](https://zips.z.cash/zip-0215) and +[can be used in consensus-critical applications](https://hdevalence.ca/blog/2020-10-04-its-25519am). +It has SUF-CMA (strong unforgeability under chosen message attacks). +`zip215: false` option switches verification criteria to strict +[RFC8032](https://www.rfc-editor.org/rfc/rfc8032) / [FIPS 186-5](https://csrc.nist.gov/publications/detail/fips/186/5/final) +and additionally provides non-repudiation with SBS [(Strongly Binding Signatures)](https://eprint.iacr.org/2020/1244). + +X25519 follows [RFC7748](https://www.rfc-editor.org/rfc/rfc7748). +ristretto255 follows [irtf draft](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448). + +```ts +// Variants from RFC8032: with context, prehashed +import { ed25519ctx, ed25519ph } from '@noble/curves/ed25519'; + +// ECDH using curve25519 aka x25519 +import { x25519 } from '@noble/curves/ed25519'; +const priv = 'a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4'; +const pub = 'e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c'; +x25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub); // aliases +x25519.getPublicKey(priv) === x25519.scalarMultBase(priv); +x25519.getPublicKey(x25519.utils.randomPrivateKey()); + +// ed25519 => x25519 conversion +import { edwardsToMontgomeryPub, edwardsToMontgomeryPriv } from '@noble/curves/ed25519'; +edwardsToMontgomeryPub(ed25519.getPublicKey(ed25519.utils.randomPrivateKey())); +edwardsToMontgomeryPriv(ed25519.utils.randomPrivateKey()); + +// hash-to-curve, ristretto255 +import { hashToCurve, encodeToCurve, RistrettoPoint } from '@noble/curves/ed25519'; +const rp = RistrettoPoint.fromHex( + '6a493210f7499cd17fecb510ae0cea23a110e8d5b901f8acadd3095c73a3b919' +); +RistrettoPoint.hashToCurve('Ristretto is traditionally a short shot of espresso coffee'); +// also has add(), equals(), multiply(), toRawBytes() methods +``` + +#### ed448, X448 + +```ts +import { ed448 } from '@noble/curves/ed448'; +const priv = ed448.utils.randomPrivateKey(); +const pub = ed448.getPublicKey(priv); +const msg = new TextEncoder().encode('whatsup'); +const sig = ed448.sign(msg, priv); +ed448.verify(sig, msg, pub); + +import { ed448ph, ed448ctx, x448, hashToCurve, encodeToCurve } from '@noble/curves/ed448'; +x448.getSharedSecret(priv, pub) === x448.scalarMult(priv, pub); // aliases +x448.getPublicKey(priv) === x448.scalarMultBase(priv); +``` + +Same RFC7748 / RFC8032 are followed. + +#### bls12-381 + +See [abstract/bls](#abstractbls-barreto-lynn-scott-curves). + +#### Accessing a curve's variables + +```ts +import { secp256k1 } from '@noble/curves/secp256k1'; +// Every curve has `CURVE` object that contains its parameters, field, and others +console.log(secp256k1.CURVE.p); // field modulus +console.log(secp256k1.CURVE.n); // curve order +console.log(secp256k1.CURVE.a, secp256k1.CURVE.b); // equation params +console.log(secp256k1.CURVE.Gx, secp256k1.CURVE.Gy); // base point coordinates +``` + +## Abstract API + +Abstract API allows to define custom curves. All arithmetics is done with JS +bigints over finite fields, which is defined from `modular` sub-module. For +scalar multiplication, we use +[precomputed tables with w-ary non-adjacent form (wNAF)](https://paulmillr.com/posts/noble-secp256k1-fast-ecc/). +Precomputes are enabled for weierstrass and edwards BASE points of a curve. You +could precompute any other point (e.g. for ECDH) using `utils.precompute()` +method: check out examples. + +There are following zero-dependency algorithms: + +- [abstract/weierstrass: Short Weierstrass curve](#abstractweierstrass-short-weierstrass-curve) +- [abstract/edwards: Twisted Edwards curve](#abstractedwards-twisted-edwards-curve) +- [abstract/montgomery: Montgomery curve](#abstractmontgomery-montgomery-curve) +- [abstract/bls: Barreto-Lynn-Scott curves](#abstractbls-barreto-lynn-scott-curves) +- [abstract/hash-to-curve: Hashing strings to curve points](#abstracthash-to-curve-hashing-strings-to-curve-points) +- [abstract/poseidon: Poseidon hash](#abstractposeidon-poseidon-hash) +- [abstract/modular: Modular arithmetics utilities](#abstractmodular-modular-arithmetics-utilities) +- [abstract/utils: General utilities](#abstractutils-general-utilities) + +### abstract/weierstrass: Short Weierstrass curve + +```ts +import { weierstrass } from '@noble/curves/abstract/weierstrass'; +import { Field } from '@noble/curves/abstract/modular'; // finite field for mod arithmetics +import { sha256 } from '@noble/hashes/sha256'; // 3rd-party sha256() of type utils.CHash +import { hmac } from '@noble/hashes/hmac'; // 3rd-party hmac() that will accept sha256() +import { concatBytes, randomBytes } from '@noble/hashes/utils'; // 3rd-party utilities +const secq256k1 = weierstrass({ + // secq256k1: cycle of secp256k1 with Fp/N flipped. + // https://personaelabs.org/posts/spartan-ecdsa + // https://zcash.github.io/halo2/background/curves.html#cycles-of-curves + a: 0n, + b: 7n, + Fp: Field(2n ** 256n - 432420386565659656852420866394968145599n), + n: 2n ** 256n - 2n ** 32n - 2n ** 9n - 2n ** 8n - 2n ** 7n - 2n ** 6n - 2n ** 4n - 1n, + Gx: 55066263022277343669578718895168534326250603453777594175500187360389116729240n, + Gy: 32670510020758816978083085130507043184471273380659243275938904335757337482424n, + hash: sha256, + hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(sha256, key, concatBytes(...msgs)), + randomBytes, +}); + +// Replace weierstrass with weierstrassPoints if you don't need ECDSA, hash, hmac, randomBytes +``` + +Short Weierstrass curve's formula is `y² = x³ + ax + b`. `weierstrass` +expects arguments `a`, `b`, field `Fp`, curve order `n`, cofactor `h` +and coordinates `Gx`, `Gy` of generator point. + +**`k` generation** is done deterministically, following +[RFC6979](https://www.rfc-editor.org/rfc/rfc6979). For this you will need +`hmac` & `hash`, which in our implementations is provided by noble-hashes. If +you're using different hashing library, make sure to wrap it in the following interface: + +```ts +type CHash = { + (message: Uint8Array): Uint8Array; + blockLen: number; + outputLen: number; + create(): any; +}; +``` + +**Weierstrass points:** + +1. Exported as `ProjectivePoint` +2. Represented in projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z) +3. Use complete exception-free formulas for addition and doubling +4. Can be decoded/encoded from/to Uint8Array / hex strings using + `ProjectivePoint.fromHex` and `ProjectivePoint#toRawBytes()` +5. Have `assertValidity()` which checks for being on-curve +6. Have `toAffine()` and `x` / `y` getters which convert to 2d xy affine coordinates + +```ts +// `weierstrassPoints()` returns `CURVE` and `ProjectivePoint` +// `weierstrass()` returns `CurveFn` +type SignOpts = { lowS?: boolean; prehash?: boolean; extraEntropy: boolean | Uint8Array }; +type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => SignatureType; + verify: ( + signature: Hex | SignatureType, + msgHash: Hex, + publicKey: Hex, + opts?: { lowS?: boolean; prehash?: boolean } + ) => boolean; + ProjectivePoint: ProjectivePointConstructor; + Signature: SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: PrivKey) => bigint; + isValidPrivateKey(key: PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: ProjPointType) => ProjPointType; + }; +}; + +// T is usually bigint, but can be something else like complex numbers in BLS curves +interface ProjPointType extends Group> { + readonly px: T; + readonly py: T; + readonly pz: T; + get x(): bigint; + get y(): bigint; + multiply(scalar: bigint): ProjPointType; + multiplyUnsafe(scalar: bigint): ProjPointType; + multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined; + toAffine(iz?: T): AffinePoint; + isTorsionFree(): boolean; + clearCofactor(): ProjPointType; + assertValidity(): void; + hasEvenY(): boolean; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; +} +// Static methods for 3d XYZ points +interface ProjConstructor extends GroupConstructor> { + new (x: T, y: T, z: T): ProjPointType; + fromAffine(p: AffinePoint): ProjPointType; + fromHex(hex: Hex): ProjPointType; + fromPrivateKey(privateKey: PrivKey): ProjPointType; +} +``` + +**ECDSA signatures** are represented by `Signature` instances and can be +described by the interface: + +```ts +interface SignatureType { + readonly r: bigint; + readonly s: bigint; + readonly recovery?: number; + assertValidity(): void; + addRecoveryBit(recovery: number): SignatureType; + hasHighS(): boolean; + normalizeS(): SignatureType; + recoverPublicKey(msgHash: Hex): ProjPointType; + toCompactRawBytes(): Uint8Array; + toCompactHex(): string; + // DER-encoded + toDERRawBytes(): Uint8Array; + toDERHex(): string; +} +type SignatureConstructor = { + new (r: bigint, s: bigint): SignatureType; + fromCompact(hex: Hex): SignatureType; + fromDER(hex: Hex): SignatureType; +}; +``` + +More examples: + +```typescript +// All curves expose same generic interface. +const priv = secq256k1.utils.randomPrivateKey(); +secq256k1.getPublicKey(priv); // Convert private key to public. +const sig = secq256k1.sign(msg, priv); // Sign msg with private key. +secq256k1.verify(sig, msg, priv); // Verify if sig is correct. + +const Point = secq256k1.ProjectivePoint; +const point = Point.BASE; // Elliptic curve Point class and BASE point static var. +point.add(point).equals(point.double()); // add(), equals(), double() methods +point.subtract(point).equals(Point.ZERO); // subtract() method, ZERO static var +point.negate(); // Flips point over x/y coordinate. +point.multiply(31415n); // Multiplication of Point by scalar. + +point.assertValidity(); // Checks for being on-curve +point.toAffine(); // Converts to 2d affine xy coordinates + +secq256k1.CURVE.n; +secq256k1.CURVE.p; +secq256k1.CURVE.Fp.mod(); +secq256k1.CURVE.hash(); + +// precomputes +const fast = secq256k1.utils.precompute(8, Point.fromHex(someonesPubKey)); +fast.multiply(privKey); // much faster ECDH now +``` + +### abstract/edwards: Twisted Edwards curve + +```ts +import { twistedEdwards } from '@noble/curves/abstract/edwards'; +import { Field } from '@noble/curves/abstract/modular'; +import { sha512 } from '@noble/hashes/sha512'; +import { randomBytes } from '@noble/hashes/utils'; + +const Fp = Field(2n ** 255n - 19n); +const ed25519 = twistedEdwards({ + a: Fp.create(-1n), + d: Fp.div(-121665n, 121666n), // -121665n/121666n mod p + Fp: Fp, + n: 2n ** 252n + 27742317777372353535851937790883648493n, + h: 8n, + Gx: 15112221349535400772501151409588531511454012693041857206046113283949847762202n, + Gy: 46316835694926478169428394003475163141307993866256225615783033603165251855960n, + hash: sha512, + randomBytes, + adjustScalarBytes(bytes) { + // optional; but mandatory in ed25519 + bytes[0] &= 248; + bytes[31] &= 127; + bytes[31] |= 64; + return bytes; + }, +} as const); +``` + +Twisted Edwards curve's formula is `ax² + y² = 1 + dx²y²`. You must specify `a`, `d`, field `Fp`, order `n`, cofactor `h` +and coordinates `Gx`, `Gy` of generator point. + +For EdDSA signatures, `hash` param required. `adjustScalarBytes` which instructs how to change private scalars could be specified. + +**Edwards points:** + +1. Exported as `ExtendedPoint` +2. Represented in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z) +3. Use complete exception-free formulas for addition and doubling +4. Can be decoded/encoded from/to Uint8Array / hex strings using `ExtendedPoint.fromHex` and `ExtendedPoint#toRawBytes()` +5. Have `assertValidity()` which checks for being on-curve +6. Have `toAffine()` and `x` / `y` getters which convert to 2d xy affine coordinates +7. Have `isTorsionFree()`, `clearCofactor()` and `isSmallOrder()` utilities to handle torsions + +```ts +// `twistedEdwards()` returns `CurveFn` of following type: +type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: Hex) => Uint8Array; + sign: (message: Hex, privateKey: Hex, context?: Hex) => Uint8Array; + verify: (sig: SigType, message: Hex, publicKey: Hex, context?: Hex) => boolean; + ExtendedPoint: ExtPointConstructor; + utils: { + randomPrivateKey: () => Uint8Array; + getExtendedPublicKey: (key: PrivKey) => { + head: Uint8Array; + prefix: Uint8Array; + scalar: bigint; + point: PointType; + pointBytes: Uint8Array; + }; + }; +}; + +interface ExtPointType extends Group { + readonly ex: bigint; + readonly ey: bigint; + readonly ez: bigint; + readonly et: bigint; + get x(): bigint; + get y(): bigint; + assertValidity(): void; + multiply(scalar: bigint): ExtPointType; + multiplyUnsafe(scalar: bigint): ExtPointType; + isSmallOrder(): boolean; + isTorsionFree(): boolean; + clearCofactor(): ExtPointType; + toAffine(iz?: bigint): AffinePoint; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; +} +// Static methods of Extended Point with coordinates in X, Y, Z, T +interface ExtPointConstructor extends GroupConstructor { + new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType; + fromAffine(p: AffinePoint): ExtPointType; + fromHex(hex: Hex): ExtPointType; + fromPrivateKey(privateKey: Hex): ExtPointType; +} +``` + +### abstract/montgomery: Montgomery curve + +```typescript +import { montgomery } from '@noble/curves/abstract/montgomery'; +import { Field } from '@noble/curves/abstract/modular'; + +const x25519 = montgomery({ + a: 486662n, + Gu: 9n, + Fp: Field(2n ** 255n - 19n), + montgomeryBits: 255, + nByteLength: 32, + // Optional param + adjustScalarBytes(bytes) { + bytes[0] &= 248; + bytes[31] &= 127; + bytes[31] |= 64; + return bytes; + }, +}); +``` + +The module contains methods for x-only ECDH on Curve25519 / Curve448 from RFC7748. +Proper Elliptic Curve Points are not implemented yet. + +You must specify curve params `Fp`, `a`, `Gu` coordinate of u, `montgomeryBits` and `nByteLength`. + +### abstract/bls: Barreto-Lynn-Scott curves + +The module abstracts BLS (Barreto-Lynn-Scott) pairing-friendly elliptic curve construction. +They allow to construct [zk-SNARKs](https://z.cash/technology/zksnarks/) and +use aggregated, batch-verifiable +[threshold signatures](https://medium.com/snigirev.stepan/bls-signatures-better-than-schnorr-5a7fe30ea716), +using Boneh-Lynn-Shacham signature scheme. + +Main methods and properties are: + +- `getPublicKey(privateKey)` +- `sign(message, privateKey)` +- `verify(signature, message, publicKey)` +- `aggregatePublicKeys(publicKeys)` +- `aggregateSignatures(signatures)` +- `G1` and `G2` curves containing `CURVE` and `ProjectivePoint` +- `Signature` property with `fromHex`, `toHex` methods +- `fields` containing `Fp`, `Fp2`, `Fp6`, `Fp12`, `Fr` + +Right now we only implement BLS12-381 (compatible with ETH and others), +but in theory defining BLS12-377, BLS24 should be straightforward. An example: + +```ts +import { bls12_381 as bls } from '@noble/curves/bls12-381'; +const privateKey = '67d53f170b908cabb9eb326c3c337762d59289a8fec79f7bc9254b584b73265c'; +const message = '64726e3da8'; +const publicKey = bls.getPublicKey(privateKey); +const signature = bls.sign(message, privateKey); +const isValid = bls.verify(signature, message, publicKey); +console.log({ publicKey, signature, isValid }); + +// Sign 1 msg with 3 keys +const privateKeys = [ + '18f020b98eb798752a50ed0563b079c125b0db5dd0b1060d1c1b47d4a193e1e4', + 'ed69a8c50cf8c9836be3b67c7eeff416612d45ba39a5c099d48fa668bf558c9c', + '16ae669f3be7a2121e17d0c68c05a8f3d6bef21ec0f2315f1d7aec12484e4cf5', +]; +const messages = ['d2', '0d98', '05caf3']; +const publicKeys = privateKeys.map(bls.getPublicKey); +const signatures2 = privateKeys.map((p) => bls.sign(message, p)); +const aggPubKey2 = bls.aggregatePublicKeys(publicKeys); +const aggSignature2 = bls.aggregateSignatures(signatures2); +const isValid2 = bls.verify(aggSignature2, message, aggPubKey2); +console.log({ signatures2, aggSignature2, isValid2 }); + +// Sign 3 msgs with 3 keys +const signatures3 = privateKeys.map((p, i) => bls.sign(messages[i], p)); +const aggSignature3 = bls.aggregateSignatures(signatures3); +const isValid3 = bls.verifyBatch(aggSignature3, messages, publicKeys); +console.log({ publicKeys, signatures3, aggSignature3, isValid3 }); + +// bls.pairing(PointG1, PointG2) // pairings +// bls.G1.ProjectivePoint.BASE, bls.G2.ProjectivePoint.BASE +// bls.fields.Fp, bls.fields.Fp2, bls.fields.Fp12, bls.fields.Fr + +// hash-to-curve examples can be seen below +``` + +Full types: + +```ts +getPublicKey: (privateKey: PrivKey) => Uint8Array; +sign: { + (message: Hex, privateKey: PrivKey): Uint8Array; + (message: ProjPointType, privateKey: PrivKey): ProjPointType; +}; +verify: ( + signature: Hex | ProjPointType, + message: Hex | ProjPointType, + publicKey: Hex | ProjPointType +) => boolean; +verifyBatch: ( + signature: Hex | ProjPointType, + messages: (Hex | ProjPointType)[], + publicKeys: (Hex | ProjPointType)[] +) => boolean; +aggregatePublicKeys: { + (publicKeys: Hex[]): Uint8Array; + (publicKeys: ProjPointType[]): ProjPointType; +}; +aggregateSignatures: { + (signatures: Hex[]): Uint8Array; + (signatures: ProjPointType[]): ProjPointType; +}; +millerLoop: (ell: [Fp2, Fp2, Fp2][], g1: [Fp, Fp]) => Fp12; +pairing: (P: ProjPointType, Q: ProjPointType, withFinalExponent?: boolean) => Fp12; +G1: CurvePointsRes & ReturnType>; +G2: CurvePointsRes & ReturnType>; +Signature: SignatureCoder; +params: { + x: bigint; + r: bigint; + G1b: bigint; + G2b: Fp2; +}; +fields: { + Fp: IField; + Fp2: IField; + Fp6: IField; + Fp12: IField; + Fr: IField; +}; +utils: { + randomPrivateKey: () => Uint8Array; + calcPairingPrecomputes: (p: AffinePoint) => [Fp2, Fp2, Fp2][]; +}; +``` + +### abstract/hash-to-curve: Hashing strings to curve points + +The module allows to hash arbitrary strings to elliptic curve points. Implements [hash-to-curve v16](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16). + +Every curve has exported `hashToCurve` and `encodeToCurve` methods. You should always prefer `hashToCurve` for security: + +```ts +import { hashToCurve, encodeToCurve } from '@noble/curves/secp256k1'; +import { randomBytes } from '@noble/hashes/utils'; +hashToCurve('0102abcd'); +console.log(hashToCurve(randomBytes())); +console.log(encodeToCurve(randomBytes())); + +import { bls12_381 } from '@noble/curves/bls12-381'; +bls12_381.G1.hashToCurve(randomBytes(), { DST: 'another' }); +bls12_381.G2.hashToCurve(randomBytes(), { DST: 'custom' }); +``` + +If you need low-level methods from spec: + +`expand_message_xmd` [(spec)](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.4.1) produces a uniformly random byte string using a cryptographic hash function H that outputs b bits. + +Hash must conform to `CHash` interface (see [weierstrass section](#abstractweierstrass-short-weierstrass-curve)). + +```ts +function expand_message_xmd( + msg: Uint8Array, + DST: Uint8Array, + lenInBytes: number, + H: CHash +): Uint8Array; +function expand_message_xof( + msg: Uint8Array, + DST: Uint8Array, + lenInBytes: number, + k: number, + H: CHash +): Uint8Array; +``` + +`hash_to_field(msg, count, options)` +[(spec)](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.3) +hashes arbitrary-length byte strings to a list of one or more elements of a finite field F. + +```ts +/** + * * `DST` is a domain separation tag, defined in section 2.2.5 + * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m + * * `m` is extension degree (1 for prime fields) + * * `k` is the target security target in bits (e.g. 128), from section 5.1 + * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF) + * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props + */ +type UnicodeOrBytes = string | Uint8Array; +type Opts = { + DST: UnicodeOrBytes; + p: bigint; + m: number; + k: number; + expand?: 'xmd' | 'xof'; + hash: CHash; +}; + +/** + * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.3 + * @param msg a byte string containing the message to hash + * @param count the number of elements of F to output + * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above + * @returns [u_0, ..., u_(count - 1)], a list of field elements. + */ +function hash_to_field(msg: Uint8Array, count: number, options: Opts): bigint[][]; +``` + +### abstract/poseidon: Poseidon hash + +Implements [Poseidon](https://www.poseidon-hash.info) ZK-friendly hash. + +There are many poseidon variants with different constants. +We don't provide them: you should construct them manually. +Check out [micro-starknet](https://github.com/paulmillr/micro-starknet) package for a proper example. + +```ts +import { poseidon } from '@noble/curves/abstract/poseidon'; + +type PoseidonOpts = { + Fp: Field; + t: number; + roundsFull: number; + roundsPartial: number; + sboxPower?: number; + reversePartialPowIdx?: boolean; + mds: bigint[][]; + roundConstants: bigint[][]; +}; +const instance = poseidon(opts: PoseidonOpts); +``` + +### abstract/modular: Modular arithmetics utilities + +```ts +import * as mod from '@noble/curves/abstract/modular'; +const fp = mod.Field(2n ** 255n - 19n); // Finite field over 2^255-19 +fp.mul(591n, 932n); // multiplication +fp.pow(481n, 11024858120n); // exponentiation +fp.div(5n, 17n); // division: 5/17 mod 2^255-19 == 5 * invert(17) +fp.sqrt(21n); // square root + +// Generic non-FP utils are also available +mod.mod(21n, 10n); // 21 mod 10 == 1n; fixed version of 21 % 10 +mod.invert(17n, 10n); // invert(17) mod 10; modular multiplicative inverse +mod.invertBatch([1n, 2n, 4n], 21n); // => [1n, 11n, 16n] in one inversion +``` + +#### Creating private keys from hashes + +Suppose you have `sha256(something)` (e.g. from HMAC) and you want to make a private key from it. +Even though p256 or secp256k1 may have 32-byte private keys, +and sha256 output is also 32-byte, you can't just use it and reduce it modulo `CURVE.n`. + +Doing so will make the result key [biased](https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/). + +To avoid the bias, we implement FIPS 186 B.4.1, which allows to take arbitrary +byte array and produce valid scalars / private keys with bias being neglible. + +Use [hash-to-curve](#abstracthash-to-curve-hashing-strings-to-curve-points) if you need +hashing to **public keys**; the function in the module instead operates on **private keys**. + +```ts +import { p256 } from '@noble/curves/p256'; +import { sha256 } from '@noble/hashes/sha256'; +import { hkdf } from '@noble/hashes/hkdf'; +const someKey = new Uint8Array(32).fill(2); // Needs to actually be random, not .fill(2) +const derived = hkdf(sha256, someKey, undefined, 'application', 40); // 40 bytes +const validPrivateKey = mod.hashToPrivateScalar(derived, p256.CURVE.n); +``` + +### abstract/utils: General utilities + +```ts +import * as utils from '@noble/curves/abstract/utils'; + +utils.bytesToHex(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])); +utils.hexToBytes('deadbeef'); +utils.numberToHexUnpadded(123n); +utils.hexToNumber(); + +utils.bytesToNumberBE(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])); +utils.bytesToNumberLE(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])); +utils.numberToBytesBE(123n, 32); +utils.numberToBytesLE(123n, 64); + +utils.concatBytes(Uint8Array.from([0xde, 0xad]), Uint8Array.from([0xbe, 0xef])); +utils.nLength(255n); +utils.equalBytes(Uint8Array.from([0xde]), Uint8Array.from([0xde])); +``` + +## Security + +1. The library has been audited in Feb 2023 by an independent security firm [Trail of Bits](https://www.trailofbits.com): +[PDF](https://github.com/trailofbits/publications/blob/master/reviews/2023-01-ryanshea-noblecurveslibrary-securityreview.pdf). +The audit has been funded by [Ryan Shea](https://www.shea.io). Audit scope was abstract modules `curve`, `hash-to-curve`, `modular`, `poseidon`, `utils`, `weierstrass`, and top-level modules `_shortw_utils` and `secp256k1`. See [changes since audit](https://github.com/paulmillr/noble-curves/compare/0.7.3..main). +2. The library has been fuzzed by [Guido Vranken's cryptofuzz](https://github.com/guidovranken/cryptofuzz). You can run the fuzzer by yourself to check it. +3. [Timing attack](https://en.wikipedia.org/wiki/Timing_attack) considerations: _JIT-compiler_ and _Garbage Collector_ make "constant time" extremely hard to achieve in a scripting language. Which means _any other JS library can't have constant-timeness_. Even statically typed Rust, a language without GC, [makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security) for some cases. If your goal is absolute security, don't use any JS lib — including bindings to native ones. Use low-level libraries & languages. Nonetheless we're targetting algorithmic constant time. + +We consider infrastructure attacks like rogue NPM modules very important; that's why it's crucial to minimize the amount of 3rd-party dependencies & native bindings. If your app uses 500 dependencies, any dep could get hacked and you'll be downloading malware with every `npm install`. Our goal is to minimize this attack vector. As for devDependencies used by the library: + +- `@scure` base, bip32, bip39 (used in tests), micro-bmark (benchmark), micro-should (testing) are developed by us + and follow the same practices such as: minimal library size, auditability, signed releases +- prettier (linter), fast-check (property-based testing), + typescript versions are locked and rarely updated. Every update is checked with `npm-diff`. + The packages are big, which makes it hard to audit their source code thoroughly and fully. +- They are only used if you clone the git repo and want to add some feature to it. End-users won't use them. + +As for key generation, we're deferring to built-in +[crypto.getRandomValues](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) +which is considered cryptographically secure (CSPRNG). + +## Speed + +Benchmark results on Apple M2 with node v20: + +``` +secp256k1 +init x 68 ops/sec @ 14ms/op +getPublicKey x 6,750 ops/sec @ 148μs/op +sign x 5,206 ops/sec @ 192μs/op +verify x 880 ops/sec @ 1ms/op +getSharedSecret x 536 ops/sec @ 1ms/op +recoverPublicKey x 852 ops/sec @ 1ms/op +schnorr.sign x 685 ops/sec @ 1ms/op +schnorr.verify x 908 ops/sec @ 1ms/op + +p256 +init x 38 ops/sec @ 26ms/op +getPublicKey x 6,530 ops/sec @ 153μs/op +sign x 5,074 ops/sec @ 197μs/op +verify x 626 ops/sec @ 1ms/op + +p384 +init x 17 ops/sec @ 57ms/op +getPublicKey x 2,883 ops/sec @ 346μs/op +sign x 2,358 ops/sec @ 424μs/op +verify x 245 ops/sec @ 4ms/op + +p521 +init x 9 ops/sec @ 109ms/op +getPublicKey x 1,516 ops/sec @ 659μs/op +sign x 1,271 ops/sec @ 786μs/op +verify x 123 ops/sec @ 8ms/op + +ed25519 +init x 54 ops/sec @ 18ms/op +getPublicKey x 10,269 ops/sec @ 97μs/op +sign x 5,110 ops/sec @ 195μs/op +verify x 1,049 ops/sec @ 952μs/op + +ed448 +init x 19 ops/sec @ 51ms/op +getPublicKey x 3,775 ops/sec @ 264μs/op +sign x 1,771 ops/sec @ 564μs/op +verify x 351 ops/sec @ 2ms/op + +ecdh +├─x25519 x 1,466 ops/sec @ 682μs/op +├─secp256k1 x 539 ops/sec @ 1ms/op +├─p256 x 511 ops/sec @ 1ms/op +├─p384 x 199 ops/sec @ 5ms/op +├─p521 x 103 ops/sec @ 9ms/op +└─x448 x 548 ops/sec @ 1ms/op + +bls12-381 +init x 36 ops/sec @ 27ms/op +getPublicKey 1-bit x 973 ops/sec @ 1ms/op +getPublicKey x 970 ops/sec @ 1ms/op +sign x 55 ops/sec @ 17ms/op +verify x 39 ops/sec @ 25ms/op +pairing x 106 ops/sec @ 9ms/op +aggregatePublicKeys/8 x 129 ops/sec @ 7ms/op +aggregatePublicKeys/32 x 34 ops/sec @ 28ms/op +aggregatePublicKeys/128 x 8 ops/sec @ 112ms/op +aggregatePublicKeys/512 x 2 ops/sec @ 446ms/op +aggregatePublicKeys/2048 x 0 ops/sec @ 1778ms/op +aggregateSignatures/8 x 50 ops/sec @ 19ms/op +aggregateSignatures/32 x 13 ops/sec @ 74ms/op +aggregateSignatures/128 x 3 ops/sec @ 296ms/op +aggregateSignatures/512 x 0 ops/sec @ 1180ms/op +aggregateSignatures/2048 x 0 ops/sec @ 4715ms/op + +hash-to-curve +hash_to_field x 91,600 ops/sec @ 10μs/op +secp256k1 x 2,373 ops/sec @ 421μs/op +p256 x 4,310 ops/sec @ 231μs/op +p384 x 1,664 ops/sec @ 600μs/op +p521 x 807 ops/sec @ 1ms/op +ed25519 x 3,088 ops/sec @ 323μs/op +ed448 x 1,247 ops/sec @ 801μs/op +``` + +## Contributing & testing + +1. Clone the repository +2. `npm install` to install build dependencies like TypeScript +3. `npm run build` to compile TypeScript code +4. `npm run test` will execute all main tests + +## Upgrading + +Previously, the library was split into single-feature packages +noble-secp256k1, noble-ed25519 and noble-bls12-381. + +Curves continue their original work. The single-feature packages changed their +direction towards providing minimal 4kb implementations of cryptography, +which means they have less features. + +Upgrading from @noble/secp256k1 2.0 or @noble/ed25519 2.0: no changes, libraries are compatible. + +Upgrading from [@noble/secp256k1](https://github.com/paulmillr/noble-secp256k1) 1.7: + +- `getPublicKey` + - now produce 33-byte compressed signatures by default + - to use old behavior, which produced 65-byte uncompressed keys, set + argument `isCompressed` to `false`: `getPublicKey(priv, false)` +- `sign` + - is now sync; use `signAsync` for async version + - now returns `Signature` instance with `{ r, s, recovery }` properties + - `canonical` option was renamed to `lowS` + - `recovered` option has been removed because recovery bit is always returned now + - `der` option has been removed. There are 2 options: + 1. Use compact encoding: `fromCompact`, `toCompactRawBytes`, `toCompactHex`. + Compact encoding is simply a concatenation of 32-byte r and 32-byte s. + 2. If you must use DER encoding, switch to noble-curves (see above). +- `verify` + - `strict` option was renamed to `lowS` +- `getSharedSecret` + - now produce 33-byte compressed signatures by default + - to use old behavior, which produced 65-byte uncompressed keys, set + argument `isCompressed` to `false`: `getSharedSecret(a, b, false)` +- `recoverPublicKey(msg, sig, rec)` was changed to `sig.recoverPublicKey(msg)` +- `number` type for private keys have been removed: use `bigint` instead +- `Point` (2d xy) has been changed to `ProjectivePoint` (3d xyz) +- `utils` were split into `utils` (same api as in noble-curves) and + `etc` (`hmacSha256Sync` and others) + +Upgrading from [@noble/ed25519](https://github.com/paulmillr/noble-ed25519) 1.7: + +- Methods are now sync by default +- `bigint` is no longer allowed in `getPublicKey`, `sign`, `verify`. Reason: ed25519 is LE, can lead to bugs +- `Point` (2d xy) has been changed to `ExtendedPoint` (xyzt) +- `Signature` was removed: just use raw bytes or hex now +- `utils` were split into `utils` (same api as in noble-curves) and + `etc` (`sha512Sync` and others) +- `getSharedSecret` was moved to `x25519` module +- `toX25519` has been moved to `edwardsToMontgomeryPub` and `edwardsToMontgomeryPriv` methods + +Upgrading from [@noble/bls12-381](https://github.com/paulmillr/noble-bls12-381): + +- Methods and classes were renamed: + - PointG1 -> G1.Point, PointG2 -> G2.Point + - PointG2.fromSignature -> Signature.decode, PointG2.toSignature -> Signature.encode +- Fp2 ORDER was corrected + +## Resources + +Useful documentation and articles about the library or its primitives: + +- [Learning fast elliptic-curve cryptography](https://paulmillr.com/posts/noble-secp256k1-fast-ecc/) +- [Taming the many EdDSAs](https://csrc.nist.gov/csrc/media/Presentations/2023/crclub-2023-03-08/images-media/20230308-crypto-club-slides--taming-the-many-EdDSAs.pdf) + that describes concepts of Strong UnForgeability under Chosen Message Attacks and Strongly Binding Signatures +- Pairings and BLS + - [BLS signatures for busy people](https://gist.github.com/paulmillr/18b802ad219b1aee34d773d08ec26ca2) + - [BLS12-381 for the rest of us](https://hackmd.io/@benjaminion/bls12-381) + - [Key concepts of pairings](https://medium.com/@alonmuroch_65570/bls-signatures-part-2-key-concepts-of-pairings-27a8a9533d0c) + - Pairing over bls12-381: + [part 1](https://research.nccgroup.com/2020/07/06/pairing-over-bls12-381-part-1-fields/), + [part 2](https://research.nccgroup.com/2020/07/13/pairing-over-bls12-381-part-2-curves/), + [part 3](https://research.nccgroup.com/2020/08/13/pairing-over-bls12-381-part-3-pairing/) + - [Estimating the bit security of pairing-friendly curves](https://research.nccgroup.com/2022/02/03/estimating-the-bit-security-of-pairing-friendly-curves/) + +Online demos: + +- [Elliptic Curve Calculator](https://paulmillr.com/noble): add / multiply points, sign messages +- [BLS threshold signatures](https://genthresh.com) + +Projects using noble-curves: + +- [scure-bip32](https://github.com/paulmillr/scure-bip32) and separate [bip32](https://github.com/bitcoinjs/bip32) HDkey libraries +- Ethereum libraries: + - [ethereum-cryptography](https://github.com/ethereum/js-ethereum-cryptography) + - [@ethereumjs](https://github.com/ethereumjs/ethereumjs-monorepo) + - [micro-eth-signer](https://github.com/paulmillr/micro-eth-signer) + - [ethers](https://github.com/ethers-io/ethers.js) (old noble-secp256k1 for now) + - [viem.sh](https://viem.sh) + - [metamask's eth-sig-util](https://github.com/MetaMask/eth-sig-util) + - [gridplus lattice sdk](https://github.com/GridPlus/lattice-eth2-utils) +- Bitcoin libraries: [scure-btc-signer](https://github.com/paulmillr/scure-btc-signer) +- Solana libraries: [micro-sol-signer](https://github.com/paulmillr/micro-sol-signer), [solana-web3.js](https://github.com/solana-labs/solana-web3.js) +- [polkadot.js](https://github.com/polkadot-js/common), [micro-starknet](https://github.com/paulmillr/micro-starknet) +- [protonmail](https://github.com/ProtonMail/WebClients) (old noble-ed25519 for now) +- [did-jwt](https://github.com/decentralized-identity/did-jwt), [hpke-js](https://github.com/dajiaji/hpke-js), [nostr-tools](https://github.com/nbd-wtf/nostr-tools) +- [ed25519-keygen](https://github.com/paulmillr/ed25519-keygen) SSH, PGP, TOR key generation +- [secp256k1 compatibility layer](https://github.com/ethereum/js-ethereum-cryptography/blob/2.0.0/src/secp256k1-compat.ts) +for users who want to switch from secp256k1-node or tiny-secp256k1. Allows to see which methods map to corresponding noble code. +- [BLS BBS signatures](https://github.com/Wind4Greg/BBS-Draft-Checks) following [draft-irtf-cfrg-bbs-signatures-latest](https://identity.foundation/bbs-signature/draft-irtf-cfrg-bbs-signatures.html) +- [KZG trusted setup ceremony](https://github.com/dsrvlabs/czg-keremony) + +## License + +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller [(https://paulmillr.com)](https://paulmillr.com) + +See LICENSE file. diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/_shortw_utils.d.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/_shortw_utils.d.ts new file mode 100644 index 0000000..3eb43a8 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/_shortw_utils.d.ts @@ -0,0 +1,62 @@ +import { randomBytes } from '@noble/hashes/utils'; +import { CurveType } from './abstract/weierstrass.js'; +import { CHash } from './abstract/utils.js'; +export declare function getHash(hash: CHash): { + hash: CHash; + hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => Uint8Array; + randomBytes: typeof randomBytes; +}; +type CurveDef = Readonly>; +export declare function createCurve(curveDef: CurveDef, defHash: CHash): Readonly<{ + create: (hash: CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType | undefined) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export {}; +//# sourceMappingURL=_shortw_utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/_shortw_utils.d.ts.map b/node_modules/@scure/bip32/node_modules/@noble/curves/_shortw_utils.d.ts.map new file mode 100644 index 0000000..974f8da --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/_shortw_utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"_shortw_utils.d.ts","sourceRoot":"","sources":["src/_shortw_utils.ts"],"names":[],"mappings":"AAEA,OAAO,EAAe,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAC/D,OAAO,EAAe,SAAS,EAAE,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAG5C,wBAAgB,OAAO,CAAC,IAAI,EAAE,KAAK;;gBAGnB,UAAU,WAAW,UAAU,EAAE;;EAGhD;AAED,KAAK,QAAQ,GAAG,QAAQ,CAAC,IAAI,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,aAAa,CAAC,CAAC,CAAC;AAC3E,wBAAgB,WAAW,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK;mBACtC,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAE5B"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/_shortw_utils.js b/node_modules/@scure/bip32/node_modules/@noble/curves/_shortw_utils.js new file mode 100644 index 0000000..555de44 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/_shortw_utils.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createCurve = exports.getHash = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const hmac_1 = require("@noble/hashes/hmac"); +const utils_1 = require("@noble/hashes/utils"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +// connects noble-curves to noble-hashes +function getHash(hash) { + return { + hash, + hmac: (key, ...msgs) => (0, hmac_1.hmac)(hash, key, (0, utils_1.concatBytes)(...msgs)), + randomBytes: utils_1.randomBytes, + }; +} +exports.getHash = getHash; +function createCurve(curveDef, defHash) { + const create = (hash) => (0, weierstrass_js_1.weierstrass)({ ...curveDef, ...getHash(hash) }); + return Object.freeze({ ...create(defHash), create }); +} +exports.createCurve = createCurve; +//# sourceMappingURL=_shortw_utils.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/_shortw_utils.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/_shortw_utils.js.map new file mode 100644 index 0000000..318dfda --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/_shortw_utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_shortw_utils.js","sourceRoot":"","sources":["src/_shortw_utils.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,6CAA0C;AAC1C,+CAA+D;AAC/D,8DAAmE;AAGnE,wCAAwC;AACxC,SAAgB,OAAO,CAAC,IAAW;IACjC,OAAO;QACL,IAAI;QACJ,IAAI,EAAE,CAAC,GAAe,EAAE,GAAG,IAAkB,EAAE,EAAE,CAAC,IAAA,WAAI,EAAC,IAAI,EAAE,GAAG,EAAE,IAAA,mBAAW,EAAC,GAAG,IAAI,CAAC,CAAC;QACvF,WAAW,EAAX,mBAAW;KACZ,CAAC;AACJ,CAAC;AAND,0BAMC;AAGD,SAAgB,WAAW,CAAC,QAAkB,EAAE,OAAc;IAC5D,MAAM,MAAM,GAAG,CAAC,IAAW,EAAE,EAAE,CAAC,IAAA,4BAAW,EAAC,EAAE,GAAG,QAAQ,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAC/E,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,MAAM,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;AACvD,CAAC;AAHD,kCAGC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/bls.d.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/bls.d.ts new file mode 100644 index 0000000..f6f14ac --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/bls.d.ts @@ -0,0 +1,103 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +/** + * BLS (Barreto-Lynn-Scott) family of pairing-friendly curves. + * Implements BLS (Boneh-Lynn-Shacham) signatures. + * Consists of two curves: G1 and G2: + * - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4. + * - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1 + * - Gt, created by bilinear (ate) pairing e(G1, G2), consists of p-th roots of unity in + * Fq^k where k is embedding degree. Only degree 12 is currently supported, 24 is not. + * Pairing is used to aggregate and verify signatures. + * We are using Fp for private keys (shorter) and Fp₂ for signatures (longer). + * Some projects may prefer to swap this relation, it is not supported for now. + */ +import { AffinePoint } from './curve.js'; +import { IField } from './modular.js'; +import { Hex, PrivKey, CHash } from './utils.js'; +import * as htf from './hash-to-curve.js'; +import { CurvePointsType, ProjPointType as ProjPointType, CurvePointsRes } from './weierstrass.js'; +type Fp = bigint; +export type SignatureCoder = { + fromHex(hex: Hex): ProjPointType; + toRawBytes(point: ProjPointType): Uint8Array; + toHex(point: ProjPointType): string; +}; +export type CurveType = { + G1: Omit, 'n'> & { + mapToCurve: htf.MapToCurve; + htfDefaults: htf.Opts; + }; + G2: Omit, 'n'> & { + Signature: SignatureCoder; + mapToCurve: htf.MapToCurve; + htfDefaults: htf.Opts; + }; + fields: { + Fp: IField; + Fr: IField; + Fp2: IField & { + reim: (num: Fp2) => { + re: bigint; + im: bigint; + }; + multiplyByB: (num: Fp2) => Fp2; + frobeniusMap(num: Fp2, power: number): Fp2; + }; + Fp6: IField; + Fp12: IField & { + frobeniusMap(num: Fp12, power: number): Fp12; + multiplyBy014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12; + conjugate(num: Fp12): Fp12; + finalExponentiate(num: Fp12): Fp12; + }; + }; + params: { + x: bigint; + r: bigint; + }; + htfDefaults: htf.Opts; + hash: CHash; + randomBytes: (bytesLength?: number) => Uint8Array; +}; +export type CurveFn = { + getPublicKey: (privateKey: PrivKey) => Uint8Array; + sign: { + (message: Hex, privateKey: PrivKey): Uint8Array; + (message: ProjPointType, privateKey: PrivKey): ProjPointType; + }; + verify: (signature: Hex | ProjPointType, message: Hex | ProjPointType, publicKey: Hex | ProjPointType) => boolean; + verifyBatch: (signature: Hex | ProjPointType, messages: (Hex | ProjPointType)[], publicKeys: (Hex | ProjPointType)[]) => boolean; + aggregatePublicKeys: { + (publicKeys: Hex[]): Uint8Array; + (publicKeys: ProjPointType[]): ProjPointType; + }; + aggregateSignatures: { + (signatures: Hex[]): Uint8Array; + (signatures: ProjPointType[]): ProjPointType; + }; + millerLoop: (ell: [Fp2, Fp2, Fp2][], g1: [Fp, Fp]) => Fp12; + pairing: (P: ProjPointType, Q: ProjPointType, withFinalExponent?: boolean) => Fp12; + G1: CurvePointsRes & ReturnType>; + G2: CurvePointsRes & ReturnType>; + Signature: SignatureCoder; + params: { + x: bigint; + r: bigint; + G1b: bigint; + G2b: Fp2; + }; + fields: { + Fp: IField; + Fp2: IField; + Fp6: IField; + Fp12: IField; + Fr: IField; + }; + utils: { + randomPrivateKey: () => Uint8Array; + calcPairingPrecomputes: (p: AffinePoint) => [Fp2, Fp2, Fp2][]; + }; +}; +export declare function bls(CURVE: CurveType): CurveFn; +export {}; +//# sourceMappingURL=bls.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/bls.d.ts.map b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/bls.d.ts.map new file mode 100644 index 0000000..75b6d26 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/bls.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bls.d.ts","sourceRoot":"","sources":["../src/abstract/bls.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EAAE,MAAM,EAAuB,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,KAAK,EAA+B,MAAM,YAAY,CAAC;AAC9E,OAAO,KAAK,GAAG,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EACL,eAAe,EACf,aAAa,IAAI,aAAa,EAC9B,cAAc,EAEf,MAAM,kBAAkB,CAAC;AAE1B,KAAK,EAAE,GAAG,MAAM,CAAC;AAKjB,MAAM,MAAM,cAAc,CAAC,GAAG,IAAI;IAChC,OAAO,CAAC,GAAG,EAAE,GAAG,GAAG,aAAa,CAAC,GAAG,CAAC,CAAC;IACtC,UAAU,CAAC,KAAK,EAAE,aAAa,CAAC,GAAG,CAAC,GAAG,UAAU,CAAC;IAClD,KAAK,CAAC,KAAK,EAAE,aAAa,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC;CAC1C,CAAC;AAEF,MAAM,MAAM,SAAS,CAAC,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,IAAI;IAC1C,EAAE,EAAE,IAAI,CAAC,eAAe,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,GAAG;QACnC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;QAC/B,WAAW,EAAE,GAAG,CAAC,IAAI,CAAC;KACvB,CAAC;IACF,EAA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,EAAE,GAAG,EAAE,IAAI,EAChC,KAAK,EAAE,SAAS,CAAC,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,GACnC,OAAO,CAAC,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAqR7B"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/bls.js b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/bls.js new file mode 100644 index 0000000..1c0e956 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/bls.js @@ -0,0 +1,239 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bls = void 0; +const modular_js_1 = require("./modular.js"); +const utils_js_1 = require("./utils.js"); +const htf = require("./hash-to-curve.js"); +const weierstrass_js_1 = require("./weierstrass.js"); +// prettier-ignore +const _2n = BigInt(2), _3n = BigInt(3); +function bls(CURVE) { + // Fields are specific for curve, so for now we'll need to pass them with opts + const { Fp, Fr, Fp2, Fp6, Fp12 } = CURVE.fields; + const BLS_X_LEN = (0, utils_js_1.bitLen)(CURVE.params.x); + const groupLen = 32; // TODO: calculate; hardcoded for now + // Pre-compute coefficients for sparse multiplication + // Point addition and point double calculations is reused for coefficients + function calcPairingPrecomputes(p) { + const { x, y } = p; + // prettier-ignore + const Qx = x, Qy = y, Qz = Fp2.ONE; + // prettier-ignore + let Rx = Qx, Ry = Qy, Rz = Qz; + let ell_coeff = []; + for (let i = BLS_X_LEN - 2; i >= 0; i--) { + // Double + let t0 = Fp2.sqr(Ry); // Ry² + let t1 = Fp2.sqr(Rz); // Rz² + let t2 = Fp2.multiplyByB(Fp2.mul(t1, _3n)); // 3 * T1 * B + let t3 = Fp2.mul(t2, _3n); // 3 * T2 + let t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0); // (Ry + Rz)² - T1 - T0 + ell_coeff.push([ + Fp2.sub(t2, t0), + Fp2.mul(Fp2.sqr(Rx), _3n), + Fp2.neg(t4), // -T4 + ]); + Rx = Fp2.div(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), _2n); // ((T0 - T3) * Rx * Ry) / 2 + Ry = Fp2.sub(Fp2.sqr(Fp2.div(Fp2.add(t0, t3), _2n)), Fp2.mul(Fp2.sqr(t2), _3n)); // ((T0 + T3) / 2)² - 3 * T2² + Rz = Fp2.mul(t0, t4); // T0 * T4 + if ((0, utils_js_1.bitGet)(CURVE.params.x, i)) { + // Addition + let t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); // Ry - Qy * Rz + let t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz)); // Rx - Qx * Rz + ell_coeff.push([ + Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy)), + Fp2.neg(t0), + t1, // T1 + ]); + let t2 = Fp2.sqr(t1); // T1² + let t3 = Fp2.mul(t2, t1); // T2 * T1 + let t4 = Fp2.mul(t2, Rx); // T2 * Rx + let t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n)), Fp2.mul(Fp2.sqr(t0), Rz)); // T3 - 2 * T4 + T0² * Rz + Rx = Fp2.mul(t1, t5); // T1 * T5 + Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry)); // (T4 - T5) * T0 - T3 * Ry + Rz = Fp2.mul(Rz, t3); // Rz * T3 + } + } + return ell_coeff; + } + function millerLoop(ell, g1) { + const { x } = CURVE.params; + const Px = g1[0]; + const Py = g1[1]; + let f12 = Fp12.ONE; + for (let j = 0, i = BLS_X_LEN - 2; i >= 0; i--, j++) { + const E = ell[j]; + f12 = Fp12.multiplyBy014(f12, E[0], Fp2.mul(E[1], Px), Fp2.mul(E[2], Py)); + if ((0, utils_js_1.bitGet)(x, i)) { + j += 1; + const F = ell[j]; + f12 = Fp12.multiplyBy014(f12, F[0], Fp2.mul(F[1], Px), Fp2.mul(F[2], Py)); + } + if (i !== 0) + f12 = Fp12.sqr(f12); + } + return Fp12.conjugate(f12); + } + const utils = { + randomPrivateKey: () => { + return Fr.toBytes((0, modular_js_1.hashToPrivateScalar)(CURVE.randomBytes(groupLen + 8), CURVE.params.r)); + }, + calcPairingPrecomputes, + }; + // Point on G1 curve: (x, y) + const G1_ = (0, weierstrass_js_1.weierstrassPoints)({ n: Fr.ORDER, ...CURVE.G1 }); + const G1 = Object.assign(G1_, htf.createHasher(G1_.ProjectivePoint, CURVE.G1.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G1.htfDefaults, + })); + function pairingPrecomputes(point) { + const p = point; + if (p._PPRECOMPUTES) + return p._PPRECOMPUTES; + p._PPRECOMPUTES = calcPairingPrecomputes(point.toAffine()); + return p._PPRECOMPUTES; + } + // TODO: export + // function clearPairingPrecomputes(point: G2) { + // const p = point as G2 & withPairingPrecomputes; + // p._PPRECOMPUTES = undefined; + // } + // Point on G2 curve (complex numbers): (x₁, x₂+i), (y₁, y₂+i) + const G2_ = (0, weierstrass_js_1.weierstrassPoints)({ n: Fr.ORDER, ...CURVE.G2 }); + const G2 = Object.assign(G2_, htf.createHasher(G2_.ProjectivePoint, CURVE.G2.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G2.htfDefaults, + })); + const { Signature } = CURVE.G2; + // Calculates bilinear pairing + function pairing(Q, P, withFinalExponent = true) { + if (Q.equals(G1.ProjectivePoint.ZERO) || P.equals(G2.ProjectivePoint.ZERO)) + throw new Error('pairing is not available for ZERO point'); + Q.assertValidity(); + P.assertValidity(); + // Performance: 9ms for millerLoop and ~14ms for exp. + const Qa = Q.toAffine(); + const looped = millerLoop(pairingPrecomputes(P), [Qa.x, Qa.y]); + return withFinalExponent ? Fp12.finalExponentiate(looped) : looped; + } + function normP1(point) { + return point instanceof G1.ProjectivePoint ? point : G1.ProjectivePoint.fromHex(point); + } + function normP2(point) { + return point instanceof G2.ProjectivePoint ? point : Signature.fromHex(point); + } + function normP2Hash(point, htfOpts) { + return point instanceof G2.ProjectivePoint + ? point + : G2.hashToCurve((0, utils_js_1.ensureBytes)('point', point), htfOpts); + } + // Multiplies generator by private key. + // P = pk x G + function getPublicKey(privateKey) { + return G1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true); + } + function sign(message, privateKey, htfOpts) { + const msgPoint = normP2Hash(message, htfOpts); + msgPoint.assertValidity(); + const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey)); + if (message instanceof G2.ProjectivePoint) + return sigPoint; + return Signature.toRawBytes(sigPoint); + } + // Checks if pairing of public key & hash is equal to pairing of generator & signature. + // e(P, H(m)) == e(G, S) + function verify(signature, message, publicKey, htfOpts) { + const P = normP1(publicKey); + const Hm = normP2Hash(message, htfOpts); + const G = G1.ProjectivePoint.BASE; + const S = normP2(signature); + // Instead of doing 2 exponentiations, we use property of billinear maps + // and do one exp after multiplying 2 points. + const ePHm = pairing(P.negate(), Hm, false); + const eGS = pairing(G, S, false); + const exp = Fp12.finalExponentiate(Fp12.mul(eGS, ePHm)); + return Fp12.eql(exp, Fp12.ONE); + } + function aggregatePublicKeys(publicKeys) { + if (!publicKeys.length) + throw new Error('Expected non-empty array'); + const agg = publicKeys.map(normP1).reduce((sum, p) => sum.add(p), G1.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (publicKeys[0] instanceof G1.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + // toRawBytes ensures point validity + return aggAffine.toRawBytes(true); + } + function aggregateSignatures(signatures) { + if (!signatures.length) + throw new Error('Expected non-empty array'); + const agg = signatures.map(normP2).reduce((sum, s) => sum.add(s), G2.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (signatures[0] instanceof G2.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + return Signature.toRawBytes(aggAffine); + } + // https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407 + // e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si)) + function verifyBatch(signature, messages, publicKeys, htfOpts) { + // @ts-ignore + // console.log('verifyBatch', bytesToHex(signature as any), messages, publicKeys.map(bytesToHex)); + if (!messages.length) + throw new Error('Expected non-empty messages array'); + if (publicKeys.length !== messages.length) + throw new Error('Pubkey count should equal msg count'); + const sig = normP2(signature); + const nMessages = messages.map((i) => normP2Hash(i, htfOpts)); + const nPublicKeys = publicKeys.map(normP1); + try { + const paired = []; + for (const message of new Set(nMessages)) { + const groupPublicKey = nMessages.reduce((groupPublicKey, subMessage, i) => subMessage === message ? groupPublicKey.add(nPublicKeys[i]) : groupPublicKey, G1.ProjectivePoint.ZERO); + // const msg = message instanceof PointG2 ? message : await PointG2.hashToCurve(message); + // Possible to batch pairing for same msg with different groupPublicKey here + paired.push(pairing(groupPublicKey, message, false)); + } + paired.push(pairing(G1.ProjectivePoint.BASE.negate(), sig, false)); + const product = paired.reduce((a, b) => Fp12.mul(a, b), Fp12.ONE); + const exp = Fp12.finalExponentiate(product); + return Fp12.eql(exp, Fp12.ONE); + } + catch { + return false; + } + } + G1.ProjectivePoint.BASE._setWindowSize(4); + return { + getPublicKey, + sign, + verify, + verifyBatch, + aggregatePublicKeys, + aggregateSignatures, + millerLoop, + pairing, + G1, + G2, + Signature, + fields: { + Fr, + Fp, + Fp2, + Fp6, + Fp12, + }, + params: { + x: CURVE.params.x, + r: CURVE.params.r, + G1b: CURVE.G1.b, + G2b: CURVE.G2.b, + }, + utils, + }; +} +exports.bls = bls; +//# sourceMappingURL=bls.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/bls.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/bls.js.map new file mode 100644 index 0000000..1ce9b31 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/bls.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bls.js","sourceRoot":"","sources":["../src/abstract/bls.ts"],"names":[],"mappings":";;;AAcA,6CAA2D;AAC3D,yCAA8E;AAC9E,0C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CAAC,CAAC;SAChB;QACD,KAAK;KACN,CAAC;AACJ,CAAC;AAvRD,kBAuRC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/curve.d.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/curve.d.ts new file mode 100644 index 0000000..9caf29c --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/curve.d.ts @@ -0,0 +1,70 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { IField } from './modular.js'; +export type AffinePoint = { + x: T; + y: T; +} & { + z?: never; + t?: never; +}; +export interface Group> { + double(): T; + negate(): T; + add(other: T): T; + subtract(other: T): T; + equals(other: T): boolean; + multiply(scalar: bigint): T; +} +export type GroupConstructor = { + BASE: T; + ZERO: T; +}; +export type Mapper = (i: T[]) => T[]; +export declare function wNAF>(c: GroupConstructor, bits: number): { + constTimeNegate: (condition: boolean, item: T) => T; + unsafeLadder(elm: T, n: bigint): T; + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm: T, W: number): Group[]; + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W: number, precomputes: T[], n: bigint): { + p: T; + f: T; + }; + wNAFCached(P: T, precomputesMap: Map, n: bigint, transform: Mapper): { + p: T; + f: T; + }; +}; +export type BasicCurve = { + Fp: IField; + n: bigint; + nBitLength?: number; + nByteLength?: number; + h: bigint; + hEff?: bigint; + Gx: T; + Gy: T; + allowInfinityPoint?: boolean; +}; +export declare function validateBasic(curve: BasicCurve & T): Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; +} & BasicCurve & T & { + p: bigint; +}>; +//# sourceMappingURL=curve.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/curve.d.ts.map b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/curve.d.ts.map new file mode 100644 index 0000000..fc52e87 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/curve.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"curve.d.ts","sourceRoot":"","sources":["../src/abstract/curve.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,OAAO,EAAE,MAAM,EAA0B,MAAM,cAAc,CAAC;AAK9D,MAAM,MAAM,WAAW,CAAC,CAAC,IAAI;IAC3B,CAAC,EAAE,CAAC,CAAC;IACL,CAAC,EAAE,CAAC,CAAC;CACN,GAAG;IAAE,CAAC,CAAC,EAAE,KAAK,CAAC;IAAC,CAAC,CAAC,EAAE,KAAK,CAAA;CAAE,CAAC;AAE7B,MAAM,WAAW,KAAK,CAAC,CAAC,SAAS,KAAK,CAAC,CAAC,CAAC;IACvC,MAAM,IAAI,CAAC,CAAC;IACZ,MAAM,IAAI,CAAC,CAAC;IACZ,GAAG,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC;IACjB,QAAQ,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC;IACtB,MAAM,CAAC,KAAK,EAAE,CAAC,GAAG,OAAO,CAAC;IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,CAAC,CAAC;CAC7B;AAED,MAAM,MAAM,gBAAgB,CAAC,CAAC,IAAI;IAChC,IAAI,EAAE,CAAC,CAAC;IACR,IAAI,EAAE,CAAC,CAAC;CACT,CAAC;AACF,MAAM,MAAM,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,CAAC,EAAE,CAAC;AAaxC,wBAAgB,IAAI,CAAC,CAAC,SAAS,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,gBAAgB,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM;iCACvC,OAAO,QAAQ,CAAC,KAAG,CAAC;sBAYpC,CAAC,KAAK,MAAM;IAW9B;;;;;;;;;OASG;0BACmB,CAAC,KAAK,MAAM,GAAG,MAAM,CAAC,CAAC,EAAE;IAkB/C;;;;;;OAMG;YACK,MAAM,eAAe,CAAC,EAAE,KAAK,MAAM;WAAQ,CAAC;WAAK,CAAC;;kBAsD5C,CAAC,kBAAkB,IAAI,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,MAAM,aAAa,OAAO,CAAC,CAAC,GAAG;QAAE,CAAC,EAAE,CAAC,CAAC;QAAC,CAAC,EAAE,CAAC,CAAA;KAAE;EAcjG;AAID,MAAM,MAAM,UAAU,CAAC,CAAC,IAAI;IAC1B,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC;IACd,CAAC,EAAE,MAAM,CAAC;IACV,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,CAAC,EAAE,MAAM,CAAC;IACV,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,EAAE,EAAE,CAAC,CAAC;IACN,EAAE,EAAE,CAAC,CAAC;IACN,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B,CAAC;AAEF,wBAAgB,aAAa,CAAC,EAAE,EAAE,CAAC,EAAE,KAAK,EAAE,UAAU,CAAC,EAAE,CAAC,GAAG,CAAC;;;;;GAqB7D"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/curve.js b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/curve.js new file mode 100644 index 0000000..5a005bc --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/curve.js @@ -0,0 +1,161 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateBasic = exports.wNAF = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Abelian group utilities +const modular_js_1 = require("./modular.js"); +const utils_js_1 = require("./utils.js"); +const _0n = BigInt(0); +const _1n = BigInt(1); +// Elliptic curve multiplication of Point by scalar. Fragile. +// Scalars should always be less than curve order: this should be checked inside of a curve itself. +// Creates precomputation tables for fast multiplication: +// - private scalar is split by fixed size windows of W bits +// - every window point is collected from window's table & added to accumulator +// - since windows are different, same point inside tables won't be accessed more than once per calc +// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar) +// - +1 window is neccessary for wNAF +// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication +// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow +// windows to be in different memory locations +function wNAF(c, bits) { + const constTimeNegate = (condition, item) => { + const neg = item.negate(); + return condition ? neg : item; + }; + const opts = (W) => { + const windows = Math.ceil(bits / W) + 1; // +1, because + const windowSize = 2 ** (W - 1); // -1 because we skip zero + return { windows, windowSize }; + }; + return { + constTimeNegate, + // non-const time multiplication ladder + unsafeLadder(elm, n) { + let p = c.ZERO; + let d = elm; + while (n > _0n) { + if (n & _1n) + p = p.add(d); + d = d.double(); + n >>= _1n; + } + return p; + }, + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm, W) { + const { windows, windowSize } = opts(W); + const points = []; + let p = elm; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + // =1, because we skip zero + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + }, + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W, precomputes, n) { + // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise + // But need to carefully remove other checks before wNAF. ORDER == bits here + const { windows, windowSize } = opts(W); + let p = c.ZERO; + let f = c.BASE; + const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc. + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + // Extract W bits. + let wbits = Number(n & mask); + // Shift number by W bits. + n >>= shiftBy; + // If the bits are bigger than max size, we'll split those. + // +224 => 256 - 32 + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n; + } + // This code was first written with assumption that 'f' and 'p' will never be infinity point: + // since each addition is multiplied by 2 ** W, it cannot cancel each other. However, + // there is negate now: it is possible that negated element from low value + // would be the same as high element, which will create carry into next window. + // It's not obvious how this can fail, but still worth investigating later. + // Check if we're onto Zero point. + // Add random point inside current window to f. + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + // The most important part for const-time getPublicKey + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } + else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ() + // Even if the variable is still unused, there are some checks which will + // throw an exception, so compiler needs to prove they won't happen, which is hard. + // At this point there is a way to F be infinity-point even if p is not, + // which makes it less const-time: around 1 bigint multiply. + return { p, f }; + }, + wNAFCached(P, precomputesMap, n, transform) { + // @ts-ignore + const W = P._WINDOW_SIZE || 1; + // Calculate precomputes on a first run, reuse them after + let comp = precomputesMap.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W); + if (W !== 1) { + precomputesMap.set(P, transform(comp)); + } + } + return this.wNAF(W, comp, n); + }, + }; +} +exports.wNAF = wNAF; +function validateBasic(curve) { + (0, modular_js_1.validateField)(curve.Fp); + (0, utils_js_1.validateObject)(curve, { + n: 'bigint', + h: 'bigint', + Gx: 'field', + Gy: 'field', + }, { + nBitLength: 'isSafeInteger', + nByteLength: 'isSafeInteger', + }); + // Set defaults + return Object.freeze({ + ...(0, modular_js_1.nLength)(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER }, + }); +} +exports.validateBasic = validateBasic; +//# sourceMappingURL=curve.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/curve.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/curve.js.map new file mode 100644 index 0000000..dd6ca4b --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/curve.js.map @@ -0,0 +1 @@ +{"version":3,"file":"curve.js","sourceRoot":"","sources":["../src/abstract/curve.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,0BAA0B;AAC1B,6CAA8D;AAC9D,yCAA4C;AAC5C,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAsBtB,6DAA6D;AAC7D,mGAAmG;AACnG,yDAAyD;AACzD,4DAA4D;AAC5D,+EAA+E;AAC/E,oGAAoG;AACpG,oGAAoG;AACpG,qCAAqC;AACrC,kGAAkG;AAClG,gGAAgG;AAChG,8CAA8C;AAC9C,SAAgB,IAAI,CAAqB,CAAsB,EAAE,IAAY;IAC3E,MAAM,eAAe,GAAG,CAAC,SAAkB,EAAE,IAAO,EAAK,EAAE;QACzD,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;QAC1B,OAAO,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;IAChC,CAAC,CAAC;IACF,MAAM,IA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AA,0BAAa,EAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACxB,IAAA,yBAAc,EACZ,KAAK,EACL;QACE,CAAC,EAAE,QAAQ;QACX,CAAC,EAAE,QAAQ;QACX,EAAE,EAAE,OAAO;QACX,EAAE,EAAE,OAAO;KACZ,EACD;QACE,UAAU,EAAE,eAAe;QAC3B,WAAW,EAAE,eAAe;KAC7B,CACF,CAAC;IACF,eAAe;IACf,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,GAAG,IAAA,oBAAO,EAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,UAAU,CAAC;QACrC,GAAG,KAAK;QACR,GAAG,EAAE,CAAC,EAAE,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE;KAChB,CAAC,CAAC;AACd,CAAC;AArBD,sCAqBC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/edwards.d.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/edwards.d.ts new file mode 100644 index 0000000..9c43c66 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/edwards.d.ts @@ -0,0 +1,89 @@ +import * as ut from './utils.js'; +import { FHash, Hex } from './utils.js'; +import { Group, GroupConstructor, BasicCurve, AffinePoint } from './curve.js'; +export type CurveType = BasicCurve & { + a: bigint; + d: bigint; + hash: FHash; + randomBytes: (bytesLength?: number) => Uint8Array; + adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; + domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; + uvRatio?: (u: bigint, v: bigint) => { + isValid: boolean; + value: bigint; + }; + prehash?: FHash; + mapToCurve?: (scalar: bigint[]) => AffinePoint; +}; +declare function validateOpts(curve: CurveType): Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly d: bigint; + readonly hash: ut.FHash; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + readonly adjustScalarBytes?: ((bytes: Uint8Array) => Uint8Array) | undefined; + readonly domain?: ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array) | undefined; + readonly uvRatio?: ((u: bigint, v: bigint) => { + isValid: boolean; + value: bigint; + }) | undefined; + readonly prehash?: ut.FHash | undefined; + readonly mapToCurve?: ((scalar: bigint[]) => AffinePoint) | undefined; + readonly p: bigint; +}>; +export interface ExtPointType extends Group { + readonly ex: bigint; + readonly ey: bigint; + readonly ez: bigint; + readonly et: bigint; + get x(): bigint; + get y(): bigint; + assertValidity(): void; + multiply(scalar: bigint): ExtPointType; + multiplyUnsafe(scalar: bigint): ExtPointType; + isSmallOrder(): boolean; + isTorsionFree(): boolean; + clearCofactor(): ExtPointType; + toAffine(iz?: bigint): AffinePoint; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; +} +export interface ExtPointConstructor extends GroupConstructor { + new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType; + fromAffine(p: AffinePoint): ExtPointType; + fromHex(hex: Hex): ExtPointType; + fromPrivateKey(privateKey: Hex): ExtPointType; +} +export type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: Hex) => Uint8Array; + sign: (message: Hex, privateKey: Hex, options?: { + context?: Hex; + }) => Uint8Array; + verify: (sig: Hex, message: Hex, publicKey: Hex, options?: { + context?: Hex; + zip215: boolean; + }) => boolean; + ExtendedPoint: ExtPointConstructor; + utils: { + randomPrivateKey: () => Uint8Array; + getExtendedPublicKey: (key: Hex) => { + head: Uint8Array; + prefix: Uint8Array; + scalar: bigint; + point: ExtPointType; + pointBytes: Uint8Array; + }; + }; +}; +export declare function twistedEdwards(curveDef: CurveType): CurveFn; +export {}; +//# sourceMappingURL=edwards.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/edwards.d.ts.map b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/edwards.d.ts.map new file mode 100644 index 0000000..a32123f --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/edwards.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"edwards.d.ts","sourceRoot":"","sources":["../src/abstract/edwards.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AACjC,OAAO,EAAe,KAAK,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,EAAE,KAAK,EAAE,gBAAgB,EAAQ,UAAU,EAAiB,WAAW,EAAE,MAAM,YAAY,CAAC;AAOnG,MAAM,MAAM,SAAS,GAAG,UAAU,CAAC,MAAM,CAAC,GAAG;IAC3C,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,IAAI,EAAE,KAAK,CAAC;IACZ,WAAW,EAAE,CAAC,WAAW,CAAC,EAAE,MAAM,KAAK,UAAU,CAAC;IAClD,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,UAAU,CAAC;IACtD,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,UAAU,EAAE,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,KAAK,UAAU,CAAC;IAC5E,OAAO,CAAC,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;IACxE,OAAO,CAAC,EAAE,KAAK,CAAC;IAChB,UAAU,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,WAAW,CAAC,MAAM,CAAC,CAAC;CACxD,CAAC;AAKF,iBAAS,YAAY,CAAC,KAAK,EAAE,SAAS;;;;;;;;;;;;;;;;;;;;;;;GAmBrC;AAGD,MAAM,WAAW,YA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IAC9C,IAAI,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,EAAE,OAAO,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,GAAG,CAAA;KAAE,KAAK,UAAU,CAAC;IACjF,MAAM,EAAE,CACN,GAAG,EAAE,GAAG,EACR,OAAO,EAAE,GAAG,EACZ,SAAS,EAAE,GAAG,EACd,OAAO,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,GAAG,CAAC;QAAC,MAAM,EAAE,OAAO,CAAA;KAAE,KACzC,OAAO,CAAC;IACb,aAAa,EAAE,mBAAmB,CAAC;IACnC,KAAK,EAAE;QACL,gBAAgB,EAAE,MAAM,UAAU,CAAC;QACnC,oBAAoB,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK;YAClC,IAAI,EAAE,UAAU,CAAC;YACjB,MAAM,EAAE,UAAU,CAAC;YACnB,MAAM,EAAE,MAAM,CAAC;YACf,KAAK,EAAE,YAAY,CAAC;YACpB,UAAU,EAAE,UAAU,CAAC;SACxB,CAAC;KACH,CAAC;CACH,CAAC;AAGF,wBAAgB,cAAc,CAAC,QAAQ,EAAE,SAAS,GAAG,OAAO,CA8Z3D"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/edwards.js b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/edwards.js new file mode 100644 index 0000000..6dd4151 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/edwards.js @@ -0,0 +1,429 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.twistedEdwards = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y² +const modular_js_1 = require("./modular.js"); +const ut = require("./utils.js"); +const utils_js_1 = require("./utils.js"); +const curve_js_1 = require("./curve.js"); +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8); +// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex: +const VERIFY_DEFAULT = { zip215: true }; +function validateOpts(curve) { + const opts = (0, curve_js_1.validateBasic)(curve); + ut.validateObject(curve, { + hash: 'function', + a: 'bigint', + d: 'bigint', + randomBytes: 'function', + }, { + adjustScalarBytes: 'function', + domain: 'function', + uvRatio: 'function', + mapToCurve: 'function', + }); + // Set defaults + return Object.freeze({ ...opts }); +} +// It is not generic twisted curve for now, but ed25519/ed448 generic implementation +function twistedEdwards(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE; + const MASK = _2n << (BigInt(nByteLength * 8) - _1n); + const modP = Fp.create; // Function overrides + // sqrt(u/v) + const uvRatio = CURVE.uvRatio || + ((u, v) => { + try { + return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) }; + } + catch (e) { + return { isValid: false, value: _0n }; + } + }); + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP + const domain = CURVE.domain || + ((data, ctx, phflag) => { + if (ctx.length || phflag) + throw new Error('Contexts/pre-hash are not supported'); + return data; + }); // NOOP + const inBig = (n) => typeof n === 'bigint' && _0n < n; // n in [1..] + const inRange = (n, max) => inBig(n) && inBig(max) && n < max; // n in [1..max-1] + const in0MaskRange = (n) => n === _0n || inRange(n, MASK); // n in [0..MASK-1] + function assertInRange(n, max) { + // n in [1..max-1] + if (inRange(n, max)) + return n; + throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`); + } + function assertGE0(n) { + // n in [0..CURVE_ORDER-1] + return n === _0n ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group + } + const pointPrecomputes = new Map(); + function isPoint(other) { + if (!(other instanceof Point)) + throw new Error('ExtendedPoint expected'); + } + // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy). + // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates + class Point { + constructor(ex, ey, ez, et) { + this.ex = ex; + this.ey = ey; + this.ez = ez; + this.et = et; + if (!in0MaskRange(ex)) + throw new Error('x required'); + if (!in0MaskRange(ey)) + throw new Error('y required'); + if (!in0MaskRange(ez)) + throw new Error('z required'); + if (!in0MaskRange(et)) + throw new Error('t required'); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + static fromAffine(p) { + if (p instanceof Point) + throw new Error('extended point not allowed'); + const { x, y } = p || {}; + if (!in0MaskRange(x) || !in0MaskRange(y)) + throw new Error('invalid affine point'); + return new Point(x, y, _1n, modP(x * y)); + } + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.ez)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + // Not required for fromHex(), which always creates valid points. + // Could be useful for fromAffine(). + assertValidity() { + const { a, d } = CURVE; + if (this.is0()) + throw new Error('bad point: ZERO'); // TODO: optimize, with vars below? + // Equation in affine coordinates: ax² + y² = 1 + dx²y² + // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y² + const { ex: X, ey: Y, ez: Z, et: T } = this; + const X2 = modP(X * X); // X² + const Y2 = modP(Y * Y); // Y² + const Z2 = modP(Z * Z); // Z² + const Z4 = modP(Z2 * Z2); // Z⁴ + const aX2 = modP(X2 * a); // aX² + const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z² + const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y² + if (left !== right) + throw new Error('bad point: equation left != right (1)'); + // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T + const XY = modP(X * Y); + const ZT = modP(Z * T); + if (XY !== ZT) + throw new Error('bad point: equation left != right (2)'); + } + // Compare one point to another. + equals(other) { + isPoint(other); + const { ex: X1, ey: Y1, ez: Z1 } = this; + const { ex: X2, ey: Y2, ez: Z2 } = other; + const X1Z2 = modP(X1 * Z2); + const X2Z1 = modP(X2 * Z1); + const Y1Z2 = modP(Y1 * Z2); + const Y2Z1 = modP(Y2 * Z1); + return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; + } + is0() { + return this.equals(Point.ZERO); + } + negate() { + // Flips point sign to a negative one (-x, y in affine coords) + return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et)); + } + // Fast algo for doubling Extended Point. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd + // Cost: 4M + 4S + 1*a + 6add + 1*2. + double() { + const { a } = CURVE; + const { ex: X1, ey: Y1, ez: Z1 } = this; + const A = modP(X1 * X1); // A = X12 + const B = modP(Y1 * Y1); // B = Y12 + const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12 + const D = modP(a * A); // D = a*A + const x1y1 = X1 + Y1; + const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B + const G = D + B; // G = D+B + const F = G - C; // F = G-C + const H = D - B; // H = D-B + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + // Fast algo for adding 2 Extended Points. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd + // Cost: 9M + 1*a + 1*d + 7add. + add(other) { + isPoint(other); + const { a, d } = CURVE; + const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this; + const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other; + // Faster algo for adding 2 Extended Points when curve's a=-1. + // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4 + // Cost: 8M + 8add + 2*2. + // Note: It does not check whether the `other` point is valid. + if (a === BigInt(-1)) { + const A = modP((Y1 - X1) * (Y2 + X2)); + const B = modP((Y1 + X1) * (Y2 - X2)); + const F = modP(B - A); + if (F === _0n) + return this.double(); // Same point. Tests say it doesn't affect timing + const C = modP(Z1 * _2n * T2); + const D = modP(T1 * _2n * Z2); + const E = D + C; + const G = B + A; + const H = D - C; + const X3 = modP(E * F); + const Y3 = modP(G * H); + const T3 = modP(E * H); + const Z3 = modP(F * G); + return new Point(X3, Y3, Z3, T3); + } + const A = modP(X1 * X2); // A = X1*X2 + const B = modP(Y1 * Y2); // B = Y1*Y2 + const C = modP(T1 * d * T2); // C = T1*d*T2 + const D = modP(Z1 * Z2); // D = Z1*Z2 + const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B + const F = D - C; // F = D-C + const G = D + C; // G = D+C + const H = modP(B - a * A); // H = B-a*A + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + subtract(other) { + return this.add(other.negate()); + } + wNAF(n) { + return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ); + } + // Constant-time multiplication. + multiply(scalar) { + const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER)); + return Point.normalizeZ([p, f])[0]; + } + // Non-constant-time multiplication. Uses double-and-add algorithm. + // It's faster, but should only be used when you don't care about + // an exposed private key e.g. sig verification. + // Does NOT allow scalars higher than CURVE.n. + multiplyUnsafe(scalar) { + let n = assertGE0(scalar); // 0 <= scalar < CURVE.n + if (n === _0n) + return I; + if (this.equals(I) || n === _1n) + return this; + if (this.equals(G)) + return this.wNAF(n).p; + return wnaf.unsafeLadder(this, n); + } + // Checks if point is of small order. + // If you add something to small order point, you will have "dirty" + // point with torsion component. + // Multiplies point by cofactor and checks if the result is 0. + isSmallOrder() { + return this.multiplyUnsafe(cofactor).is0(); + } + // Multiplies point by curve order and checks if the result is 0. + // Returns `false` is the point is dirty. + isTorsionFree() { + return wnaf.unsafeLadder(this, CURVE_ORDER).is0(); + } + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + toAffine(iz) { + const { ex: x, ey: y, ez: z } = this; + const is0 = this.is0(); + if (iz == null) + iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily + const ax = modP(x * iz); + const ay = modP(y * iz); + const zz = modP(z * iz); + if (is0) + return { x: _0n, y: _1n }; + if (zz !== _1n) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + } + clearCofactor() { + const { h: cofactor } = CURVE; + if (cofactor === _1n) + return this; + return this.multiplyUnsafe(cofactor); + } + // Converts hash string or Uint8Array to Point. + // Uses algo from RFC8032 5.1.3. + static fromHex(hex, zip215 = false) { + const { d, a } = CURVE; + const len = Fp.BYTES; + hex = (0, utils_js_1.ensureBytes)('pointHex', hex, len); // copy hex to a new array + const normed = hex.slice(); // copy again, we'll manipulate it + const lastByte = hex[len - 1]; // select last byte + normed[len - 1] = lastByte & ~0x80; // clear last bit + const y = ut.bytesToNumberLE(normed); + if (y === _0n) { + // y=0 is allowed + } + else { + // RFC8032 prohibits >= p, but ZIP215 doesn't + if (zip215) + assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519) + else + assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519) + } + // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case: + // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a) + const y2 = modP(y * y); // denominator is always non-0 mod p. + const u = modP(y2 - _1n); // u = y² - 1 + const v = modP(d * y2 - a); // v = d y² + 1. + let { isValid, value: x } = uvRatio(u, v); // √(u/v) + if (!isValid) + throw new Error('Point.fromHex: invalid y coordinate'); + const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper + const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit + if (!zip215 && x === _0n && isLastByteOdd) + // if x=0 and x_0 = 1, fail + throw new Error('Point.fromHex: x=0 and x_0=1'); + if (isLastByteOdd !== isXOdd) + x = modP(-x); // if x_0 != x mod 2, set x = p-x + return Point.fromAffine({ x, y }); + } + static fromPrivateKey(privKey) { + return getExtendedPublicKey(privKey).point; + } + toRawBytes() { + const { x, y } = this.toAffine(); + const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y) + bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y + return bytes; // and use the last byte to encode sign of x + } + toHex() { + return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string. + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy)); + Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0 + const { BASE: G, ZERO: I } = Point; + const wnaf = (0, curve_js_1.wNAF)(Point, nByteLength * 8); + function modN(a) { + return (0, modular_js_1.mod)(a, CURVE_ORDER); + } + // Little-endian SHA512 with modulo n + function modN_LE(hash) { + return modN(ut.bytesToNumberLE(hash)); + } + /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */ + function getExtendedPublicKey(key) { + const len = nByteLength; + key = (0, utils_js_1.ensureBytes)('private key', key, len); + // Hash private key with curve's hash function to produce uniformingly random input + // Check byte lengths: ensure(64, h(ensure(32, key))) + const hashed = (0, utils_js_1.ensureBytes)('hashed private key', cHash(key), 2 * len); + const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE + const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6) + const scalar = modN_LE(head); // The actual private scalar + const point = G.multiply(scalar); // Point on Edwards curve aka public key + const pointBytes = point.toRawBytes(); // Uint8Array representation + return { head, prefix, scalar, point, pointBytes }; + } + // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared + function getPublicKey(privKey) { + return getExtendedPublicKey(privKey).pointBytes; + } + // int('LE', SHA512(dom2(F, C) || msgs)) mod N + function hashDomainToScalar(context = new Uint8Array(), ...msgs) { + const msg = ut.concatBytes(...msgs); + return modN_LE(cHash(domain(msg, (0, utils_js_1.ensureBytes)('context', context), !!prehash))); + } + /** Signs message with privateKey. RFC8032 5.1.6 */ + function sign(msg, privKey, options = {}) { + msg = (0, utils_js_1.ensureBytes)('message', msg); + if (prehash) + msg = prehash(msg); // for ed25519ph etc. + const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey); + const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M) + const R = G.multiply(r).toRawBytes(); // R = rG + const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M) + const s = modN(r + k * scalar); // S = (r + k * s) mod L + assertGE0(s); // 0 <= s < l + const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES)); + return (0, utils_js_1.ensureBytes)('result', res, nByteLength * 2); // 64-byte signature + } + const verifyOpts = VERIFY_DEFAULT; + function verify(sig, msg, publicKey, options = verifyOpts) { + const { context, zip215 } = options; + const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7. + sig = (0, utils_js_1.ensureBytes)('signature', sig, 2 * len); // An extended group equation is checked. + msg = (0, utils_js_1.ensureBytes)('message', msg); + if (prehash) + msg = prehash(msg); // for ed25519ph, etc + const s = ut.bytesToNumberLE(sig.slice(len, 2 * len)); + // zip215: true is good for consensus-critical apps and allows points < 2^256 + // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p + let A, R, SB; + try { + A = Point.fromHex(publicKey, zip215); + R = Point.fromHex(sig.slice(0, len), zip215); + SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside + } + catch (error) { + return false; + } + if (!zip215 && A.isSmallOrder()) + return false; + const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg); + const RkA = R.add(A.multiplyUnsafe(k)); + // [8][S]B = [8]R + [8][k]A' + return RkA.subtract(SB).clearCofactor().equals(Point.ZERO); + } + G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms. + const utils = { + getExtendedPublicKey, + // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1. + randomPrivateKey: () => randomBytes(Fp.BYTES), + /** + * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT + * values. This slows down first getPublicKey() by milliseconds (see Speed section), + * but allows to speed-up subsequent getPublicKey() calls up to 20x. + * @param windowSize 2, 4, 8, 16 + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; + }, + }; + return { + CURVE, + getPublicKey, + sign, + verify, + ExtendedPoint: Point, + utils, + }; +} +exports.twistedEdwards = twistedEdwards; +//# sourceMappingURL=edwards.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/edwards.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/edwards.js.map new file mode 100644 index 0000000..73ac6d5 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/edwards.js.map @@ -0,0 +1 @@ +{"version":3,"file":"edwards.js","sourceRoot":"","sources":["../src/abstract/edwards.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,8DAA8D;AAC9D,6CAAmC;AACnC,iCAAiC;AACjC,yCAAqD;AACrD,yCAAmG;AAEnG,qEAAqE;AACrE,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAezE,8EAA8E;AAC9E,MAAM,cAAc,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC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GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC;QACvC,4BAA4B;QAC5B,OAAO,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,aAAa,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC7D,CAAC;IAED,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,sEAAsE;IAE3F,MAAM,KAAK,GAAG;QACZ,oBAAoB;QACpB,6FAA6F;QAC7F,gBAAgB,EAAE,GAAe,EAAE,CAAC,WAAW,CAAC,EAAE,CAAC,KAAK,CAAC;QAEzD;;;;;WAKG;QACH,UAAU,CAAC,UAAU,GAAG,CAAC,EAAE,KAAK,GAAG,KAAK,CAAC,IAAI;YAC3C,KAAK,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC;YACjC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;YAC1B,OAAO,KAAK,CAAC;QACf,CAAC;KACF,CAAC;IAEF,OAAO;QACL,KAAK;QACL,YAAY;QACZ,IAAI;QACJ,MAAM;QACN,aAAa,EAAE,KAAK;QACpB,KAAK;KACN,CAAC;AACJ,CAAC;AA9ZD,wCA8ZC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/hash-to-curve.d.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/hash-to-curve.d.ts new file mode 100644 index 0000000..7f09950 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/hash-to-curve.d.ts @@ -0,0 +1,57 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import type { Group, GroupConstructor, AffinePoint } from './curve.js'; +import { IField } from './modular.js'; +import { CHash } from './utils.js'; +/** + * * `DST` is a domain separation tag, defined in section 2.2.5 + * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m + * * `m` is extension degree (1 for prime fields) + * * `k` is the target security target in bits (e.g. 128), from section 5.1 + * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF) + * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props + */ +type UnicodeOrBytes = string | Uint8Array; +export type Opts = { + DST: UnicodeOrBytes; + p: bigint; + m: number; + k: number; + expand: 'xmd' | 'xof'; + hash: CHash; +}; +export declare function expand_message_xmd(msg: Uint8Array, DST: Uint8Array, lenInBytes: number, H: CHash): Uint8Array; +export declare function expand_message_xof(msg: Uint8Array, DST: Uint8Array, lenInBytes: number, k: number, H: CHash): Uint8Array; +/** + * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.3 + * @param msg a byte string containing the message to hash + * @param count the number of elements of F to output + * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above + * @returns [u_0, ..., u_(count - 1)], a list of field elements. + */ +export declare function hash_to_field(msg: Uint8Array, count: number, options: Opts): bigint[][]; +export declare function isogenyMap>(field: F, map: [T[], T[], T[], T[]]): (x: T, y: T) => { + x: T; + y: T; +}; +export interface H2CPoint extends Group> { + add(rhs: H2CPoint): H2CPoint; + toAffine(iz?: bigint): AffinePoint; + clearCofactor(): H2CPoint; + assertValidity(): void; +} +export interface H2CPointConstructor extends GroupConstructor> { + fromAffine(ap: AffinePoint): H2CPoint; +} +export type MapToCurve = (scalar: bigint[]) => AffinePoint; +export type htfBasicOpts = { + DST: UnicodeOrBytes; +}; +export declare function createHasher(Point: H2CPointConstructor, mapToCurve: MapToCurve, def: Opts & { + encodeDST?: UnicodeOrBytes; +}): { + hashToCurve(msg: Uint8Array, options?: htfBasicOpts): H2CPoint; + encodeToCurve(msg: Uint8Array, options?: htfBasicOpts): H2CPoint; +}; +export {}; +//# sourceMappingURL=hash-to-curve.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/hash-to-curve.d.ts.map b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/hash-to-curve.d.ts.map new file mode 100644 index 0000000..e89ad84 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/hash-to-curve.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"hash-to-curve.d.ts","sourceRoot":"","sources":["../src/abstract/hash-to-curve.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,KAAK,EAAE,KAAK,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACvE,OAAO,EAAO,MAAM,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAmB,KAAK,EAA4C,MAAM,YAAY,CAAC;AAE9F;;;;;;;GAOG;AACH,KAAK,cAAc,GAAG,MAAM,GAAG,UAAU,CAAC;AAC1C,MAAM,MAAM,IAAI,GAAG;IACjB,GAAG,EAAE,cAAc,CAAC;IACpB,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,MAAM,EAAE,KAAK,GAAG,KAAK,CAAC;IACtB,IAAI,EAAE,KAAK,CAAC;CACb,CAAC;AAyCF,wBAAgB,kBAAkB,CAChC,GAAG,EAAE,UAAU,EACf,GAAG,EAAE,UAAU,EACf,UAAU,EAAE,MAAM,EAClB,CAAC,EAAE,KAAK,GACP,UAAU,CAqBZ;AAED,wBAAgB,kBAAkB,CAChC,GAAG,EAAE,UAAU,EACf,GAAG,EAAE,UAAU,EACf,UAAU,EAAE,MAAM,EAClB,CAAC,EAAE,MAAM,EACT,CAAC,EAAE,KAAK,GACP,UAAU,CAqBZ;AAED;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,GAAG,MAAM,EAAE,EAAE,CAqCvF;AAED,wBAAgB,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/node_modules/@noble/curves/abstract/hash-to-curve.js b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/hash-to-curve.js new file mode 100644 index 0000000..418a80c --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/hash-to-curve.js @@ -0,0 +1,175 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createHasher = exports.isogenyMap = exports.hash_to_field = exports.expand_message_xof = exports.expand_message_xmd = void 0; +const modular_js_1 = require("./modular.js"); +const utils_js_1 = require("./utils.js"); +function validateDST(dst) { + if (dst instanceof Uint8Array) + return dst; + if (typeof dst === 'string') + return (0, utils_js_1.utf8ToBytes)(dst); + throw new Error('DST must be Uint8Array or string'); +} +// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE. +const os2ip = utils_js_1.bytesToNumberBE; +// Integer to Octet Stream (numberToBytesBE) +function i2osp(value, length) { + if (value < 0 || value >= 1 << (8 * length)) { + throw new Error(`bad I2OSP call: value=${value} length=${length}`); + } + const res = Array.from({ length }).fill(0); + for (let i = length - 1; i >= 0; i--) { + res[i] = value & 0xff; + value >>>= 8; + } + return new Uint8Array(res); +} +function strxor(a, b) { + const arr = new Uint8Array(a.length); + for (let i = 0; i < a.length; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} +function isBytes(item) { + if (!(item instanceof Uint8Array)) + throw new Error('Uint8Array expected'); +} +function isNum(item) { + if (!Number.isSafeInteger(item)) + throw new Error('number expected'); +} +// Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.4.1 +function expand_message_xmd(msg, DST, lenInBytes, H) { + isBytes(msg); + isBytes(DST); + isNum(lenInBytes); + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-5.3.3 + if (DST.length > 255) + DST = H((0, utils_js_1.concatBytes)((0, utils_js_1.utf8ToBytes)('H2C-OVERSIZE-DST-'), DST)); + const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H; + const ell = Math.ceil(lenInBytes / b_in_bytes); + if (ell > 255) + throw new Error('Invalid xmd length'); + const DST_prime = (0, utils_js_1.concatBytes)(DST, i2osp(DST.length, 1)); + const Z_pad = i2osp(0, r_in_bytes); + const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str + const b = new Array(ell); + const b_0 = H((0, utils_js_1.concatBytes)(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); + b[0] = H((0, utils_js_1.concatBytes)(b_0, i2osp(1, 1), DST_prime)); + for (let i = 1; i <= ell; i++) { + const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime]; + b[i] = H((0, utils_js_1.concatBytes)(...args)); + } + const pseudo_random_bytes = (0, utils_js_1.concatBytes)(...b); + return pseudo_random_bytes.slice(0, lenInBytes); +} +exports.expand_message_xmd = expand_message_xmd; +function expand_message_xof(msg, DST, lenInBytes, k, H) { + isBytes(msg); + isBytes(DST); + isNum(lenInBytes); + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-5.3.3 + // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8)); + if (DST.length > 255) { + const dkLen = Math.ceil((2 * k) / 8); + DST = H.create({ dkLen }).update((0, utils_js_1.utf8ToBytes)('H2C-OVERSIZE-DST-')).update(DST).digest(); + } + if (lenInBytes > 65535 || DST.length > 255) + throw new Error('expand_message_xof: invalid lenInBytes'); + return (H.create({ dkLen: lenInBytes }) + .update(msg) + .update(i2osp(lenInBytes, 2)) + // 2. DST_prime = DST || I2OSP(len(DST), 1) + .update(DST) + .update(i2osp(DST.length, 1)) + .digest()); +} +exports.expand_message_xof = expand_message_xof; +/** + * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.3 + * @param msg a byte string containing the message to hash + * @param count the number of elements of F to output + * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above + * @returns [u_0, ..., u_(count - 1)], a list of field elements. + */ +function hash_to_field(msg, count, options) { + (0, utils_js_1.validateObject)(options, { + DST: 'string', + p: 'bigint', + m: 'isSafeInteger', + k: 'isSafeInteger', + hash: 'hash', + }); + const { p, k, m, hash, expand, DST: _DST } = options; + isBytes(msg); + isNum(count); + const DST = validateDST(_DST); + const log2p = p.toString(2).length; + const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above + const len_in_bytes = count * m * L; + let prb; // pseudo_random_bytes + if (expand === 'xmd') { + prb = expand_message_xmd(msg, DST, len_in_bytes, hash); + } + else if (expand === 'xof') { + prb = expand_message_xof(msg, DST, len_in_bytes, k, hash); + } + else if (expand === '_internal_pass') { + // for internal tests only + prb = msg; + } + else { + throw new Error('expand must be "xmd" or "xof"'); + } + const u = new Array(count); + for (let i = 0; i < count; i++) { + const e = new Array(m); + for (let j = 0; j < m; j++) { + const elm_offset = L * (j + i * m); + const tv = prb.subarray(elm_offset, elm_offset + L); + e[j] = (0, modular_js_1.mod)(os2ip(tv), p); + } + u[i] = e; + } + return u; +} +exports.hash_to_field = hash_to_field; +function isogenyMap(field, map) { + // Make same order as in spec + const COEFF = map.map((i) => Array.from(i).reverse()); + return (x, y) => { + const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i))); + x = field.div(xNum, xDen); // xNum / xDen + y = field.mul(y, field.div(yNum, yDen)); // y * (yNum / yDev) + return { x, y }; + }; +} +exports.isogenyMap = isogenyMap; +function createHasher(Point, mapToCurve, def) { + if (typeof mapToCurve !== 'function') + throw new Error('mapToCurve() must be defined'); + return { + // Encodes byte string to elliptic curve + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-3 + hashToCurve(msg, options) { + const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options }); + const u0 = Point.fromAffine(mapToCurve(u[0])); + const u1 = Point.fromAffine(mapToCurve(u[1])); + const P = u0.add(u1).clearCofactor(); + P.assertValidity(); + return P; + }, + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-3 + encodeToCurve(msg, options) { + const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options }); + const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor(); + P.assertValidity(); + return P; + }, + }; +} +exports.createHasher = createHasher; +//# sourceMappingURL=hash-to-curve.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/hash-to-curve.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/hash-to-curve.js.map new file mode 100644 index 0000000..c2fa8bd --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/hash-to-curve.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hash-to-curve.js","sourceRoot":"","sources":["../src/abstract/hash-to-curve.ts"],"names":[],"mappings":";;;AAEA,6CAA2C;AAC3C,yCAA8F;AAoB9F,SAAS,WAAW,CAAC,GAAmB;IACtC,IAAI,GAAG,YAAY,UAAU;QAAE,OAAO,GAAG,CAAC;IAC1C,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,OAAO,IAAA,sBAAW,EAAC,GAAG,CAAC,CAAC;IACrD,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;AACtD,CAAC;AAED,6FAA6F;AAC7F,MAAM,KAAK,GAAG,0BAAe,CAAC;AAE9B,4CAA4C;AAC5C,SAAS,KAAK,CAAC,KAAa,EAAE,MAAc;IAC1C,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,MAAM,CAAC,EAAE;QAC3C,MAAM,IAAI,KAAK,CAAC,yBAAyB,KAAK,WAAW,MAAM,EAAE,CAAC,CAAC;KACpE;IACD,MAAM,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,E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G,OAAO,EAAU,CAAC,CAAC;YACpF,MAAM,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,aAAa,EAAE,CAAC;YAC7D,CAAC,CAAC,cAAc,EAAE,CAAC;YACnB,OAAO,CAAC,CAAC;QACX,CAAC;KACF,CAAC;AACJ,CAAC;AA1BD,oCA0BC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/modular.d.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/modular.d.ts new file mode 100644 index 0000000..3acaa1e --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/modular.d.ts @@ -0,0 +1,83 @@ +export declare function mod(a: bigint, b: bigint): bigint; +/** + * Efficiently raise num to power and do modular division. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + * @example + * pow(2n, 6n, 11n) // 64n % 11n == 9n + */ +export declare function pow(num: bigint, power: bigint, modulo: bigint): bigint; +export declare function pow2(x: bigint, power: bigint, modulo: bigint): bigint; +export declare function invert(number: bigint, modulo: bigint): bigint; +export declare function tonelliShanks(P: bigint): (Fp: IField, n: T) => T; +export declare function FpSqrt(P: bigint): (Fp: IField, n: T) => T; +export declare const isNegativeLE: (num: bigint, modulo: bigint) => boolean; +export interface IField { + ORDER: bigint; + BYTES: number; + BITS: number; + MASK: bigint; + ZERO: T; + ONE: T; + create: (num: T) => T; + isValid: (num: T) => boolean; + is0: (num: T) => boolean; + neg(num: T): T; + inv(num: T): T; + sqrt(num: T): T; + sqr(num: T): T; + eql(lhs: T, rhs: T): boolean; + add(lhs: T, rhs: T): T; + sub(lhs: T, rhs: T): T; + mul(lhs: T, rhs: T | bigint): T; + pow(lhs: T, power: bigint): T; + div(lhs: T, rhs: T | bigint): T; + addN(lhs: T, rhs: T): T; + subN(lhs: T, rhs: T): T; + mulN(lhs: T, rhs: T | bigint): T; + sqrN(num: T): T; + isOdd?(num: T): boolean; + pow(lhs: T, power: bigint): T; + invertBatch: (lst: T[]) => T[]; + toBytes(num: T): Uint8Array; + fromBytes(bytes: Uint8Array): T; + cmov(a: T, b: T, c: boolean): T; +} +export declare function validateField(field: IField): IField; +export declare function FpPow(f: IField, num: T, power: bigint): T; +export declare function FpInvertBatch(f: IField, nums: T[]): T[]; +export declare function FpDiv(f: IField, lhs: T, rhs: T | bigint): T; +export declare function FpIsSquare(f: IField): (x: T) => boolean; +export declare function nLength(n: bigint, nBitLength?: number): { + nBitLength: number; + nByteLength: number; +}; +type FpField = IField & Required, 'isOdd'>>; +/** + * Initializes a galois field over prime. Non-primes are not supported for now. + * Do not init in loop: slow. Very fragile: always run a benchmark on change. + * Major performance gains: + * a) non-normalized operations like mulN instead of mul + * b) `Object.freeze` + * c) Same object shape: never add or remove keys + * @param ORDER prime positive bigint + * @param bitLen how many bits the field consumes + * @param isLE (def: false) if encoding / decoding should be in little-endian + * @param redef optional faster redefinitions of sqrt and other methods + */ +export declare function Field(ORDER: bigint, bitLen?: number, isLE?: boolean, redef?: Partial>): Readonly; +export declare function FpSqrtOdd(Fp: IField, elm: T): T; +export declare function FpSqrtEven(Fp: IField, elm: T): T; +/** + * FIPS 186 B.4.1-compliant "constant-time" private key generation utility. + * Can take (n+8) or more bytes of uniform input e.g. from CSPRNG or KDF + * and convert them into private scalar, with the modulo bias being negligible. + * Needs at least 40 bytes of input for 32-byte private key. + * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ + * @param hash hash output from SHA3 or a similar function + * @param groupOrder size of subgroup - (e.g. curveFn.CURVE.n) + * @param isLE interpret hash bytes as LE num + * @returns valid private scalar + */ +export declare function hashToPrivateScalar(hash: string | Uint8Array, groupOrder: bigint, isLE?: boolean): bigint; +export {}; +//# sourceMappingURL=modular.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/modular.d.ts.map b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/modular.d.ts.map new file mode 100644 index 0000000..49b9d75 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/modular.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"modular.d.ts","sourceRoot":"","sources":["../src/abstract/modular.ts"],"names":[],"mappings":"AAmBA,wBAAgB,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAGhD;AACD;;;;;GAKG;AAEH,wBAAgB,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAUtE;AAGD,wBAAgB,IAAI,CAAC,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAOrE;AAGD,wBAAgB,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAsB7D;AAKD,wBAAgB,aAAa,CAAC,CAAC,EAAE,MAAM,iCAsDtC;AAED,wBAAgB,MAAM,CAAC,CAAC,EAAE,MAAM,iCA2D/B;AAGD,eAAO,MAAM,YAAY,QAAS,MAAM,UAAU,MAAM,YAAqC,CAAC;AAG9F,MAAM,WAAW,MAAM,CAAC,CAAC;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,CAAC,CAAC;IACR,GAAG,EAAE,CAAC,CAAC;IAEP,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC;IACtB,OAAO,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,OAAO,CAAC;IAC7B,GAAG,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,OAAO,CAAC;IACzB,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC;IACf,GA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E,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,KAIjD;AAED,wBAAgB,UAAU,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,KAIlD;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,MAAM,GAAG,UAAU,EACzB,UAAU,EAAE,MAAM,EAClB,IAAI,UAAQ,GACX,MAAM,CAQR"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/modular.js b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/modular.js new file mode 100644 index 0000000..2f338e5 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/modular.js @@ -0,0 +1,381 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hashToPrivateScalar = exports.FpSqrtEven = exports.FpSqrtOdd = exports.Field = exports.nLength = exports.FpIsSquare = exports.FpDiv = exports.FpInvertBatch = exports.FpPow = exports.validateField = exports.isNegativeLE = exports.FpSqrt = exports.tonelliShanks = exports.invert = exports.pow2 = exports.pow = exports.mod = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Utilities for modular arithmetics and finite fields +const utils_js_1 = require("./utils.js"); +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); +// prettier-ignore +const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8); +// prettier-ignore +const _9n = BigInt(9), _16n = BigInt(16); +// Calculates a modulo b +function mod(a, b) { + const result = a % b; + return result >= _0n ? result : b + result; +} +exports.mod = mod; +/** + * Efficiently raise num to power and do modular division. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + * @example + * pow(2n, 6n, 11n) // 64n % 11n == 9n + */ +// TODO: use field version && remove +function pow(num, power, modulo) { + if (modulo <= _0n || power < _0n) + throw new Error('Expected power/modulo > 0'); + if (modulo === _1n) + return _0n; + let res = _1n; + while (power > _0n) { + if (power & _1n) + res = (res * num) % modulo; + num = (num * num) % modulo; + power >>= _1n; + } + return res; +} +exports.pow = pow; +// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4) +function pow2(x, power, modulo) { + let res = x; + while (power-- > _0n) { + res *= res; + res %= modulo; + } + return res; +} +exports.pow2 = pow2; +// Inverses number over modulo +function invert(number, modulo) { + if (number === _0n || modulo <= _0n) { + throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); + } + // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/ + // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower. + let a = mod(number, modulo); + let b = modulo; + // prettier-ignore + let x = _0n, y = _1n, u = _1n, v = _0n; + while (a !== _0n) { + // JIT applies optimization if those two lines follow each other + const q = b / a; + const r = b % a; + const m = x - u * q; + const n = y - v * q; + // prettier-ignore + b = a, a = r, x = u, y = v, u = m, v = n; + } + const gcd = b; + if (gcd !== _1n) + throw new Error('invert: does not exist'); + return mod(x, modulo); +} +exports.invert = invert; +// Tonelli-Shanks algorithm +// Paper 1: https://eprint.iacr.org/2012/685.pdf (page 12) +// Paper 2: Square Roots from 1; 24, 51, 10 to Dan Shanks +function tonelliShanks(P) { + // Legendre constant: used to calculate Legendre symbol (a | p), + // which denotes the value of a^((p-1)/2) (mod p). + // (a | p) ≡ 1 if a is a square (mod p) + // (a | p) ≡ -1 if a is not a square (mod p) + // (a | p) ≡ 0 if a ≡ 0 (mod p) + const legendreC = (P - _1n) / _2n; + let Q, S, Z; + // Step 1: By factoring out powers of 2 from p - 1, + // find q and s such that p - 1 = q*(2^s) with q odd + for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++) + ; + // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq + for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++) + ; + // Fast-path + if (S === 1) { + const p1div4 = (P + _1n) / _4n; + return function tonelliFast(Fp, n) { + const root = Fp.pow(n, p1div4); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Slow-path + const Q1div2 = (Q + _1n) / _2n; + return function tonelliSlow(Fp, n) { + // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1 + if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) + throw new Error('Cannot find square root'); + let r = S; + // TODO: will fail at Fp2/etc + let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b + let x = Fp.pow(n, Q1div2); // first guess at the square root + let b = Fp.pow(n, Q); // first guess at the fudge factor + while (!Fp.eql(b, Fp.ONE)) { + if (Fp.eql(b, Fp.ZERO)) + return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0) + // Find m such b^(2^m)==1 + let m = 1; + for (let t2 = Fp.sqr(b); m < r; m++) { + if (Fp.eql(t2, Fp.ONE)) + break; + t2 = Fp.sqr(t2); // t2 *= t2 + } + // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow + const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1) + g = Fp.sqr(ge); // g = ge * ge + x = Fp.mul(x, ge); // x *= ge + b = Fp.mul(b, g); // b *= g + r = m; + } + return x; + }; +} +exports.tonelliShanks = tonelliShanks; +function FpSqrt(P) { + // NOTE: different algorithms can give different roots, it is up to user to decide which one they want. + // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve). + // P ≡ 3 (mod 4) + // √n = n^((P+1)/4) + if (P % _4n === _3n) { + // Not all roots possible! + // const ORDER = + // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn; + // const NUM = 72057594037927816n; + const p1div4 = (P + _1n) / _4n; + return function sqrt3mod4(Fp, n) { + const root = Fp.pow(n, p1div4); + // Throw if root**2 != n + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10) + if (P % _8n === _5n) { + const c1 = (P - _5n) / _8n; + return function sqrt5mod8(Fp, n) { + const n2 = Fp.mul(n, _2n); + const v = Fp.pow(n2, c1); + const nv = Fp.mul(n, v); + const i = Fp.mul(Fp.mul(nv, _2n), v); + const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // P ≡ 9 (mod 16) + if (P % _16n === _9n) { + // NOTE: tonelli is too slow for bls-Fp2 calculations even on start + // Means we cannot use sqrt for constants at all! + // + // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F + // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F + // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F + // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic + // sqrt = (x) => { + // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4 + // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1 + // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1 + // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1 + // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x + // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x + // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x + // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x + // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x + // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2 + // } + } + // Other cases: Tonelli-Shanks algorithm + return tonelliShanks(P); +} +exports.FpSqrt = FpSqrt; +// Little-endian check for first LE bit (last BE bit); +const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n; +exports.isNegativeLE = isNegativeLE; +// prettier-ignore +const FIELD_FIELDS = [ + 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr', + 'eql', 'add', 'sub', 'mul', 'pow', 'div', + 'addN', 'subN', 'mulN', 'sqrN' +]; +function validateField(field) { + const initial = { + ORDER: 'bigint', + MASK: 'bigint', + BYTES: 'isSafeInteger', + BITS: 'isSafeInteger', + }; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = 'function'; + return map; + }, initial); + return (0, utils_js_1.validateObject)(field, opts); +} +exports.validateField = validateField; +// Generic field functions +function FpPow(f, num, power) { + // Should have same speed as pow for bigints + // TODO: benchmark! + if (power < _0n) + throw new Error('Expected power > 0'); + if (power === _0n) + return f.ONE; + if (power === _1n) + return num; + let p = f.ONE; + let d = num; + while (power > _0n) { + if (power & _1n) + p = f.mul(p, d); + d = f.sqr(d); + power >>= _1n; + } + return p; +} +exports.FpPow = FpPow; +// 0 is non-invertible: non-batched version will throw on 0 +function FpInvertBatch(f, nums) { + const tmp = new Array(nums.length); + // Walk from first to last, multiply them by each other MOD p + const lastMultiplied = nums.reduce((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = acc; + return f.mul(acc, num); + }, f.ONE); + // Invert last element + const inverted = f.inv(lastMultiplied); + // Walk from last to first, multiply them by inverted each other MOD p + nums.reduceRight((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = f.mul(acc, tmp[i]); + return f.mul(acc, num); + }, inverted); + return tmp; +} +exports.FpInvertBatch = FpInvertBatch; +function FpDiv(f, lhs, rhs) { + return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs)); +} +exports.FpDiv = FpDiv; +// This function returns True whenever the value x is a square in the field F. +function FpIsSquare(f) { + const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic + return (x) => { + const p = f.pow(x, legendreConst); + return f.eql(p, f.ZERO) || f.eql(p, f.ONE); + }; +} +exports.FpIsSquare = FpIsSquare; +// CURVE.n lengths +function nLength(n, nBitLength) { + // Bit size, byte size of CURVE.n + const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} +exports.nLength = nLength; +/** + * Initializes a galois field over prime. Non-primes are not supported for now. + * Do not init in loop: slow. Very fragile: always run a benchmark on change. + * Major performance gains: + * a) non-normalized operations like mulN instead of mul + * b) `Object.freeze` + * c) Same object shape: never add or remove keys + * @param ORDER prime positive bigint + * @param bitLen how many bits the field consumes + * @param isLE (def: false) if encoding / decoding should be in little-endian + * @param redef optional faster redefinitions of sqrt and other methods + */ +function Field(ORDER, bitLen, isLE = false, redef = {}) { + if (ORDER <= _0n) + throw new Error(`Expected Fp ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen); + if (BYTES > 2048) + throw new Error('Field lengths over 2048 bytes are not supported'); + const sqrtP = FpSqrt(ORDER); + const f = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: (0, utils_js_1.bitMask)(BITS), + ZERO: _0n, + ONE: _1n, + create: (num) => mod(num, ORDER), + isValid: (num) => { + if (typeof num !== 'bigint') + throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); + return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible + }, + is0: (num) => num === _0n, + isOdd: (num) => (num & _1n) === _1n, + neg: (num) => mod(-num, ORDER), + eql: (lhs, rhs) => lhs === rhs, + sqr: (num) => mod(num * num, ORDER), + add: (lhs, rhs) => mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod(lhs * rhs, ORDER), + pow: (num, power) => FpPow(f, num, power), + div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), + // Same as above, but doesn't normalize + sqrN: (num) => num * num, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + inv: (num) => invert(num, ORDER), + sqrt: redef.sqrt || ((n) => sqrtP(f, n)), + invertBatch: (lst) => FpInvertBatch(f, lst), + // TODO: do we really need constant cmov? + // We don't have const-time bigints anyway, so probably will be not very useful + cmov: (a, b, c) => (c ? b : a), + toBytes: (num) => (isLE ? (0, utils_js_1.numberToBytesLE)(num, BYTES) : (0, utils_js_1.numberToBytesBE)(num, BYTES)), + fromBytes: (bytes) => { + if (bytes.length !== BYTES) + throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); + return isLE ? (0, utils_js_1.bytesToNumberLE)(bytes) : (0, utils_js_1.bytesToNumberBE)(bytes); + }, + }); + return Object.freeze(f); +} +exports.Field = Field; +function FpSqrtOdd(Fp, elm) { + if (!Fp.isOdd) + throw new Error(`Field doesn't have isOdd`); + const root = Fp.sqrt(elm); + return Fp.isOdd(root) ? root : Fp.neg(root); +} +exports.FpSqrtOdd = FpSqrtOdd; +function FpSqrtEven(Fp, elm) { + if (!Fp.isOdd) + throw new Error(`Field doesn't have isOdd`); + const root = Fp.sqrt(elm); + return Fp.isOdd(root) ? Fp.neg(root) : root; +} +exports.FpSqrtEven = FpSqrtEven; +/** + * FIPS 186 B.4.1-compliant "constant-time" private key generation utility. + * Can take (n+8) or more bytes of uniform input e.g. from CSPRNG or KDF + * and convert them into private scalar, with the modulo bias being negligible. + * Needs at least 40 bytes of input for 32-byte private key. + * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ + * @param hash hash output from SHA3 or a similar function + * @param groupOrder size of subgroup - (e.g. curveFn.CURVE.n) + * @param isLE interpret hash bytes as LE num + * @returns valid private scalar + */ +function hashToPrivateScalar(hash, groupOrder, isLE = false) { + hash = (0, utils_js_1.ensureBytes)('privateHash', hash); + const hashLen = hash.length; + const minLen = nLength(groupOrder).nByteLength + 8; + if (minLen < 24 || hashLen < minLen || hashLen > 1024) + throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`); + const num = isLE ? (0, utils_js_1.bytesToNumberLE)(hash) : (0, utils_js_1.bytesToNumberBE)(hash); + return mod(num, groupOrder - _1n) + _1n; +} +exports.hashToPrivateScalar = hashToPrivateScalar; +//# sourceMappingURL=modular.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/modular.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/modular.js.map new file mode 100644 index 0000000..9938a17 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/modular.js.map @@ -0,0 +1 @@ +{"version":3,"file":"modular.js","sourceRoot":"","sources":["../src/abstract/modular.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,sDAAsD;AACtD,yCAQoB;AACpB,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACzE,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACxD,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EA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G,CAAC,CAAC;IACnD,IAAI,MAAM,GAAG,EAAE,IAAI,OAAO,GAAG,MAAM,IAAI,OAAO,GAAG,IAAI;QACnD,MAAM,IAAI,KAAK,CAAC,iCAAiC,MAAM,6BAA6B,OAAO,EAAE,CAAC,CAAC;IACjG,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,IAAA,0BAAe,EAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAA,0BAAe,EAAC,IAAI,CAAC,CAAC;IACjE,OAAO,GAAG,CAAC,GAAG,EAAE,UAAU,GAAG,GAAG,CAAC,GAAG,GAAG,CAAC;AAC1C,CAAC;AAZD,kDAYC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/montgomery.d.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/montgomery.d.ts new file mode 100644 index 0000000..69e2bc4 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/montgomery.d.ts @@ -0,0 +1,26 @@ +type Hex = string | Uint8Array; +export type CurveType = { + P: bigint; + nByteLength: number; + adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; + domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; + a: bigint; + montgomeryBits: number; + powPminus2?: (x: bigint) => bigint; + xyToU?: (x: bigint, y: bigint) => bigint; + Gu: bigint; + randomBytes?: (bytesLength?: number) => Uint8Array; +}; +export type CurveFn = { + scalarMult: (scalar: Hex, u: Hex) => Uint8Array; + scalarMultBase: (scalar: Hex) => Uint8Array; + getSharedSecret: (privateKeyA: Hex, publicKeyB: Hex) => Uint8Array; + getPublicKey: (privateKey: Hex) => Uint8Array; + utils: { + randomPrivateKey: () => Uint8Array; + }; + GuBytes: Uint8Array; +}; +export declare function montgomery(curveDef: CurveType): CurveFn; +export {}; +//# sourceMappingURL=montgomery.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/montgomery.d.ts.map b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/montgomery.d.ts.map new file mode 100644 index 0000000..a0d1c0b --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/montgomery.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"montgomery.d.ts","sourceRoot":"","sources":["../src/abstract/montgomery.ts"],"names":[],"mappings":"AAMA,KAAK,GAAG,GAAG,MAAM,GAAG,UAAU,CAAC;AAE/B,MAAM,MAAM,SAAS,GAAG;IACtB,CAAC,EAAE,MAAM,CAAC;IACV,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,UAAU,CAAC;IACtD,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,UAAU,EAAE,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,KAAK,UAAU,CAAC;IAC5E,CAAC,EAAE,MAAM,CAAC;IACV,cAAc,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IACnC,KAAK,CAAC,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IACzC,EAAE,EAAE,MAAM,CAAC;IACX,WAAW,CAAC,EAAE,CAAC,WAAW,CAAC,EAAE,MAAM,KAAK,UAAU,CAAC;CACpD,CAAC;AACF,MAAM,MAAM,OAAO,GAAG;IACpB,UAAU,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,KAAK,UAAU,CAAC;IAChD,cAAc,EAAE,CAAC,MAAM,EAAE,GAAG,KAAK,UAAU,CAAC;IAC5C,eAAe,EAAE,CAAC,WAAW,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,KAAK,UAAU,CAAC;IACnE,YAAY,EAAE,CAAC,UAAU,EAAE,GAAG,KAAK,UAAU,CAAC;IAC9C,KAAK,EAAE;QAAE,gBAAgB,EAAE,MAAM,UAAU,CAAA;KAAE,CAAC;IAC9C,OAAO,EAAE,UAAU,CAAC;CACrB,CAAC;AAuBF,wBAAgB,UAAU,CAAC,QAAQ,EAAE,SAAS,GAAG,OAAO,CA0IvD"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/montgomery.js b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/montgomery.js new file mode 100644 index 0000000..b43e43b --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/montgomery.js @@ -0,0 +1,161 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.montgomery = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const modular_js_1 = require("./modular.js"); +const utils_js_1 = require("./utils.js"); +const _0n = BigInt(0); +const _1n = BigInt(1); +function validateOpts(curve) { + (0, utils_js_1.validateObject)(curve, { + a: 'bigint', + }, { + montgomeryBits: 'isSafeInteger', + nByteLength: 'isSafeInteger', + adjustScalarBytes: 'function', + domain: 'function', + powPminus2: 'function', + Gu: 'bigint', + }); + // Set defaults + return Object.freeze({ ...curve }); +} +// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748) +// Uses only one coordinate instead of two +function montgomery(curveDef) { + const CURVE = validateOpts(curveDef); + const { P } = CURVE; + const modP = (n) => (0, modular_js_1.mod)(n, P); + const montgomeryBits = CURVE.montgomeryBits; + const montgomeryBytes = Math.ceil(montgomeryBits / 8); + const fieldLen = CURVE.nByteLength; + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); + const powPminus2 = CURVE.powPminus2 || ((x) => (0, modular_js_1.pow)(x, P - BigInt(2), P)); + // cswap from RFC7748. But it is not from RFC7748! + /* + cswap(swap, x_2, x_3): + dummy = mask(swap) AND (x_2 XOR x_3) + x_2 = x_2 XOR dummy + x_3 = x_3 XOR dummy + Return (x_2, x_3) + Where mask(swap) is the all-1 or all-0 word of the same length as x_2 + and x_3, computed, e.g., as mask(swap) = 0 - swap. + */ + function cswap(swap, x_2, x_3) { + const dummy = modP(swap * (x_2 - x_3)); + x_2 = modP(x_2 - dummy); + x_3 = modP(x_3 + dummy); + return [x_2, x_3]; + } + // Accepts 0 as well + function assertFieldElement(n) { + if (typeof n === 'bigint' && _0n <= n && n < P) + return n; + throw new Error('Expected valid scalar 0 < scalar < CURVE.P'); + } + // x25519 from 4 + // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 + const a24 = (CURVE.a - BigInt(2)) / BigInt(4); + /** + * + * @param pointU u coordinate (x) on Montgomery Curve 25519 + * @param scalar by which the point would be multiplied + * @returns new Point on Montgomery curve + */ + function montgomeryLadder(pointU, scalar) { + const u = assertFieldElement(pointU); + // Section 5: Implementations MUST accept non-canonical values and process them as + // if they had been reduced modulo the field prime. + const k = assertFieldElement(scalar); + const x_1 = u; + let x_2 = _1n; + let z_2 = _0n; + let x_3 = u; + let z_3 = _1n; + let swap = _0n; + let sw; + for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) { + const k_t = (k >> t) & _1n; + swap ^= k_t; + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + swap = k_t; + const A = x_2 + z_2; + const AA = modP(A * A); + const B = x_2 - z_2; + const BB = modP(B * B); + const E = AA - BB; + const C = x_3 + z_3; + const D = x_3 - z_3; + const DA = modP(D * A); + const CB = modP(C * B); + const dacb = DA + CB; + const da_cb = DA - CB; + x_3 = modP(dacb * dacb); + z_3 = modP(x_1 * modP(da_cb * da_cb)); + x_2 = modP(AA * BB); + z_2 = modP(E * (AA + modP(a24 * E))); + } + // (x_2, x_3) = cswap(swap, x_2, x_3) + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + // (z_2, z_3) = cswap(swap, z_2, z_3) + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + // z_2^(p - 2) + const z2 = powPminus2(z_2); + // Return x_2 * (z_2^(p - 2)) + return modP(x_2 * z2); + } + function encodeUCoordinate(u) { + return (0, utils_js_1.numberToBytesLE)(modP(u), montgomeryBytes); + } + function decodeUCoordinate(uEnc) { + // Section 5: When receiving such an array, implementations of X25519 + // MUST mask the most significant bit in the final byte. + // This is very ugly way, but it works because fieldLen-1 is outside of bounds for X448, so this becomes NOOP + // fieldLen - scalaryBytes = 1 for X448 and = 0 for X25519 + const u = (0, utils_js_1.ensureBytes)('u coordinate', uEnc, montgomeryBytes); + // u[fieldLen-1] crashes QuickJS (TypeError: out-of-bound numeric index) + if (fieldLen === montgomeryBytes) + u[fieldLen - 1] &= 127; // 0b0111_1111 + return (0, utils_js_1.bytesToNumberLE)(u); + } + function decodeScalar(n) { + const bytes = (0, utils_js_1.ensureBytes)('scalar', n); + if (bytes.length !== montgomeryBytes && bytes.length !== fieldLen) + throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${bytes.length}`); + return (0, utils_js_1.bytesToNumberLE)(adjustScalarBytes(bytes)); + } + function scalarMult(scalar, u) { + const pointU = decodeUCoordinate(u); + const _scalar = decodeScalar(scalar); + const pu = montgomeryLadder(pointU, _scalar); + // The result was not contributory + // https://cr.yp.to/ecdh.html#validate + if (pu === _0n) + throw new Error('Invalid private or public key received'); + return encodeUCoordinate(pu); + } + // Computes public key from private. By doing scalar multiplication of base point. + const GuBytes = encodeUCoordinate(CURVE.Gu); + function scalarMultBase(scalar) { + return scalarMult(scalar, GuBytes); + } + return { + scalarMult, + scalarMultBase, + getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey), + getPublicKey: (privateKey) => scalarMultBase(privateKey), + utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) }, + GuBytes: GuBytes, + }; +} +exports.montgomery = montgomery; +//# sourceMappingURL=montgomery.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/montgomery.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/montgomery.js.map new file mode 100644 index 0000000..1aa0c9e --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/montgomery.js.map @@ -0,0 +1 @@ +{"version":3,"file":"montgomery.js","sourceRoot":"","sources":["../src/abstract/montgomery.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,6CAAwC;AACxC,yCAA2F;AAE3F,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAwBtB,SAAS,YAAY,CAAC,KAAgB;IACpC,IAAA,yBAAc,EACZ,KAAK,EACL;QACE,CAAC,EAAE,QAAQ;KACZ,EACD;QACE,cAAc,EAAE,eAAe;QAC/B,WAAW,EAAE,eAAe;QAC5B,iBAAiB,EAAE,UAAU;QAC7B,MAAM,EAAE,UAAU;QAClB,UAAU,EAAE,UAAU;QACtB,EAAE,EAAE,QAAQ;KACb,CACF,CAAC;IACF,eAAe;IACf,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,KAAK,EAAW,CAAC,CAAC;AAC9C,CAAC;AAED,4IAA4I;AAC5I,0CAA0C;AAC1C,SAAgB,UAAU,CAAC,QAAmB;IAC5C,MAAM,KAAK,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAC;IACrC,MAAM,EAAE,CAAC,EAAE,GAAG,KAAK,CAAC;IACpB,MAAM,IAAI,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,IAAA,gBAAG,EAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IACtC,MAAM,cAAc,GAAG,KAAK,CAAC,cAAc,CAAC;IAC5C,MAAM,eAAe,GAAG,IAAI,CAAC,IAAI,CAAC,cAAc,GAAG,CAAC,CAAC,CAAC;IACtD,MAAM,QAAQ,GAAG,KAAK,CAAC,WAAW,CAAC;IACnC,MAAM,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ACd,eAAe,EAAE,CAAC,UAAe,EAAE,SAAc,EAAE,EAAE,CAAC,UAAU,CAAC,UAAU,EAAE,SAAS,CAAC;QACvF,YAAY,EAAE,CAAC,UAAe,EAAc,EAAE,CAAC,cAAc,CAAC,UAAU,CAAC;QACzE,KAAK,EAAE,EAAE,gBAAgB,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,WAAY,CAAC,KAAK,CAAC,WAAW,CAAC,EAAE;QACxE,OAAO,EAAE,OAAO;KACjB,CAAC;AACJ,CAAC;AA1ID,gCA0IC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/poseidon.d.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/poseidon.d.ts new file mode 100644 index 0000000..2f9ab81 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/poseidon.d.ts @@ -0,0 +1,30 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { IField } from './modular.js'; +export type PoseidonOpts = { + Fp: IField; + t: number; + roundsFull: number; + roundsPartial: number; + sboxPower?: number; + reversePartialPowIdx?: boolean; + mds: bigint[][]; + roundConstants: bigint[][]; +}; +export declare function validateOpts(opts: PoseidonOpts): Readonly<{ + rounds: number; + sboxFn: (n: bigint) => bigint; + roundConstants: bigint[][]; + mds: bigint[][]; + Fp: IField; + t: number; + roundsFull: number; + roundsPartial: number; + sboxPower?: number | undefined; + reversePartialPowIdx?: boolean | undefined; +}>; +export declare function splitConstants(rc: bigint[], t: number): bigint[][]; +export declare function poseidon(opts: PoseidonOpts): { + (values: bigint[]): bigint[]; + roundConstants: bigint[][]; +}; +//# sourceMappingURL=poseidon.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/poseidon.d.ts.map b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/poseidon.d.ts.map new file mode 100644 index 0000000..7107b83 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/poseidon.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"poseidon.d.ts","sourceRoot":"","sources":["../src/abstract/poseidon.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,OAAO,EAAE,MAAM,EAAwB,MAAM,cAAc,CAAC;AAG5D,MAAM,MAAM,YAAY,GAAG;IACzB,EAAE,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;IACnB,CAAC,EAAE,MAAM,CAAC;IACV,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,GAAG,EAAE,MAAM,EAAE,EAAE,CAAC;IAChB,cAAc,EAAE,MAAM,EAAE,EAAE,CAAC;CAC5B,CAAC;AAEF,wBAAgB,YAAY,CAAC,IAAI,EAAE,YAAY;;gBAgB5B,MAAM;;;;;;;;;GAgCxB;AAED,wBAAgB,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,cAarD;AAED,wBAAgB,QAAQ,CAAC,IAAI,EAAE,YAAY;aAeU,MAAM,EAAE;;EAsB5D"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/poseidon.js b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/poseidon.js new file mode 100644 index 0000000..fc66916 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/poseidon.js @@ -0,0 +1,116 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.poseidon = exports.splitConstants = exports.validateOpts = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Poseidon Hash: https://eprint.iacr.org/2019/458.pdf, https://www.poseidon-hash.info +const modular_js_1 = require("./modular.js"); +function validateOpts(opts) { + const { Fp } = opts; + (0, modular_js_1.validateField)(Fp); + for (const i of ['t', 'roundsFull', 'roundsPartial']) { + if (typeof opts[i] !== 'number' || !Number.isSafeInteger(opts[i])) + throw new Error(`Poseidon: invalid param ${i}=${opts[i]} (${typeof opts[i]})`); + } + if (opts.reversePartialPowIdx !== undefined && typeof opts.reversePartialPowIdx !== 'boolean') + throw new Error(`Poseidon: invalid param reversePartialPowIdx=${opts.reversePartialPowIdx}`); + // Default is 5, but by some reasons stark uses 3 + let sboxPower = opts.sboxPower; + if (sboxPower === undefined) + sboxPower = 5; + if (typeof sboxPower !== 'number' || !Number.isSafeInteger(sboxPower)) + throw new Error(`Poseidon wrong sboxPower=${sboxPower}`); + const _sboxPower = BigInt(sboxPower); + let sboxFn = (n) => (0, modular_js_1.FpPow)(Fp, n, _sboxPower); + // Unwrapped sbox power for common cases (195->142μs) + if (sboxPower === 3) + sboxFn = (n) => Fp.mul(Fp.sqrN(n), n); + else if (sboxPower === 5) + sboxFn = (n) => Fp.mul(Fp.sqrN(Fp.sqrN(n)), n); + if (opts.roundsFull % 2 !== 0) + throw new Error(`Poseidon roundsFull is not even: ${opts.roundsFull}`); + const rounds = opts.roundsFull + opts.roundsPartial; + if (!Array.isArray(opts.roundConstants) || opts.roundConstants.length !== rounds) + throw new Error('Poseidon: wrong round constants'); + const roundConstants = opts.roundConstants.map((rc) => { + if (!Array.isArray(rc) || rc.length !== opts.t) + throw new Error(`Poseidon wrong round constants: ${rc}`); + return rc.map((i) => { + if (typeof i !== 'bigint' || !Fp.isValid(i)) + throw new Error(`Poseidon wrong round constant=${i}`); + return Fp.create(i); + }); + }); + // MDS is TxT matrix + if (!Array.isArray(opts.mds) || opts.mds.length !== opts.t) + throw new Error('Poseidon: wrong MDS matrix'); + const mds = opts.mds.map((mdsRow) => { + if (!Array.isArray(mdsRow) || mdsRow.length !== opts.t) + throw new Error(`Poseidon MDS matrix row: ${mdsRow}`); + return mdsRow.map((i) => { + if (typeof i !== 'bigint') + throw new Error(`Poseidon MDS matrix value=${i}`); + return Fp.create(i); + }); + }); + return Object.freeze({ ...opts, rounds, sboxFn, roundConstants, mds }); +} +exports.validateOpts = validateOpts; +function splitConstants(rc, t) { + if (typeof t !== 'number') + throw new Error('poseidonSplitConstants: wrong t'); + if (!Array.isArray(rc) || rc.length % t) + throw new Error('poseidonSplitConstants: wrong rc'); + const res = []; + let tmp = []; + for (let i = 0; i < rc.length; i++) { + tmp.push(rc[i]); + if (tmp.length === t) { + res.push(tmp); + tmp = []; + } + } + return res; +} +exports.splitConstants = splitConstants; +function poseidon(opts) { + const { t, Fp, rounds, sboxFn, reversePartialPowIdx } = validateOpts(opts); + const halfRoundsFull = Math.floor(opts.roundsFull / 2); + const partialIdx = reversePartialPowIdx ? t - 1 : 0; + const poseidonRound = (values, isFull, idx) => { + values = values.map((i, j) => Fp.add(i, opts.roundConstants[idx][j])); + if (isFull) + values = values.map((i) => sboxFn(i)); + else + values[partialIdx] = sboxFn(values[partialIdx]); + // Matrix multiplication + values = opts.mds.map((i) => i.reduce((acc, i, j) => Fp.add(acc, Fp.mulN(i, values[j])), Fp.ZERO)); + return values; + }; + const poseidonHash = function poseidonHash(values) { + if (!Array.isArray(values) || values.length !== t) + throw new Error(`Poseidon: wrong values (expected array of bigints with length ${t})`); + values = values.map((i) => { + if (typeof i !== 'bigint') + throw new Error(`Poseidon: wrong value=${i} (${typeof i})`); + return Fp.create(i); + }); + let round = 0; + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) + values = poseidonRound(values, true, round++); + // Apply r_p partial rounds. + for (let i = 0; i < opts.roundsPartial; i++) + values = poseidonRound(values, false, round++); + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) + values = poseidonRound(values, true, round++); + if (round !== rounds) + throw new Error(`Poseidon: wrong number of rounds: last round=${round}, total=${rounds}`); + return values; + }; + // For verification in tests + poseidonHash.roundConstants = opts.roundConstants; + return poseidonHash; +} +exports.poseidon = poseidon; +//# sourceMappingURL=poseidon.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/poseidon.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/poseidon.js.map new file mode 100644 index 0000000..422866d --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/poseidon.js.map @@ -0,0 +1 @@ +{"version":3,"file":"poseidon.js","sourceRoot":"","sources":["../src/abstract/poseidon.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,sFAAsF;AACtF,6CAA4D;AAc5D,SAAgB,YAAY,CAAC,IAAkB;IAC7C,MAAM,EAAE,EAAE,EAAE,GAAG,IAAI,CAAC;IACpB,IAAA,0BAAa,EAAC,EAAE,CAAC,CAAC;IAClB,KAAK,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,YAAY,EAAE,eAAe,CAAU,EAAE;QAC7D,IAAI,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAC/D,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,OAAO,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;KAClF;IACD,IAAI,IAAI,CAAC,oBAAoB,KAAK,SAAS,IAAI,OAAO,IAAI,CAAC,oBAAoB,KAAK,SAAS;QAC3F,MAAM,IAAI,KAAK,CAAC,gDAAgD,IAAI,CAAC,oBAAoB,EAAE,CAAC,CAAC;IAC/F,iDAAiD;IACjD,IAAI,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;IAC/B,IAAI,SAAS,KAAK,SAAS;QAAE,SAAS,GAAG,CAAC,CAAC;IAC3C,IAAI,OAAO,SAAS,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,SAAS,CAAC;QACnE,MAAM,IAAI,KAAK,CAAC,4BAA4B,SAAS,EAAE,CAAC,CAAC;IAE3D,MAAM,UAAU,GAAG,MAAM,CAAC,SAAS,CAAC,CAA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,MAAM,GAAG,aAAa,CAAC,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;QAC5F,2BAA2B;QAC3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,cAAc,EAAE,CAAC,EAAE;YAAE,MAAM,GAAG,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;QAEvF,IAAI,KAAK,KAAK,MAAM;YAClB,MAAM,IAAI,KAAK,CAAC,gDAAgD,KAAK,WAAW,MAAM,EAAE,CAAC,CAAC;QAC5F,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IACF,4BAA4B;IAC5B,YAAY,CAAC,cAAc,GAAG,IAAI,CAAC,cAAc,CAAC;IAClD,OAAO,YAAY,CAAC;AACtB,CAAC;AArCD,4BAqCC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/utils.d.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/utils.d.ts new file mode 100644 index 0000000..2842612 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/utils.d.ts @@ -0,0 +1,91 @@ +export type Hex = Uint8Array | string; +export type PrivKey = Hex | bigint; +export type CHash = { + (message: Uint8Array | string): Uint8Array; + blockLen: number; + outputLen: number; + create(opts?: { + dkLen?: number; + }): any; +}; +export type FHash = (message: Uint8Array | string) => Uint8Array; +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export declare function bytesToHex(bytes: Uint8Array): string; +export declare function numberToHexUnpadded(num: number | bigint): string; +export declare function hexToNumber(hex: string): bigint; +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export declare function hexToBytes(hex: string): Uint8Array; +export declare function bytesToNumberBE(bytes: Uint8Array): bigint; +export declare function bytesToNumberLE(bytes: Uint8Array): bigint; +export declare function numberToBytesBE(n: number | bigint, len: number): Uint8Array; +export declare function numberToBytesLE(n: number | bigint, len: number): Uint8Array; +export declare function numberToVarBytesBE(n: number | bigint): Uint8Array; +/** + * Takes hex string or Uint8Array, converts to Uint8Array. + * Validates output length. + * Will throw error for other types. + * @param title descriptive title for an error e.g. 'private key' + * @param hex hex string or Uint8Array + * @param expectedLength optional, will compare to result array's length + * @returns + */ +export declare function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array; +/** + * Copies several Uint8Arrays into one. + */ +export declare function concatBytes(...arrays: Uint8Array[]): Uint8Array; +export declare function equalBytes(b1: Uint8Array, b2: Uint8Array): boolean; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export declare function utf8ToBytes(str: string): Uint8Array; +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + */ +export declare function bitLen(n: bigint): number; +/** + * Gets single bit at position. + * NOTE: first bit position is 0 (same as arrays) + * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` + */ +export declare function bitGet(n: bigint, pos: number): bigint; +/** + * Sets single bit at position. + */ +export declare const bitSet: (n: bigint, pos: number, value: boolean) => bigint; +/** + * Calculate mask for N bits. Not using ** operator with bigints because of old engines. + * Same as BigInt(`0b${Array(i).fill('1').join('')}`) + */ +export declare const bitMask: (n: number) => bigint; +type Pred = (v: Uint8Array) => T | undefined; +/** + * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + * @returns function that will call DRBG until 2nd arg returns something meaningful + * @example + * const drbg = createHmacDRBG(32, 32, hmac); + * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined + */ +export declare function createHmacDrbg(hashLen: number, qByteLen: number, hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array): (seed: Uint8Array, predicate: Pred) => T; +declare const validatorFns: { + readonly bigint: (val: any) => boolean; + readonly function: (val: any) => boolean; + readonly boolean: (val: any) => boolean; + readonly string: (val: any) => boolean; + readonly isSafeInteger: (val: any) => boolean; + readonly array: (val: any) => boolean; + readonly field: (val: any, object: any) => any; + readonly hash: (val: any) => boolean; +}; +type Validator = keyof typeof validatorFns; +type ValMap> = { + [K in keyof T]?: Validator; +}; +export declare function validateObject>(object: T, validators: ValMap, optValidators?: ValMap): T; +export {}; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/utils.d.ts.map b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/utils.d.ts.map new file mode 100644 index 0000000..706d651 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/abstract/utils.ts"],"names":[],"mappings":"AASA,MAAM,MAAM,GAAG,GAAG,UAAU,GAAG,MAAM,CAAC;AACtC,MAAM,MAAM,OAAO,GAAG,GAAG,GAAG,MAAM,CAAC;AACnC,MAAM,MAAM,KAAK,GAAG;IAClB,CAAC,OAAO,EAAE,UAAU,GAAG,MAAM,GAAG,UAAU,CAAC;IAC3C,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,IAAI,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,GAAG,CAAC;CACxC,CAAC;AACF,MAAM,MAAM,KAAK,GAAG,CAAC,OAAO,EAAE,UAAU,GAAG,MAAM,KAAK,UAAU,CAAC;AAGjE;;GAEG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAQpD;AAED,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAGhE;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAI/C;AAED;;GAEG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAalD;AAGD,wBAAgB,eAAe,CAAC,KAAK,EAAE,UAA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M,EAAE,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,QAAQ,EAAE,UAAU,EAAE,KAAK,UAAU,GACjE,CAAC,IAAI,EAAE,UAAU,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CA4C7C;AAID,QAAA,MAAM,YAAY;2BACF,GAAG;6BACD,GAAG;4BACJ,GAAG;2BACJ,GAAG;kCACI,GAAG;0BACX,GAAG;0BACH,GAAG,UAAU,GAAG;yBACjB,GAAG;CACP,CAAC;AACX,KAAK,SAAS,GAAG,MAAM,OAAO,YAAY,CAAC;AAC3C,KAAK,MAAM,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI;KAAG,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,EAAE,SAAS;CAAE,CAAC;AAG5E,wBAAgB,cAAc,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAC1D,MAAM,EAAE,CAAC,EACT,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC,EACrB,aAAa,GAAE,MAAM,CAAC,CAAC,CAAM,KAkB9B"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/utils.js b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/utils.js new file mode 100644 index 0000000..60774c4 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/utils.js @@ -0,0 +1,287 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateObject = exports.createHmacDrbg = exports.bitMask = exports.bitSet = exports.bitGet = exports.bitLen = exports.utf8ToBytes = exports.equalBytes = exports.concatBytes = exports.ensureBytes = exports.numberToVarBytesBE = exports.numberToBytesLE = exports.numberToBytesBE = exports.bytesToNumberLE = exports.bytesToNumberBE = exports.hexToBytes = exports.hexToNumber = exports.numberToHexUnpadded = exports.bytesToHex = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// 100 lines of code in the file are duplicated from noble-hashes (utils). +// This is OK: `abstract` directory does not use noble-hashes. +// User may opt-in into using different hashing library. This way, noble-hashes +// won't be included into their bundle. +const _0n = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +const u8a = (a) => a instanceof Uint8Array; +const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +function bytesToHex(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +exports.bytesToHex = bytesToHex; +function numberToHexUnpadded(num) { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; +} +exports.numberToHexUnpadded = numberToHexUnpadded; +function hexToNumber(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + // Big Endian + return BigInt(hex === '' ? '0' : `0x${hex}`); +} +exports.hexToNumber = hexToNumber; +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} +exports.hexToBytes = hexToBytes; +// BE: Big Endian, LE: Little Endian +function bytesToNumberBE(bytes) { + return hexToNumber(bytesToHex(bytes)); +} +exports.bytesToNumberBE = bytesToNumberBE; +function bytesToNumberLE(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); +} +exports.bytesToNumberLE = bytesToNumberLE; +function numberToBytesBE(n, len) { + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} +exports.numberToBytesBE = numberToBytesBE; +function numberToBytesLE(n, len) { + return numberToBytesBE(n, len).reverse(); +} +exports.numberToBytesLE = numberToBytesLE; +// Unpadded, rarely used +function numberToVarBytesBE(n) { + return hexToBytes(numberToHexUnpadded(n)); +} +exports.numberToVarBytesBE = numberToVarBytesBE; +/** + * Takes hex string or Uint8Array, converts to Uint8Array. + * Validates output length. + * Will throw error for other types. + * @param title descriptive title for an error e.g. 'private key' + * @param hex hex string or Uint8Array + * @param expectedLength optional, will compare to result array's length + * @returns + */ +function ensureBytes(title, hex, expectedLength) { + let res; + if (typeof hex === 'string') { + try { + res = hexToBytes(hex); + } + catch (e) { + throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`); + } + } + else if (u8a(hex)) { + // Uint8Array.from() instead of hash.slice() because node.js Buffer + // is instance of Uint8Array, and its slice() creates **mutable** copy + res = Uint8Array.from(hex); + } + else { + throw new Error(`${title} must be hex string or Uint8Array`); + } + const len = res.length; + if (typeof expectedLength === 'number' && len !== expectedLength) + throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); + return res; +} +exports.ensureBytes = ensureBytes; +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) + throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} +exports.concatBytes = concatBytes; +function equalBytes(b1, b2) { + // We don't care about timing attacks here + if (b1.length !== b2.length) + return false; + for (let i = 0; i < b1.length; i++) + if (b1[i] !== b2[i]) + return false; + return true; +} +exports.equalBytes = equalBytes; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +exports.utf8ToBytes = utf8ToBytes; +// Bit operations +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + */ +function bitLen(n) { + let len; + for (len = 0; n > _0n; n >>= _1n, len += 1) + ; + return len; +} +exports.bitLen = bitLen; +/** + * Gets single bit at position. + * NOTE: first bit position is 0 (same as arrays) + * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` + */ +function bitGet(n, pos) { + return (n >> BigInt(pos)) & _1n; +} +exports.bitGet = bitGet; +/** + * Sets single bit at position. + */ +const bitSet = (n, pos, value) => { + return n | ((value ? _1n : _0n) << BigInt(pos)); +}; +exports.bitSet = bitSet; +/** + * Calculate mask for N bits. Not using ** operator with bigints because of old engines. + * Same as BigInt(`0b${Array(i).fill('1').join('')}`) + */ +const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n; +exports.bitMask = bitMask; +// DRBG +const u8n = (data) => new Uint8Array(data); // creates Uint8Array +const u8fr = (arr) => Uint8Array.from(arr); // another shortcut +/** + * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + * @returns function that will call DRBG until 2nd arg returns something meaningful + * @example + * const drbg = createHmacDRBG(32, 32, hmac); + * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined + */ +function createHmacDrbg(hashLen, qByteLen, hmacFn) { + if (typeof hashLen !== 'number' || hashLen < 2) + throw new Error('hashLen must be a number'); + if (typeof qByteLen !== 'number' || qByteLen < 2) + throw new Error('qByteLen must be a number'); + if (typeof hmacFn !== 'function') + throw new Error('hmacFn must be a function'); + // Step B, Step C: set hashLen to 8*ceil(hlen/8) + let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same + let i = 0; // Iterations counter, will throw when over 1000 + const reset = () => { + v.fill(1); + k.fill(0); + i = 0; + }; + const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values) + const reseed = (seed = u8n()) => { + // HMAC-DRBG reseed() function. Steps D-G + k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed) + v = h(); // v = hmac(k || v) + if (seed.length === 0) + return; + k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed) + v = h(); // v = hmac(k || v) + }; + const gen = () => { + // HMAC-DRBG generate() function + if (i++ >= 1000) + throw new Error('drbg: tried 1000 values'); + let len = 0; + const out = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes(...out); + }; + const genUntil = (seed, pred) => { + reset(); + reseed(seed); // Steps D-G + let res = undefined; // Step H: grind until k is in [1..n-1] + while (!(res = pred(gen()))) + reseed(); + reset(); + return res; + }; + return genUntil; +} +exports.createHmacDrbg = createHmacDrbg; +// Validating curves and fields +const validatorFns = { + bigint: (val) => typeof val === 'bigint', + function: (val) => typeof val === 'function', + boolean: (val) => typeof val === 'boolean', + string: (val) => typeof val === 'string', + isSafeInteger: (val) => Number.isSafeInteger(val), + array: (val) => Array.isArray(val), + field: (val, object) => object.Fp.isValid(val), + hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen), +}; +// type Record = { [P in K]: T; } +function validateObject(object, validators, optValidators = {}) { + const checkField = (fieldName, type, isOptional) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== 'function') + throw new Error(`Invalid validator "${type}", expected function`); + const val = object[fieldName]; + if (isOptional && val === undefined) + return; + if (!checkVal(val, object)) { + throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); + } + }; + for (const [fieldName, type] of Object.entries(validators)) + checkField(fieldName, type, false); + for (const [fieldName, type] of Object.entries(optValidators)) + checkField(fieldName, type, true); + return object; +} +exports.validateObject = validateObject; +// validate type tests +// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 }; +// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok! +// // Should fail type-check +// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' }); +// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' }); +// const z3 = validateObject(o, { test: 'boolean', z: 'bug' }); +// const z4 = validateObject(o, { a: 'boolean', z: 'bug' }); +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/utils.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/utils.js.map new file mode 100644 index 0000000..c60d8a8 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/abstract/utils.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,0EAA0E;AAC1E,8DAA8D;AAC9D,+EAA+E;AAC/E,uCAAuC;AACvC,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,CAAC,CAAM,EAAmB,EAAE,CAAC,CAAC,YAAY,UAAU,CAAC;AAWjE,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;AACrF;;GAEG;AACH,SAAgB,UAAU,CAAC,KAAiB;IAC1C,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;IACxD,oCAAoC;IACpC,IAAI,GAAG,GAAG,EAAE,CAAC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CAAC;CAC5E,CAAC;AAGX,wEAAwE;AAExE,SAAgB,cAAc,CAC5B,MAAS,EACT,UAAqB,EACrB,gBAA2B,EAAE;IAE7B,MAAM,UAAU,GAAG,CAAC,SAAkB,EAAE,IAAe,EAAE,UAAmB,EAAE,EAAE;QAC9E,MAAM,QAAQ,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC;QACpC,IAAI,OAAO,QAAQ,KAAK,UAAU;YAChC,MAAM,IAAI,KAAK,CAAC,sBAAsB,IAAI,sBAAsB,CAAC,CAAC;QAEpE,MAAM,GAAG,GAAG,MAAM,CAAC,SAAgC,CAAC,CAAC;QACrD,IAAI,UAAU,IAAI,GAAG,KAAK,SAAS;YAAE,OAAO;QAC5C,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE;YAC1B,MAAM,IAAI,KAAK,CACb,iBAAiB,MAAM,CAAC,SAAS,CAAC,IAAI,GAAG,KAAK,OAAO,GAAG,eAAe,IAAI,EAAE,CAC9E,CAAC;SACH;IACH,CAAC,CAAC;IACF,KAAK,MAAM,CAAC,SAAS,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC;QAAE,UAAU,CAAC,SAAS,EAAE,IAAK,EAAE,KAAK,CAAC,CAAC;IAChG,KAAK,MAAM,CAAC,SAAS,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC;QAAE,UAAU,CAAC,SAAS,EAAE,IAAK,EAAE,IAAI,CAAC,CAAC;IAClG,OAAO,MAAM,CAAC;AAChB,CAAC;AArBD,wCAqBC;AACD,sBAAsB;AACtB,uEAAuE;AACvE,gFAAgF;AAChF,4BAA4B;AAC5B,2DAA2D;AAC3D,qEAAqE;AACrE,+DAA+D;AAC/D,4DAA4D"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/weierstrass.d.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/weierstrass.d.ts new file mode 100644 index 0000000..53449c5 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/weierstrass.d.ts @@ -0,0 +1,240 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import * as mod from './modular.js'; +import * as ut from './utils.js'; +import { CHash, Hex, PrivKey } from './utils.js'; +import { Group, GroupConstructor, BasicCurve, AffinePoint } from './curve.js'; +export type { AffinePoint }; +type HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; +type EndomorphismOpts = { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; +}; +export type BasicWCurve = BasicCurve & { + a: T; + b: T; + allowedPrivateKeyLengths?: readonly number[]; + wrapPrivateKey?: boolean; + endo?: EndomorphismOpts; + isTorsionFree?: (c: ProjConstructor, point: ProjPointType) => boolean; + clearCofactor?: (c: ProjConstructor, point: ProjPointType) => ProjPointType; +}; +type Entropy = Hex | true; +export type SignOpts = { + lowS?: boolean; + extraEntropy?: Entropy; + prehash?: boolean; +}; +export type VerOpts = { + lowS?: boolean; + prehash?: boolean; +}; +/** + * ### Design rationale for types + * + * * Interaction between classes from different curves should fail: + * `k256.Point.BASE.add(p256.Point.BASE)` + * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime + * * Different calls of `curve()` would return different classes - + * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve, + * it won't affect others + * + * TypeScript can't infer types for classes created inside a function. Classes is one instance of nominative types in TypeScript and interfaces only check for shape, so it's hard to create unique type for every function call. + * + * We can use generic types via some param, like curve opts, but that would: + * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params) + * which is hard to debug. + * 2. Params can be generic and we can't enforce them to be constant value: + * if somebody creates curve from non-constant params, + * it would be allowed to interact with other curves with non-constant params + * + * TODO: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol + */ +export interface ProjPointType extends Group> { + readonly px: T; + readonly py: T; + readonly pz: T; + get x(): T; + get y(): T; + multiply(scalar: bigint): ProjPointType; + toAffine(iz?: T): AffinePoint; + isTorsionFree(): boolean; + clearCofactor(): ProjPointType; + assertValidity(): void; + hasEvenY(): boolean; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; + multiplyUnsafe(scalar: bigint): ProjPointType; + multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined; + _setWindowSize(windowSize: number): void; +} +export interface ProjConstructor extends GroupConstructor> { + new (x: T, y: T, z: T): ProjPointType; + fromAffine(p: AffinePoint): ProjPointType; + fromHex(hex: Hex): ProjPointType; + fromPrivateKey(privateKey: PrivKey): ProjPointType; + normalizeZ(points: ProjPointType[]): ProjPointType[]; +} +export type CurvePointsType = BasicWCurve & { + fromBytes?: (bytes: Uint8Array) => AffinePoint; + toBytes?: (c: ProjConstructor, point: ProjPointType, isCompressed: boolean) => Uint8Array; +}; +export type CurvePointsRes = { + ProjectivePoint: ProjConstructor; + normPrivateKeyToScalar: (key: PrivKey) => bigint; + weierstrassEquation: (x: T) => T; + isWithinCurveOrder: (num: bigint) => boolean; +}; +export declare const DER: { + Err: { + new (m?: string): { + name: string; + message: string; + stack?: string | undefined; + }; + }; + _parseInt(data: Uint8Array): { + d: bigint; + l: Uint8Array; + }; + toSig(hex: string | Uint8Array): { + r: bigint; + s: bigint; + }; + hexFromSig(sig: { + r: bigint; + s: bigint; + }): string; +}; +export declare function weierstrassPoints(opts: CurvePointsType): { + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: mod.IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: T; + readonly Gy: T; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: T; + readonly b: T; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: EndomorphismOpts | undefined; + readonly isTorsionFree?: ((c: ProjConstructor, point: ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: ProjConstructor, point: ProjPointType) => ProjPointType) | undefined; + readonly fromBytes?: ((bytes: Uint8Array) => AffinePoint) | undefined; + readonly toBytes?: ((c: ProjConstructor, point: ProjPointType, isCompressed: boolean) => Uint8Array) | undefined; + readonly p: bigint; + }>; + ProjectivePoint: ProjConstructor; + normPrivateKeyToScalar: (key: PrivKey) => bigint; + weierstrassEquation: (x: T) => T; + isWithinCurveOrder: (num: bigint) => boolean; +}; +export interface SignatureType { + readonly r: bigint; + readonly s: bigint; + readonly recovery?: number; + assertValidity(): void; + addRecoveryBit(recovery: number): RecoveredSignatureType; + hasHighS(): boolean; + normalizeS(): SignatureType; + recoverPublicKey(msgHash: Hex): ProjPointType; + toCompactRawBytes(): Uint8Array; + toCompactHex(): string; + toDERRawBytes(isCompressed?: boolean): Uint8Array; + toDERHex(isCompressed?: boolean): string; +} +export type RecoveredSignatureType = SignatureType & { + readonly recovery: number; +}; +export type SignatureConstructor = { + new (r: bigint, s: bigint): SignatureType; + fromCompact(hex: Hex): SignatureType; + fromDER(hex: Hex): SignatureType; +}; +type SignatureLike = { + r: bigint; + s: bigint; +}; +export type PubKey = Hex | ProjPointType; +export type CurveType = BasicWCurve & { + hash: CHash; + hmac: HmacFnSync; + randomBytes: (bytesLength?: number) => Uint8Array; + lowS?: boolean; + bits2int?: (bytes: Uint8Array) => bigint; + bits2int_modN?: (bytes: Uint8Array) => bigint; +}; +declare function validateOpts(curve: CurveType): Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: mod.IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: EndomorphismOpts | undefined; + readonly isTorsionFree?: ((c: ProjConstructor, point: ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: ProjConstructor, point: ProjPointType) => ProjPointType) | undefined; + readonly hash: ut.CHash; + readonly hmac: HmacFnSync; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; +}>; +export type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType; + verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean; + ProjectivePoint: ProjConstructor; + Signature: SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: PrivKey) => bigint; + isValidPrivateKey(privateKey: PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: ProjPointType) => ProjPointType; + }; +}; +export declare function weierstrass(curveDef: CurveType): CurveFn; +/** + * Implementation of the Shallue and van de Woestijne method for any weierstrass curve. + * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular. + * b = True and y = sqrt(u / v) if (u / v) is square in F, and + * b = False and y = sqrt(Z * (u / v)) otherwise. + * @param Fp + * @param Z + * @returns + */ +export declare function SWUFpSqrtRatio(Fp: mod.IField, Z: T): (u: T, v: T) => { + isValid: boolean; + value: T; +}; +/** + * From draft-irtf-cfrg-hash-to-curve-16 + */ +export declare function mapToCurveSimpleSWU(Fp: mod.IField, opts: { + A: T; + B: T; + Z: T; +}): (u: T) => { + x: T; + y: T; +}; +//# sourceMappingURL=weierstrass.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/weierstrass.d.ts.map b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/weierstrass.d.ts.map new file mode 100644 index 0000000..ef26890 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/weierstrass.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"weierstrass.d.ts","sourceRoot":"","sources":["../src/abstract/weierstrass.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AACjC,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,EAAe,MAAM,YAAY,CAAC;AAC9D,OAAO,EAAE,KAAK,EAAE,gBAAgB,EAAQ,UAAU,EAAiB,WAAW,EAAE,MAAM,YAAY,CAAC;AAEnG,YAAY,EAAE,WAAW,EAAE,CAAC;AAC5B,KAAK,UAAU,GAAG,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,QAAQ,EAAE,UAAU,EAAE,KAAK,UAAU,CAAC;AAC7E,KAAK,gBAAgB,GAAG;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK;QAAE,KAAK,EAAE,OAAO,CAAC;QAAC,EAAE,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,OAAO,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC;CACxF,CAAC;AACF,MAAM,MAAM,WAAW,CAAC,CAAC,IAAI,UAAU,CAAC,CAAC,CAAC,GAAG;IAE3C,CAAC,EAAE,CAAC,CAAC;IACL,CAAC,EAAE,CAAC,CAAC;IAGL,wBAAwB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC7C,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,IAAI,CAAC,EAAE,gBAAgB,CAAC;IAGxB,aAAa,CAAC,EAAE,CAAC,CAAC,EAAE,eAAe,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,aAAa,CAAC,CAAC,CAAC,KAAK,OAAO,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,CAAC;OAAK,CAAC;EA8B5B"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/weierstrass.js b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/weierstrass.js new file mode 100644 index 0000000..b24bfbf --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/weierstrass.js @@ -0,0 +1,1061 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.mapToCurveSimpleSWU = exports.SWUFpSqrtRatio = exports.weierstrass = exports.weierstrassPoints = exports.DER = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Short Weierstrass curve. The formula is: y² = x³ + ax + b +const mod = require("./modular.js"); +const ut = require("./utils.js"); +const utils_js_1 = require("./utils.js"); +const curve_js_1 = require("./curve.js"); +function validatePointOpts(curve) { + const opts = (0, curve_js_1.validateBasic)(curve); + ut.validateObject(opts, { + a: 'field', + b: 'field', + }, { + allowedPrivateKeyLengths: 'array', + wrapPrivateKey: 'boolean', + isTorsionFree: 'function', + clearCofactor: 'function', + allowInfinityPoint: 'boolean', + fromBytes: 'function', + toBytes: 'function', + }); + const { endo, Fp, a } = opts; + if (endo) { + if (!Fp.eql(a, Fp.ZERO)) { + throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0'); + } + if (typeof endo !== 'object' || + typeof endo.beta !== 'bigint' || + typeof endo.splitScalar !== 'function') { + throw new Error('Expected endomorphism with beta: bigint and splitScalar: function'); + } + } + return Object.freeze({ ...opts }); +} +// ASN.1 DER encoding utilities +const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; +exports.DER = { + // asn.1 DER encoding utils + Err: class DERErr extends Error { + constructor(m = '') { + super(m); + } + }, + _parseInt(data) { + const { Err: E } = exports.DER; + if (data.length < 2 || data[0] !== 0x02) + throw new E('Invalid signature integer tag'); + const len = data[1]; + const res = data.subarray(2, len + 2); + if (!len || res.length !== len) + throw new E('Invalid signature integer: wrong length'); + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + if (res[0] & 0b10000000) + throw new E('Invalid signature integer: negative'); + if (res[0] === 0x00 && !(res[1] & 0b10000000)) + throw new E('Invalid signature integer: unnecessary leading zero'); + return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left + }, + toSig(hex) { + // parse DER signature + const { Err: E } = exports.DER; + const data = typeof hex === 'string' ? h2b(hex) : hex; + if (!(data instanceof Uint8Array)) + throw new Error('ui8a expected'); + let l = data.length; + if (l < 2 || data[0] != 0x30) + throw new E('Invalid signature tag'); + if (data[1] !== l - 2) + throw new E('Invalid signature: incorrect length'); + const { d: r, l: sBytes } = exports.DER._parseInt(data.subarray(2)); + const { d: s, l: rBytesLeft } = exports.DER._parseInt(sBytes); + if (rBytesLeft.length) + throw new E('Invalid signature: left bytes after parsing'); + return { r, s }; + }, + hexFromSig(sig) { + // Add leading zero if first byte has negative bit enabled. More details in '_parseInt' + const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s); + const h = (num) => { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; + }; + const s = slice(h(sig.s)); + const r = slice(h(sig.r)); + const shl = s.length / 2; + const rhl = r.length / 2; + const sl = h(shl); + const rl = h(rhl); + return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`; + }, +}; +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4); +function weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ + const toBytes = CURVE.toBytes || + ((c, point, isCompressed) => { + const a = point.toAffine(); + return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y)); + }); + const fromBytes = CURVE.fromBytes || + ((bytes) => { + // const head = bytes[0]; + const tail = bytes.subarray(1); + // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported'); + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + }); + /** + * y² = x³ + ax + b: Short weierstrass curve formula + * @returns y² + */ + function weierstrassEquation(x) { + const { a, b } = CURVE; + const x2 = Fp.sqr(x); // x * x + const x3 = Fp.mul(x2, x); // x2 * x + return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b + } + // Validate whether the passed curve params are valid. + // We check if curve equation works for generator point. + // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381. + // ProjectivePoint class has not been initialized yet. + if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error('bad generator point: equation left != right'); + // Valid group elements reside in range 1..n-1 + function isWithinCurveOrder(num) { + return typeof num === 'bigint' && _0n < num && num < CURVE.n; + } + function assertGE(num) { + if (!isWithinCurveOrder(num)) + throw new Error('Expected valid bigint: 0 < bigint < curve.n'); + } + // Validates if priv key is valid and converts it to bigint. + // Supports options allowedPrivateKeyLengths and wrapPrivateKey. + function normPrivateKeyToScalar(key) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE; + if (lengths && typeof key !== 'bigint') { + if (key instanceof Uint8Array) + key = ut.bytesToHex(key); + // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes + if (typeof key !== 'string' || !lengths.includes(key.length)) + throw new Error('Invalid key'); + key = key.padStart(nByteLength * 2, '0'); + } + let num; + try { + num = + typeof key === 'bigint' + ? key + : ut.bytesToNumberBE((0, utils_js_1.ensureBytes)('private key', key, nByteLength)); + } + catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + } + if (wrapPrivateKey) + num = mod.mod(num, n); // disabled by default, enabled for BLS + assertGE(num); // num in range [1..N-1] + return num; + } + const pointPrecomputes = new Map(); + function assertPrjPoint(other) { + if (!(other instanceof Point)) + throw new Error('ProjectivePoint expected'); + } + /** + * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z) + * Default Point works in 2d / affine coordinates: (x, y) + * We're doing calculations in projective, because its operations don't require costly inversion. + */ + class Point { + constructor(px, py, pz) { + this.px = px; + this.py = py; + this.pz = pz; + if (px == null || !Fp.isValid(px)) + throw new Error('x required'); + if (py == null || !Fp.isValid(py)) + throw new Error('y required'); + if (pz == null || !Fp.isValid(pz)) + throw new Error('z required'); + } + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + static fromAffine(p) { + const { x, y } = p || {}; + if (!p || !Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('invalid affine point'); + if (p instanceof Point) + throw new Error('projective point not allowed'); + const is0 = (i) => Fp.eql(i, Fp.ZERO); + // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0) + if (is0(x) && is0(y)) + return Point.ZERO; + return new Point(x, y, Fp.ONE); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + /** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + */ + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex) { + const P = Point.fromAffine(fromBytes((0, utils_js_1.ensureBytes)('pointHex', hex))); + P.assertValidity(); + return P; + } + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey) { + return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + // A point on curve is valid if it conforms to equation. + assertValidity() { + // Zero is valid point too! + if (this.is0()) { + if (CURVE.allowInfinityPoint) + return; + throw new Error('bad point: ZERO'); + } + // Some 3rd-party test vectors require different wording between here & `fromCompressedHex` + const { x, y } = this.toAffine(); + // Check if x, y are valid field elements + if (!Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('bad point: x or y not FE'); + const left = Fp.sqr(y); // y² + const right = weierstrassEquation(x); // x³ + ax + b + if (!Fp.eql(left, right)) + throw new Error('bad point: equation left != right'); + if (!this.isTorsionFree()) + throw new Error('bad point: not in prime-order subgroup'); + } + hasEvenY() { + const { y } = this.toAffine(); + if (Fp.isOdd) + return !Fp.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + /** + * Compare one point to another. + */ + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); + const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); + return U1 && U2; + } + /** + * Flips point to one corresponding to (x, -y) in Affine coordinates. + */ + negate() { + return new Point(this.px, Fp.neg(this.py), this.pz); + } + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a, b } = CURVE; + const b3 = Fp.mul(b, _3n); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + let t0 = Fp.mul(X1, X1); // step 1 + let t1 = Fp.mul(Y1, Y1); + let t2 = Fp.mul(Z1, Z1); + let t3 = Fp.mul(X1, Y1); + t3 = Fp.add(t3, t3); // step 5 + Z3 = Fp.mul(X1, Z1); + Z3 = Fp.add(Z3, Z3); + X3 = Fp.mul(a, Z3); + Y3 = Fp.mul(b3, t2); + Y3 = Fp.add(X3, Y3); // step 10 + X3 = Fp.sub(t1, Y3); + Y3 = Fp.add(t1, Y3); + Y3 = Fp.mul(X3, Y3); + X3 = Fp.mul(t3, X3); + Z3 = Fp.mul(b3, Z3); // step 15 + t2 = Fp.mul(a, t2); + t3 = Fp.sub(t0, t2); + t3 = Fp.mul(a, t3); + t3 = Fp.add(t3, Z3); + Z3 = Fp.add(t0, t0); // step 20 + t0 = Fp.add(Z3, t0); + t0 = Fp.add(t0, t2); + t0 = Fp.mul(t0, t3); + Y3 = Fp.add(Y3, t0); + t2 = Fp.mul(Y1, Z1); // step 25 + t2 = Fp.add(t2, t2); + t0 = Fp.mul(t2, t3); + X3 = Fp.sub(X3, t0); + Z3 = Fp.mul(t2, t1); + Z3 = Fp.add(Z3, Z3); // step 30 + Z3 = Fp.add(Z3, Z3); + return new Point(X3, Y3, Z3); + } + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + const a = CURVE.a; + const b3 = Fp.mul(CURVE.b, _3n); + let t0 = Fp.mul(X1, X2); // step 1 + let t1 = Fp.mul(Y1, Y2); + let t2 = Fp.mul(Z1, Z2); + let t3 = Fp.add(X1, Y1); + let t4 = Fp.add(X2, Y2); // step 5 + t3 = Fp.mul(t3, t4); + t4 = Fp.add(t0, t1); + t3 = Fp.sub(t3, t4); + t4 = Fp.add(X1, Z1); + let t5 = Fp.add(X2, Z2); // step 10 + t4 = Fp.mul(t4, t5); + t5 = Fp.add(t0, t2); + t4 = Fp.sub(t4, t5); + t5 = Fp.add(Y1, Z1); + X3 = Fp.add(Y2, Z2); // step 15 + t5 = Fp.mul(t5, X3); + X3 = Fp.add(t1, t2); + t5 = Fp.sub(t5, X3); + Z3 = Fp.mul(a, t4); + X3 = Fp.mul(b3, t2); // step 20 + Z3 = Fp.add(X3, Z3); + X3 = Fp.sub(t1, Z3); + Z3 = Fp.add(t1, Z3); + Y3 = Fp.mul(X3, Z3); + t1 = Fp.add(t0, t0); // step 25 + t1 = Fp.add(t1, t0); + t2 = Fp.mul(a, t2); + t4 = Fp.mul(b3, t4); + t1 = Fp.add(t1, t2); + t2 = Fp.sub(t0, t2); // step 30 + t2 = Fp.mul(a, t2); + t4 = Fp.add(t4, t2); + t0 = Fp.mul(t1, t4); + Y3 = Fp.add(Y3, t0); + t0 = Fp.mul(t5, t4); // step 35 + X3 = Fp.mul(t3, X3); + X3 = Fp.sub(X3, t0); + t0 = Fp.mul(t3, t1); + Z3 = Fp.mul(t5, Z3); + Z3 = Fp.add(Z3, t0); // step 40 + return new Point(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + is0() { + return this.equals(Point.ZERO); + } + wNAF(n) { + return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => { + const toInv = Fp.invertBatch(comp.map((p) => p.pz)); + return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + }); + } + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(n) { + const I = Point.ZERO; + if (n === _0n) + return I; + assertGE(n); // Will throw on 0 + if (n === _1n) + return this; + const { endo } = CURVE; + if (!endo) + return wnaf.unsafeLadder(this, n); + // Apply endomorphism + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let k1p = I; + let k2p = I; + let d = this; + while (k1 > _0n || k2 > _0n) { + if (k1 & _1n) + k1p = k1p.add(d); + if (k2 & _1n) + k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n; + k2 >>= _1n; + } + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar by which the point would be multiplied + * @returns New point + */ + multiply(scalar) { + assertGE(scalar); + let n = scalar; + let point, fake; // Fake point is used to const-time mult + const { endo } = CURVE; + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } + else { + const { p, f } = this.wNAF(n); + point = p; + fake = f; + } + // Normalize `z` for both points, but return only real one + return Point.normalizeZ([point, fake])[0]; + } + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q, a, b) { + const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes + const mul = (P, a // Select faster multiply() method + ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a)); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? undefined : sum; + } + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + toAffine(iz) { + const { px: x, py: y, pz: z } = this; + const is0 = this.is0(); + // If invZ was 0, we return zero point. However we still want to execute + // all operations, so we replace invZ with a random number, 1. + if (iz == null) + iz = is0 ? Fp.ONE : Fp.inv(z); + const ax = Fp.mul(x, iz); + const ay = Fp.mul(y, iz); + const zz = Fp.mul(z, iz); + if (is0) + return { x: Fp.ZERO, y: Fp.ZERO }; + if (!Fp.eql(zz, Fp.ONE)) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + } + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n) + return true; // No subgroups, always torsion-free + if (isTorsionFree) + return isTorsionFree(Point, this); + throw new Error('isTorsionFree() has not been declared for the elliptic curve'); + } + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n) + return this; // Fast-path + if (clearCofactor) + return clearCofactor(Point, this); + return this.multiplyUnsafe(CURVE.h); + } + toRawBytes(isCompressed = true) { + this.assertValidity(); + return toBytes(Point, this, isCompressed); + } + toHex(isCompressed = true) { + return ut.bytesToHex(this.toRawBytes(isCompressed)); + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); + Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = (0, curve_js_1.wNAF)(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + // Validate if generator point is on curve + return { + CURVE, + ProjectivePoint: Point, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + }; +} +exports.weierstrassPoints = weierstrassPoints; +function validateOpts(curve) { + const opts = (0, curve_js_1.validateBasic)(curve); + ut.validateObject(opts, { + hash: 'hash', + hmac: 'function', + randomBytes: 'function', + }, { + bits2int: 'function', + bits2int_modN: 'function', + lowS: 'boolean', + }); + return Object.freeze({ lowS: true, ...opts }); +} +function weierstrass(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32 + const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32 + function isValidFieldElement(num) { + return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE + } + function modN(a) { + return mod.mod(a, CURVE_ORDER); + } + function invN(a) { + return mod.invert(a, CURVE_ORDER); + } + const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({ + ...CURVE, + toBytes(c, point, isCompressed) { + const a = point.toAffine(); + const x = Fp.toBytes(a.x); + const cat = ut.concatBytes; + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x); + } + else { + return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y)); + } + }, + fromBytes(bytes) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + // this.assertValidity() is done inside of fromHex + if (len === compressedLen && (head === 0x02 || head === 0x03)) { + const x = ut.bytesToNumberBE(tail); + if (!isValidFieldElement(x)) + throw new Error('Point is not on curve'); + const y2 = weierstrassEquation(x); // y² = x³ + ax + b + let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 + const isYOdd = (y & _1n) === _1n; + // ECDSA + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y = Fp.neg(y); + return { x, y }; + } + else if (len === uncompressedLen && head === 0x04) { + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + } + else { + throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); + } + }, + }); + const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number) { + const HALF = CURVE_ORDER >> _1n; + return number > HALF; + } + function normalizeS(s) { + return isBiggerThanHalfOrder(s) ? modN(-s) : s; + } + // slice bytes num + const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to)); + /** + * ECDSA signature with its (r, s) properties. Supports DER & compact representations. + */ + class Signature { + constructor(r, s, recovery) { + this.r = r; + this.s = s; + this.recovery = recovery; + this.assertValidity(); + } + // pair (bytes of r, bytes of s) + static fromCompact(hex) { + const l = CURVE.nByteLength; + hex = (0, utils_js_1.ensureBytes)('compactSignature', hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex) { + const { r, s } = exports.DER.toSig((0, utils_js_1.ensureBytes)('DER', hex)); + return new Signature(r, s); + } + assertValidity() { + // can use assertGE here + if (!isWithinCurveOrder(this.r)) + throw new Error('r must be 0 < r < CURVE.n'); + if (!isWithinCurveOrder(this.s)) + throw new Error('s must be 0 < s < CURVE.n'); + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(msgHash) { + const { r, s, recovery: rec } = this; + const h = bits2int_modN((0, utils_js_1.ensureBytes)('msgHash', msgHash)); // Truncate hash + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error('recovery id invalid'); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp.ORDER) + throw new Error('recovery id 2 or 3 invalid'); + const prefix = (rec & 1) === 0 ? '02' : '03'; + const R = Point.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); // r^-1 + const u1 = modN(-h * ir); // -hr^-1 + const u2 = modN(s * ir); // sr^-1 + const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1) + if (!Q) + throw new Error('point at infinify'); // unsafe is fine: no priv data leaked + Q.assertValidity(); + return Q; + } + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; + } + // DER-encoded + toDERRawBytes() { + return ut.hexToBytes(this.toDERHex()); + } + toDERHex() { + return exports.DER.hexFromSig({ r: this.r, s: this.s }); + } + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return ut.hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + const utils = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } + catch (error) { + return false; + } + }, + normPrivateKeyToScalar: normPrivateKeyToScalar, + /** + * Produces cryptographically secure private key from random of size (nBitLength+64) + * as per FIPS 186 B.4.1 with modulo bias being neglible. + */ + randomPrivateKey: () => { + const rand = CURVE.randomBytes(Fp.BYTES + 8); + const num = mod.hashToPrivateScalar(rand, CURVE_ORDER); + return ut.numberToBytesBE(num, CURVE.nByteLength); + }, + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here + return point; + }, + }; + /** + * Computes public key for a private key. Checks for validity of the private key. + * @param privateKey private key + * @param isCompressed whether to return compact (default), or full key + * @returns Public key, full when isCompressed=false; short when isCompressed=true + */ + function getPublicKey(privateKey, isCompressed = true) { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + /** + * Quick and dirty check for item being public key. Does not validate hex, or being on-curve. + */ + function isProbPub(item) { + const arr = item instanceof Uint8Array; + const str = typeof item === 'string'; + const len = (arr || str) && item.length; + if (arr) + return len === compressedLen || len === uncompressedLen; + if (str) + return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point) + return true; + return false; + } + /** + * ECDH (Elliptic Curve Diffie Hellman). + * Computes shared public key from private key and public key. + * Checks: 1) private key validity 2) shared key is on-curve. + * Does NOT hash the result. + * @param privateA private key + * @param publicB different public key + * @param isCompressed whether to return compact (default), or full key + * @returns shared public key + */ + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) + throw new Error('first arg must be private key'); + if (!isProbPub(publicB)) + throw new Error('second arg must be public key'); + const b = Point.fromHex(publicB); // check for being on-curve + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets. + // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int. + // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same. + // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors + const bits2int = CURVE.bits2int || + function (bytes) { + // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m) + // for some cases, since bytes.length * 8 is not actual bitLength. + const num = ut.bytesToNumberBE(bytes); // check for == u8 done here + const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits + return delta > 0 ? num >> BigInt(delta) : num; + }; + const bits2int_modN = CURVE.bits2int_modN || + function (bytes) { + return modN(bits2int(bytes)); // can't use bytesToNumberBE here + }; + // NOTE: pads output with zero as per spec + const ORDER_MASK = ut.bitMask(CURVE.nBitLength); + /** + * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. + */ + function int2octets(num) { + if (typeof num !== 'bigint') + throw new Error('bigint expected'); + if (!(_0n <= num && num < ORDER_MASK)) + throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); + // works with order, can have different size than numToField! + return ut.numberToBytesBE(num, CURVE.nByteLength); + } + // Steps A, D of RFC6979 3.2 + // Creates RFC6979 seed; converts msg/privKey to numbers. + // Used only in sign, not in verify. + // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521. + // Also it can be bigger for P224 + SHA256 + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (['recovered', 'canonical'].some((k) => k in opts)) + throw new Error('sign() legacy options not supported'); + const { hash, randomBytes } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default + if (lowS == null) + lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash + msgHash = (0, utils_js_1.ensureBytes)('msgHash', msgHash); + if (prehash) + msgHash = (0, utils_js_1.ensureBytes)('prehashed msgHash', hash(msgHash)); + // We can't later call bits2octets, since nested bits2int is broken for curves + // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call. + // const bits2octets = (bits) => int2octets(bits2int_modN(bits)) + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint + const seedArgs = [int2octets(d), int2octets(h1int)]; + // extraEntropy. RFC6979 3.6: additional k' (optional). + if (ent != null) { + // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') + const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is + seedArgs.push((0, utils_js_1.ensureBytes)('extraEntropy', e, Fp.BYTES)); // check for being of size BYTES + } + const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2 + const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash! + // Converts signature params into point w r/s, checks result for validity. + function k2sig(kBytes) { + // RFC 6979 Section 3.2, step 3: k = bits2int(T) + const k = bits2int(kBytes); // Cannot use fields methods, since it is group element + if (!isWithinCurveOrder(k)) + return; // Important: all mod() calls here must be done over N + const ik = invN(k); // k^-1 mod n + const q = Point.BASE.multiply(k).toAffine(); // q = Gk + const r = modN(q.x); // r = q.x mod n + if (r === _0n) + return; + // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to + // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it: + // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT + const s = modN(ik * modN(m + r * d)); // Not using blinding here + if (s === _0n) + return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n) + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); // if lowS was passed, ensure s is always + recovery ^= 1; // // in the bottom half of N + } + return new Signature(r, normS, recovery); // use normS, not s + } + return { seed, k2sig }; + } + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + /** + * Signs message hash with a private key. + * ``` + * sign(m, d, k) where + * (x, y) = G × k + * r = x mod n + * s = (m + dr)/k mod n + * ``` + * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`. + * @param privKey private key + * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg. + * @returns signature with recovery param + */ + function sign(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2. + const C = CURVE; + const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); // Steps B, C, D, E, F, G + } + // Enable precomputes. Slows down first publicKey computation by 20ms. + Point.BASE._setWindowSize(8); + // utils.precompute(8, ProjectivePoint.BASE) + /** + * Verifies a signature against message hash and public key. + * Rejects lowS signatures by default: to override, + * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf: + * + * ``` + * verify(r, s, h, P) where + * U1 = hs^-1 mod n + * U2 = rs^-1 mod n + * R = U1⋅G - U2⋅P + * mod(R.x, n) == r + * ``` + */ + function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { + const sg = signature; + msgHash = (0, utils_js_1.ensureBytes)('msgHash', msgHash); + publicKey = (0, utils_js_1.ensureBytes)('publicKey', publicKey); + if ('strict' in opts) + throw new Error('options.strict was renamed to lowS'); + const { lowS, prehash } = opts; + let _sig = undefined; + let P; + try { + if (typeof sg === 'string' || sg instanceof Uint8Array) { + // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length). + // Since DER can also be 2*nByteLength bytes, we check for it first. + try { + _sig = Signature.fromDER(sg); + } + catch (derError) { + if (!(derError instanceof exports.DER.Err)) + throw derError; + _sig = Signature.fromCompact(sg); + } + } + else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') { + const { r, s } = sg; + _sig = new Signature(r, s); + } + else { + throw new Error('PARSE'); + } + P = Point.fromHex(publicKey); + } + catch (error) { + if (error.message === 'PARSE') + throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; + } + if (lowS && _sig.hasHighS()) + return false; + if (prehash) + msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element + const is = invN(s); // s^-1 + const u1 = modN(h * is); // u1 = hs^-1 mod n + const u2 = modN(r * is); // u2 = rs^-1 mod n + const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P + if (!R) + return false; + const v = modN(R.x); + return v === r; + } + return { + CURVE, + getPublicKey, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point, + Signature, + utils, + }; +} +exports.weierstrass = weierstrass; +/** + * Implementation of the Shallue and van de Woestijne method for any weierstrass curve. + * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular. + * b = True and y = sqrt(u / v) if (u / v) is square in F, and + * b = False and y = sqrt(Z * (u / v)) otherwise. + * @param Fp + * @param Z + * @returns + */ +function SWUFpSqrtRatio(Fp, Z) { + // Generic implementation + const q = Fp.ORDER; + let l = _0n; + for (let o = q - _1n; o % _2n === _0n; o /= _2n) + l += _1n; + const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1. + // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<. + // 2n ** c1 == 2n << (c1-1) + const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n); + const _2n_pow_c1 = _2n_pow_c1_1 * _2n; + const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic + const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic + const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic + const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic + const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2 + const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2) + let sqrtRatio = (u, v) => { + let tv1 = c6; // 1. tv1 = c6 + let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4 + let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2 + tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v + let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3 + tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3 + tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2 + tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v + tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u + let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2 + tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5 + let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1 + tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7 + tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1 + tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR) + tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR) + // 17. for i in (c1, c1 - 1, ..., 2): + for (let i = c1; i > _1n; i--) { + let tv5 = i - _2n; // 18. tv5 = i - 2 + tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5 + let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5 + const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1 + tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1 + tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1 + tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1 + tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1) + tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1) + } + return { isValid: isQR, value: tv3 }; + }; + if (Fp.ORDER % _4n === _3n) { + // sqrt_ratio_3mod4(u, v) + const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic + const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z) + sqrtRatio = (u, v) => { + let tv1 = Fp.sqr(v); // 1. tv1 = v^2 + const tv2 = Fp.mul(u, v); // 2. tv2 = u * v + tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2 + let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1 + y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2 + const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2 + const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v + const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u + let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR) + return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2 + }; + } + // No curves uses that + // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8 + return sqrtRatio; +} +exports.SWUFpSqrtRatio = SWUFpSqrtRatio; +/** + * From draft-irtf-cfrg-hash-to-curve-16 + */ +function mapToCurveSimpleSWU(Fp, opts) { + mod.validateField(Fp); + if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z)) + throw new Error('mapToCurveSimpleSWU: invalid opts'); + const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z); + if (!Fp.isOdd) + throw new Error('Fp.isOdd is not implemented!'); + // Input: u, an element of F. + // Output: (x, y), a point on E. + return (u) => { + // prettier-ignore + let tv1, tv2, tv3, tv4, tv5, tv6, x, y; + tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1 + tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2 + tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1 + tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1 + tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3 + tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0) + tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4 + tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2 + tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2 + tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6 + tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5 + tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3 + tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4 + tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6 + tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5 + x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3 + const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6) + y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1 + y = Fp.mul(y, value); // 20. y = y * y1 + x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square) + y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square) + const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y) + y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1) + x = Fp.div(x, tv4); // 25. x = x / tv4 + return { x, y }; + }; +} +exports.mapToCurveSimpleSWU = mapToCurveSimpleSWU; +//# sourceMappingURL=weierstrass.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/weierstrass.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/weierstrass.js.map new file mode 100644 index 0000000..56663a3 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/abstract/weierstrass.js.map @@ -0,0 +1 @@ +{"version":3,"file":"weierstrass.js","sourceRoot":"","sources":["../src/abstract/weierstrass.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,4DAA4D;AAC5D,oCAAoC;AACpC,iCAAiC;AACjC,yCAA8D;AAC9D,yCAAmG;AAqFnG,SAAS,iBAAiB,CAAI,KAAyB;IACrD,MAAM,IAAI,GAAG,IAAA,wBAAa,EAAC,KAAK,CAAC,CAAC;IAClC,EAAE,CAAC,cAAc,CACf,IAAI,EACJ;QACE,CAAC,EAAE,OAAO;QACV,CAAC,EAAE,OAAO;KACX,EACD;QACE,wBAAwB,EAAE,OAAO;QACjC,cAAc,EAAE,SAAS;QACzB,aAAa,EAAE,UAAU;QACzB,aAAa,EAAE,UAAU;QACzB,kBAAkB,EAAE,SAAS;QAC7B,SAAS,EAAE,UAAU;QACrB,OAAO,EAAE,UAAU;KACpB,CACF,CAAC;IACF,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,EAAE,GAAG,IAAI,CAAC;IAC7B,IAAI,IAAI,EAAE;QACR,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE;YACvB,MAAM,IAAI,KAAK,CAAC,mEAAmE,CAAC,CAAC;SACtF;QACD,IACE,OAAO,IAAI,KAAK,QAAQ;YACxB,OAAO,IAAI,CAAC,IAAI,KAAK,QAAQ;YAC7B,OAAO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,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,mBAAmB;QACzC,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC,wCAAwC;QACtE,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,uCAAuC;QACvE,MAAM,EAAE,GAAG,EAAE,CAAC,KAAM,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,KAAM,CAAC,CAAC,CAAC,CAAC,CAAC,+BAA+B;QACzE,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,4BAA4B;QAC3D,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,oBAAoB;QACxC,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IAClB,CAAC,CAAC;AACJ,CAAC;AA7CD,kDA6CC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/bls12-381.d.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/bls12-381.d.ts new file mode 100644 index 0000000..0e71114 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/bls12-381.d.ts @@ -0,0 +1,68 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { CurveFn } from './abstract/bls.js'; +import * as mod from './abstract/modular.js'; +declare const Fp: Readonly & Required, "isOdd">>>; +type Fp = bigint; +type BigintTuple = [bigint, bigint]; +type Fp2 = { + c0: bigint; + c1: bigint; +}; +type Fp2Utils = { + fromBigTuple: (tuple: BigintTuple | bigint[]) => Fp2; + reim: (num: Fp2) => { + re: bigint; + im: bigint; + }; + mulByNonresidue: (num: Fp2) => Fp2; + multiplyByB: (num: Fp2) => Fp2; + frobeniusMap(num: Fp2, power: number): Fp2; +}; +declare const Fp2: mod.IField & Fp2Utils; +type BigintSix = [bigint, bigint, bigint, bigint, bigint, bigint]; +type Fp6 = { + c0: Fp2; + c1: Fp2; + c2: Fp2; +}; +type Fp6Utils = { + fromBigSix: (tuple: BigintSix) => Fp6; + mulByNonresidue: (num: Fp6) => Fp6; + frobeniusMap(num: Fp6, power: number): Fp6; + multiplyBy1(num: Fp6, b1: Fp2): Fp6; + multiplyBy01(num: Fp6, b0: Fp2, b1: Fp2): Fp6; + multiplyByFp2(lhs: Fp6, rhs: Fp2): Fp6; +}; +declare const Fp6: mod.IField & Fp6Utils; +type Fp12 = { + c0: Fp6; + c1: Fp6; +}; +type BigintTwelve = [ + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint +]; +type Fp12Utils = { + fromBigTwelve: (t: BigintTwelve) => Fp12; + frobeniusMap(num: Fp12, power: number): Fp12; + multiplyBy014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12; + multiplyByFp2(lhs: Fp12, rhs: Fp2): Fp12; + conjugate(num: Fp12): Fp12; + finalExponentiate(num: Fp12): Fp12; + _cyclotomicSquare(num: Fp12): Fp12; + _cyclotomicExp(num: Fp12, n: bigint): Fp12; +}; +declare const Fp12: mod.IField & Fp12Utils; +export declare const bls12_381: CurveFn; +export {}; +//# sourceMappingURL=bls12-381.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/bls12-381.d.ts.map b/node_modules/@scure/bip32/node_modules/@noble/curves/bls12-381.d.ts.map new file mode 100644 index 0000000..b724df1 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/bls12-381.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bls12-381.d.ts","sourceRoot":"","sources":["src/bls12-381.ts"],"names":[],"mappings":"AAAA,sEAAsE;AA+BtE,OAAO,EAAO,OAAO,EAAE,MAAM,mBAAmB,CAAC;AACjD,O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EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5C,CAAC;AAEF,QAAA,MAAM,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,SA6I9B,CAAC;AAmWF,eAAO,MAAM,SAAS,EAAE,OAAO,CAAC,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,CA2ShD,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/bls12-381.js b/node_modules/@scure/bip32/node_modules/@noble/curves/bls12-381.js new file mode 100644 index 0000000..c825e0e --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/bls12-381.js @@ -0,0 +1,1176 @@ +"use strict"; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bls12_381 = void 0; +// bls12-381 pairing-friendly Barreto-Lynn-Scott elliptic curve construction allows to: +// - Construct zk-SNARKs at the 128-bit security +// - Use threshold signatures, which allows a user to sign lots of messages with one signature and +// verify them swiftly in a batch, using Boneh-Lynn-Shacham signature scheme. +// +// The library uses G1 for public keys and G2 for signatures. Support for G1 signatures is planned. +// Compatible with Algorand, Chia, Dfinity, Ethereum, FIL, Zcash. Matches specs +// [pairing-curves-11](https://tools.ietf.org/html/draft-irtf-cfrg-pairing-friendly-curves-11), +// [bls-sigs-04](https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-04), +// [hash-to-curve-12](https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-12). +// +// ### Summary +// 1. BLS Relies on Bilinear Pairing (expensive) +// 2. Private Keys: 32 bytes +// 3. Public Keys: 48 bytes: 381 bit affine x coordinate, encoded into 48 big-endian bytes. +// 4. Signatures: 96 bytes: two 381 bit integers (affine x coordinate), encoded into two 48 big-endian byte arrays. +// - The signature is a point on the G2 subgroup, which is defined over a finite field +// with elements twice as big as the G1 curve (G2 is over Fp2 rather than Fp. Fp2 is analogous to the complex numbers). +// 5. The 12 stands for the Embedding degree. +// +// ### Formulas +// - `P = pk x G` - public keys +// - `S = pk x H(m)` - signing +// - `e(P, H(m)) == e(G, S)` - verification using pairings +// - `e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))` - signature aggregation +// Filecoin uses little endian byte arrays for private keys - +// so ensure to reverse byte order if you'll use it with FIL. +const sha256_1 = require("@noble/hashes/sha256"); +const utils_1 = require("@noble/hashes/utils"); +const bls_js_1 = require("./abstract/bls.js"); +const mod = require("./abstract/modular.js"); +const utils_js_1 = require("./abstract/utils.js"); +// Types +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4); +// prettier-ignore +const _8n = BigInt(8), _16n = BigInt(16); +// CURVE FIELDS +// Finite field over p. +const Fp_raw = BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'); +const Fp = mod.Field(Fp_raw); +// Finite field over r. +// This particular field is not used anywhere in bls12-381, but it is still useful. +const Fr = mod.Field(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')); +const Fp2Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp.add(c0, r0), + c1: Fp.add(c1, r1), +}); +const Fp2Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp.sub(c0, r0), + c1: Fp.sub(c1, r1), +}); +const Fp2Multiply = ({ c0, c1 }, rhs) => { + if (typeof rhs === 'bigint') + return { c0: Fp.mul(c0, rhs), c1: Fp.mul(c1, rhs) }; + // (a+bi)(c+di) = (ac−bd) + (ad+bc)i + const { c0: r0, c1: r1 } = rhs; + let t1 = Fp.mul(c0, r0); // c0 * o0 + let t2 = Fp.mul(c1, r1); // c1 * o1 + // (T1 - T2) + ((c0 + c1) * (r0 + r1) - (T1 + T2))*i + const o0 = Fp.sub(t1, t2); + const o1 = Fp.sub(Fp.mul(Fp.add(c0, c1), Fp.add(r0, r1)), Fp.add(t1, t2)); + return { c0: o0, c1: o1 }; +}; +const Fp2Square = ({ c0, c1 }) => { + const a = Fp.add(c0, c1); + const b = Fp.sub(c0, c1); + const c = Fp.add(c0, c0); + return { c0: Fp.mul(a, b), c1: Fp.mul(c, c1) }; +}; +// G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1), +// where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where +// G² - 1 +// h2q +// NOTE: ORDER was wrong! +const FP2_ORDER = Fp_raw * Fp_raw; +const Fp2 = { + ORDER: FP2_ORDER, + BITS: (0, utils_js_1.bitLen)(FP2_ORDER), + BYTES: Math.ceil((0, utils_js_1.bitLen)(FP2_ORDER) / 8), + MASK: (0, utils_js_1.bitMask)((0, utils_js_1.bitLen)(FP2_ORDER)), + ZERO: { c0: Fp.ZERO, c1: Fp.ZERO }, + ONE: { c0: Fp.ONE, c1: Fp.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => typeof c0 === 'bigint' && typeof c1 === 'bigint', + is0: ({ c0, c1 }) => Fp.is0(c0) && Fp.is0(c1), + eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp.eql(c0, r0) && Fp.eql(c1, r1), + neg: ({ c0, c1 }) => ({ c0: Fp.neg(c0), c1: Fp.neg(c1) }), + pow: (num, power) => mod.FpPow(Fp2, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp2, nums), + // Normalized + add: Fp2Add, + sub: Fp2Subtract, + mul: Fp2Multiply, + sqr: Fp2Square, + // NonNormalized stuff + addN: Fp2Add, + subN: Fp2Subtract, + mulN: Fp2Multiply, + sqrN: Fp2Square, + // Why inversion for bigint inside Fp instead of Fp2? it is even used in that context? + div: (lhs, rhs) => Fp2.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp2.inv(rhs)), + inv: ({ c0: a, c1: b }) => { + // We wish to find the multiplicative inverse of a nonzero + // element a + bu in Fp2. We leverage an identity + // + // (a + bu)(a - bu) = a² + b² + // + // which holds because u² = -1. This can be rewritten as + // + // (a + bu)(a - bu)/(a² + b²) = 1 + // + // because a² + b² = 0 has no nonzero solutions for (a, b). + // This gives that (a - bu)/(a² + b²) is the inverse + // of (a + bu). Importantly, this can be computing using + // only a single inversion in Fp. + const factor = Fp.inv(Fp.create(a * a + b * b)); + return { c0: Fp.mul(factor, Fp.create(a)), c1: Fp.mul(factor, Fp.create(-b)) }; + }, + sqrt: (num) => { + if (Fp2.eql(num, Fp2.ZERO)) + return Fp2.ZERO; // Algo doesn't handles this case + // TODO: Optimize this line. It's extremely slow. + // Speeding this up would boost aggregateSignatures. + // https://eprint.iacr.org/2012/685.pdf applicable? + // https://github.com/zkcrypto/bls12_381/blob/080eaa74ec0e394377caa1ba302c8c121df08b07/src/fp2.rs#L250 + // https://github.com/supranational/blst/blob/aae0c7d70b799ac269ff5edf29d8191dbd357876/src/exp2.c#L1 + // Inspired by https://github.com/dalek-cryptography/curve25519-dalek/blob/17698df9d4c834204f83a3574143abacb4fc81a5/src/field.rs#L99 + const candidateSqrt = Fp2.pow(num, (Fp2.ORDER + _8n) / _16n); + const check = Fp2.div(Fp2.sqr(candidateSqrt), num); // candidateSqrt.square().div(this); + const R = FP2_ROOTS_OF_UNITY; + const divisor = [R[0], R[2], R[4], R[6]].find((r) => Fp2.eql(r, check)); + if (!divisor) + throw new Error('No root'); + const index = R.indexOf(divisor); + const root = R[index / 2]; + if (!root) + throw new Error('Invalid root'); + const x1 = Fp2.div(candidateSqrt, root); + const x2 = Fp2.neg(x1); + const { re: re1, im: im1 } = Fp2.reim(x1); + const { re: re2, im: im2 } = Fp2.reim(x2); + if (im1 > im2 || (im1 === im2 && re1 > re2)) + return x1; + return x2; + }, + // Same as sgn0_fp2 in draft-irtf-cfrg-hash-to-curve-16 + isOdd: (x) => { + const { re: x0, im: x1 } = Fp2.reim(x); + const sign_0 = x0 % _2n; + const zero_0 = x0 === _0n; + const sign_1 = x1 % _2n; + return BigInt(sign_0 || (zero_0 && sign_1)) == _1n; + }, + // Bytes util + fromBytes(b) { + if (b.length !== Fp2.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { c0: Fp.fromBytes(b.subarray(0, Fp.BYTES)), c1: Fp.fromBytes(b.subarray(Fp.BYTES)) }; + }, + toBytes: ({ c0, c1 }) => (0, utils_js_1.concatBytes)(Fp.toBytes(c0), Fp.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp.cmov(c0, r0, c), + c1: Fp.cmov(c1, r1, c), + }), + // Specific utils + // toString() { + // return `Fp2(${this.c0} + ${this.c1}×i)`; + // } + reim: ({ c0, c1 }) => ({ re: c0, im: c1 }), + // multiply by u + 1 + mulByNonresidue: ({ c0, c1 }) => ({ c0: Fp.sub(c0, c1), c1: Fp.add(c0, c1) }), + multiplyByB: ({ c0, c1 }) => { + let t0 = Fp.mul(c0, _4n); // 4 * c0 + let t1 = Fp.mul(c1, _4n); // 4 * c1 + // (T0-T1) + (T0+T1)*i + return { c0: Fp.sub(t0, t1), c1: Fp.add(t0, t1) }; + }, + fromBigTuple: (tuple) => { + if (tuple.length !== 2) + throw new Error('Invalid tuple'); + const fps = tuple.map((n) => Fp.create(n)); + return { c0: fps[0], c1: fps[1] }; + }, + frobeniusMap: ({ c0, c1 }, power) => ({ + c0, + c1: Fp.mul(c1, FP2_FROBENIUS_COEFFICIENTS[power % 2]), + }), +}; +// Finite extension field over irreducible polynominal. +// Fp(u) / (u² - β) where β = -1 +const FP2_FROBENIUS_COEFFICIENTS = [ + BigInt('0x1'), + BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'), +].map((item) => Fp.create(item)); +// For Fp2 roots of unity. +const rv1 = BigInt('0x6af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09'); +// const ev1 = +// BigInt('0x699be3b8c6870965e5bf892ad5d2cc7b0e85a117402dfd83b7f4a947e02d978498255a2aaec0ac627b5afbdf1bf1c90'); +// const ev2 = +// BigInt('0x8157cd83046453f5dd0972b6e3949e4288020b5b8a9cc99ca07e27089a2ce2436d965026adad3ef7baba37f2183e9b5'); +// const ev3 = +// BigInt('0xab1c2ffdd6c253ca155231eb3e71ba044fd562f6f72bc5bad5ec46a0b7a3b0247cf08ce6c6317f40edbc653a72dee17'); +// const ev4 = +// BigInt('0xaa404866706722864480885d68ad0ccac1967c7544b447873cc37e0181271e006df72162a3d3e0287bf597fbf7f8fc1'); +// Eighth roots of unity, used for computing square roots in Fp2. +// To verify or re-calculate: +// Array(8).fill(new Fp2([1n, 1n])).map((fp2, k) => fp2.pow(Fp2.ORDER * BigInt(k) / 8n)) +const FP2_ROOTS_OF_UNITY = [ + [_1n, _0n], + [rv1, -rv1], + [_0n, _1n], + [rv1, rv1], + [-_1n, _0n], + [-rv1, rv1], + [_0n, -_1n], + [-rv1, -rv1], +].map((pair) => Fp2.fromBigTuple(pair)); +const Fp6Add = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({ + c0: Fp2.add(c0, r0), + c1: Fp2.add(c1, r1), + c2: Fp2.add(c2, r2), +}); +const Fp6Subtract = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({ + c0: Fp2.sub(c0, r0), + c1: Fp2.sub(c1, r1), + c2: Fp2.sub(c2, r2), +}); +const Fp6Multiply = ({ c0, c1, c2 }, rhs) => { + if (typeof rhs === 'bigint') { + return { + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }; + } + const { c0: r0, c1: r1, c2: r2 } = rhs; + const t0 = Fp2.mul(c0, r0); // c0 * o0 + const t1 = Fp2.mul(c1, r1); // c1 * o1 + const t2 = Fp2.mul(c2, r2); // c2 * o2 + return { + // t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1) + c0: Fp2.add(t0, Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), Fp2.add(r1, r2)), Fp2.add(t1, t2)))), + // (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1) + c1: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c1), Fp2.add(r0, r1)), Fp2.add(t0, t1)), Fp2.mulByNonresidue(t2)), + // T1 + (c0 + c2) * (r0 + r2) - T0 + T2 + c2: Fp2.sub(Fp2.add(t1, Fp2.mul(Fp2.add(c0, c2), Fp2.add(r0, r2))), Fp2.add(t0, t2)), + }; +}; +const Fp6Square = ({ c0, c1, c2 }) => { + let t0 = Fp2.sqr(c0); // c0² + let t1 = Fp2.mul(Fp2.mul(c0, c1), _2n); // 2 * c0 * c1 + let t3 = Fp2.mul(Fp2.mul(c1, c2), _2n); // 2 * c1 * c2 + let t4 = Fp2.sqr(c2); // c2² + return { + c0: Fp2.add(Fp2.mulByNonresidue(t3), t0), + c1: Fp2.add(Fp2.mulByNonresidue(t4), t1), + // T1 + (c0 - c1 + c2)² + T3 - T0 - T4 + c2: Fp2.sub(Fp2.sub(Fp2.add(Fp2.add(t1, Fp2.sqr(Fp2.add(Fp2.sub(c0, c1), c2))), t3), t0), t4), + }; +}; +const Fp6 = { + ORDER: Fp2.ORDER, + BITS: 3 * Fp2.BITS, + BYTES: 3 * Fp2.BYTES, + MASK: (0, utils_js_1.bitMask)(3 * Fp2.BITS), + ZERO: { c0: Fp2.ZERO, c1: Fp2.ZERO, c2: Fp2.ZERO }, + ONE: { c0: Fp2.ONE, c1: Fp2.ZERO, c2: Fp2.ZERO }, + create: (num) => num, + isValid: ({ c0, c1, c2 }) => Fp2.isValid(c0) && Fp2.isValid(c1) && Fp2.isValid(c2), + is0: ({ c0, c1, c2 }) => Fp2.is0(c0) && Fp2.is0(c1) && Fp2.is0(c2), + neg: ({ c0, c1, c2 }) => ({ c0: Fp2.neg(c0), c1: Fp2.neg(c1), c2: Fp2.neg(c2) }), + eql: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => Fp2.eql(c0, r0) && Fp2.eql(c1, r1) && Fp2.eql(c2, r2), + sqrt: () => { + throw new Error('Not implemented'); + }, + // Do we need division by bigint at all? Should be done via order: + div: (lhs, rhs) => Fp6.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp6.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp6, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp6, nums), + // Normalized + add: Fp6Add, + sub: Fp6Subtract, + mul: Fp6Multiply, + sqr: Fp6Square, + // NonNormalized stuff + addN: Fp6Add, + subN: Fp6Subtract, + mulN: Fp6Multiply, + sqrN: Fp6Square, + inv: ({ c0, c1, c2 }) => { + let t0 = Fp2.sub(Fp2.sqr(c0), Fp2.mulByNonresidue(Fp2.mul(c2, c1))); // c0² - c2 * c1 * (u + 1) + let t1 = Fp2.sub(Fp2.mulByNonresidue(Fp2.sqr(c2)), Fp2.mul(c0, c1)); // c2² * (u + 1) - c0 * c1 + let t2 = Fp2.sub(Fp2.sqr(c1), Fp2.mul(c0, c2)); // c1² - c0 * c2 + // 1/(((c2 * T1 + c1 * T2) * v) + c0 * T0) + let t4 = Fp2.inv(Fp2.add(Fp2.mulByNonresidue(Fp2.add(Fp2.mul(c2, t1), Fp2.mul(c1, t2))), Fp2.mul(c0, t0))); + return { c0: Fp2.mul(t4, t0), c1: Fp2.mul(t4, t1), c2: Fp2.mul(t4, t2) }; + }, + // Bytes utils + fromBytes: (b) => { + if (b.length !== Fp6.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp2.fromBytes(b.subarray(0, Fp2.BYTES)), + c1: Fp2.fromBytes(b.subarray(Fp2.BYTES, 2 * Fp2.BYTES)), + c2: Fp2.fromBytes(b.subarray(2 * Fp2.BYTES)), + }; + }, + toBytes: ({ c0, c1, c2 }) => (0, utils_js_1.concatBytes)(Fp2.toBytes(c0), Fp2.toBytes(c1), Fp2.toBytes(c2)), + cmov: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }, c) => ({ + c0: Fp2.cmov(c0, r0, c), + c1: Fp2.cmov(c1, r1, c), + c2: Fp2.cmov(c2, r2, c), + }), + // Utils + // fromTriple(triple: [Fp2, Fp2, Fp2]) { + // return new Fp6(...triple); + // } + // toString() { + // return `Fp6(${this.c0} + ${this.c1} * v, ${this.c2} * v^2)`; + // } + fromBigSix: (t) => { + if (!Array.isArray(t) || t.length !== 6) + throw new Error('Invalid Fp6 usage'); + return { + c0: Fp2.fromBigTuple(t.slice(0, 2)), + c1: Fp2.fromBigTuple(t.slice(2, 4)), + c2: Fp2.fromBigTuple(t.slice(4, 6)), + }; + }, + frobeniusMap: ({ c0, c1, c2 }, power) => ({ + c0: Fp2.frobeniusMap(c0, power), + c1: Fp2.mul(Fp2.frobeniusMap(c1, power), FP6_FROBENIUS_COEFFICIENTS_1[power % 6]), + c2: Fp2.mul(Fp2.frobeniusMap(c2, power), FP6_FROBENIUS_COEFFICIENTS_2[power % 6]), + }), + mulByNonresidue: ({ c0, c1, c2 }) => ({ c0: Fp2.mulByNonresidue(c2), c1: c0, c2: c1 }), + // Sparse multiplication + multiplyBy1: ({ c0, c1, c2 }, b1) => ({ + c0: Fp2.mulByNonresidue(Fp2.mul(c2, b1)), + c1: Fp2.mul(c0, b1), + c2: Fp2.mul(c1, b1), + }), + // Sparse multiplication + multiplyBy01({ c0, c1, c2 }, b0, b1) { + let t0 = Fp2.mul(c0, b0); // c0 * b0 + let t1 = Fp2.mul(c1, b1); // c1 * b1 + return { + // ((c1 + c2) * b1 - T1) * (u + 1) + T0 + c0: Fp2.add(Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), b1), t1)), t0), + // (b0 + b1) * (c0 + c1) - T0 - T1 + c1: Fp2.sub(Fp2.sub(Fp2.mul(Fp2.add(b0, b1), Fp2.add(c0, c1)), t0), t1), + // (c0 + c2) * b0 - T0 + T1 + c2: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c2), b0), t0), t1), + }; + }, + multiplyByFp2: ({ c0, c1, c2 }, rhs) => ({ + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }), +}; +const FP6_FROBENIUS_COEFFICIENTS_1 = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt('0x0'), + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + BigInt('0x0'), + ], + [BigInt('0x0'), BigInt('0x1')], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + BigInt('0x0'), + ], + [ + BigInt('0x0'), + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + ], +].map((pair) => Fp2.fromBigTuple(pair)); +const FP6_FROBENIUS_COEFFICIENTS_2 = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad'), + BigInt('0x0'), + ], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + BigInt('0x0'), + ], + [ + BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'), + BigInt('0x0'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + BigInt('0x0'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff'), + BigInt('0x0'), + ], +].map((pair) => Fp2.fromBigTuple(pair)); +// The BLS parameter x for BLS12-381 +const BLS_X = BigInt('0xd201000000010000'); +const BLS_X_LEN = (0, utils_js_1.bitLen)(BLS_X); +const Fp12Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp6.add(c0, r0), + c1: Fp6.add(c1, r1), +}); +const Fp12Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp6.sub(c0, r0), + c1: Fp6.sub(c1, r1), +}); +const Fp12Multiply = ({ c0, c1 }, rhs) => { + if (typeof rhs === 'bigint') + return { c0: Fp6.mul(c0, rhs), c1: Fp6.mul(c1, rhs) }; + let { c0: r0, c1: r1 } = rhs; + let t1 = Fp6.mul(c0, r0); // c0 * r0 + let t2 = Fp6.mul(c1, r1); // c1 * r1 + return { + c0: Fp6.add(t1, Fp6.mulByNonresidue(t2)), + // (c0 + c1) * (r0 + r1) - (T1 + T2) + c1: Fp6.sub(Fp6.mul(Fp6.add(c0, c1), Fp6.add(r0, r1)), Fp6.add(t1, t2)), + }; +}; +const Fp12Square = ({ c0, c1 }) => { + let ab = Fp6.mul(c0, c1); // c0 * c1 + return { + // (c1 * v + c0) * (c0 + c1) - AB - AB * v + c0: Fp6.sub(Fp6.sub(Fp6.mul(Fp6.add(Fp6.mulByNonresidue(c1), c0), Fp6.add(c0, c1)), ab), Fp6.mulByNonresidue(ab)), + c1: Fp6.add(ab, ab), + }; // AB + AB +}; +function Fp4Square(a, b) { + const a2 = Fp2.sqr(a); + const b2 = Fp2.sqr(b); + return { + first: Fp2.add(Fp2.mulByNonresidue(b2), a2), + second: Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(a, b)), a2), b2), // (a + b)² - a² - b² + }; +} +const Fp12 = { + ORDER: Fp2.ORDER, + BITS: 2 * Fp2.BITS, + BYTES: 2 * Fp2.BYTES, + MASK: (0, utils_js_1.bitMask)(2 * Fp2.BITS), + ZERO: { c0: Fp6.ZERO, c1: Fp6.ZERO }, + ONE: { c0: Fp6.ONE, c1: Fp6.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => Fp6.isValid(c0) && Fp6.isValid(c1), + is0: ({ c0, c1 }) => Fp6.is0(c0) && Fp6.is0(c1), + neg: ({ c0, c1 }) => ({ c0: Fp6.neg(c0), c1: Fp6.neg(c1) }), + eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp6.eql(c0, r0) && Fp6.eql(c1, r1), + sqrt: () => { + throw new Error('Not implemented'); + }, + inv: ({ c0, c1 }) => { + let t = Fp6.inv(Fp6.sub(Fp6.sqr(c0), Fp6.mulByNonresidue(Fp6.sqr(c1)))); // 1 / (c0² - c1² * v) + return { c0: Fp6.mul(c0, t), c1: Fp6.neg(Fp6.mul(c1, t)) }; // ((C0 * T) * T) + (-C1 * T) * w + }, + div: (lhs, rhs) => Fp12.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp12.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp12, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp12, nums), + // Normalized + add: Fp12Add, + sub: Fp12Subtract, + mul: Fp12Multiply, + sqr: Fp12Square, + // NonNormalized stuff + addN: Fp12Add, + subN: Fp12Subtract, + mulN: Fp12Multiply, + sqrN: Fp12Square, + // Bytes utils + fromBytes: (b) => { + if (b.length !== Fp12.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp6.fromBytes(b.subarray(0, Fp6.BYTES)), + c1: Fp6.fromBytes(b.subarray(Fp6.BYTES)), + }; + }, + toBytes: ({ c0, c1 }) => (0, utils_js_1.concatBytes)(Fp6.toBytes(c0), Fp6.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp6.cmov(c0, r0, c), + c1: Fp6.cmov(c1, r1, c), + }), + // Utils + // toString() { + // return `Fp12(${this.c0} + ${this.c1} * w)`; + // }, + // fromTuple(c: [Fp6, Fp6]) { + // return new Fp12(...c); + // } + fromBigTwelve: (t) => ({ + c0: Fp6.fromBigSix(t.slice(0, 6)), + c1: Fp6.fromBigSix(t.slice(6, 12)), + }), + // Raises to q**i -th power + frobeniusMap(lhs, power) { + const r0 = Fp6.frobeniusMap(lhs.c0, power); + const { c0, c1, c2 } = Fp6.frobeniusMap(lhs.c1, power); + const coeff = FP12_FROBENIUS_COEFFICIENTS[power % 12]; + return { + c0: r0, + c1: Fp6.create({ + c0: Fp2.mul(c0, coeff), + c1: Fp2.mul(c1, coeff), + c2: Fp2.mul(c2, coeff), + }), + }; + }, + // Sparse multiplication + multiplyBy014: ({ c0, c1 }, o0, o1, o4) => { + let t0 = Fp6.multiplyBy01(c0, o0, o1); + let t1 = Fp6.multiplyBy1(c1, o4); + return { + c0: Fp6.add(Fp6.mulByNonresidue(t1), t0), + // (c1 + c0) * [o0, o1+o4] - T0 - T1 + c1: Fp6.sub(Fp6.sub(Fp6.multiplyBy01(Fp6.add(c1, c0), o0, Fp2.add(o1, o4)), t0), t1), + }; + }, + multiplyByFp2: ({ c0, c1 }, rhs) => ({ + c0: Fp6.multiplyByFp2(c0, rhs), + c1: Fp6.multiplyByFp2(c1, rhs), + }), + conjugate: ({ c0, c1 }) => ({ c0, c1: Fp6.neg(c1) }), + // A cyclotomic group is a subgroup of Fp^n defined by + // GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1} + // The result of any pairing is in a cyclotomic subgroup + // https://eprint.iacr.org/2009/565.pdf + _cyclotomicSquare: ({ c0, c1 }) => { + const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0; + const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1; + const { first: t3, second: t4 } = Fp4Square(c0c0, c1c1); + const { first: t5, second: t6 } = Fp4Square(c1c0, c0c2); + const { first: t7, second: t8 } = Fp4Square(c0c1, c1c2); + let t9 = Fp2.mulByNonresidue(t8); // T8 * (u + 1) + return { + c0: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.sub(t3, c0c0), _2n), t3), + c1: Fp2.add(Fp2.mul(Fp2.sub(t5, c0c1), _2n), t5), + c2: Fp2.add(Fp2.mul(Fp2.sub(t7, c0c2), _2n), t7), + }), + c1: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.add(t9, c1c0), _2n), t9), + c1: Fp2.add(Fp2.mul(Fp2.add(t4, c1c1), _2n), t4), + c2: Fp2.add(Fp2.mul(Fp2.add(t6, c1c2), _2n), t6), + }), + }; // 2 * (T6 + c1c2) + T6 + }, + _cyclotomicExp(num, n) { + let z = Fp12.ONE; + for (let i = BLS_X_LEN - 1; i >= 0; i--) { + z = Fp12._cyclotomicSquare(z); + if ((0, utils_js_1.bitGet)(n, i)) + z = Fp12.mul(z, num); + } + return z; + }, + // https://eprint.iacr.org/2010/354.pdf + // https://eprint.iacr.org/2009/565.pdf + finalExponentiate: (num) => { + const x = BLS_X; + // this^(q⁶) / this + const t0 = Fp12.div(Fp12.frobeniusMap(num, 6), num); + // t0^(q²) * t0 + const t1 = Fp12.mul(Fp12.frobeniusMap(t0, 2), t0); + const t2 = Fp12.conjugate(Fp12._cyclotomicExp(t1, x)); + const t3 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicSquare(t1)), t2); + const t4 = Fp12.conjugate(Fp12._cyclotomicExp(t3, x)); + const t5 = Fp12.conjugate(Fp12._cyclotomicExp(t4, x)); + const t6 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicExp(t5, x)), Fp12._cyclotomicSquare(t2)); + const t7 = Fp12.conjugate(Fp12._cyclotomicExp(t6, x)); + const t2_t5_pow_q2 = Fp12.frobeniusMap(Fp12.mul(t2, t5), 2); + const t4_t1_pow_q3 = Fp12.frobeniusMap(Fp12.mul(t4, t1), 3); + const t6_t1c_pow_q1 = Fp12.frobeniusMap(Fp12.mul(t6, Fp12.conjugate(t1)), 1); + const t7_t3c_t1 = Fp12.mul(Fp12.mul(t7, Fp12.conjugate(t3)), t1); + // (t2 * t5)^(q²) * (t4 * t1)^(q³) * (t6 * t1.conj)^(q^1) * t7 * t3.conj * t1 + return Fp12.mul(Fp12.mul(Fp12.mul(t2_t5_pow_q2, t4_t1_pow_q3), t6_t1c_pow_q1), t7_t3c_t1); + }, +}; +const FP12_FROBENIUS_COEFFICIENTS = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt('0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8'), + BigInt('0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff'), + BigInt('0x0'), + ], + [ + BigInt('0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2'), + BigInt('0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + BigInt('0x0'), + ], + [ + BigInt('0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995'), + BigInt('0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116'), + ], + [ + BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'), + BigInt('0x0'), + ], + [ + BigInt('0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3'), + BigInt('0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8'), + ], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + BigInt('0x0'), + ], + [ + BigInt('0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09'), + BigInt('0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2'), + ], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad'), + BigInt('0x0'), + ], + [ + BigInt('0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116'), + BigInt('0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995'), + ], +].map((n) => Fp2.fromBigTuple(n)); +// END OF CURVE FIELDS +// HashToCurve +// 3-isogeny map from E' to E +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#appendix-E.3 +const isogenyMapG2 = (0, hash_to_curve_js_1.isogenyMap)(Fp2, [ + // xNum + [ + [ + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + ], + [ + '0x0', + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d', + ], + [ + '0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1', + '0x0', + ], + ], + // xDen + [ + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63', + ], + [ + '0xc', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f', + ], + ['0x1', '0x0'], // LAST 1 + ], + // yNum + [ + [ + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + ], + [ + '0x0', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f', + ], + [ + '0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10', + '0x0', + ], + ], + // yDen + [ + [ + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + ], + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3', + ], + [ + '0x12', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99', + ], + ['0x1', '0x0'], // LAST 1 + ], +].map((i) => i.map((pair) => Fp2.fromBigTuple(pair.map(BigInt))))); +// 11-isogeny map from E' to E +const isogenyMapG1 = (0, hash_to_curve_js_1.isogenyMap)(Fp, [ + // xNum + [ + '0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7', + '0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb', + '0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0', + '0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861', + '0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9', + '0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983', + '0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84', + '0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e', + '0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317', + '0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e', + '0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b', + '0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229', + ], + // xDen + [ + '0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c', + '0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff', + '0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19', + '0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8', + '0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e', + '0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5', + '0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a', + '0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e', + '0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641', + '0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33', + '0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696', + '0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6', + '0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb', + '0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb', + '0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0', + '0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2', + '0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29', + '0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587', + '0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30', + '0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132', + '0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e', + '0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8', + '0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133', + '0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b', + '0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604', + ], + // yDen + [ + '0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1', + '0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d', + '0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2', + '0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416', + '0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d', + '0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac', + '0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c', + '0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9', + '0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a', + '0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55', + '0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8', + '0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092', + '0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc', + '0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7', + '0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], +].map((i) => i.map((j) => BigInt(j)))); +// SWU Map - Fp2 to G2': y² = x³ + 240i * x + 1012 + 1012i +const G2_SWU = (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp2, { + A: Fp2.create({ c0: Fp.create(_0n), c1: Fp.create(BigInt(240)) }), + B: Fp2.create({ c0: Fp.create(BigInt(1012)), c1: Fp.create(BigInt(1012)) }), + Z: Fp2.create({ c0: Fp.create(BigInt(-2)), c1: Fp.create(BigInt(-1)) }), // Z: -(2 + I) +}); +// Optimized SWU Map - Fp to G1 +const G1_SWU = (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, { + A: Fp.create(BigInt('0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d')), + B: Fp.create(BigInt('0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0')), + Z: Fp.create(BigInt(11)), +}); +// Endomorphisms (for fast cofactor clearing) +// Ψ(P) endomorphism +const ut_root = Fp6.create({ c0: Fp2.ZERO, c1: Fp2.ONE, c2: Fp2.ZERO }); +const wsq = Fp12.create({ c0: ut_root, c1: Fp6.ZERO }); +const wcu = Fp12.create({ c0: Fp6.ZERO, c1: ut_root }); +const [wsq_inv, wcu_inv] = Fp12.invertBatch([wsq, wcu]); +function psi(x, y) { + // Untwist Fp2->Fp12 && frobenius(1) && twist back + const x2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wsq_inv, x), 1), wsq).c0.c0; + const y2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wcu_inv, y), 1), wcu).c0.c0; + return [x2, y2]; +} +// Ψ endomorphism +function G2psi(c, P) { + const affine = P.toAffine(); + const p = psi(affine.x, affine.y); + return new c(p[0], p[1], Fp2.ONE); +} +// Ψ²(P) endomorphism +// 1 / F2(2)^((p-1)/3) in GF(p²) +const PSI2_C1 = BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'); +function psi2(x, y) { + return [Fp2.mul(x, PSI2_C1), Fp2.neg(y)]; +} +function G2psi2(c, P) { + const affine = P.toAffine(); + const p = psi2(affine.x, affine.y); + return new c(p[0], p[1], Fp2.ONE); +} +// Default hash_to_field options are for hash to G2. +// +// Parameter definitions are in section 5.3 of the spec unless otherwise noted. +// Parameter values come from section 8.8.2 of the spec. +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-8.8.2 +// +// Base field F is GF(p^m) +// p = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab +// m = 2 (or 1 for G1 see section 8.8.1) +// k = 128 +const htfDefaults = Object.freeze({ + // DST: a domain separation tag + // defined in section 2.2.5 + // Use utils.getDSTLabel(), utils.setDSTLabel(value) + DST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + encodeDST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + // p: the characteristic of F + // where F is a finite field of characteristic p and order q = p^m + p: Fp.ORDER, + // m: the extension degree of F, m >= 1 + // where F is a finite field of characteristic p and order q = p^m + m: 2, + // k: the target security level for the suite in bits + // defined in section 5.1 + k: 128, + // option to use a message that has already been processed by + // expand_message_xmd + expand: 'xmd', + // Hash functions for: expand_message_xmd is appropriate for use with a + // wide range of hash functions, including SHA-2, SHA-3, BLAKE2, and others. + // BBS+ uses blake2: https://github.com/hyperledger/aries-framework-go/issues/2247 + hash: sha256_1.sha256, +}); +// Encoding utils +// Point on G1 curve: (x, y) +const C_BIT_POS = Fp.BITS; // C_bit, compression bit for serialization flag +const I_BIT_POS = Fp.BITS + 1; // I_bit, point-at-infinity bit for serialization flag +const S_BIT_POS = Fp.BITS + 2; // S_bit, sign bit for serialization flag +// Compressed point of infinity +const COMPRESSED_ZERO = Fp.toBytes((0, utils_js_1.bitSet)((0, utils_js_1.bitSet)(_0n, I_BIT_POS, true), S_BIT_POS, true)); // set compressed & point-at-infinity bits +function signatureG2ToRawBytes(point) { + // NOTE: by some reasons it was missed in bls12-381, looks like bug + point.assertValidity(); + const len = Fp.BYTES; + if (point.equals(exports.bls12_381.G2.ProjectivePoint.ZERO)) + return (0, utils_js_1.concatBytes)(COMPRESSED_ZERO, (0, utils_js_1.numberToBytesBE)(_0n, len)); + const { x, y } = point.toAffine(); + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + const tmp = y1 > _0n ? y1 * _2n : y0 * _2n; + const aflag1 = Boolean((tmp / Fp.ORDER) & _1n); + const z1 = (0, utils_js_1.bitSet)((0, utils_js_1.bitSet)(x1, 381, aflag1), S_BIT_POS, true); + const z2 = x0; + return (0, utils_js_1.concatBytes)((0, utils_js_1.numberToBytesBE)(z1, len), (0, utils_js_1.numberToBytesBE)(z2, len)); +} +// To verify curve parameters, see pairing-friendly-curves spec: +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-09 +// Basic math is done over finite fields over p. +// More complicated math is done over polynominal extension fields. +// To simplify calculations in Fp12, we construct extension tower: +// Fp₁₂ = Fp₆² => Fp₂³ +// Fp(u) / (u² - β) where β = -1 +// Fp₂(v) / (v³ - ξ) where ξ = u + 1 +// Fp₆(w) / (w² - γ) where γ = v +// Here goes constants && point encoding format +exports.bls12_381 = (0, bls_js_1.bls)({ + // Fields + fields: { + Fp, + Fp2, + Fp6, + Fp12, + Fr, + }, + // G1 is the order-q subgroup of E1(Fp) : y² = x³ + 4, #E1(Fp) = h1q, where + // characteristic; z + (z⁴ - z² + 1)(z - 1)²/3 + G1: { + Fp, + // cofactor; (z - 1)²/3 + h: BigInt('0x396c8c005555e1568c00aaab0000aaab'), + // generator's coordinates + // x = 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507 + // y = 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569 + Gx: BigInt('0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb'), + Gy: BigInt('0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1'), + a: Fp.ZERO, + b: _4n, + htfDefaults: { ...htfDefaults, m: 1 }, + wrapPrivateKey: true, + allowInfinityPoint: true, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, point) => { + // φ endomorphism + const cubicRootOfUnityModP = BigInt('0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'); + const phi = new c(Fp.mul(point.px, cubicRootOfUnityModP), point.py, point.pz); + // todo: unroll + const xP = point.multiplyUnsafe(exports.bls12_381.params.x).negate(); // [x]P + const u2P = xP.multiplyUnsafe(exports.bls12_381.params.x); // [u2]P + return u2P.equals(phi); + // https://eprint.iacr.org/2019/814.pdf + // (z² − 1)/3 + // const c1 = BigInt('0x396c8c005555e1560000000055555555'); + // const P = this; + // const S = P.sigma(); + // const Q = S.double(); + // const S2 = S.sigma(); + // // [(z² − 1)/3](2σ(P) − P − σ²(P)) − σ²(P) = O + // const left = Q.subtract(P).subtract(S2).multiplyUnsafe(c1); + // const C = left.subtract(S2); + // return C.isZero(); + }, + // Clear cofactor of G1 + // https://eprint.iacr.org/2019/403 + clearCofactor: (c, point) => { + // return this.multiplyUnsafe(CURVE.h); + return point.multiplyUnsafe(exports.bls12_381.params.x).add(point); // x*P + P + }, + mapToCurve: (scalars) => { + const { x, y } = G1_SWU(Fp.create(scalars[0])); + return isogenyMapG1(x, y); + }, + fromBytes: (bytes) => { + bytes = bytes.slice(); + if (bytes.length === 48) { + // TODO: Fp.bytes + const P = Fp.ORDER; + const compressedValue = (0, utils_js_1.bytesToNumberBE)(bytes); + const bflag = (0, utils_js_1.bitGet)(compressedValue, I_BIT_POS); + // Zero + if (bflag === _1n) + return { x: _0n, y: _0n }; + const x = Fp.create(compressedValue & Fp.MASK); + const right = Fp.add(Fp.pow(x, _3n), Fp.create(exports.bls12_381.params.G1b)); // y² = x³ + b + let y = Fp.sqrt(right); + if (!y) + throw new Error('Invalid compressed G1 point'); + const aflag = (0, utils_js_1.bitGet)(compressedValue, C_BIT_POS); + if ((y * _2n) / P !== aflag) + y = Fp.neg(y); + return { x: Fp.create(x), y: Fp.create(y) }; + } + else if (bytes.length === 96) { + // Check if the infinity flag is set + if ((bytes[0] & (1 << 6)) !== 0) + return exports.bls12_381.G1.ProjectivePoint.ZERO.toAffine(); + const x = (0, utils_js_1.bytesToNumberBE)(bytes.subarray(0, Fp.BYTES)); + const y = (0, utils_js_1.bytesToNumberBE)(bytes.subarray(Fp.BYTES)); + return { x: Fp.create(x), y: Fp.create(y) }; + } + else { + throw new Error('Invalid point G1, expected 48/96 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) + return COMPRESSED_ZERO.slice(); + const P = Fp.ORDER; + let num; + num = (0, utils_js_1.bitSet)(x, C_BIT_POS, Boolean((y * _2n) / P)); // set aflag + num = (0, utils_js_1.bitSet)(num, S_BIT_POS, true); + return (0, utils_js_1.numberToBytesBE)(num, Fp.BYTES); + } + else { + if (isZero) { + // 2x PUBLIC_KEY_LENGTH + const x = (0, utils_js_1.concatBytes)(new Uint8Array([0x40]), new Uint8Array(2 * Fp.BYTES - 1)); + return x; + } + else { + return (0, utils_js_1.concatBytes)((0, utils_js_1.numberToBytesBE)(x, Fp.BYTES), (0, utils_js_1.numberToBytesBE)(y, Fp.BYTES)); + } + } + }, + }, + // G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1), + // where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where + // G² - 1 + // h2q + G2: { + Fp: Fp2, + // cofactor + h: BigInt('0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5'), + Gx: Fp2.fromBigTuple([ + BigInt('0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8'), + BigInt('0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e'), + ]), + // y = + // 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582, + // 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905 + Gy: Fp2.fromBigTuple([ + BigInt('0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801'), + BigInt('0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be'), + ]), + a: Fp2.ZERO, + b: Fp2.fromBigTuple([_4n, _4n]), + hEff: BigInt('0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551'), + htfDefaults: { ...htfDefaults }, + wrapPrivateKey: true, + allowInfinityPoint: true, + mapToCurve: (scalars) => { + const { x, y } = G2_SWU(Fp2.fromBigTuple(scalars)); + return isogenyMapG2(x, y); + }, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, P) => { + return P.multiplyUnsafe(exports.bls12_381.params.x).negate().equals(G2psi(c, P)); // ψ(P) == [u](P) + // Older version: https://eprint.iacr.org/2019/814.pdf + // Ψ²(P) => Ψ³(P) => [z]Ψ³(P) where z = -x => [z]Ψ³(P) - Ψ²(P) + P == O + // return P.psi2().psi().mulNegX().subtract(psi2).add(P).isZero(); + }, + // Maps the point into the prime-order subgroup G2. + // clear_cofactor_bls12381_g2 from cfrg-hash-to-curve-11 + // https://eprint.iacr.org/2017/419.pdf + // prettier-ignore + clearCofactor: (c, P) => { + const x = exports.bls12_381.params.x; + let t1 = P.multiplyUnsafe(x).negate(); // [-x]P + let t2 = G2psi(c, P); // Ψ(P) + let t3 = P.double(); // 2P + t3 = G2psi2(c, t3); // Ψ²(2P) + t3 = t3.subtract(t2); // Ψ²(2P) - Ψ(P) + t2 = t1.add(t2); // [-x]P + Ψ(P) + t2 = t2.multiplyUnsafe(x).negate(); // [x²]P - [x]Ψ(P) + t3 = t3.add(t2); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + t3 = t3.subtract(t1); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P + const Q = t3.subtract(P); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P - 1P + return Q; // [x²-x-1]P + [x-1]Ψ(P) + Ψ²(2P) + }, + fromBytes: (bytes) => { + bytes = bytes.slice(); + const m_byte = bytes[0] & 0xe0; + if (m_byte === 0x20 || m_byte === 0x60 || m_byte === 0xe0) { + throw new Error('Invalid encoding flag: ' + m_byte); + } + const bitC = m_byte & 0x80; // compression bit + const bitI = m_byte & 0x40; // point at infinity bit + const bitS = m_byte & 0x20; // sign bit + const L = Fp.BYTES; + const slc = (b, from, to) => (0, utils_js_1.bytesToNumberBE)(b.slice(from, to)); + if (bytes.length === 96 && bitC) { + const b = exports.bls12_381.params.G2b; + const P = Fp.ORDER; + bytes[0] = bytes[0] & 0x1f; // clear flags + if (bitI) { + // check that all bytes are 0 + if (bytes.reduce((p, c) => (p !== 0 ? c + 1 : c), 0) > 0) { + throw new Error('Invalid compressed G2 point'); + } + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x_1 = slc(bytes, 0, L); + const x_0 = slc(bytes, L, 2 * L); + const x = Fp2.create({ c0: Fp.create(x_0), c1: Fp.create(x_1) }); + const right = Fp2.add(Fp2.pow(x, _3n), b); // y² = x³ + 4 * (u+1) = x³ + b + let y = Fp2.sqrt(right); + const Y_bit = y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P ? _1n : _0n; + y = bitS > 0 && Y_bit > 0 ? y : Fp2.neg(y); + return { x, y }; + } + else if (bytes.length === 192 && !bitC) { + // Check if the infinity flag is set + if ((bytes[0] & (1 << 6)) !== 0) { + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x1 = slc(bytes, 0, L); + const x0 = slc(bytes, L, 2 * L); + const y1 = slc(bytes, 2 * L, 3 * L); + const y0 = slc(bytes, 3 * L, 4 * L); + return { x: Fp2.fromBigTuple([x0, x1]), y: Fp2.fromBigTuple([y0, y1]) }; + } + else { + throw new Error('Invalid point G2, expected 96/192 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const { BYTES: len, ORDER: P } = Fp; + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) + return (0, utils_js_1.concatBytes)(COMPRESSED_ZERO, (0, utils_js_1.numberToBytesBE)(_0n, len)); + const flag = Boolean(y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P); + // set compressed & sign bits (looks like different offsets than for G1/Fp?) + let x_1 = (0, utils_js_1.bitSet)(x.c1, C_BIT_POS, flag); + x_1 = (0, utils_js_1.bitSet)(x_1, S_BIT_POS, true); + return (0, utils_js_1.concatBytes)((0, utils_js_1.numberToBytesBE)(x_1, len), (0, utils_js_1.numberToBytesBE)(x.c0, len)); + } + else { + if (isZero) + return (0, utils_js_1.concatBytes)(new Uint8Array([0x40]), new Uint8Array(4 * len - 1)); // bytes[0] |= 1 << 6; + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + return (0, utils_js_1.concatBytes)((0, utils_js_1.numberToBytesBE)(x1, len), (0, utils_js_1.numberToBytesBE)(x0, len), (0, utils_js_1.numberToBytesBE)(y1, len), (0, utils_js_1.numberToBytesBE)(y0, len)); + } + }, + Signature: { + // TODO: Optimize, it's very slow because of sqrt. + fromHex(hex) { + hex = (0, utils_js_1.ensureBytes)('signatureHex', hex); + const P = Fp.ORDER; + const half = hex.length / 2; + if (half !== 48 && half !== 96) + throw new Error('Invalid compressed signature length, must be 96 or 192'); + const z1 = (0, utils_js_1.bytesToNumberBE)(hex.slice(0, half)); + const z2 = (0, utils_js_1.bytesToNumberBE)(hex.slice(half)); + // Indicates the infinity point + const bflag1 = (0, utils_js_1.bitGet)(z1, I_BIT_POS); + if (bflag1 === _1n) + return exports.bls12_381.G2.ProjectivePoint.ZERO; + const x1 = Fp.create(z1 & Fp.MASK); + const x2 = Fp.create(z2); + const x = Fp2.create({ c0: x2, c1: x1 }); + const y2 = Fp2.add(Fp2.pow(x, _3n), exports.bls12_381.params.G2b); // y² = x³ + 4 + // The slow part + let y = Fp2.sqrt(y2); + if (!y) + throw new Error('Failed to find a square root'); + // Choose the y whose leftmost bit of the imaginary part is equal to the a_flag1 + // If y1 happens to be zero, then use the bit of y0 + const { re: y0, im: y1 } = Fp2.reim(y); + const aflag1 = (0, utils_js_1.bitGet)(z1, 381); + const isGreater = y1 > _0n && (y1 * _2n) / P !== aflag1; + const isZero = y1 === _0n && (y0 * _2n) / P !== aflag1; + if (isGreater || isZero) + y = Fp2.neg(y); + const point = exports.bls12_381.G2.ProjectivePoint.fromAffine({ x, y }); + point.assertValidity(); + return point; + }, + toRawBytes(point) { + return signatureG2ToRawBytes(point); + }, + toHex(point) { + return (0, utils_js_1.bytesToHex)(signatureG2ToRawBytes(point)); + }, + }, + }, + params: { + x: BLS_X, + r: Fr.ORDER, // order; z⁴ − z² + 1; CURVE.n from other curves + }, + htfDefaults, + hash: sha256_1.sha256, + randomBytes: utils_1.randomBytes, +}); +//# sourceMappingURL=bls12-381.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/bls12-381.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/bls12-381.js.map new file mode 100644 index 0000000..55ecfb5 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/bls12-381.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bls12-381.js","sourceRoot":"","sources":["src/bls12-381.ts"],"names":[],"mappings":";AAAA,sEAAsE;;;AAEtE,uFAAuF;AACvF,gDAAgD;AAChD,kGAAkG;AAClG,+EAA+E;AAC/E,EAAE;AACF,mGAAmG;AACnG,+EAA+E;AAC/E,+FAA+F;AAC/F,+EAA+E;AAC/E,oFAAoF;AACpF,EAAE;AACF,cAAc;AACd,gDAAgD;AAChD,4BAA4B;AAC5B,2FAA2F;AAC3F,mHAAmH;AACnH,0FAA0F;AAC1F,2HAA2H;AAC3H,6CAA6C;AAC7C,EAAE;AACF,eAAe;AACf,+BAA+B;AAC/B,8BAA8B;AAC9B,0DAA0D;AAC1D,4EAA4E;AAC5E,6DAA6D;AAC7D,6DAA6D;AAC7D,iDAA8C;AAC9C,+CAAkD;AAClD,8CAAiD;AACjD,6CAA6C;AAC7C,kDAW6B;AAC7B,QAAQ;AACR,8DAKmC;AACnC,kEAAyD;AAEzD,qEAAqE;AACrE,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAC1F,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;AAEzC,eAAe;AACf,uBAAuB;AACvB,MAAM,MAAM,GAAG,MAAM,CACnB,oGAAoG,CACrG,CAAC;AACF,MAAM,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;AAE7B,uBAAuB;AAC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/@noble/curves/bn254.d.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/bn254.d.ts new file mode 100644 index 0000000..fd7064a --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/bn254.d.ts @@ -0,0 +1,8 @@ +/** + * bn254 pairing-friendly curve. + * Previously known as alt_bn_128, when it had 128-bit security. + * Recent research shown it's weaker, the naming has been adjusted to its prime bit count. + * https://github.com/zcash/zcash/issues/2502 + */ +export declare const bn254: import("./abstract/weierstrass.js").CurveFn; +//# sourceMappingURL=bn254.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/bn254.d.ts.map b/node_modules/@scure/bip32/node_modules/@noble/curves/bn254.d.ts.map new file mode 100644 index 0000000..572db18 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/bn254.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bn254.d.ts","sourceRoot":"","sources":["src/bn254.ts"],"names":[],"mappings":"AAKA;;;;;GAKG;AACH,eAAO,MAAM,KAAK,6CAShB,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/bn254.js b/node_modules/@scure/bip32/node_modules/@noble/curves/bn254.js new file mode 100644 index 0000000..8b1c4b7 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/bn254.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bn254 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha256_1 = require("@noble/hashes/sha256"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const modular_js_1 = require("./abstract/modular.js"); +/** + * bn254 pairing-friendly curve. + * Previously known as alt_bn_128, when it had 128-bit security. + * Recent research shown it's weaker, the naming has been adjusted to its prime bit count. + * https://github.com/zcash/zcash/issues/2502 + */ +exports.bn254 = (0, weierstrass_js_1.weierstrass)({ + a: BigInt(0), + b: BigInt(3), + Fp: (0, modular_js_1.Field)(BigInt('0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47')), + n: BigInt('0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001'), + Gx: BigInt(1), + Gy: BigInt(2), + h: BigInt(1), + ...(0, _shortw_utils_js_1.getHash)(sha256_1.sha256), +}); +//# sourceMappingURL=bn254.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/bn254.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/bn254.js.map new file mode 100644 index 0000000..a54fb58 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/bn254.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bn254.js","sourceRoot":"","sources":["src/bn254.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,iDAA8C;AAC9C,8DAAwD;AACxD,yDAA6C;AAC7C,sDAA8C;AAC9C;;;;;GAKG;AACU,QAAA,KAAK,GAAG,IAAA,4BAAW,EAAC;IAC/B,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE,EAAE,IAAA,kBAAK,EAAC,MAAM,CAAC,oEAAoE,CAAC,CAAC;IACvF,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,IAAA,0BAAO,EAAC,eAAM,CAAC;CACnB,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/ed25519.d.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/ed25519.d.ts new file mode 100644 index 0000000..b996bf4 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/ed25519.d.ts @@ -0,0 +1,75 @@ +import { ExtPointType } from './abstract/edwards.js'; +import { Hex } from './abstract/utils.js'; +import { htfBasicOpts } from './abstract/hash-to-curve.js'; +import { AffinePoint } from './abstract/curve.js'; +export declare const ED25519_TORSION_SUBGROUP: string[]; +export declare const ed25519: import("./abstract/edwards.js").CurveFn; +export declare const ed25519ctx: import("./abstract/edwards.js").CurveFn; +export declare const ed25519ph: import("./abstract/edwards.js").CurveFn; +export declare const x25519: import("./abstract/montgomery.js").CurveFn; +/** + * Converts ed25519 public key to x25519 public key. Uses formula: + * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)` + * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))` + * @example + * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey()); + * const aPriv = x25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub)) + */ +export declare function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array; +export declare const edwardsToMontgomery: typeof edwardsToMontgomeryPub; +/** + * Converts ed25519 secret key to x25519 secret key. + * @example + * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey()); + * const aPriv = ed25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub) + */ +export declare function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array; +export declare const hashToCurve: (msg: Uint8Array, options?: htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +type ExtendedPoint = ExtPointType; +/** + * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Ristretto was created to solve this. + * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +declare class RistPoint { + private readonly ep; + static BASE: RistPoint; + static ZERO: RistPoint; + constructor(ep: ExtendedPoint); + static fromAffine(ap: AffinePoint): RistPoint; + /** + * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://ristretto.group/formulas/elligator.html + * @param hex 64-byte output of a hash function + */ + static hashToCurve(hex: Hex): RistPoint; + /** + * Converts ristretto-encoded string to ristretto point. + * https://ristretto.group/formulas/decoding.html + * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding + */ + static fromHex(hex: Hex): RistPoint; + /** + * Encodes ristretto point to Uint8Array. + * https://ristretto.group/formulas/encoding.html + */ + toRawBytes(): Uint8Array; + toHex(): string; + toString(): string; + equals(other: RistPoint): boolean; + add(other: RistPoint): RistPoint; + subtract(other: RistPoint): RistPoint; + multiply(scalar: bigint): RistPoint; + multiplyUnsafe(scalar: bigint): RistPoint; +} +export declare const RistrettoPoint: typeof RistPoint; +export declare const hash_to_ristretto255: (msg: Uint8Array, options: htfBasicOpts) => RistPoint; +export {}; +//# sourceMappingURL=ed25519.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/ed25519.d.ts.map b/node_modules/@scure/bip32/node_modules/@noble/curves/ed25519.d.ts.map new file mode 100644 index 0000000..13be7bc --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/ed25519.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ed25519.d.ts","sourceRoot":"","sources":["src/ed25519.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,YAAY,EAAkB,MAAM,uBAAuB,CAAC;AAGrE,OAAO,EAKL,GAAG,EAEJ,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAgB,YAAY,EAAsB,MAAM,6BAA6B,CAAC;AAC7F,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAwElD,eA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,EAAE,MAAM,GAAG,SAAS;CAG1C;AACD,eAAO,MAAM,cAAc,kBAIvB,CAAC;AAIL,eAAO,MAAM,oBAAoB,QAAS,UAAU,WAAW,YAAY,cAM1E,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/ed25519.js b/node_modules/@scure/bip32/node_modules/@noble/curves/ed25519.js new file mode 100644 index 0000000..c750251 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/ed25519.js @@ -0,0 +1,436 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hash_to_ristretto255 = exports.RistrettoPoint = exports.encodeToCurve = exports.hashToCurve = exports.edwardsToMontgomeryPriv = exports.edwardsToMontgomery = exports.edwardsToMontgomeryPub = exports.x25519 = exports.ed25519ph = exports.ed25519ctx = exports.ed25519 = exports.ED25519_TORSION_SUBGROUP = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha512_1 = require("@noble/hashes/sha512"); +const utils_1 = require("@noble/hashes/utils"); +const edwards_js_1 = require("./abstract/edwards.js"); +const montgomery_js_1 = require("./abstract/montgomery.js"); +const modular_js_1 = require("./abstract/modular.js"); +const utils_js_1 = require("./abstract/utils.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +/** + * ed25519 Twisted Edwards curve with following addons: + * - X25519 ECDH + * - Ristretto cofactor elimination + * - Elligator hash-to-group / point indistinguishability + */ +const ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949'); +// √(-1) aka √(a) aka 2^((p-1)/4) +const ED25519_SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752'); +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _5n = BigInt(5); +// prettier-ignore +const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80); +function ed25519_pow_2_252_3(x) { + const P = ED25519_P; + const x2 = (x * x) % P; + const b2 = (x2 * x) % P; // x^3, 11 + const b4 = ((0, modular_js_1.pow2)(b2, _2n, P) * b2) % P; // x^15, 1111 + const b5 = ((0, modular_js_1.pow2)(b4, _1n, P) * x) % P; // x^31 + const b10 = ((0, modular_js_1.pow2)(b5, _5n, P) * b5) % P; + const b20 = ((0, modular_js_1.pow2)(b10, _10n, P) * b10) % P; + const b40 = ((0, modular_js_1.pow2)(b20, _20n, P) * b20) % P; + const b80 = ((0, modular_js_1.pow2)(b40, _40n, P) * b40) % P; + const b160 = ((0, modular_js_1.pow2)(b80, _80n, P) * b80) % P; + const b240 = ((0, modular_js_1.pow2)(b160, _80n, P) * b80) % P; + const b250 = ((0, modular_js_1.pow2)(b240, _10n, P) * b10) % P; + const pow_p_5_8 = ((0, modular_js_1.pow2)(b250, _2n, P) * x) % P; + // ^ To pow to (p+3)/8, multiply it by x. + return { pow_p_5_8, b2 }; +} +function adjustScalarBytes(bytes) { + // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar, + // set the three least significant bits of the first byte + bytes[0] &= 248; // 0b1111_1000 + // and the most significant bit of the last to zero, + bytes[31] &= 127; // 0b0111_1111 + // set the second most significant bit of the last byte to 1 + bytes[31] |= 64; // 0b0100_0000 + return bytes; +} +// sqrt(u/v) +function uvRatio(u, v) { + const P = ED25519_P; + const v3 = (0, modular_js_1.mod)(v * v * v, P); // v³ + const v7 = (0, modular_js_1.mod)(v3 * v3 * v, P); // v⁷ + // (p+3)/8 and (p-5)/8 + const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8; + let x = (0, modular_js_1.mod)(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8 + const vx2 = (0, modular_js_1.mod)(v * x * x, P); // vx² + const root1 = x; // First root candidate + const root2 = (0, modular_js_1.mod)(x * ED25519_SQRT_M1, P); // Second root candidate + const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root + const useRoot2 = vx2 === (0, modular_js_1.mod)(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4) + const noRoot = vx2 === (0, modular_js_1.mod)(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1) + if (useRoot1) + x = root1; + if (useRoot2 || noRoot) + x = root2; // We return root2 anyway, for const-time + if ((0, modular_js_1.isNegativeLE)(x, P)) + x = (0, modular_js_1.mod)(-x, P); + return { isValid: useRoot1 || useRoot2, value: x }; +} +// Just in case +exports.ED25519_TORSION_SUBGROUP = [ + '0100000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', + '0000000000000000000000000000000000000000000000000000000000000080', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05', + 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85', + '0000000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa', +]; +const Fp = (0, modular_js_1.Field)(ED25519_P, undefined, true); +const ed25519Defaults = { + // Param: a + a: BigInt(-1), + // d is equal to -121665/121666 over finite field. + // Negative number is P - number, and division is invert(number, P) + d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'), + // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n + Fp, + // Subgroup order: how many points curve has + // 2n**252n + 27742317777372353535851937790883648493n; + n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'), + // Cofactor + h: BigInt(8), + // Base point (x, y) aka generator point + Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'), + Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'), + hash: sha512_1.sha512, + randomBytes: utils_1.randomBytes, + adjustScalarBytes, + // dom2 + // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3. + // Constant-time, u/√v + uvRatio, +}; +exports.ed25519 = (0, edwards_js_1.twistedEdwards)(ed25519Defaults); +function ed25519_domain(data, ctx, phflag) { + if (ctx.length > 255) + throw new Error('Context is too big'); + return (0, utils_1.concatBytes)((0, utils_1.utf8ToBytes)('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); +} +exports.ed25519ctx = (0, edwards_js_1.twistedEdwards)({ ...ed25519Defaults, domain: ed25519_domain }); +exports.ed25519ph = (0, edwards_js_1.twistedEdwards)({ + ...ed25519Defaults, + domain: ed25519_domain, + prehash: sha512_1.sha512, +}); +exports.x25519 = (() => (0, montgomery_js_1.montgomery)({ + P: ED25519_P, + a: BigInt(486662), + montgomeryBits: 255, + nByteLength: 32, + Gu: BigInt(9), + powPminus2: (x) => { + const P = ED25519_P; + // x^(p-2) aka x^(2^255-21) + const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x); + return (0, modular_js_1.mod)((0, modular_js_1.pow2)(pow_p_5_8, BigInt(3), P) * b2, P); + }, + adjustScalarBytes, + randomBytes: utils_1.randomBytes, +}))(); +/** + * Converts ed25519 public key to x25519 public key. Uses formula: + * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)` + * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))` + * @example + * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey()); + * const aPriv = x25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub)) + */ +function edwardsToMontgomeryPub(edwardsPub) { + const { y } = exports.ed25519.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y))); +} +exports.edwardsToMontgomeryPub = edwardsToMontgomeryPub; +exports.edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated +/** + * Converts ed25519 secret key to x25519 secret key. + * @example + * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey()); + * const aPriv = ed25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub) + */ +function edwardsToMontgomeryPriv(edwardsPriv) { + const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32)); + return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32); +} +exports.edwardsToMontgomeryPriv = edwardsToMontgomeryPriv; +// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator) +// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since +// SageMath returns different root first and everything falls apart +const ELL2_C1 = (Fp.ORDER + BigInt(3)) / BigInt(8); // 1. c1 = (q + 3) / 8 # Integer arithmetic +const ELL2_C2 = Fp.pow(_2n, ELL2_C1); // 2. c2 = 2^c1 +const ELL2_C3 = Fp.sqrt(Fp.neg(Fp.ONE)); // 3. c3 = sqrt(-1) +const ELL2_C4 = (Fp.ORDER - BigInt(5)) / BigInt(8); // 4. c4 = (q - 5) / 8 # Integer arithmetic +const ELL2_J = BigInt(486662); +// prettier-ignore +function map_to_curve_elligator2_curve25519(u) { + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1 + let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not + let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2) + let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2 + tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4 + tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3 + tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3 + tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7 + let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8) + y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8) + let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3 + tv2 = Fp.sqr(y11); // 19. tv2 = y11^2 + tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd + let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1 + let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt + let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd + let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u + y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2 + let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3 + let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1) + tv2 = Fp.sqr(y21); // 28. tv2 = y21^2 + tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2 + let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt + tv2 = Fp.sqr(y1); // 32. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd + let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2 + let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4) + return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1) +} +const ELL2_C1_EDWARDS = (0, modular_js_1.FpSqrtEven)(Fp, Fp.neg(BigInt(486664))); // sgn0(c1) MUST equal 0 +function map_to_curve_elligator2_edwards25519(u) { + const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) = + // map_to_curve_elligator2_curve25519(u) + let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd + xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1 + let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM + let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd + let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d) + let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd + let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0 + xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e) + xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e) + yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e) + yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e) + const inv = Fp.invertBatch([xd, yd]); // batch division + return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd) +} +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.ed25519.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), { + DST: 'edwards25519_XMD:SHA-512_ELL2_RO_', + encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha512_1.sha512, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +function assertRstPoint(other) { + if (!(other instanceof RistPoint)) + throw new Error('RistrettoPoint expected'); +} +// √(-1) aka √(a) aka 2^((p-1)/4) +const SQRT_M1 = ED25519_SQRT_M1; +// √(ad - 1) +const SQRT_AD_MINUS_ONE = BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235'); +// 1 / √(a-d) +const INVSQRT_A_MINUS_D = BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578'); +// 1-d² +const ONE_MINUS_D_SQ = BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838'); +// (d-1)² +const D_MINUS_ONE_SQ = BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952'); +// Calculates 1/√(number) +const invertSqrt = (number) => uvRatio(_1n, number); +const MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const bytes255ToNumberLE = (bytes) => exports.ed25519.CURVE.Fp.create((0, utils_js_1.bytesToNumberLE)(bytes) & MAX_255B); +// Computes Elligator map for Ristretto +// https://ristretto.group/formulas/elligator.html +function calcElligatorRistrettoMap(r0) { + const { d } = exports.ed25519.CURVE; + const P = exports.ed25519.CURVE.Fp.ORDER; + const mod = exports.ed25519.CURVE.Fp.create; + const r = mod(SQRT_M1 * r0 * r0); // 1 + const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2 + let c = BigInt(-1); // 3 + const D = mod((c - d * r) * mod(r + d)); // 4 + let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5 + let s_ = mod(s * r0); // 6 + if (!(0, modular_js_1.isNegativeLE)(s_, P)) + s_ = mod(-s_); + if (!Ns_D_is_sq) + s = s_; // 7 + if (!Ns_D_is_sq) + c = r; // 8 + const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9 + const s2 = s * s; + const W0 = mod((s + s) * D); // 10 + const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11 + const W2 = mod(_1n - s2); // 12 + const W3 = mod(_1n + s2); // 13 + return new exports.ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2)); +} +/** + * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Ristretto was created to solve this. + * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +class RistPoint { + // Private property to discourage combining ExtendedPoint + RistrettoPoint + // Always use Ristretto encoding/decoding instead. + constructor(ep) { + this.ep = ep; + } + static fromAffine(ap) { + return new RistPoint(exports.ed25519.ExtendedPoint.fromAffine(ap)); + } + /** + * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://ristretto.group/formulas/elligator.html + * @param hex 64-byte output of a hash function + */ + static hashToCurve(hex) { + hex = (0, utils_js_1.ensureBytes)('ristrettoHash', hex, 64); + const r1 = bytes255ToNumberLE(hex.slice(0, 32)); + const R1 = calcElligatorRistrettoMap(r1); + const r2 = bytes255ToNumberLE(hex.slice(32, 64)); + const R2 = calcElligatorRistrettoMap(r2); + return new RistPoint(R1.add(R2)); + } + /** + * Converts ristretto-encoded string to ristretto point. + * https://ristretto.group/formulas/decoding.html + * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding + */ + static fromHex(hex) { + hex = (0, utils_js_1.ensureBytes)('ristrettoHex', hex, 32); + const { a, d } = exports.ed25519.CURVE; + const P = exports.ed25519.CURVE.Fp.ORDER; + const mod = exports.ed25519.CURVE.Fp.create; + const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint'; + const s = bytes255ToNumberLE(hex); + // 1. Check that s_bytes is the canonical encoding of a field element, or else abort. + // 3. Check that s is non-negative, or else abort + if (!(0, utils_js_1.equalBytes)((0, utils_js_1.numberToBytesLE)(s, 32), hex) || (0, modular_js_1.isNegativeLE)(s, P)) + throw new Error(emsg); + const s2 = mod(s * s); + const u1 = mod(_1n + a * s2); // 4 (a is -1) + const u2 = mod(_1n - a * s2); // 5 + const u1_2 = mod(u1 * u1); + const u2_2 = mod(u2 * u2); + const v = mod(a * d * u1_2 - u2_2); // 6 + const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7 + const Dx = mod(I * u2); // 8 + const Dy = mod(I * Dx * v); // 9 + let x = mod((s + s) * Dx); // 10 + if ((0, modular_js_1.isNegativeLE)(x, P)) + x = mod(-x); // 10 + const y = mod(u1 * Dy); // 11 + const t = mod(x * y); // 12 + if (!isValid || (0, modular_js_1.isNegativeLE)(t, P) || y === _0n) + throw new Error(emsg); + return new RistPoint(new exports.ed25519.ExtendedPoint(x, y, _1n, t)); + } + /** + * Encodes ristretto point to Uint8Array. + * https://ristretto.group/formulas/encoding.html + */ + toRawBytes() { + let { ex: x, ey: y, ez: z, et: t } = this.ep; + const P = exports.ed25519.CURVE.Fp.ORDER; + const mod = exports.ed25519.CURVE.Fp.create; + const u1 = mod(mod(z + y) * mod(z - y)); // 1 + const u2 = mod(x * y); // 2 + // Square root always exists + const u2sq = mod(u2 * u2); + const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3 + const D1 = mod(invsqrt * u1); // 4 + const D2 = mod(invsqrt * u2); // 5 + const zInv = mod(D1 * D2 * t); // 6 + let D; // 7 + if ((0, modular_js_1.isNegativeLE)(t * zInv, P)) { + let _x = mod(y * SQRT_M1); + let _y = mod(x * SQRT_M1); + x = _x; + y = _y; + D = mod(D1 * INVSQRT_A_MINUS_D); + } + else { + D = D2; // 8 + } + if ((0, modular_js_1.isNegativeLE)(x * zInv, P)) + y = mod(-y); // 9 + let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a)) + if ((0, modular_js_1.isNegativeLE)(s, P)) + s = mod(-s); + return (0, utils_js_1.numberToBytesLE)(s, 32); // 11 + } + toHex() { + return (0, utils_js_1.bytesToHex)(this.toRawBytes()); + } + toString() { + return this.toHex(); + } + // Compare one point to another. + equals(other) { + assertRstPoint(other); + const { ex: X1, ey: Y1 } = this.ep; + const { ex: X2, ey: Y2 } = other.ep; + const mod = exports.ed25519.CURVE.Fp.create; + // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2) + const one = mod(X1 * Y2) === mod(Y1 * X2); + const two = mod(Y1 * Y2) === mod(X1 * X2); + return one || two; + } + add(other) { + assertRstPoint(other); + return new RistPoint(this.ep.add(other.ep)); + } + subtract(other) { + assertRstPoint(other); + return new RistPoint(this.ep.subtract(other.ep)); + } + multiply(scalar) { + return new RistPoint(this.ep.multiply(scalar)); + } + multiplyUnsafe(scalar) { + return new RistPoint(this.ep.multiplyUnsafe(scalar)); + } +} +exports.RistrettoPoint = (() => { + if (!RistPoint.BASE) + RistPoint.BASE = new RistPoint(exports.ed25519.ExtendedPoint.BASE); + if (!RistPoint.ZERO) + RistPoint.ZERO = new RistPoint(exports.ed25519.ExtendedPoint.ZERO); + return RistPoint; +})(); +// https://datatracker.ietf.org/doc/draft-irtf-cfrg-hash-to-curve/14/ +// Appendix B. Hashing to ristretto255 +const hash_to_ristretto255 = (msg, options) => { + const d = options.DST; + const DST = typeof d === 'string' ? (0, utils_1.utf8ToBytes)(d) : d; + const uniform_bytes = (0, hash_to_curve_js_1.expand_message_xmd)(msg, DST, 64, sha512_1.sha512); + const P = RistPoint.hashToCurve(uniform_bytes); + return P; +}; +exports.hash_to_ristretto255 = hash_to_ristretto255; +//# sourceMappingURL=ed25519.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/ed25519.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/ed25519.js.map new file mode 100644 index 0000000..fb5b523 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/ed25519.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ed25519.js","sourceRoot":"","sources":["src/ed25519.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,iDAA8C;AAC9C,+CAA4E;AAC5E,sDAAqE;AACrE,4DAAsD;AACtD,sDAAmF;AACnF,kDAO6B;AAC7B,kEAA6F;AAG7F;;;;;GAKG;AAEH,MAAM,SAAS,GAAG,MAAM,CACtB,+EAA+E,CAChF,CAAC;AACF,iCAAiC;AACjC,MAAM,eAAe,GAAG,MAAM,CAC5B,+EAA+E,CAChF,CAAC;AAEF,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACzE,kBAAkB;AAClB,MAAM,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;AAEjF,SAAS,mBAAmB,CAAC,CAAS;IACpC,MAAM,CAAC,GAAG,SAAS,CAAC;IACpB,MAAM,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IACvB,MAAM,EAAE,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC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ACnD,CAAC;IAED,QAAQ,CAAC,MAAc;QACrB,OAAO,IAAI,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;IACjD,CAAC;IAED,cAAc,CAAC,MAAc;QAC3B,OAAO,IAAI,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAC;IACvD,CAAC;CACF;AACY,QAAA,cAAc,GAAmB,CAAC,GAAG,EAAE;IAClD,IAAI,CAAC,SAAS,CAAC,IAAI;QAAE,SAAS,CAAC,IAAI,GAAG,IAAI,SAAS,CAAC,eAAO,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;IAChF,IAAI,CAAC,SAAS,CAAC,IAAI;QAAE,SAAS,CAAC,IAAI,GAAG,IAAI,SAAS,CAAC,eAAO,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;IAChF,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC,EAAE,CAAC;AAEL,qEAAqE;AACrE,uCAAuC;AAChC,MAAM,oBAAoB,GAAG,CAAC,GAAe,EAAE,OAAqB,EAAE,EAAE;IAC7E,MAAM,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC;IACtB,MAAM,GAAG,GAAG,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAA,mBAAW,EAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACvD,MAAM,aAAa,GAAG,IAAA,qCAAkB,EAAC,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,eAAM,CAAC,CAAC;IAC/D,MAAM,CAAC,GAAG,SAAS,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC;IAC/C,OAAO,CAAC,CAAC;AACX,CAAC,CAAC;AANW,QAAA,oBAAoB,wBAM/B"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/ed448.d.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/ed448.d.ts new file mode 100644 index 0000000..c6e8068 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/ed448.d.ts @@ -0,0 +1,16 @@ +export declare const ed448: import("./abstract/edwards.js").CurveFn; +export declare const ed448ph: import("./abstract/edwards.js").CurveFn; +export declare const x448: import("./abstract/montgomery.js").CurveFn; +/** + * Converts edwards448 public key to x448 public key. Uses formula: + * * `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)` + * * `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))` + * @example + * const aPub = ed448.getPublicKey(utils.randomPrivateKey()); + * x448.getSharedSecret(edwardsToMontgomery(aPub), edwardsToMontgomery(someonesPub)) + */ +export declare function edwardsToMontgomeryPub(edwardsPub: string | Uint8Array): Uint8Array; +export declare const edwardsToMontgomery: typeof edwardsToMontgomeryPub; +export declare const hashToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +//# sourceMappingURL=ed448.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/ed448.d.ts.map b/node_modules/@scure/bip32/node_modules/@noble/curves/ed448.d.ts.map new file mode 100644 index 0000000..93b9d92 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/ed448.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ed448.d.ts","sourceRoot":"","sources":["src/ed448.ts"],"names":[],"mappings":"AAwHA,eAAO,MAAM,KAAK,yCAA4B,CAAC;AAE/C,eAAO,MAAM,OAAO,yCAAyD,CAAC;AAE9E,eAAO,MAAM,IAAI,4CAeV,CAAC;AAER;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,MAAM,GAAG,UAAU,GAAG,UAAU,CAIlF;AACD,eAAO,MAAM,mBAAmB,+BAAyB,CAAC;AA2F1D,eAAO,MAAM,WAAW,uJAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,uJAA8C,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/ed448.js b/node_modules/@scure/bip32/node_modules/@noble/curves/ed448.js new file mode 100644 index 0000000..5d08fc3 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/ed448.js @@ -0,0 +1,219 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeToCurve = exports.hashToCurve = exports.edwardsToMontgomery = exports.edwardsToMontgomeryPub = exports.x448 = exports.ed448ph = exports.ed448 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha3_1 = require("@noble/hashes/sha3"); +const utils_1 = require("@noble/hashes/utils"); +const edwards_js_1 = require("./abstract/edwards.js"); +const modular_js_1 = require("./abstract/modular.js"); +const montgomery_js_1 = require("./abstract/montgomery.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +/** + * Edwards448 (not Ed448-Goldilocks) curve with following addons: + * * X448 ECDH + * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2 + */ +const shake256_114 = (0, utils_1.wrapConstructor)(() => sha3_1.shake256.create({ dkLen: 114 })); +const shake256_64 = (0, utils_1.wrapConstructor)(() => sha3_1.shake256.create({ dkLen: 64 })); +const ed448P = BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439'); +// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4. +// Used for efficient square root calculation. +// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1] +function ed448_pow_Pminus3div4(x) { + const P = ed448P; + // prettier-ignore + const _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _11n = BigInt(11); + // prettier-ignore + const _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223); + const b2 = (x * x * x) % P; + const b3 = (b2 * b2 * x) % P; + const b6 = ((0, modular_js_1.pow2)(b3, _3n, P) * b3) % P; + const b9 = ((0, modular_js_1.pow2)(b6, _3n, P) * b3) % P; + const b11 = ((0, modular_js_1.pow2)(b9, _2n, P) * b2) % P; + const b22 = ((0, modular_js_1.pow2)(b11, _11n, P) * b11) % P; + const b44 = ((0, modular_js_1.pow2)(b22, _22n, P) * b22) % P; + const b88 = ((0, modular_js_1.pow2)(b44, _44n, P) * b44) % P; + const b176 = ((0, modular_js_1.pow2)(b88, _88n, P) * b88) % P; + const b220 = ((0, modular_js_1.pow2)(b176, _44n, P) * b44) % P; + const b222 = ((0, modular_js_1.pow2)(b220, _2n, P) * b2) % P; + const b223 = ((0, modular_js_1.pow2)(b222, _1n, P) * x) % P; + return ((0, modular_js_1.pow2)(b223, _223n, P) * b222) % P; +} +function adjustScalarBytes(bytes) { + // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, and the most + // significant bit of the last byte to 1. + bytes[0] &= 252; // 0b11111100 + // and the most significant bit of the last byte to 1. + bytes[55] |= 128; // 0b10000000 + // NOTE: is is NOOP for 56 bytes scalars (X25519/X448) + bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits) + return bytes; +} +const Fp = (0, modular_js_1.Field)(ed448P, 456, true); +const _4n = BigInt(4); +const ED448_DEF = { + // Param: a + a: BigInt(1), + // -39081. Negative number is P - number + d: BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358'), + // Finite field 𝔽p over which we'll do calculations; 2n**448n - 2n**224n - 1n + Fp, + // Subgroup order: how many points curve has; + // 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n + n: BigInt('181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779'), + nBitLength: 456, + // Cofactor + h: BigInt(4), + // Base point (x, y) aka generator point + Gx: BigInt('224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710'), + Gy: BigInt('298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660'), + // SHAKE256(dom4(phflag,context)||x, 114) + hash: shake256_114, + randomBytes: utils_1.randomBytes, + adjustScalarBytes, + // dom4 + domain: (data, ctx, phflag) => { + if (ctx.length > 255) + throw new Error(`Context is too big: ${ctx.length}`); + return (0, utils_1.concatBytes)((0, utils_1.utf8ToBytes)('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); + }, + // Constant-time ratio of u to v. Allows to combine inversion and square root u/√v. + // Uses algo from RFC8032 5.1.3. + uvRatio: (u, v) => { + const P = ed448P; + // https://datatracker.ietf.org/doc/html/rfc8032#section-5.2.3 + // To compute the square root of (u/v), the first step is to compute the + // candidate root x = (u/v)^((p+1)/4). This can be done using the + // following trick, to use a single modular powering for both the + // inversion of v and the square root: + // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p) + const u2v = (0, modular_js_1.mod)(u * u * v, P); // u²v + const u3v = (0, modular_js_1.mod)(u2v * u, P); // u³v + const u5v3 = (0, modular_js_1.mod)(u3v * u2v * v, P); // u⁵v³ + const root = ed448_pow_Pminus3div4(u5v3); + const x = (0, modular_js_1.mod)(u3v * root, P); + // Verify that root is exists + const x2 = (0, modular_js_1.mod)(x * x, P); // x² + // If vx² = u, the recovered x-coordinate is x. Otherwise, no + // square root exists, and the decoding fails. + return { isValid: (0, modular_js_1.mod)(x2 * v, P) === u, value: x }; + }, +}; +exports.ed448 = (0, edwards_js_1.twistedEdwards)(ED448_DEF); +// NOTE: there is no ed448ctx, since ed448 supports ctx by default +exports.ed448ph = (0, edwards_js_1.twistedEdwards)({ ...ED448_DEF, prehash: shake256_64 }); +exports.x448 = (() => (0, montgomery_js_1.montgomery)({ + a: BigInt(156326), + montgomeryBits: 448, + nByteLength: 57, + P: ed448P, + Gu: BigInt(5), + powPminus2: (x) => { + const P = ed448P; + const Pminus3div4 = ed448_pow_Pminus3div4(x); + const Pminus3 = (0, modular_js_1.pow2)(Pminus3div4, BigInt(2), P); + return (0, modular_js_1.mod)(Pminus3 * x, P); // Pminus3 * x = Pminus2 + }, + adjustScalarBytes, + randomBytes: utils_1.randomBytes, +}))(); +/** + * Converts edwards448 public key to x448 public key. Uses formula: + * * `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)` + * * `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))` + * @example + * const aPub = ed448.getPublicKey(utils.randomPrivateKey()); + * x448.getSharedSecret(edwardsToMontgomery(aPub), edwardsToMontgomery(someonesPub)) + */ +function edwardsToMontgomeryPub(edwardsPub) { + const { y } = exports.ed448.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((y - _1n) * Fp.inv(y + _1n))); +} +exports.edwardsToMontgomeryPub = edwardsToMontgomeryPub; +exports.edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated +// Hash To Curve Elligator2 Map +const ELL2_C1 = (Fp.ORDER - BigInt(3)) / BigInt(4); // 1. c1 = (q - 3) / 4 # Integer arithmetic +const ELL2_J = BigInt(156326); +function map_to_curve_elligator2_curve448(u) { + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + let e1 = Fp.eql(tv1, Fp.ONE); // 2. e1 = tv1 == 1 + tv1 = Fp.cmov(tv1, Fp.ZERO, e1); // 3. tv1 = CMOV(tv1, 0, e1) # If Z * u^2 == -1, set tv1 = 0 + let xd = Fp.sub(Fp.ONE, tv1); // 4. xd = 1 - tv1 + let x1n = Fp.neg(ELL2_J); // 5. x1n = -J + let tv2 = Fp.sqr(xd); // 6. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 7. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, Fp.neg(ELL2_J)); // 8. gx1 = -J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 9. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 10. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 11. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 12. tv3 = gxd^2 + tv2 = Fp.mul(gx1, gxd); // 13. tv2 = gx1 * gxd # gx1 * gxd + tv3 = Fp.mul(tv3, tv2); // 14. tv3 = tv3 * tv2 # gx1 * gxd^3 + let y1 = Fp.pow(tv3, ELL2_C1); // 15. y1 = tv3^c1 # (gx1 * gxd^3)^((p - 3) / 4) + y1 = Fp.mul(y1, tv2); // 16. y1 = y1 * tv2 # gx1 * gxd * (gx1 * gxd^3)^((p - 3) / 4) + let x2n = Fp.mul(x1n, Fp.neg(tv1)); // 17. x2n = -tv1 * x1n # x2 = x2n / xd = -1 * u^2 * x1n / xd + let y2 = Fp.mul(y1, u); // 18. y2 = y1 * u + y2 = Fp.cmov(y2, Fp.ZERO, e1); // 19. y2 = CMOV(y2, 0, e1) + tv2 = Fp.sqr(y1); // 20. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 21. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx1); // 22. e2 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e2); // 23. xn = CMOV(x2n, x1n, e2) # If e2, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e2); // 24. y = CMOV(y2, y1, e2) # If e2, y = y1, else y = y2 + let e3 = Fp.isOdd(y); // 25. e3 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e2 !== e3); // 26. y = CMOV(y, -y, e2 XOR e3) + return { xn, xd, yn: y, yd: Fp.ONE }; // 27. return (xn, xd, y, 1) +} +function map_to_curve_elligator2_edwards448(u) { + let { xn, xd, yn, yd } = map_to_curve_elligator2_curve448(u); // 1. (xn, xd, yn, yd) = map_to_curve_elligator2_curve448(u) + let xn2 = Fp.sqr(xn); // 2. xn2 = xn^2 + let xd2 = Fp.sqr(xd); // 3. xd2 = xd^2 + let xd4 = Fp.sqr(xd2); // 4. xd4 = xd2^2 + let yn2 = Fp.sqr(yn); // 5. yn2 = yn^2 + let yd2 = Fp.sqr(yd); // 6. yd2 = yd^2 + let xEn = Fp.sub(xn2, xd2); // 7. xEn = xn2 - xd2 + let tv2 = Fp.sub(xEn, xd2); // 8. tv2 = xEn - xd2 + xEn = Fp.mul(xEn, xd2); // 9. xEn = xEn * xd2 + xEn = Fp.mul(xEn, yd); // 10. xEn = xEn * yd + xEn = Fp.mul(xEn, yn); // 11. xEn = xEn * yn + xEn = Fp.mul(xEn, _4n); // 12. xEn = xEn * 4 + tv2 = Fp.mul(tv2, xn2); // 13. tv2 = tv2 * xn2 + tv2 = Fp.mul(tv2, yd2); // 14. tv2 = tv2 * yd2 + let tv3 = Fp.mul(yn2, _4n); // 15. tv3 = 4 * yn2 + let tv1 = Fp.add(tv3, yd2); // 16. tv1 = tv3 + yd2 + tv1 = Fp.mul(tv1, xd4); // 17. tv1 = tv1 * xd4 + let xEd = Fp.add(tv1, tv2); // 18. xEd = tv1 + tv2 + tv2 = Fp.mul(tv2, xn); // 19. tv2 = tv2 * xn + let tv4 = Fp.mul(xn, xd4); // 20. tv4 = xn * xd4 + let yEn = Fp.sub(tv3, yd2); // 21. yEn = tv3 - yd2 + yEn = Fp.mul(yEn, tv4); // 22. yEn = yEn * tv4 + yEn = Fp.sub(yEn, tv2); // 23. yEn = yEn - tv2 + tv1 = Fp.add(xn2, xd2); // 24. tv1 = xn2 + xd2 + tv1 = Fp.mul(tv1, xd2); // 25. tv1 = tv1 * xd2 + tv1 = Fp.mul(tv1, xd); // 26. tv1 = tv1 * xd + tv1 = Fp.mul(tv1, yn2); // 27. tv1 = tv1 * yn2 + tv1 = Fp.mul(tv1, BigInt(-2)); // 28. tv1 = -2 * tv1 + let yEd = Fp.add(tv2, tv1); // 29. yEd = tv2 + tv1 + tv4 = Fp.mul(tv4, yd2); // 30. tv4 = tv4 * yd2 + yEd = Fp.add(yEd, tv4); // 31. yEd = yEd + tv4 + tv1 = Fp.mul(xEd, yEd); // 32. tv1 = xEd * yEd + let e = Fp.eql(tv1, Fp.ZERO); // 33. e = tv1 == 0 + xEn = Fp.cmov(xEn, Fp.ZERO, e); // 34. xEn = CMOV(xEn, 0, e) + xEd = Fp.cmov(xEd, Fp.ONE, e); // 35. xEd = CMOV(xEd, 1, e) + yEn = Fp.cmov(yEn, Fp.ONE, e); // 36. yEn = CMOV(yEn, 1, e) + yEd = Fp.cmov(yEd, Fp.ONE, e); // 37. yEd = CMOV(yEd, 1, e) + const inv = Fp.invertBatch([xEd, yEd]); // batch division + return { x: Fp.mul(xEn, inv[0]), y: Fp.mul(yEn, inv[1]) }; // 38. return (xEn, xEd, yEn, yEd) +} +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.ed448.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards448(scalars[0]), { + DST: 'edwards448_XOF:SHAKE256_ELL2_RO_', + encodeDST: 'edwards448_XOF:SHAKE256_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 224, + expand: 'xof', + hash: sha3_1.shake256, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +//# sourceMappingURL=ed448.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/ed448.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/ed448.js.map new file mode 100644 index 0000000..b3956e2 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/ed448.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ed448.js","sourceRoot":"","sources":["src/ed448.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,6CAA8C;AAC9C,+CAA6F;AAC7F,sDAAuD;AACvD,sDAAyD;AACzD,4DAAsD;AACtD,kEAA2D;AAE3D;;;;GAIG;AAEH,MAAM,YAAY,GAAG,IAAA,uBAA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B;IACzD,OAAO,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,kCAAkC;AAC/F,CAAC;AAED,MAAM,GAAG,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAChC,IAAA,+BAAY,EACV,aAAK,CAAC,aAAa,EACnB,CAAC,OAAiB,EAAE,EAAE,CAAC,kCAAkC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EACrE;IACE,GAAG,EAAE,kCAAkC;IACvC,SAAS,EAAE,kCAAkC;IAC7C,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,eAAQ;CACf,CACF,CAAC,EAAE,CAAC;AACM,QAAA,WAAW,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACxD,QAAA,aAAa,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/_shortw_utils.js b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/_shortw_utils.js new file mode 100644 index 0000000..cc93e45 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/_shortw_utils.js @@ -0,0 +1,17 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { hmac } from '@noble/hashes/hmac'; +import { concatBytes, randomBytes } from '@noble/hashes/utils'; +import { weierstrass } from './abstract/weierstrass.js'; +// connects noble-curves to noble-hashes +export function getHash(hash) { + return { + hash, + hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)), + randomBytes, + }; +} +export function createCurve(curveDef, defHash) { + const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) }); + return Object.freeze({ ...create(defHash), create }); +} +//# sourceMappingURL=_shortw_utils.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/_shortw_utils.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/_shortw_utils.js.map new file mode 100644 index 0000000..656ee45 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/_shortw_utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_shortw_utils.js","sourceRoot":"","sources":["../src/_shortw_utils.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAa,MAAM,2BAA2B,CAAC;AAGnE,wCAAwC;AACxC,MAAM,UAAU,OAAO,CAAC,IAAW;IACjC,OAAO;QACL,IAAI;QACJ,IAAI,EAAE,CAAC,GAAe,EAAE,GAAG,IAAkB,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,EAAE,WAAW,CAAC,GAAG,IAAI,CAAC,CAAC;QACvF,WAAW;KACZ,CAAC;AACJ,CAAC;AAGD,MAAM,UAAU,WAAW,CAAC,QAAkB,EAAE,OAAc;IAC5D,MAAM,MAAM,GAAG,CAAC,IAAW,EAAE,EAAE,CAAC,WAAW,CAAC,EAAE,GAAG,QAAQ,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAC/E,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,MAAM,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;AACvD,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/bls.js b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/bls.js new file mode 100644 index 0000000..cbb3721 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/bls.js @@ -0,0 +1,235 @@ +import { hashToPrivateScalar } from './modular.js'; +import { bitLen, bitGet, ensureBytes } from './utils.js'; +import * as htf from './hash-to-curve.js'; +import { weierstrassPoints, } from './weierstrass.js'; +// prettier-ignore +const _2n = BigInt(2), _3n = BigInt(3); +export function bls(CURVE) { + // Fields are specific for curve, so for now we'll need to pass them with opts + const { Fp, Fr, Fp2, Fp6, Fp12 } = CURVE.fields; + const BLS_X_LEN = bitLen(CURVE.params.x); + const groupLen = 32; // TODO: calculate; hardcoded for now + // Pre-compute coefficients for sparse multiplication + // Point addition and point double calculations is reused for coefficients + function calcPairingPrecomputes(p) { + const { x, y } = p; + // prettier-ignore + const Qx = x, Qy = y, Qz = Fp2.ONE; + // prettier-ignore + let Rx = Qx, Ry = Qy, Rz = Qz; + let ell_coeff = []; + for (let i = BLS_X_LEN - 2; i >= 0; i--) { + // Double + let t0 = Fp2.sqr(Ry); // Ry² + let t1 = Fp2.sqr(Rz); // Rz² + let t2 = Fp2.multiplyByB(Fp2.mul(t1, _3n)); // 3 * T1 * B + let t3 = Fp2.mul(t2, _3n); // 3 * T2 + let t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0); // (Ry + Rz)² - T1 - T0 + ell_coeff.push([ + Fp2.sub(t2, t0), + Fp2.mul(Fp2.sqr(Rx), _3n), + Fp2.neg(t4), // -T4 + ]); + Rx = Fp2.div(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), _2n); // ((T0 - T3) * Rx * Ry) / 2 + Ry = Fp2.sub(Fp2.sqr(Fp2.div(Fp2.add(t0, t3), _2n)), Fp2.mul(Fp2.sqr(t2), _3n)); // ((T0 + T3) / 2)² - 3 * T2² + Rz = Fp2.mul(t0, t4); // T0 * T4 + if (bitGet(CURVE.params.x, i)) { + // Addition + let t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); // Ry - Qy * Rz + let t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz)); // Rx - Qx * Rz + ell_coeff.push([ + Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy)), + Fp2.neg(t0), + t1, // T1 + ]); + let t2 = Fp2.sqr(t1); // T1² + let t3 = Fp2.mul(t2, t1); // T2 * T1 + let t4 = Fp2.mul(t2, Rx); // T2 * Rx + let t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n)), Fp2.mul(Fp2.sqr(t0), Rz)); // T3 - 2 * T4 + T0² * Rz + Rx = Fp2.mul(t1, t5); // T1 * T5 + Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry)); // (T4 - T5) * T0 - T3 * Ry + Rz = Fp2.mul(Rz, t3); // Rz * T3 + } + } + return ell_coeff; + } + function millerLoop(ell, g1) { + const { x } = CURVE.params; + const Px = g1[0]; + const Py = g1[1]; + let f12 = Fp12.ONE; + for (let j = 0, i = BLS_X_LEN - 2; i >= 0; i--, j++) { + const E = ell[j]; + f12 = Fp12.multiplyBy014(f12, E[0], Fp2.mul(E[1], Px), Fp2.mul(E[2], Py)); + if (bitGet(x, i)) { + j += 1; + const F = ell[j]; + f12 = Fp12.multiplyBy014(f12, F[0], Fp2.mul(F[1], Px), Fp2.mul(F[2], Py)); + } + if (i !== 0) + f12 = Fp12.sqr(f12); + } + return Fp12.conjugate(f12); + } + const utils = { + randomPrivateKey: () => { + return Fr.toBytes(hashToPrivateScalar(CURVE.randomBytes(groupLen + 8), CURVE.params.r)); + }, + calcPairingPrecomputes, + }; + // Point on G1 curve: (x, y) + const G1_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G1 }); + const G1 = Object.assign(G1_, htf.createHasher(G1_.ProjectivePoint, CURVE.G1.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G1.htfDefaults, + })); + function pairingPrecomputes(point) { + const p = point; + if (p._PPRECOMPUTES) + return p._PPRECOMPUTES; + p._PPRECOMPUTES = calcPairingPrecomputes(point.toAffine()); + return p._PPRECOMPUTES; + } + // TODO: export + // function clearPairingPrecomputes(point: G2) { + // const p = point as G2 & withPairingPrecomputes; + // p._PPRECOMPUTES = undefined; + // } + // Point on G2 curve (complex numbers): (x₁, x₂+i), (y₁, y₂+i) + const G2_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G2 }); + const G2 = Object.assign(G2_, htf.createHasher(G2_.ProjectivePoint, CURVE.G2.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G2.htfDefaults, + })); + const { Signature } = CURVE.G2; + // Calculates bilinear pairing + function pairing(Q, P, withFinalExponent = true) { + if (Q.equals(G1.ProjectivePoint.ZERO) || P.equals(G2.ProjectivePoint.ZERO)) + throw new Error('pairing is not available for ZERO point'); + Q.assertValidity(); + P.assertValidity(); + // Performance: 9ms for millerLoop and ~14ms for exp. + const Qa = Q.toAffine(); + const looped = millerLoop(pairingPrecomputes(P), [Qa.x, Qa.y]); + return withFinalExponent ? Fp12.finalExponentiate(looped) : looped; + } + function normP1(point) { + return point instanceof G1.ProjectivePoint ? point : G1.ProjectivePoint.fromHex(point); + } + function normP2(point) { + return point instanceof G2.ProjectivePoint ? point : Signature.fromHex(point); + } + function normP2Hash(point, htfOpts) { + return point instanceof G2.ProjectivePoint + ? point + : G2.hashToCurve(ensureBytes('point', point), htfOpts); + } + // Multiplies generator by private key. + // P = pk x G + function getPublicKey(privateKey) { + return G1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true); + } + function sign(message, privateKey, htfOpts) { + const msgPoint = normP2Hash(message, htfOpts); + msgPoint.assertValidity(); + const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey)); + if (message instanceof G2.ProjectivePoint) + return sigPoint; + return Signature.toRawBytes(sigPoint); + } + // Checks if pairing of public key & hash is equal to pairing of generator & signature. + // e(P, H(m)) == e(G, S) + function verify(signature, message, publicKey, htfOpts) { + const P = normP1(publicKey); + const Hm = normP2Hash(message, htfOpts); + const G = G1.ProjectivePoint.BASE; + const S = normP2(signature); + // Instead of doing 2 exponentiations, we use property of billinear maps + // and do one exp after multiplying 2 points. + const ePHm = pairing(P.negate(), Hm, false); + const eGS = pairing(G, S, false); + const exp = Fp12.finalExponentiate(Fp12.mul(eGS, ePHm)); + return Fp12.eql(exp, Fp12.ONE); + } + function aggregatePublicKeys(publicKeys) { + if (!publicKeys.length) + throw new Error('Expected non-empty array'); + const agg = publicKeys.map(normP1).reduce((sum, p) => sum.add(p), G1.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (publicKeys[0] instanceof G1.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + // toRawBytes ensures point validity + return aggAffine.toRawBytes(true); + } + function aggregateSignatures(signatures) { + if (!signatures.length) + throw new Error('Expected non-empty array'); + const agg = signatures.map(normP2).reduce((sum, s) => sum.add(s), G2.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (signatures[0] instanceof G2.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + return Signature.toRawBytes(aggAffine); + } + // https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407 + // e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si)) + function verifyBatch(signature, messages, publicKeys, htfOpts) { + // @ts-ignore + // console.log('verifyBatch', bytesToHex(signature as any), messages, publicKeys.map(bytesToHex)); + if (!messages.length) + throw new Error('Expected non-empty messages array'); + if (publicKeys.length !== messages.length) + throw new Error('Pubkey count should equal msg count'); + const sig = normP2(signature); + const nMessages = messages.map((i) => normP2Hash(i, htfOpts)); + const nPublicKeys = publicKeys.map(normP1); + try { + const paired = []; + for (const message of new Set(nMessages)) { + const groupPublicKey = nMessages.reduce((groupPublicKey, subMessage, i) => subMessage === message ? groupPublicKey.add(nPublicKeys[i]) : groupPublicKey, G1.ProjectivePoint.ZERO); + // const msg = message instanceof PointG2 ? message : await PointG2.hashToCurve(message); + // Possible to batch pairing for same msg with different groupPublicKey here + paired.push(pairing(groupPublicKey, message, false)); + } + paired.push(pairing(G1.ProjectivePoint.BASE.negate(), sig, false)); + const product = paired.reduce((a, b) => Fp12.mul(a, b), Fp12.ONE); + const exp = Fp12.finalExponentiate(product); + return Fp12.eql(exp, Fp12.ONE); + } + catch { + return false; + } + } + G1.ProjectivePoint.BASE._setWindowSize(4); + return { + getPublicKey, + sign, + verify, + verifyBatch, + aggregatePublicKeys, + aggregateSignatures, + millerLoop, + pairing, + G1, + G2, + Signature, + fields: { + Fr, + Fp, + Fp2, + Fp6, + Fp12, + }, + params: { + x: CURVE.params.x, + r: CURVE.params.r, + G1b: CURVE.G1.b, + G2b: CURVE.G2.b, + }, + utils, + }; +} +//# sourceMappingURL=bls.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/bls.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/bls.js.map new file mode 100644 index 0000000..84a65d7 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/bls.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bls.js","sourceRoot":"","sources":["../../src/abstract/bls.ts"],"names":[],"mappings":"AAcA,OAAO,EAAU,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAuB,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC9E,OAAO,KAAK,GAAG,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAIL,iBAAiB,GAClB,MAAM,kBAAkB,CAAC;AAI1B,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AA2FvC,MAAM,UAAU,GAAG,CACjB,KAAoC;IAEpC,8EAA8E;IAC9E,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE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CAAC,EAAE,CAAC,eAAe,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC;YACnE,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC;YAClE,MAAM,GAAG,GAAG,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;YAC5C,OAAO,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC;SAChC;QAAC,MAAM;YACN,OAAO,KAAK,CAAC;SACd;IACH,CAAC;IAED,EAAE,CAAC,eAAe,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC;IAE1C,OAAO;QACL,YAAY;QACZ,IAAI;QACJ,MAAM;QACN,WAAW;QACX,mBAAmB;QACnB,mBAAmB;QACnB,UAAU;QACV,OAAO;QACP,EAAE;QACF,EAAE;QACF,SAAS;QACT,MAAM,EAAE;YACN,EAAE;YACF,EAAE;YACF,GAAG;YACH,GAAG;YACH,IAAI;SACL;QACD,MAAM,EAAE;YACN,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;YACjB,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;YACjB,GAAG,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;YACf,GAAG,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;SAChB;QACD,KAAK;KACN,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/curve.js b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/curve.js new file mode 100644 index 0000000..3454763 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/curve.js @@ -0,0 +1,156 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Abelian group utilities +import { validateField, nLength } from './modular.js'; +import { validateObject } from './utils.js'; +const _0n = BigInt(0); +const _1n = BigInt(1); +// Elliptic curve multiplication of Point by scalar. Fragile. +// Scalars should always be less than curve order: this should be checked inside of a curve itself. +// Creates precomputation tables for fast multiplication: +// - private scalar is split by fixed size windows of W bits +// - every window point is collected from window's table & added to accumulator +// - since windows are different, same point inside tables won't be accessed more than once per calc +// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar) +// - +1 window is neccessary for wNAF +// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication +// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow +// windows to be in different memory locations +export function wNAF(c, bits) { + const constTimeNegate = (condition, item) => { + const neg = item.negate(); + return condition ? neg : item; + }; + const opts = (W) => { + const windows = Math.ceil(bits / W) + 1; // +1, because + const windowSize = 2 ** (W - 1); // -1 because we skip zero + return { windows, windowSize }; + }; + return { + constTimeNegate, + // non-const time multiplication ladder + unsafeLadder(elm, n) { + let p = c.ZERO; + let d = elm; + while (n > _0n) { + if (n & _1n) + p = p.add(d); + d = d.double(); + n >>= _1n; + } + return p; + }, + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm, W) { + const { windows, windowSize } = opts(W); + const points = []; + let p = elm; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + // =1, because we skip zero + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + }, + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W, precomputes, n) { + // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise + // But need to carefully remove other checks before wNAF. ORDER == bits here + const { windows, windowSize } = opts(W); + let p = c.ZERO; + let f = c.BASE; + const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc. + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + // Extract W bits. + let wbits = Number(n & mask); + // Shift number by W bits. + n >>= shiftBy; + // If the bits are bigger than max size, we'll split those. + // +224 => 256 - 32 + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n; + } + // This code was first written with assumption that 'f' and 'p' will never be infinity point: + // since each addition is multiplied by 2 ** W, it cannot cancel each other. However, + // there is negate now: it is possible that negated element from low value + // would be the same as high element, which will create carry into next window. + // It's not obvious how this can fail, but still worth investigating later. + // Check if we're onto Zero point. + // Add random point inside current window to f. + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + // The most important part for const-time getPublicKey + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } + else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ() + // Even if the variable is still unused, there are some checks which will + // throw an exception, so compiler needs to prove they won't happen, which is hard. + // At this point there is a way to F be infinity-point even if p is not, + // which makes it less const-time: around 1 bigint multiply. + return { p, f }; + }, + wNAFCached(P, precomputesMap, n, transform) { + // @ts-ignore + const W = P._WINDOW_SIZE || 1; + // Calculate precomputes on a first run, reuse them after + let comp = precomputesMap.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W); + if (W !== 1) { + precomputesMap.set(P, transform(comp)); + } + } + return this.wNAF(W, comp, n); + }, + }; +} +export function validateBasic(curve) { + validateField(curve.Fp); + validateObject(curve, { + n: 'bigint', + h: 'bigint', + Gx: 'field', + Gy: 'field', + }, { + nBitLength: 'isSafeInteger', + nByteLength: 'isSafeInteger', + }); + // Set defaults + return Object.freeze({ + ...nLength(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER }, + }); +} +//# sourceMappingURL=curve.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/curve.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/curve.js.map new file mode 100644 index 0000000..f0fbc7d --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/curve.js.map @@ -0,0 +1 @@ +{"version":3,"file":"curve.js","sourceRoot":"","sources":["../../src/abstract/curve.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,0BAA0B;AAC1B,OAAO,EAAU,aAAa,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAsBtB,6DAA6D;AAC7D,mGAAmG;AACnG,yDAAyD;AACzD,4DAA4D;AAC5D,+EAA+E;AAC/E,oGAAoG;AACpG,oGAAoG;AACpG,qCAAqC;AACrC,kGAAkG;AAClG,gGAAgG;AAChG,8CAA8C;AAC9C,MAAM,UAAU,IAAI,CAAqB,CAAsB,EAAE,IAAY;IAC3E,MAAM,eAAe,GAAG,CAAC,SAAkB,EAAE,IAAO,EAAK,EAAE;QACzD,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;QAC1B,OAAO,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;IAChC,CAAC,CAAC;IACF,MAAM,IAAI,GAAG,CAAC,CAAS,EAAE,EAAE;QACz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Ac,CACZ,KAAK,EACL;QACE,CAAC,EAAE,QAAQ;QACX,CAAC,EAAE,QAAQ;QACX,EAAE,EAAE,OAAO;QACX,EAAE,EAAE,OAAO;KACZ,EACD;QACE,UAAU,EAAE,eAAe;QAC3B,WAAW,EAAE,eAAe;KAC7B,CACF,CAAC;IACF,eAAe;IACf,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,UAAU,CAAC;QACrC,GAAG,KAAK;QACR,GAAG,EAAE,CAAC,EAAE,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE;KAChB,CAAC,CAAC;AACd,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/edwards.js b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/edwards.js new file mode 100644 index 0000000..de5123a --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/edwards.js @@ -0,0 +1,425 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y² +import { mod } from './modular.js'; +import * as ut from './utils.js'; +import { ensureBytes } from './utils.js'; +import { wNAF, validateBasic } from './curve.js'; +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8); +// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex: +const VERIFY_DEFAULT = { zip215: true }; +function validateOpts(curve) { + const opts = validateBasic(curve); + ut.validateObject(curve, { + hash: 'function', + a: 'bigint', + d: 'bigint', + randomBytes: 'function', + }, { + adjustScalarBytes: 'function', + domain: 'function', + uvRatio: 'function', + mapToCurve: 'function', + }); + // Set defaults + return Object.freeze({ ...opts }); +} +// It is not generic twisted curve for now, but ed25519/ed448 generic implementation +export function twistedEdwards(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE; + const MASK = _2n << (BigInt(nByteLength * 8) - _1n); + const modP = Fp.create; // Function overrides + // sqrt(u/v) + const uvRatio = CURVE.uvRatio || + ((u, v) => { + try { + return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) }; + } + catch (e) { + return { isValid: false, value: _0n }; + } + }); + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP + const domain = CURVE.domain || + ((data, ctx, phflag) => { + if (ctx.length || phflag) + throw new Error('Contexts/pre-hash are not supported'); + return data; + }); // NOOP + const inBig = (n) => typeof n === 'bigint' && _0n < n; // n in [1..] + const inRange = (n, max) => inBig(n) && inBig(max) && n < max; // n in [1..max-1] + const in0MaskRange = (n) => n === _0n || inRange(n, MASK); // n in [0..MASK-1] + function assertInRange(n, max) { + // n in [1..max-1] + if (inRange(n, max)) + return n; + throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`); + } + function assertGE0(n) { + // n in [0..CURVE_ORDER-1] + return n === _0n ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group + } + const pointPrecomputes = new Map(); + function isPoint(other) { + if (!(other instanceof Point)) + throw new Error('ExtendedPoint expected'); + } + // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy). + // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates + class Point { + constructor(ex, ey, ez, et) { + this.ex = ex; + this.ey = ey; + this.ez = ez; + this.et = et; + if (!in0MaskRange(ex)) + throw new Error('x required'); + if (!in0MaskRange(ey)) + throw new Error('y required'); + if (!in0MaskRange(ez)) + throw new Error('z required'); + if (!in0MaskRange(et)) + throw new Error('t required'); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + static fromAffine(p) { + if (p instanceof Point) + throw new Error('extended point not allowed'); + const { x, y } = p || {}; + if (!in0MaskRange(x) || !in0MaskRange(y)) + throw new Error('invalid affine point'); + return new Point(x, y, _1n, modP(x * y)); + } + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.ez)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + // Not required for fromHex(), which always creates valid points. + // Could be useful for fromAffine(). + assertValidity() { + const { a, d } = CURVE; + if (this.is0()) + throw new Error('bad point: ZERO'); // TODO: optimize, with vars below? + // Equation in affine coordinates: ax² + y² = 1 + dx²y² + // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y² + const { ex: X, ey: Y, ez: Z, et: T } = this; + const X2 = modP(X * X); // X² + const Y2 = modP(Y * Y); // Y² + const Z2 = modP(Z * Z); // Z² + const Z4 = modP(Z2 * Z2); // Z⁴ + const aX2 = modP(X2 * a); // aX² + const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z² + const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y² + if (left !== right) + throw new Error('bad point: equation left != right (1)'); + // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T + const XY = modP(X * Y); + const ZT = modP(Z * T); + if (XY !== ZT) + throw new Error('bad point: equation left != right (2)'); + } + // Compare one point to another. + equals(other) { + isPoint(other); + const { ex: X1, ey: Y1, ez: Z1 } = this; + const { ex: X2, ey: Y2, ez: Z2 } = other; + const X1Z2 = modP(X1 * Z2); + const X2Z1 = modP(X2 * Z1); + const Y1Z2 = modP(Y1 * Z2); + const Y2Z1 = modP(Y2 * Z1); + return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; + } + is0() { + return this.equals(Point.ZERO); + } + negate() { + // Flips point sign to a negative one (-x, y in affine coords) + return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et)); + } + // Fast algo for doubling Extended Point. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd + // Cost: 4M + 4S + 1*a + 6add + 1*2. + double() { + const { a } = CURVE; + const { ex: X1, ey: Y1, ez: Z1 } = this; + const A = modP(X1 * X1); // A = X12 + const B = modP(Y1 * Y1); // B = Y12 + const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12 + const D = modP(a * A); // D = a*A + const x1y1 = X1 + Y1; + const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B + const G = D + B; // G = D+B + const F = G - C; // F = G-C + const H = D - B; // H = D-B + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + // Fast algo for adding 2 Extended Points. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd + // Cost: 9M + 1*a + 1*d + 7add. + add(other) { + isPoint(other); + const { a, d } = CURVE; + const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this; + const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other; + // Faster algo for adding 2 Extended Points when curve's a=-1. + // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4 + // Cost: 8M + 8add + 2*2. + // Note: It does not check whether the `other` point is valid. + if (a === BigInt(-1)) { + const A = modP((Y1 - X1) * (Y2 + X2)); + const B = modP((Y1 + X1) * (Y2 - X2)); + const F = modP(B - A); + if (F === _0n) + return this.double(); // Same point. Tests say it doesn't affect timing + const C = modP(Z1 * _2n * T2); + const D = modP(T1 * _2n * Z2); + const E = D + C; + const G = B + A; + const H = D - C; + const X3 = modP(E * F); + const Y3 = modP(G * H); + const T3 = modP(E * H); + const Z3 = modP(F * G); + return new Point(X3, Y3, Z3, T3); + } + const A = modP(X1 * X2); // A = X1*X2 + const B = modP(Y1 * Y2); // B = Y1*Y2 + const C = modP(T1 * d * T2); // C = T1*d*T2 + const D = modP(Z1 * Z2); // D = Z1*Z2 + const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B + const F = D - C; // F = D-C + const G = D + C; // G = D+C + const H = modP(B - a * A); // H = B-a*A + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + subtract(other) { + return this.add(other.negate()); + } + wNAF(n) { + return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ); + } + // Constant-time multiplication. + multiply(scalar) { + const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER)); + return Point.normalizeZ([p, f])[0]; + } + // Non-constant-time multiplication. Uses double-and-add algorithm. + // It's faster, but should only be used when you don't care about + // an exposed private key e.g. sig verification. + // Does NOT allow scalars higher than CURVE.n. + multiplyUnsafe(scalar) { + let n = assertGE0(scalar); // 0 <= scalar < CURVE.n + if (n === _0n) + return I; + if (this.equals(I) || n === _1n) + return this; + if (this.equals(G)) + return this.wNAF(n).p; + return wnaf.unsafeLadder(this, n); + } + // Checks if point is of small order. + // If you add something to small order point, you will have "dirty" + // point with torsion component. + // Multiplies point by cofactor and checks if the result is 0. + isSmallOrder() { + return this.multiplyUnsafe(cofactor).is0(); + } + // Multiplies point by curve order and checks if the result is 0. + // Returns `false` is the point is dirty. + isTorsionFree() { + return wnaf.unsafeLadder(this, CURVE_ORDER).is0(); + } + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + toAffine(iz) { + const { ex: x, ey: y, ez: z } = this; + const is0 = this.is0(); + if (iz == null) + iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily + const ax = modP(x * iz); + const ay = modP(y * iz); + const zz = modP(z * iz); + if (is0) + return { x: _0n, y: _1n }; + if (zz !== _1n) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + } + clearCofactor() { + const { h: cofactor } = CURVE; + if (cofactor === _1n) + return this; + return this.multiplyUnsafe(cofactor); + } + // Converts hash string or Uint8Array to Point. + // Uses algo from RFC8032 5.1.3. + static fromHex(hex, zip215 = false) { + const { d, a } = CURVE; + const len = Fp.BYTES; + hex = ensureBytes('pointHex', hex, len); // copy hex to a new array + const normed = hex.slice(); // copy again, we'll manipulate it + const lastByte = hex[len - 1]; // select last byte + normed[len - 1] = lastByte & ~0x80; // clear last bit + const y = ut.bytesToNumberLE(normed); + if (y === _0n) { + // y=0 is allowed + } + else { + // RFC8032 prohibits >= p, but ZIP215 doesn't + if (zip215) + assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519) + else + assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519) + } + // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case: + // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a) + const y2 = modP(y * y); // denominator is always non-0 mod p. + const u = modP(y2 - _1n); // u = y² - 1 + const v = modP(d * y2 - a); // v = d y² + 1. + let { isValid, value: x } = uvRatio(u, v); // √(u/v) + if (!isValid) + throw new Error('Point.fromHex: invalid y coordinate'); + const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper + const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit + if (!zip215 && x === _0n && isLastByteOdd) + // if x=0 and x_0 = 1, fail + throw new Error('Point.fromHex: x=0 and x_0=1'); + if (isLastByteOdd !== isXOdd) + x = modP(-x); // if x_0 != x mod 2, set x = p-x + return Point.fromAffine({ x, y }); + } + static fromPrivateKey(privKey) { + return getExtendedPublicKey(privKey).point; + } + toRawBytes() { + const { x, y } = this.toAffine(); + const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y) + bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y + return bytes; // and use the last byte to encode sign of x + } + toHex() { + return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string. + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy)); + Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0 + const { BASE: G, ZERO: I } = Point; + const wnaf = wNAF(Point, nByteLength * 8); + function modN(a) { + return mod(a, CURVE_ORDER); + } + // Little-endian SHA512 with modulo n + function modN_LE(hash) { + return modN(ut.bytesToNumberLE(hash)); + } + /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */ + function getExtendedPublicKey(key) { + const len = nByteLength; + key = ensureBytes('private key', key, len); + // Hash private key with curve's hash function to produce uniformingly random input + // Check byte lengths: ensure(64, h(ensure(32, key))) + const hashed = ensureBytes('hashed private key', cHash(key), 2 * len); + const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE + const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6) + const scalar = modN_LE(head); // The actual private scalar + const point = G.multiply(scalar); // Point on Edwards curve aka public key + const pointBytes = point.toRawBytes(); // Uint8Array representation + return { head, prefix, scalar, point, pointBytes }; + } + // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared + function getPublicKey(privKey) { + return getExtendedPublicKey(privKey).pointBytes; + } + // int('LE', SHA512(dom2(F, C) || msgs)) mod N + function hashDomainToScalar(context = new Uint8Array(), ...msgs) { + const msg = ut.concatBytes(...msgs); + return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash))); + } + /** Signs message with privateKey. RFC8032 5.1.6 */ + function sign(msg, privKey, options = {}) { + msg = ensureBytes('message', msg); + if (prehash) + msg = prehash(msg); // for ed25519ph etc. + const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey); + const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M) + const R = G.multiply(r).toRawBytes(); // R = rG + const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M) + const s = modN(r + k * scalar); // S = (r + k * s) mod L + assertGE0(s); // 0 <= s < l + const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES)); + return ensureBytes('result', res, nByteLength * 2); // 64-byte signature + } + const verifyOpts = VERIFY_DEFAULT; + function verify(sig, msg, publicKey, options = verifyOpts) { + const { context, zip215 } = options; + const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7. + sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked. + msg = ensureBytes('message', msg); + if (prehash) + msg = prehash(msg); // for ed25519ph, etc + const s = ut.bytesToNumberLE(sig.slice(len, 2 * len)); + // zip215: true is good for consensus-critical apps and allows points < 2^256 + // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p + let A, R, SB; + try { + A = Point.fromHex(publicKey, zip215); + R = Point.fromHex(sig.slice(0, len), zip215); + SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside + } + catch (error) { + return false; + } + if (!zip215 && A.isSmallOrder()) + return false; + const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg); + const RkA = R.add(A.multiplyUnsafe(k)); + // [8][S]B = [8]R + [8][k]A' + return RkA.subtract(SB).clearCofactor().equals(Point.ZERO); + } + G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms. + const utils = { + getExtendedPublicKey, + // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1. + randomPrivateKey: () => randomBytes(Fp.BYTES), + /** + * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT + * values. This slows down first getPublicKey() by milliseconds (see Speed section), + * but allows to speed-up subsequent getPublicKey() calls up to 20x. + * @param windowSize 2, 4, 8, 16 + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; + }, + }; + return { + CURVE, + getPublicKey, + sign, + verify, + ExtendedPoint: Point, + utils, + }; +} +//# sourceMappingURL=edwards.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/edwards.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/edwards.js.map new file mode 100644 index 0000000..dda68a8 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/edwards.js.map @@ -0,0 +1 @@ +{"version":3,"file":"edwards.js","sourceRoot":"","sources":["../../src/abstract/edwards.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,8DAA8D;AAC9D,OAAO,EAAE,GAAG,EAAE,MAAM,cAAc,CAAC;AACnC,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AACjC,OAAO,EAAE,WAAW,EAAc,MAAM,YAAY,CAAC;AACrD,OAAO,EAA2B,IAAI,EAAc,aAAa,EAAe,MAAM,YAAY,CAAC;AAEnG,qEAAqE;AACrE,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAezE,8EAA8E;AAC9E,MAAM,cAAc,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;AAExC,SAAS,YAAY,CAAC,KAAgB;IACpC,MAAM,IAAI,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC;IAClC,EAAE,CAAC,cAAc,CACf,KAAK,EACL;QACE,IAAI,EAAE,UAAU;QAChB,CAAC,EAAE,QAAQ;QACX,CAAC,EAAE,QAAQ;QACX,WAAW,EAAE,UAAU;KACxB,EACD;QACE,iBAAiB,EAAE,UAAU;QAC7B,MAAM,EAAE,UAAU;QAClB,OAAO,EAAE,UAAU;QACnB,UAAU,EAAE,UAAU;KACvB,CACF,CAAC;IACF,eAAe;IACf,OAAO,MAAM,CAAC,MAAM,CA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AG,CAAC,EAAE,KAAK,GAAG,KAAK,CAAC,IAAI;YAC3C,KAAK,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC;YACjC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;YAC1B,OAAO,KAAK,CAAC;QACf,CAAC;KACF,CAAC;IAEF,OAAO;QACL,KAAK;QACL,YAAY;QACZ,IAAI;QACJ,MAAM;QACN,aAAa,EAAE,KAAK;QACpB,KAAK;KACN,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/hash-to-curve.js b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/hash-to-curve.js new file mode 100644 index 0000000..a6419f9 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/hash-to-curve.js @@ -0,0 +1,167 @@ +import { mod } from './modular.js'; +import { bytesToNumberBE, concatBytes, utf8ToBytes, validateObject } from './utils.js'; +function validateDST(dst) { + if (dst instanceof Uint8Array) + return dst; + if (typeof dst === 'string') + return utf8ToBytes(dst); + throw new Error('DST must be Uint8Array or string'); +} +// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE. +const os2ip = bytesToNumberBE; +// Integer to Octet Stream (numberToBytesBE) +function i2osp(value, length) { + if (value < 0 || value >= 1 << (8 * length)) { + throw new Error(`bad I2OSP call: value=${value} length=${length}`); + } + const res = Array.from({ length }).fill(0); + for (let i = length - 1; i >= 0; i--) { + res[i] = value & 0xff; + value >>>= 8; + } + return new Uint8Array(res); +} +function strxor(a, b) { + const arr = new Uint8Array(a.length); + for (let i = 0; i < a.length; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} +function isBytes(item) { + if (!(item instanceof Uint8Array)) + throw new Error('Uint8Array expected'); +} +function isNum(item) { + if (!Number.isSafeInteger(item)) + throw new Error('number expected'); +} +// Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.4.1 +export function expand_message_xmd(msg, DST, lenInBytes, H) { + isBytes(msg); + isBytes(DST); + isNum(lenInBytes); + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-5.3.3 + if (DST.length > 255) + DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST)); + const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H; + const ell = Math.ceil(lenInBytes / b_in_bytes); + if (ell > 255) + throw new Error('Invalid xmd length'); + const DST_prime = concatBytes(DST, i2osp(DST.length, 1)); + const Z_pad = i2osp(0, r_in_bytes); + const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str + const b = new Array(ell); + const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); + b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime)); + for (let i = 1; i <= ell; i++) { + const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime]; + b[i] = H(concatBytes(...args)); + } + const pseudo_random_bytes = concatBytes(...b); + return pseudo_random_bytes.slice(0, lenInBytes); +} +export function expand_message_xof(msg, DST, lenInBytes, k, H) { + isBytes(msg); + isBytes(DST); + isNum(lenInBytes); + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-5.3.3 + // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8)); + if (DST.length > 255) { + const dkLen = Math.ceil((2 * k) / 8); + DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest(); + } + if (lenInBytes > 65535 || DST.length > 255) + throw new Error('expand_message_xof: invalid lenInBytes'); + return (H.create({ dkLen: lenInBytes }) + .update(msg) + .update(i2osp(lenInBytes, 2)) + // 2. DST_prime = DST || I2OSP(len(DST), 1) + .update(DST) + .update(i2osp(DST.length, 1)) + .digest()); +} +/** + * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.3 + * @param msg a byte string containing the message to hash + * @param count the number of elements of F to output + * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above + * @returns [u_0, ..., u_(count - 1)], a list of field elements. + */ +export function hash_to_field(msg, count, options) { + validateObject(options, { + DST: 'string', + p: 'bigint', + m: 'isSafeInteger', + k: 'isSafeInteger', + hash: 'hash', + }); + const { p, k, m, hash, expand, DST: _DST } = options; + isBytes(msg); + isNum(count); + const DST = validateDST(_DST); + const log2p = p.toString(2).length; + const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above + const len_in_bytes = count * m * L; + let prb; // pseudo_random_bytes + if (expand === 'xmd') { + prb = expand_message_xmd(msg, DST, len_in_bytes, hash); + } + else if (expand === 'xof') { + prb = expand_message_xof(msg, DST, len_in_bytes, k, hash); + } + else if (expand === '_internal_pass') { + // for internal tests only + prb = msg; + } + else { + throw new Error('expand must be "xmd" or "xof"'); + } + const u = new Array(count); + for (let i = 0; i < count; i++) { + const e = new Array(m); + for (let j = 0; j < m; j++) { + const elm_offset = L * (j + i * m); + const tv = prb.subarray(elm_offset, elm_offset + L); + e[j] = mod(os2ip(tv), p); + } + u[i] = e; + } + return u; +} +export function isogenyMap(field, map) { + // Make same order as in spec + const COEFF = map.map((i) => Array.from(i).reverse()); + return (x, y) => { + const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i))); + x = field.div(xNum, xDen); // xNum / xDen + y = field.mul(y, field.div(yNum, yDen)); // y * (yNum / yDev) + return { x, y }; + }; +} +export function createHasher(Point, mapToCurve, def) { + if (typeof mapToCurve !== 'function') + throw new Error('mapToCurve() must be defined'); + return { + // Encodes byte string to elliptic curve + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-3 + hashToCurve(msg, options) { + const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options }); + const u0 = Point.fromAffine(mapToCurve(u[0])); + const u1 = Point.fromAffine(mapToCurve(u[1])); + const P = u0.add(u1).clearCofactor(); + P.assertValidity(); + return P; + }, + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-3 + encodeToCurve(msg, options) { + const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options }); + const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor(); + P.assertValidity(); + return P; + }, + }; +} +//# sourceMappingURL=hash-to-curve.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/hash-to-curve.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/hash-to-curve.js.map new file mode 100644 index 0000000..02c9e79 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/hash-to-curve.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hash-to-curve.js","sourceRoot":"","sources":["../../src/abstract/hash-to-curve.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,GAAG,EAAU,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAS,WAAW,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAoB9F,SAAS,WAAW,CAAC,GAAmB;IACtC,IAAI,GAAG,YAAY,UAAU;QAAE,OAAO,GAAG,CAAC;IAC1C,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,OAAO,WAAW,CAAC,GAAG,CAAC,CAAC;IACrD,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;AACtD,CAAC;AAED,6FAA6F;AAC7F,MAAM,KAAK,GAAG,eAAe,CAAC;AAE9B,4CAA4C;AAC5C,SAAS,KAAK,CAAC,KAAa,EAAE,MAAc;IAC1C,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,MAAM,CAA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AE,GAAG,CAAC,SAAS,EAAE,GAAG,OAAO,EAAU,CAAC,CAAC;YACpF,MAAM,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,aAAa,EAAE,CAAC;YAC7D,CAAC,CAAC,cAAc,EAAE,CAAC;YACnB,OAAO,CAAC,CAAC;QACX,CAAC;KACF,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/modular.js b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/modular.js new file mode 100644 index 0000000..e26772a --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/modular.js @@ -0,0 +1,361 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Utilities for modular arithmetics and finite fields +import { bitMask, numberToBytesBE, numberToBytesLE, bytesToNumberBE, bytesToNumberLE, ensureBytes, validateObject, } from './utils.js'; +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); +// prettier-ignore +const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8); +// prettier-ignore +const _9n = BigInt(9), _16n = BigInt(16); +// Calculates a modulo b +export function mod(a, b) { + const result = a % b; + return result >= _0n ? result : b + result; +} +/** + * Efficiently raise num to power and do modular division. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + * @example + * pow(2n, 6n, 11n) // 64n % 11n == 9n + */ +// TODO: use field version && remove +export function pow(num, power, modulo) { + if (modulo <= _0n || power < _0n) + throw new Error('Expected power/modulo > 0'); + if (modulo === _1n) + return _0n; + let res = _1n; + while (power > _0n) { + if (power & _1n) + res = (res * num) % modulo; + num = (num * num) % modulo; + power >>= _1n; + } + return res; +} +// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4) +export function pow2(x, power, modulo) { + let res = x; + while (power-- > _0n) { + res *= res; + res %= modulo; + } + return res; +} +// Inverses number over modulo +export function invert(number, modulo) { + if (number === _0n || modulo <= _0n) { + throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); + } + // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/ + // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower. + let a = mod(number, modulo); + let b = modulo; + // prettier-ignore + let x = _0n, y = _1n, u = _1n, v = _0n; + while (a !== _0n) { + // JIT applies optimization if those two lines follow each other + const q = b / a; + const r = b % a; + const m = x - u * q; + const n = y - v * q; + // prettier-ignore + b = a, a = r, x = u, y = v, u = m, v = n; + } + const gcd = b; + if (gcd !== _1n) + throw new Error('invert: does not exist'); + return mod(x, modulo); +} +// Tonelli-Shanks algorithm +// Paper 1: https://eprint.iacr.org/2012/685.pdf (page 12) +// Paper 2: Square Roots from 1; 24, 51, 10 to Dan Shanks +export function tonelliShanks(P) { + // Legendre constant: used to calculate Legendre symbol (a | p), + // which denotes the value of a^((p-1)/2) (mod p). + // (a | p) ≡ 1 if a is a square (mod p) + // (a | p) ≡ -1 if a is not a square (mod p) + // (a | p) ≡ 0 if a ≡ 0 (mod p) + const legendreC = (P - _1n) / _2n; + let Q, S, Z; + // Step 1: By factoring out powers of 2 from p - 1, + // find q and s such that p - 1 = q*(2^s) with q odd + for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++) + ; + // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq + for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++) + ; + // Fast-path + if (S === 1) { + const p1div4 = (P + _1n) / _4n; + return function tonelliFast(Fp, n) { + const root = Fp.pow(n, p1div4); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Slow-path + const Q1div2 = (Q + _1n) / _2n; + return function tonelliSlow(Fp, n) { + // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1 + if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) + throw new Error('Cannot find square root'); + let r = S; + // TODO: will fail at Fp2/etc + let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b + let x = Fp.pow(n, Q1div2); // first guess at the square root + let b = Fp.pow(n, Q); // first guess at the fudge factor + while (!Fp.eql(b, Fp.ONE)) { + if (Fp.eql(b, Fp.ZERO)) + return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0) + // Find m such b^(2^m)==1 + let m = 1; + for (let t2 = Fp.sqr(b); m < r; m++) { + if (Fp.eql(t2, Fp.ONE)) + break; + t2 = Fp.sqr(t2); // t2 *= t2 + } + // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow + const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1) + g = Fp.sqr(ge); // g = ge * ge + x = Fp.mul(x, ge); // x *= ge + b = Fp.mul(b, g); // b *= g + r = m; + } + return x; + }; +} +export function FpSqrt(P) { + // NOTE: different algorithms can give different roots, it is up to user to decide which one they want. + // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve). + // P ≡ 3 (mod 4) + // √n = n^((P+1)/4) + if (P % _4n === _3n) { + // Not all roots possible! + // const ORDER = + // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn; + // const NUM = 72057594037927816n; + const p1div4 = (P + _1n) / _4n; + return function sqrt3mod4(Fp, n) { + const root = Fp.pow(n, p1div4); + // Throw if root**2 != n + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10) + if (P % _8n === _5n) { + const c1 = (P - _5n) / _8n; + return function sqrt5mod8(Fp, n) { + const n2 = Fp.mul(n, _2n); + const v = Fp.pow(n2, c1); + const nv = Fp.mul(n, v); + const i = Fp.mul(Fp.mul(nv, _2n), v); + const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // P ≡ 9 (mod 16) + if (P % _16n === _9n) { + // NOTE: tonelli is too slow for bls-Fp2 calculations even on start + // Means we cannot use sqrt for constants at all! + // + // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F + // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F + // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F + // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic + // sqrt = (x) => { + // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4 + // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1 + // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1 + // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1 + // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x + // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x + // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x + // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x + // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x + // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2 + // } + } + // Other cases: Tonelli-Shanks algorithm + return tonelliShanks(P); +} +// Little-endian check for first LE bit (last BE bit); +export const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n; +// prettier-ignore +const FIELD_FIELDS = [ + 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr', + 'eql', 'add', 'sub', 'mul', 'pow', 'div', + 'addN', 'subN', 'mulN', 'sqrN' +]; +export function validateField(field) { + const initial = { + ORDER: 'bigint', + MASK: 'bigint', + BYTES: 'isSafeInteger', + BITS: 'isSafeInteger', + }; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = 'function'; + return map; + }, initial); + return validateObject(field, opts); +} +// Generic field functions +export function FpPow(f, num, power) { + // Should have same speed as pow for bigints + // TODO: benchmark! + if (power < _0n) + throw new Error('Expected power > 0'); + if (power === _0n) + return f.ONE; + if (power === _1n) + return num; + let p = f.ONE; + let d = num; + while (power > _0n) { + if (power & _1n) + p = f.mul(p, d); + d = f.sqr(d); + power >>= _1n; + } + return p; +} +// 0 is non-invertible: non-batched version will throw on 0 +export function FpInvertBatch(f, nums) { + const tmp = new Array(nums.length); + // Walk from first to last, multiply them by each other MOD p + const lastMultiplied = nums.reduce((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = acc; + return f.mul(acc, num); + }, f.ONE); + // Invert last element + const inverted = f.inv(lastMultiplied); + // Walk from last to first, multiply them by inverted each other MOD p + nums.reduceRight((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = f.mul(acc, tmp[i]); + return f.mul(acc, num); + }, inverted); + return tmp; +} +export function FpDiv(f, lhs, rhs) { + return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs)); +} +// This function returns True whenever the value x is a square in the field F. +export function FpIsSquare(f) { + const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic + return (x) => { + const p = f.pow(x, legendreConst); + return f.eql(p, f.ZERO) || f.eql(p, f.ONE); + }; +} +// CURVE.n lengths +export function nLength(n, nBitLength) { + // Bit size, byte size of CURVE.n + const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} +/** + * Initializes a galois field over prime. Non-primes are not supported for now. + * Do not init in loop: slow. Very fragile: always run a benchmark on change. + * Major performance gains: + * a) non-normalized operations like mulN instead of mul + * b) `Object.freeze` + * c) Same object shape: never add or remove keys + * @param ORDER prime positive bigint + * @param bitLen how many bits the field consumes + * @param isLE (def: false) if encoding / decoding should be in little-endian + * @param redef optional faster redefinitions of sqrt and other methods + */ +export function Field(ORDER, bitLen, isLE = false, redef = {}) { + if (ORDER <= _0n) + throw new Error(`Expected Fp ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen); + if (BYTES > 2048) + throw new Error('Field lengths over 2048 bytes are not supported'); + const sqrtP = FpSqrt(ORDER); + const f = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: bitMask(BITS), + ZERO: _0n, + ONE: _1n, + create: (num) => mod(num, ORDER), + isValid: (num) => { + if (typeof num !== 'bigint') + throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); + return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible + }, + is0: (num) => num === _0n, + isOdd: (num) => (num & _1n) === _1n, + neg: (num) => mod(-num, ORDER), + eql: (lhs, rhs) => lhs === rhs, + sqr: (num) => mod(num * num, ORDER), + add: (lhs, rhs) => mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod(lhs * rhs, ORDER), + pow: (num, power) => FpPow(f, num, power), + div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), + // Same as above, but doesn't normalize + sqrN: (num) => num * num, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + inv: (num) => invert(num, ORDER), + sqrt: redef.sqrt || ((n) => sqrtP(f, n)), + invertBatch: (lst) => FpInvertBatch(f, lst), + // TODO: do we really need constant cmov? + // We don't have const-time bigints anyway, so probably will be not very useful + cmov: (a, b, c) => (c ? b : a), + toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)), + fromBytes: (bytes) => { + if (bytes.length !== BYTES) + throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); + return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); + }, + }); + return Object.freeze(f); +} +export function FpSqrtOdd(Fp, elm) { + if (!Fp.isOdd) + throw new Error(`Field doesn't have isOdd`); + const root = Fp.sqrt(elm); + return Fp.isOdd(root) ? root : Fp.neg(root); +} +export function FpSqrtEven(Fp, elm) { + if (!Fp.isOdd) + throw new Error(`Field doesn't have isOdd`); + const root = Fp.sqrt(elm); + return Fp.isOdd(root) ? Fp.neg(root) : root; +} +/** + * FIPS 186 B.4.1-compliant "constant-time" private key generation utility. + * Can take (n+8) or more bytes of uniform input e.g. from CSPRNG or KDF + * and convert them into private scalar, with the modulo bias being negligible. + * Needs at least 40 bytes of input for 32-byte private key. + * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ + * @param hash hash output from SHA3 or a similar function + * @param groupOrder size of subgroup - (e.g. curveFn.CURVE.n) + * @param isLE interpret hash bytes as LE num + * @returns valid private scalar + */ +export function hashToPrivateScalar(hash, groupOrder, isLE = false) { + hash = ensureBytes('privateHash', hash); + const hashLen = hash.length; + const minLen = nLength(groupOrder).nByteLength + 8; + if (minLen < 24 || hashLen < minLen || hashLen > 1024) + throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`); + const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash); + return mod(num, groupOrder - _1n) + _1n; +} +//# sourceMappingURL=modular.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/modular.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/modular.js.map new file mode 100644 index 0000000..607c1f2 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/modular.js.map @@ -0,0 +1 @@ +{"version":3,"file":"modular.js","sourceRoot":"","sources":["../../src/abstract/modular.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,sDAAsD;AACtD,OAAO,EACL,OAAO,EACP,eAAe,EACf,eAAe,EACf,eAAe,EACf,eAAe,EACf,WAAW,EACX,cAAc,GACf,MAAM,YAAY,CAAC;AACpB,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACzE,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACxD,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;AAEzC,wBAAwB;AACxB,MAAM,UAAU,GAAG,CAAC,CAAS,EAAE,CAAS;IACtC,MAAM,MAAM,GAAG,CAAC,GAAG,CAAC,CAAC;IACrB,OAAO,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC;AAC7C,CAAC;AACD;;;;;GAKG;AACH,oCAAoC;AACpC,MAAM,UAAU,GAAG,CAAC,GAAW,EAAE,KAAa,EAAE,MAAc;IAC5D,IAAI,MAAM,IAAI,GAAG,IAAI,KAAK,GAAG,GAAG;QAAE,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;IAC/E,IAAI,MAAM,KAAK,GAAG;QAAE,OAAO,GAAG,CAAC;IAC/B,IAAI,GAAG,GAAG,GAAG,CAAC;IACd,OAAO,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,CAAC,KAAK;QAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;IAC3D,MAAM,IAAI,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC1B,OAAO,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AAC9C,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,mBAAmB,CACjC,IAAyB,EACzB,UAAkB,EAClB,IAAI,GAAG,KAAK;IAEZ,IAAI,GAAG,WAAW,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC;IACxC,MAAM,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC;IAC5B,MAAM,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC,WAAW,GAAG,CAAC,CAAC;IACnD,IAAI,MAAM,GAAG,EAAE,IAAI,OAAO,GAAG,MAAM,IAAI,OAAO,GAAG,IAAI;QACnD,MAAM,IAAI,KAAK,CAAC,iCAAiC,MAAM,6BAA6B,OAAO,EAAE,CAAC,CAAC;IACjG,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC;IACjE,OAAO,GAAG,CAAC,GAAG,EAAE,UAAU,GAAG,GAAG,CAAC,GAAG,GAAG,CAAC;AAC1C,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/montgomery.js b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/montgomery.js new file mode 100644 index 0000000..19a8b6e --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/montgomery.js @@ -0,0 +1,157 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { mod, pow } from './modular.js'; +import { bytesToNumberLE, ensureBytes, numberToBytesLE, validateObject } from './utils.js'; +const _0n = BigInt(0); +const _1n = BigInt(1); +function validateOpts(curve) { + validateObject(curve, { + a: 'bigint', + }, { + montgomeryBits: 'isSafeInteger', + nByteLength: 'isSafeInteger', + adjustScalarBytes: 'function', + domain: 'function', + powPminus2: 'function', + Gu: 'bigint', + }); + // Set defaults + return Object.freeze({ ...curve }); +} +// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748) +// Uses only one coordinate instead of two +export function montgomery(curveDef) { + const CURVE = validateOpts(curveDef); + const { P } = CURVE; + const modP = (n) => mod(n, P); + const montgomeryBits = CURVE.montgomeryBits; + const montgomeryBytes = Math.ceil(montgomeryBits / 8); + const fieldLen = CURVE.nByteLength; + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); + const powPminus2 = CURVE.powPminus2 || ((x) => pow(x, P - BigInt(2), P)); + // cswap from RFC7748. But it is not from RFC7748! + /* + cswap(swap, x_2, x_3): + dummy = mask(swap) AND (x_2 XOR x_3) + x_2 = x_2 XOR dummy + x_3 = x_3 XOR dummy + Return (x_2, x_3) + Where mask(swap) is the all-1 or all-0 word of the same length as x_2 + and x_3, computed, e.g., as mask(swap) = 0 - swap. + */ + function cswap(swap, x_2, x_3) { + const dummy = modP(swap * (x_2 - x_3)); + x_2 = modP(x_2 - dummy); + x_3 = modP(x_3 + dummy); + return [x_2, x_3]; + } + // Accepts 0 as well + function assertFieldElement(n) { + if (typeof n === 'bigint' && _0n <= n && n < P) + return n; + throw new Error('Expected valid scalar 0 < scalar < CURVE.P'); + } + // x25519 from 4 + // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 + const a24 = (CURVE.a - BigInt(2)) / BigInt(4); + /** + * + * @param pointU u coordinate (x) on Montgomery Curve 25519 + * @param scalar by which the point would be multiplied + * @returns new Point on Montgomery curve + */ + function montgomeryLadder(pointU, scalar) { + const u = assertFieldElement(pointU); + // Section 5: Implementations MUST accept non-canonical values and process them as + // if they had been reduced modulo the field prime. + const k = assertFieldElement(scalar); + const x_1 = u; + let x_2 = _1n; + let z_2 = _0n; + let x_3 = u; + let z_3 = _1n; + let swap = _0n; + let sw; + for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) { + const k_t = (k >> t) & _1n; + swap ^= k_t; + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + swap = k_t; + const A = x_2 + z_2; + const AA = modP(A * A); + const B = x_2 - z_2; + const BB = modP(B * B); + const E = AA - BB; + const C = x_3 + z_3; + const D = x_3 - z_3; + const DA = modP(D * A); + const CB = modP(C * B); + const dacb = DA + CB; + const da_cb = DA - CB; + x_3 = modP(dacb * dacb); + z_3 = modP(x_1 * modP(da_cb * da_cb)); + x_2 = modP(AA * BB); + z_2 = modP(E * (AA + modP(a24 * E))); + } + // (x_2, x_3) = cswap(swap, x_2, x_3) + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + // (z_2, z_3) = cswap(swap, z_2, z_3) + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + // z_2^(p - 2) + const z2 = powPminus2(z_2); + // Return x_2 * (z_2^(p - 2)) + return modP(x_2 * z2); + } + function encodeUCoordinate(u) { + return numberToBytesLE(modP(u), montgomeryBytes); + } + function decodeUCoordinate(uEnc) { + // Section 5: When receiving such an array, implementations of X25519 + // MUST mask the most significant bit in the final byte. + // This is very ugly way, but it works because fieldLen-1 is outside of bounds for X448, so this becomes NOOP + // fieldLen - scalaryBytes = 1 for X448 and = 0 for X25519 + const u = ensureBytes('u coordinate', uEnc, montgomeryBytes); + // u[fieldLen-1] crashes QuickJS (TypeError: out-of-bound numeric index) + if (fieldLen === montgomeryBytes) + u[fieldLen - 1] &= 127; // 0b0111_1111 + return bytesToNumberLE(u); + } + function decodeScalar(n) { + const bytes = ensureBytes('scalar', n); + if (bytes.length !== montgomeryBytes && bytes.length !== fieldLen) + throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${bytes.length}`); + return bytesToNumberLE(adjustScalarBytes(bytes)); + } + function scalarMult(scalar, u) { + const pointU = decodeUCoordinate(u); + const _scalar = decodeScalar(scalar); + const pu = montgomeryLadder(pointU, _scalar); + // The result was not contributory + // https://cr.yp.to/ecdh.html#validate + if (pu === _0n) + throw new Error('Invalid private or public key received'); + return encodeUCoordinate(pu); + } + // Computes public key from private. By doing scalar multiplication of base point. + const GuBytes = encodeUCoordinate(CURVE.Gu); + function scalarMultBase(scalar) { + return scalarMult(scalar, GuBytes); + } + return { + scalarMult, + scalarMultBase, + getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey), + getPublicKey: (privateKey) => scalarMultBase(privateKey), + utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) }, + GuBytes: GuBytes, + }; +} +//# sourceMappingURL=montgomery.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/montgomery.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/montgomery.js.map new file mode 100644 index 0000000..6bc1a06 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/montgomery.js.map @@ -0,0 +1 @@ +{"version":3,"file":"montgomery.js","sourceRoot":"","sources":["../../src/abstract/montgomery.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAE3F,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAwBtB,SAAS,YAAY,CAAC,KAAgB;IACpC,cAAc,CACZ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,eAAe,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;QAC3F,OAAO,eAAe,CAAC,iBAAiB,CAAC,KAAK,CAAC,CAAC,CAAC;IACnD,CAAC;IACD,SAAS,UAAU,CAAC,MAAW,EAAE,CAAM;QACrC,MAAM,MAAM,GAAG,iBAAiB,CAAC,CAAC,CAAC,CAAC;QACpC,MAAM,OAAO,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC;QACrC,MAAM,EAAE,GAAG,gBAAgB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAC7C,kCAAkC;QAClC,sCAAsC;QACtC,IAAI,EAAE,KAAK,GAAG;YAAE,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;QAC1E,OAAO,iBAAiB,CAAC,EAAE,CAAC,CAAC;IAC/B,CAAC;IACD,kFAAkF;IAClF,MAAM,OAAO,GAAG,iBAAiB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAC5C,SAAS,cAAc,CAAC,MAAW;QACjC,OAAO,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrC,CAAC;IAED,OAAO;QACL,UAAU;QACV,cAAc;QACd,eAAe,EAAE,CAAC,UAAe,EAAE,SAAc,EAAE,EAAE,CAAC,UAAU,CAAC,UAAU,EAAE,SAAS,CAAC;QACvF,YAAY,EAAE,CAAC,UAAe,EAAc,EAAE,CAAC,cAAc,CAAC,UAAU,CAAC;QACzE,KAAK,EAAE,EAAE,gBAAgB,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,WAAY,CAAC,KAAK,CAAC,WAAW,CAAC,EAAE;QACxE,OAAO,EAAE,OAAO;KACjB,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/poseidon.js b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/poseidon.js new file mode 100644 index 0000000..7ea744b --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/poseidon.js @@ -0,0 +1,110 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Poseidon Hash: https://eprint.iacr.org/2019/458.pdf, https://www.poseidon-hash.info +import { FpPow, validateField } from './modular.js'; +export function validateOpts(opts) { + const { Fp } = opts; + validateField(Fp); + for (const i of ['t', 'roundsFull', 'roundsPartial']) { + if (typeof opts[i] !== 'number' || !Number.isSafeInteger(opts[i])) + throw new Error(`Poseidon: invalid param ${i}=${opts[i]} (${typeof opts[i]})`); + } + if (opts.reversePartialPowIdx !== undefined && typeof opts.reversePartialPowIdx !== 'boolean') + throw new Error(`Poseidon: invalid param reversePartialPowIdx=${opts.reversePartialPowIdx}`); + // Default is 5, but by some reasons stark uses 3 + let sboxPower = opts.sboxPower; + if (sboxPower === undefined) + sboxPower = 5; + if (typeof sboxPower !== 'number' || !Number.isSafeInteger(sboxPower)) + throw new Error(`Poseidon wrong sboxPower=${sboxPower}`); + const _sboxPower = BigInt(sboxPower); + let sboxFn = (n) => FpPow(Fp, n, _sboxPower); + // Unwrapped sbox power for common cases (195->142μs) + if (sboxPower === 3) + sboxFn = (n) => Fp.mul(Fp.sqrN(n), n); + else if (sboxPower === 5) + sboxFn = (n) => Fp.mul(Fp.sqrN(Fp.sqrN(n)), n); + if (opts.roundsFull % 2 !== 0) + throw new Error(`Poseidon roundsFull is not even: ${opts.roundsFull}`); + const rounds = opts.roundsFull + opts.roundsPartial; + if (!Array.isArray(opts.roundConstants) || opts.roundConstants.length !== rounds) + throw new Error('Poseidon: wrong round constants'); + const roundConstants = opts.roundConstants.map((rc) => { + if (!Array.isArray(rc) || rc.length !== opts.t) + throw new Error(`Poseidon wrong round constants: ${rc}`); + return rc.map((i) => { + if (typeof i !== 'bigint' || !Fp.isValid(i)) + throw new Error(`Poseidon wrong round constant=${i}`); + return Fp.create(i); + }); + }); + // MDS is TxT matrix + if (!Array.isArray(opts.mds) || opts.mds.length !== opts.t) + throw new Error('Poseidon: wrong MDS matrix'); + const mds = opts.mds.map((mdsRow) => { + if (!Array.isArray(mdsRow) || mdsRow.length !== opts.t) + throw new Error(`Poseidon MDS matrix row: ${mdsRow}`); + return mdsRow.map((i) => { + if (typeof i !== 'bigint') + throw new Error(`Poseidon MDS matrix value=${i}`); + return Fp.create(i); + }); + }); + return Object.freeze({ ...opts, rounds, sboxFn, roundConstants, mds }); +} +export function splitConstants(rc, t) { + if (typeof t !== 'number') + throw new Error('poseidonSplitConstants: wrong t'); + if (!Array.isArray(rc) || rc.length % t) + throw new Error('poseidonSplitConstants: wrong rc'); + const res = []; + let tmp = []; + for (let i = 0; i < rc.length; i++) { + tmp.push(rc[i]); + if (tmp.length === t) { + res.push(tmp); + tmp = []; + } + } + return res; +} +export function poseidon(opts) { + const { t, Fp, rounds, sboxFn, reversePartialPowIdx } = validateOpts(opts); + const halfRoundsFull = Math.floor(opts.roundsFull / 2); + const partialIdx = reversePartialPowIdx ? t - 1 : 0; + const poseidonRound = (values, isFull, idx) => { + values = values.map((i, j) => Fp.add(i, opts.roundConstants[idx][j])); + if (isFull) + values = values.map((i) => sboxFn(i)); + else + values[partialIdx] = sboxFn(values[partialIdx]); + // Matrix multiplication + values = opts.mds.map((i) => i.reduce((acc, i, j) => Fp.add(acc, Fp.mulN(i, values[j])), Fp.ZERO)); + return values; + }; + const poseidonHash = function poseidonHash(values) { + if (!Array.isArray(values) || values.length !== t) + throw new Error(`Poseidon: wrong values (expected array of bigints with length ${t})`); + values = values.map((i) => { + if (typeof i !== 'bigint') + throw new Error(`Poseidon: wrong value=${i} (${typeof i})`); + return Fp.create(i); + }); + let round = 0; + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) + values = poseidonRound(values, true, round++); + // Apply r_p partial rounds. + for (let i = 0; i < opts.roundsPartial; i++) + values = poseidonRound(values, false, round++); + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) + values = poseidonRound(values, true, round++); + if (round !== rounds) + throw new Error(`Poseidon: wrong number of rounds: last round=${round}, total=${rounds}`); + return values; + }; + // For verification in tests + poseidonHash.roundConstants = opts.roundConstants; + return poseidonHash; +} +//# sourceMappingURL=poseidon.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/poseidon.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/poseidon.js.map new file mode 100644 index 0000000..8863ad2 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/poseidon.js.map @@ -0,0 +1 @@ +{"version":3,"file":"poseidon.js","sourceRoot":"","sources":["../../src/abstract/poseidon.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,sFAAsF;AACtF,OAAO,EAAU,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAc5D,MAAM,UAAU,YAAY,CAAC,IAAkB;IAC7C,MAAM,EAAE,EAAE,EAAE,GAAG,IAAI,CAAC;IACpB,aAAa,CAAC,EAAE,CAAC,CAAC;IAClB,KAAK,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,YAAY,EAAE,eAAe,CAAU,EAAE;QAC7D,IAAI,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAC/D,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,OAAO,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;KAClF;IACD,IAAI,IAAI,CAAC,oBAAoB,KAAK,SAAS,IAAI,OAAO,IAAI,CAAC,oBAAoB,KAAK,SAAS;QAC3F,MAAM,IAAI,KAAK,CAAC,gDAAgD,IAAI,CAAC,oBAAoB,EAAE,CAAC,CAAC;IAC/F,iDAAiD;IACjD,IAAI,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;IAC/B,IAAI,SAAS,KAAK,SAAS;QAAE,SAAS,GAAG,CAAC,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AAM,GAAG,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;QACvF,4BAA4B;QAC5B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,aAAa,EAAE,CAAC,EAAE;YAAE,MAAM,GAAG,aAAa,CAAC,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;QAC5F,2BAA2B;QAC3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,cAAc,EAAE,CAAC,EAAE;YAAE,MAAM,GAAG,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;QAEvF,IAAI,KAAK,KAAK,MAAM;YAClB,MAAM,IAAI,KAAK,CAAC,gDAAgD,KAAK,WAAW,MAAM,EAAE,CAAC,CAAC;QAC5F,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IACF,4BAA4B;IAC5B,YAAY,CAAC,cAAc,GAAG,IAAI,CAAC,cAAc,CAAC;IAClD,OAAO,YAAY,CAAC;AACtB,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/utils.js b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/utils.js new file mode 100644 index 0000000..7839e25 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/utils.js @@ -0,0 +1,265 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// 100 lines of code in the file are duplicated from noble-hashes (utils). +// This is OK: `abstract` directory does not use noble-hashes. +// User may opt-in into using different hashing library. This way, noble-hashes +// won't be included into their bundle. +const _0n = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +const u8a = (a) => a instanceof Uint8Array; +const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export function bytesToHex(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +export function numberToHexUnpadded(num) { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; +} +export function hexToNumber(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + // Big Endian + return BigInt(hex === '' ? '0' : `0x${hex}`); +} +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} +// BE: Big Endian, LE: Little Endian +export function bytesToNumberBE(bytes) { + return hexToNumber(bytesToHex(bytes)); +} +export function bytesToNumberLE(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); +} +export function numberToBytesBE(n, len) { + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} +export function numberToBytesLE(n, len) { + return numberToBytesBE(n, len).reverse(); +} +// Unpadded, rarely used +export function numberToVarBytesBE(n) { + return hexToBytes(numberToHexUnpadded(n)); +} +/** + * Takes hex string or Uint8Array, converts to Uint8Array. + * Validates output length. + * Will throw error for other types. + * @param title descriptive title for an error e.g. 'private key' + * @param hex hex string or Uint8Array + * @param expectedLength optional, will compare to result array's length + * @returns + */ +export function ensureBytes(title, hex, expectedLength) { + let res; + if (typeof hex === 'string') { + try { + res = hexToBytes(hex); + } + catch (e) { + throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`); + } + } + else if (u8a(hex)) { + // Uint8Array.from() instead of hash.slice() because node.js Buffer + // is instance of Uint8Array, and its slice() creates **mutable** copy + res = Uint8Array.from(hex); + } + else { + throw new Error(`${title} must be hex string or Uint8Array`); + } + const len = res.length; + if (typeof expectedLength === 'number' && len !== expectedLength) + throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); + return res; +} +/** + * Copies several Uint8Arrays into one. + */ +export function concatBytes(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) + throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} +export function equalBytes(b1, b2) { + // We don't care about timing attacks here + if (b1.length !== b2.length) + return false; + for (let i = 0; i < b1.length; i++) + if (b1[i] !== b2[i]) + return false; + return true; +} +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +// Bit operations +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + */ +export function bitLen(n) { + let len; + for (len = 0; n > _0n; n >>= _1n, len += 1) + ; + return len; +} +/** + * Gets single bit at position. + * NOTE: first bit position is 0 (same as arrays) + * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` + */ +export function bitGet(n, pos) { + return (n >> BigInt(pos)) & _1n; +} +/** + * Sets single bit at position. + */ +export const bitSet = (n, pos, value) => { + return n | ((value ? _1n : _0n) << BigInt(pos)); +}; +/** + * Calculate mask for N bits. Not using ** operator with bigints because of old engines. + * Same as BigInt(`0b${Array(i).fill('1').join('')}`) + */ +export const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n; +// DRBG +const u8n = (data) => new Uint8Array(data); // creates Uint8Array +const u8fr = (arr) => Uint8Array.from(arr); // another shortcut +/** + * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + * @returns function that will call DRBG until 2nd arg returns something meaningful + * @example + * const drbg = createHmacDRBG(32, 32, hmac); + * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined + */ +export function createHmacDrbg(hashLen, qByteLen, hmacFn) { + if (typeof hashLen !== 'number' || hashLen < 2) + throw new Error('hashLen must be a number'); + if (typeof qByteLen !== 'number' || qByteLen < 2) + throw new Error('qByteLen must be a number'); + if (typeof hmacFn !== 'function') + throw new Error('hmacFn must be a function'); + // Step B, Step C: set hashLen to 8*ceil(hlen/8) + let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same + let i = 0; // Iterations counter, will throw when over 1000 + const reset = () => { + v.fill(1); + k.fill(0); + i = 0; + }; + const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values) + const reseed = (seed = u8n()) => { + // HMAC-DRBG reseed() function. Steps D-G + k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed) + v = h(); // v = hmac(k || v) + if (seed.length === 0) + return; + k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed) + v = h(); // v = hmac(k || v) + }; + const gen = () => { + // HMAC-DRBG generate() function + if (i++ >= 1000) + throw new Error('drbg: tried 1000 values'); + let len = 0; + const out = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes(...out); + }; + const genUntil = (seed, pred) => { + reset(); + reseed(seed); // Steps D-G + let res = undefined; // Step H: grind until k is in [1..n-1] + while (!(res = pred(gen()))) + reseed(); + reset(); + return res; + }; + return genUntil; +} +// Validating curves and fields +const validatorFns = { + bigint: (val) => typeof val === 'bigint', + function: (val) => typeof val === 'function', + boolean: (val) => typeof val === 'boolean', + string: (val) => typeof val === 'string', + isSafeInteger: (val) => Number.isSafeInteger(val), + array: (val) => Array.isArray(val), + field: (val, object) => object.Fp.isValid(val), + hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen), +}; +// type Record = { [P in K]: T; } +export function validateObject(object, validators, optValidators = {}) { + const checkField = (fieldName, type, isOptional) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== 'function') + throw new Error(`Invalid validator "${type}", expected function`); + const val = object[fieldName]; + if (isOptional && val === undefined) + return; + if (!checkVal(val, object)) { + throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); + } + }; + for (const [fieldName, type] of Object.entries(validators)) + checkField(fieldName, type, false); + for (const [fieldName, type] of Object.entries(optValidators)) + checkField(fieldName, type, true); + return object; +} +// validate type tests +// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 }; +// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok! +// // Should fail type-check +// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' }); +// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' }); +// const z3 = validateObject(o, { test: 'boolean', z: 'bug' }); +// const z4 = validateObject(o, { a: 'boolean', z: 'bug' }); +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/utils.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/utils.js.map new file mode 100644 index 0000000..289afb8 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/abstract/utils.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,0EAA0E;AAC1E,8DAA8D;AAC9D,+EAA+E;AAC/E,uCAAuC;AACvC,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,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,CAAC,OAAO,CAAC,aAAa,CAAC;QAAE,UAAU,CAAC,SAAS,EAAE,IAAK,EAAE,IAAI,CAAC,CAAC;IAClG,OAAO,MAAM,CAAC;AAChB,CAAC;AACD,sBAAsB;AACtB,uEAAuE;AACvE,gFAAgF;AAChF,4BAA4B;AAC5B,2DAA2D;AAC3D,qEAAqE;AACrE,+DAA+D;AAC/D,4DAA4D"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/weierstrass.js b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/weierstrass.js new file mode 100644 index 0000000..3d79ba0 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/weierstrass.js @@ -0,0 +1,1054 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Short Weierstrass curve. The formula is: y² = x³ + ax + b +import * as mod from './modular.js'; +import * as ut from './utils.js'; +import { ensureBytes } from './utils.js'; +import { wNAF, validateBasic } from './curve.js'; +function validatePointOpts(curve) { + const opts = validateBasic(curve); + ut.validateObject(opts, { + a: 'field', + b: 'field', + }, { + allowedPrivateKeyLengths: 'array', + wrapPrivateKey: 'boolean', + isTorsionFree: 'function', + clearCofactor: 'function', + allowInfinityPoint: 'boolean', + fromBytes: 'function', + toBytes: 'function', + }); + const { endo, Fp, a } = opts; + if (endo) { + if (!Fp.eql(a, Fp.ZERO)) { + throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0'); + } + if (typeof endo !== 'object' || + typeof endo.beta !== 'bigint' || + typeof endo.splitScalar !== 'function') { + throw new Error('Expected endomorphism with beta: bigint and splitScalar: function'); + } + } + return Object.freeze({ ...opts }); +} +// ASN.1 DER encoding utilities +const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; +export const DER = { + // asn.1 DER encoding utils + Err: class DERErr extends Error { + constructor(m = '') { + super(m); + } + }, + _parseInt(data) { + const { Err: E } = DER; + if (data.length < 2 || data[0] !== 0x02) + throw new E('Invalid signature integer tag'); + const len = data[1]; + const res = data.subarray(2, len + 2); + if (!len || res.length !== len) + throw new E('Invalid signature integer: wrong length'); + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + if (res[0] & 0b10000000) + throw new E('Invalid signature integer: negative'); + if (res[0] === 0x00 && !(res[1] & 0b10000000)) + throw new E('Invalid signature integer: unnecessary leading zero'); + return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left + }, + toSig(hex) { + // parse DER signature + const { Err: E } = DER; + const data = typeof hex === 'string' ? h2b(hex) : hex; + if (!(data instanceof Uint8Array)) + throw new Error('ui8a expected'); + let l = data.length; + if (l < 2 || data[0] != 0x30) + throw new E('Invalid signature tag'); + if (data[1] !== l - 2) + throw new E('Invalid signature: incorrect length'); + const { d: r, l: sBytes } = DER._parseInt(data.subarray(2)); + const { d: s, l: rBytesLeft } = DER._parseInt(sBytes); + if (rBytesLeft.length) + throw new E('Invalid signature: left bytes after parsing'); + return { r, s }; + }, + hexFromSig(sig) { + // Add leading zero if first byte has negative bit enabled. More details in '_parseInt' + const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s); + const h = (num) => { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; + }; + const s = slice(h(sig.s)); + const r = slice(h(sig.r)); + const shl = s.length / 2; + const rhl = r.length / 2; + const sl = h(shl); + const rl = h(rhl); + return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`; + }, +}; +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4); +export function weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ + const toBytes = CURVE.toBytes || + ((c, point, isCompressed) => { + const a = point.toAffine(); + return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y)); + }); + const fromBytes = CURVE.fromBytes || + ((bytes) => { + // const head = bytes[0]; + const tail = bytes.subarray(1); + // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported'); + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + }); + /** + * y² = x³ + ax + b: Short weierstrass curve formula + * @returns y² + */ + function weierstrassEquation(x) { + const { a, b } = CURVE; + const x2 = Fp.sqr(x); // x * x + const x3 = Fp.mul(x2, x); // x2 * x + return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b + } + // Validate whether the passed curve params are valid. + // We check if curve equation works for generator point. + // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381. + // ProjectivePoint class has not been initialized yet. + if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error('bad generator point: equation left != right'); + // Valid group elements reside in range 1..n-1 + function isWithinCurveOrder(num) { + return typeof num === 'bigint' && _0n < num && num < CURVE.n; + } + function assertGE(num) { + if (!isWithinCurveOrder(num)) + throw new Error('Expected valid bigint: 0 < bigint < curve.n'); + } + // Validates if priv key is valid and converts it to bigint. + // Supports options allowedPrivateKeyLengths and wrapPrivateKey. + function normPrivateKeyToScalar(key) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE; + if (lengths && typeof key !== 'bigint') { + if (key instanceof Uint8Array) + key = ut.bytesToHex(key); + // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes + if (typeof key !== 'string' || !lengths.includes(key.length)) + throw new Error('Invalid key'); + key = key.padStart(nByteLength * 2, '0'); + } + let num; + try { + num = + typeof key === 'bigint' + ? key + : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength)); + } + catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + } + if (wrapPrivateKey) + num = mod.mod(num, n); // disabled by default, enabled for BLS + assertGE(num); // num in range [1..N-1] + return num; + } + const pointPrecomputes = new Map(); + function assertPrjPoint(other) { + if (!(other instanceof Point)) + throw new Error('ProjectivePoint expected'); + } + /** + * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z) + * Default Point works in 2d / affine coordinates: (x, y) + * We're doing calculations in projective, because its operations don't require costly inversion. + */ + class Point { + constructor(px, py, pz) { + this.px = px; + this.py = py; + this.pz = pz; + if (px == null || !Fp.isValid(px)) + throw new Error('x required'); + if (py == null || !Fp.isValid(py)) + throw new Error('y required'); + if (pz == null || !Fp.isValid(pz)) + throw new Error('z required'); + } + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + static fromAffine(p) { + const { x, y } = p || {}; + if (!p || !Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('invalid affine point'); + if (p instanceof Point) + throw new Error('projective point not allowed'); + const is0 = (i) => Fp.eql(i, Fp.ZERO); + // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0) + if (is0(x) && is0(y)) + return Point.ZERO; + return new Point(x, y, Fp.ONE); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + /** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + */ + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex) { + const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex))); + P.assertValidity(); + return P; + } + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey) { + return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + // A point on curve is valid if it conforms to equation. + assertValidity() { + // Zero is valid point too! + if (this.is0()) { + if (CURVE.allowInfinityPoint) + return; + throw new Error('bad point: ZERO'); + } + // Some 3rd-party test vectors require different wording between here & `fromCompressedHex` + const { x, y } = this.toAffine(); + // Check if x, y are valid field elements + if (!Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('bad point: x or y not FE'); + const left = Fp.sqr(y); // y² + const right = weierstrassEquation(x); // x³ + ax + b + if (!Fp.eql(left, right)) + throw new Error('bad point: equation left != right'); + if (!this.isTorsionFree()) + throw new Error('bad point: not in prime-order subgroup'); + } + hasEvenY() { + const { y } = this.toAffine(); + if (Fp.isOdd) + return !Fp.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + /** + * Compare one point to another. + */ + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); + const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); + return U1 && U2; + } + /** + * Flips point to one corresponding to (x, -y) in Affine coordinates. + */ + negate() { + return new Point(this.px, Fp.neg(this.py), this.pz); + } + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a, b } = CURVE; + const b3 = Fp.mul(b, _3n); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + let t0 = Fp.mul(X1, X1); // step 1 + let t1 = Fp.mul(Y1, Y1); + let t2 = Fp.mul(Z1, Z1); + let t3 = Fp.mul(X1, Y1); + t3 = Fp.add(t3, t3); // step 5 + Z3 = Fp.mul(X1, Z1); + Z3 = Fp.add(Z3, Z3); + X3 = Fp.mul(a, Z3); + Y3 = Fp.mul(b3, t2); + Y3 = Fp.add(X3, Y3); // step 10 + X3 = Fp.sub(t1, Y3); + Y3 = Fp.add(t1, Y3); + Y3 = Fp.mul(X3, Y3); + X3 = Fp.mul(t3, X3); + Z3 = Fp.mul(b3, Z3); // step 15 + t2 = Fp.mul(a, t2); + t3 = Fp.sub(t0, t2); + t3 = Fp.mul(a, t3); + t3 = Fp.add(t3, Z3); + Z3 = Fp.add(t0, t0); // step 20 + t0 = Fp.add(Z3, t0); + t0 = Fp.add(t0, t2); + t0 = Fp.mul(t0, t3); + Y3 = Fp.add(Y3, t0); + t2 = Fp.mul(Y1, Z1); // step 25 + t2 = Fp.add(t2, t2); + t0 = Fp.mul(t2, t3); + X3 = Fp.sub(X3, t0); + Z3 = Fp.mul(t2, t1); + Z3 = Fp.add(Z3, Z3); // step 30 + Z3 = Fp.add(Z3, Z3); + return new Point(X3, Y3, Z3); + } + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + const a = CURVE.a; + const b3 = Fp.mul(CURVE.b, _3n); + let t0 = Fp.mul(X1, X2); // step 1 + let t1 = Fp.mul(Y1, Y2); + let t2 = Fp.mul(Z1, Z2); + let t3 = Fp.add(X1, Y1); + let t4 = Fp.add(X2, Y2); // step 5 + t3 = Fp.mul(t3, t4); + t4 = Fp.add(t0, t1); + t3 = Fp.sub(t3, t4); + t4 = Fp.add(X1, Z1); + let t5 = Fp.add(X2, Z2); // step 10 + t4 = Fp.mul(t4, t5); + t5 = Fp.add(t0, t2); + t4 = Fp.sub(t4, t5); + t5 = Fp.add(Y1, Z1); + X3 = Fp.add(Y2, Z2); // step 15 + t5 = Fp.mul(t5, X3); + X3 = Fp.add(t1, t2); + t5 = Fp.sub(t5, X3); + Z3 = Fp.mul(a, t4); + X3 = Fp.mul(b3, t2); // step 20 + Z3 = Fp.add(X3, Z3); + X3 = Fp.sub(t1, Z3); + Z3 = Fp.add(t1, Z3); + Y3 = Fp.mul(X3, Z3); + t1 = Fp.add(t0, t0); // step 25 + t1 = Fp.add(t1, t0); + t2 = Fp.mul(a, t2); + t4 = Fp.mul(b3, t4); + t1 = Fp.add(t1, t2); + t2 = Fp.sub(t0, t2); // step 30 + t2 = Fp.mul(a, t2); + t4 = Fp.add(t4, t2); + t0 = Fp.mul(t1, t4); + Y3 = Fp.add(Y3, t0); + t0 = Fp.mul(t5, t4); // step 35 + X3 = Fp.mul(t3, X3); + X3 = Fp.sub(X3, t0); + t0 = Fp.mul(t3, t1); + Z3 = Fp.mul(t5, Z3); + Z3 = Fp.add(Z3, t0); // step 40 + return new Point(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + is0() { + return this.equals(Point.ZERO); + } + wNAF(n) { + return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => { + const toInv = Fp.invertBatch(comp.map((p) => p.pz)); + return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + }); + } + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(n) { + const I = Point.ZERO; + if (n === _0n) + return I; + assertGE(n); // Will throw on 0 + if (n === _1n) + return this; + const { endo } = CURVE; + if (!endo) + return wnaf.unsafeLadder(this, n); + // Apply endomorphism + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let k1p = I; + let k2p = I; + let d = this; + while (k1 > _0n || k2 > _0n) { + if (k1 & _1n) + k1p = k1p.add(d); + if (k2 & _1n) + k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n; + k2 >>= _1n; + } + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar by which the point would be multiplied + * @returns New point + */ + multiply(scalar) { + assertGE(scalar); + let n = scalar; + let point, fake; // Fake point is used to const-time mult + const { endo } = CURVE; + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } + else { + const { p, f } = this.wNAF(n); + point = p; + fake = f; + } + // Normalize `z` for both points, but return only real one + return Point.normalizeZ([point, fake])[0]; + } + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q, a, b) { + const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes + const mul = (P, a // Select faster multiply() method + ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a)); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? undefined : sum; + } + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + toAffine(iz) { + const { px: x, py: y, pz: z } = this; + const is0 = this.is0(); + // If invZ was 0, we return zero point. However we still want to execute + // all operations, so we replace invZ with a random number, 1. + if (iz == null) + iz = is0 ? Fp.ONE : Fp.inv(z); + const ax = Fp.mul(x, iz); + const ay = Fp.mul(y, iz); + const zz = Fp.mul(z, iz); + if (is0) + return { x: Fp.ZERO, y: Fp.ZERO }; + if (!Fp.eql(zz, Fp.ONE)) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + } + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n) + return true; // No subgroups, always torsion-free + if (isTorsionFree) + return isTorsionFree(Point, this); + throw new Error('isTorsionFree() has not been declared for the elliptic curve'); + } + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n) + return this; // Fast-path + if (clearCofactor) + return clearCofactor(Point, this); + return this.multiplyUnsafe(CURVE.h); + } + toRawBytes(isCompressed = true) { + this.assertValidity(); + return toBytes(Point, this, isCompressed); + } + toHex(isCompressed = true) { + return ut.bytesToHex(this.toRawBytes(isCompressed)); + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); + Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + // Validate if generator point is on curve + return { + CURVE, + ProjectivePoint: Point, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + }; +} +function validateOpts(curve) { + const opts = validateBasic(curve); + ut.validateObject(opts, { + hash: 'hash', + hmac: 'function', + randomBytes: 'function', + }, { + bits2int: 'function', + bits2int_modN: 'function', + lowS: 'boolean', + }); + return Object.freeze({ lowS: true, ...opts }); +} +export function weierstrass(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32 + const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32 + function isValidFieldElement(num) { + return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE + } + function modN(a) { + return mod.mod(a, CURVE_ORDER); + } + function invN(a) { + return mod.invert(a, CURVE_ORDER); + } + const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({ + ...CURVE, + toBytes(c, point, isCompressed) { + const a = point.toAffine(); + const x = Fp.toBytes(a.x); + const cat = ut.concatBytes; + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x); + } + else { + return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y)); + } + }, + fromBytes(bytes) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + // this.assertValidity() is done inside of fromHex + if (len === compressedLen && (head === 0x02 || head === 0x03)) { + const x = ut.bytesToNumberBE(tail); + if (!isValidFieldElement(x)) + throw new Error('Point is not on curve'); + const y2 = weierstrassEquation(x); // y² = x³ + ax + b + let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 + const isYOdd = (y & _1n) === _1n; + // ECDSA + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y = Fp.neg(y); + return { x, y }; + } + else if (len === uncompressedLen && head === 0x04) { + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + } + else { + throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); + } + }, + }); + const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number) { + const HALF = CURVE_ORDER >> _1n; + return number > HALF; + } + function normalizeS(s) { + return isBiggerThanHalfOrder(s) ? modN(-s) : s; + } + // slice bytes num + const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to)); + /** + * ECDSA signature with its (r, s) properties. Supports DER & compact representations. + */ + class Signature { + constructor(r, s, recovery) { + this.r = r; + this.s = s; + this.recovery = recovery; + this.assertValidity(); + } + // pair (bytes of r, bytes of s) + static fromCompact(hex) { + const l = CURVE.nByteLength; + hex = ensureBytes('compactSignature', hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex) { + const { r, s } = DER.toSig(ensureBytes('DER', hex)); + return new Signature(r, s); + } + assertValidity() { + // can use assertGE here + if (!isWithinCurveOrder(this.r)) + throw new Error('r must be 0 < r < CURVE.n'); + if (!isWithinCurveOrder(this.s)) + throw new Error('s must be 0 < s < CURVE.n'); + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(msgHash) { + const { r, s, recovery: rec } = this; + const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error('recovery id invalid'); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp.ORDER) + throw new Error('recovery id 2 or 3 invalid'); + const prefix = (rec & 1) === 0 ? '02' : '03'; + const R = Point.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); // r^-1 + const u1 = modN(-h * ir); // -hr^-1 + const u2 = modN(s * ir); // sr^-1 + const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1) + if (!Q) + throw new Error('point at infinify'); // unsafe is fine: no priv data leaked + Q.assertValidity(); + return Q; + } + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; + } + // DER-encoded + toDERRawBytes() { + return ut.hexToBytes(this.toDERHex()); + } + toDERHex() { + return DER.hexFromSig({ r: this.r, s: this.s }); + } + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return ut.hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + const utils = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } + catch (error) { + return false; + } + }, + normPrivateKeyToScalar: normPrivateKeyToScalar, + /** + * Produces cryptographically secure private key from random of size (nBitLength+64) + * as per FIPS 186 B.4.1 with modulo bias being neglible. + */ + randomPrivateKey: () => { + const rand = CURVE.randomBytes(Fp.BYTES + 8); + const num = mod.hashToPrivateScalar(rand, CURVE_ORDER); + return ut.numberToBytesBE(num, CURVE.nByteLength); + }, + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here + return point; + }, + }; + /** + * Computes public key for a private key. Checks for validity of the private key. + * @param privateKey private key + * @param isCompressed whether to return compact (default), or full key + * @returns Public key, full when isCompressed=false; short when isCompressed=true + */ + function getPublicKey(privateKey, isCompressed = true) { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + /** + * Quick and dirty check for item being public key. Does not validate hex, or being on-curve. + */ + function isProbPub(item) { + const arr = item instanceof Uint8Array; + const str = typeof item === 'string'; + const len = (arr || str) && item.length; + if (arr) + return len === compressedLen || len === uncompressedLen; + if (str) + return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point) + return true; + return false; + } + /** + * ECDH (Elliptic Curve Diffie Hellman). + * Computes shared public key from private key and public key. + * Checks: 1) private key validity 2) shared key is on-curve. + * Does NOT hash the result. + * @param privateA private key + * @param publicB different public key + * @param isCompressed whether to return compact (default), or full key + * @returns shared public key + */ + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) + throw new Error('first arg must be private key'); + if (!isProbPub(publicB)) + throw new Error('second arg must be public key'); + const b = Point.fromHex(publicB); // check for being on-curve + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets. + // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int. + // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same. + // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors + const bits2int = CURVE.bits2int || + function (bytes) { + // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m) + // for some cases, since bytes.length * 8 is not actual bitLength. + const num = ut.bytesToNumberBE(bytes); // check for == u8 done here + const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits + return delta > 0 ? num >> BigInt(delta) : num; + }; + const bits2int_modN = CURVE.bits2int_modN || + function (bytes) { + return modN(bits2int(bytes)); // can't use bytesToNumberBE here + }; + // NOTE: pads output with zero as per spec + const ORDER_MASK = ut.bitMask(CURVE.nBitLength); + /** + * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. + */ + function int2octets(num) { + if (typeof num !== 'bigint') + throw new Error('bigint expected'); + if (!(_0n <= num && num < ORDER_MASK)) + throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); + // works with order, can have different size than numToField! + return ut.numberToBytesBE(num, CURVE.nByteLength); + } + // Steps A, D of RFC6979 3.2 + // Creates RFC6979 seed; converts msg/privKey to numbers. + // Used only in sign, not in verify. + // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521. + // Also it can be bigger for P224 + SHA256 + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (['recovered', 'canonical'].some((k) => k in opts)) + throw new Error('sign() legacy options not supported'); + const { hash, randomBytes } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default + if (lowS == null) + lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash + msgHash = ensureBytes('msgHash', msgHash); + if (prehash) + msgHash = ensureBytes('prehashed msgHash', hash(msgHash)); + // We can't later call bits2octets, since nested bits2int is broken for curves + // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call. + // const bits2octets = (bits) => int2octets(bits2int_modN(bits)) + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint + const seedArgs = [int2octets(d), int2octets(h1int)]; + // extraEntropy. RFC6979 3.6: additional k' (optional). + if (ent != null) { + // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') + const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is + seedArgs.push(ensureBytes('extraEntropy', e, Fp.BYTES)); // check for being of size BYTES + } + const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2 + const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash! + // Converts signature params into point w r/s, checks result for validity. + function k2sig(kBytes) { + // RFC 6979 Section 3.2, step 3: k = bits2int(T) + const k = bits2int(kBytes); // Cannot use fields methods, since it is group element + if (!isWithinCurveOrder(k)) + return; // Important: all mod() calls here must be done over N + const ik = invN(k); // k^-1 mod n + const q = Point.BASE.multiply(k).toAffine(); // q = Gk + const r = modN(q.x); // r = q.x mod n + if (r === _0n) + return; + // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to + // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it: + // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT + const s = modN(ik * modN(m + r * d)); // Not using blinding here + if (s === _0n) + return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n) + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); // if lowS was passed, ensure s is always + recovery ^= 1; // // in the bottom half of N + } + return new Signature(r, normS, recovery); // use normS, not s + } + return { seed, k2sig }; + } + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + /** + * Signs message hash with a private key. + * ``` + * sign(m, d, k) where + * (x, y) = G × k + * r = x mod n + * s = (m + dr)/k mod n + * ``` + * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`. + * @param privKey private key + * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg. + * @returns signature with recovery param + */ + function sign(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2. + const C = CURVE; + const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); // Steps B, C, D, E, F, G + } + // Enable precomputes. Slows down first publicKey computation by 20ms. + Point.BASE._setWindowSize(8); + // utils.precompute(8, ProjectivePoint.BASE) + /** + * Verifies a signature against message hash and public key. + * Rejects lowS signatures by default: to override, + * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf: + * + * ``` + * verify(r, s, h, P) where + * U1 = hs^-1 mod n + * U2 = rs^-1 mod n + * R = U1⋅G - U2⋅P + * mod(R.x, n) == r + * ``` + */ + function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { + const sg = signature; + msgHash = ensureBytes('msgHash', msgHash); + publicKey = ensureBytes('publicKey', publicKey); + if ('strict' in opts) + throw new Error('options.strict was renamed to lowS'); + const { lowS, prehash } = opts; + let _sig = undefined; + let P; + try { + if (typeof sg === 'string' || sg instanceof Uint8Array) { + // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length). + // Since DER can also be 2*nByteLength bytes, we check for it first. + try { + _sig = Signature.fromDER(sg); + } + catch (derError) { + if (!(derError instanceof DER.Err)) + throw derError; + _sig = Signature.fromCompact(sg); + } + } + else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') { + const { r, s } = sg; + _sig = new Signature(r, s); + } + else { + throw new Error('PARSE'); + } + P = Point.fromHex(publicKey); + } + catch (error) { + if (error.message === 'PARSE') + throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; + } + if (lowS && _sig.hasHighS()) + return false; + if (prehash) + msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element + const is = invN(s); // s^-1 + const u1 = modN(h * is); // u1 = hs^-1 mod n + const u2 = modN(r * is); // u2 = rs^-1 mod n + const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P + if (!R) + return false; + const v = modN(R.x); + return v === r; + } + return { + CURVE, + getPublicKey, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point, + Signature, + utils, + }; +} +/** + * Implementation of the Shallue and van de Woestijne method for any weierstrass curve. + * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular. + * b = True and y = sqrt(u / v) if (u / v) is square in F, and + * b = False and y = sqrt(Z * (u / v)) otherwise. + * @param Fp + * @param Z + * @returns + */ +export function SWUFpSqrtRatio(Fp, Z) { + // Generic implementation + const q = Fp.ORDER; + let l = _0n; + for (let o = q - _1n; o % _2n === _0n; o /= _2n) + l += _1n; + const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1. + // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<. + // 2n ** c1 == 2n << (c1-1) + const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n); + const _2n_pow_c1 = _2n_pow_c1_1 * _2n; + const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic + const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic + const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic + const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic + const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2 + const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2) + let sqrtRatio = (u, v) => { + let tv1 = c6; // 1. tv1 = c6 + let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4 + let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2 + tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v + let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3 + tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3 + tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2 + tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v + tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u + let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2 + tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5 + let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1 + tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7 + tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1 + tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR) + tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR) + // 17. for i in (c1, c1 - 1, ..., 2): + for (let i = c1; i > _1n; i--) { + let tv5 = i - _2n; // 18. tv5 = i - 2 + tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5 + let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5 + const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1 + tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1 + tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1 + tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1 + tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1) + tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1) + } + return { isValid: isQR, value: tv3 }; + }; + if (Fp.ORDER % _4n === _3n) { + // sqrt_ratio_3mod4(u, v) + const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic + const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z) + sqrtRatio = (u, v) => { + let tv1 = Fp.sqr(v); // 1. tv1 = v^2 + const tv2 = Fp.mul(u, v); // 2. tv2 = u * v + tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2 + let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1 + y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2 + const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2 + const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v + const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u + let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR) + return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2 + }; + } + // No curves uses that + // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8 + return sqrtRatio; +} +/** + * From draft-irtf-cfrg-hash-to-curve-16 + */ +export function mapToCurveSimpleSWU(Fp, opts) { + mod.validateField(Fp); + if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z)) + throw new Error('mapToCurveSimpleSWU: invalid opts'); + const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z); + if (!Fp.isOdd) + throw new Error('Fp.isOdd is not implemented!'); + // Input: u, an element of F. + // Output: (x, y), a point on E. + return (u) => { + // prettier-ignore + let tv1, tv2, tv3, tv4, tv5, tv6, x, y; + tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1 + tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2 + tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1 + tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1 + tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3 + tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0) + tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4 + tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2 + tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2 + tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6 + tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5 + tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3 + tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4 + tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6 + tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5 + x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3 + const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6) + y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1 + y = Fp.mul(y, value); // 20. y = y * y1 + x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square) + y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square) + const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y) + y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1) + x = Fp.div(x, tv4); // 25. x = x / tv4 + return { x, y }; + }; +} +//# sourceMappingURL=weierstrass.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/weierstrass.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/weierstrass.js.map new file mode 100644 index 0000000..7d2bc4b --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/abstract/weierstrass.js.map @@ -0,0 +1 @@ +{"version":3,"file":"weierstrass.js","sourceRoot":"","sources":["../../src/abstract/weierstrass.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,4DAA4D;AAC5D,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AACjC,OAAO,EAAuB,WAAW,EAAE,MAAM,YAAY,CAAC;AAC9D,OAAO,EAA2B,IAAI,EAAc,aAAa,EAAe,MAAM,YAAY,CAAC;AAqFnG,SAAS,iBAAiB,CAAI,KAAyB;IACrD,MAAM,IAAI,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC;IAClC,EAAE,CAAC,cAAc,CACf,IAAI,EACJ;QACE,CAAC,EAAE,OAAO;QACV,CAAC,EAAE,OAAO;KACX,EACD;QACE,wBAAwB,EAAE,OAAO;QACjC,cAAc,EAAE,SAAS;QACzB,aAAa,EAAE,UAAU;QACzB,aAAa,EAAE,UAAU;QACzB,kBAAkB,EAAE,SAAS;QAC7B,SAAS,EAAE,UAAU;QACrB,OAAO,EAAE,UAAU;KACpB,CACF,CAAC;IACF,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,EAAE,GAAG,IAAI,CAAC;IAC7B,IAAI,IAAI,EAAE;QACR,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE;YACvB,MAAM,IAAI,KAAK,CAAC,mEAAmE,CAAC,CAAC;SACtF;QACD,IACE,OAAO,IAAI,KAAK,QAAQ;YACxB,OAAO,IAAI,CAAC,IAAI,KAAK,QAAQ;YAC7B,OAAO,IAAI,CAAC,WAAW,KAAK,UAAU,EACtC;YACA,MAAM,IA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CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,uCAAuC;QACvE,MAAM,EAAE,GAAG,EAAE,CAAC,KAAM,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,KAAM,CAAC,CAAC,CAAC,CAAC,CAAC,+BAA+B;QACzE,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,4BAA4B;QAC3D,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,oBAAoB;QACxC,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IAClB,CAAC,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/bls12-381.js b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/bls12-381.js new file mode 100644 index 0000000..4173044 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/bls12-381.js @@ -0,0 +1,1173 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// bls12-381 pairing-friendly Barreto-Lynn-Scott elliptic curve construction allows to: +// - Construct zk-SNARKs at the 128-bit security +// - Use threshold signatures, which allows a user to sign lots of messages with one signature and +// verify them swiftly in a batch, using Boneh-Lynn-Shacham signature scheme. +// +// The library uses G1 for public keys and G2 for signatures. Support for G1 signatures is planned. +// Compatible with Algorand, Chia, Dfinity, Ethereum, FIL, Zcash. Matches specs +// [pairing-curves-11](https://tools.ietf.org/html/draft-irtf-cfrg-pairing-friendly-curves-11), +// [bls-sigs-04](https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-04), +// [hash-to-curve-12](https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-12). +// +// ### Summary +// 1. BLS Relies on Bilinear Pairing (expensive) +// 2. Private Keys: 32 bytes +// 3. Public Keys: 48 bytes: 381 bit affine x coordinate, encoded into 48 big-endian bytes. +// 4. Signatures: 96 bytes: two 381 bit integers (affine x coordinate), encoded into two 48 big-endian byte arrays. +// - The signature is a point on the G2 subgroup, which is defined over a finite field +// with elements twice as big as the G1 curve (G2 is over Fp2 rather than Fp. Fp2 is analogous to the complex numbers). +// 5. The 12 stands for the Embedding degree. +// +// ### Formulas +// - `P = pk x G` - public keys +// - `S = pk x H(m)` - signing +// - `e(P, H(m)) == e(G, S)` - verification using pairings +// - `e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))` - signature aggregation +// Filecoin uses little endian byte arrays for private keys - +// so ensure to reverse byte order if you'll use it with FIL. +import { sha256 } from '@noble/hashes/sha256'; +import { randomBytes } from '@noble/hashes/utils'; +import { bls } from './abstract/bls.js'; +import * as mod from './abstract/modular.js'; +import { concatBytes as concatB, ensureBytes, numberToBytesBE, bytesToNumberBE, bitLen, bitSet, bitGet, bitMask, bytesToHex, } from './abstract/utils.js'; +// Types +import { mapToCurveSimpleSWU, } from './abstract/weierstrass.js'; +import { isogenyMap } from './abstract/hash-to-curve.js'; +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4); +// prettier-ignore +const _8n = BigInt(8), _16n = BigInt(16); +// CURVE FIELDS +// Finite field over p. +const Fp_raw = BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'); +const Fp = mod.Field(Fp_raw); +// Finite field over r. +// This particular field is not used anywhere in bls12-381, but it is still useful. +const Fr = mod.Field(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')); +const Fp2Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp.add(c0, r0), + c1: Fp.add(c1, r1), +}); +const Fp2Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp.sub(c0, r0), + c1: Fp.sub(c1, r1), +}); +const Fp2Multiply = ({ c0, c1 }, rhs) => { + if (typeof rhs === 'bigint') + return { c0: Fp.mul(c0, rhs), c1: Fp.mul(c1, rhs) }; + // (a+bi)(c+di) = (ac−bd) + (ad+bc)i + const { c0: r0, c1: r1 } = rhs; + let t1 = Fp.mul(c0, r0); // c0 * o0 + let t2 = Fp.mul(c1, r1); // c1 * o1 + // (T1 - T2) + ((c0 + c1) * (r0 + r1) - (T1 + T2))*i + const o0 = Fp.sub(t1, t2); + const o1 = Fp.sub(Fp.mul(Fp.add(c0, c1), Fp.add(r0, r1)), Fp.add(t1, t2)); + return { c0: o0, c1: o1 }; +}; +const Fp2Square = ({ c0, c1 }) => { + const a = Fp.add(c0, c1); + const b = Fp.sub(c0, c1); + const c = Fp.add(c0, c0); + return { c0: Fp.mul(a, b), c1: Fp.mul(c, c1) }; +}; +// G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1), +// where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where +// G² - 1 +// h2q +// NOTE: ORDER was wrong! +const FP2_ORDER = Fp_raw * Fp_raw; +const Fp2 = { + ORDER: FP2_ORDER, + BITS: bitLen(FP2_ORDER), + BYTES: Math.ceil(bitLen(FP2_ORDER) / 8), + MASK: bitMask(bitLen(FP2_ORDER)), + ZERO: { c0: Fp.ZERO, c1: Fp.ZERO }, + ONE: { c0: Fp.ONE, c1: Fp.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => typeof c0 === 'bigint' && typeof c1 === 'bigint', + is0: ({ c0, c1 }) => Fp.is0(c0) && Fp.is0(c1), + eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp.eql(c0, r0) && Fp.eql(c1, r1), + neg: ({ c0, c1 }) => ({ c0: Fp.neg(c0), c1: Fp.neg(c1) }), + pow: (num, power) => mod.FpPow(Fp2, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp2, nums), + // Normalized + add: Fp2Add, + sub: Fp2Subtract, + mul: Fp2Multiply, + sqr: Fp2Square, + // NonNormalized stuff + addN: Fp2Add, + subN: Fp2Subtract, + mulN: Fp2Multiply, + sqrN: Fp2Square, + // Why inversion for bigint inside Fp instead of Fp2? it is even used in that context? + div: (lhs, rhs) => Fp2.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp2.inv(rhs)), + inv: ({ c0: a, c1: b }) => { + // We wish to find the multiplicative inverse of a nonzero + // element a + bu in Fp2. We leverage an identity + // + // (a + bu)(a - bu) = a² + b² + // + // which holds because u² = -1. This can be rewritten as + // + // (a + bu)(a - bu)/(a² + b²) = 1 + // + // because a² + b² = 0 has no nonzero solutions for (a, b). + // This gives that (a - bu)/(a² + b²) is the inverse + // of (a + bu). Importantly, this can be computing using + // only a single inversion in Fp. + const factor = Fp.inv(Fp.create(a * a + b * b)); + return { c0: Fp.mul(factor, Fp.create(a)), c1: Fp.mul(factor, Fp.create(-b)) }; + }, + sqrt: (num) => { + if (Fp2.eql(num, Fp2.ZERO)) + return Fp2.ZERO; // Algo doesn't handles this case + // TODO: Optimize this line. It's extremely slow. + // Speeding this up would boost aggregateSignatures. + // https://eprint.iacr.org/2012/685.pdf applicable? + // https://github.com/zkcrypto/bls12_381/blob/080eaa74ec0e394377caa1ba302c8c121df08b07/src/fp2.rs#L250 + // https://github.com/supranational/blst/blob/aae0c7d70b799ac269ff5edf29d8191dbd357876/src/exp2.c#L1 + // Inspired by https://github.com/dalek-cryptography/curve25519-dalek/blob/17698df9d4c834204f83a3574143abacb4fc81a5/src/field.rs#L99 + const candidateSqrt = Fp2.pow(num, (Fp2.ORDER + _8n) / _16n); + const check = Fp2.div(Fp2.sqr(candidateSqrt), num); // candidateSqrt.square().div(this); + const R = FP2_ROOTS_OF_UNITY; + const divisor = [R[0], R[2], R[4], R[6]].find((r) => Fp2.eql(r, check)); + if (!divisor) + throw new Error('No root'); + const index = R.indexOf(divisor); + const root = R[index / 2]; + if (!root) + throw new Error('Invalid root'); + const x1 = Fp2.div(candidateSqrt, root); + const x2 = Fp2.neg(x1); + const { re: re1, im: im1 } = Fp2.reim(x1); + const { re: re2, im: im2 } = Fp2.reim(x2); + if (im1 > im2 || (im1 === im2 && re1 > re2)) + return x1; + return x2; + }, + // Same as sgn0_fp2 in draft-irtf-cfrg-hash-to-curve-16 + isOdd: (x) => { + const { re: x0, im: x1 } = Fp2.reim(x); + const sign_0 = x0 % _2n; + const zero_0 = x0 === _0n; + const sign_1 = x1 % _2n; + return BigInt(sign_0 || (zero_0 && sign_1)) == _1n; + }, + // Bytes util + fromBytes(b) { + if (b.length !== Fp2.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { c0: Fp.fromBytes(b.subarray(0, Fp.BYTES)), c1: Fp.fromBytes(b.subarray(Fp.BYTES)) }; + }, + toBytes: ({ c0, c1 }) => concatB(Fp.toBytes(c0), Fp.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp.cmov(c0, r0, c), + c1: Fp.cmov(c1, r1, c), + }), + // Specific utils + // toString() { + // return `Fp2(${this.c0} + ${this.c1}×i)`; + // } + reim: ({ c0, c1 }) => ({ re: c0, im: c1 }), + // multiply by u + 1 + mulByNonresidue: ({ c0, c1 }) => ({ c0: Fp.sub(c0, c1), c1: Fp.add(c0, c1) }), + multiplyByB: ({ c0, c1 }) => { + let t0 = Fp.mul(c0, _4n); // 4 * c0 + let t1 = Fp.mul(c1, _4n); // 4 * c1 + // (T0-T1) + (T0+T1)*i + return { c0: Fp.sub(t0, t1), c1: Fp.add(t0, t1) }; + }, + fromBigTuple: (tuple) => { + if (tuple.length !== 2) + throw new Error('Invalid tuple'); + const fps = tuple.map((n) => Fp.create(n)); + return { c0: fps[0], c1: fps[1] }; + }, + frobeniusMap: ({ c0, c1 }, power) => ({ + c0, + c1: Fp.mul(c1, FP2_FROBENIUS_COEFFICIENTS[power % 2]), + }), +}; +// Finite extension field over irreducible polynominal. +// Fp(u) / (u² - β) where β = -1 +const FP2_FROBENIUS_COEFFICIENTS = [ + BigInt('0x1'), + BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'), +].map((item) => Fp.create(item)); +// For Fp2 roots of unity. +const rv1 = BigInt('0x6af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09'); +// const ev1 = +// BigInt('0x699be3b8c6870965e5bf892ad5d2cc7b0e85a117402dfd83b7f4a947e02d978498255a2aaec0ac627b5afbdf1bf1c90'); +// const ev2 = +// BigInt('0x8157cd83046453f5dd0972b6e3949e4288020b5b8a9cc99ca07e27089a2ce2436d965026adad3ef7baba37f2183e9b5'); +// const ev3 = +// BigInt('0xab1c2ffdd6c253ca155231eb3e71ba044fd562f6f72bc5bad5ec46a0b7a3b0247cf08ce6c6317f40edbc653a72dee17'); +// const ev4 = +// BigInt('0xaa404866706722864480885d68ad0ccac1967c7544b447873cc37e0181271e006df72162a3d3e0287bf597fbf7f8fc1'); +// Eighth roots of unity, used for computing square roots in Fp2. +// To verify or re-calculate: +// Array(8).fill(new Fp2([1n, 1n])).map((fp2, k) => fp2.pow(Fp2.ORDER * BigInt(k) / 8n)) +const FP2_ROOTS_OF_UNITY = [ + [_1n, _0n], + [rv1, -rv1], + [_0n, _1n], + [rv1, rv1], + [-_1n, _0n], + [-rv1, rv1], + [_0n, -_1n], + [-rv1, -rv1], +].map((pair) => Fp2.fromBigTuple(pair)); +const Fp6Add = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({ + c0: Fp2.add(c0, r0), + c1: Fp2.add(c1, r1), + c2: Fp2.add(c2, r2), +}); +const Fp6Subtract = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({ + c0: Fp2.sub(c0, r0), + c1: Fp2.sub(c1, r1), + c2: Fp2.sub(c2, r2), +}); +const Fp6Multiply = ({ c0, c1, c2 }, rhs) => { + if (typeof rhs === 'bigint') { + return { + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }; + } + const { c0: r0, c1: r1, c2: r2 } = rhs; + const t0 = Fp2.mul(c0, r0); // c0 * o0 + const t1 = Fp2.mul(c1, r1); // c1 * o1 + const t2 = Fp2.mul(c2, r2); // c2 * o2 + return { + // t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1) + c0: Fp2.add(t0, Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), Fp2.add(r1, r2)), Fp2.add(t1, t2)))), + // (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1) + c1: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c1), Fp2.add(r0, r1)), Fp2.add(t0, t1)), Fp2.mulByNonresidue(t2)), + // T1 + (c0 + c2) * (r0 + r2) - T0 + T2 + c2: Fp2.sub(Fp2.add(t1, Fp2.mul(Fp2.add(c0, c2), Fp2.add(r0, r2))), Fp2.add(t0, t2)), + }; +}; +const Fp6Square = ({ c0, c1, c2 }) => { + let t0 = Fp2.sqr(c0); // c0² + let t1 = Fp2.mul(Fp2.mul(c0, c1), _2n); // 2 * c0 * c1 + let t3 = Fp2.mul(Fp2.mul(c1, c2), _2n); // 2 * c1 * c2 + let t4 = Fp2.sqr(c2); // c2² + return { + c0: Fp2.add(Fp2.mulByNonresidue(t3), t0), + c1: Fp2.add(Fp2.mulByNonresidue(t4), t1), + // T1 + (c0 - c1 + c2)² + T3 - T0 - T4 + c2: Fp2.sub(Fp2.sub(Fp2.add(Fp2.add(t1, Fp2.sqr(Fp2.add(Fp2.sub(c0, c1), c2))), t3), t0), t4), + }; +}; +const Fp6 = { + ORDER: Fp2.ORDER, + BITS: 3 * Fp2.BITS, + BYTES: 3 * Fp2.BYTES, + MASK: bitMask(3 * Fp2.BITS), + ZERO: { c0: Fp2.ZERO, c1: Fp2.ZERO, c2: Fp2.ZERO }, + ONE: { c0: Fp2.ONE, c1: Fp2.ZERO, c2: Fp2.ZERO }, + create: (num) => num, + isValid: ({ c0, c1, c2 }) => Fp2.isValid(c0) && Fp2.isValid(c1) && Fp2.isValid(c2), + is0: ({ c0, c1, c2 }) => Fp2.is0(c0) && Fp2.is0(c1) && Fp2.is0(c2), + neg: ({ c0, c1, c2 }) => ({ c0: Fp2.neg(c0), c1: Fp2.neg(c1), c2: Fp2.neg(c2) }), + eql: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => Fp2.eql(c0, r0) && Fp2.eql(c1, r1) && Fp2.eql(c2, r2), + sqrt: () => { + throw new Error('Not implemented'); + }, + // Do we need division by bigint at all? Should be done via order: + div: (lhs, rhs) => Fp6.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp6.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp6, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp6, nums), + // Normalized + add: Fp6Add, + sub: Fp6Subtract, + mul: Fp6Multiply, + sqr: Fp6Square, + // NonNormalized stuff + addN: Fp6Add, + subN: Fp6Subtract, + mulN: Fp6Multiply, + sqrN: Fp6Square, + inv: ({ c0, c1, c2 }) => { + let t0 = Fp2.sub(Fp2.sqr(c0), Fp2.mulByNonresidue(Fp2.mul(c2, c1))); // c0² - c2 * c1 * (u + 1) + let t1 = Fp2.sub(Fp2.mulByNonresidue(Fp2.sqr(c2)), Fp2.mul(c0, c1)); // c2² * (u + 1) - c0 * c1 + let t2 = Fp2.sub(Fp2.sqr(c1), Fp2.mul(c0, c2)); // c1² - c0 * c2 + // 1/(((c2 * T1 + c1 * T2) * v) + c0 * T0) + let t4 = Fp2.inv(Fp2.add(Fp2.mulByNonresidue(Fp2.add(Fp2.mul(c2, t1), Fp2.mul(c1, t2))), Fp2.mul(c0, t0))); + return { c0: Fp2.mul(t4, t0), c1: Fp2.mul(t4, t1), c2: Fp2.mul(t4, t2) }; + }, + // Bytes utils + fromBytes: (b) => { + if (b.length !== Fp6.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp2.fromBytes(b.subarray(0, Fp2.BYTES)), + c1: Fp2.fromBytes(b.subarray(Fp2.BYTES, 2 * Fp2.BYTES)), + c2: Fp2.fromBytes(b.subarray(2 * Fp2.BYTES)), + }; + }, + toBytes: ({ c0, c1, c2 }) => concatB(Fp2.toBytes(c0), Fp2.toBytes(c1), Fp2.toBytes(c2)), + cmov: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }, c) => ({ + c0: Fp2.cmov(c0, r0, c), + c1: Fp2.cmov(c1, r1, c), + c2: Fp2.cmov(c2, r2, c), + }), + // Utils + // fromTriple(triple: [Fp2, Fp2, Fp2]) { + // return new Fp6(...triple); + // } + // toString() { + // return `Fp6(${this.c0} + ${this.c1} * v, ${this.c2} * v^2)`; + // } + fromBigSix: (t) => { + if (!Array.isArray(t) || t.length !== 6) + throw new Error('Invalid Fp6 usage'); + return { + c0: Fp2.fromBigTuple(t.slice(0, 2)), + c1: Fp2.fromBigTuple(t.slice(2, 4)), + c2: Fp2.fromBigTuple(t.slice(4, 6)), + }; + }, + frobeniusMap: ({ c0, c1, c2 }, power) => ({ + c0: Fp2.frobeniusMap(c0, power), + c1: Fp2.mul(Fp2.frobeniusMap(c1, power), FP6_FROBENIUS_COEFFICIENTS_1[power % 6]), + c2: Fp2.mul(Fp2.frobeniusMap(c2, power), FP6_FROBENIUS_COEFFICIENTS_2[power % 6]), + }), + mulByNonresidue: ({ c0, c1, c2 }) => ({ c0: Fp2.mulByNonresidue(c2), c1: c0, c2: c1 }), + // Sparse multiplication + multiplyBy1: ({ c0, c1, c2 }, b1) => ({ + c0: Fp2.mulByNonresidue(Fp2.mul(c2, b1)), + c1: Fp2.mul(c0, b1), + c2: Fp2.mul(c1, b1), + }), + // Sparse multiplication + multiplyBy01({ c0, c1, c2 }, b0, b1) { + let t0 = Fp2.mul(c0, b0); // c0 * b0 + let t1 = Fp2.mul(c1, b1); // c1 * b1 + return { + // ((c1 + c2) * b1 - T1) * (u + 1) + T0 + c0: Fp2.add(Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), b1), t1)), t0), + // (b0 + b1) * (c0 + c1) - T0 - T1 + c1: Fp2.sub(Fp2.sub(Fp2.mul(Fp2.add(b0, b1), Fp2.add(c0, c1)), t0), t1), + // (c0 + c2) * b0 - T0 + T1 + c2: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c2), b0), t0), t1), + }; + }, + multiplyByFp2: ({ c0, c1, c2 }, rhs) => ({ + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }), +}; +const FP6_FROBENIUS_COEFFICIENTS_1 = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt('0x0'), + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + BigInt('0x0'), + ], + [BigInt('0x0'), BigInt('0x1')], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + BigInt('0x0'), + ], + [ + BigInt('0x0'), + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + ], +].map((pair) => Fp2.fromBigTuple(pair)); +const FP6_FROBENIUS_COEFFICIENTS_2 = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad'), + BigInt('0x0'), + ], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + BigInt('0x0'), + ], + [ + BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'), + BigInt('0x0'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + BigInt('0x0'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff'), + BigInt('0x0'), + ], +].map((pair) => Fp2.fromBigTuple(pair)); +// The BLS parameter x for BLS12-381 +const BLS_X = BigInt('0xd201000000010000'); +const BLS_X_LEN = bitLen(BLS_X); +const Fp12Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp6.add(c0, r0), + c1: Fp6.add(c1, r1), +}); +const Fp12Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp6.sub(c0, r0), + c1: Fp6.sub(c1, r1), +}); +const Fp12Multiply = ({ c0, c1 }, rhs) => { + if (typeof rhs === 'bigint') + return { c0: Fp6.mul(c0, rhs), c1: Fp6.mul(c1, rhs) }; + let { c0: r0, c1: r1 } = rhs; + let t1 = Fp6.mul(c0, r0); // c0 * r0 + let t2 = Fp6.mul(c1, r1); // c1 * r1 + return { + c0: Fp6.add(t1, Fp6.mulByNonresidue(t2)), + // (c0 + c1) * (r0 + r1) - (T1 + T2) + c1: Fp6.sub(Fp6.mul(Fp6.add(c0, c1), Fp6.add(r0, r1)), Fp6.add(t1, t2)), + }; +}; +const Fp12Square = ({ c0, c1 }) => { + let ab = Fp6.mul(c0, c1); // c0 * c1 + return { + // (c1 * v + c0) * (c0 + c1) - AB - AB * v + c0: Fp6.sub(Fp6.sub(Fp6.mul(Fp6.add(Fp6.mulByNonresidue(c1), c0), Fp6.add(c0, c1)), ab), Fp6.mulByNonresidue(ab)), + c1: Fp6.add(ab, ab), + }; // AB + AB +}; +function Fp4Square(a, b) { + const a2 = Fp2.sqr(a); + const b2 = Fp2.sqr(b); + return { + first: Fp2.add(Fp2.mulByNonresidue(b2), a2), + second: Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(a, b)), a2), b2), // (a + b)² - a² - b² + }; +} +const Fp12 = { + ORDER: Fp2.ORDER, + BITS: 2 * Fp2.BITS, + BYTES: 2 * Fp2.BYTES, + MASK: bitMask(2 * Fp2.BITS), + ZERO: { c0: Fp6.ZERO, c1: Fp6.ZERO }, + ONE: { c0: Fp6.ONE, c1: Fp6.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => Fp6.isValid(c0) && Fp6.isValid(c1), + is0: ({ c0, c1 }) => Fp6.is0(c0) && Fp6.is0(c1), + neg: ({ c0, c1 }) => ({ c0: Fp6.neg(c0), c1: Fp6.neg(c1) }), + eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp6.eql(c0, r0) && Fp6.eql(c1, r1), + sqrt: () => { + throw new Error('Not implemented'); + }, + inv: ({ c0, c1 }) => { + let t = Fp6.inv(Fp6.sub(Fp6.sqr(c0), Fp6.mulByNonresidue(Fp6.sqr(c1)))); // 1 / (c0² - c1² * v) + return { c0: Fp6.mul(c0, t), c1: Fp6.neg(Fp6.mul(c1, t)) }; // ((C0 * T) * T) + (-C1 * T) * w + }, + div: (lhs, rhs) => Fp12.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp12.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp12, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp12, nums), + // Normalized + add: Fp12Add, + sub: Fp12Subtract, + mul: Fp12Multiply, + sqr: Fp12Square, + // NonNormalized stuff + addN: Fp12Add, + subN: Fp12Subtract, + mulN: Fp12Multiply, + sqrN: Fp12Square, + // Bytes utils + fromBytes: (b) => { + if (b.length !== Fp12.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp6.fromBytes(b.subarray(0, Fp6.BYTES)), + c1: Fp6.fromBytes(b.subarray(Fp6.BYTES)), + }; + }, + toBytes: ({ c0, c1 }) => concatB(Fp6.toBytes(c0), Fp6.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp6.cmov(c0, r0, c), + c1: Fp6.cmov(c1, r1, c), + }), + // Utils + // toString() { + // return `Fp12(${this.c0} + ${this.c1} * w)`; + // }, + // fromTuple(c: [Fp6, Fp6]) { + // return new Fp12(...c); + // } + fromBigTwelve: (t) => ({ + c0: Fp6.fromBigSix(t.slice(0, 6)), + c1: Fp6.fromBigSix(t.slice(6, 12)), + }), + // Raises to q**i -th power + frobeniusMap(lhs, power) { + const r0 = Fp6.frobeniusMap(lhs.c0, power); + const { c0, c1, c2 } = Fp6.frobeniusMap(lhs.c1, power); + const coeff = FP12_FROBENIUS_COEFFICIENTS[power % 12]; + return { + c0: r0, + c1: Fp6.create({ + c0: Fp2.mul(c0, coeff), + c1: Fp2.mul(c1, coeff), + c2: Fp2.mul(c2, coeff), + }), + }; + }, + // Sparse multiplication + multiplyBy014: ({ c0, c1 }, o0, o1, o4) => { + let t0 = Fp6.multiplyBy01(c0, o0, o1); + let t1 = Fp6.multiplyBy1(c1, o4); + return { + c0: Fp6.add(Fp6.mulByNonresidue(t1), t0), + // (c1 + c0) * [o0, o1+o4] - T0 - T1 + c1: Fp6.sub(Fp6.sub(Fp6.multiplyBy01(Fp6.add(c1, c0), o0, Fp2.add(o1, o4)), t0), t1), + }; + }, + multiplyByFp2: ({ c0, c1 }, rhs) => ({ + c0: Fp6.multiplyByFp2(c0, rhs), + c1: Fp6.multiplyByFp2(c1, rhs), + }), + conjugate: ({ c0, c1 }) => ({ c0, c1: Fp6.neg(c1) }), + // A cyclotomic group is a subgroup of Fp^n defined by + // GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1} + // The result of any pairing is in a cyclotomic subgroup + // https://eprint.iacr.org/2009/565.pdf + _cyclotomicSquare: ({ c0, c1 }) => { + const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0; + const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1; + const { first: t3, second: t4 } = Fp4Square(c0c0, c1c1); + const { first: t5, second: t6 } = Fp4Square(c1c0, c0c2); + const { first: t7, second: t8 } = Fp4Square(c0c1, c1c2); + let t9 = Fp2.mulByNonresidue(t8); // T8 * (u + 1) + return { + c0: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.sub(t3, c0c0), _2n), t3), + c1: Fp2.add(Fp2.mul(Fp2.sub(t5, c0c1), _2n), t5), + c2: Fp2.add(Fp2.mul(Fp2.sub(t7, c0c2), _2n), t7), + }), + c1: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.add(t9, c1c0), _2n), t9), + c1: Fp2.add(Fp2.mul(Fp2.add(t4, c1c1), _2n), t4), + c2: Fp2.add(Fp2.mul(Fp2.add(t6, c1c2), _2n), t6), + }), + }; // 2 * (T6 + c1c2) + T6 + }, + _cyclotomicExp(num, n) { + let z = Fp12.ONE; + for (let i = BLS_X_LEN - 1; i >= 0; i--) { + z = Fp12._cyclotomicSquare(z); + if (bitGet(n, i)) + z = Fp12.mul(z, num); + } + return z; + }, + // https://eprint.iacr.org/2010/354.pdf + // https://eprint.iacr.org/2009/565.pdf + finalExponentiate: (num) => { + const x = BLS_X; + // this^(q⁶) / this + const t0 = Fp12.div(Fp12.frobeniusMap(num, 6), num); + // t0^(q²) * t0 + const t1 = Fp12.mul(Fp12.frobeniusMap(t0, 2), t0); + const t2 = Fp12.conjugate(Fp12._cyclotomicExp(t1, x)); + const t3 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicSquare(t1)), t2); + const t4 = Fp12.conjugate(Fp12._cyclotomicExp(t3, x)); + const t5 = Fp12.conjugate(Fp12._cyclotomicExp(t4, x)); + const t6 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicExp(t5, x)), Fp12._cyclotomicSquare(t2)); + const t7 = Fp12.conjugate(Fp12._cyclotomicExp(t6, x)); + const t2_t5_pow_q2 = Fp12.frobeniusMap(Fp12.mul(t2, t5), 2); + const t4_t1_pow_q3 = Fp12.frobeniusMap(Fp12.mul(t4, t1), 3); + const t6_t1c_pow_q1 = Fp12.frobeniusMap(Fp12.mul(t6, Fp12.conjugate(t1)), 1); + const t7_t3c_t1 = Fp12.mul(Fp12.mul(t7, Fp12.conjugate(t3)), t1); + // (t2 * t5)^(q²) * (t4 * t1)^(q³) * (t6 * t1.conj)^(q^1) * t7 * t3.conj * t1 + return Fp12.mul(Fp12.mul(Fp12.mul(t2_t5_pow_q2, t4_t1_pow_q3), t6_t1c_pow_q1), t7_t3c_t1); + }, +}; +const FP12_FROBENIUS_COEFFICIENTS = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt('0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8'), + BigInt('0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff'), + BigInt('0x0'), + ], + [ + BigInt('0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2'), + BigInt('0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + BigInt('0x0'), + ], + [ + BigInt('0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995'), + BigInt('0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116'), + ], + [ + BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'), + BigInt('0x0'), + ], + [ + BigInt('0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3'), + BigInt('0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8'), + ], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + BigInt('0x0'), + ], + [ + BigInt('0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09'), + BigInt('0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2'), + ], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad'), + BigInt('0x0'), + ], + [ + BigInt('0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116'), + BigInt('0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995'), + ], +].map((n) => Fp2.fromBigTuple(n)); +// END OF CURVE FIELDS +// HashToCurve +// 3-isogeny map from E' to E +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#appendix-E.3 +const isogenyMapG2 = isogenyMap(Fp2, [ + // xNum + [ + [ + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + ], + [ + '0x0', + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d', + ], + [ + '0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1', + '0x0', + ], + ], + // xDen + [ + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63', + ], + [ + '0xc', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f', + ], + ['0x1', '0x0'], // LAST 1 + ], + // yNum + [ + [ + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + ], + [ + '0x0', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f', + ], + [ + '0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10', + '0x0', + ], + ], + // yDen + [ + [ + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + ], + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3', + ], + [ + '0x12', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99', + ], + ['0x1', '0x0'], // LAST 1 + ], +].map((i) => i.map((pair) => Fp2.fromBigTuple(pair.map(BigInt))))); +// 11-isogeny map from E' to E +const isogenyMapG1 = isogenyMap(Fp, [ + // xNum + [ + '0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7', + '0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb', + '0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0', + '0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861', + '0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9', + '0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983', + '0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84', + '0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e', + '0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317', + '0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e', + '0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b', + '0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229', + ], + // xDen + [ + '0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c', + '0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff', + '0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19', + '0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8', + '0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e', + '0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5', + '0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a', + '0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e', + '0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641', + '0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33', + '0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696', + '0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6', + '0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb', + '0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb', + '0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0', + '0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2', + '0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29', + '0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587', + '0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30', + '0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132', + '0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e', + '0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8', + '0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133', + '0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b', + '0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604', + ], + // yDen + [ + '0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1', + '0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d', + '0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2', + '0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416', + '0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d', + '0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac', + '0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c', + '0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9', + '0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a', + '0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55', + '0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8', + '0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092', + '0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc', + '0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7', + '0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], +].map((i) => i.map((j) => BigInt(j)))); +// SWU Map - Fp2 to G2': y² = x³ + 240i * x + 1012 + 1012i +const G2_SWU = mapToCurveSimpleSWU(Fp2, { + A: Fp2.create({ c0: Fp.create(_0n), c1: Fp.create(BigInt(240)) }), + B: Fp2.create({ c0: Fp.create(BigInt(1012)), c1: Fp.create(BigInt(1012)) }), + Z: Fp2.create({ c0: Fp.create(BigInt(-2)), c1: Fp.create(BigInt(-1)) }), // Z: -(2 + I) +}); +// Optimized SWU Map - Fp to G1 +const G1_SWU = mapToCurveSimpleSWU(Fp, { + A: Fp.create(BigInt('0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d')), + B: Fp.create(BigInt('0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0')), + Z: Fp.create(BigInt(11)), +}); +// Endomorphisms (for fast cofactor clearing) +// Ψ(P) endomorphism +const ut_root = Fp6.create({ c0: Fp2.ZERO, c1: Fp2.ONE, c2: Fp2.ZERO }); +const wsq = Fp12.create({ c0: ut_root, c1: Fp6.ZERO }); +const wcu = Fp12.create({ c0: Fp6.ZERO, c1: ut_root }); +const [wsq_inv, wcu_inv] = Fp12.invertBatch([wsq, wcu]); +function psi(x, y) { + // Untwist Fp2->Fp12 && frobenius(1) && twist back + const x2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wsq_inv, x), 1), wsq).c0.c0; + const y2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wcu_inv, y), 1), wcu).c0.c0; + return [x2, y2]; +} +// Ψ endomorphism +function G2psi(c, P) { + const affine = P.toAffine(); + const p = psi(affine.x, affine.y); + return new c(p[0], p[1], Fp2.ONE); +} +// Ψ²(P) endomorphism +// 1 / F2(2)^((p-1)/3) in GF(p²) +const PSI2_C1 = BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'); +function psi2(x, y) { + return [Fp2.mul(x, PSI2_C1), Fp2.neg(y)]; +} +function G2psi2(c, P) { + const affine = P.toAffine(); + const p = psi2(affine.x, affine.y); + return new c(p[0], p[1], Fp2.ONE); +} +// Default hash_to_field options are for hash to G2. +// +// Parameter definitions are in section 5.3 of the spec unless otherwise noted. +// Parameter values come from section 8.8.2 of the spec. +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-8.8.2 +// +// Base field F is GF(p^m) +// p = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab +// m = 2 (or 1 for G1 see section 8.8.1) +// k = 128 +const htfDefaults = Object.freeze({ + // DST: a domain separation tag + // defined in section 2.2.5 + // Use utils.getDSTLabel(), utils.setDSTLabel(value) + DST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + encodeDST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + // p: the characteristic of F + // where F is a finite field of characteristic p and order q = p^m + p: Fp.ORDER, + // m: the extension degree of F, m >= 1 + // where F is a finite field of characteristic p and order q = p^m + m: 2, + // k: the target security level for the suite in bits + // defined in section 5.1 + k: 128, + // option to use a message that has already been processed by + // expand_message_xmd + expand: 'xmd', + // Hash functions for: expand_message_xmd is appropriate for use with a + // wide range of hash functions, including SHA-2, SHA-3, BLAKE2, and others. + // BBS+ uses blake2: https://github.com/hyperledger/aries-framework-go/issues/2247 + hash: sha256, +}); +// Encoding utils +// Point on G1 curve: (x, y) +const C_BIT_POS = Fp.BITS; // C_bit, compression bit for serialization flag +const I_BIT_POS = Fp.BITS + 1; // I_bit, point-at-infinity bit for serialization flag +const S_BIT_POS = Fp.BITS + 2; // S_bit, sign bit for serialization flag +// Compressed point of infinity +const COMPRESSED_ZERO = Fp.toBytes(bitSet(bitSet(_0n, I_BIT_POS, true), S_BIT_POS, true)); // set compressed & point-at-infinity bits +function signatureG2ToRawBytes(point) { + // NOTE: by some reasons it was missed in bls12-381, looks like bug + point.assertValidity(); + const len = Fp.BYTES; + if (point.equals(bls12_381.G2.ProjectivePoint.ZERO)) + return concatB(COMPRESSED_ZERO, numberToBytesBE(_0n, len)); + const { x, y } = point.toAffine(); + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + const tmp = y1 > _0n ? y1 * _2n : y0 * _2n; + const aflag1 = Boolean((tmp / Fp.ORDER) & _1n); + const z1 = bitSet(bitSet(x1, 381, aflag1), S_BIT_POS, true); + const z2 = x0; + return concatB(numberToBytesBE(z1, len), numberToBytesBE(z2, len)); +} +// To verify curve parameters, see pairing-friendly-curves spec: +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-09 +// Basic math is done over finite fields over p. +// More complicated math is done over polynominal extension fields. +// To simplify calculations in Fp12, we construct extension tower: +// Fp₁₂ = Fp₆² => Fp₂³ +// Fp(u) / (u² - β) where β = -1 +// Fp₂(v) / (v³ - ξ) where ξ = u + 1 +// Fp₆(w) / (w² - γ) where γ = v +// Here goes constants && point encoding format +export const bls12_381 = bls({ + // Fields + fields: { + Fp, + Fp2, + Fp6, + Fp12, + Fr, + }, + // G1 is the order-q subgroup of E1(Fp) : y² = x³ + 4, #E1(Fp) = h1q, where + // characteristic; z + (z⁴ - z² + 1)(z - 1)²/3 + G1: { + Fp, + // cofactor; (z - 1)²/3 + h: BigInt('0x396c8c005555e1568c00aaab0000aaab'), + // generator's coordinates + // x = 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507 + // y = 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569 + Gx: BigInt('0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb'), + Gy: BigInt('0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1'), + a: Fp.ZERO, + b: _4n, + htfDefaults: { ...htfDefaults, m: 1 }, + wrapPrivateKey: true, + allowInfinityPoint: true, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, point) => { + // φ endomorphism + const cubicRootOfUnityModP = BigInt('0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'); + const phi = new c(Fp.mul(point.px, cubicRootOfUnityModP), point.py, point.pz); + // todo: unroll + const xP = point.multiplyUnsafe(bls12_381.params.x).negate(); // [x]P + const u2P = xP.multiplyUnsafe(bls12_381.params.x); // [u2]P + return u2P.equals(phi); + // https://eprint.iacr.org/2019/814.pdf + // (z² − 1)/3 + // const c1 = BigInt('0x396c8c005555e1560000000055555555'); + // const P = this; + // const S = P.sigma(); + // const Q = S.double(); + // const S2 = S.sigma(); + // // [(z² − 1)/3](2σ(P) − P − σ²(P)) − σ²(P) = O + // const left = Q.subtract(P).subtract(S2).multiplyUnsafe(c1); + // const C = left.subtract(S2); + // return C.isZero(); + }, + // Clear cofactor of G1 + // https://eprint.iacr.org/2019/403 + clearCofactor: (c, point) => { + // return this.multiplyUnsafe(CURVE.h); + return point.multiplyUnsafe(bls12_381.params.x).add(point); // x*P + P + }, + mapToCurve: (scalars) => { + const { x, y } = G1_SWU(Fp.create(scalars[0])); + return isogenyMapG1(x, y); + }, + fromBytes: (bytes) => { + bytes = bytes.slice(); + if (bytes.length === 48) { + // TODO: Fp.bytes + const P = Fp.ORDER; + const compressedValue = bytesToNumberBE(bytes); + const bflag = bitGet(compressedValue, I_BIT_POS); + // Zero + if (bflag === _1n) + return { x: _0n, y: _0n }; + const x = Fp.create(compressedValue & Fp.MASK); + const right = Fp.add(Fp.pow(x, _3n), Fp.create(bls12_381.params.G1b)); // y² = x³ + b + let y = Fp.sqrt(right); + if (!y) + throw new Error('Invalid compressed G1 point'); + const aflag = bitGet(compressedValue, C_BIT_POS); + if ((y * _2n) / P !== aflag) + y = Fp.neg(y); + return { x: Fp.create(x), y: Fp.create(y) }; + } + else if (bytes.length === 96) { + // Check if the infinity flag is set + if ((bytes[0] & (1 << 6)) !== 0) + return bls12_381.G1.ProjectivePoint.ZERO.toAffine(); + const x = bytesToNumberBE(bytes.subarray(0, Fp.BYTES)); + const y = bytesToNumberBE(bytes.subarray(Fp.BYTES)); + return { x: Fp.create(x), y: Fp.create(y) }; + } + else { + throw new Error('Invalid point G1, expected 48/96 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) + return COMPRESSED_ZERO.slice(); + const P = Fp.ORDER; + let num; + num = bitSet(x, C_BIT_POS, Boolean((y * _2n) / P)); // set aflag + num = bitSet(num, S_BIT_POS, true); + return numberToBytesBE(num, Fp.BYTES); + } + else { + if (isZero) { + // 2x PUBLIC_KEY_LENGTH + const x = concatB(new Uint8Array([0x40]), new Uint8Array(2 * Fp.BYTES - 1)); + return x; + } + else { + return concatB(numberToBytesBE(x, Fp.BYTES), numberToBytesBE(y, Fp.BYTES)); + } + } + }, + }, + // G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1), + // where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where + // G² - 1 + // h2q + G2: { + Fp: Fp2, + // cofactor + h: BigInt('0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5'), + Gx: Fp2.fromBigTuple([ + BigInt('0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8'), + BigInt('0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e'), + ]), + // y = + // 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582, + // 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905 + Gy: Fp2.fromBigTuple([ + BigInt('0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801'), + BigInt('0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be'), + ]), + a: Fp2.ZERO, + b: Fp2.fromBigTuple([_4n, _4n]), + hEff: BigInt('0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551'), + htfDefaults: { ...htfDefaults }, + wrapPrivateKey: true, + allowInfinityPoint: true, + mapToCurve: (scalars) => { + const { x, y } = G2_SWU(Fp2.fromBigTuple(scalars)); + return isogenyMapG2(x, y); + }, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, P) => { + return P.multiplyUnsafe(bls12_381.params.x).negate().equals(G2psi(c, P)); // ψ(P) == [u](P) + // Older version: https://eprint.iacr.org/2019/814.pdf + // Ψ²(P) => Ψ³(P) => [z]Ψ³(P) where z = -x => [z]Ψ³(P) - Ψ²(P) + P == O + // return P.psi2().psi().mulNegX().subtract(psi2).add(P).isZero(); + }, + // Maps the point into the prime-order subgroup G2. + // clear_cofactor_bls12381_g2 from cfrg-hash-to-curve-11 + // https://eprint.iacr.org/2017/419.pdf + // prettier-ignore + clearCofactor: (c, P) => { + const x = bls12_381.params.x; + let t1 = P.multiplyUnsafe(x).negate(); // [-x]P + let t2 = G2psi(c, P); // Ψ(P) + let t3 = P.double(); // 2P + t3 = G2psi2(c, t3); // Ψ²(2P) + t3 = t3.subtract(t2); // Ψ²(2P) - Ψ(P) + t2 = t1.add(t2); // [-x]P + Ψ(P) + t2 = t2.multiplyUnsafe(x).negate(); // [x²]P - [x]Ψ(P) + t3 = t3.add(t2); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + t3 = t3.subtract(t1); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P + const Q = t3.subtract(P); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P - 1P + return Q; // [x²-x-1]P + [x-1]Ψ(P) + Ψ²(2P) + }, + fromBytes: (bytes) => { + bytes = bytes.slice(); + const m_byte = bytes[0] & 0xe0; + if (m_byte === 0x20 || m_byte === 0x60 || m_byte === 0xe0) { + throw new Error('Invalid encoding flag: ' + m_byte); + } + const bitC = m_byte & 0x80; // compression bit + const bitI = m_byte & 0x40; // point at infinity bit + const bitS = m_byte & 0x20; // sign bit + const L = Fp.BYTES; + const slc = (b, from, to) => bytesToNumberBE(b.slice(from, to)); + if (bytes.length === 96 && bitC) { + const b = bls12_381.params.G2b; + const P = Fp.ORDER; + bytes[0] = bytes[0] & 0x1f; // clear flags + if (bitI) { + // check that all bytes are 0 + if (bytes.reduce((p, c) => (p !== 0 ? c + 1 : c), 0) > 0) { + throw new Error('Invalid compressed G2 point'); + } + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x_1 = slc(bytes, 0, L); + const x_0 = slc(bytes, L, 2 * L); + const x = Fp2.create({ c0: Fp.create(x_0), c1: Fp.create(x_1) }); + const right = Fp2.add(Fp2.pow(x, _3n), b); // y² = x³ + 4 * (u+1) = x³ + b + let y = Fp2.sqrt(right); + const Y_bit = y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P ? _1n : _0n; + y = bitS > 0 && Y_bit > 0 ? y : Fp2.neg(y); + return { x, y }; + } + else if (bytes.length === 192 && !bitC) { + // Check if the infinity flag is set + if ((bytes[0] & (1 << 6)) !== 0) { + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x1 = slc(bytes, 0, L); + const x0 = slc(bytes, L, 2 * L); + const y1 = slc(bytes, 2 * L, 3 * L); + const y0 = slc(bytes, 3 * L, 4 * L); + return { x: Fp2.fromBigTuple([x0, x1]), y: Fp2.fromBigTuple([y0, y1]) }; + } + else { + throw new Error('Invalid point G2, expected 96/192 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const { BYTES: len, ORDER: P } = Fp; + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) + return concatB(COMPRESSED_ZERO, numberToBytesBE(_0n, len)); + const flag = Boolean(y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P); + // set compressed & sign bits (looks like different offsets than for G1/Fp?) + let x_1 = bitSet(x.c1, C_BIT_POS, flag); + x_1 = bitSet(x_1, S_BIT_POS, true); + return concatB(numberToBytesBE(x_1, len), numberToBytesBE(x.c0, len)); + } + else { + if (isZero) + return concatB(new Uint8Array([0x40]), new Uint8Array(4 * len - 1)); // bytes[0] |= 1 << 6; + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + return concatB(numberToBytesBE(x1, len), numberToBytesBE(x0, len), numberToBytesBE(y1, len), numberToBytesBE(y0, len)); + } + }, + Signature: { + // TODO: Optimize, it's very slow because of sqrt. + fromHex(hex) { + hex = ensureBytes('signatureHex', hex); + const P = Fp.ORDER; + const half = hex.length / 2; + if (half !== 48 && half !== 96) + throw new Error('Invalid compressed signature length, must be 96 or 192'); + const z1 = bytesToNumberBE(hex.slice(0, half)); + const z2 = bytesToNumberBE(hex.slice(half)); + // Indicates the infinity point + const bflag1 = bitGet(z1, I_BIT_POS); + if (bflag1 === _1n) + return bls12_381.G2.ProjectivePoint.ZERO; + const x1 = Fp.create(z1 & Fp.MASK); + const x2 = Fp.create(z2); + const x = Fp2.create({ c0: x2, c1: x1 }); + const y2 = Fp2.add(Fp2.pow(x, _3n), bls12_381.params.G2b); // y² = x³ + 4 + // The slow part + let y = Fp2.sqrt(y2); + if (!y) + throw new Error('Failed to find a square root'); + // Choose the y whose leftmost bit of the imaginary part is equal to the a_flag1 + // If y1 happens to be zero, then use the bit of y0 + const { re: y0, im: y1 } = Fp2.reim(y); + const aflag1 = bitGet(z1, 381); + const isGreater = y1 > _0n && (y1 * _2n) / P !== aflag1; + const isZero = y1 === _0n && (y0 * _2n) / P !== aflag1; + if (isGreater || isZero) + y = Fp2.neg(y); + const point = bls12_381.G2.ProjectivePoint.fromAffine({ x, y }); + point.assertValidity(); + return point; + }, + toRawBytes(point) { + return signatureG2ToRawBytes(point); + }, + toHex(point) { + return bytesToHex(signatureG2ToRawBytes(point)); + }, + }, + }, + params: { + x: BLS_X, + r: Fr.ORDER, // order; z⁴ − z² + 1; CURVE.n from other curves + }, + htfDefaults, + hash: sha256, + randomBytes, +}); +//# sourceMappingURL=bls12-381.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/bls12-381.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/bls12-381.js.map new file mode 100644 index 0000000..09f0c12 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/bls12-381.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bls12-381.js","sourceRoot":"","sources":["../src/bls12-381.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,uFAAuF;AACvF,gDAAgD;AAChD,kGAAkG;AAClG,+EAA+E;AAC/E,EAAE;AACF,mGAAmG;AACnG,+EAA+E;AAC/E,+FAA+F;AAC/F,+EAA+E;AAC/E,oFAAoF;AACpF,EAAE;AACF,cAAc;AACd,gDAAgD;AAChD,4BAA4B;AAC5B,2FAA2F;AAC3F,mHAAmH;AACnH,0FAA0F;AAC1F,2HAA2H;AAC3H,6CAA6C;AAC7C,EAAE;AACF,eAAe;AACf,+BAA+B;AAC/B,8BAA8B;AAC9B,0DAA0D;AAC1D,4EAA4E;AAC5E,6DAA6D;AAC7D,6DAA6D;A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MAAM,KAAK,GAAG,SAAS,CAAC,EAAE,CAAC,eAAe,CAAC,UAAU,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;gBAChE,KAAK,CAAC,cAAc,EAAE,CAAC;gBACvB,OAAO,KAAK,CAAC;YACf,CAAC;YACD,UAAU,CAAC,KAAyB;gBAClC,OAAO,qBAAqB,CAAC,KAAK,CAAC,CAAC;YACtC,CAAC;YACD,KAAK,CAAC,KAAyB;gBAC7B,OAAO,UAAU,CAAC,qBAAqB,CAAC,KAAK,CAAC,CAAC,CAAC;YAClD,CAAC;SACF;KACF;IACD,MAAM,EAAE;QACN,CAAC,EAAE,KAAK;QACR,CAAC,EAAE,EAAE,CAAC,KAAK,EAAE,gDAAgD;KAC9D;IACD,WAAW;IACX,IAAI,EAAE,MAAM;IACZ,WAAW;CACZ,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/bn254.js b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/bn254.js new file mode 100644 index 0000000..6b4f7c6 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/bn254.js @@ -0,0 +1,22 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { weierstrass } from './abstract/weierstrass.js'; +import { getHash } from './_shortw_utils.js'; +import { Field } from './abstract/modular.js'; +/** + * bn254 pairing-friendly curve. + * Previously known as alt_bn_128, when it had 128-bit security. + * Recent research shown it's weaker, the naming has been adjusted to its prime bit count. + * https://github.com/zcash/zcash/issues/2502 + */ +export const bn254 = weierstrass({ + a: BigInt(0), + b: BigInt(3), + Fp: Field(BigInt('0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47')), + n: BigInt('0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001'), + Gx: BigInt(1), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); +//# sourceMappingURL=bn254.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/bn254.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/bn254.js.map new file mode 100644 index 0000000..e0ec023 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/bn254.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bn254.js","sourceRoot":"","sources":["../src/bn254.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAC7C,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC9C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,KAAK,GAAG,WAAW,CAAC;IAC/B,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE,EAAE,KAAK,CAAC,MAAM,CAAC,oEAAoE,CAAC,CAAC;IACvF,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,OAAO,CAAC,MAAM,CAAC;CACnB,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/ed25519.js b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/ed25519.js new file mode 100644 index 0000000..01ee630 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/ed25519.js @@ -0,0 +1,430 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha512 } from '@noble/hashes/sha512'; +import { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils'; +import { twistedEdwards } from './abstract/edwards.js'; +import { montgomery } from './abstract/montgomery.js'; +import { Field, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.js'; +import { bytesToHex, bytesToNumberLE, ensureBytes, equalBytes, numberToBytesLE, } from './abstract/utils.js'; +import { createHasher, expand_message_xmd } from './abstract/hash-to-curve.js'; +/** + * ed25519 Twisted Edwards curve with following addons: + * - X25519 ECDH + * - Ristretto cofactor elimination + * - Elligator hash-to-group / point indistinguishability + */ +const ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949'); +// √(-1) aka √(a) aka 2^((p-1)/4) +const ED25519_SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752'); +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _5n = BigInt(5); +// prettier-ignore +const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80); +function ed25519_pow_2_252_3(x) { + const P = ED25519_P; + const x2 = (x * x) % P; + const b2 = (x2 * x) % P; // x^3, 11 + const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111 + const b5 = (pow2(b4, _1n, P) * x) % P; // x^31 + const b10 = (pow2(b5, _5n, P) * b5) % P; + const b20 = (pow2(b10, _10n, P) * b10) % P; + const b40 = (pow2(b20, _20n, P) * b20) % P; + const b80 = (pow2(b40, _40n, P) * b40) % P; + const b160 = (pow2(b80, _80n, P) * b80) % P; + const b240 = (pow2(b160, _80n, P) * b80) % P; + const b250 = (pow2(b240, _10n, P) * b10) % P; + const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P; + // ^ To pow to (p+3)/8, multiply it by x. + return { pow_p_5_8, b2 }; +} +function adjustScalarBytes(bytes) { + // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar, + // set the three least significant bits of the first byte + bytes[0] &= 248; // 0b1111_1000 + // and the most significant bit of the last to zero, + bytes[31] &= 127; // 0b0111_1111 + // set the second most significant bit of the last byte to 1 + bytes[31] |= 64; // 0b0100_0000 + return bytes; +} +// sqrt(u/v) +function uvRatio(u, v) { + const P = ED25519_P; + const v3 = mod(v * v * v, P); // v³ + const v7 = mod(v3 * v3 * v, P); // v⁷ + // (p+3)/8 and (p-5)/8 + const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8; + let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8 + const vx2 = mod(v * x * x, P); // vx² + const root1 = x; // First root candidate + const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate + const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root + const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4) + const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1) + if (useRoot1) + x = root1; + if (useRoot2 || noRoot) + x = root2; // We return root2 anyway, for const-time + if (isNegativeLE(x, P)) + x = mod(-x, P); + return { isValid: useRoot1 || useRoot2, value: x }; +} +// Just in case +export const ED25519_TORSION_SUBGROUP = [ + '0100000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', + '0000000000000000000000000000000000000000000000000000000000000080', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05', + 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85', + '0000000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa', +]; +const Fp = Field(ED25519_P, undefined, true); +const ed25519Defaults = { + // Param: a + a: BigInt(-1), + // d is equal to -121665/121666 over finite field. + // Negative number is P - number, and division is invert(number, P) + d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'), + // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n + Fp, + // Subgroup order: how many points curve has + // 2n**252n + 27742317777372353535851937790883648493n; + n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'), + // Cofactor + h: BigInt(8), + // Base point (x, y) aka generator point + Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'), + Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'), + hash: sha512, + randomBytes, + adjustScalarBytes, + // dom2 + // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3. + // Constant-time, u/√v + uvRatio, +}; +export const ed25519 = twistedEdwards(ed25519Defaults); +function ed25519_domain(data, ctx, phflag) { + if (ctx.length > 255) + throw new Error('Context is too big'); + return concatBytes(utf8ToBytes('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); +} +export const ed25519ctx = twistedEdwards({ ...ed25519Defaults, domain: ed25519_domain }); +export const ed25519ph = twistedEdwards({ + ...ed25519Defaults, + domain: ed25519_domain, + prehash: sha512, +}); +export const x25519 = /* @__PURE__ */ (() => montgomery({ + P: ED25519_P, + a: BigInt(486662), + montgomeryBits: 255, + nByteLength: 32, + Gu: BigInt(9), + powPminus2: (x) => { + const P = ED25519_P; + // x^(p-2) aka x^(2^255-21) + const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x); + return mod(pow2(pow_p_5_8, BigInt(3), P) * b2, P); + }, + adjustScalarBytes, + randomBytes, +}))(); +/** + * Converts ed25519 public key to x25519 public key. Uses formula: + * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)` + * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))` + * @example + * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey()); + * const aPriv = x25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub)) + */ +export function edwardsToMontgomeryPub(edwardsPub) { + const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y))); +} +export const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated +/** + * Converts ed25519 secret key to x25519 secret key. + * @example + * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey()); + * const aPriv = ed25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub) + */ +export function edwardsToMontgomeryPriv(edwardsPriv) { + const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32)); + return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32); +} +// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator) +// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since +// SageMath returns different root first and everything falls apart +const ELL2_C1 = (Fp.ORDER + BigInt(3)) / BigInt(8); // 1. c1 = (q + 3) / 8 # Integer arithmetic +const ELL2_C2 = Fp.pow(_2n, ELL2_C1); // 2. c2 = 2^c1 +const ELL2_C3 = Fp.sqrt(Fp.neg(Fp.ONE)); // 3. c3 = sqrt(-1) +const ELL2_C4 = (Fp.ORDER - BigInt(5)) / BigInt(8); // 4. c4 = (q - 5) / 8 # Integer arithmetic +const ELL2_J = BigInt(486662); +// prettier-ignore +function map_to_curve_elligator2_curve25519(u) { + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1 + let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not + let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2) + let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2 + tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4 + tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3 + tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3 + tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7 + let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8) + y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8) + let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3 + tv2 = Fp.sqr(y11); // 19. tv2 = y11^2 + tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd + let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1 + let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt + let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd + let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u + y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2 + let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3 + let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1) + tv2 = Fp.sqr(y21); // 28. tv2 = y21^2 + tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2 + let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt + tv2 = Fp.sqr(y1); // 32. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd + let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2 + let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4) + return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1) +} +const ELL2_C1_EDWARDS = FpSqrtEven(Fp, Fp.neg(BigInt(486664))); // sgn0(c1) MUST equal 0 +function map_to_curve_elligator2_edwards25519(u) { + const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) = + // map_to_curve_elligator2_curve25519(u) + let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd + xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1 + let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM + let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd + let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d) + let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd + let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0 + xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e) + xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e) + yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e) + yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e) + const inv = Fp.invertBatch([xd, yd]); // batch division + return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd) +} +const htf = /* @__PURE__ */ (() => createHasher(ed25519.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), { + DST: 'edwards25519_XMD:SHA-512_ELL2_RO_', + encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha512, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +function assertRstPoint(other) { + if (!(other instanceof RistPoint)) + throw new Error('RistrettoPoint expected'); +} +// √(-1) aka √(a) aka 2^((p-1)/4) +const SQRT_M1 = ED25519_SQRT_M1; +// √(ad - 1) +const SQRT_AD_MINUS_ONE = BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235'); +// 1 / √(a-d) +const INVSQRT_A_MINUS_D = BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578'); +// 1-d² +const ONE_MINUS_D_SQ = BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838'); +// (d-1)² +const D_MINUS_ONE_SQ = BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952'); +// Calculates 1/√(number) +const invertSqrt = (number) => uvRatio(_1n, number); +const MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const bytes255ToNumberLE = (bytes) => ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B); +// Computes Elligator map for Ristretto +// https://ristretto.group/formulas/elligator.html +function calcElligatorRistrettoMap(r0) { + const { d } = ed25519.CURVE; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const r = mod(SQRT_M1 * r0 * r0); // 1 + const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2 + let c = BigInt(-1); // 3 + const D = mod((c - d * r) * mod(r + d)); // 4 + let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5 + let s_ = mod(s * r0); // 6 + if (!isNegativeLE(s_, P)) + s_ = mod(-s_); + if (!Ns_D_is_sq) + s = s_; // 7 + if (!Ns_D_is_sq) + c = r; // 8 + const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9 + const s2 = s * s; + const W0 = mod((s + s) * D); // 10 + const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11 + const W2 = mod(_1n - s2); // 12 + const W3 = mod(_1n + s2); // 13 + return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2)); +} +/** + * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Ristretto was created to solve this. + * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +class RistPoint { + // Private property to discourage combining ExtendedPoint + RistrettoPoint + // Always use Ristretto encoding/decoding instead. + constructor(ep) { + this.ep = ep; + } + static fromAffine(ap) { + return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap)); + } + /** + * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://ristretto.group/formulas/elligator.html + * @param hex 64-byte output of a hash function + */ + static hashToCurve(hex) { + hex = ensureBytes('ristrettoHash', hex, 64); + const r1 = bytes255ToNumberLE(hex.slice(0, 32)); + const R1 = calcElligatorRistrettoMap(r1); + const r2 = bytes255ToNumberLE(hex.slice(32, 64)); + const R2 = calcElligatorRistrettoMap(r2); + return new RistPoint(R1.add(R2)); + } + /** + * Converts ristretto-encoded string to ristretto point. + * https://ristretto.group/formulas/decoding.html + * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding + */ + static fromHex(hex) { + hex = ensureBytes('ristrettoHex', hex, 32); + const { a, d } = ed25519.CURVE; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint'; + const s = bytes255ToNumberLE(hex); + // 1. Check that s_bytes is the canonical encoding of a field element, or else abort. + // 3. Check that s is non-negative, or else abort + if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P)) + throw new Error(emsg); + const s2 = mod(s * s); + const u1 = mod(_1n + a * s2); // 4 (a is -1) + const u2 = mod(_1n - a * s2); // 5 + const u1_2 = mod(u1 * u1); + const u2_2 = mod(u2 * u2); + const v = mod(a * d * u1_2 - u2_2); // 6 + const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7 + const Dx = mod(I * u2); // 8 + const Dy = mod(I * Dx * v); // 9 + let x = mod((s + s) * Dx); // 10 + if (isNegativeLE(x, P)) + x = mod(-x); // 10 + const y = mod(u1 * Dy); // 11 + const t = mod(x * y); // 12 + if (!isValid || isNegativeLE(t, P) || y === _0n) + throw new Error(emsg); + return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t)); + } + /** + * Encodes ristretto point to Uint8Array. + * https://ristretto.group/formulas/encoding.html + */ + toRawBytes() { + let { ex: x, ey: y, ez: z, et: t } = this.ep; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const u1 = mod(mod(z + y) * mod(z - y)); // 1 + const u2 = mod(x * y); // 2 + // Square root always exists + const u2sq = mod(u2 * u2); + const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3 + const D1 = mod(invsqrt * u1); // 4 + const D2 = mod(invsqrt * u2); // 5 + const zInv = mod(D1 * D2 * t); // 6 + let D; // 7 + if (isNegativeLE(t * zInv, P)) { + let _x = mod(y * SQRT_M1); + let _y = mod(x * SQRT_M1); + x = _x; + y = _y; + D = mod(D1 * INVSQRT_A_MINUS_D); + } + else { + D = D2; // 8 + } + if (isNegativeLE(x * zInv, P)) + y = mod(-y); // 9 + let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a)) + if (isNegativeLE(s, P)) + s = mod(-s); + return numberToBytesLE(s, 32); // 11 + } + toHex() { + return bytesToHex(this.toRawBytes()); + } + toString() { + return this.toHex(); + } + // Compare one point to another. + equals(other) { + assertRstPoint(other); + const { ex: X1, ey: Y1 } = this.ep; + const { ex: X2, ey: Y2 } = other.ep; + const mod = ed25519.CURVE.Fp.create; + // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2) + const one = mod(X1 * Y2) === mod(Y1 * X2); + const two = mod(Y1 * Y2) === mod(X1 * X2); + return one || two; + } + add(other) { + assertRstPoint(other); + return new RistPoint(this.ep.add(other.ep)); + } + subtract(other) { + assertRstPoint(other); + return new RistPoint(this.ep.subtract(other.ep)); + } + multiply(scalar) { + return new RistPoint(this.ep.multiply(scalar)); + } + multiplyUnsafe(scalar) { + return new RistPoint(this.ep.multiplyUnsafe(scalar)); + } +} +export const RistrettoPoint = /* @__PURE__ */ (() => { + if (!RistPoint.BASE) + RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE); + if (!RistPoint.ZERO) + RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO); + return RistPoint; +})(); +// https://datatracker.ietf.org/doc/draft-irtf-cfrg-hash-to-curve/14/ +// Appendix B. Hashing to ristretto255 +export const hash_to_ristretto255 = (msg, options) => { + const d = options.DST; + const DST = typeof d === 'string' ? utf8ToBytes(d) : d; + const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512); + const P = RistPoint.hashToCurve(uniform_bytes); + return P; +}; +//# sourceMappingURL=ed25519.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/ed25519.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/ed25519.js.map new file mode 100644 index 0000000..5a84c43 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/ed25519.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ed25519.js","sourceRoot":"","sources":["../src/ed25519.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,EAAgB,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AACtD,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AACnF,OAAO,EACL,UAAU,EACV,eAAe,EACf,WAAW,EACX,UAAU,EAEV,eAAe,GAChB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,YAAY,EAAgB,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAG7F;;;;;GAKG;AAEH,MAAM,SAAS,GAAG,MAAM,CACtB,+EAA+E,CAChF,CAAC;AACF,iCAAiC;AACjC,MAAM,eAAe,GAAG,MAAM,CAC5B,+EAA+E,CAChF,CAAC;AAEF,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACzE,kBAAkB;AAClB,MAAM,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG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C,CAAC,CAAC;IACnD,CAAC;IAED,QAAQ,CAAC,MAAc;QACrB,OAAO,IAAI,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;IACjD,CAAC;IAED,cAAc,CAAC,MAAc;QAC3B,OAAO,IAAI,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAC;IACvD,CAAC;CACF;AACD,MAAM,CAAC,MAAM,cAAc,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE;IAClD,IAAI,CAAC,SAAS,CAAC,IAAI;QAAE,SAAS,CAAC,IAAI,GAAG,IAAI,SAAS,CAAC,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;IAChF,IAAI,CAAC,SAAS,CAAC,IAAI;QAAE,SAAS,CAAC,IAAI,GAAG,IAAI,SAAS,CAAC,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;IAChF,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC,EAAE,CAAC;AAEL,qEAAqE;AACrE,uCAAuC;AACvC,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,GAAe,EAAE,OAAqB,EAAE,EAAE;IAC7E,MAAM,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC;IACtB,MAAM,GAAG,GAAG,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACvD,MAAM,aAAa,GAAG,kBAAkB,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,CAAC,CAAC;IAC/D,MAAM,CAAC,GAAG,SAAS,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC;IAC/C,OAAO,CAAC,CAAC;AACX,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/ed448.js b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/ed448.js new file mode 100644 index 0000000..76b4633 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/ed448.js @@ -0,0 +1,215 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { shake256 } from '@noble/hashes/sha3'; +import { concatBytes, randomBytes, utf8ToBytes, wrapConstructor } from '@noble/hashes/utils'; +import { twistedEdwards } from './abstract/edwards.js'; +import { mod, pow2, Field } from './abstract/modular.js'; +import { montgomery } from './abstract/montgomery.js'; +import { createHasher } from './abstract/hash-to-curve.js'; +/** + * Edwards448 (not Ed448-Goldilocks) curve with following addons: + * * X448 ECDH + * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2 + */ +const shake256_114 = wrapConstructor(() => shake256.create({ dkLen: 114 })); +const shake256_64 = wrapConstructor(() => shake256.create({ dkLen: 64 })); +const ed448P = BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439'); +// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4. +// Used for efficient square root calculation. +// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1] +function ed448_pow_Pminus3div4(x) { + const P = ed448P; + // prettier-ignore + const _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _11n = BigInt(11); + // prettier-ignore + const _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223); + const b2 = (x * x * x) % P; + const b3 = (b2 * b2 * x) % P; + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b222 = (pow2(b220, _2n, P) * b2) % P; + const b223 = (pow2(b222, _1n, P) * x) % P; + return (pow2(b223, _223n, P) * b222) % P; +} +function adjustScalarBytes(bytes) { + // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, and the most + // significant bit of the last byte to 1. + bytes[0] &= 252; // 0b11111100 + // and the most significant bit of the last byte to 1. + bytes[55] |= 128; // 0b10000000 + // NOTE: is is NOOP for 56 bytes scalars (X25519/X448) + bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits) + return bytes; +} +const Fp = Field(ed448P, 456, true); +const _4n = BigInt(4); +const ED448_DEF = { + // Param: a + a: BigInt(1), + // -39081. Negative number is P - number + d: BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358'), + // Finite field 𝔽p over which we'll do calculations; 2n**448n - 2n**224n - 1n + Fp, + // Subgroup order: how many points curve has; + // 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n + n: BigInt('181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779'), + nBitLength: 456, + // Cofactor + h: BigInt(4), + // Base point (x, y) aka generator point + Gx: BigInt('224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710'), + Gy: BigInt('298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660'), + // SHAKE256(dom4(phflag,context)||x, 114) + hash: shake256_114, + randomBytes, + adjustScalarBytes, + // dom4 + domain: (data, ctx, phflag) => { + if (ctx.length > 255) + throw new Error(`Context is too big: ${ctx.length}`); + return concatBytes(utf8ToBytes('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); + }, + // Constant-time ratio of u to v. Allows to combine inversion and square root u/√v. + // Uses algo from RFC8032 5.1.3. + uvRatio: (u, v) => { + const P = ed448P; + // https://datatracker.ietf.org/doc/html/rfc8032#section-5.2.3 + // To compute the square root of (u/v), the first step is to compute the + // candidate root x = (u/v)^((p+1)/4). This can be done using the + // following trick, to use a single modular powering for both the + // inversion of v and the square root: + // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p) + const u2v = mod(u * u * v, P); // u²v + const u3v = mod(u2v * u, P); // u³v + const u5v3 = mod(u3v * u2v * v, P); // u⁵v³ + const root = ed448_pow_Pminus3div4(u5v3); + const x = mod(u3v * root, P); + // Verify that root is exists + const x2 = mod(x * x, P); // x² + // If vx² = u, the recovered x-coordinate is x. Otherwise, no + // square root exists, and the decoding fails. + return { isValid: mod(x2 * v, P) === u, value: x }; + }, +}; +export const ed448 = twistedEdwards(ED448_DEF); +// NOTE: there is no ed448ctx, since ed448 supports ctx by default +export const ed448ph = twistedEdwards({ ...ED448_DEF, prehash: shake256_64 }); +export const x448 = /* @__PURE__ */ (() => montgomery({ + a: BigInt(156326), + montgomeryBits: 448, + nByteLength: 57, + P: ed448P, + Gu: BigInt(5), + powPminus2: (x) => { + const P = ed448P; + const Pminus3div4 = ed448_pow_Pminus3div4(x); + const Pminus3 = pow2(Pminus3div4, BigInt(2), P); + return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2 + }, + adjustScalarBytes, + randomBytes, +}))(); +/** + * Converts edwards448 public key to x448 public key. Uses formula: + * * `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)` + * * `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))` + * @example + * const aPub = ed448.getPublicKey(utils.randomPrivateKey()); + * x448.getSharedSecret(edwardsToMontgomery(aPub), edwardsToMontgomery(someonesPub)) + */ +export function edwardsToMontgomeryPub(edwardsPub) { + const { y } = ed448.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((y - _1n) * Fp.inv(y + _1n))); +} +export const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated +// Hash To Curve Elligator2 Map +const ELL2_C1 = (Fp.ORDER - BigInt(3)) / BigInt(4); // 1. c1 = (q - 3) / 4 # Integer arithmetic +const ELL2_J = BigInt(156326); +function map_to_curve_elligator2_curve448(u) { + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + let e1 = Fp.eql(tv1, Fp.ONE); // 2. e1 = tv1 == 1 + tv1 = Fp.cmov(tv1, Fp.ZERO, e1); // 3. tv1 = CMOV(tv1, 0, e1) # If Z * u^2 == -1, set tv1 = 0 + let xd = Fp.sub(Fp.ONE, tv1); // 4. xd = 1 - tv1 + let x1n = Fp.neg(ELL2_J); // 5. x1n = -J + let tv2 = Fp.sqr(xd); // 6. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 7. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, Fp.neg(ELL2_J)); // 8. gx1 = -J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 9. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 10. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 11. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 12. tv3 = gxd^2 + tv2 = Fp.mul(gx1, gxd); // 13. tv2 = gx1 * gxd # gx1 * gxd + tv3 = Fp.mul(tv3, tv2); // 14. tv3 = tv3 * tv2 # gx1 * gxd^3 + let y1 = Fp.pow(tv3, ELL2_C1); // 15. y1 = tv3^c1 # (gx1 * gxd^3)^((p - 3) / 4) + y1 = Fp.mul(y1, tv2); // 16. y1 = y1 * tv2 # gx1 * gxd * (gx1 * gxd^3)^((p - 3) / 4) + let x2n = Fp.mul(x1n, Fp.neg(tv1)); // 17. x2n = -tv1 * x1n # x2 = x2n / xd = -1 * u^2 * x1n / xd + let y2 = Fp.mul(y1, u); // 18. y2 = y1 * u + y2 = Fp.cmov(y2, Fp.ZERO, e1); // 19. y2 = CMOV(y2, 0, e1) + tv2 = Fp.sqr(y1); // 20. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 21. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx1); // 22. e2 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e2); // 23. xn = CMOV(x2n, x1n, e2) # If e2, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e2); // 24. y = CMOV(y2, y1, e2) # If e2, y = y1, else y = y2 + let e3 = Fp.isOdd(y); // 25. e3 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e2 !== e3); // 26. y = CMOV(y, -y, e2 XOR e3) + return { xn, xd, yn: y, yd: Fp.ONE }; // 27. return (xn, xd, y, 1) +} +function map_to_curve_elligator2_edwards448(u) { + let { xn, xd, yn, yd } = map_to_curve_elligator2_curve448(u); // 1. (xn, xd, yn, yd) = map_to_curve_elligator2_curve448(u) + let xn2 = Fp.sqr(xn); // 2. xn2 = xn^2 + let xd2 = Fp.sqr(xd); // 3. xd2 = xd^2 + let xd4 = Fp.sqr(xd2); // 4. xd4 = xd2^2 + let yn2 = Fp.sqr(yn); // 5. yn2 = yn^2 + let yd2 = Fp.sqr(yd); // 6. yd2 = yd^2 + let xEn = Fp.sub(xn2, xd2); // 7. xEn = xn2 - xd2 + let tv2 = Fp.sub(xEn, xd2); // 8. tv2 = xEn - xd2 + xEn = Fp.mul(xEn, xd2); // 9. xEn = xEn * xd2 + xEn = Fp.mul(xEn, yd); // 10. xEn = xEn * yd + xEn = Fp.mul(xEn, yn); // 11. xEn = xEn * yn + xEn = Fp.mul(xEn, _4n); // 12. xEn = xEn * 4 + tv2 = Fp.mul(tv2, xn2); // 13. tv2 = tv2 * xn2 + tv2 = Fp.mul(tv2, yd2); // 14. tv2 = tv2 * yd2 + let tv3 = Fp.mul(yn2, _4n); // 15. tv3 = 4 * yn2 + let tv1 = Fp.add(tv3, yd2); // 16. tv1 = tv3 + yd2 + tv1 = Fp.mul(tv1, xd4); // 17. tv1 = tv1 * xd4 + let xEd = Fp.add(tv1, tv2); // 18. xEd = tv1 + tv2 + tv2 = Fp.mul(tv2, xn); // 19. tv2 = tv2 * xn + let tv4 = Fp.mul(xn, xd4); // 20. tv4 = xn * xd4 + let yEn = Fp.sub(tv3, yd2); // 21. yEn = tv3 - yd2 + yEn = Fp.mul(yEn, tv4); // 22. yEn = yEn * tv4 + yEn = Fp.sub(yEn, tv2); // 23. yEn = yEn - tv2 + tv1 = Fp.add(xn2, xd2); // 24. tv1 = xn2 + xd2 + tv1 = Fp.mul(tv1, xd2); // 25. tv1 = tv1 * xd2 + tv1 = Fp.mul(tv1, xd); // 26. tv1 = tv1 * xd + tv1 = Fp.mul(tv1, yn2); // 27. tv1 = tv1 * yn2 + tv1 = Fp.mul(tv1, BigInt(-2)); // 28. tv1 = -2 * tv1 + let yEd = Fp.add(tv2, tv1); // 29. yEd = tv2 + tv1 + tv4 = Fp.mul(tv4, yd2); // 30. tv4 = tv4 * yd2 + yEd = Fp.add(yEd, tv4); // 31. yEd = yEd + tv4 + tv1 = Fp.mul(xEd, yEd); // 32. tv1 = xEd * yEd + let e = Fp.eql(tv1, Fp.ZERO); // 33. e = tv1 == 0 + xEn = Fp.cmov(xEn, Fp.ZERO, e); // 34. xEn = CMOV(xEn, 0, e) + xEd = Fp.cmov(xEd, Fp.ONE, e); // 35. xEd = CMOV(xEd, 1, e) + yEn = Fp.cmov(yEn, Fp.ONE, e); // 36. yEn = CMOV(yEn, 1, e) + yEd = Fp.cmov(yEd, Fp.ONE, e); // 37. yEd = CMOV(yEd, 1, e) + const inv = Fp.invertBatch([xEd, yEd]); // batch division + return { x: Fp.mul(xEn, inv[0]), y: Fp.mul(yEn, inv[1]) }; // 38. return (xEn, xEd, yEn, yEd) +} +const htf = /* @__PURE__ */ (() => createHasher(ed448.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards448(scalars[0]), { + DST: 'edwards448_XOF:SHAKE256_ELL2_RO_', + encodeDST: 'edwards448_XOF:SHAKE256_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 224, + expand: 'xof', + hash: shake256, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +//# sourceMappingURL=ed448.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/ed448.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/ed448.js.map new file mode 100644 index 0000000..e877407 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/ed448.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ed448.js","sourceRoot":"","sources":["../src/ed448.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAC7F,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAE3D;;;;GAIG;AAEH,MAAM,YAAY,GAAG,eAAe,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;AAC5E,MAAM,WAAW,GAAG,eAAe,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC;AAC1E,MAAM,MAAM,GAAG,MAAM,CACnB,yIAAyI,CAC1I,CAAC;AAEF,8DAA8D;AAC9D,8CAA8C;AAC9C,+DAA+D;AAC/D,SAAS,qBAAqB,CAAC,CAAS;IACtC,MAAM,CAAC,GAAG,MAAM,CAAC;IACjB,kBAAkB;IAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,C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,MAAM,WAAW,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACrE,MAAM,CAAC,MAAM,aAAa,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/index.js b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/index.js new file mode 100644 index 0000000..ac4f223 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/index.js @@ -0,0 +1,3 @@ +"use strict"; +throw new Error('Incorrect usage. Import submodules instead'); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/index.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/index.js.map new file mode 100644 index 0000000..b5117dc --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/jubjub.js b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/jubjub.js new file mode 100644 index 0000000..2b1f575 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/jubjub.js @@ -0,0 +1,54 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha512 } from '@noble/hashes/sha512'; +import { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils'; +import { twistedEdwards } from './abstract/edwards.js'; +import { blake2s } from '@noble/hashes/blake2s'; +import { Field } from './abstract/modular.js'; +/** + * jubjub Twisted Edwards curve. + * https://neuromancer.sk/std/other/JubJub + * jubjub does not use EdDSA, so `hash`/sha512 params are passed because interface expects them. + */ +export const jubjub = twistedEdwards({ + // Params: a, d + a: BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000'), + d: BigInt('0x2a9318e74bfa2b48f5fd9207e6bd7fd4292d7f6d37579d2601065fd6d6343eb1'), + // Finite field 𝔽p over which we'll do calculations + // Same value as bls12-381 Fr (not Fp) + Fp: Field(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')), + // Subgroup order: how many points curve has + n: BigInt('0xe7db4ea6533afa906673b0101343b00a6682093ccc81082d0970e5ed6f72cb7'), + // Cofactor + h: BigInt(8), + // Base point (x, y) aka generator point + Gx: BigInt('0x11dafe5d23e1218086a365b99fbf3d3be72f6afd7d1f72623e6b071492d1122b'), + Gy: BigInt('0x1d523cf1ddab1a1793132e78c866c0c33e26ba5cc220fed7cc3f870e59d292aa'), + hash: sha512, + randomBytes, +}); +const GH_FIRST_BLOCK = utf8ToBytes('096b36a5804bfacef1691e173c366a47ff5ba84a44f26ddd7e8d9f79d5b42df0'); +// Returns point at JubJub curve which is prime order and not zero +export function groupHash(tag, personalization) { + const h = blake2s.create({ personalization, dkLen: 32 }); + h.update(GH_FIRST_BLOCK); + h.update(tag); + // NOTE: returns ExtendedPoint, in case it will be multiplied later + let p = jubjub.ExtendedPoint.fromHex(h.digest()); + // NOTE: cannot replace with isSmallOrder, returns Point*8 + p = p.multiply(jubjub.CURVE.h); + if (p.equals(jubjub.ExtendedPoint.ZERO)) + throw new Error('Point has small order'); + return p; +} +export function findGroupHash(m, personalization) { + const tag = concatBytes(m, new Uint8Array([0])); + for (let i = 0; i < 256; i++) { + tag[tag.length - 1] = i; + try { + return groupHash(tag, personalization); + } + catch (e) { } + } + throw new Error('findGroupHash tag overflow'); +} +//# sourceMappingURL=jubjub.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/jubjub.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/jubjub.js.map new file mode 100644 index 0000000..41ad6bb --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/jubjub.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jubjub.js","sourceRoot":"","sources":["../src/jubjub.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAChD,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAE9C;;;;GAIG;AAEH,MAAM,CAAC,MAAM,MAAM,GAAG,cAAc,CAAC;IACnC,eAAe;IACf,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,oDAAoD;IACpD,sCAAsC;IACtC,EAAE,EAAE,KAAK,CAAC,MAAM,CAAC,oEAAoE,CAAC,CAAC;IACvF,4CAA4C;IAC5C,CAAC,EAAE,MAAM,CAAC,mEAAmE,CAAC;IAC9E,WAAW;IACX,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,wCAAwC;IACxC,EAAE,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAChF,EAAE,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAChF,IAAI,EAAE,MAAM;IACZ,WAAW;CACH,CAAC,CAAC;AAEZ,MAAM,cAAc,GAAG,WAAW,CAChC,kEAAkE,CACnE,CAAC;AAEF,kEAAkE;AAClE,MAAM,UAAU,SAAS,CAAC,GAAe,EAAE,eAA2B;IACpE,MAAM,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,EAAE,eAAe,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;IACzD,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;IACzB,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IACd,mEAAmE;IACnE,IAAI,CAAC,GAAG,MAAM,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC;IACjD,0DAA0D;IAC1D,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAC/B,IAAI,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC;IAClF,OAAO,CAAC,CAAC;AACX,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,CAAa,EAAE,eAA2B;IACtE,MAAM,GAAG,GAAG,WAAW,CAAC,CAAC,EAAE,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAChD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE;QAC5B,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;QACxB,IAAI;YACF,OAAO,SAAS,CAAC,GAAG,EAAE,eAAe,CAAC,CAAC;SACxC;QAAC,OAAO,CAAC,EAAE,GAAE;KACf;IACD,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;AAChD,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/p256.js b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/p256.js new file mode 100644 index 0000000..5e2e89e --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/p256.js @@ -0,0 +1,42 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { createCurve } from './_shortw_utils.js'; +import { sha256 } from '@noble/hashes/sha256'; +import { Field } from './abstract/modular.js'; +import { mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import { createHasher } from './abstract/hash-to-curve.js'; +// NIST secp256r1 aka p256 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256 +const Fp = Field(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff')); +const CURVE_A = Fp.create(BigInt('-3')); +const CURVE_B = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'); +// prettier-ignore +export const p256 = createCurve({ + a: CURVE_A, + b: CURVE_B, + Fp, + // Curve order, total count of valid points in the field + n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'), + // Base (generator) point (x, y) + Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'), + Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'), + h: BigInt(1), + lowS: false, +}, sha256); +export const secp256r1 = p256; +const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-10')), +}))(); +const htf = /* @__PURE__ */ (() => createHasher(secp256r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P256_XMD:SHA-256_SSWU_RO_', + encodeDST: 'P256_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +//# sourceMappingURL=p256.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/p256.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/p256.js.map new file mode 100644 index 0000000..1efec39 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/p256.js.map @@ -0,0 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AC,CAAC,EAAE,CAAC;AAER,MAAM,GAAG,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAChC,YAAY,CAAC,SAAS,CAAC,eAAe,EAAE,CAAC,OAAiB,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE;IACjF,GAAG,EAAE,2BAA2B;IAChC,SAAS,EAAE,2BAA2B;IACtC,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,MAAM;CACb,CAAC,CAAC,EAAE,CAAC;AACR,MAAM,CAAC,MAAM,WAAW,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACrE,MAAM,CAAC,MAAM,aAAa,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/p384.js b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/p384.js new file mode 100644 index 0000000..21d9308 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/p384.js @@ -0,0 +1,46 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { createCurve } from './_shortw_utils.js'; +import { sha384 } from '@noble/hashes/sha512'; +import { Field } from './abstract/modular.js'; +import { mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import { createHasher } from './abstract/hash-to-curve.js'; +// NIST secp384r1 aka p384 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-384 +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'); +const Fp = Field(P); +const CURVE_A = Fp.create(BigInt('-3')); +// prettier-ignore +const CURVE_B = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'); +// prettier-ignore +export const p384 = createCurve({ + a: CURVE_A, + b: CURVE_B, + Fp, + // Curve order, total count of valid points in the field. + n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'), + // Base (generator) point (x, y) + Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'), + Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'), + h: BigInt(1), + lowS: false, +}, sha384); +export const secp384r1 = p384; +const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-12')), +}))(); +const htf = /* @__PURE__ */ (() => createHasher(secp384r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P384_XMD:SHA-384_SSWU_RO_', + encodeDST: 'P384_XMD:SHA-384_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 192, + expand: 'xmd', + hash: sha384, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +//# sourceMappingURL=p384.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/p384.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/p384.js.map new file mode 100644 index 0000000..bf8b8ed --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/p384.js.map @@ -0,0 +1 @@ +{"version":3,"file":"p384.js","sourceRoot":"","sources":["../src/p384.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,C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e,CAAC,CAAC,GAAG,EAAE,CAChC,YAAY,CAAC,SAAS,CAAC,eAAe,EAAE,CAAC,OAAiB,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE;IACjF,GAAG,EAAE,2BAA2B;IAChC,SAAS,EAAE,2BAA2B;IACtC,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,MAAM;CACb,CAAC,CAAC,EAAE,CAAC;AACR,MAAM,CAAC,MAAM,WAAW,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACrE,MAAM,CAAC,MAAM,aAAa,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/p521.js b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/p521.js new file mode 100644 index 0000000..0131155 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/p521.js @@ -0,0 +1,53 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { createCurve } from './_shortw_utils.js'; +import { sha512 } from '@noble/hashes/sha512'; +import { Field } from './abstract/modular.js'; +import { mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import { createHasher } from './abstract/hash-to-curve.js'; +// NIST secp521r1 aka p521 +// Note that it's 521, which differs from 512 of its hash function. +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-521 +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const Fp = Field(P); +const CURVE = { + a: Fp.create(BigInt('-3')), + b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'), + Fp, + n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'), + Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'), + Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'), + h: BigInt(1), +}; +// prettier-ignore +export const p521 = createCurve({ + a: CURVE.a, + b: CURVE.b, + Fp, + // Curve order, total count of valid points in the field + n: CURVE.n, + Gx: CURVE.Gx, + Gy: CURVE.Gy, + h: CURVE.h, + lowS: false, + allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b +}, sha512); +export const secp521r1 = p521; +const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, { + A: CURVE.a, + B: CURVE.b, + Z: Fp.create(BigInt('-4')), +}))(); +const htf = /* @__PURE__ */ (() => createHasher(secp521r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P521_XMD:SHA-512_SSWU_RO_', + encodeDST: 'P521_XMD:SHA-512_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 256, + expand: 'xmd', + hash: sha512, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +//# sourceMappingURL=p521.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/p521.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/p521.js.map new file mode 100644 index 0000000..cd24eb5 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/p521.js.map @@ -0,0 +1 @@ +{"version":3,"file":"p521.js","sourceRoot":"","sources":["../src/p521.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC9C,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAE3D,0BAA0B;AAC1B,mEAAmE;AACnE,0EAA0E;AAE1E,0CAA0C;AAC1C,kBAAkB;AAClB,MAAM,CAAC,GAAG,MAAM,CAAC,uIAAuI,CAAC,CAAC;AAC1J,MAAM,EAAE,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAEpB,MAAM,KAAK,GAAG;IACZ,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC1B,CAAC,EAAE,MAAM,CACP,wIAAwI,CACzI;IACD,EAAE;IACF,CAAC,EAAE,MAAM,CACP,wIAAwI,CACzI;IACD,EAAE,EAAE,MAAM,CACR,wIAAwI,CACzI;IACD,EAAE,EAAE,MAAM,CACR,wIAAwI,CACzI;IACD,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;CACb,CAAC;AAEF,kBAAkB;AAClB,MAAM,CAAC,MAAM,IAAI,GAAG,WAAW,CAAC;IAC9B,CAAC,EAAE,KAAK,CAAC,CAAC;IACV,CAAC,EAAE,KAAK,CAAC,CAAC;IACV,EAAE;IACF,wDAAwD;IACxD,CAAC,EAAE,KAAK,CAAC,CAAC;IACV,EAAE,EAAE,KAAK,CAAC,EAAE;IACZ,EAAE,EAAE,KAAK,CAAC,EAAE;IACZ,CAAC,EAAE,KAAK,CAAC,CAAC;IACV,IAAI,EAAE,KAAK;IACX,wBAAwB,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,mDAAmD;CACrF,EAAE,MAAM,CAAC,CAAC;AACpB,MAAM,CAAC,MAAM,SAAS,GAAG,IAAI,CAAC;AAE9B,MAAM,MAAM,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CACnC,mBAAmB,CAAC,EAAE,EAAE;IACtB,CAAC,EAAE,KAAK,CAAC,CAAC;IACV,CAAC,EAAE,KAAK,CAAC,CAAC;IACV,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;CAC3B,CAAC,CAAC,EAAE,CAAC;AAER,MAAM,GAAG,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAChC,YAAY,CAAC,SAAS,CAAC,eAAe,EAAE,CAAC,OAAiB,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE;IACjF,GAAG,EAAE,2BAA2B;IAChC,SAAS,EAAE,2BAA2B;IACtC,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,MAAM;CACb,CAAC,CAAC,EAAE,CAAC;AACR,MAAM,CAAC,MAAM,WAAW,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACrE,MAAM,CAAC,MAAM,aAAa,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/package.json b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/package.json new file mode 100644 index 0000000..267769c --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/package.json @@ -0,0 +1,7 @@ +{ + "type": "module", + "browser": { + "crypto": false, + "./crypto": "./esm/crypto.js" + } +} diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/pasta.js b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/pasta.js new file mode 100644 index 0000000..fa5ca52 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/pasta.js @@ -0,0 +1,30 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { weierstrass } from './abstract/weierstrass.js'; +import { getHash } from './_shortw_utils.js'; +import * as mod from './abstract/modular.js'; +export const p = BigInt('0x40000000000000000000000000000000224698fc094cf91b992d30ed00000001'); +export const q = BigInt('0x40000000000000000000000000000000224698fc0994a8dd8c46eb2100000001'); +// https://neuromancer.sk/std/other/Pallas +export const pallas = weierstrass({ + a: BigInt(0), + b: BigInt(5), + Fp: mod.Field(p), + n: q, + Gx: mod.mod(BigInt(-1), p), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); +// https://neuromancer.sk/std/other/Vesta +export const vesta = weierstrass({ + a: BigInt(0), + b: BigInt(5), + Fp: mod.Field(q), + n: p, + Gx: mod.mod(BigInt(-1), q), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); +//# sourceMappingURL=pasta.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/pasta.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/pasta.js.map new file mode 100644 index 0000000..4942dd2 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/pasta.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pasta.js","sourceRoot":"","sources":["../src/pasta.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAC7C,OAAO,KAAK,GAAG,MAAM,uBAAuB,CAAC;AAE7C,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAC9F,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAE9F,0CAA0C;AAC1C,MAAM,CAAC,MAAM,MAAM,GAAG,WAAW,CAAC;IAChC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC;IAChB,CAAC,EAAE,CAAC;IACJ,EAAE,EAAE,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAC1B,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,OAAO,CAAC,MAAM,CAAC;CACnB,CAAC,CAAC;AACH,yCAAyC;AACzC,MAAM,CAAC,MAAM,KAAK,GAAG,WAAW,CAAC;IAC/B,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC;IAChB,CAAC,EAAE,CAAC;IACJ,EAAE,EAAE,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAC1B,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,OAAO,CAAC,MAAM,CAAC;CACnB,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/secp256k1.js b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/secp256k1.js new file mode 100644 index 0000000..eb36ebc --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/secp256k1.js @@ -0,0 +1,254 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { randomBytes } from '@noble/hashes/utils'; +import { Field, mod, pow2 } from './abstract/modular.js'; +import { mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import { bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE } from './abstract/utils.js'; +import { createHasher, isogenyMap } from './abstract/hash-to-curve.js'; +import { createCurve } from './_shortw_utils.js'; +const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'); +const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); +const _1n = BigInt(1); +const _2n = BigInt(2); +const divNearest = (a, b) => (a + b / _2n) / b; +/** + * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit. + * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00] + */ +function sqrtMod(y) { + const P = secp256k1P; + // prettier-ignore + const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + // prettier-ignore + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = (y * y * y) % P; // x^3, 11 + const b3 = (b2 * b2 * y) % P; // x^7 + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b223 = (pow2(b220, _3n, P) * b3) % P; + const t1 = (pow2(b223, _23n, P) * b22) % P; + const t2 = (pow2(t1, _6n, P) * b2) % P; + const root = pow2(t2, _2n, P); + if (!Fp.eql(Fp.sqr(root), y)) + throw new Error('Cannot find square root'); + return root; +} +const Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod }); +export const secp256k1 = createCurve({ + a: BigInt(0), + b: BigInt(7), + Fp, + n: secp256k1N, + // Base point (x, y) aka generator point + Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), + Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), + h: BigInt(1), + lowS: true, + /** + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 + */ + endo: { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + splitScalar: (k) => { + const n = secp256k1N; + const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); + const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); + const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); + const b2 = a1; + const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16) + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = mod(k - c1 * a1 - c2 * a2, n); + let k2 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) + k1 = n - k1; + if (k2neg) + k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error('splitScalar: Endomorphism failed, k=' + k); + } + return { k1neg, k1, k2neg, k2 }; + }, + }, +}, sha256); +// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code. +// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki +const _0n = BigInt(0); +const fe = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1P; +const ge = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1N; +/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */ +const TAGGED_HASH_PREFIXES = {}; +function taggedHash(tag, ...messages) { + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === undefined) { + const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + tagP = concatBytes(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return sha256(concatBytes(tagP, ...messages)); +} +// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03 +const pointToBytes = (point) => point.toRawBytes(true).slice(1); +const numTo32b = (n) => numberToBytesBE(n, 32); +const modP = (x) => mod(x, secp256k1P); +const modN = (x) => mod(x, secp256k1N); +const Point = secp256k1.ProjectivePoint; +const GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b); +// Calculate point, scalar and bytes +function schnorrGetExtPubKey(priv) { + let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey + let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside + const scalar = p.hasEvenY() ? d_ : modN(-d_); + return { scalar: scalar, bytes: pointToBytes(p) }; +} +/** + * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point. + * @returns valid point checked for being on-curve + */ +function lift_x(x) { + if (!fe(x)) + throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p. + const xx = modP(x * x); + const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p. + let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p. + if (y % _2n !== _0n) + y = modP(-y); // Return the unique point P such that x(P) = x and + const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise. + p.assertValidity(); + return p; +} +/** + * Create tagged hash, convert it to bigint, reduce modulo-n. + */ +function challenge(...args) { + return modN(bytesToNumberBE(taggedHash('BIP0340/challenge', ...args))); +} +/** + * Schnorr public key is just `x` coordinate of Point as per BIP340. + */ +function schnorrGetPublicKey(privateKey) { + return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G) +} +/** + * Creates Schnorr signature as per BIP340. Verifies itself before returning anything. + * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous. + */ +function schnorrSign(message, privateKey, auxRand = randomBytes(32)) { + const m = ensureBytes('message', message); + const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder + const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array + const t = numTo32b(d ^ bytesToNumberBE(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a) + const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m) + const k_ = modN(bytesToNumberBE(rand)); // Let k' = int(rand) mod n + if (k_ === _0n) + throw new Error('sign failed: k is zero'); // Fail if k' = 0. + const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G. + const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n. + const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n). + sig.set(rx, 0); + sig.set(numTo32b(modN(k + e * d)), 32); + // If Verify(bytes(P), m, sig) (see below) returns failure, abort + if (!schnorrVerify(sig, m, px)) + throw new Error('sign: Invalid signature produced'); + return sig; +} +/** + * Verifies Schnorr signature. + * Will swallow errors & return false except for initial type validation of arguments. + */ +function schnorrVerify(signature, message, publicKey) { + const sig = ensureBytes('signature', signature, 64); + const m = ensureBytes('message', message); + const pub = ensureBytes('publicKey', publicKey, 32); + try { + const P = lift_x(bytesToNumberBE(pub)); // P = lift_x(int(pk)); fail if that fails + const r = bytesToNumberBE(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p. + if (!fe(r)) + return false; + const s = bytesToNumberBE(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n. + if (!ge(s)) + return false; + const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n + const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P + if (!R || !R.hasEvenY() || R.toAffine().x !== r) + return false; // -eP == (n-e)P + return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r. + } + catch (error) { + return false; + } +} +export const schnorr = /* @__PURE__ */ (() => ({ + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + utils: { + randomPrivateKey: secp256k1.utils.randomPrivateKey, + lift_x, + pointToBytes, + numberToBytesBE, + bytesToNumberBE, + taggedHash, + mod, + }, +}))(); +const isoMap = /* @__PURE__ */ (() => isogenyMap(Fp, [ + // xNum + [ + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7', + '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581', + '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262', + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c', + ], + // xDen + [ + '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b', + '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c', + '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3', + '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931', + '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84', + ], + // yDen + [ + '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b', + '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573', + '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], +].map((i) => i.map((j) => BigInt(j)))))(); +const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, { + A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'), + B: BigInt('1771'), + Z: Fp.create(BigInt('-11')), +}))(); +const htf = /* @__PURE__ */ (() => createHasher(secp256k1.ProjectivePoint, (scalars) => { + const { x, y } = mapSWU(Fp.create(scalars[0])); + return isoMap(x, y); +}, { + DST: 'secp256k1_XMD:SHA-256_SSWU_RO_', + encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +//# sourceMappingURL=secp256k1.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/esm/secp256k1.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/secp256k1.js.map new file mode 100644 index 0000000..692678a --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/esm/secp256k1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"secp256k1.js","sourceRoot":"","sources":["../src/secp256k1.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAA8B,mBAAmB,EAAE,MAAM,2BA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CAAC,EAAE,EAAE;IACtB,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,CAAC,EAAE,MAAM,CAAC,MAAM,CAAC;IACjB,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;CAC5B,CAAC,CAAC,EAAE,CAAC;AACR,MAAM,GAAG,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAChC,YAAY,CACV,SAAS,CAAC,eAAe,EACzB,CAAC,OAAiB,EAAE,EAAE;IACpB,MAAM,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/C,OAAO,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AACtB,CAAC,EACD;IACE,GAAG,EAAE,gCAAgC;IACrC,SAAS,EAAE,gCAAgC;IAC3C,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,MAAM;CACb,CACF,CAAC,EAAE,CAAC;AACP,MAAM,CAAC,MAAM,WAAW,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACrE,MAAM,CAAC,MAAM,aAAa,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/index.d.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/index.d.ts new file mode 100644 index 0000000..f36479a --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/index.d.ts @@ -0,0 +1 @@ +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/index.d.ts.map b/node_modules/@scure/bip32/node_modules/@noble/curves/index.d.ts.map new file mode 100644 index 0000000..4e8c581 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/index.js b/node_modules/@scure/bip32/node_modules/@noble/curves/index.js new file mode 100644 index 0000000..ac4f223 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/index.js @@ -0,0 +1,3 @@ +"use strict"; +throw new Error('Incorrect usage. Import submodules instead'); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/index.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/index.js.map new file mode 100644 index 0000000..292b53a --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":";AAAA,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/jubjub.d.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/jubjub.d.ts new file mode 100644 index 0000000..7d2c398 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/jubjub.d.ts @@ -0,0 +1,9 @@ +/** + * jubjub Twisted Edwards curve. + * https://neuromancer.sk/std/other/JubJub + * jubjub does not use EdDSA, so `hash`/sha512 params are passed because interface expects them. + */ +export declare const jubjub: import("./abstract/edwards.js").CurveFn; +export declare function groupHash(tag: Uint8Array, personalization: Uint8Array): import("./abstract/edwards.js").ExtPointType; +export declare function findGroupHash(m: Uint8Array, personalization: Uint8Array): import("./abstract/edwards.js").ExtPointType; +//# sourceMappingURL=jubjub.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/jubjub.d.ts.map b/node_modules/@scure/bip32/node_modules/@noble/curves/jubjub.d.ts.map new file mode 100644 index 0000000..e79099d --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/jubjub.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"jubjub.d.ts","sourceRoot":"","sources":["src/jubjub.ts"],"names":[],"mappings":"AAOA;;;;GAIG;AAEH,eAAO,MAAM,MAAM,yCAgBR,CAAC;AAOZ,wBAAgB,SAAS,CAAC,GAAG,EAAE,UAAU,EAAE,eAAe,EAAE,UAAU,gDAUrE;AAED,wBAAgB,aAAa,CAAC,CAAC,EAAE,UAAU,EAAE,eAAe,EAAE,UAAU,gDASvE"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/jubjub.js b/node_modules/@scure/bip32/node_modules/@noble/curves/jubjub.js new file mode 100644 index 0000000..60c8329 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/jubjub.js @@ -0,0 +1,59 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.findGroupHash = exports.groupHash = exports.jubjub = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha512_1 = require("@noble/hashes/sha512"); +const utils_1 = require("@noble/hashes/utils"); +const edwards_js_1 = require("./abstract/edwards.js"); +const blake2s_1 = require("@noble/hashes/blake2s"); +const modular_js_1 = require("./abstract/modular.js"); +/** + * jubjub Twisted Edwards curve. + * https://neuromancer.sk/std/other/JubJub + * jubjub does not use EdDSA, so `hash`/sha512 params are passed because interface expects them. + */ +exports.jubjub = (0, edwards_js_1.twistedEdwards)({ + // Params: a, d + a: BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000'), + d: BigInt('0x2a9318e74bfa2b48f5fd9207e6bd7fd4292d7f6d37579d2601065fd6d6343eb1'), + // Finite field 𝔽p over which we'll do calculations + // Same value as bls12-381 Fr (not Fp) + Fp: (0, modular_js_1.Field)(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')), + // Subgroup order: how many points curve has + n: BigInt('0xe7db4ea6533afa906673b0101343b00a6682093ccc81082d0970e5ed6f72cb7'), + // Cofactor + h: BigInt(8), + // Base point (x, y) aka generator point + Gx: BigInt('0x11dafe5d23e1218086a365b99fbf3d3be72f6afd7d1f72623e6b071492d1122b'), + Gy: BigInt('0x1d523cf1ddab1a1793132e78c866c0c33e26ba5cc220fed7cc3f870e59d292aa'), + hash: sha512_1.sha512, + randomBytes: utils_1.randomBytes, +}); +const GH_FIRST_BLOCK = (0, utils_1.utf8ToBytes)('096b36a5804bfacef1691e173c366a47ff5ba84a44f26ddd7e8d9f79d5b42df0'); +// Returns point at JubJub curve which is prime order and not zero +function groupHash(tag, personalization) { + const h = blake2s_1.blake2s.create({ personalization, dkLen: 32 }); + h.update(GH_FIRST_BLOCK); + h.update(tag); + // NOTE: returns ExtendedPoint, in case it will be multiplied later + let p = exports.jubjub.ExtendedPoint.fromHex(h.digest()); + // NOTE: cannot replace with isSmallOrder, returns Point*8 + p = p.multiply(exports.jubjub.CURVE.h); + if (p.equals(exports.jubjub.ExtendedPoint.ZERO)) + throw new Error('Point has small order'); + return p; +} +exports.groupHash = groupHash; +function findGroupHash(m, personalization) { + const tag = (0, utils_1.concatBytes)(m, new Uint8Array([0])); + for (let i = 0; i < 256; i++) { + tag[tag.length - 1] = i; + try { + return groupHash(tag, personalization); + } + catch (e) { } + } + throw new Error('findGroupHash tag overflow'); +} +exports.findGroupHash = findGroupHash; +//# sourceMappingURL=jubjub.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/jubjub.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/jubjub.js.map new file mode 100644 index 0000000..08b1694 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/jubjub.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jubjub.js","sourceRoot":"","sources":["src/jubjub.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CAAC,aAAa,CAAC,IAAI,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC;IAClF,OAAO,CAAC,CAAC;AACX,CAAC;AAVD,8BAUC;AAED,SAAgB,aAAa,CAAC,CAAa,EAAE,eAA2B;IACtE,MAAM,GAAG,GAAG,IAAA,mBAAW,EAAC,CAAC,EAAE,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAChD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE;QAC5B,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;QACxB,IAAI;YACF,OAAO,SAAS,CAAC,GAAG,EAAE,eAAe,CAAC,CAAC;SACxC;QAAC,OAAO,CAAC,EAAE,GAAE;KACf;IACD,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;AAChD,CAAC;AATD,sCASC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/p256.d.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/p256.d.ts new file mode 100644 index 0000000..cf8c0d6 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/p256.d.ts @@ -0,0 +1,105 @@ +export declare const p256: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType | undefined) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const secp256r1: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType | undefined) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const hashToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +//# sourceMappingURL=p256.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/p256.d.ts.map b/node_modules/@scure/bip32/node_modules/@noble/curves/p256.d.ts.map new file mode 100644 index 0000000..d16f812 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/p256.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"p256.d.ts","sourceRoot":"","sources":["src/p256.ts"],"names":[],"mappings":"AAeA,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAWE,CAAC;AACpB,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAO,CAAC;AAmB9B,eAAO,MAAM,WAAW,uJAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,uJAA8C,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/p256.js b/node_modules/@scure/bip32/node_modules/@noble/curves/p256.js new file mode 100644 index 0000000..1e7e809 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/p256.js @@ -0,0 +1,45 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeToCurve = exports.hashToCurve = exports.secp256r1 = exports.p256 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const sha256_1 = require("@noble/hashes/sha256"); +const modular_js_1 = require("./abstract/modular.js"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +// NIST secp256r1 aka p256 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256 +const Fp = (0, modular_js_1.Field)(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff')); +const CURVE_A = Fp.create(BigInt('-3')); +const CURVE_B = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'); +// prettier-ignore +exports.p256 = (0, _shortw_utils_js_1.createCurve)({ + a: CURVE_A, + b: CURVE_B, + Fp, + // Curve order, total count of valid points in the field + n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'), + // Base (generator) point (x, y) + Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'), + Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'), + h: BigInt(1), + lowS: false, +}, sha256_1.sha256); +exports.secp256r1 = exports.p256; +const mapSWU = /* @__PURE__ */ (() => (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-10')), +}))(); +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.secp256r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P256_XMD:SHA-256_SSWU_RO_', + encodeDST: 'P256_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256_1.sha256, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +//# sourceMappingURL=p256.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/p256.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/p256.js.map new file mode 100644 index 0000000..0459df9 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/p256.js.map @@ -0,0 +1 @@ +{"version":3,"file":"p256.js","sourceRoot":"","sources":["src/p256.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,yDAAiD;AACjD,iDAA8C;AAC9C,sDAA8C;AAC9C,8DAAgE;AAChE,kEAA2D;AAE3D,0BAA0B;AAC1B,0EAA0E;AAE1E,MAAM,EAAE,GAAG,IAAA,kBAAK,EAAC,MAAM,CAAC,oEAAoE,CAAC,CAAC,CAAC;AAC/F,MAAM,OAAO,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AACxC,MAAM,OAAO,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAE7F,kBAAkB;AACL,QAAA,IAAI,GAAG,IAAA,8BAAW,EAAC;IAC9B,CAAC,EAAE,OAAO;IACV,CAAC,EAAE,OAAO;IACV,EAAE;IACF,wDAAwD;IACxD,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,gCAAgC;IAChC,EAAE,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAChF,EAAE,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAChF,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,IAAI,EAAE,KAAK;CACH,EAAE,eAAM,CAAC,CAAC;AACP,QAAA,SAAS,GAAG,YAAI,CAAC;AAE9B,MAAM,MAAM,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CACnC,IAAA,oCAAmB,EAAC,EAAE,EAAE;IACtB,CAAC,EAAE,OAAO;IACV,CAAC,EAAE,OAAO;IACV,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;CAC5B,CAAC,CAAC,EAAE,CAAC;AAER,MAAM,GAAG,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAChC,IAAA,+BAAY,EAAC,iBAAS,CAAC,eAAe,EAAE,CAAC,OAAiB,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE;IACjF,GAAG,EAAE,2BAA2B;IAChC,SAAS,EAAE,2BAA2B;IACtC,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,eAAM;CACb,CAAC,CAAC,EAAE,CAAC;AACK,QAAA,WAAW,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACxD,QAAA,aAAa,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/p384.d.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/p384.d.ts new file mode 100644 index 0000000..0be4254 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/p384.d.ts @@ -0,0 +1,105 @@ +export declare const p384: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType | undefined) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const secp384r1: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType | undefined) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const hashToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +//# sourceMappingURL=p384.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/p384.d.ts.map b/node_modules/@scure/bip32/node_modules/@noble/curves/p384.d.ts.map new file mode 100644 index 0000000..547746d --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/p384.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"p384.d.ts","sourceRoot":"","sources":["src/p384.ts"],"names":[],"mappings":"AAmBA,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAWE,CAAC;AACpB,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAO,CAAC;AAmB9B,eAAO,MAAM,WAAW,uJAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,uJAA8C,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/p384.js b/node_modules/@scure/bip32/node_modules/@noble/curves/p384.js new file mode 100644 index 0000000..d3a472b --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/p384.js @@ -0,0 +1,49 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeToCurve = exports.hashToCurve = exports.secp384r1 = exports.p384 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const sha512_1 = require("@noble/hashes/sha512"); +const modular_js_1 = require("./abstract/modular.js"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +// NIST secp384r1 aka p384 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-384 +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'); +const Fp = (0, modular_js_1.Field)(P); +const CURVE_A = Fp.create(BigInt('-3')); +// prettier-ignore +const CURVE_B = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'); +// prettier-ignore +exports.p384 = (0, _shortw_utils_js_1.createCurve)({ + a: CURVE_A, + b: CURVE_B, + Fp, + // Curve order, total count of valid points in the field. + n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'), + // Base (generator) point (x, y) + Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'), + Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'), + h: BigInt(1), + lowS: false, +}, sha512_1.sha384); +exports.secp384r1 = exports.p384; +const mapSWU = /* @__PURE__ */ (() => (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-12')), +}))(); +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.secp384r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P384_XMD:SHA-384_SSWU_RO_', + encodeDST: 'P384_XMD:SHA-384_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 192, + expand: 'xmd', + hash: sha512_1.sha384, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +//# sourceMappingURL=p384.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/p384.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/p384.js.map new file mode 100644 index 0000000..6816f0d --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/p384.js.map @@ -0,0 +1 @@ +{"version":3,"file":"p384.js","sourceRoot":"","sources":["src/p384.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,yDAAiD;AACjD,iDAA8C;AAC9C,sDAA8C;AAC9C,8DAAgE;AAChE,kEAA2D;AAE3D,0BAA0B;AAC1B,0EAA0E;AAE1E,0CAA0C;AAC1C,kBAAkB;AAClB,MAAM,CAAC,GAAG,MAAM,CAAC,oGAAoG,CAAC,CAAC;AACvH,MAAM,EAAE,GAAG,IAAA,kBAAK,EAAC,CAAC,CAAC,CAAC;AACpB,MAAM,OAAO,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AACxC,kBAAkB;AAClB,MAAM,OAAO,GAAG,MAAM,CAAC,oGAAoG,CAAC,CAAC;AAE7H,kBAAkB;AACL,QAAA,IAAI,GAAG,IAAA,8BAAW,EAAC;IAC9B,CAAC,EAAE,OAAO;IACV,CAAC,EAAE,OAAO;IACV,EAAE;IACF,yDAAyD;IACzD,CAAC,EAAE,MAAM,CAAC,oGAAoG,CAAC;IAC/G,gCAAgC;IAChC,EAAE,EAAE,MAAM,CAAC,oGAAoG,CAAC;IAChH,EAAE,EAAE,MAAM,CAAC,oGAAoG,CAAC;IAChH,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,IAAI,EAAE,KAAK;CACH,EAAE,eAAM,CAAC,CAAC;AACP,QAAA,SAAS,GAAG,YAAI,CAAC;AAE9B,MAAM,MAAM,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CACnC,IAAA,oCAAmB,EAAC,EAAE,EAAE;IACtB,CAAC,EAAE,OAAO;IACV,CAAC,EAAE,OAAO;IACV,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;CAC5B,CAAC,CAAC,EAAE,CAAC;AAER,MAAM,GAAG,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAChC,IAAA,+BAAY,EAAC,iBAAS,CAAC,eAAe,EAAE,CAAC,OAAiB,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE;IACjF,GAAG,EAAE,2BAA2B;IAChC,SAAS,EAAE,2BAA2B;IACtC,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,eAAM;CACb,CAAC,CAAC,EAAE,CAAC;AACK,QAAA,WAAW,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACxD,QAAA,aAAa,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/p521.d.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/p521.d.ts new file mode 100644 index 0000000..47cca46 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/p521.d.ts @@ -0,0 +1,105 @@ +export declare const p521: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType | undefined) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const secp521r1: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType | undefined) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const hashToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +//# sourceMappingURL=p521.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/p521.d.ts.map b/node_modules/@scure/bip32/node_modules/@noble/curves/p521.d.ts.map new file mode 100644 index 0000000..1c3cdaa --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/p521.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"p521.d.ts","sourceRoot":"","sources":["src/p521.ts"],"names":[],"mappings":"AAmCA,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAWE,CAAC;AACpB,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAO,CAAC;AAmB9B,eAAO,MAAM,WAAW,uJAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,uJAA8C,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/p521.js b/node_modules/@scure/bip32/node_modules/@noble/curves/p521.js new file mode 100644 index 0000000..c1c0e22 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/p521.js @@ -0,0 +1,56 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeToCurve = exports.hashToCurve = exports.secp521r1 = exports.p521 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const sha512_1 = require("@noble/hashes/sha512"); +const modular_js_1 = require("./abstract/modular.js"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +// NIST secp521r1 aka p521 +// Note that it's 521, which differs from 512 of its hash function. +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-521 +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const Fp = (0, modular_js_1.Field)(P); +const CURVE = { + a: Fp.create(BigInt('-3')), + b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'), + Fp, + n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'), + Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'), + Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'), + h: BigInt(1), +}; +// prettier-ignore +exports.p521 = (0, _shortw_utils_js_1.createCurve)({ + a: CURVE.a, + b: CURVE.b, + Fp, + // Curve order, total count of valid points in the field + n: CURVE.n, + Gx: CURVE.Gx, + Gy: CURVE.Gy, + h: CURVE.h, + lowS: false, + allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b +}, sha512_1.sha512); +exports.secp521r1 = exports.p521; +const mapSWU = /* @__PURE__ */ (() => (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, { + A: CURVE.a, + B: CURVE.b, + Z: Fp.create(BigInt('-4')), +}))(); +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.secp521r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P521_XMD:SHA-512_SSWU_RO_', + encodeDST: 'P521_XMD:SHA-512_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 256, + expand: 'xmd', + hash: sha512_1.sha512, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +//# sourceMappingURL=p521.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/p521.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/p521.js.map new file mode 100644 index 0000000..f79e5f0 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/p521.js.map @@ -0,0 +1 @@ +{"version":3,"file":"p521.js","sourceRoot":"","sources":["src/p521.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,yDAAiD;AACjD,iDAA8C;AAC9C,sDAA8C;AAC9C,8DAAgE;AAChE,kEAA2D;AAE3D,0BAA0B;AAC1B,mEAAmE;AACnE,0EAA0E;AAE1E,0CAA0C;AAC1C,kBAAkB;AAClB,MAAM,CAAC,GAAG,MAAM,CAAC,uIAAuI,CAAC,CAAC;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AiB,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE;IACjF,GAAG,EAAE,2BAA2B;IAChC,SAAS,EAAE,2BAA2B;IACtC,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,eAAM;CACb,CAAC,CAAC,EAAE,CAAC;AACK,QAAA,WAAW,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACxD,QAAA,aAAa,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/package.json b/node_modules/@scure/bip32/node_modules/@noble/curves/package.json new file mode 100644 index 0000000..8d59a95 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/package.json @@ -0,0 +1,180 @@ +{ + "name": "@noble/curves", + "version": "1.1.0", + "description": "Audited & minimal JS implementation of elliptic curve cryptography", + "files": [ + "abstract", + "esm", + "src", + "*.js", + "*.js.map", + "*.d.ts", + "*.d.ts.map" + ], + "scripts": { + "bench": "cd benchmark; node secp256k1.js; node curves.js; node ecdh.js; node hash-to-curve.js; node modular.js; node bls.js", + "build": "tsc && tsc -p tsconfig.esm.json", + "build:release": "rollup -c rollup.config.js", + "build:clean": "rm *.{js,d.ts,d.ts.map,js.map} esm/*.{js,d.ts,d.ts.map,js.map} 2> /dev/null", + "lint": "prettier --check 'src/**/*.{js,ts}' 'test/*.js'", + "format": "prettier --write 'src/**/*.{js,ts}' 'test/*.js'", + "test": "node test/index.test.js" + }, + "author": "Paul Miller (https://paulmillr.com)", + "homepage": "https://paulmillr.com/noble/", + "repository": { + "type": "git", + "url": "https://github.com/paulmillr/noble-curves.git" + }, + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.3.1" + }, + "devDependencies": { + "fast-check": "3.0.0", + "micro-bmark": "0.3.1", + "micro-should": "0.4.0", + "prettier": "2.8.4", + "typescript": "5.0.2" + }, + "main": "index.js", + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./esm/index.js", + "default": "./index.js" + }, + "./abstract/edwards": { + "types": "./abstract/edwards.d.ts", + "import": "./esm/abstract/edwards.js", + "default": "./abstract/edwards.js" + }, + "./abstract/modular": { + "types": "./abstract/modular.d.ts", + "import": "./esm/abstract/modular.js", + "default": "./abstract/modular.js" + }, + "./abstract/montgomery": { + "types": "./abstract/montgomery.d.ts", + "import": "./esm/abstract/montgomery.js", + "default": "./abstract/montgomery.js" + }, + "./abstract/weierstrass": { + "types": "./abstract/weierstrass.d.ts", + "import": "./esm/abstract/weierstrass.js", + "default": "./abstract/weierstrass.js" + }, + "./abstract/bls": { + "types": "./abstract/bls.d.ts", + "import": "./esm/abstract/bls.js", + "default": "./abstract/bls.js" + }, + "./abstract/hash-to-curve": { + "types": "./abstract/hash-to-curve.d.ts", + "import": "./esm/abstract/hash-to-curve.js", + "default": "./abstract/hash-to-curve.js" + }, + "./abstract/curve": { + "types": "./abstract/curve.d.ts", + "import": "./esm/abstract/curve.js", + "default": "./abstract/curve.js" + }, + "./abstract/utils": { + "types": "./abstract/utils.d.ts", + "import": "./esm/abstract/utils.js", + "default": "./abstract/utils.js" + }, + "./abstract/poseidon": { + "types": "./abstract/poseidon.d.ts", + "import": "./esm/abstract/poseidon.js", + "default": "./abstract/poseidon.js" + }, + "./_shortw_utils": { + "types": "./_shortw_utils.d.ts", + "import": "./esm/_shortw_utils.js", + "default": "./_shortw_utils.js" + }, + "./bls12-381": { + "types": "./bls12-381.d.ts", + "import": "./esm/bls12-381.js", + "default": "./bls12-381.js" + }, + "./bn254": { + "types": "./bn254.d.ts", + "import": "./esm/bn254.js", + "default": "./bn254.js" + }, + "./ed25519": { + "types": "./ed25519.d.ts", + "import": "./esm/ed25519.js", + "default": "./ed25519.js" + }, + "./ed448": { + "types": "./ed448.d.ts", + "import": "./esm/ed448.js", + "default": "./ed448.js" + }, + "./index": { + "types": "./index.d.ts", + "import": "./esm/index.js", + "default": "./index.js" + }, + "./jubjub": { + "types": "./jubjub.d.ts", + "import": "./esm/jubjub.js", + "default": "./jubjub.js" + }, + "./p256": { + "types": "./p256.d.ts", + "import": "./esm/p256.js", + "default": "./p256.js" + }, + "./p384": { + "types": "./p384.d.ts", + "import": "./esm/p384.js", + "default": "./p384.js" + }, + "./p521": { + "types": "./p521.d.ts", + "import": "./esm/p521.js", + "default": "./p521.js" + }, + "./pasta": { + "types": "./pasta.d.ts", + "import": "./esm/pasta.js", + "default": "./pasta.js" + }, + "./secp256k1": { + "types": "./secp256k1.d.ts", + "import": "./esm/secp256k1.js", + "default": "./secp256k1.js" + } + }, + "keywords": [ + "elliptic", + "curve", + "cryptography", + "weierstrass", + "montgomery", + "edwards", + "p256", + "p384", + "p521", + "secp256r1", + "secp256k1", + "ed25519", + "ed448", + "x25519", + "ed25519", + "bls12-381", + "bn254", + "pasta", + "bls", + "noble", + "ecc", + "ecdsa", + "eddsa", + "schnorr" + ], + "funding": "https://paulmillr.com/funding/" +} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/pasta.d.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/pasta.d.ts new file mode 100644 index 0000000..9e1f4ed --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/pasta.d.ts @@ -0,0 +1,5 @@ +export declare const p: bigint; +export declare const q: bigint; +export declare const pallas: import("./abstract/weierstrass.js").CurveFn; +export declare const vesta: import("./abstract/weierstrass.js").CurveFn; +//# sourceMappingURL=pasta.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/pasta.d.ts.map b/node_modules/@scure/bip32/node_modules/@noble/curves/pasta.d.ts.map new file mode 100644 index 0000000..d4e6dd5 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/pasta.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"pasta.d.ts","sourceRoot":"","sources":["src/pasta.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,CAAC,QAA+E,CAAC;AAC9F,eAAO,MAAM,CAAC,QAA+E,CAAC;AAG9F,eAAO,MAAM,MAAM,6CASjB,CAAC;AAEH,eAAO,MAAM,KAAK,6CAShB,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/pasta.js b/node_modules/@scure/bip32/node_modules/@noble/curves/pasta.js new file mode 100644 index 0000000..c3bee21 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/pasta.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.vesta = exports.pallas = exports.q = exports.p = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha256_1 = require("@noble/hashes/sha256"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const mod = require("./abstract/modular.js"); +exports.p = BigInt('0x40000000000000000000000000000000224698fc094cf91b992d30ed00000001'); +exports.q = BigInt('0x40000000000000000000000000000000224698fc0994a8dd8c46eb2100000001'); +// https://neuromancer.sk/std/other/Pallas +exports.pallas = (0, weierstrass_js_1.weierstrass)({ + a: BigInt(0), + b: BigInt(5), + Fp: mod.Field(exports.p), + n: exports.q, + Gx: mod.mod(BigInt(-1), exports.p), + Gy: BigInt(2), + h: BigInt(1), + ...(0, _shortw_utils_js_1.getHash)(sha256_1.sha256), +}); +// https://neuromancer.sk/std/other/Vesta +exports.vesta = (0, weierstrass_js_1.weierstrass)({ + a: BigInt(0), + b: BigInt(5), + Fp: mod.Field(exports.q), + n: exports.p, + Gx: mod.mod(BigInt(-1), exports.q), + Gy: BigInt(2), + h: BigInt(1), + ...(0, _shortw_utils_js_1.getHash)(sha256_1.sha256), +}); +//# sourceMappingURL=pasta.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/pasta.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/pasta.js.map new file mode 100644 index 0000000..5ea530c --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/pasta.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pasta.js","sourceRoot":"","sources":["src/pasta.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,iDAA8C;AAC9C,8DAAwD;AACxD,yDAA6C;AAC7C,6CAA6C;AAEhC,QAAA,CAAC,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AACjF,QAAA,CAAC,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAE9F,0CAA0C;AAC7B,QAAA,MAAM,GAAG,IAAA,4BAAW,EAAC;IAChC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,SAAC,CAAC;IAChB,CAAC,EAAE,SAAC;IACJ,EAAE,EAAE,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,SAAC,CAAC;IAC1B,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,IAAA,0BAAO,EAAC,eAAM,CAAC;CACnB,CAAC,CAAC;AACH,yCAAyC;AAC5B,QAAA,KAAK,GAAG,IAAA,4BAAW,EAAC;IAC/B,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,SAAC,CAAC;IAChB,CAAC,EAAE,SAAC;IACJ,EAAE,EAAE,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,SAAC,CAAC;IAC1B,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,IAAA,0BAAO,EAAC,eAAM,CAAC;CACnB,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/secp256k1.d.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/secp256k1.d.ts new file mode 100644 index 0000000..b94df77 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/secp256k1.d.ts @@ -0,0 +1,93 @@ +import { mod } from './abstract/modular.js'; +import { ProjPointType as PointType } from './abstract/weierstrass.js'; +import type { Hex, PrivKey } from './abstract/utils.js'; +import { bytesToNumberBE, numberToBytesBE } from './abstract/utils.js'; +export declare const secp256k1: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: PointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: PointType) => PointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: Hex, privKey: PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: Hex | { + r: bigint; + s: bigint; + }, msgHash: Hex, publicKey: Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: PrivKey) => bigint; + isValidPrivateKey(privateKey: PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: PointType | undefined) => PointType; + }; +}>; +declare function taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array; +/** + * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point. + * @returns valid point checked for being on-curve + */ +declare function lift_x(x: bigint): PointType; +/** + * Schnorr public key is just `x` coordinate of Point as per BIP340. + */ +declare function schnorrGetPublicKey(privateKey: Hex): Uint8Array; +/** + * Creates Schnorr signature as per BIP340. Verifies itself before returning anything. + * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous. + */ +declare function schnorrSign(message: Hex, privateKey: PrivKey, auxRand?: Hex): Uint8Array; +/** + * Verifies Schnorr signature. + * Will swallow errors & return false except for initial type validation of arguments. + */ +declare function schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean; +export declare const schnorr: { + getPublicKey: typeof schnorrGetPublicKey; + sign: typeof schnorrSign; + verify: typeof schnorrVerify; + utils: { + randomPrivateKey: () => Uint8Array; + lift_x: typeof lift_x; + pointToBytes: (point: PointType) => Uint8Array; + numberToBytesBE: typeof numberToBytesBE; + bytesToNumberBE: typeof bytesToNumberBE; + taggedHash: typeof taggedHash; + mod: typeof mod; + }; +}; +export declare const hashToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +export {}; +//# sourceMappingURL=secp256k1.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/secp256k1.d.ts.map b/node_modules/@scure/bip32/node_modules/@noble/curves/secp256k1.d.ts.map new file mode 100644 index 0000000..c6ddafc --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/secp256k1.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"secp256k1.d.ts","sourceRoot":"","sources":["src/secp256k1.ts"],"names":[],"mappings":"AAGA,OAAO,EAAS,GAAG,EAAQ,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,aAAa,IAAI,SAAS,EAAuB,MAAM,2BAA2B,CAAC;AAC5F,OAAO,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,eAAe,EAA4B,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAwCjG,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA2CrB,CAAC;AASF,iBAAS,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,QAAQ,EAAE,UAAU,EAAE,GAAG,UAAU,CAQtE;AAkBD;;;GAGG;AACH,iBAAS,MAAM,CAAC,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC,MAAM,CAAC,CAS5C;AAQD;;GAEG;AACH,iBAAS,mBAAmB,CAAC,UAAU,EAAE,GAAG,GAAG,UAAU,CAExD;AAED;;;GAGG;AACH,iBAAS,WAAW,CAClB,OAAO,EAAE,GAAG,EACZ,UAAU,EAAE,OAAO,EACnB,OAAO,GAAE,GAAqB,GAC7B,UAAU,CAgBZ;AAED;;;GAGG;AACH,iBAAS,aAAa,CAAC,SAAS,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,GAAG,OAAO,CAiB5E;AAED,eAAO,MAAM,OAAO;;;;;;;8BA5FS,UAAU,MAAM,CAAC;;;;;;CAyGzC,CAAC;AA0DN,eAAO,MAAM,WAAW,uJAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,uJAA8C,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/secp256k1.js b/node_modules/@scure/bip32/node_modules/@noble/curves/secp256k1.js new file mode 100644 index 0000000..463edcc --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/secp256k1.js @@ -0,0 +1,257 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeToCurve = exports.hashToCurve = exports.schnorr = exports.secp256k1 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha256_1 = require("@noble/hashes/sha256"); +const utils_1 = require("@noble/hashes/utils"); +const modular_js_1 = require("./abstract/modular.js"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const utils_js_1 = require("./abstract/utils.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'); +const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); +const _1n = BigInt(1); +const _2n = BigInt(2); +const divNearest = (a, b) => (a + b / _2n) / b; +/** + * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit. + * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00] + */ +function sqrtMod(y) { + const P = secp256k1P; + // prettier-ignore + const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + // prettier-ignore + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = (y * y * y) % P; // x^3, 11 + const b3 = (b2 * b2 * y) % P; // x^7 + const b6 = ((0, modular_js_1.pow2)(b3, _3n, P) * b3) % P; + const b9 = ((0, modular_js_1.pow2)(b6, _3n, P) * b3) % P; + const b11 = ((0, modular_js_1.pow2)(b9, _2n, P) * b2) % P; + const b22 = ((0, modular_js_1.pow2)(b11, _11n, P) * b11) % P; + const b44 = ((0, modular_js_1.pow2)(b22, _22n, P) * b22) % P; + const b88 = ((0, modular_js_1.pow2)(b44, _44n, P) * b44) % P; + const b176 = ((0, modular_js_1.pow2)(b88, _88n, P) * b88) % P; + const b220 = ((0, modular_js_1.pow2)(b176, _44n, P) * b44) % P; + const b223 = ((0, modular_js_1.pow2)(b220, _3n, P) * b3) % P; + const t1 = ((0, modular_js_1.pow2)(b223, _23n, P) * b22) % P; + const t2 = ((0, modular_js_1.pow2)(t1, _6n, P) * b2) % P; + const root = (0, modular_js_1.pow2)(t2, _2n, P); + if (!Fp.eql(Fp.sqr(root), y)) + throw new Error('Cannot find square root'); + return root; +} +const Fp = (0, modular_js_1.Field)(secp256k1P, undefined, undefined, { sqrt: sqrtMod }); +exports.secp256k1 = (0, _shortw_utils_js_1.createCurve)({ + a: BigInt(0), + b: BigInt(7), + Fp, + n: secp256k1N, + // Base point (x, y) aka generator point + Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), + Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), + h: BigInt(1), + lowS: true, + /** + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 + */ + endo: { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + splitScalar: (k) => { + const n = secp256k1N; + const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); + const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); + const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); + const b2 = a1; + const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16) + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = (0, modular_js_1.mod)(k - c1 * a1 - c2 * a2, n); + let k2 = (0, modular_js_1.mod)(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) + k1 = n - k1; + if (k2neg) + k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error('splitScalar: Endomorphism failed, k=' + k); + } + return { k1neg, k1, k2neg, k2 }; + }, + }, +}, sha256_1.sha256); +// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code. +// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki +const _0n = BigInt(0); +const fe = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1P; +const ge = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1N; +/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */ +const TAGGED_HASH_PREFIXES = {}; +function taggedHash(tag, ...messages) { + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === undefined) { + const tagH = (0, sha256_1.sha256)(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + tagP = (0, utils_js_1.concatBytes)(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return (0, sha256_1.sha256)((0, utils_js_1.concatBytes)(tagP, ...messages)); +} +// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03 +const pointToBytes = (point) => point.toRawBytes(true).slice(1); +const numTo32b = (n) => (0, utils_js_1.numberToBytesBE)(n, 32); +const modP = (x) => (0, modular_js_1.mod)(x, secp256k1P); +const modN = (x) => (0, modular_js_1.mod)(x, secp256k1N); +const Point = exports.secp256k1.ProjectivePoint; +const GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b); +// Calculate point, scalar and bytes +function schnorrGetExtPubKey(priv) { + let d_ = exports.secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey + let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside + const scalar = p.hasEvenY() ? d_ : modN(-d_); + return { scalar: scalar, bytes: pointToBytes(p) }; +} +/** + * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point. + * @returns valid point checked for being on-curve + */ +function lift_x(x) { + if (!fe(x)) + throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p. + const xx = modP(x * x); + const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p. + let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p. + if (y % _2n !== _0n) + y = modP(-y); // Return the unique point P such that x(P) = x and + const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise. + p.assertValidity(); + return p; +} +/** + * Create tagged hash, convert it to bigint, reduce modulo-n. + */ +function challenge(...args) { + return modN((0, utils_js_1.bytesToNumberBE)(taggedHash('BIP0340/challenge', ...args))); +} +/** + * Schnorr public key is just `x` coordinate of Point as per BIP340. + */ +function schnorrGetPublicKey(privateKey) { + return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G) +} +/** + * Creates Schnorr signature as per BIP340. Verifies itself before returning anything. + * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous. + */ +function schnorrSign(message, privateKey, auxRand = (0, utils_1.randomBytes)(32)) { + const m = (0, utils_js_1.ensureBytes)('message', message); + const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder + const a = (0, utils_js_1.ensureBytes)('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array + const t = numTo32b(d ^ (0, utils_js_1.bytesToNumberBE)(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a) + const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m) + const k_ = modN((0, utils_js_1.bytesToNumberBE)(rand)); // Let k' = int(rand) mod n + if (k_ === _0n) + throw new Error('sign failed: k is zero'); // Fail if k' = 0. + const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G. + const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n. + const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n). + sig.set(rx, 0); + sig.set(numTo32b(modN(k + e * d)), 32); + // If Verify(bytes(P), m, sig) (see below) returns failure, abort + if (!schnorrVerify(sig, m, px)) + throw new Error('sign: Invalid signature produced'); + return sig; +} +/** + * Verifies Schnorr signature. + * Will swallow errors & return false except for initial type validation of arguments. + */ +function schnorrVerify(signature, message, publicKey) { + const sig = (0, utils_js_1.ensureBytes)('signature', signature, 64); + const m = (0, utils_js_1.ensureBytes)('message', message); + const pub = (0, utils_js_1.ensureBytes)('publicKey', publicKey, 32); + try { + const P = lift_x((0, utils_js_1.bytesToNumberBE)(pub)); // P = lift_x(int(pk)); fail if that fails + const r = (0, utils_js_1.bytesToNumberBE)(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p. + if (!fe(r)) + return false; + const s = (0, utils_js_1.bytesToNumberBE)(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n. + if (!ge(s)) + return false; + const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n + const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P + if (!R || !R.hasEvenY() || R.toAffine().x !== r) + return false; // -eP == (n-e)P + return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r. + } + catch (error) { + return false; + } +} +exports.schnorr = (() => ({ + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + utils: { + randomPrivateKey: exports.secp256k1.utils.randomPrivateKey, + lift_x, + pointToBytes, + numberToBytesBE: utils_js_1.numberToBytesBE, + bytesToNumberBE: utils_js_1.bytesToNumberBE, + taggedHash, + mod: modular_js_1.mod, + }, +}))(); +const isoMap = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.isogenyMap)(Fp, [ + // xNum + [ + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7', + '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581', + '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262', + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c', + ], + // xDen + [ + '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b', + '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c', + '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3', + '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931', + '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84', + ], + // yDen + [ + '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b', + '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573', + '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], +].map((i) => i.map((j) => BigInt(j)))))(); +const mapSWU = /* @__PURE__ */ (() => (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, { + A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'), + B: BigInt('1771'), + Z: Fp.create(BigInt('-11')), +}))(); +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.secp256k1.ProjectivePoint, (scalars) => { + const { x, y } = mapSWU(Fp.create(scalars[0])); + return isoMap(x, y); +}, { + DST: 'secp256k1_XMD:SHA-256_SSWU_RO_', + encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256_1.sha256, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +//# sourceMappingURL=secp256k1.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/secp256k1.js.map b/node_modules/@scure/bip32/node_modules/@noble/curves/secp256k1.js.map new file mode 100644 index 0000000..4d76de2 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/secp256k1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"secp256k1.js","sourceRoot":"","sources":["src/secp256k1.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,iDAA8C;AAC9C,+CAAkD;AAClD,sDAAyD;AACzD,8DAA4F;AAE5F,kDAAiG;AACjG,kEAAuE;AACvE,yDAAiD;AAEjD,MAAM,UAAU,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAChG,MAAM,UAAU,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAChG,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,UAAU,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,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AAE,CAChC,IAAA,+BAAY,EACV,iBAAS,CAAC,eAAe,EACzB,CAAC,OAAiB,EAAE,EAAE;IACpB,MAAM,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/C,OAAO,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AACtB,CAAC,EACD;IACE,GAAG,EAAE,gCAAgC;IACrC,SAAS,EAAE,gCAAgC;IAC3C,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,eAAM;CACb,CACF,CAAC,EAAE,CAAC;AACM,QAAA,WAAW,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACxD,QAAA,aAAa,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/src/_shortw_utils.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/src/_shortw_utils.ts new file mode 100644 index 0000000..3ae5ca4 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/src/_shortw_utils.ts @@ -0,0 +1,20 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { hmac } from '@noble/hashes/hmac'; +import { concatBytes, randomBytes } from '@noble/hashes/utils'; +import { weierstrass, CurveType } from './abstract/weierstrass.js'; +import { CHash } from './abstract/utils.js'; + +// connects noble-curves to noble-hashes +export function getHash(hash: CHash) { + return { + hash, + hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(hash, key, concatBytes(...msgs)), + randomBytes, + }; +} +// Same API as @noble/hashes, with ability to create curve with custom hash +type CurveDef = Readonly>; +export function createCurve(curveDef: CurveDef, defHash: CHash) { + const create = (hash: CHash) => weierstrass({ ...curveDef, ...getHash(hash) }); + return Object.freeze({ ...create(defHash), create }); +} diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/bls.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/bls.ts new file mode 100644 index 0000000..7e965b2 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/bls.ts @@ -0,0 +1,398 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +/** + * BLS (Barreto-Lynn-Scott) family of pairing-friendly curves. + * Implements BLS (Boneh-Lynn-Shacham) signatures. + * Consists of two curves: G1 and G2: + * - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4. + * - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1 + * - Gt, created by bilinear (ate) pairing e(G1, G2), consists of p-th roots of unity in + * Fq^k where k is embedding degree. Only degree 12 is currently supported, 24 is not. + * Pairing is used to aggregate and verify signatures. + * We are using Fp for private keys (shorter) and Fp₂ for signatures (longer). + * Some projects may prefer to swap this relation, it is not supported for now. + */ +import { AffinePoint } from './curve.js'; +import { IField, hashToPrivateScalar } from './modular.js'; +import { Hex, PrivKey, CHash, bitLen, bitGet, ensureBytes } from './utils.js'; +import * as htf from './hash-to-curve.js'; +import { + CurvePointsType, + ProjPointType as ProjPointType, + CurvePointsRes, + weierstrassPoints, +} from './weierstrass.js'; + +type Fp = bigint; // Can be different field? + +// prettier-ignore +const _2n = BigInt(2), _3n = BigInt(3); + +export type SignatureCoder = { + fromHex(hex: Hex): ProjPointType; + toRawBytes(point: ProjPointType): Uint8Array; + toHex(point: ProjPointType): string; +}; + +export type CurveType = { + G1: Omit, 'n'> & { + mapToCurve: htf.MapToCurve; + htfDefaults: htf.Opts; + }; + G2: Omit, 'n'> & { + Signature: SignatureCoder; + mapToCurve: htf.MapToCurve; + htfDefaults: htf.Opts; + }; + fields: { + Fp: IField; + Fr: IField; + Fp2: IField & { + reim: (num: Fp2) => { re: bigint; im: bigint }; + multiplyByB: (num: Fp2) => Fp2; + frobeniusMap(num: Fp2, power: number): Fp2; + }; + Fp6: IField; + Fp12: IField & { + frobeniusMap(num: Fp12, power: number): Fp12; + multiplyBy014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12; + conjugate(num: Fp12): Fp12; + finalExponentiate(num: Fp12): Fp12; + }; + }; + params: { + x: bigint; + r: bigint; + }; + htfDefaults: htf.Opts; + hash: CHash; // Because we need outputLen for DRBG + randomBytes: (bytesLength?: number) => Uint8Array; +}; + +export type CurveFn = { + getPublicKey: (privateKey: PrivKey) => Uint8Array; + sign: { + (message: Hex, privateKey: PrivKey): Uint8Array; + (message: ProjPointType, privateKey: PrivKey): ProjPointType; + }; + verify: ( + signature: Hex | ProjPointType, + message: Hex | ProjPointType, + publicKey: Hex | ProjPointType + ) => boolean; + verifyBatch: ( + signature: Hex | ProjPointType, + messages: (Hex | ProjPointType)[], + publicKeys: (Hex | ProjPointType)[] + ) => boolean; + aggregatePublicKeys: { + (publicKeys: Hex[]): Uint8Array; + (publicKeys: ProjPointType[]): ProjPointType; + }; + aggregateSignatures: { + (signatures: Hex[]): Uint8Array; + (signatures: ProjPointType[]): ProjPointType; + }; + millerLoop: (ell: [Fp2, Fp2, Fp2][], g1: [Fp, Fp]) => Fp12; + pairing: (P: ProjPointType, Q: ProjPointType, withFinalExponent?: boolean) => Fp12; + G1: CurvePointsRes & ReturnType>; + G2: CurvePointsRes & ReturnType>; + Signature: SignatureCoder; + params: { + x: bigint; + r: bigint; + G1b: bigint; + G2b: Fp2; + }; + fields: { + Fp: IField; + Fp2: IField; + Fp6: IField; + Fp12: IField; + Fr: IField; + }; + utils: { + randomPrivateKey: () => Uint8Array; + calcPairingPrecomputes: (p: AffinePoint) => [Fp2, Fp2, Fp2][]; + }; +}; + +export function bls( + CURVE: CurveType +): CurveFn { + // Fields are specific for curve, so for now we'll need to pass them with opts + const { Fp, Fr, Fp2, Fp6, Fp12 } = CURVE.fields; + const BLS_X_LEN = bitLen(CURVE.params.x); + const groupLen = 32; // TODO: calculate; hardcoded for now + + // Pre-compute coefficients for sparse multiplication + // Point addition and point double calculations is reused for coefficients + function calcPairingPrecomputes(p: AffinePoint) { + const { x, y } = p; + // prettier-ignore + const Qx = x, Qy = y, Qz = Fp2.ONE; + // prettier-ignore + let Rx = Qx, Ry = Qy, Rz = Qz; + let ell_coeff: [Fp2, Fp2, Fp2][] = []; + for (let i = BLS_X_LEN - 2; i >= 0; i--) { + // Double + let t0 = Fp2.sqr(Ry); // Ry² + let t1 = Fp2.sqr(Rz); // Rz² + let t2 = Fp2.multiplyByB(Fp2.mul(t1, _3n)); // 3 * T1 * B + let t3 = Fp2.mul(t2, _3n); // 3 * T2 + let t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0); // (Ry + Rz)² - T1 - T0 + ell_coeff.push([ + Fp2.sub(t2, t0), // T2 - T0 + Fp2.mul(Fp2.sqr(Rx), _3n), // 3 * Rx² + Fp2.neg(t4), // -T4 + ]); + Rx = Fp2.div(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), _2n); // ((T0 - T3) * Rx * Ry) / 2 + Ry = Fp2.sub(Fp2.sqr(Fp2.div(Fp2.add(t0, t3), _2n)), Fp2.mul(Fp2.sqr(t2), _3n)); // ((T0 + T3) / 2)² - 3 * T2² + Rz = Fp2.mul(t0, t4); // T0 * T4 + if (bitGet(CURVE.params.x, i)) { + // Addition + let t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); // Ry - Qy * Rz + let t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz)); // Rx - Qx * Rz + ell_coeff.push([ + Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy)), // T0 * Qx - T1 * Qy + Fp2.neg(t0), // -T0 + t1, // T1 + ]); + let t2 = Fp2.sqr(t1); // T1² + let t3 = Fp2.mul(t2, t1); // T2 * T1 + let t4 = Fp2.mul(t2, Rx); // T2 * Rx + let t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n)), Fp2.mul(Fp2.sqr(t0), Rz)); // T3 - 2 * T4 + T0² * Rz + Rx = Fp2.mul(t1, t5); // T1 * T5 + Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry)); // (T4 - T5) * T0 - T3 * Ry + Rz = Fp2.mul(Rz, t3); // Rz * T3 + } + } + return ell_coeff; + } + + function millerLoop(ell: [Fp2, Fp2, Fp2][], g1: [Fp, Fp]): Fp12 { + const { x } = CURVE.params; + const Px = g1[0]; + const Py = g1[1]; + let f12 = Fp12.ONE; + for (let j = 0, i = BLS_X_LEN - 2; i >= 0; i--, j++) { + const E = ell[j]; + f12 = Fp12.multiplyBy014(f12, E[0], Fp2.mul(E[1], Px), Fp2.mul(E[2], Py)); + if (bitGet(x, i)) { + j += 1; + const F = ell[j]; + f12 = Fp12.multiplyBy014(f12, F[0], Fp2.mul(F[1], Px), Fp2.mul(F[2], Py)); + } + if (i !== 0) f12 = Fp12.sqr(f12); + } + return Fp12.conjugate(f12); + } + + const utils = { + randomPrivateKey: (): Uint8Array => { + return Fr.toBytes(hashToPrivateScalar(CURVE.randomBytes(groupLen + 8), CURVE.params.r)); + }, + calcPairingPrecomputes, + }; + + // Point on G1 curve: (x, y) + const G1_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G1 }); + const G1 = Object.assign( + G1_, + htf.createHasher(G1_.ProjectivePoint, CURVE.G1.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G1.htfDefaults, + }) + ); + + // Sparse multiplication against precomputed coefficients + // TODO: replace with weakmap? + type withPairingPrecomputes = { _PPRECOMPUTES: [Fp2, Fp2, Fp2][] | undefined }; + function pairingPrecomputes(point: G2): [Fp2, Fp2, Fp2][] { + const p = point as G2 & withPairingPrecomputes; + if (p._PPRECOMPUTES) return p._PPRECOMPUTES; + p._PPRECOMPUTES = calcPairingPrecomputes(point.toAffine()); + return p._PPRECOMPUTES; + } + + // TODO: export + // function clearPairingPrecomputes(point: G2) { + // const p = point as G2 & withPairingPrecomputes; + // p._PPRECOMPUTES = undefined; + // } + + // Point on G2 curve (complex numbers): (x₁, x₂+i), (y₁, y₂+i) + const G2_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G2 }); + const G2 = Object.assign( + G2_, + htf.createHasher(G2_.ProjectivePoint as htf.H2CPointConstructor, CURVE.G2.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G2.htfDefaults, + }) + ); + + const { Signature } = CURVE.G2; + + // Calculates bilinear pairing + function pairing(Q: G1, P: G2, withFinalExponent: boolean = true): Fp12 { + if (Q.equals(G1.ProjectivePoint.ZERO) || P.equals(G2.ProjectivePoint.ZERO)) + throw new Error('pairing is not available for ZERO point'); + Q.assertValidity(); + P.assertValidity(); + // Performance: 9ms for millerLoop and ~14ms for exp. + const Qa = Q.toAffine(); + const looped = millerLoop(pairingPrecomputes(P), [Qa.x, Qa.y]); + return withFinalExponent ? Fp12.finalExponentiate(looped) : looped; + } + type G1 = typeof G1.ProjectivePoint.BASE; + type G2 = typeof G2.ProjectivePoint.BASE; + + type G1Hex = Hex | G1; + type G2Hex = Hex | G2; + function normP1(point: G1Hex): G1 { + return point instanceof G1.ProjectivePoint ? (point as G1) : G1.ProjectivePoint.fromHex(point); + } + function normP2(point: G2Hex): G2 { + return point instanceof G2.ProjectivePoint ? point : Signature.fromHex(point); + } + function normP2Hash(point: G2Hex, htfOpts?: htf.htfBasicOpts): G2 { + return point instanceof G2.ProjectivePoint + ? point + : (G2.hashToCurve(ensureBytes('point', point), htfOpts) as G2); + } + + // Multiplies generator by private key. + // P = pk x G + function getPublicKey(privateKey: PrivKey): Uint8Array { + return G1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true); + } + + // Executes `hashToCurve` on the message and then multiplies the result by private key. + // S = pk x H(m) + function sign(message: Hex, privateKey: PrivKey, htfOpts?: htf.htfBasicOpts): Uint8Array; + function sign(message: G2, privateKey: PrivKey, htfOpts?: htf.htfBasicOpts): G2; + function sign(message: G2Hex, privateKey: PrivKey, htfOpts?: htf.htfBasicOpts): Uint8Array | G2 { + const msgPoint = normP2Hash(message, htfOpts); + msgPoint.assertValidity(); + const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey)); + if (message instanceof G2.ProjectivePoint) return sigPoint; + return Signature.toRawBytes(sigPoint); + } + + // Checks if pairing of public key & hash is equal to pairing of generator & signature. + // e(P, H(m)) == e(G, S) + function verify( + signature: G2Hex, + message: G2Hex, + publicKey: G1Hex, + htfOpts?: htf.htfBasicOpts + ): boolean { + const P = normP1(publicKey); + const Hm = normP2Hash(message, htfOpts); + const G = G1.ProjectivePoint.BASE; + const S = normP2(signature); + // Instead of doing 2 exponentiations, we use property of billinear maps + // and do one exp after multiplying 2 points. + const ePHm = pairing(P.negate(), Hm, false); + const eGS = pairing(G, S, false); + const exp = Fp12.finalExponentiate(Fp12.mul(eGS, ePHm)); + return Fp12.eql(exp, Fp12.ONE); + } + + // Adds a bunch of public key points together. + // pk1 + pk2 + pk3 = pkA + function aggregatePublicKeys(publicKeys: Hex[]): Uint8Array; + function aggregatePublicKeys(publicKeys: G1[]): G1; + function aggregatePublicKeys(publicKeys: G1Hex[]): Uint8Array | G1 { + if (!publicKeys.length) throw new Error('Expected non-empty array'); + const agg = publicKeys.map(normP1).reduce((sum, p) => sum.add(p), G1.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (publicKeys[0] instanceof G1.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + // toRawBytes ensures point validity + return aggAffine.toRawBytes(true); + } + + // Adds a bunch of signature points together. + function aggregateSignatures(signatures: Hex[]): Uint8Array; + function aggregateSignatures(signatures: G2[]): G2; + function aggregateSignatures(signatures: G2Hex[]): Uint8Array | G2 { + if (!signatures.length) throw new Error('Expected non-empty array'); + const agg = signatures.map(normP2).reduce((sum, s) => sum.add(s), G2.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (signatures[0] instanceof G2.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + return Signature.toRawBytes(aggAffine); + } + + // https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407 + // e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si)) + function verifyBatch( + signature: G2Hex, + messages: G2Hex[], + publicKeys: G1Hex[], + htfOpts?: htf.htfBasicOpts + ): boolean { + // @ts-ignore + // console.log('verifyBatch', bytesToHex(signature as any), messages, publicKeys.map(bytesToHex)); + + if (!messages.length) throw new Error('Expected non-empty messages array'); + if (publicKeys.length !== messages.length) + throw new Error('Pubkey count should equal msg count'); + const sig = normP2(signature); + const nMessages = messages.map((i) => normP2Hash(i, htfOpts)); + const nPublicKeys = publicKeys.map(normP1); + try { + const paired = []; + for (const message of new Set(nMessages)) { + const groupPublicKey = nMessages.reduce( + (groupPublicKey, subMessage, i) => + subMessage === message ? groupPublicKey.add(nPublicKeys[i]) : groupPublicKey, + G1.ProjectivePoint.ZERO + ); + // const msg = message instanceof PointG2 ? message : await PointG2.hashToCurve(message); + // Possible to batch pairing for same msg with different groupPublicKey here + paired.push(pairing(groupPublicKey, message, false)); + } + paired.push(pairing(G1.ProjectivePoint.BASE.negate(), sig, false)); + const product = paired.reduce((a, b) => Fp12.mul(a, b), Fp12.ONE); + const exp = Fp12.finalExponentiate(product); + return Fp12.eql(exp, Fp12.ONE); + } catch { + return false; + } + } + + G1.ProjectivePoint.BASE._setWindowSize(4); + + return { + getPublicKey, + sign, + verify, + verifyBatch, + aggregatePublicKeys, + aggregateSignatures, + millerLoop, + pairing, + G1, + G2, + Signature, + fields: { + Fr, + Fp, + Fp2, + Fp6, + Fp12, + }, + params: { + x: CURVE.params.x, + r: CURVE.params.r, + G1b: CURVE.G1.b, + G2b: CURVE.G2.b, + }, + utils, + }; +} diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/curve.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/curve.ts new file mode 100644 index 0000000..2876377 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/curve.ts @@ -0,0 +1,203 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Abelian group utilities +import { IField, validateField, nLength } from './modular.js'; +import { validateObject } from './utils.js'; +const _0n = BigInt(0); +const _1n = BigInt(1); + +export type AffinePoint = { + x: T; + y: T; +} & { z?: never; t?: never }; + +export interface Group> { + double(): T; + negate(): T; + add(other: T): T; + subtract(other: T): T; + equals(other: T): boolean; + multiply(scalar: bigint): T; +} + +export type GroupConstructor = { + BASE: T; + ZERO: T; +}; +export type Mapper = (i: T[]) => T[]; + +// Elliptic curve multiplication of Point by scalar. Fragile. +// Scalars should always be less than curve order: this should be checked inside of a curve itself. +// Creates precomputation tables for fast multiplication: +// - private scalar is split by fixed size windows of W bits +// - every window point is collected from window's table & added to accumulator +// - since windows are different, same point inside tables won't be accessed more than once per calc +// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar) +// - +1 window is neccessary for wNAF +// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication +// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow +// windows to be in different memory locations +export function wNAF>(c: GroupConstructor, bits: number) { + const constTimeNegate = (condition: boolean, item: T): T => { + const neg = item.negate(); + return condition ? neg : item; + }; + const opts = (W: number) => { + const windows = Math.ceil(bits / W) + 1; // +1, because + const windowSize = 2 ** (W - 1); // -1 because we skip zero + return { windows, windowSize }; + }; + return { + constTimeNegate, + // non-const time multiplication ladder + unsafeLadder(elm: T, n: bigint) { + let p = c.ZERO; + let d: T = elm; + while (n > _0n) { + if (n & _1n) p = p.add(d); + d = d.double(); + n >>= _1n; + } + return p; + }, + + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm: T, W: number): Group[] { + const { windows, windowSize } = opts(W); + const points: T[] = []; + let p: T = elm; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + // =1, because we skip zero + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + }, + + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T } { + // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise + // But need to carefully remove other checks before wNAF. ORDER == bits here + const { windows, windowSize } = opts(W); + + let p = c.ZERO; + let f = c.BASE; + + const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc. + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + // Extract W bits. + let wbits = Number(n & mask); + + // Shift number by W bits. + n >>= shiftBy; + + // If the bits are bigger than max size, we'll split those. + // +224 => 256 - 32 + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n; + } + + // This code was first written with assumption that 'f' and 'p' will never be infinity point: + // since each addition is multiplied by 2 ** W, it cannot cancel each other. However, + // there is negate now: it is possible that negated element from low value + // would be the same as high element, which will create carry into next window. + // It's not obvious how this can fail, but still worth investigating later. + + // Check if we're onto Zero point. + // Add random point inside current window to f. + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + // The most important part for const-time getPublicKey + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ() + // Even if the variable is still unused, there are some checks which will + // throw an exception, so compiler needs to prove they won't happen, which is hard. + // At this point there is a way to F be infinity-point even if p is not, + // which makes it less const-time: around 1 bigint multiply. + return { p, f }; + }, + + wNAFCached(P: T, precomputesMap: Map, n: bigint, transform: Mapper): { p: T; f: T } { + // @ts-ignore + const W: number = P._WINDOW_SIZE || 1; + // Calculate precomputes on a first run, reuse them after + let comp = precomputesMap.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W) as T[]; + if (W !== 1) { + precomputesMap.set(P, transform(comp)); + } + } + return this.wNAF(W, comp, n); + }, + }; +} + +// Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok. +// Though generator can be different (Fp2 / Fp6 for BLS). +export type BasicCurve = { + Fp: IField; // Field over which we'll do calculations (Fp) + n: bigint; // Curve order, total count of valid points in the field + nBitLength?: number; // bit length of curve order + nByteLength?: number; // byte length of curve order + h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation + hEff?: bigint; // Number to multiply to clear cofactor + Gx: T; // base point X coordinate + Gy: T; // base point Y coordinate + allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey +}; + +export function validateBasic(curve: BasicCurve & T) { + validateField(curve.Fp); + validateObject( + curve, + { + n: 'bigint', + h: 'bigint', + Gx: 'field', + Gy: 'field', + }, + { + nBitLength: 'isSafeInteger', + nByteLength: 'isSafeInteger', + } + ); + // Set defaults + return Object.freeze({ + ...nLength(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER }, + } as const); +} diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/edwards.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/edwards.ts new file mode 100644 index 0000000..9124f66 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/edwards.ts @@ -0,0 +1,513 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y² +import { mod } from './modular.js'; +import * as ut from './utils.js'; +import { ensureBytes, FHash, Hex } from './utils.js'; +import { Group, GroupConstructor, wNAF, BasicCurve, validateBasic, AffinePoint } from './curve.js'; + +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8); + +// Edwards curves must declare params a & d. +export type CurveType = BasicCurve & { + a: bigint; // curve param a + d: bigint; // curve param d + hash: FHash; // Hashing + randomBytes: (bytesLength?: number) => Uint8Array; // CSPRNG + adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; // clears bits to get valid field elemtn + domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; // Used for hashing + uvRatio?: (u: bigint, v: bigint) => { isValid: boolean; value: bigint }; // Ratio √(u/v) + prehash?: FHash; // RFC 8032 pre-hashing of messages to sign() / verify() + mapToCurve?: (scalar: bigint[]) => AffinePoint; // for hash-to-curve standard +}; + +// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex: +const VERIFY_DEFAULT = { zip215: true }; + +function validateOpts(curve: CurveType) { + const opts = validateBasic(curve); + ut.validateObject( + curve, + { + hash: 'function', + a: 'bigint', + d: 'bigint', + randomBytes: 'function', + }, + { + adjustScalarBytes: 'function', + domain: 'function', + uvRatio: 'function', + mapToCurve: 'function', + } + ); + // Set defaults + return Object.freeze({ ...opts } as const); +} + +// Instance of Extended Point with coordinates in X, Y, Z, T +export interface ExtPointType extends Group { + readonly ex: bigint; + readonly ey: bigint; + readonly ez: bigint; + readonly et: bigint; + get x(): bigint; + get y(): bigint; + assertValidity(): void; + multiply(scalar: bigint): ExtPointType; + multiplyUnsafe(scalar: bigint): ExtPointType; + isSmallOrder(): boolean; + isTorsionFree(): boolean; + clearCofactor(): ExtPointType; + toAffine(iz?: bigint): AffinePoint; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; +} +// Static methods of Extended Point with coordinates in X, Y, Z, T +export interface ExtPointConstructor extends GroupConstructor { + new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType; + fromAffine(p: AffinePoint): ExtPointType; + fromHex(hex: Hex): ExtPointType; + fromPrivateKey(privateKey: Hex): ExtPointType; +} + +export type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: Hex) => Uint8Array; + sign: (message: Hex, privateKey: Hex, options?: { context?: Hex }) => Uint8Array; + verify: ( + sig: Hex, + message: Hex, + publicKey: Hex, + options?: { context?: Hex; zip215: boolean } + ) => boolean; + ExtendedPoint: ExtPointConstructor; + utils: { + randomPrivateKey: () => Uint8Array; + getExtendedPublicKey: (key: Hex) => { + head: Uint8Array; + prefix: Uint8Array; + scalar: bigint; + point: ExtPointType; + pointBytes: Uint8Array; + }; + }; +}; + +// It is not generic twisted curve for now, but ed25519/ed448 generic implementation +export function twistedEdwards(curveDef: CurveType): CurveFn { + const CURVE = validateOpts(curveDef) as ReturnType; + const { + Fp, + n: CURVE_ORDER, + prehash: prehash, + hash: cHash, + randomBytes, + nByteLength, + h: cofactor, + } = CURVE; + const MASK = _2n << (BigInt(nByteLength * 8) - _1n); + const modP = Fp.create; // Function overrides + + // sqrt(u/v) + const uvRatio = + CURVE.uvRatio || + ((u: bigint, v: bigint) => { + try { + return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) }; + } catch (e) { + return { isValid: false, value: _0n }; + } + }); + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes); // NOOP + const domain = + CURVE.domain || + ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => { + if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported'); + return data; + }); // NOOP + const inBig = (n: bigint) => typeof n === 'bigint' && _0n < n; // n in [1..] + const inRange = (n: bigint, max: bigint) => inBig(n) && inBig(max) && n < max; // n in [1..max-1] + const in0MaskRange = (n: bigint) => n === _0n || inRange(n, MASK); // n in [0..MASK-1] + function assertInRange(n: bigint, max: bigint) { + // n in [1..max-1] + if (inRange(n, max)) return n; + throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`); + } + function assertGE0(n: bigint) { + // n in [0..CURVE_ORDER-1] + return n === _0n ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group + } + const pointPrecomputes = new Map(); + function isPoint(other: unknown) { + if (!(other instanceof Point)) throw new Error('ExtendedPoint expected'); + } + // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy). + // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates + class Point implements ExtPointType { + static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy)); + static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0 + + constructor( + readonly ex: bigint, + readonly ey: bigint, + readonly ez: bigint, + readonly et: bigint + ) { + if (!in0MaskRange(ex)) throw new Error('x required'); + if (!in0MaskRange(ey)) throw new Error('y required'); + if (!in0MaskRange(ez)) throw new Error('z required'); + if (!in0MaskRange(et)) throw new Error('t required'); + } + + get x(): bigint { + return this.toAffine().x; + } + get y(): bigint { + return this.toAffine().y; + } + + static fromAffine(p: AffinePoint): Point { + if (p instanceof Point) throw new Error('extended point not allowed'); + const { x, y } = p || {}; + if (!in0MaskRange(x) || !in0MaskRange(y)) throw new Error('invalid affine point'); + return new Point(x, y, _1n, modP(x * y)); + } + static normalizeZ(points: Point[]): Point[] { + const toInv = Fp.invertBatch(points.map((p) => p.ez)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + + // We calculate precomputes for elliptic curve point multiplication + // using windowed method. This specifies window size and + // stores precomputed values. Usually only base point would be precomputed. + _WINDOW_SIZE?: number; + + // "Private method", don't use it directly + _setWindowSize(windowSize: number) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + // Not required for fromHex(), which always creates valid points. + // Could be useful for fromAffine(). + assertValidity(): void { + const { a, d } = CURVE; + if (this.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below? + // Equation in affine coordinates: ax² + y² = 1 + dx²y² + // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y² + const { ex: X, ey: Y, ez: Z, et: T } = this; + const X2 = modP(X * X); // X² + const Y2 = modP(Y * Y); // Y² + const Z2 = modP(Z * Z); // Z² + const Z4 = modP(Z2 * Z2); // Z⁴ + const aX2 = modP(X2 * a); // aX² + const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z² + const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y² + if (left !== right) throw new Error('bad point: equation left != right (1)'); + // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T + const XY = modP(X * Y); + const ZT = modP(Z * T); + if (XY !== ZT) throw new Error('bad point: equation left != right (2)'); + } + + // Compare one point to another. + equals(other: Point): boolean { + isPoint(other); + const { ex: X1, ey: Y1, ez: Z1 } = this; + const { ex: X2, ey: Y2, ez: Z2 } = other; + const X1Z2 = modP(X1 * Z2); + const X2Z1 = modP(X2 * Z1); + const Y1Z2 = modP(Y1 * Z2); + const Y2Z1 = modP(Y2 * Z1); + return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; + } + + protected is0(): boolean { + return this.equals(Point.ZERO); + } + + negate(): Point { + // Flips point sign to a negative one (-x, y in affine coords) + return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et)); + } + + // Fast algo for doubling Extended Point. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd + // Cost: 4M + 4S + 1*a + 6add + 1*2. + double(): Point { + const { a } = CURVE; + const { ex: X1, ey: Y1, ez: Z1 } = this; + const A = modP(X1 * X1); // A = X12 + const B = modP(Y1 * Y1); // B = Y12 + const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12 + const D = modP(a * A); // D = a*A + const x1y1 = X1 + Y1; + const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B + const G = D + B; // G = D+B + const F = G - C; // F = G-C + const H = D - B; // H = D-B + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + + // Fast algo for adding 2 Extended Points. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd + // Cost: 9M + 1*a + 1*d + 7add. + add(other: Point) { + isPoint(other); + const { a, d } = CURVE; + const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this; + const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other; + // Faster algo for adding 2 Extended Points when curve's a=-1. + // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4 + // Cost: 8M + 8add + 2*2. + // Note: It does not check whether the `other` point is valid. + if (a === BigInt(-1)) { + const A = modP((Y1 - X1) * (Y2 + X2)); + const B = modP((Y1 + X1) * (Y2 - X2)); + const F = modP(B - A); + if (F === _0n) return this.double(); // Same point. Tests say it doesn't affect timing + const C = modP(Z1 * _2n * T2); + const D = modP(T1 * _2n * Z2); + const E = D + C; + const G = B + A; + const H = D - C; + const X3 = modP(E * F); + const Y3 = modP(G * H); + const T3 = modP(E * H); + const Z3 = modP(F * G); + return new Point(X3, Y3, Z3, T3); + } + const A = modP(X1 * X2); // A = X1*X2 + const B = modP(Y1 * Y2); // B = Y1*Y2 + const C = modP(T1 * d * T2); // C = T1*d*T2 + const D = modP(Z1 * Z2); // D = Z1*Z2 + const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B + const F = D - C; // F = D-C + const G = D + C; // G = D+C + const H = modP(B - a * A); // H = B-a*A + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + + return new Point(X3, Y3, Z3, T3); + } + + subtract(other: Point): Point { + return this.add(other.negate()); + } + + private wNAF(n: bigint): { p: Point; f: Point } { + return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ); + } + + // Constant-time multiplication. + multiply(scalar: bigint): Point { + const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER)); + return Point.normalizeZ([p, f])[0]; + } + + // Non-constant-time multiplication. Uses double-and-add algorithm. + // It's faster, but should only be used when you don't care about + // an exposed private key e.g. sig verification. + // Does NOT allow scalars higher than CURVE.n. + multiplyUnsafe(scalar: bigint): Point { + let n = assertGE0(scalar); // 0 <= scalar < CURVE.n + if (n === _0n) return I; + if (this.equals(I) || n === _1n) return this; + if (this.equals(G)) return this.wNAF(n).p; + return wnaf.unsafeLadder(this, n); + } + + // Checks if point is of small order. + // If you add something to small order point, you will have "dirty" + // point with torsion component. + // Multiplies point by cofactor and checks if the result is 0. + isSmallOrder(): boolean { + return this.multiplyUnsafe(cofactor).is0(); + } + + // Multiplies point by curve order and checks if the result is 0. + // Returns `false` is the point is dirty. + isTorsionFree(): boolean { + return wnaf.unsafeLadder(this, CURVE_ORDER).is0(); + } + + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + toAffine(iz?: bigint): AffinePoint { + const { ex: x, ey: y, ez: z } = this; + const is0 = this.is0(); + if (iz == null) iz = is0 ? _8n : (Fp.inv(z) as bigint); // 8 was chosen arbitrarily + const ax = modP(x * iz); + const ay = modP(y * iz); + const zz = modP(z * iz); + if (is0) return { x: _0n, y: _1n }; + if (zz !== _1n) throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + } + + clearCofactor(): Point { + const { h: cofactor } = CURVE; + if (cofactor === _1n) return this; + return this.multiplyUnsafe(cofactor); + } + + // Converts hash string or Uint8Array to Point. + // Uses algo from RFC8032 5.1.3. + static fromHex(hex: Hex, zip215 = false): Point { + const { d, a } = CURVE; + const len = Fp.BYTES; + hex = ensureBytes('pointHex', hex, len); // copy hex to a new array + const normed = hex.slice(); // copy again, we'll manipulate it + const lastByte = hex[len - 1]; // select last byte + normed[len - 1] = lastByte & ~0x80; // clear last bit + const y = ut.bytesToNumberLE(normed); + if (y === _0n) { + // y=0 is allowed + } else { + // RFC8032 prohibits >= p, but ZIP215 doesn't + if (zip215) assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519) + else assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519) + } + + // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case: + // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a) + const y2 = modP(y * y); // denominator is always non-0 mod p. + const u = modP(y2 - _1n); // u = y² - 1 + const v = modP(d * y2 - a); // v = d y² + 1. + let { isValid, value: x } = uvRatio(u, v); // √(u/v) + if (!isValid) throw new Error('Point.fromHex: invalid y coordinate'); + const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper + const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit + if (!zip215 && x === _0n && isLastByteOdd) + // if x=0 and x_0 = 1, fail + throw new Error('Point.fromHex: x=0 and x_0=1'); + if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x + return Point.fromAffine({ x, y }); + } + static fromPrivateKey(privKey: Hex) { + return getExtendedPublicKey(privKey).point; + } + toRawBytes(): Uint8Array { + const { x, y } = this.toAffine(); + const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y) + bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y + return bytes; // and use the last byte to encode sign of x + } + toHex(): string { + return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string. + } + } + const { BASE: G, ZERO: I } = Point; + const wnaf = wNAF(Point, nByteLength * 8); + + function modN(a: bigint) { + return mod(a, CURVE_ORDER); + } + // Little-endian SHA512 with modulo n + function modN_LE(hash: Uint8Array): bigint { + return modN(ut.bytesToNumberLE(hash)); + } + + /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */ + function getExtendedPublicKey(key: Hex) { + const len = nByteLength; + key = ensureBytes('private key', key, len); + // Hash private key with curve's hash function to produce uniformingly random input + // Check byte lengths: ensure(64, h(ensure(32, key))) + const hashed = ensureBytes('hashed private key', cHash(key), 2 * len); + const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE + const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6) + const scalar = modN_LE(head); // The actual private scalar + const point = G.multiply(scalar); // Point on Edwards curve aka public key + const pointBytes = point.toRawBytes(); // Uint8Array representation + return { head, prefix, scalar, point, pointBytes }; + } + + // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared + function getPublicKey(privKey: Hex): Uint8Array { + return getExtendedPublicKey(privKey).pointBytes; + } + + // int('LE', SHA512(dom2(F, C) || msgs)) mod N + function hashDomainToScalar(context: Hex = new Uint8Array(), ...msgs: Uint8Array[]) { + const msg = ut.concatBytes(...msgs); + return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash))); + } + + /** Signs message with privateKey. RFC8032 5.1.6 */ + function sign(msg: Hex, privKey: Hex, options: { context?: Hex } = {}): Uint8Array { + msg = ensureBytes('message', msg); + if (prehash) msg = prehash(msg); // for ed25519ph etc. + const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey); + const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M) + const R = G.multiply(r).toRawBytes(); // R = rG + const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M) + const s = modN(r + k * scalar); // S = (r + k * s) mod L + assertGE0(s); // 0 <= s < l + const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES)); + return ensureBytes('result', res, nByteLength * 2); // 64-byte signature + } + + const verifyOpts: { context?: Hex; zip215?: boolean } = VERIFY_DEFAULT; + function verify(sig: Hex, msg: Hex, publicKey: Hex, options = verifyOpts): boolean { + const { context, zip215 } = options; + const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7. + sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked. + msg = ensureBytes('message', msg); + if (prehash) msg = prehash(msg); // for ed25519ph, etc + + const s = ut.bytesToNumberLE(sig.slice(len, 2 * len)); + // zip215: true is good for consensus-critical apps and allows points < 2^256 + // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p + let A, R, SB; + try { + A = Point.fromHex(publicKey, zip215); + R = Point.fromHex(sig.slice(0, len), zip215); + SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside + } catch (error) { + return false; + } + if (!zip215 && A.isSmallOrder()) return false; + + const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg); + const RkA = R.add(A.multiplyUnsafe(k)); + // [8][S]B = [8]R + [8][k]A' + return RkA.subtract(SB).clearCofactor().equals(Point.ZERO); + } + + G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms. + + const utils = { + getExtendedPublicKey, + // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1. + randomPrivateKey: (): Uint8Array => randomBytes(Fp.BYTES), + + /** + * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT + * values. This slows down first getPublicKey() by milliseconds (see Speed section), + * but allows to speed-up subsequent getPublicKey() calls up to 20x. + * @param windowSize 2, 4, 8, 16 + */ + precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; + }, + }; + + return { + CURVE, + getPublicKey, + sign, + verify, + ExtendedPoint: Point, + utils, + }; +} diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/hash-to-curve.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/hash-to-curve.ts new file mode 100644 index 0000000..38d31d4 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/hash-to-curve.ts @@ -0,0 +1,223 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import type { Group, GroupConstructor, AffinePoint } from './curve.js'; +import { mod, IField } from './modular.js'; +import { bytesToNumberBE, CHash, concatBytes, utf8ToBytes, validateObject } from './utils.js'; + +/** + * * `DST` is a domain separation tag, defined in section 2.2.5 + * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m + * * `m` is extension degree (1 for prime fields) + * * `k` is the target security target in bits (e.g. 128), from section 5.1 + * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF) + * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props + */ +type UnicodeOrBytes = string | Uint8Array; +export type Opts = { + DST: UnicodeOrBytes; + p: bigint; + m: number; + k: number; + expand: 'xmd' | 'xof'; + hash: CHash; +}; + +function validateDST(dst: UnicodeOrBytes): Uint8Array { + if (dst instanceof Uint8Array) return dst; + if (typeof dst === 'string') return utf8ToBytes(dst); + throw new Error('DST must be Uint8Array or string'); +} + +// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE. +const os2ip = bytesToNumberBE; + +// Integer to Octet Stream (numberToBytesBE) +function i2osp(value: number, length: number): Uint8Array { + if (value < 0 || value >= 1 << (8 * length)) { + throw new Error(`bad I2OSP call: value=${value} length=${length}`); + } + const res = Array.from({ length }).fill(0) as number[]; + for (let i = length - 1; i >= 0; i--) { + res[i] = value & 0xff; + value >>>= 8; + } + return new Uint8Array(res); +} + +function strxor(a: Uint8Array, b: Uint8Array): Uint8Array { + const arr = new Uint8Array(a.length); + for (let i = 0; i < a.length; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} + +function isBytes(item: unknown): void { + if (!(item instanceof Uint8Array)) throw new Error('Uint8Array expected'); +} +function isNum(item: unknown): void { + if (!Number.isSafeInteger(item)) throw new Error('number expected'); +} + +// Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.4.1 +export function expand_message_xmd( + msg: Uint8Array, + DST: Uint8Array, + lenInBytes: number, + H: CHash +): Uint8Array { + isBytes(msg); + isBytes(DST); + isNum(lenInBytes); + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-5.3.3 + if (DST.length > 255) DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST)); + const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H; + const ell = Math.ceil(lenInBytes / b_in_bytes); + if (ell > 255) throw new Error('Invalid xmd length'); + const DST_prime = concatBytes(DST, i2osp(DST.length, 1)); + const Z_pad = i2osp(0, r_in_bytes); + const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str + const b = new Array(ell); + const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); + b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime)); + for (let i = 1; i <= ell; i++) { + const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime]; + b[i] = H(concatBytes(...args)); + } + const pseudo_random_bytes = concatBytes(...b); + return pseudo_random_bytes.slice(0, lenInBytes); +} + +export function expand_message_xof( + msg: Uint8Array, + DST: Uint8Array, + lenInBytes: number, + k: number, + H: CHash +): Uint8Array { + isBytes(msg); + isBytes(DST); + isNum(lenInBytes); + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-5.3.3 + // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8)); + if (DST.length > 255) { + const dkLen = Math.ceil((2 * k) / 8); + DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest(); + } + if (lenInBytes > 65535 || DST.length > 255) + throw new Error('expand_message_xof: invalid lenInBytes'); + return ( + H.create({ dkLen: lenInBytes }) + .update(msg) + .update(i2osp(lenInBytes, 2)) + // 2. DST_prime = DST || I2OSP(len(DST), 1) + .update(DST) + .update(i2osp(DST.length, 1)) + .digest() + ); +} + +/** + * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.3 + * @param msg a byte string containing the message to hash + * @param count the number of elements of F to output + * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above + * @returns [u_0, ..., u_(count - 1)], a list of field elements. + */ +export function hash_to_field(msg: Uint8Array, count: number, options: Opts): bigint[][] { + validateObject(options, { + DST: 'string', + p: 'bigint', + m: 'isSafeInteger', + k: 'isSafeInteger', + hash: 'hash', + }); + const { p, k, m, hash, expand, DST: _DST } = options; + isBytes(msg); + isNum(count); + const DST = validateDST(_DST); + const log2p = p.toString(2).length; + const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above + const len_in_bytes = count * m * L; + let prb; // pseudo_random_bytes + if (expand === 'xmd') { + prb = expand_message_xmd(msg, DST, len_in_bytes, hash); + } else if (expand === 'xof') { + prb = expand_message_xof(msg, DST, len_in_bytes, k, hash); + } else if (expand === '_internal_pass') { + // for internal tests only + prb = msg; + } else { + throw new Error('expand must be "xmd" or "xof"'); + } + const u = new Array(count); + for (let i = 0; i < count; i++) { + const e = new Array(m); + for (let j = 0; j < m; j++) { + const elm_offset = L * (j + i * m); + const tv = prb.subarray(elm_offset, elm_offset + L); + e[j] = mod(os2ip(tv), p); + } + u[i] = e; + } + return u; +} + +export function isogenyMap>(field: F, map: [T[], T[], T[], T[]]) { + // Make same order as in spec + const COEFF = map.map((i) => Array.from(i).reverse()); + return (x: T, y: T) => { + const [xNum, xDen, yNum, yDen] = COEFF.map((val) => + val.reduce((acc, i) => field.add(field.mul(acc, x), i)) + ); + x = field.div(xNum, xDen); // xNum / xDen + y = field.mul(y, field.div(yNum, yDen)); // y * (yNum / yDev) + return { x, y }; + }; +} + +export interface H2CPoint extends Group> { + add(rhs: H2CPoint): H2CPoint; + toAffine(iz?: bigint): AffinePoint; + clearCofactor(): H2CPoint; + assertValidity(): void; +} + +export interface H2CPointConstructor extends GroupConstructor> { + fromAffine(ap: AffinePoint): H2CPoint; +} + +export type MapToCurve = (scalar: bigint[]) => AffinePoint; + +// Separated from initialization opts, so users won't accidentally change per-curve parameters +// (changing DST is ok!) +export type htfBasicOpts = { DST: UnicodeOrBytes }; + +export function createHasher( + Point: H2CPointConstructor, + mapToCurve: MapToCurve, + def: Opts & { encodeDST?: UnicodeOrBytes } +) { + if (typeof mapToCurve !== 'function') throw new Error('mapToCurve() must be defined'); + return { + // Encodes byte string to elliptic curve + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-3 + hashToCurve(msg: Uint8Array, options?: htfBasicOpts) { + const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options } as Opts); + const u0 = Point.fromAffine(mapToCurve(u[0])); + const u1 = Point.fromAffine(mapToCurve(u[1])); + const P = u0.add(u1).clearCofactor(); + P.assertValidity(); + return P; + }, + + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-3 + encodeToCurve(msg: Uint8Array, options?: htfBasicOpts) { + const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options } as Opts); + const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor(); + P.assertValidity(); + return P; + }, + }; +} diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/modular.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/modular.ts new file mode 100644 index 0000000..bb1061b --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/modular.ts @@ -0,0 +1,425 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Utilities for modular arithmetics and finite fields +import { + bitMask, + numberToBytesBE, + numberToBytesLE, + bytesToNumberBE, + bytesToNumberLE, + ensureBytes, + validateObject, +} from './utils.js'; +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); +// prettier-ignore +const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8); +// prettier-ignore +const _9n = BigInt(9), _16n = BigInt(16); + +// Calculates a modulo b +export function mod(a: bigint, b: bigint): bigint { + const result = a % b; + return result >= _0n ? result : b + result; +} +/** + * Efficiently raise num to power and do modular division. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + * @example + * pow(2n, 6n, 11n) // 64n % 11n == 9n + */ +// TODO: use field version && remove +export function pow(num: bigint, power: bigint, modulo: bigint): bigint { + if (modulo <= _0n || power < _0n) throw new Error('Expected power/modulo > 0'); + if (modulo === _1n) return _0n; + let res = _1n; + while (power > _0n) { + if (power & _1n) res = (res * num) % modulo; + num = (num * num) % modulo; + power >>= _1n; + } + return res; +} + +// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4) +export function pow2(x: bigint, power: bigint, modulo: bigint): bigint { + let res = x; + while (power-- > _0n) { + res *= res; + res %= modulo; + } + return res; +} + +// Inverses number over modulo +export function invert(number: bigint, modulo: bigint): bigint { + if (number === _0n || modulo <= _0n) { + throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); + } + // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/ + // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower. + let a = mod(number, modulo); + let b = modulo; + // prettier-ignore + let x = _0n, y = _1n, u = _1n, v = _0n; + while (a !== _0n) { + // JIT applies optimization if those two lines follow each other + const q = b / a; + const r = b % a; + const m = x - u * q; + const n = y - v * q; + // prettier-ignore + b = a, a = r, x = u, y = v, u = m, v = n; + } + const gcd = b; + if (gcd !== _1n) throw new Error('invert: does not exist'); + return mod(x, modulo); +} + +// Tonelli-Shanks algorithm +// Paper 1: https://eprint.iacr.org/2012/685.pdf (page 12) +// Paper 2: Square Roots from 1; 24, 51, 10 to Dan Shanks +export function tonelliShanks(P: bigint) { + // Legendre constant: used to calculate Legendre symbol (a | p), + // which denotes the value of a^((p-1)/2) (mod p). + // (a | p) ≡ 1 if a is a square (mod p) + // (a | p) ≡ -1 if a is not a square (mod p) + // (a | p) ≡ 0 if a ≡ 0 (mod p) + const legendreC = (P - _1n) / _2n; + + let Q: bigint, S: number, Z: bigint; + // Step 1: By factoring out powers of 2 from p - 1, + // find q and s such that p - 1 = q*(2^s) with q odd + for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++); + + // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq + for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++); + + // Fast-path + if (S === 1) { + const p1div4 = (P + _1n) / _4n; + return function tonelliFast(Fp: IField, n: T) { + const root = Fp.pow(n, p1div4); + if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root'); + return root; + }; + } + + // Slow-path + const Q1div2 = (Q + _1n) / _2n; + return function tonelliSlow(Fp: IField, n: T): T { + // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1 + if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) throw new Error('Cannot find square root'); + let r = S; + // TODO: will fail at Fp2/etc + let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b + let x = Fp.pow(n, Q1div2); // first guess at the square root + let b = Fp.pow(n, Q); // first guess at the fudge factor + + while (!Fp.eql(b, Fp.ONE)) { + if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0) + // Find m such b^(2^m)==1 + let m = 1; + for (let t2 = Fp.sqr(b); m < r; m++) { + if (Fp.eql(t2, Fp.ONE)) break; + t2 = Fp.sqr(t2); // t2 *= t2 + } + // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow + const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1) + g = Fp.sqr(ge); // g = ge * ge + x = Fp.mul(x, ge); // x *= ge + b = Fp.mul(b, g); // b *= g + r = m; + } + return x; + }; +} + +export function FpSqrt(P: bigint) { + // NOTE: different algorithms can give different roots, it is up to user to decide which one they want. + // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve). + + // P ≡ 3 (mod 4) + // √n = n^((P+1)/4) + if (P % _4n === _3n) { + // Not all roots possible! + // const ORDER = + // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn; + // const NUM = 72057594037927816n; + const p1div4 = (P + _1n) / _4n; + return function sqrt3mod4(Fp: IField, n: T) { + const root = Fp.pow(n, p1div4); + // Throw if root**2 != n + if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root'); + return root; + }; + } + + // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10) + if (P % _8n === _5n) { + const c1 = (P - _5n) / _8n; + return function sqrt5mod8(Fp: IField, n: T) { + const n2 = Fp.mul(n, _2n); + const v = Fp.pow(n2, c1); + const nv = Fp.mul(n, v); + const i = Fp.mul(Fp.mul(nv, _2n), v); + const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); + if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root'); + return root; + }; + } + + // P ≡ 9 (mod 16) + if (P % _16n === _9n) { + // NOTE: tonelli is too slow for bls-Fp2 calculations even on start + // Means we cannot use sqrt for constants at all! + // + // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F + // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F + // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F + // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic + // sqrt = (x) => { + // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4 + // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1 + // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1 + // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1 + // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x + // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x + // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x + // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x + // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x + // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2 + // } + } + + // Other cases: Tonelli-Shanks algorithm + return tonelliShanks(P); +} + +// Little-endian check for first LE bit (last BE bit); +export const isNegativeLE = (num: bigint, modulo: bigint) => (mod(num, modulo) & _1n) === _1n; + +// Field is not always over prime, Fp2 for example has ORDER(q)=p^m +export interface IField { + ORDER: bigint; + BYTES: number; + BITS: number; + MASK: bigint; + ZERO: T; + ONE: T; + // 1-arg + create: (num: T) => T; + isValid: (num: T) => boolean; + is0: (num: T) => boolean; + neg(num: T): T; + inv(num: T): T; + sqrt(num: T): T; + sqr(num: T): T; + // 2-args + eql(lhs: T, rhs: T): boolean; + add(lhs: T, rhs: T): T; + sub(lhs: T, rhs: T): T; + mul(lhs: T, rhs: T | bigint): T; + pow(lhs: T, power: bigint): T; + div(lhs: T, rhs: T | bigint): T; + // N for NonNormalized (for now) + addN(lhs: T, rhs: T): T; + subN(lhs: T, rhs: T): T; + mulN(lhs: T, rhs: T | bigint): T; + sqrN(num: T): T; + + // Optional + // Should be same as sgn0 function in https://datatracker.ietf.org/doc/draft-irtf-cfrg-hash-to-curve/ + // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway. + isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2 + // legendre?(num: T): T; + pow(lhs: T, power: bigint): T; + invertBatch: (lst: T[]) => T[]; + toBytes(num: T): Uint8Array; + fromBytes(bytes: Uint8Array): T; + // If c is False, CMOV returns a, otherwise it returns b. + cmov(a: T, b: T, c: boolean): T; +} +// prettier-ignore +const FIELD_FIELDS = [ + 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr', + 'eql', 'add', 'sub', 'mul', 'pow', 'div', + 'addN', 'subN', 'mulN', 'sqrN' +] as const; +export function validateField(field: IField) { + const initial = { + ORDER: 'bigint', + MASK: 'bigint', + BYTES: 'isSafeInteger', + BITS: 'isSafeInteger', + } as Record; + const opts = FIELD_FIELDS.reduce((map, val: string) => { + map[val] = 'function'; + return map; + }, initial); + return validateObject(field, opts); +} + +// Generic field functions +export function FpPow(f: IField, num: T, power: bigint): T { + // Should have same speed as pow for bigints + // TODO: benchmark! + if (power < _0n) throw new Error('Expected power > 0'); + if (power === _0n) return f.ONE; + if (power === _1n) return num; + let p = f.ONE; + let d = num; + while (power > _0n) { + if (power & _1n) p = f.mul(p, d); + d = f.sqr(d); + power >>= _1n; + } + return p; +} + +// 0 is non-invertible: non-batched version will throw on 0 +export function FpInvertBatch(f: IField, nums: T[]): T[] { + const tmp = new Array(nums.length); + // Walk from first to last, multiply them by each other MOD p + const lastMultiplied = nums.reduce((acc, num, i) => { + if (f.is0(num)) return acc; + tmp[i] = acc; + return f.mul(acc, num); + }, f.ONE); + // Invert last element + const inverted = f.inv(lastMultiplied); + // Walk from last to first, multiply them by inverted each other MOD p + nums.reduceRight((acc, num, i) => { + if (f.is0(num)) return acc; + tmp[i] = f.mul(acc, tmp[i]); + return f.mul(acc, num); + }, inverted); + return tmp; +} + +export function FpDiv(f: IField, lhs: T, rhs: T | bigint): T { + return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs)); +} + +// This function returns True whenever the value x is a square in the field F. +export function FpIsSquare(f: IField) { + const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic + return (x: T): boolean => { + const p = f.pow(x, legendreConst); + return f.eql(p, f.ZERO) || f.eql(p, f.ONE); + }; +} + +// CURVE.n lengths +export function nLength(n: bigint, nBitLength?: number) { + // Bit size, byte size of CURVE.n + const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} + +type FpField = IField & Required, 'isOdd'>>; +/** + * Initializes a galois field over prime. Non-primes are not supported for now. + * Do not init in loop: slow. Very fragile: always run a benchmark on change. + * Major performance gains: + * a) non-normalized operations like mulN instead of mul + * b) `Object.freeze` + * c) Same object shape: never add or remove keys + * @param ORDER prime positive bigint + * @param bitLen how many bits the field consumes + * @param isLE (def: false) if encoding / decoding should be in little-endian + * @param redef optional faster redefinitions of sqrt and other methods + */ +export function Field( + ORDER: bigint, + bitLen?: number, + isLE = false, + redef: Partial> = {} +): Readonly { + if (ORDER <= _0n) throw new Error(`Expected Fp ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen); + if (BYTES > 2048) throw new Error('Field lengths over 2048 bytes are not supported'); + const sqrtP = FpSqrt(ORDER); + const f: Readonly = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: bitMask(BITS), + ZERO: _0n, + ONE: _1n, + create: (num) => mod(num, ORDER), + isValid: (num) => { + if (typeof num !== 'bigint') + throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); + return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible + }, + is0: (num) => num === _0n, + isOdd: (num) => (num & _1n) === _1n, + neg: (num) => mod(-num, ORDER), + eql: (lhs, rhs) => lhs === rhs, + + sqr: (num) => mod(num * num, ORDER), + add: (lhs, rhs) => mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod(lhs * rhs, ORDER), + pow: (num, power) => FpPow(f, num, power), + div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), + + // Same as above, but doesn't normalize + sqrN: (num) => num * num, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + + inv: (num) => invert(num, ORDER), + sqrt: redef.sqrt || ((n) => sqrtP(f, n)), + invertBatch: (lst) => FpInvertBatch(f, lst), + // TODO: do we really need constant cmov? + // We don't have const-time bigints anyway, so probably will be not very useful + cmov: (a, b, c) => (c ? b : a), + toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)), + fromBytes: (bytes) => { + if (bytes.length !== BYTES) + throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); + return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); + }, + } as FpField); + return Object.freeze(f); +} + +export function FpSqrtOdd(Fp: IField, elm: T) { + if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`); + const root = Fp.sqrt(elm); + return Fp.isOdd(root) ? root : Fp.neg(root); +} + +export function FpSqrtEven(Fp: IField, elm: T) { + if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`); + const root = Fp.sqrt(elm); + return Fp.isOdd(root) ? Fp.neg(root) : root; +} + +/** + * FIPS 186 B.4.1-compliant "constant-time" private key generation utility. + * Can take (n+8) or more bytes of uniform input e.g. from CSPRNG or KDF + * and convert them into private scalar, with the modulo bias being negligible. + * Needs at least 40 bytes of input for 32-byte private key. + * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ + * @param hash hash output from SHA3 or a similar function + * @param groupOrder size of subgroup - (e.g. curveFn.CURVE.n) + * @param isLE interpret hash bytes as LE num + * @returns valid private scalar + */ +export function hashToPrivateScalar( + hash: string | Uint8Array, + groupOrder: bigint, + isLE = false +): bigint { + hash = ensureBytes('privateHash', hash); + const hashLen = hash.length; + const minLen = nLength(groupOrder).nByteLength + 8; + if (minLen < 24 || hashLen < minLen || hashLen > 1024) + throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`); + const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash); + return mod(num, groupOrder - _1n) + _1n; +} diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/montgomery.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/montgomery.ts new file mode 100644 index 0000000..64d1b53 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/montgomery.ts @@ -0,0 +1,189 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { mod, pow } from './modular.js'; +import { bytesToNumberLE, ensureBytes, numberToBytesLE, validateObject } from './utils.js'; + +const _0n = BigInt(0); +const _1n = BigInt(1); +type Hex = string | Uint8Array; + +export type CurveType = { + P: bigint; // finite field prime + nByteLength: number; + adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; + domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; + a: bigint; + montgomeryBits: number; + powPminus2?: (x: bigint) => bigint; + xyToU?: (x: bigint, y: bigint) => bigint; + Gu: bigint; + randomBytes?: (bytesLength?: number) => Uint8Array; +}; +export type CurveFn = { + scalarMult: (scalar: Hex, u: Hex) => Uint8Array; + scalarMultBase: (scalar: Hex) => Uint8Array; + getSharedSecret: (privateKeyA: Hex, publicKeyB: Hex) => Uint8Array; + getPublicKey: (privateKey: Hex) => Uint8Array; + utils: { randomPrivateKey: () => Uint8Array }; + GuBytes: Uint8Array; +}; + +function validateOpts(curve: CurveType) { + validateObject( + curve, + { + a: 'bigint', + }, + { + montgomeryBits: 'isSafeInteger', + nByteLength: 'isSafeInteger', + adjustScalarBytes: 'function', + domain: 'function', + powPminus2: 'function', + Gu: 'bigint', + } + ); + // Set defaults + return Object.freeze({ ...curve } as const); +} + +// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748) +// Uses only one coordinate instead of two +export function montgomery(curveDef: CurveType): CurveFn { + const CURVE = validateOpts(curveDef); + const { P } = CURVE; + const modP = (n: bigint) => mod(n, P); + const montgomeryBits = CURVE.montgomeryBits; + const montgomeryBytes = Math.ceil(montgomeryBits / 8); + const fieldLen = CURVE.nByteLength; + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes); + const powPminus2 = CURVE.powPminus2 || ((x: bigint) => pow(x, P - BigInt(2), P)); + + // cswap from RFC7748. But it is not from RFC7748! + /* + cswap(swap, x_2, x_3): + dummy = mask(swap) AND (x_2 XOR x_3) + x_2 = x_2 XOR dummy + x_3 = x_3 XOR dummy + Return (x_2, x_3) + Where mask(swap) is the all-1 or all-0 word of the same length as x_2 + and x_3, computed, e.g., as mask(swap) = 0 - swap. + */ + function cswap(swap: bigint, x_2: bigint, x_3: bigint): [bigint, bigint] { + const dummy = modP(swap * (x_2 - x_3)); + x_2 = modP(x_2 - dummy); + x_3 = modP(x_3 + dummy); + return [x_2, x_3]; + } + + // Accepts 0 as well + function assertFieldElement(n: bigint): bigint { + if (typeof n === 'bigint' && _0n <= n && n < P) return n; + throw new Error('Expected valid scalar 0 < scalar < CURVE.P'); + } + + // x25519 from 4 + // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 + const a24 = (CURVE.a - BigInt(2)) / BigInt(4); + /** + * + * @param pointU u coordinate (x) on Montgomery Curve 25519 + * @param scalar by which the point would be multiplied + * @returns new Point on Montgomery curve + */ + function montgomeryLadder(pointU: bigint, scalar: bigint): bigint { + const u = assertFieldElement(pointU); + // Section 5: Implementations MUST accept non-canonical values and process them as + // if they had been reduced modulo the field prime. + const k = assertFieldElement(scalar); + const x_1 = u; + let x_2 = _1n; + let z_2 = _0n; + let x_3 = u; + let z_3 = _1n; + let swap = _0n; + let sw: [bigint, bigint]; + for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) { + const k_t = (k >> t) & _1n; + swap ^= k_t; + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + swap = k_t; + + const A = x_2 + z_2; + const AA = modP(A * A); + const B = x_2 - z_2; + const BB = modP(B * B); + const E = AA - BB; + const C = x_3 + z_3; + const D = x_3 - z_3; + const DA = modP(D * A); + const CB = modP(C * B); + const dacb = DA + CB; + const da_cb = DA - CB; + x_3 = modP(dacb * dacb); + z_3 = modP(x_1 * modP(da_cb * da_cb)); + x_2 = modP(AA * BB); + z_2 = modP(E * (AA + modP(a24 * E))); + } + // (x_2, x_3) = cswap(swap, x_2, x_3) + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + // (z_2, z_3) = cswap(swap, z_2, z_3) + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + // z_2^(p - 2) + const z2 = powPminus2(z_2); + // Return x_2 * (z_2^(p - 2)) + return modP(x_2 * z2); + } + + function encodeUCoordinate(u: bigint): Uint8Array { + return numberToBytesLE(modP(u), montgomeryBytes); + } + + function decodeUCoordinate(uEnc: Hex): bigint { + // Section 5: When receiving such an array, implementations of X25519 + // MUST mask the most significant bit in the final byte. + // This is very ugly way, but it works because fieldLen-1 is outside of bounds for X448, so this becomes NOOP + // fieldLen - scalaryBytes = 1 for X448 and = 0 for X25519 + const u = ensureBytes('u coordinate', uEnc, montgomeryBytes); + // u[fieldLen-1] crashes QuickJS (TypeError: out-of-bound numeric index) + if (fieldLen === montgomeryBytes) u[fieldLen - 1] &= 127; // 0b0111_1111 + return bytesToNumberLE(u); + } + function decodeScalar(n: Hex): bigint { + const bytes = ensureBytes('scalar', n); + if (bytes.length !== montgomeryBytes && bytes.length !== fieldLen) + throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${bytes.length}`); + return bytesToNumberLE(adjustScalarBytes(bytes)); + } + function scalarMult(scalar: Hex, u: Hex): Uint8Array { + const pointU = decodeUCoordinate(u); + const _scalar = decodeScalar(scalar); + const pu = montgomeryLadder(pointU, _scalar); + // The result was not contributory + // https://cr.yp.to/ecdh.html#validate + if (pu === _0n) throw new Error('Invalid private or public key received'); + return encodeUCoordinate(pu); + } + // Computes public key from private. By doing scalar multiplication of base point. + const GuBytes = encodeUCoordinate(CURVE.Gu); + function scalarMultBase(scalar: Hex): Uint8Array { + return scalarMult(scalar, GuBytes); + } + + return { + scalarMult, + scalarMultBase, + getSharedSecret: (privateKey: Hex, publicKey: Hex) => scalarMult(privateKey, publicKey), + getPublicKey: (privateKey: Hex): Uint8Array => scalarMultBase(privateKey), + utils: { randomPrivateKey: () => CURVE.randomBytes!(CURVE.nByteLength) }, + GuBytes: GuBytes, + }; +} diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/poseidon.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/poseidon.ts new file mode 100644 index 0000000..38ab17d --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/poseidon.ts @@ -0,0 +1,119 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Poseidon Hash: https://eprint.iacr.org/2019/458.pdf, https://www.poseidon-hash.info +import { IField, FpPow, validateField } from './modular.js'; +// We don't provide any constants, since different implementations use different constants. +// For reference constants see './test/poseidon.test.js'. +export type PoseidonOpts = { + Fp: IField; + t: number; + roundsFull: number; + roundsPartial: number; + sboxPower?: number; + reversePartialPowIdx?: boolean; // Hack for stark + mds: bigint[][]; + roundConstants: bigint[][]; +}; + +export function validateOpts(opts: PoseidonOpts) { + const { Fp } = opts; + validateField(Fp); + for (const i of ['t', 'roundsFull', 'roundsPartial'] as const) { + if (typeof opts[i] !== 'number' || !Number.isSafeInteger(opts[i])) + throw new Error(`Poseidon: invalid param ${i}=${opts[i]} (${typeof opts[i]})`); + } + if (opts.reversePartialPowIdx !== undefined && typeof opts.reversePartialPowIdx !== 'boolean') + throw new Error(`Poseidon: invalid param reversePartialPowIdx=${opts.reversePartialPowIdx}`); + // Default is 5, but by some reasons stark uses 3 + let sboxPower = opts.sboxPower; + if (sboxPower === undefined) sboxPower = 5; + if (typeof sboxPower !== 'number' || !Number.isSafeInteger(sboxPower)) + throw new Error(`Poseidon wrong sboxPower=${sboxPower}`); + + const _sboxPower = BigInt(sboxPower); + let sboxFn = (n: bigint) => FpPow(Fp, n, _sboxPower); + // Unwrapped sbox power for common cases (195->142μs) + if (sboxPower === 3) sboxFn = (n: bigint) => Fp.mul(Fp.sqrN(n), n); + else if (sboxPower === 5) sboxFn = (n: bigint) => Fp.mul(Fp.sqrN(Fp.sqrN(n)), n); + + if (opts.roundsFull % 2 !== 0) + throw new Error(`Poseidon roundsFull is not even: ${opts.roundsFull}`); + const rounds = opts.roundsFull + opts.roundsPartial; + + if (!Array.isArray(opts.roundConstants) || opts.roundConstants.length !== rounds) + throw new Error('Poseidon: wrong round constants'); + const roundConstants = opts.roundConstants.map((rc) => { + if (!Array.isArray(rc) || rc.length !== opts.t) + throw new Error(`Poseidon wrong round constants: ${rc}`); + return rc.map((i) => { + if (typeof i !== 'bigint' || !Fp.isValid(i)) + throw new Error(`Poseidon wrong round constant=${i}`); + return Fp.create(i); + }); + }); + // MDS is TxT matrix + if (!Array.isArray(opts.mds) || opts.mds.length !== opts.t) + throw new Error('Poseidon: wrong MDS matrix'); + const mds = opts.mds.map((mdsRow) => { + if (!Array.isArray(mdsRow) || mdsRow.length !== opts.t) + throw new Error(`Poseidon MDS matrix row: ${mdsRow}`); + return mdsRow.map((i) => { + if (typeof i !== 'bigint') throw new Error(`Poseidon MDS matrix value=${i}`); + return Fp.create(i); + }); + }); + return Object.freeze({ ...opts, rounds, sboxFn, roundConstants, mds }); +} + +export function splitConstants(rc: bigint[], t: number) { + if (typeof t !== 'number') throw new Error('poseidonSplitConstants: wrong t'); + if (!Array.isArray(rc) || rc.length % t) throw new Error('poseidonSplitConstants: wrong rc'); + const res = []; + let tmp = []; + for (let i = 0; i < rc.length; i++) { + tmp.push(rc[i]); + if (tmp.length === t) { + res.push(tmp); + tmp = []; + } + } + return res; +} + +export function poseidon(opts: PoseidonOpts) { + const { t, Fp, rounds, sboxFn, reversePartialPowIdx } = validateOpts(opts); + const halfRoundsFull = Math.floor(opts.roundsFull / 2); + const partialIdx = reversePartialPowIdx ? t - 1 : 0; + const poseidonRound = (values: bigint[], isFull: boolean, idx: number) => { + values = values.map((i, j) => Fp.add(i, opts.roundConstants[idx][j])); + + if (isFull) values = values.map((i) => sboxFn(i)); + else values[partialIdx] = sboxFn(values[partialIdx]); + // Matrix multiplication + values = opts.mds.map((i) => + i.reduce((acc, i, j) => Fp.add(acc, Fp.mulN(i, values[j])), Fp.ZERO) + ); + return values; + }; + const poseidonHash = function poseidonHash(values: bigint[]) { + if (!Array.isArray(values) || values.length !== t) + throw new Error(`Poseidon: wrong values (expected array of bigints with length ${t})`); + values = values.map((i) => { + if (typeof i !== 'bigint') throw new Error(`Poseidon: wrong value=${i} (${typeof i})`); + return Fp.create(i); + }); + let round = 0; + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) values = poseidonRound(values, true, round++); + // Apply r_p partial rounds. + for (let i = 0; i < opts.roundsPartial; i++) values = poseidonRound(values, false, round++); + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) values = poseidonRound(values, true, round++); + + if (round !== rounds) + throw new Error(`Poseidon: wrong number of rounds: last round=${round}, total=${rounds}`); + return values; + }; + // For verification in tests + poseidonHash.roundConstants = opts.roundConstants; + return poseidonHash; +} diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/utils.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/utils.ts new file mode 100644 index 0000000..00fc18f --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/utils.ts @@ -0,0 +1,287 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// 100 lines of code in the file are duplicated from noble-hashes (utils). +// This is OK: `abstract` directory does not use noble-hashes. +// User may opt-in into using different hashing library. This way, noble-hashes +// won't be included into their bundle. +const _0n = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +const u8a = (a: any): a is Uint8Array => a instanceof Uint8Array; +export type Hex = Uint8Array | string; // hex strings are accepted for simplicity +export type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve +export type CHash = { + (message: Uint8Array | string): Uint8Array; + blockLen: number; + outputLen: number; + create(opts?: { dkLen?: number }): any; // For shake +}; +export type FHash = (message: Uint8Array | string) => Uint8Array; + +const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export function bytesToHex(bytes: Uint8Array): string { + if (!u8a(bytes)) throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} + +export function numberToHexUnpadded(num: number | bigint): string { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; +} + +export function hexToNumber(hex: string): bigint { + if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex); + // Big Endian + return BigInt(hex === '' ? '0' : `0x${hex}`); +} + +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export function hexToBytes(hex: string): Uint8Array { + if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} + +// BE: Big Endian, LE: Little Endian +export function bytesToNumberBE(bytes: Uint8Array): bigint { + return hexToNumber(bytesToHex(bytes)); +} +export function bytesToNumberLE(bytes: Uint8Array): bigint { + if (!u8a(bytes)) throw new Error('Uint8Array expected'); + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); +} + +export function numberToBytesBE(n: number | bigint, len: number): Uint8Array { + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} +export function numberToBytesLE(n: number | bigint, len: number): Uint8Array { + return numberToBytesBE(n, len).reverse(); +} +// Unpadded, rarely used +export function numberToVarBytesBE(n: number | bigint): Uint8Array { + return hexToBytes(numberToHexUnpadded(n)); +} + +/** + * Takes hex string or Uint8Array, converts to Uint8Array. + * Validates output length. + * Will throw error for other types. + * @param title descriptive title for an error e.g. 'private key' + * @param hex hex string or Uint8Array + * @param expectedLength optional, will compare to result array's length + * @returns + */ +export function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array { + let res: Uint8Array; + if (typeof hex === 'string') { + try { + res = hexToBytes(hex); + } catch (e) { + throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`); + } + } else if (u8a(hex)) { + // Uint8Array.from() instead of hash.slice() because node.js Buffer + // is instance of Uint8Array, and its slice() creates **mutable** copy + res = Uint8Array.from(hex); + } else { + throw new Error(`${title} must be hex string or Uint8Array`); + } + const len = res.length; + if (typeof expectedLength === 'number' && len !== expectedLength) + throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); + return res; +} + +/** + * Copies several Uint8Arrays into one. + */ +export function concatBytes(...arrays: Uint8Array[]): Uint8Array { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} + +export function equalBytes(b1: Uint8Array, b2: Uint8Array) { + // We don't care about timing attacks here + if (b1.length !== b2.length) return false; + for (let i = 0; i < b1.length; i++) if (b1[i] !== b2[i]) return false; + return true; +} + +// Global symbols in both browsers and Node.js since v11 +// See https://github.com/microsoft/TypeScript/issues/31535 +declare const TextEncoder: any; + +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export function utf8ToBytes(str: string): Uint8Array { + if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} + +// Bit operations + +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + */ +export function bitLen(n: bigint) { + let len; + for (len = 0; n > _0n; n >>= _1n, len += 1); + return len; +} + +/** + * Gets single bit at position. + * NOTE: first bit position is 0 (same as arrays) + * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` + */ +export function bitGet(n: bigint, pos: number) { + return (n >> BigInt(pos)) & _1n; +} + +/** + * Sets single bit at position. + */ +export const bitSet = (n: bigint, pos: number, value: boolean) => { + return n | ((value ? _1n : _0n) << BigInt(pos)); +}; + +/** + * Calculate mask for N bits. Not using ** operator with bigints because of old engines. + * Same as BigInt(`0b${Array(i).fill('1').join('')}`) + */ +export const bitMask = (n: number) => (_2n << BigInt(n - 1)) - _1n; + +// DRBG + +const u8n = (data?: any) => new Uint8Array(data); // creates Uint8Array +const u8fr = (arr: any) => Uint8Array.from(arr); // another shortcut +type Pred = (v: Uint8Array) => T | undefined; +/** + * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + * @returns function that will call DRBG until 2nd arg returns something meaningful + * @example + * const drbg = createHmacDRBG(32, 32, hmac); + * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined + */ +export function createHmacDrbg( + hashLen: number, + qByteLen: number, + hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array +): (seed: Uint8Array, predicate: Pred) => T { + if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number'); + if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number'); + if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function'); + // Step B, Step C: set hashLen to 8*ceil(hlen/8) + let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same + let i = 0; // Iterations counter, will throw when over 1000 + const reset = () => { + v.fill(1); + k.fill(0); + i = 0; + }; + const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values) + const reseed = (seed = u8n()) => { + // HMAC-DRBG reseed() function. Steps D-G + k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed) + v = h(); // v = hmac(k || v) + if (seed.length === 0) return; + k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed) + v = h(); // v = hmac(k || v) + }; + const gen = () => { + // HMAC-DRBG generate() function + if (i++ >= 1000) throw new Error('drbg: tried 1000 values'); + let len = 0; + const out: Uint8Array[] = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes(...out); + }; + const genUntil = (seed: Uint8Array, pred: Pred): T => { + reset(); + reseed(seed); // Steps D-G + let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1] + while (!(res = pred(gen()))) reseed(); + reset(); + return res; + }; + return genUntil; +} + +// Validating curves and fields + +const validatorFns = { + bigint: (val: any) => typeof val === 'bigint', + function: (val: any) => typeof val === 'function', + boolean: (val: any) => typeof val === 'boolean', + string: (val: any) => typeof val === 'string', + isSafeInteger: (val: any) => Number.isSafeInteger(val), + array: (val: any) => Array.isArray(val), + field: (val: any, object: any) => (object as any).Fp.isValid(val), + hash: (val: any) => typeof val === 'function' && Number.isSafeInteger(val.outputLen), +} as const; +type Validator = keyof typeof validatorFns; +type ValMap> = { [K in keyof T]?: Validator }; +// type Record = { [P in K]: T; } + +export function validateObject>( + object: T, + validators: ValMap, + optValidators: ValMap = {} +) { + const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== 'function') + throw new Error(`Invalid validator "${type}", expected function`); + + const val = object[fieldName as keyof typeof object]; + if (isOptional && val === undefined) return; + if (!checkVal(val, object)) { + throw new Error( + `Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}` + ); + } + }; + for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false); + for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true); + return object; +} +// validate type tests +// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 }; +// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok! +// // Should fail type-check +// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' }); +// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' }); +// const z3 = validateObject(o, { test: 'boolean', z: 'bug' }); +// const z4 = validateObject(o, { a: 'boolean', z: 'bug' }); diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/weierstrass.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/weierstrass.ts new file mode 100644 index 0000000..5981ca4 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/src/abstract/weierstrass.ts @@ -0,0 +1,1220 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Short Weierstrass curve. The formula is: y² = x³ + ax + b +import * as mod from './modular.js'; +import * as ut from './utils.js'; +import { CHash, Hex, PrivKey, ensureBytes } from './utils.js'; +import { Group, GroupConstructor, wNAF, BasicCurve, validateBasic, AffinePoint } from './curve.js'; + +export type { AffinePoint }; +type HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; +type EndomorphismOpts = { + beta: bigint; + splitScalar: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint }; +}; +export type BasicWCurve = BasicCurve & { + // Params: a, b + a: T; + b: T; + + // Optional params + allowedPrivateKeyLengths?: readonly number[]; // for P521 + wrapPrivateKey?: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n + endo?: EndomorphismOpts; // Endomorphism options for Koblitz curves + // When a cofactor != 1, there can be an effective methods to: + // 1. Determine whether a point is torsion-free + isTorsionFree?: (c: ProjConstructor, point: ProjPointType) => boolean; + // 2. Clear torsion component + clearCofactor?: (c: ProjConstructor, point: ProjPointType) => ProjPointType; +}; + +type Entropy = Hex | true; +export type SignOpts = { lowS?: boolean; extraEntropy?: Entropy; prehash?: boolean }; +export type VerOpts = { lowS?: boolean; prehash?: boolean }; + +/** + * ### Design rationale for types + * + * * Interaction between classes from different curves should fail: + * `k256.Point.BASE.add(p256.Point.BASE)` + * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime + * * Different calls of `curve()` would return different classes - + * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve, + * it won't affect others + * + * TypeScript can't infer types for classes created inside a function. Classes is one instance of nominative types in TypeScript and interfaces only check for shape, so it's hard to create unique type for every function call. + * + * We can use generic types via some param, like curve opts, but that would: + * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params) + * which is hard to debug. + * 2. Params can be generic and we can't enforce them to be constant value: + * if somebody creates curve from non-constant params, + * it would be allowed to interact with other curves with non-constant params + * + * TODO: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol + */ + +// Instance for 3d XYZ points +export interface ProjPointType extends Group> { + readonly px: T; + readonly py: T; + readonly pz: T; + get x(): T; + get y(): T; + multiply(scalar: bigint): ProjPointType; + toAffine(iz?: T): AffinePoint; + isTorsionFree(): boolean; + clearCofactor(): ProjPointType; + assertValidity(): void; + hasEvenY(): boolean; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; + + multiplyUnsafe(scalar: bigint): ProjPointType; + multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined; + _setWindowSize(windowSize: number): void; +} +// Static methods for 3d XYZ points +export interface ProjConstructor extends GroupConstructor> { + new (x: T, y: T, z: T): ProjPointType; + fromAffine(p: AffinePoint): ProjPointType; + fromHex(hex: Hex): ProjPointType; + fromPrivateKey(privateKey: PrivKey): ProjPointType; + normalizeZ(points: ProjPointType[]): ProjPointType[]; +} + +export type CurvePointsType = BasicWCurve & { + // Bytes + fromBytes?: (bytes: Uint8Array) => AffinePoint; + toBytes?: (c: ProjConstructor, point: ProjPointType, isCompressed: boolean) => Uint8Array; +}; + +function validatePointOpts(curve: CurvePointsType) { + const opts = validateBasic(curve); + ut.validateObject( + opts, + { + a: 'field', + b: 'field', + }, + { + allowedPrivateKeyLengths: 'array', + wrapPrivateKey: 'boolean', + isTorsionFree: 'function', + clearCofactor: 'function', + allowInfinityPoint: 'boolean', + fromBytes: 'function', + toBytes: 'function', + } + ); + const { endo, Fp, a } = opts; + if (endo) { + if (!Fp.eql(a, Fp.ZERO)) { + throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0'); + } + if ( + typeof endo !== 'object' || + typeof endo.beta !== 'bigint' || + typeof endo.splitScalar !== 'function' + ) { + throw new Error('Expected endomorphism with beta: bigint and splitScalar: function'); + } + } + return Object.freeze({ ...opts } as const); +} + +export type CurvePointsRes = { + ProjectivePoint: ProjConstructor; + normPrivateKeyToScalar: (key: PrivKey) => bigint; + weierstrassEquation: (x: T) => T; + isWithinCurveOrder: (num: bigint) => boolean; +}; + +// ASN.1 DER encoding utilities +const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; +export const DER = { + // asn.1 DER encoding utils + Err: class DERErr extends Error { + constructor(m = '') { + super(m); + } + }, + _parseInt(data: Uint8Array): { d: bigint; l: Uint8Array } { + const { Err: E } = DER; + if (data.length < 2 || data[0] !== 0x02) throw new E('Invalid signature integer tag'); + const len = data[1]; + const res = data.subarray(2, len + 2); + if (!len || res.length !== len) throw new E('Invalid signature integer: wrong length'); + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + if (res[0] & 0b10000000) throw new E('Invalid signature integer: negative'); + if (res[0] === 0x00 && !(res[1] & 0b10000000)) + throw new E('Invalid signature integer: unnecessary leading zero'); + return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left + }, + toSig(hex: string | Uint8Array): { r: bigint; s: bigint } { + // parse DER signature + const { Err: E } = DER; + const data = typeof hex === 'string' ? h2b(hex) : hex; + if (!(data instanceof Uint8Array)) throw new Error('ui8a expected'); + let l = data.length; + if (l < 2 || data[0] != 0x30) throw new E('Invalid signature tag'); + if (data[1] !== l - 2) throw new E('Invalid signature: incorrect length'); + const { d: r, l: sBytes } = DER._parseInt(data.subarray(2)); + const { d: s, l: rBytesLeft } = DER._parseInt(sBytes); + if (rBytesLeft.length) throw new E('Invalid signature: left bytes after parsing'); + return { r, s }; + }, + hexFromSig(sig: { r: bigint; s: bigint }): string { + // Add leading zero if first byte has negative bit enabled. More details in '_parseInt' + const slice = (s: string): string => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s); + const h = (num: number | bigint) => { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; + }; + const s = slice(h(sig.s)); + const r = slice(h(sig.r)); + const shl = s.length / 2; + const rhl = r.length / 2; + const sl = h(shl); + const rl = h(rhl); + return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`; + }, +}; + +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4); + +export function weierstrassPoints(opts: CurvePointsType) { + const CURVE = validatePointOpts(opts); + const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ + + const toBytes = + CURVE.toBytes || + ((c: ProjConstructor, point: ProjPointType, isCompressed: boolean) => { + const a = point.toAffine(); + return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y)); + }); + const fromBytes = + CURVE.fromBytes || + ((bytes: Uint8Array) => { + // const head = bytes[0]; + const tail = bytes.subarray(1); + // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported'); + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + }); + + /** + * y² = x³ + ax + b: Short weierstrass curve formula + * @returns y² + */ + function weierstrassEquation(x: T): T { + const { a, b } = CURVE; + const x2 = Fp.sqr(x); // x * x + const x3 = Fp.mul(x2, x); // x2 * x + return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b + } + // Validate whether the passed curve params are valid. + // We check if curve equation works for generator point. + // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381. + // ProjectivePoint class has not been initialized yet. + if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error('bad generator point: equation left != right'); + + // Valid group elements reside in range 1..n-1 + function isWithinCurveOrder(num: bigint): boolean { + return typeof num === 'bigint' && _0n < num && num < CURVE.n; + } + function assertGE(num: bigint) { + if (!isWithinCurveOrder(num)) throw new Error('Expected valid bigint: 0 < bigint < curve.n'); + } + // Validates if priv key is valid and converts it to bigint. + // Supports options allowedPrivateKeyLengths and wrapPrivateKey. + function normPrivateKeyToScalar(key: PrivKey): bigint { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE; + if (lengths && typeof key !== 'bigint') { + if (key instanceof Uint8Array) key = ut.bytesToHex(key); + // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes + if (typeof key !== 'string' || !lengths.includes(key.length)) throw new Error('Invalid key'); + key = key.padStart(nByteLength * 2, '0'); + } + let num: bigint; + try { + num = + typeof key === 'bigint' + ? key + : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength)); + } catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + } + if (wrapPrivateKey) num = mod.mod(num, n); // disabled by default, enabled for BLS + assertGE(num); // num in range [1..N-1] + return num; + } + + const pointPrecomputes = new Map(); + function assertPrjPoint(other: unknown) { + if (!(other instanceof Point)) throw new Error('ProjectivePoint expected'); + } + /** + * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z) + * Default Point works in 2d / affine coordinates: (x, y) + * We're doing calculations in projective, because its operations don't require costly inversion. + */ + class Point implements ProjPointType { + static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); + static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); + + constructor(readonly px: T, readonly py: T, readonly pz: T) { + if (px == null || !Fp.isValid(px)) throw new Error('x required'); + if (py == null || !Fp.isValid(py)) throw new Error('y required'); + if (pz == null || !Fp.isValid(pz)) throw new Error('z required'); + } + + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + static fromAffine(p: AffinePoint): Point { + const { x, y } = p || {}; + if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point'); + if (p instanceof Point) throw new Error('projective point not allowed'); + const is0 = (i: T) => Fp.eql(i, Fp.ZERO); + // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0) + if (is0(x) && is0(y)) return Point.ZERO; + return new Point(x, y, Fp.ONE); + } + + get x(): T { + return this.toAffine().x; + } + get y(): T { + return this.toAffine().y; + } + + /** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + */ + static normalizeZ(points: Point[]): Point[] { + const toInv = Fp.invertBatch(points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex: Hex): Point { + const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex))); + P.assertValidity(); + return P; + } + + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey: PrivKey) { + return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + + // We calculate precomputes for elliptic curve point multiplication + // using windowed method. This specifies window size and + // stores precomputed values. Usually only base point would be precomputed. + _WINDOW_SIZE?: number; + + // "Private method", don't use it directly + _setWindowSize(windowSize: number) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + + // A point on curve is valid if it conforms to equation. + assertValidity(): void { + // Zero is valid point too! + if (this.is0()) { + if (CURVE.allowInfinityPoint) return; + throw new Error('bad point: ZERO'); + } + // Some 3rd-party test vectors require different wording between here & `fromCompressedHex` + const { x, y } = this.toAffine(); + // Check if x, y are valid field elements + if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not FE'); + const left = Fp.sqr(y); // y² + const right = weierstrassEquation(x); // x³ + ax + b + if (!Fp.eql(left, right)) throw new Error('bad point: equation left != right'); + if (!this.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup'); + } + hasEvenY(): boolean { + const { y } = this.toAffine(); + if (Fp.isOdd) return !Fp.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + + /** + * Compare one point to another. + */ + equals(other: Point): boolean { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); + const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); + return U1 && U2; + } + + /** + * Flips point to one corresponding to (x, -y) in Affine coordinates. + */ + negate(): Point { + return new Point(this.px, Fp.neg(this.py), this.pz); + } + + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a, b } = CURVE; + const b3 = Fp.mul(b, _3n); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + let t0 = Fp.mul(X1, X1); // step 1 + let t1 = Fp.mul(Y1, Y1); + let t2 = Fp.mul(Z1, Z1); + let t3 = Fp.mul(X1, Y1); + t3 = Fp.add(t3, t3); // step 5 + Z3 = Fp.mul(X1, Z1); + Z3 = Fp.add(Z3, Z3); + X3 = Fp.mul(a, Z3); + Y3 = Fp.mul(b3, t2); + Y3 = Fp.add(X3, Y3); // step 10 + X3 = Fp.sub(t1, Y3); + Y3 = Fp.add(t1, Y3); + Y3 = Fp.mul(X3, Y3); + X3 = Fp.mul(t3, X3); + Z3 = Fp.mul(b3, Z3); // step 15 + t2 = Fp.mul(a, t2); + t3 = Fp.sub(t0, t2); + t3 = Fp.mul(a, t3); + t3 = Fp.add(t3, Z3); + Z3 = Fp.add(t0, t0); // step 20 + t0 = Fp.add(Z3, t0); + t0 = Fp.add(t0, t2); + t0 = Fp.mul(t0, t3); + Y3 = Fp.add(Y3, t0); + t2 = Fp.mul(Y1, Z1); // step 25 + t2 = Fp.add(t2, t2); + t0 = Fp.mul(t2, t3); + X3 = Fp.sub(X3, t0); + Z3 = Fp.mul(t2, t1); + Z3 = Fp.add(Z3, Z3); // step 30 + Z3 = Fp.add(Z3, Z3); + return new Point(X3, Y3, Z3); + } + + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other: Point): Point { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + const a = CURVE.a; + const b3 = Fp.mul(CURVE.b, _3n); + let t0 = Fp.mul(X1, X2); // step 1 + let t1 = Fp.mul(Y1, Y2); + let t2 = Fp.mul(Z1, Z2); + let t3 = Fp.add(X1, Y1); + let t4 = Fp.add(X2, Y2); // step 5 + t3 = Fp.mul(t3, t4); + t4 = Fp.add(t0, t1); + t3 = Fp.sub(t3, t4); + t4 = Fp.add(X1, Z1); + let t5 = Fp.add(X2, Z2); // step 10 + t4 = Fp.mul(t4, t5); + t5 = Fp.add(t0, t2); + t4 = Fp.sub(t4, t5); + t5 = Fp.add(Y1, Z1); + X3 = Fp.add(Y2, Z2); // step 15 + t5 = Fp.mul(t5, X3); + X3 = Fp.add(t1, t2); + t5 = Fp.sub(t5, X3); + Z3 = Fp.mul(a, t4); + X3 = Fp.mul(b3, t2); // step 20 + Z3 = Fp.add(X3, Z3); + X3 = Fp.sub(t1, Z3); + Z3 = Fp.add(t1, Z3); + Y3 = Fp.mul(X3, Z3); + t1 = Fp.add(t0, t0); // step 25 + t1 = Fp.add(t1, t0); + t2 = Fp.mul(a, t2); + t4 = Fp.mul(b3, t4); + t1 = Fp.add(t1, t2); + t2 = Fp.sub(t0, t2); // step 30 + t2 = Fp.mul(a, t2); + t4 = Fp.add(t4, t2); + t0 = Fp.mul(t1, t4); + Y3 = Fp.add(Y3, t0); + t0 = Fp.mul(t5, t4); // step 35 + X3 = Fp.mul(t3, X3); + X3 = Fp.sub(X3, t0); + t0 = Fp.mul(t3, t1); + Z3 = Fp.mul(t5, Z3); + Z3 = Fp.add(Z3, t0); // step 40 + return new Point(X3, Y3, Z3); + } + + subtract(other: Point) { + return this.add(other.negate()); + } + + private is0() { + return this.equals(Point.ZERO); + } + private wNAF(n: bigint): { p: Point; f: Point } { + return wnaf.wNAFCached(this, pointPrecomputes, n, (comp: Point[]) => { + const toInv = Fp.invertBatch(comp.map((p) => p.pz)); + return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + }); + } + + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(n: bigint): Point { + const I = Point.ZERO; + if (n === _0n) return I; + assertGE(n); // Will throw on 0 + if (n === _1n) return this; + const { endo } = CURVE; + if (!endo) return wnaf.unsafeLadder(this, n); + + // Apply endomorphism + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let k1p = I; + let k2p = I; + let d: Point = this; + while (k1 > _0n || k2 > _0n) { + if (k1 & _1n) k1p = k1p.add(d); + if (k2 & _1n) k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n; + k2 >>= _1n; + } + if (k1neg) k1p = k1p.negate(); + if (k2neg) k2p = k2p.negate(); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar by which the point would be multiplied + * @returns New point + */ + multiply(scalar: bigint): Point { + assertGE(scalar); + let n = scalar; + let point: Point, fake: Point; // Fake point is used to const-time mult + const { endo } = CURVE; + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } else { + const { p, f } = this.wNAF(n); + point = p; + fake = f; + } + // Normalize `z` for both points, but return only real one + return Point.normalizeZ([point, fake])[0]; + } + + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q: Point, a: bigint, b: bigint): Point | undefined { + const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes + const mul = ( + P: Point, + a: bigint // Select faster multiply() method + ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a)); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? undefined : sum; + } + + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + toAffine(iz?: T): AffinePoint { + const { px: x, py: y, pz: z } = this; + const is0 = this.is0(); + // If invZ was 0, we return zero point. However we still want to execute + // all operations, so we replace invZ with a random number, 1. + if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(z); + const ax = Fp.mul(x, iz); + const ay = Fp.mul(y, iz); + const zz = Fp.mul(z, iz); + if (is0) return { x: Fp.ZERO, y: Fp.ZERO }; + if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + } + isTorsionFree(): boolean { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n) return true; // No subgroups, always torsion-free + if (isTorsionFree) return isTorsionFree(Point, this); + throw new Error('isTorsionFree() has not been declared for the elliptic curve'); + } + clearCofactor(): Point { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n) return this; // Fast-path + if (clearCofactor) return clearCofactor(Point, this) as Point; + return this.multiplyUnsafe(CURVE.h); + } + + toRawBytes(isCompressed = true): Uint8Array { + this.assertValidity(); + return toBytes(Point, this, isCompressed); + } + + toHex(isCompressed = true): string { + return ut.bytesToHex(this.toRawBytes(isCompressed)); + } + } + const _bits = CURVE.nBitLength; + const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + // Validate if generator point is on curve + return { + CURVE, + ProjectivePoint: Point as ProjConstructor, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + }; +} + +// Instance +export interface SignatureType { + readonly r: bigint; + readonly s: bigint; + readonly recovery?: number; + assertValidity(): void; + addRecoveryBit(recovery: number): RecoveredSignatureType; + hasHighS(): boolean; + normalizeS(): SignatureType; + recoverPublicKey(msgHash: Hex): ProjPointType; + toCompactRawBytes(): Uint8Array; + toCompactHex(): string; + // DER-encoded + toDERRawBytes(isCompressed?: boolean): Uint8Array; + toDERHex(isCompressed?: boolean): string; +} +export type RecoveredSignatureType = SignatureType & { + readonly recovery: number; +}; +// Static methods +export type SignatureConstructor = { + new (r: bigint, s: bigint): SignatureType; + fromCompact(hex: Hex): SignatureType; + fromDER(hex: Hex): SignatureType; +}; +type SignatureLike = { r: bigint; s: bigint }; + +export type PubKey = Hex | ProjPointType; + +export type CurveType = BasicWCurve & { + hash: CHash; // CHash not FHash because we need outputLen for DRBG + hmac: HmacFnSync; + randomBytes: (bytesLength?: number) => Uint8Array; + lowS?: boolean; + bits2int?: (bytes: Uint8Array) => bigint; + bits2int_modN?: (bytes: Uint8Array) => bigint; +}; + +function validateOpts(curve: CurveType) { + const opts = validateBasic(curve); + ut.validateObject( + opts, + { + hash: 'hash', + hmac: 'function', + randomBytes: 'function', + }, + { + bits2int: 'function', + bits2int_modN: 'function', + lowS: 'boolean', + } + ); + return Object.freeze({ lowS: true, ...opts } as const); +} + +export type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType; + verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean; + ProjectivePoint: ProjConstructor; + Signature: SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: PrivKey) => bigint; + isValidPrivateKey(privateKey: PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: ProjPointType) => ProjPointType; + }; +}; + +export function weierstrass(curveDef: CurveType): CurveFn { + const CURVE = validateOpts(curveDef) as ReturnType; + const { Fp, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32 + const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32 + + function isValidFieldElement(num: bigint): boolean { + return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE + } + function modN(a: bigint) { + return mod.mod(a, CURVE_ORDER); + } + function invN(a: bigint) { + return mod.invert(a, CURVE_ORDER); + } + + const { + ProjectivePoint: Point, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + } = weierstrassPoints({ + ...CURVE, + toBytes(c, point, isCompressed: boolean): Uint8Array { + const a = point.toAffine(); + const x = Fp.toBytes(a.x); + const cat = ut.concatBytes; + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x); + } else { + return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y)); + } + }, + fromBytes(bytes: Uint8Array) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + // this.assertValidity() is done inside of fromHex + if (len === compressedLen && (head === 0x02 || head === 0x03)) { + const x = ut.bytesToNumberBE(tail); + if (!isValidFieldElement(x)) throw new Error('Point is not on curve'); + const y2 = weierstrassEquation(x); // y² = x³ + ax + b + let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 + const isYOdd = (y & _1n) === _1n; + // ECDSA + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) y = Fp.neg(y); + return { x, y }; + } else if (len === uncompressedLen && head === 0x04) { + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + } else { + throw new Error( + `Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes` + ); + } + }, + }); + const numToNByteStr = (num: bigint): string => + ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength)); + + function isBiggerThanHalfOrder(number: bigint) { + const HALF = CURVE_ORDER >> _1n; + return number > HALF; + } + + function normalizeS(s: bigint) { + return isBiggerThanHalfOrder(s) ? modN(-s) : s; + } + // slice bytes num + const slcNum = (b: Uint8Array, from: number, to: number) => ut.bytesToNumberBE(b.slice(from, to)); + + /** + * ECDSA signature with its (r, s) properties. Supports DER & compact representations. + */ + class Signature implements SignatureType { + constructor(readonly r: bigint, readonly s: bigint, readonly recovery?: number) { + this.assertValidity(); + } + + // pair (bytes of r, bytes of s) + static fromCompact(hex: Hex) { + const l = CURVE.nByteLength; + hex = ensureBytes('compactSignature', hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex: Hex) { + const { r, s } = DER.toSig(ensureBytes('DER', hex)); + return new Signature(r, s); + } + + assertValidity(): void { + // can use assertGE here + if (!isWithinCurveOrder(this.r)) throw new Error('r must be 0 < r < CURVE.n'); + if (!isWithinCurveOrder(this.s)) throw new Error('s must be 0 < s < CURVE.n'); + } + + addRecoveryBit(recovery: number): RecoveredSignature { + return new Signature(this.r, this.s, recovery) as RecoveredSignature; + } + + recoverPublicKey(msgHash: Hex): typeof Point.BASE { + const { r, s, recovery: rec } = this; + const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash + if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error('recovery id invalid'); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp.ORDER) throw new Error('recovery id 2 or 3 invalid'); + const prefix = (rec & 1) === 0 ? '02' : '03'; + const R = Point.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); // r^-1 + const u1 = modN(-h * ir); // -hr^-1 + const u2 = modN(s * ir); // sr^-1 + const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1) + if (!Q) throw new Error('point at infinify'); // unsafe is fine: no priv data leaked + Q.assertValidity(); + return Q; + } + + // Signatures should be low-s, to prevent malleability. + hasHighS(): boolean { + return isBiggerThanHalfOrder(this.s); + } + + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; + } + + // DER-encoded + toDERRawBytes() { + return ut.hexToBytes(this.toDERHex()); + } + toDERHex() { + return DER.hexFromSig({ r: this.r, s: this.s }); + } + + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return ut.hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + type RecoveredSignature = Signature & { recovery: number }; + + const utils = { + isValidPrivateKey(privateKey: PrivKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } catch (error) { + return false; + } + }, + normPrivateKeyToScalar: normPrivateKeyToScalar, + + /** + * Produces cryptographically secure private key from random of size (nBitLength+64) + * as per FIPS 186 B.4.1 with modulo bias being neglible. + */ + randomPrivateKey: (): Uint8Array => { + const rand = CURVE.randomBytes(Fp.BYTES + 8); + const num = mod.hashToPrivateScalar(rand, CURVE_ORDER); + return ut.numberToBytesBE(num, CURVE.nByteLength); + }, + + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here + return point; + }, + }; + + /** + * Computes public key for a private key. Checks for validity of the private key. + * @param privateKey private key + * @param isCompressed whether to return compact (default), or full key + * @returns Public key, full when isCompressed=false; short when isCompressed=true + */ + function getPublicKey(privateKey: PrivKey, isCompressed = true): Uint8Array { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + + /** + * Quick and dirty check for item being public key. Does not validate hex, or being on-curve. + */ + function isProbPub(item: PrivKey | PubKey): boolean { + const arr = item instanceof Uint8Array; + const str = typeof item === 'string'; + const len = (arr || str) && (item as Hex).length; + if (arr) return len === compressedLen || len === uncompressedLen; + if (str) return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point) return true; + return false; + } + + /** + * ECDH (Elliptic Curve Diffie Hellman). + * Computes shared public key from private key and public key. + * Checks: 1) private key validity 2) shared key is on-curve. + * Does NOT hash the result. + * @param privateA private key + * @param publicB different public key + * @param isCompressed whether to return compact (default), or full key + * @returns shared public key + */ + function getSharedSecret(privateA: PrivKey, publicB: Hex, isCompressed = true): Uint8Array { + if (isProbPub(privateA)) throw new Error('first arg must be private key'); + if (!isProbPub(publicB)) throw new Error('second arg must be public key'); + const b = Point.fromHex(publicB); // check for being on-curve + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + + // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets. + // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int. + // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same. + // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors + const bits2int = + CURVE.bits2int || + function (bytes: Uint8Array): bigint { + // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m) + // for some cases, since bytes.length * 8 is not actual bitLength. + const num = ut.bytesToNumberBE(bytes); // check for == u8 done here + const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits + return delta > 0 ? num >> BigInt(delta) : num; + }; + const bits2int_modN = + CURVE.bits2int_modN || + function (bytes: Uint8Array): bigint { + return modN(bits2int(bytes)); // can't use bytesToNumberBE here + }; + // NOTE: pads output with zero as per spec + const ORDER_MASK = ut.bitMask(CURVE.nBitLength); + /** + * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. + */ + function int2octets(num: bigint): Uint8Array { + if (typeof num !== 'bigint') throw new Error('bigint expected'); + if (!(_0n <= num && num < ORDER_MASK)) + throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); + // works with order, can have different size than numToField! + return ut.numberToBytesBE(num, CURVE.nByteLength); + } + + // Steps A, D of RFC6979 3.2 + // Creates RFC6979 seed; converts msg/privKey to numbers. + // Used only in sign, not in verify. + // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521. + // Also it can be bigger for P224 + SHA256 + function prepSig(msgHash: Hex, privateKey: PrivKey, opts = defaultSigOpts) { + if (['recovered', 'canonical'].some((k) => k in opts)) + throw new Error('sign() legacy options not supported'); + const { hash, randomBytes } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default + if (lowS == null) lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash + msgHash = ensureBytes('msgHash', msgHash); + if (prehash) msgHash = ensureBytes('prehashed msgHash', hash(msgHash)); + + // We can't later call bits2octets, since nested bits2int is broken for curves + // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call. + // const bits2octets = (bits) => int2octets(bits2int_modN(bits)) + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint + const seedArgs = [int2octets(d), int2octets(h1int)]; + // extraEntropy. RFC6979 3.6: additional k' (optional). + if (ent != null) { + // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') + const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is + seedArgs.push(ensureBytes('extraEntropy', e, Fp.BYTES)); // check for being of size BYTES + } + const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2 + const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash! + // Converts signature params into point w r/s, checks result for validity. + function k2sig(kBytes: Uint8Array): RecoveredSignature | undefined { + // RFC 6979 Section 3.2, step 3: k = bits2int(T) + const k = bits2int(kBytes); // Cannot use fields methods, since it is group element + if (!isWithinCurveOrder(k)) return; // Important: all mod() calls here must be done over N + const ik = invN(k); // k^-1 mod n + const q = Point.BASE.multiply(k).toAffine(); // q = Gk + const r = modN(q.x); // r = q.x mod n + if (r === _0n) return; + // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to + // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it: + // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT + const s = modN(ik * modN(m + r * d)); // Not using blinding here + if (s === _0n) return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n) + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); // if lowS was passed, ensure s is always + recovery ^= 1; // // in the bottom half of N + } + return new Signature(r, normS, recovery) as RecoveredSignature; // use normS, not s + } + return { seed, k2sig }; + } + const defaultSigOpts: SignOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts: VerOpts = { lowS: CURVE.lowS, prehash: false }; + + /** + * Signs message hash with a private key. + * ``` + * sign(m, d, k) where + * (x, y) = G × k + * r = x mod n + * s = (m + dr)/k mod n + * ``` + * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`. + * @param privKey private key + * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg. + * @returns signature with recovery param + */ + function sign(msgHash: Hex, privKey: PrivKey, opts = defaultSigOpts): RecoveredSignature { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2. + const C = CURVE; + const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); // Steps B, C, D, E, F, G + } + + // Enable precomputes. Slows down first publicKey computation by 20ms. + Point.BASE._setWindowSize(8); + // utils.precompute(8, ProjectivePoint.BASE) + + /** + * Verifies a signature against message hash and public key. + * Rejects lowS signatures by default: to override, + * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf: + * + * ``` + * verify(r, s, h, P) where + * U1 = hs^-1 mod n + * U2 = rs^-1 mod n + * R = U1⋅G - U2⋅P + * mod(R.x, n) == r + * ``` + */ + function verify( + signature: Hex | SignatureLike, + msgHash: Hex, + publicKey: Hex, + opts = defaultVerOpts + ): boolean { + const sg = signature; + msgHash = ensureBytes('msgHash', msgHash); + publicKey = ensureBytes('publicKey', publicKey); + if ('strict' in opts) throw new Error('options.strict was renamed to lowS'); + const { lowS, prehash } = opts; + + let _sig: Signature | undefined = undefined; + let P: ProjPointType; + try { + if (typeof sg === 'string' || sg instanceof Uint8Array) { + // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length). + // Since DER can also be 2*nByteLength bytes, we check for it first. + try { + _sig = Signature.fromDER(sg); + } catch (derError) { + if (!(derError instanceof DER.Err)) throw derError; + _sig = Signature.fromCompact(sg); + } + } else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') { + const { r, s } = sg; + _sig = new Signature(r, s); + } else { + throw new Error('PARSE'); + } + P = Point.fromHex(publicKey); + } catch (error) { + if ((error as Error).message === 'PARSE') + throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; + } + if (lowS && _sig.hasHighS()) return false; + if (prehash) msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element + const is = invN(s); // s^-1 + const u1 = modN(h * is); // u1 = hs^-1 mod n + const u2 = modN(r * is); // u2 = rs^-1 mod n + const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P + if (!R) return false; + const v = modN(R.x); + return v === r; + } + return { + CURVE, + getPublicKey, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point, + Signature, + utils, + }; +} + +/** + * Implementation of the Shallue and van de Woestijne method for any weierstrass curve. + * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular. + * b = True and y = sqrt(u / v) if (u / v) is square in F, and + * b = False and y = sqrt(Z * (u / v)) otherwise. + * @param Fp + * @param Z + * @returns + */ +export function SWUFpSqrtRatio(Fp: mod.IField, Z: T) { + // Generic implementation + const q = Fp.ORDER; + let l = _0n; + for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n; + const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1. + // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<. + // 2n ** c1 == 2n << (c1-1) + const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n); + const _2n_pow_c1 = _2n_pow_c1_1 * _2n; + const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic + const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic + const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic + const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic + const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2 + const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2) + let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => { + let tv1 = c6; // 1. tv1 = c6 + let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4 + let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2 + tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v + let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3 + tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3 + tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2 + tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v + tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u + let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2 + tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5 + let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1 + tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7 + tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1 + tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR) + tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR) + // 17. for i in (c1, c1 - 1, ..., 2): + for (let i = c1; i > _1n; i--) { + let tv5 = i - _2n; // 18. tv5 = i - 2 + tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5 + let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5 + const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1 + tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1 + tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1 + tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1 + tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1) + tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1) + } + return { isValid: isQR, value: tv3 }; + }; + if (Fp.ORDER % _4n === _3n) { + // sqrt_ratio_3mod4(u, v) + const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic + const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z) + sqrtRatio = (u: T, v: T) => { + let tv1 = Fp.sqr(v); // 1. tv1 = v^2 + const tv2 = Fp.mul(u, v); // 2. tv2 = u * v + tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2 + let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1 + y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2 + const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2 + const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v + const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u + let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR) + return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2 + }; + } + // No curves uses that + // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8 + return sqrtRatio; +} +/** + * From draft-irtf-cfrg-hash-to-curve-16 + */ +export function mapToCurveSimpleSWU( + Fp: mod.IField, + opts: { + A: T; + B: T; + Z: T; + } +) { + mod.validateField(Fp); + if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z)) + throw new Error('mapToCurveSimpleSWU: invalid opts'); + const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z); + if (!Fp.isOdd) throw new Error('Fp.isOdd is not implemented!'); + // Input: u, an element of F. + // Output: (x, y), a point on E. + return (u: T): { x: T; y: T } => { + // prettier-ignore + let tv1, tv2, tv3, tv4, tv5, tv6, x, y; + tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1 + tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2 + tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1 + tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1 + tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3 + tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0) + tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4 + tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2 + tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2 + tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6 + tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5 + tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3 + tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4 + tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6 + tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5 + x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3 + const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6) + y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1 + y = Fp.mul(y, value); // 20. y = y * y1 + x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square) + y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square) + const e1 = Fp.isOdd!(u) === Fp.isOdd!(y); // 23. e1 = sgn0(u) == sgn0(y) + y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1) + x = Fp.div(x, tv4); // 25. x = x / tv4 + return { x, y }; + }; +} diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/src/bls12-381.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/src/bls12-381.ts new file mode 100644 index 0000000..5f6fdc2 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/src/bls12-381.ts @@ -0,0 +1,1351 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + +// bls12-381 pairing-friendly Barreto-Lynn-Scott elliptic curve construction allows to: +// - Construct zk-SNARKs at the 128-bit security +// - Use threshold signatures, which allows a user to sign lots of messages with one signature and +// verify them swiftly in a batch, using Boneh-Lynn-Shacham signature scheme. +// +// The library uses G1 for public keys and G2 for signatures. Support for G1 signatures is planned. +// Compatible with Algorand, Chia, Dfinity, Ethereum, FIL, Zcash. Matches specs +// [pairing-curves-11](https://tools.ietf.org/html/draft-irtf-cfrg-pairing-friendly-curves-11), +// [bls-sigs-04](https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-04), +// [hash-to-curve-12](https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-12). +// +// ### Summary +// 1. BLS Relies on Bilinear Pairing (expensive) +// 2. Private Keys: 32 bytes +// 3. Public Keys: 48 bytes: 381 bit affine x coordinate, encoded into 48 big-endian bytes. +// 4. Signatures: 96 bytes: two 381 bit integers (affine x coordinate), encoded into two 48 big-endian byte arrays. +// - The signature is a point on the G2 subgroup, which is defined over a finite field +// with elements twice as big as the G1 curve (G2 is over Fp2 rather than Fp. Fp2 is analogous to the complex numbers). +// 5. The 12 stands for the Embedding degree. +// +// ### Formulas +// - `P = pk x G` - public keys +// - `S = pk x H(m)` - signing +// - `e(P, H(m)) == e(G, S)` - verification using pairings +// - `e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))` - signature aggregation +// Filecoin uses little endian byte arrays for private keys - +// so ensure to reverse byte order if you'll use it with FIL. +import { sha256 } from '@noble/hashes/sha256'; +import { randomBytes } from '@noble/hashes/utils'; +import { bls, CurveFn } from './abstract/bls.js'; +import * as mod from './abstract/modular.js'; +import { + concatBytes as concatB, + ensureBytes, + numberToBytesBE, + bytesToNumberBE, + bitLen, + bitSet, + bitGet, + Hex, + bitMask, + bytesToHex, +} from './abstract/utils.js'; +// Types +import { + ProjPointType, + ProjConstructor, + mapToCurveSimpleSWU, + AffinePoint, +} from './abstract/weierstrass.js'; +import { isogenyMap } from './abstract/hash-to-curve.js'; + +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4); +// prettier-ignore +const _8n = BigInt(8), _16n = BigInt(16); + +// CURVE FIELDS +// Finite field over p. +const Fp_raw = BigInt( + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab' +); +const Fp = mod.Field(Fp_raw); +type Fp = bigint; +// Finite field over r. +// This particular field is not used anywhere in bls12-381, but it is still useful. +const Fr = mod.Field(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')); + +// Fp₂ over complex plane +type BigintTuple = [bigint, bigint]; +type Fp2 = { c0: bigint; c1: bigint }; +const Fp2Add = ({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2) => ({ + c0: Fp.add(c0, r0), + c1: Fp.add(c1, r1), +}); +const Fp2Subtract = ({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2) => ({ + c0: Fp.sub(c0, r0), + c1: Fp.sub(c1, r1), +}); +const Fp2Multiply = ({ c0, c1 }: Fp2, rhs: Fp2) => { + if (typeof rhs === 'bigint') return { c0: Fp.mul(c0, rhs), c1: Fp.mul(c1, rhs) }; + // (a+bi)(c+di) = (ac−bd) + (ad+bc)i + const { c0: r0, c1: r1 } = rhs; + let t1 = Fp.mul(c0, r0); // c0 * o0 + let t2 = Fp.mul(c1, r1); // c1 * o1 + // (T1 - T2) + ((c0 + c1) * (r0 + r1) - (T1 + T2))*i + const o0 = Fp.sub(t1, t2); + const o1 = Fp.sub(Fp.mul(Fp.add(c0, c1), Fp.add(r0, r1)), Fp.add(t1, t2)); + return { c0: o0, c1: o1 }; +}; +const Fp2Square = ({ c0, c1 }: Fp2) => { + const a = Fp.add(c0, c1); + const b = Fp.sub(c0, c1); + const c = Fp.add(c0, c0); + return { c0: Fp.mul(a, b), c1: Fp.mul(c, c1) }; +}; +type Fp2Utils = { + fromBigTuple: (tuple: BigintTuple | bigint[]) => Fp2; + reim: (num: Fp2) => { re: bigint; im: bigint }; + mulByNonresidue: (num: Fp2) => Fp2; + multiplyByB: (num: Fp2) => Fp2; + frobeniusMap(num: Fp2, power: number): Fp2; +}; +// G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1), +// where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where +// G² - 1 +// h2q +// NOTE: ORDER was wrong! +const FP2_ORDER = Fp_raw * Fp_raw; + +const Fp2: mod.IField & Fp2Utils = { + ORDER: FP2_ORDER, + BITS: bitLen(FP2_ORDER), + BYTES: Math.ceil(bitLen(FP2_ORDER) / 8), + MASK: bitMask(bitLen(FP2_ORDER)), + ZERO: { c0: Fp.ZERO, c1: Fp.ZERO }, + ONE: { c0: Fp.ONE, c1: Fp.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => typeof c0 === 'bigint' && typeof c1 === 'bigint', + is0: ({ c0, c1 }) => Fp.is0(c0) && Fp.is0(c1), + eql: ({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2) => Fp.eql(c0, r0) && Fp.eql(c1, r1), + neg: ({ c0, c1 }) => ({ c0: Fp.neg(c0), c1: Fp.neg(c1) }), + pow: (num, power) => mod.FpPow(Fp2, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp2, nums), + // Normalized + add: Fp2Add, + sub: Fp2Subtract, + mul: Fp2Multiply, + sqr: Fp2Square, + // NonNormalized stuff + addN: Fp2Add, + subN: Fp2Subtract, + mulN: Fp2Multiply, + sqrN: Fp2Square, + // Why inversion for bigint inside Fp instead of Fp2? it is even used in that context? + div: (lhs, rhs) => Fp2.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp2.inv(rhs)), + inv: ({ c0: a, c1: b }) => { + // We wish to find the multiplicative inverse of a nonzero + // element a + bu in Fp2. We leverage an identity + // + // (a + bu)(a - bu) = a² + b² + // + // which holds because u² = -1. This can be rewritten as + // + // (a + bu)(a - bu)/(a² + b²) = 1 + // + // because a² + b² = 0 has no nonzero solutions for (a, b). + // This gives that (a - bu)/(a² + b²) is the inverse + // of (a + bu). Importantly, this can be computing using + // only a single inversion in Fp. + const factor = Fp.inv(Fp.create(a * a + b * b)); + return { c0: Fp.mul(factor, Fp.create(a)), c1: Fp.mul(factor, Fp.create(-b)) }; + }, + sqrt: (num) => { + if (Fp2.eql(num, Fp2.ZERO)) return Fp2.ZERO; // Algo doesn't handles this case + // TODO: Optimize this line. It's extremely slow. + // Speeding this up would boost aggregateSignatures. + // https://eprint.iacr.org/2012/685.pdf applicable? + // https://github.com/zkcrypto/bls12_381/blob/080eaa74ec0e394377caa1ba302c8c121df08b07/src/fp2.rs#L250 + // https://github.com/supranational/blst/blob/aae0c7d70b799ac269ff5edf29d8191dbd357876/src/exp2.c#L1 + // Inspired by https://github.com/dalek-cryptography/curve25519-dalek/blob/17698df9d4c834204f83a3574143abacb4fc81a5/src/field.rs#L99 + const candidateSqrt = Fp2.pow(num, (Fp2.ORDER + _8n) / _16n); + const check = Fp2.div(Fp2.sqr(candidateSqrt), num); // candidateSqrt.square().div(this); + const R = FP2_ROOTS_OF_UNITY; + const divisor = [R[0], R[2], R[4], R[6]].find((r) => Fp2.eql(r, check)); + if (!divisor) throw new Error('No root'); + const index = R.indexOf(divisor); + const root = R[index / 2]; + if (!root) throw new Error('Invalid root'); + const x1 = Fp2.div(candidateSqrt, root); + const x2 = Fp2.neg(x1); + const { re: re1, im: im1 } = Fp2.reim(x1); + const { re: re2, im: im2 } = Fp2.reim(x2); + if (im1 > im2 || (im1 === im2 && re1 > re2)) return x1; + return x2; + }, + // Same as sgn0_fp2 in draft-irtf-cfrg-hash-to-curve-16 + isOdd: (x: Fp2) => { + const { re: x0, im: x1 } = Fp2.reim(x); + const sign_0 = x0 % _2n; + const zero_0 = x0 === _0n; + const sign_1 = x1 % _2n; + return BigInt(sign_0 || (zero_0 && sign_1)) == _1n; + }, + // Bytes util + fromBytes(b: Uint8Array): Fp2 { + if (b.length !== Fp2.BYTES) throw new Error(`fromBytes wrong length=${b.length}`); + return { c0: Fp.fromBytes(b.subarray(0, Fp.BYTES)), c1: Fp.fromBytes(b.subarray(Fp.BYTES)) }; + }, + toBytes: ({ c0, c1 }) => concatB(Fp.toBytes(c0), Fp.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp.cmov(c0, r0, c), + c1: Fp.cmov(c1, r1, c), + }), + // Specific utils + // toString() { + // return `Fp2(${this.c0} + ${this.c1}×i)`; + // } + reim: ({ c0, c1 }) => ({ re: c0, im: c1 }), + // multiply by u + 1 + mulByNonresidue: ({ c0, c1 }) => ({ c0: Fp.sub(c0, c1), c1: Fp.add(c0, c1) }), + multiplyByB: ({ c0, c1 }) => { + let t0 = Fp.mul(c0, _4n); // 4 * c0 + let t1 = Fp.mul(c1, _4n); // 4 * c1 + // (T0-T1) + (T0+T1)*i + return { c0: Fp.sub(t0, t1), c1: Fp.add(t0, t1) }; + }, + fromBigTuple: (tuple: BigintTuple | bigint[]) => { + if (tuple.length !== 2) throw new Error('Invalid tuple'); + const fps = tuple.map((n) => Fp.create(n)) as [Fp, Fp]; + return { c0: fps[0], c1: fps[1] }; + }, + frobeniusMap: ({ c0, c1 }, power: number): Fp2 => ({ + c0, + c1: Fp.mul(c1, FP2_FROBENIUS_COEFFICIENTS[power % 2]), + }), +}; +// Finite extension field over irreducible polynominal. +// Fp(u) / (u² - β) where β = -1 +const FP2_FROBENIUS_COEFFICIENTS = [ + BigInt('0x1'), + BigInt( + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa' + ), +].map((item) => Fp.create(item)); + +// For Fp2 roots of unity. +const rv1 = BigInt( + '0x6af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09' +); +// const ev1 = +// BigInt('0x699be3b8c6870965e5bf892ad5d2cc7b0e85a117402dfd83b7f4a947e02d978498255a2aaec0ac627b5afbdf1bf1c90'); +// const ev2 = +// BigInt('0x8157cd83046453f5dd0972b6e3949e4288020b5b8a9cc99ca07e27089a2ce2436d965026adad3ef7baba37f2183e9b5'); +// const ev3 = +// BigInt('0xab1c2ffdd6c253ca155231eb3e71ba044fd562f6f72bc5bad5ec46a0b7a3b0247cf08ce6c6317f40edbc653a72dee17'); +// const ev4 = +// BigInt('0xaa404866706722864480885d68ad0ccac1967c7544b447873cc37e0181271e006df72162a3d3e0287bf597fbf7f8fc1'); + +// Eighth roots of unity, used for computing square roots in Fp2. +// To verify or re-calculate: +// Array(8).fill(new Fp2([1n, 1n])).map((fp2, k) => fp2.pow(Fp2.ORDER * BigInt(k) / 8n)) +const FP2_ROOTS_OF_UNITY = [ + [_1n, _0n], + [rv1, -rv1], + [_0n, _1n], + [rv1, rv1], + [-_1n, _0n], + [-rv1, rv1], + [_0n, -_1n], + [-rv1, -rv1], +].map((pair) => Fp2.fromBigTuple(pair)); +// eta values, used for computing sqrt(g(X1(t))) +// const FP2_ETAs = [ +// [ev1, ev2], +// [-ev2, ev1], +// [ev3, ev4], +// [-ev4, ev3], +// ].map((pair) => Fp2.fromBigTuple(pair)); + +// Finite extension field over irreducible polynominal. +// Fp2(v) / (v³ - ξ) where ξ = u + 1 +type BigintSix = [bigint, bigint, bigint, bigint, bigint, bigint]; +type Fp6 = { c0: Fp2; c1: Fp2; c2: Fp2 }; +const Fp6Add = ({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6) => ({ + c0: Fp2.add(c0, r0), + c1: Fp2.add(c1, r1), + c2: Fp2.add(c2, r2), +}); +const Fp6Subtract = ({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6) => ({ + c0: Fp2.sub(c0, r0), + c1: Fp2.sub(c1, r1), + c2: Fp2.sub(c2, r2), +}); +const Fp6Multiply = ({ c0, c1, c2 }: Fp6, rhs: Fp6 | bigint) => { + if (typeof rhs === 'bigint') { + return { + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }; + } + const { c0: r0, c1: r1, c2: r2 } = rhs; + const t0 = Fp2.mul(c0, r0); // c0 * o0 + const t1 = Fp2.mul(c1, r1); // c1 * o1 + const t2 = Fp2.mul(c2, r2); // c2 * o2 + return { + // t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1) + c0: Fp2.add( + t0, + Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), Fp2.add(r1, r2)), Fp2.add(t1, t2))) + ), + // (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1) + c1: Fp2.add( + Fp2.sub(Fp2.mul(Fp2.add(c0, c1), Fp2.add(r0, r1)), Fp2.add(t0, t1)), + Fp2.mulByNonresidue(t2) + ), + // T1 + (c0 + c2) * (r0 + r2) - T0 + T2 + c2: Fp2.sub(Fp2.add(t1, Fp2.mul(Fp2.add(c0, c2), Fp2.add(r0, r2))), Fp2.add(t0, t2)), + }; +}; +const Fp6Square = ({ c0, c1, c2 }: Fp6) => { + let t0 = Fp2.sqr(c0); // c0² + let t1 = Fp2.mul(Fp2.mul(c0, c1), _2n); // 2 * c0 * c1 + let t3 = Fp2.mul(Fp2.mul(c1, c2), _2n); // 2 * c1 * c2 + let t4 = Fp2.sqr(c2); // c2² + return { + c0: Fp2.add(Fp2.mulByNonresidue(t3), t0), // T3 * (u + 1) + T0 + c1: Fp2.add(Fp2.mulByNonresidue(t4), t1), // T4 * (u + 1) + T1 + // T1 + (c0 - c1 + c2)² + T3 - T0 - T4 + c2: Fp2.sub(Fp2.sub(Fp2.add(Fp2.add(t1, Fp2.sqr(Fp2.add(Fp2.sub(c0, c1), c2))), t3), t0), t4), + }; +}; +type Fp6Utils = { + fromBigSix: (tuple: BigintSix) => Fp6; + mulByNonresidue: (num: Fp6) => Fp6; + frobeniusMap(num: Fp6, power: number): Fp6; + multiplyBy1(num: Fp6, b1: Fp2): Fp6; + multiplyBy01(num: Fp6, b0: Fp2, b1: Fp2): Fp6; + multiplyByFp2(lhs: Fp6, rhs: Fp2): Fp6; +}; + +const Fp6: mod.IField & Fp6Utils = { + ORDER: Fp2.ORDER, // TODO: unused, but need to verify + BITS: 3 * Fp2.BITS, + BYTES: 3 * Fp2.BYTES, + MASK: bitMask(3 * Fp2.BITS), + ZERO: { c0: Fp2.ZERO, c1: Fp2.ZERO, c2: Fp2.ZERO }, + ONE: { c0: Fp2.ONE, c1: Fp2.ZERO, c2: Fp2.ZERO }, + create: (num) => num, + isValid: ({ c0, c1, c2 }) => Fp2.isValid(c0) && Fp2.isValid(c1) && Fp2.isValid(c2), + is0: ({ c0, c1, c2 }) => Fp2.is0(c0) && Fp2.is0(c1) && Fp2.is0(c2), + neg: ({ c0, c1, c2 }) => ({ c0: Fp2.neg(c0), c1: Fp2.neg(c1), c2: Fp2.neg(c2) }), + eql: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => + Fp2.eql(c0, r0) && Fp2.eql(c1, r1) && Fp2.eql(c2, r2), + sqrt: () => { + throw new Error('Not implemented'); + }, + // Do we need division by bigint at all? Should be done via order: + div: (lhs, rhs) => Fp6.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp6.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp6, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp6, nums), + // Normalized + add: Fp6Add, + sub: Fp6Subtract, + mul: Fp6Multiply, + sqr: Fp6Square, + // NonNormalized stuff + addN: Fp6Add, + subN: Fp6Subtract, + mulN: Fp6Multiply, + sqrN: Fp6Square, + + inv: ({ c0, c1, c2 }) => { + let t0 = Fp2.sub(Fp2.sqr(c0), Fp2.mulByNonresidue(Fp2.mul(c2, c1))); // c0² - c2 * c1 * (u + 1) + let t1 = Fp2.sub(Fp2.mulByNonresidue(Fp2.sqr(c2)), Fp2.mul(c0, c1)); // c2² * (u + 1) - c0 * c1 + let t2 = Fp2.sub(Fp2.sqr(c1), Fp2.mul(c0, c2)); // c1² - c0 * c2 + // 1/(((c2 * T1 + c1 * T2) * v) + c0 * T0) + let t4 = Fp2.inv( + Fp2.add(Fp2.mulByNonresidue(Fp2.add(Fp2.mul(c2, t1), Fp2.mul(c1, t2))), Fp2.mul(c0, t0)) + ); + return { c0: Fp2.mul(t4, t0), c1: Fp2.mul(t4, t1), c2: Fp2.mul(t4, t2) }; + }, + // Bytes utils + fromBytes: (b: Uint8Array): Fp6 => { + if (b.length !== Fp6.BYTES) throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp2.fromBytes(b.subarray(0, Fp2.BYTES)), + c1: Fp2.fromBytes(b.subarray(Fp2.BYTES, 2 * Fp2.BYTES)), + c2: Fp2.fromBytes(b.subarray(2 * Fp2.BYTES)), + }; + }, + toBytes: ({ c0, c1, c2 }): Uint8Array => + concatB(Fp2.toBytes(c0), Fp2.toBytes(c1), Fp2.toBytes(c2)), + cmov: ({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6, c) => ({ + c0: Fp2.cmov(c0, r0, c), + c1: Fp2.cmov(c1, r1, c), + c2: Fp2.cmov(c2, r2, c), + }), + // Utils + // fromTriple(triple: [Fp2, Fp2, Fp2]) { + // return new Fp6(...triple); + // } + // toString() { + // return `Fp6(${this.c0} + ${this.c1} * v, ${this.c2} * v^2)`; + // } + fromBigSix: (t: BigintSix): Fp6 => { + if (!Array.isArray(t) || t.length !== 6) throw new Error('Invalid Fp6 usage'); + return { + c0: Fp2.fromBigTuple(t.slice(0, 2)), + c1: Fp2.fromBigTuple(t.slice(2, 4)), + c2: Fp2.fromBigTuple(t.slice(4, 6)), + }; + }, + frobeniusMap: ({ c0, c1, c2 }, power: number) => ({ + c0: Fp2.frobeniusMap(c0, power), + c1: Fp2.mul(Fp2.frobeniusMap(c1, power), FP6_FROBENIUS_COEFFICIENTS_1[power % 6]), + c2: Fp2.mul(Fp2.frobeniusMap(c2, power), FP6_FROBENIUS_COEFFICIENTS_2[power % 6]), + }), + mulByNonresidue: ({ c0, c1, c2 }) => ({ c0: Fp2.mulByNonresidue(c2), c1: c0, c2: c1 }), + + // Sparse multiplication + multiplyBy1: ({ c0, c1, c2 }, b1: Fp2): Fp6 => ({ + c0: Fp2.mulByNonresidue(Fp2.mul(c2, b1)), + c1: Fp2.mul(c0, b1), + c2: Fp2.mul(c1, b1), + }), + // Sparse multiplication + multiplyBy01({ c0, c1, c2 }, b0: Fp2, b1: Fp2): Fp6 { + let t0 = Fp2.mul(c0, b0); // c0 * b0 + let t1 = Fp2.mul(c1, b1); // c1 * b1 + return { + // ((c1 + c2) * b1 - T1) * (u + 1) + T0 + c0: Fp2.add(Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), b1), t1)), t0), + // (b0 + b1) * (c0 + c1) - T0 - T1 + c1: Fp2.sub(Fp2.sub(Fp2.mul(Fp2.add(b0, b1), Fp2.add(c0, c1)), t0), t1), + // (c0 + c2) * b0 - T0 + T1 + c2: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c2), b0), t0), t1), + }; + }, + + multiplyByFp2: ({ c0, c1, c2 }, rhs: Fp2): Fp6 => ({ + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }), +}; + +const FP6_FROBENIUS_COEFFICIENTS_1 = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt('0x0'), + BigInt( + '0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac' + ), + ], + [ + BigInt( + '0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe' + ), + BigInt('0x0'), + ], + [BigInt('0x0'), BigInt('0x1')], + [ + BigInt( + '0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac' + ), + BigInt('0x0'), + ], + [ + BigInt('0x0'), + BigInt( + '0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe' + ), + ], +].map((pair) => Fp2.fromBigTuple(pair)); +const FP6_FROBENIUS_COEFFICIENTS_2 = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt( + '0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff' + ), + BigInt('0x0'), + ], +].map((pair) => Fp2.fromBigTuple(pair)); + +// Finite extension field over irreducible polynominal. +// Fp₁₂ = Fp₆² => Fp₂³ +// Fp₆(w) / (w² - γ) where γ = v +type Fp12 = { c0: Fp6; c1: Fp6 }; +// The BLS parameter x for BLS12-381 +const BLS_X = BigInt('0xd201000000010000'); +const BLS_X_LEN = bitLen(BLS_X); + +// prettier-ignore +type BigintTwelve = [ + bigint, bigint, bigint, bigint, bigint, bigint, + bigint, bigint, bigint, bigint, bigint, bigint + ]; +const Fp12Add = ({ c0, c1 }: Fp12, { c0: r0, c1: r1 }: Fp12) => ({ + c0: Fp6.add(c0, r0), + c1: Fp6.add(c1, r1), +}); +const Fp12Subtract = ({ c0, c1 }: Fp12, { c0: r0, c1: r1 }: Fp12) => ({ + c0: Fp6.sub(c0, r0), + c1: Fp6.sub(c1, r1), +}); +const Fp12Multiply = ({ c0, c1 }: Fp12, rhs: Fp12 | bigint) => { + if (typeof rhs === 'bigint') return { c0: Fp6.mul(c0, rhs), c1: Fp6.mul(c1, rhs) }; + let { c0: r0, c1: r1 } = rhs; + let t1 = Fp6.mul(c0, r0); // c0 * r0 + let t2 = Fp6.mul(c1, r1); // c1 * r1 + return { + c0: Fp6.add(t1, Fp6.mulByNonresidue(t2)), // T1 + T2 * v + // (c0 + c1) * (r0 + r1) - (T1 + T2) + c1: Fp6.sub(Fp6.mul(Fp6.add(c0, c1), Fp6.add(r0, r1)), Fp6.add(t1, t2)), + }; +}; +const Fp12Square = ({ c0, c1 }: Fp12) => { + let ab = Fp6.mul(c0, c1); // c0 * c1 + return { + // (c1 * v + c0) * (c0 + c1) - AB - AB * v + c0: Fp6.sub( + Fp6.sub(Fp6.mul(Fp6.add(Fp6.mulByNonresidue(c1), c0), Fp6.add(c0, c1)), ab), + Fp6.mulByNonresidue(ab) + ), + c1: Fp6.add(ab, ab), + }; // AB + AB +}; +function Fp4Square(a: Fp2, b: Fp2): { first: Fp2; second: Fp2 } { + const a2 = Fp2.sqr(a); + const b2 = Fp2.sqr(b); + return { + first: Fp2.add(Fp2.mulByNonresidue(b2), a2), // b² * Nonresidue + a² + second: Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(a, b)), a2), b2), // (a + b)² - a² - b² + }; +} +type Fp12Utils = { + fromBigTwelve: (t: BigintTwelve) => Fp12; + frobeniusMap(num: Fp12, power: number): Fp12; + multiplyBy014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12; + multiplyByFp2(lhs: Fp12, rhs: Fp2): Fp12; + conjugate(num: Fp12): Fp12; + finalExponentiate(num: Fp12): Fp12; + _cyclotomicSquare(num: Fp12): Fp12; + _cyclotomicExp(num: Fp12, n: bigint): Fp12; +}; + +const Fp12: mod.IField & Fp12Utils = { + ORDER: Fp2.ORDER, // TODO: unused, but need to verify + BITS: 2 * Fp2.BITS, + BYTES: 2 * Fp2.BYTES, + MASK: bitMask(2 * Fp2.BITS), + ZERO: { c0: Fp6.ZERO, c1: Fp6.ZERO }, + ONE: { c0: Fp6.ONE, c1: Fp6.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => Fp6.isValid(c0) && Fp6.isValid(c1), + is0: ({ c0, c1 }) => Fp6.is0(c0) && Fp6.is0(c1), + neg: ({ c0, c1 }) => ({ c0: Fp6.neg(c0), c1: Fp6.neg(c1) }), + eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp6.eql(c0, r0) && Fp6.eql(c1, r1), + sqrt: () => { + throw new Error('Not implemented'); + }, + inv: ({ c0, c1 }) => { + let t = Fp6.inv(Fp6.sub(Fp6.sqr(c0), Fp6.mulByNonresidue(Fp6.sqr(c1)))); // 1 / (c0² - c1² * v) + return { c0: Fp6.mul(c0, t), c1: Fp6.neg(Fp6.mul(c1, t)) }; // ((C0 * T) * T) + (-C1 * T) * w + }, + div: (lhs, rhs) => + Fp12.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp12.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp12, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp12, nums), + // Normalized + add: Fp12Add, + sub: Fp12Subtract, + mul: Fp12Multiply, + sqr: Fp12Square, + // NonNormalized stuff + addN: Fp12Add, + subN: Fp12Subtract, + mulN: Fp12Multiply, + sqrN: Fp12Square, + + // Bytes utils + fromBytes: (b: Uint8Array): Fp12 => { + if (b.length !== Fp12.BYTES) throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp6.fromBytes(b.subarray(0, Fp6.BYTES)), + c1: Fp6.fromBytes(b.subarray(Fp6.BYTES)), + }; + }, + toBytes: ({ c0, c1 }): Uint8Array => concatB(Fp6.toBytes(c0), Fp6.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp6.cmov(c0, r0, c), + c1: Fp6.cmov(c1, r1, c), + }), + // Utils + // toString() { + // return `Fp12(${this.c0} + ${this.c1} * w)`; + // }, + // fromTuple(c: [Fp6, Fp6]) { + // return new Fp12(...c); + // } + fromBigTwelve: (t: BigintTwelve): Fp12 => ({ + c0: Fp6.fromBigSix(t.slice(0, 6) as BigintSix), + c1: Fp6.fromBigSix(t.slice(6, 12) as BigintSix), + }), + // Raises to q**i -th power + frobeniusMap(lhs, power: number) { + const r0 = Fp6.frobeniusMap(lhs.c0, power); + const { c0, c1, c2 } = Fp6.frobeniusMap(lhs.c1, power); + const coeff = FP12_FROBENIUS_COEFFICIENTS[power % 12]; + return { + c0: r0, + c1: Fp6.create({ + c0: Fp2.mul(c0, coeff), + c1: Fp2.mul(c1, coeff), + c2: Fp2.mul(c2, coeff), + }), + }; + }, + // Sparse multiplication + multiplyBy014: ({ c0, c1 }, o0: Fp2, o1: Fp2, o4: Fp2) => { + let t0 = Fp6.multiplyBy01(c0, o0, o1); + let t1 = Fp6.multiplyBy1(c1, o4); + return { + c0: Fp6.add(Fp6.mulByNonresidue(t1), t0), // T1 * v + T0 + // (c1 + c0) * [o0, o1+o4] - T0 - T1 + c1: Fp6.sub(Fp6.sub(Fp6.multiplyBy01(Fp6.add(c1, c0), o0, Fp2.add(o1, o4)), t0), t1), + }; + }, + multiplyByFp2: ({ c0, c1 }, rhs: Fp2): Fp12 => ({ + c0: Fp6.multiplyByFp2(c0, rhs), + c1: Fp6.multiplyByFp2(c1, rhs), + }), + conjugate: ({ c0, c1 }): Fp12 => ({ c0, c1: Fp6.neg(c1) }), + + // A cyclotomic group is a subgroup of Fp^n defined by + // GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1} + // The result of any pairing is in a cyclotomic subgroup + // https://eprint.iacr.org/2009/565.pdf + _cyclotomicSquare: ({ c0, c1 }): Fp12 => { + const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0; + const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1; + const { first: t3, second: t4 } = Fp4Square(c0c0, c1c1); + const { first: t5, second: t6 } = Fp4Square(c1c0, c0c2); + const { first: t7, second: t8 } = Fp4Square(c0c1, c1c2); + let t9 = Fp2.mulByNonresidue(t8); // T8 * (u + 1) + return { + c0: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.sub(t3, c0c0), _2n), t3), // 2 * (T3 - c0c0) + T3 + c1: Fp2.add(Fp2.mul(Fp2.sub(t5, c0c1), _2n), t5), // 2 * (T5 - c0c1) + T5 + c2: Fp2.add(Fp2.mul(Fp2.sub(t7, c0c2), _2n), t7), + }), // 2 * (T7 - c0c2) + T7 + c1: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.add(t9, c1c0), _2n), t9), // 2 * (T9 + c1c0) + T9 + c1: Fp2.add(Fp2.mul(Fp2.add(t4, c1c1), _2n), t4), // 2 * (T4 + c1c1) + T4 + c2: Fp2.add(Fp2.mul(Fp2.add(t6, c1c2), _2n), t6), + }), + }; // 2 * (T6 + c1c2) + T6 + }, + _cyclotomicExp(num, n) { + let z = Fp12.ONE; + for (let i = BLS_X_LEN - 1; i >= 0; i--) { + z = Fp12._cyclotomicSquare(z); + if (bitGet(n, i)) z = Fp12.mul(z, num); + } + return z; + }, + // https://eprint.iacr.org/2010/354.pdf + // https://eprint.iacr.org/2009/565.pdf + finalExponentiate: (num) => { + const x = BLS_X; + // this^(q⁶) / this + const t0 = Fp12.div(Fp12.frobeniusMap(num, 6), num); + // t0^(q²) * t0 + const t1 = Fp12.mul(Fp12.frobeniusMap(t0, 2), t0); + const t2 = Fp12.conjugate(Fp12._cyclotomicExp(t1, x)); + const t3 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicSquare(t1)), t2); + const t4 = Fp12.conjugate(Fp12._cyclotomicExp(t3, x)); + const t5 = Fp12.conjugate(Fp12._cyclotomicExp(t4, x)); + const t6 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicExp(t5, x)), Fp12._cyclotomicSquare(t2)); + const t7 = Fp12.conjugate(Fp12._cyclotomicExp(t6, x)); + const t2_t5_pow_q2 = Fp12.frobeniusMap(Fp12.mul(t2, t5), 2); + const t4_t1_pow_q3 = Fp12.frobeniusMap(Fp12.mul(t4, t1), 3); + const t6_t1c_pow_q1 = Fp12.frobeniusMap(Fp12.mul(t6, Fp12.conjugate(t1)), 1); + const t7_t3c_t1 = Fp12.mul(Fp12.mul(t7, Fp12.conjugate(t3)), t1); + // (t2 * t5)^(q²) * (t4 * t1)^(q³) * (t6 * t1.conj)^(q^1) * t7 * t3.conj * t1 + return Fp12.mul(Fp12.mul(Fp12.mul(t2_t5_pow_q2, t4_t1_pow_q3), t6_t1c_pow_q1), t7_t3c_t1); + }, +}; +const FP12_FROBENIUS_COEFFICIENTS = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt( + '0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8' + ), + BigInt( + '0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3' + ), + ], + [ + BigInt( + '0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2' + ), + BigInt( + '0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09' + ), + ], + [ + BigInt( + '0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995' + ), + BigInt( + '0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116' + ), + ], + [ + BigInt( + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3' + ), + BigInt( + '0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8' + ), + ], + [ + BigInt( + '0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09' + ), + BigInt( + '0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2' + ), + ], + [ + BigInt( + '0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116' + ), + BigInt( + '0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995' + ), + ], +].map((n) => Fp2.fromBigTuple(n)); +// END OF CURVE FIELDS + +// HashToCurve + +// 3-isogeny map from E' to E +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#appendix-E.3 +const isogenyMapG2 = isogenyMap( + Fp2, + [ + // xNum + [ + [ + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + ], + [ + '0x0', + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d', + ], + [ + '0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1', + '0x0', + ], + ], + // xDen + [ + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63', + ], + [ + '0xc', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f', + ], + ['0x1', '0x0'], // LAST 1 + ], + // yNum + [ + [ + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + ], + [ + '0x0', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f', + ], + [ + '0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10', + '0x0', + ], + ], + // yDen + [ + [ + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + ], + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3', + ], + [ + '0x12', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99', + ], + ['0x1', '0x0'], // LAST 1 + ], + ].map((i) => i.map((pair) => Fp2.fromBigTuple(pair.map(BigInt)))) as [Fp2[], Fp2[], Fp2[], Fp2[]] +); +// 11-isogeny map from E' to E +const isogenyMapG1 = isogenyMap( + Fp, + [ + // xNum + [ + '0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7', + '0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb', + '0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0', + '0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861', + '0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9', + '0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983', + '0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84', + '0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e', + '0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317', + '0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e', + '0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b', + '0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229', + ], + // xDen + [ + '0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c', + '0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff', + '0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19', + '0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8', + '0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e', + '0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5', + '0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a', + '0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e', + '0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641', + '0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33', + '0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696', + '0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6', + '0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb', + '0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb', + '0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0', + '0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2', + '0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29', + '0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587', + '0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30', + '0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132', + '0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e', + '0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8', + '0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133', + '0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b', + '0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604', + ], + // yDen + [ + '0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1', + '0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d', + '0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2', + '0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416', + '0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d', + '0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac', + '0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c', + '0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9', + '0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a', + '0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55', + '0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8', + '0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092', + '0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc', + '0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7', + '0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + ].map((i) => i.map((j) => BigInt(j))) as [Fp[], Fp[], Fp[], Fp[]] +); + +// SWU Map - Fp2 to G2': y² = x³ + 240i * x + 1012 + 1012i +const G2_SWU = mapToCurveSimpleSWU(Fp2, { + A: Fp2.create({ c0: Fp.create(_0n), c1: Fp.create(BigInt(240)) }), // A' = 240 * I + B: Fp2.create({ c0: Fp.create(BigInt(1012)), c1: Fp.create(BigInt(1012)) }), // B' = 1012 * (1 + I) + Z: Fp2.create({ c0: Fp.create(BigInt(-2)), c1: Fp.create(BigInt(-1)) }), // Z: -(2 + I) +}); +// Optimized SWU Map - Fp to G1 +const G1_SWU = mapToCurveSimpleSWU(Fp, { + A: Fp.create( + BigInt( + '0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d' + ) + ), + B: Fp.create( + BigInt( + '0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0' + ) + ), + Z: Fp.create(BigInt(11)), +}); + +// Endomorphisms (for fast cofactor clearing) +// Ψ(P) endomorphism +const ut_root = Fp6.create({ c0: Fp2.ZERO, c1: Fp2.ONE, c2: Fp2.ZERO }); +const wsq = Fp12.create({ c0: ut_root, c1: Fp6.ZERO }); +const wcu = Fp12.create({ c0: Fp6.ZERO, c1: ut_root }); +const [wsq_inv, wcu_inv] = Fp12.invertBatch([wsq, wcu]); +function psi(x: Fp2, y: Fp2): [Fp2, Fp2] { + // Untwist Fp2->Fp12 && frobenius(1) && twist back + const x2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wsq_inv, x), 1), wsq).c0.c0; + const y2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wcu_inv, y), 1), wcu).c0.c0; + return [x2, y2]; +} +// Ψ endomorphism +function G2psi(c: ProjConstructor, P: ProjPointType) { + const affine = P.toAffine(); + const p = psi(affine.x, affine.y); + return new c(p[0], p[1], Fp2.ONE); +} +// Ψ²(P) endomorphism +// 1 / F2(2)^((p-1)/3) in GF(p²) +const PSI2_C1 = BigInt( + '0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac' +); + +function psi2(x: Fp2, y: Fp2): [Fp2, Fp2] { + return [Fp2.mul(x, PSI2_C1), Fp2.neg(y)]; +} +function G2psi2(c: ProjConstructor, P: ProjPointType) { + const affine = P.toAffine(); + const p = psi2(affine.x, affine.y); + return new c(p[0], p[1], Fp2.ONE); +} + +// Default hash_to_field options are for hash to G2. +// +// Parameter definitions are in section 5.3 of the spec unless otherwise noted. +// Parameter values come from section 8.8.2 of the spec. +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-8.8.2 +// +// Base field F is GF(p^m) +// p = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab +// m = 2 (or 1 for G1 see section 8.8.1) +// k = 128 +const htfDefaults = Object.freeze({ + // DST: a domain separation tag + // defined in section 2.2.5 + // Use utils.getDSTLabel(), utils.setDSTLabel(value) + DST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + encodeDST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + // p: the characteristic of F + // where F is a finite field of characteristic p and order q = p^m + p: Fp.ORDER, + // m: the extension degree of F, m >= 1 + // where F is a finite field of characteristic p and order q = p^m + m: 2, + // k: the target security level for the suite in bits + // defined in section 5.1 + k: 128, + // option to use a message that has already been processed by + // expand_message_xmd + expand: 'xmd', + // Hash functions for: expand_message_xmd is appropriate for use with a + // wide range of hash functions, including SHA-2, SHA-3, BLAKE2, and others. + // BBS+ uses blake2: https://github.com/hyperledger/aries-framework-go/issues/2247 + hash: sha256, +} as const); + +// Encoding utils +// Point on G1 curve: (x, y) +const C_BIT_POS = Fp.BITS; // C_bit, compression bit for serialization flag +const I_BIT_POS = Fp.BITS + 1; // I_bit, point-at-infinity bit for serialization flag +const S_BIT_POS = Fp.BITS + 2; // S_bit, sign bit for serialization flag +// Compressed point of infinity +const COMPRESSED_ZERO = Fp.toBytes(bitSet(bitSet(_0n, I_BIT_POS, true), S_BIT_POS, true)); // set compressed & point-at-infinity bits + +function signatureG2ToRawBytes(point: ProjPointType) { + // NOTE: by some reasons it was missed in bls12-381, looks like bug + point.assertValidity(); + const len = Fp.BYTES; + if (point.equals(bls12_381.G2.ProjectivePoint.ZERO)) + return concatB(COMPRESSED_ZERO, numberToBytesBE(_0n, len)); + const { x, y } = point.toAffine(); + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + const tmp = y1 > _0n ? y1 * _2n : y0 * _2n; + const aflag1 = Boolean((tmp / Fp.ORDER) & _1n); + const z1 = bitSet(bitSet(x1, 381, aflag1), S_BIT_POS, true); + const z2 = x0; + return concatB(numberToBytesBE(z1, len), numberToBytesBE(z2, len)); +} + +// To verify curve parameters, see pairing-friendly-curves spec: +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-09 +// Basic math is done over finite fields over p. +// More complicated math is done over polynominal extension fields. +// To simplify calculations in Fp12, we construct extension tower: +// Fp₁₂ = Fp₆² => Fp₂³ +// Fp(u) / (u² - β) where β = -1 +// Fp₂(v) / (v³ - ξ) where ξ = u + 1 +// Fp₆(w) / (w² - γ) where γ = v +// Here goes constants && point encoding format +export const bls12_381: CurveFn = bls({ + // Fields + fields: { + Fp, + Fp2, + Fp6, + Fp12, + Fr, + }, + // G1 is the order-q subgroup of E1(Fp) : y² = x³ + 4, #E1(Fp) = h1q, where + // characteristic; z + (z⁴ - z² + 1)(z - 1)²/3 + G1: { + Fp, + // cofactor; (z - 1)²/3 + h: BigInt('0x396c8c005555e1568c00aaab0000aaab'), + // generator's coordinates + // x = 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507 + // y = 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569 + Gx: BigInt( + '0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb' + ), + Gy: BigInt( + '0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1' + ), + a: Fp.ZERO, + b: _4n, + htfDefaults: { ...htfDefaults, m: 1 }, + wrapPrivateKey: true, + allowInfinityPoint: true, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, point): boolean => { + // φ endomorphism + const cubicRootOfUnityModP = BigInt( + '0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe' + ); + const phi = new c(Fp.mul(point.px, cubicRootOfUnityModP), point.py, point.pz); + + // todo: unroll + const xP = point.multiplyUnsafe(bls12_381.params.x).negate(); // [x]P + const u2P = xP.multiplyUnsafe(bls12_381.params.x); // [u2]P + return u2P.equals(phi); + + // https://eprint.iacr.org/2019/814.pdf + // (z² − 1)/3 + // const c1 = BigInt('0x396c8c005555e1560000000055555555'); + // const P = this; + // const S = P.sigma(); + // const Q = S.double(); + // const S2 = S.sigma(); + // // [(z² − 1)/3](2σ(P) − P − σ²(P)) − σ²(P) = O + // const left = Q.subtract(P).subtract(S2).multiplyUnsafe(c1); + // const C = left.subtract(S2); + // return C.isZero(); + }, + // Clear cofactor of G1 + // https://eprint.iacr.org/2019/403 + clearCofactor: (c, point) => { + // return this.multiplyUnsafe(CURVE.h); + return point.multiplyUnsafe(bls12_381.params.x).add(point); // x*P + P + }, + mapToCurve: (scalars: bigint[]) => { + const { x, y } = G1_SWU(Fp.create(scalars[0])); + return isogenyMapG1(x, y); + }, + fromBytes: (bytes: Uint8Array): AffinePoint => { + bytes = bytes.slice(); + if (bytes.length === 48) { + // TODO: Fp.bytes + const P = Fp.ORDER; + const compressedValue = bytesToNumberBE(bytes); + const bflag = bitGet(compressedValue, I_BIT_POS); + // Zero + if (bflag === _1n) return { x: _0n, y: _0n }; + const x = Fp.create(compressedValue & Fp.MASK); + const right = Fp.add(Fp.pow(x, _3n), Fp.create(bls12_381.params.G1b)); // y² = x³ + b + let y = Fp.sqrt(right); + if (!y) throw new Error('Invalid compressed G1 point'); + const aflag = bitGet(compressedValue, C_BIT_POS); + if ((y * _2n) / P !== aflag) y = Fp.neg(y); + return { x: Fp.create(x), y: Fp.create(y) }; + } else if (bytes.length === 96) { + // Check if the infinity flag is set + if ((bytes[0] & (1 << 6)) !== 0) return bls12_381.G1.ProjectivePoint.ZERO.toAffine(); + const x = bytesToNumberBE(bytes.subarray(0, Fp.BYTES)); + const y = bytesToNumberBE(bytes.subarray(Fp.BYTES)); + return { x: Fp.create(x), y: Fp.create(y) }; + } else { + throw new Error('Invalid point G1, expected 48/96 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) return COMPRESSED_ZERO.slice(); + const P = Fp.ORDER; + let num; + num = bitSet(x, C_BIT_POS, Boolean((y * _2n) / P)); // set aflag + num = bitSet(num, S_BIT_POS, true); + return numberToBytesBE(num, Fp.BYTES); + } else { + if (isZero) { + // 2x PUBLIC_KEY_LENGTH + const x = concatB(new Uint8Array([0x40]), new Uint8Array(2 * Fp.BYTES - 1)); + return x; + } else { + return concatB(numberToBytesBE(x, Fp.BYTES), numberToBytesBE(y, Fp.BYTES)); + } + } + }, + }, + // G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1), + // where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where + // G² - 1 + // h2q + G2: { + Fp: Fp2, + // cofactor + h: BigInt( + '0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5' + ), + Gx: Fp2.fromBigTuple([ + BigInt( + '0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8' + ), + BigInt( + '0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e' + ), + ]), + // y = + // 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582, + // 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905 + Gy: Fp2.fromBigTuple([ + BigInt( + '0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801' + ), + BigInt( + '0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be' + ), + ]), + a: Fp2.ZERO, + b: Fp2.fromBigTuple([_4n, _4n]), + hEff: BigInt( + '0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551' + ), + htfDefaults: { ...htfDefaults }, + wrapPrivateKey: true, + allowInfinityPoint: true, + mapToCurve: (scalars: bigint[]) => { + const { x, y } = G2_SWU(Fp2.fromBigTuple(scalars)); + return isogenyMapG2(x, y); + }, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, P): boolean => { + return P.multiplyUnsafe(bls12_381.params.x).negate().equals(G2psi(c, P)); // ψ(P) == [u](P) + // Older version: https://eprint.iacr.org/2019/814.pdf + // Ψ²(P) => Ψ³(P) => [z]Ψ³(P) where z = -x => [z]Ψ³(P) - Ψ²(P) + P == O + // return P.psi2().psi().mulNegX().subtract(psi2).add(P).isZero(); + }, + // Maps the point into the prime-order subgroup G2. + // clear_cofactor_bls12381_g2 from cfrg-hash-to-curve-11 + // https://eprint.iacr.org/2017/419.pdf + // prettier-ignore + clearCofactor: (c, P) => { + const x = bls12_381.params.x; + let t1 = P.multiplyUnsafe(x).negate(); // [-x]P + let t2 = G2psi(c, P); // Ψ(P) + let t3 = P.double(); // 2P + t3 = G2psi2(c, t3); // Ψ²(2P) + t3 = t3.subtract(t2); // Ψ²(2P) - Ψ(P) + t2 = t1.add(t2); // [-x]P + Ψ(P) + t2 = t2.multiplyUnsafe(x).negate(); // [x²]P - [x]Ψ(P) + t3 = t3.add(t2); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + t3 = t3.subtract(t1); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P + const Q = t3.subtract(P); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P - 1P + return Q; // [x²-x-1]P + [x-1]Ψ(P) + Ψ²(2P) + }, + fromBytes: (bytes: Uint8Array): AffinePoint => { + bytes = bytes.slice(); + const m_byte = bytes[0] & 0xe0; + if (m_byte === 0x20 || m_byte === 0x60 || m_byte === 0xe0) { + throw new Error('Invalid encoding flag: ' + m_byte); + } + const bitC = m_byte & 0x80; // compression bit + const bitI = m_byte & 0x40; // point at infinity bit + const bitS = m_byte & 0x20; // sign bit + const L = Fp.BYTES; + const slc = (b: Uint8Array, from: number, to?: number) => bytesToNumberBE(b.slice(from, to)); + if (bytes.length === 96 && bitC) { + const b = bls12_381.params.G2b; + const P = Fp.ORDER; + + bytes[0] = bytes[0] & 0x1f; // clear flags + if (bitI) { + // check that all bytes are 0 + if (bytes.reduce((p, c) => (p !== 0 ? c + 1 : c), 0) > 0) { + throw new Error('Invalid compressed G2 point'); + } + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x_1 = slc(bytes, 0, L); + const x_0 = slc(bytes, L, 2 * L); + const x = Fp2.create({ c0: Fp.create(x_0), c1: Fp.create(x_1) }); + const right = Fp2.add(Fp2.pow(x, _3n), b); // y² = x³ + 4 * (u+1) = x³ + b + let y = Fp2.sqrt(right); + const Y_bit = y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P ? _1n : _0n; + y = bitS > 0 && Y_bit > 0 ? y : Fp2.neg(y); + return { x, y }; + } else if (bytes.length === 192 && !bitC) { + // Check if the infinity flag is set + if ((bytes[0] & (1 << 6)) !== 0) { + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x1 = slc(bytes, 0, L); + const x0 = slc(bytes, L, 2 * L); + const y1 = slc(bytes, 2 * L, 3 * L); + const y0 = slc(bytes, 3 * L, 4 * L); + return { x: Fp2.fromBigTuple([x0, x1]), y: Fp2.fromBigTuple([y0, y1]) }; + } else { + throw new Error('Invalid point G2, expected 96/192 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const { BYTES: len, ORDER: P } = Fp; + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) return concatB(COMPRESSED_ZERO, numberToBytesBE(_0n, len)); + const flag = Boolean(y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P); + // set compressed & sign bits (looks like different offsets than for G1/Fp?) + let x_1 = bitSet(x.c1, C_BIT_POS, flag); + x_1 = bitSet(x_1, S_BIT_POS, true); + return concatB(numberToBytesBE(x_1, len), numberToBytesBE(x.c0, len)); + } else { + if (isZero) return concatB(new Uint8Array([0x40]), new Uint8Array(4 * len - 1)); // bytes[0] |= 1 << 6; + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + return concatB( + numberToBytesBE(x1, len), + numberToBytesBE(x0, len), + numberToBytesBE(y1, len), + numberToBytesBE(y0, len) + ); + } + }, + Signature: { + // TODO: Optimize, it's very slow because of sqrt. + fromHex(hex: Hex): ProjPointType { + hex = ensureBytes('signatureHex', hex); + const P = Fp.ORDER; + const half = hex.length / 2; + if (half !== 48 && half !== 96) + throw new Error('Invalid compressed signature length, must be 96 or 192'); + const z1 = bytesToNumberBE(hex.slice(0, half)); + const z2 = bytesToNumberBE(hex.slice(half)); + // Indicates the infinity point + const bflag1 = bitGet(z1, I_BIT_POS); + if (bflag1 === _1n) return bls12_381.G2.ProjectivePoint.ZERO; + + const x1 = Fp.create(z1 & Fp.MASK); + const x2 = Fp.create(z2); + const x = Fp2.create({ c0: x2, c1: x1 }); + const y2 = Fp2.add(Fp2.pow(x, _3n), bls12_381.params.G2b); // y² = x³ + 4 + // The slow part + let y = Fp2.sqrt(y2); + if (!y) throw new Error('Failed to find a square root'); + + // Choose the y whose leftmost bit of the imaginary part is equal to the a_flag1 + // If y1 happens to be zero, then use the bit of y0 + const { re: y0, im: y1 } = Fp2.reim(y); + const aflag1 = bitGet(z1, 381); + const isGreater = y1 > _0n && (y1 * _2n) / P !== aflag1; + const isZero = y1 === _0n && (y0 * _2n) / P !== aflag1; + if (isGreater || isZero) y = Fp2.neg(y); + const point = bls12_381.G2.ProjectivePoint.fromAffine({ x, y }); + point.assertValidity(); + return point; + }, + toRawBytes(point: ProjPointType) { + return signatureG2ToRawBytes(point); + }, + toHex(point: ProjPointType) { + return bytesToHex(signatureG2ToRawBytes(point)); + }, + }, + }, + params: { + x: BLS_X, // The BLS parameter x for BLS12-381 + r: Fr.ORDER, // order; z⁴ − z² + 1; CURVE.n from other curves + }, + htfDefaults, + hash: sha256, + randomBytes, +}); diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/src/bn254.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/src/bn254.ts new file mode 100644 index 0000000..64ccfe0 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/src/bn254.ts @@ -0,0 +1,21 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { weierstrass } from './abstract/weierstrass.js'; +import { getHash } from './_shortw_utils.js'; +import { Field } from './abstract/modular.js'; +/** + * bn254 pairing-friendly curve. + * Previously known as alt_bn_128, when it had 128-bit security. + * Recent research shown it's weaker, the naming has been adjusted to its prime bit count. + * https://github.com/zcash/zcash/issues/2502 + */ +export const bn254 = weierstrass({ + a: BigInt(0), + b: BigInt(3), + Fp: Field(BigInt('0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47')), + n: BigInt('0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001'), + Gx: BigInt(1), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/src/ed25519.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/src/ed25519.ts new file mode 100644 index 0000000..da610dc --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/src/ed25519.ts @@ -0,0 +1,486 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha512 } from '@noble/hashes/sha512'; +import { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils'; +import { ExtPointType, twistedEdwards } from './abstract/edwards.js'; +import { montgomery } from './abstract/montgomery.js'; +import { Field, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.js'; +import { + bytesToHex, + bytesToNumberLE, + ensureBytes, + equalBytes, + Hex, + numberToBytesLE, +} from './abstract/utils.js'; +import { createHasher, htfBasicOpts, expand_message_xmd } from './abstract/hash-to-curve.js'; +import { AffinePoint } from './abstract/curve.js'; + +/** + * ed25519 Twisted Edwards curve with following addons: + * - X25519 ECDH + * - Ristretto cofactor elimination + * - Elligator hash-to-group / point indistinguishability + */ + +const ED25519_P = BigInt( + '57896044618658097711785492504343953926634992332820282019728792003956564819949' +); +// √(-1) aka √(a) aka 2^((p-1)/4) +const ED25519_SQRT_M1 = BigInt( + '19681161376707505956807079304988542015446066515923890162744021073123829784752' +); + +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _5n = BigInt(5); +// prettier-ignore +const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80); + +function ed25519_pow_2_252_3(x: bigint) { + const P = ED25519_P; + const x2 = (x * x) % P; + const b2 = (x2 * x) % P; // x^3, 11 + const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111 + const b5 = (pow2(b4, _1n, P) * x) % P; // x^31 + const b10 = (pow2(b5, _5n, P) * b5) % P; + const b20 = (pow2(b10, _10n, P) * b10) % P; + const b40 = (pow2(b20, _20n, P) * b20) % P; + const b80 = (pow2(b40, _40n, P) * b40) % P; + const b160 = (pow2(b80, _80n, P) * b80) % P; + const b240 = (pow2(b160, _80n, P) * b80) % P; + const b250 = (pow2(b240, _10n, P) * b10) % P; + const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P; + // ^ To pow to (p+3)/8, multiply it by x. + return { pow_p_5_8, b2 }; +} + +function adjustScalarBytes(bytes: Uint8Array): Uint8Array { + // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar, + // set the three least significant bits of the first byte + bytes[0] &= 248; // 0b1111_1000 + // and the most significant bit of the last to zero, + bytes[31] &= 127; // 0b0111_1111 + // set the second most significant bit of the last byte to 1 + bytes[31] |= 64; // 0b0100_0000 + return bytes; +} + +// sqrt(u/v) +function uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } { + const P = ED25519_P; + const v3 = mod(v * v * v, P); // v³ + const v7 = mod(v3 * v3 * v, P); // v⁷ + // (p+3)/8 and (p-5)/8 + const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8; + let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8 + const vx2 = mod(v * x * x, P); // vx² + const root1 = x; // First root candidate + const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate + const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root + const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4) + const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1) + if (useRoot1) x = root1; + if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time + if (isNegativeLE(x, P)) x = mod(-x, P); + return { isValid: useRoot1 || useRoot2, value: x }; +} + +// Just in case +export const ED25519_TORSION_SUBGROUP = [ + '0100000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', + '0000000000000000000000000000000000000000000000000000000000000080', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05', + 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85', + '0000000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa', +]; + +const Fp = Field(ED25519_P, undefined, true); + +const ed25519Defaults = { + // Param: a + a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster + // d is equal to -121665/121666 over finite field. + // Negative number is P - number, and division is invert(number, P) + d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'), + // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n + Fp, + // Subgroup order: how many points curve has + // 2n**252n + 27742317777372353535851937790883648493n; + n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'), + // Cofactor + h: BigInt(8), + // Base point (x, y) aka generator point + Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'), + Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'), + hash: sha512, + randomBytes, + adjustScalarBytes, + // dom2 + // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3. + // Constant-time, u/√v + uvRatio, +} as const; + +export const ed25519 = twistedEdwards(ed25519Defaults); + +function ed25519_domain(data: Uint8Array, ctx: Uint8Array, phflag: boolean) { + if (ctx.length > 255) throw new Error('Context is too big'); + return concatBytes( + utf8ToBytes('SigEd25519 no Ed25519 collisions'), + new Uint8Array([phflag ? 1 : 0, ctx.length]), + ctx, + data + ); +} + +export const ed25519ctx = twistedEdwards({ ...ed25519Defaults, domain: ed25519_domain }); +export const ed25519ph = twistedEdwards({ + ...ed25519Defaults, + domain: ed25519_domain, + prehash: sha512, +}); + +export const x25519 = /* @__PURE__ */ (() => + montgomery({ + P: ED25519_P, + a: BigInt(486662), + montgomeryBits: 255, // n is 253 bits + nByteLength: 32, + Gu: BigInt(9), + powPminus2: (x: bigint): bigint => { + const P = ED25519_P; + // x^(p-2) aka x^(2^255-21) + const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x); + return mod(pow2(pow_p_5_8, BigInt(3), P) * b2, P); + }, + adjustScalarBytes, + randomBytes, + }))(); + +/** + * Converts ed25519 public key to x25519 public key. Uses formula: + * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)` + * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))` + * @example + * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey()); + * const aPriv = x25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub)) + */ +export function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array { + const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y))); +} +export const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated + +/** + * Converts ed25519 secret key to x25519 secret key. + * @example + * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey()); + * const aPriv = ed25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub) + */ +export function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array { + const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32)); + return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32); +} + +// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator) +// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since +// SageMath returns different root first and everything falls apart + +const ELL2_C1 = (Fp.ORDER + BigInt(3)) / BigInt(8); // 1. c1 = (q + 3) / 8 # Integer arithmetic + +const ELL2_C2 = Fp.pow(_2n, ELL2_C1); // 2. c2 = 2^c1 +const ELL2_C3 = Fp.sqrt(Fp.neg(Fp.ONE)); // 3. c3 = sqrt(-1) +const ELL2_C4 = (Fp.ORDER - BigInt(5)) / BigInt(8); // 4. c4 = (q - 5) / 8 # Integer arithmetic +const ELL2_J = BigInt(486662); + +// prettier-ignore +function map_to_curve_elligator2_curve25519(u: bigint) { + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1 + let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not + let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2) + let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2 + tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4 + tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3 + tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3 + tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7 + let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8) + y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8) + let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3 + tv2 = Fp.sqr(y11); // 19. tv2 = y11^2 + tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd + let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1 + let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt + let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd + let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u + y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2 + let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3 + let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1) + tv2 = Fp.sqr(y21); // 28. tv2 = y21^2 + tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2 + let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt + tv2 = Fp.sqr(y1); // 32. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd + let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2 + let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4) + return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1) +} + +const ELL2_C1_EDWARDS = FpSqrtEven(Fp, Fp.neg(BigInt(486664))); // sgn0(c1) MUST equal 0 +function map_to_curve_elligator2_edwards25519(u: bigint) { + const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) = + // map_to_curve_elligator2_curve25519(u) + let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd + xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1 + let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM + let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd + let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d) + let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd + let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0 + xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e) + xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e) + yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e) + yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e) + + const inv = Fp.invertBatch([xd, yd]); // batch division + return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd) +} + +const htf = /* @__PURE__ */ (() => + createHasher( + ed25519.ExtendedPoint, + (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]), + { + DST: 'edwards25519_XMD:SHA-512_ELL2_RO_', + encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha512, + } + ))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); + +function assertRstPoint(other: unknown) { + if (!(other instanceof RistPoint)) throw new Error('RistrettoPoint expected'); +} + +// √(-1) aka √(a) aka 2^((p-1)/4) +const SQRT_M1 = ED25519_SQRT_M1; +// √(ad - 1) +const SQRT_AD_MINUS_ONE = BigInt( + '25063068953384623474111414158702152701244531502492656460079210482610430750235' +); +// 1 / √(a-d) +const INVSQRT_A_MINUS_D = BigInt( + '54469307008909316920995813868745141605393597292927456921205312896311721017578' +); +// 1-d² +const ONE_MINUS_D_SQ = BigInt( + '1159843021668779879193775521855586647937357759715417654439879720876111806838' +); +// (d-1)² +const D_MINUS_ONE_SQ = BigInt( + '40440834346308536858101042469323190826248399146238708352240133220865137265952' +); +// Calculates 1/√(number) +const invertSqrt = (number: bigint) => uvRatio(_1n, number); + +const MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const bytes255ToNumberLE = (bytes: Uint8Array) => + ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B); + +type ExtendedPoint = ExtPointType; + +// Computes Elligator map for Ristretto +// https://ristretto.group/formulas/elligator.html +function calcElligatorRistrettoMap(r0: bigint): ExtendedPoint { + const { d } = ed25519.CURVE; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const r = mod(SQRT_M1 * r0 * r0); // 1 + const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2 + let c = BigInt(-1); // 3 + const D = mod((c - d * r) * mod(r + d)); // 4 + let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5 + let s_ = mod(s * r0); // 6 + if (!isNegativeLE(s_, P)) s_ = mod(-s_); + if (!Ns_D_is_sq) s = s_; // 7 + if (!Ns_D_is_sq) c = r; // 8 + const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9 + const s2 = s * s; + const W0 = mod((s + s) * D); // 10 + const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11 + const W2 = mod(_1n - s2); // 12 + const W3 = mod(_1n + s2); // 13 + return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2)); +} + +/** + * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Ristretto was created to solve this. + * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +class RistPoint { + static BASE: RistPoint; + static ZERO: RistPoint; + // Private property to discourage combining ExtendedPoint + RistrettoPoint + // Always use Ristretto encoding/decoding instead. + constructor(private readonly ep: ExtendedPoint) {} + + static fromAffine(ap: AffinePoint) { + return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap)); + } + + /** + * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://ristretto.group/formulas/elligator.html + * @param hex 64-byte output of a hash function + */ + static hashToCurve(hex: Hex): RistPoint { + hex = ensureBytes('ristrettoHash', hex, 64); + const r1 = bytes255ToNumberLE(hex.slice(0, 32)); + const R1 = calcElligatorRistrettoMap(r1); + const r2 = bytes255ToNumberLE(hex.slice(32, 64)); + const R2 = calcElligatorRistrettoMap(r2); + return new RistPoint(R1.add(R2)); + } + + /** + * Converts ristretto-encoded string to ristretto point. + * https://ristretto.group/formulas/decoding.html + * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding + */ + static fromHex(hex: Hex): RistPoint { + hex = ensureBytes('ristrettoHex', hex, 32); + const { a, d } = ed25519.CURVE; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint'; + const s = bytes255ToNumberLE(hex); + // 1. Check that s_bytes is the canonical encoding of a field element, or else abort. + // 3. Check that s is non-negative, or else abort + if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P)) throw new Error(emsg); + const s2 = mod(s * s); + const u1 = mod(_1n + a * s2); // 4 (a is -1) + const u2 = mod(_1n - a * s2); // 5 + const u1_2 = mod(u1 * u1); + const u2_2 = mod(u2 * u2); + const v = mod(a * d * u1_2 - u2_2); // 6 + const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7 + const Dx = mod(I * u2); // 8 + const Dy = mod(I * Dx * v); // 9 + let x = mod((s + s) * Dx); // 10 + if (isNegativeLE(x, P)) x = mod(-x); // 10 + const y = mod(u1 * Dy); // 11 + const t = mod(x * y); // 12 + if (!isValid || isNegativeLE(t, P) || y === _0n) throw new Error(emsg); + return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t)); + } + + /** + * Encodes ristretto point to Uint8Array. + * https://ristretto.group/formulas/encoding.html + */ + toRawBytes(): Uint8Array { + let { ex: x, ey: y, ez: z, et: t } = this.ep; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const u1 = mod(mod(z + y) * mod(z - y)); // 1 + const u2 = mod(x * y); // 2 + // Square root always exists + const u2sq = mod(u2 * u2); + const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3 + const D1 = mod(invsqrt * u1); // 4 + const D2 = mod(invsqrt * u2); // 5 + const zInv = mod(D1 * D2 * t); // 6 + let D: bigint; // 7 + if (isNegativeLE(t * zInv, P)) { + let _x = mod(y * SQRT_M1); + let _y = mod(x * SQRT_M1); + x = _x; + y = _y; + D = mod(D1 * INVSQRT_A_MINUS_D); + } else { + D = D2; // 8 + } + if (isNegativeLE(x * zInv, P)) y = mod(-y); // 9 + let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a)) + if (isNegativeLE(s, P)) s = mod(-s); + return numberToBytesLE(s, 32); // 11 + } + + toHex(): string { + return bytesToHex(this.toRawBytes()); + } + + toString(): string { + return this.toHex(); + } + + // Compare one point to another. + equals(other: RistPoint): boolean { + assertRstPoint(other); + const { ex: X1, ey: Y1 } = this.ep; + const { ex: X2, ey: Y2 } = other.ep; + const mod = ed25519.CURVE.Fp.create; + // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2) + const one = mod(X1 * Y2) === mod(Y1 * X2); + const two = mod(Y1 * Y2) === mod(X1 * X2); + return one || two; + } + + add(other: RistPoint): RistPoint { + assertRstPoint(other); + return new RistPoint(this.ep.add(other.ep)); + } + + subtract(other: RistPoint): RistPoint { + assertRstPoint(other); + return new RistPoint(this.ep.subtract(other.ep)); + } + + multiply(scalar: bigint): RistPoint { + return new RistPoint(this.ep.multiply(scalar)); + } + + multiplyUnsafe(scalar: bigint): RistPoint { + return new RistPoint(this.ep.multiplyUnsafe(scalar)); + } +} +export const RistrettoPoint = /* @__PURE__ */ (() => { + if (!RistPoint.BASE) RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE); + if (!RistPoint.ZERO) RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO); + return RistPoint; +})(); + +// https://datatracker.ietf.org/doc/draft-irtf-cfrg-hash-to-curve/14/ +// Appendix B. Hashing to ristretto255 +export const hash_to_ristretto255 = (msg: Uint8Array, options: htfBasicOpts) => { + const d = options.DST; + const DST = typeof d === 'string' ? utf8ToBytes(d) : d; + const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512); + const P = RistPoint.hashToCurve(uniform_bytes); + return P; +}; diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/src/ed448.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/src/ed448.ts new file mode 100644 index 0000000..b0cf63e --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/src/ed448.ts @@ -0,0 +1,247 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { shake256 } from '@noble/hashes/sha3'; +import { concatBytes, randomBytes, utf8ToBytes, wrapConstructor } from '@noble/hashes/utils'; +import { twistedEdwards } from './abstract/edwards.js'; +import { mod, pow2, Field } from './abstract/modular.js'; +import { montgomery } from './abstract/montgomery.js'; +import { createHasher } from './abstract/hash-to-curve.js'; + +/** + * Edwards448 (not Ed448-Goldilocks) curve with following addons: + * * X448 ECDH + * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2 + */ + +const shake256_114 = wrapConstructor(() => shake256.create({ dkLen: 114 })); +const shake256_64 = wrapConstructor(() => shake256.create({ dkLen: 64 })); +const ed448P = BigInt( + '726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439' +); + +// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4. +// Used for efficient square root calculation. +// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1] +function ed448_pow_Pminus3div4(x: bigint): bigint { + const P = ed448P; + // prettier-ignore + const _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _11n = BigInt(11); + // prettier-ignore + const _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223); + const b2 = (x * x * x) % P; + const b3 = (b2 * b2 * x) % P; + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b222 = (pow2(b220, _2n, P) * b2) % P; + const b223 = (pow2(b222, _1n, P) * x) % P; + return (pow2(b223, _223n, P) * b222) % P; +} + +function adjustScalarBytes(bytes: Uint8Array): Uint8Array { + // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, and the most + // significant bit of the last byte to 1. + bytes[0] &= 252; // 0b11111100 + // and the most significant bit of the last byte to 1. + bytes[55] |= 128; // 0b10000000 + // NOTE: is is NOOP for 56 bytes scalars (X25519/X448) + bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits) + return bytes; +} + +const Fp = Field(ed448P, 456, true); +const _4n = BigInt(4); + +const ED448_DEF = { + // Param: a + a: BigInt(1), + // -39081. Negative number is P - number + d: BigInt( + '726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358' + ), + // Finite field 𝔽p over which we'll do calculations; 2n**448n - 2n**224n - 1n + Fp, + // Subgroup order: how many points curve has; + // 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n + n: BigInt( + '181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779' + ), + nBitLength: 456, + // Cofactor + h: BigInt(4), + // Base point (x, y) aka generator point + Gx: BigInt( + '224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710' + ), + Gy: BigInt( + '298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660' + ), + // SHAKE256(dom4(phflag,context)||x, 114) + hash: shake256_114, + randomBytes, + adjustScalarBytes, + // dom4 + domain: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => { + if (ctx.length > 255) throw new Error(`Context is too big: ${ctx.length}`); + return concatBytes( + utf8ToBytes('SigEd448'), + new Uint8Array([phflag ? 1 : 0, ctx.length]), + ctx, + data + ); + }, + + // Constant-time ratio of u to v. Allows to combine inversion and square root u/√v. + // Uses algo from RFC8032 5.1.3. + uvRatio: (u: bigint, v: bigint): { isValid: boolean; value: bigint } => { + const P = ed448P; + // https://datatracker.ietf.org/doc/html/rfc8032#section-5.2.3 + // To compute the square root of (u/v), the first step is to compute the + // candidate root x = (u/v)^((p+1)/4). This can be done using the + // following trick, to use a single modular powering for both the + // inversion of v and the square root: + // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p) + const u2v = mod(u * u * v, P); // u²v + const u3v = mod(u2v * u, P); // u³v + const u5v3 = mod(u3v * u2v * v, P); // u⁵v³ + const root = ed448_pow_Pminus3div4(u5v3); + const x = mod(u3v * root, P); + // Verify that root is exists + const x2 = mod(x * x, P); // x² + // If vx² = u, the recovered x-coordinate is x. Otherwise, no + // square root exists, and the decoding fails. + return { isValid: mod(x2 * v, P) === u, value: x }; + }, +} as const; + +export const ed448 = twistedEdwards(ED448_DEF); +// NOTE: there is no ed448ctx, since ed448 supports ctx by default +export const ed448ph = twistedEdwards({ ...ED448_DEF, prehash: shake256_64 }); + +export const x448 = /* @__PURE__ */ (() => + montgomery({ + a: BigInt(156326), + montgomeryBits: 448, + nByteLength: 57, + P: ed448P, + Gu: BigInt(5), + powPminus2: (x: bigint): bigint => { + const P = ed448P; + const Pminus3div4 = ed448_pow_Pminus3div4(x); + const Pminus3 = pow2(Pminus3div4, BigInt(2), P); + return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2 + }, + adjustScalarBytes, + randomBytes, + }))(); + +/** + * Converts edwards448 public key to x448 public key. Uses formula: + * * `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)` + * * `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))` + * @example + * const aPub = ed448.getPublicKey(utils.randomPrivateKey()); + * x448.getSharedSecret(edwardsToMontgomery(aPub), edwardsToMontgomery(someonesPub)) + */ +export function edwardsToMontgomeryPub(edwardsPub: string | Uint8Array): Uint8Array { + const { y } = ed448.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((y - _1n) * Fp.inv(y + _1n))); +} +export const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated + +// Hash To Curve Elligator2 Map +const ELL2_C1 = (Fp.ORDER - BigInt(3)) / BigInt(4); // 1. c1 = (q - 3) / 4 # Integer arithmetic +const ELL2_J = BigInt(156326); +function map_to_curve_elligator2_curve448(u: bigint) { + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + let e1 = Fp.eql(tv1, Fp.ONE); // 2. e1 = tv1 == 1 + tv1 = Fp.cmov(tv1, Fp.ZERO, e1); // 3. tv1 = CMOV(tv1, 0, e1) # If Z * u^2 == -1, set tv1 = 0 + let xd = Fp.sub(Fp.ONE, tv1); // 4. xd = 1 - tv1 + let x1n = Fp.neg(ELL2_J); // 5. x1n = -J + let tv2 = Fp.sqr(xd); // 6. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 7. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, Fp.neg(ELL2_J)); // 8. gx1 = -J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 9. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 10. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 11. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 12. tv3 = gxd^2 + tv2 = Fp.mul(gx1, gxd); // 13. tv2 = gx1 * gxd # gx1 * gxd + tv3 = Fp.mul(tv3, tv2); // 14. tv3 = tv3 * tv2 # gx1 * gxd^3 + let y1 = Fp.pow(tv3, ELL2_C1); // 15. y1 = tv3^c1 # (gx1 * gxd^3)^((p - 3) / 4) + y1 = Fp.mul(y1, tv2); // 16. y1 = y1 * tv2 # gx1 * gxd * (gx1 * gxd^3)^((p - 3) / 4) + let x2n = Fp.mul(x1n, Fp.neg(tv1)); // 17. x2n = -tv1 * x1n # x2 = x2n / xd = -1 * u^2 * x1n / xd + let y2 = Fp.mul(y1, u); // 18. y2 = y1 * u + y2 = Fp.cmov(y2, Fp.ZERO, e1); // 19. y2 = CMOV(y2, 0, e1) + tv2 = Fp.sqr(y1); // 20. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 21. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx1); // 22. e2 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e2); // 23. xn = CMOV(x2n, x1n, e2) # If e2, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e2); // 24. y = CMOV(y2, y1, e2) # If e2, y = y1, else y = y2 + let e3 = Fp.isOdd(y); // 25. e3 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e2 !== e3); // 26. y = CMOV(y, -y, e2 XOR e3) + return { xn, xd, yn: y, yd: Fp.ONE }; // 27. return (xn, xd, y, 1) +} +function map_to_curve_elligator2_edwards448(u: bigint) { + let { xn, xd, yn, yd } = map_to_curve_elligator2_curve448(u); // 1. (xn, xd, yn, yd) = map_to_curve_elligator2_curve448(u) + let xn2 = Fp.sqr(xn); // 2. xn2 = xn^2 + let xd2 = Fp.sqr(xd); // 3. xd2 = xd^2 + let xd4 = Fp.sqr(xd2); // 4. xd4 = xd2^2 + let yn2 = Fp.sqr(yn); // 5. yn2 = yn^2 + let yd2 = Fp.sqr(yd); // 6. yd2 = yd^2 + let xEn = Fp.sub(xn2, xd2); // 7. xEn = xn2 - xd2 + let tv2 = Fp.sub(xEn, xd2); // 8. tv2 = xEn - xd2 + xEn = Fp.mul(xEn, xd2); // 9. xEn = xEn * xd2 + xEn = Fp.mul(xEn, yd); // 10. xEn = xEn * yd + xEn = Fp.mul(xEn, yn); // 11. xEn = xEn * yn + xEn = Fp.mul(xEn, _4n); // 12. xEn = xEn * 4 + tv2 = Fp.mul(tv2, xn2); // 13. tv2 = tv2 * xn2 + tv2 = Fp.mul(tv2, yd2); // 14. tv2 = tv2 * yd2 + let tv3 = Fp.mul(yn2, _4n); // 15. tv3 = 4 * yn2 + let tv1 = Fp.add(tv3, yd2); // 16. tv1 = tv3 + yd2 + tv1 = Fp.mul(tv1, xd4); // 17. tv1 = tv1 * xd4 + let xEd = Fp.add(tv1, tv2); // 18. xEd = tv1 + tv2 + tv2 = Fp.mul(tv2, xn); // 19. tv2 = tv2 * xn + let tv4 = Fp.mul(xn, xd4); // 20. tv4 = xn * xd4 + let yEn = Fp.sub(tv3, yd2); // 21. yEn = tv3 - yd2 + yEn = Fp.mul(yEn, tv4); // 22. yEn = yEn * tv4 + yEn = Fp.sub(yEn, tv2); // 23. yEn = yEn - tv2 + tv1 = Fp.add(xn2, xd2); // 24. tv1 = xn2 + xd2 + tv1 = Fp.mul(tv1, xd2); // 25. tv1 = tv1 * xd2 + tv1 = Fp.mul(tv1, xd); // 26. tv1 = tv1 * xd + tv1 = Fp.mul(tv1, yn2); // 27. tv1 = tv1 * yn2 + tv1 = Fp.mul(tv1, BigInt(-2)); // 28. tv1 = -2 * tv1 + let yEd = Fp.add(tv2, tv1); // 29. yEd = tv2 + tv1 + tv4 = Fp.mul(tv4, yd2); // 30. tv4 = tv4 * yd2 + yEd = Fp.add(yEd, tv4); // 31. yEd = yEd + tv4 + tv1 = Fp.mul(xEd, yEd); // 32. tv1 = xEd * yEd + let e = Fp.eql(tv1, Fp.ZERO); // 33. e = tv1 == 0 + xEn = Fp.cmov(xEn, Fp.ZERO, e); // 34. xEn = CMOV(xEn, 0, e) + xEd = Fp.cmov(xEd, Fp.ONE, e); // 35. xEd = CMOV(xEd, 1, e) + yEn = Fp.cmov(yEn, Fp.ONE, e); // 36. yEn = CMOV(yEn, 1, e) + yEd = Fp.cmov(yEd, Fp.ONE, e); // 37. yEd = CMOV(yEd, 1, e) + + const inv = Fp.invertBatch([xEd, yEd]); // batch division + return { x: Fp.mul(xEn, inv[0]), y: Fp.mul(yEn, inv[1]) }; // 38. return (xEn, xEd, yEn, yEd) +} + +const htf = /* @__PURE__ */ (() => + createHasher( + ed448.ExtendedPoint, + (scalars: bigint[]) => map_to_curve_elligator2_edwards448(scalars[0]), + { + DST: 'edwards448_XOF:SHAKE256_ELL2_RO_', + encodeDST: 'edwards448_XOF:SHAKE256_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 224, + expand: 'xof', + hash: shake256, + } + ))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/src/index.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/src/index.ts new file mode 100644 index 0000000..0ffab52 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/src/index.ts @@ -0,0 +1 @@ +throw new Error('Incorrect usage. Import submodules instead'); diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/src/jubjub.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/src/jubjub.ts new file mode 100644 index 0000000..203cfa1 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/src/jubjub.ts @@ -0,0 +1,58 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha512 } from '@noble/hashes/sha512'; +import { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils'; +import { twistedEdwards } from './abstract/edwards.js'; +import { blake2s } from '@noble/hashes/blake2s'; +import { Field } from './abstract/modular.js'; + +/** + * jubjub Twisted Edwards curve. + * https://neuromancer.sk/std/other/JubJub + * jubjub does not use EdDSA, so `hash`/sha512 params are passed because interface expects them. + */ + +export const jubjub = twistedEdwards({ + // Params: a, d + a: BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000'), + d: BigInt('0x2a9318e74bfa2b48f5fd9207e6bd7fd4292d7f6d37579d2601065fd6d6343eb1'), + // Finite field 𝔽p over which we'll do calculations + // Same value as bls12-381 Fr (not Fp) + Fp: Field(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')), + // Subgroup order: how many points curve has + n: BigInt('0xe7db4ea6533afa906673b0101343b00a6682093ccc81082d0970e5ed6f72cb7'), + // Cofactor + h: BigInt(8), + // Base point (x, y) aka generator point + Gx: BigInt('0x11dafe5d23e1218086a365b99fbf3d3be72f6afd7d1f72623e6b071492d1122b'), + Gy: BigInt('0x1d523cf1ddab1a1793132e78c866c0c33e26ba5cc220fed7cc3f870e59d292aa'), + hash: sha512, + randomBytes, +} as const); + +const GH_FIRST_BLOCK = utf8ToBytes( + '096b36a5804bfacef1691e173c366a47ff5ba84a44f26ddd7e8d9f79d5b42df0' +); + +// Returns point at JubJub curve which is prime order and not zero +export function groupHash(tag: Uint8Array, personalization: Uint8Array) { + const h = blake2s.create({ personalization, dkLen: 32 }); + h.update(GH_FIRST_BLOCK); + h.update(tag); + // NOTE: returns ExtendedPoint, in case it will be multiplied later + let p = jubjub.ExtendedPoint.fromHex(h.digest()); + // NOTE: cannot replace with isSmallOrder, returns Point*8 + p = p.multiply(jubjub.CURVE.h); + if (p.equals(jubjub.ExtendedPoint.ZERO)) throw new Error('Point has small order'); + return p; +} + +export function findGroupHash(m: Uint8Array, personalization: Uint8Array) { + const tag = concatBytes(m, new Uint8Array([0])); + for (let i = 0; i < 256; i++) { + tag[tag.length - 1] = i; + try { + return groupHash(tag, personalization); + } catch (e) {} + } + throw new Error('findGroupHash tag overflow'); +} diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/src/p256.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/src/p256.ts new file mode 100644 index 0000000..164c470 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/src/p256.ts @@ -0,0 +1,48 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { createCurve } from './_shortw_utils.js'; +import { sha256 } from '@noble/hashes/sha256'; +import { Field } from './abstract/modular.js'; +import { mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import { createHasher } from './abstract/hash-to-curve.js'; + +// NIST secp256r1 aka p256 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256 + +const Fp = Field(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff')); +const CURVE_A = Fp.create(BigInt('-3')); +const CURVE_B = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'); + +// prettier-ignore +export const p256 = createCurve({ + a: CURVE_A, // Equation params: a, b + b: CURVE_B, + Fp, // Field: 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n + // Curve order, total count of valid points in the field + n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'), + // Base (generator) point (x, y) + Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'), + Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'), + h: BigInt(1), + lowS: false, +} as const, sha256); +export const secp256r1 = p256; + +const mapSWU = /* @__PURE__ */ (() => + mapToCurveSimpleSWU(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-10')), + }))(); + +const htf = /* @__PURE__ */ (() => + createHasher(secp256r1.ProjectivePoint, (scalars: bigint[]) => mapSWU(scalars[0]), { + DST: 'P256_XMD:SHA-256_SSWU_RO_', + encodeDST: 'P256_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256, + }))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/src/p384.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/src/p384.ts new file mode 100644 index 0000000..436de9b --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/src/p384.ts @@ -0,0 +1,52 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { createCurve } from './_shortw_utils.js'; +import { sha384 } from '@noble/hashes/sha512'; +import { Field } from './abstract/modular.js'; +import { mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import { createHasher } from './abstract/hash-to-curve.js'; + +// NIST secp384r1 aka p384 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-384 + +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'); +const Fp = Field(P); +const CURVE_A = Fp.create(BigInt('-3')); +// prettier-ignore +const CURVE_B = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'); + +// prettier-ignore +export const p384 = createCurve({ + a: CURVE_A, // Equation params: a, b + b: CURVE_B, + Fp, // Field: 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n + // Curve order, total count of valid points in the field. + n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'), + // Base (generator) point (x, y) + Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'), + Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'), + h: BigInt(1), + lowS: false, +} as const, sha384); +export const secp384r1 = p384; + +const mapSWU = /* @__PURE__ */ (() => + mapToCurveSimpleSWU(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-12')), + }))(); + +const htf = /* @__PURE__ */ (() => + createHasher(secp384r1.ProjectivePoint, (scalars: bigint[]) => mapSWU(scalars[0]), { + DST: 'P384_XMD:SHA-384_SSWU_RO_', + encodeDST: 'P384_XMD:SHA-384_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 192, + expand: 'xmd', + hash: sha384, + }))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/src/p521.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/src/p521.ts new file mode 100644 index 0000000..cc9fbbc --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/src/p521.ts @@ -0,0 +1,68 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { createCurve } from './_shortw_utils.js'; +import { sha512 } from '@noble/hashes/sha512'; +import { Field } from './abstract/modular.js'; +import { mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import { createHasher } from './abstract/hash-to-curve.js'; + +// NIST secp521r1 aka p521 +// Note that it's 521, which differs from 512 of its hash function. +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-521 + +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const Fp = Field(P); + +const CURVE = { + a: Fp.create(BigInt('-3')), + b: BigInt( + '0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00' + ), + Fp, + n: BigInt( + '0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409' + ), + Gx: BigInt( + '0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66' + ), + Gy: BigInt( + '0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650' + ), + h: BigInt(1), +}; + +// prettier-ignore +export const p521 = createCurve({ + a: CURVE.a, // Equation params: a, b + b: CURVE.b, + Fp, // Field: 2n**521n - 1n + // Curve order, total count of valid points in the field + n: CURVE.n, + Gx: CURVE.Gx, // Base point (x, y) aka generator point + Gy: CURVE.Gy, + h: CURVE.h, + lowS: false, + allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b +} as const, sha512); +export const secp521r1 = p521; + +const mapSWU = /* @__PURE__ */ (() => + mapToCurveSimpleSWU(Fp, { + A: CURVE.a, + B: CURVE.b, + Z: Fp.create(BigInt('-4')), + }))(); + +const htf = /* @__PURE__ */ (() => + createHasher(secp521r1.ProjectivePoint, (scalars: bigint[]) => mapSWU(scalars[0]), { + DST: 'P521_XMD:SHA-512_SSWU_RO_', + encodeDST: 'P521_XMD:SHA-512_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 256, + expand: 'xmd', + hash: sha512, + }))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/src/pasta.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/src/pasta.ts new file mode 100644 index 0000000..faed89e --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/src/pasta.ts @@ -0,0 +1,31 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { weierstrass } from './abstract/weierstrass.js'; +import { getHash } from './_shortw_utils.js'; +import * as mod from './abstract/modular.js'; + +export const p = BigInt('0x40000000000000000000000000000000224698fc094cf91b992d30ed00000001'); +export const q = BigInt('0x40000000000000000000000000000000224698fc0994a8dd8c46eb2100000001'); + +// https://neuromancer.sk/std/other/Pallas +export const pallas = weierstrass({ + a: BigInt(0), + b: BigInt(5), + Fp: mod.Field(p), + n: q, + Gx: mod.mod(BigInt(-1), p), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); +// https://neuromancer.sk/std/other/Vesta +export const vesta = weierstrass({ + a: BigInt(0), + b: BigInt(5), + Fp: mod.Field(q), + n: p, + Gx: mod.mod(BigInt(-1), q), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); diff --git a/node_modules/@scure/bip32/node_modules/@noble/curves/src/secp256k1.ts b/node_modules/@scure/bip32/node_modules/@noble/curves/src/secp256k1.ts new file mode 100644 index 0000000..7119222 --- /dev/null +++ b/node_modules/@scure/bip32/node_modules/@noble/curves/src/secp256k1.ts @@ -0,0 +1,274 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { randomBytes } from '@noble/hashes/utils'; +import { Field, mod, pow2 } from './abstract/modular.js'; +import { ProjPointType as PointType, mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import type { Hex, PrivKey } from './abstract/utils.js'; +import { bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE } from './abstract/utils.js'; +import { createHasher, isogenyMap } from './abstract/hash-to-curve.js'; +import { createCurve } from './_shortw_utils.js'; + +const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'); +const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); +const _1n = BigInt(1); +const _2n = BigInt(2); +const divNearest = (a: bigint, b: bigint) => (a + b / _2n) / b; + +/** + * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit. + * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00] + */ +function sqrtMod(y: bigint): bigint { + const P = secp256k1P; + // prettier-ignore + const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + // prettier-ignore + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = (y * y * y) % P; // x^3, 11 + const b3 = (b2 * b2 * y) % P; // x^7 + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b223 = (pow2(b220, _3n, P) * b3) % P; + const t1 = (pow2(b223, _23n, P) * b22) % P; + const t2 = (pow2(t1, _6n, P) * b2) % P; + const root = pow2(t2, _2n, P); + if (!Fp.eql(Fp.sqr(root), y)) throw new Error('Cannot find square root'); + return root; +} + +const Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod }); + +export const secp256k1 = createCurve( + { + a: BigInt(0), // equation params: a, b + b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975 + Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n + n: secp256k1N, // Curve order, total count of valid points in the field + // Base point (x, y) aka generator point + Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), + Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), + h: BigInt(1), // Cofactor + lowS: true, // Allow only low-S signatures by default in sign() and verify() + /** + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 + */ + endo: { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + splitScalar: (k: bigint) => { + const n = secp256k1N; + const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); + const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); + const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); + const b2 = a1; + const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16) + + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = mod(k - c1 * a1 - c2 * a2, n); + let k2 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) k1 = n - k1; + if (k2neg) k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error('splitScalar: Endomorphism failed, k=' + k); + } + return { k1neg, k1, k2neg, k2 }; + }, + }, + }, + sha256 +); + +// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code. +// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki +const _0n = BigInt(0); +const fe = (x: bigint) => typeof x === 'bigint' && _0n < x && x < secp256k1P; +const ge = (x: bigint) => typeof x === 'bigint' && _0n < x && x < secp256k1N; +/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */ +const TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {}; +function taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array { + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === undefined) { + const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + tagP = concatBytes(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return sha256(concatBytes(tagP, ...messages)); +} + +// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03 +const pointToBytes = (point: PointType) => point.toRawBytes(true).slice(1); +const numTo32b = (n: bigint) => numberToBytesBE(n, 32); +const modP = (x: bigint) => mod(x, secp256k1P); +const modN = (x: bigint) => mod(x, secp256k1N); +const Point = secp256k1.ProjectivePoint; +const GmulAdd = (Q: PointType, a: bigint, b: bigint) => + Point.BASE.multiplyAndAddUnsafe(Q, a, b); + +// Calculate point, scalar and bytes +function schnorrGetExtPubKey(priv: PrivKey) { + let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey + let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside + const scalar = p.hasEvenY() ? d_ : modN(-d_); + return { scalar: scalar, bytes: pointToBytes(p) }; +} +/** + * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point. + * @returns valid point checked for being on-curve + */ +function lift_x(x: bigint): PointType { + if (!fe(x)) throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p. + const xx = modP(x * x); + const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p. + let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p. + if (y % _2n !== _0n) y = modP(-y); // Return the unique point P such that x(P) = x and + const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise. + p.assertValidity(); + return p; +} +/** + * Create tagged hash, convert it to bigint, reduce modulo-n. + */ +function challenge(...args: Uint8Array[]): bigint { + return modN(bytesToNumberBE(taggedHash('BIP0340/challenge', ...args))); +} + +/** + * Schnorr public key is just `x` coordinate of Point as per BIP340. + */ +function schnorrGetPublicKey(privateKey: Hex): Uint8Array { + return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G) +} + +/** + * Creates Schnorr signature as per BIP340. Verifies itself before returning anything. + * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous. + */ +function schnorrSign( + message: Hex, + privateKey: PrivKey, + auxRand: Hex = randomBytes(32) +): Uint8Array { + const m = ensureBytes('message', message); + const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder + const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array + const t = numTo32b(d ^ bytesToNumberBE(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a) + const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m) + const k_ = modN(bytesToNumberBE(rand)); // Let k' = int(rand) mod n + if (k_ === _0n) throw new Error('sign failed: k is zero'); // Fail if k' = 0. + const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G. + const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n. + const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n). + sig.set(rx, 0); + sig.set(numTo32b(modN(k + e * d)), 32); + // If Verify(bytes(P), m, sig) (see below) returns failure, abort + if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced'); + return sig; +} + +/** + * Verifies Schnorr signature. + * Will swallow errors & return false except for initial type validation of arguments. + */ +function schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean { + const sig = ensureBytes('signature', signature, 64); + const m = ensureBytes('message', message); + const pub = ensureBytes('publicKey', publicKey, 32); + try { + const P = lift_x(bytesToNumberBE(pub)); // P = lift_x(int(pk)); fail if that fails + const r = bytesToNumberBE(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p. + if (!fe(r)) return false; + const s = bytesToNumberBE(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n. + if (!ge(s)) return false; + const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n + const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P + if (!R || !R.hasEvenY() || R.toAffine().x !== r) return false; // -eP == (n-e)P + return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r. + } catch (error) { + return false; + } +} + +export const schnorr = /* @__PURE__ */ (() => ({ + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + utils: { + randomPrivateKey: secp256k1.utils.randomPrivateKey, + lift_x, + pointToBytes, + numberToBytesBE, + bytesToNumberBE, + taggedHash, + mod, + }, +}))(); + +const isoMap = /* @__PURE__ */ (() => + isogenyMap( + Fp, + [ + // xNum + [ + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7', + '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581', + '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262', + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c', + ], + // xDen + [ + '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b', + '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c', + '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3', + '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931', + '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84', + ], + // yDen + [ + '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b', + '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573', + '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + ].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]] + ))(); +const mapSWU = /* @__PURE__ */ (() => + mapToCurveSimpleSWU(Fp, { + A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'), + B: BigInt('1771'), + Z: Fp.create(BigInt('-11')), + }))(); +const htf = /* @__PURE__ */ (() => + createHasher( + secp256k1.ProjectivePoint, + (scalars: bigint[]) => { + const { x, y } = mapSWU(Fp.create(scalars[0])); + return isoMap(x, y); + }, + { + DST: 'secp256k1_XMD:SHA-256_SSWU_RO_', + encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256, + } + ))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); diff --git a/node_modules/@scure/bip32/package.json b/node_modules/@scure/bip32/package.json new file mode 100644 index 0000000..dcfaf67 --- /dev/null +++ b/node_modules/@scure/bip32/package.json @@ -0,0 +1,72 @@ +{ + "name": "@scure/bip32", + "version": "1.3.1", + "description": "Secure, audited & minimal implementation of BIP32 hierarchical deterministic (HD) wallets over secp256k1", + "files": [ + "index.ts", + "lib/index.js", + "lib/index.d.ts", + "lib/index.js.map", + "lib/esm/package.json", + "lib/esm/index.js", + "lib/esm/index.js.map" + ], + "main": "lib/index.js", + "module": "lib/esm/index.js", + "types": "lib/index.d.ts", + "exports": { + ".": { + "types": "./lib/index.d.ts", + "import": "./lib/esm/index.js", + "default": "./lib/index.js" + } + }, + "dependencies": { + "@noble/curves": "~1.1.0", + "@noble/hashes": "~1.3.1", + "@scure/base": "~1.1.0" + }, + "devDependencies": { + "micro-should": "0.4.0", + "prettier": "2.8.4", + "typescript": "5.0.2" + }, + "author": "Paul Miller (https://paulmillr.com)", + "homepage": "https://paulmillr.com/", + "repository": { + "type": "git", + "url": "https://github.com/paulmillr/scure-bip32.git" + }, + "contributors": [ + { + "name": "Patricio Palladino", + "email": "patricio@nomiclabs.io" + }, + { + "name": "Paul Miller", + "url": "https://paulmillr.com" + } + ], + "license": "MIT", + "scripts": { + "build": "tsc -d && tsc -p tsconfig.esm.json", + "lint": "prettier --check 'index.ts' 'test/*.test.ts'", + "format": "prettier --write 'index.ts' 'test/*.test.ts'", + "test": "cd test && tsc && node hdkey.test.js" + }, + "keywords": [ + "bip32", + "hierarchical", + "deterministic", + "hd key", + "bip0032", + "bip-32", + "bip39", + "micro", + "scure", + "mnemonic", + "phrase", + "code" + ], + "funding": "https://paulmillr.com/funding/" +} diff --git a/node_modules/@scure/bip39/LICENSE b/node_modules/@scure/bip39/LICENSE new file mode 100644 index 0000000..68222b8 --- /dev/null +++ b/node_modules/@scure/bip39/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/@scure/bip39/README.md b/node_modules/@scure/bip39/README.md new file mode 100644 index 0000000..281df3b --- /dev/null +++ b/node_modules/@scure/bip39/README.md @@ -0,0 +1,97 @@ +# scure-bip39 + +Secure, [audited](#security) & minimal implementation of BIP39 mnemonic phrases. + +Compared to popular `bip39` package, scure-bip39: + +- Supports ESM and common.js +- Supports tree-shaking: only actually used wordlists are bundled +- Is 491KB all-bundled instead of 1.3MB +- Uses 2 dependencies instead of 15 +- Wordlists are 157KB instead of 315KB +- Had an external security [audit](#security) by Cure53 + +Check out [scure-bip32](https://github.com/paulmillr/scure-bip32) if you need +hierarchical deterministic wallets ("HD Wallets"). + +### This library belongs to *scure* + +> **scure** — secure, independently audited packages for every use case. + +- All releases are signed with PGP keys +- As minimal as possible +- Check out all libraries: + [base](https://github.com/paulmillr/scure-base), + [bip32](https://github.com/paulmillr/scure-bip32), + [bip39](https://github.com/paulmillr/scure-bip39), + [btc-signer](https://github.com/paulmillr/scure-btc-signer) + +## Usage + +> npm install @scure/bip39 + +Or + +> yarn add @scure/bip39 + +```js +import * as bip39 from '@scure/bip39'; +import { wordlist } from '@scure/bip39/wordlists/english'; + +// Generate x random words. Uses Cryptographically-Secure Random Number Generator. +const mn = bip39.generateMnemonic(wordlist); +console.log(mn); + +// Reversible: Converts mnemonic string to raw entropy in form of byte array. +const ent = bip39.mnemonicToEntropy(mn, wordlist) + +// Reversible: Converts raw entropy in form of byte array to mnemonic string. +bip39.entropyToMnemonic(ent, wordlist); + +// Validates mnemonic for being 12-24 words contained in `wordlist`. +bip39.validateMnemonic(mn, wordlist); + +// Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password. +await bip39.mnemonicToSeed(mn, 'password'); +bip39.mnemonicToSeedSync(mn, 'password'); +``` + +This submodule contains the word lists defined by BIP39 for Czech, English, French, Italian, Japanese, Korean, Simplified and Traditional Chinese, and Spanish. These are not imported by default, as that would increase bundle sizes too much. Instead, you should import and use them explicitly. + +```typescript +function generateMnemonic(wordlist: string[], strength?: number): string; +function mnemonicToEntropy(mnemonic: string, wordlist: string[]): Uint8Array; +function entropyToMnemonic(entropy: Uint8Array, wordlist: string[]): string; +function validateMnemonic(mnemonic: string, wordlist: string[]): boolean; +function mnemonicToSeed(mnemonic: string, passphrase?: string): Promise; +function mnemonicToSeedSync(mnemonic: string, passphrase?: string): Uint8Array; +``` + +All wordlists: + +```typescript +import { wordlist as czech } from '@scure/bip39/wordlists/czech'; +import { wordlist as english } from '@scure/bip39/wordlists/english'; +import { wordlist as french } from '@scure/bip39/wordlists/french'; +import { wordlist as italian } from '@scure/bip39/wordlists/italian'; +import { wordlist as japanese } from '@scure/bip39/wordlists/japanese'; +import { wordlist as korean } from '@scure/bip39/wordlists/korean'; +import { wordlist as simp } from '@scure/bip39/wordlists/simplified-chinese'; +import { wordlist as spanish } from '@scure/bip39/wordlists/spanish'; +import { wordlist as trad } from '@scure/bip39/wordlists/traditional-chinese'; +``` + +## Security + +The library has been audited by Cure53 on Jan 5, 2022. Check out the audit [PDF](./audit/2022-01-05-cure53-audit-nbl2.pdf) & [URL](https://cure53.de/pentest-report_hashing-libs.pdf). See [changes since audit](https://github.com/paulmillr/scure-bip39/compare/1.0.0..main). + +1. The library was initially developed for [js-ethereum-cryptography](https://github.com/ethereum/js-ethereum-cryptography) +2. At commit [ae00e6d7](https://github.com/ethereum/js-ethereum-cryptography/commit/ae00e6d7d24fb3c76a1c7fe10039f6ecd120b77e), it + was extracted to a separate package called `micro-bip39` +3. After the audit we've decided to use NPM namespace for security. Since `@micro` namespace was taken, we've renamed the package to `@scure/bip39` + +## License + +[MIT License](./LICENSE) + +Copyright (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) diff --git a/node_modules/@scure/bip39/esm/index.js b/node_modules/@scure/bip39/esm/index.js new file mode 100644 index 0000000..fd55e60 --- /dev/null +++ b/node_modules/@scure/bip39/esm/index.js @@ -0,0 +1,69 @@ +import assert from '@noble/hashes/_assert'; +import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2'; +import { sha256 } from '@noble/hashes/sha256'; +import { sha512 } from '@noble/hashes/sha512'; +import { randomBytes } from '@noble/hashes/utils'; +import { utils as baseUtils } from '@scure/base'; +const isJapanese = (wordlist) => wordlist[0] === '\u3042\u3044\u3053\u304f\u3057\u3093'; +function nfkd(str) { + if (typeof str !== 'string') + throw new TypeError(`Invalid mnemonic type: ${typeof str}`); + return str.normalize('NFKD'); +} +function normalize(str) { + const norm = nfkd(str); + const words = norm.split(' '); + if (![12, 15, 18, 21, 24].includes(words.length)) + throw new Error('Invalid mnemonic'); + return { nfkd: norm, words }; +} +function assertEntropy(entropy) { + assert.bytes(entropy, 16, 20, 24, 28, 32); +} +export function generateMnemonic(wordlist, strength = 128) { + assert.number(strength); + if (strength % 32 !== 0 || strength > 256) + throw new TypeError('Invalid entropy'); + return entropyToMnemonic(randomBytes(strength / 8), wordlist); +} +const calcChecksum = (entropy) => { + const bitsLeft = 8 - entropy.length / 4; + return new Uint8Array([(sha256(entropy)[0] >> bitsLeft) << bitsLeft]); +}; +function getCoder(wordlist) { + if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string') + throw new Error('Worlist: expected array of 2048 strings'); + wordlist.forEach((i) => { + if (typeof i !== 'string') + throw new Error(`Wordlist: non-string element: ${i}`); + }); + return baseUtils.chain(baseUtils.checksum(1, calcChecksum), baseUtils.radix2(11, true), baseUtils.alphabet(wordlist)); +} +export function mnemonicToEntropy(mnemonic, wordlist) { + const { words } = normalize(mnemonic); + const entropy = getCoder(wordlist).decode(words); + assertEntropy(entropy); + return entropy; +} +export function entropyToMnemonic(entropy, wordlist) { + assertEntropy(entropy); + const words = getCoder(wordlist).encode(entropy); + return words.join(isJapanese(wordlist) ? '\u3000' : ' '); +} +export function validateMnemonic(mnemonic, wordlist) { + try { + mnemonicToEntropy(mnemonic, wordlist); + } + catch (e) { + return false; + } + return true; +} +const salt = (passphrase) => nfkd(`mnemonic${passphrase}`); +export function mnemonicToSeed(mnemonic, passphrase = '') { + return pbkdf2Async(sha512, normalize(mnemonic).nfkd, salt(passphrase), { c: 2048, dkLen: 64 }); +} +export function mnemonicToSeedSync(mnemonic, passphrase = '') { + return pbkdf2(sha512, normalize(mnemonic).nfkd, salt(passphrase), { c: 2048, dkLen: 64 }); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/esm/index.js.map b/node_modules/@scure/bip39/esm/index.js.map new file mode 100644 index 0000000..a8297d2 --- /dev/null +++ b/node_modules/@scure/bip39/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,MAAM,MAAM,uBAAuB,CAAC;AAC3C,OAAO,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E,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;AAC5F,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip39/esm/package.json b/node_modules/@scure/bip39/esm/package.json new file mode 100644 index 0000000..aead43d --- /dev/null +++ b/node_modules/@scure/bip39/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} \ No newline at end of file diff --git a/node_modules/@scure/bip39/esm/wordlists/czech.js b/node_modules/@scure/bip39/esm/wordlists/czech.js new file mode 100644 index 0000000..cf7b564 --- /dev/null +++ b/node_modules/@scure/bip39/esm/wordlists/czech.js @@ -0,0 +1,2049 @@ +export const wordlist = `abdikace +abeceda +adresa +agrese +akce +aktovka +alej +alkohol +amputace +ananas +andulka +anekdota +anketa +antika +anulovat +archa +arogance +asfalt +asistent +aspirace +astma +astronom +atlas +atletika +atol +autobus +azyl +babka +bachor +bacil +baculka +badatel +bageta +bagr +bahno +bakterie +balada +baletka +balkon +balonek +balvan +balza +bambus +bankomat +barbar +baret +barman +baroko +barva +baterka +batoh +bavlna +bazalka +bazilika +bazuka +bedna +beran +beseda +bestie +beton +bezinka +bezmoc +beztak +bicykl +bidlo +biftek +bikiny +bilance +biograf +biolog +bitva +bizon +blahobyt +blatouch +blecha +bledule +blesk +blikat +blizna +blokovat +bloudit +blud +bobek +bobr +bodlina +bodnout +bohatost +bojkot +bojovat +bokorys +bolest +borec +borovice +bota +boubel +bouchat +bouda +boule +bourat +boxer +bradavka +brambora +branka +bratr +brepta +briketa +brko +brloh +bronz +broskev +brunetka +brusinka +brzda +brzy +bublina +bubnovat +buchta +buditel +budka +budova +bufet +bujarost +bukvice +buldok +bulva +bunda +bunkr +burza +butik +buvol +buzola +bydlet +bylina +bytovka +bzukot +capart +carevna +cedr +cedule +cejch +cejn +cela +celer +celkem +celnice +cenina +cennost +cenovka +centrum +cenzor +cestopis +cetka +chalupa +chapadlo +charita +chata +chechtat +chemie +chichot +chirurg +chlad +chleba +chlubit +chmel +chmura +chobot +chochol +chodba +cholera +chomout +chopit +choroba +chov +chrapot +chrlit +chrt +chrup +chtivost +chudina +chutnat +chvat +chvilka +chvost +chyba +chystat +chytit +cibule +cigareta +cihelna +cihla +cinkot +cirkus +cisterna +citace +citrus +cizinec +cizost +clona +cokoliv +couvat +ctitel +ctnost +cudnost +cuketa +cukr +cupot +cvaknout +cval +cvik +cvrkot +cyklista +daleko +dareba +datel +datum +dcera +debata +dechovka +decibel +deficit +deflace +dekl +dekret +demokrat +deprese +derby +deska +detektiv +dikobraz +diktovat +dioda +diplom +disk +displej +divadlo +divoch +dlaha +dlouho +dluhopis +dnes +dobro +dobytek +docent +dochutit +dodnes +dohled +dohoda +dohra +dojem +dojnice +doklad +dokola +doktor +dokument +dolar +doleva +dolina +doma +dominant +domluvit +domov +donutit +dopad +dopis +doplnit +doposud +doprovod +dopustit +dorazit +dorost +dort +dosah +doslov +dostatek +dosud +dosyta +dotaz +dotek +dotknout +doufat +doutnat +dovozce +dozadu +doznat +dozorce +drahota +drak +dramatik +dravec +draze +drdol +drobnost +drogerie +drozd +drsnost +drtit +drzost +duben +duchovno +dudek +duha +duhovka +dusit +dusno +dutost +dvojice +dvorec +dynamit +ekolog +ekonomie +elektron +elipsa +email +emise +emoce +empatie +epizoda +epocha +epopej +epos +esej +esence +eskorta +eskymo +etiketa +euforie +evoluce +exekuce +exkurze +expedice +exploze +export +extrakt +facka +fajfka +fakulta +fanatik +fantazie +farmacie +favorit +fazole +federace +fejeton +fenka +fialka +figurant +filozof +filtr +finance +finta +fixace +fjord +flanel +flirt +flotila +fond +fosfor +fotbal +fotka +foton +frakce +freska +fronta +fukar +funkce +fyzika +galeje +garant +genetika +geolog +gilotina +glazura +glejt +golem +golfista +gotika +graf +gramofon +granule +grep +gril +grog +groteska +guma +hadice +hadr +hala +halenka +hanba +hanopis +harfa +harpuna +havran +hebkost +hejkal +hejno +hejtman +hektar +helma +hematom +herec +herna +heslo +hezky +historik +hladovka +hlasivky +hlava +hledat +hlen +hlodavec +hloh +hloupost +hltat +hlubina +hluchota +hmat +hmota +hmyz +hnis +hnojivo +hnout +hoblina +hoboj +hoch +hodiny +hodlat +hodnota +hodovat +hojnost +hokej +holinka +holka +holub +homole +honitba +honorace +horal +horda +horizont +horko +horlivec +hormon +hornina +horoskop +horstvo +hospoda +hostina +hotovost +houba +houf +houpat +houska +hovor +hradba +hranice +hravost +hrazda +hrbolek +hrdina +hrdlo +hrdost +hrnek +hrobka +hromada +hrot +hrouda +hrozen +hrstka +hrubost +hryzat +hubenost +hubnout +hudba +hukot +humr +husita +hustota +hvozd +hybnost +hydrant +hygiena +hymna +hysterik +idylka +ihned +ikona +iluze +imunita +infekce +inflace +inkaso +inovace +inspekce +internet +invalida +investor +inzerce +ironie +jablko +jachta +jahoda +jakmile +jakost +jalovec +jantar +jarmark +jaro +jasan +jasno +jatka +javor +jazyk +jedinec +jedle +jednatel +jehlan +jekot +jelen +jelito +jemnost +jenom +jepice +jeseter +jevit +jezdec +jezero +jinak +jindy +jinoch +jiskra +jistota +jitrnice +jizva +jmenovat +jogurt +jurta +kabaret +kabel +kabinet +kachna +kadet +kadidlo +kahan +kajak +kajuta +kakao +kaktus +kalamita +kalhoty +kalibr +kalnost +kamera +kamkoliv +kamna +kanibal +kanoe +kantor +kapalina +kapela +kapitola +kapka +kaple +kapota +kapr +kapusta +kapybara +karamel +karotka +karton +kasa +katalog +katedra +kauce +kauza +kavalec +kazajka +kazeta +kazivost +kdekoliv +kdesi +kedluben +kemp +keramika +kino +klacek +kladivo +klam +klapot +klasika +klaun +klec +klenba +klepat +klesnout +klid +klima +klisna +klobouk +klokan +klopa +kloub +klubovna +klusat +kluzkost +kmen +kmitat +kmotr +kniha +knot +koalice +koberec +kobka +kobliha +kobyla +kocour +kohout +kojenec +kokos +koktejl +kolaps +koleda +kolize +kolo +komando +kometa +komik +komnata +komora +kompas +komunita +konat +koncept +kondice +konec +konfese +kongres +konina +konkurs +kontakt +konzerva +kopanec +kopie +kopnout +koprovka +korbel +korektor +kormidlo +koroptev +korpus +koruna +koryto +korzet +kosatec +kostka +kotel +kotleta +kotoul +koukat +koupelna +kousek +kouzlo +kovboj +koza +kozoroh +krabice +krach +krajina +kralovat +krasopis +kravata +kredit +krejcar +kresba +kreveta +kriket +kritik +krize +krkavec +krmelec +krmivo +krocan +krok +kronika +kropit +kroupa +krovka +krtek +kruhadlo +krupice +krutost +krvinka +krychle +krypta +krystal +kryt +kudlanka +kufr +kujnost +kukla +kulajda +kulich +kulka +kulomet +kultura +kuna +kupodivu +kurt +kurzor +kutil +kvalita +kvasinka +kvestor +kynolog +kyselina +kytara +kytice +kytka +kytovec +kyvadlo +labrador +lachtan +ladnost +laik +lakomec +lamela +lampa +lanovka +lasice +laso +lastura +latinka +lavina +lebka +leckdy +leden +lednice +ledovka +ledvina +legenda +legie +legrace +lehce +lehkost +lehnout +lektvar +lenochod +lentilka +lepenka +lepidlo +letadlo +letec +letmo +letokruh +levhart +levitace +levobok +libra +lichotka +lidojed +lidskost +lihovina +lijavec +lilek +limetka +linie +linka +linoleum +listopad +litina +litovat +lobista +lodivod +logika +logoped +lokalita +loket +lomcovat +lopata +lopuch +lord +losos +lotr +loudal +louh +louka +louskat +lovec +lstivost +lucerna +lucifer +lump +lusk +lustrace +lvice +lyra +lyrika +lysina +madam +madlo +magistr +mahagon +majetek +majitel +majorita +makak +makovice +makrela +malba +malina +malovat +malvice +maminka +mandle +manko +marnost +masakr +maskot +masopust +matice +matrika +maturita +mazanec +mazivo +mazlit +mazurka +mdloba +mechanik +meditace +medovina +melasa +meloun +mentolka +metla +metoda +metr +mezera +migrace +mihnout +mihule +mikina +mikrofon +milenec +milimetr +milost +mimika +mincovna +minibar +minomet +minulost +miska +mistr +mixovat +mladost +mlha +mlhovina +mlok +mlsat +mluvit +mnich +mnohem +mobil +mocnost +modelka +modlitba +mohyla +mokro +molekula +momentka +monarcha +monokl +monstrum +montovat +monzun +mosaz +moskyt +most +motivace +motorka +motyka +moucha +moudrost +mozaika +mozek +mozol +mramor +mravenec +mrkev +mrtvola +mrzet +mrzutost +mstitel +mudrc +muflon +mulat +mumie +munice +muset +mutace +muzeum +muzikant +myslivec +mzda +nabourat +nachytat +nadace +nadbytek +nadhoz +nadobro +nadpis +nahlas +nahnat +nahodile +nahradit +naivita +najednou +najisto +najmout +naklonit +nakonec +nakrmit +nalevo +namazat +namluvit +nanometr +naoko +naopak +naostro +napadat +napevno +naplnit +napnout +naposled +naprosto +narodit +naruby +narychlo +nasadit +nasekat +naslepo +nastat +natolik +navenek +navrch +navzdory +nazvat +nebe +nechat +necky +nedaleko +nedbat +neduh +negace +nehet +nehoda +nejen +nejprve +neklid +nelibost +nemilost +nemoc +neochota +neonka +nepokoj +nerost +nerv +nesmysl +nesoulad +netvor +neuron +nevina +nezvykle +nicota +nijak +nikam +nikdy +nikl +nikterak +nitro +nocleh +nohavice +nominace +nora +norek +nositel +nosnost +nouze +noviny +novota +nozdra +nuda +nudle +nuget +nutit +nutnost +nutrie +nymfa +obal +obarvit +obava +obdiv +obec +obehnat +obejmout +obezita +obhajoba +obilnice +objasnit +objekt +obklopit +oblast +oblek +obliba +obloha +obluda +obnos +obohatit +obojek +obout +obrazec +obrna +obruba +obrys +obsah +obsluha +obstarat +obuv +obvaz +obvinit +obvod +obvykle +obyvatel +obzor +ocas +ocel +ocenit +ochladit +ochota +ochrana +ocitnout +odboj +odbyt +odchod +odcizit +odebrat +odeslat +odevzdat +odezva +odhadce +odhodit +odjet +odjinud +odkaz +odkoupit +odliv +odluka +odmlka +odolnost +odpad +odpis +odplout +odpor +odpustit +odpykat +odrazka +odsoudit +odstup +odsun +odtok +odtud +odvaha +odveta +odvolat +odvracet +odznak +ofina +ofsajd +ohlas +ohnisko +ohrada +ohrozit +ohryzek +okap +okenice +oklika +okno +okouzlit +okovy +okrasa +okres +okrsek +okruh +okupant +okurka +okusit +olejnina +olizovat +omak +omeleta +omezit +omladina +omlouvat +omluva +omyl +onehdy +opakovat +opasek +operace +opice +opilost +opisovat +opora +opozice +opravdu +oproti +orbital +orchestr +orgie +orlice +orloj +ortel +osada +oschnout +osika +osivo +oslava +oslepit +oslnit +oslovit +osnova +osoba +osolit +ospalec +osten +ostraha +ostuda +ostych +osvojit +oteplit +otisk +otop +otrhat +otrlost +otrok +otruby +otvor +ovanout +ovar +oves +ovlivnit +ovoce +oxid +ozdoba +pachatel +pacient +padouch +pahorek +pakt +palanda +palec +palivo +paluba +pamflet +pamlsek +panenka +panika +panna +panovat +panstvo +pantofle +paprika +parketa +parodie +parta +paruka +paryba +paseka +pasivita +pastelka +patent +patrona +pavouk +pazneht +pazourek +pecka +pedagog +pejsek +peklo +peloton +penalta +pendrek +penze +periskop +pero +pestrost +petarda +petice +petrolej +pevnina +pexeso +pianista +piha +pijavice +pikle +piknik +pilina +pilnost +pilulka +pinzeta +pipeta +pisatel +pistole +pitevna +pivnice +pivovar +placenta +plakat +plamen +planeta +plastika +platit +plavidlo +plaz +plech +plemeno +plenta +ples +pletivo +plevel +plivat +plnit +plno +plocha +plodina +plomba +plout +pluk +plyn +pobavit +pobyt +pochod +pocit +poctivec +podat +podcenit +podepsat +podhled +podivit +podklad +podmanit +podnik +podoba +podpora +podraz +podstata +podvod +podzim +poezie +pohanka +pohnutka +pohovor +pohroma +pohyb +pointa +pojistka +pojmout +pokazit +pokles +pokoj +pokrok +pokuta +pokyn +poledne +polibek +polknout +poloha +polynom +pomalu +pominout +pomlka +pomoc +pomsta +pomyslet +ponechat +ponorka +ponurost +popadat +popel +popisek +poplach +poprosit +popsat +popud +poradce +porce +porod +porucha +poryv +posadit +posed +posila +poskok +poslanec +posoudit +pospolu +postava +posudek +posyp +potah +potkan +potlesk +potomek +potrava +potupa +potvora +poukaz +pouto +pouzdro +povaha +povidla +povlak +povoz +povrch +povstat +povyk +povzdech +pozdrav +pozemek +poznatek +pozor +pozvat +pracovat +prahory +praktika +prales +praotec +praporek +prase +pravda +princip +prkno +probudit +procento +prodej +profese +prohra +projekt +prolomit +promile +pronikat +propad +prorok +prosba +proton +proutek +provaz +prskavka +prsten +prudkost +prut +prvek +prvohory +psanec +psovod +pstruh +ptactvo +puberta +puch +pudl +pukavec +puklina +pukrle +pult +pumpa +punc +pupen +pusa +pusinka +pustina +putovat +putyka +pyramida +pysk +pytel +racek +rachot +radiace +radnice +radon +raft +ragby +raketa +rakovina +rameno +rampouch +rande +rarach +rarita +rasovna +rastr +ratolest +razance +razidlo +reagovat +reakce +recept +redaktor +referent +reflex +rejnok +reklama +rekord +rekrut +rektor +reputace +revize +revma +revolver +rezerva +riskovat +riziko +robotika +rodokmen +rohovka +rokle +rokoko +romaneto +ropovod +ropucha +rorejs +rosol +rostlina +rotmistr +rotoped +rotunda +roubenka +roucho +roup +roura +rovina +rovnice +rozbor +rozchod +rozdat +rozeznat +rozhodce +rozinka +rozjezd +rozkaz +rozloha +rozmar +rozpad +rozruch +rozsah +roztok +rozum +rozvod +rubrika +ruchadlo +rukavice +rukopis +ryba +rybolov +rychlost +rydlo +rypadlo +rytina +ryzost +sadista +sahat +sako +samec +samizdat +samota +sanitka +sardinka +sasanka +satelit +sazba +sazenice +sbor +schovat +sebranka +secese +sedadlo +sediment +sedlo +sehnat +sejmout +sekera +sekta +sekunda +sekvoje +semeno +seno +servis +sesadit +seshora +seskok +seslat +sestra +sesuv +sesypat +setba +setina +setkat +setnout +setrvat +sever +seznam +shoda +shrnout +sifon +silnice +sirka +sirotek +sirup +situace +skafandr +skalisko +skanzen +skaut +skeptik +skica +skladba +sklenice +sklo +skluz +skoba +skokan +skoro +skripta +skrz +skupina +skvost +skvrna +slabika +sladidlo +slanina +slast +slavnost +sledovat +slepec +sleva +slezina +slib +slina +sliznice +slon +sloupek +slovo +sluch +sluha +slunce +slupka +slza +smaragd +smetana +smilstvo +smlouva +smog +smrad +smrk +smrtka +smutek +smysl +snad +snaha +snob +sobota +socha +sodovka +sokol +sopka +sotva +souboj +soucit +soudce +souhlas +soulad +soumrak +souprava +soused +soutok +souviset +spalovna +spasitel +spis +splav +spodek +spojenec +spolu +sponzor +spornost +spousta +sprcha +spustit +sranda +sraz +srdce +srna +srnec +srovnat +srpen +srst +srub +stanice +starosta +statika +stavba +stehno +stezka +stodola +stolek +stopa +storno +stoupat +strach +stres +strhnout +strom +struna +studna +stupnice +stvol +styk +subjekt +subtropy +suchar +sudost +sukno +sundat +sunout +surikata +surovina +svah +svalstvo +svetr +svatba +svazek +svisle +svitek +svoboda +svodidlo +svorka +svrab +sykavka +sykot +synek +synovec +sypat +sypkost +syrovost +sysel +sytost +tabletka +tabule +tahoun +tajemno +tajfun +tajga +tajit +tajnost +taktika +tamhle +tampon +tancovat +tanec +tanker +tapeta +tavenina +tazatel +technika +tehdy +tekutina +telefon +temnota +tendence +tenista +tenor +teplota +tepna +teprve +terapie +termoska +textil +ticho +tiskopis +titulek +tkadlec +tkanina +tlapka +tleskat +tlukot +tlupa +tmel +toaleta +topinka +topol +torzo +touha +toulec +tradice +traktor +tramp +trasa +traverza +trefit +trest +trezor +trhavina +trhlina +trochu +trojice +troska +trouba +trpce +trpitel +trpkost +trubec +truchlit +truhlice +trus +trvat +tudy +tuhnout +tuhost +tundra +turista +turnaj +tuzemsko +tvaroh +tvorba +tvrdost +tvrz +tygr +tykev +ubohost +uboze +ubrat +ubrousek +ubrus +ubytovna +ucho +uctivost +udivit +uhradit +ujednat +ujistit +ujmout +ukazatel +uklidnit +uklonit +ukotvit +ukrojit +ulice +ulita +ulovit +umyvadlo +unavit +uniforma +uniknout +upadnout +uplatnit +uplynout +upoutat +upravit +uran +urazit +usednout +usilovat +usmrtit +usnadnit +usnout +usoudit +ustlat +ustrnout +utahovat +utkat +utlumit +utonout +utopenec +utrousit +uvalit +uvolnit +uvozovka +uzdravit +uzel +uzenina +uzlina +uznat +vagon +valcha +valoun +vana +vandal +vanilka +varan +varhany +varovat +vcelku +vchod +vdova +vedro +vegetace +vejce +velbloud +veletrh +velitel +velmoc +velryba +venkov +veranda +verze +veselka +veskrze +vesnice +vespodu +vesta +veterina +veverka +vibrace +vichr +videohra +vidina +vidle +vila +vinice +viset +vitalita +vize +vizitka +vjezd +vklad +vkus +vlajka +vlak +vlasec +vlevo +vlhkost +vliv +vlnovka +vloupat +vnucovat +vnuk +voda +vodivost +vodoznak +vodstvo +vojensky +vojna +vojsko +volant +volba +volit +volno +voskovka +vozidlo +vozovna +vpravo +vrabec +vracet +vrah +vrata +vrba +vrcholek +vrhat +vrstva +vrtule +vsadit +vstoupit +vstup +vtip +vybavit +vybrat +vychovat +vydat +vydra +vyfotit +vyhledat +vyhnout +vyhodit +vyhradit +vyhubit +vyjasnit +vyjet +vyjmout +vyklopit +vykonat +vylekat +vymazat +vymezit +vymizet +vymyslet +vynechat +vynikat +vynutit +vypadat +vyplatit +vypravit +vypustit +vyrazit +vyrovnat +vyrvat +vyslovit +vysoko +vystavit +vysunout +vysypat +vytasit +vytesat +vytratit +vyvinout +vyvolat +vyvrhel +vyzdobit +vyznat +vzadu +vzbudit +vzchopit +vzdor +vzduch +vzdychat +vzestup +vzhledem +vzkaz +vzlykat +vznik +vzorek +vzpoura +vztah +vztek +xylofon +zabrat +zabydlet +zachovat +zadarmo +zadusit +zafoukat +zahltit +zahodit +zahrada +zahynout +zajatec +zajet +zajistit +zaklepat +zakoupit +zalepit +zamezit +zamotat +zamyslet +zanechat +zanikat +zaplatit +zapojit +zapsat +zarazit +zastavit +zasunout +zatajit +zatemnit +zatknout +zaujmout +zavalit +zavelet +zavinit +zavolat +zavrtat +zazvonit +zbavit +zbrusu +zbudovat +zbytek +zdaleka +zdarma +zdatnost +zdivo +zdobit +zdroj +zdvih +zdymadlo +zelenina +zeman +zemina +zeptat +zezadu +zezdola +zhatit +zhltnout +zhluboka +zhotovit +zhruba +zima +zimnice +zjemnit +zklamat +zkoumat +zkratka +zkumavka +zlato +zlehka +zloba +zlom +zlost +zlozvyk +zmapovat +zmar +zmatek +zmije +zmizet +zmocnit +zmodrat +zmrzlina +zmutovat +znak +znalost +znamenat +znovu +zobrazit +zotavit +zoubek +zoufale +zplodit +zpomalit +zprava +zprostit +zprudka +zprvu +zrada +zranit +zrcadlo +zrnitost +zrno +zrovna +zrychlit +zrzavost +zticha +ztratit +zubovina +zubr +zvednout +zvenku +zvesela +zvon +zvrat +zvukovod +zvyk`.split('\n'); +//# sourceMappingURL=czech.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/esm/wordlists/czech.js.map b/node_modules/@scure/bip39/esm/wordlists/czech.js.map new file mode 100644 index 0000000..613dd9f --- /dev/null +++ b/node_modules/@scure/bip39/esm/wordlists/czech.js.map @@ -0,0 +1 @@ +{"version":3,"file":"czech.js","sourceRoot":"","sources":["../../src/wordlists/czech.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,QAAQ,GAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA+/D7B,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip39/esm/wordlists/english.js b/node_modules/@scure/bip39/esm/wordlists/english.js new file mode 100644 index 0000000..bb8972e --- /dev/null +++ b/node_modules/@scure/bip39/esm/wordlists/english.js @@ -0,0 +1,2049 @@ +export const wordlist = `abandon +ability +able +about +above +absent +absorb +abstract +absurd +abuse +access +accident +account +accuse +achieve +acid +acoustic +acquire +across +act +action +actor +actress +actual +adapt +add +addict +address +adjust +admit +adult +advance +advice +aerobic +affair +afford +afraid +again +age +agent +agree +ahead +aim +air +airport +aisle +alarm +album +alcohol +alert +alien +all +alley +allow +almost +alone +alpha +already +also +alter +always +amateur +amazing +among +amount +amused +analyst +anchor +ancient +anger +angle +angry +animal +ankle +announce +annual +another +answer +antenna +antique +anxiety +any +apart +apology +appear +apple +approve +april +arch +arctic +area +arena +argue +arm +armed +armor +army +around +arrange +arrest +arrive +arrow +art +artefact +artist +artwork +ask +aspect +assault +asset +assist +assume +asthma +athlete +atom +attack +attend +attitude +attract +auction +audit +august +aunt +author +auto +autumn +average +avocado +avoid +awake +aware +away +awesome +awful +awkward +axis +baby +bachelor +bacon +badge +bag +balance +balcony +ball +bamboo +banana +banner +bar +barely +bargain +barrel +base +basic +basket +battle +beach +bean +beauty +because +become +beef +before +begin +behave +behind +believe +below +belt +bench +benefit +best +betray +better +between +beyond +bicycle +bid +bike +bind +biology +bird +birth +bitter +black +blade +blame +blanket +blast +bleak +bless +blind +blood +blossom +blouse +blue +blur +blush +board +boat +body +boil +bomb +bone +bonus +book +boost +border +boring +borrow +boss +bottom +bounce +box +boy +bracket +brain +brand +brass +brave +bread +breeze +brick +bridge +brief +bright +bring +brisk +broccoli +broken +bronze +broom +brother +brown +brush +bubble +buddy +budget +buffalo +build +bulb +bulk +bullet +bundle +bunker +burden +burger +burst +bus +business +busy +butter +buyer +buzz +cabbage +cabin +cable +cactus +cage +cake +call +calm +camera +camp +can +canal +cancel +candy +cannon +canoe +canvas +canyon +capable +capital +captain +car +carbon +card +cargo +carpet +carry +cart +case +cash +casino +castle +casual +cat +catalog +catch +category +cattle +caught +cause +caution +cave +ceiling +celery +cement +census +century +cereal +certain +chair +chalk +champion +change +chaos +chapter +charge +chase +chat +cheap +check +cheese +chef +cherry +chest +chicken +chief +child +chimney +choice +choose +chronic +chuckle +chunk +churn +cigar +cinnamon +circle +citizen +city +civil +claim +clap +clarify +claw +clay +clean +clerk +clever +click +client +cliff +climb +clinic +clip +clock +clog +close +cloth +cloud +clown +club +clump +cluster +clutch +coach +coast +coconut +code +coffee +coil +coin +collect +color +column +combine +come +comfort +comic +common +company +concert +conduct +confirm +congress +connect +consider +control +convince +cook +cool +copper +copy +coral +core +corn +correct +cost +cotton +couch +country +couple +course +cousin +cover +coyote +crack +cradle +craft +cram +crane +crash +crater +crawl +crazy +cream +credit +creek +crew +cricket +crime +crisp +critic +crop +cross +crouch +crowd +crucial +cruel +cruise +crumble +crunch +crush +cry +crystal +cube +culture +cup +cupboard +curious +current +curtain +curve +cushion +custom +cute +cycle +dad +damage +damp +dance +danger +daring +dash +daughter +dawn +day +deal +debate +debris +decade +december +decide +decline +decorate +decrease +deer +defense +define +defy +degree +delay +deliver +demand +demise +denial +dentist +deny +depart +depend +deposit +depth +deputy +derive +describe +desert +design +desk +despair +destroy +detail +detect +develop +device +devote +diagram +dial +diamond +diary +dice +diesel +diet +differ +digital +dignity +dilemma +dinner +dinosaur +direct +dirt +disagree +discover +disease +dish +dismiss +disorder +display +distance +divert +divide +divorce +dizzy +doctor +document +dog +doll +dolphin +domain +donate +donkey +donor +door +dose +double +dove +draft +dragon +drama +drastic +draw +dream +dress +drift +drill +drink +drip +drive +drop +drum +dry +duck +dumb +dune +during +dust +dutch +duty +dwarf +dynamic +eager +eagle +early +earn +earth +easily +east +easy +echo +ecology +economy +edge +edit +educate +effort +egg +eight +either +elbow +elder +electric +elegant +element +elephant +elevator +elite +else +embark +embody +embrace +emerge +emotion +employ +empower +empty +enable +enact +end +endless +endorse +enemy +energy +enforce +engage +engine +enhance +enjoy +enlist +enough +enrich +enroll +ensure +enter +entire +entry +envelope +episode +equal +equip +era +erase +erode +erosion +error +erupt +escape +essay +essence +estate +eternal +ethics +evidence +evil +evoke +evolve +exact +example +excess +exchange +excite +exclude +excuse +execute +exercise +exhaust +exhibit +exile +exist +exit +exotic +expand +expect +expire +explain +expose +express +extend +extra +eye +eyebrow +fabric +face +faculty +fade +faint +faith +fall +false +fame +family +famous +fan +fancy +fantasy +farm +fashion +fat +fatal +father +fatigue +fault +favorite +feature +february +federal +fee +feed +feel +female +fence +festival +fetch +fever +few +fiber +fiction +field +figure +file +film +filter +final +find +fine +finger +finish +fire +firm +first +fiscal +fish +fit +fitness +fix +flag +flame +flash +flat +flavor +flee +flight +flip +float +flock +floor +flower +fluid +flush +fly +foam +focus +fog +foil +fold +follow +food +foot +force +forest +forget +fork +fortune +forum +forward +fossil +foster +found +fox +fragile +frame +frequent +fresh +friend +fringe +frog +front +frost +frown +frozen +fruit +fuel +fun +funny +furnace +fury +future +gadget +gain +galaxy +gallery +game +gap +garage +garbage +garden +garlic +garment +gas +gasp +gate +gather +gauge +gaze +general +genius +genre +gentle +genuine +gesture +ghost +giant +gift +giggle +ginger +giraffe +girl +give +glad +glance +glare +glass +glide +glimpse +globe +gloom +glory +glove +glow +glue +goat +goddess +gold +good +goose +gorilla +gospel +gossip +govern +gown +grab +grace +grain +grant +grape +grass +gravity +great +green +grid +grief +grit +grocery +group +grow +grunt +guard +guess +guide +guilt +guitar +gun +gym +habit +hair +half +hammer +hamster +hand +happy +harbor +hard +harsh +harvest +hat +have +hawk +hazard +head +health +heart +heavy +hedgehog +height +hello +helmet +help +hen +hero +hidden +high +hill +hint +hip +hire +history +hobby +hockey +hold +hole +holiday +hollow +home +honey +hood +hope +horn +horror +horse +hospital +host +hotel +hour +hover +hub +huge +human +humble +humor +hundred +hungry +hunt +hurdle +hurry +hurt +husband +hybrid +ice +icon +idea +identify +idle +ignore +ill +illegal +illness +image +imitate +immense +immune +impact +impose +improve +impulse +inch +include +income +increase +index +indicate +indoor +industry +infant +inflict +inform +inhale +inherit +initial +inject +injury +inmate +inner +innocent +input +inquiry +insane +insect +inside +inspire +install +intact +interest +into +invest +invite +involve +iron +island +isolate +issue +item +ivory +jacket +jaguar +jar +jazz +jealous +jeans +jelly +jewel +job +join +joke +journey +joy +judge +juice +jump +jungle +junior +junk +just +kangaroo +keen +keep +ketchup +key +kick +kid +kidney +kind +kingdom +kiss +kit +kitchen +kite +kitten +kiwi +knee +knife +knock +know +lab +label +labor +ladder +lady +lake +lamp +language +laptop +large +later +latin +laugh +laundry +lava +law +lawn +lawsuit +layer +lazy +leader +leaf +learn +leave +lecture +left +leg +legal +legend +leisure +lemon +lend +length +lens +leopard +lesson +letter +level +liar +liberty +library +license +life +lift +light +like +limb +limit +link +lion +liquid +list +little +live +lizard +load +loan +lobster +local +lock +logic +lonely +long +loop +lottery +loud +lounge +love +loyal +lucky +luggage +lumber +lunar +lunch +luxury +lyrics +machine +mad +magic +magnet +maid +mail +main +major +make +mammal +man +manage +mandate +mango +mansion +manual +maple +marble +march +margin +marine +market +marriage +mask +mass +master +match +material +math +matrix +matter +maximum +maze +meadow +mean +measure +meat +mechanic +medal +media +melody +melt +member +memory +mention +menu +mercy +merge +merit +merry +mesh +message +metal +method +middle +midnight +milk +million +mimic +mind +minimum +minor +minute +miracle +mirror +misery +miss +mistake +mix +mixed +mixture +mobile +model +modify +mom +moment +monitor +monkey +monster +month +moon +moral +more +morning +mosquito +mother +motion +motor +mountain +mouse +move +movie +much +muffin +mule +multiply +muscle +museum +mushroom +music +must +mutual +myself +mystery +myth +naive +name +napkin +narrow +nasty +nation +nature +near +neck +need +negative +neglect +neither +nephew +nerve +nest +net +network +neutral +never +news +next +nice +night +noble +noise +nominee +noodle +normal +north +nose +notable +note +nothing +notice +novel +now +nuclear +number +nurse +nut +oak +obey +object +oblige +obscure +observe +obtain +obvious +occur +ocean +october +odor +off +offer +office +often +oil +okay +old +olive +olympic +omit +once +one +onion +online +only +open +opera +opinion +oppose +option +orange +orbit +orchard +order +ordinary +organ +orient +original +orphan +ostrich +other +outdoor +outer +output +outside +oval +oven +over +own +owner +oxygen +oyster +ozone +pact +paddle +page +pair +palace +palm +panda +panel +panic +panther +paper +parade +parent +park +parrot +party +pass +patch +path +patient +patrol +pattern +pause +pave +payment +peace +peanut +pear +peasant +pelican +pen +penalty +pencil +people +pepper +perfect +permit +person +pet +phone +photo +phrase +physical +piano +picnic +picture +piece +pig +pigeon +pill +pilot +pink +pioneer +pipe +pistol +pitch +pizza +place +planet +plastic +plate +play +please +pledge +pluck +plug +plunge +poem +poet +point +polar +pole +police +pond +pony +pool +popular +portion +position +possible +post +potato +pottery +poverty +powder +power +practice +praise +predict +prefer +prepare +present +pretty +prevent +price +pride +primary +print +priority +prison +private +prize +problem +process +produce +profit +program +project +promote +proof +property +prosper +protect +proud +provide +public +pudding +pull +pulp +pulse +pumpkin +punch +pupil +puppy +purchase +purity +purpose +purse +push +put +puzzle +pyramid +quality +quantum +quarter +question +quick +quit +quiz +quote +rabbit +raccoon +race +rack +radar +radio +rail +rain +raise +rally +ramp +ranch +random +range +rapid +rare +rate +rather +raven +raw +razor +ready +real +reason +rebel +rebuild +recall +receive +recipe +record +recycle +reduce +reflect +reform +refuse +region +regret +regular +reject +relax +release +relief +rely +remain +remember +remind +remove +render +renew +rent +reopen +repair +repeat +replace +report +require +rescue +resemble +resist +resource +response +result +retire +retreat +return +reunion +reveal +review +reward +rhythm +rib +ribbon +rice +rich +ride +ridge +rifle +right +rigid +ring +riot +ripple +risk +ritual +rival +river +road +roast +robot +robust +rocket +romance +roof +rookie +room +rose +rotate +rough +round +route +royal +rubber +rude +rug +rule +run +runway +rural +sad +saddle +sadness +safe +sail +salad +salmon +salon +salt +salute +same +sample +sand +satisfy +satoshi +sauce +sausage +save +say +scale +scan +scare +scatter +scene +scheme +school +science +scissors +scorpion +scout +scrap +screen +script +scrub +sea +search +season +seat +second +secret +section +security +seed +seek +segment +select +sell +seminar +senior +sense +sentence +series +service +session +settle +setup +seven +shadow +shaft +shallow +share +shed +shell +sheriff +shield +shift +shine +ship +shiver +shock +shoe +shoot +shop +short +shoulder +shove +shrimp +shrug +shuffle +shy +sibling +sick +side +siege +sight +sign +silent +silk +silly +silver +similar +simple +since +sing +siren +sister +situate +six +size +skate +sketch +ski +skill +skin +skirt +skull +slab +slam +sleep +slender +slice +slide +slight +slim +slogan +slot +slow +slush +small +smart +smile +smoke +smooth +snack +snake +snap +sniff +snow +soap +soccer +social +sock +soda +soft +solar +soldier +solid +solution +solve +someone +song +soon +sorry +sort +soul +sound +soup +source +south +space +spare +spatial +spawn +speak +special +speed +spell +spend +sphere +spice +spider +spike +spin +spirit +split +spoil +sponsor +spoon +sport +spot +spray +spread +spring +spy +square +squeeze +squirrel +stable +stadium +staff +stage +stairs +stamp +stand +start +state +stay +steak +steel +stem +step +stereo +stick +still +sting +stock +stomach +stone +stool +story +stove +strategy +street +strike +strong +struggle +student +stuff +stumble +style +subject +submit +subway +success +such +sudden +suffer +sugar +suggest +suit +summer +sun +sunny +sunset +super +supply +supreme +sure +surface +surge +surprise +surround +survey +suspect +sustain +swallow +swamp +swap +swarm +swear +sweet +swift +swim +swing +switch +sword +symbol +symptom +syrup +system +table +tackle +tag +tail +talent +talk +tank +tape +target +task +taste +tattoo +taxi +teach +team +tell +ten +tenant +tennis +tent +term +test +text +thank +that +theme +then +theory +there +they +thing +this +thought +three +thrive +throw +thumb +thunder +ticket +tide +tiger +tilt +timber +time +tiny +tip +tired +tissue +title +toast +tobacco +today +toddler +toe +together +toilet +token +tomato +tomorrow +tone +tongue +tonight +tool +tooth +top +topic +topple +torch +tornado +tortoise +toss +total +tourist +toward +tower +town +toy +track +trade +traffic +tragic +train +transfer +trap +trash +travel +tray +treat +tree +trend +trial +tribe +trick +trigger +trim +trip +trophy +trouble +truck +true +truly +trumpet +trust +truth +try +tube +tuition +tumble +tuna +tunnel +turkey +turn +turtle +twelve +twenty +twice +twin +twist +two +type +typical +ugly +umbrella +unable +unaware +uncle +uncover +under +undo +unfair +unfold +unhappy +uniform +unique +unit +universe +unknown +unlock +until +unusual +unveil +update +upgrade +uphold +upon +upper +upset +urban +urge +usage +use +used +useful +useless +usual +utility +vacant +vacuum +vague +valid +valley +valve +van +vanish +vapor +various +vast +vault +vehicle +velvet +vendor +venture +venue +verb +verify +version +very +vessel +veteran +viable +vibrant +vicious +victory +video +view +village +vintage +violin +virtual +virus +visa +visit +visual +vital +vivid +vocal +voice +void +volcano +volume +vote +voyage +wage +wagon +wait +walk +wall +walnut +want +warfare +warm +warrior +wash +wasp +waste +water +wave +way +wealth +weapon +wear +weasel +weather +web +wedding +weekend +weird +welcome +west +wet +whale +what +wheat +wheel +when +where +whip +whisper +wide +width +wife +wild +will +win +window +wine +wing +wink +winner +winter +wire +wisdom +wise +wish +witness +wolf +woman +wonder +wood +wool +word +work +world +worry +worth +wrap +wreck +wrestle +wrist +write +wrong +yard +year +yellow +you +young +youth +zebra +zero +zone +zoo`.split('\n'); +//# sourceMappingURL=english.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/esm/wordlists/english.js.map b/node_modules/@scure/bip39/esm/wordlists/english.js.map new file mode 100644 index 0000000..927739d --- /dev/null +++ b/node_modules/@scure/bip39/esm/wordlists/english.js.map @@ -0,0 +1 @@ +{"version":3,"file":"english.js","sourceRoot":"","sources":["../../src/wordlists/english.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,QAAQ,GAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA+/D9B,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip39/esm/wordlists/french.js b/node_modules/@scure/bip39/esm/wordlists/french.js new file mode 100644 index 0000000..b599b65 --- /dev/null +++ b/node_modules/@scure/bip39/esm/wordlists/french.js @@ -0,0 +1,2049 @@ +export const wordlist = `abaisser +abandon +abdiquer +abeille +abolir +aborder +aboutir +aboyer +abrasif +abreuver +abriter +abroger +abrupt +absence +absolu +absurde +abusif +abyssal +académie +acajou +acarien +accabler +accepter +acclamer +accolade +accroche +accuser +acerbe +achat +acheter +aciduler +acier +acompte +acquérir +acronyme +acteur +actif +actuel +adepte +adéquat +adhésif +adjectif +adjuger +admettre +admirer +adopter +adorer +adoucir +adresse +adroit +adulte +adverbe +aérer +aéronef +affaire +affecter +affiche +affreux +affubler +agacer +agencer +agile +agiter +agrafer +agréable +agrume +aider +aiguille +ailier +aimable +aisance +ajouter +ajuster +alarmer +alchimie +alerte +algèbre +algue +aliéner +aliment +alléger +alliage +allouer +allumer +alourdir +alpaga +altesse +alvéole +amateur +ambigu +ambre +aménager +amertume +amidon +amiral +amorcer +amour +amovible +amphibie +ampleur +amusant +analyse +anaphore +anarchie +anatomie +ancien +anéantir +angle +angoisse +anguleux +animal +annexer +annonce +annuel +anodin +anomalie +anonyme +anormal +antenne +antidote +anxieux +apaiser +apéritif +aplanir +apologie +appareil +appeler +apporter +appuyer +aquarium +aqueduc +arbitre +arbuste +ardeur +ardoise +argent +arlequin +armature +armement +armoire +armure +arpenter +arracher +arriver +arroser +arsenic +artériel +article +aspect +asphalte +aspirer +assaut +asservir +assiette +associer +assurer +asticot +astre +astuce +atelier +atome +atrium +atroce +attaque +attentif +attirer +attraper +aubaine +auberge +audace +audible +augurer +aurore +automne +autruche +avaler +avancer +avarice +avenir +averse +aveugle +aviateur +avide +avion +aviser +avoine +avouer +avril +axial +axiome +badge +bafouer +bagage +baguette +baignade +balancer +balcon +baleine +balisage +bambin +bancaire +bandage +banlieue +bannière +banquier +barbier +baril +baron +barque +barrage +bassin +bastion +bataille +bateau +batterie +baudrier +bavarder +belette +bélier +belote +bénéfice +berceau +berger +berline +bermuda +besace +besogne +bétail +beurre +biberon +bicycle +bidule +bijou +bilan +bilingue +billard +binaire +biologie +biopsie +biotype +biscuit +bison +bistouri +bitume +bizarre +blafard +blague +blanchir +blessant +blinder +blond +bloquer +blouson +bobard +bobine +boire +boiser +bolide +bonbon +bondir +bonheur +bonifier +bonus +bordure +borne +botte +boucle +boueux +bougie +boulon +bouquin +bourse +boussole +boutique +boxeur +branche +brasier +brave +brebis +brèche +breuvage +bricoler +brigade +brillant +brioche +brique +brochure +broder +bronzer +brousse +broyeur +brume +brusque +brutal +bruyant +buffle +buisson +bulletin +bureau +burin +bustier +butiner +butoir +buvable +buvette +cabanon +cabine +cachette +cadeau +cadre +caféine +caillou +caisson +calculer +calepin +calibre +calmer +calomnie +calvaire +camarade +caméra +camion +campagne +canal +caneton +canon +cantine +canular +capable +caporal +caprice +capsule +capter +capuche +carabine +carbone +caresser +caribou +carnage +carotte +carreau +carton +cascade +casier +casque +cassure +causer +caution +cavalier +caverne +caviar +cédille +ceinture +céleste +cellule +cendrier +censurer +central +cercle +cérébral +cerise +cerner +cerveau +cesser +chagrin +chaise +chaleur +chambre +chance +chapitre +charbon +chasseur +chaton +chausson +chavirer +chemise +chenille +chéquier +chercher +cheval +chien +chiffre +chignon +chimère +chiot +chlorure +chocolat +choisir +chose +chouette +chrome +chute +cigare +cigogne +cimenter +cinéma +cintrer +circuler +cirer +cirque +citerne +citoyen +citron +civil +clairon +clameur +claquer +classe +clavier +client +cligner +climat +clivage +cloche +clonage +cloporte +cobalt +cobra +cocasse +cocotier +coder +codifier +coffre +cogner +cohésion +coiffer +coincer +colère +colibri +colline +colmater +colonel +combat +comédie +commande +compact +concert +conduire +confier +congeler +connoter +consonne +contact +convexe +copain +copie +corail +corbeau +cordage +corniche +corpus +correct +cortège +cosmique +costume +coton +coude +coupure +courage +couteau +couvrir +coyote +crabe +crainte +cravate +crayon +créature +créditer +crémeux +creuser +crevette +cribler +crier +cristal +critère +croire +croquer +crotale +crucial +cruel +crypter +cubique +cueillir +cuillère +cuisine +cuivre +culminer +cultiver +cumuler +cupide +curatif +curseur +cyanure +cycle +cylindre +cynique +daigner +damier +danger +danseur +dauphin +débattre +débiter +déborder +débrider +débutant +décaler +décembre +déchirer +décider +déclarer +décorer +décrire +décupler +dédale +déductif +déesse +défensif +défiler +défrayer +dégager +dégivrer +déglutir +dégrafer +déjeuner +délice +déloger +demander +demeurer +démolir +dénicher +dénouer +dentelle +dénuder +départ +dépenser +déphaser +déplacer +déposer +déranger +dérober +désastre +descente +désert +désigner +désobéir +dessiner +destrier +détacher +détester +détourer +détresse +devancer +devenir +deviner +devoir +diable +dialogue +diamant +dicter +différer +digérer +digital +digne +diluer +dimanche +diminuer +dioxyde +directif +diriger +discuter +disposer +dissiper +distance +divertir +diviser +docile +docteur +dogme +doigt +domaine +domicile +dompter +donateur +donjon +donner +dopamine +dortoir +dorure +dosage +doseur +dossier +dotation +douanier +double +douceur +douter +doyen +dragon +draper +dresser +dribbler +droiture +duperie +duplexe +durable +durcir +dynastie +éblouir +écarter +écharpe +échelle +éclairer +éclipse +éclore +écluse +école +économie +écorce +écouter +écraser +écrémer +écrivain +écrou +écume +écureuil +édifier +éduquer +effacer +effectif +effigie +effort +effrayer +effusion +égaliser +égarer +éjecter +élaborer +élargir +électron +élégant +éléphant +élève +éligible +élitisme +éloge +élucider +éluder +emballer +embellir +embryon +émeraude +émission +emmener +émotion +émouvoir +empereur +employer +emporter +emprise +émulsion +encadrer +enchère +enclave +encoche +endiguer +endosser +endroit +enduire +énergie +enfance +enfermer +enfouir +engager +engin +englober +énigme +enjamber +enjeu +enlever +ennemi +ennuyeux +enrichir +enrobage +enseigne +entasser +entendre +entier +entourer +entraver +énumérer +envahir +enviable +envoyer +enzyme +éolien +épaissir +épargne +épatant +épaule +épicerie +épidémie +épier +épilogue +épine +épisode +épitaphe +époque +épreuve +éprouver +épuisant +équerre +équipe +ériger +érosion +erreur +éruption +escalier +espadon +espèce +espiègle +espoir +esprit +esquiver +essayer +essence +essieu +essorer +estime +estomac +estrade +étagère +étaler +étanche +étatique +éteindre +étendoir +éternel +éthanol +éthique +ethnie +étirer +étoffer +étoile +étonnant +étourdir +étrange +étroit +étude +euphorie +évaluer +évasion +éventail +évidence +éviter +évolutif +évoquer +exact +exagérer +exaucer +exceller +excitant +exclusif +excuse +exécuter +exemple +exercer +exhaler +exhorter +exigence +exiler +exister +exotique +expédier +explorer +exposer +exprimer +exquis +extensif +extraire +exulter +fable +fabuleux +facette +facile +facture +faiblir +falaise +fameux +famille +farceur +farfelu +farine +farouche +fasciner +fatal +fatigue +faucon +fautif +faveur +favori +fébrile +féconder +fédérer +félin +femme +fémur +fendoir +féodal +fermer +féroce +ferveur +festival +feuille +feutre +février +fiasco +ficeler +fictif +fidèle +figure +filature +filetage +filière +filleul +filmer +filou +filtrer +financer +finir +fiole +firme +fissure +fixer +flairer +flamme +flasque +flatteur +fléau +flèche +fleur +flexion +flocon +flore +fluctuer +fluide +fluvial +folie +fonderie +fongible +fontaine +forcer +forgeron +formuler +fortune +fossile +foudre +fougère +fouiller +foulure +fourmi +fragile +fraise +franchir +frapper +frayeur +frégate +freiner +frelon +frémir +frénésie +frère +friable +friction +frisson +frivole +froid +fromage +frontal +frotter +fruit +fugitif +fuite +fureur +furieux +furtif +fusion +futur +gagner +galaxie +galerie +gambader +garantir +gardien +garnir +garrigue +gazelle +gazon +géant +gélatine +gélule +gendarme +général +génie +genou +gentil +géologie +géomètre +géranium +germe +gestuel +geyser +gibier +gicler +girafe +givre +glace +glaive +glisser +globe +gloire +glorieux +golfeur +gomme +gonfler +gorge +gorille +goudron +gouffre +goulot +goupille +gourmand +goutte +graduel +graffiti +graine +grand +grappin +gratuit +gravir +grenat +griffure +griller +grimper +grogner +gronder +grotte +groupe +gruger +grutier +gruyère +guépard +guerrier +guide +guimauve +guitare +gustatif +gymnaste +gyrostat +habitude +hachoir +halte +hameau +hangar +hanneton +haricot +harmonie +harpon +hasard +hélium +hématome +herbe +hérisson +hermine +héron +hésiter +heureux +hiberner +hibou +hilarant +histoire +hiver +homard +hommage +homogène +honneur +honorer +honteux +horde +horizon +horloge +hormone +horrible +houleux +housse +hublot +huileux +humain +humble +humide +humour +hurler +hydromel +hygiène +hymne +hypnose +idylle +ignorer +iguane +illicite +illusion +image +imbiber +imiter +immense +immobile +immuable +impact +impérial +implorer +imposer +imprimer +imputer +incarner +incendie +incident +incliner +incolore +indexer +indice +inductif +inédit +ineptie +inexact +infini +infliger +informer +infusion +ingérer +inhaler +inhiber +injecter +injure +innocent +inoculer +inonder +inscrire +insecte +insigne +insolite +inspirer +instinct +insulter +intact +intense +intime +intrigue +intuitif +inutile +invasion +inventer +inviter +invoquer +ironique +irradier +irréel +irriter +isoler +ivoire +ivresse +jaguar +jaillir +jambe +janvier +jardin +jauger +jaune +javelot +jetable +jeton +jeudi +jeunesse +joindre +joncher +jongler +joueur +jouissif +journal +jovial +joyau +joyeux +jubiler +jugement +junior +jupon +juriste +justice +juteux +juvénile +kayak +kimono +kiosque +label +labial +labourer +lacérer +lactose +lagune +laine +laisser +laitier +lambeau +lamelle +lampe +lanceur +langage +lanterne +lapin +largeur +larme +laurier +lavabo +lavoir +lecture +légal +léger +légume +lessive +lettre +levier +lexique +lézard +liasse +libérer +libre +licence +licorne +liège +lièvre +ligature +ligoter +ligue +limer +limite +limonade +limpide +linéaire +lingot +lionceau +liquide +lisière +lister +lithium +litige +littoral +livreur +logique +lointain +loisir +lombric +loterie +louer +lourd +loutre +louve +loyal +lubie +lucide +lucratif +lueur +lugubre +luisant +lumière +lunaire +lundi +luron +lutter +luxueux +machine +magasin +magenta +magique +maigre +maillon +maintien +mairie +maison +majorer +malaxer +maléfice +malheur +malice +mallette +mammouth +mandater +maniable +manquant +manteau +manuel +marathon +marbre +marchand +mardi +maritime +marqueur +marron +marteler +mascotte +massif +matériel +matière +matraque +maudire +maussade +mauve +maximal +méchant +méconnu +médaille +médecin +méditer +méduse +meilleur +mélange +mélodie +membre +mémoire +menacer +mener +menhir +mensonge +mentor +mercredi +mérite +merle +messager +mesure +métal +météore +méthode +métier +meuble +miauler +microbe +miette +mignon +migrer +milieu +million +mimique +mince +minéral +minimal +minorer +minute +miracle +miroiter +missile +mixte +mobile +moderne +moelleux +mondial +moniteur +monnaie +monotone +monstre +montagne +monument +moqueur +morceau +morsure +mortier +moteur +motif +mouche +moufle +moulin +mousson +mouton +mouvant +multiple +munition +muraille +murène +murmure +muscle +muséum +musicien +mutation +muter +mutuel +myriade +myrtille +mystère +mythique +nageur +nappe +narquois +narrer +natation +nation +nature +naufrage +nautique +navire +nébuleux +nectar +néfaste +négation +négliger +négocier +neige +nerveux +nettoyer +neurone +neutron +neveu +niche +nickel +nitrate +niveau +noble +nocif +nocturne +noirceur +noisette +nomade +nombreux +nommer +normatif +notable +notifier +notoire +nourrir +nouveau +novateur +novembre +novice +nuage +nuancer +nuire +nuisible +numéro +nuptial +nuque +nutritif +obéir +objectif +obliger +obscur +observer +obstacle +obtenir +obturer +occasion +occuper +océan +octobre +octroyer +octupler +oculaire +odeur +odorant +offenser +officier +offrir +ogive +oiseau +oisillon +olfactif +olivier +ombrage +omettre +onctueux +onduler +onéreux +onirique +opale +opaque +opérer +opinion +opportun +opprimer +opter +optique +orageux +orange +orbite +ordonner +oreille +organe +orgueil +orifice +ornement +orque +ortie +osciller +osmose +ossature +otarie +ouragan +ourson +outil +outrager +ouvrage +ovation +oxyde +oxygène +ozone +paisible +palace +palmarès +palourde +palper +panache +panda +pangolin +paniquer +panneau +panorama +pantalon +papaye +papier +papoter +papyrus +paradoxe +parcelle +paresse +parfumer +parler +parole +parrain +parsemer +partager +parure +parvenir +passion +pastèque +paternel +patience +patron +pavillon +pavoiser +payer +paysage +peigne +peintre +pelage +pélican +pelle +pelouse +peluche +pendule +pénétrer +pénible +pensif +pénurie +pépite +péplum +perdrix +perforer +période +permuter +perplexe +persil +perte +peser +pétale +petit +pétrir +peuple +pharaon +phobie +phoque +photon +phrase +physique +piano +pictural +pièce +pierre +pieuvre +pilote +pinceau +pipette +piquer +pirogue +piscine +piston +pivoter +pixel +pizza +placard +plafond +plaisir +planer +plaque +plastron +plateau +pleurer +plexus +pliage +plomb +plonger +pluie +plumage +pochette +poésie +poète +pointe +poirier +poisson +poivre +polaire +policier +pollen +polygone +pommade +pompier +ponctuel +pondérer +poney +portique +position +posséder +posture +potager +poteau +potion +pouce +poulain +poumon +pourpre +poussin +pouvoir +prairie +pratique +précieux +prédire +préfixe +prélude +prénom +présence +prétexte +prévoir +primitif +prince +prison +priver +problème +procéder +prodige +profond +progrès +proie +projeter +prologue +promener +propre +prospère +protéger +prouesse +proverbe +prudence +pruneau +psychose +public +puceron +puiser +pulpe +pulsar +punaise +punitif +pupitre +purifier +puzzle +pyramide +quasar +querelle +question +quiétude +quitter +quotient +racine +raconter +radieux +ragondin +raideur +raisin +ralentir +rallonge +ramasser +rapide +rasage +ratisser +ravager +ravin +rayonner +réactif +réagir +réaliser +réanimer +recevoir +réciter +réclamer +récolter +recruter +reculer +recycler +rédiger +redouter +refaire +réflexe +réformer +refrain +refuge +régalien +région +réglage +régulier +réitérer +rejeter +rejouer +relatif +relever +relief +remarque +remède +remise +remonter +remplir +remuer +renard +renfort +renifler +renoncer +rentrer +renvoi +replier +reporter +reprise +reptile +requin +réserve +résineux +résoudre +respect +rester +résultat +rétablir +retenir +réticule +retomber +retracer +réunion +réussir +revanche +revivre +révolte +révulsif +richesse +rideau +rieur +rigide +rigoler +rincer +riposter +risible +risque +rituel +rival +rivière +rocheux +romance +rompre +ronce +rondin +roseau +rosier +rotatif +rotor +rotule +rouge +rouille +rouleau +routine +royaume +ruban +rubis +ruche +ruelle +rugueux +ruiner +ruisseau +ruser +rustique +rythme +sabler +saboter +sabre +sacoche +safari +sagesse +saisir +salade +salive +salon +saluer +samedi +sanction +sanglier +sarcasme +sardine +saturer +saugrenu +saumon +sauter +sauvage +savant +savonner +scalpel +scandale +scélérat +scénario +sceptre +schéma +science +scinder +score +scrutin +sculpter +séance +sécable +sécher +secouer +sécréter +sédatif +séduire +seigneur +séjour +sélectif +semaine +sembler +semence +séminal +sénateur +sensible +sentence +séparer +séquence +serein +sergent +sérieux +serrure +sérum +service +sésame +sévir +sevrage +sextuple +sidéral +siècle +siéger +siffler +sigle +signal +silence +silicium +simple +sincère +sinistre +siphon +sirop +sismique +situer +skier +social +socle +sodium +soigneux +soldat +soleil +solitude +soluble +sombre +sommeil +somnoler +sonde +songeur +sonnette +sonore +sorcier +sortir +sosie +sottise +soucieux +soudure +souffle +soulever +soupape +source +soutirer +souvenir +spacieux +spatial +spécial +sphère +spiral +stable +station +sternum +stimulus +stipuler +strict +studieux +stupeur +styliste +sublime +substrat +subtil +subvenir +succès +sucre +suffixe +suggérer +suiveur +sulfate +superbe +supplier +surface +suricate +surmener +surprise +sursaut +survie +suspect +syllabe +symbole +symétrie +synapse +syntaxe +système +tabac +tablier +tactile +tailler +talent +talisman +talonner +tambour +tamiser +tangible +tapis +taquiner +tarder +tarif +tartine +tasse +tatami +tatouage +taupe +taureau +taxer +témoin +temporel +tenaille +tendre +teneur +tenir +tension +terminer +terne +terrible +tétine +texte +thème +théorie +thérapie +thorax +tibia +tiède +timide +tirelire +tiroir +tissu +titane +titre +tituber +toboggan +tolérant +tomate +tonique +tonneau +toponyme +torche +tordre +tornade +torpille +torrent +torse +tortue +totem +toucher +tournage +tousser +toxine +traction +trafic +tragique +trahir +train +trancher +travail +trèfle +tremper +trésor +treuil +triage +tribunal +tricoter +trilogie +triomphe +tripler +triturer +trivial +trombone +tronc +tropical +troupeau +tuile +tulipe +tumulte +tunnel +turbine +tuteur +tutoyer +tuyau +tympan +typhon +typique +tyran +ubuesque +ultime +ultrason +unanime +unifier +union +unique +unitaire +univers +uranium +urbain +urticant +usage +usine +usuel +usure +utile +utopie +vacarme +vaccin +vagabond +vague +vaillant +vaincre +vaisseau +valable +valise +vallon +valve +vampire +vanille +vapeur +varier +vaseux +vassal +vaste +vecteur +vedette +végétal +véhicule +veinard +véloce +vendredi +vénérer +venger +venimeux +ventouse +verdure +vérin +vernir +verrou +verser +vertu +veston +vétéran +vétuste +vexant +vexer +viaduc +viande +victoire +vidange +vidéo +vignette +vigueur +vilain +village +vinaigre +violon +vipère +virement +virtuose +virus +visage +viseur +vision +visqueux +visuel +vital +vitesse +viticole +vitrine +vivace +vivipare +vocation +voguer +voile +voisin +voiture +volaille +volcan +voltiger +volume +vorace +vortex +voter +vouloir +voyage +voyelle +wagon +xénon +yacht +zèbre +zénith +zeste +zoologie`.split('\n'); +//# sourceMappingURL=french.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/esm/wordlists/french.js.map b/node_modules/@scure/bip39/esm/wordlists/french.js.map new file mode 100644 index 0000000..9d2bc2e --- /dev/null +++ b/node_modules/@scure/bip39/esm/wordlists/french.js.map @@ -0,0 +1 @@ +{"version":3,"file":"french.js","sourceRoot":"","sources":["../../src/wordlists/french.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,QAAQ,GAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SA+/DzB,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip39/esm/wordlists/italian.js b/node_modules/@scure/bip39/esm/wordlists/italian.js new file mode 100644 index 0000000..5fd1b4e --- /dev/null +++ b/node_modules/@scure/bip39/esm/wordlists/italian.js @@ -0,0 +1,2049 @@ +export const wordlist = `abaco +abbaglio +abbinato +abete +abisso +abolire +abrasivo +abrogato +accadere +accenno +accusato +acetone +achille +acido +acqua +acre +acrilico +acrobata +acuto +adagio +addebito +addome +adeguato +aderire +adipe +adottare +adulare +affabile +affetto +affisso +affranto +aforisma +afoso +africano +agave +agente +agevole +aggancio +agire +agitare +agonismo +agricolo +agrumeto +aguzzo +alabarda +alato +albatro +alberato +albo +albume +alce +alcolico +alettone +alfa +algebra +aliante +alibi +alimento +allagato +allegro +allievo +allodola +allusivo +almeno +alogeno +alpaca +alpestre +altalena +alterno +alticcio +altrove +alunno +alveolo +alzare +amalgama +amanita +amarena +ambito +ambrato +ameba +america +ametista +amico +ammasso +ammenda +ammirare +ammonito +amore +ampio +ampliare +amuleto +anacardo +anagrafe +analista +anarchia +anatra +anca +ancella +ancora +andare +andrea +anello +angelo +angolare +angusto +anima +annegare +annidato +anno +annuncio +anonimo +anticipo +anzi +apatico +apertura +apode +apparire +appetito +appoggio +approdo +appunto +aprile +arabica +arachide +aragosta +araldica +arancio +aratura +arazzo +arbitro +archivio +ardito +arenile +argento +argine +arguto +aria +armonia +arnese +arredato +arringa +arrosto +arsenico +arso +artefice +arzillo +asciutto +ascolto +asepsi +asettico +asfalto +asino +asola +aspirato +aspro +assaggio +asse +assoluto +assurdo +asta +astenuto +astice +astratto +atavico +ateismo +atomico +atono +attesa +attivare +attorno +attrito +attuale +ausilio +austria +autista +autonomo +autunno +avanzato +avere +avvenire +avviso +avvolgere +azione +azoto +azzimo +azzurro +babele +baccano +bacino +baco +badessa +badilata +bagnato +baita +balcone +baldo +balena +ballata +balzano +bambino +bandire +baraonda +barbaro +barca +baritono +barlume +barocco +basilico +basso +batosta +battuto +baule +bava +bavosa +becco +beffa +belgio +belva +benda +benevole +benigno +benzina +bere +berlina +beta +bibita +bici +bidone +bifido +biga +bilancia +bimbo +binocolo +biologo +bipede +bipolare +birbante +birra +biscotto +bisesto +bisnonno +bisonte +bisturi +bizzarro +blando +blatta +bollito +bonifico +bordo +bosco +botanico +bottino +bozzolo +braccio +bradipo +brama +branca +bravura +bretella +brevetto +brezza +briglia +brillante +brindare +broccolo +brodo +bronzina +brullo +bruno +bubbone +buca +budino +buffone +buio +bulbo +buono +burlone +burrasca +bussola +busta +cadetto +caduco +calamaro +calcolo +calesse +calibro +calmo +caloria +cambusa +camerata +camicia +cammino +camola +campale +canapa +candela +cane +canino +canotto +cantina +capace +capello +capitolo +capogiro +cappero +capra +capsula +carapace +carcassa +cardo +carisma +carovana +carretto +cartolina +casaccio +cascata +caserma +caso +cassone +castello +casuale +catasta +catena +catrame +cauto +cavillo +cedibile +cedrata +cefalo +celebre +cellulare +cena +cenone +centesimo +ceramica +cercare +certo +cerume +cervello +cesoia +cespo +ceto +chela +chiaro +chicca +chiedere +chimera +china +chirurgo +chitarra +ciao +ciclismo +cifrare +cigno +cilindro +ciottolo +circa +cirrosi +citrico +cittadino +ciuffo +civetta +civile +classico +clinica +cloro +cocco +codardo +codice +coerente +cognome +collare +colmato +colore +colposo +coltivato +colza +coma +cometa +commando +comodo +computer +comune +conciso +condurre +conferma +congelare +coniuge +connesso +conoscere +consumo +continuo +convegno +coperto +copione +coppia +copricapo +corazza +cordata +coricato +cornice +corolla +corpo +corredo +corsia +cortese +cosmico +costante +cottura +covato +cratere +cravatta +creato +credere +cremoso +crescita +creta +criceto +crinale +crisi +critico +croce +cronaca +crostata +cruciale +crusca +cucire +cuculo +cugino +cullato +cupola +curatore +cursore +curvo +cuscino +custode +dado +daino +dalmata +damerino +daniela +dannoso +danzare +datato +davanti +davvero +debutto +decennio +deciso +declino +decollo +decreto +dedicato +definito +deforme +degno +delegare +delfino +delirio +delta +demenza +denotato +dentro +deposito +derapata +derivare +deroga +descritto +deserto +desiderio +desumere +detersivo +devoto +diametro +dicembre +diedro +difeso +diffuso +digerire +digitale +diluvio +dinamico +dinnanzi +dipinto +diploma +dipolo +diradare +dire +dirotto +dirupo +disagio +discreto +disfare +disgelo +disposto +distanza +disumano +dito +divano +divelto +dividere +divorato +doblone +docente +doganale +dogma +dolce +domato +domenica +dominare +dondolo +dono +dormire +dote +dottore +dovuto +dozzina +drago +druido +dubbio +dubitare +ducale +duna +duomo +duplice +duraturo +ebano +eccesso +ecco +eclissi +economia +edera +edicola +edile +editoria +educare +egemonia +egli +egoismo +egregio +elaborato +elargire +elegante +elencato +eletto +elevare +elfico +elica +elmo +elsa +eluso +emanato +emblema +emesso +emiro +emotivo +emozione +empirico +emulo +endemico +enduro +energia +enfasi +enoteca +entrare +enzima +epatite +epilogo +episodio +epocale +eppure +equatore +erario +erba +erboso +erede +eremita +erigere +ermetico +eroe +erosivo +errante +esagono +esame +esanime +esaudire +esca +esempio +esercito +esibito +esigente +esistere +esito +esofago +esortato +esoso +espanso +espresso +essenza +esso +esteso +estimare +estonia +estroso +esultare +etilico +etnico +etrusco +etto +euclideo +europa +evaso +evidenza +evitato +evoluto +evviva +fabbrica +faccenda +fachiro +falco +famiglia +fanale +fanfara +fango +fantasma +fare +farfalla +farinoso +farmaco +fascia +fastoso +fasullo +faticare +fato +favoloso +febbre +fecola +fede +fegato +felpa +feltro +femmina +fendere +fenomeno +fermento +ferro +fertile +fessura +festivo +fetta +feudo +fiaba +fiducia +fifa +figurato +filo +finanza +finestra +finire +fiore +fiscale +fisico +fiume +flacone +flamenco +flebo +flemma +florido +fluente +fluoro +fobico +focaccia +focoso +foderato +foglio +folata +folclore +folgore +fondente +fonetico +fonia +fontana +forbito +forchetta +foresta +formica +fornaio +foro +fortezza +forzare +fosfato +fosso +fracasso +frana +frassino +fratello +freccetta +frenata +fresco +frigo +frollino +fronde +frugale +frutta +fucilata +fucsia +fuggente +fulmine +fulvo +fumante +fumetto +fumoso +fune +funzione +fuoco +furbo +furgone +furore +fuso +futile +gabbiano +gaffe +galateo +gallina +galoppo +gambero +gamma +garanzia +garbo +garofano +garzone +gasdotto +gasolio +gastrico +gatto +gaudio +gazebo +gazzella +geco +gelatina +gelso +gemello +gemmato +gene +genitore +gennaio +genotipo +gergo +ghepardo +ghiaccio +ghisa +giallo +gilda +ginepro +giocare +gioiello +giorno +giove +girato +girone +gittata +giudizio +giurato +giusto +globulo +glutine +gnomo +gobba +golf +gomito +gommone +gonfio +gonna +governo +gracile +grado +grafico +grammo +grande +grattare +gravoso +grazia +greca +gregge +grifone +grigio +grinza +grotta +gruppo +guadagno +guaio +guanto +guardare +gufo +guidare +ibernato +icona +identico +idillio +idolo +idra +idrico +idrogeno +igiene +ignaro +ignorato +ilare +illeso +illogico +illudere +imballo +imbevuto +imbocco +imbuto +immane +immerso +immolato +impacco +impeto +impiego +importo +impronta +inalare +inarcare +inattivo +incanto +incendio +inchino +incisivo +incluso +incontro +incrocio +incubo +indagine +india +indole +inedito +infatti +infilare +inflitto +ingaggio +ingegno +inglese +ingordo +ingrosso +innesco +inodore +inoltrare +inondato +insano +insetto +insieme +insonnia +insulina +intasato +intero +intonaco +intuito +inumidire +invalido +invece +invito +iperbole +ipnotico +ipotesi +ippica +iride +irlanda +ironico +irrigato +irrorare +isolato +isotopo +isterico +istituto +istrice +italia +iterare +labbro +labirinto +lacca +lacerato +lacrima +lacuna +laddove +lago +lampo +lancetta +lanterna +lardoso +larga +laringe +lastra +latenza +latino +lattuga +lavagna +lavoro +legale +leggero +lembo +lentezza +lenza +leone +lepre +lesivo +lessato +lesto +letterale +leva +levigato +libero +lido +lievito +lilla +limatura +limitare +limpido +lineare +lingua +liquido +lira +lirica +lisca +lite +litigio +livrea +locanda +lode +logica +lombare +londra +longevo +loquace +lorenzo +loto +lotteria +luce +lucidato +lumaca +luminoso +lungo +lupo +luppolo +lusinga +lusso +lutto +macabro +macchina +macero +macinato +madama +magico +maglia +magnete +magro +maiolica +malafede +malgrado +malinteso +malsano +malto +malumore +mana +mancia +mandorla +mangiare +manifesto +mannaro +manovra +mansarda +mantide +manubrio +mappa +maratona +marcire +maretta +marmo +marsupio +maschera +massaia +mastino +materasso +matricola +mattone +maturo +mazurca +meandro +meccanico +mecenate +medesimo +meditare +mega +melassa +melis +melodia +meninge +meno +mensola +mercurio +merenda +merlo +meschino +mese +messere +mestolo +metallo +metodo +mettere +miagolare +mica +micelio +michele +microbo +midollo +miele +migliore +milano +milite +mimosa +minerale +mini +minore +mirino +mirtillo +miscela +missiva +misto +misurare +mitezza +mitigare +mitra +mittente +mnemonico +modello +modifica +modulo +mogano +mogio +mole +molosso +monastero +monco +mondina +monetario +monile +monotono +monsone +montato +monviso +mora +mordere +morsicato +mostro +motivato +motosega +motto +movenza +movimento +mozzo +mucca +mucosa +muffa +mughetto +mugnaio +mulatto +mulinello +multiplo +mummia +munto +muovere +murale +musa +muscolo +musica +mutevole +muto +nababbo +nafta +nanometro +narciso +narice +narrato +nascere +nastrare +naturale +nautica +naviglio +nebulosa +necrosi +negativo +negozio +nemmeno +neofita +neretto +nervo +nessuno +nettuno +neutrale +neve +nevrotico +nicchia +ninfa +nitido +nobile +nocivo +nodo +nome +nomina +nordico +normale +norvegese +nostrano +notare +notizia +notturno +novella +nucleo +nulla +numero +nuovo +nutrire +nuvola +nuziale +oasi +obbedire +obbligo +obelisco +oblio +obolo +obsoleto +occasione +occhio +occidente +occorrere +occultare +ocra +oculato +odierno +odorare +offerta +offrire +offuscato +oggetto +oggi +ognuno +olandese +olfatto +oliato +oliva +ologramma +oltre +omaggio +ombelico +ombra +omega +omissione +ondoso +onere +onice +onnivoro +onorevole +onta +operato +opinione +opposto +oracolo +orafo +ordine +orecchino +orefice +orfano +organico +origine +orizzonte +orma +ormeggio +ornativo +orologio +orrendo +orribile +ortensia +ortica +orzata +orzo +osare +oscurare +osmosi +ospedale +ospite +ossa +ossidare +ostacolo +oste +otite +otre +ottagono +ottimo +ottobre +ovale +ovest +ovino +oviparo +ovocito +ovunque +ovviare +ozio +pacchetto +pace +pacifico +padella +padrone +paese +paga +pagina +palazzina +palesare +pallido +palo +palude +pandoro +pannello +paolo +paonazzo +paprica +parabola +parcella +parere +pargolo +pari +parlato +parola +partire +parvenza +parziale +passivo +pasticca +patacca +patologia +pattume +pavone +peccato +pedalare +pedonale +peggio +peloso +penare +pendice +penisola +pennuto +penombra +pensare +pentola +pepe +pepita +perbene +percorso +perdonato +perforare +pergamena +periodo +permesso +perno +perplesso +persuaso +pertugio +pervaso +pesatore +pesista +peso +pestifero +petalo +pettine +petulante +pezzo +piacere +pianta +piattino +piccino +picozza +piega +pietra +piffero +pigiama +pigolio +pigro +pila +pilifero +pillola +pilota +pimpante +pineta +pinna +pinolo +pioggia +piombo +piramide +piretico +pirite +pirolisi +pitone +pizzico +placebo +planare +plasma +platano +plenario +pochezza +poderoso +podismo +poesia +poggiare +polenta +poligono +pollice +polmonite +polpetta +polso +poltrona +polvere +pomice +pomodoro +ponte +popoloso +porfido +poroso +porpora +porre +portata +posa +positivo +possesso +postulato +potassio +potere +pranzo +prassi +pratica +precluso +predica +prefisso +pregiato +prelievo +premere +prenotare +preparato +presenza +pretesto +prevalso +prima +principe +privato +problema +procura +produrre +profumo +progetto +prolunga +promessa +pronome +proposta +proroga +proteso +prova +prudente +prugna +prurito +psiche +pubblico +pudica +pugilato +pugno +pulce +pulito +pulsante +puntare +pupazzo +pupilla +puro +quadro +qualcosa +quasi +querela +quota +raccolto +raddoppio +radicale +radunato +raffica +ragazzo +ragione +ragno +ramarro +ramingo +ramo +randagio +rantolare +rapato +rapina +rappreso +rasatura +raschiato +rasente +rassegna +rastrello +rata +ravveduto +reale +recepire +recinto +recluta +recondito +recupero +reddito +redimere +regalato +registro +regola +regresso +relazione +remare +remoto +renna +replica +reprimere +reputare +resa +residente +responso +restauro +rete +retina +retorica +rettifica +revocato +riassunto +ribadire +ribelle +ribrezzo +ricarica +ricco +ricevere +riciclato +ricordo +ricreduto +ridicolo +ridurre +rifasare +riflesso +riforma +rifugio +rigare +rigettato +righello +rilassato +rilevato +rimanere +rimbalzo +rimedio +rimorchio +rinascita +rincaro +rinforzo +rinnovo +rinomato +rinsavito +rintocco +rinuncia +rinvenire +riparato +ripetuto +ripieno +riportare +ripresa +ripulire +risata +rischio +riserva +risibile +riso +rispetto +ristoro +risultato +risvolto +ritardo +ritegno +ritmico +ritrovo +riunione +riva +riverso +rivincita +rivolto +rizoma +roba +robotico +robusto +roccia +roco +rodaggio +rodere +roditore +rogito +rollio +romantico +rompere +ronzio +rosolare +rospo +rotante +rotondo +rotula +rovescio +rubizzo +rubrica +ruga +rullino +rumine +rumoroso +ruolo +rupe +russare +rustico +sabato +sabbiare +sabotato +sagoma +salasso +saldatura +salgemma +salivare +salmone +salone +saltare +saluto +salvo +sapere +sapido +saporito +saraceno +sarcasmo +sarto +sassoso +satellite +satira +satollo +saturno +savana +savio +saziato +sbadiglio +sbalzo +sbancato +sbarra +sbattere +sbavare +sbendare +sbirciare +sbloccato +sbocciato +sbrinare +sbruffone +sbuffare +scabroso +scadenza +scala +scambiare +scandalo +scapola +scarso +scatenare +scavato +scelto +scenico +scettro +scheda +schiena +sciarpa +scienza +scindere +scippo +sciroppo +scivolo +sclerare +scodella +scolpito +scomparto +sconforto +scoprire +scorta +scossone +scozzese +scriba +scrollare +scrutinio +scuderia +scultore +scuola +scuro +scusare +sdebitare +sdoganare +seccatura +secondo +sedano +seggiola +segnalato +segregato +seguito +selciato +selettivo +sella +selvaggio +semaforo +sembrare +seme +seminato +sempre +senso +sentire +sepolto +sequenza +serata +serbato +sereno +serio +serpente +serraglio +servire +sestina +setola +settimana +sfacelo +sfaldare +sfamato +sfarzoso +sfaticato +sfera +sfida +sfilato +sfinge +sfocato +sfoderare +sfogo +sfoltire +sforzato +sfratto +sfruttato +sfuggito +sfumare +sfuso +sgabello +sgarbato +sgonfiare +sgorbio +sgrassato +sguardo +sibilo +siccome +sierra +sigla +signore +silenzio +sillaba +simbolo +simpatico +simulato +sinfonia +singolo +sinistro +sino +sintesi +sinusoide +sipario +sisma +sistole +situato +slitta +slogatura +sloveno +smarrito +smemorato +smentito +smeraldo +smilzo +smontare +smottato +smussato +snellire +snervato +snodo +sobbalzo +sobrio +soccorso +sociale +sodale +soffitto +sogno +soldato +solenne +solido +sollazzo +solo +solubile +solvente +somatico +somma +sonda +sonetto +sonnifero +sopire +soppeso +sopra +sorgere +sorpasso +sorriso +sorso +sorteggio +sorvolato +sospiro +sosta +sottile +spada +spalla +spargere +spatola +spavento +spazzola +specie +spedire +spegnere +spelatura +speranza +spessore +spettrale +spezzato +spia +spigoloso +spillato +spinoso +spirale +splendido +sportivo +sposo +spranga +sprecare +spronato +spruzzo +spuntino +squillo +sradicare +srotolato +stabile +stacco +staffa +stagnare +stampato +stantio +starnuto +stasera +statuto +stelo +steppa +sterzo +stiletto +stima +stirpe +stivale +stizzoso +stonato +storico +strappo +stregato +stridulo +strozzare +strutto +stuccare +stufo +stupendo +subentro +succoso +sudore +suggerito +sugo +sultano +suonare +superbo +supporto +surgelato +surrogato +sussurro +sutura +svagare +svedese +sveglio +svelare +svenuto +svezia +sviluppo +svista +svizzera +svolta +svuotare +tabacco +tabulato +tacciare +taciturno +tale +talismano +tampone +tannino +tara +tardivo +targato +tariffa +tarpare +tartaruga +tasto +tattico +taverna +tavolata +tazza +teca +tecnico +telefono +temerario +tempo +temuto +tendone +tenero +tensione +tentacolo +teorema +terme +terrazzo +terzetto +tesi +tesserato +testato +tetro +tettoia +tifare +tigella +timbro +tinto +tipico +tipografo +tiraggio +tiro +titanio +titolo +titubante +tizio +tizzone +toccare +tollerare +tolto +tombola +tomo +tonfo +tonsilla +topazio +topologia +toppa +torba +tornare +torrone +tortora +toscano +tossire +tostatura +totano +trabocco +trachea +trafila +tragedia +tralcio +tramonto +transito +trapano +trarre +trasloco +trattato +trave +treccia +tremolio +trespolo +tributo +tricheco +trifoglio +trillo +trincea +trio +tristezza +triturato +trivella +tromba +trono +troppo +trottola +trovare +truccato +tubatura +tuffato +tulipano +tumulto +tunisia +turbare +turchino +tuta +tutela +ubicato +uccello +uccisore +udire +uditivo +uffa +ufficio +uguale +ulisse +ultimato +umano +umile +umorismo +uncinetto +ungere +ungherese +unicorno +unificato +unisono +unitario +unte +uovo +upupa +uragano +urgenza +urlo +usanza +usato +uscito +usignolo +usuraio +utensile +utilizzo +utopia +vacante +vaccinato +vagabondo +vagliato +valanga +valgo +valico +valletta +valoroso +valutare +valvola +vampata +vangare +vanitoso +vano +vantaggio +vanvera +vapore +varano +varcato +variante +vasca +vedetta +vedova +veduto +vegetale +veicolo +velcro +velina +velluto +veloce +venato +vendemmia +vento +verace +verbale +vergogna +verifica +vero +verruca +verticale +vescica +vessillo +vestale +veterano +vetrina +vetusto +viandante +vibrante +vicenda +vichingo +vicinanza +vidimare +vigilia +vigneto +vigore +vile +villano +vimini +vincitore +viola +vipera +virgola +virologo +virulento +viscoso +visione +vispo +vissuto +visura +vita +vitello +vittima +vivanda +vivido +viziare +voce +voga +volatile +volere +volpe +voragine +vulcano +zampogna +zanna +zappato +zattera +zavorra +zefiro +zelante +zelo +zenzero +zerbino +zibetto +zinco +zircone +zitto +zolla +zotico +zucchero +zufolo +zulu +zuppa`.split('\n'); +//# sourceMappingURL=italian.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/esm/wordlists/italian.js.map b/node_modules/@scure/bip39/esm/wordlists/italian.js.map new file mode 100644 index 0000000..db9246a --- /dev/null +++ b/node_modules/@scure/bip39/esm/wordlists/italian.js.map @@ -0,0 +1 @@ +{"version":3,"file":"italian.js","sourceRoot":"","sources":["../../src/wordlists/italian.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,QAAQ,GAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MA+/D5B,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip39/esm/wordlists/japanese.js b/node_modules/@scure/bip39/esm/wordlists/japanese.js new file mode 100644 index 0000000..44c62bf --- /dev/null +++ b/node_modules/@scure/bip39/esm/wordlists/japanese.js @@ -0,0 +1,2049 @@ +export const wordlist = `あいこくしん +あいさつ +あいだ +あおぞら +あかちゃん +あきる +あけがた +あける +あこがれる +あさい +あさひ +あしあと +あじわう +あずかる +あずき +あそぶ +あたえる +あたためる +あたりまえ +あたる +あつい +あつかう +あっしゅく +あつまり +あつめる +あてな +あてはまる +あひる +あぶら +あぶる +あふれる +あまい +あまど +あまやかす +あまり +あみもの +あめりか +あやまる +あゆむ +あらいぐま +あらし +あらすじ +あらためる +あらゆる +あらわす +ありがとう +あわせる +あわてる +あんい +あんがい +あんこ +あんぜん +あんてい +あんない +あんまり +いいだす +いおん +いがい +いがく +いきおい +いきなり +いきもの +いきる +いくじ +いくぶん +いけばな +いけん +いこう +いこく +いこつ +いさましい +いさん +いしき +いじゅう +いじょう +いじわる +いずみ +いずれ +いせい +いせえび +いせかい +いせき +いぜん +いそうろう +いそがしい +いだい +いだく +いたずら +いたみ +いたりあ +いちおう +いちじ +いちど +いちば +いちぶ +いちりゅう +いつか +いっしゅん +いっせい +いっそう +いったん +いっち +いってい +いっぽう +いてざ +いてん +いどう +いとこ +いない +いなか +いねむり +いのち +いのる +いはつ +いばる +いはん +いびき +いひん +いふく +いへん +いほう +いみん +いもうと +いもたれ +いもり +いやがる +いやす +いよかん +いよく +いらい +いらすと +いりぐち +いりょう +いれい +いれもの +いれる +いろえんぴつ +いわい +いわう +いわかん +いわば +いわゆる +いんげんまめ +いんさつ +いんしょう +いんよう +うえき +うえる +うおざ +うがい +うかぶ +うかべる +うきわ +うくらいな +うくれれ +うけたまわる +うけつけ +うけとる +うけもつ +うける +うごかす +うごく +うこん +うさぎ +うしなう +うしろがみ +うすい +うすぎ +うすぐらい +うすめる +うせつ +うちあわせ +うちがわ +うちき +うちゅう +うっかり +うつくしい +うったえる +うつる +うどん +うなぎ +うなじ +うなずく +うなる +うねる +うのう +うぶげ +うぶごえ +うまれる +うめる +うもう +うやまう +うよく +うらがえす +うらぐち +うらない +うりあげ +うりきれ +うるさい +うれしい +うれゆき +うれる +うろこ +うわき +うわさ +うんこう +うんちん +うんてん +うんどう +えいえん +えいが +えいきょう +えいご +えいせい +えいぶん +えいよう +えいわ +えおり +えがお +えがく +えきたい +えくせる +えしゃく +えすて +えつらん +えのぐ +えほうまき +えほん +えまき +えもじ +えもの +えらい +えらぶ +えりあ +えんえん +えんかい +えんぎ +えんげき +えんしゅう +えんぜつ +えんそく +えんちょう +えんとつ +おいかける +おいこす +おいしい +おいつく +おうえん +おうさま +おうじ +おうせつ +おうたい +おうふく +おうべい +おうよう +おえる +おおい +おおう +おおどおり +おおや +おおよそ +おかえり +おかず +おがむ +おかわり +おぎなう +おきる +おくさま +おくじょう +おくりがな +おくる +おくれる +おこす +おこなう +おこる +おさえる +おさない +おさめる +おしいれ +おしえる +おじぎ +おじさん +おしゃれ +おそらく +おそわる +おたがい +おたく +おだやか +おちつく +おっと +おつり +おでかけ +おとしもの +おとなしい +おどり +おどろかす +おばさん +おまいり +おめでとう +おもいで +おもう +おもたい +おもちゃ +おやつ +おやゆび +およぼす +おらんだ +おろす +おんがく +おんけい +おんしゃ +おんせん +おんだん +おんちゅう +おんどけい +かあつ +かいが +がいき +がいけん +がいこう +かいさつ +かいしゃ +かいすいよく +かいぜん +かいぞうど +かいつう +かいてん +かいとう +かいふく +がいへき +かいほう +かいよう +がいらい +かいわ +かえる +かおり +かかえる +かがく +かがし +かがみ +かくご +かくとく +かざる +がぞう +かたい +かたち +がちょう +がっきゅう +がっこう +がっさん +がっしょう +かなざわし +かのう +がはく +かぶか +かほう +かほご +かまう +かまぼこ +かめれおん +かゆい +かようび +からい +かるい +かろう +かわく +かわら +がんか +かんけい +かんこう +かんしゃ +かんそう +かんたん +かんち +がんばる +きあい +きあつ +きいろ +ぎいん +きうい +きうん +きえる +きおう +きおく +きおち +きおん +きかい +きかく +きかんしゃ +ききて +きくばり +きくらげ +きけんせい +きこう +きこえる +きこく +きさい +きさく +きさま +きさらぎ +ぎじかがく +ぎしき +ぎじたいけん +ぎじにってい +ぎじゅつしゃ +きすう +きせい +きせき +きせつ +きそう +きぞく +きぞん +きたえる +きちょう +きつえん +ぎっちり +きつつき +きつね +きてい +きどう +きどく +きない +きなが +きなこ +きぬごし +きねん +きのう +きのした +きはく +きびしい +きひん +きふく +きぶん +きぼう +きほん +きまる +きみつ +きむずかしい +きめる +きもだめし +きもち +きもの +きゃく +きやく +ぎゅうにく +きよう +きょうりゅう +きらい +きらく +きりん +きれい +きれつ +きろく +ぎろん +きわめる +ぎんいろ +きんかくじ +きんじょ +きんようび +ぐあい +くいず +くうかん +くうき +くうぐん +くうこう +ぐうせい +くうそう +ぐうたら +くうふく +くうぼ +くかん +くきょう +くげん +ぐこう +くさい +くさき +くさばな +くさる +くしゃみ +くしょう +くすのき +くすりゆび +くせげ +くせん +ぐたいてき +くださる +くたびれる +くちこみ +くちさき +くつした +ぐっすり +くつろぐ +くとうてん +くどく +くなん +くねくね +くのう +くふう +くみあわせ +くみたてる +くめる +くやくしょ +くらす +くらべる +くるま +くれる +くろう +くわしい +ぐんかん +ぐんしょく +ぐんたい +ぐんて +けあな +けいかく +けいけん +けいこ +けいさつ +げいじゅつ +けいたい +げいのうじん +けいれき +けいろ +けおとす +けおりもの +げきか +げきげん +げきだん +げきちん +げきとつ +げきは +げきやく +げこう +げこくじょう +げざい +けさき +げざん +けしき +けしごむ +けしょう +げすと +けたば +けちゃっぷ +けちらす +けつあつ +けつい +けつえき +けっこん +けつじょ +けっせき +けってい +けつまつ +げつようび +げつれい +けつろん +げどく +けとばす +けとる +けなげ +けなす +けなみ +けぬき +げねつ +けねん +けはい +げひん +けぶかい +げぼく +けまり +けみかる +けむし +けむり +けもの +けらい +けろけろ +けわしい +けんい +けんえつ +けんお +けんか +げんき +けんげん +けんこう +けんさく +けんしゅう +けんすう +げんそう +けんちく +けんてい +けんとう +けんない +けんにん +げんぶつ +けんま +けんみん +けんめい +けんらん +けんり +こあくま +こいぬ +こいびと +ごうい +こうえん +こうおん +こうかん +ごうきゅう +ごうけい +こうこう +こうさい +こうじ +こうすい +ごうせい +こうそく +こうたい +こうちゃ +こうつう +こうてい +こうどう +こうない +こうはい +ごうほう +ごうまん +こうもく +こうりつ +こえる +こおり +ごかい +ごがつ +ごかん +こくご +こくさい +こくとう +こくない +こくはく +こぐま +こけい +こける +ここのか +こころ +こさめ +こしつ +こすう +こせい +こせき +こぜん +こそだて +こたい +こたえる +こたつ +こちょう +こっか +こつこつ +こつばん +こつぶ +こてい +こてん +ことがら +ことし +ことば +ことり +こなごな +こねこね +このまま +このみ +このよ +ごはん +こひつじ +こふう +こふん +こぼれる +ごまあぶら +こまかい +ごますり +こまつな +こまる +こむぎこ +こもじ +こもち +こもの +こもん +こやく +こやま +こゆう +こゆび +こよい +こよう +こりる +これくしょん +ころっけ +こわもて +こわれる +こんいん +こんかい +こんき +こんしゅう +こんすい +こんだて +こんとん +こんなん +こんびに +こんぽん +こんまけ +こんや +こんれい +こんわく +ざいえき +さいかい +さいきん +ざいげん +ざいこ +さいしょ +さいせい +ざいたく +ざいちゅう +さいてき +ざいりょう +さうな +さかいし +さがす +さかな +さかみち +さがる +さぎょう +さくし +さくひん +さくら +さこく +さこつ +さずかる +ざせき +さたん +さつえい +ざつおん +ざっか +ざつがく +さっきょく +ざっし +さつじん +ざっそう +さつたば +さつまいも +さてい +さといも +さとう +さとおや +さとし +さとる +さのう +さばく +さびしい +さべつ +さほう +さほど +さます +さみしい +さみだれ +さむけ +さめる +さやえんどう +さゆう +さよう +さよく +さらだ +ざるそば +さわやか +さわる +さんいん +さんか +さんきゃく +さんこう +さんさい +ざんしょ +さんすう +さんせい +さんそ +さんち +さんま +さんみ +さんらん +しあい +しあげ +しあさって +しあわせ +しいく +しいん +しうち +しえい +しおけ +しかい +しかく +じかん +しごと +しすう +じだい +したうけ +したぎ +したて +したみ +しちょう +しちりん +しっかり +しつじ +しつもん +してい +してき +してつ +じてん +じどう +しなぎれ +しなもの +しなん +しねま +しねん +しのぐ +しのぶ +しはい +しばかり +しはつ +しはらい +しはん +しひょう +しふく +じぶん +しへい +しほう +しほん +しまう +しまる +しみん +しむける +じむしょ +しめい +しめる +しもん +しゃいん +しゃうん +しゃおん +じゃがいも +しやくしょ +しゃくほう +しゃけん +しゃこ +しゃざい +しゃしん +しゃせん +しゃそう +しゃたい +しゃちょう +しゃっきん +じゃま +しゃりん +しゃれい +じゆう +じゅうしょ +しゅくはく +じゅしん +しゅっせき +しゅみ +しゅらば +じゅんばん +しょうかい +しょくたく +しょっけん +しょどう +しょもつ +しらせる +しらべる +しんか +しんこう +じんじゃ +しんせいじ +しんちく +しんりん +すあげ +すあし +すあな +ずあん +すいえい +すいか +すいとう +ずいぶん +すいようび +すうがく +すうじつ +すうせん +すおどり +すきま +すくう +すくない +すける +すごい +すこし +ずさん +すずしい +すすむ +すすめる +すっかり +ずっしり +ずっと +すてき +すてる +すねる +すのこ +すはだ +すばらしい +ずひょう +ずぶぬれ +すぶり +すふれ +すべて +すべる +ずほう +すぼん +すまい +すめし +すもう +すやき +すらすら +するめ +すれちがう +すろっと +すわる +すんぜん +すんぽう +せあぶら +せいかつ +せいげん +せいじ +せいよう +せおう +せかいかん +せきにん +せきむ +せきゆ +せきらんうん +せけん +せこう +せすじ +せたい +せたけ +せっかく +せっきゃく +ぜっく +せっけん +せっこつ +せっさたくま +せつぞく +せつだん +せつでん +せっぱん +せつび +せつぶん +せつめい +せつりつ +せなか +せのび +せはば +せびろ +せぼね +せまい +せまる +せめる +せもたれ +せりふ +ぜんあく +せんい +せんえい +せんか +せんきょ +せんく +せんげん +ぜんご +せんさい +せんしゅ +せんすい +せんせい +せんぞ +せんたく +せんちょう +せんてい +せんとう +せんぬき +せんねん +せんぱい +ぜんぶ +ぜんぽう +せんむ +せんめんじょ +せんもん +せんやく +せんゆう +せんよう +ぜんら +ぜんりゃく +せんれい +せんろ +そあく +そいとげる +そいね +そうがんきょう +そうき +そうご +そうしん +そうだん +そうなん +そうび +そうめん +そうり +そえもの +そえん +そがい +そげき +そこう +そこそこ +そざい +そしな +そせい +そせん +そそぐ +そだてる +そつう +そつえん +そっかん +そつぎょう +そっけつ +そっこう +そっせん +そっと +そとがわ +そとづら +そなえる +そなた +そふぼ +そぼく +そぼろ +そまつ +そまる +そむく +そむりえ +そめる +そもそも +そよかぜ +そらまめ +そろう +そんかい +そんけい +そんざい +そんしつ +そんぞく +そんちょう +ぞんび +ぞんぶん +そんみん +たあい +たいいん +たいうん +たいえき +たいおう +だいがく +たいき +たいぐう +たいけん +たいこ +たいざい +だいじょうぶ +だいすき +たいせつ +たいそう +だいたい +たいちょう +たいてい +だいどころ +たいない +たいねつ +たいのう +たいはん +だいひょう +たいふう +たいへん +たいほ +たいまつばな +たいみんぐ +たいむ +たいめん +たいやき +たいよう +たいら +たいりょく +たいる +たいわん +たうえ +たえる +たおす +たおる +たおれる +たかい +たかね +たきび +たくさん +たこく +たこやき +たさい +たしざん +だじゃれ +たすける +たずさわる +たそがれ +たたかう +たたく +ただしい +たたみ +たちばな +だっかい +だっきゃく +だっこ +だっしゅつ +だったい +たてる +たとえる +たなばた +たにん +たぬき +たのしみ +たはつ +たぶん +たべる +たぼう +たまご +たまる +だむる +ためいき +ためす +ためる +たもつ +たやすい +たよる +たらす +たりきほんがん +たりょう +たりる +たると +たれる +たれんと +たろっと +たわむれる +だんあつ +たんい +たんおん +たんか +たんき +たんけん +たんご +たんさん +たんじょうび +だんせい +たんそく +たんたい +だんち +たんてい +たんとう +だんな +たんにん +だんねつ +たんのう +たんぴん +だんぼう +たんまつ +たんめい +だんれつ +だんろ +だんわ +ちあい +ちあん +ちいき +ちいさい +ちえん +ちかい +ちから +ちきゅう +ちきん +ちけいず +ちけん +ちこく +ちさい +ちしき +ちしりょう +ちせい +ちそう +ちたい +ちたん +ちちおや +ちつじょ +ちてき +ちてん +ちぬき +ちぬり +ちのう +ちひょう +ちへいせん +ちほう +ちまた +ちみつ +ちみどろ +ちめいど +ちゃんこなべ +ちゅうい +ちゆりょく +ちょうし +ちょさくけん +ちらし +ちらみ +ちりがみ +ちりょう +ちるど +ちわわ +ちんたい +ちんもく +ついか +ついたち +つうか +つうじょう +つうはん +つうわ +つかう +つかれる +つくね +つくる +つけね +つける +つごう +つたえる +つづく +つつじ +つつむ +つとめる +つながる +つなみ +つねづね +つのる +つぶす +つまらない +つまる +つみき +つめたい +つもり +つもる +つよい +つるぼ +つるみく +つわもの +つわり +てあし +てあて +てあみ +ていおん +ていか +ていき +ていけい +ていこく +ていさつ +ていし +ていせい +ていたい +ていど +ていねい +ていひょう +ていへん +ていぼう +てうち +ておくれ +てきとう +てくび +でこぼこ +てさぎょう +てさげ +てすり +てそう +てちがい +てちょう +てつがく +てつづき +でっぱ +てつぼう +てつや +でぬかえ +てぬき +てぬぐい +てのひら +てはい +てぶくろ +てふだ +てほどき +てほん +てまえ +てまきずし +てみじか +てみやげ +てらす +てれび +てわけ +てわたし +でんあつ +てんいん +てんかい +てんき +てんぐ +てんけん +てんごく +てんさい +てんし +てんすう +でんち +てんてき +てんとう +てんない +てんぷら +てんぼうだい +てんめつ +てんらんかい +でんりょく +でんわ +どあい +といれ +どうかん +とうきゅう +どうぐ +とうし +とうむぎ +とおい +とおか +とおく +とおす +とおる +とかい +とかす +ときおり +ときどき +とくい +とくしゅう +とくてん +とくに +とくべつ +とけい +とける +とこや +とさか +としょかん +とそう +とたん +とちゅう +とっきゅう +とっくん +とつぜん +とつにゅう +とどける +ととのえる +とない +となえる +となり +とのさま +とばす +どぶがわ +とほう +とまる +とめる +ともだち +ともる +どようび +とらえる +とんかつ +どんぶり +ないかく +ないこう +ないしょ +ないす +ないせん +ないそう +なおす +ながい +なくす +なげる +なこうど +なさけ +なたでここ +なっとう +なつやすみ +ななおし +なにごと +なにもの +なにわ +なのか +なふだ +なまいき +なまえ +なまみ +なみだ +なめらか +なめる +なやむ +ならう +ならび +ならぶ +なれる +なわとび +なわばり +にあう +にいがた +にうけ +におい +にかい +にがて +にきび +にくしみ +にくまん +にげる +にさんかたんそ +にしき +にせもの +にちじょう +にちようび +にっか +にっき +にっけい +にっこう +にっさん +にっしょく +にっすう +にっせき +にってい +になう +にほん +にまめ +にもつ +にやり +にゅういん +にりんしゃ +にわとり +にんい +にんか +にんき +にんげん +にんしき +にんずう +にんそう +にんたい +にんち +にんてい +にんにく +にんぷ +にんまり +にんむ +にんめい +にんよう +ぬいくぎ +ぬかす +ぬぐいとる +ぬぐう +ぬくもり +ぬすむ +ぬまえび +ぬめり +ぬらす +ぬんちゃく +ねあげ +ねいき +ねいる +ねいろ +ねぐせ +ねくたい +ねくら +ねこぜ +ねこむ +ねさげ +ねすごす +ねそべる +ねだん +ねつい +ねっしん +ねつぞう +ねったいぎょ +ねぶそく +ねふだ +ねぼう +ねほりはほり +ねまき +ねまわし +ねみみ +ねむい +ねむたい +ねもと +ねらう +ねわざ +ねんいり +ねんおし +ねんかん +ねんきん +ねんぐ +ねんざ +ねんし +ねんちゃく +ねんど +ねんぴ +ねんぶつ +ねんまつ +ねんりょう +ねんれい +のいず +のおづま +のがす +のきなみ +のこぎり +のこす +のこる +のせる +のぞく +のぞむ +のたまう +のちほど +のっく +のばす +のはら +のべる +のぼる +のみもの +のやま +のらいぬ +のらねこ +のりもの +のりゆき +のれん +のんき +ばあい +はあく +ばあさん +ばいか +ばいく +はいけん +はいご +はいしん +はいすい +はいせん +はいそう +はいち +ばいばい +はいれつ +はえる +はおる +はかい +ばかり +はかる +はくしゅ +はけん +はこぶ +はさみ +はさん +はしご +ばしょ +はしる +はせる +ぱそこん +はそん +はたん +はちみつ +はつおん +はっかく +はづき +はっきり +はっくつ +はっけん +はっこう +はっさん +はっしん +はったつ +はっちゅう +はってん +はっぴょう +はっぽう +はなす +はなび +はにかむ +はぶらし +はみがき +はむかう +はめつ +はやい +はやし +はらう +はろうぃん +はわい +はんい +はんえい +はんおん +はんかく +はんきょう +ばんぐみ +はんこ +はんしゃ +はんすう +はんだん +ぱんち +ぱんつ +はんてい +はんとし +はんのう +はんぱ +はんぶん +はんぺん +はんぼうき +はんめい +はんらん +はんろん +ひいき +ひうん +ひえる +ひかく +ひかり +ひかる +ひかん +ひくい +ひけつ +ひこうき +ひこく +ひさい +ひさしぶり +ひさん +びじゅつかん +ひしょ +ひそか +ひそむ +ひたむき +ひだり +ひたる +ひつぎ +ひっこし +ひっし +ひつじゅひん +ひっす +ひつぜん +ぴったり +ぴっちり +ひつよう +ひてい +ひとごみ +ひなまつり +ひなん +ひねる +ひはん +ひびく +ひひょう +ひほう +ひまわり +ひまん +ひみつ +ひめい +ひめじし +ひやけ +ひやす +ひよう +びょうき +ひらがな +ひらく +ひりつ +ひりょう +ひるま +ひるやすみ +ひれい +ひろい +ひろう +ひろき +ひろゆき +ひんかく +ひんけつ +ひんこん +ひんしゅ +ひんそう +ぴんち +ひんぱん +びんぼう +ふあん +ふいうち +ふうけい +ふうせん +ぷうたろう +ふうとう +ふうふ +ふえる +ふおん +ふかい +ふきん +ふくざつ +ふくぶくろ +ふこう +ふさい +ふしぎ +ふじみ +ふすま +ふせい +ふせぐ +ふそく +ぶたにく +ふたん +ふちょう +ふつう +ふつか +ふっかつ +ふっき +ふっこく +ぶどう +ふとる +ふとん +ふのう +ふはい +ふひょう +ふへん +ふまん +ふみん +ふめつ +ふめん +ふよう +ふりこ +ふりる +ふるい +ふんいき +ぶんがく +ぶんぐ +ふんしつ +ぶんせき +ふんそう +ぶんぽう +へいあん +へいおん +へいがい +へいき +へいげん +へいこう +へいさ +へいしゃ +へいせつ +へいそ +へいたく +へいてん +へいねつ +へいわ +へきが +へこむ +べにいろ +べにしょうが +へらす +へんかん +べんきょう +べんごし +へんさい +へんたい +べんり +ほあん +ほいく +ぼうぎょ +ほうこく +ほうそう +ほうほう +ほうもん +ほうりつ +ほえる +ほおん +ほかん +ほきょう +ぼきん +ほくろ +ほけつ +ほけん +ほこう +ほこる +ほしい +ほしつ +ほしゅ +ほしょう +ほせい +ほそい +ほそく +ほたて +ほたる +ぽちぶくろ +ほっきょく +ほっさ +ほったん +ほとんど +ほめる +ほんい +ほんき +ほんけ +ほんしつ +ほんやく +まいにち +まかい +まかせる +まがる +まける +まこと +まさつ +まじめ +ますく +まぜる +まつり +まとめ +まなぶ +まぬけ +まねく +まほう +まもる +まゆげ +まよう +まろやか +まわす +まわり +まわる +まんが +まんきつ +まんぞく +まんなか +みいら +みうち +みえる +みがく +みかた +みかん +みけん +みこん +みじかい +みすい +みすえる +みせる +みっか +みつかる +みつける +みてい +みとめる +みなと +みなみかさい +みねらる +みのう +みのがす +みほん +みもと +みやげ +みらい +みりょく +みわく +みんか +みんぞく +むいか +むえき +むえん +むかい +むかう +むかえ +むかし +むぎちゃ +むける +むげん +むさぼる +むしあつい +むしば +むじゅん +むしろ +むすう +むすこ +むすぶ +むすめ +むせる +むせん +むちゅう +むなしい +むのう +むやみ +むよう +むらさき +むりょう +むろん +めいあん +めいうん +めいえん +めいかく +めいきょく +めいさい +めいし +めいそう +めいぶつ +めいれい +めいわく +めぐまれる +めざす +めした +めずらしい +めだつ +めまい +めやす +めんきょ +めんせき +めんどう +もうしあげる +もうどうけん +もえる +もくし +もくてき +もくようび +もちろん +もどる +もらう +もんく +もんだい +やおや +やける +やさい +やさしい +やすい +やすたろう +やすみ +やせる +やそう +やたい +やちん +やっと +やっぱり +やぶる +やめる +ややこしい +やよい +やわらかい +ゆうき +ゆうびんきょく +ゆうべ +ゆうめい +ゆけつ +ゆしゅつ +ゆせん +ゆそう +ゆたか +ゆちゃく +ゆでる +ゆにゅう +ゆびわ +ゆらい +ゆれる +ようい +ようか +ようきゅう +ようじ +ようす +ようちえん +よかぜ +よかん +よきん +よくせい +よくぼう +よけい +よごれる +よさん +よしゅう +よそう +よそく +よっか +よてい +よどがわく +よねつ +よやく +よゆう +よろこぶ +よろしい +らいう +らくがき +らくご +らくさつ +らくだ +らしんばん +らせん +らぞく +らたい +らっか +られつ +りえき +りかい +りきさく +りきせつ +りくぐん +りくつ +りけん +りこう +りせい +りそう +りそく +りてん +りねん +りゆう +りゅうがく +りよう +りょうり +りょかん +りょくちゃ +りょこう +りりく +りれき +りろん +りんご +るいけい +るいさい +るいじ +るいせき +るすばん +るりがわら +れいかん +れいぎ +れいせい +れいぞうこ +れいとう +れいぼう +れきし +れきだい +れんあい +れんけい +れんこん +れんさい +れんしゅう +れんぞく +れんらく +ろうか +ろうご +ろうじん +ろうそく +ろくが +ろこつ +ろじうら +ろしゅつ +ろせん +ろてん +ろめん +ろれつ +ろんぎ +ろんぱ +ろんぶん +ろんり +わかす +わかめ +わかやま +わかれる +わしつ +わじまし +わすれもの +わらう +われる`.split('\n'); +//# sourceMappingURL=japanese.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/esm/wordlists/japanese.js.map b/node_modules/@scure/bip39/esm/wordlists/japanese.js.map new file mode 100644 index 0000000..ee1323c --- /dev/null +++ b/node_modules/@scure/bip39/esm/wordlists/japanese.js.map @@ -0,0 +1 @@ +{"version":3,"file":"japanese.js","sourceRoot":"","sources":["../../src/wordlists/japanese.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,QAAQ,GAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA+/D9B,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip39/esm/wordlists/korean.js b/node_modules/@scure/bip39/esm/wordlists/korean.js new file mode 100644 index 0000000..535ae22 --- /dev/null +++ b/node_modules/@scure/bip39/esm/wordlists/korean.js @@ -0,0 +1,2049 @@ +export const wordlist = `가격 +가끔 +가난 +가능 +가득 +가르침 +가뭄 +가방 +가상 +가슴 +가운데 +가을 +가이드 +가입 +가장 +가정 +가족 +가죽 +각오 +각자 +간격 +간부 +간섭 +간장 +간접 +간판 +갈등 +갈비 +갈색 +갈증 +감각 +감기 +감소 +감수성 +감자 +감정 +갑자기 +강남 +강당 +강도 +강력히 +강변 +강북 +강사 +강수량 +강아지 +강원도 +강의 +강제 +강조 +같이 +개구리 +개나리 +개방 +개별 +개선 +개성 +개인 +객관적 +거실 +거액 +거울 +거짓 +거품 +걱정 +건강 +건물 +건설 +건조 +건축 +걸음 +검사 +검토 +게시판 +게임 +겨울 +견해 +결과 +결국 +결론 +결석 +결승 +결심 +결정 +결혼 +경계 +경고 +경기 +경력 +경복궁 +경비 +경상도 +경영 +경우 +경쟁 +경제 +경주 +경찰 +경치 +경향 +경험 +계곡 +계단 +계란 +계산 +계속 +계약 +계절 +계층 +계획 +고객 +고구려 +고궁 +고급 +고등학생 +고무신 +고민 +고양이 +고장 +고전 +고집 +고춧가루 +고통 +고향 +곡식 +골목 +골짜기 +골프 +공간 +공개 +공격 +공군 +공급 +공기 +공동 +공무원 +공부 +공사 +공식 +공업 +공연 +공원 +공장 +공짜 +공책 +공통 +공포 +공항 +공휴일 +과목 +과일 +과장 +과정 +과학 +관객 +관계 +관광 +관념 +관람 +관련 +관리 +관습 +관심 +관점 +관찰 +광경 +광고 +광장 +광주 +괴로움 +굉장히 +교과서 +교문 +교복 +교실 +교양 +교육 +교장 +교직 +교통 +교환 +교훈 +구경 +구름 +구멍 +구별 +구분 +구석 +구성 +구속 +구역 +구입 +구청 +구체적 +국가 +국기 +국내 +국립 +국물 +국민 +국수 +국어 +국왕 +국적 +국제 +국회 +군대 +군사 +군인 +궁극적 +권리 +권위 +권투 +귀국 +귀신 +규정 +규칙 +균형 +그날 +그냥 +그늘 +그러나 +그룹 +그릇 +그림 +그제서야 +그토록 +극복 +극히 +근거 +근교 +근래 +근로 +근무 +근본 +근원 +근육 +근처 +글씨 +글자 +금강산 +금고 +금년 +금메달 +금액 +금연 +금요일 +금지 +긍정적 +기간 +기관 +기념 +기능 +기독교 +기둥 +기록 +기름 +기법 +기본 +기분 +기쁨 +기숙사 +기술 +기억 +기업 +기온 +기운 +기원 +기적 +기준 +기침 +기혼 +기획 +긴급 +긴장 +길이 +김밥 +김치 +김포공항 +깍두기 +깜빡 +깨달음 +깨소금 +껍질 +꼭대기 +꽃잎 +나들이 +나란히 +나머지 +나물 +나침반 +나흘 +낙엽 +난방 +날개 +날씨 +날짜 +남녀 +남대문 +남매 +남산 +남자 +남편 +남학생 +낭비 +낱말 +내년 +내용 +내일 +냄비 +냄새 +냇물 +냉동 +냉면 +냉방 +냉장고 +넥타이 +넷째 +노동 +노란색 +노력 +노인 +녹음 +녹차 +녹화 +논리 +논문 +논쟁 +놀이 +농구 +농담 +농민 +농부 +농업 +농장 +농촌 +높이 +눈동자 +눈물 +눈썹 +뉴욕 +느낌 +늑대 +능동적 +능력 +다방 +다양성 +다음 +다이어트 +다행 +단계 +단골 +단독 +단맛 +단순 +단어 +단위 +단점 +단체 +단추 +단편 +단풍 +달걀 +달러 +달력 +달리 +닭고기 +담당 +담배 +담요 +담임 +답변 +답장 +당근 +당분간 +당연히 +당장 +대규모 +대낮 +대단히 +대답 +대도시 +대략 +대량 +대륙 +대문 +대부분 +대신 +대응 +대장 +대전 +대접 +대중 +대책 +대출 +대충 +대통령 +대학 +대한민국 +대합실 +대형 +덩어리 +데이트 +도대체 +도덕 +도둑 +도망 +도서관 +도심 +도움 +도입 +도자기 +도저히 +도전 +도중 +도착 +독감 +독립 +독서 +독일 +독창적 +동화책 +뒷모습 +뒷산 +딸아이 +마누라 +마늘 +마당 +마라톤 +마련 +마무리 +마사지 +마약 +마요네즈 +마을 +마음 +마이크 +마중 +마지막 +마찬가지 +마찰 +마흔 +막걸리 +막내 +막상 +만남 +만두 +만세 +만약 +만일 +만점 +만족 +만화 +많이 +말기 +말씀 +말투 +맘대로 +망원경 +매년 +매달 +매력 +매번 +매스컴 +매일 +매장 +맥주 +먹이 +먼저 +먼지 +멀리 +메일 +며느리 +며칠 +면담 +멸치 +명단 +명령 +명예 +명의 +명절 +명칭 +명함 +모금 +모니터 +모델 +모든 +모범 +모습 +모양 +모임 +모조리 +모집 +모퉁이 +목걸이 +목록 +목사 +목소리 +목숨 +목적 +목표 +몰래 +몸매 +몸무게 +몸살 +몸속 +몸짓 +몸통 +몹시 +무관심 +무궁화 +무더위 +무덤 +무릎 +무슨 +무엇 +무역 +무용 +무조건 +무지개 +무척 +문구 +문득 +문법 +문서 +문제 +문학 +문화 +물가 +물건 +물결 +물고기 +물론 +물리학 +물음 +물질 +물체 +미국 +미디어 +미사일 +미술 +미역 +미용실 +미움 +미인 +미팅 +미혼 +민간 +민족 +민주 +믿음 +밀가루 +밀리미터 +밑바닥 +바가지 +바구니 +바나나 +바늘 +바닥 +바닷가 +바람 +바이러스 +바탕 +박물관 +박사 +박수 +반대 +반드시 +반말 +반발 +반성 +반응 +반장 +반죽 +반지 +반찬 +받침 +발가락 +발걸음 +발견 +발달 +발레 +발목 +발바닥 +발생 +발음 +발자국 +발전 +발톱 +발표 +밤하늘 +밥그릇 +밥맛 +밥상 +밥솥 +방금 +방면 +방문 +방바닥 +방법 +방송 +방식 +방안 +방울 +방지 +방학 +방해 +방향 +배경 +배꼽 +배달 +배드민턴 +백두산 +백색 +백성 +백인 +백제 +백화점 +버릇 +버섯 +버튼 +번개 +번역 +번지 +번호 +벌금 +벌레 +벌써 +범위 +범인 +범죄 +법률 +법원 +법적 +법칙 +베이징 +벨트 +변경 +변동 +변명 +변신 +변호사 +변화 +별도 +별명 +별일 +병실 +병아리 +병원 +보관 +보너스 +보라색 +보람 +보름 +보상 +보안 +보자기 +보장 +보전 +보존 +보통 +보편적 +보험 +복도 +복사 +복숭아 +복습 +볶음 +본격적 +본래 +본부 +본사 +본성 +본인 +본질 +볼펜 +봉사 +봉지 +봉투 +부근 +부끄러움 +부담 +부동산 +부문 +부분 +부산 +부상 +부엌 +부인 +부작용 +부장 +부정 +부족 +부지런히 +부친 +부탁 +부품 +부회장 +북부 +북한 +분노 +분량 +분리 +분명 +분석 +분야 +분위기 +분필 +분홍색 +불고기 +불과 +불교 +불꽃 +불만 +불법 +불빛 +불안 +불이익 +불행 +브랜드 +비극 +비난 +비닐 +비둘기 +비디오 +비로소 +비만 +비명 +비밀 +비바람 +비빔밥 +비상 +비용 +비율 +비중 +비타민 +비판 +빌딩 +빗물 +빗방울 +빗줄기 +빛깔 +빨간색 +빨래 +빨리 +사건 +사계절 +사나이 +사냥 +사람 +사랑 +사립 +사모님 +사물 +사방 +사상 +사생활 +사설 +사슴 +사실 +사업 +사용 +사월 +사장 +사전 +사진 +사촌 +사춘기 +사탕 +사투리 +사흘 +산길 +산부인과 +산업 +산책 +살림 +살인 +살짝 +삼계탕 +삼국 +삼십 +삼월 +삼촌 +상관 +상금 +상대 +상류 +상반기 +상상 +상식 +상업 +상인 +상자 +상점 +상처 +상추 +상태 +상표 +상품 +상황 +새벽 +색깔 +색연필 +생각 +생명 +생물 +생방송 +생산 +생선 +생신 +생일 +생활 +서랍 +서른 +서명 +서민 +서비스 +서양 +서울 +서적 +서점 +서쪽 +서클 +석사 +석유 +선거 +선물 +선배 +선생 +선수 +선원 +선장 +선전 +선택 +선풍기 +설거지 +설날 +설렁탕 +설명 +설문 +설사 +설악산 +설치 +설탕 +섭씨 +성공 +성당 +성명 +성별 +성인 +성장 +성적 +성질 +성함 +세금 +세미나 +세상 +세월 +세종대왕 +세탁 +센터 +센티미터 +셋째 +소규모 +소극적 +소금 +소나기 +소년 +소득 +소망 +소문 +소설 +소속 +소아과 +소용 +소원 +소음 +소중히 +소지품 +소질 +소풍 +소형 +속담 +속도 +속옷 +손가락 +손길 +손녀 +손님 +손등 +손목 +손뼉 +손실 +손질 +손톱 +손해 +솔직히 +솜씨 +송아지 +송이 +송편 +쇠고기 +쇼핑 +수건 +수년 +수단 +수돗물 +수동적 +수면 +수명 +수박 +수상 +수석 +수술 +수시로 +수업 +수염 +수영 +수입 +수준 +수집 +수출 +수컷 +수필 +수학 +수험생 +수화기 +숙녀 +숙소 +숙제 +순간 +순서 +순수 +순식간 +순위 +숟가락 +술병 +술집 +숫자 +스님 +스물 +스스로 +스승 +스웨터 +스위치 +스케이트 +스튜디오 +스트레스 +스포츠 +슬쩍 +슬픔 +습관 +습기 +승객 +승리 +승부 +승용차 +승진 +시각 +시간 +시골 +시금치 +시나리오 +시댁 +시리즈 +시멘트 +시민 +시부모 +시선 +시설 +시스템 +시아버지 +시어머니 +시월 +시인 +시일 +시작 +시장 +시절 +시점 +시중 +시즌 +시집 +시청 +시합 +시험 +식구 +식기 +식당 +식량 +식료품 +식물 +식빵 +식사 +식생활 +식초 +식탁 +식품 +신고 +신규 +신념 +신문 +신발 +신비 +신사 +신세 +신용 +신제품 +신청 +신체 +신화 +실감 +실내 +실력 +실례 +실망 +실수 +실습 +실시 +실장 +실정 +실질적 +실천 +실체 +실컷 +실태 +실패 +실험 +실현 +심리 +심부름 +심사 +심장 +심정 +심판 +쌍둥이 +씨름 +씨앗 +아가씨 +아나운서 +아드님 +아들 +아쉬움 +아스팔트 +아시아 +아울러 +아저씨 +아줌마 +아직 +아침 +아파트 +아프리카 +아픔 +아홉 +아흔 +악기 +악몽 +악수 +안개 +안경 +안과 +안내 +안녕 +안동 +안방 +안부 +안주 +알루미늄 +알코올 +암시 +암컷 +압력 +앞날 +앞문 +애인 +애정 +액수 +앨범 +야간 +야단 +야옹 +약간 +약국 +약속 +약수 +약점 +약품 +약혼녀 +양념 +양력 +양말 +양배추 +양주 +양파 +어둠 +어려움 +어른 +어젯밤 +어쨌든 +어쩌다가 +어쩐지 +언니 +언덕 +언론 +언어 +얼굴 +얼른 +얼음 +얼핏 +엄마 +업무 +업종 +업체 +엉덩이 +엉망 +엉터리 +엊그제 +에너지 +에어컨 +엔진 +여건 +여고생 +여관 +여군 +여권 +여대생 +여덟 +여동생 +여든 +여론 +여름 +여섯 +여성 +여왕 +여인 +여전히 +여직원 +여학생 +여행 +역사 +역시 +역할 +연결 +연구 +연극 +연기 +연락 +연설 +연세 +연속 +연습 +연애 +연예인 +연인 +연장 +연주 +연출 +연필 +연합 +연휴 +열기 +열매 +열쇠 +열심히 +열정 +열차 +열흘 +염려 +엽서 +영국 +영남 +영상 +영양 +영역 +영웅 +영원히 +영하 +영향 +영혼 +영화 +옆구리 +옆방 +옆집 +예감 +예금 +예방 +예산 +예상 +예선 +예술 +예습 +예식장 +예약 +예전 +예절 +예정 +예컨대 +옛날 +오늘 +오락 +오랫동안 +오렌지 +오로지 +오른발 +오븐 +오십 +오염 +오월 +오전 +오직 +오징어 +오페라 +오피스텔 +오히려 +옥상 +옥수수 +온갖 +온라인 +온몸 +온종일 +온통 +올가을 +올림픽 +올해 +옷차림 +와이셔츠 +와인 +완성 +완전 +왕비 +왕자 +왜냐하면 +왠지 +외갓집 +외국 +외로움 +외삼촌 +외출 +외침 +외할머니 +왼발 +왼손 +왼쪽 +요금 +요일 +요즘 +요청 +용기 +용서 +용어 +우산 +우선 +우승 +우연히 +우정 +우체국 +우편 +운동 +운명 +운반 +운전 +운행 +울산 +울음 +움직임 +웃어른 +웃음 +워낙 +원고 +원래 +원서 +원숭이 +원인 +원장 +원피스 +월급 +월드컵 +월세 +월요일 +웨이터 +위반 +위법 +위성 +위원 +위험 +위협 +윗사람 +유난히 +유럽 +유명 +유물 +유산 +유적 +유치원 +유학 +유행 +유형 +육군 +육상 +육십 +육체 +은행 +음력 +음료 +음반 +음성 +음식 +음악 +음주 +의견 +의논 +의문 +의복 +의식 +의심 +의외로 +의욕 +의원 +의학 +이것 +이곳 +이념 +이놈 +이달 +이대로 +이동 +이렇게 +이력서 +이론적 +이름 +이민 +이발소 +이별 +이불 +이빨 +이상 +이성 +이슬 +이야기 +이용 +이웃 +이월 +이윽고 +이익 +이전 +이중 +이튿날 +이틀 +이혼 +인간 +인격 +인공 +인구 +인근 +인기 +인도 +인류 +인물 +인생 +인쇄 +인연 +인원 +인재 +인종 +인천 +인체 +인터넷 +인하 +인형 +일곱 +일기 +일단 +일대 +일등 +일반 +일본 +일부 +일상 +일생 +일손 +일요일 +일월 +일정 +일종 +일주일 +일찍 +일체 +일치 +일행 +일회용 +임금 +임무 +입대 +입력 +입맛 +입사 +입술 +입시 +입원 +입장 +입학 +자가용 +자격 +자극 +자동 +자랑 +자부심 +자식 +자신 +자연 +자원 +자율 +자전거 +자정 +자존심 +자판 +작가 +작년 +작성 +작업 +작용 +작은딸 +작품 +잔디 +잔뜩 +잔치 +잘못 +잠깐 +잠수함 +잠시 +잠옷 +잠자리 +잡지 +장관 +장군 +장기간 +장래 +장례 +장르 +장마 +장면 +장모 +장미 +장비 +장사 +장소 +장식 +장애인 +장인 +장점 +장차 +장학금 +재능 +재빨리 +재산 +재생 +재작년 +재정 +재채기 +재판 +재학 +재활용 +저것 +저고리 +저곳 +저녁 +저런 +저렇게 +저번 +저울 +저절로 +저축 +적극 +적당히 +적성 +적용 +적응 +전개 +전공 +전기 +전달 +전라도 +전망 +전문 +전반 +전부 +전세 +전시 +전용 +전자 +전쟁 +전주 +전철 +전체 +전통 +전혀 +전후 +절대 +절망 +절반 +절약 +절차 +점검 +점수 +점심 +점원 +점점 +점차 +접근 +접시 +접촉 +젓가락 +정거장 +정도 +정류장 +정리 +정말 +정면 +정문 +정반대 +정보 +정부 +정비 +정상 +정성 +정오 +정원 +정장 +정지 +정치 +정확히 +제공 +제과점 +제대로 +제목 +제발 +제법 +제삿날 +제안 +제일 +제작 +제주도 +제출 +제품 +제한 +조각 +조건 +조금 +조깅 +조명 +조미료 +조상 +조선 +조용히 +조절 +조정 +조직 +존댓말 +존재 +졸업 +졸음 +종교 +종로 +종류 +종소리 +종업원 +종종 +종합 +좌석 +죄인 +주관적 +주름 +주말 +주머니 +주먹 +주문 +주민 +주방 +주변 +주식 +주인 +주일 +주장 +주전자 +주택 +준비 +줄거리 +줄기 +줄무늬 +중간 +중계방송 +중국 +중년 +중단 +중독 +중반 +중부 +중세 +중소기업 +중순 +중앙 +중요 +중학교 +즉석 +즉시 +즐거움 +증가 +증거 +증권 +증상 +증세 +지각 +지갑 +지경 +지극히 +지금 +지급 +지능 +지름길 +지리산 +지방 +지붕 +지식 +지역 +지우개 +지원 +지적 +지점 +지진 +지출 +직선 +직업 +직원 +직장 +진급 +진동 +진로 +진료 +진리 +진짜 +진찰 +진출 +진통 +진행 +질문 +질병 +질서 +짐작 +집단 +집안 +집중 +짜증 +찌꺼기 +차남 +차라리 +차량 +차림 +차별 +차선 +차츰 +착각 +찬물 +찬성 +참가 +참기름 +참새 +참석 +참여 +참외 +참조 +찻잔 +창가 +창고 +창구 +창문 +창밖 +창작 +창조 +채널 +채점 +책가방 +책방 +책상 +책임 +챔피언 +처벌 +처음 +천국 +천둥 +천장 +천재 +천천히 +철도 +철저히 +철학 +첫날 +첫째 +청년 +청바지 +청소 +청춘 +체계 +체력 +체온 +체육 +체중 +체험 +초등학생 +초반 +초밥 +초상화 +초순 +초여름 +초원 +초저녁 +초점 +초청 +초콜릿 +촛불 +총각 +총리 +총장 +촬영 +최근 +최상 +최선 +최신 +최악 +최종 +추석 +추억 +추진 +추천 +추측 +축구 +축소 +축제 +축하 +출근 +출발 +출산 +출신 +출연 +출입 +출장 +출판 +충격 +충고 +충돌 +충분히 +충청도 +취업 +취직 +취향 +치약 +친구 +친척 +칠십 +칠월 +칠판 +침대 +침묵 +침실 +칫솔 +칭찬 +카메라 +카운터 +칼국수 +캐릭터 +캠퍼스 +캠페인 +커튼 +컨디션 +컬러 +컴퓨터 +코끼리 +코미디 +콘서트 +콜라 +콤플렉스 +콩나물 +쾌감 +쿠데타 +크림 +큰길 +큰딸 +큰소리 +큰아들 +큰어머니 +큰일 +큰절 +클래식 +클럽 +킬로 +타입 +타자기 +탁구 +탁자 +탄생 +태권도 +태양 +태풍 +택시 +탤런트 +터널 +터미널 +테니스 +테스트 +테이블 +텔레비전 +토론 +토마토 +토요일 +통계 +통과 +통로 +통신 +통역 +통일 +통장 +통제 +통증 +통합 +통화 +퇴근 +퇴원 +퇴직금 +튀김 +트럭 +특급 +특별 +특성 +특수 +특징 +특히 +튼튼히 +티셔츠 +파란색 +파일 +파출소 +판결 +판단 +판매 +판사 +팔십 +팔월 +팝송 +패션 +팩스 +팩시밀리 +팬티 +퍼센트 +페인트 +편견 +편의 +편지 +편히 +평가 +평균 +평생 +평소 +평양 +평일 +평화 +포스터 +포인트 +포장 +포함 +표면 +표정 +표준 +표현 +품목 +품질 +풍경 +풍속 +풍습 +프랑스 +프린터 +플라스틱 +피곤 +피망 +피아노 +필름 +필수 +필요 +필자 +필통 +핑계 +하느님 +하늘 +하드웨어 +하룻밤 +하반기 +하숙집 +하순 +하여튼 +하지만 +하천 +하품 +하필 +학과 +학교 +학급 +학기 +학년 +학력 +학번 +학부모 +학비 +학생 +학술 +학습 +학용품 +학원 +학위 +학자 +학점 +한계 +한글 +한꺼번에 +한낮 +한눈 +한동안 +한때 +한라산 +한마디 +한문 +한번 +한복 +한식 +한여름 +한쪽 +할머니 +할아버지 +할인 +함께 +함부로 +합격 +합리적 +항공 +항구 +항상 +항의 +해결 +해군 +해답 +해당 +해물 +해석 +해설 +해수욕장 +해안 +핵심 +핸드백 +햄버거 +햇볕 +햇살 +행동 +행복 +행사 +행운 +행위 +향기 +향상 +향수 +허락 +허용 +헬기 +현관 +현금 +현대 +현상 +현실 +현장 +현재 +현지 +혈액 +협력 +형부 +형사 +형수 +형식 +형제 +형태 +형편 +혜택 +호기심 +호남 +호랑이 +호박 +호텔 +호흡 +혹시 +홀로 +홈페이지 +홍보 +홍수 +홍차 +화면 +화분 +화살 +화요일 +화장 +화학 +확보 +확인 +확장 +확정 +환갑 +환경 +환영 +환율 +환자 +활기 +활동 +활발히 +활용 +활짝 +회견 +회관 +회복 +회색 +회원 +회장 +회전 +횟수 +횡단보도 +효율적 +후반 +후춧가루 +훈련 +훨씬 +휴식 +휴일 +흉내 +흐름 +흑백 +흑인 +흔적 +흔히 +흥미 +흥분 +희곡 +희망 +희생 +흰색 +힘껏`.split('\n'); +//# sourceMappingURL=korean.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/esm/wordlists/korean.js.map b/node_modules/@scure/bip39/esm/wordlists/korean.js.map new file mode 100644 index 0000000..082def0 --- /dev/null +++ b/node_modules/@scure/bip39/esm/wordlists/korean.js.map @@ -0,0 +1 @@ +{"version":3,"file":"korean.js","sourceRoot":"","sources":["../../src/wordlists/korean.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,QAAQ,GAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA+/D3B,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip39/esm/wordlists/simplified-chinese.js b/node_modules/@scure/bip39/esm/wordlists/simplified-chinese.js new file mode 100644 index 0000000..bb5512d --- /dev/null +++ b/node_modules/@scure/bip39/esm/wordlists/simplified-chinese.js @@ -0,0 +1,2049 @@ +export const wordlist = `的 +一 +是 +在 +不 +了 +有 +和 +人 +这 +中 +大 +为 +上 +个 +国 +我 +以 +要 +他 +时 +来 +用 +们 +生 +到 +作 +地 +于 +出 +就 +分 +对 +成 +会 +可 +主 +发 +年 +动 +同 +工 +也 +能 +下 +过 +子 +说 +产 +种 +面 +而 +方 +后 +多 +定 +行 +学 +法 +所 +民 +得 +经 +十 +三 +之 +进 +着 +等 +部 +度 +家 +电 +力 +里 +如 +水 +化 +高 +自 +二 +理 +起 +小 +物 +现 +实 +加 +量 +都 +两 +体 +制 +机 +当 +使 +点 +从 +业 +本 +去 +把 +性 +好 +应 +开 +它 +合 +还 +因 +由 +其 +些 +然 +前 +外 +天 +政 +四 +日 +那 +社 +义 +事 +平 +形 +相 +全 +表 +间 +样 +与 +关 +各 +重 +新 +线 +内 +数 +正 +心 +反 +你 +明 +看 +原 +又 +么 +利 +比 +或 +但 +质 +气 +第 +向 +道 +命 +此 +变 +条 +只 +没 +结 +解 +问 +意 +建 +月 +公 +无 +系 +军 +很 +情 +者 +最 +立 +代 +想 +已 +通 +并 +提 +直 +题 +党 +程 +展 +五 +果 +料 +象 +员 +革 +位 +入 +常 +文 +总 +次 +品 +式 +活 +设 +及 +管 +特 +件 +长 +求 +老 +头 +基 +资 +边 +流 +路 +级 +少 +图 +山 +统 +接 +知 +较 +将 +组 +见 +计 +别 +她 +手 +角 +期 +根 +论 +运 +农 +指 +几 +九 +区 +强 +放 +决 +西 +被 +干 +做 +必 +战 +先 +回 +则 +任 +取 +据 +处 +队 +南 +给 +色 +光 +门 +即 +保 +治 +北 +造 +百 +规 +热 +领 +七 +海 +口 +东 +导 +器 +压 +志 +世 +金 +增 +争 +济 +阶 +油 +思 +术 +极 +交 +受 +联 +什 +认 +六 +共 +权 +收 +证 +改 +清 +美 +再 +采 +转 +更 +单 +风 +切 +打 +白 +教 +速 +花 +带 +安 +场 +身 +车 +例 +真 +务 +具 +万 +每 +目 +至 +达 +走 +积 +示 +议 +声 +报 +斗 +完 +类 +八 +离 +华 +名 +确 +才 +科 +张 +信 +马 +节 +话 +米 +整 +空 +元 +况 +今 +集 +温 +传 +土 +许 +步 +群 +广 +石 +记 +需 +段 +研 +界 +拉 +林 +律 +叫 +且 +究 +观 +越 +织 +装 +影 +算 +低 +持 +音 +众 +书 +布 +复 +容 +儿 +须 +际 +商 +非 +验 +连 +断 +深 +难 +近 +矿 +千 +周 +委 +素 +技 +备 +半 +办 +青 +省 +列 +习 +响 +约 +支 +般 +史 +感 +劳 +便 +团 +往 +酸 +历 +市 +克 +何 +除 +消 +构 +府 +称 +太 +准 +精 +值 +号 +率 +族 +维 +划 +选 +标 +写 +存 +候 +毛 +亲 +快 +效 +斯 +院 +查 +江 +型 +眼 +王 +按 +格 +养 +易 +置 +派 +层 +片 +始 +却 +专 +状 +育 +厂 +京 +识 +适 +属 +圆 +包 +火 +住 +调 +满 +县 +局 +照 +参 +红 +细 +引 +听 +该 +铁 +价 +严 +首 +底 +液 +官 +德 +随 +病 +苏 +失 +尔 +死 +讲 +配 +女 +黄 +推 +显 +谈 +罪 +神 +艺 +呢 +席 +含 +企 +望 +密 +批 +营 +项 +防 +举 +球 +英 +氧 +势 +告 +李 +台 +落 +木 +帮 +轮 +破 +亚 +师 +围 +注 +远 +字 +材 +排 +供 +河 +态 +封 +另 +施 +减 +树 +溶 +怎 +止 +案 +言 +士 +均 +武 +固 +叶 +鱼 +波 +视 +仅 +费 +紧 +爱 +左 +章 +早 +朝 +害 +续 +轻 +服 +试 +食 +充 +兵 +源 +判 +护 +司 +足 +某 +练 +差 +致 +板 +田 +降 +黑 +犯 +负 +击 +范 +继 +兴 +似 +余 +坚 +曲 +输 +修 +故 +城 +夫 +够 +送 +笔 +船 +占 +右 +财 +吃 +富 +春 +职 +觉 +汉 +画 +功 +巴 +跟 +虽 +杂 +飞 +检 +吸 +助 +升 +阳 +互 +初 +创 +抗 +考 +投 +坏 +策 +古 +径 +换 +未 +跑 +留 +钢 +曾 +端 +责 +站 +简 +述 +钱 +副 +尽 +帝 +射 +草 +冲 +承 +独 +令 +限 +阿 +宣 +环 +双 +请 +超 +微 +让 +控 +州 +良 +轴 +找 +否 +纪 +益 +依 +优 +顶 +础 +载 +倒 +房 +突 +坐 +粉 +敌 +略 +客 +袁 +冷 +胜 +绝 +析 +块 +剂 +测 +丝 +协 +诉 +念 +陈 +仍 +罗 +盐 +友 +洋 +错 +苦 +夜 +刑 +移 +频 +逐 +靠 +混 +母 +短 +皮 +终 +聚 +汽 +村 +云 +哪 +既 +距 +卫 +停 +烈 +央 +察 +烧 +迅 +境 +若 +印 +洲 +刻 +括 +激 +孔 +搞 +甚 +室 +待 +核 +校 +散 +侵 +吧 +甲 +游 +久 +菜 +味 +旧 +模 +湖 +货 +损 +预 +阻 +毫 +普 +稳 +乙 +妈 +植 +息 +扩 +银 +语 +挥 +酒 +守 +拿 +序 +纸 +医 +缺 +雨 +吗 +针 +刘 +啊 +急 +唱 +误 +训 +愿 +审 +附 +获 +茶 +鲜 +粮 +斤 +孩 +脱 +硫 +肥 +善 +龙 +演 +父 +渐 +血 +欢 +械 +掌 +歌 +沙 +刚 +攻 +谓 +盾 +讨 +晚 +粒 +乱 +燃 +矛 +乎 +杀 +药 +宁 +鲁 +贵 +钟 +煤 +读 +班 +伯 +香 +介 +迫 +句 +丰 +培 +握 +兰 +担 +弦 +蛋 +沉 +假 +穿 +执 +答 +乐 +谁 +顺 +烟 +缩 +征 +脸 +喜 +松 +脚 +困 +异 +免 +背 +星 +福 +买 +染 +井 +概 +慢 +怕 +磁 +倍 +祖 +皇 +促 +静 +补 +评 +翻 +肉 +践 +尼 +衣 +宽 +扬 +棉 +希 +伤 +操 +垂 +秋 +宜 +氢 +套 +督 +振 +架 +亮 +末 +宪 +庆 +编 +牛 +触 +映 +雷 +销 +诗 +座 +居 +抓 +裂 +胞 +呼 +娘 +景 +威 +绿 +晶 +厚 +盟 +衡 +鸡 +孙 +延 +危 +胶 +屋 +乡 +临 +陆 +顾 +掉 +呀 +灯 +岁 +措 +束 +耐 +剧 +玉 +赵 +跳 +哥 +季 +课 +凯 +胡 +额 +款 +绍 +卷 +齐 +伟 +蒸 +殖 +永 +宗 +苗 +川 +炉 +岩 +弱 +零 +杨 +奏 +沿 +露 +杆 +探 +滑 +镇 +饭 +浓 +航 +怀 +赶 +库 +夺 +伊 +灵 +税 +途 +灭 +赛 +归 +召 +鼓 +播 +盘 +裁 +险 +康 +唯 +录 +菌 +纯 +借 +糖 +盖 +横 +符 +私 +努 +堂 +域 +枪 +润 +幅 +哈 +竟 +熟 +虫 +泽 +脑 +壤 +碳 +欧 +遍 +侧 +寨 +敢 +彻 +虑 +斜 +薄 +庭 +纳 +弹 +饲 +伸 +折 +麦 +湿 +暗 +荷 +瓦 +塞 +床 +筑 +恶 +户 +访 +塔 +奇 +透 +梁 +刀 +旋 +迹 +卡 +氯 +遇 +份 +毒 +泥 +退 +洗 +摆 +灰 +彩 +卖 +耗 +夏 +择 +忙 +铜 +献 +硬 +予 +繁 +圈 +雪 +函 +亦 +抽 +篇 +阵 +阴 +丁 +尺 +追 +堆 +雄 +迎 +泛 +爸 +楼 +避 +谋 +吨 +野 +猪 +旗 +累 +偏 +典 +馆 +索 +秦 +脂 +潮 +爷 +豆 +忽 +托 +惊 +塑 +遗 +愈 +朱 +替 +纤 +粗 +倾 +尚 +痛 +楚 +谢 +奋 +购 +磨 +君 +池 +旁 +碎 +骨 +监 +捕 +弟 +暴 +割 +贯 +殊 +释 +词 +亡 +壁 +顿 +宝 +午 +尘 +闻 +揭 +炮 +残 +冬 +桥 +妇 +警 +综 +招 +吴 +付 +浮 +遭 +徐 +您 +摇 +谷 +赞 +箱 +隔 +订 +男 +吹 +园 +纷 +唐 +败 +宋 +玻 +巨 +耕 +坦 +荣 +闭 +湾 +键 +凡 +驻 +锅 +救 +恩 +剥 +凝 +碱 +齿 +截 +炼 +麻 +纺 +禁 +废 +盛 +版 +缓 +净 +睛 +昌 +婚 +涉 +筒 +嘴 +插 +岸 +朗 +庄 +街 +藏 +姑 +贸 +腐 +奴 +啦 +惯 +乘 +伙 +恢 +匀 +纱 +扎 +辩 +耳 +彪 +臣 +亿 +璃 +抵 +脉 +秀 +萨 +俄 +网 +舞 +店 +喷 +纵 +寸 +汗 +挂 +洪 +贺 +闪 +柬 +爆 +烯 +津 +稻 +墙 +软 +勇 +像 +滚 +厘 +蒙 +芳 +肯 +坡 +柱 +荡 +腿 +仪 +旅 +尾 +轧 +冰 +贡 +登 +黎 +削 +钻 +勒 +逃 +障 +氨 +郭 +峰 +币 +港 +伏 +轨 +亩 +毕 +擦 +莫 +刺 +浪 +秘 +援 +株 +健 +售 +股 +岛 +甘 +泡 +睡 +童 +铸 +汤 +阀 +休 +汇 +舍 +牧 +绕 +炸 +哲 +磷 +绩 +朋 +淡 +尖 +启 +陷 +柴 +呈 +徒 +颜 +泪 +稍 +忘 +泵 +蓝 +拖 +洞 +授 +镜 +辛 +壮 +锋 +贫 +虚 +弯 +摩 +泰 +幼 +廷 +尊 +窗 +纲 +弄 +隶 +疑 +氏 +宫 +姐 +震 +瑞 +怪 +尤 +琴 +循 +描 +膜 +违 +夹 +腰 +缘 +珠 +穷 +森 +枝 +竹 +沟 +催 +绳 +忆 +邦 +剩 +幸 +浆 +栏 +拥 +牙 +贮 +礼 +滤 +钠 +纹 +罢 +拍 +咱 +喊 +袖 +埃 +勤 +罚 +焦 +潜 +伍 +墨 +欲 +缝 +姓 +刊 +饱 +仿 +奖 +铝 +鬼 +丽 +跨 +默 +挖 +链 +扫 +喝 +袋 +炭 +污 +幕 +诸 +弧 +励 +梅 +奶 +洁 +灾 +舟 +鉴 +苯 +讼 +抱 +毁 +懂 +寒 +智 +埔 +寄 +届 +跃 +渡 +挑 +丹 +艰 +贝 +碰 +拔 +爹 +戴 +码 +梦 +芽 +熔 +赤 +渔 +哭 +敬 +颗 +奔 +铅 +仲 +虎 +稀 +妹 +乏 +珍 +申 +桌 +遵 +允 +隆 +螺 +仓 +魏 +锐 +晓 +氮 +兼 +隐 +碍 +赫 +拨 +忠 +肃 +缸 +牵 +抢 +博 +巧 +壳 +兄 +杜 +讯 +诚 +碧 +祥 +柯 +页 +巡 +矩 +悲 +灌 +龄 +伦 +票 +寻 +桂 +铺 +圣 +恐 +恰 +郑 +趣 +抬 +荒 +腾 +贴 +柔 +滴 +猛 +阔 +辆 +妻 +填 +撤 +储 +签 +闹 +扰 +紫 +砂 +递 +戏 +吊 +陶 +伐 +喂 +疗 +瓶 +婆 +抚 +臂 +摸 +忍 +虾 +蜡 +邻 +胸 +巩 +挤 +偶 +弃 +槽 +劲 +乳 +邓 +吉 +仁 +烂 +砖 +租 +乌 +舰 +伴 +瓜 +浅 +丙 +暂 +燥 +橡 +柳 +迷 +暖 +牌 +秧 +胆 +详 +簧 +踏 +瓷 +谱 +呆 +宾 +糊 +洛 +辉 +愤 +竞 +隙 +怒 +粘 +乃 +绪 +肩 +籍 +敏 +涂 +熙 +皆 +侦 +悬 +掘 +享 +纠 +醒 +狂 +锁 +淀 +恨 +牲 +霸 +爬 +赏 +逆 +玩 +陵 +祝 +秒 +浙 +貌 +役 +彼 +悉 +鸭 +趋 +凤 +晨 +畜 +辈 +秩 +卵 +署 +梯 +炎 +滩 +棋 +驱 +筛 +峡 +冒 +啥 +寿 +译 +浸 +泉 +帽 +迟 +硅 +疆 +贷 +漏 +稿 +冠 +嫩 +胁 +芯 +牢 +叛 +蚀 +奥 +鸣 +岭 +羊 +凭 +串 +塘 +绘 +酵 +融 +盆 +锡 +庙 +筹 +冻 +辅 +摄 +袭 +筋 +拒 +僚 +旱 +钾 +鸟 +漆 +沈 +眉 +疏 +添 +棒 +穗 +硝 +韩 +逼 +扭 +侨 +凉 +挺 +碗 +栽 +炒 +杯 +患 +馏 +劝 +豪 +辽 +勃 +鸿 +旦 +吏 +拜 +狗 +埋 +辊 +掩 +饮 +搬 +骂 +辞 +勾 +扣 +估 +蒋 +绒 +雾 +丈 +朵 +姆 +拟 +宇 +辑 +陕 +雕 +偿 +蓄 +崇 +剪 +倡 +厅 +咬 +驶 +薯 +刷 +斥 +番 +赋 +奉 +佛 +浇 +漫 +曼 +扇 +钙 +桃 +扶 +仔 +返 +俗 +亏 +腔 +鞋 +棱 +覆 +框 +悄 +叔 +撞 +骗 +勘 +旺 +沸 +孤 +吐 +孟 +渠 +屈 +疾 +妙 +惜 +仰 +狠 +胀 +谐 +抛 +霉 +桑 +岗 +嘛 +衰 +盗 +渗 +脏 +赖 +涌 +甜 +曹 +阅 +肌 +哩 +厉 +烃 +纬 +毅 +昨 +伪 +症 +煮 +叹 +钉 +搭 +茎 +笼 +酷 +偷 +弓 +锥 +恒 +杰 +坑 +鼻 +翼 +纶 +叙 +狱 +逮 +罐 +络 +棚 +抑 +膨 +蔬 +寺 +骤 +穆 +冶 +枯 +册 +尸 +凸 +绅 +坯 +牺 +焰 +轰 +欣 +晋 +瘦 +御 +锭 +锦 +丧 +旬 +锻 +垄 +搜 +扑 +邀 +亭 +酯 +迈 +舒 +脆 +酶 +闲 +忧 +酚 +顽 +羽 +涨 +卸 +仗 +陪 +辟 +惩 +杭 +姚 +肚 +捉 +飘 +漂 +昆 +欺 +吾 +郎 +烷 +汁 +呵 +饰 +萧 +雅 +邮 +迁 +燕 +撒 +姻 +赴 +宴 +烦 +债 +帐 +斑 +铃 +旨 +醇 +董 +饼 +雏 +姿 +拌 +傅 +腹 +妥 +揉 +贤 +拆 +歪 +葡 +胺 +丢 +浩 +徽 +昂 +垫 +挡 +览 +贪 +慰 +缴 +汪 +慌 +冯 +诺 +姜 +谊 +凶 +劣 +诬 +耀 +昏 +躺 +盈 +骑 +乔 +溪 +丛 +卢 +抹 +闷 +咨 +刮 +驾 +缆 +悟 +摘 +铒 +掷 +颇 +幻 +柄 +惠 +惨 +佳 +仇 +腊 +窝 +涤 +剑 +瞧 +堡 +泼 +葱 +罩 +霍 +捞 +胎 +苍 +滨 +俩 +捅 +湘 +砍 +霞 +邵 +萄 +疯 +淮 +遂 +熊 +粪 +烘 +宿 +档 +戈 +驳 +嫂 +裕 +徙 +箭 +捐 +肠 +撑 +晒 +辨 +殿 +莲 +摊 +搅 +酱 +屏 +疫 +哀 +蔡 +堵 +沫 +皱 +畅 +叠 +阁 +莱 +敲 +辖 +钩 +痕 +坝 +巷 +饿 +祸 +丘 +玄 +溜 +曰 +逻 +彭 +尝 +卿 +妨 +艇 +吞 +韦 +怨 +矮 +歇`.split('\n'); +//# sourceMappingURL=simplified-chinese.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/esm/wordlists/simplified-chinese.js.map b/node_modules/@scure/bip39/esm/wordlists/simplified-chinese.js.map new file mode 100644 index 0000000..99ab9ca --- /dev/null +++ b/node_modules/@scure/bip39/esm/wordlists/simplified-chinese.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simplified-chinese.js","sourceRoot":"","sources":["../../src/wordlists/simplified-chinese.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,QAAQ,GAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+/DhC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip39/esm/wordlists/spanish.js b/node_modules/@scure/bip39/esm/wordlists/spanish.js new file mode 100644 index 0000000..afd6c53 --- /dev/null +++ b/node_modules/@scure/bip39/esm/wordlists/spanish.js @@ -0,0 +1,2049 @@ +export const wordlist = `ábaco +abdomen +abeja +abierto +abogado +abono +aborto +abrazo +abrir +abuelo +abuso +acabar +academia +acceso +acción +aceite +acelga +acento +aceptar +ácido +aclarar +acné +acoger +acoso +activo +acto +actriz +actuar +acudir +acuerdo +acusar +adicto +admitir +adoptar +adorno +aduana +adulto +aéreo +afectar +afición +afinar +afirmar +ágil +agitar +agonía +agosto +agotar +agregar +agrio +agua +agudo +águila +aguja +ahogo +ahorro +aire +aislar +ajedrez +ajeno +ajuste +alacrán +alambre +alarma +alba +álbum +alcalde +aldea +alegre +alejar +alerta +aleta +alfiler +alga +algodón +aliado +aliento +alivio +alma +almeja +almíbar +altar +alteza +altivo +alto +altura +alumno +alzar +amable +amante +amapola +amargo +amasar +ámbar +ámbito +ameno +amigo +amistad +amor +amparo +amplio +ancho +anciano +ancla +andar +andén +anemia +ángulo +anillo +ánimo +anís +anotar +antena +antiguo +antojo +anual +anular +anuncio +añadir +añejo +año +apagar +aparato +apetito +apio +aplicar +apodo +aporte +apoyo +aprender +aprobar +apuesta +apuro +arado +araña +arar +árbitro +árbol +arbusto +archivo +arco +arder +ardilla +arduo +área +árido +aries +armonía +arnés +aroma +arpa +arpón +arreglo +arroz +arruga +arte +artista +asa +asado +asalto +ascenso +asegurar +aseo +asesor +asiento +asilo +asistir +asno +asombro +áspero +astilla +astro +astuto +asumir +asunto +atajo +ataque +atar +atento +ateo +ático +atleta +átomo +atraer +atroz +atún +audaz +audio +auge +aula +aumento +ausente +autor +aval +avance +avaro +ave +avellana +avena +avestruz +avión +aviso +ayer +ayuda +ayuno +azafrán +azar +azote +azúcar +azufre +azul +baba +babor +bache +bahía +baile +bajar +balanza +balcón +balde +bambú +banco +banda +baño +barba +barco +barniz +barro +báscula +bastón +basura +batalla +batería +batir +batuta +baúl +bazar +bebé +bebida +bello +besar +beso +bestia +bicho +bien +bingo +blanco +bloque +blusa +boa +bobina +bobo +boca +bocina +boda +bodega +boina +bola +bolero +bolsa +bomba +bondad +bonito +bono +bonsái +borde +borrar +bosque +bote +botín +bóveda +bozal +bravo +brazo +brecha +breve +brillo +brinco +brisa +broca +broma +bronce +brote +bruja +brusco +bruto +buceo +bucle +bueno +buey +bufanda +bufón +búho +buitre +bulto +burbuja +burla +burro +buscar +butaca +buzón +caballo +cabeza +cabina +cabra +cacao +cadáver +cadena +caer +café +caída +caimán +caja +cajón +cal +calamar +calcio +caldo +calidad +calle +calma +calor +calvo +cama +cambio +camello +camino +campo +cáncer +candil +canela +canguro +canica +canto +caña +cañón +caoba +caos +capaz +capitán +capote +captar +capucha +cara +carbón +cárcel +careta +carga +cariño +carne +carpeta +carro +carta +casa +casco +casero +caspa +castor +catorce +catre +caudal +causa +cazo +cebolla +ceder +cedro +celda +célebre +celoso +célula +cemento +ceniza +centro +cerca +cerdo +cereza +cero +cerrar +certeza +césped +cetro +chacal +chaleco +champú +chancla +chapa +charla +chico +chiste +chivo +choque +choza +chuleta +chupar +ciclón +ciego +cielo +cien +cierto +cifra +cigarro +cima +cinco +cine +cinta +ciprés +circo +ciruela +cisne +cita +ciudad +clamor +clan +claro +clase +clave +cliente +clima +clínica +cobre +cocción +cochino +cocina +coco +código +codo +cofre +coger +cohete +cojín +cojo +cola +colcha +colegio +colgar +colina +collar +colmo +columna +combate +comer +comida +cómodo +compra +conde +conejo +conga +conocer +consejo +contar +copa +copia +corazón +corbata +corcho +cordón +corona +correr +coser +cosmos +costa +cráneo +cráter +crear +crecer +creído +crema +cría +crimen +cripta +crisis +cromo +crónica +croqueta +crudo +cruz +cuadro +cuarto +cuatro +cubo +cubrir +cuchara +cuello +cuento +cuerda +cuesta +cueva +cuidar +culebra +culpa +culto +cumbre +cumplir +cuna +cuneta +cuota +cupón +cúpula +curar +curioso +curso +curva +cutis +dama +danza +dar +dardo +dátil +deber +débil +década +decir +dedo +defensa +definir +dejar +delfín +delgado +delito +demora +denso +dental +deporte +derecho +derrota +desayuno +deseo +desfile +desnudo +destino +desvío +detalle +detener +deuda +día +diablo +diadema +diamante +diana +diario +dibujo +dictar +diente +dieta +diez +difícil +digno +dilema +diluir +dinero +directo +dirigir +disco +diseño +disfraz +diva +divino +doble +doce +dolor +domingo +don +donar +dorado +dormir +dorso +dos +dosis +dragón +droga +ducha +duda +duelo +dueño +dulce +dúo +duque +durar +dureza +duro +ébano +ebrio +echar +eco +ecuador +edad +edición +edificio +editor +educar +efecto +eficaz +eje +ejemplo +elefante +elegir +elemento +elevar +elipse +élite +elixir +elogio +eludir +embudo +emitir +emoción +empate +empeño +empleo +empresa +enano +encargo +enchufe +encía +enemigo +enero +enfado +enfermo +engaño +enigma +enlace +enorme +enredo +ensayo +enseñar +entero +entrar +envase +envío +época +equipo +erizo +escala +escena +escolar +escribir +escudo +esencia +esfera +esfuerzo +espada +espejo +espía +esposa +espuma +esquí +estar +este +estilo +estufa +etapa +eterno +ética +etnia +evadir +evaluar +evento +evitar +exacto +examen +exceso +excusa +exento +exigir +exilio +existir +éxito +experto +explicar +exponer +extremo +fábrica +fábula +fachada +fácil +factor +faena +faja +falda +fallo +falso +faltar +fama +familia +famoso +faraón +farmacia +farol +farsa +fase +fatiga +fauna +favor +fax +febrero +fecha +feliz +feo +feria +feroz +fértil +fervor +festín +fiable +fianza +fiar +fibra +ficción +ficha +fideo +fiebre +fiel +fiera +fiesta +figura +fijar +fijo +fila +filete +filial +filtro +fin +finca +fingir +finito +firma +flaco +flauta +flecha +flor +flota +fluir +flujo +flúor +fobia +foca +fogata +fogón +folio +folleto +fondo +forma +forro +fortuna +forzar +fosa +foto +fracaso +frágil +franja +frase +fraude +freír +freno +fresa +frío +frito +fruta +fuego +fuente +fuerza +fuga +fumar +función +funda +furgón +furia +fusil +fútbol +futuro +gacela +gafas +gaita +gajo +gala +galería +gallo +gamba +ganar +gancho +ganga +ganso +garaje +garza +gasolina +gastar +gato +gavilán +gemelo +gemir +gen +género +genio +gente +geranio +gerente +germen +gesto +gigante +gimnasio +girar +giro +glaciar +globo +gloria +gol +golfo +goloso +golpe +goma +gordo +gorila +gorra +gota +goteo +gozar +grada +gráfico +grano +grasa +gratis +grave +grieta +grillo +gripe +gris +grito +grosor +grúa +grueso +grumo +grupo +guante +guapo +guardia +guerra +guía +guiño +guion +guiso +guitarra +gusano +gustar +haber +hábil +hablar +hacer +hacha +hada +hallar +hamaca +harina +haz +hazaña +hebilla +hebra +hecho +helado +helio +hembra +herir +hermano +héroe +hervir +hielo +hierro +hígado +higiene +hijo +himno +historia +hocico +hogar +hoguera +hoja +hombre +hongo +honor +honra +hora +hormiga +horno +hostil +hoyo +hueco +huelga +huerta +hueso +huevo +huida +huir +humano +húmedo +humilde +humo +hundir +huracán +hurto +icono +ideal +idioma +ídolo +iglesia +iglú +igual +ilegal +ilusión +imagen +imán +imitar +impar +imperio +imponer +impulso +incapaz +índice +inerte +infiel +informe +ingenio +inicio +inmenso +inmune +innato +insecto +instante +interés +íntimo +intuir +inútil +invierno +ira +iris +ironía +isla +islote +jabalí +jabón +jamón +jarabe +jardín +jarra +jaula +jazmín +jefe +jeringa +jinete +jornada +joroba +joven +joya +juerga +jueves +juez +jugador +jugo +juguete +juicio +junco +jungla +junio +juntar +júpiter +jurar +justo +juvenil +juzgar +kilo +koala +labio +lacio +lacra +lado +ladrón +lagarto +lágrima +laguna +laico +lamer +lámina +lámpara +lana +lancha +langosta +lanza +lápiz +largo +larva +lástima +lata +látex +latir +laurel +lavar +lazo +leal +lección +leche +lector +leer +legión +legumbre +lejano +lengua +lento +leña +león +leopardo +lesión +letal +letra +leve +leyenda +libertad +libro +licor +líder +lidiar +lienzo +liga +ligero +lima +límite +limón +limpio +lince +lindo +línea +lingote +lino +linterna +líquido +liso +lista +litera +litio +litro +llaga +llama +llanto +llave +llegar +llenar +llevar +llorar +llover +lluvia +lobo +loción +loco +locura +lógica +logro +lombriz +lomo +lonja +lote +lucha +lucir +lugar +lujo +luna +lunes +lupa +lustro +luto +luz +maceta +macho +madera +madre +maduro +maestro +mafia +magia +mago +maíz +maldad +maleta +malla +malo +mamá +mambo +mamut +manco +mando +manejar +manga +maniquí +manjar +mano +manso +manta +mañana +mapa +máquina +mar +marco +marea +marfil +margen +marido +mármol +marrón +martes +marzo +masa +máscara +masivo +matar +materia +matiz +matriz +máximo +mayor +mazorca +mecha +medalla +medio +médula +mejilla +mejor +melena +melón +memoria +menor +mensaje +mente +menú +mercado +merengue +mérito +mes +mesón +meta +meter +método +metro +mezcla +miedo +miel +miembro +miga +mil +milagro +militar +millón +mimo +mina +minero +mínimo +minuto +miope +mirar +misa +miseria +misil +mismo +mitad +mito +mochila +moción +moda +modelo +moho +mojar +molde +moler +molino +momento +momia +monarca +moneda +monja +monto +moño +morada +morder +moreno +morir +morro +morsa +mortal +mosca +mostrar +motivo +mover +móvil +mozo +mucho +mudar +mueble +muela +muerte +muestra +mugre +mujer +mula +muleta +multa +mundo +muñeca +mural +muro +músculo +museo +musgo +música +muslo +nácar +nación +nadar +naipe +naranja +nariz +narrar +nasal +natal +nativo +natural +náusea +naval +nave +navidad +necio +néctar +negar +negocio +negro +neón +nervio +neto +neutro +nevar +nevera +nicho +nido +niebla +nieto +niñez +niño +nítido +nivel +nobleza +noche +nómina +noria +norma +norte +nota +noticia +novato +novela +novio +nube +nuca +núcleo +nudillo +nudo +nuera +nueve +nuez +nulo +número +nutria +oasis +obeso +obispo +objeto +obra +obrero +observar +obtener +obvio +oca +ocaso +océano +ochenta +ocho +ocio +ocre +octavo +octubre +oculto +ocupar +ocurrir +odiar +odio +odisea +oeste +ofensa +oferta +oficio +ofrecer +ogro +oído +oír +ojo +ola +oleada +olfato +olivo +olla +olmo +olor +olvido +ombligo +onda +onza +opaco +opción +ópera +opinar +oponer +optar +óptica +opuesto +oración +orador +oral +órbita +orca +orden +oreja +órgano +orgía +orgullo +oriente +origen +orilla +oro +orquesta +oruga +osadía +oscuro +osezno +oso +ostra +otoño +otro +oveja +óvulo +óxido +oxígeno +oyente +ozono +pacto +padre +paella +página +pago +país +pájaro +palabra +palco +paleta +pálido +palma +paloma +palpar +pan +panal +pánico +pantera +pañuelo +papá +papel +papilla +paquete +parar +parcela +pared +parir +paro +párpado +parque +párrafo +parte +pasar +paseo +pasión +paso +pasta +pata +patio +patria +pausa +pauta +pavo +payaso +peatón +pecado +pecera +pecho +pedal +pedir +pegar +peine +pelar +peldaño +pelea +peligro +pellejo +pelo +peluca +pena +pensar +peñón +peón +peor +pepino +pequeño +pera +percha +perder +pereza +perfil +perico +perla +permiso +perro +persona +pesa +pesca +pésimo +pestaña +pétalo +petróleo +pez +pezuña +picar +pichón +pie +piedra +pierna +pieza +pijama +pilar +piloto +pimienta +pino +pintor +pinza +piña +piojo +pipa +pirata +pisar +piscina +piso +pista +pitón +pizca +placa +plan +plata +playa +plaza +pleito +pleno +plomo +pluma +plural +pobre +poco +poder +podio +poema +poesía +poeta +polen +policía +pollo +polvo +pomada +pomelo +pomo +pompa +poner +porción +portal +posada +poseer +posible +poste +potencia +potro +pozo +prado +precoz +pregunta +premio +prensa +preso +previo +primo +príncipe +prisión +privar +proa +probar +proceso +producto +proeza +profesor +programa +prole +promesa +pronto +propio +próximo +prueba +público +puchero +pudor +pueblo +puerta +puesto +pulga +pulir +pulmón +pulpo +pulso +puma +punto +puñal +puño +pupa +pupila +puré +quedar +queja +quemar +querer +queso +quieto +química +quince +quitar +rábano +rabia +rabo +ración +radical +raíz +rama +rampa +rancho +rango +rapaz +rápido +rapto +rasgo +raspa +rato +rayo +raza +razón +reacción +realidad +rebaño +rebote +recaer +receta +rechazo +recoger +recreo +recto +recurso +red +redondo +reducir +reflejo +reforma +refrán +refugio +regalo +regir +regla +regreso +rehén +reino +reír +reja +relato +relevo +relieve +relleno +reloj +remar +remedio +remo +rencor +rendir +renta +reparto +repetir +reposo +reptil +res +rescate +resina +respeto +resto +resumen +retiro +retorno +retrato +reunir +revés +revista +rey +rezar +rico +riego +rienda +riesgo +rifa +rígido +rigor +rincón +riñón +río +riqueza +risa +ritmo +rito +rizo +roble +roce +rociar +rodar +rodeo +rodilla +roer +rojizo +rojo +romero +romper +ron +ronco +ronda +ropa +ropero +rosa +rosca +rostro +rotar +rubí +rubor +rudo +rueda +rugir +ruido +ruina +ruleta +rulo +rumbo +rumor +ruptura +ruta +rutina +sábado +saber +sabio +sable +sacar +sagaz +sagrado +sala +saldo +salero +salir +salmón +salón +salsa +salto +salud +salvar +samba +sanción +sandía +sanear +sangre +sanidad +sano +santo +sapo +saque +sardina +sartén +sastre +satán +sauna +saxofón +sección +seco +secreto +secta +sed +seguir +seis +sello +selva +semana +semilla +senda +sensor +señal +señor +separar +sepia +sequía +ser +serie +sermón +servir +sesenta +sesión +seta +setenta +severo +sexo +sexto +sidra +siesta +siete +siglo +signo +sílaba +silbar +silencio +silla +símbolo +simio +sirena +sistema +sitio +situar +sobre +socio +sodio +sol +solapa +soldado +soledad +sólido +soltar +solución +sombra +sondeo +sonido +sonoro +sonrisa +sopa +soplar +soporte +sordo +sorpresa +sorteo +sostén +sótano +suave +subir +suceso +sudor +suegra +suelo +sueño +suerte +sufrir +sujeto +sultán +sumar +superar +suplir +suponer +supremo +sur +surco +sureño +surgir +susto +sutil +tabaco +tabique +tabla +tabú +taco +tacto +tajo +talar +talco +talento +talla +talón +tamaño +tambor +tango +tanque +tapa +tapete +tapia +tapón +taquilla +tarde +tarea +tarifa +tarjeta +tarot +tarro +tarta +tatuaje +tauro +taza +tazón +teatro +techo +tecla +técnica +tejado +tejer +tejido +tela +teléfono +tema +temor +templo +tenaz +tender +tener +tenis +tenso +teoría +terapia +terco +término +ternura +terror +tesis +tesoro +testigo +tetera +texto +tez +tibio +tiburón +tiempo +tienda +tierra +tieso +tigre +tijera +tilde +timbre +tímido +timo +tinta +tío +típico +tipo +tira +tirón +titán +títere +título +tiza +toalla +tobillo +tocar +tocino +todo +toga +toldo +tomar +tono +tonto +topar +tope +toque +tórax +torero +tormenta +torneo +toro +torpedo +torre +torso +tortuga +tos +tosco +toser +tóxico +trabajo +tractor +traer +tráfico +trago +traje +tramo +trance +trato +trauma +trazar +trébol +tregua +treinta +tren +trepar +tres +tribu +trigo +tripa +triste +triunfo +trofeo +trompa +tronco +tropa +trote +trozo +truco +trueno +trufa +tubería +tubo +tuerto +tumba +tumor +túnel +túnica +turbina +turismo +turno +tutor +ubicar +úlcera +umbral +unidad +unir +universo +uno +untar +uña +urbano +urbe +urgente +urna +usar +usuario +útil +utopía +uva +vaca +vacío +vacuna +vagar +vago +vaina +vajilla +vale +válido +valle +valor +válvula +vampiro +vara +variar +varón +vaso +vecino +vector +vehículo +veinte +vejez +vela +velero +veloz +vena +vencer +venda +veneno +vengar +venir +venta +venus +ver +verano +verbo +verde +vereda +verja +verso +verter +vía +viaje +vibrar +vicio +víctima +vida +vídeo +vidrio +viejo +viernes +vigor +vil +villa +vinagre +vino +viñedo +violín +viral +virgo +virtud +visor +víspera +vista +vitamina +viudo +vivaz +vivero +vivir +vivo +volcán +volumen +volver +voraz +votar +voto +voz +vuelo +vulgar +yacer +yate +yegua +yema +yerno +yeso +yodo +yoga +yogur +zafiro +zanja +zapato +zarza +zona +zorro +zumo +zurdo`.split('\n'); +//# sourceMappingURL=spanish.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/esm/wordlists/spanish.js.map b/node_modules/@scure/bip39/esm/wordlists/spanish.js.map new file mode 100644 index 0000000..46c5704 --- /dev/null +++ b/node_modules/@scure/bip39/esm/wordlists/spanish.js.map @@ -0,0 +1 @@ +{"version":3,"file":"spanish.js","sourceRoot":"","sources":["../../src/wordlists/spanish.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,QAAQ,GAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MA+/D5B,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip39/esm/wordlists/traditional-chinese.js b/node_modules/@scure/bip39/esm/wordlists/traditional-chinese.js new file mode 100644 index 0000000..82ca23c --- /dev/null +++ b/node_modules/@scure/bip39/esm/wordlists/traditional-chinese.js @@ -0,0 +1,2049 @@ +export const wordlist = `的 +一 +是 +在 +不 +了 +有 +和 +人 +這 +中 +大 +為 +上 +個 +國 +我 +以 +要 +他 +時 +來 +用 +們 +生 +到 +作 +地 +於 +出 +就 +分 +對 +成 +會 +可 +主 +發 +年 +動 +同 +工 +也 +能 +下 +過 +子 +說 +產 +種 +面 +而 +方 +後 +多 +定 +行 +學 +法 +所 +民 +得 +經 +十 +三 +之 +進 +著 +等 +部 +度 +家 +電 +力 +裡 +如 +水 +化 +高 +自 +二 +理 +起 +小 +物 +現 +實 +加 +量 +都 +兩 +體 +制 +機 +當 +使 +點 +從 +業 +本 +去 +把 +性 +好 +應 +開 +它 +合 +還 +因 +由 +其 +些 +然 +前 +外 +天 +政 +四 +日 +那 +社 +義 +事 +平 +形 +相 +全 +表 +間 +樣 +與 +關 +各 +重 +新 +線 +內 +數 +正 +心 +反 +你 +明 +看 +原 +又 +麼 +利 +比 +或 +但 +質 +氣 +第 +向 +道 +命 +此 +變 +條 +只 +沒 +結 +解 +問 +意 +建 +月 +公 +無 +系 +軍 +很 +情 +者 +最 +立 +代 +想 +已 +通 +並 +提 +直 +題 +黨 +程 +展 +五 +果 +料 +象 +員 +革 +位 +入 +常 +文 +總 +次 +品 +式 +活 +設 +及 +管 +特 +件 +長 +求 +老 +頭 +基 +資 +邊 +流 +路 +級 +少 +圖 +山 +統 +接 +知 +較 +將 +組 +見 +計 +別 +她 +手 +角 +期 +根 +論 +運 +農 +指 +幾 +九 +區 +強 +放 +決 +西 +被 +幹 +做 +必 +戰 +先 +回 +則 +任 +取 +據 +處 +隊 +南 +給 +色 +光 +門 +即 +保 +治 +北 +造 +百 +規 +熱 +領 +七 +海 +口 +東 +導 +器 +壓 +志 +世 +金 +增 +爭 +濟 +階 +油 +思 +術 +極 +交 +受 +聯 +什 +認 +六 +共 +權 +收 +證 +改 +清 +美 +再 +採 +轉 +更 +單 +風 +切 +打 +白 +教 +速 +花 +帶 +安 +場 +身 +車 +例 +真 +務 +具 +萬 +每 +目 +至 +達 +走 +積 +示 +議 +聲 +報 +鬥 +完 +類 +八 +離 +華 +名 +確 +才 +科 +張 +信 +馬 +節 +話 +米 +整 +空 +元 +況 +今 +集 +溫 +傳 +土 +許 +步 +群 +廣 +石 +記 +需 +段 +研 +界 +拉 +林 +律 +叫 +且 +究 +觀 +越 +織 +裝 +影 +算 +低 +持 +音 +眾 +書 +布 +复 +容 +兒 +須 +際 +商 +非 +驗 +連 +斷 +深 +難 +近 +礦 +千 +週 +委 +素 +技 +備 +半 +辦 +青 +省 +列 +習 +響 +約 +支 +般 +史 +感 +勞 +便 +團 +往 +酸 +歷 +市 +克 +何 +除 +消 +構 +府 +稱 +太 +準 +精 +值 +號 +率 +族 +維 +劃 +選 +標 +寫 +存 +候 +毛 +親 +快 +效 +斯 +院 +查 +江 +型 +眼 +王 +按 +格 +養 +易 +置 +派 +層 +片 +始 +卻 +專 +狀 +育 +廠 +京 +識 +適 +屬 +圓 +包 +火 +住 +調 +滿 +縣 +局 +照 +參 +紅 +細 +引 +聽 +該 +鐵 +價 +嚴 +首 +底 +液 +官 +德 +隨 +病 +蘇 +失 +爾 +死 +講 +配 +女 +黃 +推 +顯 +談 +罪 +神 +藝 +呢 +席 +含 +企 +望 +密 +批 +營 +項 +防 +舉 +球 +英 +氧 +勢 +告 +李 +台 +落 +木 +幫 +輪 +破 +亞 +師 +圍 +注 +遠 +字 +材 +排 +供 +河 +態 +封 +另 +施 +減 +樹 +溶 +怎 +止 +案 +言 +士 +均 +武 +固 +葉 +魚 +波 +視 +僅 +費 +緊 +愛 +左 +章 +早 +朝 +害 +續 +輕 +服 +試 +食 +充 +兵 +源 +判 +護 +司 +足 +某 +練 +差 +致 +板 +田 +降 +黑 +犯 +負 +擊 +范 +繼 +興 +似 +餘 +堅 +曲 +輸 +修 +故 +城 +夫 +夠 +送 +筆 +船 +佔 +右 +財 +吃 +富 +春 +職 +覺 +漢 +畫 +功 +巴 +跟 +雖 +雜 +飛 +檢 +吸 +助 +昇 +陽 +互 +初 +創 +抗 +考 +投 +壞 +策 +古 +徑 +換 +未 +跑 +留 +鋼 +曾 +端 +責 +站 +簡 +述 +錢 +副 +盡 +帝 +射 +草 +衝 +承 +獨 +令 +限 +阿 +宣 +環 +雙 +請 +超 +微 +讓 +控 +州 +良 +軸 +找 +否 +紀 +益 +依 +優 +頂 +礎 +載 +倒 +房 +突 +坐 +粉 +敵 +略 +客 +袁 +冷 +勝 +絕 +析 +塊 +劑 +測 +絲 +協 +訴 +念 +陳 +仍 +羅 +鹽 +友 +洋 +錯 +苦 +夜 +刑 +移 +頻 +逐 +靠 +混 +母 +短 +皮 +終 +聚 +汽 +村 +雲 +哪 +既 +距 +衛 +停 +烈 +央 +察 +燒 +迅 +境 +若 +印 +洲 +刻 +括 +激 +孔 +搞 +甚 +室 +待 +核 +校 +散 +侵 +吧 +甲 +遊 +久 +菜 +味 +舊 +模 +湖 +貨 +損 +預 +阻 +毫 +普 +穩 +乙 +媽 +植 +息 +擴 +銀 +語 +揮 +酒 +守 +拿 +序 +紙 +醫 +缺 +雨 +嗎 +針 +劉 +啊 +急 +唱 +誤 +訓 +願 +審 +附 +獲 +茶 +鮮 +糧 +斤 +孩 +脫 +硫 +肥 +善 +龍 +演 +父 +漸 +血 +歡 +械 +掌 +歌 +沙 +剛 +攻 +謂 +盾 +討 +晚 +粒 +亂 +燃 +矛 +乎 +殺 +藥 +寧 +魯 +貴 +鐘 +煤 +讀 +班 +伯 +香 +介 +迫 +句 +豐 +培 +握 +蘭 +擔 +弦 +蛋 +沉 +假 +穿 +執 +答 +樂 +誰 +順 +煙 +縮 +徵 +臉 +喜 +松 +腳 +困 +異 +免 +背 +星 +福 +買 +染 +井 +概 +慢 +怕 +磁 +倍 +祖 +皇 +促 +靜 +補 +評 +翻 +肉 +踐 +尼 +衣 +寬 +揚 +棉 +希 +傷 +操 +垂 +秋 +宜 +氫 +套 +督 +振 +架 +亮 +末 +憲 +慶 +編 +牛 +觸 +映 +雷 +銷 +詩 +座 +居 +抓 +裂 +胞 +呼 +娘 +景 +威 +綠 +晶 +厚 +盟 +衡 +雞 +孫 +延 +危 +膠 +屋 +鄉 +臨 +陸 +顧 +掉 +呀 +燈 +歲 +措 +束 +耐 +劇 +玉 +趙 +跳 +哥 +季 +課 +凱 +胡 +額 +款 +紹 +卷 +齊 +偉 +蒸 +殖 +永 +宗 +苗 +川 +爐 +岩 +弱 +零 +楊 +奏 +沿 +露 +桿 +探 +滑 +鎮 +飯 +濃 +航 +懷 +趕 +庫 +奪 +伊 +靈 +稅 +途 +滅 +賽 +歸 +召 +鼓 +播 +盤 +裁 +險 +康 +唯 +錄 +菌 +純 +借 +糖 +蓋 +橫 +符 +私 +努 +堂 +域 +槍 +潤 +幅 +哈 +竟 +熟 +蟲 +澤 +腦 +壤 +碳 +歐 +遍 +側 +寨 +敢 +徹 +慮 +斜 +薄 +庭 +納 +彈 +飼 +伸 +折 +麥 +濕 +暗 +荷 +瓦 +塞 +床 +築 +惡 +戶 +訪 +塔 +奇 +透 +梁 +刀 +旋 +跡 +卡 +氯 +遇 +份 +毒 +泥 +退 +洗 +擺 +灰 +彩 +賣 +耗 +夏 +擇 +忙 +銅 +獻 +硬 +予 +繁 +圈 +雪 +函 +亦 +抽 +篇 +陣 +陰 +丁 +尺 +追 +堆 +雄 +迎 +泛 +爸 +樓 +避 +謀 +噸 +野 +豬 +旗 +累 +偏 +典 +館 +索 +秦 +脂 +潮 +爺 +豆 +忽 +托 +驚 +塑 +遺 +愈 +朱 +替 +纖 +粗 +傾 +尚 +痛 +楚 +謝 +奮 +購 +磨 +君 +池 +旁 +碎 +骨 +監 +捕 +弟 +暴 +割 +貫 +殊 +釋 +詞 +亡 +壁 +頓 +寶 +午 +塵 +聞 +揭 +炮 +殘 +冬 +橋 +婦 +警 +綜 +招 +吳 +付 +浮 +遭 +徐 +您 +搖 +谷 +贊 +箱 +隔 +訂 +男 +吹 +園 +紛 +唐 +敗 +宋 +玻 +巨 +耕 +坦 +榮 +閉 +灣 +鍵 +凡 +駐 +鍋 +救 +恩 +剝 +凝 +鹼 +齒 +截 +煉 +麻 +紡 +禁 +廢 +盛 +版 +緩 +淨 +睛 +昌 +婚 +涉 +筒 +嘴 +插 +岸 +朗 +莊 +街 +藏 +姑 +貿 +腐 +奴 +啦 +慣 +乘 +夥 +恢 +勻 +紗 +扎 +辯 +耳 +彪 +臣 +億 +璃 +抵 +脈 +秀 +薩 +俄 +網 +舞 +店 +噴 +縱 +寸 +汗 +掛 +洪 +賀 +閃 +柬 +爆 +烯 +津 +稻 +牆 +軟 +勇 +像 +滾 +厘 +蒙 +芳 +肯 +坡 +柱 +盪 +腿 +儀 +旅 +尾 +軋 +冰 +貢 +登 +黎 +削 +鑽 +勒 +逃 +障 +氨 +郭 +峰 +幣 +港 +伏 +軌 +畝 +畢 +擦 +莫 +刺 +浪 +秘 +援 +株 +健 +售 +股 +島 +甘 +泡 +睡 +童 +鑄 +湯 +閥 +休 +匯 +舍 +牧 +繞 +炸 +哲 +磷 +績 +朋 +淡 +尖 +啟 +陷 +柴 +呈 +徒 +顏 +淚 +稍 +忘 +泵 +藍 +拖 +洞 +授 +鏡 +辛 +壯 +鋒 +貧 +虛 +彎 +摩 +泰 +幼 +廷 +尊 +窗 +綱 +弄 +隸 +疑 +氏 +宮 +姐 +震 +瑞 +怪 +尤 +琴 +循 +描 +膜 +違 +夾 +腰 +緣 +珠 +窮 +森 +枝 +竹 +溝 +催 +繩 +憶 +邦 +剩 +幸 +漿 +欄 +擁 +牙 +貯 +禮 +濾 +鈉 +紋 +罷 +拍 +咱 +喊 +袖 +埃 +勤 +罰 +焦 +潛 +伍 +墨 +欲 +縫 +姓 +刊 +飽 +仿 +獎 +鋁 +鬼 +麗 +跨 +默 +挖 +鏈 +掃 +喝 +袋 +炭 +污 +幕 +諸 +弧 +勵 +梅 +奶 +潔 +災 +舟 +鑑 +苯 +訟 +抱 +毀 +懂 +寒 +智 +埔 +寄 +屆 +躍 +渡 +挑 +丹 +艱 +貝 +碰 +拔 +爹 +戴 +碼 +夢 +芽 +熔 +赤 +漁 +哭 +敬 +顆 +奔 +鉛 +仲 +虎 +稀 +妹 +乏 +珍 +申 +桌 +遵 +允 +隆 +螺 +倉 +魏 +銳 +曉 +氮 +兼 +隱 +礙 +赫 +撥 +忠 +肅 +缸 +牽 +搶 +博 +巧 +殼 +兄 +杜 +訊 +誠 +碧 +祥 +柯 +頁 +巡 +矩 +悲 +灌 +齡 +倫 +票 +尋 +桂 +鋪 +聖 +恐 +恰 +鄭 +趣 +抬 +荒 +騰 +貼 +柔 +滴 +猛 +闊 +輛 +妻 +填 +撤 +儲 +簽 +鬧 +擾 +紫 +砂 +遞 +戲 +吊 +陶 +伐 +餵 +療 +瓶 +婆 +撫 +臂 +摸 +忍 +蝦 +蠟 +鄰 +胸 +鞏 +擠 +偶 +棄 +槽 +勁 +乳 +鄧 +吉 +仁 +爛 +磚 +租 +烏 +艦 +伴 +瓜 +淺 +丙 +暫 +燥 +橡 +柳 +迷 +暖 +牌 +秧 +膽 +詳 +簧 +踏 +瓷 +譜 +呆 +賓 +糊 +洛 +輝 +憤 +競 +隙 +怒 +粘 +乃 +緒 +肩 +籍 +敏 +塗 +熙 +皆 +偵 +懸 +掘 +享 +糾 +醒 +狂 +鎖 +淀 +恨 +牲 +霸 +爬 +賞 +逆 +玩 +陵 +祝 +秒 +浙 +貌 +役 +彼 +悉 +鴨 +趨 +鳳 +晨 +畜 +輩 +秩 +卵 +署 +梯 +炎 +灘 +棋 +驅 +篩 +峽 +冒 +啥 +壽 +譯 +浸 +泉 +帽 +遲 +矽 +疆 +貸 +漏 +稿 +冠 +嫩 +脅 +芯 +牢 +叛 +蝕 +奧 +鳴 +嶺 +羊 +憑 +串 +塘 +繪 +酵 +融 +盆 +錫 +廟 +籌 +凍 +輔 +攝 +襲 +筋 +拒 +僚 +旱 +鉀 +鳥 +漆 +沈 +眉 +疏 +添 +棒 +穗 +硝 +韓 +逼 +扭 +僑 +涼 +挺 +碗 +栽 +炒 +杯 +患 +餾 +勸 +豪 +遼 +勃 +鴻 +旦 +吏 +拜 +狗 +埋 +輥 +掩 +飲 +搬 +罵 +辭 +勾 +扣 +估 +蔣 +絨 +霧 +丈 +朵 +姆 +擬 +宇 +輯 +陝 +雕 +償 +蓄 +崇 +剪 +倡 +廳 +咬 +駛 +薯 +刷 +斥 +番 +賦 +奉 +佛 +澆 +漫 +曼 +扇 +鈣 +桃 +扶 +仔 +返 +俗 +虧 +腔 +鞋 +棱 +覆 +框 +悄 +叔 +撞 +騙 +勘 +旺 +沸 +孤 +吐 +孟 +渠 +屈 +疾 +妙 +惜 +仰 +狠 +脹 +諧 +拋 +黴 +桑 +崗 +嘛 +衰 +盜 +滲 +臟 +賴 +湧 +甜 +曹 +閱 +肌 +哩 +厲 +烴 +緯 +毅 +昨 +偽 +症 +煮 +嘆 +釘 +搭 +莖 +籠 +酷 +偷 +弓 +錐 +恆 +傑 +坑 +鼻 +翼 +綸 +敘 +獄 +逮 +罐 +絡 +棚 +抑 +膨 +蔬 +寺 +驟 +穆 +冶 +枯 +冊 +屍 +凸 +紳 +坯 +犧 +焰 +轟 +欣 +晉 +瘦 +禦 +錠 +錦 +喪 +旬 +鍛 +壟 +搜 +撲 +邀 +亭 +酯 +邁 +舒 +脆 +酶 +閒 +憂 +酚 +頑 +羽 +漲 +卸 +仗 +陪 +闢 +懲 +杭 +姚 +肚 +捉 +飄 +漂 +昆 +欺 +吾 +郎 +烷 +汁 +呵 +飾 +蕭 +雅 +郵 +遷 +燕 +撒 +姻 +赴 +宴 +煩 +債 +帳 +斑 +鈴 +旨 +醇 +董 +餅 +雛 +姿 +拌 +傅 +腹 +妥 +揉 +賢 +拆 +歪 +葡 +胺 +丟 +浩 +徽 +昂 +墊 +擋 +覽 +貪 +慰 +繳 +汪 +慌 +馮 +諾 +姜 +誼 +兇 +劣 +誣 +耀 +昏 +躺 +盈 +騎 +喬 +溪 +叢 +盧 +抹 +悶 +諮 +刮 +駕 +纜 +悟 +摘 +鉺 +擲 +頗 +幻 +柄 +惠 +慘 +佳 +仇 +臘 +窩 +滌 +劍 +瞧 +堡 +潑 +蔥 +罩 +霍 +撈 +胎 +蒼 +濱 +倆 +捅 +湘 +砍 +霞 +邵 +萄 +瘋 +淮 +遂 +熊 +糞 +烘 +宿 +檔 +戈 +駁 +嫂 +裕 +徙 +箭 +捐 +腸 +撐 +曬 +辨 +殿 +蓮 +攤 +攪 +醬 +屏 +疫 +哀 +蔡 +堵 +沫 +皺 +暢 +疊 +閣 +萊 +敲 +轄 +鉤 +痕 +壩 +巷 +餓 +禍 +丘 +玄 +溜 +曰 +邏 +彭 +嘗 +卿 +妨 +艇 +吞 +韋 +怨 +矮 +歇`.split('\n'); +//# sourceMappingURL=traditional-chinese.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/esm/wordlists/traditional-chinese.js.map b/node_modules/@scure/bip39/esm/wordlists/traditional-chinese.js.map new file mode 100644 index 0000000..efa45e0 --- /dev/null +++ b/node_modules/@scure/bip39/esm/wordlists/traditional-chinese.js.map @@ -0,0 +1 @@ +{"version":3,"file":"traditional-chinese.js","sourceRoot":"","sources":["../../src/wordlists/traditional-chinese.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,QAAQ,GAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+/DhC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip39/index.d.ts b/node_modules/@scure/bip39/index.d.ts new file mode 100644 index 0000000..85cdb22 --- /dev/null +++ b/node_modules/@scure/bip39/index.d.ts @@ -0,0 +1,63 @@ +/** + * Generate x random words. Uses Cryptographically-Secure Random Number Generator. + * @param wordlist imported wordlist for specific language + * @param strength mnemonic strength 128-256 bits + * @example + * generateMnemonic(wordlist, 128) + * // 'legal winner thank year wave sausage worth useful legal winner thank yellow' + */ +export declare function generateMnemonic(wordlist: string[], strength?: number): string; +/** + * Reversible: Converts mnemonic string to raw entropy in form of byte array. + * @param mnemonic 12-24 words + * @param wordlist imported wordlist for specific language + * @example + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * mnemonicToEntropy(mnem, wordlist) + * // Produces + * new Uint8Array([ + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f + * ]) + */ +export declare function mnemonicToEntropy(mnemonic: string, wordlist: string[]): Uint8Array; +/** + * Reversible: Converts raw entropy in form of byte array to mnemonic string. + * @param entropy byte array + * @param wordlist imported wordlist for specific language + * @returns 12-24 words + * @example + * const ent = new Uint8Array([ + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f + * ]); + * entropyToMnemonic(ent, wordlist); + * // 'legal winner thank year wave sausage worth useful legal winner thank yellow' + */ +export declare function entropyToMnemonic(entropy: Uint8Array, wordlist: string[]): string; +/** + * Validates mnemonic for being 12-24 words contained in `wordlist`. + */ +export declare function validateMnemonic(mnemonic: string, wordlist: string[]): boolean; +/** + * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password. + * @param mnemonic 12-24 words + * @param passphrase string that will additionally protect the key + * @returns 64 bytes of key data + * @example + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * await mnemonicToSeed(mnem, 'password'); + * // new Uint8Array([...64 bytes]) + */ +export declare function mnemonicToSeed(mnemonic: string, passphrase?: string): Promise; +/** + * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password. + * @param mnemonic 12-24 words + * @param passphrase string that will additionally protect the key + * @returns 64 bytes of key data + * @example + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * mnemonicToSeedSync(mnem, 'password'); + * // new Uint8Array([...64 bytes]) + */ +export declare function mnemonicToSeedSync(mnemonic: string, passphrase?: string): Uint8Array; diff --git a/node_modules/@scure/bip39/index.js b/node_modules/@scure/bip39/index.js new file mode 100644 index 0000000..924ae10 --- /dev/null +++ b/node_modules/@scure/bip39/index.js @@ -0,0 +1,142 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.mnemonicToSeedSync = exports.mnemonicToSeed = exports.validateMnemonic = exports.entropyToMnemonic = exports.mnemonicToEntropy = exports.generateMnemonic = void 0; +/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */ +const _assert_1 = require("@noble/hashes/_assert"); +const pbkdf2_1 = require("@noble/hashes/pbkdf2"); +const sha256_1 = require("@noble/hashes/sha256"); +const sha512_1 = require("@noble/hashes/sha512"); +const utils_1 = require("@noble/hashes/utils"); +const base_1 = require("@scure/base"); +// Japanese wordlist +const isJapanese = (wordlist) => wordlist[0] === '\u3042\u3044\u3053\u304f\u3057\u3093'; +// Normalization replaces equivalent sequences of characters +// so that any two texts that are equivalent will be reduced +// to the same sequence of code points, called the normal form of the original text. +function nfkd(str) { + if (typeof str !== 'string') + throw new TypeError(`Invalid mnemonic type: ${typeof str}`); + return str.normalize('NFKD'); +} +function normalize(str) { + const norm = nfkd(str); + const words = norm.split(' '); + if (![12, 15, 18, 21, 24].includes(words.length)) + throw new Error('Invalid mnemonic'); + return { nfkd: norm, words }; +} +function assertEntropy(entropy) { + _assert_1.default.bytes(entropy, 16, 20, 24, 28, 32); +} +/** + * Generate x random words. Uses Cryptographically-Secure Random Number Generator. + * @param wordlist imported wordlist for specific language + * @param strength mnemonic strength 128-256 bits + * @example + * generateMnemonic(wordlist, 128) + * // 'legal winner thank year wave sausage worth useful legal winner thank yellow' + */ +function generateMnemonic(wordlist, strength = 128) { + _assert_1.default.number(strength); + if (strength % 32 !== 0 || strength > 256) + throw new TypeError('Invalid entropy'); + return entropyToMnemonic((0, utils_1.randomBytes)(strength / 8), wordlist); +} +exports.generateMnemonic = generateMnemonic; +const calcChecksum = (entropy) => { + // Checksum is ent.length/4 bits long + const bitsLeft = 8 - entropy.length / 4; + // Zero rightmost "bitsLeft" bits in byte + // For example: bitsLeft=4 val=10111101 -> 10110000 + return new Uint8Array([((0, sha256_1.sha256)(entropy)[0] >> bitsLeft) << bitsLeft]); +}; +function getCoder(wordlist) { + if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string') + throw new Error('Worlist: expected array of 2048 strings'); + wordlist.forEach((i) => { + if (typeof i !== 'string') + throw new Error(`Wordlist: non-string element: ${i}`); + }); + return base_1.utils.chain(base_1.utils.checksum(1, calcChecksum), base_1.utils.radix2(11, true), base_1.utils.alphabet(wordlist)); +} +/** + * Reversible: Converts mnemonic string to raw entropy in form of byte array. + * @param mnemonic 12-24 words + * @param wordlist imported wordlist for specific language + * @example + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * mnemonicToEntropy(mnem, wordlist) + * // Produces + * new Uint8Array([ + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f + * ]) + */ +function mnemonicToEntropy(mnemonic, wordlist) { + const { words } = normalize(mnemonic); + const entropy = getCoder(wordlist).decode(words); + assertEntropy(entropy); + return entropy; +} +exports.mnemonicToEntropy = mnemonicToEntropy; +/** + * Reversible: Converts raw entropy in form of byte array to mnemonic string. + * @param entropy byte array + * @param wordlist imported wordlist for specific language + * @returns 12-24 words + * @example + * const ent = new Uint8Array([ + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f + * ]); + * entropyToMnemonic(ent, wordlist); + * // 'legal winner thank year wave sausage worth useful legal winner thank yellow' + */ +function entropyToMnemonic(entropy, wordlist) { + assertEntropy(entropy); + const words = getCoder(wordlist).encode(entropy); + return words.join(isJapanese(wordlist) ? '\u3000' : ' '); +} +exports.entropyToMnemonic = entropyToMnemonic; +/** + * Validates mnemonic for being 12-24 words contained in `wordlist`. + */ +function validateMnemonic(mnemonic, wordlist) { + try { + mnemonicToEntropy(mnemonic, wordlist); + } + catch (e) { + return false; + } + return true; +} +exports.validateMnemonic = validateMnemonic; +const salt = (passphrase) => nfkd(`mnemonic${passphrase}`); +/** + * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password. + * @param mnemonic 12-24 words + * @param passphrase string that will additionally protect the key + * @returns 64 bytes of key data + * @example + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * await mnemonicToSeed(mnem, 'password'); + * // new Uint8Array([...64 bytes]) + */ +function mnemonicToSeed(mnemonic, passphrase = '') { + return (0, pbkdf2_1.pbkdf2Async)(sha512_1.sha512, normalize(mnemonic).nfkd, salt(passphrase), { c: 2048, dkLen: 64 }); +} +exports.mnemonicToSeed = mnemonicToSeed; +/** + * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password. + * @param mnemonic 12-24 words + * @param passphrase string that will additionally protect the key + * @returns 64 bytes of key data + * @example + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * mnemonicToSeedSync(mnem, 'password'); + * // new Uint8Array([...64 bytes]) + */ +function mnemonicToSeedSync(mnemonic, passphrase = '') { + return (0, pbkdf2_1.pbkdf2)(sha512_1.sha512, normalize(mnemonic).nfkd, salt(passphrase), { c: 2048, dkLen: 64 }); +} +exports.mnemonicToSeedSync = mnemonicToSeedSync; diff --git a/node_modules/@scure/bip39/package.json b/node_modules/@scure/bip39/package.json new file mode 100644 index 0000000..51102a9 --- /dev/null +++ b/node_modules/@scure/bip39/package.json @@ -0,0 +1,116 @@ +{ + "name": "@scure/bip39", + "version": "1.2.1", + "description": "Secure, audited & minimal implementation of BIP39 mnemonic phrases", + "main": "index.js", + "files": [ + "index.js", + "index.d.ts", + "wordlists/*.js", + "wordlists/*.d.ts", + "esm" + ], + "types": "index.d.ts", + "dependencies": { + "@noble/hashes": "~1.3.0", + "@scure/base": "~1.1.0" + }, + "devDependencies": { + "micro-should": "0.4.0", + "prettier": "2.8.4", + "typescript": "5.0.2" + }, + "author": "Paul Miller (https://paulmillr.com)", + "homepage": "https://paulmillr.com/", + "repository": { + "type": "git", + "url": "https://github.com/paulmillr/scure-bip39.git" + }, + "contributors": [ + { + "name": "Patricio Palladino", + "email": "patricio@nomiclabs.io" + }, + { + "name": "Paul Miller", + "url": "https://paulmillr.com" + } + ], + "license": "MIT", + "scripts": { + "build": "tsc && tsc -p tsconfig.esm.json", + "lint": "prettier --check 'src/**/*.ts' 'test/*.test.ts'", + "format": "prettier --write 'src/**/*.ts' 'test/*.test.ts'", + "test": "cd test && tsc && node bip39.test.js" + }, + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./esm/index.js", + "default": "./index.js" + }, + "./index": { + "types": "./index.d.ts", + "import": "./esm/index.js", + "default": "./index.js" + }, + "./wordlists/czech": { + "types": "./wordlists/czech.d.ts", + "import": "./esm/wordlists/czech.js", + "default": "./wordlists/czech.js" + }, + "./wordlists/english": { + "types": "./wordlists/english.d.ts", + "import": "./esm/wordlists/english.js", + "default": "./wordlists/english.js" + }, + "./wordlists/french": { + "types": "./wordlists/french.d.ts", + "import": "./esm/wordlists/french.js", + "default": "./wordlists/french.js" + }, + "./wordlists/italian": { + "types": "./wordlists/italian.d.ts", + "import": "./esm/wordlists/italian.js", + "default": "./wordlists/italian.js" + }, + "./wordlists/japanese": { + "types": "./wordlists/japanese.d.ts", + "import": "./esm/wordlists/japanese.js", + "default": "./wordlists/japanese.js" + }, + "./wordlists/korean": { + "types": "./wordlists/korean.d.ts", + "import": "./esm/wordlists/korean.js", + "default": "./wordlists/korean.js" + }, + "./wordlists/simplified-chinese": { + "types": "./wordlists/simplified-chinese.d.ts", + "import": "./esm/wordlists/simplified-chinese.js", + "default": "./wordlists/simplified-chinese.js" + }, + "./wordlists/spanish": { + "types": "./wordlists/spanish.d.ts", + "import": "./esm/wordlists/spanish.js", + "default": "./wordlists/spanish.js" + }, + "./wordlists/traditional-chinese": { + "types": "./wordlists/traditional-chinese.d.ts", + "import": "./esm/wordlists/traditional-chinese.js", + "default": "./wordlists/traditional-chinese.js" + } + }, + "keywords": [ + "bip39", + "mnemonic", + "phrase", + "code", + "bip0039", + "bip-39", + "micro", + "scure", + "wordlist", + "noble" + ], + "funding": "https://paulmillr.com/funding/" +} diff --git a/node_modules/@scure/bip39/wordlists/czech.d.ts b/node_modules/@scure/bip39/wordlists/czech.d.ts new file mode 100644 index 0000000..b566a1d --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/czech.d.ts @@ -0,0 +1 @@ +export declare const wordlist: string[]; diff --git a/node_modules/@scure/bip39/wordlists/czech.js b/node_modules/@scure/bip39/wordlists/czech.js new file mode 100644 index 0000000..0295622 --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/czech.js @@ -0,0 +1,2051 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +exports.wordlist = `abdikace +abeceda +adresa +agrese +akce +aktovka +alej +alkohol +amputace +ananas +andulka +anekdota +anketa +antika +anulovat +archa +arogance +asfalt +asistent +aspirace +astma +astronom +atlas +atletika +atol +autobus +azyl +babka +bachor +bacil +baculka +badatel +bageta +bagr +bahno +bakterie +balada +baletka +balkon +balonek +balvan +balza +bambus +bankomat +barbar +baret +barman +baroko +barva +baterka +batoh +bavlna +bazalka +bazilika +bazuka +bedna +beran +beseda +bestie +beton +bezinka +bezmoc +beztak +bicykl +bidlo +biftek +bikiny +bilance +biograf +biolog +bitva +bizon +blahobyt +blatouch +blecha +bledule +blesk +blikat +blizna +blokovat +bloudit +blud +bobek +bobr +bodlina +bodnout +bohatost +bojkot +bojovat +bokorys +bolest +borec +borovice +bota +boubel +bouchat +bouda +boule +bourat +boxer +bradavka +brambora +branka +bratr +brepta +briketa +brko +brloh +bronz +broskev +brunetka +brusinka +brzda +brzy +bublina +bubnovat +buchta +buditel +budka +budova +bufet +bujarost +bukvice +buldok +bulva +bunda +bunkr +burza +butik +buvol +buzola +bydlet +bylina +bytovka +bzukot +capart +carevna +cedr +cedule +cejch +cejn +cela +celer +celkem +celnice +cenina +cennost +cenovka +centrum +cenzor +cestopis +cetka +chalupa +chapadlo +charita +chata +chechtat +chemie +chichot +chirurg +chlad +chleba +chlubit +chmel +chmura +chobot +chochol +chodba +cholera +chomout +chopit +choroba +chov +chrapot +chrlit +chrt +chrup +chtivost +chudina +chutnat +chvat +chvilka +chvost +chyba +chystat +chytit +cibule +cigareta +cihelna +cihla +cinkot +cirkus +cisterna +citace +citrus +cizinec +cizost +clona +cokoliv +couvat +ctitel +ctnost +cudnost +cuketa +cukr +cupot +cvaknout +cval +cvik +cvrkot +cyklista +daleko +dareba +datel +datum +dcera +debata +dechovka +decibel +deficit +deflace +dekl +dekret +demokrat +deprese +derby +deska +detektiv +dikobraz +diktovat +dioda +diplom +disk +displej +divadlo +divoch +dlaha +dlouho +dluhopis +dnes +dobro +dobytek +docent +dochutit +dodnes +dohled +dohoda +dohra +dojem +dojnice +doklad +dokola +doktor +dokument +dolar +doleva +dolina +doma +dominant +domluvit +domov +donutit +dopad +dopis +doplnit +doposud +doprovod +dopustit +dorazit +dorost +dort +dosah +doslov +dostatek +dosud +dosyta +dotaz +dotek +dotknout +doufat +doutnat +dovozce +dozadu +doznat +dozorce +drahota +drak +dramatik +dravec +draze +drdol +drobnost +drogerie +drozd +drsnost +drtit +drzost +duben +duchovno +dudek +duha +duhovka +dusit +dusno +dutost +dvojice +dvorec +dynamit +ekolog +ekonomie +elektron +elipsa +email +emise +emoce +empatie +epizoda +epocha +epopej +epos +esej +esence +eskorta +eskymo +etiketa +euforie +evoluce +exekuce +exkurze +expedice +exploze +export +extrakt +facka +fajfka +fakulta +fanatik +fantazie +farmacie +favorit +fazole +federace +fejeton +fenka +fialka +figurant +filozof +filtr +finance +finta +fixace +fjord +flanel +flirt +flotila +fond +fosfor +fotbal +fotka +foton +frakce +freska +fronta +fukar +funkce +fyzika +galeje +garant +genetika +geolog +gilotina +glazura +glejt +golem +golfista +gotika +graf +gramofon +granule +grep +gril +grog +groteska +guma +hadice +hadr +hala +halenka +hanba +hanopis +harfa +harpuna +havran +hebkost +hejkal +hejno +hejtman +hektar +helma +hematom +herec +herna +heslo +hezky +historik +hladovka +hlasivky +hlava +hledat +hlen +hlodavec +hloh +hloupost +hltat +hlubina +hluchota +hmat +hmota +hmyz +hnis +hnojivo +hnout +hoblina +hoboj +hoch +hodiny +hodlat +hodnota +hodovat +hojnost +hokej +holinka +holka +holub +homole +honitba +honorace +horal +horda +horizont +horko +horlivec +hormon +hornina +horoskop +horstvo +hospoda +hostina +hotovost +houba +houf +houpat +houska +hovor +hradba +hranice +hravost +hrazda +hrbolek +hrdina +hrdlo +hrdost +hrnek +hrobka +hromada +hrot +hrouda +hrozen +hrstka +hrubost +hryzat +hubenost +hubnout +hudba +hukot +humr +husita +hustota +hvozd +hybnost +hydrant +hygiena +hymna +hysterik +idylka +ihned +ikona +iluze +imunita +infekce +inflace +inkaso +inovace +inspekce +internet +invalida +investor +inzerce +ironie +jablko +jachta +jahoda +jakmile +jakost +jalovec +jantar +jarmark +jaro +jasan +jasno +jatka +javor +jazyk +jedinec +jedle +jednatel +jehlan +jekot +jelen +jelito +jemnost +jenom +jepice +jeseter +jevit +jezdec +jezero +jinak +jindy +jinoch +jiskra +jistota +jitrnice +jizva +jmenovat +jogurt +jurta +kabaret +kabel +kabinet +kachna +kadet +kadidlo +kahan +kajak +kajuta +kakao +kaktus +kalamita +kalhoty +kalibr +kalnost +kamera +kamkoliv +kamna +kanibal +kanoe +kantor +kapalina +kapela +kapitola +kapka +kaple +kapota +kapr +kapusta +kapybara +karamel +karotka +karton +kasa +katalog +katedra +kauce +kauza +kavalec +kazajka +kazeta +kazivost +kdekoliv +kdesi +kedluben +kemp +keramika +kino +klacek +kladivo +klam +klapot +klasika +klaun +klec +klenba +klepat +klesnout +klid +klima +klisna +klobouk +klokan +klopa +kloub +klubovna +klusat +kluzkost +kmen +kmitat +kmotr +kniha +knot +koalice +koberec +kobka +kobliha +kobyla +kocour +kohout +kojenec +kokos +koktejl +kolaps +koleda +kolize +kolo +komando +kometa +komik +komnata +komora +kompas +komunita +konat +koncept +kondice +konec +konfese +kongres +konina +konkurs +kontakt +konzerva +kopanec +kopie +kopnout +koprovka +korbel +korektor +kormidlo +koroptev +korpus +koruna +koryto +korzet +kosatec +kostka +kotel +kotleta +kotoul +koukat +koupelna +kousek +kouzlo +kovboj +koza +kozoroh +krabice +krach +krajina +kralovat +krasopis +kravata +kredit +krejcar +kresba +kreveta +kriket +kritik +krize +krkavec +krmelec +krmivo +krocan +krok +kronika +kropit +kroupa +krovka +krtek +kruhadlo +krupice +krutost +krvinka +krychle +krypta +krystal +kryt +kudlanka +kufr +kujnost +kukla +kulajda +kulich +kulka +kulomet +kultura +kuna +kupodivu +kurt +kurzor +kutil +kvalita +kvasinka +kvestor +kynolog +kyselina +kytara +kytice +kytka +kytovec +kyvadlo +labrador +lachtan +ladnost +laik +lakomec +lamela +lampa +lanovka +lasice +laso +lastura +latinka +lavina +lebka +leckdy +leden +lednice +ledovka +ledvina +legenda +legie +legrace +lehce +lehkost +lehnout +lektvar +lenochod +lentilka +lepenka +lepidlo +letadlo +letec +letmo +letokruh +levhart +levitace +levobok +libra +lichotka +lidojed +lidskost +lihovina +lijavec +lilek +limetka +linie +linka +linoleum +listopad +litina +litovat +lobista +lodivod +logika +logoped +lokalita +loket +lomcovat +lopata +lopuch +lord +losos +lotr +loudal +louh +louka +louskat +lovec +lstivost +lucerna +lucifer +lump +lusk +lustrace +lvice +lyra +lyrika +lysina +madam +madlo +magistr +mahagon +majetek +majitel +majorita +makak +makovice +makrela +malba +malina +malovat +malvice +maminka +mandle +manko +marnost +masakr +maskot +masopust +matice +matrika +maturita +mazanec +mazivo +mazlit +mazurka +mdloba +mechanik +meditace +medovina +melasa +meloun +mentolka +metla +metoda +metr +mezera +migrace +mihnout +mihule +mikina +mikrofon +milenec +milimetr +milost +mimika +mincovna +minibar +minomet +minulost +miska +mistr +mixovat +mladost +mlha +mlhovina +mlok +mlsat +mluvit +mnich +mnohem +mobil +mocnost +modelka +modlitba +mohyla +mokro +molekula +momentka +monarcha +monokl +monstrum +montovat +monzun +mosaz +moskyt +most +motivace +motorka +motyka +moucha +moudrost +mozaika +mozek +mozol +mramor +mravenec +mrkev +mrtvola +mrzet +mrzutost +mstitel +mudrc +muflon +mulat +mumie +munice +muset +mutace +muzeum +muzikant +myslivec +mzda +nabourat +nachytat +nadace +nadbytek +nadhoz +nadobro +nadpis +nahlas +nahnat +nahodile +nahradit +naivita +najednou +najisto +najmout +naklonit +nakonec +nakrmit +nalevo +namazat +namluvit +nanometr +naoko +naopak +naostro +napadat +napevno +naplnit +napnout +naposled +naprosto +narodit +naruby +narychlo +nasadit +nasekat +naslepo +nastat +natolik +navenek +navrch +navzdory +nazvat +nebe +nechat +necky +nedaleko +nedbat +neduh +negace +nehet +nehoda +nejen +nejprve +neklid +nelibost +nemilost +nemoc +neochota +neonka +nepokoj +nerost +nerv +nesmysl +nesoulad +netvor +neuron +nevina +nezvykle +nicota +nijak +nikam +nikdy +nikl +nikterak +nitro +nocleh +nohavice +nominace +nora +norek +nositel +nosnost +nouze +noviny +novota +nozdra +nuda +nudle +nuget +nutit +nutnost +nutrie +nymfa +obal +obarvit +obava +obdiv +obec +obehnat +obejmout +obezita +obhajoba +obilnice +objasnit +objekt +obklopit +oblast +oblek +obliba +obloha +obluda +obnos +obohatit +obojek +obout +obrazec +obrna +obruba +obrys +obsah +obsluha +obstarat +obuv +obvaz +obvinit +obvod +obvykle +obyvatel +obzor +ocas +ocel +ocenit +ochladit +ochota +ochrana +ocitnout +odboj +odbyt +odchod +odcizit +odebrat +odeslat +odevzdat +odezva +odhadce +odhodit +odjet +odjinud +odkaz +odkoupit +odliv +odluka +odmlka +odolnost +odpad +odpis +odplout +odpor +odpustit +odpykat +odrazka +odsoudit +odstup +odsun +odtok +odtud +odvaha +odveta +odvolat +odvracet +odznak +ofina +ofsajd +ohlas +ohnisko +ohrada +ohrozit +ohryzek +okap +okenice +oklika +okno +okouzlit +okovy +okrasa +okres +okrsek +okruh +okupant +okurka +okusit +olejnina +olizovat +omak +omeleta +omezit +omladina +omlouvat +omluva +omyl +onehdy +opakovat +opasek +operace +opice +opilost +opisovat +opora +opozice +opravdu +oproti +orbital +orchestr +orgie +orlice +orloj +ortel +osada +oschnout +osika +osivo +oslava +oslepit +oslnit +oslovit +osnova +osoba +osolit +ospalec +osten +ostraha +ostuda +ostych +osvojit +oteplit +otisk +otop +otrhat +otrlost +otrok +otruby +otvor +ovanout +ovar +oves +ovlivnit +ovoce +oxid +ozdoba +pachatel +pacient +padouch +pahorek +pakt +palanda +palec +palivo +paluba +pamflet +pamlsek +panenka +panika +panna +panovat +panstvo +pantofle +paprika +parketa +parodie +parta +paruka +paryba +paseka +pasivita +pastelka +patent +patrona +pavouk +pazneht +pazourek +pecka +pedagog +pejsek +peklo +peloton +penalta +pendrek +penze +periskop +pero +pestrost +petarda +petice +petrolej +pevnina +pexeso +pianista +piha +pijavice +pikle +piknik +pilina +pilnost +pilulka +pinzeta +pipeta +pisatel +pistole +pitevna +pivnice +pivovar +placenta +plakat +plamen +planeta +plastika +platit +plavidlo +plaz +plech +plemeno +plenta +ples +pletivo +plevel +plivat +plnit +plno +plocha +plodina +plomba +plout +pluk +plyn +pobavit +pobyt +pochod +pocit +poctivec +podat +podcenit +podepsat +podhled +podivit +podklad +podmanit +podnik +podoba +podpora +podraz +podstata +podvod +podzim +poezie +pohanka +pohnutka +pohovor +pohroma +pohyb +pointa +pojistka +pojmout +pokazit +pokles +pokoj +pokrok +pokuta +pokyn +poledne +polibek +polknout +poloha +polynom +pomalu +pominout +pomlka +pomoc +pomsta +pomyslet +ponechat +ponorka +ponurost +popadat +popel +popisek +poplach +poprosit +popsat +popud +poradce +porce +porod +porucha +poryv +posadit +posed +posila +poskok +poslanec +posoudit +pospolu +postava +posudek +posyp +potah +potkan +potlesk +potomek +potrava +potupa +potvora +poukaz +pouto +pouzdro +povaha +povidla +povlak +povoz +povrch +povstat +povyk +povzdech +pozdrav +pozemek +poznatek +pozor +pozvat +pracovat +prahory +praktika +prales +praotec +praporek +prase +pravda +princip +prkno +probudit +procento +prodej +profese +prohra +projekt +prolomit +promile +pronikat +propad +prorok +prosba +proton +proutek +provaz +prskavka +prsten +prudkost +prut +prvek +prvohory +psanec +psovod +pstruh +ptactvo +puberta +puch +pudl +pukavec +puklina +pukrle +pult +pumpa +punc +pupen +pusa +pusinka +pustina +putovat +putyka +pyramida +pysk +pytel +racek +rachot +radiace +radnice +radon +raft +ragby +raketa +rakovina +rameno +rampouch +rande +rarach +rarita +rasovna +rastr +ratolest +razance +razidlo +reagovat +reakce +recept +redaktor +referent +reflex +rejnok +reklama +rekord +rekrut +rektor +reputace +revize +revma +revolver +rezerva +riskovat +riziko +robotika +rodokmen +rohovka +rokle +rokoko +romaneto +ropovod +ropucha +rorejs +rosol +rostlina +rotmistr +rotoped +rotunda +roubenka +roucho +roup +roura +rovina +rovnice +rozbor +rozchod +rozdat +rozeznat +rozhodce +rozinka +rozjezd +rozkaz +rozloha +rozmar +rozpad +rozruch +rozsah +roztok +rozum +rozvod +rubrika +ruchadlo +rukavice +rukopis +ryba +rybolov +rychlost +rydlo +rypadlo +rytina +ryzost +sadista +sahat +sako +samec +samizdat +samota +sanitka +sardinka +sasanka +satelit +sazba +sazenice +sbor +schovat +sebranka +secese +sedadlo +sediment +sedlo +sehnat +sejmout +sekera +sekta +sekunda +sekvoje +semeno +seno +servis +sesadit +seshora +seskok +seslat +sestra +sesuv +sesypat +setba +setina +setkat +setnout +setrvat +sever +seznam +shoda +shrnout +sifon +silnice +sirka +sirotek +sirup +situace +skafandr +skalisko +skanzen +skaut +skeptik +skica +skladba +sklenice +sklo +skluz +skoba +skokan +skoro +skripta +skrz +skupina +skvost +skvrna +slabika +sladidlo +slanina +slast +slavnost +sledovat +slepec +sleva +slezina +slib +slina +sliznice +slon +sloupek +slovo +sluch +sluha +slunce +slupka +slza +smaragd +smetana +smilstvo +smlouva +smog +smrad +smrk +smrtka +smutek +smysl +snad +snaha +snob +sobota +socha +sodovka +sokol +sopka +sotva +souboj +soucit +soudce +souhlas +soulad +soumrak +souprava +soused +soutok +souviset +spalovna +spasitel +spis +splav +spodek +spojenec +spolu +sponzor +spornost +spousta +sprcha +spustit +sranda +sraz +srdce +srna +srnec +srovnat +srpen +srst +srub +stanice +starosta +statika +stavba +stehno +stezka +stodola +stolek +stopa +storno +stoupat +strach +stres +strhnout +strom +struna +studna +stupnice +stvol +styk +subjekt +subtropy +suchar +sudost +sukno +sundat +sunout +surikata +surovina +svah +svalstvo +svetr +svatba +svazek +svisle +svitek +svoboda +svodidlo +svorka +svrab +sykavka +sykot +synek +synovec +sypat +sypkost +syrovost +sysel +sytost +tabletka +tabule +tahoun +tajemno +tajfun +tajga +tajit +tajnost +taktika +tamhle +tampon +tancovat +tanec +tanker +tapeta +tavenina +tazatel +technika +tehdy +tekutina +telefon +temnota +tendence +tenista +tenor +teplota +tepna +teprve +terapie +termoska +textil +ticho +tiskopis +titulek +tkadlec +tkanina +tlapka +tleskat +tlukot +tlupa +tmel +toaleta +topinka +topol +torzo +touha +toulec +tradice +traktor +tramp +trasa +traverza +trefit +trest +trezor +trhavina +trhlina +trochu +trojice +troska +trouba +trpce +trpitel +trpkost +trubec +truchlit +truhlice +trus +trvat +tudy +tuhnout +tuhost +tundra +turista +turnaj +tuzemsko +tvaroh +tvorba +tvrdost +tvrz +tygr +tykev +ubohost +uboze +ubrat +ubrousek +ubrus +ubytovna +ucho +uctivost +udivit +uhradit +ujednat +ujistit +ujmout +ukazatel +uklidnit +uklonit +ukotvit +ukrojit +ulice +ulita +ulovit +umyvadlo +unavit +uniforma +uniknout +upadnout +uplatnit +uplynout +upoutat +upravit +uran +urazit +usednout +usilovat +usmrtit +usnadnit +usnout +usoudit +ustlat +ustrnout +utahovat +utkat +utlumit +utonout +utopenec +utrousit +uvalit +uvolnit +uvozovka +uzdravit +uzel +uzenina +uzlina +uznat +vagon +valcha +valoun +vana +vandal +vanilka +varan +varhany +varovat +vcelku +vchod +vdova +vedro +vegetace +vejce +velbloud +veletrh +velitel +velmoc +velryba +venkov +veranda +verze +veselka +veskrze +vesnice +vespodu +vesta +veterina +veverka +vibrace +vichr +videohra +vidina +vidle +vila +vinice +viset +vitalita +vize +vizitka +vjezd +vklad +vkus +vlajka +vlak +vlasec +vlevo +vlhkost +vliv +vlnovka +vloupat +vnucovat +vnuk +voda +vodivost +vodoznak +vodstvo +vojensky +vojna +vojsko +volant +volba +volit +volno +voskovka +vozidlo +vozovna +vpravo +vrabec +vracet +vrah +vrata +vrba +vrcholek +vrhat +vrstva +vrtule +vsadit +vstoupit +vstup +vtip +vybavit +vybrat +vychovat +vydat +vydra +vyfotit +vyhledat +vyhnout +vyhodit +vyhradit +vyhubit +vyjasnit +vyjet +vyjmout +vyklopit +vykonat +vylekat +vymazat +vymezit +vymizet +vymyslet +vynechat +vynikat +vynutit +vypadat +vyplatit +vypravit +vypustit +vyrazit +vyrovnat +vyrvat +vyslovit +vysoko +vystavit +vysunout +vysypat +vytasit +vytesat +vytratit +vyvinout +vyvolat +vyvrhel +vyzdobit +vyznat +vzadu +vzbudit +vzchopit +vzdor +vzduch +vzdychat +vzestup +vzhledem +vzkaz +vzlykat +vznik +vzorek +vzpoura +vztah +vztek +xylofon +zabrat +zabydlet +zachovat +zadarmo +zadusit +zafoukat +zahltit +zahodit +zahrada +zahynout +zajatec +zajet +zajistit +zaklepat +zakoupit +zalepit +zamezit +zamotat +zamyslet +zanechat +zanikat +zaplatit +zapojit +zapsat +zarazit +zastavit +zasunout +zatajit +zatemnit +zatknout +zaujmout +zavalit +zavelet +zavinit +zavolat +zavrtat +zazvonit +zbavit +zbrusu +zbudovat +zbytek +zdaleka +zdarma +zdatnost +zdivo +zdobit +zdroj +zdvih +zdymadlo +zelenina +zeman +zemina +zeptat +zezadu +zezdola +zhatit +zhltnout +zhluboka +zhotovit +zhruba +zima +zimnice +zjemnit +zklamat +zkoumat +zkratka +zkumavka +zlato +zlehka +zloba +zlom +zlost +zlozvyk +zmapovat +zmar +zmatek +zmije +zmizet +zmocnit +zmodrat +zmrzlina +zmutovat +znak +znalost +znamenat +znovu +zobrazit +zotavit +zoubek +zoufale +zplodit +zpomalit +zprava +zprostit +zprudka +zprvu +zrada +zranit +zrcadlo +zrnitost +zrno +zrovna +zrychlit +zrzavost +zticha +ztratit +zubovina +zubr +zvednout +zvenku +zvesela +zvon +zvrat +zvukovod +zvyk`.split('\n'); diff --git a/node_modules/@scure/bip39/wordlists/english.d.ts b/node_modules/@scure/bip39/wordlists/english.d.ts new file mode 100644 index 0000000..b566a1d --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/english.d.ts @@ -0,0 +1 @@ +export declare const wordlist: string[]; diff --git a/node_modules/@scure/bip39/wordlists/english.js b/node_modules/@scure/bip39/wordlists/english.js new file mode 100644 index 0000000..10c9c19 --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/english.js @@ -0,0 +1,2051 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +exports.wordlist = `abandon +ability +able +about +above +absent +absorb +abstract +absurd +abuse +access +accident +account +accuse +achieve +acid +acoustic +acquire +across +act +action +actor +actress +actual +adapt +add +addict +address +adjust +admit +adult +advance +advice +aerobic +affair +afford +afraid +again +age +agent +agree +ahead +aim +air +airport +aisle +alarm +album +alcohol +alert +alien +all +alley +allow +almost +alone +alpha +already +also +alter +always +amateur +amazing +among +amount +amused +analyst +anchor +ancient +anger +angle +angry +animal +ankle +announce +annual +another +answer +antenna +antique +anxiety +any +apart +apology +appear +apple +approve +april +arch +arctic +area +arena +argue +arm +armed +armor +army +around +arrange +arrest +arrive +arrow +art +artefact +artist +artwork +ask +aspect +assault +asset +assist +assume +asthma +athlete +atom +attack +attend +attitude +attract +auction +audit +august +aunt +author +auto +autumn +average +avocado +avoid +awake +aware +away +awesome +awful +awkward +axis +baby +bachelor +bacon +badge +bag +balance +balcony +ball +bamboo +banana +banner +bar +barely +bargain +barrel +base +basic +basket +battle +beach +bean +beauty +because +become +beef +before +begin +behave +behind +believe +below +belt +bench +benefit +best +betray +better +between +beyond +bicycle +bid +bike +bind +biology +bird +birth +bitter +black +blade +blame +blanket +blast +bleak +bless +blind +blood +blossom +blouse +blue +blur +blush +board +boat +body +boil +bomb +bone +bonus +book +boost +border +boring +borrow +boss +bottom +bounce +box +boy +bracket +brain +brand +brass +brave +bread +breeze +brick +bridge +brief +bright +bring +brisk +broccoli +broken +bronze +broom +brother +brown +brush +bubble +buddy +budget +buffalo +build +bulb +bulk +bullet +bundle +bunker +burden +burger +burst +bus +business +busy +butter +buyer +buzz +cabbage +cabin +cable +cactus +cage +cake +call +calm +camera +camp +can +canal +cancel +candy +cannon +canoe +canvas +canyon +capable +capital +captain +car +carbon +card +cargo +carpet +carry +cart +case +cash +casino +castle +casual +cat +catalog +catch +category +cattle +caught +cause +caution +cave +ceiling +celery +cement +census +century +cereal +certain +chair +chalk +champion +change +chaos +chapter +charge +chase +chat +cheap +check +cheese +chef +cherry +chest +chicken +chief +child +chimney +choice +choose +chronic +chuckle +chunk +churn +cigar +cinnamon +circle +citizen +city +civil +claim +clap +clarify +claw +clay +clean +clerk +clever +click +client +cliff +climb +clinic +clip +clock +clog +close +cloth +cloud +clown +club +clump +cluster +clutch +coach +coast +coconut +code +coffee +coil +coin +collect +color +column +combine +come +comfort +comic +common +company +concert +conduct +confirm +congress +connect +consider +control +convince +cook +cool +copper +copy +coral +core +corn +correct +cost +cotton +couch +country +couple +course +cousin +cover +coyote +crack +cradle +craft +cram +crane +crash +crater +crawl +crazy +cream +credit +creek +crew +cricket +crime +crisp +critic +crop +cross +crouch +crowd +crucial +cruel +cruise +crumble +crunch +crush +cry +crystal +cube +culture +cup +cupboard +curious +current +curtain +curve +cushion +custom +cute +cycle +dad +damage +damp +dance +danger +daring +dash +daughter +dawn +day +deal +debate +debris +decade +december +decide +decline +decorate +decrease +deer +defense +define +defy +degree +delay +deliver +demand +demise +denial +dentist +deny +depart +depend +deposit +depth +deputy +derive +describe +desert +design +desk +despair +destroy +detail +detect +develop +device +devote +diagram +dial +diamond +diary +dice +diesel +diet +differ +digital +dignity +dilemma +dinner +dinosaur +direct +dirt +disagree +discover +disease +dish +dismiss +disorder +display +distance +divert +divide +divorce +dizzy +doctor +document +dog +doll +dolphin +domain +donate +donkey +donor +door +dose +double +dove +draft +dragon +drama +drastic +draw +dream +dress +drift +drill +drink +drip +drive +drop +drum +dry +duck +dumb +dune +during +dust +dutch +duty +dwarf +dynamic +eager +eagle +early +earn +earth +easily +east +easy +echo +ecology +economy +edge +edit +educate +effort +egg +eight +either +elbow +elder +electric +elegant +element +elephant +elevator +elite +else +embark +embody +embrace +emerge +emotion +employ +empower +empty +enable +enact +end +endless +endorse +enemy +energy +enforce +engage +engine +enhance +enjoy +enlist +enough +enrich +enroll +ensure +enter +entire +entry +envelope +episode +equal +equip +era +erase +erode +erosion +error +erupt +escape +essay +essence +estate +eternal +ethics +evidence +evil +evoke +evolve +exact +example +excess +exchange +excite +exclude +excuse +execute +exercise +exhaust +exhibit +exile +exist +exit +exotic +expand +expect +expire +explain +expose +express +extend +extra +eye +eyebrow +fabric +face +faculty +fade +faint +faith +fall +false +fame +family +famous +fan +fancy +fantasy +farm +fashion +fat +fatal +father +fatigue +fault +favorite +feature +february +federal +fee +feed +feel +female +fence +festival +fetch +fever +few +fiber +fiction +field +figure +file +film +filter +final +find +fine +finger +finish +fire +firm +first +fiscal +fish +fit +fitness +fix +flag +flame +flash +flat +flavor +flee +flight +flip +float +flock +floor +flower +fluid +flush +fly +foam +focus +fog +foil +fold +follow +food +foot +force +forest +forget +fork +fortune +forum +forward +fossil +foster +found +fox +fragile +frame +frequent +fresh +friend +fringe +frog +front +frost +frown +frozen +fruit +fuel +fun +funny +furnace +fury +future +gadget +gain +galaxy +gallery +game +gap +garage +garbage +garden +garlic +garment +gas +gasp +gate +gather +gauge +gaze +general +genius +genre +gentle +genuine +gesture +ghost +giant +gift +giggle +ginger +giraffe +girl +give +glad +glance +glare +glass +glide +glimpse +globe +gloom +glory +glove +glow +glue +goat +goddess +gold +good +goose +gorilla +gospel +gossip +govern +gown +grab +grace +grain +grant +grape +grass +gravity +great +green +grid +grief +grit +grocery +group +grow +grunt +guard +guess +guide +guilt +guitar +gun +gym +habit +hair +half +hammer +hamster +hand +happy +harbor +hard +harsh +harvest +hat +have +hawk +hazard +head +health +heart +heavy +hedgehog +height +hello +helmet +help +hen +hero +hidden +high +hill +hint +hip +hire +history +hobby +hockey +hold +hole +holiday +hollow +home +honey +hood +hope +horn +horror +horse +hospital +host +hotel +hour +hover +hub +huge +human +humble +humor +hundred +hungry +hunt +hurdle +hurry +hurt +husband +hybrid +ice +icon +idea +identify +idle +ignore +ill +illegal +illness +image +imitate +immense +immune +impact +impose +improve +impulse +inch +include +income +increase +index +indicate +indoor +industry +infant +inflict +inform +inhale +inherit +initial +inject +injury +inmate +inner +innocent +input +inquiry +insane +insect +inside +inspire +install +intact +interest +into +invest +invite +involve +iron +island +isolate +issue +item +ivory +jacket +jaguar +jar +jazz +jealous +jeans +jelly +jewel +job +join +joke +journey +joy +judge +juice +jump +jungle +junior +junk +just +kangaroo +keen +keep +ketchup +key +kick +kid +kidney +kind +kingdom +kiss +kit +kitchen +kite +kitten +kiwi +knee +knife +knock +know +lab +label +labor +ladder +lady +lake +lamp +language +laptop +large +later +latin +laugh +laundry +lava +law +lawn +lawsuit +layer +lazy +leader +leaf +learn +leave +lecture +left +leg +legal +legend +leisure +lemon +lend +length +lens +leopard +lesson +letter +level +liar +liberty +library +license +life +lift +light +like +limb +limit +link +lion +liquid +list +little +live +lizard +load +loan +lobster +local +lock +logic +lonely +long +loop +lottery +loud +lounge +love +loyal +lucky +luggage +lumber +lunar +lunch +luxury +lyrics +machine +mad +magic +magnet +maid +mail +main +major +make +mammal +man +manage +mandate +mango +mansion +manual +maple +marble +march +margin +marine +market +marriage +mask +mass +master +match +material +math +matrix +matter +maximum +maze +meadow +mean +measure +meat +mechanic +medal +media +melody +melt +member +memory +mention +menu +mercy +merge +merit +merry +mesh +message +metal +method +middle +midnight +milk +million +mimic +mind +minimum +minor +minute +miracle +mirror +misery +miss +mistake +mix +mixed +mixture +mobile +model +modify +mom +moment +monitor +monkey +monster +month +moon +moral +more +morning +mosquito +mother +motion +motor +mountain +mouse +move +movie +much +muffin +mule +multiply +muscle +museum +mushroom +music +must +mutual +myself +mystery +myth +naive +name +napkin +narrow +nasty +nation +nature +near +neck +need +negative +neglect +neither +nephew +nerve +nest +net +network +neutral +never +news +next +nice +night +noble +noise +nominee +noodle +normal +north +nose +notable +note +nothing +notice +novel +now +nuclear +number +nurse +nut +oak +obey +object +oblige +obscure +observe +obtain +obvious +occur +ocean +october +odor +off +offer +office +often +oil +okay +old +olive +olympic +omit +once +one +onion +online +only +open +opera +opinion +oppose +option +orange +orbit +orchard +order +ordinary +organ +orient +original +orphan +ostrich +other +outdoor +outer +output +outside +oval +oven +over +own +owner +oxygen +oyster +ozone +pact +paddle +page +pair +palace +palm +panda +panel +panic +panther +paper +parade +parent +park +parrot +party +pass +patch +path +patient +patrol +pattern +pause +pave +payment +peace +peanut +pear +peasant +pelican +pen +penalty +pencil +people +pepper +perfect +permit +person +pet +phone +photo +phrase +physical +piano +picnic +picture +piece +pig +pigeon +pill +pilot +pink +pioneer +pipe +pistol +pitch +pizza +place +planet +plastic +plate +play +please +pledge +pluck +plug +plunge +poem +poet +point +polar +pole +police +pond +pony +pool +popular +portion +position +possible +post +potato +pottery +poverty +powder +power +practice +praise +predict +prefer +prepare +present +pretty +prevent +price +pride +primary +print +priority +prison +private +prize +problem +process +produce +profit +program +project +promote +proof +property +prosper +protect +proud +provide +public +pudding +pull +pulp +pulse +pumpkin +punch +pupil +puppy +purchase +purity +purpose +purse +push +put +puzzle +pyramid +quality +quantum +quarter +question +quick +quit +quiz +quote +rabbit +raccoon +race +rack +radar +radio +rail +rain +raise +rally +ramp +ranch +random +range +rapid +rare +rate +rather +raven +raw +razor +ready +real +reason +rebel +rebuild +recall +receive +recipe +record +recycle +reduce +reflect +reform +refuse +region +regret +regular +reject +relax +release +relief +rely +remain +remember +remind +remove +render +renew +rent +reopen +repair +repeat +replace +report +require +rescue +resemble +resist +resource +response +result +retire +retreat +return +reunion +reveal +review +reward +rhythm +rib +ribbon +rice +rich +ride +ridge +rifle +right +rigid +ring +riot +ripple +risk +ritual +rival +river +road +roast +robot +robust +rocket +romance +roof +rookie +room +rose +rotate +rough +round +route +royal +rubber +rude +rug +rule +run +runway +rural +sad +saddle +sadness +safe +sail +salad +salmon +salon +salt +salute +same +sample +sand +satisfy +satoshi +sauce +sausage +save +say +scale +scan +scare +scatter +scene +scheme +school +science +scissors +scorpion +scout +scrap +screen +script +scrub +sea +search +season +seat +second +secret +section +security +seed +seek +segment +select +sell +seminar +senior +sense +sentence +series +service +session +settle +setup +seven +shadow +shaft +shallow +share +shed +shell +sheriff +shield +shift +shine +ship +shiver +shock +shoe +shoot +shop +short +shoulder +shove +shrimp +shrug +shuffle +shy +sibling +sick +side +siege +sight +sign +silent +silk +silly +silver +similar +simple +since +sing +siren +sister +situate +six +size +skate +sketch +ski +skill +skin +skirt +skull +slab +slam +sleep +slender +slice +slide +slight +slim +slogan +slot +slow +slush +small +smart +smile +smoke +smooth +snack +snake +snap +sniff +snow +soap +soccer +social +sock +soda +soft +solar +soldier +solid +solution +solve +someone +song +soon +sorry +sort +soul +sound +soup +source +south +space +spare +spatial +spawn +speak +special +speed +spell +spend +sphere +spice +spider +spike +spin +spirit +split +spoil +sponsor +spoon +sport +spot +spray +spread +spring +spy +square +squeeze +squirrel +stable +stadium +staff +stage +stairs +stamp +stand +start +state +stay +steak +steel +stem +step +stereo +stick +still +sting +stock +stomach +stone +stool +story +stove +strategy +street +strike +strong +struggle +student +stuff +stumble +style +subject +submit +subway +success +such +sudden +suffer +sugar +suggest +suit +summer +sun +sunny +sunset +super +supply +supreme +sure +surface +surge +surprise +surround +survey +suspect +sustain +swallow +swamp +swap +swarm +swear +sweet +swift +swim +swing +switch +sword +symbol +symptom +syrup +system +table +tackle +tag +tail +talent +talk +tank +tape +target +task +taste +tattoo +taxi +teach +team +tell +ten +tenant +tennis +tent +term +test +text +thank +that +theme +then +theory +there +they +thing +this +thought +three +thrive +throw +thumb +thunder +ticket +tide +tiger +tilt +timber +time +tiny +tip +tired +tissue +title +toast +tobacco +today +toddler +toe +together +toilet +token +tomato +tomorrow +tone +tongue +tonight +tool +tooth +top +topic +topple +torch +tornado +tortoise +toss +total +tourist +toward +tower +town +toy +track +trade +traffic +tragic +train +transfer +trap +trash +travel +tray +treat +tree +trend +trial +tribe +trick +trigger +trim +trip +trophy +trouble +truck +true +truly +trumpet +trust +truth +try +tube +tuition +tumble +tuna +tunnel +turkey +turn +turtle +twelve +twenty +twice +twin +twist +two +type +typical +ugly +umbrella +unable +unaware +uncle +uncover +under +undo +unfair +unfold +unhappy +uniform +unique +unit +universe +unknown +unlock +until +unusual +unveil +update +upgrade +uphold +upon +upper +upset +urban +urge +usage +use +used +useful +useless +usual +utility +vacant +vacuum +vague +valid +valley +valve +van +vanish +vapor +various +vast +vault +vehicle +velvet +vendor +venture +venue +verb +verify +version +very +vessel +veteran +viable +vibrant +vicious +victory +video +view +village +vintage +violin +virtual +virus +visa +visit +visual +vital +vivid +vocal +voice +void +volcano +volume +vote +voyage +wage +wagon +wait +walk +wall +walnut +want +warfare +warm +warrior +wash +wasp +waste +water +wave +way +wealth +weapon +wear +weasel +weather +web +wedding +weekend +weird +welcome +west +wet +whale +what +wheat +wheel +when +where +whip +whisper +wide +width +wife +wild +will +win +window +wine +wing +wink +winner +winter +wire +wisdom +wise +wish +witness +wolf +woman +wonder +wood +wool +word +work +world +worry +worth +wrap +wreck +wrestle +wrist +write +wrong +yard +year +yellow +you +young +youth +zebra +zero +zone +zoo`.split('\n'); diff --git a/node_modules/@scure/bip39/wordlists/french.d.ts b/node_modules/@scure/bip39/wordlists/french.d.ts new file mode 100644 index 0000000..b566a1d --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/french.d.ts @@ -0,0 +1 @@ +export declare const wordlist: string[]; diff --git a/node_modules/@scure/bip39/wordlists/french.js b/node_modules/@scure/bip39/wordlists/french.js new file mode 100644 index 0000000..6010582 --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/french.js @@ -0,0 +1,2051 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +exports.wordlist = `abaisser +abandon +abdiquer +abeille +abolir +aborder +aboutir +aboyer +abrasif +abreuver +abriter +abroger +abrupt +absence +absolu +absurde +abusif +abyssal +académie +acajou +acarien +accabler +accepter +acclamer +accolade +accroche +accuser +acerbe +achat +acheter +aciduler +acier +acompte +acquérir +acronyme +acteur +actif +actuel +adepte +adéquat +adhésif +adjectif +adjuger +admettre +admirer +adopter +adorer +adoucir +adresse +adroit +adulte +adverbe +aérer +aéronef +affaire +affecter +affiche +affreux +affubler +agacer +agencer +agile +agiter +agrafer +agréable +agrume +aider +aiguille +ailier +aimable +aisance +ajouter +ajuster +alarmer +alchimie +alerte +algèbre +algue +aliéner +aliment +alléger +alliage +allouer +allumer +alourdir +alpaga +altesse +alvéole +amateur +ambigu +ambre +aménager +amertume +amidon +amiral +amorcer +amour +amovible +amphibie +ampleur +amusant +analyse +anaphore +anarchie +anatomie +ancien +anéantir +angle +angoisse +anguleux +animal +annexer +annonce +annuel +anodin +anomalie +anonyme +anormal +antenne +antidote +anxieux +apaiser +apéritif +aplanir +apologie +appareil +appeler +apporter +appuyer +aquarium +aqueduc +arbitre +arbuste +ardeur +ardoise +argent +arlequin +armature +armement +armoire +armure +arpenter +arracher +arriver +arroser +arsenic +artériel +article +aspect +asphalte +aspirer +assaut +asservir +assiette +associer +assurer +asticot +astre +astuce +atelier +atome +atrium +atroce +attaque +attentif +attirer +attraper +aubaine +auberge +audace +audible +augurer +aurore +automne +autruche +avaler +avancer +avarice +avenir +averse +aveugle +aviateur +avide +avion +aviser +avoine +avouer +avril +axial +axiome +badge +bafouer +bagage +baguette +baignade +balancer +balcon +baleine +balisage +bambin +bancaire +bandage +banlieue +bannière +banquier +barbier +baril +baron +barque +barrage +bassin +bastion +bataille +bateau +batterie +baudrier +bavarder +belette +bélier +belote +bénéfice +berceau +berger +berline +bermuda +besace +besogne +bétail +beurre +biberon +bicycle +bidule +bijou +bilan +bilingue +billard +binaire +biologie +biopsie +biotype +biscuit +bison +bistouri +bitume +bizarre +blafard +blague +blanchir +blessant +blinder +blond +bloquer +blouson +bobard +bobine +boire +boiser +bolide +bonbon +bondir +bonheur +bonifier +bonus +bordure +borne +botte +boucle +boueux +bougie +boulon +bouquin +bourse +boussole +boutique +boxeur +branche +brasier +brave +brebis +brèche +breuvage +bricoler +brigade +brillant +brioche +brique +brochure +broder +bronzer +brousse +broyeur +brume +brusque +brutal +bruyant +buffle +buisson +bulletin +bureau +burin +bustier +butiner +butoir +buvable +buvette +cabanon +cabine +cachette +cadeau +cadre +caféine +caillou +caisson +calculer +calepin +calibre +calmer +calomnie +calvaire +camarade +caméra +camion +campagne +canal +caneton +canon +cantine +canular +capable +caporal +caprice +capsule +capter +capuche +carabine +carbone +caresser +caribou +carnage +carotte +carreau +carton +cascade +casier +casque +cassure +causer +caution +cavalier +caverne +caviar +cédille +ceinture +céleste +cellule +cendrier +censurer +central +cercle +cérébral +cerise +cerner +cerveau +cesser +chagrin +chaise +chaleur +chambre +chance +chapitre +charbon +chasseur +chaton +chausson +chavirer +chemise +chenille +chéquier +chercher +cheval +chien +chiffre +chignon +chimère +chiot +chlorure +chocolat +choisir +chose +chouette +chrome +chute +cigare +cigogne +cimenter +cinéma +cintrer +circuler +cirer +cirque +citerne +citoyen +citron +civil +clairon +clameur +claquer +classe +clavier +client +cligner +climat +clivage +cloche +clonage +cloporte +cobalt +cobra +cocasse +cocotier +coder +codifier +coffre +cogner +cohésion +coiffer +coincer +colère +colibri +colline +colmater +colonel +combat +comédie +commande +compact +concert +conduire +confier +congeler +connoter +consonne +contact +convexe +copain +copie +corail +corbeau +cordage +corniche +corpus +correct +cortège +cosmique +costume +coton +coude +coupure +courage +couteau +couvrir +coyote +crabe +crainte +cravate +crayon +créature +créditer +crémeux +creuser +crevette +cribler +crier +cristal +critère +croire +croquer +crotale +crucial +cruel +crypter +cubique +cueillir +cuillère +cuisine +cuivre +culminer +cultiver +cumuler +cupide +curatif +curseur +cyanure +cycle +cylindre +cynique +daigner +damier +danger +danseur +dauphin +débattre +débiter +déborder +débrider +débutant +décaler +décembre +déchirer +décider +déclarer +décorer +décrire +décupler +dédale +déductif +déesse +défensif +défiler +défrayer +dégager +dégivrer +déglutir +dégrafer +déjeuner +délice +déloger +demander +demeurer +démolir +dénicher +dénouer +dentelle +dénuder +départ +dépenser +déphaser +déplacer +déposer +déranger +dérober +désastre +descente +désert +désigner +désobéir +dessiner +destrier +détacher +détester +détourer +détresse +devancer +devenir +deviner +devoir +diable +dialogue +diamant +dicter +différer +digérer +digital +digne +diluer +dimanche +diminuer +dioxyde +directif +diriger +discuter +disposer +dissiper +distance +divertir +diviser +docile +docteur +dogme +doigt +domaine +domicile +dompter +donateur +donjon +donner +dopamine +dortoir +dorure +dosage +doseur +dossier +dotation +douanier +double +douceur +douter +doyen +dragon +draper +dresser +dribbler +droiture +duperie +duplexe +durable +durcir +dynastie +éblouir +écarter +écharpe +échelle +éclairer +éclipse +éclore +écluse +école +économie +écorce +écouter +écraser +écrémer +écrivain +écrou +écume +écureuil +édifier +éduquer +effacer +effectif +effigie +effort +effrayer +effusion +égaliser +égarer +éjecter +élaborer +élargir +électron +élégant +éléphant +élève +éligible +élitisme +éloge +élucider +éluder +emballer +embellir +embryon +émeraude +émission +emmener +émotion +émouvoir +empereur +employer +emporter +emprise +émulsion +encadrer +enchère +enclave +encoche +endiguer +endosser +endroit +enduire +énergie +enfance +enfermer +enfouir +engager +engin +englober +énigme +enjamber +enjeu +enlever +ennemi +ennuyeux +enrichir +enrobage +enseigne +entasser +entendre +entier +entourer +entraver +énumérer +envahir +enviable +envoyer +enzyme +éolien +épaissir +épargne +épatant +épaule +épicerie +épidémie +épier +épilogue +épine +épisode +épitaphe +époque +épreuve +éprouver +épuisant +équerre +équipe +ériger +érosion +erreur +éruption +escalier +espadon +espèce +espiègle +espoir +esprit +esquiver +essayer +essence +essieu +essorer +estime +estomac +estrade +étagère +étaler +étanche +étatique +éteindre +étendoir +éternel +éthanol +éthique +ethnie +étirer +étoffer +étoile +étonnant +étourdir +étrange +étroit +étude +euphorie +évaluer +évasion +éventail +évidence +éviter +évolutif +évoquer +exact +exagérer +exaucer +exceller +excitant +exclusif +excuse +exécuter +exemple +exercer +exhaler +exhorter +exigence +exiler +exister +exotique +expédier +explorer +exposer +exprimer +exquis +extensif +extraire +exulter +fable +fabuleux +facette +facile +facture +faiblir +falaise +fameux +famille +farceur +farfelu +farine +farouche +fasciner +fatal +fatigue +faucon +fautif +faveur +favori +fébrile +féconder +fédérer +félin +femme +fémur +fendoir +féodal +fermer +féroce +ferveur +festival +feuille +feutre +février +fiasco +ficeler +fictif +fidèle +figure +filature +filetage +filière +filleul +filmer +filou +filtrer +financer +finir +fiole +firme +fissure +fixer +flairer +flamme +flasque +flatteur +fléau +flèche +fleur +flexion +flocon +flore +fluctuer +fluide +fluvial +folie +fonderie +fongible +fontaine +forcer +forgeron +formuler +fortune +fossile +foudre +fougère +fouiller +foulure +fourmi +fragile +fraise +franchir +frapper +frayeur +frégate +freiner +frelon +frémir +frénésie +frère +friable +friction +frisson +frivole +froid +fromage +frontal +frotter +fruit +fugitif +fuite +fureur +furieux +furtif +fusion +futur +gagner +galaxie +galerie +gambader +garantir +gardien +garnir +garrigue +gazelle +gazon +géant +gélatine +gélule +gendarme +général +génie +genou +gentil +géologie +géomètre +géranium +germe +gestuel +geyser +gibier +gicler +girafe +givre +glace +glaive +glisser +globe +gloire +glorieux +golfeur +gomme +gonfler +gorge +gorille +goudron +gouffre +goulot +goupille +gourmand +goutte +graduel +graffiti +graine +grand +grappin +gratuit +gravir +grenat +griffure +griller +grimper +grogner +gronder +grotte +groupe +gruger +grutier +gruyère +guépard +guerrier +guide +guimauve +guitare +gustatif +gymnaste +gyrostat +habitude +hachoir +halte +hameau +hangar +hanneton +haricot +harmonie +harpon +hasard +hélium +hématome +herbe +hérisson +hermine +héron +hésiter +heureux +hiberner +hibou +hilarant +histoire +hiver +homard +hommage +homogène +honneur +honorer +honteux +horde +horizon +horloge +hormone +horrible +houleux +housse +hublot +huileux +humain +humble +humide +humour +hurler +hydromel +hygiène +hymne +hypnose +idylle +ignorer +iguane +illicite +illusion +image +imbiber +imiter +immense +immobile +immuable +impact +impérial +implorer +imposer +imprimer +imputer +incarner +incendie +incident +incliner +incolore +indexer +indice +inductif +inédit +ineptie +inexact +infini +infliger +informer +infusion +ingérer +inhaler +inhiber +injecter +injure +innocent +inoculer +inonder +inscrire +insecte +insigne +insolite +inspirer +instinct +insulter +intact +intense +intime +intrigue +intuitif +inutile +invasion +inventer +inviter +invoquer +ironique +irradier +irréel +irriter +isoler +ivoire +ivresse +jaguar +jaillir +jambe +janvier +jardin +jauger +jaune +javelot +jetable +jeton +jeudi +jeunesse +joindre +joncher +jongler +joueur +jouissif +journal +jovial +joyau +joyeux +jubiler +jugement +junior +jupon +juriste +justice +juteux +juvénile +kayak +kimono +kiosque +label +labial +labourer +lacérer +lactose +lagune +laine +laisser +laitier +lambeau +lamelle +lampe +lanceur +langage +lanterne +lapin +largeur +larme +laurier +lavabo +lavoir +lecture +légal +léger +légume +lessive +lettre +levier +lexique +lézard +liasse +libérer +libre +licence +licorne +liège +lièvre +ligature +ligoter +ligue +limer +limite +limonade +limpide +linéaire +lingot +lionceau +liquide +lisière +lister +lithium +litige +littoral +livreur +logique +lointain +loisir +lombric +loterie +louer +lourd +loutre +louve +loyal +lubie +lucide +lucratif +lueur +lugubre +luisant +lumière +lunaire +lundi +luron +lutter +luxueux +machine +magasin +magenta +magique +maigre +maillon +maintien +mairie +maison +majorer +malaxer +maléfice +malheur +malice +mallette +mammouth +mandater +maniable +manquant +manteau +manuel +marathon +marbre +marchand +mardi +maritime +marqueur +marron +marteler +mascotte +massif +matériel +matière +matraque +maudire +maussade +mauve +maximal +méchant +méconnu +médaille +médecin +méditer +méduse +meilleur +mélange +mélodie +membre +mémoire +menacer +mener +menhir +mensonge +mentor +mercredi +mérite +merle +messager +mesure +métal +météore +méthode +métier +meuble +miauler +microbe +miette +mignon +migrer +milieu +million +mimique +mince +minéral +minimal +minorer +minute +miracle +miroiter +missile +mixte +mobile +moderne +moelleux +mondial +moniteur +monnaie +monotone +monstre +montagne +monument +moqueur +morceau +morsure +mortier +moteur +motif +mouche +moufle +moulin +mousson +mouton +mouvant +multiple +munition +muraille +murène +murmure +muscle +muséum +musicien +mutation +muter +mutuel +myriade +myrtille +mystère +mythique +nageur +nappe +narquois +narrer +natation +nation +nature +naufrage +nautique +navire +nébuleux +nectar +néfaste +négation +négliger +négocier +neige +nerveux +nettoyer +neurone +neutron +neveu +niche +nickel +nitrate +niveau +noble +nocif +nocturne +noirceur +noisette +nomade +nombreux +nommer +normatif +notable +notifier +notoire +nourrir +nouveau +novateur +novembre +novice +nuage +nuancer +nuire +nuisible +numéro +nuptial +nuque +nutritif +obéir +objectif +obliger +obscur +observer +obstacle +obtenir +obturer +occasion +occuper +océan +octobre +octroyer +octupler +oculaire +odeur +odorant +offenser +officier +offrir +ogive +oiseau +oisillon +olfactif +olivier +ombrage +omettre +onctueux +onduler +onéreux +onirique +opale +opaque +opérer +opinion +opportun +opprimer +opter +optique +orageux +orange +orbite +ordonner +oreille +organe +orgueil +orifice +ornement +orque +ortie +osciller +osmose +ossature +otarie +ouragan +ourson +outil +outrager +ouvrage +ovation +oxyde +oxygène +ozone +paisible +palace +palmarès +palourde +palper +panache +panda +pangolin +paniquer +panneau +panorama +pantalon +papaye +papier +papoter +papyrus +paradoxe +parcelle +paresse +parfumer +parler +parole +parrain +parsemer +partager +parure +parvenir +passion +pastèque +paternel +patience +patron +pavillon +pavoiser +payer +paysage +peigne +peintre +pelage +pélican +pelle +pelouse +peluche +pendule +pénétrer +pénible +pensif +pénurie +pépite +péplum +perdrix +perforer +période +permuter +perplexe +persil +perte +peser +pétale +petit +pétrir +peuple +pharaon +phobie +phoque +photon +phrase +physique +piano +pictural +pièce +pierre +pieuvre +pilote +pinceau +pipette +piquer +pirogue +piscine +piston +pivoter +pixel +pizza +placard +plafond +plaisir +planer +plaque +plastron +plateau +pleurer +plexus +pliage +plomb +plonger +pluie +plumage +pochette +poésie +poète +pointe +poirier +poisson +poivre +polaire +policier +pollen +polygone +pommade +pompier +ponctuel +pondérer +poney +portique +position +posséder +posture +potager +poteau +potion +pouce +poulain +poumon +pourpre +poussin +pouvoir +prairie +pratique +précieux +prédire +préfixe +prélude +prénom +présence +prétexte +prévoir +primitif +prince +prison +priver +problème +procéder +prodige +profond +progrès +proie +projeter +prologue +promener +propre +prospère +protéger +prouesse +proverbe +prudence +pruneau +psychose +public +puceron +puiser +pulpe +pulsar +punaise +punitif +pupitre +purifier +puzzle +pyramide +quasar +querelle +question +quiétude +quitter +quotient +racine +raconter +radieux +ragondin +raideur +raisin +ralentir +rallonge +ramasser +rapide +rasage +ratisser +ravager +ravin +rayonner +réactif +réagir +réaliser +réanimer +recevoir +réciter +réclamer +récolter +recruter +reculer +recycler +rédiger +redouter +refaire +réflexe +réformer +refrain +refuge +régalien +région +réglage +régulier +réitérer +rejeter +rejouer +relatif +relever +relief +remarque +remède +remise +remonter +remplir +remuer +renard +renfort +renifler +renoncer +rentrer +renvoi +replier +reporter +reprise +reptile +requin +réserve +résineux +résoudre +respect +rester +résultat +rétablir +retenir +réticule +retomber +retracer +réunion +réussir +revanche +revivre +révolte +révulsif +richesse +rideau +rieur +rigide +rigoler +rincer +riposter +risible +risque +rituel +rival +rivière +rocheux +romance +rompre +ronce +rondin +roseau +rosier +rotatif +rotor +rotule +rouge +rouille +rouleau +routine +royaume +ruban +rubis +ruche +ruelle +rugueux +ruiner +ruisseau +ruser +rustique +rythme +sabler +saboter +sabre +sacoche +safari +sagesse +saisir +salade +salive +salon +saluer +samedi +sanction +sanglier +sarcasme +sardine +saturer +saugrenu +saumon +sauter +sauvage +savant +savonner +scalpel +scandale +scélérat +scénario +sceptre +schéma +science +scinder +score +scrutin +sculpter +séance +sécable +sécher +secouer +sécréter +sédatif +séduire +seigneur +séjour +sélectif +semaine +sembler +semence +séminal +sénateur +sensible +sentence +séparer +séquence +serein +sergent +sérieux +serrure +sérum +service +sésame +sévir +sevrage +sextuple +sidéral +siècle +siéger +siffler +sigle +signal +silence +silicium +simple +sincère +sinistre +siphon +sirop +sismique +situer +skier +social +socle +sodium +soigneux +soldat +soleil +solitude +soluble +sombre +sommeil +somnoler +sonde +songeur +sonnette +sonore +sorcier +sortir +sosie +sottise +soucieux +soudure +souffle +soulever +soupape +source +soutirer +souvenir +spacieux +spatial +spécial +sphère +spiral +stable +station +sternum +stimulus +stipuler +strict +studieux +stupeur +styliste +sublime +substrat +subtil +subvenir +succès +sucre +suffixe +suggérer +suiveur +sulfate +superbe +supplier +surface +suricate +surmener +surprise +sursaut +survie +suspect +syllabe +symbole +symétrie +synapse +syntaxe +système +tabac +tablier +tactile +tailler +talent +talisman +talonner +tambour +tamiser +tangible +tapis +taquiner +tarder +tarif +tartine +tasse +tatami +tatouage +taupe +taureau +taxer +témoin +temporel +tenaille +tendre +teneur +tenir +tension +terminer +terne +terrible +tétine +texte +thème +théorie +thérapie +thorax +tibia +tiède +timide +tirelire +tiroir +tissu +titane +titre +tituber +toboggan +tolérant +tomate +tonique +tonneau +toponyme +torche +tordre +tornade +torpille +torrent +torse +tortue +totem +toucher +tournage +tousser +toxine +traction +trafic +tragique +trahir +train +trancher +travail +trèfle +tremper +trésor +treuil +triage +tribunal +tricoter +trilogie +triomphe +tripler +triturer +trivial +trombone +tronc +tropical +troupeau +tuile +tulipe +tumulte +tunnel +turbine +tuteur +tutoyer +tuyau +tympan +typhon +typique +tyran +ubuesque +ultime +ultrason +unanime +unifier +union +unique +unitaire +univers +uranium +urbain +urticant +usage +usine +usuel +usure +utile +utopie +vacarme +vaccin +vagabond +vague +vaillant +vaincre +vaisseau +valable +valise +vallon +valve +vampire +vanille +vapeur +varier +vaseux +vassal +vaste +vecteur +vedette +végétal +véhicule +veinard +véloce +vendredi +vénérer +venger +venimeux +ventouse +verdure +vérin +vernir +verrou +verser +vertu +veston +vétéran +vétuste +vexant +vexer +viaduc +viande +victoire +vidange +vidéo +vignette +vigueur +vilain +village +vinaigre +violon +vipère +virement +virtuose +virus +visage +viseur +vision +visqueux +visuel +vital +vitesse +viticole +vitrine +vivace +vivipare +vocation +voguer +voile +voisin +voiture +volaille +volcan +voltiger +volume +vorace +vortex +voter +vouloir +voyage +voyelle +wagon +xénon +yacht +zèbre +zénith +zeste +zoologie`.split('\n'); diff --git a/node_modules/@scure/bip39/wordlists/italian.d.ts b/node_modules/@scure/bip39/wordlists/italian.d.ts new file mode 100644 index 0000000..b566a1d --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/italian.d.ts @@ -0,0 +1 @@ +export declare const wordlist: string[]; diff --git a/node_modules/@scure/bip39/wordlists/italian.js b/node_modules/@scure/bip39/wordlists/italian.js new file mode 100644 index 0000000..7eabb0e --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/italian.js @@ -0,0 +1,2051 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +exports.wordlist = `abaco +abbaglio +abbinato +abete +abisso +abolire +abrasivo +abrogato +accadere +accenno +accusato +acetone +achille +acido +acqua +acre +acrilico +acrobata +acuto +adagio +addebito +addome +adeguato +aderire +adipe +adottare +adulare +affabile +affetto +affisso +affranto +aforisma +afoso +africano +agave +agente +agevole +aggancio +agire +agitare +agonismo +agricolo +agrumeto +aguzzo +alabarda +alato +albatro +alberato +albo +albume +alce +alcolico +alettone +alfa +algebra +aliante +alibi +alimento +allagato +allegro +allievo +allodola +allusivo +almeno +alogeno +alpaca +alpestre +altalena +alterno +alticcio +altrove +alunno +alveolo +alzare +amalgama +amanita +amarena +ambito +ambrato +ameba +america +ametista +amico +ammasso +ammenda +ammirare +ammonito +amore +ampio +ampliare +amuleto +anacardo +anagrafe +analista +anarchia +anatra +anca +ancella +ancora +andare +andrea +anello +angelo +angolare +angusto +anima +annegare +annidato +anno +annuncio +anonimo +anticipo +anzi +apatico +apertura +apode +apparire +appetito +appoggio +approdo +appunto +aprile +arabica +arachide +aragosta +araldica +arancio +aratura +arazzo +arbitro +archivio +ardito +arenile +argento +argine +arguto +aria +armonia +arnese +arredato +arringa +arrosto +arsenico +arso +artefice +arzillo +asciutto +ascolto +asepsi +asettico +asfalto +asino +asola +aspirato +aspro +assaggio +asse +assoluto +assurdo +asta +astenuto +astice +astratto +atavico +ateismo +atomico +atono +attesa +attivare +attorno +attrito +attuale +ausilio +austria +autista +autonomo +autunno +avanzato +avere +avvenire +avviso +avvolgere +azione +azoto +azzimo +azzurro +babele +baccano +bacino +baco +badessa +badilata +bagnato +baita +balcone +baldo +balena +ballata +balzano +bambino +bandire +baraonda +barbaro +barca +baritono +barlume +barocco +basilico +basso +batosta +battuto +baule +bava +bavosa +becco +beffa +belgio +belva +benda +benevole +benigno +benzina +bere +berlina +beta +bibita +bici +bidone +bifido +biga +bilancia +bimbo +binocolo +biologo +bipede +bipolare +birbante +birra +biscotto +bisesto +bisnonno +bisonte +bisturi +bizzarro +blando +blatta +bollito +bonifico +bordo +bosco +botanico +bottino +bozzolo +braccio +bradipo +brama +branca +bravura +bretella +brevetto +brezza +briglia +brillante +brindare +broccolo +brodo +bronzina +brullo +bruno +bubbone +buca +budino +buffone +buio +bulbo +buono +burlone +burrasca +bussola +busta +cadetto +caduco +calamaro +calcolo +calesse +calibro +calmo +caloria +cambusa +camerata +camicia +cammino +camola +campale +canapa +candela +cane +canino +canotto +cantina +capace +capello +capitolo +capogiro +cappero +capra +capsula +carapace +carcassa +cardo +carisma +carovana +carretto +cartolina +casaccio +cascata +caserma +caso +cassone +castello +casuale +catasta +catena +catrame +cauto +cavillo +cedibile +cedrata +cefalo +celebre +cellulare +cena +cenone +centesimo +ceramica +cercare +certo +cerume +cervello +cesoia +cespo +ceto +chela +chiaro +chicca +chiedere +chimera +china +chirurgo +chitarra +ciao +ciclismo +cifrare +cigno +cilindro +ciottolo +circa +cirrosi +citrico +cittadino +ciuffo +civetta +civile +classico +clinica +cloro +cocco +codardo +codice +coerente +cognome +collare +colmato +colore +colposo +coltivato +colza +coma +cometa +commando +comodo +computer +comune +conciso +condurre +conferma +congelare +coniuge +connesso +conoscere +consumo +continuo +convegno +coperto +copione +coppia +copricapo +corazza +cordata +coricato +cornice +corolla +corpo +corredo +corsia +cortese +cosmico +costante +cottura +covato +cratere +cravatta +creato +credere +cremoso +crescita +creta +criceto +crinale +crisi +critico +croce +cronaca +crostata +cruciale +crusca +cucire +cuculo +cugino +cullato +cupola +curatore +cursore +curvo +cuscino +custode +dado +daino +dalmata +damerino +daniela +dannoso +danzare +datato +davanti +davvero +debutto +decennio +deciso +declino +decollo +decreto +dedicato +definito +deforme +degno +delegare +delfino +delirio +delta +demenza +denotato +dentro +deposito +derapata +derivare +deroga +descritto +deserto +desiderio +desumere +detersivo +devoto +diametro +dicembre +diedro +difeso +diffuso +digerire +digitale +diluvio +dinamico +dinnanzi +dipinto +diploma +dipolo +diradare +dire +dirotto +dirupo +disagio +discreto +disfare +disgelo +disposto +distanza +disumano +dito +divano +divelto +dividere +divorato +doblone +docente +doganale +dogma +dolce +domato +domenica +dominare +dondolo +dono +dormire +dote +dottore +dovuto +dozzina +drago +druido +dubbio +dubitare +ducale +duna +duomo +duplice +duraturo +ebano +eccesso +ecco +eclissi +economia +edera +edicola +edile +editoria +educare +egemonia +egli +egoismo +egregio +elaborato +elargire +elegante +elencato +eletto +elevare +elfico +elica +elmo +elsa +eluso +emanato +emblema +emesso +emiro +emotivo +emozione +empirico +emulo +endemico +enduro +energia +enfasi +enoteca +entrare +enzima +epatite +epilogo +episodio +epocale +eppure +equatore +erario +erba +erboso +erede +eremita +erigere +ermetico +eroe +erosivo +errante +esagono +esame +esanime +esaudire +esca +esempio +esercito +esibito +esigente +esistere +esito +esofago +esortato +esoso +espanso +espresso +essenza +esso +esteso +estimare +estonia +estroso +esultare +etilico +etnico +etrusco +etto +euclideo +europa +evaso +evidenza +evitato +evoluto +evviva +fabbrica +faccenda +fachiro +falco +famiglia +fanale +fanfara +fango +fantasma +fare +farfalla +farinoso +farmaco +fascia +fastoso +fasullo +faticare +fato +favoloso +febbre +fecola +fede +fegato +felpa +feltro +femmina +fendere +fenomeno +fermento +ferro +fertile +fessura +festivo +fetta +feudo +fiaba +fiducia +fifa +figurato +filo +finanza +finestra +finire +fiore +fiscale +fisico +fiume +flacone +flamenco +flebo +flemma +florido +fluente +fluoro +fobico +focaccia +focoso +foderato +foglio +folata +folclore +folgore +fondente +fonetico +fonia +fontana +forbito +forchetta +foresta +formica +fornaio +foro +fortezza +forzare +fosfato +fosso +fracasso +frana +frassino +fratello +freccetta +frenata +fresco +frigo +frollino +fronde +frugale +frutta +fucilata +fucsia +fuggente +fulmine +fulvo +fumante +fumetto +fumoso +fune +funzione +fuoco +furbo +furgone +furore +fuso +futile +gabbiano +gaffe +galateo +gallina +galoppo +gambero +gamma +garanzia +garbo +garofano +garzone +gasdotto +gasolio +gastrico +gatto +gaudio +gazebo +gazzella +geco +gelatina +gelso +gemello +gemmato +gene +genitore +gennaio +genotipo +gergo +ghepardo +ghiaccio +ghisa +giallo +gilda +ginepro +giocare +gioiello +giorno +giove +girato +girone +gittata +giudizio +giurato +giusto +globulo +glutine +gnomo +gobba +golf +gomito +gommone +gonfio +gonna +governo +gracile +grado +grafico +grammo +grande +grattare +gravoso +grazia +greca +gregge +grifone +grigio +grinza +grotta +gruppo +guadagno +guaio +guanto +guardare +gufo +guidare +ibernato +icona +identico +idillio +idolo +idra +idrico +idrogeno +igiene +ignaro +ignorato +ilare +illeso +illogico +illudere +imballo +imbevuto +imbocco +imbuto +immane +immerso +immolato +impacco +impeto +impiego +importo +impronta +inalare +inarcare +inattivo +incanto +incendio +inchino +incisivo +incluso +incontro +incrocio +incubo +indagine +india +indole +inedito +infatti +infilare +inflitto +ingaggio +ingegno +inglese +ingordo +ingrosso +innesco +inodore +inoltrare +inondato +insano +insetto +insieme +insonnia +insulina +intasato +intero +intonaco +intuito +inumidire +invalido +invece +invito +iperbole +ipnotico +ipotesi +ippica +iride +irlanda +ironico +irrigato +irrorare +isolato +isotopo +isterico +istituto +istrice +italia +iterare +labbro +labirinto +lacca +lacerato +lacrima +lacuna +laddove +lago +lampo +lancetta +lanterna +lardoso +larga +laringe +lastra +latenza +latino +lattuga +lavagna +lavoro +legale +leggero +lembo +lentezza +lenza +leone +lepre +lesivo +lessato +lesto +letterale +leva +levigato +libero +lido +lievito +lilla +limatura +limitare +limpido +lineare +lingua +liquido +lira +lirica +lisca +lite +litigio +livrea +locanda +lode +logica +lombare +londra +longevo +loquace +lorenzo +loto +lotteria +luce +lucidato +lumaca +luminoso +lungo +lupo +luppolo +lusinga +lusso +lutto +macabro +macchina +macero +macinato +madama +magico +maglia +magnete +magro +maiolica +malafede +malgrado +malinteso +malsano +malto +malumore +mana +mancia +mandorla +mangiare +manifesto +mannaro +manovra +mansarda +mantide +manubrio +mappa +maratona +marcire +maretta +marmo +marsupio +maschera +massaia +mastino +materasso +matricola +mattone +maturo +mazurca +meandro +meccanico +mecenate +medesimo +meditare +mega +melassa +melis +melodia +meninge +meno +mensola +mercurio +merenda +merlo +meschino +mese +messere +mestolo +metallo +metodo +mettere +miagolare +mica +micelio +michele +microbo +midollo +miele +migliore +milano +milite +mimosa +minerale +mini +minore +mirino +mirtillo +miscela +missiva +misto +misurare +mitezza +mitigare +mitra +mittente +mnemonico +modello +modifica +modulo +mogano +mogio +mole +molosso +monastero +monco +mondina +monetario +monile +monotono +monsone +montato +monviso +mora +mordere +morsicato +mostro +motivato +motosega +motto +movenza +movimento +mozzo +mucca +mucosa +muffa +mughetto +mugnaio +mulatto +mulinello +multiplo +mummia +munto +muovere +murale +musa +muscolo +musica +mutevole +muto +nababbo +nafta +nanometro +narciso +narice +narrato +nascere +nastrare +naturale +nautica +naviglio +nebulosa +necrosi +negativo +negozio +nemmeno +neofita +neretto +nervo +nessuno +nettuno +neutrale +neve +nevrotico +nicchia +ninfa +nitido +nobile +nocivo +nodo +nome +nomina +nordico +normale +norvegese +nostrano +notare +notizia +notturno +novella +nucleo +nulla +numero +nuovo +nutrire +nuvola +nuziale +oasi +obbedire +obbligo +obelisco +oblio +obolo +obsoleto +occasione +occhio +occidente +occorrere +occultare +ocra +oculato +odierno +odorare +offerta +offrire +offuscato +oggetto +oggi +ognuno +olandese +olfatto +oliato +oliva +ologramma +oltre +omaggio +ombelico +ombra +omega +omissione +ondoso +onere +onice +onnivoro +onorevole +onta +operato +opinione +opposto +oracolo +orafo +ordine +orecchino +orefice +orfano +organico +origine +orizzonte +orma +ormeggio +ornativo +orologio +orrendo +orribile +ortensia +ortica +orzata +orzo +osare +oscurare +osmosi +ospedale +ospite +ossa +ossidare +ostacolo +oste +otite +otre +ottagono +ottimo +ottobre +ovale +ovest +ovino +oviparo +ovocito +ovunque +ovviare +ozio +pacchetto +pace +pacifico +padella +padrone +paese +paga +pagina +palazzina +palesare +pallido +palo +palude +pandoro +pannello +paolo +paonazzo +paprica +parabola +parcella +parere +pargolo +pari +parlato +parola +partire +parvenza +parziale +passivo +pasticca +patacca +patologia +pattume +pavone +peccato +pedalare +pedonale +peggio +peloso +penare +pendice +penisola +pennuto +penombra +pensare +pentola +pepe +pepita +perbene +percorso +perdonato +perforare +pergamena +periodo +permesso +perno +perplesso +persuaso +pertugio +pervaso +pesatore +pesista +peso +pestifero +petalo +pettine +petulante +pezzo +piacere +pianta +piattino +piccino +picozza +piega +pietra +piffero +pigiama +pigolio +pigro +pila +pilifero +pillola +pilota +pimpante +pineta +pinna +pinolo +pioggia +piombo +piramide +piretico +pirite +pirolisi +pitone +pizzico +placebo +planare +plasma +platano +plenario +pochezza +poderoso +podismo +poesia +poggiare +polenta +poligono +pollice +polmonite +polpetta +polso +poltrona +polvere +pomice +pomodoro +ponte +popoloso +porfido +poroso +porpora +porre +portata +posa +positivo +possesso +postulato +potassio +potere +pranzo +prassi +pratica +precluso +predica +prefisso +pregiato +prelievo +premere +prenotare +preparato +presenza +pretesto +prevalso +prima +principe +privato +problema +procura +produrre +profumo +progetto +prolunga +promessa +pronome +proposta +proroga +proteso +prova +prudente +prugna +prurito +psiche +pubblico +pudica +pugilato +pugno +pulce +pulito +pulsante +puntare +pupazzo +pupilla +puro +quadro +qualcosa +quasi +querela +quota +raccolto +raddoppio +radicale +radunato +raffica +ragazzo +ragione +ragno +ramarro +ramingo +ramo +randagio +rantolare +rapato +rapina +rappreso +rasatura +raschiato +rasente +rassegna +rastrello +rata +ravveduto +reale +recepire +recinto +recluta +recondito +recupero +reddito +redimere +regalato +registro +regola +regresso +relazione +remare +remoto +renna +replica +reprimere +reputare +resa +residente +responso +restauro +rete +retina +retorica +rettifica +revocato +riassunto +ribadire +ribelle +ribrezzo +ricarica +ricco +ricevere +riciclato +ricordo +ricreduto +ridicolo +ridurre +rifasare +riflesso +riforma +rifugio +rigare +rigettato +righello +rilassato +rilevato +rimanere +rimbalzo +rimedio +rimorchio +rinascita +rincaro +rinforzo +rinnovo +rinomato +rinsavito +rintocco +rinuncia +rinvenire +riparato +ripetuto +ripieno +riportare +ripresa +ripulire +risata +rischio +riserva +risibile +riso +rispetto +ristoro +risultato +risvolto +ritardo +ritegno +ritmico +ritrovo +riunione +riva +riverso +rivincita +rivolto +rizoma +roba +robotico +robusto +roccia +roco +rodaggio +rodere +roditore +rogito +rollio +romantico +rompere +ronzio +rosolare +rospo +rotante +rotondo +rotula +rovescio +rubizzo +rubrica +ruga +rullino +rumine +rumoroso +ruolo +rupe +russare +rustico +sabato +sabbiare +sabotato +sagoma +salasso +saldatura +salgemma +salivare +salmone +salone +saltare +saluto +salvo +sapere +sapido +saporito +saraceno +sarcasmo +sarto +sassoso +satellite +satira +satollo +saturno +savana +savio +saziato +sbadiglio +sbalzo +sbancato +sbarra +sbattere +sbavare +sbendare +sbirciare +sbloccato +sbocciato +sbrinare +sbruffone +sbuffare +scabroso +scadenza +scala +scambiare +scandalo +scapola +scarso +scatenare +scavato +scelto +scenico +scettro +scheda +schiena +sciarpa +scienza +scindere +scippo +sciroppo +scivolo +sclerare +scodella +scolpito +scomparto +sconforto +scoprire +scorta +scossone +scozzese +scriba +scrollare +scrutinio +scuderia +scultore +scuola +scuro +scusare +sdebitare +sdoganare +seccatura +secondo +sedano +seggiola +segnalato +segregato +seguito +selciato +selettivo +sella +selvaggio +semaforo +sembrare +seme +seminato +sempre +senso +sentire +sepolto +sequenza +serata +serbato +sereno +serio +serpente +serraglio +servire +sestina +setola +settimana +sfacelo +sfaldare +sfamato +sfarzoso +sfaticato +sfera +sfida +sfilato +sfinge +sfocato +sfoderare +sfogo +sfoltire +sforzato +sfratto +sfruttato +sfuggito +sfumare +sfuso +sgabello +sgarbato +sgonfiare +sgorbio +sgrassato +sguardo +sibilo +siccome +sierra +sigla +signore +silenzio +sillaba +simbolo +simpatico +simulato +sinfonia +singolo +sinistro +sino +sintesi +sinusoide +sipario +sisma +sistole +situato +slitta +slogatura +sloveno +smarrito +smemorato +smentito +smeraldo +smilzo +smontare +smottato +smussato +snellire +snervato +snodo +sobbalzo +sobrio +soccorso +sociale +sodale +soffitto +sogno +soldato +solenne +solido +sollazzo +solo +solubile +solvente +somatico +somma +sonda +sonetto +sonnifero +sopire +soppeso +sopra +sorgere +sorpasso +sorriso +sorso +sorteggio +sorvolato +sospiro +sosta +sottile +spada +spalla +spargere +spatola +spavento +spazzola +specie +spedire +spegnere +spelatura +speranza +spessore +spettrale +spezzato +spia +spigoloso +spillato +spinoso +spirale +splendido +sportivo +sposo +spranga +sprecare +spronato +spruzzo +spuntino +squillo +sradicare +srotolato +stabile +stacco +staffa +stagnare +stampato +stantio +starnuto +stasera +statuto +stelo +steppa +sterzo +stiletto +stima +stirpe +stivale +stizzoso +stonato +storico +strappo +stregato +stridulo +strozzare +strutto +stuccare +stufo +stupendo +subentro +succoso +sudore +suggerito +sugo +sultano +suonare +superbo +supporto +surgelato +surrogato +sussurro +sutura +svagare +svedese +sveglio +svelare +svenuto +svezia +sviluppo +svista +svizzera +svolta +svuotare +tabacco +tabulato +tacciare +taciturno +tale +talismano +tampone +tannino +tara +tardivo +targato +tariffa +tarpare +tartaruga +tasto +tattico +taverna +tavolata +tazza +teca +tecnico +telefono +temerario +tempo +temuto +tendone +tenero +tensione +tentacolo +teorema +terme +terrazzo +terzetto +tesi +tesserato +testato +tetro +tettoia +tifare +tigella +timbro +tinto +tipico +tipografo +tiraggio +tiro +titanio +titolo +titubante +tizio +tizzone +toccare +tollerare +tolto +tombola +tomo +tonfo +tonsilla +topazio +topologia +toppa +torba +tornare +torrone +tortora +toscano +tossire +tostatura +totano +trabocco +trachea +trafila +tragedia +tralcio +tramonto +transito +trapano +trarre +trasloco +trattato +trave +treccia +tremolio +trespolo +tributo +tricheco +trifoglio +trillo +trincea +trio +tristezza +triturato +trivella +tromba +trono +troppo +trottola +trovare +truccato +tubatura +tuffato +tulipano +tumulto +tunisia +turbare +turchino +tuta +tutela +ubicato +uccello +uccisore +udire +uditivo +uffa +ufficio +uguale +ulisse +ultimato +umano +umile +umorismo +uncinetto +ungere +ungherese +unicorno +unificato +unisono +unitario +unte +uovo +upupa +uragano +urgenza +urlo +usanza +usato +uscito +usignolo +usuraio +utensile +utilizzo +utopia +vacante +vaccinato +vagabondo +vagliato +valanga +valgo +valico +valletta +valoroso +valutare +valvola +vampata +vangare +vanitoso +vano +vantaggio +vanvera +vapore +varano +varcato +variante +vasca +vedetta +vedova +veduto +vegetale +veicolo +velcro +velina +velluto +veloce +venato +vendemmia +vento +verace +verbale +vergogna +verifica +vero +verruca +verticale +vescica +vessillo +vestale +veterano +vetrina +vetusto +viandante +vibrante +vicenda +vichingo +vicinanza +vidimare +vigilia +vigneto +vigore +vile +villano +vimini +vincitore +viola +vipera +virgola +virologo +virulento +viscoso +visione +vispo +vissuto +visura +vita +vitello +vittima +vivanda +vivido +viziare +voce +voga +volatile +volere +volpe +voragine +vulcano +zampogna +zanna +zappato +zattera +zavorra +zefiro +zelante +zelo +zenzero +zerbino +zibetto +zinco +zircone +zitto +zolla +zotico +zucchero +zufolo +zulu +zuppa`.split('\n'); diff --git a/node_modules/@scure/bip39/wordlists/japanese.d.ts b/node_modules/@scure/bip39/wordlists/japanese.d.ts new file mode 100644 index 0000000..b566a1d --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/japanese.d.ts @@ -0,0 +1 @@ +export declare const wordlist: string[]; diff --git a/node_modules/@scure/bip39/wordlists/japanese.js b/node_modules/@scure/bip39/wordlists/japanese.js new file mode 100644 index 0000000..82eda6b --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/japanese.js @@ -0,0 +1,2051 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +exports.wordlist = `あいこくしん +あいさつ +あいだ +あおぞら +あかちゃん +あきる +あけがた +あける +あこがれる +あさい +あさひ +あしあと +あじわう +あずかる +あずき +あそぶ +あたえる +あたためる +あたりまえ +あたる +あつい +あつかう +あっしゅく +あつまり +あつめる +あてな +あてはまる +あひる +あぶら +あぶる +あふれる +あまい +あまど +あまやかす +あまり +あみもの +あめりか +あやまる +あゆむ +あらいぐま +あらし +あらすじ +あらためる +あらゆる +あらわす +ありがとう +あわせる +あわてる +あんい +あんがい +あんこ +あんぜん +あんてい +あんない +あんまり +いいだす +いおん +いがい +いがく +いきおい +いきなり +いきもの +いきる +いくじ +いくぶん +いけばな +いけん +いこう +いこく +いこつ +いさましい +いさん +いしき +いじゅう +いじょう +いじわる +いずみ +いずれ +いせい +いせえび +いせかい +いせき +いぜん +いそうろう +いそがしい +いだい +いだく +いたずら +いたみ +いたりあ +いちおう +いちじ +いちど +いちば +いちぶ +いちりゅう +いつか +いっしゅん +いっせい +いっそう +いったん +いっち +いってい +いっぽう +いてざ +いてん +いどう +いとこ +いない +いなか +いねむり +いのち +いのる +いはつ +いばる +いはん +いびき +いひん +いふく +いへん +いほう +いみん +いもうと +いもたれ +いもり +いやがる +いやす +いよかん +いよく +いらい +いらすと +いりぐち +いりょう +いれい +いれもの +いれる +いろえんぴつ +いわい +いわう +いわかん +いわば +いわゆる +いんげんまめ +いんさつ +いんしょう +いんよう +うえき +うえる +うおざ +うがい +うかぶ +うかべる +うきわ +うくらいな +うくれれ +うけたまわる +うけつけ +うけとる +うけもつ +うける +うごかす +うごく +うこん +うさぎ +うしなう +うしろがみ +うすい +うすぎ +うすぐらい +うすめる +うせつ +うちあわせ +うちがわ +うちき +うちゅう +うっかり +うつくしい +うったえる +うつる +うどん +うなぎ +うなじ +うなずく +うなる +うねる +うのう +うぶげ +うぶごえ +うまれる +うめる +うもう +うやまう +うよく +うらがえす +うらぐち +うらない +うりあげ +うりきれ +うるさい +うれしい +うれゆき +うれる +うろこ +うわき +うわさ +うんこう +うんちん +うんてん +うんどう +えいえん +えいが +えいきょう +えいご +えいせい +えいぶん +えいよう +えいわ +えおり +えがお +えがく +えきたい +えくせる +えしゃく +えすて +えつらん +えのぐ +えほうまき +えほん +えまき +えもじ +えもの +えらい +えらぶ +えりあ +えんえん +えんかい +えんぎ +えんげき +えんしゅう +えんぜつ +えんそく +えんちょう +えんとつ +おいかける +おいこす +おいしい +おいつく +おうえん +おうさま +おうじ +おうせつ +おうたい +おうふく +おうべい +おうよう +おえる +おおい +おおう +おおどおり +おおや +おおよそ +おかえり +おかず +おがむ +おかわり +おぎなう +おきる +おくさま +おくじょう +おくりがな +おくる +おくれる +おこす +おこなう +おこる +おさえる +おさない +おさめる +おしいれ +おしえる +おじぎ +おじさん +おしゃれ +おそらく +おそわる +おたがい +おたく +おだやか +おちつく +おっと +おつり +おでかけ +おとしもの +おとなしい +おどり +おどろかす +おばさん +おまいり +おめでとう +おもいで +おもう +おもたい +おもちゃ +おやつ +おやゆび +およぼす +おらんだ +おろす +おんがく +おんけい +おんしゃ +おんせん +おんだん +おんちゅう +おんどけい +かあつ +かいが +がいき +がいけん +がいこう +かいさつ +かいしゃ +かいすいよく +かいぜん +かいぞうど +かいつう +かいてん +かいとう +かいふく +がいへき +かいほう +かいよう +がいらい +かいわ +かえる +かおり +かかえる +かがく +かがし +かがみ +かくご +かくとく +かざる +がぞう +かたい +かたち +がちょう +がっきゅう +がっこう +がっさん +がっしょう +かなざわし +かのう +がはく +かぶか +かほう +かほご +かまう +かまぼこ +かめれおん +かゆい +かようび +からい +かるい +かろう +かわく +かわら +がんか +かんけい +かんこう +かんしゃ +かんそう +かんたん +かんち +がんばる +きあい +きあつ +きいろ +ぎいん +きうい +きうん +きえる +きおう +きおく +きおち +きおん +きかい +きかく +きかんしゃ +ききて +きくばり +きくらげ +きけんせい +きこう +きこえる +きこく +きさい +きさく +きさま +きさらぎ +ぎじかがく +ぎしき +ぎじたいけん +ぎじにってい +ぎじゅつしゃ +きすう +きせい +きせき +きせつ +きそう +きぞく +きぞん +きたえる +きちょう +きつえん +ぎっちり +きつつき +きつね +きてい +きどう +きどく +きない +きなが +きなこ +きぬごし +きねん +きのう +きのした +きはく +きびしい +きひん +きふく +きぶん +きぼう +きほん +きまる +きみつ +きむずかしい +きめる +きもだめし +きもち +きもの +きゃく +きやく +ぎゅうにく +きよう +きょうりゅう +きらい +きらく +きりん +きれい +きれつ +きろく +ぎろん +きわめる +ぎんいろ +きんかくじ +きんじょ +きんようび +ぐあい +くいず +くうかん +くうき +くうぐん +くうこう +ぐうせい +くうそう +ぐうたら +くうふく +くうぼ +くかん +くきょう +くげん +ぐこう +くさい +くさき +くさばな +くさる +くしゃみ +くしょう +くすのき +くすりゆび +くせげ +くせん +ぐたいてき +くださる +くたびれる +くちこみ +くちさき +くつした +ぐっすり +くつろぐ +くとうてん +くどく +くなん +くねくね +くのう +くふう +くみあわせ +くみたてる +くめる +くやくしょ +くらす +くらべる +くるま +くれる +くろう +くわしい +ぐんかん +ぐんしょく +ぐんたい +ぐんて +けあな +けいかく +けいけん +けいこ +けいさつ +げいじゅつ +けいたい +げいのうじん +けいれき +けいろ +けおとす +けおりもの +げきか +げきげん +げきだん +げきちん +げきとつ +げきは +げきやく +げこう +げこくじょう +げざい +けさき +げざん +けしき +けしごむ +けしょう +げすと +けたば +けちゃっぷ +けちらす +けつあつ +けつい +けつえき +けっこん +けつじょ +けっせき +けってい +けつまつ +げつようび +げつれい +けつろん +げどく +けとばす +けとる +けなげ +けなす +けなみ +けぬき +げねつ +けねん +けはい +げひん +けぶかい +げぼく +けまり +けみかる +けむし +けむり +けもの +けらい +けろけろ +けわしい +けんい +けんえつ +けんお +けんか +げんき +けんげん +けんこう +けんさく +けんしゅう +けんすう +げんそう +けんちく +けんてい +けんとう +けんない +けんにん +げんぶつ +けんま +けんみん +けんめい +けんらん +けんり +こあくま +こいぬ +こいびと +ごうい +こうえん +こうおん +こうかん +ごうきゅう +ごうけい +こうこう +こうさい +こうじ +こうすい +ごうせい +こうそく +こうたい +こうちゃ +こうつう +こうてい +こうどう +こうない +こうはい +ごうほう +ごうまん +こうもく +こうりつ +こえる +こおり +ごかい +ごがつ +ごかん +こくご +こくさい +こくとう +こくない +こくはく +こぐま +こけい +こける +ここのか +こころ +こさめ +こしつ +こすう +こせい +こせき +こぜん +こそだて +こたい +こたえる +こたつ +こちょう +こっか +こつこつ +こつばん +こつぶ +こてい +こてん +ことがら +ことし +ことば +ことり +こなごな +こねこね +このまま +このみ +このよ +ごはん +こひつじ +こふう +こふん +こぼれる +ごまあぶら +こまかい +ごますり +こまつな +こまる +こむぎこ +こもじ +こもち +こもの +こもん +こやく +こやま +こゆう +こゆび +こよい +こよう +こりる +これくしょん +ころっけ +こわもて +こわれる +こんいん +こんかい +こんき +こんしゅう +こんすい +こんだて +こんとん +こんなん +こんびに +こんぽん +こんまけ +こんや +こんれい +こんわく +ざいえき +さいかい +さいきん +ざいげん +ざいこ +さいしょ +さいせい +ざいたく +ざいちゅう +さいてき +ざいりょう +さうな +さかいし +さがす +さかな +さかみち +さがる +さぎょう +さくし +さくひん +さくら +さこく +さこつ +さずかる +ざせき +さたん +さつえい +ざつおん +ざっか +ざつがく +さっきょく +ざっし +さつじん +ざっそう +さつたば +さつまいも +さてい +さといも +さとう +さとおや +さとし +さとる +さのう +さばく +さびしい +さべつ +さほう +さほど +さます +さみしい +さみだれ +さむけ +さめる +さやえんどう +さゆう +さよう +さよく +さらだ +ざるそば +さわやか +さわる +さんいん +さんか +さんきゃく +さんこう +さんさい +ざんしょ +さんすう +さんせい +さんそ +さんち +さんま +さんみ +さんらん +しあい +しあげ +しあさって +しあわせ +しいく +しいん +しうち +しえい +しおけ +しかい +しかく +じかん +しごと +しすう +じだい +したうけ +したぎ +したて +したみ +しちょう +しちりん +しっかり +しつじ +しつもん +してい +してき +してつ +じてん +じどう +しなぎれ +しなもの +しなん +しねま +しねん +しのぐ +しのぶ +しはい +しばかり +しはつ +しはらい +しはん +しひょう +しふく +じぶん +しへい +しほう +しほん +しまう +しまる +しみん +しむける +じむしょ +しめい +しめる +しもん +しゃいん +しゃうん +しゃおん +じゃがいも +しやくしょ +しゃくほう +しゃけん +しゃこ +しゃざい +しゃしん +しゃせん +しゃそう +しゃたい +しゃちょう +しゃっきん +じゃま +しゃりん +しゃれい +じゆう +じゅうしょ +しゅくはく +じゅしん +しゅっせき +しゅみ +しゅらば +じゅんばん +しょうかい +しょくたく +しょっけん +しょどう +しょもつ +しらせる +しらべる +しんか +しんこう +じんじゃ +しんせいじ +しんちく +しんりん +すあげ +すあし +すあな +ずあん +すいえい +すいか +すいとう +ずいぶん +すいようび +すうがく +すうじつ +すうせん +すおどり +すきま +すくう +すくない +すける +すごい +すこし +ずさん +すずしい +すすむ +すすめる +すっかり +ずっしり +ずっと +すてき +すてる +すねる +すのこ +すはだ +すばらしい +ずひょう +ずぶぬれ +すぶり +すふれ +すべて +すべる +ずほう +すぼん +すまい +すめし +すもう +すやき +すらすら +するめ +すれちがう +すろっと +すわる +すんぜん +すんぽう +せあぶら +せいかつ +せいげん +せいじ +せいよう +せおう +せかいかん +せきにん +せきむ +せきゆ +せきらんうん +せけん +せこう +せすじ +せたい +せたけ +せっかく +せっきゃく +ぜっく +せっけん +せっこつ +せっさたくま +せつぞく +せつだん +せつでん +せっぱん +せつび +せつぶん +せつめい +せつりつ +せなか +せのび +せはば +せびろ +せぼね +せまい +せまる +せめる +せもたれ +せりふ +ぜんあく +せんい +せんえい +せんか +せんきょ +せんく +せんげん +ぜんご +せんさい +せんしゅ +せんすい +せんせい +せんぞ +せんたく +せんちょう +せんてい +せんとう +せんぬき +せんねん +せんぱい +ぜんぶ +ぜんぽう +せんむ +せんめんじょ +せんもん +せんやく +せんゆう +せんよう +ぜんら +ぜんりゃく +せんれい +せんろ +そあく +そいとげる +そいね +そうがんきょう +そうき +そうご +そうしん +そうだん +そうなん +そうび +そうめん +そうり +そえもの +そえん +そがい +そげき +そこう +そこそこ +そざい +そしな +そせい +そせん +そそぐ +そだてる +そつう +そつえん +そっかん +そつぎょう +そっけつ +そっこう +そっせん +そっと +そとがわ +そとづら +そなえる +そなた +そふぼ +そぼく +そぼろ +そまつ +そまる +そむく +そむりえ +そめる +そもそも +そよかぜ +そらまめ +そろう +そんかい +そんけい +そんざい +そんしつ +そんぞく +そんちょう +ぞんび +ぞんぶん +そんみん +たあい +たいいん +たいうん +たいえき +たいおう +だいがく +たいき +たいぐう +たいけん +たいこ +たいざい +だいじょうぶ +だいすき +たいせつ +たいそう +だいたい +たいちょう +たいてい +だいどころ +たいない +たいねつ +たいのう +たいはん +だいひょう +たいふう +たいへん +たいほ +たいまつばな +たいみんぐ +たいむ +たいめん +たいやき +たいよう +たいら +たいりょく +たいる +たいわん +たうえ +たえる +たおす +たおる +たおれる +たかい +たかね +たきび +たくさん +たこく +たこやき +たさい +たしざん +だじゃれ +たすける +たずさわる +たそがれ +たたかう +たたく +ただしい +たたみ +たちばな +だっかい +だっきゃく +だっこ +だっしゅつ +だったい +たてる +たとえる +たなばた +たにん +たぬき +たのしみ +たはつ +たぶん +たべる +たぼう +たまご +たまる +だむる +ためいき +ためす +ためる +たもつ +たやすい +たよる +たらす +たりきほんがん +たりょう +たりる +たると +たれる +たれんと +たろっと +たわむれる +だんあつ +たんい +たんおん +たんか +たんき +たんけん +たんご +たんさん +たんじょうび +だんせい +たんそく +たんたい +だんち +たんてい +たんとう +だんな +たんにん +だんねつ +たんのう +たんぴん +だんぼう +たんまつ +たんめい +だんれつ +だんろ +だんわ +ちあい +ちあん +ちいき +ちいさい +ちえん +ちかい +ちから +ちきゅう +ちきん +ちけいず +ちけん +ちこく +ちさい +ちしき +ちしりょう +ちせい +ちそう +ちたい +ちたん +ちちおや +ちつじょ +ちてき +ちてん +ちぬき +ちぬり +ちのう +ちひょう +ちへいせん +ちほう +ちまた +ちみつ +ちみどろ +ちめいど +ちゃんこなべ +ちゅうい +ちゆりょく +ちょうし +ちょさくけん +ちらし +ちらみ +ちりがみ +ちりょう +ちるど +ちわわ +ちんたい +ちんもく +ついか +ついたち +つうか +つうじょう +つうはん +つうわ +つかう +つかれる +つくね +つくる +つけね +つける +つごう +つたえる +つづく +つつじ +つつむ +つとめる +つながる +つなみ +つねづね +つのる +つぶす +つまらない +つまる +つみき +つめたい +つもり +つもる +つよい +つるぼ +つるみく +つわもの +つわり +てあし +てあて +てあみ +ていおん +ていか +ていき +ていけい +ていこく +ていさつ +ていし +ていせい +ていたい +ていど +ていねい +ていひょう +ていへん +ていぼう +てうち +ておくれ +てきとう +てくび +でこぼこ +てさぎょう +てさげ +てすり +てそう +てちがい +てちょう +てつがく +てつづき +でっぱ +てつぼう +てつや +でぬかえ +てぬき +てぬぐい +てのひら +てはい +てぶくろ +てふだ +てほどき +てほん +てまえ +てまきずし +てみじか +てみやげ +てらす +てれび +てわけ +てわたし +でんあつ +てんいん +てんかい +てんき +てんぐ +てんけん +てんごく +てんさい +てんし +てんすう +でんち +てんてき +てんとう +てんない +てんぷら +てんぼうだい +てんめつ +てんらんかい +でんりょく +でんわ +どあい +といれ +どうかん +とうきゅう +どうぐ +とうし +とうむぎ +とおい +とおか +とおく +とおす +とおる +とかい +とかす +ときおり +ときどき +とくい +とくしゅう +とくてん +とくに +とくべつ +とけい +とける +とこや +とさか +としょかん +とそう +とたん +とちゅう +とっきゅう +とっくん +とつぜん +とつにゅう +とどける +ととのえる +とない +となえる +となり +とのさま +とばす +どぶがわ +とほう +とまる +とめる +ともだち +ともる +どようび +とらえる +とんかつ +どんぶり +ないかく +ないこう +ないしょ +ないす +ないせん +ないそう +なおす +ながい +なくす +なげる +なこうど +なさけ +なたでここ +なっとう +なつやすみ +ななおし +なにごと +なにもの +なにわ +なのか +なふだ +なまいき +なまえ +なまみ +なみだ +なめらか +なめる +なやむ +ならう +ならび +ならぶ +なれる +なわとび +なわばり +にあう +にいがた +にうけ +におい +にかい +にがて +にきび +にくしみ +にくまん +にげる +にさんかたんそ +にしき +にせもの +にちじょう +にちようび +にっか +にっき +にっけい +にっこう +にっさん +にっしょく +にっすう +にっせき +にってい +になう +にほん +にまめ +にもつ +にやり +にゅういん +にりんしゃ +にわとり +にんい +にんか +にんき +にんげん +にんしき +にんずう +にんそう +にんたい +にんち +にんてい +にんにく +にんぷ +にんまり +にんむ +にんめい +にんよう +ぬいくぎ +ぬかす +ぬぐいとる +ぬぐう +ぬくもり +ぬすむ +ぬまえび +ぬめり +ぬらす +ぬんちゃく +ねあげ +ねいき +ねいる +ねいろ +ねぐせ +ねくたい +ねくら +ねこぜ +ねこむ +ねさげ +ねすごす +ねそべる +ねだん +ねつい +ねっしん +ねつぞう +ねったいぎょ +ねぶそく +ねふだ +ねぼう +ねほりはほり +ねまき +ねまわし +ねみみ +ねむい +ねむたい +ねもと +ねらう +ねわざ +ねんいり +ねんおし +ねんかん +ねんきん +ねんぐ +ねんざ +ねんし +ねんちゃく +ねんど +ねんぴ +ねんぶつ +ねんまつ +ねんりょう +ねんれい +のいず +のおづま +のがす +のきなみ +のこぎり +のこす +のこる +のせる +のぞく +のぞむ +のたまう +のちほど +のっく +のばす +のはら +のべる +のぼる +のみもの +のやま +のらいぬ +のらねこ +のりもの +のりゆき +のれん +のんき +ばあい +はあく +ばあさん +ばいか +ばいく +はいけん +はいご +はいしん +はいすい +はいせん +はいそう +はいち +ばいばい +はいれつ +はえる +はおる +はかい +ばかり +はかる +はくしゅ +はけん +はこぶ +はさみ +はさん +はしご +ばしょ +はしる +はせる +ぱそこん +はそん +はたん +はちみつ +はつおん +はっかく +はづき +はっきり +はっくつ +はっけん +はっこう +はっさん +はっしん +はったつ +はっちゅう +はってん +はっぴょう +はっぽう +はなす +はなび +はにかむ +はぶらし +はみがき +はむかう +はめつ +はやい +はやし +はらう +はろうぃん +はわい +はんい +はんえい +はんおん +はんかく +はんきょう +ばんぐみ +はんこ +はんしゃ +はんすう +はんだん +ぱんち +ぱんつ +はんてい +はんとし +はんのう +はんぱ +はんぶん +はんぺん +はんぼうき +はんめい +はんらん +はんろん +ひいき +ひうん +ひえる +ひかく +ひかり +ひかる +ひかん +ひくい +ひけつ +ひこうき +ひこく +ひさい +ひさしぶり +ひさん +びじゅつかん +ひしょ +ひそか +ひそむ +ひたむき +ひだり +ひたる +ひつぎ +ひっこし +ひっし +ひつじゅひん +ひっす +ひつぜん +ぴったり +ぴっちり +ひつよう +ひてい +ひとごみ +ひなまつり +ひなん +ひねる +ひはん +ひびく +ひひょう +ひほう +ひまわり +ひまん +ひみつ +ひめい +ひめじし +ひやけ +ひやす +ひよう +びょうき +ひらがな +ひらく +ひりつ +ひりょう +ひるま +ひるやすみ +ひれい +ひろい +ひろう +ひろき +ひろゆき +ひんかく +ひんけつ +ひんこん +ひんしゅ +ひんそう +ぴんち +ひんぱん +びんぼう +ふあん +ふいうち +ふうけい +ふうせん +ぷうたろう +ふうとう +ふうふ +ふえる +ふおん +ふかい +ふきん +ふくざつ +ふくぶくろ +ふこう +ふさい +ふしぎ +ふじみ +ふすま +ふせい +ふせぐ +ふそく +ぶたにく +ふたん +ふちょう +ふつう +ふつか +ふっかつ +ふっき +ふっこく +ぶどう +ふとる +ふとん +ふのう +ふはい +ふひょう +ふへん +ふまん +ふみん +ふめつ +ふめん +ふよう +ふりこ +ふりる +ふるい +ふんいき +ぶんがく +ぶんぐ +ふんしつ +ぶんせき +ふんそう +ぶんぽう +へいあん +へいおん +へいがい +へいき +へいげん +へいこう +へいさ +へいしゃ +へいせつ +へいそ +へいたく +へいてん +へいねつ +へいわ +へきが +へこむ +べにいろ +べにしょうが +へらす +へんかん +べんきょう +べんごし +へんさい +へんたい +べんり +ほあん +ほいく +ぼうぎょ +ほうこく +ほうそう +ほうほう +ほうもん +ほうりつ +ほえる +ほおん +ほかん +ほきょう +ぼきん +ほくろ +ほけつ +ほけん +ほこう +ほこる +ほしい +ほしつ +ほしゅ +ほしょう +ほせい +ほそい +ほそく +ほたて +ほたる +ぽちぶくろ +ほっきょく +ほっさ +ほったん +ほとんど +ほめる +ほんい +ほんき +ほんけ +ほんしつ +ほんやく +まいにち +まかい +まかせる +まがる +まける +まこと +まさつ +まじめ +ますく +まぜる +まつり +まとめ +まなぶ +まぬけ +まねく +まほう +まもる +まゆげ +まよう +まろやか +まわす +まわり +まわる +まんが +まんきつ +まんぞく +まんなか +みいら +みうち +みえる +みがく +みかた +みかん +みけん +みこん +みじかい +みすい +みすえる +みせる +みっか +みつかる +みつける +みてい +みとめる +みなと +みなみかさい +みねらる +みのう +みのがす +みほん +みもと +みやげ +みらい +みりょく +みわく +みんか +みんぞく +むいか +むえき +むえん +むかい +むかう +むかえ +むかし +むぎちゃ +むける +むげん +むさぼる +むしあつい +むしば +むじゅん +むしろ +むすう +むすこ +むすぶ +むすめ +むせる +むせん +むちゅう +むなしい +むのう +むやみ +むよう +むらさき +むりょう +むろん +めいあん +めいうん +めいえん +めいかく +めいきょく +めいさい +めいし +めいそう +めいぶつ +めいれい +めいわく +めぐまれる +めざす +めした +めずらしい +めだつ +めまい +めやす +めんきょ +めんせき +めんどう +もうしあげる +もうどうけん +もえる +もくし +もくてき +もくようび +もちろん +もどる +もらう +もんく +もんだい +やおや +やける +やさい +やさしい +やすい +やすたろう +やすみ +やせる +やそう +やたい +やちん +やっと +やっぱり +やぶる +やめる +ややこしい +やよい +やわらかい +ゆうき +ゆうびんきょく +ゆうべ +ゆうめい +ゆけつ +ゆしゅつ +ゆせん +ゆそう +ゆたか +ゆちゃく +ゆでる +ゆにゅう +ゆびわ +ゆらい +ゆれる +ようい +ようか +ようきゅう +ようじ +ようす +ようちえん +よかぜ +よかん +よきん +よくせい +よくぼう +よけい +よごれる +よさん +よしゅう +よそう +よそく +よっか +よてい +よどがわく +よねつ +よやく +よゆう +よろこぶ +よろしい +らいう +らくがき +らくご +らくさつ +らくだ +らしんばん +らせん +らぞく +らたい +らっか +られつ +りえき +りかい +りきさく +りきせつ +りくぐん +りくつ +りけん +りこう +りせい +りそう +りそく +りてん +りねん +りゆう +りゅうがく +りよう +りょうり +りょかん +りょくちゃ +りょこう +りりく +りれき +りろん +りんご +るいけい +るいさい +るいじ +るいせき +るすばん +るりがわら +れいかん +れいぎ +れいせい +れいぞうこ +れいとう +れいぼう +れきし +れきだい +れんあい +れんけい +れんこん +れんさい +れんしゅう +れんぞく +れんらく +ろうか +ろうご +ろうじん +ろうそく +ろくが +ろこつ +ろじうら +ろしゅつ +ろせん +ろてん +ろめん +ろれつ +ろんぎ +ろんぱ +ろんぶん +ろんり +わかす +わかめ +わかやま +わかれる +わしつ +わじまし +わすれもの +わらう +われる`.split('\n'); diff --git a/node_modules/@scure/bip39/wordlists/korean.d.ts b/node_modules/@scure/bip39/wordlists/korean.d.ts new file mode 100644 index 0000000..b566a1d --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/korean.d.ts @@ -0,0 +1 @@ +export declare const wordlist: string[]; diff --git a/node_modules/@scure/bip39/wordlists/korean.js b/node_modules/@scure/bip39/wordlists/korean.js new file mode 100644 index 0000000..15ba442 --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/korean.js @@ -0,0 +1,2051 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +exports.wordlist = `가격 +가끔 +가난 +가능 +가득 +가르침 +가뭄 +가방 +가상 +가슴 +가운데 +가을 +가이드 +가입 +가장 +가정 +가족 +가죽 +각오 +각자 +간격 +간부 +간섭 +간장 +간접 +간판 +갈등 +갈비 +갈색 +갈증 +감각 +감기 +감소 +감수성 +감자 +감정 +갑자기 +강남 +강당 +강도 +강력히 +강변 +강북 +강사 +강수량 +강아지 +강원도 +강의 +강제 +강조 +같이 +개구리 +개나리 +개방 +개별 +개선 +개성 +개인 +객관적 +거실 +거액 +거울 +거짓 +거품 +걱정 +건강 +건물 +건설 +건조 +건축 +걸음 +검사 +검토 +게시판 +게임 +겨울 +견해 +결과 +결국 +결론 +결석 +결승 +결심 +결정 +결혼 +경계 +경고 +경기 +경력 +경복궁 +경비 +경상도 +경영 +경우 +경쟁 +경제 +경주 +경찰 +경치 +경향 +경험 +계곡 +계단 +계란 +계산 +계속 +계약 +계절 +계층 +계획 +고객 +고구려 +고궁 +고급 +고등학생 +고무신 +고민 +고양이 +고장 +고전 +고집 +고춧가루 +고통 +고향 +곡식 +골목 +골짜기 +골프 +공간 +공개 +공격 +공군 +공급 +공기 +공동 +공무원 +공부 +공사 +공식 +공업 +공연 +공원 +공장 +공짜 +공책 +공통 +공포 +공항 +공휴일 +과목 +과일 +과장 +과정 +과학 +관객 +관계 +관광 +관념 +관람 +관련 +관리 +관습 +관심 +관점 +관찰 +광경 +광고 +광장 +광주 +괴로움 +굉장히 +교과서 +교문 +교복 +교실 +교양 +교육 +교장 +교직 +교통 +교환 +교훈 +구경 +구름 +구멍 +구별 +구분 +구석 +구성 +구속 +구역 +구입 +구청 +구체적 +국가 +국기 +국내 +국립 +국물 +국민 +국수 +국어 +국왕 +국적 +국제 +국회 +군대 +군사 +군인 +궁극적 +권리 +권위 +권투 +귀국 +귀신 +규정 +규칙 +균형 +그날 +그냥 +그늘 +그러나 +그룹 +그릇 +그림 +그제서야 +그토록 +극복 +극히 +근거 +근교 +근래 +근로 +근무 +근본 +근원 +근육 +근처 +글씨 +글자 +금강산 +금고 +금년 +금메달 +금액 +금연 +금요일 +금지 +긍정적 +기간 +기관 +기념 +기능 +기독교 +기둥 +기록 +기름 +기법 +기본 +기분 +기쁨 +기숙사 +기술 +기억 +기업 +기온 +기운 +기원 +기적 +기준 +기침 +기혼 +기획 +긴급 +긴장 +길이 +김밥 +김치 +김포공항 +깍두기 +깜빡 +깨달음 +깨소금 +껍질 +꼭대기 +꽃잎 +나들이 +나란히 +나머지 +나물 +나침반 +나흘 +낙엽 +난방 +날개 +날씨 +날짜 +남녀 +남대문 +남매 +남산 +남자 +남편 +남학생 +낭비 +낱말 +내년 +내용 +내일 +냄비 +냄새 +냇물 +냉동 +냉면 +냉방 +냉장고 +넥타이 +넷째 +노동 +노란색 +노력 +노인 +녹음 +녹차 +녹화 +논리 +논문 +논쟁 +놀이 +농구 +농담 +농민 +농부 +농업 +농장 +농촌 +높이 +눈동자 +눈물 +눈썹 +뉴욕 +느낌 +늑대 +능동적 +능력 +다방 +다양성 +다음 +다이어트 +다행 +단계 +단골 +단독 +단맛 +단순 +단어 +단위 +단점 +단체 +단추 +단편 +단풍 +달걀 +달러 +달력 +달리 +닭고기 +담당 +담배 +담요 +담임 +답변 +답장 +당근 +당분간 +당연히 +당장 +대규모 +대낮 +대단히 +대답 +대도시 +대략 +대량 +대륙 +대문 +대부분 +대신 +대응 +대장 +대전 +대접 +대중 +대책 +대출 +대충 +대통령 +대학 +대한민국 +대합실 +대형 +덩어리 +데이트 +도대체 +도덕 +도둑 +도망 +도서관 +도심 +도움 +도입 +도자기 +도저히 +도전 +도중 +도착 +독감 +독립 +독서 +독일 +독창적 +동화책 +뒷모습 +뒷산 +딸아이 +마누라 +마늘 +마당 +마라톤 +마련 +마무리 +마사지 +마약 +마요네즈 +마을 +마음 +마이크 +마중 +마지막 +마찬가지 +마찰 +마흔 +막걸리 +막내 +막상 +만남 +만두 +만세 +만약 +만일 +만점 +만족 +만화 +많이 +말기 +말씀 +말투 +맘대로 +망원경 +매년 +매달 +매력 +매번 +매스컴 +매일 +매장 +맥주 +먹이 +먼저 +먼지 +멀리 +메일 +며느리 +며칠 +면담 +멸치 +명단 +명령 +명예 +명의 +명절 +명칭 +명함 +모금 +모니터 +모델 +모든 +모범 +모습 +모양 +모임 +모조리 +모집 +모퉁이 +목걸이 +목록 +목사 +목소리 +목숨 +목적 +목표 +몰래 +몸매 +몸무게 +몸살 +몸속 +몸짓 +몸통 +몹시 +무관심 +무궁화 +무더위 +무덤 +무릎 +무슨 +무엇 +무역 +무용 +무조건 +무지개 +무척 +문구 +문득 +문법 +문서 +문제 +문학 +문화 +물가 +물건 +물결 +물고기 +물론 +물리학 +물음 +물질 +물체 +미국 +미디어 +미사일 +미술 +미역 +미용실 +미움 +미인 +미팅 +미혼 +민간 +민족 +민주 +믿음 +밀가루 +밀리미터 +밑바닥 +바가지 +바구니 +바나나 +바늘 +바닥 +바닷가 +바람 +바이러스 +바탕 +박물관 +박사 +박수 +반대 +반드시 +반말 +반발 +반성 +반응 +반장 +반죽 +반지 +반찬 +받침 +발가락 +발걸음 +발견 +발달 +발레 +발목 +발바닥 +발생 +발음 +발자국 +발전 +발톱 +발표 +밤하늘 +밥그릇 +밥맛 +밥상 +밥솥 +방금 +방면 +방문 +방바닥 +방법 +방송 +방식 +방안 +방울 +방지 +방학 +방해 +방향 +배경 +배꼽 +배달 +배드민턴 +백두산 +백색 +백성 +백인 +백제 +백화점 +버릇 +버섯 +버튼 +번개 +번역 +번지 +번호 +벌금 +벌레 +벌써 +범위 +범인 +범죄 +법률 +법원 +법적 +법칙 +베이징 +벨트 +변경 +변동 +변명 +변신 +변호사 +변화 +별도 +별명 +별일 +병실 +병아리 +병원 +보관 +보너스 +보라색 +보람 +보름 +보상 +보안 +보자기 +보장 +보전 +보존 +보통 +보편적 +보험 +복도 +복사 +복숭아 +복습 +볶음 +본격적 +본래 +본부 +본사 +본성 +본인 +본질 +볼펜 +봉사 +봉지 +봉투 +부근 +부끄러움 +부담 +부동산 +부문 +부분 +부산 +부상 +부엌 +부인 +부작용 +부장 +부정 +부족 +부지런히 +부친 +부탁 +부품 +부회장 +북부 +북한 +분노 +분량 +분리 +분명 +분석 +분야 +분위기 +분필 +분홍색 +불고기 +불과 +불교 +불꽃 +불만 +불법 +불빛 +불안 +불이익 +불행 +브랜드 +비극 +비난 +비닐 +비둘기 +비디오 +비로소 +비만 +비명 +비밀 +비바람 +비빔밥 +비상 +비용 +비율 +비중 +비타민 +비판 +빌딩 +빗물 +빗방울 +빗줄기 +빛깔 +빨간색 +빨래 +빨리 +사건 +사계절 +사나이 +사냥 +사람 +사랑 +사립 +사모님 +사물 +사방 +사상 +사생활 +사설 +사슴 +사실 +사업 +사용 +사월 +사장 +사전 +사진 +사촌 +사춘기 +사탕 +사투리 +사흘 +산길 +산부인과 +산업 +산책 +살림 +살인 +살짝 +삼계탕 +삼국 +삼십 +삼월 +삼촌 +상관 +상금 +상대 +상류 +상반기 +상상 +상식 +상업 +상인 +상자 +상점 +상처 +상추 +상태 +상표 +상품 +상황 +새벽 +색깔 +색연필 +생각 +생명 +생물 +생방송 +생산 +생선 +생신 +생일 +생활 +서랍 +서른 +서명 +서민 +서비스 +서양 +서울 +서적 +서점 +서쪽 +서클 +석사 +석유 +선거 +선물 +선배 +선생 +선수 +선원 +선장 +선전 +선택 +선풍기 +설거지 +설날 +설렁탕 +설명 +설문 +설사 +설악산 +설치 +설탕 +섭씨 +성공 +성당 +성명 +성별 +성인 +성장 +성적 +성질 +성함 +세금 +세미나 +세상 +세월 +세종대왕 +세탁 +센터 +센티미터 +셋째 +소규모 +소극적 +소금 +소나기 +소년 +소득 +소망 +소문 +소설 +소속 +소아과 +소용 +소원 +소음 +소중히 +소지품 +소질 +소풍 +소형 +속담 +속도 +속옷 +손가락 +손길 +손녀 +손님 +손등 +손목 +손뼉 +손실 +손질 +손톱 +손해 +솔직히 +솜씨 +송아지 +송이 +송편 +쇠고기 +쇼핑 +수건 +수년 +수단 +수돗물 +수동적 +수면 +수명 +수박 +수상 +수석 +수술 +수시로 +수업 +수염 +수영 +수입 +수준 +수집 +수출 +수컷 +수필 +수학 +수험생 +수화기 +숙녀 +숙소 +숙제 +순간 +순서 +순수 +순식간 +순위 +숟가락 +술병 +술집 +숫자 +스님 +스물 +스스로 +스승 +스웨터 +스위치 +스케이트 +스튜디오 +스트레스 +스포츠 +슬쩍 +슬픔 +습관 +습기 +승객 +승리 +승부 +승용차 +승진 +시각 +시간 +시골 +시금치 +시나리오 +시댁 +시리즈 +시멘트 +시민 +시부모 +시선 +시설 +시스템 +시아버지 +시어머니 +시월 +시인 +시일 +시작 +시장 +시절 +시점 +시중 +시즌 +시집 +시청 +시합 +시험 +식구 +식기 +식당 +식량 +식료품 +식물 +식빵 +식사 +식생활 +식초 +식탁 +식품 +신고 +신규 +신념 +신문 +신발 +신비 +신사 +신세 +신용 +신제품 +신청 +신체 +신화 +실감 +실내 +실력 +실례 +실망 +실수 +실습 +실시 +실장 +실정 +실질적 +실천 +실체 +실컷 +실태 +실패 +실험 +실현 +심리 +심부름 +심사 +심장 +심정 +심판 +쌍둥이 +씨름 +씨앗 +아가씨 +아나운서 +아드님 +아들 +아쉬움 +아스팔트 +아시아 +아울러 +아저씨 +아줌마 +아직 +아침 +아파트 +아프리카 +아픔 +아홉 +아흔 +악기 +악몽 +악수 +안개 +안경 +안과 +안내 +안녕 +안동 +안방 +안부 +안주 +알루미늄 +알코올 +암시 +암컷 +압력 +앞날 +앞문 +애인 +애정 +액수 +앨범 +야간 +야단 +야옹 +약간 +약국 +약속 +약수 +약점 +약품 +약혼녀 +양념 +양력 +양말 +양배추 +양주 +양파 +어둠 +어려움 +어른 +어젯밤 +어쨌든 +어쩌다가 +어쩐지 +언니 +언덕 +언론 +언어 +얼굴 +얼른 +얼음 +얼핏 +엄마 +업무 +업종 +업체 +엉덩이 +엉망 +엉터리 +엊그제 +에너지 +에어컨 +엔진 +여건 +여고생 +여관 +여군 +여권 +여대생 +여덟 +여동생 +여든 +여론 +여름 +여섯 +여성 +여왕 +여인 +여전히 +여직원 +여학생 +여행 +역사 +역시 +역할 +연결 +연구 +연극 +연기 +연락 +연설 +연세 +연속 +연습 +연애 +연예인 +연인 +연장 +연주 +연출 +연필 +연합 +연휴 +열기 +열매 +열쇠 +열심히 +열정 +열차 +열흘 +염려 +엽서 +영국 +영남 +영상 +영양 +영역 +영웅 +영원히 +영하 +영향 +영혼 +영화 +옆구리 +옆방 +옆집 +예감 +예금 +예방 +예산 +예상 +예선 +예술 +예습 +예식장 +예약 +예전 +예절 +예정 +예컨대 +옛날 +오늘 +오락 +오랫동안 +오렌지 +오로지 +오른발 +오븐 +오십 +오염 +오월 +오전 +오직 +오징어 +오페라 +오피스텔 +오히려 +옥상 +옥수수 +온갖 +온라인 +온몸 +온종일 +온통 +올가을 +올림픽 +올해 +옷차림 +와이셔츠 +와인 +완성 +완전 +왕비 +왕자 +왜냐하면 +왠지 +외갓집 +외국 +외로움 +외삼촌 +외출 +외침 +외할머니 +왼발 +왼손 +왼쪽 +요금 +요일 +요즘 +요청 +용기 +용서 +용어 +우산 +우선 +우승 +우연히 +우정 +우체국 +우편 +운동 +운명 +운반 +운전 +운행 +울산 +울음 +움직임 +웃어른 +웃음 +워낙 +원고 +원래 +원서 +원숭이 +원인 +원장 +원피스 +월급 +월드컵 +월세 +월요일 +웨이터 +위반 +위법 +위성 +위원 +위험 +위협 +윗사람 +유난히 +유럽 +유명 +유물 +유산 +유적 +유치원 +유학 +유행 +유형 +육군 +육상 +육십 +육체 +은행 +음력 +음료 +음반 +음성 +음식 +음악 +음주 +의견 +의논 +의문 +의복 +의식 +의심 +의외로 +의욕 +의원 +의학 +이것 +이곳 +이념 +이놈 +이달 +이대로 +이동 +이렇게 +이력서 +이론적 +이름 +이민 +이발소 +이별 +이불 +이빨 +이상 +이성 +이슬 +이야기 +이용 +이웃 +이월 +이윽고 +이익 +이전 +이중 +이튿날 +이틀 +이혼 +인간 +인격 +인공 +인구 +인근 +인기 +인도 +인류 +인물 +인생 +인쇄 +인연 +인원 +인재 +인종 +인천 +인체 +인터넷 +인하 +인형 +일곱 +일기 +일단 +일대 +일등 +일반 +일본 +일부 +일상 +일생 +일손 +일요일 +일월 +일정 +일종 +일주일 +일찍 +일체 +일치 +일행 +일회용 +임금 +임무 +입대 +입력 +입맛 +입사 +입술 +입시 +입원 +입장 +입학 +자가용 +자격 +자극 +자동 +자랑 +자부심 +자식 +자신 +자연 +자원 +자율 +자전거 +자정 +자존심 +자판 +작가 +작년 +작성 +작업 +작용 +작은딸 +작품 +잔디 +잔뜩 +잔치 +잘못 +잠깐 +잠수함 +잠시 +잠옷 +잠자리 +잡지 +장관 +장군 +장기간 +장래 +장례 +장르 +장마 +장면 +장모 +장미 +장비 +장사 +장소 +장식 +장애인 +장인 +장점 +장차 +장학금 +재능 +재빨리 +재산 +재생 +재작년 +재정 +재채기 +재판 +재학 +재활용 +저것 +저고리 +저곳 +저녁 +저런 +저렇게 +저번 +저울 +저절로 +저축 +적극 +적당히 +적성 +적용 +적응 +전개 +전공 +전기 +전달 +전라도 +전망 +전문 +전반 +전부 +전세 +전시 +전용 +전자 +전쟁 +전주 +전철 +전체 +전통 +전혀 +전후 +절대 +절망 +절반 +절약 +절차 +점검 +점수 +점심 +점원 +점점 +점차 +접근 +접시 +접촉 +젓가락 +정거장 +정도 +정류장 +정리 +정말 +정면 +정문 +정반대 +정보 +정부 +정비 +정상 +정성 +정오 +정원 +정장 +정지 +정치 +정확히 +제공 +제과점 +제대로 +제목 +제발 +제법 +제삿날 +제안 +제일 +제작 +제주도 +제출 +제품 +제한 +조각 +조건 +조금 +조깅 +조명 +조미료 +조상 +조선 +조용히 +조절 +조정 +조직 +존댓말 +존재 +졸업 +졸음 +종교 +종로 +종류 +종소리 +종업원 +종종 +종합 +좌석 +죄인 +주관적 +주름 +주말 +주머니 +주먹 +주문 +주민 +주방 +주변 +주식 +주인 +주일 +주장 +주전자 +주택 +준비 +줄거리 +줄기 +줄무늬 +중간 +중계방송 +중국 +중년 +중단 +중독 +중반 +중부 +중세 +중소기업 +중순 +중앙 +중요 +중학교 +즉석 +즉시 +즐거움 +증가 +증거 +증권 +증상 +증세 +지각 +지갑 +지경 +지극히 +지금 +지급 +지능 +지름길 +지리산 +지방 +지붕 +지식 +지역 +지우개 +지원 +지적 +지점 +지진 +지출 +직선 +직업 +직원 +직장 +진급 +진동 +진로 +진료 +진리 +진짜 +진찰 +진출 +진통 +진행 +질문 +질병 +질서 +짐작 +집단 +집안 +집중 +짜증 +찌꺼기 +차남 +차라리 +차량 +차림 +차별 +차선 +차츰 +착각 +찬물 +찬성 +참가 +참기름 +참새 +참석 +참여 +참외 +참조 +찻잔 +창가 +창고 +창구 +창문 +창밖 +창작 +창조 +채널 +채점 +책가방 +책방 +책상 +책임 +챔피언 +처벌 +처음 +천국 +천둥 +천장 +천재 +천천히 +철도 +철저히 +철학 +첫날 +첫째 +청년 +청바지 +청소 +청춘 +체계 +체력 +체온 +체육 +체중 +체험 +초등학생 +초반 +초밥 +초상화 +초순 +초여름 +초원 +초저녁 +초점 +초청 +초콜릿 +촛불 +총각 +총리 +총장 +촬영 +최근 +최상 +최선 +최신 +최악 +최종 +추석 +추억 +추진 +추천 +추측 +축구 +축소 +축제 +축하 +출근 +출발 +출산 +출신 +출연 +출입 +출장 +출판 +충격 +충고 +충돌 +충분히 +충청도 +취업 +취직 +취향 +치약 +친구 +친척 +칠십 +칠월 +칠판 +침대 +침묵 +침실 +칫솔 +칭찬 +카메라 +카운터 +칼국수 +캐릭터 +캠퍼스 +캠페인 +커튼 +컨디션 +컬러 +컴퓨터 +코끼리 +코미디 +콘서트 +콜라 +콤플렉스 +콩나물 +쾌감 +쿠데타 +크림 +큰길 +큰딸 +큰소리 +큰아들 +큰어머니 +큰일 +큰절 +클래식 +클럽 +킬로 +타입 +타자기 +탁구 +탁자 +탄생 +태권도 +태양 +태풍 +택시 +탤런트 +터널 +터미널 +테니스 +테스트 +테이블 +텔레비전 +토론 +토마토 +토요일 +통계 +통과 +통로 +통신 +통역 +통일 +통장 +통제 +통증 +통합 +통화 +퇴근 +퇴원 +퇴직금 +튀김 +트럭 +특급 +특별 +특성 +특수 +특징 +특히 +튼튼히 +티셔츠 +파란색 +파일 +파출소 +판결 +판단 +판매 +판사 +팔십 +팔월 +팝송 +패션 +팩스 +팩시밀리 +팬티 +퍼센트 +페인트 +편견 +편의 +편지 +편히 +평가 +평균 +평생 +평소 +평양 +평일 +평화 +포스터 +포인트 +포장 +포함 +표면 +표정 +표준 +표현 +품목 +품질 +풍경 +풍속 +풍습 +프랑스 +프린터 +플라스틱 +피곤 +피망 +피아노 +필름 +필수 +필요 +필자 +필통 +핑계 +하느님 +하늘 +하드웨어 +하룻밤 +하반기 +하숙집 +하순 +하여튼 +하지만 +하천 +하품 +하필 +학과 +학교 +학급 +학기 +학년 +학력 +학번 +학부모 +학비 +학생 +학술 +학습 +학용품 +학원 +학위 +학자 +학점 +한계 +한글 +한꺼번에 +한낮 +한눈 +한동안 +한때 +한라산 +한마디 +한문 +한번 +한복 +한식 +한여름 +한쪽 +할머니 +할아버지 +할인 +함께 +함부로 +합격 +합리적 +항공 +항구 +항상 +항의 +해결 +해군 +해답 +해당 +해물 +해석 +해설 +해수욕장 +해안 +핵심 +핸드백 +햄버거 +햇볕 +햇살 +행동 +행복 +행사 +행운 +행위 +향기 +향상 +향수 +허락 +허용 +헬기 +현관 +현금 +현대 +현상 +현실 +현장 +현재 +현지 +혈액 +협력 +형부 +형사 +형수 +형식 +형제 +형태 +형편 +혜택 +호기심 +호남 +호랑이 +호박 +호텔 +호흡 +혹시 +홀로 +홈페이지 +홍보 +홍수 +홍차 +화면 +화분 +화살 +화요일 +화장 +화학 +확보 +확인 +확장 +확정 +환갑 +환경 +환영 +환율 +환자 +활기 +활동 +활발히 +활용 +활짝 +회견 +회관 +회복 +회색 +회원 +회장 +회전 +횟수 +횡단보도 +효율적 +후반 +후춧가루 +훈련 +훨씬 +휴식 +휴일 +흉내 +흐름 +흑백 +흑인 +흔적 +흔히 +흥미 +흥분 +희곡 +희망 +희생 +흰색 +힘껏`.split('\n'); diff --git a/node_modules/@scure/bip39/wordlists/simplified-chinese.d.ts b/node_modules/@scure/bip39/wordlists/simplified-chinese.d.ts new file mode 100644 index 0000000..b566a1d --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/simplified-chinese.d.ts @@ -0,0 +1 @@ +export declare const wordlist: string[]; diff --git a/node_modules/@scure/bip39/wordlists/simplified-chinese.js b/node_modules/@scure/bip39/wordlists/simplified-chinese.js new file mode 100644 index 0000000..43ac9d2 --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/simplified-chinese.js @@ -0,0 +1,2051 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +exports.wordlist = `的 +一 +是 +在 +不 +了 +有 +和 +人 +这 +中 +大 +为 +上 +个 +国 +我 +以 +要 +他 +时 +来 +用 +们 +生 +到 +作 +地 +于 +出 +就 +分 +对 +成 +会 +可 +主 +发 +年 +动 +同 +工 +也 +能 +下 +过 +子 +说 +产 +种 +面 +而 +方 +后 +多 +定 +行 +学 +法 +所 +民 +得 +经 +十 +三 +之 +进 +着 +等 +部 +度 +家 +电 +力 +里 +如 +水 +化 +高 +自 +二 +理 +起 +小 +物 +现 +实 +加 +量 +都 +两 +体 +制 +机 +当 +使 +点 +从 +业 +本 +去 +把 +性 +好 +应 +开 +它 +合 +还 +因 +由 +其 +些 +然 +前 +外 +天 +政 +四 +日 +那 +社 +义 +事 +平 +形 +相 +全 +表 +间 +样 +与 +关 +各 +重 +新 +线 +内 +数 +正 +心 +反 +你 +明 +看 +原 +又 +么 +利 +比 +或 +但 +质 +气 +第 +向 +道 +命 +此 +变 +条 +只 +没 +结 +解 +问 +意 +建 +月 +公 +无 +系 +军 +很 +情 +者 +最 +立 +代 +想 +已 +通 +并 +提 +直 +题 +党 +程 +展 +五 +果 +料 +象 +员 +革 +位 +入 +常 +文 +总 +次 +品 +式 +活 +设 +及 +管 +特 +件 +长 +求 +老 +头 +基 +资 +边 +流 +路 +级 +少 +图 +山 +统 +接 +知 +较 +将 +组 +见 +计 +别 +她 +手 +角 +期 +根 +论 +运 +农 +指 +几 +九 +区 +强 +放 +决 +西 +被 +干 +做 +必 +战 +先 +回 +则 +任 +取 +据 +处 +队 +南 +给 +色 +光 +门 +即 +保 +治 +北 +造 +百 +规 +热 +领 +七 +海 +口 +东 +导 +器 +压 +志 +世 +金 +增 +争 +济 +阶 +油 +思 +术 +极 +交 +受 +联 +什 +认 +六 +共 +权 +收 +证 +改 +清 +美 +再 +采 +转 +更 +单 +风 +切 +打 +白 +教 +速 +花 +带 +安 +场 +身 +车 +例 +真 +务 +具 +万 +每 +目 +至 +达 +走 +积 +示 +议 +声 +报 +斗 +完 +类 +八 +离 +华 +名 +确 +才 +科 +张 +信 +马 +节 +话 +米 +整 +空 +元 +况 +今 +集 +温 +传 +土 +许 +步 +群 +广 +石 +记 +需 +段 +研 +界 +拉 +林 +律 +叫 +且 +究 +观 +越 +织 +装 +影 +算 +低 +持 +音 +众 +书 +布 +复 +容 +儿 +须 +际 +商 +非 +验 +连 +断 +深 +难 +近 +矿 +千 +周 +委 +素 +技 +备 +半 +办 +青 +省 +列 +习 +响 +约 +支 +般 +史 +感 +劳 +便 +团 +往 +酸 +历 +市 +克 +何 +除 +消 +构 +府 +称 +太 +准 +精 +值 +号 +率 +族 +维 +划 +选 +标 +写 +存 +候 +毛 +亲 +快 +效 +斯 +院 +查 +江 +型 +眼 +王 +按 +格 +养 +易 +置 +派 +层 +片 +始 +却 +专 +状 +育 +厂 +京 +识 +适 +属 +圆 +包 +火 +住 +调 +满 +县 +局 +照 +参 +红 +细 +引 +听 +该 +铁 +价 +严 +首 +底 +液 +官 +德 +随 +病 +苏 +失 +尔 +死 +讲 +配 +女 +黄 +推 +显 +谈 +罪 +神 +艺 +呢 +席 +含 +企 +望 +密 +批 +营 +项 +防 +举 +球 +英 +氧 +势 +告 +李 +台 +落 +木 +帮 +轮 +破 +亚 +师 +围 +注 +远 +字 +材 +排 +供 +河 +态 +封 +另 +施 +减 +树 +溶 +怎 +止 +案 +言 +士 +均 +武 +固 +叶 +鱼 +波 +视 +仅 +费 +紧 +爱 +左 +章 +早 +朝 +害 +续 +轻 +服 +试 +食 +充 +兵 +源 +判 +护 +司 +足 +某 +练 +差 +致 +板 +田 +降 +黑 +犯 +负 +击 +范 +继 +兴 +似 +余 +坚 +曲 +输 +修 +故 +城 +夫 +够 +送 +笔 +船 +占 +右 +财 +吃 +富 +春 +职 +觉 +汉 +画 +功 +巴 +跟 +虽 +杂 +飞 +检 +吸 +助 +升 +阳 +互 +初 +创 +抗 +考 +投 +坏 +策 +古 +径 +换 +未 +跑 +留 +钢 +曾 +端 +责 +站 +简 +述 +钱 +副 +尽 +帝 +射 +草 +冲 +承 +独 +令 +限 +阿 +宣 +环 +双 +请 +超 +微 +让 +控 +州 +良 +轴 +找 +否 +纪 +益 +依 +优 +顶 +础 +载 +倒 +房 +突 +坐 +粉 +敌 +略 +客 +袁 +冷 +胜 +绝 +析 +块 +剂 +测 +丝 +协 +诉 +念 +陈 +仍 +罗 +盐 +友 +洋 +错 +苦 +夜 +刑 +移 +频 +逐 +靠 +混 +母 +短 +皮 +终 +聚 +汽 +村 +云 +哪 +既 +距 +卫 +停 +烈 +央 +察 +烧 +迅 +境 +若 +印 +洲 +刻 +括 +激 +孔 +搞 +甚 +室 +待 +核 +校 +散 +侵 +吧 +甲 +游 +久 +菜 +味 +旧 +模 +湖 +货 +损 +预 +阻 +毫 +普 +稳 +乙 +妈 +植 +息 +扩 +银 +语 +挥 +酒 +守 +拿 +序 +纸 +医 +缺 +雨 +吗 +针 +刘 +啊 +急 +唱 +误 +训 +愿 +审 +附 +获 +茶 +鲜 +粮 +斤 +孩 +脱 +硫 +肥 +善 +龙 +演 +父 +渐 +血 +欢 +械 +掌 +歌 +沙 +刚 +攻 +谓 +盾 +讨 +晚 +粒 +乱 +燃 +矛 +乎 +杀 +药 +宁 +鲁 +贵 +钟 +煤 +读 +班 +伯 +香 +介 +迫 +句 +丰 +培 +握 +兰 +担 +弦 +蛋 +沉 +假 +穿 +执 +答 +乐 +谁 +顺 +烟 +缩 +征 +脸 +喜 +松 +脚 +困 +异 +免 +背 +星 +福 +买 +染 +井 +概 +慢 +怕 +磁 +倍 +祖 +皇 +促 +静 +补 +评 +翻 +肉 +践 +尼 +衣 +宽 +扬 +棉 +希 +伤 +操 +垂 +秋 +宜 +氢 +套 +督 +振 +架 +亮 +末 +宪 +庆 +编 +牛 +触 +映 +雷 +销 +诗 +座 +居 +抓 +裂 +胞 +呼 +娘 +景 +威 +绿 +晶 +厚 +盟 +衡 +鸡 +孙 +延 +危 +胶 +屋 +乡 +临 +陆 +顾 +掉 +呀 +灯 +岁 +措 +束 +耐 +剧 +玉 +赵 +跳 +哥 +季 +课 +凯 +胡 +额 +款 +绍 +卷 +齐 +伟 +蒸 +殖 +永 +宗 +苗 +川 +炉 +岩 +弱 +零 +杨 +奏 +沿 +露 +杆 +探 +滑 +镇 +饭 +浓 +航 +怀 +赶 +库 +夺 +伊 +灵 +税 +途 +灭 +赛 +归 +召 +鼓 +播 +盘 +裁 +险 +康 +唯 +录 +菌 +纯 +借 +糖 +盖 +横 +符 +私 +努 +堂 +域 +枪 +润 +幅 +哈 +竟 +熟 +虫 +泽 +脑 +壤 +碳 +欧 +遍 +侧 +寨 +敢 +彻 +虑 +斜 +薄 +庭 +纳 +弹 +饲 +伸 +折 +麦 +湿 +暗 +荷 +瓦 +塞 +床 +筑 +恶 +户 +访 +塔 +奇 +透 +梁 +刀 +旋 +迹 +卡 +氯 +遇 +份 +毒 +泥 +退 +洗 +摆 +灰 +彩 +卖 +耗 +夏 +择 +忙 +铜 +献 +硬 +予 +繁 +圈 +雪 +函 +亦 +抽 +篇 +阵 +阴 +丁 +尺 +追 +堆 +雄 +迎 +泛 +爸 +楼 +避 +谋 +吨 +野 +猪 +旗 +累 +偏 +典 +馆 +索 +秦 +脂 +潮 +爷 +豆 +忽 +托 +惊 +塑 +遗 +愈 +朱 +替 +纤 +粗 +倾 +尚 +痛 +楚 +谢 +奋 +购 +磨 +君 +池 +旁 +碎 +骨 +监 +捕 +弟 +暴 +割 +贯 +殊 +释 +词 +亡 +壁 +顿 +宝 +午 +尘 +闻 +揭 +炮 +残 +冬 +桥 +妇 +警 +综 +招 +吴 +付 +浮 +遭 +徐 +您 +摇 +谷 +赞 +箱 +隔 +订 +男 +吹 +园 +纷 +唐 +败 +宋 +玻 +巨 +耕 +坦 +荣 +闭 +湾 +键 +凡 +驻 +锅 +救 +恩 +剥 +凝 +碱 +齿 +截 +炼 +麻 +纺 +禁 +废 +盛 +版 +缓 +净 +睛 +昌 +婚 +涉 +筒 +嘴 +插 +岸 +朗 +庄 +街 +藏 +姑 +贸 +腐 +奴 +啦 +惯 +乘 +伙 +恢 +匀 +纱 +扎 +辩 +耳 +彪 +臣 +亿 +璃 +抵 +脉 +秀 +萨 +俄 +网 +舞 +店 +喷 +纵 +寸 +汗 +挂 +洪 +贺 +闪 +柬 +爆 +烯 +津 +稻 +墙 +软 +勇 +像 +滚 +厘 +蒙 +芳 +肯 +坡 +柱 +荡 +腿 +仪 +旅 +尾 +轧 +冰 +贡 +登 +黎 +削 +钻 +勒 +逃 +障 +氨 +郭 +峰 +币 +港 +伏 +轨 +亩 +毕 +擦 +莫 +刺 +浪 +秘 +援 +株 +健 +售 +股 +岛 +甘 +泡 +睡 +童 +铸 +汤 +阀 +休 +汇 +舍 +牧 +绕 +炸 +哲 +磷 +绩 +朋 +淡 +尖 +启 +陷 +柴 +呈 +徒 +颜 +泪 +稍 +忘 +泵 +蓝 +拖 +洞 +授 +镜 +辛 +壮 +锋 +贫 +虚 +弯 +摩 +泰 +幼 +廷 +尊 +窗 +纲 +弄 +隶 +疑 +氏 +宫 +姐 +震 +瑞 +怪 +尤 +琴 +循 +描 +膜 +违 +夹 +腰 +缘 +珠 +穷 +森 +枝 +竹 +沟 +催 +绳 +忆 +邦 +剩 +幸 +浆 +栏 +拥 +牙 +贮 +礼 +滤 +钠 +纹 +罢 +拍 +咱 +喊 +袖 +埃 +勤 +罚 +焦 +潜 +伍 +墨 +欲 +缝 +姓 +刊 +饱 +仿 +奖 +铝 +鬼 +丽 +跨 +默 +挖 +链 +扫 +喝 +袋 +炭 +污 +幕 +诸 +弧 +励 +梅 +奶 +洁 +灾 +舟 +鉴 +苯 +讼 +抱 +毁 +懂 +寒 +智 +埔 +寄 +届 +跃 +渡 +挑 +丹 +艰 +贝 +碰 +拔 +爹 +戴 +码 +梦 +芽 +熔 +赤 +渔 +哭 +敬 +颗 +奔 +铅 +仲 +虎 +稀 +妹 +乏 +珍 +申 +桌 +遵 +允 +隆 +螺 +仓 +魏 +锐 +晓 +氮 +兼 +隐 +碍 +赫 +拨 +忠 +肃 +缸 +牵 +抢 +博 +巧 +壳 +兄 +杜 +讯 +诚 +碧 +祥 +柯 +页 +巡 +矩 +悲 +灌 +龄 +伦 +票 +寻 +桂 +铺 +圣 +恐 +恰 +郑 +趣 +抬 +荒 +腾 +贴 +柔 +滴 +猛 +阔 +辆 +妻 +填 +撤 +储 +签 +闹 +扰 +紫 +砂 +递 +戏 +吊 +陶 +伐 +喂 +疗 +瓶 +婆 +抚 +臂 +摸 +忍 +虾 +蜡 +邻 +胸 +巩 +挤 +偶 +弃 +槽 +劲 +乳 +邓 +吉 +仁 +烂 +砖 +租 +乌 +舰 +伴 +瓜 +浅 +丙 +暂 +燥 +橡 +柳 +迷 +暖 +牌 +秧 +胆 +详 +簧 +踏 +瓷 +谱 +呆 +宾 +糊 +洛 +辉 +愤 +竞 +隙 +怒 +粘 +乃 +绪 +肩 +籍 +敏 +涂 +熙 +皆 +侦 +悬 +掘 +享 +纠 +醒 +狂 +锁 +淀 +恨 +牲 +霸 +爬 +赏 +逆 +玩 +陵 +祝 +秒 +浙 +貌 +役 +彼 +悉 +鸭 +趋 +凤 +晨 +畜 +辈 +秩 +卵 +署 +梯 +炎 +滩 +棋 +驱 +筛 +峡 +冒 +啥 +寿 +译 +浸 +泉 +帽 +迟 +硅 +疆 +贷 +漏 +稿 +冠 +嫩 +胁 +芯 +牢 +叛 +蚀 +奥 +鸣 +岭 +羊 +凭 +串 +塘 +绘 +酵 +融 +盆 +锡 +庙 +筹 +冻 +辅 +摄 +袭 +筋 +拒 +僚 +旱 +钾 +鸟 +漆 +沈 +眉 +疏 +添 +棒 +穗 +硝 +韩 +逼 +扭 +侨 +凉 +挺 +碗 +栽 +炒 +杯 +患 +馏 +劝 +豪 +辽 +勃 +鸿 +旦 +吏 +拜 +狗 +埋 +辊 +掩 +饮 +搬 +骂 +辞 +勾 +扣 +估 +蒋 +绒 +雾 +丈 +朵 +姆 +拟 +宇 +辑 +陕 +雕 +偿 +蓄 +崇 +剪 +倡 +厅 +咬 +驶 +薯 +刷 +斥 +番 +赋 +奉 +佛 +浇 +漫 +曼 +扇 +钙 +桃 +扶 +仔 +返 +俗 +亏 +腔 +鞋 +棱 +覆 +框 +悄 +叔 +撞 +骗 +勘 +旺 +沸 +孤 +吐 +孟 +渠 +屈 +疾 +妙 +惜 +仰 +狠 +胀 +谐 +抛 +霉 +桑 +岗 +嘛 +衰 +盗 +渗 +脏 +赖 +涌 +甜 +曹 +阅 +肌 +哩 +厉 +烃 +纬 +毅 +昨 +伪 +症 +煮 +叹 +钉 +搭 +茎 +笼 +酷 +偷 +弓 +锥 +恒 +杰 +坑 +鼻 +翼 +纶 +叙 +狱 +逮 +罐 +络 +棚 +抑 +膨 +蔬 +寺 +骤 +穆 +冶 +枯 +册 +尸 +凸 +绅 +坯 +牺 +焰 +轰 +欣 +晋 +瘦 +御 +锭 +锦 +丧 +旬 +锻 +垄 +搜 +扑 +邀 +亭 +酯 +迈 +舒 +脆 +酶 +闲 +忧 +酚 +顽 +羽 +涨 +卸 +仗 +陪 +辟 +惩 +杭 +姚 +肚 +捉 +飘 +漂 +昆 +欺 +吾 +郎 +烷 +汁 +呵 +饰 +萧 +雅 +邮 +迁 +燕 +撒 +姻 +赴 +宴 +烦 +债 +帐 +斑 +铃 +旨 +醇 +董 +饼 +雏 +姿 +拌 +傅 +腹 +妥 +揉 +贤 +拆 +歪 +葡 +胺 +丢 +浩 +徽 +昂 +垫 +挡 +览 +贪 +慰 +缴 +汪 +慌 +冯 +诺 +姜 +谊 +凶 +劣 +诬 +耀 +昏 +躺 +盈 +骑 +乔 +溪 +丛 +卢 +抹 +闷 +咨 +刮 +驾 +缆 +悟 +摘 +铒 +掷 +颇 +幻 +柄 +惠 +惨 +佳 +仇 +腊 +窝 +涤 +剑 +瞧 +堡 +泼 +葱 +罩 +霍 +捞 +胎 +苍 +滨 +俩 +捅 +湘 +砍 +霞 +邵 +萄 +疯 +淮 +遂 +熊 +粪 +烘 +宿 +档 +戈 +驳 +嫂 +裕 +徙 +箭 +捐 +肠 +撑 +晒 +辨 +殿 +莲 +摊 +搅 +酱 +屏 +疫 +哀 +蔡 +堵 +沫 +皱 +畅 +叠 +阁 +莱 +敲 +辖 +钩 +痕 +坝 +巷 +饿 +祸 +丘 +玄 +溜 +曰 +逻 +彭 +尝 +卿 +妨 +艇 +吞 +韦 +怨 +矮 +歇`.split('\n'); diff --git a/node_modules/@scure/bip39/wordlists/spanish.d.ts b/node_modules/@scure/bip39/wordlists/spanish.d.ts new file mode 100644 index 0000000..b566a1d --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/spanish.d.ts @@ -0,0 +1 @@ +export declare const wordlist: string[]; diff --git a/node_modules/@scure/bip39/wordlists/spanish.js b/node_modules/@scure/bip39/wordlists/spanish.js new file mode 100644 index 0000000..0a8328a --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/spanish.js @@ -0,0 +1,2051 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +exports.wordlist = `ábaco +abdomen +abeja +abierto +abogado +abono +aborto +abrazo +abrir +abuelo +abuso +acabar +academia +acceso +acción +aceite +acelga +acento +aceptar +ácido +aclarar +acné +acoger +acoso +activo +acto +actriz +actuar +acudir +acuerdo +acusar +adicto +admitir +adoptar +adorno +aduana +adulto +aéreo +afectar +afición +afinar +afirmar +ágil +agitar +agonía +agosto +agotar +agregar +agrio +agua +agudo +águila +aguja +ahogo +ahorro +aire +aislar +ajedrez +ajeno +ajuste +alacrán +alambre +alarma +alba +álbum +alcalde +aldea +alegre +alejar +alerta +aleta +alfiler +alga +algodón +aliado +aliento +alivio +alma +almeja +almíbar +altar +alteza +altivo +alto +altura +alumno +alzar +amable +amante +amapola +amargo +amasar +ámbar +ámbito +ameno +amigo +amistad +amor +amparo +amplio +ancho +anciano +ancla +andar +andén +anemia +ángulo +anillo +ánimo +anís +anotar +antena +antiguo +antojo +anual +anular +anuncio +añadir +añejo +año +apagar +aparato +apetito +apio +aplicar +apodo +aporte +apoyo +aprender +aprobar +apuesta +apuro +arado +araña +arar +árbitro +árbol +arbusto +archivo +arco +arder +ardilla +arduo +área +árido +aries +armonía +arnés +aroma +arpa +arpón +arreglo +arroz +arruga +arte +artista +asa +asado +asalto +ascenso +asegurar +aseo +asesor +asiento +asilo +asistir +asno +asombro +áspero +astilla +astro +astuto +asumir +asunto +atajo +ataque +atar +atento +ateo +ático +atleta +átomo +atraer +atroz +atún +audaz +audio +auge +aula +aumento +ausente +autor +aval +avance +avaro +ave +avellana +avena +avestruz +avión +aviso +ayer +ayuda +ayuno +azafrán +azar +azote +azúcar +azufre +azul +baba +babor +bache +bahía +baile +bajar +balanza +balcón +balde +bambú +banco +banda +baño +barba +barco +barniz +barro +báscula +bastón +basura +batalla +batería +batir +batuta +baúl +bazar +bebé +bebida +bello +besar +beso +bestia +bicho +bien +bingo +blanco +bloque +blusa +boa +bobina +bobo +boca +bocina +boda +bodega +boina +bola +bolero +bolsa +bomba +bondad +bonito +bono +bonsái +borde +borrar +bosque +bote +botín +bóveda +bozal +bravo +brazo +brecha +breve +brillo +brinco +brisa +broca +broma +bronce +brote +bruja +brusco +bruto +buceo +bucle +bueno +buey +bufanda +bufón +búho +buitre +bulto +burbuja +burla +burro +buscar +butaca +buzón +caballo +cabeza +cabina +cabra +cacao +cadáver +cadena +caer +café +caída +caimán +caja +cajón +cal +calamar +calcio +caldo +calidad +calle +calma +calor +calvo +cama +cambio +camello +camino +campo +cáncer +candil +canela +canguro +canica +canto +caña +cañón +caoba +caos +capaz +capitán +capote +captar +capucha +cara +carbón +cárcel +careta +carga +cariño +carne +carpeta +carro +carta +casa +casco +casero +caspa +castor +catorce +catre +caudal +causa +cazo +cebolla +ceder +cedro +celda +célebre +celoso +célula +cemento +ceniza +centro +cerca +cerdo +cereza +cero +cerrar +certeza +césped +cetro +chacal +chaleco +champú +chancla +chapa +charla +chico +chiste +chivo +choque +choza +chuleta +chupar +ciclón +ciego +cielo +cien +cierto +cifra +cigarro +cima +cinco +cine +cinta +ciprés +circo +ciruela +cisne +cita +ciudad +clamor +clan +claro +clase +clave +cliente +clima +clínica +cobre +cocción +cochino +cocina +coco +código +codo +cofre +coger +cohete +cojín +cojo +cola +colcha +colegio +colgar +colina +collar +colmo +columna +combate +comer +comida +cómodo +compra +conde +conejo +conga +conocer +consejo +contar +copa +copia +corazón +corbata +corcho +cordón +corona +correr +coser +cosmos +costa +cráneo +cráter +crear +crecer +creído +crema +cría +crimen +cripta +crisis +cromo +crónica +croqueta +crudo +cruz +cuadro +cuarto +cuatro +cubo +cubrir +cuchara +cuello +cuento +cuerda +cuesta +cueva +cuidar +culebra +culpa +culto +cumbre +cumplir +cuna +cuneta +cuota +cupón +cúpula +curar +curioso +curso +curva +cutis +dama +danza +dar +dardo +dátil +deber +débil +década +decir +dedo +defensa +definir +dejar +delfín +delgado +delito +demora +denso +dental +deporte +derecho +derrota +desayuno +deseo +desfile +desnudo +destino +desvío +detalle +detener +deuda +día +diablo +diadema +diamante +diana +diario +dibujo +dictar +diente +dieta +diez +difícil +digno +dilema +diluir +dinero +directo +dirigir +disco +diseño +disfraz +diva +divino +doble +doce +dolor +domingo +don +donar +dorado +dormir +dorso +dos +dosis +dragón +droga +ducha +duda +duelo +dueño +dulce +dúo +duque +durar +dureza +duro +ébano +ebrio +echar +eco +ecuador +edad +edición +edificio +editor +educar +efecto +eficaz +eje +ejemplo +elefante +elegir +elemento +elevar +elipse +élite +elixir +elogio +eludir +embudo +emitir +emoción +empate +empeño +empleo +empresa +enano +encargo +enchufe +encía +enemigo +enero +enfado +enfermo +engaño +enigma +enlace +enorme +enredo +ensayo +enseñar +entero +entrar +envase +envío +época +equipo +erizo +escala +escena +escolar +escribir +escudo +esencia +esfera +esfuerzo +espada +espejo +espía +esposa +espuma +esquí +estar +este +estilo +estufa +etapa +eterno +ética +etnia +evadir +evaluar +evento +evitar +exacto +examen +exceso +excusa +exento +exigir +exilio +existir +éxito +experto +explicar +exponer +extremo +fábrica +fábula +fachada +fácil +factor +faena +faja +falda +fallo +falso +faltar +fama +familia +famoso +faraón +farmacia +farol +farsa +fase +fatiga +fauna +favor +fax +febrero +fecha +feliz +feo +feria +feroz +fértil +fervor +festín +fiable +fianza +fiar +fibra +ficción +ficha +fideo +fiebre +fiel +fiera +fiesta +figura +fijar +fijo +fila +filete +filial +filtro +fin +finca +fingir +finito +firma +flaco +flauta +flecha +flor +flota +fluir +flujo +flúor +fobia +foca +fogata +fogón +folio +folleto +fondo +forma +forro +fortuna +forzar +fosa +foto +fracaso +frágil +franja +frase +fraude +freír +freno +fresa +frío +frito +fruta +fuego +fuente +fuerza +fuga +fumar +función +funda +furgón +furia +fusil +fútbol +futuro +gacela +gafas +gaita +gajo +gala +galería +gallo +gamba +ganar +gancho +ganga +ganso +garaje +garza +gasolina +gastar +gato +gavilán +gemelo +gemir +gen +género +genio +gente +geranio +gerente +germen +gesto +gigante +gimnasio +girar +giro +glaciar +globo +gloria +gol +golfo +goloso +golpe +goma +gordo +gorila +gorra +gota +goteo +gozar +grada +gráfico +grano +grasa +gratis +grave +grieta +grillo +gripe +gris +grito +grosor +grúa +grueso +grumo +grupo +guante +guapo +guardia +guerra +guía +guiño +guion +guiso +guitarra +gusano +gustar +haber +hábil +hablar +hacer +hacha +hada +hallar +hamaca +harina +haz +hazaña +hebilla +hebra +hecho +helado +helio +hembra +herir +hermano +héroe +hervir +hielo +hierro +hígado +higiene +hijo +himno +historia +hocico +hogar +hoguera +hoja +hombre +hongo +honor +honra +hora +hormiga +horno +hostil +hoyo +hueco +huelga +huerta +hueso +huevo +huida +huir +humano +húmedo +humilde +humo +hundir +huracán +hurto +icono +ideal +idioma +ídolo +iglesia +iglú +igual +ilegal +ilusión +imagen +imán +imitar +impar +imperio +imponer +impulso +incapaz +índice +inerte +infiel +informe +ingenio +inicio +inmenso +inmune +innato +insecto +instante +interés +íntimo +intuir +inútil +invierno +ira +iris +ironía +isla +islote +jabalí +jabón +jamón +jarabe +jardín +jarra +jaula +jazmín +jefe +jeringa +jinete +jornada +joroba +joven +joya +juerga +jueves +juez +jugador +jugo +juguete +juicio +junco +jungla +junio +juntar +júpiter +jurar +justo +juvenil +juzgar +kilo +koala +labio +lacio +lacra +lado +ladrón +lagarto +lágrima +laguna +laico +lamer +lámina +lámpara +lana +lancha +langosta +lanza +lápiz +largo +larva +lástima +lata +látex +latir +laurel +lavar +lazo +leal +lección +leche +lector +leer +legión +legumbre +lejano +lengua +lento +leña +león +leopardo +lesión +letal +letra +leve +leyenda +libertad +libro +licor +líder +lidiar +lienzo +liga +ligero +lima +límite +limón +limpio +lince +lindo +línea +lingote +lino +linterna +líquido +liso +lista +litera +litio +litro +llaga +llama +llanto +llave +llegar +llenar +llevar +llorar +llover +lluvia +lobo +loción +loco +locura +lógica +logro +lombriz +lomo +lonja +lote +lucha +lucir +lugar +lujo +luna +lunes +lupa +lustro +luto +luz +maceta +macho +madera +madre +maduro +maestro +mafia +magia +mago +maíz +maldad +maleta +malla +malo +mamá +mambo +mamut +manco +mando +manejar +manga +maniquí +manjar +mano +manso +manta +mañana +mapa +máquina +mar +marco +marea +marfil +margen +marido +mármol +marrón +martes +marzo +masa +máscara +masivo +matar +materia +matiz +matriz +máximo +mayor +mazorca +mecha +medalla +medio +médula +mejilla +mejor +melena +melón +memoria +menor +mensaje +mente +menú +mercado +merengue +mérito +mes +mesón +meta +meter +método +metro +mezcla +miedo +miel +miembro +miga +mil +milagro +militar +millón +mimo +mina +minero +mínimo +minuto +miope +mirar +misa +miseria +misil +mismo +mitad +mito +mochila +moción +moda +modelo +moho +mojar +molde +moler +molino +momento +momia +monarca +moneda +monja +monto +moño +morada +morder +moreno +morir +morro +morsa +mortal +mosca +mostrar +motivo +mover +móvil +mozo +mucho +mudar +mueble +muela +muerte +muestra +mugre +mujer +mula +muleta +multa +mundo +muñeca +mural +muro +músculo +museo +musgo +música +muslo +nácar +nación +nadar +naipe +naranja +nariz +narrar +nasal +natal +nativo +natural +náusea +naval +nave +navidad +necio +néctar +negar +negocio +negro +neón +nervio +neto +neutro +nevar +nevera +nicho +nido +niebla +nieto +niñez +niño +nítido +nivel +nobleza +noche +nómina +noria +norma +norte +nota +noticia +novato +novela +novio +nube +nuca +núcleo +nudillo +nudo +nuera +nueve +nuez +nulo +número +nutria +oasis +obeso +obispo +objeto +obra +obrero +observar +obtener +obvio +oca +ocaso +océano +ochenta +ocho +ocio +ocre +octavo +octubre +oculto +ocupar +ocurrir +odiar +odio +odisea +oeste +ofensa +oferta +oficio +ofrecer +ogro +oído +oír +ojo +ola +oleada +olfato +olivo +olla +olmo +olor +olvido +ombligo +onda +onza +opaco +opción +ópera +opinar +oponer +optar +óptica +opuesto +oración +orador +oral +órbita +orca +orden +oreja +órgano +orgía +orgullo +oriente +origen +orilla +oro +orquesta +oruga +osadía +oscuro +osezno +oso +ostra +otoño +otro +oveja +óvulo +óxido +oxígeno +oyente +ozono +pacto +padre +paella +página +pago +país +pájaro +palabra +palco +paleta +pálido +palma +paloma +palpar +pan +panal +pánico +pantera +pañuelo +papá +papel +papilla +paquete +parar +parcela +pared +parir +paro +párpado +parque +párrafo +parte +pasar +paseo +pasión +paso +pasta +pata +patio +patria +pausa +pauta +pavo +payaso +peatón +pecado +pecera +pecho +pedal +pedir +pegar +peine +pelar +peldaño +pelea +peligro +pellejo +pelo +peluca +pena +pensar +peñón +peón +peor +pepino +pequeño +pera +percha +perder +pereza +perfil +perico +perla +permiso +perro +persona +pesa +pesca +pésimo +pestaña +pétalo +petróleo +pez +pezuña +picar +pichón +pie +piedra +pierna +pieza +pijama +pilar +piloto +pimienta +pino +pintor +pinza +piña +piojo +pipa +pirata +pisar +piscina +piso +pista +pitón +pizca +placa +plan +plata +playa +plaza +pleito +pleno +plomo +pluma +plural +pobre +poco +poder +podio +poema +poesía +poeta +polen +policía +pollo +polvo +pomada +pomelo +pomo +pompa +poner +porción +portal +posada +poseer +posible +poste +potencia +potro +pozo +prado +precoz +pregunta +premio +prensa +preso +previo +primo +príncipe +prisión +privar +proa +probar +proceso +producto +proeza +profesor +programa +prole +promesa +pronto +propio +próximo +prueba +público +puchero +pudor +pueblo +puerta +puesto +pulga +pulir +pulmón +pulpo +pulso +puma +punto +puñal +puño +pupa +pupila +puré +quedar +queja +quemar +querer +queso +quieto +química +quince +quitar +rábano +rabia +rabo +ración +radical +raíz +rama +rampa +rancho +rango +rapaz +rápido +rapto +rasgo +raspa +rato +rayo +raza +razón +reacción +realidad +rebaño +rebote +recaer +receta +rechazo +recoger +recreo +recto +recurso +red +redondo +reducir +reflejo +reforma +refrán +refugio +regalo +regir +regla +regreso +rehén +reino +reír +reja +relato +relevo +relieve +relleno +reloj +remar +remedio +remo +rencor +rendir +renta +reparto +repetir +reposo +reptil +res +rescate +resina +respeto +resto +resumen +retiro +retorno +retrato +reunir +revés +revista +rey +rezar +rico +riego +rienda +riesgo +rifa +rígido +rigor +rincón +riñón +río +riqueza +risa +ritmo +rito +rizo +roble +roce +rociar +rodar +rodeo +rodilla +roer +rojizo +rojo +romero +romper +ron +ronco +ronda +ropa +ropero +rosa +rosca +rostro +rotar +rubí +rubor +rudo +rueda +rugir +ruido +ruina +ruleta +rulo +rumbo +rumor +ruptura +ruta +rutina +sábado +saber +sabio +sable +sacar +sagaz +sagrado +sala +saldo +salero +salir +salmón +salón +salsa +salto +salud +salvar +samba +sanción +sandía +sanear +sangre +sanidad +sano +santo +sapo +saque +sardina +sartén +sastre +satán +sauna +saxofón +sección +seco +secreto +secta +sed +seguir +seis +sello +selva +semana +semilla +senda +sensor +señal +señor +separar +sepia +sequía +ser +serie +sermón +servir +sesenta +sesión +seta +setenta +severo +sexo +sexto +sidra +siesta +siete +siglo +signo +sílaba +silbar +silencio +silla +símbolo +simio +sirena +sistema +sitio +situar +sobre +socio +sodio +sol +solapa +soldado +soledad +sólido +soltar +solución +sombra +sondeo +sonido +sonoro +sonrisa +sopa +soplar +soporte +sordo +sorpresa +sorteo +sostén +sótano +suave +subir +suceso +sudor +suegra +suelo +sueño +suerte +sufrir +sujeto +sultán +sumar +superar +suplir +suponer +supremo +sur +surco +sureño +surgir +susto +sutil +tabaco +tabique +tabla +tabú +taco +tacto +tajo +talar +talco +talento +talla +talón +tamaño +tambor +tango +tanque +tapa +tapete +tapia +tapón +taquilla +tarde +tarea +tarifa +tarjeta +tarot +tarro +tarta +tatuaje +tauro +taza +tazón +teatro +techo +tecla +técnica +tejado +tejer +tejido +tela +teléfono +tema +temor +templo +tenaz +tender +tener +tenis +tenso +teoría +terapia +terco +término +ternura +terror +tesis +tesoro +testigo +tetera +texto +tez +tibio +tiburón +tiempo +tienda +tierra +tieso +tigre +tijera +tilde +timbre +tímido +timo +tinta +tío +típico +tipo +tira +tirón +titán +títere +título +tiza +toalla +tobillo +tocar +tocino +todo +toga +toldo +tomar +tono +tonto +topar +tope +toque +tórax +torero +tormenta +torneo +toro +torpedo +torre +torso +tortuga +tos +tosco +toser +tóxico +trabajo +tractor +traer +tráfico +trago +traje +tramo +trance +trato +trauma +trazar +trébol +tregua +treinta +tren +trepar +tres +tribu +trigo +tripa +triste +triunfo +trofeo +trompa +tronco +tropa +trote +trozo +truco +trueno +trufa +tubería +tubo +tuerto +tumba +tumor +túnel +túnica +turbina +turismo +turno +tutor +ubicar +úlcera +umbral +unidad +unir +universo +uno +untar +uña +urbano +urbe +urgente +urna +usar +usuario +útil +utopía +uva +vaca +vacío +vacuna +vagar +vago +vaina +vajilla +vale +válido +valle +valor +válvula +vampiro +vara +variar +varón +vaso +vecino +vector +vehículo +veinte +vejez +vela +velero +veloz +vena +vencer +venda +veneno +vengar +venir +venta +venus +ver +verano +verbo +verde +vereda +verja +verso +verter +vía +viaje +vibrar +vicio +víctima +vida +vídeo +vidrio +viejo +viernes +vigor +vil +villa +vinagre +vino +viñedo +violín +viral +virgo +virtud +visor +víspera +vista +vitamina +viudo +vivaz +vivero +vivir +vivo +volcán +volumen +volver +voraz +votar +voto +voz +vuelo +vulgar +yacer +yate +yegua +yema +yerno +yeso +yodo +yoga +yogur +zafiro +zanja +zapato +zarza +zona +zorro +zumo +zurdo`.split('\n'); diff --git a/node_modules/@scure/bip39/wordlists/traditional-chinese.d.ts b/node_modules/@scure/bip39/wordlists/traditional-chinese.d.ts new file mode 100644 index 0000000..b566a1d --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/traditional-chinese.d.ts @@ -0,0 +1 @@ +export declare const wordlist: string[]; diff --git a/node_modules/@scure/bip39/wordlists/traditional-chinese.js b/node_modules/@scure/bip39/wordlists/traditional-chinese.js new file mode 100644 index 0000000..789a0bc --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/traditional-chinese.js @@ -0,0 +1,2051 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +exports.wordlist = `的 +一 +是 +在 +不 +了 +有 +和 +人 +這 +中 +大 +為 +上 +個 +國 +我 +以 +要 +他 +時 +來 +用 +們 +生 +到 +作 +地 +於 +出 +就 +分 +對 +成 +會 +可 +主 +發 +年 +動 +同 +工 +也 +能 +下 +過 +子 +說 +產 +種 +面 +而 +方 +後 +多 +定 +行 +學 +法 +所 +民 +得 +經 +十 +三 +之 +進 +著 +等 +部 +度 +家 +電 +力 +裡 +如 +水 +化 +高 +自 +二 +理 +起 +小 +物 +現 +實 +加 +量 +都 +兩 +體 +制 +機 +當 +使 +點 +從 +業 +本 +去 +把 +性 +好 +應 +開 +它 +合 +還 +因 +由 +其 +些 +然 +前 +外 +天 +政 +四 +日 +那 +社 +義 +事 +平 +形 +相 +全 +表 +間 +樣 +與 +關 +各 +重 +新 +線 +內 +數 +正 +心 +反 +你 +明 +看 +原 +又 +麼 +利 +比 +或 +但 +質 +氣 +第 +向 +道 +命 +此 +變 +條 +只 +沒 +結 +解 +問 +意 +建 +月 +公 +無 +系 +軍 +很 +情 +者 +最 +立 +代 +想 +已 +通 +並 +提 +直 +題 +黨 +程 +展 +五 +果 +料 +象 +員 +革 +位 +入 +常 +文 +總 +次 +品 +式 +活 +設 +及 +管 +特 +件 +長 +求 +老 +頭 +基 +資 +邊 +流 +路 +級 +少 +圖 +山 +統 +接 +知 +較 +將 +組 +見 +計 +別 +她 +手 +角 +期 +根 +論 +運 +農 +指 +幾 +九 +區 +強 +放 +決 +西 +被 +幹 +做 +必 +戰 +先 +回 +則 +任 +取 +據 +處 +隊 +南 +給 +色 +光 +門 +即 +保 +治 +北 +造 +百 +規 +熱 +領 +七 +海 +口 +東 +導 +器 +壓 +志 +世 +金 +增 +爭 +濟 +階 +油 +思 +術 +極 +交 +受 +聯 +什 +認 +六 +共 +權 +收 +證 +改 +清 +美 +再 +採 +轉 +更 +單 +風 +切 +打 +白 +教 +速 +花 +帶 +安 +場 +身 +車 +例 +真 +務 +具 +萬 +每 +目 +至 +達 +走 +積 +示 +議 +聲 +報 +鬥 +完 +類 +八 +離 +華 +名 +確 +才 +科 +張 +信 +馬 +節 +話 +米 +整 +空 +元 +況 +今 +集 +溫 +傳 +土 +許 +步 +群 +廣 +石 +記 +需 +段 +研 +界 +拉 +林 +律 +叫 +且 +究 +觀 +越 +織 +裝 +影 +算 +低 +持 +音 +眾 +書 +布 +复 +容 +兒 +須 +際 +商 +非 +驗 +連 +斷 +深 +難 +近 +礦 +千 +週 +委 +素 +技 +備 +半 +辦 +青 +省 +列 +習 +響 +約 +支 +般 +史 +感 +勞 +便 +團 +往 +酸 +歷 +市 +克 +何 +除 +消 +構 +府 +稱 +太 +準 +精 +值 +號 +率 +族 +維 +劃 +選 +標 +寫 +存 +候 +毛 +親 +快 +效 +斯 +院 +查 +江 +型 +眼 +王 +按 +格 +養 +易 +置 +派 +層 +片 +始 +卻 +專 +狀 +育 +廠 +京 +識 +適 +屬 +圓 +包 +火 +住 +調 +滿 +縣 +局 +照 +參 +紅 +細 +引 +聽 +該 +鐵 +價 +嚴 +首 +底 +液 +官 +德 +隨 +病 +蘇 +失 +爾 +死 +講 +配 +女 +黃 +推 +顯 +談 +罪 +神 +藝 +呢 +席 +含 +企 +望 +密 +批 +營 +項 +防 +舉 +球 +英 +氧 +勢 +告 +李 +台 +落 +木 +幫 +輪 +破 +亞 +師 +圍 +注 +遠 +字 +材 +排 +供 +河 +態 +封 +另 +施 +減 +樹 +溶 +怎 +止 +案 +言 +士 +均 +武 +固 +葉 +魚 +波 +視 +僅 +費 +緊 +愛 +左 +章 +早 +朝 +害 +續 +輕 +服 +試 +食 +充 +兵 +源 +判 +護 +司 +足 +某 +練 +差 +致 +板 +田 +降 +黑 +犯 +負 +擊 +范 +繼 +興 +似 +餘 +堅 +曲 +輸 +修 +故 +城 +夫 +夠 +送 +筆 +船 +佔 +右 +財 +吃 +富 +春 +職 +覺 +漢 +畫 +功 +巴 +跟 +雖 +雜 +飛 +檢 +吸 +助 +昇 +陽 +互 +初 +創 +抗 +考 +投 +壞 +策 +古 +徑 +換 +未 +跑 +留 +鋼 +曾 +端 +責 +站 +簡 +述 +錢 +副 +盡 +帝 +射 +草 +衝 +承 +獨 +令 +限 +阿 +宣 +環 +雙 +請 +超 +微 +讓 +控 +州 +良 +軸 +找 +否 +紀 +益 +依 +優 +頂 +礎 +載 +倒 +房 +突 +坐 +粉 +敵 +略 +客 +袁 +冷 +勝 +絕 +析 +塊 +劑 +測 +絲 +協 +訴 +念 +陳 +仍 +羅 +鹽 +友 +洋 +錯 +苦 +夜 +刑 +移 +頻 +逐 +靠 +混 +母 +短 +皮 +終 +聚 +汽 +村 +雲 +哪 +既 +距 +衛 +停 +烈 +央 +察 +燒 +迅 +境 +若 +印 +洲 +刻 +括 +激 +孔 +搞 +甚 +室 +待 +核 +校 +散 +侵 +吧 +甲 +遊 +久 +菜 +味 +舊 +模 +湖 +貨 +損 +預 +阻 +毫 +普 +穩 +乙 +媽 +植 +息 +擴 +銀 +語 +揮 +酒 +守 +拿 +序 +紙 +醫 +缺 +雨 +嗎 +針 +劉 +啊 +急 +唱 +誤 +訓 +願 +審 +附 +獲 +茶 +鮮 +糧 +斤 +孩 +脫 +硫 +肥 +善 +龍 +演 +父 +漸 +血 +歡 +械 +掌 +歌 +沙 +剛 +攻 +謂 +盾 +討 +晚 +粒 +亂 +燃 +矛 +乎 +殺 +藥 +寧 +魯 +貴 +鐘 +煤 +讀 +班 +伯 +香 +介 +迫 +句 +豐 +培 +握 +蘭 +擔 +弦 +蛋 +沉 +假 +穿 +執 +答 +樂 +誰 +順 +煙 +縮 +徵 +臉 +喜 +松 +腳 +困 +異 +免 +背 +星 +福 +買 +染 +井 +概 +慢 +怕 +磁 +倍 +祖 +皇 +促 +靜 +補 +評 +翻 +肉 +踐 +尼 +衣 +寬 +揚 +棉 +希 +傷 +操 +垂 +秋 +宜 +氫 +套 +督 +振 +架 +亮 +末 +憲 +慶 +編 +牛 +觸 +映 +雷 +銷 +詩 +座 +居 +抓 +裂 +胞 +呼 +娘 +景 +威 +綠 +晶 +厚 +盟 +衡 +雞 +孫 +延 +危 +膠 +屋 +鄉 +臨 +陸 +顧 +掉 +呀 +燈 +歲 +措 +束 +耐 +劇 +玉 +趙 +跳 +哥 +季 +課 +凱 +胡 +額 +款 +紹 +卷 +齊 +偉 +蒸 +殖 +永 +宗 +苗 +川 +爐 +岩 +弱 +零 +楊 +奏 +沿 +露 +桿 +探 +滑 +鎮 +飯 +濃 +航 +懷 +趕 +庫 +奪 +伊 +靈 +稅 +途 +滅 +賽 +歸 +召 +鼓 +播 +盤 +裁 +險 +康 +唯 +錄 +菌 +純 +借 +糖 +蓋 +橫 +符 +私 +努 +堂 +域 +槍 +潤 +幅 +哈 +竟 +熟 +蟲 +澤 +腦 +壤 +碳 +歐 +遍 +側 +寨 +敢 +徹 +慮 +斜 +薄 +庭 +納 +彈 +飼 +伸 +折 +麥 +濕 +暗 +荷 +瓦 +塞 +床 +築 +惡 +戶 +訪 +塔 +奇 +透 +梁 +刀 +旋 +跡 +卡 +氯 +遇 +份 +毒 +泥 +退 +洗 +擺 +灰 +彩 +賣 +耗 +夏 +擇 +忙 +銅 +獻 +硬 +予 +繁 +圈 +雪 +函 +亦 +抽 +篇 +陣 +陰 +丁 +尺 +追 +堆 +雄 +迎 +泛 +爸 +樓 +避 +謀 +噸 +野 +豬 +旗 +累 +偏 +典 +館 +索 +秦 +脂 +潮 +爺 +豆 +忽 +托 +驚 +塑 +遺 +愈 +朱 +替 +纖 +粗 +傾 +尚 +痛 +楚 +謝 +奮 +購 +磨 +君 +池 +旁 +碎 +骨 +監 +捕 +弟 +暴 +割 +貫 +殊 +釋 +詞 +亡 +壁 +頓 +寶 +午 +塵 +聞 +揭 +炮 +殘 +冬 +橋 +婦 +警 +綜 +招 +吳 +付 +浮 +遭 +徐 +您 +搖 +谷 +贊 +箱 +隔 +訂 +男 +吹 +園 +紛 +唐 +敗 +宋 +玻 +巨 +耕 +坦 +榮 +閉 +灣 +鍵 +凡 +駐 +鍋 +救 +恩 +剝 +凝 +鹼 +齒 +截 +煉 +麻 +紡 +禁 +廢 +盛 +版 +緩 +淨 +睛 +昌 +婚 +涉 +筒 +嘴 +插 +岸 +朗 +莊 +街 +藏 +姑 +貿 +腐 +奴 +啦 +慣 +乘 +夥 +恢 +勻 +紗 +扎 +辯 +耳 +彪 +臣 +億 +璃 +抵 +脈 +秀 +薩 +俄 +網 +舞 +店 +噴 +縱 +寸 +汗 +掛 +洪 +賀 +閃 +柬 +爆 +烯 +津 +稻 +牆 +軟 +勇 +像 +滾 +厘 +蒙 +芳 +肯 +坡 +柱 +盪 +腿 +儀 +旅 +尾 +軋 +冰 +貢 +登 +黎 +削 +鑽 +勒 +逃 +障 +氨 +郭 +峰 +幣 +港 +伏 +軌 +畝 +畢 +擦 +莫 +刺 +浪 +秘 +援 +株 +健 +售 +股 +島 +甘 +泡 +睡 +童 +鑄 +湯 +閥 +休 +匯 +舍 +牧 +繞 +炸 +哲 +磷 +績 +朋 +淡 +尖 +啟 +陷 +柴 +呈 +徒 +顏 +淚 +稍 +忘 +泵 +藍 +拖 +洞 +授 +鏡 +辛 +壯 +鋒 +貧 +虛 +彎 +摩 +泰 +幼 +廷 +尊 +窗 +綱 +弄 +隸 +疑 +氏 +宮 +姐 +震 +瑞 +怪 +尤 +琴 +循 +描 +膜 +違 +夾 +腰 +緣 +珠 +窮 +森 +枝 +竹 +溝 +催 +繩 +憶 +邦 +剩 +幸 +漿 +欄 +擁 +牙 +貯 +禮 +濾 +鈉 +紋 +罷 +拍 +咱 +喊 +袖 +埃 +勤 +罰 +焦 +潛 +伍 +墨 +欲 +縫 +姓 +刊 +飽 +仿 +獎 +鋁 +鬼 +麗 +跨 +默 +挖 +鏈 +掃 +喝 +袋 +炭 +污 +幕 +諸 +弧 +勵 +梅 +奶 +潔 +災 +舟 +鑑 +苯 +訟 +抱 +毀 +懂 +寒 +智 +埔 +寄 +屆 +躍 +渡 +挑 +丹 +艱 +貝 +碰 +拔 +爹 +戴 +碼 +夢 +芽 +熔 +赤 +漁 +哭 +敬 +顆 +奔 +鉛 +仲 +虎 +稀 +妹 +乏 +珍 +申 +桌 +遵 +允 +隆 +螺 +倉 +魏 +銳 +曉 +氮 +兼 +隱 +礙 +赫 +撥 +忠 +肅 +缸 +牽 +搶 +博 +巧 +殼 +兄 +杜 +訊 +誠 +碧 +祥 +柯 +頁 +巡 +矩 +悲 +灌 +齡 +倫 +票 +尋 +桂 +鋪 +聖 +恐 +恰 +鄭 +趣 +抬 +荒 +騰 +貼 +柔 +滴 +猛 +闊 +輛 +妻 +填 +撤 +儲 +簽 +鬧 +擾 +紫 +砂 +遞 +戲 +吊 +陶 +伐 +餵 +療 +瓶 +婆 +撫 +臂 +摸 +忍 +蝦 +蠟 +鄰 +胸 +鞏 +擠 +偶 +棄 +槽 +勁 +乳 +鄧 +吉 +仁 +爛 +磚 +租 +烏 +艦 +伴 +瓜 +淺 +丙 +暫 +燥 +橡 +柳 +迷 +暖 +牌 +秧 +膽 +詳 +簧 +踏 +瓷 +譜 +呆 +賓 +糊 +洛 +輝 +憤 +競 +隙 +怒 +粘 +乃 +緒 +肩 +籍 +敏 +塗 +熙 +皆 +偵 +懸 +掘 +享 +糾 +醒 +狂 +鎖 +淀 +恨 +牲 +霸 +爬 +賞 +逆 +玩 +陵 +祝 +秒 +浙 +貌 +役 +彼 +悉 +鴨 +趨 +鳳 +晨 +畜 +輩 +秩 +卵 +署 +梯 +炎 +灘 +棋 +驅 +篩 +峽 +冒 +啥 +壽 +譯 +浸 +泉 +帽 +遲 +矽 +疆 +貸 +漏 +稿 +冠 +嫩 +脅 +芯 +牢 +叛 +蝕 +奧 +鳴 +嶺 +羊 +憑 +串 +塘 +繪 +酵 +融 +盆 +錫 +廟 +籌 +凍 +輔 +攝 +襲 +筋 +拒 +僚 +旱 +鉀 +鳥 +漆 +沈 +眉 +疏 +添 +棒 +穗 +硝 +韓 +逼 +扭 +僑 +涼 +挺 +碗 +栽 +炒 +杯 +患 +餾 +勸 +豪 +遼 +勃 +鴻 +旦 +吏 +拜 +狗 +埋 +輥 +掩 +飲 +搬 +罵 +辭 +勾 +扣 +估 +蔣 +絨 +霧 +丈 +朵 +姆 +擬 +宇 +輯 +陝 +雕 +償 +蓄 +崇 +剪 +倡 +廳 +咬 +駛 +薯 +刷 +斥 +番 +賦 +奉 +佛 +澆 +漫 +曼 +扇 +鈣 +桃 +扶 +仔 +返 +俗 +虧 +腔 +鞋 +棱 +覆 +框 +悄 +叔 +撞 +騙 +勘 +旺 +沸 +孤 +吐 +孟 +渠 +屈 +疾 +妙 +惜 +仰 +狠 +脹 +諧 +拋 +黴 +桑 +崗 +嘛 +衰 +盜 +滲 +臟 +賴 +湧 +甜 +曹 +閱 +肌 +哩 +厲 +烴 +緯 +毅 +昨 +偽 +症 +煮 +嘆 +釘 +搭 +莖 +籠 +酷 +偷 +弓 +錐 +恆 +傑 +坑 +鼻 +翼 +綸 +敘 +獄 +逮 +罐 +絡 +棚 +抑 +膨 +蔬 +寺 +驟 +穆 +冶 +枯 +冊 +屍 +凸 +紳 +坯 +犧 +焰 +轟 +欣 +晉 +瘦 +禦 +錠 +錦 +喪 +旬 +鍛 +壟 +搜 +撲 +邀 +亭 +酯 +邁 +舒 +脆 +酶 +閒 +憂 +酚 +頑 +羽 +漲 +卸 +仗 +陪 +闢 +懲 +杭 +姚 +肚 +捉 +飄 +漂 +昆 +欺 +吾 +郎 +烷 +汁 +呵 +飾 +蕭 +雅 +郵 +遷 +燕 +撒 +姻 +赴 +宴 +煩 +債 +帳 +斑 +鈴 +旨 +醇 +董 +餅 +雛 +姿 +拌 +傅 +腹 +妥 +揉 +賢 +拆 +歪 +葡 +胺 +丟 +浩 +徽 +昂 +墊 +擋 +覽 +貪 +慰 +繳 +汪 +慌 +馮 +諾 +姜 +誼 +兇 +劣 +誣 +耀 +昏 +躺 +盈 +騎 +喬 +溪 +叢 +盧 +抹 +悶 +諮 +刮 +駕 +纜 +悟 +摘 +鉺 +擲 +頗 +幻 +柄 +惠 +慘 +佳 +仇 +臘 +窩 +滌 +劍 +瞧 +堡 +潑 +蔥 +罩 +霍 +撈 +胎 +蒼 +濱 +倆 +捅 +湘 +砍 +霞 +邵 +萄 +瘋 +淮 +遂 +熊 +糞 +烘 +宿 +檔 +戈 +駁 +嫂 +裕 +徙 +箭 +捐 +腸 +撐 +曬 +辨 +殿 +蓮 +攤 +攪 +醬 +屏 +疫 +哀 +蔡 +堵 +沫 +皺 +暢 +疊 +閣 +萊 +敲 +轄 +鉤 +痕 +壩 +巷 +餓 +禍 +丘 +玄 +溜 +曰 +邏 +彭 +嘗 +卿 +妨 +艇 +吞 +韋 +怨 +矮 +歇`.split('\n'); diff --git a/node_modules/accepts/HISTORY.md b/node_modules/accepts/HISTORY.md new file mode 100644 index 0000000..627a81d --- /dev/null +++ b/node_modules/accepts/HISTORY.md @@ -0,0 +1,250 @@ +2.0.0 / 2024-08-31 +================== + + * Drop node <18 support + * deps: mime-types@^3.0.0 + * deps: negotiator@^1.0.0 + +1.3.8 / 2022-02-02 +================== + + * deps: mime-types@~2.1.34 + - deps: mime-db@~1.51.0 + * deps: negotiator@0.6.3 + +1.3.7 / 2019-04-29 +================== + + * deps: negotiator@0.6.2 + - Fix sorting charset, encoding, and language with extra parameters + +1.3.6 / 2019-04-28 +================== + + * deps: mime-types@~2.1.24 + - deps: mime-db@~1.40.0 + +1.3.5 / 2018-02-28 +================== + + * deps: mime-types@~2.1.18 + - deps: mime-db@~1.33.0 + +1.3.4 / 2017-08-22 +================== + + * deps: mime-types@~2.1.16 + - deps: mime-db@~1.29.0 + +1.3.3 / 2016-05-02 +================== + + * deps: mime-types@~2.1.11 + - deps: mime-db@~1.23.0 + * deps: negotiator@0.6.1 + - perf: improve `Accept` parsing speed + - perf: improve `Accept-Charset` parsing speed + - perf: improve `Accept-Encoding` parsing speed + - perf: improve `Accept-Language` parsing speed + +1.3.2 / 2016-03-08 +================== + + * deps: mime-types@~2.1.10 + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + - deps: mime-db@~1.22.0 + +1.3.1 / 2016-01-19 +================== + + * deps: mime-types@~2.1.9 + - deps: mime-db@~1.21.0 + +1.3.0 / 2015-09-29 +================== + + * deps: mime-types@~2.1.7 + - deps: mime-db@~1.19.0 + * deps: negotiator@0.6.0 + - Fix including type extensions in parameters in `Accept` parsing + - Fix parsing `Accept` parameters with quoted equals + - Fix parsing `Accept` parameters with quoted semicolons + - Lazy-load modules from main entry point + - perf: delay type concatenation until needed + - perf: enable strict mode + - perf: hoist regular expressions + - perf: remove closures getting spec properties + - perf: remove a closure from media type parsing + - perf: remove property delete from media type parsing + +1.2.13 / 2015-09-06 +=================== + + * deps: mime-types@~2.1.6 + - deps: mime-db@~1.18.0 + +1.2.12 / 2015-07-30 +=================== + + * deps: mime-types@~2.1.4 + - deps: mime-db@~1.16.0 + +1.2.11 / 2015-07-16 +=================== + + * deps: mime-types@~2.1.3 + - deps: mime-db@~1.15.0 + +1.2.10 / 2015-07-01 +=================== + + * deps: mime-types@~2.1.2 + - deps: mime-db@~1.14.0 + +1.2.9 / 2015-06-08 +================== + + * deps: mime-types@~2.1.1 + - perf: fix deopt during mapping + +1.2.8 / 2015-06-07 +================== + + * deps: mime-types@~2.1.0 + - deps: mime-db@~1.13.0 + * perf: avoid argument reassignment & argument slice + * perf: avoid negotiator recursive construction + * perf: enable strict mode + * perf: remove unnecessary bitwise operator + +1.2.7 / 2015-05-10 +================== + + * deps: negotiator@0.5.3 + - Fix media type parameter matching to be case-insensitive + +1.2.6 / 2015-05-07 +================== + + * deps: mime-types@~2.0.11 + - deps: mime-db@~1.9.1 + * deps: negotiator@0.5.2 + - Fix comparing media types with quoted values + - Fix splitting media types with quoted commas + +1.2.5 / 2015-03-13 +================== + + * deps: mime-types@~2.0.10 + - deps: mime-db@~1.8.0 + +1.2.4 / 2015-02-14 +================== + + * Support Node.js 0.6 + * deps: mime-types@~2.0.9 + - deps: mime-db@~1.7.0 + * deps: negotiator@0.5.1 + - Fix preference sorting to be stable for long acceptable lists + +1.2.3 / 2015-01-31 +================== + + * deps: mime-types@~2.0.8 + - deps: mime-db@~1.6.0 + +1.2.2 / 2014-12-30 +================== + + * deps: mime-types@~2.0.7 + - deps: mime-db@~1.5.0 + +1.2.1 / 2014-12-30 +================== + + * deps: mime-types@~2.0.5 + - deps: mime-db@~1.3.1 + +1.2.0 / 2014-12-19 +================== + + * deps: negotiator@0.5.0 + - Fix list return order when large accepted list + - Fix missing identity encoding when q=0 exists + - Remove dynamic building of Negotiator class + +1.1.4 / 2014-12-10 +================== + + * deps: mime-types@~2.0.4 + - deps: mime-db@~1.3.0 + +1.1.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - deps: mime-db@~1.2.0 + +1.1.2 / 2014-10-14 +================== + + * deps: negotiator@0.4.9 + - Fix error when media type has invalid parameter + +1.1.1 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - deps: mime-db@~1.1.0 + * deps: negotiator@0.4.8 + - Fix all negotiations to be case-insensitive + - Stable sort preferences of same quality according to client order + +1.1.0 / 2014-09-02 +================== + + * update `mime-types` + +1.0.7 / 2014-07-04 +================== + + * Fix wrong type returned from `type` when match after unknown extension + +1.0.6 / 2014-06-24 +================== + + * deps: negotiator@0.4.7 + +1.0.5 / 2014-06-20 +================== + + * fix crash when unknown extension given + +1.0.4 / 2014-06-19 +================== + + * use `mime-types` + +1.0.3 / 2014-06-11 +================== + + * deps: negotiator@0.4.6 + - Order by specificity when quality is the same + +1.0.2 / 2014-05-29 +================== + + * Fix interpretation when header not in request + * deps: pin negotiator@0.4.5 + +1.0.1 / 2014-01-18 +================== + + * Identity encoding isn't always acceptable + * deps: negotiator@~0.4.0 + +1.0.0 / 2013-12-27 +================== + + * Genesis diff --git a/node_modules/accepts/LICENSE b/node_modules/accepts/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/node_modules/accepts/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/accepts/README.md b/node_modules/accepts/README.md new file mode 100644 index 0000000..f3f10c4 --- /dev/null +++ b/node_modules/accepts/README.md @@ -0,0 +1,140 @@ +# accepts + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator). +Extracted from [koa](https://www.npmjs.com/package/koa) for general use. + +In addition to negotiator, it allows: + +- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])` + as well as `('text/html', 'application/json')`. +- Allows type shorthands such as `json`. +- Returns `false` when no types match +- Treats non-existent headers as `*` + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install accepts +``` + +## API + +```js +var accepts = require('accepts') +``` + +### accepts(req) + +Create a new `Accepts` object for the given `req`. + +#### .charset(charsets) + +Return the first accepted charset. If nothing in `charsets` is accepted, +then `false` is returned. + +#### .charsets() + +Return the charsets that the request accepts, in the order of the client's +preference (most preferred first). + +#### .encoding(encodings) + +Return the first accepted encoding. If nothing in `encodings` is accepted, +then `false` is returned. + +#### .encodings() + +Return the encodings that the request accepts, in the order of the client's +preference (most preferred first). + +#### .language(languages) + +Return the first accepted language. If nothing in `languages` is accepted, +then `false` is returned. + +#### .languages() + +Return the languages that the request accepts, in the order of the client's +preference (most preferred first). + +#### .type(types) + +Return the first accepted type (and it is returned as the same text as what +appears in the `types` array). If nothing in `types` is accepted, then `false` +is returned. + +The `types` array can contain full MIME types or file extensions. Any value +that is not a full MIME type is passed to `require('mime-types').lookup`. + +#### .types() + +Return the types that the request accepts, in the order of the client's +preference (most preferred first). + +## Examples + +### Simple type negotiation + +This simple example shows how to use `accepts` to return a different typed +respond body based on what the client wants to accept. The server lists it's +preferences in order and will get back the best match between the client and +server. + +```js +var accepts = require('accepts') +var http = require('http') + +function app (req, res) { + var accept = accepts(req) + + // the order of this list is significant; should be server preferred order + switch (accept.type(['json', 'html'])) { + case 'json': + res.setHeader('Content-Type', 'application/json') + res.write('{"hello":"world!"}') + break + case 'html': + res.setHeader('Content-Type', 'text/html') + res.write('hello, world!') + break + default: + // the fallback is text/plain, so no need to specify it above + res.setHeader('Content-Type', 'text/plain') + res.write('hello, world!') + break + } + + res.end() +} + +http.createServer(app).listen(3000) +``` + +You can test this out with the cURL program: +```sh +curl -I -H'Accept: text/html' http://localhost:3000/ +``` + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/accepts/master +[coveralls-url]: https://coveralls.io/r/jshttp/accepts?branch=master +[github-actions-ci-image]: https://badgen.net/github/checks/jshttp/accepts/master?label=ci +[github-actions-ci-url]: https://github.com/jshttp/accepts/actions/workflows/ci.yml +[node-version-image]: https://badgen.net/npm/node/accepts +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/accepts +[npm-url]: https://npmjs.org/package/accepts +[npm-version-image]: https://badgen.net/npm/v/accepts diff --git a/node_modules/accepts/index.js b/node_modules/accepts/index.js new file mode 100644 index 0000000..4f2840c --- /dev/null +++ b/node_modules/accepts/index.js @@ -0,0 +1,238 @@ +/*! + * accepts + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var Negotiator = require('negotiator') +var mime = require('mime-types') + +/** + * Module exports. + * @public + */ + +module.exports = Accepts + +/** + * Create a new Accepts object for the given req. + * + * @param {object} req + * @public + */ + +function Accepts (req) { + if (!(this instanceof Accepts)) { + return new Accepts(req) + } + + this.headers = req.headers + this.negotiator = new Negotiator(req) +} + +/** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json" or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * this.types('html'); + * // => "html" + * + * // Accept: text/*, application/json + * this.types('html'); + * // => "html" + * this.types('text/html'); + * // => "text/html" + * this.types('json', 'text'); + * // => "json" + * this.types('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * this.types('image/png'); + * this.types('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * this.types(['html', 'json']); + * this.types('html', 'json'); + * // => "json" + * + * @param {String|Array} types... + * @return {String|Array|Boolean} + * @public + */ + +Accepts.prototype.type = +Accepts.prototype.types = function (types_) { + var types = types_ + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i] + } + } + + // no types, return all requested types + if (!types || types.length === 0) { + return this.negotiator.mediaTypes() + } + + // no accept header, return first given type + if (!this.headers.accept) { + return types[0] + } + + var mimes = types.map(extToMime) + var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)) + var first = accepts[0] + + return first + ? types[mimes.indexOf(first)] + : false +} + +/** + * Return accepted encodings or best fit based on `encodings`. + * + * Given `Accept-Encoding: gzip, deflate` + * an array sorted by quality is returned: + * + * ['gzip', 'deflate'] + * + * @param {String|Array} encodings... + * @return {String|Array} + * @public + */ + +Accepts.prototype.encoding = +Accepts.prototype.encodings = function (encodings_) { + var encodings = encodings_ + + // support flattened arguments + if (encodings && !Array.isArray(encodings)) { + encodings = new Array(arguments.length) + for (var i = 0; i < encodings.length; i++) { + encodings[i] = arguments[i] + } + } + + // no encodings, return all requested encodings + if (!encodings || encodings.length === 0) { + return this.negotiator.encodings() + } + + return this.negotiator.encodings(encodings)[0] || false +} + +/** + * Return accepted charsets or best fit based on `charsets`. + * + * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` + * an array sorted by quality is returned: + * + * ['utf-8', 'utf-7', 'iso-8859-1'] + * + * @param {String|Array} charsets... + * @return {String|Array} + * @public + */ + +Accepts.prototype.charset = +Accepts.prototype.charsets = function (charsets_) { + var charsets = charsets_ + + // support flattened arguments + if (charsets && !Array.isArray(charsets)) { + charsets = new Array(arguments.length) + for (var i = 0; i < charsets.length; i++) { + charsets[i] = arguments[i] + } + } + + // no charsets, return all requested charsets + if (!charsets || charsets.length === 0) { + return this.negotiator.charsets() + } + + return this.negotiator.charsets(charsets)[0] || false +} + +/** + * Return accepted languages or best fit based on `langs`. + * + * Given `Accept-Language: en;q=0.8, es, pt` + * an array sorted by quality is returned: + * + * ['es', 'pt', 'en'] + * + * @param {String|Array} langs... + * @return {Array|String} + * @public + */ + +Accepts.prototype.lang = +Accepts.prototype.langs = +Accepts.prototype.language = +Accepts.prototype.languages = function (languages_) { + var languages = languages_ + + // support flattened arguments + if (languages && !Array.isArray(languages)) { + languages = new Array(arguments.length) + for (var i = 0; i < languages.length; i++) { + languages[i] = arguments[i] + } + } + + // no languages, return all requested languages + if (!languages || languages.length === 0) { + return this.negotiator.languages() + } + + return this.negotiator.languages(languages)[0] || false +} + +/** + * Convert extnames to mime. + * + * @param {String} type + * @return {String} + * @private + */ + +function extToMime (type) { + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if mime is valid. + * + * @param {String} type + * @return {Boolean} + * @private + */ + +function validMime (type) { + return typeof type === 'string' +} diff --git a/node_modules/accepts/package.json b/node_modules/accepts/package.json new file mode 100644 index 0000000..b35b262 --- /dev/null +++ b/node_modules/accepts/package.json @@ -0,0 +1,47 @@ +{ + "name": "accepts", + "description": "Higher-level content negotiation", + "version": "2.0.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "jshttp/accepts", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "devDependencies": { + "deep-equal": "1.0.1", + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "4.3.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.0", + "nyc": "15.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + }, + "keywords": [ + "content", + "negotiation", + "accept", + "accepts" + ] +} diff --git a/node_modules/async/CHANGELOG.md b/node_modules/async/CHANGELOG.md new file mode 100644 index 0000000..ce990a5 --- /dev/null +++ b/node_modules/async/CHANGELOG.md @@ -0,0 +1,351 @@ +# v3.2.5 +- Ensure `Error` objects such as `AggregateError` are propagated without modification (#1920) + +# v3.2.4 +- Fix a bug in `priorityQueue` where it didn't wait for the result. (#1725) +- Fix a bug where `unshiftAsync` was included in `priorityQueue`. (#1790) + +# v3.2.3 +- Fix bugs in comment parsing in `autoInject`. (#1767, #1780) + +# v3.2.2 +- Fix potential prototype pollution exploit + +# v3.2.1 +- Use `queueMicrotask` if available to the environment (#1761) +- Minor perf improvement in `priorityQueue` (#1727) +- More examples in documentation (#1726) +- Various doc fixes (#1708, #1712, #1717, #1740, #1739, #1749, #1756) +- Improved test coverage (#1754) + +# v3.2.0 +- Fix a bug in Safari related to overwriting `func.name` +- Remove built-in browserify configuration (#1653) +- Varios doc fixes (#1688, #1703, #1704) + +# v3.1.1 +- Allow redefining `name` property on wrapped functions. + +# v3.1.0 + +- Added `q.pushAsync` and `q.unshiftAsync`, analagous to `q.push` and `q.unshift`, except they always do not accept a callback, and reject if processing the task errors. (#1659) +- Promises returned from `q.push` and `q.unshift` when a callback is not passed now resolve even if an error ocurred. (#1659) +- Fixed a parsing bug in `autoInject` with complicated function bodies (#1663) +- Added ES6+ configuration for Browserify bundlers (#1653) +- Various doc fixes (#1664, #1658, #1665, #1652) + +# v3.0.1 + +## Bug fixes +- Fixed a regression where arrays passed to `queue` and `cargo` would be completely flattened. (#1645) +- Clarified Async's browser support (#1643) + + +# v3.0.0 + +The `async`/`await` release! + +There are a lot of new features and subtle breaking changes in this major version, but the biggest feature is that most Async methods return a Promise if you omit the callback, meaning you can `await` them from within an `async` function. + +```js +const results = await async.mapLimit(urls, 5, async url => { + const resp = await fetch(url) + return resp.body +}) +``` + +## Breaking Changes +- Most Async methods return a Promise when the final callback is omitted, making them `await`-able! (#1572) +- We are now making heavy use of ES2015 features, this means we have dropped out-of-the-box support for Node 4 and earlier, and many old versions of browsers. (#1541, #1553) +- In `queue`, `priorityQueue`, `cargo` and `cargoQueue`, the "event"-style methods, like `q.drain` and `q.saturated` are now methods that register a callback, rather than properties you assign a callback to. They are now of the form `q.drain(callback)`. If you do not pass a callback a Promise will be returned for the next occurrence of the event, making them `await`-able, e.g. `await q.drain()`. (#1586, #1641) +- Calling `callback(false)` will cancel an async method, preventing further iteration and callback calls. This is useful for preventing memory leaks when you break out of an async flow by calling an outer callback. (#1064, #1542) +- `during` and `doDuring` have been removed, and instead `whilst`, `doWhilst`, `until` and `doUntil` now have asynchronous `test` functions. (#850, #1557) +- `limits` of less than 1 now cause an error to be thrown in queues and collection methods. (#1249, #1552) +- `memoize` no longer memoizes errors (#1465, #1466) +- `applyEach`/`applyEachSeries` have a simpler interface, to make them more easily type-able. It always returns a function that takes in a single callback argument. If that callback is omitted, a promise is returned, making it awaitable. (#1228, #1640) + +## New Features +- Async generators are now supported in all the Collection methods. (#1560) +- Added `cargoQueue`, a queue with both `concurrency` and `payload` size parameters. (#1567) +- Queue objects returned from `queue` now have a `Symbol.iterator` method, meaning they can be iterated over to inspect the current list of items in the queue. (#1459, #1556) +- A ESM-flavored `async.mjs` is included in the `async` package. This is described in the `package.json` `"module"` field, meaning it should be automatically used by Webpack and other compatible bundlers. + +## Bug fixes +- Better handle arbitrary error objects in `asyncify` (#1568, #1569) + +## Other +- Removed Lodash as a dependency (#1283, #1528) +- Miscellaneous docs fixes (#1393, #1501, #1540, #1543, #1558, #1563, #1564, #1579, #1581) +- Miscellaneous test fixes (#1538) + +------- + +# v2.6.1 +- Updated lodash to prevent `npm audit` warnings. (#1532, #1533) +- Made `async-es` more optimized for webpack users (#1517) +- Fixed a stack overflow with large collections and a synchronous iterator (#1514) +- Various small fixes/chores (#1505, #1511, #1527, #1530) + +# v2.6.0 +- Added missing aliases for many methods. Previously, you could not (e.g.) `require('async/find')` or use `async.anyLimit`. (#1483) +- Improved `queue` performance. (#1448, #1454) +- Add missing sourcemap (#1452, #1453) +- Various doc updates (#1448, #1471, #1483) + +# v2.5.0 +- Added `concatLimit`, the `Limit` equivalent of [`concat`](https://caolan.github.io/async/docs.html#concat) ([#1426](https://github.com/caolan/async/issues/1426), [#1430](https://github.com/caolan/async/pull/1430)) +- `concat` improvements: it now preserves order, handles falsy values and the `iteratee` callback takes a variable number of arguments ([#1437](https://github.com/caolan/async/issues/1437), [#1436](https://github.com/caolan/async/pull/1436)) +- Fixed an issue in `queue` where there was a size discrepancy between `workersList().length` and `running()` ([#1428](https://github.com/caolan/async/issues/1428), [#1429](https://github.com/caolan/async/pull/1429)) +- Various doc fixes ([#1422](https://github.com/caolan/async/issues/1422), [#1424](https://github.com/caolan/async/pull/1424)) + +# v2.4.1 +- Fixed a bug preventing functions wrapped with `timeout()` from being re-used. ([#1418](https://github.com/caolan/async/issues/1418), [#1419](https://github.com/caolan/async/issues/1419)) + +# v2.4.0 +- Added `tryEach`, for running async functions in parallel, where you only expect one to succeed. ([#1365](https://github.com/caolan/async/issues/1365), [#687](https://github.com/caolan/async/issues/687)) +- Improved performance, most notably in `parallel` and `waterfall` ([#1395](https://github.com/caolan/async/issues/1395)) +- Added `queue.remove()`, for removing items in a `queue` ([#1397](https://github.com/caolan/async/issues/1397), [#1391](https://github.com/caolan/async/issues/1391)) +- Fixed using `eval`, preventing Async from running in pages with Content Security Policy ([#1404](https://github.com/caolan/async/issues/1404), [#1403](https://github.com/caolan/async/issues/1403)) +- Fixed errors thrown in an `asyncify`ed function's callback being caught by the underlying Promise ([#1408](https://github.com/caolan/async/issues/1408)) +- Fixed timing of `queue.empty()` ([#1367](https://github.com/caolan/async/issues/1367)) +- Various doc fixes ([#1314](https://github.com/caolan/async/issues/1314), [#1394](https://github.com/caolan/async/issues/1394), [#1412](https://github.com/caolan/async/issues/1412)) + +# v2.3.0 +- Added support for ES2017 `async` functions. Wherever you can pass a Node-style/CPS function that uses a callback, you can also pass an `async` function. Previously, you had to wrap `async` functions with `asyncify`. The caveat is that it will only work if `async` functions are supported natively in your environment, transpiled implementations can't be detected. ([#1386](https://github.com/caolan/async/issues/1386), [#1390](https://github.com/caolan/async/issues/1390)) +- Small doc fix ([#1392](https://github.com/caolan/async/issues/1392)) + +# v2.2.0 +- Added `groupBy`, and the `Series`/`Limit` equivalents, analogous to [`_.groupBy`](http://lodash.com/docs#groupBy) ([#1364](https://github.com/caolan/async/issues/1364)) +- Fixed `transform` bug when `callback` was not passed ([#1381](https://github.com/caolan/async/issues/1381)) +- Added note about `reflect` to `parallel` docs ([#1385](https://github.com/caolan/async/issues/1385)) + +# v2.1.5 +- Fix `auto` bug when function names collided with Array.prototype ([#1358](https://github.com/caolan/async/issues/1358)) +- Improve some error messages ([#1349](https://github.com/caolan/async/issues/1349)) +- Avoid stack overflow case in queue +- Fixed an issue in `some`, `every` and `find` where processing would continue after the result was determined. +- Cleanup implementations of `some`, `every` and `find` + +# v2.1.3 +- Make bundle size smaller +- Create optimized hotpath for `filter` in array case. + +# v2.1.2 +- Fixed a stackoverflow bug with `detect`, `some`, `every` on large inputs ([#1293](https://github.com/caolan/async/issues/1293)). + +# v2.1.0 + +- `retry` and `retryable` now support an optional `errorFilter` function that determines if the `task` should retry on the error ([#1256](https://github.com/caolan/async/issues/1256), [#1261](https://github.com/caolan/async/issues/1261)) +- Optimized array iteration in `race`, `cargo`, `queue`, and `priorityQueue` ([#1253](https://github.com/caolan/async/issues/1253)) +- Added alias documentation to doc site ([#1251](https://github.com/caolan/async/issues/1251), [#1254](https://github.com/caolan/async/issues/1254)) +- Added [BootStrap scrollspy](http://getbootstrap.com/javascript/#scrollspy) to docs to highlight in the sidebar the current method being viewed ([#1289](https://github.com/caolan/async/issues/1289), [#1300](https://github.com/caolan/async/issues/1300)) +- Various minor doc fixes ([#1263](https://github.com/caolan/async/issues/1263), [#1264](https://github.com/caolan/async/issues/1264), [#1271](https://github.com/caolan/async/issues/1271), [#1278](https://github.com/caolan/async/issues/1278), [#1280](https://github.com/caolan/async/issues/1280), [#1282](https://github.com/caolan/async/issues/1282), [#1302](https://github.com/caolan/async/issues/1302)) + +# v2.0.1 + +- Significantly optimized all iteration based collection methods such as `each`, `map`, `filter`, etc ([#1245](https://github.com/caolan/async/issues/1245), [#1246](https://github.com/caolan/async/issues/1246), [#1247](https://github.com/caolan/async/issues/1247)). + +# v2.0.0 + +Lots of changes here! + +First and foremost, we have a slick new [site for docs](https://caolan.github.io/async/). Special thanks to [**@hargasinski**](https://github.com/hargasinski) for his work converting our old docs to `jsdoc` format and implementing the new website. Also huge ups to [**@ivanseidel**](https://github.com/ivanseidel) for designing our new logo. It was a long process for both of these tasks, but I think these changes turned out extraordinary well. + +The biggest feature is modularization. You can now `require("async/series")` to only require the `series` function. Every Async library function is available this way. You still can `require("async")` to require the entire library, like you could do before. + +We also provide Async as a collection of ES2015 modules. You can now `import {each} from 'async-es'` or `import waterfall from 'async-es/waterfall'`. If you are using only a few Async functions, and are using a ES bundler such as Rollup, this can significantly lower your build size. + +Major thanks to [**@Kikobeats**](github.com/Kikobeats), [**@aearly**](github.com/aearly) and [**@megawac**](github.com/megawac) for doing the majority of the modularization work, as well as [**@jdalton**](github.com/jdalton) and [**@Rich-Harris**](github.com/Rich-Harris) for advisory work on the general modularization strategy. + +Another one of the general themes of the 2.0 release is standardization of what an "async" function is. We are now more strictly following the node-style continuation passing style. That is, an async function is a function that: + +1. Takes a variable number of arguments +2. The last argument is always a callback +3. The callback can accept any number of arguments +4. The first argument passed to the callback will be treated as an error result, if the argument is truthy +5. Any number of result arguments can be passed after the "error" argument +6. The callback is called once and exactly once, either on the same tick or later tick of the JavaScript event loop. + +There were several cases where Async accepted some functions that did not strictly have these properties, most notably `auto`, `every`, `some`, `filter`, `reject` and `detect`. + +Another theme is performance. We have eliminated internal deferrals in all cases where they make sense. For example, in `waterfall` and `auto`, there was a `setImmediate` between each task -- these deferrals have been removed. A `setImmediate` call can add up to 1ms of delay. This might not seem like a lot, but it can add up if you are using many Async functions in the course of processing a HTTP request, for example. Nearly all asynchronous functions that do I/O already have some sort of deferral built in, so the extra deferral is unnecessary. The trade-off of this change is removing our built-in stack-overflow defense. Many synchronous callback calls in series can quickly overflow the JS call stack. If you do have a function that is sometimes synchronous (calling its callback on the same tick), and are running into stack overflows, wrap it with `async.ensureAsync()`. + +Another big performance win has been re-implementing `queue`, `cargo`, and `priorityQueue` with [doubly linked lists](https://en.wikipedia.org/wiki/Doubly_linked_list) instead of arrays. This has lead to queues being an order of [magnitude faster on large sets of tasks](https://github.com/caolan/async/pull/1205). + +## New Features + +- Async is now modularized. Individual functions can be `require()`d from the main package. (`require('async/auto')`) ([#984](https://github.com/caolan/async/issues/984), [#996](https://github.com/caolan/async/issues/996)) +- Async is also available as a collection of ES2015 modules in the new `async-es` package. (`import {forEachSeries} from 'async-es'`) ([#984](https://github.com/caolan/async/issues/984), [#996](https://github.com/caolan/async/issues/996)) +- Added `race`, analogous to `Promise.race()`. It will run an array of async tasks in parallel and will call its callback with the result of the first task to respond. ([#568](https://github.com/caolan/async/issues/568), [#1038](https://github.com/caolan/async/issues/1038)) +- Collection methods now accept ES2015 iterators. Maps, Sets, and anything that implements the iterator spec can now be passed directly to `each`, `map`, `parallel`, etc.. ([#579](https://github.com/caolan/async/issues/579), [#839](https://github.com/caolan/async/issues/839), [#1074](https://github.com/caolan/async/issues/1074)) +- Added `mapValues`, for mapping over the properties of an object and returning an object with the same keys. ([#1157](https://github.com/caolan/async/issues/1157), [#1177](https://github.com/caolan/async/issues/1177)) +- Added `timeout`, a wrapper for an async function that will make the task time-out after the specified time. ([#1007](https://github.com/caolan/async/issues/1007), [#1027](https://github.com/caolan/async/issues/1027)) +- Added `reflect` and `reflectAll`, analagous to [`Promise.reflect()`](http://bluebirdjs.com/docs/api/reflect.html), a wrapper for async tasks that always succeeds, by gathering results and errors into an object. ([#942](https://github.com/caolan/async/issues/942), [#1012](https://github.com/caolan/async/issues/1012), [#1095](https://github.com/caolan/async/issues/1095)) +- `constant` supports dynamic arguments -- it will now always use its last argument as the callback. ([#1016](https://github.com/caolan/async/issues/1016), [#1052](https://github.com/caolan/async/issues/1052)) +- `setImmediate` and `nextTick` now support arguments to partially apply to the deferred function, like the node-native versions do. ([#940](https://github.com/caolan/async/issues/940), [#1053](https://github.com/caolan/async/issues/1053)) +- `auto` now supports resolving cyclic dependencies using [Kahn's algorithm](https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm) ([#1140](https://github.com/caolan/async/issues/1140)). +- Added `autoInject`, a relative of `auto` that automatically spreads a task's dependencies as arguments to the task function. ([#608](https://github.com/caolan/async/issues/608), [#1055](https://github.com/caolan/async/issues/1055), [#1099](https://github.com/caolan/async/issues/1099), [#1100](https://github.com/caolan/async/issues/1100)) +- You can now limit the concurrency of `auto` tasks. ([#635](https://github.com/caolan/async/issues/635), [#637](https://github.com/caolan/async/issues/637)) +- Added `retryable`, a relative of `retry` that wraps an async function, making it retry when called. ([#1058](https://github.com/caolan/async/issues/1058)) +- `retry` now supports specifying a function that determines the next time interval, useful for exponential backoff, logging and other retry strategies. ([#1161](https://github.com/caolan/async/issues/1161)) +- `retry` will now pass all of the arguments the task function was resolved with to the callback ([#1231](https://github.com/caolan/async/issues/1231)). +- Added `q.unsaturated` -- callback called when a `queue`'s number of running workers falls below a threshold. ([#868](https://github.com/caolan/async/issues/868), [#1030](https://github.com/caolan/async/issues/1030), [#1033](https://github.com/caolan/async/issues/1033), [#1034](https://github.com/caolan/async/issues/1034)) +- Added `q.error` -- a callback called whenever a `queue` task calls its callback with an error. ([#1170](https://github.com/caolan/async/issues/1170)) +- `applyEach` and `applyEachSeries` now pass results to the final callback. ([#1088](https://github.com/caolan/async/issues/1088)) + +## Breaking changes + +- Calling a callback more than once is considered an error, and an error will be thrown. This had an explicit breaking change in `waterfall`. If you were relying on this behavior, you should more accurately represent your control flow as an event emitter or stream. ([#814](https://github.com/caolan/async/issues/814), [#815](https://github.com/caolan/async/issues/815), [#1048](https://github.com/caolan/async/issues/1048), [#1050](https://github.com/caolan/async/issues/1050)) +- `auto` task functions now always take the callback as the last argument. If a task has dependencies, the `results` object will be passed as the first argument. To migrate old task functions, wrap them with [`_.flip`](https://lodash.com/docs#flip) ([#1036](https://github.com/caolan/async/issues/1036), [#1042](https://github.com/caolan/async/issues/1042)) +- Internal `setImmediate` calls have been refactored away. This may make existing flows vulnerable to stack overflows if you use many synchronous functions in series. Use `ensureAsync` to work around this. ([#696](https://github.com/caolan/async/issues/696), [#704](https://github.com/caolan/async/issues/704), [#1049](https://github.com/caolan/async/issues/1049), [#1050](https://github.com/caolan/async/issues/1050)) +- `map` used to return an object when iterating over an object. `map` now always returns an array, like in other libraries. The previous object behavior has been split out into `mapValues`. ([#1157](https://github.com/caolan/async/issues/1157), [#1177](https://github.com/caolan/async/issues/1177)) +- `filter`, `reject`, `some`, `every`, `detect` and their families like `{METHOD}Series` and `{METHOD}Limit` now expect an error as the first callback argument, rather than just a simple boolean. Pass `null` as the first argument, or use `fs.access` instead of `fs.exists`. ([#118](https://github.com/caolan/async/issues/118), [#774](https://github.com/caolan/async/issues/774), [#1028](https://github.com/caolan/async/issues/1028), [#1041](https://github.com/caolan/async/issues/1041)) +- `{METHOD}` and `{METHOD}Series` are now implemented in terms of `{METHOD}Limit`. This is a major internal simplification, and is not expected to cause many problems, but it does subtly affect how functions execute internally. ([#778](https://github.com/caolan/async/issues/778), [#847](https://github.com/caolan/async/issues/847)) +- `retry`'s callback is now optional. Previously, omitting the callback would partially apply the function, meaning it could be passed directly as a task to `series` or `auto`. The partially applied "control-flow" behavior has been separated out into `retryable`. ([#1054](https://github.com/caolan/async/issues/1054), [#1058](https://github.com/caolan/async/issues/1058)) +- The test function for `whilst`, `until`, and `during` used to be passed non-error args from the iteratee function's callback, but this led to weirdness where the first call of the test function would be passed no args. We have made it so the test function is never passed extra arguments, and only the `doWhilst`, `doUntil`, and `doDuring` functions pass iteratee callback arguments to the test function ([#1217](https://github.com/caolan/async/issues/1217), [#1224](https://github.com/caolan/async/issues/1224)) +- The `q.tasks` array has been renamed `q._tasks` and is now implemented as a doubly linked list (DLL). Any code that used to interact with this array will need to be updated to either use the provided helpers or support DLLs ([#1205](https://github.com/caolan/async/issues/1205)). +- The timing of the `q.saturated()` callback in a `queue` has been modified to better reflect when tasks pushed to the queue will start queueing. ([#724](https://github.com/caolan/async/issues/724), [#1078](https://github.com/caolan/async/issues/1078)) +- Removed `iterator` method in favour of [ES2015 iterator protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators ) which natively supports arrays ([#1237](https://github.com/caolan/async/issues/1237)) +- Dropped support for Component, Jam, SPM, and Volo ([#1175](https://github.com/caolan/async/issues/1175), #[#176](https://github.com/caolan/async/issues/176)) + +## Bug Fixes + +- Improved handling of no dependency cases in `auto` & `autoInject` ([#1147](https://github.com/caolan/async/issues/1147)). +- Fixed a bug where the callback generated by `asyncify` with `Promises` could resolve twice ([#1197](https://github.com/caolan/async/issues/1197)). +- Fixed several documented optional callbacks not actually being optional ([#1223](https://github.com/caolan/async/issues/1223)). + +## Other + +- Added `someSeries` and `everySeries` for symmetry, as well as a complete set of `any`/`anyLimit`/`anySeries` and `all`/`/allLmit`/`allSeries` aliases. +- Added `find` as an alias for `detect. (as well as `findLimit` and `findSeries`). +- Various doc fixes ([#1005](https://github.com/caolan/async/issues/1005), [#1008](https://github.com/caolan/async/issues/1008), [#1010](https://github.com/caolan/async/issues/1010), [#1015](https://github.com/caolan/async/issues/1015), [#1021](https://github.com/caolan/async/issues/1021), [#1037](https://github.com/caolan/async/issues/1037), [#1039](https://github.com/caolan/async/issues/1039), [#1051](https://github.com/caolan/async/issues/1051), [#1102](https://github.com/caolan/async/issues/1102), [#1107](https://github.com/caolan/async/issues/1107), [#1121](https://github.com/caolan/async/issues/1121), [#1123](https://github.com/caolan/async/issues/1123), [#1129](https://github.com/caolan/async/issues/1129), [#1135](https://github.com/caolan/async/issues/1135), [#1138](https://github.com/caolan/async/issues/1138), [#1141](https://github.com/caolan/async/issues/1141), [#1153](https://github.com/caolan/async/issues/1153), [#1216](https://github.com/caolan/async/issues/1216), [#1217](https://github.com/caolan/async/issues/1217), [#1232](https://github.com/caolan/async/issues/1232), [#1233](https://github.com/caolan/async/issues/1233), [#1236](https://github.com/caolan/async/issues/1236), [#1238](https://github.com/caolan/async/issues/1238)) + +Thank you [**@aearly**](github.com/aearly) and [**@megawac**](github.com/megawac) for taking the lead on version 2 of async. + +------------------------------------------ + +# v1.5.2 +- Allow using `"constructor"` as an argument in `memoize` ([#998](https://github.com/caolan/async/issues/998)) +- Give a better error messsage when `auto` dependency checking fails ([#994](https://github.com/caolan/async/issues/994)) +- Various doc updates ([#936](https://github.com/caolan/async/issues/936), [#956](https://github.com/caolan/async/issues/956), [#979](https://github.com/caolan/async/issues/979), [#1002](https://github.com/caolan/async/issues/1002)) + +# v1.5.1 +- Fix issue with `pause` in `queue` with concurrency enabled ([#946](https://github.com/caolan/async/issues/946)) +- `while` and `until` now pass the final result to callback ([#963](https://github.com/caolan/async/issues/963)) +- `auto` will properly handle concurrency when there is no callback ([#966](https://github.com/caolan/async/issues/966)) +- `auto` will no. properly stop execution when an error occurs ([#988](https://github.com/caolan/async/issues/988), [#993](https://github.com/caolan/async/issues/993)) +- Various doc fixes ([#971](https://github.com/caolan/async/issues/971), [#980](https://github.com/caolan/async/issues/980)) + +# v1.5.0 + +- Added `transform`, analogous to [`_.transform`](http://lodash.com/docs#transform) ([#892](https://github.com/caolan/async/issues/892)) +- `map` now returns an object when an object is passed in, rather than array with non-numeric keys. `map` will begin always returning an array with numeric indexes in the next major release. ([#873](https://github.com/caolan/async/issues/873)) +- `auto` now accepts an optional `concurrency` argument to limit the number o. running tasks ([#637](https://github.com/caolan/async/issues/637)) +- Added `queue#workersList()`, to retrieve the lis. of currently running tasks. ([#891](https://github.com/caolan/async/issues/891)) +- Various code simplifications ([#896](https://github.com/caolan/async/issues/896), [#904](https://github.com/caolan/async/issues/904)) +- Various doc fixes :scroll: ([#890](https://github.com/caolan/async/issues/890), [#894](https://github.com/caolan/async/issues/894), [#903](https://github.com/caolan/async/issues/903), [#905](https://github.com/caolan/async/issues/905), [#912](https://github.com/caolan/async/issues/912)) + +# v1.4.2 + +- Ensure coverage files don't get published on npm ([#879](https://github.com/caolan/async/issues/879)) + +# v1.4.1 + +- Add in overlooked `detectLimit` method ([#866](https://github.com/caolan/async/issues/866)) +- Removed unnecessary files from npm releases ([#861](https://github.com/caolan/async/issues/861)) +- Removed usage of a reserved word to prevent :boom: in older environments ([#870](https://github.com/caolan/async/issues/870)) + +# v1.4.0 + +- `asyncify` now supports promises ([#840](https://github.com/caolan/async/issues/840)) +- Added `Limit` versions of `filter` and `reject` ([#836](https://github.com/caolan/async/issues/836)) +- Add `Limit` versions of `detect`, `some` and `every` ([#828](https://github.com/caolan/async/issues/828), [#829](https://github.com/caolan/async/issues/829)) +- `some`, `every` and `detect` now short circuit early ([#828](https://github.com/caolan/async/issues/828), [#829](https://github.com/caolan/async/issues/829)) +- Improve detection of the global object ([#804](https://github.com/caolan/async/issues/804)), enabling use in WebWorkers +- `whilst` now called with arguments from iterator ([#823](https://github.com/caolan/async/issues/823)) +- `during` now gets called with arguments from iterator ([#824](https://github.com/caolan/async/issues/824)) +- Code simplifications and optimizations aplenty ([diff](https://github.com/caolan/async/compare/v1.3.0...v1.4.0)) + + +# v1.3.0 + +New Features: +- Added `constant` +- Added `asyncify`/`wrapSync` for making sync functions work with callbacks. ([#671](https://github.com/caolan/async/issues/671), [#806](https://github.com/caolan/async/issues/806)) +- Added `during` and `doDuring`, which are like `whilst` with an async truth test. ([#800](https://github.com/caolan/async/issues/800)) +- `retry` now accepts an `interval` parameter to specify a delay between retries. ([#793](https://github.com/caolan/async/issues/793)) +- `async` should work better in Web Workers due to better `root` detection ([#804](https://github.com/caolan/async/issues/804)) +- Callbacks are now optional in `whilst`, `doWhilst`, `until`, and `doUntil` ([#642](https://github.com/caolan/async/issues/642)) +- Various internal updates ([#786](https://github.com/caolan/async/issues/786), [#801](https://github.com/caolan/async/issues/801), [#802](https://github.com/caolan/async/issues/802), [#803](https://github.com/caolan/async/issues/803)) +- Various doc fixes ([#790](https://github.com/caolan/async/issues/790), [#794](https://github.com/caolan/async/issues/794)) + +Bug Fixes: +- `cargo` now exposes the `payload` size, and `cargo.payload` can be changed on the fly after the `cargo` is created. ([#740](https://github.com/caolan/async/issues/740), [#744](https://github.com/caolan/async/issues/744), [#783](https://github.com/caolan/async/issues/783)) + + +# v1.2.1 + +Bug Fix: + +- Small regression with synchronous iterator behavior in `eachSeries` with a 1-element array. Before 1.1.0, `eachSeries`'s callback was called on the same tick, which this patch restores. In 2.0.0, it will be called on the next tick. ([#782](https://github.com/caolan/async/issues/782)) + + +# v1.2.0 + +New Features: + +- Added `timesLimit` ([#743](https://github.com/caolan/async/issues/743)) +- `concurrency` can be changed after initialization in `queue` by setting `q.concurrency`. The new concurrency will be reflected the next time a task is processed. ([#747](https://github.com/caolan/async/issues/747), [#772](https://github.com/caolan/async/issues/772)) + +Bug Fixes: + +- Fixed a regression in `each` and family with empty arrays that have additional properties. ([#775](https://github.com/caolan/async/issues/775), [#777](https://github.com/caolan/async/issues/777)) + + +# v1.1.1 + +Bug Fix: + +- Small regression with synchronous iterator behavior in `eachSeries` with a 1-element array. Before 1.1.0, `eachSeries`'s callback was called on the same tick, which this patch restores. In 2.0.0, it will be called on the next tick. ([#782](https://github.com/caolan/async/issues/782)) + + +# v1.1.0 + +New Features: + +- `cargo` now supports all of the same methods and event callbacks as `queue`. +- Added `ensureAsync` - A wrapper that ensures an async function calls its callback on a later tick. ([#769](https://github.com/caolan/async/issues/769)) +- Optimized `map`, `eachOf`, and `waterfall` families of functions +- Passing a `null` or `undefined` array to `map`, `each`, `parallel` and families will be treated as an empty array ([#667](https://github.com/caolan/async/issues/667)). +- The callback is now optional for the composed results of `compose` and `seq`. ([#618](https://github.com/caolan/async/issues/618)) +- Reduced file size by 4kb, (minified version by 1kb) +- Added code coverage through `nyc` and `coveralls` ([#768](https://github.com/caolan/async/issues/768)) + +Bug Fixes: + +- `forever` will no longer stack overflow with a synchronous iterator ([#622](https://github.com/caolan/async/issues/622)) +- `eachLimit` and other limit functions will stop iterating once an error occurs ([#754](https://github.com/caolan/async/issues/754)) +- Always pass `null` in callbacks when there is no error ([#439](https://github.com/caolan/async/issues/439)) +- Ensure proper conditions when calling `drain()` after pushing an empty data set to a queue ([#668](https://github.com/caolan/async/issues/668)) +- `each` and family will properly handle an empty array ([#578](https://github.com/caolan/async/issues/578)) +- `eachSeries` and family will finish if the underlying array is modified during execution ([#557](https://github.com/caolan/async/issues/557)) +- `queue` will throw if a non-function is passed to `q.push()` ([#593](https://github.com/caolan/async/issues/593)) +- Doc fixes ([#629](https://github.com/caolan/async/issues/629), [#766](https://github.com/caolan/async/issues/766)) + + +# v1.0.0 + +No known breaking changes, we are simply complying with semver from here on out. + +Changes: + +- Start using a changelog! +- Add `forEachOf` for iterating over Objects (or to iterate Arrays with indexes available) ([#168](https://github.com/caolan/async/issues/168) [#704](https://github.com/caolan/async/issues/704) [#321](https://github.com/caolan/async/issues/321)) +- Detect deadlocks in `auto` ([#663](https://github.com/caolan/async/issues/663)) +- Better support for require.js ([#527](https://github.com/caolan/async/issues/527)) +- Throw if queue created with concurrency `0` ([#714](https://github.com/caolan/async/issues/714)) +- Fix unneeded iteration in `queue.resume()` ([#758](https://github.com/caolan/async/issues/758)) +- Guard against timer mocking overriding `setImmediate` ([#609](https://github.com/caolan/async/issues/609) [#611](https://github.com/caolan/async/issues/611)) +- Miscellaneous doc fixes ([#542](https://github.com/caolan/async/issues/542) [#596](https://github.com/caolan/async/issues/596) [#615](https://github.com/caolan/async/issues/615) [#628](https://github.com/caolan/async/issues/628) [#631](https://github.com/caolan/async/issues/631) [#690](https://github.com/caolan/async/issues/690) [#729](https://github.com/caolan/async/issues/729)) +- Use single noop function internally ([#546](https://github.com/caolan/async/issues/546)) +- Optimize internal `_each`, `_map` and `_keys` functions. diff --git a/node_modules/async/LICENSE b/node_modules/async/LICENSE new file mode 100644 index 0000000..b18aed6 --- /dev/null +++ b/node_modules/async/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010-2018 Caolan McMahon + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/async/README.md b/node_modules/async/README.md new file mode 100644 index 0000000..55a0626 --- /dev/null +++ b/node_modules/async/README.md @@ -0,0 +1,59 @@ +![Async Logo](https://raw.githubusercontent.com/caolan/async/master/logo/async-logo_readme.jpg) + +![Github Actions CI status](https://github.com/caolan/async/actions/workflows/ci.yml/badge.svg) +[![NPM version](https://img.shields.io/npm/v/async.svg)](https://www.npmjs.com/package/async) +[![Coverage Status](https://coveralls.io/repos/caolan/async/badge.svg?branch=master)](https://coveralls.io/r/caolan/async?branch=master) +[![Join the chat at https://gitter.im/caolan/async](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/caolan/async?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +[![jsDelivr Hits](https://data.jsdelivr.com/v1/package/npm/async/badge?style=rounded)](https://www.jsdelivr.com/package/npm/async) + + + +Async is a utility module which provides straight-forward, powerful functions for working with [asynchronous JavaScript](http://caolan.github.io/async/v3/global.html). Although originally designed for use with [Node.js](https://nodejs.org/) and installable via `npm i async`, it can also be used directly in the browser. An ESM/MJS version is included in the main `async` package that should automatically be used with compatible bundlers such as Webpack and Rollup. + +A pure ESM version of Async is available as [`async-es`](https://www.npmjs.com/package/async-es). + +For Documentation, visit + +*For Async v1.5.x documentation, go [HERE](https://github.com/caolan/async/blob/v1.5.2/README.md)* + + +```javascript +// for use with Node-style callbacks... +var async = require("async"); + +var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; +var configs = {}; + +async.forEachOf(obj, (value, key, callback) => { + fs.readFile(__dirname + value, "utf8", (err, data) => { + if (err) return callback(err); + try { + configs[key] = JSON.parse(data); + } catch (e) { + return callback(e); + } + callback(); + }); +}, err => { + if (err) console.error(err.message); + // configs is now a map of JSON data + doSomethingWith(configs); +}); +``` + +```javascript +var async = require("async"); + +// ...or ES2017 async functions +async.mapLimit(urls, 5, async function(url) { + const response = await fetch(url) + return response.body +}, (err, results) => { + if (err) throw err + // results is now an array of the response bodies + console.log(results) +}) +``` diff --git a/node_modules/async/all.js b/node_modules/async/all.js new file mode 100644 index 0000000..622b301 --- /dev/null +++ b/node_modules/async/all.js @@ -0,0 +1,119 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.every(fileList, fileExists, function(err, result) { + * console.log(result); + * // true + * // result is true since every file exists + * }); + * + * async.every(withMissingFileList, fileExists, function(err, result) { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }); + * + * // Using Promises + * async.every(fileList, fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.every(withMissingFileList, fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.every(fileList, fileExists); + * console.log(result); + * // true + * // result is true since every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.every(withMissingFileList, fileExists); + * console.log(result); + * // false + * // result is false since NOT every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function every(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(every, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/allLimit.js b/node_modules/async/allLimit.js new file mode 100644 index 0000000..375e126 --- /dev/null +++ b/node_modules/async/allLimit.js @@ -0,0 +1,46 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everyLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(everyLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/allSeries.js b/node_modules/async/allSeries.js new file mode 100644 index 0000000..9a6bf7d --- /dev/null +++ b/node_modules/async/allSeries.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everySeries(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(everySeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/any.js b/node_modules/async/any.js new file mode 100644 index 0000000..a5bd328 --- /dev/null +++ b/node_modules/async/any.js @@ -0,0 +1,122 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + *); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // false + * // result is false since none of the files exists + * } + *); + * + * // Using Promises + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since some file in the list exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since none of the files exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists); + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists); + * console.log(result); + * // false + * // result is false since none of the files exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function some(coll, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(some, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/anyLimit.js b/node_modules/async/anyLimit.js new file mode 100644 index 0000000..3a8096f --- /dev/null +++ b/node_modules/async/anyLimit.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(someLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/anySeries.js b/node_modules/async/anySeries.js new file mode 100644 index 0000000..51aad19 --- /dev/null +++ b/node_modules/async/anySeries.js @@ -0,0 +1,46 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someSeries(coll, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(someSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/apply.js b/node_modules/async/apply.js new file mode 100644 index 0000000..d40784f --- /dev/null +++ b/node_modules/async/apply.js @@ -0,0 +1,11 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (fn, ...args) { + return (...callArgs) => fn(...args, ...callArgs); +}; + +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/applyEach.js b/node_modules/async/applyEach.js new file mode 100644 index 0000000..841842c --- /dev/null +++ b/node_modules/async/applyEach.js @@ -0,0 +1,57 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _applyEach = require('./internal/applyEach.js'); + +var _applyEach2 = _interopRequireDefault(_applyEach); + +var _map = require('./map.js'); + +var _map2 = _interopRequireDefault(_map); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Applies the provided arguments to each function in the array, calling + * `callback` after all functions have completed. If you only provide the first + * argument, `fns`, then it will return a function which lets you pass in the + * arguments as if it were a single function call. If more arguments are + * provided, `callback` is required while `args` is still optional. The results + * for each of the applied async functions are passed to the final callback + * as an array. + * + * @name applyEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s + * to all call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - Returns a function that takes no args other than + * an optional callback, that is the result of applying the `args` to each + * of the functions. + * @example + * + * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket') + * + * appliedFn((err, results) => { + * // results[0] is the results for `enableSearch` + * // results[1] is the results for `updateSchema` + * }); + * + * // partial application example: + * async.each( + * buckets, + * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(), + * callback + * ); + */ +exports.default = (0, _applyEach2.default)(_map2.default); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/applyEachSeries.js b/node_modules/async/applyEachSeries.js new file mode 100644 index 0000000..f5267f6 --- /dev/null +++ b/node_modules/async/applyEachSeries.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _applyEach = require('./internal/applyEach.js'); + +var _applyEach2 = _interopRequireDefault(_applyEach); + +var _mapSeries = require('./mapSeries.js'); + +var _mapSeries2 = _interopRequireDefault(_mapSeries); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. + * + * @name applyEachSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.applyEach]{@link module:ControlFlow.applyEach} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all + * call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - A function, that when called, is the result of + * appling the `args` to the list of functions. It takes no args, other than + * a callback. + */ +exports.default = (0, _applyEach2.default)(_mapSeries2.default); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/asyncify.js b/node_modules/async/asyncify.js new file mode 100644 index 0000000..ddc3f02 --- /dev/null +++ b/node_modules/async/asyncify.js @@ -0,0 +1,118 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = asyncify; + +var _initialParams = require('./internal/initialParams.js'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _setImmediate = require('./internal/setImmediate.js'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ +function asyncify(func) { + if ((0, _wrapAsync.isAsync)(func)) { + return function (...args /*, callback*/) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback); + }; + } + + return (0, _initialParams2.default)(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (result && typeof result.then === 'function') { + return handlePromise(result, callback); + } else { + callback(null, result); + } + }); +} + +function handlePromise(promise, callback) { + return promise.then(value => { + invokeCallback(callback, null, value); + }, err => { + invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err)); + }); +} + +function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + (0, _setImmediate2.default)(e => { + throw e; + }, err); + } +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/auto.js b/node_modules/async/auto.js new file mode 100644 index 0000000..163c4f2 --- /dev/null +++ b/node_modules/async/auto.js @@ -0,0 +1,333 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = auto; + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _promiseCallback = require('./internal/promiseCallback.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on + * their requirements. Each function can optionally depend on other functions + * being completed first, and each function is run as soon as its requirements + * are satisfied. + * + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence + * will stop. Further tasks will not execute (so any other functions depending + * on it will not run), and the main `callback` is immediately called with the + * error. + * + * {@link AsyncFunction}s also receive an object containing the results of functions which + * have completed so far as the first argument, if they have dependencies. If a + * task function has no dependencies, it will only be passed a callback. + * + * @name auto + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Object} tasks - An object. Each of its properties is either a + * function or an array of requirements, with the {@link AsyncFunction} itself the last item + * in the array. The object's key of a property serves as the name of the task + * defined by that property, i.e. can be used when specifying requirements for + * other tasks. The function receives one or two arguments: + * * a `results` object, containing the results of the previously executed + * functions, only passed if the task has any dependencies, + * * a `callback(err, result)` function, which must be called when finished, + * passing an `error` (which can be `null`) and the result of the function's + * execution. + * @param {number} [concurrency=Infinity] - An optional `integer` for + * determining the maximum number of tasks that can be run in parallel. By + * default, as many as possible. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback. Results are always returned; however, if an + * error occurs, no further `tasks` will be performed, and the results object + * will only contain partial results. Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * @example + * + * //Using Callbacks + * async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }, function(err, results) { + * if (err) { + * console.log('err = ', err); + * } + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }); + * + * //Using Promises + * async.auto({ + * get_data: function(callback) { + * console.log('in get_data'); + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * console.log('in make_folder'); + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }).then(results => { + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }).catch(err => { + * console.log('err = ', err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }); + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function auto(tasks, concurrency, callback) { + if (typeof concurrency !== 'number') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = (0, _once2.default)(callback || (0, _promiseCallback.promiseCallback)()); + var numTasks = Object.keys(tasks).length; + if (!numTasks) { + return callback(null); + } + if (!concurrency) { + concurrency = numTasks; + } + + var results = {}; + var runningTasks = 0; + var canceled = false; + var hasError = false; + + var listeners = Object.create(null); + + var readyTasks = []; + + // for cycle detection: + var readyToCheck = []; // tasks that have been identified as reachable + // without the possibility of returning to an ancestor task + var uncheckedDependencies = {}; + + Object.keys(tasks).forEach(key => { + var task = tasks[key]; + if (!Array.isArray(task)) { + // no dependencies + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } + + var dependencies = task.slice(0, task.length - 1); + var remainingDependencies = dependencies.length; + if (remainingDependencies === 0) { + enqueueTask(key, task); + readyToCheck.push(key); + return; + } + uncheckedDependencies[key] = remainingDependencies; + + dependencies.forEach(dependencyName => { + if (!tasks[dependencyName]) { + throw new Error('async.auto task `' + key + '` has a non-existent dependency `' + dependencyName + '` in ' + dependencies.join(', ')); + } + addListener(dependencyName, () => { + remainingDependencies--; + if (remainingDependencies === 0) { + enqueueTask(key, task); + } + }); + }); + }); + + checkForDeadlocks(); + processQueue(); + + function enqueueTask(key, task) { + readyTasks.push(() => runTask(key, task)); + } + + function processQueue() { + if (canceled) return; + if (readyTasks.length === 0 && runningTasks === 0) { + return callback(null, results); + } + while (readyTasks.length && runningTasks < concurrency) { + var run = readyTasks.shift(); + run(); + } + } + + function addListener(taskName, fn) { + var taskListeners = listeners[taskName]; + if (!taskListeners) { + taskListeners = listeners[taskName] = []; + } + + taskListeners.push(fn); + } + + function taskComplete(taskName) { + var taskListeners = listeners[taskName] || []; + taskListeners.forEach(fn => fn()); + processQueue(); + } + + function runTask(key, task) { + if (hasError) return; + + var taskCallback = (0, _onlyOnce2.default)((err, ...result) => { + runningTasks--; + if (err === false) { + canceled = true; + return; + } + if (result.length < 2) { + [result] = result; + } + if (err) { + var safeResults = {}; + Object.keys(results).forEach(rkey => { + safeResults[rkey] = results[rkey]; + }); + safeResults[key] = result; + hasError = true; + listeners = Object.create(null); + if (canceled) return; + callback(err, safeResults); + } else { + results[key] = result; + taskComplete(key); + } + }); + + runningTasks++; + var taskFn = (0, _wrapAsync2.default)(task[task.length - 1]); + if (task.length > 1) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } + } + + function checkForDeadlocks() { + // Kahn's algorithm + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html + var currentTask; + var counter = 0; + while (readyToCheck.length) { + currentTask = readyToCheck.pop(); + counter++; + getDependents(currentTask).forEach(dependent => { + if (--uncheckedDependencies[dependent] === 0) { + readyToCheck.push(dependent); + } + }); + } + + if (counter !== numTasks) { + throw new Error('async.auto cannot execute tasks due to a recursive dependency'); + } + } + + function getDependents(taskName) { + var result = []; + Object.keys(tasks).forEach(key => { + const task = tasks[key]; + if (Array.isArray(task) && task.indexOf(taskName) >= 0) { + result.push(key); + } + }); + return result; + } + + return callback[_promiseCallback.PROMISE_SYMBOL]; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/autoInject.js b/node_modules/async/autoInject.js new file mode 100644 index 0000000..5db2653 --- /dev/null +++ b/node_modules/async/autoInject.js @@ -0,0 +1,182 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = autoInject; + +var _auto = require('./auto.js'); + +var _auto2 = _interopRequireDefault(_auto); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var FN_ARGS = /^(?:async\s)?(?:function)?\s*(?:\w+\s*)?\(([^)]+)\)(?:\s*{)/; +var ARROW_FN_ARGS = /^(?:async\s)?\s*(?:\(\s*)?((?:[^)=\s]\s*)*)(?:\)\s*)?=>/; +var FN_ARG_SPLIT = /,/; +var FN_ARG = /(=.+)?(\s*)$/; + +function stripComments(string) { + let stripped = ''; + let index = 0; + let endBlockComment = string.indexOf('*/'); + while (index < string.length) { + if (string[index] === '/' && string[index + 1] === '/') { + // inline comment + let endIndex = string.indexOf('\n', index); + index = endIndex === -1 ? string.length : endIndex; + } else if (endBlockComment !== -1 && string[index] === '/' && string[index + 1] === '*') { + // block comment + let endIndex = string.indexOf('*/', index); + if (endIndex !== -1) { + index = endIndex + 2; + endBlockComment = string.indexOf('*/', index); + } else { + stripped += string[index]; + index++; + } + } else { + stripped += string[index]; + index++; + } + } + return stripped; +} + +function parseParams(func) { + const src = stripComments(func.toString()); + let match = src.match(FN_ARGS); + if (!match) { + match = src.match(ARROW_FN_ARGS); + } + if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src); + let [, args] = match; + return args.replace(/\s/g, '').split(FN_ARG_SPLIT).map(arg => arg.replace(FN_ARG, '').trim()); +} + +/** + * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent + * tasks are specified as parameters to the function, after the usual callback + * parameter, with the parameter names matching the names of the tasks it + * depends on. This can provide even more readable task graphs which can be + * easier to maintain. + * + * If a final callback is specified, the task results are similarly injected, + * specified as named parameters after the initial error parameter. + * + * The autoInject function is purely syntactic sugar and its semantics are + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. + * + * @name autoInject + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.auto]{@link module:ControlFlow.auto} + * @category Control Flow + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of + * the form 'func([dependencies...], callback). The object's key of a property + * serves as the name of the task defined by that property, i.e. can be used + * when specifying requirements for other tasks. + * * The `callback` parameter is a `callback(err, result)` which must be called + * when finished, passing an `error` (which can be `null`) and the result of + * the function's execution. The remaining parameters name other tasks on + * which the task is dependent, and the results from those tasks are the + * arguments of those parameters. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback, and a `results` object with any completed + * task results, similar to `auto`. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // The example from `auto` can be rewritten as follows: + * async.autoInject({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: function(get_data, make_folder, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }, + * email_link: function(write_file, callback) { + * // once the file is written let's email a link to it... + * // write_file contains the filename returned by write_file. + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * } + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + * + * // If you are using a JS minifier that mangles parameter names, `autoInject` + * // will not work with plain functions, since the parameter names will be + * // collapsed to a single letter identifier. To work around this, you can + * // explicitly specify the names of the parameters your task function needs + * // in an array, similar to Angular.js dependency injection. + * + * // This still has an advantage over plain `auto`, since the results a task + * // depends on are still spread into arguments. + * async.autoInject({ + * //... + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(write_file, callback) { + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * }] + * //... + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + */ +function autoInject(tasks, callback) { + var newTasks = {}; + + Object.keys(tasks).forEach(key => { + var taskFn = tasks[key]; + var params; + var fnIsAsync = (0, _wrapAsync.isAsync)(taskFn); + var hasNoDeps = !fnIsAsync && taskFn.length === 1 || fnIsAsync && taskFn.length === 0; + + if (Array.isArray(taskFn)) { + params = [...taskFn]; + taskFn = params.pop(); + + newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); + } else if (hasNoDeps) { + // no dependencies, use the function as-is + newTasks[key] = taskFn; + } else { + params = parseParams(taskFn); + if (taskFn.length === 0 && !fnIsAsync && params.length === 0) { + throw new Error("autoInject task functions require explicit parameters."); + } + + // remove callback param + if (!fnIsAsync) params.pop(); + + newTasks[key] = params.concat(newTask); + } + + function newTask(results, taskCb) { + var newArgs = params.map(name => results[name]); + newArgs.push(taskCb); + (0, _wrapAsync2.default)(taskFn)(...newArgs); + } + }); + + return (0, _auto2.default)(newTasks, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/bower.json b/node_modules/async/bower.json new file mode 100644 index 0000000..390c650 --- /dev/null +++ b/node_modules/async/bower.json @@ -0,0 +1,17 @@ +{ + "name": "async", + "main": "dist/async.js", + "ignore": [ + "bower_components", + "lib", + "test", + "node_modules", + "perf", + "support", + "**/.*", + "*.config.js", + "*.json", + "index.js", + "Makefile" + ] +} diff --git a/node_modules/async/cargo.js b/node_modules/async/cargo.js new file mode 100644 index 0000000..d4abd21 --- /dev/null +++ b/node_modules/async/cargo.js @@ -0,0 +1,63 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = cargo; + +var _queue = require('./internal/queue.js'); + +var _queue2 = _interopRequireDefault(_queue); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Creates a `cargo` object with the specified payload. Tasks added to the + * cargo will be processed altogether (up to the `payload` limit). If the + * `worker` is in progress, the task is queued until it becomes available. Once + * the `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, cargo passes an array of tasks to a single worker, repeating + * when the worker is finished. + * + * @name cargo + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargo and inner queue. + * @example + * + * // create a cargo object with payload 2 + * var cargo = async.cargo(function(tasks, callback) { + * for (var i=0; i { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir) + * .then(results => { + * console.log(results); + * }).catch(err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.concat(directoryList, fs.readdir); + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.concat(withMissingDirectoryList, fs.readdir); + * console.log(results); + * } catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } + * } + * + */ +function concat(coll, iteratee, callback) { + return (0, _concatLimit2.default)(coll, Infinity, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(concat, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/concatLimit.js b/node_modules/async/concatLimit.js new file mode 100644 index 0000000..a27cc7d --- /dev/null +++ b/node_modules/async/concatLimit.js @@ -0,0 +1,60 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _mapLimit = require('./mapLimit.js'); + +var _mapLimit2 = _interopRequireDefault(_mapLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. + * + * @name concatLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapLimit + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatLimit(coll, limit, iteratee, callback) { + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _mapLimit2.default)(coll, limit, (val, iterCb) => { + _iteratee(val, (err, ...args) => { + if (err) return iterCb(err); + return iterCb(err, args); + }); + }, (err, mapResults) => { + var result = []; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + result = result.concat(...mapResults[i]); + } + } + + return callback(err, result); + }); +} +exports.default = (0, _awaitify2.default)(concatLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/concatSeries.js b/node_modules/async/concatSeries.js new file mode 100644 index 0000000..332de3f --- /dev/null +++ b/node_modules/async/concatSeries.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _concatLimit = require('./concatLimit.js'); + +var _concatLimit2 = _interopRequireDefault(_concatLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * + * @name concatSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapSeries + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. + * The iteratee should complete with an array an array of results. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatSeries(coll, iteratee, callback) { + return (0, _concatLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(concatSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/constant.js b/node_modules/async/constant.js new file mode 100644 index 0000000..ea406f6 --- /dev/null +++ b/node_modules/async/constant.js @@ -0,0 +1,14 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (...args) { + return function (...ignoredArgs /*, callback*/) { + var callback = ignoredArgs.pop(); + return callback(null, ...args); + }; +}; + +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/detect.js b/node_modules/async/detect.js new file mode 100644 index 0000000..d5896ef --- /dev/null +++ b/node_modules/async/detect.js @@ -0,0 +1,96 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. + + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * } + *); + * + * // Using Promises + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists) + * .then(result => { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); + * console.log(result); + * // dir1/file1.txt + * // result now equals the file in the list that exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function detect(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(detect, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/detectLimit.js b/node_modules/async/detectLimit.js new file mode 100644 index 0000000..c59843b --- /dev/null +++ b/node_modules/async/detectLimit.js @@ -0,0 +1,48 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ +function detectLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(detectLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/detectSeries.js b/node_modules/async/detectSeries.js new file mode 100644 index 0000000..b486899 --- /dev/null +++ b/node_modules/async/detectSeries.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ +function detectSeries(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(1), coll, iteratee, callback); +} + +exports.default = (0, _awaitify2.default)(detectSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/dir.js b/node_modules/async/dir.js new file mode 100644 index 0000000..8e9fafd --- /dev/null +++ b/node_modules/async/dir.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _consoleFunc = require('./internal/consoleFunc.js'); + +var _consoleFunc2 = _interopRequireDefault(_consoleFunc); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Logs the result of an [`async` function]{@link AsyncFunction} to the + * `console` using `console.dir` to display the properties of the resulting object. + * Only works in Node.js or in browsers that support `console.dir` and + * `console.error` (such as FF and Chrome). + * If multiple arguments are returned from the async function, + * `console.dir` is called on each argument in order. + * + * @name dir + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, {hello: name}); + * }, 1000); + * }; + * + * // in the node repl + * node> async.dir(hello, 'world'); + * {hello: 'world'} + */ +exports.default = (0, _consoleFunc2.default)('dir'); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/dist/async.js b/node_modules/async/dist/async.js new file mode 100644 index 0000000..d7b7918 --- /dev/null +++ b/node_modules/async/dist/async.js @@ -0,0 +1,6061 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.async = {})); +})(this, (function (exports) { 'use strict'; + + /** + * Creates a continuation function with some arguments already applied. + * + * Useful as a shorthand when combined with other control flow functions. Any + * arguments passed to the returned function are added to the arguments + * originally passed to apply. + * + * @name apply + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {Function} fn - The function you want to eventually apply all + * arguments to. Invokes with (arguments...). + * @param {...*} arguments... - Any number of arguments to automatically apply + * when the continuation is called. + * @returns {Function} the partially-applied function + * @example + * + * // using apply + * async.parallel([ + * async.apply(fs.writeFile, 'testfile1', 'test1'), + * async.apply(fs.writeFile, 'testfile2', 'test2') + * ]); + * + * + * // the same process without using apply + * async.parallel([ + * function(callback) { + * fs.writeFile('testfile1', 'test1', callback); + * }, + * function(callback) { + * fs.writeFile('testfile2', 'test2', callback); + * } + * ]); + * + * // It's possible to pass any number of additional arguments when calling the + * // continuation: + * + * node> var fn = async.apply(sys.puts, 'one'); + * node> fn('two', 'three'); + * one + * two + * three + */ + function apply(fn, ...args) { + return (...callArgs) => fn(...args,...callArgs); + } + + function initialParams (fn) { + return function (...args/*, callback*/) { + var callback = args.pop(); + return fn.call(this, args, callback); + }; + } + + /* istanbul ignore file */ + + var hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask; + var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; + var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; + + function fallback(fn) { + setTimeout(fn, 0); + } + + function wrap(defer) { + return (fn, ...args) => defer(() => fn(...args)); + } + + var _defer$1; + + if (hasQueueMicrotask) { + _defer$1 = queueMicrotask; + } else if (hasSetImmediate) { + _defer$1 = setImmediate; + } else if (hasNextTick) { + _defer$1 = process.nextTick; + } else { + _defer$1 = fallback; + } + + var setImmediate$1 = wrap(_defer$1); + + /** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ + function asyncify(func) { + if (isAsync(func)) { + return function (...args/*, callback*/) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback) + } + } + + return initialParams(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (result && typeof result.then === 'function') { + return handlePromise(result, callback) + } else { + callback(null, result); + } + }); + } + + function handlePromise(promise, callback) { + return promise.then(value => { + invokeCallback(callback, null, value); + }, err => { + invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err)); + }); + } + + function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + setImmediate$1(e => { throw e }, err); + } + } + + function isAsync(fn) { + return fn[Symbol.toStringTag] === 'AsyncFunction'; + } + + function isAsyncGenerator(fn) { + return fn[Symbol.toStringTag] === 'AsyncGenerator'; + } + + function isAsyncIterable(obj) { + return typeof obj[Symbol.asyncIterator] === 'function'; + } + + function wrapAsync(asyncFn) { + if (typeof asyncFn !== 'function') throw new Error('expected a function') + return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; + } + + // conditionally promisify a function. + // only return a promise if a callback is omitted + function awaitify (asyncFn, arity) { + if (!arity) arity = asyncFn.length; + if (!arity) throw new Error('arity is undefined') + function awaitable (...args) { + if (typeof args[arity - 1] === 'function') { + return asyncFn.apply(this, args) + } + + return new Promise((resolve, reject) => { + args[arity - 1] = (err, ...cbArgs) => { + if (err) return reject(err) + resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); + }; + asyncFn.apply(this, args); + }) + } + + return awaitable + } + + function applyEach$1 (eachfn) { + return function applyEach(fns, ...callArgs) { + const go = awaitify(function (callback) { + var that = this; + return eachfn(fns, (fn, cb) => { + wrapAsync(fn).apply(that, callArgs.concat(cb)); + }, callback); + }); + return go; + }; + } + + function _asyncMap(eachfn, arr, iteratee, callback) { + arr = arr || []; + var results = []; + var counter = 0; + var _iteratee = wrapAsync(iteratee); + + return eachfn(arr, (value, _, iterCb) => { + var index = counter++; + _iteratee(value, (err, v) => { + results[index] = v; + iterCb(err); + }); + }, err => { + callback(err, results); + }); + } + + function isArrayLike(value) { + return value && + typeof value.length === 'number' && + value.length >= 0 && + value.length % 1 === 0; + } + + // A temporary value used to identify if the loop should be broken. + // See #1064, #1293 + const breakLoop = {}; + + function once(fn) { + function wrapper (...args) { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, args); + } + Object.assign(wrapper, fn); + return wrapper + } + + function getIterator (coll) { + return coll[Symbol.iterator] && coll[Symbol.iterator](); + } + + function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? {value: coll[i], key: i} : null; + } + } + + function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) + return null; + i++; + return {value: item.value, key: i}; + } + } + + function createObjectIterator(obj) { + var okeys = obj ? Object.keys(obj) : []; + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + if (key === '__proto__') { + return next(); + } + return i < len ? {value: obj[key], key} : null; + }; + } + + function createIterator(coll) { + if (isArrayLike(coll)) { + return createArrayIterator(coll); + } + + var iterator = getIterator(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); + } + + function onlyOnce(fn) { + return function (...args) { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; + callFn.apply(this, args); + }; + } + + // for async generators + function asyncEachOfLimit(generator, limit, iteratee, callback) { + let done = false; + let canceled = false; + let awaiting = false; + let running = 0; + let idx = 0; + + function replenish() { + //console.log('replenish') + if (running >= limit || awaiting || done) return + //console.log('replenish awaiting') + awaiting = true; + generator.next().then(({value, done: iterDone}) => { + //console.log('got value', value) + if (canceled || done) return + awaiting = false; + if (iterDone) { + done = true; + if (running <= 0) { + //console.log('done nextCb') + callback(null); + } + return; + } + running++; + iteratee(value, idx, iterateeCallback); + idx++; + replenish(); + }).catch(handleError); + } + + function iterateeCallback(err, result) { + //console.log('iterateeCallback') + running -= 1; + if (canceled) return + if (err) return handleError(err) + + if (err === false) { + done = true; + canceled = true; + return + } + + if (result === breakLoop || (done && running <= 0)) { + done = true; + //console.log('done iterCb') + return callback(null); + } + replenish(); + } + + function handleError(err) { + if (canceled) return + awaiting = false; + done = true; + callback(err); + } + + replenish(); + } + + var eachOfLimit$2 = (limit) => { + return (obj, iteratee, callback) => { + callback = once(callback); + if (limit <= 0) { + throw new RangeError('concurrency limit cannot be less than 1') + } + if (!obj) { + return callback(null); + } + if (isAsyncGenerator(obj)) { + return asyncEachOfLimit(obj, limit, iteratee, callback) + } + if (isAsyncIterable(obj)) { + return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback) + } + var nextElem = createIterator(obj); + var done = false; + var canceled = false; + var running = 0; + var looping = false; + + function iterateeCallback(err, value) { + if (canceled) return + running -= 1; + if (err) { + done = true; + callback(err); + } + else if (err === false) { + done = true; + canceled = true; + } + else if (value === breakLoop || (done && running <= 0)) { + done = true; + return callback(null); + } + else if (!looping) { + replenish(); + } + } + + function replenish () { + looping = true; + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); + } + looping = false; + } + + replenish(); + }; + }; + + /** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachOfLimit(coll, limit, iteratee, callback) { + return eachOfLimit$2(limit)(coll, wrapAsync(iteratee), callback); + } + + var eachOfLimit$1 = awaitify(eachOfLimit, 4); + + // eachOf implementation optimized for array-likes + function eachOfArrayLike(coll, iteratee, callback) { + callback = once(callback); + var index = 0, + completed = 0, + {length} = coll, + canceled = false; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } + if (canceled === true) return + if (err) { + callback(err); + } else if ((++completed === length) || value === breakLoop) { + callback(null); + } + } + + for (; index < length; index++) { + iteratee(coll[index], index, onlyOnce(iteratorCallback)); + } + } + + // a generic version of eachOf which can handle array, object, and iterator cases. + function eachOfGeneric (coll, iteratee, callback) { + return eachOfLimit$1(coll, Infinity, iteratee, callback); + } + + /** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dev.json is a file containing a valid json object config for dev environment + * // dev.json is a file containing a valid json object config for test environment + * // prod.json is a file containing a valid json object config for prod environment + * // invalid.json is a file with a malformed json object + * + * let configs = {}; //global variable + * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'}; + * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'}; + * + * // asynchronous function that reads a json file and parses the contents as json object + * function parseFile(file, key, callback) { + * fs.readFile(file, "utf8", function(err, data) { + * if (err) return calback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * } + * + * // Using callbacks + * async.forEachOf(validConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * } else { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * // JSON parse error exception + * } else { + * console.log(configs); + * } + * }); + * + * // Using Promises + * async.forEachOf(validConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * }).catch( err => { + * console.error(err); + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * }).catch( err => { + * console.error(err); + * // JSON parse error exception + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.forEachOf(validConfigFileMap, parseFile); + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * catch (err) { + * console.log(err); + * } + * } + * + * //Error handing + * async () => { + * try { + * let result = await async.forEachOf(invalidConfigFileMap, parseFile); + * console.log(configs); + * } + * catch (err) { + * console.log(err); + * // JSON parse error exception + * } + * } + * + */ + function eachOf(coll, iteratee, callback) { + var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, wrapAsync(iteratee), callback); + } + + var eachOf$1 = awaitify(eachOf, 3); + + /** + * Produces a new collection of values by mapping each value in `coll` through + * the `iteratee` function. The `iteratee` is called with an item from `coll` + * and a callback for when it has finished processing. Each of these callbacks + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.map(fileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.map(fileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.map(fileList, getFileSizeInBytes); + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.map(withMissingFileList, getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ + function map (coll, iteratee, callback) { + return _asyncMap(eachOf$1, coll, iteratee, callback) + } + var map$1 = awaitify(map, 3); + + /** + * Applies the provided arguments to each function in the array, calling + * `callback` after all functions have completed. If you only provide the first + * argument, `fns`, then it will return a function which lets you pass in the + * arguments as if it were a single function call. If more arguments are + * provided, `callback` is required while `args` is still optional. The results + * for each of the applied async functions are passed to the final callback + * as an array. + * + * @name applyEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s + * to all call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - Returns a function that takes no args other than + * an optional callback, that is the result of applying the `args` to each + * of the functions. + * @example + * + * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket') + * + * appliedFn((err, results) => { + * // results[0] is the results for `enableSearch` + * // results[1] is the results for `updateSchema` + * }); + * + * // partial application example: + * async.each( + * buckets, + * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(), + * callback + * ); + */ + var applyEach = applyEach$1(map$1); + + /** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachOfSeries(coll, iteratee, callback) { + return eachOfLimit$1(coll, 1, iteratee, callback) + } + var eachOfSeries$1 = awaitify(eachOfSeries, 3); + + /** + * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. + * + * @name mapSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function mapSeries (coll, iteratee, callback) { + return _asyncMap(eachOfSeries$1, coll, iteratee, callback) + } + var mapSeries$1 = awaitify(mapSeries, 3); + + /** + * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. + * + * @name applyEachSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.applyEach]{@link module:ControlFlow.applyEach} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all + * call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - A function, that when called, is the result of + * appling the `args` to the list of functions. It takes no args, other than + * a callback. + */ + var applyEachSeries = applyEach$1(mapSeries$1); + + const PROMISE_SYMBOL = Symbol('promiseCallback'); + + function promiseCallback () { + let resolve, reject; + function callback (err, ...args) { + if (err) return reject(err) + resolve(args.length > 1 ? args : args[0]); + } + + callback[PROMISE_SYMBOL] = new Promise((res, rej) => { + resolve = res, + reject = rej; + }); + + return callback + } + + /** + * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on + * their requirements. Each function can optionally depend on other functions + * being completed first, and each function is run as soon as its requirements + * are satisfied. + * + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence + * will stop. Further tasks will not execute (so any other functions depending + * on it will not run), and the main `callback` is immediately called with the + * error. + * + * {@link AsyncFunction}s also receive an object containing the results of functions which + * have completed so far as the first argument, if they have dependencies. If a + * task function has no dependencies, it will only be passed a callback. + * + * @name auto + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Object} tasks - An object. Each of its properties is either a + * function or an array of requirements, with the {@link AsyncFunction} itself the last item + * in the array. The object's key of a property serves as the name of the task + * defined by that property, i.e. can be used when specifying requirements for + * other tasks. The function receives one or two arguments: + * * a `results` object, containing the results of the previously executed + * functions, only passed if the task has any dependencies, + * * a `callback(err, result)` function, which must be called when finished, + * passing an `error` (which can be `null`) and the result of the function's + * execution. + * @param {number} [concurrency=Infinity] - An optional `integer` for + * determining the maximum number of tasks that can be run in parallel. By + * default, as many as possible. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback. Results are always returned; however, if an + * error occurs, no further `tasks` will be performed, and the results object + * will only contain partial results. Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * @example + * + * //Using Callbacks + * async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }, function(err, results) { + * if (err) { + * console.log('err = ', err); + * } + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }); + * + * //Using Promises + * async.auto({ + * get_data: function(callback) { + * console.log('in get_data'); + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * console.log('in make_folder'); + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }).then(results => { + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }).catch(err => { + * console.log('err = ', err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }); + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function auto(tasks, concurrency, callback) { + if (typeof concurrency !== 'number') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = once(callback || promiseCallback()); + var numTasks = Object.keys(tasks).length; + if (!numTasks) { + return callback(null); + } + if (!concurrency) { + concurrency = numTasks; + } + + var results = {}; + var runningTasks = 0; + var canceled = false; + var hasError = false; + + var listeners = Object.create(null); + + var readyTasks = []; + + // for cycle detection: + var readyToCheck = []; // tasks that have been identified as reachable + // without the possibility of returning to an ancestor task + var uncheckedDependencies = {}; + + Object.keys(tasks).forEach(key => { + var task = tasks[key]; + if (!Array.isArray(task)) { + // no dependencies + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } + + var dependencies = task.slice(0, task.length - 1); + var remainingDependencies = dependencies.length; + if (remainingDependencies === 0) { + enqueueTask(key, task); + readyToCheck.push(key); + return; + } + uncheckedDependencies[key] = remainingDependencies; + + dependencies.forEach(dependencyName => { + if (!tasks[dependencyName]) { + throw new Error('async.auto task `' + key + + '` has a non-existent dependency `' + + dependencyName + '` in ' + + dependencies.join(', ')); + } + addListener(dependencyName, () => { + remainingDependencies--; + if (remainingDependencies === 0) { + enqueueTask(key, task); + } + }); + }); + }); + + checkForDeadlocks(); + processQueue(); + + function enqueueTask(key, task) { + readyTasks.push(() => runTask(key, task)); + } + + function processQueue() { + if (canceled) return + if (readyTasks.length === 0 && runningTasks === 0) { + return callback(null, results); + } + while(readyTasks.length && runningTasks < concurrency) { + var run = readyTasks.shift(); + run(); + } + + } + + function addListener(taskName, fn) { + var taskListeners = listeners[taskName]; + if (!taskListeners) { + taskListeners = listeners[taskName] = []; + } + + taskListeners.push(fn); + } + + function taskComplete(taskName) { + var taskListeners = listeners[taskName] || []; + taskListeners.forEach(fn => fn()); + processQueue(); + } + + + function runTask(key, task) { + if (hasError) return; + + var taskCallback = onlyOnce((err, ...result) => { + runningTasks--; + if (err === false) { + canceled = true; + return + } + if (result.length < 2) { + [result] = result; + } + if (err) { + var safeResults = {}; + Object.keys(results).forEach(rkey => { + safeResults[rkey] = results[rkey]; + }); + safeResults[key] = result; + hasError = true; + listeners = Object.create(null); + if (canceled) return + callback(err, safeResults); + } else { + results[key] = result; + taskComplete(key); + } + }); + + runningTasks++; + var taskFn = wrapAsync(task[task.length - 1]); + if (task.length > 1) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } + } + + function checkForDeadlocks() { + // Kahn's algorithm + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html + var currentTask; + var counter = 0; + while (readyToCheck.length) { + currentTask = readyToCheck.pop(); + counter++; + getDependents(currentTask).forEach(dependent => { + if (--uncheckedDependencies[dependent] === 0) { + readyToCheck.push(dependent); + } + }); + } + + if (counter !== numTasks) { + throw new Error( + 'async.auto cannot execute tasks due to a recursive dependency' + ); + } + } + + function getDependents(taskName) { + var result = []; + Object.keys(tasks).forEach(key => { + const task = tasks[key]; + if (Array.isArray(task) && task.indexOf(taskName) >= 0) { + result.push(key); + } + }); + return result; + } + + return callback[PROMISE_SYMBOL] + } + + var FN_ARGS = /^(?:async\s)?(?:function)?\s*(?:\w+\s*)?\(([^)]+)\)(?:\s*{)/; + var ARROW_FN_ARGS = /^(?:async\s)?\s*(?:\(\s*)?((?:[^)=\s]\s*)*)(?:\)\s*)?=>/; + var FN_ARG_SPLIT = /,/; + var FN_ARG = /(=.+)?(\s*)$/; + + function stripComments(string) { + let stripped = ''; + let index = 0; + let endBlockComment = string.indexOf('*/'); + while (index < string.length) { + if (string[index] === '/' && string[index+1] === '/') { + // inline comment + let endIndex = string.indexOf('\n', index); + index = (endIndex === -1) ? string.length : endIndex; + } else if ((endBlockComment !== -1) && (string[index] === '/') && (string[index+1] === '*')) { + // block comment + let endIndex = string.indexOf('*/', index); + if (endIndex !== -1) { + index = endIndex + 2; + endBlockComment = string.indexOf('*/', index); + } else { + stripped += string[index]; + index++; + } + } else { + stripped += string[index]; + index++; + } + } + return stripped; + } + + function parseParams(func) { + const src = stripComments(func.toString()); + let match = src.match(FN_ARGS); + if (!match) { + match = src.match(ARROW_FN_ARGS); + } + if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src) + let [, args] = match; + return args + .replace(/\s/g, '') + .split(FN_ARG_SPLIT) + .map((arg) => arg.replace(FN_ARG, '').trim()); + } + + /** + * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent + * tasks are specified as parameters to the function, after the usual callback + * parameter, with the parameter names matching the names of the tasks it + * depends on. This can provide even more readable task graphs which can be + * easier to maintain. + * + * If a final callback is specified, the task results are similarly injected, + * specified as named parameters after the initial error parameter. + * + * The autoInject function is purely syntactic sugar and its semantics are + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. + * + * @name autoInject + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.auto]{@link module:ControlFlow.auto} + * @category Control Flow + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of + * the form 'func([dependencies...], callback). The object's key of a property + * serves as the name of the task defined by that property, i.e. can be used + * when specifying requirements for other tasks. + * * The `callback` parameter is a `callback(err, result)` which must be called + * when finished, passing an `error` (which can be `null`) and the result of + * the function's execution. The remaining parameters name other tasks on + * which the task is dependent, and the results from those tasks are the + * arguments of those parameters. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback, and a `results` object with any completed + * task results, similar to `auto`. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // The example from `auto` can be rewritten as follows: + * async.autoInject({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: function(get_data, make_folder, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }, + * email_link: function(write_file, callback) { + * // once the file is written let's email a link to it... + * // write_file contains the filename returned by write_file. + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * } + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + * + * // If you are using a JS minifier that mangles parameter names, `autoInject` + * // will not work with plain functions, since the parameter names will be + * // collapsed to a single letter identifier. To work around this, you can + * // explicitly specify the names of the parameters your task function needs + * // in an array, similar to Angular.js dependency injection. + * + * // This still has an advantage over plain `auto`, since the results a task + * // depends on are still spread into arguments. + * async.autoInject({ + * //... + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(write_file, callback) { + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * }] + * //... + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + */ + function autoInject(tasks, callback) { + var newTasks = {}; + + Object.keys(tasks).forEach(key => { + var taskFn = tasks[key]; + var params; + var fnIsAsync = isAsync(taskFn); + var hasNoDeps = + (!fnIsAsync && taskFn.length === 1) || + (fnIsAsync && taskFn.length === 0); + + if (Array.isArray(taskFn)) { + params = [...taskFn]; + taskFn = params.pop(); + + newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); + } else if (hasNoDeps) { + // no dependencies, use the function as-is + newTasks[key] = taskFn; + } else { + params = parseParams(taskFn); + if ((taskFn.length === 0 && !fnIsAsync) && params.length === 0) { + throw new Error("autoInject task functions require explicit parameters."); + } + + // remove callback param + if (!fnIsAsync) params.pop(); + + newTasks[key] = params.concat(newTask); + } + + function newTask(results, taskCb) { + var newArgs = params.map(name => results[name]); + newArgs.push(taskCb); + wrapAsync(taskFn)(...newArgs); + } + }); + + return auto(newTasks, callback); + } + + // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation + // used for queues. This implementation assumes that the node provided by the user can be modified + // to adjust the next and last properties. We implement only the minimal functionality + // for queue support. + class DLL { + constructor() { + this.head = this.tail = null; + this.length = 0; + } + + removeLink(node) { + if (node.prev) node.prev.next = node.next; + else this.head = node.next; + if (node.next) node.next.prev = node.prev; + else this.tail = node.prev; + + node.prev = node.next = null; + this.length -= 1; + return node; + } + + empty () { + while(this.head) this.shift(); + return this; + } + + insertAfter(node, newNode) { + newNode.prev = node; + newNode.next = node.next; + if (node.next) node.next.prev = newNode; + else this.tail = newNode; + node.next = newNode; + this.length += 1; + } + + insertBefore(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode; + else this.head = newNode; + node.prev = newNode; + this.length += 1; + } + + unshift(node) { + if (this.head) this.insertBefore(this.head, node); + else setInitial(this, node); + } + + push(node) { + if (this.tail) this.insertAfter(this.tail, node); + else setInitial(this, node); + } + + shift() { + return this.head && this.removeLink(this.head); + } + + pop() { + return this.tail && this.removeLink(this.tail); + } + + toArray() { + return [...this] + } + + *[Symbol.iterator] () { + var cur = this.head; + while (cur) { + yield cur.data; + cur = cur.next; + } + } + + remove (testFn) { + var curr = this.head; + while(curr) { + var {next} = curr; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; + } + } + + function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; + } + + function queue$1(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new RangeError('Concurrency must not be zero'); + } + + var _worker = wrapAsync(worker); + var numRunning = 0; + var workersList = []; + const events = { + error: [], + drain: [], + saturated: [], + unsaturated: [], + empty: [] + }; + + function on (event, handler) { + events[event].push(handler); + } + + function once (event, handler) { + const handleAndRemove = (...args) => { + off(event, handleAndRemove); + handler(...args); + }; + events[event].push(handleAndRemove); + } + + function off (event, handler) { + if (!event) return Object.keys(events).forEach(ev => events[ev] = []) + if (!handler) return events[event] = [] + events[event] = events[event].filter(ev => ev !== handler); + } + + function trigger (event, ...args) { + events[event].forEach(handler => handler(...args)); + } + + var processingScheduled = false; + function _insert(data, insertAtFront, rejectOnError, callback) { + if (callback != null && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + + var res, rej; + function promiseCallback (err, ...args) { + // we don't care about the error, let the global error handler + // deal with it + if (err) return rejectOnError ? rej(err) : res() + if (args.length <= 1) return res(args[0]) + res(args); + } + + var item = q._createTaskItem( + data, + rejectOnError ? promiseCallback : + (callback || promiseCallback) + ); + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + if (!processingScheduled) { + processingScheduled = true; + setImmediate$1(() => { + processingScheduled = false; + q.process(); + }); + } + + if (rejectOnError || !callback) { + return new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }) + } + } + + function _createCB(tasks) { + return function (err, ...args) { + numRunning -= 1; + + for (var i = 0, l = tasks.length; i < l; i++) { + var task = tasks[i]; + + var index = workersList.indexOf(task); + if (index === 0) { + workersList.shift(); + } else if (index > 0) { + workersList.splice(index, 1); + } + + task.callback(err, ...args); + + if (err != null) { + trigger('error', err, task.data); + } + } + + if (numRunning <= (q.concurrency - q.buffer) ) { + trigger('unsaturated'); + } + + if (q.idle()) { + trigger('drain'); + } + q.process(); + }; + } + + function _maybeDrain(data) { + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + setImmediate$1(() => trigger('drain')); + return true + } + return false + } + + const eventMethod = (name) => (handler) => { + if (!handler) { + return new Promise((resolve, reject) => { + once(name, (err, data) => { + if (err) return reject(err) + resolve(data); + }); + }) + } + off(name); + on(name, handler); + + }; + + var isProcessing = false; + var q = { + _tasks: new DLL(), + _createTaskItem (data, callback) { + return { + data, + callback + }; + }, + *[Symbol.iterator] () { + yield* q._tasks[Symbol.iterator](); + }, + concurrency, + payload, + buffer: concurrency / 4, + started: false, + paused: false, + push (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, false, callback)) + } + return _insert(data, false, false, callback); + }, + pushAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, true, callback)) + } + return _insert(data, false, true, callback); + }, + kill () { + off(); + q._tasks.empty(); + }, + unshift (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, false, callback)) + } + return _insert(data, true, false, callback); + }, + unshiftAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, true, callback)) + } + return _insert(data, true, true, callback); + }, + remove (testFn) { + q._tasks.remove(testFn); + }, + process () { + // Avoid trying to start too many processing operations. This can occur + // when callbacks resolve synchronously (#1267). + if (isProcessing) { + return; + } + isProcessing = true; + while(!q.paused && numRunning < q.concurrency && q._tasks.length){ + var tasks = [], data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); + tasks.push(node); + workersList.push(node); + data.push(node.data); + } + + numRunning += 1; + + if (q._tasks.length === 0) { + trigger('empty'); + } + + if (numRunning === q.concurrency) { + trigger('saturated'); + } + + var cb = onlyOnce(_createCB(tasks)); + _worker(data, cb); + } + isProcessing = false; + }, + length () { + return q._tasks.length; + }, + running () { + return numRunning; + }, + workersList () { + return workersList; + }, + idle() { + return q._tasks.length + numRunning === 0; + }, + pause () { + q.paused = true; + }, + resume () { + if (q.paused === false) { return; } + q.paused = false; + setImmediate$1(q.process); + } + }; + // define these as fixed properties, so people get useful errors when updating + Object.defineProperties(q, { + saturated: { + writable: false, + value: eventMethod('saturated') + }, + unsaturated: { + writable: false, + value: eventMethod('unsaturated') + }, + empty: { + writable: false, + value: eventMethod('empty') + }, + drain: { + writable: false, + value: eventMethod('drain') + }, + error: { + writable: false, + value: eventMethod('error') + }, + }); + return q; + } + + /** + * Creates a `cargo` object with the specified payload. Tasks added to the + * cargo will be processed altogether (up to the `payload` limit). If the + * `worker` is in progress, the task is queued until it becomes available. Once + * the `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, cargo passes an array of tasks to a single worker, repeating + * when the worker is finished. + * + * @name cargo + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargo and inner queue. + * @example + * + * // create a cargo object with payload 2 + * var cargo = async.cargo(function(tasks, callback) { + * for (var i=0; i { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.reduce(fileList, 0, getFileSizeInBytes); + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ + function reduce(coll, memo, iteratee, callback) { + callback = once(callback); + var _iteratee = wrapAsync(iteratee); + return eachOfSeries$1(coll, (x, i, iterCb) => { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); + } + var reduce$1 = awaitify(reduce, 4); + + /** + * Version of the compose function that is more natural to read. Each function + * consumes the return value of the previous function. It is the equivalent of + * [compose]{@link module:ControlFlow.compose} with the arguments reversed. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name seq + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.compose]{@link module:ControlFlow.compose} + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} a function that composes the `functions` in order + * @example + * + * // Requires lodash (or underscore), express3 and dresende's orm2. + * // Part of an app, that fetches cats of the logged user. + * // This example uses `seq` function to avoid overnesting and error + * // handling clutter. + * app.get('/cats', function(request, response) { + * var User = request.models.User; + * async.seq( + * User.get.bind(User), // 'User.get' has signature (id, callback(err, data)) + * function(user, fn) { + * user.getCats(fn); // 'getCats' has signature (callback(err, data)) + * } + * )(req.session.user_id, function (err, cats) { + * if (err) { + * console.error(err); + * response.json({ status: 'error', message: err.message }); + * } else { + * response.json({ status: 'ok', message: 'Cats found', data: cats }); + * } + * }); + * }); + */ + function seq(...functions) { + var _functions = functions.map(wrapAsync); + return function (...args) { + var that = this; + + var cb = args[args.length - 1]; + if (typeof cb == 'function') { + args.pop(); + } else { + cb = promiseCallback(); + } + + reduce$1(_functions, args, (newargs, fn, iterCb) => { + fn.apply(that, newargs.concat((err, ...nextargs) => { + iterCb(err, nextargs); + })); + }, + (err, results) => cb(err, ...results)); + + return cb[PROMISE_SYMBOL] + }; + } + + /** + * Creates a function which is a composition of the passed asynchronous + * functions. Each function consumes the return value of the function that + * follows. Composing functions `f()`, `g()`, and `h()` would produce the result + * of `f(g(h()))`, only this version uses callbacks to obtain the return values. + * + * If the last argument to the composed function is not a function, a promise + * is returned when you call it. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name compose + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} an asynchronous function that is the composed + * asynchronous `functions` + * @example + * + * function add1(n, callback) { + * setTimeout(function () { + * callback(null, n + 1); + * }, 10); + * } + * + * function mul3(n, callback) { + * setTimeout(function () { + * callback(null, n * 3); + * }, 10); + * } + * + * var add1mul3 = async.compose(mul3, add1); + * add1mul3(4, function (err, result) { + * // result now equals 15 + * }); + */ + function compose(...args) { + return seq(...args.reverse()); + } + + /** + * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. + * + * @name mapLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function mapLimit (coll, limit, iteratee, callback) { + return _asyncMap(eachOfLimit$2(limit), coll, iteratee, callback) + } + var mapLimit$1 = awaitify(mapLimit, 4); + + /** + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. + * + * @name concatLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapLimit + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ + function concatLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, ...args) => { + if (err) return iterCb(err); + return iterCb(err, args); + }); + }, (err, mapResults) => { + var result = []; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + result = result.concat(...mapResults[i]); + } + } + + return callback(err, result); + }); + } + var concatLimit$1 = awaitify(concatLimit, 4); + + /** + * Applies `iteratee` to each item in `coll`, concatenating the results. Returns + * the concatenated list. The `iteratee`s are called in parallel, and the + * results are concatenated as they return. The results array will be returned in + * the original order of `coll` passed to the `iteratee` function. + * + * @name concat + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @alias flatMap + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * let directoryList = ['dir1','dir2','dir3']; + * let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4']; + * + * // Using callbacks + * async.concat(directoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.concat(directoryList, fs.readdir) + * .then(results => { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir) + * .then(results => { + * console.log(results); + * }).catch(err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.concat(directoryList, fs.readdir); + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.concat(withMissingDirectoryList, fs.readdir); + * console.log(results); + * } catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } + * } + * + */ + function concat(coll, iteratee, callback) { + return concatLimit$1(coll, Infinity, iteratee, callback) + } + var concat$1 = awaitify(concat, 3); + + /** + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * + * @name concatSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapSeries + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. + * The iteratee should complete with an array an array of results. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ + function concatSeries(coll, iteratee, callback) { + return concatLimit$1(coll, 1, iteratee, callback) + } + var concatSeries$1 = awaitify(concatSeries, 3); + + /** + * Returns a function that when called, calls-back with the values provided. + * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to + * [`auto`]{@link module:ControlFlow.auto}. + * + * @name constant + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {...*} arguments... - Any number of arguments to automatically invoke + * callback with. + * @returns {AsyncFunction} Returns a function that when invoked, automatically + * invokes the callback with the previous given arguments. + * @example + * + * async.waterfall([ + * async.constant(42), + * function (value, next) { + * // value === 42 + * }, + * //... + * ], callback); + * + * async.waterfall([ + * async.constant(filename, "utf8"), + * fs.readFile, + * function (fileData, next) { + * //... + * } + * //... + * ], callback); + * + * async.auto({ + * hostname: async.constant("https://server.net/"), + * port: findFreePort, + * launchServer: ["hostname", "port", function (options, cb) { + * startServer(options, cb); + * }], + * //... + * }, callback); + */ + function constant$1(...args) { + return function (...ignoredArgs/*, callback*/) { + var callback = ignoredArgs.pop(); + return callback(null, ...args); + }; + } + + function _createTester(check, getResult) { + return (eachfn, arr, _iteratee, cb) => { + var testPassed = false; + var testResult; + const iteratee = wrapAsync(_iteratee); + eachfn(arr, (value, _, callback) => { + iteratee(value, (err, result) => { + if (err || err === false) return callback(err); + + if (check(result) && !testResult) { + testPassed = true; + testResult = getResult(true, value); + return callback(null, breakLoop); + } + callback(); + }); + }, err => { + if (err) return cb(err); + cb(null, testPassed ? testResult : getResult(false)); + }); + }; + } + + /** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. + + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * } + *); + * + * // Using Promises + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists) + * .then(result => { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); + * console.log(result); + * // dir1/file1.txt + * // result now equals the file in the list that exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function detect(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback) + } + var detect$1 = awaitify(detect, 3); + + /** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ + function detectLimit(coll, limit, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(limit), coll, iteratee, callback) + } + var detectLimit$1 = awaitify(detectLimit, 4); + + /** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ + function detectSeries(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(1), coll, iteratee, callback) + } + + var detectSeries$1 = awaitify(detectSeries, 3); + + function consoleFunc(name) { + return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => { + /* istanbul ignore else */ + if (typeof console === 'object') { + /* istanbul ignore else */ + if (err) { + /* istanbul ignore else */ + if (console.error) { + console.error(err); + } + } else if (console[name]) { /* istanbul ignore else */ + resultArgs.forEach(x => console[name](x)); + } + } + }) + } + + /** + * Logs the result of an [`async` function]{@link AsyncFunction} to the + * `console` using `console.dir` to display the properties of the resulting object. + * Only works in Node.js or in browsers that support `console.dir` and + * `console.error` (such as FF and Chrome). + * If multiple arguments are returned from the async function, + * `console.dir` is called on each argument in order. + * + * @name dir + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, {hello: name}); + * }, 1000); + * }; + * + * // in the node repl + * node> async.dir(hello, 'world'); + * {hello: 'world'} + */ + var dir = consoleFunc('dir'); + + /** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ + function doWhilst(iteratee, test, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results; + + function next(err, ...args) { + if (err) return callback(err); + if (err === false) return; + results = args; + _test(...args, check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return check(null, true); + } + + var doWhilst$1 = awaitify(doWhilst, 3); + + /** + * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the + * argument ordering differs from `until`. + * + * @name doUntil + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee` + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ + function doUntil(iteratee, test, callback) { + const _test = wrapAsync(test); + return doWhilst$1(iteratee, (...args) => { + const cb = args.pop(); + _test(...args, (err, truth) => cb (err, !truth)); + }, callback); + } + + function _withoutIndex(iteratee) { + return (value, index, callback) => iteratee(value, callback); + } + + /** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt']; + * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt']; + * + * // asynchronous function that deletes a file + * const deleteFile = function(file, callback) { + * fs.unlink(file, callback); + * }; + * + * // Using callbacks + * async.each(fileList, deleteFile, function(err) { + * if( err ) { + * console.log(err); + * } else { + * console.log('All files have been deleted successfully'); + * } + * }); + * + * // Error Handling + * async.each(withMissingFileList, deleteFile, function(err){ + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using Promises + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using async/await + * async () => { + * try { + * await async.each(files, deleteFile); + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * await async.each(withMissingFileList, deleteFile); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * } + * } + * + */ + function eachLimit$2(coll, iteratee, callback) { + return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback); + } + + var each = awaitify(eachLimit$2, 3); + + /** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachLimit(coll, limit, iteratee, callback) { + return eachOfLimit$2(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); + } + var eachLimit$1 = awaitify(eachLimit, 4); + + /** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item + * in series and therefore the iteratee functions will complete in order. + + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachSeries(coll, iteratee, callback) { + return eachLimit$1(coll, 1, iteratee, callback) + } + var eachSeries$1 = awaitify(eachSeries, 3); + + /** + * Wrap an async function and ensure it calls its callback on a later tick of + * the event loop. If the function already calls its callback on a next tick, + * no extra deferral is added. This is useful for preventing stack overflows + * (`RangeError: Maximum call stack size exceeded`) and generally keeping + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + * contained. ES2017 `async` functions are returned as-is -- they are immune + * to Zalgo's corrupting influences, as they always resolve on a later tick. + * + * @name ensureAsync + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - an async function, one that expects a node-style + * callback as its last argument. + * @returns {AsyncFunction} Returns a wrapped function with the exact same call + * signature as the function passed in. + * @example + * + * function sometimesAsync(arg, callback) { + * if (cache[arg]) { + * return callback(null, cache[arg]); // this would be synchronous!! + * } else { + * doSomeIO(arg, callback); // this IO would be asynchronous + * } + * } + * + * // this has a risk of stack overflows if many results are cached in a row + * async.mapSeries(args, sometimesAsync, done); + * + * // this will defer sometimesAsync's callback if necessary, + * // preventing stack overflows + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + */ + function ensureAsync(fn) { + if (isAsync(fn)) return fn; + return function (...args/*, callback*/) { + var callback = args.pop(); + var sync = true; + args.push((...innerArgs) => { + if (sync) { + setImmediate$1(() => callback(...innerArgs)); + } else { + callback(...innerArgs); + } + }); + fn.apply(this, args); + sync = false; + }; + } + + /** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.every(fileList, fileExists, function(err, result) { + * console.log(result); + * // true + * // result is true since every file exists + * }); + * + * async.every(withMissingFileList, fileExists, function(err, result) { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }); + * + * // Using Promises + * async.every(fileList, fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.every(withMissingFileList, fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.every(fileList, fileExists); + * console.log(result); + * // true + * // result is true since every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.every(withMissingFileList, fileExists); + * console.log(result); + * // false + * // result is false since NOT every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function every(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback) + } + var every$1 = awaitify(every, 3); + + /** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function everyLimit(coll, limit, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfLimit$2(limit), coll, iteratee, callback) + } + var everyLimit$1 = awaitify(everyLimit, 4); + + /** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function everySeries(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback) + } + var everySeries$1 = awaitify(everySeries, 3); + + function filterArray(eachfn, arr, iteratee, callback) { + var truthValues = new Array(arr.length); + eachfn(arr, (x, index, iterCb) => { + iteratee(x, (err, v) => { + truthValues[index] = !!v; + iterCb(err); + }); + }, err => { + if (err) return callback(err); + var results = []; + for (var i = 0; i < arr.length; i++) { + if (truthValues[i]) results.push(arr[i]); + } + callback(null, results); + }); + } + + function filterGeneric(eachfn, coll, iteratee, callback) { + var results = []; + eachfn(coll, (x, index, iterCb) => { + iteratee(x, (err, v) => { + if (err) return iterCb(err); + if (v) { + results.push({index, value: x}); + } + iterCb(err); + }); + }, err => { + if (err) return callback(err); + callback(null, results + .sort((a, b) => a.index - b.index) + .map(v => v.value)); + }); + } + + function _filter(eachfn, coll, iteratee, callback) { + var filter = isArrayLike(coll) ? filterArray : filterGeneric; + return filter(eachfn, coll, wrapAsync(iteratee), callback); + } + + /** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.filter(files, fileExists, function(err, results) { + * if(err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * }); + * + * // Using Promises + * async.filter(files, fileExists) + * .then(results => { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.filter(files, fileExists); + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function filter (coll, iteratee, callback) { + return _filter(eachOf$1, coll, iteratee, callback) + } + var filter$1 = awaitify(filter, 3); + + /** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + */ + function filterLimit (coll, limit, iteratee, callback) { + return _filter(eachOfLimit$2(limit), coll, iteratee, callback) + } + var filterLimit$1 = awaitify(filterLimit, 4); + + /** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + * @returns {Promise} a promise, if no callback provided + */ + function filterSeries (coll, iteratee, callback) { + return _filter(eachOfSeries$1, coll, iteratee, callback) + } + var filterSeries$1 = awaitify(filterSeries, 3); + + /** + * Calls the asynchronous function `fn` with a callback parameter that allows it + * to call itself again, in series, indefinitely. + + * If an error is passed to the callback then `errback` is called with the + * error, and execution stops, otherwise it will never be called. + * + * @name forever + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} fn - an async function to call repeatedly. + * Invoked with (next). + * @param {Function} [errback] - when `fn` passes an error to it's callback, + * this function will be called, and execution stops. Invoked with (err). + * @returns {Promise} a promise that rejects if an error occurs and an errback + * is not passed + * @example + * + * async.forever( + * function(next) { + * // next is suitable for passing to things that need a callback(err [, whatever]); + * // it will result in this function being called again. + * }, + * function(err) { + * // if next is called with a value in its first parameter, it will appear + * // in here as 'err', and execution will stop. + * } + * ); + */ + function forever(fn, errback) { + var done = onlyOnce(errback); + var task = wrapAsync(ensureAsync(fn)); + + function next(err) { + if (err) return done(err); + if (err === false) return; + task(next); + } + return next(); + } + var forever$1 = awaitify(forever, 2); + + /** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. + * + * @name groupByLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ + function groupByLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, key) => { + if (err) return iterCb(err); + return iterCb(err, {key, val}); + }); + }, (err, mapResults) => { + var result = {}; + // from MDN, handle object having an `hasOwnProperty` prop + var {hasOwnProperty} = Object.prototype; + + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + var {key} = mapResults[i]; + var {val} = mapResults[i]; + + if (hasOwnProperty.call(result, key)) { + result[key].push(val); + } else { + result[key] = [val]; + } + } + } + + return callback(err, result); + }); + } + + var groupByLimit$1 = awaitify(groupByLimit, 4); + + /** + * Returns a new object, where each value corresponds to an array of items, from + * `coll`, that returned the corresponding key. That is, the keys of the object + * correspond to the values passed to the `iteratee` callback. + * + * Note: Since this function applies the `iteratee` to each item in parallel, + * there is no guarantee that the `iteratee` functions will complete in order. + * However, the values for each key in the `result` will be in the same order as + * the original `coll`. For Objects, the values will roughly be in the order of + * the original Objects' keys (but this can vary across JavaScript engines). + * + * @name groupBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const files = ['dir1/file1.txt','dir2','dir4'] + * + * // asynchronous function that detects file type as none, file, or directory + * function detectFile(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(null, 'none'); + * } + * callback(null, stat.isDirectory() ? 'directory' : 'file'); + * }); + * } + * + * //Using callbacks + * async.groupBy(files, detectFile, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * }); + * + * // Using Promises + * async.groupBy(files, detectFile) + * .then( result => { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.groupBy(files, detectFile); + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function groupBy (coll, iteratee, callback) { + return groupByLimit$1(coll, Infinity, iteratee, callback) + } + + /** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. + * + * @name groupBySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whose + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ + function groupBySeries (coll, iteratee, callback) { + return groupByLimit$1(coll, 1, iteratee, callback) + } + + /** + * Logs the result of an `async` function to the `console`. Only works in + * Node.js or in browsers that support `console.log` and `console.error` (such + * as FF and Chrome). If multiple arguments are returned from the async + * function, `console.log` is called on each argument in order. + * + * @name log + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, 'hello ' + name); + * }, 1000); + * }; + * + * // in the node repl + * node> async.log(hello, 'world'); + * 'hello world' + */ + var log = consoleFunc('log'); + + /** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a + * time. + * + * @name mapValuesLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function mapValuesLimit(obj, limit, iteratee, callback) { + callback = once(callback); + var newObj = {}; + var _iteratee = wrapAsync(iteratee); + return eachOfLimit$2(limit)(obj, (val, key, next) => { + _iteratee(val, key, (err, result) => { + if (err) return next(err); + newObj[key] = result; + next(err); + }); + }, err => callback(err, newObj)); + } + + var mapValuesLimit$1 = awaitify(mapValuesLimit, 4); + + /** + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. + * + * Produces a new Object by mapping each value of `obj` through the `iteratee` + * function. The `iteratee` is called each `value` and `key` from `obj` and a + * callback for when it has finished processing. Each of these callbacks takes + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` + * passes an error to its callback, the main `callback` (for the `mapValues` + * function) is immediately called with the error. + * + * Note, the order of the keys in the result is not guaranteed. The keys will + * be roughly in the order they complete, (but this is very engine-specific) + * + * @name mapValues + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file3.txt' + * }; + * + * const withMissingFileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file4.txt' + * }; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, key, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.mapValues(fileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * }); + * + * // Error handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.mapValues(fileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * }).catch (err => { + * console.log(err); + * }); + * + * // Error Handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch (err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.mapValues(fileMap, getFileSizeInBytes); + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ + function mapValues(obj, iteratee, callback) { + return mapValuesLimit$1(obj, Infinity, iteratee, callback) + } + + /** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. + * + * @name mapValuesSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function mapValuesSeries(obj, iteratee, callback) { + return mapValuesLimit$1(obj, 1, iteratee, callback) + } + + /** + * Caches the results of an async function. When creating a hash to store + * function results against, the callback is omitted from the hash and an + * optional hash function can be used. + * + * **Note: if the async function errs, the result will not be cached and + * subsequent calls will call the wrapped function.** + * + * If no hash function is specified, the first argument is used as a hash key, + * which may work reasonably if it is a string or a data type that converts to a + * distinct string. Note that objects and arrays will not behave reasonably. + * Neither will cases where the other arguments are significant. In such cases, + * specify your own hash function. + * + * The cache of results is exposed as the `memo` property of the function + * returned by `memoize`. + * + * @name memoize + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function to proxy and cache results from. + * @param {Function} hasher - An optional function for generating a custom hash + * for storing results. It has all the arguments applied to it apart from the + * callback, and must be synchronous. + * @returns {AsyncFunction} a memoized version of `fn` + * @example + * + * var slow_fn = function(name, callback) { + * // do something + * callback(null, result); + * }; + * var fn = async.memoize(slow_fn); + * + * // fn can now be used as if it were slow_fn + * fn('some name', function() { + * // callback + * }); + */ + function memoize(fn, hasher = v => v) { + var memo = Object.create(null); + var queues = Object.create(null); + var _fn = wrapAsync(fn); + var memoized = initialParams((args, callback) => { + var key = hasher(...args); + if (key in memo) { + setImmediate$1(() => callback(null, ...memo[key])); + } else if (key in queues) { + queues[key].push(callback); + } else { + queues[key] = [callback]; + _fn(...args, (err, ...resultArgs) => { + // #1465 don't memoize if an error occurred + if (!err) { + memo[key] = resultArgs; + } + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i](err, ...resultArgs); + } + }); + } + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; + } + + /* istanbul ignore file */ + + /** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `process.nextTick`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name nextTick + * @static + * @memberOf module:Utils + * @method + * @see [async.setImmediate]{@link module:Utils.setImmediate} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ + var _defer; + + if (hasNextTick) { + _defer = process.nextTick; + } else if (hasSetImmediate) { + _defer = setImmediate; + } else { + _defer = fallback; + } + + var nextTick = wrap(_defer); + + var _parallel = awaitify((eachfn, tasks, callback) => { + var results = isArrayLike(tasks) ? [] : {}; + + eachfn(tasks, (task, key, taskCb) => { + wrapAsync(task)((err, ...result) => { + if (result.length < 2) { + [result] = result; + } + results[key] = result; + taskCb(err); + }); + }, err => callback(err, results)); + }, 3); + + /** + * Run the `tasks` collection of functions in parallel, without waiting until + * the previous function has completed. If any of the functions pass an error to + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * + * //Using Callbacks + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function parallel(tasks, callback) { + return _parallel(eachOf$1, tasks, callback); + } + + /** + * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a + * time. + * + * @name parallelLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.parallel]{@link module:ControlFlow.parallel} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + */ + function parallelLimit(tasks, limit, callback) { + return _parallel(eachOfLimit$2(limit), tasks, callback); + } + + /** + * A queue of tasks for the worker function to complete. + * @typedef {Iterable} QueueObject + * @memberOf module:ControlFlow + * @property {Function} length - a function returning the number of items + * waiting to be processed. Invoke with `queue.length()`. + * @property {boolean} started - a boolean indicating whether or not any + * items have been pushed and processed by the queue. + * @property {Function} running - a function returning the number of items + * currently being processed. Invoke with `queue.running()`. + * @property {Function} workersList - a function returning the array of items + * currently being processed. Invoke with `queue.workersList()`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke with `queue.idle()`. + * @property {number} concurrency - an integer for determining how many `worker` + * functions should be run in parallel. This property can be changed after a + * `queue` is created to alter the concurrency on-the-fly. + * @property {number} payload - an integer that specifies how many items are + * passed to the worker function at a time. only applies if this is a + * [cargo]{@link module:ControlFlow.cargo} object + * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback` + * once the `worker` has finished processing the task. Instead of a single task, + * a `tasks` array can be submitted. The respective callback is used for every + * task in the list. Invoke with `queue.push(task, [callback])`, + * @property {AsyncFunction} unshift - add a new task to the front of the `queue`. + * Invoke with `queue.unshift(task, [callback])`. + * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns + * a promise that rejects if an error occurs. + * @property {AsyncFunction} unshiftAsync - the same as `q.unshift`, except this returns + * a promise that rejects if an error occurs. + * @property {Function} remove - remove items from the queue that match a test + * function. The test function will be passed an object with a `data` property, + * and a `priority` property, if this is a + * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. + * Invoked with `queue.remove(testFn)`, where `testFn` is of the form + * `function ({data, priority}) {}` and returns a Boolean. + * @property {Function} saturated - a function that sets a callback that is + * called when the number of running workers hits the `concurrency` limit, and + * further tasks will be queued. If the callback is omitted, `q.saturated()` + * returns a promise for the next occurrence. + * @property {Function} unsaturated - a function that sets a callback that is + * called when the number of running workers is less than the `concurrency` & + * `buffer` limits, and further tasks will not be queued. If the callback is + * omitted, `q.unsaturated()` returns a promise for the next occurrence. + * @property {number} buffer - A minimum threshold buffer in order to say that + * the `queue` is `unsaturated`. + * @property {Function} empty - a function that sets a callback that is called + * when the last item from the `queue` is given to a `worker`. If the callback + * is omitted, `q.empty()` returns a promise for the next occurrence. + * @property {Function} drain - a function that sets a callback that is called + * when the last item from the `queue` has returned from the `worker`. If the + * callback is omitted, `q.drain()` returns a promise for the next occurrence. + * @property {Function} error - a function that sets a callback that is called + * when a task errors. Has the signature `function(error, task)`. If the + * callback is omitted, `error()` returns a promise that rejects on the next + * error. + * @property {boolean} paused - a boolean for determining whether the queue is + * in a paused state. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke with `queue.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke with `queue.resume()`. + * @property {Function} kill - a function that removes the `drain` callback and + * empties remaining tasks from the queue forcing it to go idle. No more tasks + * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. + * + * @example + * const q = async.queue(worker, 2) + * q.push(item1) + * q.push(item2) + * q.push(item3) + * // queues are iterable, spread into an array to inspect + * const items = [...q] // [item1, item2, item3] + * // or use for of + * for (let item of q) { + * console.log(item) + * } + * + * q.drain(() => { + * console.log('all done') + * }) + * // or + * await q.drain() + */ + + /** + * Creates a `queue` object with the specified `concurrency`. Tasks added to the + * `queue` are processed in parallel (up to the `concurrency` limit). If all + * `worker`s are in progress, the task is queued until one becomes available. + * Once a `worker` completes a `task`, that `task`'s callback is called. + * + * @name queue + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. Invoked with (task, callback). + * @param {number} [concurrency=1] - An `integer` for determining how many + * `worker` functions should be run in parallel. If omitted, the concurrency + * defaults to `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be + * attached as certain properties to listen for specific events during the + * lifecycle of the queue. + * @example + * + * // create a queue object with concurrency 2 + * var q = async.queue(function(task, callback) { + * console.log('hello ' + task.name); + * callback(); + * }, 2); + * + * // assign a callback + * q.drain(function() { + * console.log('all items have been processed'); + * }); + * // or await the end + * await q.drain() + * + * // assign an error callback + * q.error(function(err, task) { + * console.error('task experienced an error'); + * }); + * + * // add some items to the queue + * q.push({name: 'foo'}, function(err) { + * console.log('finished processing foo'); + * }); + * // callback is optional + * q.push({name: 'bar'}); + * + * // add some items to the queue (batch-wise) + * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { + * console.log('finished processing item'); + * }); + * + * // add some items to the front of the queue + * q.unshift({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + */ + function queue (worker, concurrency) { + var _worker = wrapAsync(worker); + return queue$1((items, cb) => { + _worker(items[0], cb); + }, concurrency, 1); + } + + // Binary min-heap implementation used for priority queue. + // Implementation is stable, i.e. push time is considered for equal priorities + class Heap { + constructor() { + this.heap = []; + this.pushCount = Number.MIN_SAFE_INTEGER; + } + + get length() { + return this.heap.length; + } + + empty () { + this.heap = []; + return this; + } + + percUp(index) { + let p; + + while (index > 0 && smaller(this.heap[index], this.heap[p=parent(index)])) { + let t = this.heap[index]; + this.heap[index] = this.heap[p]; + this.heap[p] = t; + + index = p; + } + } + + percDown(index) { + let l; + + while ((l=leftChi(index)) < this.heap.length) { + if (l+1 < this.heap.length && smaller(this.heap[l+1], this.heap[l])) { + l = l+1; + } + + if (smaller(this.heap[index], this.heap[l])) { + break; + } + + let t = this.heap[index]; + this.heap[index] = this.heap[l]; + this.heap[l] = t; + + index = l; + } + } + + push(node) { + node.pushCount = ++this.pushCount; + this.heap.push(node); + this.percUp(this.heap.length-1); + } + + unshift(node) { + return this.heap.push(node); + } + + shift() { + let [top] = this.heap; + + this.heap[0] = this.heap[this.heap.length-1]; + this.heap.pop(); + this.percDown(0); + + return top; + } + + toArray() { + return [...this]; + } + + *[Symbol.iterator] () { + for (let i = 0; i < this.heap.length; i++) { + yield this.heap[i].data; + } + } + + remove (testFn) { + let j = 0; + for (let i = 0; i < this.heap.length; i++) { + if (!testFn(this.heap[i])) { + this.heap[j] = this.heap[i]; + j++; + } + } + + this.heap.splice(j); + + for (let i = parent(this.heap.length-1); i >= 0; i--) { + this.percDown(i); + } + + return this; + } + } + + function leftChi(i) { + return (i<<1)+1; + } + + function parent(i) { + return ((i+1)>>1)-1; + } + + function smaller(x, y) { + if (x.priority !== y.priority) { + return x.priority < y.priority; + } + else { + return x.pushCount < y.pushCount; + } + } + + /** + * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and + * completed in ascending priority order. + * + * @name priorityQueue + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. + * Invoked with (task, callback). + * @param {number} concurrency - An `integer` for determining how many `worker` + * functions should be run in parallel. If omitted, the concurrency defaults to + * `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are three + * differences between `queue` and `priorityQueue` objects: + * * `push(task, priority, [callback])` - `priority` should be a number. If an + * array of `tasks` is given, all tasks will be assigned the same priority. + * * `pushAsync(task, priority, [callback])` - the same as `priorityQueue.push`, + * except this returns a promise that rejects if an error occurs. + * * The `unshift` and `unshiftAsync` methods were removed. + */ + function priorityQueue(worker, concurrency) { + // Start with a normal queue + var q = queue(worker, concurrency); + + var { + push, + pushAsync + } = q; + + q._tasks = new Heap(); + q._createTaskItem = ({data, priority}, callback) => { + return { + data, + priority, + callback + }; + }; + + function createDataItems(tasks, priority) { + if (!Array.isArray(tasks)) { + return {data: tasks, priority}; + } + return tasks.map(data => { return {data, priority}; }); + } + + // Override push to accept second parameter representing priority + q.push = function(data, priority = 0, callback) { + return push(createDataItems(data, priority), callback); + }; + + q.pushAsync = function(data, priority = 0, callback) { + return pushAsync(createDataItems(data, priority), callback); + }; + + // Remove unshift functions + delete q.unshift; + delete q.unshiftAsync; + + return q; + } + + /** + * Runs the `tasks` array of functions in parallel, without waiting until the + * previous function has completed. Once any of the `tasks` complete or pass an + * error to its callback, the main `callback` is immediately called. It's + * equivalent to `Promise.race()`. + * + * @name race + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} + * to run. Each function can complete with an optional `result` value. + * @param {Function} callback - A callback to run once any of the functions have + * completed. This function gets an error or result from the first function that + * completed. Invoked with (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.race([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // main callback + * function(err, result) { + * // the result will be equal to 'two' as it finishes earlier + * }); + */ + function race(tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); + if (!tasks.length) return callback(); + for (var i = 0, l = tasks.length; i < l; i++) { + wrapAsync(tasks[i])(callback); + } + } + + var race$1 = awaitify(race, 2); + + /** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function reduceRight (array, memo, iteratee, callback) { + var reversed = [...array].reverse(); + return reduce$1(reversed, memo, iteratee, callback); + } + + /** + * Wraps the async function in another function that always completes with a + * result object, even when it errors. + * + * The result object has either the property `error` or `value`. + * + * @name reflect + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function you want to wrap + * @returns {Function} - A function that always passes null to it's callback as + * the error. The second argument to the callback will be an `object` with + * either an `error` or a `value` property. + * @example + * + * async.parallel([ + * async.reflect(function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }), + * async.reflect(function(callback) { + * // do some more stuff but error ... + * callback('bad stuff happened'); + * }), + * async.reflect(function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * }) + * ], + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = 'bad stuff happened' + * // results[2].value = 'two' + * }); + */ + function reflect(fn) { + var _fn = wrapAsync(fn); + return initialParams(function reflectOn(args, reflectCallback) { + args.push((error, ...cbArgs) => { + let retVal = {}; + if (error) { + retVal.error = error; + } + if (cbArgs.length > 0){ + var value = cbArgs; + if (cbArgs.length <= 1) { + [value] = cbArgs; + } + retVal.value = value; + } + reflectCallback(null, retVal); + }); + + return _fn.apply(this, args); + }); + } + + /** + * A helper function that wraps an array or an object of functions with `reflect`. + * + * @name reflectAll + * @static + * @memberOf module:Utils + * @method + * @see [async.reflect]{@link module:Utils.reflect} + * @category Util + * @param {Array|Object|Iterable} tasks - The collection of + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. + * @returns {Array} Returns an array of async functions, each wrapped in + * `async.reflect` + * @example + * + * let tasks = [ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * // do some more stuff but error ... + * callback(new Error('bad stuff happened')); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = Error('bad stuff happened') + * // results[2].value = 'two' + * }); + * + * // an example using an object instead of an array + * let tasks = { + * one: function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * two: function(callback) { + * callback('two'); + * }, + * three: function(callback) { + * setTimeout(function() { + * callback(null, 'three'); + * }, 100); + * } + * }; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results.one.value = 'one' + * // results.two.error = 'two' + * // results.three.value = 'three' + * }); + */ + function reflectAll(tasks) { + var results; + if (Array.isArray(tasks)) { + results = tasks.map(reflect); + } else { + results = {}; + Object.keys(tasks).forEach(key => { + results[key] = reflect.call(this, tasks[key]); + }); + } + return results; + } + + function reject$2(eachfn, arr, _iteratee, callback) { + const iteratee = wrapAsync(_iteratee); + return _filter(eachfn, arr, (value, cb) => { + iteratee(value, (err, v) => { + cb(err, !v); + }); + }, callback); + } + + /** + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. + * + * @name reject + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.reject(fileList, fileExists, function(err, results) { + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }); + * + * // Using Promises + * async.reject(fileList, fileExists) + * .then( results => { + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.reject(fileList, fileExists); + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function reject (coll, iteratee, callback) { + return reject$2(eachOf$1, coll, iteratee, callback) + } + var reject$1 = awaitify(reject, 3); + + /** + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a + * time. + * + * @name rejectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function rejectLimit (coll, limit, iteratee, callback) { + return reject$2(eachOfLimit$2(limit), coll, iteratee, callback) + } + var rejectLimit$1 = awaitify(rejectLimit, 4); + + /** + * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. + * + * @name rejectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function rejectSeries (coll, iteratee, callback) { + return reject$2(eachOfSeries$1, coll, iteratee, callback) + } + var rejectSeries$1 = awaitify(rejectSeries, 3); + + function constant(value) { + return function () { + return value; + } + } + + /** + * Attempts to get a successful response from `task` no more than `times` times + * before returning an error. If the task is successful, the `callback` will be + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * @returns {Promise} a promise if no callback provided + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ + const DEFAULT_TIMES = 5; + const DEFAULT_INTERVAL = 0; + + function retry(opts, task, callback) { + var options = { + times: DEFAULT_TIMES, + intervalFunc: constant(DEFAULT_INTERVAL) + }; + + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || promiseCallback(); + task = opts; + } else { + parseTimes(options, opts); + callback = callback || promiseCallback(); + } + + if (typeof task !== 'function') { + throw new Error("Invalid arguments for async.retry"); + } + + var _task = wrapAsync(task); + + var attempt = 1; + function retryAttempt() { + _task((err, ...args) => { + if (err === false) return + if (err && attempt++ < options.times && + (typeof options.errorFilter != 'function' || + options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt - 1)); + } else { + callback(err, ...args); + } + }); + } + + retryAttempt(); + return callback[PROMISE_SYMBOL] + } + + function parseTimes(acc, t) { + if (typeof t === 'object') { + acc.times = +t.times || DEFAULT_TIMES; + + acc.intervalFunc = typeof t.interval === 'function' ? + t.interval : + constant(+t.interval || DEFAULT_INTERVAL); + + acc.errorFilter = t.errorFilter; + } else if (typeof t === 'number' || typeof t === 'string') { + acc.times = +t || DEFAULT_TIMES; + } else { + throw new Error("Invalid arguments for async.retry"); + } + } + + /** + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method + * wraps a task and makes it retryable, rather than immediately calling it + * with retries. + * + * @name retryable + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.retry]{@link module:ControlFlow.retry} + * @category Control Flow + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional + * options, exactly the same as from `retry`, except for a `opts.arity` that + * is the arity of the `task` function, defaulting to `task.length` + * @param {AsyncFunction} task - the asynchronous function to wrap. + * This function will be passed any arguments passed to the returned wrapper. + * Invoked with (...args, callback). + * @returns {AsyncFunction} The wrapped function, which when invoked, will + * retry on an error, based on the parameters specified in `opts`. + * This function will accept the same parameters as `task`. + * @example + * + * async.auto({ + * dep1: async.retryable(3, getFromFlakyService), + * process: ["dep1", async.retryable(3, function (results, cb) { + * maybeProcessData(results.dep1, cb); + * })] + * }, callback); + */ + function retryable (opts, task) { + if (!task) { + task = opts; + opts = null; + } + let arity = (opts && opts.arity) || task.length; + if (isAsync(task)) { + arity += 1; + } + var _task = wrapAsync(task); + return initialParams((args, callback) => { + if (args.length < arity - 1 || callback == null) { + args.push(callback); + callback = promiseCallback(); + } + function taskFn(cb) { + _task(...args, cb); + } + + if (opts) retry(opts, taskFn, callback); + else retry(taskFn, callback); + + return callback[PROMISE_SYMBOL] + }); + } + + /** + * Run the functions in the `tasks` collection in series, each one running once + * the previous function has completed. If any functions in the series pass an + * error to its callback, no more functions are run, and `callback` is + * immediately called with the value of the error. Otherwise, `callback` + * receives an array of results when `tasks` have completed. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function, and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.series}. + * + * **Note** that while many implementations preserve the order of object + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) + * explicitly states that + * + * > The mechanics and order of enumerating the properties is not specified. + * + * So if you rely on the order in which your series of functions are executed, + * and want this to work on all platforms, consider using an array. + * + * @name series + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing + * [async functions]{@link AsyncFunction} to run in series. + * Each function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This function gets a results array (or object) + * containing all the result arguments passed to the `task` callbacks. Invoked + * with (err, result). + * @return {Promise} a promise, if no callback is passed + * @example + * + * //Using Callbacks + * async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] + * }); + * + * // an example using objects instead of arrays + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.series([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function series(tasks, callback) { + return _parallel(eachOfSeries$1, tasks, callback); + } + + /** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + *); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // false + * // result is false since none of the files exists + * } + *); + * + * // Using Promises + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since some file in the list exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since none of the files exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists); + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists); + * console.log(result); + * // false + * // result is false since none of the files exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function some(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback) + } + var some$1 = awaitify(some, 3); + + /** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function someLimit(coll, limit, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfLimit$2(limit), coll, iteratee, callback) + } + var someLimit$1 = awaitify(someLimit, 4); + + /** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function someSeries(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback) + } + var someSeries$1 = awaitify(someSeries, 3); + + /** + * Sorts a list by the results of running each `coll` value through an async + * `iteratee`. + * + * @name sortBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a value to use as the sort criteria as + * its `result`. + * Invoked with (item, callback). + * @param {Function} callback - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is the items + * from the original `coll` sorted by the values returned by the `iteratee` + * calls. Invoked with (err, results). + * @returns {Promise} a promise, if no callback passed + * @example + * + * // bigfile.txt is a file that is 251100 bytes in size + * // mediumfile.txt is a file that is 11000 bytes in size + * // smallfile.txt is a file that is 121 bytes in size + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // By modifying the callback parameter the + * // sorting order can be influenced: + * + * // ascending order + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) return callback(getFileSizeErr); + * callback(null, fileSize); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // descending order + * async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) { + * return callback(getFileSizeErr); + * } + * callback(null, fileSize * -1); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt'] + * } + * } + * ); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * } + * ); + * + * // Using Promises + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * (async () => { + * try { + * let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * // Error handling + * async () => { + * try { + * let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ + function sortBy (coll, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return map$1(coll, (x, iterCb) => { + _iteratee(x, (err, criteria) => { + if (err) return iterCb(err); + iterCb(err, {value: x, criteria}); + }); + }, (err, results) => { + if (err) return callback(err); + callback(null, results.sort(comparator).map(v => v.value)); + }); + + function comparator(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } + } + var sortBy$1 = awaitify(sortBy, 3); + + /** + * Sets a time limit on an asynchronous function. If the function does not call + * its callback within the specified milliseconds, it will be called with a + * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * + * @name timeout + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} asyncFn - The async function to limit in time. + * @param {number} milliseconds - The specified time limit. + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) + * to timeout Error for more information.. + * @returns {AsyncFunction} Returns a wrapped function that can be used with any + * of the control flow functions. + * Invoke this function with the same parameters as you would `asyncFunc`. + * @example + * + * function myFunction(foo, callback) { + * doAsyncTask(foo, function(err, data) { + * // handle errors + * if (err) return callback(err); + * + * // do some stuff ... + * + * // return processed data + * return callback(null, data); + * }); + * } + * + * var wrapped = async.timeout(myFunction, 1000); + * + * // call `wrapped` as you would `myFunction` + * wrapped({ bar: 'bar' }, function(err, data) { + * // if `myFunction` takes < 1000 ms to execute, `err` + * // and `data` will have their expected values + * + * // else `err` will be an Error with the code 'ETIMEDOUT' + * }); + */ + function timeout(asyncFn, milliseconds, info) { + var fn = wrapAsync(asyncFn); + + return initialParams((args, callback) => { + var timedOut = false; + var timer; + + function timeoutCallback() { + var name = asyncFn.name || 'anonymous'; + var error = new Error('Callback function "' + name + '" timed out.'); + error.code = 'ETIMEDOUT'; + if (info) { + error.info = info; + } + timedOut = true; + callback(error); + } + + args.push((...cbArgs) => { + if (!timedOut) { + callback(...cbArgs); + clearTimeout(timer); + } + }); + + // setup timer and call original function + timer = setTimeout(timeoutCallback, milliseconds); + fn(...args); + }); + } + + function range(size) { + var result = Array(size); + while (size--) { + result[size] = size; + } + return result; + } + + /** + * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a + * time. + * + * @name timesLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} count - The number of times to run the function. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see [async.map]{@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ + function timesLimit(count, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(range(count), limit, _iteratee, callback); + } + + /** + * Calls the `iteratee` function `n` times, and accumulates results in the same + * manner you would use with [map]{@link module:Collections.map}. + * + * @name times + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.map]{@link module:Collections.map} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + * @example + * + * // Pretend this is some complicated async factory + * var createUser = function(id, callback) { + * callback(null, { + * id: 'user' + id + * }); + * }; + * + * // generate 5 users + * async.times(5, function(n, next) { + * createUser(n, function(err, user) { + * next(err, user); + * }); + * }, function(err, users) { + * // we should now have 5 users + * }); + */ + function times (n, iteratee, callback) { + return timesLimit(n, Infinity, iteratee, callback) + } + + /** + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * + * @name timesSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ + function timesSeries (n, iteratee, callback) { + return timesLimit(n, 1, iteratee, callback) + } + + /** + * A relative of `reduce`. Takes an Object or Array, and iterates over each + * element in parallel, each step potentially mutating an `accumulator` value. + * The type of the accumulator defaults to the type of collection passed in. + * + * @name transform + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} [accumulator] - The initial state of the transform. If omitted, + * it will default to an empty Object or Array, depending on the type of `coll` + * @param {AsyncFunction} iteratee - A function applied to each item in the + * collection that potentially modifies the accumulator. + * Invoked with (accumulator, item, key, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the transformed accumulator. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileList, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * }); + * + * // Using Promises + * async.transform(fileList, transformFileSize) + * .then(result => { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.transform(fileList, transformFileSize); + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' }; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileMap, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * }); + * + * // Using Promises + * async.transform(fileMap, transformFileSize) + * .then(result => { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.transform(fileMap, transformFileSize); + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function transform (coll, accumulator, iteratee, callback) { + if (arguments.length <= 3 && typeof accumulator === 'function') { + callback = iteratee; + iteratee = accumulator; + accumulator = Array.isArray(coll) ? [] : {}; + } + callback = once(callback || promiseCallback()); + var _iteratee = wrapAsync(iteratee); + + eachOf$1(coll, (v, k, cb) => { + _iteratee(accumulator, v, k, cb); + }, err => callback(err, accumulator)); + return callback[PROMISE_SYMBOL] + } + + /** + * It runs each task in series but stops whenever any of the functions were + * successful. If one of the tasks were successful, the `callback` will be + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * async.tryEach([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ + function tryEach(tasks, callback) { + var error = null; + var result; + return eachSeries$1(tasks, (task, taskCb) => { + wrapAsync(task)((err, ...args) => { + if (err === false) return taskCb(err); + + if (args.length < 2) { + [result] = args; + } else { + result = args; + } + error = err; + taskCb(err ? null : {}); + }); + }, () => callback(error, result)); + } + + var tryEach$1 = awaitify(tryEach); + + /** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ + function unmemoize(fn) { + return (...args) => { + return (fn.unmemoized || fn)(...args); + }; + } + + /** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5); }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ + function whilst(test, iteratee, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results = []; + + function next(err, ...rest) { + if (err) return callback(err); + results = rest; + if (err === false) return; + _test(check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return _test(check); + } + var whilst$1 = awaitify(whilst, 3); + + /** + * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. `callback` will be passed an error and any + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * const results = [] + * let finished = false + * async.until(function test(cb) { + * cb(null, finished) + * }, function iter(next) { + * fetchPage(url, (err, body) => { + * if (err) return next(err) + * results = results.concat(body.objects) + * finished = !!body.next + * next(err) + * }) + * }, function done (err) { + * // all pages have been fetched + * }) + */ + function until(test, iteratee, callback) { + const _test = wrapAsync(test); + return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback); + } + + /** + * Runs the `tasks` array of functions in series, each passing their results to + * the next in the array. However, if any of the `tasks` pass an error to their + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ + function waterfall (tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); + if (!tasks.length) return callback(); + var taskIndex = 0; + + function nextTask(args) { + var task = wrapAsync(tasks[taskIndex++]); + task(...args, onlyOnce(next)); + } + + function next(err, ...args) { + if (err === false) return + if (err || taskIndex === tasks.length) { + return callback(err, ...args); + } + nextTask(args); + } + + nextTask([]); + } + + var waterfall$1 = awaitify(waterfall); + + /** + * An "async function" in the context of Async is an asynchronous function with + * a variable number of parameters, with the final parameter being a callback. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. + * + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static + */ + + + var index = { + apply, + applyEach, + applyEachSeries, + asyncify, + auto, + autoInject, + cargo: cargo$1, + cargoQueue: cargo, + compose, + concat: concat$1, + concatLimit: concatLimit$1, + concatSeries: concatSeries$1, + constant: constant$1, + detect: detect$1, + detectLimit: detectLimit$1, + detectSeries: detectSeries$1, + dir, + doUntil, + doWhilst: doWhilst$1, + each, + eachLimit: eachLimit$1, + eachOf: eachOf$1, + eachOfLimit: eachOfLimit$1, + eachOfSeries: eachOfSeries$1, + eachSeries: eachSeries$1, + ensureAsync, + every: every$1, + everyLimit: everyLimit$1, + everySeries: everySeries$1, + filter: filter$1, + filterLimit: filterLimit$1, + filterSeries: filterSeries$1, + forever: forever$1, + groupBy, + groupByLimit: groupByLimit$1, + groupBySeries, + log, + map: map$1, + mapLimit: mapLimit$1, + mapSeries: mapSeries$1, + mapValues, + mapValuesLimit: mapValuesLimit$1, + mapValuesSeries, + memoize, + nextTick, + parallel, + parallelLimit, + priorityQueue, + queue, + race: race$1, + reduce: reduce$1, + reduceRight, + reflect, + reflectAll, + reject: reject$1, + rejectLimit: rejectLimit$1, + rejectSeries: rejectSeries$1, + retry, + retryable, + seq, + series, + setImmediate: setImmediate$1, + some: some$1, + someLimit: someLimit$1, + someSeries: someSeries$1, + sortBy: sortBy$1, + timeout, + times, + timesLimit, + timesSeries, + transform, + tryEach: tryEach$1, + unmemoize, + until, + waterfall: waterfall$1, + whilst: whilst$1, + + // aliases + all: every$1, + allLimit: everyLimit$1, + allSeries: everySeries$1, + any: some$1, + anyLimit: someLimit$1, + anySeries: someSeries$1, + find: detect$1, + findLimit: detectLimit$1, + findSeries: detectSeries$1, + flatMap: concat$1, + flatMapLimit: concatLimit$1, + flatMapSeries: concatSeries$1, + forEach: each, + forEachSeries: eachSeries$1, + forEachLimit: eachLimit$1, + forEachOf: eachOf$1, + forEachOfSeries: eachOfSeries$1, + forEachOfLimit: eachOfLimit$1, + inject: reduce$1, + foldl: reduce$1, + foldr: reduceRight, + select: filter$1, + selectLimit: filterLimit$1, + selectSeries: filterSeries$1, + wrapSync: asyncify, + during: whilst$1, + doDuring: doWhilst$1 + }; + + exports.all = every$1; + exports.allLimit = everyLimit$1; + exports.allSeries = everySeries$1; + exports.any = some$1; + exports.anyLimit = someLimit$1; + exports.anySeries = someSeries$1; + exports.apply = apply; + exports.applyEach = applyEach; + exports.applyEachSeries = applyEachSeries; + exports.asyncify = asyncify; + exports.auto = auto; + exports.autoInject = autoInject; + exports.cargo = cargo$1; + exports.cargoQueue = cargo; + exports.compose = compose; + exports.concat = concat$1; + exports.concatLimit = concatLimit$1; + exports.concatSeries = concatSeries$1; + exports.constant = constant$1; + exports.default = index; + exports.detect = detect$1; + exports.detectLimit = detectLimit$1; + exports.detectSeries = detectSeries$1; + exports.dir = dir; + exports.doDuring = doWhilst$1; + exports.doUntil = doUntil; + exports.doWhilst = doWhilst$1; + exports.during = whilst$1; + exports.each = each; + exports.eachLimit = eachLimit$1; + exports.eachOf = eachOf$1; + exports.eachOfLimit = eachOfLimit$1; + exports.eachOfSeries = eachOfSeries$1; + exports.eachSeries = eachSeries$1; + exports.ensureAsync = ensureAsync; + exports.every = every$1; + exports.everyLimit = everyLimit$1; + exports.everySeries = everySeries$1; + exports.filter = filter$1; + exports.filterLimit = filterLimit$1; + exports.filterSeries = filterSeries$1; + exports.find = detect$1; + exports.findLimit = detectLimit$1; + exports.findSeries = detectSeries$1; + exports.flatMap = concat$1; + exports.flatMapLimit = concatLimit$1; + exports.flatMapSeries = concatSeries$1; + exports.foldl = reduce$1; + exports.foldr = reduceRight; + exports.forEach = each; + exports.forEachLimit = eachLimit$1; + exports.forEachOf = eachOf$1; + exports.forEachOfLimit = eachOfLimit$1; + exports.forEachOfSeries = eachOfSeries$1; + exports.forEachSeries = eachSeries$1; + exports.forever = forever$1; + exports.groupBy = groupBy; + exports.groupByLimit = groupByLimit$1; + exports.groupBySeries = groupBySeries; + exports.inject = reduce$1; + exports.log = log; + exports.map = map$1; + exports.mapLimit = mapLimit$1; + exports.mapSeries = mapSeries$1; + exports.mapValues = mapValues; + exports.mapValuesLimit = mapValuesLimit$1; + exports.mapValuesSeries = mapValuesSeries; + exports.memoize = memoize; + exports.nextTick = nextTick; + exports.parallel = parallel; + exports.parallelLimit = parallelLimit; + exports.priorityQueue = priorityQueue; + exports.queue = queue; + exports.race = race$1; + exports.reduce = reduce$1; + exports.reduceRight = reduceRight; + exports.reflect = reflect; + exports.reflectAll = reflectAll; + exports.reject = reject$1; + exports.rejectLimit = rejectLimit$1; + exports.rejectSeries = rejectSeries$1; + exports.retry = retry; + exports.retryable = retryable; + exports.select = filter$1; + exports.selectLimit = filterLimit$1; + exports.selectSeries = filterSeries$1; + exports.seq = seq; + exports.series = series; + exports.setImmediate = setImmediate$1; + exports.some = some$1; + exports.someLimit = someLimit$1; + exports.someSeries = someSeries$1; + exports.sortBy = sortBy$1; + exports.timeout = timeout; + exports.times = times; + exports.timesLimit = timesLimit; + exports.timesSeries = timesSeries; + exports.transform = transform; + exports.tryEach = tryEach$1; + exports.unmemoize = unmemoize; + exports.until = until; + exports.waterfall = waterfall$1; + exports.whilst = whilst$1; + exports.wrapSync = asyncify; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); diff --git a/node_modules/async/dist/async.min.js b/node_modules/async/dist/async.min.js new file mode 100644 index 0000000..f0b7fdf --- /dev/null +++ b/node_modules/async/dist/async.min.js @@ -0,0 +1 @@ +(function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):(e="undefined"==typeof globalThis?e||self:globalThis,t(e.async={}))})(this,function(e){"use strict";function t(e,...t){return(...n)=>e(...t,...n)}function n(e){return function(...t){var n=t.pop();return e.call(this,t,n)}}function a(e){setTimeout(e,0)}function i(e){return(t,...n)=>e(()=>t(...n))}function r(e){return d(e)?function(...t){const n=t.pop(),a=e.apply(this,t);return s(a,n)}:n(function(t,n){var a;try{a=e.apply(this,t)}catch(t){return n(t)}return a&&"function"==typeof a.then?s(a,n):void n(null,a)})}function s(e,t){return e.then(e=>{l(t,null,e)},e=>{l(t,e&&(e instanceof Error||e.message)?e:new Error(e))})}function l(e,t,n){try{e(t,n)}catch(e){_e(t=>{throw t},e)}}function d(e){return"AsyncFunction"===e[Symbol.toStringTag]}function u(e){return"AsyncGenerator"===e[Symbol.toStringTag]}function p(e){return"function"==typeof e[Symbol.asyncIterator]}function c(e){if("function"!=typeof e)throw new Error("expected a function");return d(e)?r(e):e}function o(e,t){function n(...n){return"function"==typeof n[t-1]?e.apply(this,n):new Promise((a,i)=>{n[t-1]=(e,...t)=>e?i(e):void a(1{c(e).apply(i,n.concat(t))},a)});return i}}function f(e,t,n,a){t=t||[];var i=[],r=0,s=c(n);return e(t,(e,t,n)=>{var a=r++;s(e,(e,t)=>{i[a]=t,n(e)})},e=>{a(e,i)})}function y(e){return e&&"number"==typeof e.length&&0<=e.length&&0==e.length%1}function m(e){function t(...t){if(null!==e){var n=e;e=null,n.apply(this,t)}}return Object.assign(t,e),t}function g(e){return e[Symbol.iterator]&&e[Symbol.iterator]()}function k(e){var t=-1,n=e.length;return function a(){return++t=t||u||l||(u=!0,e.next().then(({value:e,done:t})=>{if(!(d||l))return u=!1,t?(l=!0,void(0>=p&&a(null))):void(p++,n(e,c,r),c++,i())}).catch(s))}function r(e,t){return p-=1,d?void 0:e?s(e):!1===e?(l=!0,void(d=!0)):t===be||l&&0>=p?(l=!0,a(null)):void i()}function s(e){d||(u=!1,l=!0,a(e))}let l=!1,d=!1,u=!1,p=0,c=0;i()}function O(e,t,n){function a(e,t){!1===e&&(l=!0);!0===l||(e?n(e):(++r===s||t===be)&&n(null))}n=m(n);var i=0,r=0,{length:s}=e,l=!1;for(0===s&&n(null);i{t=e,n=a}),e}function A(e,t,n){function a(e,t){k.push(()=>l(e,t))}function i(){if(!f){if(0===k.length&&0===h)return n(null,o);for(;k.length&&he()),i()}function l(e,t){if(!y){var a=L((t,...a)=>{if(h--,!1===t)return void(f=!0);if(2>a.length&&([a]=a),t){var i={};if(Object.keys(o).forEach(e=>{i[e]=o[e]}),i[e]=a,y=!0,g=Object.create(null),f)return;n(t,i)}else o[e]=a,s(e)});h++;var i=c(t[t.length-1]);1{0==--S[e]&&v.push(e)});if(t!==p)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function u(t){var n=[];return Object.keys(e).forEach(a=>{const i=e[a];Array.isArray(i)&&0<=i.indexOf(t)&&n.push(a)}),n}"number"!=typeof t&&(n=t,t=null),n=m(n||b());var p=Object.keys(e).length;if(!p)return n(null);t||(t=p);var o={},h=0,f=!1,y=!1,g=Object.create(null),k=[],v=[],S={};return Object.keys(e).forEach(t=>{var n=e[t];if(!Array.isArray(n))return a(t,[n]),void v.push(t);var i=n.slice(0,n.length-1),s=i.length;return 0===s?(a(t,n),void v.push(t)):void(S[t]=s,i.forEach(l=>{if(!e[l])throw new Error("async.auto task `"+t+"` has a non-existent dependency `"+l+"` in "+i.join(", "));r(l,()=>{s--,0===s&&a(t,n)})}))}),d(),i(),n[Ce]}function I(e){let t="",n=0,a=e.indexOf("*/");for(;ne.replace(Ne,"").trim())}function j(e,t){var n={};return Object.keys(e).forEach(t=>{function a(e,t){var n=i.map(t=>e[t]);n.push(t),c(r)(...n)}var i,r=e[t],s=d(r),l=!s&&1===r.length||s&&0===r.length;if(Array.isArray(r))i=[...r],r=i.pop(),n[t]=i.concat(0{r(e,n),t(...a)};f[e].push(n)}function r(e,t){return e?t?void(f[e]=f[e].filter(e=>e!==t)):f[e]=[]:Object.keys(f).forEach(e=>f[e]=[])}function s(e,...t){f[e].forEach(e=>e(...t))}function l(e,t,n,a){function i(e,...t){return e?n?s(e):r():1>=t.length?r(t[0]):void r(t)}if(null!=a&&"function"!=typeof a)throw new Error("task callback must be a function");k.started=!0;var r,s,l=k._createTaskItem(e,n?i:a||i);if(t?k._tasks.unshift(l):k._tasks.push(l),y||(y=!0,_e(()=>{y=!1,k.process()})),n||!a)return new Promise((e,t)=>{r=e,s=t})}function d(e){return function(t,...n){o-=1;for(var a=0,r=e.length;as("drain")),!0)}if(null==t)t=1;else if(0===t)throw new RangeError("Concurrency must not be zero");var p=c(e),o=0,h=[];const f={error:[],drain:[],saturated:[],unsaturated:[],empty:[]};var y=!1;const m=e=>t=>t?void(r(e),a(e,t)):new Promise((t,n)=>{i(e,(e,a)=>e?n(e):void t(a))});var g=!1,k={_tasks:new Ve,_createTaskItem(e,t){return{data:e,callback:t}},*[Symbol.iterator](){yield*k._tasks[Symbol.iterator]()},concurrency:t,payload:n,buffer:t/4,started:!1,paused:!1,push(e,t){return Array.isArray(e)?u(e)?void 0:e.map(e=>l(e,!1,!1,t)):l(e,!1,!1,t)},pushAsync(e,t){return Array.isArray(e)?u(e)?void 0:e.map(e=>l(e,!1,!0,t)):l(e,!1,!0,t)},kill(){r(),k._tasks.empty()},unshift(e,t){return Array.isArray(e)?u(e)?void 0:e.map(e=>l(e,!0,!1,t)):l(e,!0,!1,t)},unshiftAsync(e,t){return Array.isArray(e)?u(e)?void 0:e.map(e=>l(e,!0,!0,t)):l(e,!0,!0,t)},remove(e){k._tasks.remove(e)},process(){var e=Math.min;if(!g){for(g=!0;!k.paused&&o{t.apply(n,e.concat((e,...t)=>{a(e,t)}))},(e,t)=>a(e,...t)),a[Ce]}}function P(...e){return C(...e.reverse())}function R(...e){return function(...t){var n=t.pop();return n(null,...e)}}function z(e,t){return(n,a,i,r)=>{var s,l=!1;const d=c(i);n(a,(n,a,i)=>{d(n,(a,r)=>a||!1===a?i(a):e(r)&&!s?(l=!0,s=t(!0,n),i(null,be)):void i())},e=>e?r(e):void r(null,l?s:t(!1)))}}function N(e){return(t,...n)=>c(t)(...n,(t,...n)=>{"object"==typeof console&&(t?console.error&&console.error(t):console[e]&&n.forEach(t=>console[e](t)))})}function V(e,t,n){const a=c(t);return Xe(e,(...e)=>{const t=e.pop();a(...e,(e,n)=>t(e,!n))},n)}function Y(e){return(t,n,a)=>e(t,a)}function q(e){return d(e)?e:function(...t){var n=t.pop(),a=!0;t.push((...e)=>{a?_e(()=>n(...e)):n(...e)}),e.apply(this,t),a=!1}}function D(e,t,n,a){var r=Array(t.length);e(t,(e,t,a)=>{n(e,(e,n)=>{r[t]=!!n,a(e)})},e=>{if(e)return a(e);for(var n=[],s=0;s{n(e,(n,r)=>n?a(n):void(r&&i.push({index:t,value:e}),a(n)))},e=>e?a(e):void a(null,i.sort((e,t)=>e.index-t.index).map(e=>e.value)))}function U(e,t,n,a){var i=y(t)?D:Q;return i(e,t,c(n),a)}function G(e,t,n){return dt(e,1/0,t,n)}function W(e,t,n){return dt(e,1,t,n)}function H(e,t,n){return pt(e,1/0,t,n)}function J(e,t,n){return pt(e,1,t,n)}function K(e,t=e=>e){var a=Object.create(null),r=Object.create(null),s=c(e),l=n((e,n)=>{var d=t(...e);d in a?_e(()=>n(null,...a[d])):d in r?r[d].push(n):(r[d]=[n],s(...e,(e,...t)=>{e||(a[d]=t);var n=r[d];delete r[d];for(var s=0,u=n.length;s{n(e[0],t)},t,1)}function ee(e){return(e<<1)+1}function te(e){return(e+1>>1)-1}function ne(e,t){return e.priority===t.priority?e.pushCount({data:e,priority:t})):{data:e,priority:t}}var a=$(e,t),{push:i,pushAsync:r}=a;return a._tasks=new ht,a._createTaskItem=({data:e,priority:t},n)=>({data:e,priority:t,callback:n}),a.push=function(e,t=0,a){return i(n(e,t),a)},a.pushAsync=function(e,t=0,a){return r(n(e,t),a)},delete a.unshift,delete a.unshiftAsync,a}function ie(e,t,n,a){var i=[...e].reverse();return qe(i,t,n,a)}function re(e){var t=c(e);return n(function a(e,n){return e.push((e,...t)=>{let a={};if(e&&(a.error=e),0=t.length&&([i]=t),a.value=i}n(null,a)}),t.apply(this,e)})}function se(e){var t;return Array.isArray(e)?t=e.map(re):(t={},Object.keys(e).forEach(n=>{t[n]=re.call(this,e[n])})),t}function le(e,t,n,a){const i=c(n);return U(e,t,(e,t)=>{i(e,(e,n)=>{t(e,!n)})},a)}function de(e){return function(){return e}}function ue(e,t,n){function a(){r((e,...t)=>{!1===e||(e&&s++arguments.length&&"function"==typeof e?(n=t||b(),t=e):(pe(i,e),n=n||b()),"function"!=typeof t)throw new Error("Invalid arguments for async.retry");var r=c(t),s=1;return a(),n[Ce]}function pe(e,n){if("object"==typeof n)e.times=+n.times||kt,e.intervalFunc="function"==typeof n.interval?n.interval:de(+n.interval||vt),e.errorFilter=n.errorFilter;else if("number"==typeof n||"string"==typeof n)e.times=+n||kt;else throw new Error("Invalid arguments for async.retry")}function ce(e,t){t||(t=e,e=null);let a=e&&e.arity||t.length;d(t)&&(a+=1);var i=c(t);return n((t,n)=>{function r(e){i(...t,e)}return(t.length{function s(){var t=e.name||"anonymous",n=new Error("Callback function \""+t+"\" timed out.");n.code="ETIMEDOUT",a&&(n.info=a),d=!0,r(n)}var l,d=!1;n.push((...e)=>{d||(r(...e),clearTimeout(l))}),l=setTimeout(s,t),i(...n)})}function fe(e){for(var t=Array(e);e--;)t[e]=e;return t}function ye(e,t,n,a){var i=c(n);return De(fe(e),t,i,a)}function me(e,t,n){return ye(e,1/0,t,n)}function ge(e,t,n){return ye(e,1,t,n)}function ke(e,t,n,a){3>=arguments.length&&"function"==typeof t&&(a=n,n=t,t=Array.isArray(e)?[]:{}),a=m(a||b());var i=c(n);return Me(e,(e,n,a)=>{i(t,e,n,a)},e=>a(e,t)),a[Ce]}function ve(e){return(...t)=>(e.unmemoized||e)(...t)}function Se(e,t,n){const a=c(e);return _t(e=>a((t,n)=>e(t,!n)),t,n)}var xe,Le="function"==typeof queueMicrotask&&queueMicrotask,Ee="function"==typeof setImmediate&&setImmediate,Oe="object"==typeof process&&"function"==typeof process.nextTick;xe=Le?queueMicrotask:Ee?setImmediate:Oe?process.nextTick:a;var _e=i(xe);const be={};var Ae=e=>(t,n,a)=>{function i(e,t){if(!d)if(c-=1,e)l=!0,a(e);else if(!1===e)l=!0,d=!0;else{if(t===be||l&&0>=c)return l=!0,a(null);o||r()}}function r(){for(o=!0;c=c&&a(null));c+=1,n(t.value,t.key,L(i))}o=!1}if(a=m(a),0>=e)throw new RangeError("concurrency limit cannot be less than 1");if(!t)return a(null);if(u(t))return E(t,e,n,a);if(p(t))return E(t[Symbol.asyncIterator](),e,n,a);var s=x(t),l=!1,d=!1,c=0,o=!1;r()},Ie=o(function i(e,t,n,a){return Ae(t)(e,c(n),a)},4),Me=o(function a(e,t,n){var i=y(e)?O:_;return i(e,c(t),n)},3),je=o(function a(e,t,n){return f(Me,e,t,n)},3),we=h(je),Be=o(function a(e,t,n){return Ie(e,1,t,n)},3),Te=o(function a(e,t,n){return f(Be,e,t,n)},3),Fe=h(Te);const Ce=Symbol("promiseCallback");var Pe=/^(?:async\s)?(?:function)?\s*(?:\w+\s*)?\(([^)]+)\)(?:\s*{)/,Re=/^(?:async\s)?\s*(?:\(\s*)?((?:[^)=\s]\s*)*)(?:\)\s*)?=>/,ze=/,/,Ne=/(=.+)?(\s*)$/;class Ve{constructor(){this.head=this.tail=null,this.length=0}removeLink(e){return e.prev?e.prev.next=e.next:this.head=e.next,e.next?e.next.prev=e.prev:this.tail=e.prev,e.prev=e.next=null,this.length-=1,e}empty(){for(;this.head;)this.shift();return this}insertAfter(e,t){t.prev=e,t.next=e.next,e.next?e.next.prev=t:this.tail=t,e.next=t,this.length+=1}insertBefore(e,t){t.prev=e.prev,t.next=e,e.prev?e.prev.next=t:this.head=t,e.prev=t,this.length+=1}unshift(e){this.head?this.insertBefore(this.head,e):w(this,e)}push(e){this.tail?this.insertAfter(this.tail,e):w(this,e)}shift(){return this.head&&this.removeLink(this.head)}pop(){return this.tail&&this.removeLink(this.tail)}toArray(){return[...this]}*[Symbol.iterator](){for(var e=this.head;e;)yield e.data,e=e.next}remove(e){for(var t=this.head;t;){var{next:n}=t;e(t)&&this.removeLink(t),t=n}return this}}var Ye,qe=o(function i(e,t,n,a){a=m(a);var r=c(n);return Be(e,(e,n,a)=>{r(t,e,(e,n)=>{t=n,a(e)})},e=>a(e,t))},4),De=o(function i(e,t,n,a){return f(Ae(t),e,n,a)},4),Qe=o(function i(e,t,n,a){var r=c(n);return De(e,t,(e,t)=>{r(e,(e,...n)=>e?t(e):t(e,n))},(e,t)=>{for(var n=[],r=0;re,(e,t)=>t)(Me,e,t,n)},3),He=o(function i(e,t,n,a){return z(e=>e,(e,t)=>t)(Ae(t),e,n,a)},4),Je=o(function a(e,t,n){return z(e=>e,(e,t)=>t)(Ae(1),e,t,n)},3),Ke=N("dir"),Xe=o(function a(e,t,n){function i(e,...t){return e?n(e):void(!1===e||(s=t,d(...t,r)))}function r(e,t){return e?n(e):!1===e?void 0:t?void l(i):n(null,...s)}n=L(n);var s,l=c(e),d=c(t);return r(null,!0)},3),Ze=o(function a(e,t,n){return Me(e,Y(c(t)),n)},3),$e=o(function i(e,t,n,a){return Ae(t)(e,Y(c(n)),a)},4),et=o(function a(e,t,n){return $e(e,1,t,n)},3),tt=o(function a(e,t,n){return z(e=>!e,e=>!e)(Me,e,t,n)},3),nt=o(function i(e,t,n,a){return z(e=>!e,e=>!e)(Ae(t),e,n,a)},4),at=o(function a(e,t,n){return z(e=>!e,e=>!e)(Be,e,t,n)},3),it=o(function a(e,t,n){return U(Me,e,t,n)},3),rt=o(function i(e,t,n,a){return U(Ae(t),e,n,a)},4),st=o(function a(e,t,n){return U(Be,e,t,n)},3),lt=o(function n(e,t){function a(e){return e?i(e):void(!1===e||r(a))}var i=L(t),r=c(q(e));return a()},2),dt=o(function i(e,t,n,a){var r=c(n);return De(e,t,(e,t)=>{r(e,(n,a)=>n?t(n):t(n,{key:a,val:e}))},(e,t)=>{for(var n={},{hasOwnProperty:r}=Object.prototype,s=0;s{s(e,t,(e,a)=>e?n(e):void(r[t]=a,n(e)))},e=>a(e,r))},4);Ye=Oe?process.nextTick:Ee?setImmediate:a;var ct=i(Ye),ot=o((e,t,n)=>{var a=y(t)?[]:{};e(t,(e,t,n)=>{c(e)((e,...i)=>{2>i.length&&([i]=i),a[t]=i,n(e)})},e=>n(e,a))},3);class ht{constructor(){this.heap=[],this.pushCount=Number.MIN_SAFE_INTEGER}get length(){return this.heap.length}empty(){return this.heap=[],this}percUp(e){for(let n;0e)(Me,e,t,n)},3),xt=o(function i(e,t,n,a){return z(Boolean,e=>e)(Ae(t),e,n,a)},4),Lt=o(function a(e,t,n){return z(Boolean,e=>e)(Be,e,t,n)},3),Et=o(function a(e,t,n){function i(e,t){var n=e.criteria,a=t.criteria;return na?1:0}var r=c(t);return je(e,(e,t)=>{r(e,(n,a)=>n?t(n):void t(n,{value:e,criteria:a}))},(e,t)=>e?n(e):void n(null,t.sort(i).map(e=>e.value)))},3),Ot=o(function n(e,t){var a,i=null;return et(e,(e,t)=>{c(e)((e,...n)=>!1===e?t(e):void(2>n.length?[a]=n:a=n,i=e,t(e?null:{})))},()=>t(i,a))}),_t=o(function a(e,t,n){function i(e,...t){if(e)return n(e);d=t;!1===e||l(r)}function r(e,t){return e?n(e):!1===e?void 0:t?void s(i):n(null,...d)}n=L(n);var s=c(t),l=c(e),d=[];return l(r)},3),bt=o(function n(e,t){function a(t){var n=c(e[r++]);n(...t,L(i))}function i(n,...i){return!1===n?void 0:n||r===e.length?t(n,...i):void a(i)}if(t=m(t),!Array.isArray(e))return t(new Error("First argument to waterfall must be an array of functions"));if(!e.length)return t();var r=0;a([])});e.all=tt,e.allLimit=nt,e.allSeries=at,e.any=St,e.anyLimit=xt,e.anySeries=Lt,e.apply=t,e.applyEach=we,e.applyEachSeries=Fe,e.asyncify=r,e.auto=A,e.autoInject=j,e.cargo=T,e.cargoQueue=F,e.compose=P,e.concat=Ue,e.concatLimit=Qe,e.concatSeries=Ge,e.constant=R,e.default={apply:t,applyEach:we,applyEachSeries:Fe,asyncify:r,auto:A,autoInject:j,cargo:T,cargoQueue:F,compose:P,concat:Ue,concatLimit:Qe,concatSeries:Ge,constant:R,detect:We,detectLimit:He,detectSeries:Je,dir:Ke,doUntil:V,doWhilst:Xe,each:Ze,eachLimit:$e,eachOf:Me,eachOfLimit:Ie,eachOfSeries:Be,eachSeries:et,ensureAsync:q,every:tt,everyLimit:nt,everySeries:at,filter:it,filterLimit:rt,filterSeries:st,forever:lt,groupBy:G,groupByLimit:dt,groupBySeries:W,log:ut,map:je,mapLimit:De,mapSeries:Te,mapValues:H,mapValuesLimit:pt,mapValuesSeries:J,memoize:K,nextTick:ct,parallel:X,parallelLimit:Z,priorityQueue:ae,queue:$,race:ft,reduce:qe,reduceRight:ie,reflect:re,reflectAll:se,reject:yt,rejectLimit:mt,rejectSeries:gt,retry:ue,retryable:ce,seq:C,series:oe,setImmediate:_e,some:St,someLimit:xt,someSeries:Lt,sortBy:Et,timeout:he,times:me,timesLimit:ye,timesSeries:ge,transform:ke,tryEach:Ot,unmemoize:ve,until:Se,waterfall:bt,whilst:_t,all:tt,allLimit:nt,allSeries:at,any:St,anyLimit:xt,anySeries:Lt,find:We,findLimit:He,findSeries:Je,flatMap:Ue,flatMapLimit:Qe,flatMapSeries:Ge,forEach:Ze,forEachSeries:et,forEachLimit:$e,forEachOf:Me,forEachOfSeries:Be,forEachOfLimit:Ie,inject:qe,foldl:qe,foldr:ie,select:it,selectLimit:rt,selectSeries:st,wrapSync:r,during:_t,doDuring:Xe},e.detect=We,e.detectLimit=He,e.detectSeries=Je,e.dir=Ke,e.doDuring=Xe,e.doUntil=V,e.doWhilst=Xe,e.during=_t,e.each=Ze,e.eachLimit=$e,e.eachOf=Me,e.eachOfLimit=Ie,e.eachOfSeries=Be,e.eachSeries=et,e.ensureAsync=q,e.every=tt,e.everyLimit=nt,e.everySeries=at,e.filter=it,e.filterLimit=rt,e.filterSeries=st,e.find=We,e.findLimit=He,e.findSeries=Je,e.flatMap=Ue,e.flatMapLimit=Qe,e.flatMapSeries=Ge,e.foldl=qe,e.foldr=ie,e.forEach=Ze,e.forEachLimit=$e,e.forEachOf=Me,e.forEachOfLimit=Ie,e.forEachOfSeries=Be,e.forEachSeries=et,e.forever=lt,e.groupBy=G,e.groupByLimit=dt,e.groupBySeries=W,e.inject=qe,e.log=ut,e.map=je,e.mapLimit=De,e.mapSeries=Te,e.mapValues=H,e.mapValuesLimit=pt,e.mapValuesSeries=J,e.memoize=K,e.nextTick=ct,e.parallel=X,e.parallelLimit=Z,e.priorityQueue=ae,e.queue=$,e.race=ft,e.reduce=qe,e.reduceRight=ie,e.reflect=re,e.reflectAll=se,e.reject=yt,e.rejectLimit=mt,e.rejectSeries=gt,e.retry=ue,e.retryable=ce,e.select=it,e.selectLimit=rt,e.selectSeries=st,e.seq=C,e.series=oe,e.setImmediate=_e,e.some=St,e.someLimit=xt,e.someSeries=Lt,e.sortBy=Et,e.timeout=he,e.times=me,e.timesLimit=ye,e.timesSeries=ge,e.transform=ke,e.tryEach=Ot,e.unmemoize=ve,e.until=Se,e.waterfall=bt,e.whilst=_t,e.wrapSync=r,Object.defineProperty(e,"__esModule",{value:!0})}); \ No newline at end of file diff --git a/node_modules/async/dist/async.mjs b/node_modules/async/dist/async.mjs new file mode 100644 index 0000000..2c59965 --- /dev/null +++ b/node_modules/async/dist/async.mjs @@ -0,0 +1,5948 @@ +/** + * Creates a continuation function with some arguments already applied. + * + * Useful as a shorthand when combined with other control flow functions. Any + * arguments passed to the returned function are added to the arguments + * originally passed to apply. + * + * @name apply + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {Function} fn - The function you want to eventually apply all + * arguments to. Invokes with (arguments...). + * @param {...*} arguments... - Any number of arguments to automatically apply + * when the continuation is called. + * @returns {Function} the partially-applied function + * @example + * + * // using apply + * async.parallel([ + * async.apply(fs.writeFile, 'testfile1', 'test1'), + * async.apply(fs.writeFile, 'testfile2', 'test2') + * ]); + * + * + * // the same process without using apply + * async.parallel([ + * function(callback) { + * fs.writeFile('testfile1', 'test1', callback); + * }, + * function(callback) { + * fs.writeFile('testfile2', 'test2', callback); + * } + * ]); + * + * // It's possible to pass any number of additional arguments when calling the + * // continuation: + * + * node> var fn = async.apply(sys.puts, 'one'); + * node> fn('two', 'three'); + * one + * two + * three + */ +function apply(fn, ...args) { + return (...callArgs) => fn(...args,...callArgs); +} + +function initialParams (fn) { + return function (...args/*, callback*/) { + var callback = args.pop(); + return fn.call(this, args, callback); + }; +} + +/* istanbul ignore file */ + +var hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask; +var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; +var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; + +function fallback(fn) { + setTimeout(fn, 0); +} + +function wrap(defer) { + return (fn, ...args) => defer(() => fn(...args)); +} + +var _defer$1; + +if (hasQueueMicrotask) { + _defer$1 = queueMicrotask; +} else if (hasSetImmediate) { + _defer$1 = setImmediate; +} else if (hasNextTick) { + _defer$1 = process.nextTick; +} else { + _defer$1 = fallback; +} + +var setImmediate$1 = wrap(_defer$1); + +/** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ +function asyncify(func) { + if (isAsync(func)) { + return function (...args/*, callback*/) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback) + } + } + + return initialParams(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (result && typeof result.then === 'function') { + return handlePromise(result, callback) + } else { + callback(null, result); + } + }); +} + +function handlePromise(promise, callback) { + return promise.then(value => { + invokeCallback(callback, null, value); + }, err => { + invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err)); + }); +} + +function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + setImmediate$1(e => { throw e }, err); + } +} + +function isAsync(fn) { + return fn[Symbol.toStringTag] === 'AsyncFunction'; +} + +function isAsyncGenerator(fn) { + return fn[Symbol.toStringTag] === 'AsyncGenerator'; +} + +function isAsyncIterable(obj) { + return typeof obj[Symbol.asyncIterator] === 'function'; +} + +function wrapAsync(asyncFn) { + if (typeof asyncFn !== 'function') throw new Error('expected a function') + return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; +} + +// conditionally promisify a function. +// only return a promise if a callback is omitted +function awaitify (asyncFn, arity) { + if (!arity) arity = asyncFn.length; + if (!arity) throw new Error('arity is undefined') + function awaitable (...args) { + if (typeof args[arity - 1] === 'function') { + return asyncFn.apply(this, args) + } + + return new Promise((resolve, reject) => { + args[arity - 1] = (err, ...cbArgs) => { + if (err) return reject(err) + resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); + }; + asyncFn.apply(this, args); + }) + } + + return awaitable +} + +function applyEach$1 (eachfn) { + return function applyEach(fns, ...callArgs) { + const go = awaitify(function (callback) { + var that = this; + return eachfn(fns, (fn, cb) => { + wrapAsync(fn).apply(that, callArgs.concat(cb)); + }, callback); + }); + return go; + }; +} + +function _asyncMap(eachfn, arr, iteratee, callback) { + arr = arr || []; + var results = []; + var counter = 0; + var _iteratee = wrapAsync(iteratee); + + return eachfn(arr, (value, _, iterCb) => { + var index = counter++; + _iteratee(value, (err, v) => { + results[index] = v; + iterCb(err); + }); + }, err => { + callback(err, results); + }); +} + +function isArrayLike(value) { + return value && + typeof value.length === 'number' && + value.length >= 0 && + value.length % 1 === 0; +} + +// A temporary value used to identify if the loop should be broken. +// See #1064, #1293 +const breakLoop = {}; + +function once(fn) { + function wrapper (...args) { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, args); + } + Object.assign(wrapper, fn); + return wrapper +} + +function getIterator (coll) { + return coll[Symbol.iterator] && coll[Symbol.iterator](); +} + +function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? {value: coll[i], key: i} : null; + } +} + +function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) + return null; + i++; + return {value: item.value, key: i}; + } +} + +function createObjectIterator(obj) { + var okeys = obj ? Object.keys(obj) : []; + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + if (key === '__proto__') { + return next(); + } + return i < len ? {value: obj[key], key} : null; + }; +} + +function createIterator(coll) { + if (isArrayLike(coll)) { + return createArrayIterator(coll); + } + + var iterator = getIterator(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); +} + +function onlyOnce(fn) { + return function (...args) { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; + callFn.apply(this, args); + }; +} + +// for async generators +function asyncEachOfLimit(generator, limit, iteratee, callback) { + let done = false; + let canceled = false; + let awaiting = false; + let running = 0; + let idx = 0; + + function replenish() { + //console.log('replenish') + if (running >= limit || awaiting || done) return + //console.log('replenish awaiting') + awaiting = true; + generator.next().then(({value, done: iterDone}) => { + //console.log('got value', value) + if (canceled || done) return + awaiting = false; + if (iterDone) { + done = true; + if (running <= 0) { + //console.log('done nextCb') + callback(null); + } + return; + } + running++; + iteratee(value, idx, iterateeCallback); + idx++; + replenish(); + }).catch(handleError); + } + + function iterateeCallback(err, result) { + //console.log('iterateeCallback') + running -= 1; + if (canceled) return + if (err) return handleError(err) + + if (err === false) { + done = true; + canceled = true; + return + } + + if (result === breakLoop || (done && running <= 0)) { + done = true; + //console.log('done iterCb') + return callback(null); + } + replenish(); + } + + function handleError(err) { + if (canceled) return + awaiting = false; + done = true; + callback(err); + } + + replenish(); +} + +var eachOfLimit$2 = (limit) => { + return (obj, iteratee, callback) => { + callback = once(callback); + if (limit <= 0) { + throw new RangeError('concurrency limit cannot be less than 1') + } + if (!obj) { + return callback(null); + } + if (isAsyncGenerator(obj)) { + return asyncEachOfLimit(obj, limit, iteratee, callback) + } + if (isAsyncIterable(obj)) { + return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback) + } + var nextElem = createIterator(obj); + var done = false; + var canceled = false; + var running = 0; + var looping = false; + + function iterateeCallback(err, value) { + if (canceled) return + running -= 1; + if (err) { + done = true; + callback(err); + } + else if (err === false) { + done = true; + canceled = true; + } + else if (value === breakLoop || (done && running <= 0)) { + done = true; + return callback(null); + } + else if (!looping) { + replenish(); + } + } + + function replenish () { + looping = true; + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); + } + looping = false; + } + + replenish(); + }; +}; + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfLimit(coll, limit, iteratee, callback) { + return eachOfLimit$2(limit)(coll, wrapAsync(iteratee), callback); +} + +var eachOfLimit$1 = awaitify(eachOfLimit, 4); + +// eachOf implementation optimized for array-likes +function eachOfArrayLike(coll, iteratee, callback) { + callback = once(callback); + var index = 0, + completed = 0, + {length} = coll, + canceled = false; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } + if (canceled === true) return + if (err) { + callback(err); + } else if ((++completed === length) || value === breakLoop) { + callback(null); + } + } + + for (; index < length; index++) { + iteratee(coll[index], index, onlyOnce(iteratorCallback)); + } +} + +// a generic version of eachOf which can handle array, object, and iterator cases. +function eachOfGeneric (coll, iteratee, callback) { + return eachOfLimit$1(coll, Infinity, iteratee, callback); +} + +/** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dev.json is a file containing a valid json object config for dev environment + * // dev.json is a file containing a valid json object config for test environment + * // prod.json is a file containing a valid json object config for prod environment + * // invalid.json is a file with a malformed json object + * + * let configs = {}; //global variable + * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'}; + * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'}; + * + * // asynchronous function that reads a json file and parses the contents as json object + * function parseFile(file, key, callback) { + * fs.readFile(file, "utf8", function(err, data) { + * if (err) return calback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * } + * + * // Using callbacks + * async.forEachOf(validConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * } else { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * // JSON parse error exception + * } else { + * console.log(configs); + * } + * }); + * + * // Using Promises + * async.forEachOf(validConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * }).catch( err => { + * console.error(err); + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * }).catch( err => { + * console.error(err); + * // JSON parse error exception + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.forEachOf(validConfigFileMap, parseFile); + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * catch (err) { + * console.log(err); + * } + * } + * + * //Error handing + * async () => { + * try { + * let result = await async.forEachOf(invalidConfigFileMap, parseFile); + * console.log(configs); + * } + * catch (err) { + * console.log(err); + * // JSON parse error exception + * } + * } + * + */ +function eachOf(coll, iteratee, callback) { + var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, wrapAsync(iteratee), callback); +} + +var eachOf$1 = awaitify(eachOf, 3); + +/** + * Produces a new collection of values by mapping each value in `coll` through + * the `iteratee` function. The `iteratee` is called with an item from `coll` + * and a callback for when it has finished processing. Each of these callbacks + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.map(fileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.map(fileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.map(fileList, getFileSizeInBytes); + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.map(withMissingFileList, getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function map (coll, iteratee, callback) { + return _asyncMap(eachOf$1, coll, iteratee, callback) +} +var map$1 = awaitify(map, 3); + +/** + * Applies the provided arguments to each function in the array, calling + * `callback` after all functions have completed. If you only provide the first + * argument, `fns`, then it will return a function which lets you pass in the + * arguments as if it were a single function call. If more arguments are + * provided, `callback` is required while `args` is still optional. The results + * for each of the applied async functions are passed to the final callback + * as an array. + * + * @name applyEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s + * to all call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - Returns a function that takes no args other than + * an optional callback, that is the result of applying the `args` to each + * of the functions. + * @example + * + * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket') + * + * appliedFn((err, results) => { + * // results[0] is the results for `enableSearch` + * // results[1] is the results for `updateSchema` + * }); + * + * // partial application example: + * async.each( + * buckets, + * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(), + * callback + * ); + */ +var applyEach = applyEach$1(map$1); + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfSeries(coll, iteratee, callback) { + return eachOfLimit$1(coll, 1, iteratee, callback) +} +var eachOfSeries$1 = awaitify(eachOfSeries, 3); + +/** + * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. + * + * @name mapSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function mapSeries (coll, iteratee, callback) { + return _asyncMap(eachOfSeries$1, coll, iteratee, callback) +} +var mapSeries$1 = awaitify(mapSeries, 3); + +/** + * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. + * + * @name applyEachSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.applyEach]{@link module:ControlFlow.applyEach} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all + * call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - A function, that when called, is the result of + * appling the `args` to the list of functions. It takes no args, other than + * a callback. + */ +var applyEachSeries = applyEach$1(mapSeries$1); + +const PROMISE_SYMBOL = Symbol('promiseCallback'); + +function promiseCallback () { + let resolve, reject; + function callback (err, ...args) { + if (err) return reject(err) + resolve(args.length > 1 ? args : args[0]); + } + + callback[PROMISE_SYMBOL] = new Promise((res, rej) => { + resolve = res, + reject = rej; + }); + + return callback +} + +/** + * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on + * their requirements. Each function can optionally depend on other functions + * being completed first, and each function is run as soon as its requirements + * are satisfied. + * + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence + * will stop. Further tasks will not execute (so any other functions depending + * on it will not run), and the main `callback` is immediately called with the + * error. + * + * {@link AsyncFunction}s also receive an object containing the results of functions which + * have completed so far as the first argument, if they have dependencies. If a + * task function has no dependencies, it will only be passed a callback. + * + * @name auto + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Object} tasks - An object. Each of its properties is either a + * function or an array of requirements, with the {@link AsyncFunction} itself the last item + * in the array. The object's key of a property serves as the name of the task + * defined by that property, i.e. can be used when specifying requirements for + * other tasks. The function receives one or two arguments: + * * a `results` object, containing the results of the previously executed + * functions, only passed if the task has any dependencies, + * * a `callback(err, result)` function, which must be called when finished, + * passing an `error` (which can be `null`) and the result of the function's + * execution. + * @param {number} [concurrency=Infinity] - An optional `integer` for + * determining the maximum number of tasks that can be run in parallel. By + * default, as many as possible. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback. Results are always returned; however, if an + * error occurs, no further `tasks` will be performed, and the results object + * will only contain partial results. Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * @example + * + * //Using Callbacks + * async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }, function(err, results) { + * if (err) { + * console.log('err = ', err); + * } + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }); + * + * //Using Promises + * async.auto({ + * get_data: function(callback) { + * console.log('in get_data'); + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * console.log('in make_folder'); + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }).then(results => { + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }).catch(err => { + * console.log('err = ', err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }); + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function auto(tasks, concurrency, callback) { + if (typeof concurrency !== 'number') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = once(callback || promiseCallback()); + var numTasks = Object.keys(tasks).length; + if (!numTasks) { + return callback(null); + } + if (!concurrency) { + concurrency = numTasks; + } + + var results = {}; + var runningTasks = 0; + var canceled = false; + var hasError = false; + + var listeners = Object.create(null); + + var readyTasks = []; + + // for cycle detection: + var readyToCheck = []; // tasks that have been identified as reachable + // without the possibility of returning to an ancestor task + var uncheckedDependencies = {}; + + Object.keys(tasks).forEach(key => { + var task = tasks[key]; + if (!Array.isArray(task)) { + // no dependencies + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } + + var dependencies = task.slice(0, task.length - 1); + var remainingDependencies = dependencies.length; + if (remainingDependencies === 0) { + enqueueTask(key, task); + readyToCheck.push(key); + return; + } + uncheckedDependencies[key] = remainingDependencies; + + dependencies.forEach(dependencyName => { + if (!tasks[dependencyName]) { + throw new Error('async.auto task `' + key + + '` has a non-existent dependency `' + + dependencyName + '` in ' + + dependencies.join(', ')); + } + addListener(dependencyName, () => { + remainingDependencies--; + if (remainingDependencies === 0) { + enqueueTask(key, task); + } + }); + }); + }); + + checkForDeadlocks(); + processQueue(); + + function enqueueTask(key, task) { + readyTasks.push(() => runTask(key, task)); + } + + function processQueue() { + if (canceled) return + if (readyTasks.length === 0 && runningTasks === 0) { + return callback(null, results); + } + while(readyTasks.length && runningTasks < concurrency) { + var run = readyTasks.shift(); + run(); + } + + } + + function addListener(taskName, fn) { + var taskListeners = listeners[taskName]; + if (!taskListeners) { + taskListeners = listeners[taskName] = []; + } + + taskListeners.push(fn); + } + + function taskComplete(taskName) { + var taskListeners = listeners[taskName] || []; + taskListeners.forEach(fn => fn()); + processQueue(); + } + + + function runTask(key, task) { + if (hasError) return; + + var taskCallback = onlyOnce((err, ...result) => { + runningTasks--; + if (err === false) { + canceled = true; + return + } + if (result.length < 2) { + [result] = result; + } + if (err) { + var safeResults = {}; + Object.keys(results).forEach(rkey => { + safeResults[rkey] = results[rkey]; + }); + safeResults[key] = result; + hasError = true; + listeners = Object.create(null); + if (canceled) return + callback(err, safeResults); + } else { + results[key] = result; + taskComplete(key); + } + }); + + runningTasks++; + var taskFn = wrapAsync(task[task.length - 1]); + if (task.length > 1) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } + } + + function checkForDeadlocks() { + // Kahn's algorithm + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html + var currentTask; + var counter = 0; + while (readyToCheck.length) { + currentTask = readyToCheck.pop(); + counter++; + getDependents(currentTask).forEach(dependent => { + if (--uncheckedDependencies[dependent] === 0) { + readyToCheck.push(dependent); + } + }); + } + + if (counter !== numTasks) { + throw new Error( + 'async.auto cannot execute tasks due to a recursive dependency' + ); + } + } + + function getDependents(taskName) { + var result = []; + Object.keys(tasks).forEach(key => { + const task = tasks[key]; + if (Array.isArray(task) && task.indexOf(taskName) >= 0) { + result.push(key); + } + }); + return result; + } + + return callback[PROMISE_SYMBOL] +} + +var FN_ARGS = /^(?:async\s)?(?:function)?\s*(?:\w+\s*)?\(([^)]+)\)(?:\s*{)/; +var ARROW_FN_ARGS = /^(?:async\s)?\s*(?:\(\s*)?((?:[^)=\s]\s*)*)(?:\)\s*)?=>/; +var FN_ARG_SPLIT = /,/; +var FN_ARG = /(=.+)?(\s*)$/; + +function stripComments(string) { + let stripped = ''; + let index = 0; + let endBlockComment = string.indexOf('*/'); + while (index < string.length) { + if (string[index] === '/' && string[index+1] === '/') { + // inline comment + let endIndex = string.indexOf('\n', index); + index = (endIndex === -1) ? string.length : endIndex; + } else if ((endBlockComment !== -1) && (string[index] === '/') && (string[index+1] === '*')) { + // block comment + let endIndex = string.indexOf('*/', index); + if (endIndex !== -1) { + index = endIndex + 2; + endBlockComment = string.indexOf('*/', index); + } else { + stripped += string[index]; + index++; + } + } else { + stripped += string[index]; + index++; + } + } + return stripped; +} + +function parseParams(func) { + const src = stripComments(func.toString()); + let match = src.match(FN_ARGS); + if (!match) { + match = src.match(ARROW_FN_ARGS); + } + if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src) + let [, args] = match; + return args + .replace(/\s/g, '') + .split(FN_ARG_SPLIT) + .map((arg) => arg.replace(FN_ARG, '').trim()); +} + +/** + * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent + * tasks are specified as parameters to the function, after the usual callback + * parameter, with the parameter names matching the names of the tasks it + * depends on. This can provide even more readable task graphs which can be + * easier to maintain. + * + * If a final callback is specified, the task results are similarly injected, + * specified as named parameters after the initial error parameter. + * + * The autoInject function is purely syntactic sugar and its semantics are + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. + * + * @name autoInject + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.auto]{@link module:ControlFlow.auto} + * @category Control Flow + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of + * the form 'func([dependencies...], callback). The object's key of a property + * serves as the name of the task defined by that property, i.e. can be used + * when specifying requirements for other tasks. + * * The `callback` parameter is a `callback(err, result)` which must be called + * when finished, passing an `error` (which can be `null`) and the result of + * the function's execution. The remaining parameters name other tasks on + * which the task is dependent, and the results from those tasks are the + * arguments of those parameters. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback, and a `results` object with any completed + * task results, similar to `auto`. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // The example from `auto` can be rewritten as follows: + * async.autoInject({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: function(get_data, make_folder, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }, + * email_link: function(write_file, callback) { + * // once the file is written let's email a link to it... + * // write_file contains the filename returned by write_file. + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * } + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + * + * // If you are using a JS minifier that mangles parameter names, `autoInject` + * // will not work with plain functions, since the parameter names will be + * // collapsed to a single letter identifier. To work around this, you can + * // explicitly specify the names of the parameters your task function needs + * // in an array, similar to Angular.js dependency injection. + * + * // This still has an advantage over plain `auto`, since the results a task + * // depends on are still spread into arguments. + * async.autoInject({ + * //... + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(write_file, callback) { + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * }] + * //... + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + */ +function autoInject(tasks, callback) { + var newTasks = {}; + + Object.keys(tasks).forEach(key => { + var taskFn = tasks[key]; + var params; + var fnIsAsync = isAsync(taskFn); + var hasNoDeps = + (!fnIsAsync && taskFn.length === 1) || + (fnIsAsync && taskFn.length === 0); + + if (Array.isArray(taskFn)) { + params = [...taskFn]; + taskFn = params.pop(); + + newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); + } else if (hasNoDeps) { + // no dependencies, use the function as-is + newTasks[key] = taskFn; + } else { + params = parseParams(taskFn); + if ((taskFn.length === 0 && !fnIsAsync) && params.length === 0) { + throw new Error("autoInject task functions require explicit parameters."); + } + + // remove callback param + if (!fnIsAsync) params.pop(); + + newTasks[key] = params.concat(newTask); + } + + function newTask(results, taskCb) { + var newArgs = params.map(name => results[name]); + newArgs.push(taskCb); + wrapAsync(taskFn)(...newArgs); + } + }); + + return auto(newTasks, callback); +} + +// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation +// used for queues. This implementation assumes that the node provided by the user can be modified +// to adjust the next and last properties. We implement only the minimal functionality +// for queue support. +class DLL { + constructor() { + this.head = this.tail = null; + this.length = 0; + } + + removeLink(node) { + if (node.prev) node.prev.next = node.next; + else this.head = node.next; + if (node.next) node.next.prev = node.prev; + else this.tail = node.prev; + + node.prev = node.next = null; + this.length -= 1; + return node; + } + + empty () { + while(this.head) this.shift(); + return this; + } + + insertAfter(node, newNode) { + newNode.prev = node; + newNode.next = node.next; + if (node.next) node.next.prev = newNode; + else this.tail = newNode; + node.next = newNode; + this.length += 1; + } + + insertBefore(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode; + else this.head = newNode; + node.prev = newNode; + this.length += 1; + } + + unshift(node) { + if (this.head) this.insertBefore(this.head, node); + else setInitial(this, node); + } + + push(node) { + if (this.tail) this.insertAfter(this.tail, node); + else setInitial(this, node); + } + + shift() { + return this.head && this.removeLink(this.head); + } + + pop() { + return this.tail && this.removeLink(this.tail); + } + + toArray() { + return [...this] + } + + *[Symbol.iterator] () { + var cur = this.head; + while (cur) { + yield cur.data; + cur = cur.next; + } + } + + remove (testFn) { + var curr = this.head; + while(curr) { + var {next} = curr; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; + } +} + +function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; +} + +function queue$1(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new RangeError('Concurrency must not be zero'); + } + + var _worker = wrapAsync(worker); + var numRunning = 0; + var workersList = []; + const events = { + error: [], + drain: [], + saturated: [], + unsaturated: [], + empty: [] + }; + + function on (event, handler) { + events[event].push(handler); + } + + function once (event, handler) { + const handleAndRemove = (...args) => { + off(event, handleAndRemove); + handler(...args); + }; + events[event].push(handleAndRemove); + } + + function off (event, handler) { + if (!event) return Object.keys(events).forEach(ev => events[ev] = []) + if (!handler) return events[event] = [] + events[event] = events[event].filter(ev => ev !== handler); + } + + function trigger (event, ...args) { + events[event].forEach(handler => handler(...args)); + } + + var processingScheduled = false; + function _insert(data, insertAtFront, rejectOnError, callback) { + if (callback != null && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + + var res, rej; + function promiseCallback (err, ...args) { + // we don't care about the error, let the global error handler + // deal with it + if (err) return rejectOnError ? rej(err) : res() + if (args.length <= 1) return res(args[0]) + res(args); + } + + var item = q._createTaskItem( + data, + rejectOnError ? promiseCallback : + (callback || promiseCallback) + ); + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + if (!processingScheduled) { + processingScheduled = true; + setImmediate$1(() => { + processingScheduled = false; + q.process(); + }); + } + + if (rejectOnError || !callback) { + return new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }) + } + } + + function _createCB(tasks) { + return function (err, ...args) { + numRunning -= 1; + + for (var i = 0, l = tasks.length; i < l; i++) { + var task = tasks[i]; + + var index = workersList.indexOf(task); + if (index === 0) { + workersList.shift(); + } else if (index > 0) { + workersList.splice(index, 1); + } + + task.callback(err, ...args); + + if (err != null) { + trigger('error', err, task.data); + } + } + + if (numRunning <= (q.concurrency - q.buffer) ) { + trigger('unsaturated'); + } + + if (q.idle()) { + trigger('drain'); + } + q.process(); + }; + } + + function _maybeDrain(data) { + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + setImmediate$1(() => trigger('drain')); + return true + } + return false + } + + const eventMethod = (name) => (handler) => { + if (!handler) { + return new Promise((resolve, reject) => { + once(name, (err, data) => { + if (err) return reject(err) + resolve(data); + }); + }) + } + off(name); + on(name, handler); + + }; + + var isProcessing = false; + var q = { + _tasks: new DLL(), + _createTaskItem (data, callback) { + return { + data, + callback + }; + }, + *[Symbol.iterator] () { + yield* q._tasks[Symbol.iterator](); + }, + concurrency, + payload, + buffer: concurrency / 4, + started: false, + paused: false, + push (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, false, callback)) + } + return _insert(data, false, false, callback); + }, + pushAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, true, callback)) + } + return _insert(data, false, true, callback); + }, + kill () { + off(); + q._tasks.empty(); + }, + unshift (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, false, callback)) + } + return _insert(data, true, false, callback); + }, + unshiftAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, true, callback)) + } + return _insert(data, true, true, callback); + }, + remove (testFn) { + q._tasks.remove(testFn); + }, + process () { + // Avoid trying to start too many processing operations. This can occur + // when callbacks resolve synchronously (#1267). + if (isProcessing) { + return; + } + isProcessing = true; + while(!q.paused && numRunning < q.concurrency && q._tasks.length){ + var tasks = [], data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); + tasks.push(node); + workersList.push(node); + data.push(node.data); + } + + numRunning += 1; + + if (q._tasks.length === 0) { + trigger('empty'); + } + + if (numRunning === q.concurrency) { + trigger('saturated'); + } + + var cb = onlyOnce(_createCB(tasks)); + _worker(data, cb); + } + isProcessing = false; + }, + length () { + return q._tasks.length; + }, + running () { + return numRunning; + }, + workersList () { + return workersList; + }, + idle() { + return q._tasks.length + numRunning === 0; + }, + pause () { + q.paused = true; + }, + resume () { + if (q.paused === false) { return; } + q.paused = false; + setImmediate$1(q.process); + } + }; + // define these as fixed properties, so people get useful errors when updating + Object.defineProperties(q, { + saturated: { + writable: false, + value: eventMethod('saturated') + }, + unsaturated: { + writable: false, + value: eventMethod('unsaturated') + }, + empty: { + writable: false, + value: eventMethod('empty') + }, + drain: { + writable: false, + value: eventMethod('drain') + }, + error: { + writable: false, + value: eventMethod('error') + }, + }); + return q; +} + +/** + * Creates a `cargo` object with the specified payload. Tasks added to the + * cargo will be processed altogether (up to the `payload` limit). If the + * `worker` is in progress, the task is queued until it becomes available. Once + * the `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, cargo passes an array of tasks to a single worker, repeating + * when the worker is finished. + * + * @name cargo + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargo and inner queue. + * @example + * + * // create a cargo object with payload 2 + * var cargo = async.cargo(function(tasks, callback) { + * for (var i=0; i { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.reduce(fileList, 0, getFileSizeInBytes); + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function reduce(coll, memo, iteratee, callback) { + callback = once(callback); + var _iteratee = wrapAsync(iteratee); + return eachOfSeries$1(coll, (x, i, iterCb) => { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); +} +var reduce$1 = awaitify(reduce, 4); + +/** + * Version of the compose function that is more natural to read. Each function + * consumes the return value of the previous function. It is the equivalent of + * [compose]{@link module:ControlFlow.compose} with the arguments reversed. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name seq + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.compose]{@link module:ControlFlow.compose} + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} a function that composes the `functions` in order + * @example + * + * // Requires lodash (or underscore), express3 and dresende's orm2. + * // Part of an app, that fetches cats of the logged user. + * // This example uses `seq` function to avoid overnesting and error + * // handling clutter. + * app.get('/cats', function(request, response) { + * var User = request.models.User; + * async.seq( + * User.get.bind(User), // 'User.get' has signature (id, callback(err, data)) + * function(user, fn) { + * user.getCats(fn); // 'getCats' has signature (callback(err, data)) + * } + * )(req.session.user_id, function (err, cats) { + * if (err) { + * console.error(err); + * response.json({ status: 'error', message: err.message }); + * } else { + * response.json({ status: 'ok', message: 'Cats found', data: cats }); + * } + * }); + * }); + */ +function seq(...functions) { + var _functions = functions.map(wrapAsync); + return function (...args) { + var that = this; + + var cb = args[args.length - 1]; + if (typeof cb == 'function') { + args.pop(); + } else { + cb = promiseCallback(); + } + + reduce$1(_functions, args, (newargs, fn, iterCb) => { + fn.apply(that, newargs.concat((err, ...nextargs) => { + iterCb(err, nextargs); + })); + }, + (err, results) => cb(err, ...results)); + + return cb[PROMISE_SYMBOL] + }; +} + +/** + * Creates a function which is a composition of the passed asynchronous + * functions. Each function consumes the return value of the function that + * follows. Composing functions `f()`, `g()`, and `h()` would produce the result + * of `f(g(h()))`, only this version uses callbacks to obtain the return values. + * + * If the last argument to the composed function is not a function, a promise + * is returned when you call it. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name compose + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} an asynchronous function that is the composed + * asynchronous `functions` + * @example + * + * function add1(n, callback) { + * setTimeout(function () { + * callback(null, n + 1); + * }, 10); + * } + * + * function mul3(n, callback) { + * setTimeout(function () { + * callback(null, n * 3); + * }, 10); + * } + * + * var add1mul3 = async.compose(mul3, add1); + * add1mul3(4, function (err, result) { + * // result now equals 15 + * }); + */ +function compose(...args) { + return seq(...args.reverse()); +} + +/** + * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. + * + * @name mapLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function mapLimit (coll, limit, iteratee, callback) { + return _asyncMap(eachOfLimit$2(limit), coll, iteratee, callback) +} +var mapLimit$1 = awaitify(mapLimit, 4); + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. + * + * @name concatLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapLimit + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, ...args) => { + if (err) return iterCb(err); + return iterCb(err, args); + }); + }, (err, mapResults) => { + var result = []; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + result = result.concat(...mapResults[i]); + } + } + + return callback(err, result); + }); +} +var concatLimit$1 = awaitify(concatLimit, 4); + +/** + * Applies `iteratee` to each item in `coll`, concatenating the results. Returns + * the concatenated list. The `iteratee`s are called in parallel, and the + * results are concatenated as they return. The results array will be returned in + * the original order of `coll` passed to the `iteratee` function. + * + * @name concat + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @alias flatMap + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * let directoryList = ['dir1','dir2','dir3']; + * let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4']; + * + * // Using callbacks + * async.concat(directoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.concat(directoryList, fs.readdir) + * .then(results => { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir) + * .then(results => { + * console.log(results); + * }).catch(err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.concat(directoryList, fs.readdir); + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.concat(withMissingDirectoryList, fs.readdir); + * console.log(results); + * } catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } + * } + * + */ +function concat(coll, iteratee, callback) { + return concatLimit$1(coll, Infinity, iteratee, callback) +} +var concat$1 = awaitify(concat, 3); + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * + * @name concatSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapSeries + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. + * The iteratee should complete with an array an array of results. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatSeries(coll, iteratee, callback) { + return concatLimit$1(coll, 1, iteratee, callback) +} +var concatSeries$1 = awaitify(concatSeries, 3); + +/** + * Returns a function that when called, calls-back with the values provided. + * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to + * [`auto`]{@link module:ControlFlow.auto}. + * + * @name constant + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {...*} arguments... - Any number of arguments to automatically invoke + * callback with. + * @returns {AsyncFunction} Returns a function that when invoked, automatically + * invokes the callback with the previous given arguments. + * @example + * + * async.waterfall([ + * async.constant(42), + * function (value, next) { + * // value === 42 + * }, + * //... + * ], callback); + * + * async.waterfall([ + * async.constant(filename, "utf8"), + * fs.readFile, + * function (fileData, next) { + * //... + * } + * //... + * ], callback); + * + * async.auto({ + * hostname: async.constant("https://server.net/"), + * port: findFreePort, + * launchServer: ["hostname", "port", function (options, cb) { + * startServer(options, cb); + * }], + * //... + * }, callback); + */ +function constant$1(...args) { + return function (...ignoredArgs/*, callback*/) { + var callback = ignoredArgs.pop(); + return callback(null, ...args); + }; +} + +function _createTester(check, getResult) { + return (eachfn, arr, _iteratee, cb) => { + var testPassed = false; + var testResult; + const iteratee = wrapAsync(_iteratee); + eachfn(arr, (value, _, callback) => { + iteratee(value, (err, result) => { + if (err || err === false) return callback(err); + + if (check(result) && !testResult) { + testPassed = true; + testResult = getResult(true, value); + return callback(null, breakLoop); + } + callback(); + }); + }, err => { + if (err) return cb(err); + cb(null, testPassed ? testResult : getResult(false)); + }); + }; +} + +/** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. + + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * } + *); + * + * // Using Promises + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists) + * .then(result => { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); + * console.log(result); + * // dir1/file1.txt + * // result now equals the file in the list that exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function detect(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback) +} +var detect$1 = awaitify(detect, 3); + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ +function detectLimit(coll, limit, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(limit), coll, iteratee, callback) +} +var detectLimit$1 = awaitify(detectLimit, 4); + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ +function detectSeries(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(1), coll, iteratee, callback) +} + +var detectSeries$1 = awaitify(detectSeries, 3); + +function consoleFunc(name) { + return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => { + /* istanbul ignore else */ + if (typeof console === 'object') { + /* istanbul ignore else */ + if (err) { + /* istanbul ignore else */ + if (console.error) { + console.error(err); + } + } else if (console[name]) { /* istanbul ignore else */ + resultArgs.forEach(x => console[name](x)); + } + } + }) +} + +/** + * Logs the result of an [`async` function]{@link AsyncFunction} to the + * `console` using `console.dir` to display the properties of the resulting object. + * Only works in Node.js or in browsers that support `console.dir` and + * `console.error` (such as FF and Chrome). + * If multiple arguments are returned from the async function, + * `console.dir` is called on each argument in order. + * + * @name dir + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, {hello: name}); + * }, 1000); + * }; + * + * // in the node repl + * node> async.dir(hello, 'world'); + * {hello: 'world'} + */ +var dir = consoleFunc('dir'); + +/** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ +function doWhilst(iteratee, test, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results; + + function next(err, ...args) { + if (err) return callback(err); + if (err === false) return; + results = args; + _test(...args, check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return check(null, true); +} + +var doWhilst$1 = awaitify(doWhilst, 3); + +/** + * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the + * argument ordering differs from `until`. + * + * @name doUntil + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee` + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ +function doUntil(iteratee, test, callback) { + const _test = wrapAsync(test); + return doWhilst$1(iteratee, (...args) => { + const cb = args.pop(); + _test(...args, (err, truth) => cb (err, !truth)); + }, callback); +} + +function _withoutIndex(iteratee) { + return (value, index, callback) => iteratee(value, callback); +} + +/** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt']; + * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt']; + * + * // asynchronous function that deletes a file + * const deleteFile = function(file, callback) { + * fs.unlink(file, callback); + * }; + * + * // Using callbacks + * async.each(fileList, deleteFile, function(err) { + * if( err ) { + * console.log(err); + * } else { + * console.log('All files have been deleted successfully'); + * } + * }); + * + * // Error Handling + * async.each(withMissingFileList, deleteFile, function(err){ + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using Promises + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using async/await + * async () => { + * try { + * await async.each(files, deleteFile); + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * await async.each(withMissingFileList, deleteFile); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * } + * } + * + */ +function eachLimit$2(coll, iteratee, callback) { + return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback); +} + +var each = awaitify(eachLimit$2, 3); + +/** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachLimit(coll, limit, iteratee, callback) { + return eachOfLimit$2(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); +} +var eachLimit$1 = awaitify(eachLimit, 4); + +/** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item + * in series and therefore the iteratee functions will complete in order. + + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachSeries(coll, iteratee, callback) { + return eachLimit$1(coll, 1, iteratee, callback) +} +var eachSeries$1 = awaitify(eachSeries, 3); + +/** + * Wrap an async function and ensure it calls its callback on a later tick of + * the event loop. If the function already calls its callback on a next tick, + * no extra deferral is added. This is useful for preventing stack overflows + * (`RangeError: Maximum call stack size exceeded`) and generally keeping + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + * contained. ES2017 `async` functions are returned as-is -- they are immune + * to Zalgo's corrupting influences, as they always resolve on a later tick. + * + * @name ensureAsync + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - an async function, one that expects a node-style + * callback as its last argument. + * @returns {AsyncFunction} Returns a wrapped function with the exact same call + * signature as the function passed in. + * @example + * + * function sometimesAsync(arg, callback) { + * if (cache[arg]) { + * return callback(null, cache[arg]); // this would be synchronous!! + * } else { + * doSomeIO(arg, callback); // this IO would be asynchronous + * } + * } + * + * // this has a risk of stack overflows if many results are cached in a row + * async.mapSeries(args, sometimesAsync, done); + * + * // this will defer sometimesAsync's callback if necessary, + * // preventing stack overflows + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + */ +function ensureAsync(fn) { + if (isAsync(fn)) return fn; + return function (...args/*, callback*/) { + var callback = args.pop(); + var sync = true; + args.push((...innerArgs) => { + if (sync) { + setImmediate$1(() => callback(...innerArgs)); + } else { + callback(...innerArgs); + } + }); + fn.apply(this, args); + sync = false; + }; +} + +/** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.every(fileList, fileExists, function(err, result) { + * console.log(result); + * // true + * // result is true since every file exists + * }); + * + * async.every(withMissingFileList, fileExists, function(err, result) { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }); + * + * // Using Promises + * async.every(fileList, fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.every(withMissingFileList, fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.every(fileList, fileExists); + * console.log(result); + * // true + * // result is true since every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.every(withMissingFileList, fileExists); + * console.log(result); + * // false + * // result is false since NOT every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function every(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback) +} +var every$1 = awaitify(every, 3); + +/** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everyLimit(coll, limit, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfLimit$2(limit), coll, iteratee, callback) +} +var everyLimit$1 = awaitify(everyLimit, 4); + +/** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everySeries(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback) +} +var everySeries$1 = awaitify(everySeries, 3); + +function filterArray(eachfn, arr, iteratee, callback) { + var truthValues = new Array(arr.length); + eachfn(arr, (x, index, iterCb) => { + iteratee(x, (err, v) => { + truthValues[index] = !!v; + iterCb(err); + }); + }, err => { + if (err) return callback(err); + var results = []; + for (var i = 0; i < arr.length; i++) { + if (truthValues[i]) results.push(arr[i]); + } + callback(null, results); + }); +} + +function filterGeneric(eachfn, coll, iteratee, callback) { + var results = []; + eachfn(coll, (x, index, iterCb) => { + iteratee(x, (err, v) => { + if (err) return iterCb(err); + if (v) { + results.push({index, value: x}); + } + iterCb(err); + }); + }, err => { + if (err) return callback(err); + callback(null, results + .sort((a, b) => a.index - b.index) + .map(v => v.value)); + }); +} + +function _filter(eachfn, coll, iteratee, callback) { + var filter = isArrayLike(coll) ? filterArray : filterGeneric; + return filter(eachfn, coll, wrapAsync(iteratee), callback); +} + +/** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.filter(files, fileExists, function(err, results) { + * if(err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * }); + * + * // Using Promises + * async.filter(files, fileExists) + * .then(results => { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.filter(files, fileExists); + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function filter (coll, iteratee, callback) { + return _filter(eachOf$1, coll, iteratee, callback) +} +var filter$1 = awaitify(filter, 3); + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + */ +function filterLimit (coll, limit, iteratee, callback) { + return _filter(eachOfLimit$2(limit), coll, iteratee, callback) +} +var filterLimit$1 = awaitify(filterLimit, 4); + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + * @returns {Promise} a promise, if no callback provided + */ +function filterSeries (coll, iteratee, callback) { + return _filter(eachOfSeries$1, coll, iteratee, callback) +} +var filterSeries$1 = awaitify(filterSeries, 3); + +/** + * Calls the asynchronous function `fn` with a callback parameter that allows it + * to call itself again, in series, indefinitely. + + * If an error is passed to the callback then `errback` is called with the + * error, and execution stops, otherwise it will never be called. + * + * @name forever + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} fn - an async function to call repeatedly. + * Invoked with (next). + * @param {Function} [errback] - when `fn` passes an error to it's callback, + * this function will be called, and execution stops. Invoked with (err). + * @returns {Promise} a promise that rejects if an error occurs and an errback + * is not passed + * @example + * + * async.forever( + * function(next) { + * // next is suitable for passing to things that need a callback(err [, whatever]); + * // it will result in this function being called again. + * }, + * function(err) { + * // if next is called with a value in its first parameter, it will appear + * // in here as 'err', and execution will stop. + * } + * ); + */ +function forever(fn, errback) { + var done = onlyOnce(errback); + var task = wrapAsync(ensureAsync(fn)); + + function next(err) { + if (err) return done(err); + if (err === false) return; + task(next); + } + return next(); +} +var forever$1 = awaitify(forever, 2); + +/** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. + * + * @name groupByLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ +function groupByLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, key) => { + if (err) return iterCb(err); + return iterCb(err, {key, val}); + }); + }, (err, mapResults) => { + var result = {}; + // from MDN, handle object having an `hasOwnProperty` prop + var {hasOwnProperty} = Object.prototype; + + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + var {key} = mapResults[i]; + var {val} = mapResults[i]; + + if (hasOwnProperty.call(result, key)) { + result[key].push(val); + } else { + result[key] = [val]; + } + } + } + + return callback(err, result); + }); +} + +var groupByLimit$1 = awaitify(groupByLimit, 4); + +/** + * Returns a new object, where each value corresponds to an array of items, from + * `coll`, that returned the corresponding key. That is, the keys of the object + * correspond to the values passed to the `iteratee` callback. + * + * Note: Since this function applies the `iteratee` to each item in parallel, + * there is no guarantee that the `iteratee` functions will complete in order. + * However, the values for each key in the `result` will be in the same order as + * the original `coll`. For Objects, the values will roughly be in the order of + * the original Objects' keys (but this can vary across JavaScript engines). + * + * @name groupBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const files = ['dir1/file1.txt','dir2','dir4'] + * + * // asynchronous function that detects file type as none, file, or directory + * function detectFile(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(null, 'none'); + * } + * callback(null, stat.isDirectory() ? 'directory' : 'file'); + * }); + * } + * + * //Using callbacks + * async.groupBy(files, detectFile, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * }); + * + * // Using Promises + * async.groupBy(files, detectFile) + * .then( result => { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.groupBy(files, detectFile); + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function groupBy (coll, iteratee, callback) { + return groupByLimit$1(coll, Infinity, iteratee, callback) +} + +/** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. + * + * @name groupBySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whose + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ +function groupBySeries (coll, iteratee, callback) { + return groupByLimit$1(coll, 1, iteratee, callback) +} + +/** + * Logs the result of an `async` function to the `console`. Only works in + * Node.js or in browsers that support `console.log` and `console.error` (such + * as FF and Chrome). If multiple arguments are returned from the async + * function, `console.log` is called on each argument in order. + * + * @name log + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, 'hello ' + name); + * }, 1000); + * }; + * + * // in the node repl + * node> async.log(hello, 'world'); + * 'hello world' + */ +var log = consoleFunc('log'); + +/** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a + * time. + * + * @name mapValuesLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function mapValuesLimit(obj, limit, iteratee, callback) { + callback = once(callback); + var newObj = {}; + var _iteratee = wrapAsync(iteratee); + return eachOfLimit$2(limit)(obj, (val, key, next) => { + _iteratee(val, key, (err, result) => { + if (err) return next(err); + newObj[key] = result; + next(err); + }); + }, err => callback(err, newObj)); +} + +var mapValuesLimit$1 = awaitify(mapValuesLimit, 4); + +/** + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. + * + * Produces a new Object by mapping each value of `obj` through the `iteratee` + * function. The `iteratee` is called each `value` and `key` from `obj` and a + * callback for when it has finished processing. Each of these callbacks takes + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` + * passes an error to its callback, the main `callback` (for the `mapValues` + * function) is immediately called with the error. + * + * Note, the order of the keys in the result is not guaranteed. The keys will + * be roughly in the order they complete, (but this is very engine-specific) + * + * @name mapValues + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file3.txt' + * }; + * + * const withMissingFileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file4.txt' + * }; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, key, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.mapValues(fileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * }); + * + * // Error handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.mapValues(fileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * }).catch (err => { + * console.log(err); + * }); + * + * // Error Handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch (err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.mapValues(fileMap, getFileSizeInBytes); + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function mapValues(obj, iteratee, callback) { + return mapValuesLimit$1(obj, Infinity, iteratee, callback) +} + +/** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. + * + * @name mapValuesSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function mapValuesSeries(obj, iteratee, callback) { + return mapValuesLimit$1(obj, 1, iteratee, callback) +} + +/** + * Caches the results of an async function. When creating a hash to store + * function results against, the callback is omitted from the hash and an + * optional hash function can be used. + * + * **Note: if the async function errs, the result will not be cached and + * subsequent calls will call the wrapped function.** + * + * If no hash function is specified, the first argument is used as a hash key, + * which may work reasonably if it is a string or a data type that converts to a + * distinct string. Note that objects and arrays will not behave reasonably. + * Neither will cases where the other arguments are significant. In such cases, + * specify your own hash function. + * + * The cache of results is exposed as the `memo` property of the function + * returned by `memoize`. + * + * @name memoize + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function to proxy and cache results from. + * @param {Function} hasher - An optional function for generating a custom hash + * for storing results. It has all the arguments applied to it apart from the + * callback, and must be synchronous. + * @returns {AsyncFunction} a memoized version of `fn` + * @example + * + * var slow_fn = function(name, callback) { + * // do something + * callback(null, result); + * }; + * var fn = async.memoize(slow_fn); + * + * // fn can now be used as if it were slow_fn + * fn('some name', function() { + * // callback + * }); + */ +function memoize(fn, hasher = v => v) { + var memo = Object.create(null); + var queues = Object.create(null); + var _fn = wrapAsync(fn); + var memoized = initialParams((args, callback) => { + var key = hasher(...args); + if (key in memo) { + setImmediate$1(() => callback(null, ...memo[key])); + } else if (key in queues) { + queues[key].push(callback); + } else { + queues[key] = [callback]; + _fn(...args, (err, ...resultArgs) => { + // #1465 don't memoize if an error occurred + if (!err) { + memo[key] = resultArgs; + } + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i](err, ...resultArgs); + } + }); + } + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; +} + +/* istanbul ignore file */ + +/** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `process.nextTick`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name nextTick + * @static + * @memberOf module:Utils + * @method + * @see [async.setImmediate]{@link module:Utils.setImmediate} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ +var _defer; + +if (hasNextTick) { + _defer = process.nextTick; +} else if (hasSetImmediate) { + _defer = setImmediate; +} else { + _defer = fallback; +} + +var nextTick = wrap(_defer); + +var _parallel = awaitify((eachfn, tasks, callback) => { + var results = isArrayLike(tasks) ? [] : {}; + + eachfn(tasks, (task, key, taskCb) => { + wrapAsync(task)((err, ...result) => { + if (result.length < 2) { + [result] = result; + } + results[key] = result; + taskCb(err); + }); + }, err => callback(err, results)); +}, 3); + +/** + * Run the `tasks` collection of functions in parallel, without waiting until + * the previous function has completed. If any of the functions pass an error to + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * + * //Using Callbacks + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function parallel(tasks, callback) { + return _parallel(eachOf$1, tasks, callback); +} + +/** + * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a + * time. + * + * @name parallelLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.parallel]{@link module:ControlFlow.parallel} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + */ +function parallelLimit(tasks, limit, callback) { + return _parallel(eachOfLimit$2(limit), tasks, callback); +} + +/** + * A queue of tasks for the worker function to complete. + * @typedef {Iterable} QueueObject + * @memberOf module:ControlFlow + * @property {Function} length - a function returning the number of items + * waiting to be processed. Invoke with `queue.length()`. + * @property {boolean} started - a boolean indicating whether or not any + * items have been pushed and processed by the queue. + * @property {Function} running - a function returning the number of items + * currently being processed. Invoke with `queue.running()`. + * @property {Function} workersList - a function returning the array of items + * currently being processed. Invoke with `queue.workersList()`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke with `queue.idle()`. + * @property {number} concurrency - an integer for determining how many `worker` + * functions should be run in parallel. This property can be changed after a + * `queue` is created to alter the concurrency on-the-fly. + * @property {number} payload - an integer that specifies how many items are + * passed to the worker function at a time. only applies if this is a + * [cargo]{@link module:ControlFlow.cargo} object + * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback` + * once the `worker` has finished processing the task. Instead of a single task, + * a `tasks` array can be submitted. The respective callback is used for every + * task in the list. Invoke with `queue.push(task, [callback])`, + * @property {AsyncFunction} unshift - add a new task to the front of the `queue`. + * Invoke with `queue.unshift(task, [callback])`. + * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns + * a promise that rejects if an error occurs. + * @property {AsyncFunction} unshiftAsync - the same as `q.unshift`, except this returns + * a promise that rejects if an error occurs. + * @property {Function} remove - remove items from the queue that match a test + * function. The test function will be passed an object with a `data` property, + * and a `priority` property, if this is a + * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. + * Invoked with `queue.remove(testFn)`, where `testFn` is of the form + * `function ({data, priority}) {}` and returns a Boolean. + * @property {Function} saturated - a function that sets a callback that is + * called when the number of running workers hits the `concurrency` limit, and + * further tasks will be queued. If the callback is omitted, `q.saturated()` + * returns a promise for the next occurrence. + * @property {Function} unsaturated - a function that sets a callback that is + * called when the number of running workers is less than the `concurrency` & + * `buffer` limits, and further tasks will not be queued. If the callback is + * omitted, `q.unsaturated()` returns a promise for the next occurrence. + * @property {number} buffer - A minimum threshold buffer in order to say that + * the `queue` is `unsaturated`. + * @property {Function} empty - a function that sets a callback that is called + * when the last item from the `queue` is given to a `worker`. If the callback + * is omitted, `q.empty()` returns a promise for the next occurrence. + * @property {Function} drain - a function that sets a callback that is called + * when the last item from the `queue` has returned from the `worker`. If the + * callback is omitted, `q.drain()` returns a promise for the next occurrence. + * @property {Function} error - a function that sets a callback that is called + * when a task errors. Has the signature `function(error, task)`. If the + * callback is omitted, `error()` returns a promise that rejects on the next + * error. + * @property {boolean} paused - a boolean for determining whether the queue is + * in a paused state. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke with `queue.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke with `queue.resume()`. + * @property {Function} kill - a function that removes the `drain` callback and + * empties remaining tasks from the queue forcing it to go idle. No more tasks + * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. + * + * @example + * const q = async.queue(worker, 2) + * q.push(item1) + * q.push(item2) + * q.push(item3) + * // queues are iterable, spread into an array to inspect + * const items = [...q] // [item1, item2, item3] + * // or use for of + * for (let item of q) { + * console.log(item) + * } + * + * q.drain(() => { + * console.log('all done') + * }) + * // or + * await q.drain() + */ + +/** + * Creates a `queue` object with the specified `concurrency`. Tasks added to the + * `queue` are processed in parallel (up to the `concurrency` limit). If all + * `worker`s are in progress, the task is queued until one becomes available. + * Once a `worker` completes a `task`, that `task`'s callback is called. + * + * @name queue + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. Invoked with (task, callback). + * @param {number} [concurrency=1] - An `integer` for determining how many + * `worker` functions should be run in parallel. If omitted, the concurrency + * defaults to `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be + * attached as certain properties to listen for specific events during the + * lifecycle of the queue. + * @example + * + * // create a queue object with concurrency 2 + * var q = async.queue(function(task, callback) { + * console.log('hello ' + task.name); + * callback(); + * }, 2); + * + * // assign a callback + * q.drain(function() { + * console.log('all items have been processed'); + * }); + * // or await the end + * await q.drain() + * + * // assign an error callback + * q.error(function(err, task) { + * console.error('task experienced an error'); + * }); + * + * // add some items to the queue + * q.push({name: 'foo'}, function(err) { + * console.log('finished processing foo'); + * }); + * // callback is optional + * q.push({name: 'bar'}); + * + * // add some items to the queue (batch-wise) + * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { + * console.log('finished processing item'); + * }); + * + * // add some items to the front of the queue + * q.unshift({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + */ +function queue (worker, concurrency) { + var _worker = wrapAsync(worker); + return queue$1((items, cb) => { + _worker(items[0], cb); + }, concurrency, 1); +} + +// Binary min-heap implementation used for priority queue. +// Implementation is stable, i.e. push time is considered for equal priorities +class Heap { + constructor() { + this.heap = []; + this.pushCount = Number.MIN_SAFE_INTEGER; + } + + get length() { + return this.heap.length; + } + + empty () { + this.heap = []; + return this; + } + + percUp(index) { + let p; + + while (index > 0 && smaller(this.heap[index], this.heap[p=parent(index)])) { + let t = this.heap[index]; + this.heap[index] = this.heap[p]; + this.heap[p] = t; + + index = p; + } + } + + percDown(index) { + let l; + + while ((l=leftChi(index)) < this.heap.length) { + if (l+1 < this.heap.length && smaller(this.heap[l+1], this.heap[l])) { + l = l+1; + } + + if (smaller(this.heap[index], this.heap[l])) { + break; + } + + let t = this.heap[index]; + this.heap[index] = this.heap[l]; + this.heap[l] = t; + + index = l; + } + } + + push(node) { + node.pushCount = ++this.pushCount; + this.heap.push(node); + this.percUp(this.heap.length-1); + } + + unshift(node) { + return this.heap.push(node); + } + + shift() { + let [top] = this.heap; + + this.heap[0] = this.heap[this.heap.length-1]; + this.heap.pop(); + this.percDown(0); + + return top; + } + + toArray() { + return [...this]; + } + + *[Symbol.iterator] () { + for (let i = 0; i < this.heap.length; i++) { + yield this.heap[i].data; + } + } + + remove (testFn) { + let j = 0; + for (let i = 0; i < this.heap.length; i++) { + if (!testFn(this.heap[i])) { + this.heap[j] = this.heap[i]; + j++; + } + } + + this.heap.splice(j); + + for (let i = parent(this.heap.length-1); i >= 0; i--) { + this.percDown(i); + } + + return this; + } +} + +function leftChi(i) { + return (i<<1)+1; +} + +function parent(i) { + return ((i+1)>>1)-1; +} + +function smaller(x, y) { + if (x.priority !== y.priority) { + return x.priority < y.priority; + } + else { + return x.pushCount < y.pushCount; + } +} + +/** + * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and + * completed in ascending priority order. + * + * @name priorityQueue + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. + * Invoked with (task, callback). + * @param {number} concurrency - An `integer` for determining how many `worker` + * functions should be run in parallel. If omitted, the concurrency defaults to + * `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are three + * differences between `queue` and `priorityQueue` objects: + * * `push(task, priority, [callback])` - `priority` should be a number. If an + * array of `tasks` is given, all tasks will be assigned the same priority. + * * `pushAsync(task, priority, [callback])` - the same as `priorityQueue.push`, + * except this returns a promise that rejects if an error occurs. + * * The `unshift` and `unshiftAsync` methods were removed. + */ +function priorityQueue(worker, concurrency) { + // Start with a normal queue + var q = queue(worker, concurrency); + + var { + push, + pushAsync + } = q; + + q._tasks = new Heap(); + q._createTaskItem = ({data, priority}, callback) => { + return { + data, + priority, + callback + }; + }; + + function createDataItems(tasks, priority) { + if (!Array.isArray(tasks)) { + return {data: tasks, priority}; + } + return tasks.map(data => { return {data, priority}; }); + } + + // Override push to accept second parameter representing priority + q.push = function(data, priority = 0, callback) { + return push(createDataItems(data, priority), callback); + }; + + q.pushAsync = function(data, priority = 0, callback) { + return pushAsync(createDataItems(data, priority), callback); + }; + + // Remove unshift functions + delete q.unshift; + delete q.unshiftAsync; + + return q; +} + +/** + * Runs the `tasks` array of functions in parallel, without waiting until the + * previous function has completed. Once any of the `tasks` complete or pass an + * error to its callback, the main `callback` is immediately called. It's + * equivalent to `Promise.race()`. + * + * @name race + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} + * to run. Each function can complete with an optional `result` value. + * @param {Function} callback - A callback to run once any of the functions have + * completed. This function gets an error or result from the first function that + * completed. Invoked with (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.race([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // main callback + * function(err, result) { + * // the result will be equal to 'two' as it finishes earlier + * }); + */ +function race(tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); + if (!tasks.length) return callback(); + for (var i = 0, l = tasks.length; i < l; i++) { + wrapAsync(tasks[i])(callback); + } +} + +var race$1 = awaitify(race, 2); + +/** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function reduceRight (array, memo, iteratee, callback) { + var reversed = [...array].reverse(); + return reduce$1(reversed, memo, iteratee, callback); +} + +/** + * Wraps the async function in another function that always completes with a + * result object, even when it errors. + * + * The result object has either the property `error` or `value`. + * + * @name reflect + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function you want to wrap + * @returns {Function} - A function that always passes null to it's callback as + * the error. The second argument to the callback will be an `object` with + * either an `error` or a `value` property. + * @example + * + * async.parallel([ + * async.reflect(function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }), + * async.reflect(function(callback) { + * // do some more stuff but error ... + * callback('bad stuff happened'); + * }), + * async.reflect(function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * }) + * ], + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = 'bad stuff happened' + * // results[2].value = 'two' + * }); + */ +function reflect(fn) { + var _fn = wrapAsync(fn); + return initialParams(function reflectOn(args, reflectCallback) { + args.push((error, ...cbArgs) => { + let retVal = {}; + if (error) { + retVal.error = error; + } + if (cbArgs.length > 0){ + var value = cbArgs; + if (cbArgs.length <= 1) { + [value] = cbArgs; + } + retVal.value = value; + } + reflectCallback(null, retVal); + }); + + return _fn.apply(this, args); + }); +} + +/** + * A helper function that wraps an array or an object of functions with `reflect`. + * + * @name reflectAll + * @static + * @memberOf module:Utils + * @method + * @see [async.reflect]{@link module:Utils.reflect} + * @category Util + * @param {Array|Object|Iterable} tasks - The collection of + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. + * @returns {Array} Returns an array of async functions, each wrapped in + * `async.reflect` + * @example + * + * let tasks = [ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * // do some more stuff but error ... + * callback(new Error('bad stuff happened')); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = Error('bad stuff happened') + * // results[2].value = 'two' + * }); + * + * // an example using an object instead of an array + * let tasks = { + * one: function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * two: function(callback) { + * callback('two'); + * }, + * three: function(callback) { + * setTimeout(function() { + * callback(null, 'three'); + * }, 100); + * } + * }; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results.one.value = 'one' + * // results.two.error = 'two' + * // results.three.value = 'three' + * }); + */ +function reflectAll(tasks) { + var results; + if (Array.isArray(tasks)) { + results = tasks.map(reflect); + } else { + results = {}; + Object.keys(tasks).forEach(key => { + results[key] = reflect.call(this, tasks[key]); + }); + } + return results; +} + +function reject$2(eachfn, arr, _iteratee, callback) { + const iteratee = wrapAsync(_iteratee); + return _filter(eachfn, arr, (value, cb) => { + iteratee(value, (err, v) => { + cb(err, !v); + }); + }, callback); +} + +/** + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. + * + * @name reject + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.reject(fileList, fileExists, function(err, results) { + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }); + * + * // Using Promises + * async.reject(fileList, fileExists) + * .then( results => { + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.reject(fileList, fileExists); + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function reject (coll, iteratee, callback) { + return reject$2(eachOf$1, coll, iteratee, callback) +} +var reject$1 = awaitify(reject, 3); + +/** + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a + * time. + * + * @name rejectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function rejectLimit (coll, limit, iteratee, callback) { + return reject$2(eachOfLimit$2(limit), coll, iteratee, callback) +} +var rejectLimit$1 = awaitify(rejectLimit, 4); + +/** + * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. + * + * @name rejectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function rejectSeries (coll, iteratee, callback) { + return reject$2(eachOfSeries$1, coll, iteratee, callback) +} +var rejectSeries$1 = awaitify(rejectSeries, 3); + +function constant(value) { + return function () { + return value; + } +} + +/** + * Attempts to get a successful response from `task` no more than `times` times + * before returning an error. If the task is successful, the `callback` will be + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * @returns {Promise} a promise if no callback provided + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ +const DEFAULT_TIMES = 5; +const DEFAULT_INTERVAL = 0; + +function retry(opts, task, callback) { + var options = { + times: DEFAULT_TIMES, + intervalFunc: constant(DEFAULT_INTERVAL) + }; + + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || promiseCallback(); + task = opts; + } else { + parseTimes(options, opts); + callback = callback || promiseCallback(); + } + + if (typeof task !== 'function') { + throw new Error("Invalid arguments for async.retry"); + } + + var _task = wrapAsync(task); + + var attempt = 1; + function retryAttempt() { + _task((err, ...args) => { + if (err === false) return + if (err && attempt++ < options.times && + (typeof options.errorFilter != 'function' || + options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt - 1)); + } else { + callback(err, ...args); + } + }); + } + + retryAttempt(); + return callback[PROMISE_SYMBOL] +} + +function parseTimes(acc, t) { + if (typeof t === 'object') { + acc.times = +t.times || DEFAULT_TIMES; + + acc.intervalFunc = typeof t.interval === 'function' ? + t.interval : + constant(+t.interval || DEFAULT_INTERVAL); + + acc.errorFilter = t.errorFilter; + } else if (typeof t === 'number' || typeof t === 'string') { + acc.times = +t || DEFAULT_TIMES; + } else { + throw new Error("Invalid arguments for async.retry"); + } +} + +/** + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method + * wraps a task and makes it retryable, rather than immediately calling it + * with retries. + * + * @name retryable + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.retry]{@link module:ControlFlow.retry} + * @category Control Flow + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional + * options, exactly the same as from `retry`, except for a `opts.arity` that + * is the arity of the `task` function, defaulting to `task.length` + * @param {AsyncFunction} task - the asynchronous function to wrap. + * This function will be passed any arguments passed to the returned wrapper. + * Invoked with (...args, callback). + * @returns {AsyncFunction} The wrapped function, which when invoked, will + * retry on an error, based on the parameters specified in `opts`. + * This function will accept the same parameters as `task`. + * @example + * + * async.auto({ + * dep1: async.retryable(3, getFromFlakyService), + * process: ["dep1", async.retryable(3, function (results, cb) { + * maybeProcessData(results.dep1, cb); + * })] + * }, callback); + */ +function retryable (opts, task) { + if (!task) { + task = opts; + opts = null; + } + let arity = (opts && opts.arity) || task.length; + if (isAsync(task)) { + arity += 1; + } + var _task = wrapAsync(task); + return initialParams((args, callback) => { + if (args.length < arity - 1 || callback == null) { + args.push(callback); + callback = promiseCallback(); + } + function taskFn(cb) { + _task(...args, cb); + } + + if (opts) retry(opts, taskFn, callback); + else retry(taskFn, callback); + + return callback[PROMISE_SYMBOL] + }); +} + +/** + * Run the functions in the `tasks` collection in series, each one running once + * the previous function has completed. If any functions in the series pass an + * error to its callback, no more functions are run, and `callback` is + * immediately called with the value of the error. Otherwise, `callback` + * receives an array of results when `tasks` have completed. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function, and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.series}. + * + * **Note** that while many implementations preserve the order of object + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) + * explicitly states that + * + * > The mechanics and order of enumerating the properties is not specified. + * + * So if you rely on the order in which your series of functions are executed, + * and want this to work on all platforms, consider using an array. + * + * @name series + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing + * [async functions]{@link AsyncFunction} to run in series. + * Each function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This function gets a results array (or object) + * containing all the result arguments passed to the `task` callbacks. Invoked + * with (err, result). + * @return {Promise} a promise, if no callback is passed + * @example + * + * //Using Callbacks + * async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] + * }); + * + * // an example using objects instead of arrays + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.series([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function series(tasks, callback) { + return _parallel(eachOfSeries$1, tasks, callback); +} + +/** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + *); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // false + * // result is false since none of the files exists + * } + *); + * + * // Using Promises + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since some file in the list exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since none of the files exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists); + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists); + * console.log(result); + * // false + * // result is false since none of the files exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function some(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback) +} +var some$1 = awaitify(some, 3); + +/** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someLimit(coll, limit, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfLimit$2(limit), coll, iteratee, callback) +} +var someLimit$1 = awaitify(someLimit, 4); + +/** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someSeries(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback) +} +var someSeries$1 = awaitify(someSeries, 3); + +/** + * Sorts a list by the results of running each `coll` value through an async + * `iteratee`. + * + * @name sortBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a value to use as the sort criteria as + * its `result`. + * Invoked with (item, callback). + * @param {Function} callback - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is the items + * from the original `coll` sorted by the values returned by the `iteratee` + * calls. Invoked with (err, results). + * @returns {Promise} a promise, if no callback passed + * @example + * + * // bigfile.txt is a file that is 251100 bytes in size + * // mediumfile.txt is a file that is 11000 bytes in size + * // smallfile.txt is a file that is 121 bytes in size + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // By modifying the callback parameter the + * // sorting order can be influenced: + * + * // ascending order + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) return callback(getFileSizeErr); + * callback(null, fileSize); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // descending order + * async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) { + * return callback(getFileSizeErr); + * } + * callback(null, fileSize * -1); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt'] + * } + * } + * ); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * } + * ); + * + * // Using Promises + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * (async () => { + * try { + * let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * // Error handling + * async () => { + * try { + * let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function sortBy (coll, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return map$1(coll, (x, iterCb) => { + _iteratee(x, (err, criteria) => { + if (err) return iterCb(err); + iterCb(err, {value: x, criteria}); + }); + }, (err, results) => { + if (err) return callback(err); + callback(null, results.sort(comparator).map(v => v.value)); + }); + + function comparator(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } +} +var sortBy$1 = awaitify(sortBy, 3); + +/** + * Sets a time limit on an asynchronous function. If the function does not call + * its callback within the specified milliseconds, it will be called with a + * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * + * @name timeout + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} asyncFn - The async function to limit in time. + * @param {number} milliseconds - The specified time limit. + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) + * to timeout Error for more information.. + * @returns {AsyncFunction} Returns a wrapped function that can be used with any + * of the control flow functions. + * Invoke this function with the same parameters as you would `asyncFunc`. + * @example + * + * function myFunction(foo, callback) { + * doAsyncTask(foo, function(err, data) { + * // handle errors + * if (err) return callback(err); + * + * // do some stuff ... + * + * // return processed data + * return callback(null, data); + * }); + * } + * + * var wrapped = async.timeout(myFunction, 1000); + * + * // call `wrapped` as you would `myFunction` + * wrapped({ bar: 'bar' }, function(err, data) { + * // if `myFunction` takes < 1000 ms to execute, `err` + * // and `data` will have their expected values + * + * // else `err` will be an Error with the code 'ETIMEDOUT' + * }); + */ +function timeout(asyncFn, milliseconds, info) { + var fn = wrapAsync(asyncFn); + + return initialParams((args, callback) => { + var timedOut = false; + var timer; + + function timeoutCallback() { + var name = asyncFn.name || 'anonymous'; + var error = new Error('Callback function "' + name + '" timed out.'); + error.code = 'ETIMEDOUT'; + if (info) { + error.info = info; + } + timedOut = true; + callback(error); + } + + args.push((...cbArgs) => { + if (!timedOut) { + callback(...cbArgs); + clearTimeout(timer); + } + }); + + // setup timer and call original function + timer = setTimeout(timeoutCallback, milliseconds); + fn(...args); + }); +} + +function range(size) { + var result = Array(size); + while (size--) { + result[size] = size; + } + return result; +} + +/** + * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a + * time. + * + * @name timesLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} count - The number of times to run the function. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see [async.map]{@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ +function timesLimit(count, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(range(count), limit, _iteratee, callback); +} + +/** + * Calls the `iteratee` function `n` times, and accumulates results in the same + * manner you would use with [map]{@link module:Collections.map}. + * + * @name times + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.map]{@link module:Collections.map} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + * @example + * + * // Pretend this is some complicated async factory + * var createUser = function(id, callback) { + * callback(null, { + * id: 'user' + id + * }); + * }; + * + * // generate 5 users + * async.times(5, function(n, next) { + * createUser(n, function(err, user) { + * next(err, user); + * }); + * }, function(err, users) { + * // we should now have 5 users + * }); + */ +function times (n, iteratee, callback) { + return timesLimit(n, Infinity, iteratee, callback) +} + +/** + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * + * @name timesSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ +function timesSeries (n, iteratee, callback) { + return timesLimit(n, 1, iteratee, callback) +} + +/** + * A relative of `reduce`. Takes an Object or Array, and iterates over each + * element in parallel, each step potentially mutating an `accumulator` value. + * The type of the accumulator defaults to the type of collection passed in. + * + * @name transform + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} [accumulator] - The initial state of the transform. If omitted, + * it will default to an empty Object or Array, depending on the type of `coll` + * @param {AsyncFunction} iteratee - A function applied to each item in the + * collection that potentially modifies the accumulator. + * Invoked with (accumulator, item, key, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the transformed accumulator. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileList, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * }); + * + * // Using Promises + * async.transform(fileList, transformFileSize) + * .then(result => { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.transform(fileList, transformFileSize); + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' }; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileMap, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * }); + * + * // Using Promises + * async.transform(fileMap, transformFileSize) + * .then(result => { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.transform(fileMap, transformFileSize); + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function transform (coll, accumulator, iteratee, callback) { + if (arguments.length <= 3 && typeof accumulator === 'function') { + callback = iteratee; + iteratee = accumulator; + accumulator = Array.isArray(coll) ? [] : {}; + } + callback = once(callback || promiseCallback()); + var _iteratee = wrapAsync(iteratee); + + eachOf$1(coll, (v, k, cb) => { + _iteratee(accumulator, v, k, cb); + }, err => callback(err, accumulator)); + return callback[PROMISE_SYMBOL] +} + +/** + * It runs each task in series but stops whenever any of the functions were + * successful. If one of the tasks were successful, the `callback` will be + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * async.tryEach([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ +function tryEach(tasks, callback) { + var error = null; + var result; + return eachSeries$1(tasks, (task, taskCb) => { + wrapAsync(task)((err, ...args) => { + if (err === false) return taskCb(err); + + if (args.length < 2) { + [result] = args; + } else { + result = args; + } + error = err; + taskCb(err ? null : {}); + }); + }, () => callback(error, result)); +} + +var tryEach$1 = awaitify(tryEach); + +/** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ +function unmemoize(fn) { + return (...args) => { + return (fn.unmemoized || fn)(...args); + }; +} + +/** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5); }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ +function whilst(test, iteratee, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results = []; + + function next(err, ...rest) { + if (err) return callback(err); + results = rest; + if (err === false) return; + _test(check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return _test(check); +} +var whilst$1 = awaitify(whilst, 3); + +/** + * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. `callback` will be passed an error and any + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * const results = [] + * let finished = false + * async.until(function test(cb) { + * cb(null, finished) + * }, function iter(next) { + * fetchPage(url, (err, body) => { + * if (err) return next(err) + * results = results.concat(body.objects) + * finished = !!body.next + * next(err) + * }) + * }, function done (err) { + * // all pages have been fetched + * }) + */ +function until(test, iteratee, callback) { + const _test = wrapAsync(test); + return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback); +} + +/** + * Runs the `tasks` array of functions in series, each passing their results to + * the next in the array. However, if any of the `tasks` pass an error to their + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ +function waterfall (tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); + if (!tasks.length) return callback(); + var taskIndex = 0; + + function nextTask(args) { + var task = wrapAsync(tasks[taskIndex++]); + task(...args, onlyOnce(next)); + } + + function next(err, ...args) { + if (err === false) return + if (err || taskIndex === tasks.length) { + return callback(err, ...args); + } + nextTask(args); + } + + nextTask([]); +} + +var waterfall$1 = awaitify(waterfall); + +/** + * An "async function" in the context of Async is an asynchronous function with + * a variable number of parameters, with the final parameter being a callback. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. + * + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static + */ + + +var index = { + apply, + applyEach, + applyEachSeries, + asyncify, + auto, + autoInject, + cargo: cargo$1, + cargoQueue: cargo, + compose, + concat: concat$1, + concatLimit: concatLimit$1, + concatSeries: concatSeries$1, + constant: constant$1, + detect: detect$1, + detectLimit: detectLimit$1, + detectSeries: detectSeries$1, + dir, + doUntil, + doWhilst: doWhilst$1, + each, + eachLimit: eachLimit$1, + eachOf: eachOf$1, + eachOfLimit: eachOfLimit$1, + eachOfSeries: eachOfSeries$1, + eachSeries: eachSeries$1, + ensureAsync, + every: every$1, + everyLimit: everyLimit$1, + everySeries: everySeries$1, + filter: filter$1, + filterLimit: filterLimit$1, + filterSeries: filterSeries$1, + forever: forever$1, + groupBy, + groupByLimit: groupByLimit$1, + groupBySeries, + log, + map: map$1, + mapLimit: mapLimit$1, + mapSeries: mapSeries$1, + mapValues, + mapValuesLimit: mapValuesLimit$1, + mapValuesSeries, + memoize, + nextTick, + parallel, + parallelLimit, + priorityQueue, + queue, + race: race$1, + reduce: reduce$1, + reduceRight, + reflect, + reflectAll, + reject: reject$1, + rejectLimit: rejectLimit$1, + rejectSeries: rejectSeries$1, + retry, + retryable, + seq, + series, + setImmediate: setImmediate$1, + some: some$1, + someLimit: someLimit$1, + someSeries: someSeries$1, + sortBy: sortBy$1, + timeout, + times, + timesLimit, + timesSeries, + transform, + tryEach: tryEach$1, + unmemoize, + until, + waterfall: waterfall$1, + whilst: whilst$1, + + // aliases + all: every$1, + allLimit: everyLimit$1, + allSeries: everySeries$1, + any: some$1, + anyLimit: someLimit$1, + anySeries: someSeries$1, + find: detect$1, + findLimit: detectLimit$1, + findSeries: detectSeries$1, + flatMap: concat$1, + flatMapLimit: concatLimit$1, + flatMapSeries: concatSeries$1, + forEach: each, + forEachSeries: eachSeries$1, + forEachLimit: eachLimit$1, + forEachOf: eachOf$1, + forEachOfSeries: eachOfSeries$1, + forEachOfLimit: eachOfLimit$1, + inject: reduce$1, + foldl: reduce$1, + foldr: reduceRight, + select: filter$1, + selectLimit: filterLimit$1, + selectSeries: filterSeries$1, + wrapSync: asyncify, + during: whilst$1, + doDuring: doWhilst$1 +}; + +export { every$1 as all, everyLimit$1 as allLimit, everySeries$1 as allSeries, some$1 as any, someLimit$1 as anyLimit, someSeries$1 as anySeries, apply, applyEach, applyEachSeries, asyncify, auto, autoInject, cargo$1 as cargo, cargo as cargoQueue, compose, concat$1 as concat, concatLimit$1 as concatLimit, concatSeries$1 as concatSeries, constant$1 as constant, index as default, detect$1 as detect, detectLimit$1 as detectLimit, detectSeries$1 as detectSeries, dir, doWhilst$1 as doDuring, doUntil, doWhilst$1 as doWhilst, whilst$1 as during, each, eachLimit$1 as eachLimit, eachOf$1 as eachOf, eachOfLimit$1 as eachOfLimit, eachOfSeries$1 as eachOfSeries, eachSeries$1 as eachSeries, ensureAsync, every$1 as every, everyLimit$1 as everyLimit, everySeries$1 as everySeries, filter$1 as filter, filterLimit$1 as filterLimit, filterSeries$1 as filterSeries, detect$1 as find, detectLimit$1 as findLimit, detectSeries$1 as findSeries, concat$1 as flatMap, concatLimit$1 as flatMapLimit, concatSeries$1 as flatMapSeries, reduce$1 as foldl, reduceRight as foldr, each as forEach, eachLimit$1 as forEachLimit, eachOf$1 as forEachOf, eachOfLimit$1 as forEachOfLimit, eachOfSeries$1 as forEachOfSeries, eachSeries$1 as forEachSeries, forever$1 as forever, groupBy, groupByLimit$1 as groupByLimit, groupBySeries, reduce$1 as inject, log, map$1 as map, mapLimit$1 as mapLimit, mapSeries$1 as mapSeries, mapValues, mapValuesLimit$1 as mapValuesLimit, mapValuesSeries, memoize, nextTick, parallel, parallelLimit, priorityQueue, queue, race$1 as race, reduce$1 as reduce, reduceRight, reflect, reflectAll, reject$1 as reject, rejectLimit$1 as rejectLimit, rejectSeries$1 as rejectSeries, retry, retryable, filter$1 as select, filterLimit$1 as selectLimit, filterSeries$1 as selectSeries, seq, series, setImmediate$1 as setImmediate, some$1 as some, someLimit$1 as someLimit, someSeries$1 as someSeries, sortBy$1 as sortBy, timeout, times, timesLimit, timesSeries, transform, tryEach$1 as tryEach, unmemoize, until, waterfall$1 as waterfall, whilst$1 as whilst, asyncify as wrapSync }; diff --git a/node_modules/async/doDuring.js b/node_modules/async/doDuring.js new file mode 100644 index 0000000..c72766d --- /dev/null +++ b/node_modules/async/doDuring.js @@ -0,0 +1,68 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ +function doWhilst(iteratee, test, callback) { + callback = (0, _onlyOnce2.default)(callback); + var _fn = (0, _wrapAsync2.default)(iteratee); + var _test = (0, _wrapAsync2.default)(test); + var results; + + function next(err, ...args) { + if (err) return callback(err); + if (err === false) return; + results = args; + _test(...args, check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return check(null, true); +} + +exports.default = (0, _awaitify2.default)(doWhilst, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/doUntil.js b/node_modules/async/doUntil.js new file mode 100644 index 0000000..519900e --- /dev/null +++ b/node_modules/async/doUntil.js @@ -0,0 +1,46 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = doUntil; + +var _doWhilst = require('./doWhilst.js'); + +var _doWhilst2 = _interopRequireDefault(_doWhilst); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the + * argument ordering differs from `until`. + * + * @name doUntil + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee` + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ +function doUntil(iteratee, test, callback) { + const _test = (0, _wrapAsync2.default)(test); + return (0, _doWhilst2.default)(iteratee, (...args) => { + const cb = args.pop(); + _test(...args, (err, truth) => cb(err, !truth)); + }, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/doWhilst.js b/node_modules/async/doWhilst.js new file mode 100644 index 0000000..c72766d --- /dev/null +++ b/node_modules/async/doWhilst.js @@ -0,0 +1,68 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ +function doWhilst(iteratee, test, callback) { + callback = (0, _onlyOnce2.default)(callback); + var _fn = (0, _wrapAsync2.default)(iteratee); + var _test = (0, _wrapAsync2.default)(test); + var results; + + function next(err, ...args) { + if (err) return callback(err); + if (err === false) return; + results = args; + _test(...args, check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return check(null, true); +} + +exports.default = (0, _awaitify2.default)(doWhilst, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/during.js b/node_modules/async/during.js new file mode 100644 index 0000000..4165543 --- /dev/null +++ b/node_modules/async/during.js @@ -0,0 +1,78 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5); }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ +function whilst(test, iteratee, callback) { + callback = (0, _onlyOnce2.default)(callback); + var _fn = (0, _wrapAsync2.default)(iteratee); + var _test = (0, _wrapAsync2.default)(test); + var results = []; + + function next(err, ...rest) { + if (err) return callback(err); + results = rest; + if (err === false) return; + _test(check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return _test(check); +} +exports.default = (0, _awaitify2.default)(whilst, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/each.js b/node_modules/async/each.js new file mode 100644 index 0000000..fdfcbd8 --- /dev/null +++ b/node_modules/async/each.js @@ -0,0 +1,129 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _withoutIndex = require('./internal/withoutIndex.js'); + +var _withoutIndex2 = _interopRequireDefault(_withoutIndex); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt']; + * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt']; + * + * // asynchronous function that deletes a file + * const deleteFile = function(file, callback) { + * fs.unlink(file, callback); + * }; + * + * // Using callbacks + * async.each(fileList, deleteFile, function(err) { + * if( err ) { + * console.log(err); + * } else { + * console.log('All files have been deleted successfully'); + * } + * }); + * + * // Error Handling + * async.each(withMissingFileList, deleteFile, function(err){ + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using Promises + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using async/await + * async () => { + * try { + * await async.each(files, deleteFile); + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * await async.each(withMissingFileList, deleteFile); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * } + * } + * + */ +function eachLimit(coll, iteratee, callback) { + return (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); +} + +exports.default = (0, _awaitify2.default)(eachLimit, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/eachLimit.js b/node_modules/async/eachLimit.js new file mode 100644 index 0000000..7f5928c --- /dev/null +++ b/node_modules/async/eachLimit.js @@ -0,0 +1,50 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _withoutIndex = require('./internal/withoutIndex.js'); + +var _withoutIndex2 = _interopRequireDefault(_withoutIndex); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachLimit(coll, limit, iteratee, callback) { + return (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); +} +exports.default = (0, _awaitify2.default)(eachLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/eachOf.js b/node_modules/async/eachOf.js new file mode 100644 index 0000000..9ed20f6 --- /dev/null +++ b/node_modules/async/eachOf.js @@ -0,0 +1,185 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _isArrayLike = require('./internal/isArrayLike.js'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _breakLoop = require('./internal/breakLoop.js'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +var _eachOfLimit = require('./eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// eachOf implementation optimized for array-likes +function eachOfArrayLike(coll, iteratee, callback) { + callback = (0, _once2.default)(callback); + var index = 0, + completed = 0, + { length } = coll, + canceled = false; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } + if (canceled === true) return; + if (err) { + callback(err); + } else if (++completed === length || value === _breakLoop2.default) { + callback(null); + } + } + + for (; index < length; index++) { + iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback)); + } +} + +// a generic version of eachOf which can handle array, object, and iterator cases. +function eachOfGeneric(coll, iteratee, callback) { + return (0, _eachOfLimit2.default)(coll, Infinity, iteratee, callback); +} + +/** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dev.json is a file containing a valid json object config for dev environment + * // dev.json is a file containing a valid json object config for test environment + * // prod.json is a file containing a valid json object config for prod environment + * // invalid.json is a file with a malformed json object + * + * let configs = {}; //global variable + * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'}; + * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'}; + * + * // asynchronous function that reads a json file and parses the contents as json object + * function parseFile(file, key, callback) { + * fs.readFile(file, "utf8", function(err, data) { + * if (err) return calback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * } + * + * // Using callbacks + * async.forEachOf(validConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * } else { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * // JSON parse error exception + * } else { + * console.log(configs); + * } + * }); + * + * // Using Promises + * async.forEachOf(validConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * }).catch( err => { + * console.error(err); + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * }).catch( err => { + * console.error(err); + * // JSON parse error exception + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.forEachOf(validConfigFileMap, parseFile); + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * catch (err) { + * console.log(err); + * } + * } + * + * //Error handing + * async () => { + * try { + * let result = await async.forEachOf(invalidConfigFileMap, parseFile); + * console.log(configs); + * } + * catch (err) { + * console.log(err); + * // JSON parse error exception + * } + * } + * + */ +function eachOf(coll, iteratee, callback) { + var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback); +} + +exports.default = (0, _awaitify2.default)(eachOf, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/eachOfLimit.js b/node_modules/async/eachOfLimit.js new file mode 100644 index 0000000..a596e5a --- /dev/null +++ b/node_modules/async/eachOfLimit.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit2 = require('./internal/eachOfLimit.js'); + +var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfLimit(coll, limit, iteratee, callback) { + return (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); +} + +exports.default = (0, _awaitify2.default)(eachOfLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/eachOfSeries.js b/node_modules/async/eachOfSeries.js new file mode 100644 index 0000000..04243ad --- /dev/null +++ b/node_modules/async/eachOfSeries.js @@ -0,0 +1,39 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit = require('./eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfSeries(coll, iteratee, callback) { + return (0, _eachOfLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(eachOfSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/eachSeries.js b/node_modules/async/eachSeries.js new file mode 100644 index 0000000..b04896e --- /dev/null +++ b/node_modules/async/eachSeries.js @@ -0,0 +1,44 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachLimit = require('./eachLimit.js'); + +var _eachLimit2 = _interopRequireDefault(_eachLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item + * in series and therefore the iteratee functions will complete in order. + + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachSeries(coll, iteratee, callback) { + return (0, _eachLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(eachSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/ensureAsync.js b/node_modules/async/ensureAsync.js new file mode 100644 index 0000000..749c5da --- /dev/null +++ b/node_modules/async/ensureAsync.js @@ -0,0 +1,67 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = ensureAsync; + +var _setImmediate = require('./internal/setImmediate.js'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Wrap an async function and ensure it calls its callback on a later tick of + * the event loop. If the function already calls its callback on a next tick, + * no extra deferral is added. This is useful for preventing stack overflows + * (`RangeError: Maximum call stack size exceeded`) and generally keeping + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + * contained. ES2017 `async` functions are returned as-is -- they are immune + * to Zalgo's corrupting influences, as they always resolve on a later tick. + * + * @name ensureAsync + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - an async function, one that expects a node-style + * callback as its last argument. + * @returns {AsyncFunction} Returns a wrapped function with the exact same call + * signature as the function passed in. + * @example + * + * function sometimesAsync(arg, callback) { + * if (cache[arg]) { + * return callback(null, cache[arg]); // this would be synchronous!! + * } else { + * doSomeIO(arg, callback); // this IO would be asynchronous + * } + * } + * + * // this has a risk of stack overflows if many results are cached in a row + * async.mapSeries(args, sometimesAsync, done); + * + * // this will defer sometimesAsync's callback if necessary, + * // preventing stack overflows + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + */ +function ensureAsync(fn) { + if ((0, _wrapAsync.isAsync)(fn)) return fn; + return function (...args /*, callback*/) { + var callback = args.pop(); + var sync = true; + args.push((...innerArgs) => { + if (sync) { + (0, _setImmediate2.default)(() => callback(...innerArgs)); + } else { + callback(...innerArgs); + } + }); + fn.apply(this, args); + sync = false; + }; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/every.js b/node_modules/async/every.js new file mode 100644 index 0000000..622b301 --- /dev/null +++ b/node_modules/async/every.js @@ -0,0 +1,119 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.every(fileList, fileExists, function(err, result) { + * console.log(result); + * // true + * // result is true since every file exists + * }); + * + * async.every(withMissingFileList, fileExists, function(err, result) { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }); + * + * // Using Promises + * async.every(fileList, fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.every(withMissingFileList, fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.every(fileList, fileExists); + * console.log(result); + * // true + * // result is true since every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.every(withMissingFileList, fileExists); + * console.log(result); + * // false + * // result is false since NOT every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function every(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(every, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/everyLimit.js b/node_modules/async/everyLimit.js new file mode 100644 index 0000000..375e126 --- /dev/null +++ b/node_modules/async/everyLimit.js @@ -0,0 +1,46 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everyLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(everyLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/everySeries.js b/node_modules/async/everySeries.js new file mode 100644 index 0000000..9a6bf7d --- /dev/null +++ b/node_modules/async/everySeries.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everySeries(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(everySeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/filter.js b/node_modules/async/filter.js new file mode 100644 index 0000000..2c9a63d --- /dev/null +++ b/node_modules/async/filter.js @@ -0,0 +1,93 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter.js'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.filter(files, fileExists, function(err, results) { + * if(err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * }); + * + * // Using Promises + * async.filter(files, fileExists) + * .then(results => { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.filter(files, fileExists); + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function filter(coll, iteratee, callback) { + return (0, _filter3.default)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filter, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/filterLimit.js b/node_modules/async/filterLimit.js new file mode 100644 index 0000000..d3b3f50 --- /dev/null +++ b/node_modules/async/filterLimit.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter.js'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + */ +function filterLimit(coll, limit, iteratee, callback) { + return (0, _filter3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filterLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/filterSeries.js b/node_modules/async/filterSeries.js new file mode 100644 index 0000000..019a2d0 --- /dev/null +++ b/node_modules/async/filterSeries.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter.js'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + * @returns {Promise} a promise, if no callback provided + */ +function filterSeries(coll, iteratee, callback) { + return (0, _filter3.default)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filterSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/find.js b/node_modules/async/find.js new file mode 100644 index 0000000..d5896ef --- /dev/null +++ b/node_modules/async/find.js @@ -0,0 +1,96 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. + + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * } + *); + * + * // Using Promises + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists) + * .then(result => { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); + * console.log(result); + * // dir1/file1.txt + * // result now equals the file in the list that exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function detect(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(detect, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/findLimit.js b/node_modules/async/findLimit.js new file mode 100644 index 0000000..c59843b --- /dev/null +++ b/node_modules/async/findLimit.js @@ -0,0 +1,48 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ +function detectLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(detectLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/findSeries.js b/node_modules/async/findSeries.js new file mode 100644 index 0000000..b486899 --- /dev/null +++ b/node_modules/async/findSeries.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ +function detectSeries(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(1), coll, iteratee, callback); +} + +exports.default = (0, _awaitify2.default)(detectSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/flatMap.js b/node_modules/async/flatMap.js new file mode 100644 index 0000000..4540a79 --- /dev/null +++ b/node_modules/async/flatMap.js @@ -0,0 +1,115 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _concatLimit = require('./concatLimit.js'); + +var _concatLimit2 = _interopRequireDefault(_concatLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Applies `iteratee` to each item in `coll`, concatenating the results. Returns + * the concatenated list. The `iteratee`s are called in parallel, and the + * results are concatenated as they return. The results array will be returned in + * the original order of `coll` passed to the `iteratee` function. + * + * @name concat + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @alias flatMap + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * let directoryList = ['dir1','dir2','dir3']; + * let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4']; + * + * // Using callbacks + * async.concat(directoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.concat(directoryList, fs.readdir) + * .then(results => { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir) + * .then(results => { + * console.log(results); + * }).catch(err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.concat(directoryList, fs.readdir); + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.concat(withMissingDirectoryList, fs.readdir); + * console.log(results); + * } catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } + * } + * + */ +function concat(coll, iteratee, callback) { + return (0, _concatLimit2.default)(coll, Infinity, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(concat, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/flatMapLimit.js b/node_modules/async/flatMapLimit.js new file mode 100644 index 0000000..a27cc7d --- /dev/null +++ b/node_modules/async/flatMapLimit.js @@ -0,0 +1,60 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _mapLimit = require('./mapLimit.js'); + +var _mapLimit2 = _interopRequireDefault(_mapLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. + * + * @name concatLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapLimit + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatLimit(coll, limit, iteratee, callback) { + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _mapLimit2.default)(coll, limit, (val, iterCb) => { + _iteratee(val, (err, ...args) => { + if (err) return iterCb(err); + return iterCb(err, args); + }); + }, (err, mapResults) => { + var result = []; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + result = result.concat(...mapResults[i]); + } + } + + return callback(err, result); + }); +} +exports.default = (0, _awaitify2.default)(concatLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/flatMapSeries.js b/node_modules/async/flatMapSeries.js new file mode 100644 index 0000000..332de3f --- /dev/null +++ b/node_modules/async/flatMapSeries.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _concatLimit = require('./concatLimit.js'); + +var _concatLimit2 = _interopRequireDefault(_concatLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * + * @name concatSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapSeries + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. + * The iteratee should complete with an array an array of results. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatSeries(coll, iteratee, callback) { + return (0, _concatLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(concatSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/foldl.js b/node_modules/async/foldl.js new file mode 100644 index 0000000..8a69548 --- /dev/null +++ b/node_modules/async/foldl.js @@ -0,0 +1,153 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Reduces `coll` into a single value using an async `iteratee` to return each + * successive step. `memo` is the initial state of the reduction. This function + * only operates in series. + * + * For performance reasons, it may make sense to split a call to this function + * into a parallel map, and then use the normal `Array.prototype.reduce` on the + * results. This function is for situations where each step in the reduction + * needs to be async; if you can get the data before reducing it, then it's + * probably a good idea to do so. + * + * @name reduce + * @static + * @memberOf module:Collections + * @method + * @alias inject + * @alias foldl + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt']; + * + * // asynchronous function that computes the file size in bytes + * // file size is added to the memoized value, then returned + * function getFileSizeInBytes(memo, file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, memo + stat.size); + * }); + * } + * + * // Using callbacks + * async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.reduce(fileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.reduce(fileList, 0, getFileSizeInBytes); + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function reduce(coll, memo, iteratee, callback) { + callback = (0, _once2.default)(callback); + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _eachOfSeries2.default)(coll, (x, i, iterCb) => { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); +} +exports.default = (0, _awaitify2.default)(reduce, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/foldr.js b/node_modules/async/foldr.js new file mode 100644 index 0000000..5be1b68 --- /dev/null +++ b/node_modules/async/foldr.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reduceRight; + +var _reduce = require('./reduce.js'); + +var _reduce2 = _interopRequireDefault(_reduce); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function reduceRight(array, memo, iteratee, callback) { + var reversed = [...array].reverse(); + return (0, _reduce2.default)(reversed, memo, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/forEach.js b/node_modules/async/forEach.js new file mode 100644 index 0000000..fdfcbd8 --- /dev/null +++ b/node_modules/async/forEach.js @@ -0,0 +1,129 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _withoutIndex = require('./internal/withoutIndex.js'); + +var _withoutIndex2 = _interopRequireDefault(_withoutIndex); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt']; + * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt']; + * + * // asynchronous function that deletes a file + * const deleteFile = function(file, callback) { + * fs.unlink(file, callback); + * }; + * + * // Using callbacks + * async.each(fileList, deleteFile, function(err) { + * if( err ) { + * console.log(err); + * } else { + * console.log('All files have been deleted successfully'); + * } + * }); + * + * // Error Handling + * async.each(withMissingFileList, deleteFile, function(err){ + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using Promises + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using async/await + * async () => { + * try { + * await async.each(files, deleteFile); + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * await async.each(withMissingFileList, deleteFile); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * } + * } + * + */ +function eachLimit(coll, iteratee, callback) { + return (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); +} + +exports.default = (0, _awaitify2.default)(eachLimit, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/forEachLimit.js b/node_modules/async/forEachLimit.js new file mode 100644 index 0000000..7f5928c --- /dev/null +++ b/node_modules/async/forEachLimit.js @@ -0,0 +1,50 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _withoutIndex = require('./internal/withoutIndex.js'); + +var _withoutIndex2 = _interopRequireDefault(_withoutIndex); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachLimit(coll, limit, iteratee, callback) { + return (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); +} +exports.default = (0, _awaitify2.default)(eachLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/forEachOf.js b/node_modules/async/forEachOf.js new file mode 100644 index 0000000..9ed20f6 --- /dev/null +++ b/node_modules/async/forEachOf.js @@ -0,0 +1,185 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _isArrayLike = require('./internal/isArrayLike.js'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _breakLoop = require('./internal/breakLoop.js'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +var _eachOfLimit = require('./eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// eachOf implementation optimized for array-likes +function eachOfArrayLike(coll, iteratee, callback) { + callback = (0, _once2.default)(callback); + var index = 0, + completed = 0, + { length } = coll, + canceled = false; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } + if (canceled === true) return; + if (err) { + callback(err); + } else if (++completed === length || value === _breakLoop2.default) { + callback(null); + } + } + + for (; index < length; index++) { + iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback)); + } +} + +// a generic version of eachOf which can handle array, object, and iterator cases. +function eachOfGeneric(coll, iteratee, callback) { + return (0, _eachOfLimit2.default)(coll, Infinity, iteratee, callback); +} + +/** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dev.json is a file containing a valid json object config for dev environment + * // dev.json is a file containing a valid json object config for test environment + * // prod.json is a file containing a valid json object config for prod environment + * // invalid.json is a file with a malformed json object + * + * let configs = {}; //global variable + * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'}; + * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'}; + * + * // asynchronous function that reads a json file and parses the contents as json object + * function parseFile(file, key, callback) { + * fs.readFile(file, "utf8", function(err, data) { + * if (err) return calback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * } + * + * // Using callbacks + * async.forEachOf(validConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * } else { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * // JSON parse error exception + * } else { + * console.log(configs); + * } + * }); + * + * // Using Promises + * async.forEachOf(validConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * }).catch( err => { + * console.error(err); + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * }).catch( err => { + * console.error(err); + * // JSON parse error exception + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.forEachOf(validConfigFileMap, parseFile); + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * catch (err) { + * console.log(err); + * } + * } + * + * //Error handing + * async () => { + * try { + * let result = await async.forEachOf(invalidConfigFileMap, parseFile); + * console.log(configs); + * } + * catch (err) { + * console.log(err); + * // JSON parse error exception + * } + * } + * + */ +function eachOf(coll, iteratee, callback) { + var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback); +} + +exports.default = (0, _awaitify2.default)(eachOf, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/forEachOfLimit.js b/node_modules/async/forEachOfLimit.js new file mode 100644 index 0000000..a596e5a --- /dev/null +++ b/node_modules/async/forEachOfLimit.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit2 = require('./internal/eachOfLimit.js'); + +var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfLimit(coll, limit, iteratee, callback) { + return (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); +} + +exports.default = (0, _awaitify2.default)(eachOfLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/forEachOfSeries.js b/node_modules/async/forEachOfSeries.js new file mode 100644 index 0000000..04243ad --- /dev/null +++ b/node_modules/async/forEachOfSeries.js @@ -0,0 +1,39 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit = require('./eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfSeries(coll, iteratee, callback) { + return (0, _eachOfLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(eachOfSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/forEachSeries.js b/node_modules/async/forEachSeries.js new file mode 100644 index 0000000..b04896e --- /dev/null +++ b/node_modules/async/forEachSeries.js @@ -0,0 +1,44 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachLimit = require('./eachLimit.js'); + +var _eachLimit2 = _interopRequireDefault(_eachLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item + * in series and therefore the iteratee functions will complete in order. + + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachSeries(coll, iteratee, callback) { + return (0, _eachLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(eachSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/forever.js b/node_modules/async/forever.js new file mode 100644 index 0000000..2292518 --- /dev/null +++ b/node_modules/async/forever.js @@ -0,0 +1,68 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _ensureAsync = require('./ensureAsync.js'); + +var _ensureAsync2 = _interopRequireDefault(_ensureAsync); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Calls the asynchronous function `fn` with a callback parameter that allows it + * to call itself again, in series, indefinitely. + + * If an error is passed to the callback then `errback` is called with the + * error, and execution stops, otherwise it will never be called. + * + * @name forever + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} fn - an async function to call repeatedly. + * Invoked with (next). + * @param {Function} [errback] - when `fn` passes an error to it's callback, + * this function will be called, and execution stops. Invoked with (err). + * @returns {Promise} a promise that rejects if an error occurs and an errback + * is not passed + * @example + * + * async.forever( + * function(next) { + * // next is suitable for passing to things that need a callback(err [, whatever]); + * // it will result in this function being called again. + * }, + * function(err) { + * // if next is called with a value in its first parameter, it will appear + * // in here as 'err', and execution will stop. + * } + * ); + */ +function forever(fn, errback) { + var done = (0, _onlyOnce2.default)(errback); + var task = (0, _wrapAsync2.default)((0, _ensureAsync2.default)(fn)); + + function next(err) { + if (err) return done(err); + if (err === false) return; + task(next); + } + return next(); +} +exports.default = (0, _awaitify2.default)(forever, 2); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/groupBy.js b/node_modules/async/groupBy.js new file mode 100644 index 0000000..f295763 --- /dev/null +++ b/node_modules/async/groupBy.js @@ -0,0 +1,108 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = groupBy; + +var _groupByLimit = require('./groupByLimit.js'); + +var _groupByLimit2 = _interopRequireDefault(_groupByLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns a new object, where each value corresponds to an array of items, from + * `coll`, that returned the corresponding key. That is, the keys of the object + * correspond to the values passed to the `iteratee` callback. + * + * Note: Since this function applies the `iteratee` to each item in parallel, + * there is no guarantee that the `iteratee` functions will complete in order. + * However, the values for each key in the `result` will be in the same order as + * the original `coll`. For Objects, the values will roughly be in the order of + * the original Objects' keys (but this can vary across JavaScript engines). + * + * @name groupBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const files = ['dir1/file1.txt','dir2','dir4'] + * + * // asynchronous function that detects file type as none, file, or directory + * function detectFile(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(null, 'none'); + * } + * callback(null, stat.isDirectory() ? 'directory' : 'file'); + * }); + * } + * + * //Using callbacks + * async.groupBy(files, detectFile, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * }); + * + * // Using Promises + * async.groupBy(files, detectFile) + * .then( result => { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.groupBy(files, detectFile); + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function groupBy(coll, iteratee, callback) { + return (0, _groupByLimit2.default)(coll, Infinity, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/groupByLimit.js b/node_modules/async/groupByLimit.js new file mode 100644 index 0000000..30fd290 --- /dev/null +++ b/node_modules/async/groupByLimit.js @@ -0,0 +1,71 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _mapLimit = require('./mapLimit.js'); + +var _mapLimit2 = _interopRequireDefault(_mapLimit); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. + * + * @name groupByLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ +function groupByLimit(coll, limit, iteratee, callback) { + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _mapLimit2.default)(coll, limit, (val, iterCb) => { + _iteratee(val, (err, key) => { + if (err) return iterCb(err); + return iterCb(err, { key, val }); + }); + }, (err, mapResults) => { + var result = {}; + // from MDN, handle object having an `hasOwnProperty` prop + var { hasOwnProperty } = Object.prototype; + + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + var { key } = mapResults[i]; + var { val } = mapResults[i]; + + if (hasOwnProperty.call(result, key)) { + result[key].push(val); + } else { + result[key] = [val]; + } + } + } + + return callback(err, result); + }); +} + +exports.default = (0, _awaitify2.default)(groupByLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/groupBySeries.js b/node_modules/async/groupBySeries.js new file mode 100644 index 0000000..e2a5287 --- /dev/null +++ b/node_modules/async/groupBySeries.js @@ -0,0 +1,36 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = groupBySeries; + +var _groupByLimit = require('./groupByLimit.js'); + +var _groupByLimit2 = _interopRequireDefault(_groupByLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. + * + * @name groupBySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whose + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ +function groupBySeries(coll, iteratee, callback) { + return (0, _groupByLimit2.default)(coll, 1, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/index.js b/node_modules/async/index.js new file mode 100644 index 0000000..6154647 --- /dev/null +++ b/node_modules/async/index.js @@ -0,0 +1,588 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.doDuring = exports.during = exports.wrapSync = undefined; +exports.selectSeries = exports.selectLimit = exports.select = exports.foldr = exports.foldl = exports.inject = exports.forEachOfLimit = exports.forEachOfSeries = exports.forEachOf = exports.forEachLimit = exports.forEachSeries = exports.forEach = exports.flatMapSeries = exports.flatMapLimit = exports.flatMap = exports.findSeries = exports.findLimit = exports.find = exports.anySeries = exports.anyLimit = exports.any = exports.allSeries = exports.allLimit = exports.all = exports.whilst = exports.waterfall = exports.until = exports.unmemoize = exports.tryEach = exports.transform = exports.timesSeries = exports.timesLimit = exports.times = exports.timeout = exports.sortBy = exports.someSeries = exports.someLimit = exports.some = exports.setImmediate = exports.series = exports.seq = exports.retryable = exports.retry = exports.rejectSeries = exports.rejectLimit = exports.reject = exports.reflectAll = exports.reflect = exports.reduceRight = exports.reduce = exports.race = exports.queue = exports.priorityQueue = exports.parallelLimit = exports.parallel = exports.nextTick = exports.memoize = exports.mapValuesSeries = exports.mapValuesLimit = exports.mapValues = exports.mapSeries = exports.mapLimit = exports.map = exports.log = exports.groupBySeries = exports.groupByLimit = exports.groupBy = exports.forever = exports.filterSeries = exports.filterLimit = exports.filter = exports.everySeries = exports.everyLimit = exports.every = exports.ensureAsync = exports.eachSeries = exports.eachOfSeries = exports.eachOfLimit = exports.eachOf = exports.eachLimit = exports.each = exports.doWhilst = exports.doUntil = exports.dir = exports.detectSeries = exports.detectLimit = exports.detect = exports.constant = exports.concatSeries = exports.concatLimit = exports.concat = exports.compose = exports.cargoQueue = exports.cargo = exports.autoInject = exports.auto = exports.asyncify = exports.applyEachSeries = exports.applyEach = exports.apply = undefined; + +var _apply = require('./apply'); + +var _apply2 = _interopRequireDefault(_apply); + +var _applyEach = require('./applyEach'); + +var _applyEach2 = _interopRequireDefault(_applyEach); + +var _applyEachSeries = require('./applyEachSeries'); + +var _applyEachSeries2 = _interopRequireDefault(_applyEachSeries); + +var _asyncify = require('./asyncify'); + +var _asyncify2 = _interopRequireDefault(_asyncify); + +var _auto = require('./auto'); + +var _auto2 = _interopRequireDefault(_auto); + +var _autoInject = require('./autoInject'); + +var _autoInject2 = _interopRequireDefault(_autoInject); + +var _cargo = require('./cargo'); + +var _cargo2 = _interopRequireDefault(_cargo); + +var _cargoQueue = require('./cargoQueue'); + +var _cargoQueue2 = _interopRequireDefault(_cargoQueue); + +var _compose = require('./compose'); + +var _compose2 = _interopRequireDefault(_compose); + +var _concat = require('./concat'); + +var _concat2 = _interopRequireDefault(_concat); + +var _concatLimit = require('./concatLimit'); + +var _concatLimit2 = _interopRequireDefault(_concatLimit); + +var _concatSeries = require('./concatSeries'); + +var _concatSeries2 = _interopRequireDefault(_concatSeries); + +var _constant = require('./constant'); + +var _constant2 = _interopRequireDefault(_constant); + +var _detect = require('./detect'); + +var _detect2 = _interopRequireDefault(_detect); + +var _detectLimit = require('./detectLimit'); + +var _detectLimit2 = _interopRequireDefault(_detectLimit); + +var _detectSeries = require('./detectSeries'); + +var _detectSeries2 = _interopRequireDefault(_detectSeries); + +var _dir = require('./dir'); + +var _dir2 = _interopRequireDefault(_dir); + +var _doUntil = require('./doUntil'); + +var _doUntil2 = _interopRequireDefault(_doUntil); + +var _doWhilst = require('./doWhilst'); + +var _doWhilst2 = _interopRequireDefault(_doWhilst); + +var _each = require('./each'); + +var _each2 = _interopRequireDefault(_each); + +var _eachLimit = require('./eachLimit'); + +var _eachLimit2 = _interopRequireDefault(_eachLimit); + +var _eachOf = require('./eachOf'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _eachOfLimit = require('./eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _eachOfSeries = require('./eachOfSeries'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _eachSeries = require('./eachSeries'); + +var _eachSeries2 = _interopRequireDefault(_eachSeries); + +var _ensureAsync = require('./ensureAsync'); + +var _ensureAsync2 = _interopRequireDefault(_ensureAsync); + +var _every = require('./every'); + +var _every2 = _interopRequireDefault(_every); + +var _everyLimit = require('./everyLimit'); + +var _everyLimit2 = _interopRequireDefault(_everyLimit); + +var _everySeries = require('./everySeries'); + +var _everySeries2 = _interopRequireDefault(_everySeries); + +var _filter = require('./filter'); + +var _filter2 = _interopRequireDefault(_filter); + +var _filterLimit = require('./filterLimit'); + +var _filterLimit2 = _interopRequireDefault(_filterLimit); + +var _filterSeries = require('./filterSeries'); + +var _filterSeries2 = _interopRequireDefault(_filterSeries); + +var _forever = require('./forever'); + +var _forever2 = _interopRequireDefault(_forever); + +var _groupBy = require('./groupBy'); + +var _groupBy2 = _interopRequireDefault(_groupBy); + +var _groupByLimit = require('./groupByLimit'); + +var _groupByLimit2 = _interopRequireDefault(_groupByLimit); + +var _groupBySeries = require('./groupBySeries'); + +var _groupBySeries2 = _interopRequireDefault(_groupBySeries); + +var _log = require('./log'); + +var _log2 = _interopRequireDefault(_log); + +var _map = require('./map'); + +var _map2 = _interopRequireDefault(_map); + +var _mapLimit = require('./mapLimit'); + +var _mapLimit2 = _interopRequireDefault(_mapLimit); + +var _mapSeries = require('./mapSeries'); + +var _mapSeries2 = _interopRequireDefault(_mapSeries); + +var _mapValues = require('./mapValues'); + +var _mapValues2 = _interopRequireDefault(_mapValues); + +var _mapValuesLimit = require('./mapValuesLimit'); + +var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit); + +var _mapValuesSeries = require('./mapValuesSeries'); + +var _mapValuesSeries2 = _interopRequireDefault(_mapValuesSeries); + +var _memoize = require('./memoize'); + +var _memoize2 = _interopRequireDefault(_memoize); + +var _nextTick = require('./nextTick'); + +var _nextTick2 = _interopRequireDefault(_nextTick); + +var _parallel = require('./parallel'); + +var _parallel2 = _interopRequireDefault(_parallel); + +var _parallelLimit = require('./parallelLimit'); + +var _parallelLimit2 = _interopRequireDefault(_parallelLimit); + +var _priorityQueue = require('./priorityQueue'); + +var _priorityQueue2 = _interopRequireDefault(_priorityQueue); + +var _queue = require('./queue'); + +var _queue2 = _interopRequireDefault(_queue); + +var _race = require('./race'); + +var _race2 = _interopRequireDefault(_race); + +var _reduce = require('./reduce'); + +var _reduce2 = _interopRequireDefault(_reduce); + +var _reduceRight = require('./reduceRight'); + +var _reduceRight2 = _interopRequireDefault(_reduceRight); + +var _reflect = require('./reflect'); + +var _reflect2 = _interopRequireDefault(_reflect); + +var _reflectAll = require('./reflectAll'); + +var _reflectAll2 = _interopRequireDefault(_reflectAll); + +var _reject = require('./reject'); + +var _reject2 = _interopRequireDefault(_reject); + +var _rejectLimit = require('./rejectLimit'); + +var _rejectLimit2 = _interopRequireDefault(_rejectLimit); + +var _rejectSeries = require('./rejectSeries'); + +var _rejectSeries2 = _interopRequireDefault(_rejectSeries); + +var _retry = require('./retry'); + +var _retry2 = _interopRequireDefault(_retry); + +var _retryable = require('./retryable'); + +var _retryable2 = _interopRequireDefault(_retryable); + +var _seq = require('./seq'); + +var _seq2 = _interopRequireDefault(_seq); + +var _series = require('./series'); + +var _series2 = _interopRequireDefault(_series); + +var _setImmediate = require('./setImmediate'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _some = require('./some'); + +var _some2 = _interopRequireDefault(_some); + +var _someLimit = require('./someLimit'); + +var _someLimit2 = _interopRequireDefault(_someLimit); + +var _someSeries = require('./someSeries'); + +var _someSeries2 = _interopRequireDefault(_someSeries); + +var _sortBy = require('./sortBy'); + +var _sortBy2 = _interopRequireDefault(_sortBy); + +var _timeout = require('./timeout'); + +var _timeout2 = _interopRequireDefault(_timeout); + +var _times = require('./times'); + +var _times2 = _interopRequireDefault(_times); + +var _timesLimit = require('./timesLimit'); + +var _timesLimit2 = _interopRequireDefault(_timesLimit); + +var _timesSeries = require('./timesSeries'); + +var _timesSeries2 = _interopRequireDefault(_timesSeries); + +var _transform = require('./transform'); + +var _transform2 = _interopRequireDefault(_transform); + +var _tryEach = require('./tryEach'); + +var _tryEach2 = _interopRequireDefault(_tryEach); + +var _unmemoize = require('./unmemoize'); + +var _unmemoize2 = _interopRequireDefault(_unmemoize); + +var _until = require('./until'); + +var _until2 = _interopRequireDefault(_until); + +var _waterfall = require('./waterfall'); + +var _waterfall2 = _interopRequireDefault(_waterfall); + +var _whilst = require('./whilst'); + +var _whilst2 = _interopRequireDefault(_whilst); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * An "async function" in the context of Async is an asynchronous function with + * a variable number of parameters, with the final parameter being a callback. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. + * + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static + */ + +/** + * Async is a utility module which provides straight-forward, powerful functions + * for working with asynchronous JavaScript. Although originally designed for + * use with [Node.js](http://nodejs.org) and installable via + * `npm install --save async`, it can also be used directly in the browser. + * @module async + * @see AsyncFunction + */ + +/** + * A collection of `async` functions for manipulating collections, such as + * arrays and objects. + * @module Collections + */ + +/** + * A collection of `async` functions for controlling the flow through a script. + * @module ControlFlow + */ + +/** + * A collection of `async` utility functions. + * @module Utils + */ + +exports.default = { + apply: _apply2.default, + applyEach: _applyEach2.default, + applyEachSeries: _applyEachSeries2.default, + asyncify: _asyncify2.default, + auto: _auto2.default, + autoInject: _autoInject2.default, + cargo: _cargo2.default, + cargoQueue: _cargoQueue2.default, + compose: _compose2.default, + concat: _concat2.default, + concatLimit: _concatLimit2.default, + concatSeries: _concatSeries2.default, + constant: _constant2.default, + detect: _detect2.default, + detectLimit: _detectLimit2.default, + detectSeries: _detectSeries2.default, + dir: _dir2.default, + doUntil: _doUntil2.default, + doWhilst: _doWhilst2.default, + each: _each2.default, + eachLimit: _eachLimit2.default, + eachOf: _eachOf2.default, + eachOfLimit: _eachOfLimit2.default, + eachOfSeries: _eachOfSeries2.default, + eachSeries: _eachSeries2.default, + ensureAsync: _ensureAsync2.default, + every: _every2.default, + everyLimit: _everyLimit2.default, + everySeries: _everySeries2.default, + filter: _filter2.default, + filterLimit: _filterLimit2.default, + filterSeries: _filterSeries2.default, + forever: _forever2.default, + groupBy: _groupBy2.default, + groupByLimit: _groupByLimit2.default, + groupBySeries: _groupBySeries2.default, + log: _log2.default, + map: _map2.default, + mapLimit: _mapLimit2.default, + mapSeries: _mapSeries2.default, + mapValues: _mapValues2.default, + mapValuesLimit: _mapValuesLimit2.default, + mapValuesSeries: _mapValuesSeries2.default, + memoize: _memoize2.default, + nextTick: _nextTick2.default, + parallel: _parallel2.default, + parallelLimit: _parallelLimit2.default, + priorityQueue: _priorityQueue2.default, + queue: _queue2.default, + race: _race2.default, + reduce: _reduce2.default, + reduceRight: _reduceRight2.default, + reflect: _reflect2.default, + reflectAll: _reflectAll2.default, + reject: _reject2.default, + rejectLimit: _rejectLimit2.default, + rejectSeries: _rejectSeries2.default, + retry: _retry2.default, + retryable: _retryable2.default, + seq: _seq2.default, + series: _series2.default, + setImmediate: _setImmediate2.default, + some: _some2.default, + someLimit: _someLimit2.default, + someSeries: _someSeries2.default, + sortBy: _sortBy2.default, + timeout: _timeout2.default, + times: _times2.default, + timesLimit: _timesLimit2.default, + timesSeries: _timesSeries2.default, + transform: _transform2.default, + tryEach: _tryEach2.default, + unmemoize: _unmemoize2.default, + until: _until2.default, + waterfall: _waterfall2.default, + whilst: _whilst2.default, + + // aliases + all: _every2.default, + allLimit: _everyLimit2.default, + allSeries: _everySeries2.default, + any: _some2.default, + anyLimit: _someLimit2.default, + anySeries: _someSeries2.default, + find: _detect2.default, + findLimit: _detectLimit2.default, + findSeries: _detectSeries2.default, + flatMap: _concat2.default, + flatMapLimit: _concatLimit2.default, + flatMapSeries: _concatSeries2.default, + forEach: _each2.default, + forEachSeries: _eachSeries2.default, + forEachLimit: _eachLimit2.default, + forEachOf: _eachOf2.default, + forEachOfSeries: _eachOfSeries2.default, + forEachOfLimit: _eachOfLimit2.default, + inject: _reduce2.default, + foldl: _reduce2.default, + foldr: _reduceRight2.default, + select: _filter2.default, + selectLimit: _filterLimit2.default, + selectSeries: _filterSeries2.default, + wrapSync: _asyncify2.default, + during: _whilst2.default, + doDuring: _doWhilst2.default +}; +exports.apply = _apply2.default; +exports.applyEach = _applyEach2.default; +exports.applyEachSeries = _applyEachSeries2.default; +exports.asyncify = _asyncify2.default; +exports.auto = _auto2.default; +exports.autoInject = _autoInject2.default; +exports.cargo = _cargo2.default; +exports.cargoQueue = _cargoQueue2.default; +exports.compose = _compose2.default; +exports.concat = _concat2.default; +exports.concatLimit = _concatLimit2.default; +exports.concatSeries = _concatSeries2.default; +exports.constant = _constant2.default; +exports.detect = _detect2.default; +exports.detectLimit = _detectLimit2.default; +exports.detectSeries = _detectSeries2.default; +exports.dir = _dir2.default; +exports.doUntil = _doUntil2.default; +exports.doWhilst = _doWhilst2.default; +exports.each = _each2.default; +exports.eachLimit = _eachLimit2.default; +exports.eachOf = _eachOf2.default; +exports.eachOfLimit = _eachOfLimit2.default; +exports.eachOfSeries = _eachOfSeries2.default; +exports.eachSeries = _eachSeries2.default; +exports.ensureAsync = _ensureAsync2.default; +exports.every = _every2.default; +exports.everyLimit = _everyLimit2.default; +exports.everySeries = _everySeries2.default; +exports.filter = _filter2.default; +exports.filterLimit = _filterLimit2.default; +exports.filterSeries = _filterSeries2.default; +exports.forever = _forever2.default; +exports.groupBy = _groupBy2.default; +exports.groupByLimit = _groupByLimit2.default; +exports.groupBySeries = _groupBySeries2.default; +exports.log = _log2.default; +exports.map = _map2.default; +exports.mapLimit = _mapLimit2.default; +exports.mapSeries = _mapSeries2.default; +exports.mapValues = _mapValues2.default; +exports.mapValuesLimit = _mapValuesLimit2.default; +exports.mapValuesSeries = _mapValuesSeries2.default; +exports.memoize = _memoize2.default; +exports.nextTick = _nextTick2.default; +exports.parallel = _parallel2.default; +exports.parallelLimit = _parallelLimit2.default; +exports.priorityQueue = _priorityQueue2.default; +exports.queue = _queue2.default; +exports.race = _race2.default; +exports.reduce = _reduce2.default; +exports.reduceRight = _reduceRight2.default; +exports.reflect = _reflect2.default; +exports.reflectAll = _reflectAll2.default; +exports.reject = _reject2.default; +exports.rejectLimit = _rejectLimit2.default; +exports.rejectSeries = _rejectSeries2.default; +exports.retry = _retry2.default; +exports.retryable = _retryable2.default; +exports.seq = _seq2.default; +exports.series = _series2.default; +exports.setImmediate = _setImmediate2.default; +exports.some = _some2.default; +exports.someLimit = _someLimit2.default; +exports.someSeries = _someSeries2.default; +exports.sortBy = _sortBy2.default; +exports.timeout = _timeout2.default; +exports.times = _times2.default; +exports.timesLimit = _timesLimit2.default; +exports.timesSeries = _timesSeries2.default; +exports.transform = _transform2.default; +exports.tryEach = _tryEach2.default; +exports.unmemoize = _unmemoize2.default; +exports.until = _until2.default; +exports.waterfall = _waterfall2.default; +exports.whilst = _whilst2.default; +exports.all = _every2.default; +exports.allLimit = _everyLimit2.default; +exports.allSeries = _everySeries2.default; +exports.any = _some2.default; +exports.anyLimit = _someLimit2.default; +exports.anySeries = _someSeries2.default; +exports.find = _detect2.default; +exports.findLimit = _detectLimit2.default; +exports.findSeries = _detectSeries2.default; +exports.flatMap = _concat2.default; +exports.flatMapLimit = _concatLimit2.default; +exports.flatMapSeries = _concatSeries2.default; +exports.forEach = _each2.default; +exports.forEachSeries = _eachSeries2.default; +exports.forEachLimit = _eachLimit2.default; +exports.forEachOf = _eachOf2.default; +exports.forEachOfSeries = _eachOfSeries2.default; +exports.forEachOfLimit = _eachOfLimit2.default; +exports.inject = _reduce2.default; +exports.foldl = _reduce2.default; +exports.foldr = _reduceRight2.default; +exports.select = _filter2.default; +exports.selectLimit = _filterLimit2.default; +exports.selectSeries = _filterSeries2.default; +exports.wrapSync = _asyncify2.default; +exports.during = _whilst2.default; +exports.doDuring = _doWhilst2.default; \ No newline at end of file diff --git a/node_modules/async/inject.js b/node_modules/async/inject.js new file mode 100644 index 0000000..8a69548 --- /dev/null +++ b/node_modules/async/inject.js @@ -0,0 +1,153 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Reduces `coll` into a single value using an async `iteratee` to return each + * successive step. `memo` is the initial state of the reduction. This function + * only operates in series. + * + * For performance reasons, it may make sense to split a call to this function + * into a parallel map, and then use the normal `Array.prototype.reduce` on the + * results. This function is for situations where each step in the reduction + * needs to be async; if you can get the data before reducing it, then it's + * probably a good idea to do so. + * + * @name reduce + * @static + * @memberOf module:Collections + * @method + * @alias inject + * @alias foldl + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt']; + * + * // asynchronous function that computes the file size in bytes + * // file size is added to the memoized value, then returned + * function getFileSizeInBytes(memo, file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, memo + stat.size); + * }); + * } + * + * // Using callbacks + * async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.reduce(fileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.reduce(fileList, 0, getFileSizeInBytes); + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function reduce(coll, memo, iteratee, callback) { + callback = (0, _once2.default)(callback); + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _eachOfSeries2.default)(coll, (x, i, iterCb) => { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); +} +exports.default = (0, _awaitify2.default)(reduce, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/DoublyLinkedList.js b/node_modules/async/internal/DoublyLinkedList.js new file mode 100644 index 0000000..419ce44 --- /dev/null +++ b/node_modules/async/internal/DoublyLinkedList.js @@ -0,0 +1,92 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation +// used for queues. This implementation assumes that the node provided by the user can be modified +// to adjust the next and last properties. We implement only the minimal functionality +// for queue support. +class DLL { + constructor() { + this.head = this.tail = null; + this.length = 0; + } + + removeLink(node) { + if (node.prev) node.prev.next = node.next;else this.head = node.next; + if (node.next) node.next.prev = node.prev;else this.tail = node.prev; + + node.prev = node.next = null; + this.length -= 1; + return node; + } + + empty() { + while (this.head) this.shift(); + return this; + } + + insertAfter(node, newNode) { + newNode.prev = node; + newNode.next = node.next; + if (node.next) node.next.prev = newNode;else this.tail = newNode; + node.next = newNode; + this.length += 1; + } + + insertBefore(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode;else this.head = newNode; + node.prev = newNode; + this.length += 1; + } + + unshift(node) { + if (this.head) this.insertBefore(this.head, node);else setInitial(this, node); + } + + push(node) { + if (this.tail) this.insertAfter(this.tail, node);else setInitial(this, node); + } + + shift() { + return this.head && this.removeLink(this.head); + } + + pop() { + return this.tail && this.removeLink(this.tail); + } + + toArray() { + return [...this]; + } + + *[Symbol.iterator]() { + var cur = this.head; + while (cur) { + yield cur.data; + cur = cur.next; + } + } + + remove(testFn) { + var curr = this.head; + while (curr) { + var { next } = curr; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; + } +} + +exports.default = DLL; +function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/Heap.js b/node_modules/async/internal/Heap.js new file mode 100644 index 0000000..7867c92 --- /dev/null +++ b/node_modules/async/internal/Heap.js @@ -0,0 +1,120 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +// Binary min-heap implementation used for priority queue. +// Implementation is stable, i.e. push time is considered for equal priorities +class Heap { + constructor() { + this.heap = []; + this.pushCount = Number.MIN_SAFE_INTEGER; + } + + get length() { + return this.heap.length; + } + + empty() { + this.heap = []; + return this; + } + + percUp(index) { + let p; + + while (index > 0 && smaller(this.heap[index], this.heap[p = parent(index)])) { + let t = this.heap[index]; + this.heap[index] = this.heap[p]; + this.heap[p] = t; + + index = p; + } + } + + percDown(index) { + let l; + + while ((l = leftChi(index)) < this.heap.length) { + if (l + 1 < this.heap.length && smaller(this.heap[l + 1], this.heap[l])) { + l = l + 1; + } + + if (smaller(this.heap[index], this.heap[l])) { + break; + } + + let t = this.heap[index]; + this.heap[index] = this.heap[l]; + this.heap[l] = t; + + index = l; + } + } + + push(node) { + node.pushCount = ++this.pushCount; + this.heap.push(node); + this.percUp(this.heap.length - 1); + } + + unshift(node) { + return this.heap.push(node); + } + + shift() { + let [top] = this.heap; + + this.heap[0] = this.heap[this.heap.length - 1]; + this.heap.pop(); + this.percDown(0); + + return top; + } + + toArray() { + return [...this]; + } + + *[Symbol.iterator]() { + for (let i = 0; i < this.heap.length; i++) { + yield this.heap[i].data; + } + } + + remove(testFn) { + let j = 0; + for (let i = 0; i < this.heap.length; i++) { + if (!testFn(this.heap[i])) { + this.heap[j] = this.heap[i]; + j++; + } + } + + this.heap.splice(j); + + for (let i = parent(this.heap.length - 1); i >= 0; i--) { + this.percDown(i); + } + + return this; + } +} + +exports.default = Heap; +function leftChi(i) { + return (i << 1) + 1; +} + +function parent(i) { + return (i + 1 >> 1) - 1; +} + +function smaller(x, y) { + if (x.priority !== y.priority) { + return x.priority < y.priority; + } else { + return x.pushCount < y.pushCount; + } +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/applyEach.js b/node_modules/async/internal/applyEach.js new file mode 100644 index 0000000..5444912 --- /dev/null +++ b/node_modules/async/internal/applyEach.js @@ -0,0 +1,29 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (eachfn) { + return function applyEach(fns, ...callArgs) { + const go = (0, _awaitify2.default)(function (callback) { + var that = this; + return eachfn(fns, (fn, cb) => { + (0, _wrapAsync2.default)(fn).apply(that, callArgs.concat(cb)); + }, callback); + }); + return go; + }; +}; + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/asyncEachOfLimit.js b/node_modules/async/internal/asyncEachOfLimit.js new file mode 100644 index 0000000..34dd82b --- /dev/null +++ b/node_modules/async/internal/asyncEachOfLimit.js @@ -0,0 +1,75 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = asyncEachOfLimit; + +var _breakLoop = require('./breakLoop.js'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// for async generators +function asyncEachOfLimit(generator, limit, iteratee, callback) { + let done = false; + let canceled = false; + let awaiting = false; + let running = 0; + let idx = 0; + + function replenish() { + //console.log('replenish') + if (running >= limit || awaiting || done) return; + //console.log('replenish awaiting') + awaiting = true; + generator.next().then(({ value, done: iterDone }) => { + //console.log('got value', value) + if (canceled || done) return; + awaiting = false; + if (iterDone) { + done = true; + if (running <= 0) { + //console.log('done nextCb') + callback(null); + } + return; + } + running++; + iteratee(value, idx, iterateeCallback); + idx++; + replenish(); + }).catch(handleError); + } + + function iterateeCallback(err, result) { + //console.log('iterateeCallback') + running -= 1; + if (canceled) return; + if (err) return handleError(err); + + if (err === false) { + done = true; + canceled = true; + return; + } + + if (result === _breakLoop2.default || done && running <= 0) { + done = true; + //console.log('done iterCb') + return callback(null); + } + replenish(); + } + + function handleError(err) { + if (canceled) return; + awaiting = false; + done = true; + callback(err); + } + + replenish(); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/awaitify.js b/node_modules/async/internal/awaitify.js new file mode 100644 index 0000000..bb7a609 --- /dev/null +++ b/node_modules/async/internal/awaitify.js @@ -0,0 +1,28 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = awaitify; +// conditionally promisify a function. +// only return a promise if a callback is omitted +function awaitify(asyncFn, arity) { + if (!arity) arity = asyncFn.length; + if (!arity) throw new Error('arity is undefined'); + function awaitable(...args) { + if (typeof args[arity - 1] === 'function') { + return asyncFn.apply(this, args); + } + + return new Promise((resolve, reject) => { + args[arity - 1] = (err, ...cbArgs) => { + if (err) return reject(err); + resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); + }; + asyncFn.apply(this, args); + }); + } + + return awaitable; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/breakLoop.js b/node_modules/async/internal/breakLoop.js new file mode 100644 index 0000000..87413dd --- /dev/null +++ b/node_modules/async/internal/breakLoop.js @@ -0,0 +1,10 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +// A temporary value used to identify if the loop should be broken. +// See #1064, #1293 +const breakLoop = {}; +exports.default = breakLoop; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/consoleFunc.js b/node_modules/async/internal/consoleFunc.js new file mode 100644 index 0000000..748d54b --- /dev/null +++ b/node_modules/async/internal/consoleFunc.js @@ -0,0 +1,31 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = consoleFunc; + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function consoleFunc(name) { + return (fn, ...args) => (0, _wrapAsync2.default)(fn)(...args, (err, ...resultArgs) => { + /* istanbul ignore else */ + if (typeof console === 'object') { + /* istanbul ignore else */ + if (err) { + /* istanbul ignore else */ + if (console.error) { + console.error(err); + } + } else if (console[name]) { + /* istanbul ignore else */ + resultArgs.forEach(x => console[name](x)); + } + } + }); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/createTester.js b/node_modules/async/internal/createTester.js new file mode 100644 index 0000000..cafdf62 --- /dev/null +++ b/node_modules/async/internal/createTester.js @@ -0,0 +1,40 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _createTester; + +var _breakLoop = require('./breakLoop.js'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _createTester(check, getResult) { + return (eachfn, arr, _iteratee, cb) => { + var testPassed = false; + var testResult; + const iteratee = (0, _wrapAsync2.default)(_iteratee); + eachfn(arr, (value, _, callback) => { + iteratee(value, (err, result) => { + if (err || err === false) return callback(err); + + if (check(result) && !testResult) { + testPassed = true; + testResult = getResult(true, value); + return callback(null, _breakLoop2.default); + } + callback(); + }); + }, err => { + if (err) return cb(err); + cb(null, testPassed ? testResult : getResult(false)); + }); + }; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/eachOfLimit.js b/node_modules/async/internal/eachOfLimit.js new file mode 100644 index 0000000..ceed60f --- /dev/null +++ b/node_modules/async/internal/eachOfLimit.js @@ -0,0 +1,90 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _once = require('./once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _iterator = require('./iterator.js'); + +var _iterator2 = _interopRequireDefault(_iterator); + +var _onlyOnce = require('./onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./wrapAsync.js'); + +var _asyncEachOfLimit = require('./asyncEachOfLimit.js'); + +var _asyncEachOfLimit2 = _interopRequireDefault(_asyncEachOfLimit); + +var _breakLoop = require('./breakLoop.js'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = limit => { + return (obj, iteratee, callback) => { + callback = (0, _once2.default)(callback); + if (limit <= 0) { + throw new RangeError('concurrency limit cannot be less than 1'); + } + if (!obj) { + return callback(null); + } + if ((0, _wrapAsync.isAsyncGenerator)(obj)) { + return (0, _asyncEachOfLimit2.default)(obj, limit, iteratee, callback); + } + if ((0, _wrapAsync.isAsyncIterable)(obj)) { + return (0, _asyncEachOfLimit2.default)(obj[Symbol.asyncIterator](), limit, iteratee, callback); + } + var nextElem = (0, _iterator2.default)(obj); + var done = false; + var canceled = false; + var running = 0; + var looping = false; + + function iterateeCallback(err, value) { + if (canceled) return; + running -= 1; + if (err) { + done = true; + callback(err); + } else if (err === false) { + done = true; + canceled = true; + } else if (value === _breakLoop2.default || done && running <= 0) { + done = true; + return callback(null); + } else if (!looping) { + replenish(); + } + } + + function replenish() { + looping = true; + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iteratee(elem.value, elem.key, (0, _onlyOnce2.default)(iterateeCallback)); + } + looping = false; + } + + replenish(); + }; +}; + +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/filter.js b/node_modules/async/internal/filter.js new file mode 100644 index 0000000..065c211 --- /dev/null +++ b/node_modules/async/internal/filter.js @@ -0,0 +1,55 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _filter; + +var _isArrayLike = require('./isArrayLike.js'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function filterArray(eachfn, arr, iteratee, callback) { + var truthValues = new Array(arr.length); + eachfn(arr, (x, index, iterCb) => { + iteratee(x, (err, v) => { + truthValues[index] = !!v; + iterCb(err); + }); + }, err => { + if (err) return callback(err); + var results = []; + for (var i = 0; i < arr.length; i++) { + if (truthValues[i]) results.push(arr[i]); + } + callback(null, results); + }); +} + +function filterGeneric(eachfn, coll, iteratee, callback) { + var results = []; + eachfn(coll, (x, index, iterCb) => { + iteratee(x, (err, v) => { + if (err) return iterCb(err); + if (v) { + results.push({ index, value: x }); + } + iterCb(err); + }); + }, err => { + if (err) return callback(err); + callback(null, results.sort((a, b) => a.index - b.index).map(v => v.value)); + }); +} + +function _filter(eachfn, coll, iteratee, callback) { + var filter = (0, _isArrayLike2.default)(coll) ? filterArray : filterGeneric; + return filter(eachfn, coll, (0, _wrapAsync2.default)(iteratee), callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/getIterator.js b/node_modules/async/internal/getIterator.js new file mode 100644 index 0000000..f518fce --- /dev/null +++ b/node_modules/async/internal/getIterator.js @@ -0,0 +1,11 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (coll) { + return coll[Symbol.iterator] && coll[Symbol.iterator](); +}; + +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/initialParams.js b/node_modules/async/internal/initialParams.js new file mode 100644 index 0000000..04c0eff --- /dev/null +++ b/node_modules/async/internal/initialParams.js @@ -0,0 +1,14 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (fn) { + return function (...args /*, callback*/) { + var callback = args.pop(); + return fn.call(this, args, callback); + }; +}; + +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/isArrayLike.js b/node_modules/async/internal/isArrayLike.js new file mode 100644 index 0000000..a4c4c8a --- /dev/null +++ b/node_modules/async/internal/isArrayLike.js @@ -0,0 +1,10 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isArrayLike; +function isArrayLike(value) { + return value && typeof value.length === 'number' && value.length >= 0 && value.length % 1 === 0; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/iterator.js b/node_modules/async/internal/iterator.js new file mode 100644 index 0000000..5778b1e --- /dev/null +++ b/node_modules/async/internal/iterator.js @@ -0,0 +1,57 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = createIterator; + +var _isArrayLike = require('./isArrayLike.js'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _getIterator = require('./getIterator.js'); + +var _getIterator2 = _interopRequireDefault(_getIterator); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? { value: coll[i], key: i } : null; + }; +} + +function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) return null; + i++; + return { value: item.value, key: i }; + }; +} + +function createObjectIterator(obj) { + var okeys = obj ? Object.keys(obj) : []; + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + if (key === '__proto__') { + return next(); + } + return i < len ? { value: obj[key], key } : null; + }; +} + +function createIterator(coll) { + if ((0, _isArrayLike2.default)(coll)) { + return createArrayIterator(coll); + } + + var iterator = (0, _getIterator2.default)(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/map.js b/node_modules/async/internal/map.js new file mode 100644 index 0000000..acab1e7 --- /dev/null +++ b/node_modules/async/internal/map.js @@ -0,0 +1,30 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _asyncMap; + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _asyncMap(eachfn, arr, iteratee, callback) { + arr = arr || []; + var results = []; + var counter = 0; + var _iteratee = (0, _wrapAsync2.default)(iteratee); + + return eachfn(arr, (value, _, iterCb) => { + var index = counter++; + _iteratee(value, (err, v) => { + results[index] = v; + iterCb(err); + }); + }, err => { + callback(err, results); + }); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/once.js b/node_modules/async/internal/once.js new file mode 100644 index 0000000..a8b5792 --- /dev/null +++ b/node_modules/async/internal/once.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = once; +function once(fn) { + function wrapper(...args) { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, args); + } + Object.assign(wrapper, fn); + return wrapper; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/onlyOnce.js b/node_modules/async/internal/onlyOnce.js new file mode 100644 index 0000000..c95a92d --- /dev/null +++ b/node_modules/async/internal/onlyOnce.js @@ -0,0 +1,15 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = onlyOnce; +function onlyOnce(fn) { + return function (...args) { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; + callFn.apply(this, args); + }; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/parallel.js b/node_modules/async/internal/parallel.js new file mode 100644 index 0000000..57fbd0d --- /dev/null +++ b/node_modules/async/internal/parallel.js @@ -0,0 +1,34 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _isArrayLike = require('./isArrayLike.js'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = (0, _awaitify2.default)((eachfn, tasks, callback) => { + var results = (0, _isArrayLike2.default)(tasks) ? [] : {}; + + eachfn(tasks, (task, key, taskCb) => { + (0, _wrapAsync2.default)(task)((err, ...result) => { + if (result.length < 2) { + [result] = result; + } + results[key] = result; + taskCb(err); + }); + }, err => callback(err, results)); +}, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/promiseCallback.js b/node_modules/async/internal/promiseCallback.js new file mode 100644 index 0000000..17a8301 --- /dev/null +++ b/node_modules/async/internal/promiseCallback.js @@ -0,0 +1,23 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +const PROMISE_SYMBOL = Symbol('promiseCallback'); + +function promiseCallback() { + let resolve, reject; + function callback(err, ...args) { + if (err) return reject(err); + resolve(args.length > 1 ? args : args[0]); + } + + callback[PROMISE_SYMBOL] = new Promise((res, rej) => { + resolve = res, reject = rej; + }); + + return callback; +} + +exports.promiseCallback = promiseCallback; +exports.PROMISE_SYMBOL = PROMISE_SYMBOL; \ No newline at end of file diff --git a/node_modules/async/internal/queue.js b/node_modules/async/internal/queue.js new file mode 100644 index 0000000..7414e03 --- /dev/null +++ b/node_modules/async/internal/queue.js @@ -0,0 +1,294 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = queue; + +var _onlyOnce = require('./onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _setImmediate = require('./setImmediate.js'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _DoublyLinkedList = require('./DoublyLinkedList.js'); + +var _DoublyLinkedList2 = _interopRequireDefault(_DoublyLinkedList); + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function queue(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } else if (concurrency === 0) { + throw new RangeError('Concurrency must not be zero'); + } + + var _worker = (0, _wrapAsync2.default)(worker); + var numRunning = 0; + var workersList = []; + const events = { + error: [], + drain: [], + saturated: [], + unsaturated: [], + empty: [] + }; + + function on(event, handler) { + events[event].push(handler); + } + + function once(event, handler) { + const handleAndRemove = (...args) => { + off(event, handleAndRemove); + handler(...args); + }; + events[event].push(handleAndRemove); + } + + function off(event, handler) { + if (!event) return Object.keys(events).forEach(ev => events[ev] = []); + if (!handler) return events[event] = []; + events[event] = events[event].filter(ev => ev !== handler); + } + + function trigger(event, ...args) { + events[event].forEach(handler => handler(...args)); + } + + var processingScheduled = false; + function _insert(data, insertAtFront, rejectOnError, callback) { + if (callback != null && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + + var res, rej; + function promiseCallback(err, ...args) { + // we don't care about the error, let the global error handler + // deal with it + if (err) return rejectOnError ? rej(err) : res(); + if (args.length <= 1) return res(args[0]); + res(args); + } + + var item = q._createTaskItem(data, rejectOnError ? promiseCallback : callback || promiseCallback); + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + if (!processingScheduled) { + processingScheduled = true; + (0, _setImmediate2.default)(() => { + processingScheduled = false; + q.process(); + }); + } + + if (rejectOnError || !callback) { + return new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }); + } + } + + function _createCB(tasks) { + return function (err, ...args) { + numRunning -= 1; + + for (var i = 0, l = tasks.length; i < l; i++) { + var task = tasks[i]; + + var index = workersList.indexOf(task); + if (index === 0) { + workersList.shift(); + } else if (index > 0) { + workersList.splice(index, 1); + } + + task.callback(err, ...args); + + if (err != null) { + trigger('error', err, task.data); + } + } + + if (numRunning <= q.concurrency - q.buffer) { + trigger('unsaturated'); + } + + if (q.idle()) { + trigger('drain'); + } + q.process(); + }; + } + + function _maybeDrain(data) { + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + (0, _setImmediate2.default)(() => trigger('drain')); + return true; + } + return false; + } + + const eventMethod = name => handler => { + if (!handler) { + return new Promise((resolve, reject) => { + once(name, (err, data) => { + if (err) return reject(err); + resolve(data); + }); + }); + } + off(name); + on(name, handler); + }; + + var isProcessing = false; + var q = { + _tasks: new _DoublyLinkedList2.default(), + _createTaskItem(data, callback) { + return { + data, + callback + }; + }, + *[Symbol.iterator]() { + yield* q._tasks[Symbol.iterator](); + }, + concurrency, + payload, + buffer: concurrency / 4, + started: false, + paused: false, + push(data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return; + return data.map(datum => _insert(datum, false, false, callback)); + } + return _insert(data, false, false, callback); + }, + pushAsync(data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return; + return data.map(datum => _insert(datum, false, true, callback)); + } + return _insert(data, false, true, callback); + }, + kill() { + off(); + q._tasks.empty(); + }, + unshift(data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return; + return data.map(datum => _insert(datum, true, false, callback)); + } + return _insert(data, true, false, callback); + }, + unshiftAsync(data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return; + return data.map(datum => _insert(datum, true, true, callback)); + } + return _insert(data, true, true, callback); + }, + remove(testFn) { + q._tasks.remove(testFn); + }, + process() { + // Avoid trying to start too many processing operations. This can occur + // when callbacks resolve synchronously (#1267). + if (isProcessing) { + return; + } + isProcessing = true; + while (!q.paused && numRunning < q.concurrency && q._tasks.length) { + var tasks = [], + data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); + tasks.push(node); + workersList.push(node); + data.push(node.data); + } + + numRunning += 1; + + if (q._tasks.length === 0) { + trigger('empty'); + } + + if (numRunning === q.concurrency) { + trigger('saturated'); + } + + var cb = (0, _onlyOnce2.default)(_createCB(tasks)); + _worker(data, cb); + } + isProcessing = false; + }, + length() { + return q._tasks.length; + }, + running() { + return numRunning; + }, + workersList() { + return workersList; + }, + idle() { + return q._tasks.length + numRunning === 0; + }, + pause() { + q.paused = true; + }, + resume() { + if (q.paused === false) { + return; + } + q.paused = false; + (0, _setImmediate2.default)(q.process); + } + }; + // define these as fixed properties, so people get useful errors when updating + Object.defineProperties(q, { + saturated: { + writable: false, + value: eventMethod('saturated') + }, + unsaturated: { + writable: false, + value: eventMethod('unsaturated') + }, + empty: { + writable: false, + value: eventMethod('empty') + }, + drain: { + writable: false, + value: eventMethod('drain') + }, + error: { + writable: false, + value: eventMethod('error') + } + }); + return q; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/range.js b/node_modules/async/internal/range.js new file mode 100644 index 0000000..cc7b3a9 --- /dev/null +++ b/node_modules/async/internal/range.js @@ -0,0 +1,14 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = range; +function range(size) { + var result = Array(size); + while (size--) { + result[size] = size; + } + return result; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/reject.js b/node_modules/async/internal/reject.js new file mode 100644 index 0000000..9d9bc80 --- /dev/null +++ b/node_modules/async/internal/reject.js @@ -0,0 +1,26 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reject; + +var _filter = require('./filter.js'); + +var _filter2 = _interopRequireDefault(_filter); + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function reject(eachfn, arr, _iteratee, callback) { + const iteratee = (0, _wrapAsync2.default)(_iteratee); + return (0, _filter2.default)(eachfn, arr, (value, cb) => { + iteratee(value, (err, v) => { + cb(err, !v); + }); + }, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/setImmediate.js b/node_modules/async/internal/setImmediate.js new file mode 100644 index 0000000..513efd1 --- /dev/null +++ b/node_modules/async/internal/setImmediate.js @@ -0,0 +1,34 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.fallback = fallback; +exports.wrap = wrap; +/* istanbul ignore file */ + +var hasQueueMicrotask = exports.hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask; +var hasSetImmediate = exports.hasSetImmediate = typeof setImmediate === 'function' && setImmediate; +var hasNextTick = exports.hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; + +function fallback(fn) { + setTimeout(fn, 0); +} + +function wrap(defer) { + return (fn, ...args) => defer(() => fn(...args)); +} + +var _defer; + +if (hasQueueMicrotask) { + _defer = queueMicrotask; +} else if (hasSetImmediate) { + _defer = setImmediate; +} else if (hasNextTick) { + _defer = process.nextTick; +} else { + _defer = fallback; +} + +exports.default = wrap(_defer); \ No newline at end of file diff --git a/node_modules/async/internal/withoutIndex.js b/node_modules/async/internal/withoutIndex.js new file mode 100644 index 0000000..fa91c2d --- /dev/null +++ b/node_modules/async/internal/withoutIndex.js @@ -0,0 +1,10 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _withoutIndex; +function _withoutIndex(iteratee) { + return (value, index, callback) => iteratee(value, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/wrapAsync.js b/node_modules/async/internal/wrapAsync.js new file mode 100644 index 0000000..ad4d619 --- /dev/null +++ b/node_modules/async/internal/wrapAsync.js @@ -0,0 +1,34 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isAsyncIterable = exports.isAsyncGenerator = exports.isAsync = undefined; + +var _asyncify = require('../asyncify.js'); + +var _asyncify2 = _interopRequireDefault(_asyncify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function isAsync(fn) { + return fn[Symbol.toStringTag] === 'AsyncFunction'; +} + +function isAsyncGenerator(fn) { + return fn[Symbol.toStringTag] === 'AsyncGenerator'; +} + +function isAsyncIterable(obj) { + return typeof obj[Symbol.asyncIterator] === 'function'; +} + +function wrapAsync(asyncFn) { + if (typeof asyncFn !== 'function') throw new Error('expected a function'); + return isAsync(asyncFn) ? (0, _asyncify2.default)(asyncFn) : asyncFn; +} + +exports.default = wrapAsync; +exports.isAsync = isAsync; +exports.isAsyncGenerator = isAsyncGenerator; +exports.isAsyncIterable = isAsyncIterable; \ No newline at end of file diff --git a/node_modules/async/log.js b/node_modules/async/log.js new file mode 100644 index 0000000..332b9da --- /dev/null +++ b/node_modules/async/log.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _consoleFunc = require('./internal/consoleFunc.js'); + +var _consoleFunc2 = _interopRequireDefault(_consoleFunc); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Logs the result of an `async` function to the `console`. Only works in + * Node.js or in browsers that support `console.log` and `console.error` (such + * as FF and Chrome). If multiple arguments are returned from the async + * function, `console.log` is called on each argument in order. + * + * @name log + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, 'hello ' + name); + * }, 1000); + * }; + * + * // in the node repl + * node> async.log(hello, 'world'); + * 'hello world' + */ +exports.default = (0, _consoleFunc2.default)('log'); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/map.js b/node_modules/async/map.js new file mode 100644 index 0000000..c4b7a5a --- /dev/null +++ b/node_modules/async/map.js @@ -0,0 +1,142 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _map2 = require('./internal/map.js'); + +var _map3 = _interopRequireDefault(_map2); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Produces a new collection of values by mapping each value in `coll` through + * the `iteratee` function. The `iteratee` is called with an item from `coll` + * and a callback for when it has finished processing. Each of these callbacks + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.map(fileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.map(fileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.map(fileList, getFileSizeInBytes); + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.map(withMissingFileList, getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function map(coll, iteratee, callback) { + return (0, _map3.default)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(map, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/mapLimit.js b/node_modules/async/mapLimit.js new file mode 100644 index 0000000..6ad3572 --- /dev/null +++ b/node_modules/async/mapLimit.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _map2 = require('./internal/map.js'); + +var _map3 = _interopRequireDefault(_map2); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. + * + * @name mapLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function mapLimit(coll, limit, iteratee, callback) { + return (0, _map3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(mapLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/mapSeries.js b/node_modules/async/mapSeries.js new file mode 100644 index 0000000..8dfdd8a --- /dev/null +++ b/node_modules/async/mapSeries.js @@ -0,0 +1,44 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _map2 = require('./internal/map.js'); + +var _map3 = _interopRequireDefault(_map2); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. + * + * @name mapSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function mapSeries(coll, iteratee, callback) { + return (0, _map3.default)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(mapSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/mapValues.js b/node_modules/async/mapValues.js new file mode 100644 index 0000000..3d0470e --- /dev/null +++ b/node_modules/async/mapValues.js @@ -0,0 +1,152 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = mapValues; + +var _mapValuesLimit = require('./mapValuesLimit.js'); + +var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. + * + * Produces a new Object by mapping each value of `obj` through the `iteratee` + * function. The `iteratee` is called each `value` and `key` from `obj` and a + * callback for when it has finished processing. Each of these callbacks takes + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` + * passes an error to its callback, the main `callback` (for the `mapValues` + * function) is immediately called with the error. + * + * Note, the order of the keys in the result is not guaranteed. The keys will + * be roughly in the order they complete, (but this is very engine-specific) + * + * @name mapValues + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file3.txt' + * }; + * + * const withMissingFileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file4.txt' + * }; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, key, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.mapValues(fileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * }); + * + * // Error handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.mapValues(fileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * }).catch (err => { + * console.log(err); + * }); + * + * // Error Handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch (err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.mapValues(fileMap, getFileSizeInBytes); + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function mapValues(obj, iteratee, callback) { + return (0, _mapValuesLimit2.default)(obj, Infinity, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/mapValuesLimit.js b/node_modules/async/mapValuesLimit.js new file mode 100644 index 0000000..f59e36f --- /dev/null +++ b/node_modules/async/mapValuesLimit.js @@ -0,0 +1,61 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a + * time. + * + * @name mapValuesLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function mapValuesLimit(obj, limit, iteratee, callback) { + callback = (0, _once2.default)(callback); + var newObj = {}; + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _eachOfLimit2.default)(limit)(obj, (val, key, next) => { + _iteratee(val, key, (err, result) => { + if (err) return next(err); + newObj[key] = result; + next(err); + }); + }, err => callback(err, newObj)); +} + +exports.default = (0, _awaitify2.default)(mapValuesLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/mapValuesSeries.js b/node_modules/async/mapValuesSeries.js new file mode 100644 index 0000000..5f05bf2 --- /dev/null +++ b/node_modules/async/mapValuesSeries.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = mapValuesSeries; + +var _mapValuesLimit = require('./mapValuesLimit.js'); + +var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. + * + * @name mapValuesSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function mapValuesSeries(obj, iteratee, callback) { + return (0, _mapValuesLimit2.default)(obj, 1, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/memoize.js b/node_modules/async/memoize.js new file mode 100644 index 0000000..6535d4e --- /dev/null +++ b/node_modules/async/memoize.js @@ -0,0 +1,91 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = memoize; + +var _setImmediate = require('./internal/setImmediate.js'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _initialParams = require('./internal/initialParams.js'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Caches the results of an async function. When creating a hash to store + * function results against, the callback is omitted from the hash and an + * optional hash function can be used. + * + * **Note: if the async function errs, the result will not be cached and + * subsequent calls will call the wrapped function.** + * + * If no hash function is specified, the first argument is used as a hash key, + * which may work reasonably if it is a string or a data type that converts to a + * distinct string. Note that objects and arrays will not behave reasonably. + * Neither will cases where the other arguments are significant. In such cases, + * specify your own hash function. + * + * The cache of results is exposed as the `memo` property of the function + * returned by `memoize`. + * + * @name memoize + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function to proxy and cache results from. + * @param {Function} hasher - An optional function for generating a custom hash + * for storing results. It has all the arguments applied to it apart from the + * callback, and must be synchronous. + * @returns {AsyncFunction} a memoized version of `fn` + * @example + * + * var slow_fn = function(name, callback) { + * // do something + * callback(null, result); + * }; + * var fn = async.memoize(slow_fn); + * + * // fn can now be used as if it were slow_fn + * fn('some name', function() { + * // callback + * }); + */ +function memoize(fn, hasher = v => v) { + var memo = Object.create(null); + var queues = Object.create(null); + var _fn = (0, _wrapAsync2.default)(fn); + var memoized = (0, _initialParams2.default)((args, callback) => { + var key = hasher(...args); + if (key in memo) { + (0, _setImmediate2.default)(() => callback(null, ...memo[key])); + } else if (key in queues) { + queues[key].push(callback); + } else { + queues[key] = [callback]; + _fn(...args, (err, ...resultArgs) => { + // #1465 don't memoize if an error occurred + if (!err) { + memo[key] = resultArgs; + } + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i](err, ...resultArgs); + } + }); + } + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/nextTick.js b/node_modules/async/nextTick.js new file mode 100644 index 0000000..8ebfda9 --- /dev/null +++ b/node_modules/async/nextTick.js @@ -0,0 +1,52 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _setImmediate = require('./internal/setImmediate.js'); + +/** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `process.nextTick`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name nextTick + * @static + * @memberOf module:Utils + * @method + * @see [async.setImmediate]{@link module:Utils.setImmediate} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ +var _defer; /* istanbul ignore file */ + + +if (_setImmediate.hasNextTick) { + _defer = process.nextTick; +} else if (_setImmediate.hasSetImmediate) { + _defer = setImmediate; +} else { + _defer = _setImmediate.fallback; +} + +exports.default = (0, _setImmediate.wrap)(_defer); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/package.json b/node_modules/async/package.json new file mode 100644 index 0000000..bcf4c41 --- /dev/null +++ b/node_modules/async/package.json @@ -0,0 +1,75 @@ +{ + "name": "async", + "description": "Higher-order functions and common patterns for asynchronous code", + "version": "3.2.6", + "main": "dist/async.js", + "author": "Caolan McMahon", + "homepage": "https://caolan.github.io/async/", + "repository": { + "type": "git", + "url": "https://github.com/caolan/async.git" + }, + "bugs": { + "url": "https://github.com/caolan/async/issues" + }, + "keywords": [ + "async", + "callback", + "module", + "utility" + ], + "devDependencies": { + "@babel/eslint-parser": "^7.16.5", + "@babel/core": "7.25.2", + "babel-minify": "^0.5.0", + "babel-plugin-add-module-exports": "^1.0.4", + "babel-plugin-istanbul": "^7.0.0", + "babel-plugin-syntax-async-generators": "^6.13.0", + "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2", + "babel-preset-es2015": "^6.3.13", + "babel-preset-es2017": "^6.22.0", + "babel-register": "^6.26.0", + "babelify": "^10.0.0", + "benchmark": "^2.1.1", + "bluebird": "^3.4.6", + "browserify": "^17.0.0", + "chai": "^4.2.0", + "cheerio": "^0.22.0", + "es6-promise": "^4.2.8", + "eslint": "^8.6.0", + "eslint-plugin-prefer-arrow": "^1.2.3", + "fs-extra": "^11.1.1", + "jsdoc": "^4.0.3", + "karma": "^6.3.12", + "karma-browserify": "^8.1.0", + "karma-firefox-launcher": "^2.1.2", + "karma-mocha": "^2.0.1", + "karma-mocha-reporter": "^2.2.0", + "karma-safari-launcher": "^1.0.0", + "mocha": "^6.1.4", + "native-promise-only": "^0.8.0-a", + "nyc": "^17.0.0", + "rollup": "^4.2.0", + "rollup-plugin-node-resolve": "^5.2.0", + "rollup-plugin-npm": "^2.0.0", + "rsvp": "^4.8.5", + "semver": "^7.3.5", + "yargs": "^17.3.1" + }, + "scripts": { + "coverage": "nyc npm run mocha-node-test -- --grep @nycinvalid --invert", + "jsdoc": "jsdoc -c ./support/jsdoc/jsdoc.json && node support/jsdoc/jsdoc-fix-html.js", + "lint": "eslint --fix .", + "mocha-browser-test": "karma start", + "mocha-node-test": "mocha", + "mocha-test": "npm run mocha-node-test && npm run mocha-browser-test", + "test": "npm run lint && npm run mocha-node-test" + }, + "license": "MIT", + "nyc": { + "exclude": [ + "test" + ] + }, + "module": "dist/async.mjs" +} \ No newline at end of file diff --git a/node_modules/async/parallel.js b/node_modules/async/parallel.js new file mode 100644 index 0000000..2c7976f --- /dev/null +++ b/node_modules/async/parallel.js @@ -0,0 +1,180 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = parallel; + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _parallel2 = require('./internal/parallel.js'); + +var _parallel3 = _interopRequireDefault(_parallel2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Run the `tasks` collection of functions in parallel, without waiting until + * the previous function has completed. If any of the functions pass an error to + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * + * //Using Callbacks + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function parallel(tasks, callback) { + return (0, _parallel3.default)(_eachOf2.default, tasks, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/parallelLimit.js b/node_modules/async/parallelLimit.js new file mode 100644 index 0000000..4337957 --- /dev/null +++ b/node_modules/async/parallelLimit.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = parallelLimit; + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _parallel = require('./internal/parallel.js'); + +var _parallel2 = _interopRequireDefault(_parallel); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a + * time. + * + * @name parallelLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.parallel]{@link module:ControlFlow.parallel} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + */ +function parallelLimit(tasks, limit, callback) { + return (0, _parallel2.default)((0, _eachOfLimit2.default)(limit), tasks, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/priorityQueue.js b/node_modules/async/priorityQueue.js new file mode 100644 index 0000000..16c4daa --- /dev/null +++ b/node_modules/async/priorityQueue.js @@ -0,0 +1,60 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (worker, concurrency) { + // Start with a normal queue + var q = (0, _queue2.default)(worker, concurrency); + + var { + push, + pushAsync + } = q; + + q._tasks = new _Heap2.default(); + q._createTaskItem = ({ data, priority }, callback) => { + return { + data, + priority, + callback + }; + }; + + function createDataItems(tasks, priority) { + if (!Array.isArray(tasks)) { + return { data: tasks, priority }; + } + return tasks.map(data => { + return { data, priority }; + }); + } + + // Override push to accept second parameter representing priority + q.push = function (data, priority = 0, callback) { + return push(createDataItems(data, priority), callback); + }; + + q.pushAsync = function (data, priority = 0, callback) { + return pushAsync(createDataItems(data, priority), callback); + }; + + // Remove unshift functions + delete q.unshift; + delete q.unshiftAsync; + + return q; +}; + +var _queue = require('./queue.js'); + +var _queue2 = _interopRequireDefault(_queue); + +var _Heap = require('./internal/Heap.js'); + +var _Heap2 = _interopRequireDefault(_Heap); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/queue.js b/node_modules/async/queue.js new file mode 100644 index 0000000..c01340d --- /dev/null +++ b/node_modules/async/queue.js @@ -0,0 +1,24 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (worker, concurrency) { + var _worker = (0, _wrapAsync2.default)(worker); + return (0, _queue2.default)((items, cb) => { + _worker(items[0], cb); + }, concurrency, 1); +}; + +var _queue = require('./internal/queue.js'); + +var _queue2 = _interopRequireDefault(_queue); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/race.js b/node_modules/async/race.js new file mode 100644 index 0000000..aa167be --- /dev/null +++ b/node_modules/async/race.js @@ -0,0 +1,67 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Runs the `tasks` array of functions in parallel, without waiting until the + * previous function has completed. Once any of the `tasks` complete or pass an + * error to its callback, the main `callback` is immediately called. It's + * equivalent to `Promise.race()`. + * + * @name race + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} + * to run. Each function can complete with an optional `result` value. + * @param {Function} callback - A callback to run once any of the functions have + * completed. This function gets an error or result from the first function that + * completed. Invoked with (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.race([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // main callback + * function(err, result) { + * // the result will be equal to 'two' as it finishes earlier + * }); + */ +function race(tasks, callback) { + callback = (0, _once2.default)(callback); + if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); + if (!tasks.length) return callback(); + for (var i = 0, l = tasks.length; i < l; i++) { + (0, _wrapAsync2.default)(tasks[i])(callback); + } +} + +exports.default = (0, _awaitify2.default)(race, 2); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/reduce.js b/node_modules/async/reduce.js new file mode 100644 index 0000000..8a69548 --- /dev/null +++ b/node_modules/async/reduce.js @@ -0,0 +1,153 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Reduces `coll` into a single value using an async `iteratee` to return each + * successive step. `memo` is the initial state of the reduction. This function + * only operates in series. + * + * For performance reasons, it may make sense to split a call to this function + * into a parallel map, and then use the normal `Array.prototype.reduce` on the + * results. This function is for situations where each step in the reduction + * needs to be async; if you can get the data before reducing it, then it's + * probably a good idea to do so. + * + * @name reduce + * @static + * @memberOf module:Collections + * @method + * @alias inject + * @alias foldl + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt']; + * + * // asynchronous function that computes the file size in bytes + * // file size is added to the memoized value, then returned + * function getFileSizeInBytes(memo, file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, memo + stat.size); + * }); + * } + * + * // Using callbacks + * async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.reduce(fileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.reduce(fileList, 0, getFileSizeInBytes); + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function reduce(coll, memo, iteratee, callback) { + callback = (0, _once2.default)(callback); + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _eachOfSeries2.default)(coll, (x, i, iterCb) => { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); +} +exports.default = (0, _awaitify2.default)(reduce, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/reduceRight.js b/node_modules/async/reduceRight.js new file mode 100644 index 0000000..5be1b68 --- /dev/null +++ b/node_modules/async/reduceRight.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reduceRight; + +var _reduce = require('./reduce.js'); + +var _reduce2 = _interopRequireDefault(_reduce); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function reduceRight(array, memo, iteratee, callback) { + var reversed = [...array].reverse(); + return (0, _reduce2.default)(reversed, memo, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/reflect.js b/node_modules/async/reflect.js new file mode 100644 index 0000000..3954495 --- /dev/null +++ b/node_modules/async/reflect.js @@ -0,0 +1,78 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reflect; + +var _initialParams = require('./internal/initialParams.js'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Wraps the async function in another function that always completes with a + * result object, even when it errors. + * + * The result object has either the property `error` or `value`. + * + * @name reflect + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function you want to wrap + * @returns {Function} - A function that always passes null to it's callback as + * the error. The second argument to the callback will be an `object` with + * either an `error` or a `value` property. + * @example + * + * async.parallel([ + * async.reflect(function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }), + * async.reflect(function(callback) { + * // do some more stuff but error ... + * callback('bad stuff happened'); + * }), + * async.reflect(function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * }) + * ], + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = 'bad stuff happened' + * // results[2].value = 'two' + * }); + */ +function reflect(fn) { + var _fn = (0, _wrapAsync2.default)(fn); + return (0, _initialParams2.default)(function reflectOn(args, reflectCallback) { + args.push((error, ...cbArgs) => { + let retVal = {}; + if (error) { + retVal.error = error; + } + if (cbArgs.length > 0) { + var value = cbArgs; + if (cbArgs.length <= 1) { + [value] = cbArgs; + } + retVal.value = value; + } + reflectCallback(null, retVal); + }); + + return _fn.apply(this, args); + }); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/reflectAll.js b/node_modules/async/reflectAll.js new file mode 100644 index 0000000..b78d598 --- /dev/null +++ b/node_modules/async/reflectAll.js @@ -0,0 +1,93 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reflectAll; + +var _reflect = require('./reflect.js'); + +var _reflect2 = _interopRequireDefault(_reflect); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * A helper function that wraps an array or an object of functions with `reflect`. + * + * @name reflectAll + * @static + * @memberOf module:Utils + * @method + * @see [async.reflect]{@link module:Utils.reflect} + * @category Util + * @param {Array|Object|Iterable} tasks - The collection of + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. + * @returns {Array} Returns an array of async functions, each wrapped in + * `async.reflect` + * @example + * + * let tasks = [ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * // do some more stuff but error ... + * callback(new Error('bad stuff happened')); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = Error('bad stuff happened') + * // results[2].value = 'two' + * }); + * + * // an example using an object instead of an array + * let tasks = { + * one: function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * two: function(callback) { + * callback('two'); + * }, + * three: function(callback) { + * setTimeout(function() { + * callback(null, 'three'); + * }, 100); + * } + * }; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results.one.value = 'one' + * // results.two.error = 'two' + * // results.three.value = 'three' + * }); + */ +function reflectAll(tasks) { + var results; + if (Array.isArray(tasks)) { + results = tasks.map(_reflect2.default); + } else { + results = {}; + Object.keys(tasks).forEach(key => { + results[key] = _reflect2.default.call(this, tasks[key]); + }); + } + return results; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/reject.js b/node_modules/async/reject.js new file mode 100644 index 0000000..895949b --- /dev/null +++ b/node_modules/async/reject.js @@ -0,0 +1,87 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _reject2 = require('./internal/reject.js'); + +var _reject3 = _interopRequireDefault(_reject2); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. + * + * @name reject + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.reject(fileList, fileExists, function(err, results) { + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }); + * + * // Using Promises + * async.reject(fileList, fileExists) + * .then( results => { + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.reject(fileList, fileExists); + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function reject(coll, iteratee, callback) { + return (0, _reject3.default)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(reject, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/rejectLimit.js b/node_modules/async/rejectLimit.js new file mode 100644 index 0000000..ce10edf --- /dev/null +++ b/node_modules/async/rejectLimit.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _reject2 = require('./internal/reject.js'); + +var _reject3 = _interopRequireDefault(_reject2); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a + * time. + * + * @name rejectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function rejectLimit(coll, limit, iteratee, callback) { + return (0, _reject3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(rejectLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/rejectSeries.js b/node_modules/async/rejectSeries.js new file mode 100644 index 0000000..c08e413 --- /dev/null +++ b/node_modules/async/rejectSeries.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _reject2 = require('./internal/reject.js'); + +var _reject3 = _interopRequireDefault(_reject2); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. + * + * @name rejectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function rejectSeries(coll, iteratee, callback) { + return (0, _reject3.default)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(rejectSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/retry.js b/node_modules/async/retry.js new file mode 100644 index 0000000..a4b0235 --- /dev/null +++ b/node_modules/async/retry.js @@ -0,0 +1,159 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = retry; + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _promiseCallback = require('./internal/promiseCallback.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function constant(value) { + return function () { + return value; + }; +} + +/** + * Attempts to get a successful response from `task` no more than `times` times + * before returning an error. If the task is successful, the `callback` will be + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * @returns {Promise} a promise if no callback provided + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ +const DEFAULT_TIMES = 5; +const DEFAULT_INTERVAL = 0; + +function retry(opts, task, callback) { + var options = { + times: DEFAULT_TIMES, + intervalFunc: constant(DEFAULT_INTERVAL) + }; + + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || (0, _promiseCallback.promiseCallback)(); + task = opts; + } else { + parseTimes(options, opts); + callback = callback || (0, _promiseCallback.promiseCallback)(); + } + + if (typeof task !== 'function') { + throw new Error("Invalid arguments for async.retry"); + } + + var _task = (0, _wrapAsync2.default)(task); + + var attempt = 1; + function retryAttempt() { + _task((err, ...args) => { + if (err === false) return; + if (err && attempt++ < options.times && (typeof options.errorFilter != 'function' || options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt - 1)); + } else { + callback(err, ...args); + } + }); + } + + retryAttempt(); + return callback[_promiseCallback.PROMISE_SYMBOL]; +} + +function parseTimes(acc, t) { + if (typeof t === 'object') { + acc.times = +t.times || DEFAULT_TIMES; + + acc.intervalFunc = typeof t.interval === 'function' ? t.interval : constant(+t.interval || DEFAULT_INTERVAL); + + acc.errorFilter = t.errorFilter; + } else if (typeof t === 'number' || typeof t === 'string') { + acc.times = +t || DEFAULT_TIMES; + } else { + throw new Error("Invalid arguments for async.retry"); + } +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/retryable.js b/node_modules/async/retryable.js new file mode 100644 index 0000000..68256c3 --- /dev/null +++ b/node_modules/async/retryable.js @@ -0,0 +1,77 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = retryable; + +var _retry = require('./retry.js'); + +var _retry2 = _interopRequireDefault(_retry); + +var _initialParams = require('./internal/initialParams.js'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _promiseCallback = require('./internal/promiseCallback.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method + * wraps a task and makes it retryable, rather than immediately calling it + * with retries. + * + * @name retryable + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.retry]{@link module:ControlFlow.retry} + * @category Control Flow + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional + * options, exactly the same as from `retry`, except for a `opts.arity` that + * is the arity of the `task` function, defaulting to `task.length` + * @param {AsyncFunction} task - the asynchronous function to wrap. + * This function will be passed any arguments passed to the returned wrapper. + * Invoked with (...args, callback). + * @returns {AsyncFunction} The wrapped function, which when invoked, will + * retry on an error, based on the parameters specified in `opts`. + * This function will accept the same parameters as `task`. + * @example + * + * async.auto({ + * dep1: async.retryable(3, getFromFlakyService), + * process: ["dep1", async.retryable(3, function (results, cb) { + * maybeProcessData(results.dep1, cb); + * })] + * }, callback); + */ +function retryable(opts, task) { + if (!task) { + task = opts; + opts = null; + } + let arity = opts && opts.arity || task.length; + if ((0, _wrapAsync.isAsync)(task)) { + arity += 1; + } + var _task = (0, _wrapAsync2.default)(task); + return (0, _initialParams2.default)((args, callback) => { + if (args.length < arity - 1 || callback == null) { + args.push(callback); + callback = (0, _promiseCallback.promiseCallback)(); + } + function taskFn(cb) { + _task(...args, cb); + } + + if (opts) (0, _retry2.default)(opts, taskFn, callback);else (0, _retry2.default)(taskFn, callback); + + return callback[_promiseCallback.PROMISE_SYMBOL]; + }); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/select.js b/node_modules/async/select.js new file mode 100644 index 0000000..2c9a63d --- /dev/null +++ b/node_modules/async/select.js @@ -0,0 +1,93 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter.js'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.filter(files, fileExists, function(err, results) { + * if(err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * }); + * + * // Using Promises + * async.filter(files, fileExists) + * .then(results => { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.filter(files, fileExists); + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function filter(coll, iteratee, callback) { + return (0, _filter3.default)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filter, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/selectLimit.js b/node_modules/async/selectLimit.js new file mode 100644 index 0000000..d3b3f50 --- /dev/null +++ b/node_modules/async/selectLimit.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter.js'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + */ +function filterLimit(coll, limit, iteratee, callback) { + return (0, _filter3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filterLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/selectSeries.js b/node_modules/async/selectSeries.js new file mode 100644 index 0000000..019a2d0 --- /dev/null +++ b/node_modules/async/selectSeries.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter.js'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + * @returns {Promise} a promise, if no callback provided + */ +function filterSeries(coll, iteratee, callback) { + return (0, _filter3.default)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filterSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/seq.js b/node_modules/async/seq.js new file mode 100644 index 0000000..e7881cd --- /dev/null +++ b/node_modules/async/seq.js @@ -0,0 +1,79 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = seq; + +var _reduce = require('./reduce.js'); + +var _reduce2 = _interopRequireDefault(_reduce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _promiseCallback = require('./internal/promiseCallback.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Version of the compose function that is more natural to read. Each function + * consumes the return value of the previous function. It is the equivalent of + * [compose]{@link module:ControlFlow.compose} with the arguments reversed. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name seq + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.compose]{@link module:ControlFlow.compose} + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} a function that composes the `functions` in order + * @example + * + * // Requires lodash (or underscore), express3 and dresende's orm2. + * // Part of an app, that fetches cats of the logged user. + * // This example uses `seq` function to avoid overnesting and error + * // handling clutter. + * app.get('/cats', function(request, response) { + * var User = request.models.User; + * async.seq( + * User.get.bind(User), // 'User.get' has signature (id, callback(err, data)) + * function(user, fn) { + * user.getCats(fn); // 'getCats' has signature (callback(err, data)) + * } + * )(req.session.user_id, function (err, cats) { + * if (err) { + * console.error(err); + * response.json({ status: 'error', message: err.message }); + * } else { + * response.json({ status: 'ok', message: 'Cats found', data: cats }); + * } + * }); + * }); + */ +function seq(...functions) { + var _functions = functions.map(_wrapAsync2.default); + return function (...args) { + var that = this; + + var cb = args[args.length - 1]; + if (typeof cb == 'function') { + args.pop(); + } else { + cb = (0, _promiseCallback.promiseCallback)(); + } + + (0, _reduce2.default)(_functions, args, (newargs, fn, iterCb) => { + fn.apply(that, newargs.concat((err, ...nextargs) => { + iterCb(err, nextargs); + })); + }, (err, results) => cb(err, ...results)); + + return cb[_promiseCallback.PROMISE_SYMBOL]; + }; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/series.js b/node_modules/async/series.js new file mode 100644 index 0000000..60c17ed --- /dev/null +++ b/node_modules/async/series.js @@ -0,0 +1,186 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = series; + +var _parallel2 = require('./internal/parallel.js'); + +var _parallel3 = _interopRequireDefault(_parallel2); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Run the functions in the `tasks` collection in series, each one running once + * the previous function has completed. If any functions in the series pass an + * error to its callback, no more functions are run, and `callback` is + * immediately called with the value of the error. Otherwise, `callback` + * receives an array of results when `tasks` have completed. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function, and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.series}. + * + * **Note** that while many implementations preserve the order of object + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) + * explicitly states that + * + * > The mechanics and order of enumerating the properties is not specified. + * + * So if you rely on the order in which your series of functions are executed, + * and want this to work on all platforms, consider using an array. + * + * @name series + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing + * [async functions]{@link AsyncFunction} to run in series. + * Each function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This function gets a results array (or object) + * containing all the result arguments passed to the `task` callbacks. Invoked + * with (err, result). + * @return {Promise} a promise, if no callback is passed + * @example + * + * //Using Callbacks + * async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] + * }); + * + * // an example using objects instead of arrays + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.series([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function series(tasks, callback) { + return (0, _parallel3.default)(_eachOfSeries2.default, tasks, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/setImmediate.js b/node_modules/async/setImmediate.js new file mode 100644 index 0000000..eea8677 --- /dev/null +++ b/node_modules/async/setImmediate.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _setImmediate = require('./internal/setImmediate.js'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `setImmediate`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name setImmediate + * @static + * @memberOf module:Utils + * @method + * @see [async.nextTick]{@link module:Utils.nextTick} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ +exports.default = _setImmediate2.default; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/some.js b/node_modules/async/some.js new file mode 100644 index 0000000..a5bd328 --- /dev/null +++ b/node_modules/async/some.js @@ -0,0 +1,122 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + *); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // false + * // result is false since none of the files exists + * } + *); + * + * // Using Promises + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since some file in the list exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since none of the files exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists); + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists); + * console.log(result); + * // false + * // result is false since none of the files exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function some(coll, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(some, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/someLimit.js b/node_modules/async/someLimit.js new file mode 100644 index 0000000..3a8096f --- /dev/null +++ b/node_modules/async/someLimit.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(someLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/someSeries.js b/node_modules/async/someSeries.js new file mode 100644 index 0000000..51aad19 --- /dev/null +++ b/node_modules/async/someSeries.js @@ -0,0 +1,46 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someSeries(coll, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(someSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/sortBy.js b/node_modules/async/sortBy.js new file mode 100644 index 0000000..0988b61 --- /dev/null +++ b/node_modules/async/sortBy.js @@ -0,0 +1,190 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _map = require('./map.js'); + +var _map2 = _interopRequireDefault(_map); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Sorts a list by the results of running each `coll` value through an async + * `iteratee`. + * + * @name sortBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a value to use as the sort criteria as + * its `result`. + * Invoked with (item, callback). + * @param {Function} callback - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is the items + * from the original `coll` sorted by the values returned by the `iteratee` + * calls. Invoked with (err, results). + * @returns {Promise} a promise, if no callback passed + * @example + * + * // bigfile.txt is a file that is 251100 bytes in size + * // mediumfile.txt is a file that is 11000 bytes in size + * // smallfile.txt is a file that is 121 bytes in size + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // By modifying the callback parameter the + * // sorting order can be influenced: + * + * // ascending order + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) return callback(getFileSizeErr); + * callback(null, fileSize); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // descending order + * async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) { + * return callback(getFileSizeErr); + * } + * callback(null, fileSize * -1); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt'] + * } + * } + * ); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * } + * ); + * + * // Using Promises + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * (async () => { + * try { + * let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * // Error handling + * async () => { + * try { + * let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function sortBy(coll, iteratee, callback) { + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _map2.default)(coll, (x, iterCb) => { + _iteratee(x, (err, criteria) => { + if (err) return iterCb(err); + iterCb(err, { value: x, criteria }); + }); + }, (err, results) => { + if (err) return callback(err); + callback(null, results.sort(comparator).map(v => v.value)); + }); + + function comparator(left, right) { + var a = left.criteria, + b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } +} +exports.default = (0, _awaitify2.default)(sortBy, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/timeout.js b/node_modules/async/timeout.js new file mode 100644 index 0000000..46bb233 --- /dev/null +++ b/node_modules/async/timeout.js @@ -0,0 +1,89 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = timeout; + +var _initialParams = require('./internal/initialParams.js'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Sets a time limit on an asynchronous function. If the function does not call + * its callback within the specified milliseconds, it will be called with a + * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * + * @name timeout + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} asyncFn - The async function to limit in time. + * @param {number} milliseconds - The specified time limit. + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) + * to timeout Error for more information.. + * @returns {AsyncFunction} Returns a wrapped function that can be used with any + * of the control flow functions. + * Invoke this function with the same parameters as you would `asyncFunc`. + * @example + * + * function myFunction(foo, callback) { + * doAsyncTask(foo, function(err, data) { + * // handle errors + * if (err) return callback(err); + * + * // do some stuff ... + * + * // return processed data + * return callback(null, data); + * }); + * } + * + * var wrapped = async.timeout(myFunction, 1000); + * + * // call `wrapped` as you would `myFunction` + * wrapped({ bar: 'bar' }, function(err, data) { + * // if `myFunction` takes < 1000 ms to execute, `err` + * // and `data` will have their expected values + * + * // else `err` will be an Error with the code 'ETIMEDOUT' + * }); + */ +function timeout(asyncFn, milliseconds, info) { + var fn = (0, _wrapAsync2.default)(asyncFn); + + return (0, _initialParams2.default)((args, callback) => { + var timedOut = false; + var timer; + + function timeoutCallback() { + var name = asyncFn.name || 'anonymous'; + var error = new Error('Callback function "' + name + '" timed out.'); + error.code = 'ETIMEDOUT'; + if (info) { + error.info = info; + } + timedOut = true; + callback(error); + } + + args.push((...cbArgs) => { + if (!timedOut) { + callback(...cbArgs); + clearTimeout(timer); + } + }); + + // setup timer and call original function + timer = setTimeout(timeoutCallback, milliseconds); + fn(...args); + }); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/times.js b/node_modules/async/times.js new file mode 100644 index 0000000..ca7df51 --- /dev/null +++ b/node_modules/async/times.js @@ -0,0 +1,50 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = times; + +var _timesLimit = require('./timesLimit.js'); + +var _timesLimit2 = _interopRequireDefault(_timesLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Calls the `iteratee` function `n` times, and accumulates results in the same + * manner you would use with [map]{@link module:Collections.map}. + * + * @name times + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.map]{@link module:Collections.map} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + * @example + * + * // Pretend this is some complicated async factory + * var createUser = function(id, callback) { + * callback(null, { + * id: 'user' + id + * }); + * }; + * + * // generate 5 users + * async.times(5, function(n, next) { + * createUser(n, function(err, user) { + * next(err, user); + * }); + * }, function(err, users) { + * // we should now have 5 users + * }); + */ +function times(n, iteratee, callback) { + return (0, _timesLimit2.default)(n, Infinity, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/timesLimit.js b/node_modules/async/timesLimit.js new file mode 100644 index 0000000..f76de25 --- /dev/null +++ b/node_modules/async/timesLimit.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = timesLimit; + +var _mapLimit = require('./mapLimit.js'); + +var _mapLimit2 = _interopRequireDefault(_mapLimit); + +var _range = require('./internal/range.js'); + +var _range2 = _interopRequireDefault(_range); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a + * time. + * + * @name timesLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} count - The number of times to run the function. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see [async.map]{@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ +function timesLimit(count, limit, iteratee, callback) { + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _mapLimit2.default)((0, _range2.default)(count), limit, _iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/timesSeries.js b/node_modules/async/timesSeries.js new file mode 100644 index 0000000..776b4f3 --- /dev/null +++ b/node_modules/async/timesSeries.js @@ -0,0 +1,32 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = timesSeries; + +var _timesLimit = require('./timesLimit.js'); + +var _timesLimit2 = _interopRequireDefault(_timesLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * + * @name timesSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ +function timesSeries(n, iteratee, callback) { + return (0, _timesLimit2.default)(n, 1, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/transform.js b/node_modules/async/transform.js new file mode 100644 index 0000000..75dadea --- /dev/null +++ b/node_modules/async/transform.js @@ -0,0 +1,173 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = transform; + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _promiseCallback = require('./internal/promiseCallback.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * A relative of `reduce`. Takes an Object or Array, and iterates over each + * element in parallel, each step potentially mutating an `accumulator` value. + * The type of the accumulator defaults to the type of collection passed in. + * + * @name transform + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} [accumulator] - The initial state of the transform. If omitted, + * it will default to an empty Object or Array, depending on the type of `coll` + * @param {AsyncFunction} iteratee - A function applied to each item in the + * collection that potentially modifies the accumulator. + * Invoked with (accumulator, item, key, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the transformed accumulator. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileList, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * }); + * + * // Using Promises + * async.transform(fileList, transformFileSize) + * .then(result => { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.transform(fileList, transformFileSize); + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' }; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileMap, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * }); + * + * // Using Promises + * async.transform(fileMap, transformFileSize) + * .then(result => { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.transform(fileMap, transformFileSize); + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function transform(coll, accumulator, iteratee, callback) { + if (arguments.length <= 3 && typeof accumulator === 'function') { + callback = iteratee; + iteratee = accumulator; + accumulator = Array.isArray(coll) ? [] : {}; + } + callback = (0, _once2.default)(callback || (0, _promiseCallback.promiseCallback)()); + var _iteratee = (0, _wrapAsync2.default)(iteratee); + + (0, _eachOf2.default)(coll, (v, k, cb) => { + _iteratee(accumulator, v, k, cb); + }, err => callback(err, accumulator)); + return callback[_promiseCallback.PROMISE_SYMBOL]; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/tryEach.js b/node_modules/async/tryEach.js new file mode 100644 index 0000000..7e63f9d --- /dev/null +++ b/node_modules/async/tryEach.js @@ -0,0 +1,78 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachSeries = require('./eachSeries.js'); + +var _eachSeries2 = _interopRequireDefault(_eachSeries); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * It runs each task in series but stops whenever any of the functions were + * successful. If one of the tasks were successful, the `callback` will be + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * async.tryEach([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ +function tryEach(tasks, callback) { + var error = null; + var result; + return (0, _eachSeries2.default)(tasks, (task, taskCb) => { + (0, _wrapAsync2.default)(task)((err, ...args) => { + if (err === false) return taskCb(err); + + if (args.length < 2) { + [result] = args; + } else { + result = args; + } + error = err; + taskCb(err ? null : {}); + }); + }, () => callback(error, result)); +} + +exports.default = (0, _awaitify2.default)(tryEach); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/unmemoize.js b/node_modules/async/unmemoize.js new file mode 100644 index 0000000..badd7ae --- /dev/null +++ b/node_modules/async/unmemoize.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = unmemoize; +/** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ +function unmemoize(fn) { + return (...args) => { + return (fn.unmemoized || fn)(...args); + }; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/until.js b/node_modules/async/until.js new file mode 100644 index 0000000..4b69b97 --- /dev/null +++ b/node_modules/async/until.js @@ -0,0 +1,61 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = until; + +var _whilst = require('./whilst.js'); + +var _whilst2 = _interopRequireDefault(_whilst); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. `callback` will be passed an error and any + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * const results = [] + * let finished = false + * async.until(function test(cb) { + * cb(null, finished) + * }, function iter(next) { + * fetchPage(url, (err, body) => { + * if (err) return next(err) + * results = results.concat(body.objects) + * finished = !!body.next + * next(err) + * }) + * }, function done (err) { + * // all pages have been fetched + * }) + */ +function until(test, iteratee, callback) { + const _test = (0, _wrapAsync2.default)(test); + return (0, _whilst2.default)(cb => _test((err, truth) => cb(err, !truth)), iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/waterfall.js b/node_modules/async/waterfall.js new file mode 100644 index 0000000..c3242f7 --- /dev/null +++ b/node_modules/async/waterfall.js @@ -0,0 +1,105 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Runs the `tasks` array of functions in series, each passing their results to + * the next in the array. However, if any of the `tasks` pass an error to their + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ +function waterfall(tasks, callback) { + callback = (0, _once2.default)(callback); + if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); + if (!tasks.length) return callback(); + var taskIndex = 0; + + function nextTask(args) { + var task = (0, _wrapAsync2.default)(tasks[taskIndex++]); + task(...args, (0, _onlyOnce2.default)(next)); + } + + function next(err, ...args) { + if (err === false) return; + if (err || taskIndex === tasks.length) { + return callback(err, ...args); + } + nextTask(args); + } + + nextTask([]); +} + +exports.default = (0, _awaitify2.default)(waterfall); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/whilst.js b/node_modules/async/whilst.js new file mode 100644 index 0000000..4165543 --- /dev/null +++ b/node_modules/async/whilst.js @@ -0,0 +1,78 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5); }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ +function whilst(test, iteratee, callback) { + callback = (0, _onlyOnce2.default)(callback); + var _fn = (0, _wrapAsync2.default)(iteratee); + var _test = (0, _wrapAsync2.default)(test); + var results = []; + + function next(err, ...rest) { + if (err) return callback(err); + results = rest; + if (err === false) return; + _test(check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return _test(check); +} +exports.default = (0, _awaitify2.default)(whilst, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/wrapSync.js b/node_modules/async/wrapSync.js new file mode 100644 index 0000000..ddc3f02 --- /dev/null +++ b/node_modules/async/wrapSync.js @@ -0,0 +1,118 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = asyncify; + +var _initialParams = require('./internal/initialParams.js'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _setImmediate = require('./internal/setImmediate.js'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ +function asyncify(func) { + if ((0, _wrapAsync.isAsync)(func)) { + return function (...args /*, callback*/) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback); + }; + } + + return (0, _initialParams2.default)(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (result && typeof result.then === 'function') { + return handlePromise(result, callback); + } else { + callback(null, result); + } + }); +} + +function handlePromise(promise, callback) { + return promise.then(value => { + invokeCallback(callback, null, value); + }, err => { + invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err)); + }); +} + +function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + (0, _setImmediate2.default)(e => { + throw e; + }, err); + } +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/balanced-match/.github/FUNDING.yml b/node_modules/balanced-match/.github/FUNDING.yml new file mode 100644 index 0000000..cea8b16 --- /dev/null +++ b/node_modules/balanced-match/.github/FUNDING.yml @@ -0,0 +1,2 @@ +tidelift: "npm/balanced-match" +patreon: juliangruber diff --git a/node_modules/balanced-match/LICENSE.md b/node_modules/balanced-match/LICENSE.md new file mode 100644 index 0000000..2cdc8e4 --- /dev/null +++ b/node_modules/balanced-match/LICENSE.md @@ -0,0 +1,21 @@ +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/balanced-match/README.md b/node_modules/balanced-match/README.md new file mode 100644 index 0000000..d2a48b6 --- /dev/null +++ b/node_modules/balanced-match/README.md @@ -0,0 +1,97 @@ +# balanced-match + +Match balanced string pairs, like `{` and `}` or `` and ``. Supports regular expressions as well! + +[![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) +[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) + +[![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) + +## Example + +Get the first matching pair of braces: + +```js +var balanced = require('balanced-match'); + +console.log(balanced('{', '}', 'pre{in{nested}}post')); +console.log(balanced('{', '}', 'pre{first}between{second}post')); +console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')); +``` + +The matches are: + +```bash +$ node example.js +{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } +{ start: 3, + end: 9, + pre: 'pre', + body: 'first', + post: 'between{second}post' } +{ start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } +``` + +## API + +### var m = balanced(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +object with those keys: + +* **start** the index of the first match of `a` +* **end** the index of the matching `b` +* **pre** the preamble, `a` and `b` not included +* **body** the match, `a` and `b` not included +* **post** the postscript, `a` and `b` not included + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. + +### var r = balanced.range(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +array with indexes: `[ , ]`. + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install balanced-match +``` + +## Security contact information + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/balanced-match/index.js b/node_modules/balanced-match/index.js new file mode 100644 index 0000000..c67a646 --- /dev/null +++ b/node_modules/balanced-match/index.js @@ -0,0 +1,62 @@ +'use strict'; +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + + var r = range(a, b, str); + + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} + +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} + +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; + + if (ai >= 0 && bi > 0) { + if(a===b) { + return [ai, bi]; + } + begs = []; + left = str.length; + + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } + + bi = str.indexOf(b, i + 1); + } + + i = ai < bi && ai >= 0 ? ai : bi; + } + + if (begs.length) { + result = [ left, right ]; + } + } + + return result; +} diff --git a/node_modules/balanced-match/package.json b/node_modules/balanced-match/package.json new file mode 100644 index 0000000..ce6073e --- /dev/null +++ b/node_modules/balanced-match/package.json @@ -0,0 +1,48 @@ +{ + "name": "balanced-match", + "description": "Match balanced character pairs, like \"{\" and \"}\"", + "version": "1.0.2", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/balanced-match.git" + }, + "homepage": "https://github.com/juliangruber/balanced-match", + "main": "index.js", + "scripts": { + "test": "tape test/test.js", + "bench": "matcha test/bench.js" + }, + "devDependencies": { + "matcha": "^0.7.0", + "tape": "^4.6.0" + }, + "keywords": [ + "match", + "regexp", + "test", + "balanced", + "parse" + ], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + } +} diff --git a/node_modules/body-parser/HISTORY.md b/node_modules/body-parser/HISTORY.md new file mode 100644 index 0000000..17dd110 --- /dev/null +++ b/node_modules/body-parser/HISTORY.md @@ -0,0 +1,731 @@ +2.2.0 / 2025-03-27 +========================= + +* refactor: normalize common options for all parsers +* deps: + * iconv-lite@^0.6.3 + +2.1.0 / 2025-02-10 +========================= + +* deps: + * type-is@^2.0.0 + * debug@^4.4.0 + * Removed destroy +* refactor: prefix built-in node module imports +* use the node require cache instead of custom caching + +2.0.2 / 2024-10-31 +========================= + +* remove `unpipe` package and use native `unpipe()` method + +2.0.1 / 2024-09-10 +========================= + +* Restore expected behavior `extended` to `false` + +2.0.0 / 2024-09-10 +========================= +* Propagate changes from 1.20.3 +* add brotli support #406 +* Breaking Change: Node.js 18 is the minimum supported version + +2.0.0-beta.2 / 2023-02-23 +========================= + +This incorporates all changes after 1.19.1 up to 1.20.2. + + * Remove deprecated `bodyParser()` combination middleware + * deps: debug@3.1.0 + - Add `DEBUG_HIDE_DATE` environment variable + - Change timer to per-namespace instead of global + - Change non-TTY date format + - Remove `DEBUG_FD` environment variable support + - Support 256 namespace colors + * deps: iconv-lite@0.5.2 + - Add encoding cp720 + - Add encoding UTF-32 + * deps: raw-body@3.0.0-beta.1 + +2.0.0-beta.1 / 2021-12-17 +========================= + + * Drop support for Node.js 0.8 + * `req.body` is no longer always initialized to `{}` + - it is left `undefined` unless a body is parsed + * `urlencoded` parser now defaults `extended` to `false` + * Use `on-finished` to determine when body read + +1.20.3 / 2024-09-10 +=================== + + * deps: qs@6.13.0 + * add `depth` option to customize the depth level in the parser + * IMPORTANT: The default `depth` level for parsing URL-encoded data is now `32` (previously was `Infinity`) + +1.20.2 / 2023-02-21 +=================== + + * Fix strict json error message on Node.js 19+ + * deps: content-type@~1.0.5 + - perf: skip value escaping when unnecessary + * deps: raw-body@2.5.2 + +1.20.1 / 2022-10-06 +=================== + + * deps: qs@6.11.0 + * perf: remove unnecessary object clone + +1.20.0 / 2022-04-02 +=================== + + * Fix error message for json parse whitespace in `strict` + * Fix internal error when inflated body exceeds limit + * Prevent loss of async hooks context + * Prevent hanging when request already read + * deps: depd@2.0.0 + - Replace internal `eval` usage with `Function` constructor + - Use instance methods on `process` to check for listeners + * deps: http-errors@2.0.0 + - deps: depd@2.0.0 + - deps: statuses@2.0.1 + * deps: on-finished@2.4.1 + * deps: qs@6.10.3 + * deps: raw-body@2.5.1 + - deps: http-errors@2.0.0 + +1.19.2 / 2022-02-15 +=================== + + * deps: bytes@3.1.2 + * deps: qs@6.9.7 + * Fix handling of `__proto__` keys + * deps: raw-body@2.4.3 + - deps: bytes@3.1.2 + +1.19.1 / 2021-12-10 +=================== + + * deps: bytes@3.1.1 + * deps: http-errors@1.8.1 + - deps: inherits@2.0.4 + - deps: toidentifier@1.0.1 + - deps: setprototypeof@1.2.0 + * deps: qs@6.9.6 + * deps: raw-body@2.4.2 + - deps: bytes@3.1.1 + - deps: http-errors@1.8.1 + * deps: safe-buffer@5.2.1 + * deps: type-is@~1.6.18 + +1.19.0 / 2019-04-25 +=================== + + * deps: bytes@3.1.0 + - Add petabyte (`pb`) support + * deps: http-errors@1.7.2 + - Set constructor name when possible + - deps: setprototypeof@1.1.1 + - deps: statuses@'>= 1.5.0 < 2' + * deps: iconv-lite@0.4.24 + - Added encoding MIK + * deps: qs@6.7.0 + - Fix parsing array brackets after index + * deps: raw-body@2.4.0 + - deps: bytes@3.1.0 + - deps: http-errors@1.7.2 + - deps: iconv-lite@0.4.24 + * deps: type-is@~1.6.17 + - deps: mime-types@~2.1.24 + - perf: prevent internal `throw` on invalid type + +1.18.3 / 2018-05-14 +=================== + + * Fix stack trace for strict json parse error + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: http-errors@~1.6.3 + - deps: depd@~1.1.2 + - deps: setprototypeof@1.1.0 + - deps: statuses@'>= 1.3.1 < 2' + * deps: iconv-lite@0.4.23 + - Fix loading encoding with year appended + - Fix deprecation warnings on Node.js 10+ + * deps: qs@6.5.2 + * deps: raw-body@2.3.3 + - deps: http-errors@1.6.3 + - deps: iconv-lite@0.4.23 + * deps: type-is@~1.6.16 + - deps: mime-types@~2.1.18 + +1.18.2 / 2017-09-22 +=================== + + * deps: debug@2.6.9 + * perf: remove argument reassignment + +1.18.1 / 2017-09-12 +=================== + + * deps: content-type@~1.0.4 + - perf: remove argument reassignment + - perf: skip parameter parsing when no parameters + * deps: iconv-lite@0.4.19 + - Fix ISO-8859-1 regression + - Update Windows-1255 + * deps: qs@6.5.1 + - Fix parsing & compacting very deep objects + * deps: raw-body@2.3.2 + - deps: iconv-lite@0.4.19 + +1.18.0 / 2017-09-08 +=================== + + * Fix JSON strict violation error to match native parse error + * Include the `body` property on verify errors + * Include the `type` property on all generated errors + * Use `http-errors` to set status code on errors + * deps: bytes@3.0.0 + * deps: debug@2.6.8 + * deps: depd@~1.1.1 + - Remove unnecessary `Buffer` loading + * deps: http-errors@~1.6.2 + - deps: depd@1.1.1 + * deps: iconv-lite@0.4.18 + - Add support for React Native + - Add a warning if not loaded as utf-8 + - Fix CESU-8 decoding in Node.js 8 + - Improve speed of ISO-8859-1 encoding + * deps: qs@6.5.0 + * deps: raw-body@2.3.1 + - Use `http-errors` for standard emitted errors + - deps: bytes@3.0.0 + - deps: iconv-lite@0.4.18 + - perf: skip buffer decoding on overage chunk + * perf: prevent internal `throw` when missing charset + +1.17.2 / 2017-05-17 +=================== + + * deps: debug@2.6.7 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@2.0.0 + * deps: type-is@~1.6.15 + - deps: mime-types@~2.1.15 + +1.17.1 / 2017-03-06 +=================== + + * deps: qs@6.4.0 + - Fix regression parsing keys starting with `[` + +1.17.0 / 2017-03-01 +=================== + + * deps: http-errors@~1.6.1 + - Make `message` property enumerable for `HttpError`s + - deps: setprototypeof@1.0.3 + * deps: qs@6.3.1 + - Fix compacting nested arrays + +1.16.1 / 2017-02-10 +=================== + + * deps: debug@2.6.1 + - Fix deprecation messages in WebStorm and other editors + - Undeprecate `DEBUG_FD` set to `1` or `2` + +1.16.0 / 2017-01-17 +=================== + + * deps: debug@2.6.0 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + * deps: http-errors@~1.5.1 + - deps: inherits@2.0.3 + - deps: setprototypeof@1.0.2 + - deps: statuses@'>= 1.3.1 < 2' + * deps: iconv-lite@0.4.15 + - Added encoding MS-31J + - Added encoding MS-932 + - Added encoding MS-936 + - Added encoding MS-949 + - Added encoding MS-950 + - Fix GBK/GB18030 handling of Euro character + * deps: qs@6.2.1 + - Fix array parsing from skipping empty values + * deps: raw-body@~2.2.0 + - deps: iconv-lite@0.4.15 + * deps: type-is@~1.6.14 + - deps: mime-types@~2.1.13 + +1.15.2 / 2016-06-19 +=================== + + * deps: bytes@2.4.0 + * deps: content-type@~1.0.2 + - perf: enable strict mode + * deps: http-errors@~1.5.0 + - Use `setprototypeof` module to replace `__proto__` setting + - deps: statuses@'>= 1.3.0 < 2' + - perf: enable strict mode + * deps: qs@6.2.0 + * deps: raw-body@~2.1.7 + - deps: bytes@2.4.0 + - perf: remove double-cleanup on happy path + * deps: type-is@~1.6.13 + - deps: mime-types@~2.1.11 + +1.15.1 / 2016-05-05 +=================== + + * deps: bytes@2.3.0 + - Drop partial bytes on all parsed units + - Fix parsing byte string that looks like hex + * deps: raw-body@~2.1.6 + - deps: bytes@2.3.0 + * deps: type-is@~1.6.12 + - deps: mime-types@~2.1.10 + +1.15.0 / 2016-02-10 +=================== + + * deps: http-errors@~1.4.0 + - Add `HttpError` export, for `err instanceof createError.HttpError` + - deps: inherits@2.0.1 + - deps: statuses@'>= 1.2.1 < 2' + * deps: qs@6.1.0 + * deps: type-is@~1.6.11 + - deps: mime-types@~2.1.9 + +1.14.2 / 2015-12-16 +=================== + + * deps: bytes@2.2.0 + * deps: iconv-lite@0.4.13 + * deps: qs@5.2.0 + * deps: raw-body@~2.1.5 + - deps: bytes@2.2.0 + - deps: iconv-lite@0.4.13 + * deps: type-is@~1.6.10 + - deps: mime-types@~2.1.8 + +1.14.1 / 2015-09-27 +=================== + + * Fix issue where invalid charset results in 400 when `verify` used + * deps: iconv-lite@0.4.12 + - Fix CESU-8 decoding in Node.js 4.x + * deps: raw-body@~2.1.4 + - Fix masking critical errors from `iconv-lite` + - deps: iconv-lite@0.4.12 + * deps: type-is@~1.6.9 + - deps: mime-types@~2.1.7 + +1.14.0 / 2015-09-16 +=================== + + * Fix JSON strict parse error to match syntax errors + * Provide static `require` analysis in `urlencoded` parser + * deps: depd@~1.1.0 + - Support web browser loading + * deps: qs@5.1.0 + * deps: raw-body@~2.1.3 + - Fix sync callback when attaching data listener causes sync read + * deps: type-is@~1.6.8 + - Fix type error when given invalid type to match against + - deps: mime-types@~2.1.6 + +1.13.3 / 2015-07-31 +=================== + + * deps: type-is@~1.6.6 + - deps: mime-types@~2.1.4 + +1.13.2 / 2015-07-05 +=================== + + * deps: iconv-lite@0.4.11 + * deps: qs@4.0.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix user-visible incompatibilities from 3.1.0 + - Fix various parsing edge cases + * deps: raw-body@~2.1.2 + - Fix error stack traces to skip `makeError` + - deps: iconv-lite@0.4.11 + * deps: type-is@~1.6.4 + - deps: mime-types@~2.1.2 + - perf: enable strict mode + - perf: remove argument reassignment + +1.13.1 / 2015-06-16 +=================== + + * deps: qs@2.4.2 + - Downgraded from 3.1.0 because of user-visible incompatibilities + +1.13.0 / 2015-06-14 +=================== + + * Add `statusCode` property on `Error`s, in addition to `status` + * Change `type` default to `application/json` for JSON parser + * Change `type` default to `application/x-www-form-urlencoded` for urlencoded parser + * Provide static `require` analysis + * Use the `http-errors` module to generate errors + * deps: bytes@2.1.0 + - Slight optimizations + * deps: iconv-lite@0.4.10 + - The encoding UTF-16 without BOM now defaults to UTF-16LE when detection fails + - Leading BOM is now removed when decoding + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * deps: qs@3.1.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix various parsing edge cases + - Parsed object now has `null` prototype + * deps: raw-body@~2.1.1 + - Use `unpipe` module for unpiping requests + - deps: iconv-lite@0.4.10 + * deps: type-is@~1.6.3 + - deps: mime-types@~2.1.1 + - perf: reduce try block size + - perf: remove bitwise operations + * perf: enable strict mode + * perf: remove argument reassignment + * perf: remove delete call + +1.12.4 / 2015-05-10 +=================== + + * deps: debug@~2.2.0 + * deps: qs@2.4.2 + - Fix allowing parameters like `constructor` + * deps: on-finished@~2.2.1 + * deps: raw-body@~2.0.1 + - Fix a false-positive when unpiping in Node.js 0.8 + - deps: bytes@2.0.1 + * deps: type-is@~1.6.2 + - deps: mime-types@~2.0.11 + +1.12.3 / 2015-04-15 +=================== + + * Slight efficiency improvement when not debugging + * deps: depd@~1.0.1 + * deps: iconv-lite@0.4.8 + - Add encoding alias UNICODE-1-1-UTF-7 + * deps: raw-body@1.3.4 + - Fix hanging callback if request aborts during read + - deps: iconv-lite@0.4.8 + +1.12.2 / 2015-03-16 +=================== + + * deps: qs@2.4.1 + - Fix error when parameter `hasOwnProperty` is present + +1.12.1 / 2015-03-15 +=================== + + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: type-is@~1.6.1 + - deps: mime-types@~2.0.10 + +1.12.0 / 2015-02-13 +=================== + + * add `debug` messages + * accept a function for the `type` option + * use `content-type` to parse `Content-Type` headers + * deps: iconv-lite@0.4.7 + - Gracefully support enumerables on `Object.prototype` + * deps: raw-body@1.3.3 + - deps: iconv-lite@0.4.7 + * deps: type-is@~1.6.0 + - fix argument reassignment + - fix false-positives in `hasBody` `Transfer-Encoding` check + - support wildcard for both type and subtype (`*/*`) + - deps: mime-types@~2.0.9 + +1.11.0 / 2015-01-30 +=================== + + * make internal `extended: true` depth limit infinity + * deps: type-is@~1.5.6 + - deps: mime-types@~2.0.8 + +1.10.2 / 2015-01-20 +=================== + + * deps: iconv-lite@0.4.6 + - Fix rare aliases of single-byte encodings + * deps: raw-body@1.3.2 + - deps: iconv-lite@0.4.6 + +1.10.1 / 2015-01-01 +=================== + + * deps: on-finished@~2.2.0 + * deps: type-is@~1.5.5 + - deps: mime-types@~2.0.7 + +1.10.0 / 2014-12-02 +=================== + + * make internal `extended: true` array limit dynamic + +1.9.3 / 2014-11-21 +================== + + * deps: iconv-lite@0.4.5 + - Fix Windows-31J and X-SJIS encoding support + * deps: qs@2.3.3 + - Fix `arrayLimit` behavior + * deps: raw-body@1.3.1 + - deps: iconv-lite@0.4.5 + * deps: type-is@~1.5.3 + - deps: mime-types@~2.0.3 + +1.9.2 / 2014-10-27 +================== + + * deps: qs@2.3.2 + - Fix parsing of mixed objects and values + +1.9.1 / 2014-10-22 +================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + * deps: qs@2.3.0 + - Fix parsing of mixed implicit and explicit arrays + * deps: type-is@~1.5.2 + - deps: mime-types@~2.0.2 + +1.9.0 / 2014-09-24 +================== + + * include the charset in "unsupported charset" error message + * include the encoding in "unsupported content encoding" error message + * deps: depd@~1.0.0 + +1.8.4 / 2014-09-23 +================== + + * fix content encoding to be case-insensitive + +1.8.3 / 2014-09-19 +================== + + * deps: qs@2.2.4 + - Fix issue with object keys starting with numbers truncated + +1.8.2 / 2014-09-15 +================== + + * deps: depd@0.4.5 + +1.8.1 / 2014-09-07 +================== + + * deps: media-typer@0.3.0 + * deps: type-is@~1.5.1 + +1.8.0 / 2014-09-05 +================== + + * make empty-body-handling consistent between chunked requests + - empty `json` produces `{}` + - empty `raw` produces `new Buffer(0)` + - empty `text` produces `''` + - empty `urlencoded` produces `{}` + * deps: qs@2.2.3 + - Fix issue where first empty value in array is discarded + * deps: type-is@~1.5.0 + - fix `hasbody` to be true for `content-length: 0` + +1.7.0 / 2014-09-01 +================== + + * add `parameterLimit` option to `urlencoded` parser + * change `urlencoded` extended array limit to 100 + * respond with 413 when over `parameterLimit` in `urlencoded` + +1.6.7 / 2014-08-29 +================== + + * deps: qs@2.2.2 + - Remove unnecessary cloning + +1.6.6 / 2014-08-27 +================== + + * deps: qs@2.2.0 + - Array parsing fix + - Performance improvements + +1.6.5 / 2014-08-16 +================== + + * deps: on-finished@2.1.0 + +1.6.4 / 2014-08-14 +================== + + * deps: qs@1.2.2 + +1.6.3 / 2014-08-10 +================== + + * deps: qs@1.2.1 + +1.6.2 / 2014-08-07 +================== + + * deps: qs@1.2.0 + - Fix parsing array of objects + +1.6.1 / 2014-08-06 +================== + + * deps: qs@1.1.0 + - Accept urlencoded square brackets + - Accept empty values in implicit array notation + +1.6.0 / 2014-08-05 +================== + + * deps: qs@1.0.2 + - Complete rewrite + - Limits array length to 20 + - Limits object depth to 5 + - Limits parameters to 1,000 + +1.5.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + +1.5.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + +1.5.0 / 2014-07-20 +================== + + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + * deps: raw-body@1.3.0 + - deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + - Fix `Cannot switch to old mode now` error on Node.js 0.10+ + * deps: type-is@~1.3.2 + +1.4.3 / 2014-06-19 +================== + + * deps: type-is@1.3.1 + - fix global variable leak + +1.4.2 / 2014-06-19 +================== + + * deps: type-is@1.3.0 + - improve type parsing + +1.4.1 / 2014-06-19 +================== + + * fix urlencoded extended deprecation message + +1.4.0 / 2014-06-19 +================== + + * add `text` parser + * add `raw` parser + * check accepted charset in content-type (accepts utf-8) + * check accepted encoding in content-encoding (accepts identity) + * deprecate `bodyParser()` middleware; use `.json()` and `.urlencoded()` as needed + * deprecate `urlencoded()` without provided `extended` option + * lazy-load urlencoded parsers + * parsers split into files for reduced mem usage + * support gzip and deflate bodies + - set `inflate: false` to turn off + * deps: raw-body@1.2.2 + - Support all encodings from `iconv-lite` + +1.3.1 / 2014-06-11 +================== + + * deps: type-is@1.2.1 + - Switch dependency from mime to mime-types@1.0.0 + +1.3.0 / 2014-05-31 +================== + + * add `extended` option to urlencoded parser + +1.2.2 / 2014-05-27 +================== + + * deps: raw-body@1.1.6 + - assert stream encoding on node.js 0.8 + - assert stream encoding on node.js < 0.10.6 + - deps: bytes@1 + +1.2.1 / 2014-05-26 +================== + + * invoke `next(err)` after request fully read + - prevents hung responses and socket hang ups + +1.2.0 / 2014-05-11 +================== + + * add `verify` option + * deps: type-is@1.2.0 + - support suffix matching + +1.1.2 / 2014-05-11 +================== + + * improve json parser speed + +1.1.1 / 2014-05-11 +================== + + * fix repeated limit parsing with every request + +1.1.0 / 2014-05-10 +================== + + * add `type` option + * deps: pin for safety and consistency + +1.0.2 / 2014-04-14 +================== + + * use `type-is` module + +1.0.1 / 2014-03-20 +================== + + * lower default limits to 100kb diff --git a/node_modules/body-parser/LICENSE b/node_modules/body-parser/LICENSE new file mode 100644 index 0000000..386b7b6 --- /dev/null +++ b/node_modules/body-parser/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014-2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/body-parser/README.md b/node_modules/body-parser/README.md new file mode 100644 index 0000000..9fcd4c6 --- /dev/null +++ b/node_modules/body-parser/README.md @@ -0,0 +1,491 @@ +# body-parser + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] +[![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer] + +Node.js body parsing middleware. + +Parse incoming request bodies in a middleware before your handlers, available +under the `req.body` property. + +**Note** As `req.body`'s shape is based on user-controlled input, all +properties and values in this object are untrusted and should be validated +before trusting. For example, `req.body.foo.toString()` may fail in multiple +ways, for example the `foo` property may not be there or may not be a string, +and `toString` may not be a function and instead a string or other user input. + +[Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/). + +_This does not handle multipart bodies_, due to their complex and typically +large nature. For multipart bodies, you may be interested in the following +modules: + + * [busboy](https://www.npmjs.org/package/busboy#readme) and + [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme) + * [multiparty](https://www.npmjs.org/package/multiparty#readme) and + [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme) + * [formidable](https://www.npmjs.org/package/formidable#readme) + * [multer](https://www.npmjs.org/package/multer#readme) + +This module provides the following parsers: + + * [JSON body parser](#bodyparserjsonoptions) + * [Raw body parser](#bodyparserrawoptions) + * [Text body parser](#bodyparsertextoptions) + * [URL-encoded form body parser](#bodyparserurlencodedoptions) + +Other body parsers you might be interested in: + +- [body](https://www.npmjs.org/package/body#readme) +- [co-body](https://www.npmjs.org/package/co-body#readme) + +## Installation + +```sh +$ npm install body-parser +``` + +## API + +```js +const bodyParser = require('body-parser') +``` + +The `bodyParser` object exposes various factories to create middlewares. All +middlewares will populate the `req.body` property with the parsed body when +the `Content-Type` request header matches the `type` option. + +The various errors returned by this module are described in the +[errors section](#errors). + +### bodyParser.json([options]) + +Returns middleware that only parses `json` and only looks at requests where +the `Content-Type` header matches the `type` option. This parser accepts any +Unicode encoding of the body and supports automatic inflation of `gzip`, +`br` (brotli) and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). + +#### Options + +The `json` function takes an optional `options` object that may contain any of +the following keys: + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### reviver + +The `reviver` option is passed directly to `JSON.parse` as the second +argument. You can find more information on this argument +[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter). + +##### strict + +When set to `true`, will only accept arrays and objects; when `false` will +accept anything `JSON.parse` accepts. Defaults to `true`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not a +function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this can +be an extension name (like `json`), a mime type (like `application/json`), or +a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type` +option is called as `fn(req)` and the request is parsed if it returns a truthy +value. Defaults to `application/json`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.raw([options]) + +Returns middleware that parses all bodies as a `Buffer` and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser supports automatic inflation of `gzip`, `br` (brotli) and `deflate` +encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a `Buffer` object +of the body. + +#### Options + +The `raw` function takes an optional `options` object that may contain any of +the following keys: + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. +If not a function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this +can be an extension name (like `bin`), a mime type (like +`application/octet-stream`), or a mime type with a wildcard (like `*/*` or +`application/*`). If a function, the `type` option is called as `fn(req)` +and the request is parsed if it returns a truthy value. Defaults to +`application/octet-stream`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.text([options]) + +Returns middleware that parses all bodies as a string and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser supports automatic inflation of `gzip`, `br` (brotli) and `deflate` +encodings. + +A new `body` string containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a string of the +body. + +#### Options + +The `text` function takes an optional `options` object that may contain any of +the following keys: + +##### defaultCharset + +Specify the default character set for the text content if the charset is not +specified in the `Content-Type` header of the request. Defaults to `utf-8`. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not +a function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this can +be an extension name (like `txt`), a mime type (like `text/plain`), or a mime +type with a wildcard (like `*/*` or `text/*`). If a function, the `type` +option is called as `fn(req)` and the request is parsed if it returns a +truthy value. Defaults to `text/plain`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.urlencoded([options]) + +Returns middleware that only parses `urlencoded` bodies and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser accepts only UTF-8 encoding of the body and supports automatic +inflation of `gzip`, `br` (brotli) and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This object will contain +key-value pairs, where the value can be a string or array (when `extended` is +`false`), or any type (when `extended` is `true`). + +#### Options + +The `urlencoded` function takes an optional `options` object that may contain +any of the following keys: + +##### extended + +The "extended" syntax allows for rich objects and arrays to be encoded into the +URL-encoded format, allowing for a JSON-like experience with URL-encoded. For +more information, please [see the qs +library](https://www.npmjs.org/package/qs#readme). + +Defaults to `false`. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### parameterLimit + +The `parameterLimit` option controls the maximum number of parameters that +are allowed in the URL-encoded data. If a request contains more parameters +than this value, a 413 will be returned to the client. Defaults to `1000`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not +a function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this can +be an extension name (like `urlencoded`), a mime type (like +`application/x-www-form-urlencoded`), or a mime type with a wildcard (like +`*/x-www-form-urlencoded`). If a function, the `type` option is called as +`fn(req)` and the request is parsed if it returns a truthy value. Defaults +to `application/x-www-form-urlencoded`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +##### defaultCharset + +The default charset to parse as, if not specified in content-type. Must be +either `utf-8` or `iso-8859-1`. Defaults to `utf-8`. + +##### charsetSentinel + +Whether to let the value of the `utf8` parameter take precedence as the charset +selector. It requires the form to contain a parameter named `utf8` with a value +of `✓`. Defaults to `false`. + +##### interpretNumericEntities + +Whether to decode numeric entities such as `☺` when parsing an iso-8859-1 +form. Defaults to `false`. + + +#### depth + +The `depth` option is used to configure the maximum depth of the `qs` library when `extended` is `true`. This allows you to limit the amount of keys that are parsed and can be useful to prevent certain types of abuse. Defaults to `32`. It is recommended to keep this value as low as possible. + +## Errors + +The middlewares provided by this module create errors using the +[`http-errors` module](https://www.npmjs.com/package/http-errors). The errors +will typically have a `status`/`statusCode` property that contains the suggested +HTTP response code, an `expose` property to determine if the `message` property +should be displayed to the client, a `type` property to determine the type of +error without matching against the `message`, and a `body` property containing +the read body, if available. + +The following are the common errors created, though any error can come through +for various reasons. + +### content encoding unsupported + +This error will occur when the request had a `Content-Encoding` header that +contained an encoding but the "inflation" option was set to `false`. The +`status` property is set to `415`, the `type` property is set to +`'encoding.unsupported'`, and the `charset` property will be set to the +encoding that is unsupported. + +### entity parse failed + +This error will occur when the request contained an entity that could not be +parsed by the middleware. The `status` property is set to `400`, the `type` +property is set to `'entity.parse.failed'`, and the `body` property is set to +the entity value that failed parsing. + +### entity verify failed + +This error will occur when the request contained an entity that could not be +failed verification by the defined `verify` option. The `status` property is +set to `403`, the `type` property is set to `'entity.verify.failed'`, and the +`body` property is set to the entity value that failed verification. + +### request aborted + +This error will occur when the request is aborted by the client before reading +the body has finished. The `received` property will be set to the number of +bytes received before the request was aborted and the `expected` property is +set to the number of expected bytes. The `status` property is set to `400` +and `type` property is set to `'request.aborted'`. + +### request entity too large + +This error will occur when the request body's size is larger than the "limit" +option. The `limit` property will be set to the byte limit and the `length` +property will be set to the request body's length. The `status` property is +set to `413` and the `type` property is set to `'entity.too.large'`. + +### request size did not match content length + +This error will occur when the request's length did not match the length from +the `Content-Length` header. This typically occurs when the request is malformed, +typically when the `Content-Length` header was calculated based on characters +instead of bytes. The `status` property is set to `400` and the `type` property +is set to `'request.size.invalid'`. + +### stream encoding should not be set + +This error will occur when something called the `req.setEncoding` method prior +to this middleware. This module operates directly on bytes only and you cannot +call `req.setEncoding` when using this module. The `status` property is set to +`500` and the `type` property is set to `'stream.encoding.set'`. + +### stream is not readable + +This error will occur when the request is no longer readable when this middleware +attempts to read it. This typically means something other than a middleware from +this module read the request body already and the middleware was also configured to +read the same request. The `status` property is set to `500` and the `type` +property is set to `'stream.not.readable'`. + +### too many parameters + +This error will occur when the content of the request exceeds the configured +`parameterLimit` for the `urlencoded` parser. The `status` property is set to +`413` and the `type` property is set to `'parameters.too.many'`. + +### unsupported charset "BOGUS" + +This error will occur when the request had a charset parameter in the +`Content-Type` header, but the `iconv-lite` module does not support it OR the +parser does not support it. The charset is contained in the message as well +as in the `charset` property. The `status` property is set to `415`, the +`type` property is set to `'charset.unsupported'`, and the `charset` property +is set to the charset that is unsupported. + +### unsupported content encoding "bogus" + +This error will occur when the request had a `Content-Encoding` header that +contained an unsupported encoding. The encoding is contained in the message +as well as in the `encoding` property. The `status` property is set to `415`, +the `type` property is set to `'encoding.unsupported'`, and the `encoding` +property is set to the encoding that is unsupported. + +### The input exceeded the depth + +This error occurs when using `bodyParser.urlencoded` with the `extended` property set to `true` and the input exceeds the configured `depth` option. The `status` property is set to `400`. It is recommended to review the `depth` option and evaluate if it requires a higher value. When the `depth` option is set to `32` (default value), the error will not be thrown. + +## Examples + +### Express/Connect top-level generic + +This example demonstrates adding a generic JSON and URL-encoded parser as a +top-level middleware, which will parse the bodies of all incoming requests. +This is the simplest setup. + +```js +const express = require('express') +const bodyParser = require('body-parser') + +const app = express() + +// parse application/x-www-form-urlencoded +app.use(bodyParser.urlencoded()) + +// parse application/json +app.use(bodyParser.json()) + +app.use(function (req, res) { + res.setHeader('Content-Type', 'text/plain') + res.write('you posted:\n') + res.end(String(JSON.stringify(req.body, null, 2))) +}) +``` + +### Express route-specific + +This example demonstrates adding body parsers specifically to the routes that +need them. In general, this is the most recommended way to use body-parser with +Express. + +```js +const express = require('express') +const bodyParser = require('body-parser') + +const app = express() + +// create application/json parser +const jsonParser = bodyParser.json() + +// create application/x-www-form-urlencoded parser +const urlencodedParser = bodyParser.urlencoded() + +// POST /login gets urlencoded bodies +app.post('/login', urlencodedParser, function (req, res) { + if (!req.body || !req.body.username) res.sendStatus(400) + res.send('welcome, ' + req.body.username) +}) + +// POST /api/users gets JSON bodies +app.post('/api/users', jsonParser, function (req, res) { + if (!req.body) res.sendStatus(400) + // create user in req.body +}) +``` + +### Change accepted type for parsers + +All the parsers accept a `type` option which allows you to change the +`Content-Type` that the middleware will parse. + +```js +const express = require('express') +const bodyParser = require('body-parser') + +const app = express() + +// parse various different custom JSON types as JSON +app.use(bodyParser.json({ type: 'application/*+json' })) + +// parse some custom thing into a Buffer +app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })) + +// parse an HTML body into a string +app.use(bodyParser.text({ type: 'text/html' })) +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/expressjs/body-parser/master?label=ci +[ci-url]: https://github.com/expressjs/body-parser/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/body-parser/master +[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master +[node-version-image]: https://badgen.net/npm/node/body-parser +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/body-parser +[npm-url]: https://npmjs.org/package/body-parser +[npm-version-image]: https://badgen.net/npm/v/body-parser +[ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/body-parser/badge +[ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/body-parser \ No newline at end of file diff --git a/node_modules/body-parser/index.js b/node_modules/body-parser/index.js new file mode 100644 index 0000000..d722d0b --- /dev/null +++ b/node_modules/body-parser/index.js @@ -0,0 +1,80 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * @typedef Parsers + * @type {function} + * @property {function} json + * @property {function} raw + * @property {function} text + * @property {function} urlencoded + */ + +/** + * Module exports. + * @type {Parsers} + */ + +exports = module.exports = bodyParser + +/** + * JSON parser. + * @public + */ + +Object.defineProperty(exports, 'json', { + configurable: true, + enumerable: true, + get: () => require('./lib/types/json') +}) + +/** + * Raw parser. + * @public + */ + +Object.defineProperty(exports, 'raw', { + configurable: true, + enumerable: true, + get: () => require('./lib/types/raw') +}) + +/** + * Text parser. + * @public + */ + +Object.defineProperty(exports, 'text', { + configurable: true, + enumerable: true, + get: () => require('./lib/types/text') +}) + +/** + * URL-encoded parser. + * @public + */ + +Object.defineProperty(exports, 'urlencoded', { + configurable: true, + enumerable: true, + get: () => require('./lib/types/urlencoded') +}) + +/** + * Create a middleware to parse json and urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @deprecated + * @public + */ + +function bodyParser () { + throw new Error('The bodyParser() generic has been split into individual middleware to use instead.') +} diff --git a/node_modules/body-parser/lib/read.js b/node_modules/body-parser/lib/read.js new file mode 100644 index 0000000..eee8b11 --- /dev/null +++ b/node_modules/body-parser/lib/read.js @@ -0,0 +1,210 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var getBody = require('raw-body') +var iconv = require('iconv-lite') +var onFinished = require('on-finished') +var zlib = require('node:zlib') + +/** + * Module exports. + */ + +module.exports = read + +/** + * Read a request into a buffer and parse. + * + * @param {object} req + * @param {object} res + * @param {function} next + * @param {function} parse + * @param {function} debug + * @param {object} options + * @private + */ + +function read (req, res, next, parse, debug, options) { + var length + var opts = options + var stream + + // read options + var encoding = opts.encoding !== null + ? opts.encoding + : null + var verify = opts.verify + + try { + // get the content stream + stream = contentstream(req, debug, opts.inflate) + length = stream.length + stream.length = undefined + } catch (err) { + return next(err) + } + + // set raw-body options + opts.length = length + opts.encoding = verify + ? null + : encoding + + // assert charset is supported + if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) { + return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + })) + } + + // read body + debug('read body') + getBody(stream, opts, function (error, body) { + if (error) { + var _error + + if (error.type === 'encoding.unsupported') { + // echo back charset + _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + }) + } else { + // set status code on error + _error = createError(400, error) + } + + // unpipe from stream and destroy + if (stream !== req) { + req.unpipe() + stream.destroy() + } + + // read off entire request + dump(req, function onfinished () { + next(createError(400, _error)) + }) + return + } + + // verify + if (verify) { + try { + debug('verify body') + verify(req, res, body, encoding) + } catch (err) { + next(createError(403, err, { + body: body, + type: err.type || 'entity.verify.failed' + })) + return + } + } + + // parse + var str = body + try { + debug('parse body') + str = typeof body !== 'string' && encoding !== null + ? iconv.decode(body, encoding) + : body + req.body = parse(str, encoding) + } catch (err) { + next(createError(400, err, { + body: str, + type: err.type || 'entity.parse.failed' + })) + return + } + + next() + }) +} + +/** + * Get the content stream of the request. + * + * @param {object} req + * @param {function} debug + * @param {boolean} [inflate=true] + * @return {object} + * @api private + */ + +function contentstream (req, debug, inflate) { + var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase() + var length = req.headers['content-length'] + + debug('content-encoding "%s"', encoding) + + if (inflate === false && encoding !== 'identity') { + throw createError(415, 'content encoding unsupported', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } + + if (encoding === 'identity') { + req.length = length + return req + } + + var stream = createDecompressionStream(encoding, debug) + req.pipe(stream) + return stream +} + +/** + * Create a decompression stream for the given encoding. + * @param {string} encoding + * @param {function} debug + * @return {object} + * @api private + */ +function createDecompressionStream (encoding, debug) { + switch (encoding) { + case 'deflate': + debug('inflate body') + return zlib.createInflate() + case 'gzip': + debug('gunzip body') + return zlib.createGunzip() + case 'br': + debug('brotli decompress body') + return zlib.createBrotliDecompress() + default: + throw createError(415, 'unsupported content encoding "' + encoding + '"', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } +} + +/** + * Dump the contents of a request. + * + * @param {object} req + * @param {function} callback + * @api private + */ + +function dump (req, callback) { + if (onFinished.isFinished(req)) { + callback(null) + } else { + onFinished(req, callback) + req.resume() + } +} diff --git a/node_modules/body-parser/lib/types/json.js b/node_modules/body-parser/lib/types/json.js new file mode 100644 index 0000000..078ce71 --- /dev/null +++ b/node_modules/body-parser/lib/types/json.js @@ -0,0 +1,206 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var debug = require('debug')('body-parser:json') +var isFinished = require('on-finished').isFinished +var read = require('../read') +var typeis = require('type-is') +var { getCharset, normalizeOptions } = require('../utils') + +/** + * Module exports. + */ + +module.exports = json + +/** + * RegExp to match the first non-space in a string. + * + * Allowed whitespace is defined in RFC 7159: + * + * ws = *( + * %x20 / ; Space + * %x09 / ; Horizontal tab + * %x0A / ; Line feed or New line + * %x0D ) ; Carriage return + */ + +var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d])/ // eslint-disable-line no-control-regex + +var JSON_SYNTAX_CHAR = '#' +var JSON_SYNTAX_REGEXP = /#+/g + +/** + * Create a middleware to parse JSON bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ + +function json (options) { + var { inflate, limit, verify, shouldParse } = normalizeOptions(options, 'application/json') + + var reviver = options?.reviver + var strict = options?.strict !== false + + function parse (body) { + if (body.length === 0) { + // special-case empty json body, as it's a common client-side mistake + // TODO: maybe make this configurable or part of "strict" option + return {} + } + + if (strict) { + var first = firstchar(body) + + if (first !== '{' && first !== '[') { + debug('strict violation') + throw createStrictSyntaxError(body, first) + } + } + + try { + debug('parse json') + return JSON.parse(body, reviver) + } catch (e) { + throw normalizeJsonSyntaxError(e, { + message: e.message, + stack: e.stack + }) + } + } + + return function jsonParser (req, res, next) { + if (isFinished(req)) { + debug('body already parsed') + next() + return + } + + if (!('body' in req)) { + req.body = undefined + } + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // assert charset per RFC 7159 sec 8.1 + var charset = getCharset(req) || 'utf-8' + if (charset.slice(0, 4) !== 'utf-') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset, + type: 'charset.unsupported' + })) + return + } + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate, + limit, + verify + }) + } +} + +/** + * Create strict violation syntax error matching native error. + * + * @param {string} str + * @param {string} char + * @return {Error} + * @private + */ + +function createStrictSyntaxError (str, char) { + var index = str.indexOf(char) + var partial = '' + + if (index !== -1) { + partial = str.substring(0, index) + JSON_SYNTAX_CHAR + + for (var i = index + 1; i < str.length; i++) { + partial += JSON_SYNTAX_CHAR + } + } + + try { + JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation') + } catch (e) { + return normalizeJsonSyntaxError(e, { + message: e.message.replace(JSON_SYNTAX_REGEXP, function (placeholder) { + return str.substring(index, index + placeholder.length) + }), + stack: e.stack + }) + } +} + +/** + * Get the first non-whitespace character in a string. + * + * @param {string} str + * @return {function} + * @private + */ + +function firstchar (str) { + var match = FIRST_CHAR_REGEXP.exec(str) + + return match + ? match[1] + : undefined +} + +/** + * Normalize a SyntaxError for JSON.parse. + * + * @param {SyntaxError} error + * @param {object} obj + * @return {SyntaxError} + */ + +function normalizeJsonSyntaxError (error, obj) { + var keys = Object.getOwnPropertyNames(error) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + if (key !== 'stack' && key !== 'message') { + delete error[key] + } + } + + // replace stack before message for Node.js 0.10 and below + error.stack = obj.stack.replace(error.message, obj.message) + error.message = obj.message + + return error +} diff --git a/node_modules/body-parser/lib/types/raw.js b/node_modules/body-parser/lib/types/raw.js new file mode 100644 index 0000000..3788ff2 --- /dev/null +++ b/node_modules/body-parser/lib/types/raw.js @@ -0,0 +1,75 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var debug = require('debug')('body-parser:raw') +var isFinished = require('on-finished').isFinished +var read = require('../read') +var typeis = require('type-is') +var { normalizeOptions } = require('../utils') + +/** + * Module exports. + */ + +module.exports = raw + +/** + * Create a middleware to parse raw bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function raw (options) { + var { inflate, limit, verify, shouldParse } = normalizeOptions(options, 'application/octet-stream') + + function parse (buf) { + return buf + } + + return function rawParser (req, res, next) { + if (isFinished(req)) { + debug('body already parsed') + next() + return + } + + if (!('body' in req)) { + req.body = undefined + } + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // read + read(req, res, next, parse, debug, { + encoding: null, + inflate, + limit, + verify + }) + } +} diff --git a/node_modules/body-parser/lib/types/text.js b/node_modules/body-parser/lib/types/text.js new file mode 100644 index 0000000..3e0ab1b --- /dev/null +++ b/node_modules/body-parser/lib/types/text.js @@ -0,0 +1,80 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var debug = require('debug')('body-parser:text') +var isFinished = require('on-finished').isFinished +var read = require('../read') +var typeis = require('type-is') +var { getCharset, normalizeOptions } = require('../utils') + +/** + * Module exports. + */ + +module.exports = text + +/** + * Create a middleware to parse text bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function text (options) { + var { inflate, limit, verify, shouldParse } = normalizeOptions(options, 'text/plain') + + var defaultCharset = options?.defaultCharset || 'utf-8' + + function parse (buf) { + return buf + } + + return function textParser (req, res, next) { + if (isFinished(req)) { + debug('body already parsed') + next() + return + } + + if (!('body' in req)) { + req.body = undefined + } + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // get charset + var charset = getCharset(req) || defaultCharset + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate, + limit, + verify + }) + } +} diff --git a/node_modules/body-parser/lib/types/urlencoded.js b/node_modules/body-parser/lib/types/urlencoded.js new file mode 100644 index 0000000..f993425 --- /dev/null +++ b/node_modules/body-parser/lib/types/urlencoded.js @@ -0,0 +1,177 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var debug = require('debug')('body-parser:urlencoded') +var isFinished = require('on-finished').isFinished +var read = require('../read') +var typeis = require('type-is') +var qs = require('qs') +var { getCharset, normalizeOptions } = require('../utils') + +/** + * Module exports. + */ + +module.exports = urlencoded + +/** + * Create a middleware to parse urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ + +function urlencoded (options) { + var { inflate, limit, verify, shouldParse } = normalizeOptions(options, 'application/x-www-form-urlencoded') + + var defaultCharset = options?.defaultCharset || 'utf-8' + if (defaultCharset !== 'utf-8' && defaultCharset !== 'iso-8859-1') { + throw new TypeError('option defaultCharset must be either utf-8 or iso-8859-1') + } + + // create the appropriate query parser + var queryparse = createQueryParser(options) + + function parse (body, encoding) { + return body.length + ? queryparse(body, encoding) + : {} + } + + return function urlencodedParser (req, res, next) { + if (isFinished(req)) { + debug('body already parsed') + next() + return + } + + if (!('body' in req)) { + req.body = undefined + } + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // assert charset + var charset = getCharset(req) || defaultCharset + if (charset !== 'utf-8' && charset !== 'iso-8859-1') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset, + type: 'charset.unsupported' + })) + return + } + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate, + limit, + verify + }) + } +} + +/** + * Get the extended query parser. + * + * @param {object} options + */ + +function createQueryParser (options) { + var extended = Boolean(options?.extended) + var parameterLimit = options?.parameterLimit !== undefined + ? options?.parameterLimit + : 1000 + var charsetSentinel = options?.charsetSentinel + var interpretNumericEntities = options?.interpretNumericEntities + var depth = extended ? (options?.depth !== undefined ? options?.depth : 32) : 0 + + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } + + if (isNaN(depth) || depth < 0) { + throw new TypeError('option depth must be a zero or a positive number') + } + + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } + + return function queryparse (body, encoding) { + var paramCount = parameterCount(body, parameterLimit) + + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } + + var arrayLimit = extended ? Math.max(100, paramCount) : 0 + + debug('parse ' + (extended ? 'extended ' : '') + 'urlencoding') + try { + return qs.parse(body, { + allowPrototypes: true, + arrayLimit: arrayLimit, + depth: depth, + charsetSentinel: charsetSentinel, + interpretNumericEntities: interpretNumericEntities, + charset: encoding, + parameterLimit: parameterLimit, + strictDepth: true + }) + } catch (err) { + if (err instanceof RangeError) { + throw createError(400, 'The input exceeded the depth', { + type: 'querystring.parse.rangeError' + }) + } else { + throw err + } + } + } +} + +/** + * Count the number of parameters, stopping once limit reached + * + * @param {string} body + * @param {number} limit + * @api private + */ + +function parameterCount (body, limit) { + var len = body.split('&').length + + return len > limit ? undefined : len - 1 +} diff --git a/node_modules/body-parser/lib/utils.js b/node_modules/body-parser/lib/utils.js new file mode 100644 index 0000000..eee5d95 --- /dev/null +++ b/node_modules/body-parser/lib/utils.js @@ -0,0 +1,83 @@ +'use strict' + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = { + getCharset, + normalizeOptions +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch { + return undefined + } +} + +/** + * Get the simple type checker. + * + * @param {string | string[]} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} + +/** + * Normalizes the common options for all parsers. + * + * @param {object} options options to normalize + * @param {string | string[] | function} defaultType default content type(s) or a function to determine it + * @returns {object} + */ +function normalizeOptions (options, defaultType) { + if (!defaultType) { + // Parsers must define a default content type + throw new TypeError('defaultType must be provided') + } + + var inflate = options?.inflate !== false + var limit = typeof options?.limit !== 'number' + ? bytes.parse(options?.limit || '100kb') + : options?.limit + var type = options?.type || defaultType + var verify = options?.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + return { + inflate, + limit, + verify, + shouldParse + } +} diff --git a/node_modules/body-parser/package.json b/node_modules/body-parser/package.json new file mode 100644 index 0000000..e7f763b --- /dev/null +++ b/node_modules/body-parser/package.json @@ -0,0 +1,49 @@ +{ + "name": "body-parser", + "description": "Node.js body parsing middleware", + "version": "2.2.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "expressjs/body-parser", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^1.0.5", + "debug": "^4.4.0", + "http-errors": "^2.0.0", + "iconv-lite": "^0.6.3", + "on-finished": "^2.4.1", + "qs": "^6.14.0", + "raw-body": "^3.0.0", + "type-is": "^2.0.0" + }, + "devDependencies": { + "eslint": "8.34.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.27.5", + "eslint-plugin-markdown": "3.0.0", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "6.1.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "^11.1.0", + "nyc": "^17.1.0", + "supertest": "^7.0.0" + }, + "files": [ + "lib/", + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">=18" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/brace-expansion/.github/FUNDING.yml b/node_modules/brace-expansion/.github/FUNDING.yml new file mode 100644 index 0000000..79d1eaf --- /dev/null +++ b/node_modules/brace-expansion/.github/FUNDING.yml @@ -0,0 +1,2 @@ +tidelift: "npm/brace-expansion" +patreon: juliangruber diff --git a/node_modules/brace-expansion/LICENSE b/node_modules/brace-expansion/LICENSE new file mode 100644 index 0000000..de32266 --- /dev/null +++ b/node_modules/brace-expansion/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 Julian Gruber + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/brace-expansion/README.md b/node_modules/brace-expansion/README.md new file mode 100644 index 0000000..e55c583 --- /dev/null +++ b/node_modules/brace-expansion/README.md @@ -0,0 +1,135 @@ +# brace-expansion + +[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), +as known from sh/bash, in JavaScript. + +[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) +[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) +[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) + +[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) + +## Example + +```js +var expand = require('brace-expansion'); + +expand('file-{a,b,c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('-v{,,}') +// => ['-v', '-v', '-v'] + +expand('file{0..2}.jpg') +// => ['file0.jpg', 'file1.jpg', 'file2.jpg'] + +expand('file-{a..c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('file{2..0}.jpg') +// => ['file2.jpg', 'file1.jpg', 'file0.jpg'] + +expand('file{0..4..2}.jpg') +// => ['file0.jpg', 'file2.jpg', 'file4.jpg'] + +expand('file-{a..e..2}.jpg') +// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] + +expand('file{00..10..5}.jpg') +// => ['file00.jpg', 'file05.jpg', 'file10.jpg'] + +expand('{{A..C},{a..c}}') +// => ['A', 'B', 'C', 'a', 'b', 'c'] + +expand('ppp{,config,oe{,conf}}') +// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] +``` + +## API + +```js +var expand = require('brace-expansion'); +``` + +### var expanded = expand(str) + +Return an array of all possible and valid expansions of `str`. If none are +found, `[str]` is returned. + +Valid expansions are: + +```js +/^(.*,)+(.+)?$/ +// {a,b,...} +``` + +A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +A numeric sequence from `x` to `y` inclusive, with optional increment. +If `x` or `y` start with a leading `0`, all the numbers will be padded +to have equal length. Negative numbers and backwards iteration work too. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +An alphabetic sequence from `x` to `y` inclusive, with optional increment. +`x` and `y` must be exactly one character, and if given, `incr` must be a +number. + +For compatibility reasons, the string `${` is not eligible for brace expansion. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install brace-expansion +``` + +## Contributors + +- [Julian Gruber](https://github.com/juliangruber) +- [Isaac Z. Schlueter](https://github.com/isaacs) + +## Sponsors + +This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! + +Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! + +## Security contact information + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/brace-expansion/index.js b/node_modules/brace-expansion/index.js new file mode 100644 index 0000000..a27f81c --- /dev/null +++ b/node_modules/brace-expansion/index.js @@ -0,0 +1,203 @@ +var balanced = require('balanced-match'); + +module.exports = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m) return [str]; + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; + + if (/\$$/.test(m.pre)) { + for (var k = 0; k < post.length; k++) { + var expansion = pre+ '{' + m.body + '}' + post[k]; + expansions.push(expansion); + } + } else { + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,(?!,).*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = []; + + for (var j = 0; j < n.length; j++) { + N.push.apply(N, expand(n[j], false)); + } + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + } + + return expansions; +} + diff --git a/node_modules/brace-expansion/package.json b/node_modules/brace-expansion/package.json new file mode 100644 index 0000000..c7eee34 --- /dev/null +++ b/node_modules/brace-expansion/package.json @@ -0,0 +1,49 @@ +{ + "name": "brace-expansion", + "description": "Brace expansion as known from sh/bash", + "version": "2.0.2", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/brace-expansion.git" + }, + "homepage": "https://github.com/juliangruber/brace-expansion", + "main": "index.js", + "scripts": { + "test": "tape test/*.js", + "gentest": "bash test/generate.sh", + "bench": "matcha test/perf/bench.js" + }, + "dependencies": { + "balanced-match": "^1.0.0" + }, + "devDependencies": { + "@c4312/matcha": "^1.3.1", + "tape": "^4.6.0" + }, + "keywords": [], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "publishConfig": { + "tag": "2.x" + } +} diff --git a/node_modules/buffer-equal-constant-time/.npmignore b/node_modules/buffer-equal-constant-time/.npmignore new file mode 100644 index 0000000..34e4f5c --- /dev/null +++ b/node_modules/buffer-equal-constant-time/.npmignore @@ -0,0 +1,2 @@ +.*.sw[mnop] +node_modules/ diff --git a/node_modules/buffer-equal-constant-time/.travis.yml b/node_modules/buffer-equal-constant-time/.travis.yml new file mode 100644 index 0000000..78e1c01 --- /dev/null +++ b/node_modules/buffer-equal-constant-time/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: +- "0.11" +- "0.10" diff --git a/node_modules/buffer-equal-constant-time/LICENSE.txt b/node_modules/buffer-equal-constant-time/LICENSE.txt new file mode 100644 index 0000000..9a064f3 --- /dev/null +++ b/node_modules/buffer-equal-constant-time/LICENSE.txt @@ -0,0 +1,12 @@ +Copyright (c) 2013, GoInstant Inc., a salesforce.com company +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +* Neither the name of salesforce.com, nor GoInstant, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/buffer-equal-constant-time/README.md b/node_modules/buffer-equal-constant-time/README.md new file mode 100644 index 0000000..4f227f5 --- /dev/null +++ b/node_modules/buffer-equal-constant-time/README.md @@ -0,0 +1,50 @@ +# buffer-equal-constant-time + +Constant-time `Buffer` comparison for node.js. Should work with browserify too. + +[![Build Status](https://travis-ci.org/goinstant/buffer-equal-constant-time.png?branch=master)](https://travis-ci.org/goinstant/buffer-equal-constant-time) + +```sh + npm install buffer-equal-constant-time +``` + +# Usage + +```js + var bufferEq = require('buffer-equal-constant-time'); + + var a = new Buffer('asdf'); + var b = new Buffer('asdf'); + if (bufferEq(a,b)) { + // the same! + } else { + // different in at least one byte! + } +``` + +If you'd like to install an `.equal()` method onto the node.js `Buffer` and +`SlowBuffer` prototypes: + +```js + require('buffer-equal-constant-time').install(); + + var a = new Buffer('asdf'); + var b = new Buffer('asdf'); + if (a.equal(b)) { + // the same! + } else { + // different in at least one byte! + } +``` + +To get rid of the installed `.equal()` method, call `.restore()`: + +```js + require('buffer-equal-constant-time').restore(); +``` + +# Legal + +© 2013 GoInstant Inc., a salesforce.com company + +Licensed under the BSD 3-clause license. diff --git a/node_modules/buffer-equal-constant-time/index.js b/node_modules/buffer-equal-constant-time/index.js new file mode 100644 index 0000000..5462c1f --- /dev/null +++ b/node_modules/buffer-equal-constant-time/index.js @@ -0,0 +1,41 @@ +/*jshint node:true */ +'use strict'; +var Buffer = require('buffer').Buffer; // browserify +var SlowBuffer = require('buffer').SlowBuffer; + +module.exports = bufferEq; + +function bufferEq(a, b) { + + // shortcutting on type is necessary for correctness + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + return false; + } + + // buffer sizes should be well-known information, so despite this + // shortcutting, it doesn't leak any information about the *contents* of the + // buffers. + if (a.length !== b.length) { + return false; + } + + var c = 0; + for (var i = 0; i < a.length; i++) { + /*jshint bitwise:false */ + c |= a[i] ^ b[i]; // XOR + } + return c === 0; +} + +bufferEq.install = function() { + Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { + return bufferEq(this, that); + }; +}; + +var origBufEqual = Buffer.prototype.equal; +var origSlowBufEqual = SlowBuffer.prototype.equal; +bufferEq.restore = function() { + Buffer.prototype.equal = origBufEqual; + SlowBuffer.prototype.equal = origSlowBufEqual; +}; diff --git a/node_modules/buffer-equal-constant-time/package.json b/node_modules/buffer-equal-constant-time/package.json new file mode 100644 index 0000000..17c7de2 --- /dev/null +++ b/node_modules/buffer-equal-constant-time/package.json @@ -0,0 +1,21 @@ +{ + "name": "buffer-equal-constant-time", + "version": "1.0.1", + "description": "Constant-time comparison of Buffers", + "main": "index.js", + "scripts": { + "test": "mocha test.js" + }, + "repository": "git@github.com:goinstant/buffer-equal-constant-time.git", + "keywords": [ + "buffer", + "equal", + "constant-time", + "crypto" + ], + "author": "GoInstant Inc., a salesforce.com company", + "license": "BSD-3-Clause", + "devDependencies": { + "mocha": "~1.15.1" + } +} diff --git a/node_modules/buffer-equal-constant-time/test.js b/node_modules/buffer-equal-constant-time/test.js new file mode 100644 index 0000000..0bc972d --- /dev/null +++ b/node_modules/buffer-equal-constant-time/test.js @@ -0,0 +1,42 @@ +/*jshint node:true */ +'use strict'; + +var bufferEq = require('./index'); +var assert = require('assert'); + +describe('buffer-equal-constant-time', function() { + var a = new Buffer('asdfasdf123456'); + var b = new Buffer('asdfasdf123456'); + var c = new Buffer('asdfasdf'); + + describe('bufferEq', function() { + it('says a == b', function() { + assert.strictEqual(bufferEq(a, b), true); + }); + + it('says a != c', function() { + assert.strictEqual(bufferEq(a, c), false); + }); + }); + + describe('install/restore', function() { + before(function() { + bufferEq.install(); + }); + after(function() { + bufferEq.restore(); + }); + + it('installed an .equal method', function() { + var SlowBuffer = require('buffer').SlowBuffer; + assert.ok(Buffer.prototype.equal); + assert.ok(SlowBuffer.prototype.equal); + }); + + it('infected existing Buffers', function() { + assert.strictEqual(a.equal(b), true); + assert.strictEqual(a.equal(c), false); + }); + }); + +}); diff --git a/node_modules/bytes/History.md b/node_modules/bytes/History.md new file mode 100644 index 0000000..d60ce0e --- /dev/null +++ b/node_modules/bytes/History.md @@ -0,0 +1,97 @@ +3.1.2 / 2022-01-27 +================== + + * Fix return value for un-parsable strings + +3.1.1 / 2021-11-15 +================== + + * Fix "thousandsSeparator" incorrecting formatting fractional part + +3.1.0 / 2019-01-22 +================== + + * Add petabyte (`pb`) support + +3.0.0 / 2017-08-31 +================== + + * Change "kB" to "KB" in format output + * Remove support for Node.js 0.6 + * Remove support for ComponentJS + +2.5.0 / 2017-03-24 +================== + + * Add option "unit" + +2.4.0 / 2016-06-01 +================== + + * Add option "unitSeparator" + +2.3.0 / 2016-02-15 +================== + + * Drop partial bytes on all parsed units + * Fix non-finite numbers to `.format` to return `null` + * Fix parsing byte string that looks like hex + * perf: hoist regular expressions + +2.2.0 / 2015-11-13 +================== + + * add option "decimalPlaces" + * add option "fixedDecimals" + +2.1.0 / 2015-05-21 +================== + + * add `.format` export + * add `.parse` export + +2.0.2 / 2015-05-20 +================== + + * remove map recreation + * remove unnecessary object construction + +2.0.1 / 2015-05-07 +================== + + * fix browserify require + * remove node.extend dependency + +2.0.0 / 2015-04-12 +================== + + * add option "case" + * add option "thousandsSeparator" + * return "null" on invalid parse input + * support proper round-trip: bytes(bytes(num)) === num + * units no longer case sensitive when parsing + +1.0.0 / 2014-05-05 +================== + + * add negative support. fixes #6 + +0.3.0 / 2014-03-19 +================== + + * added terabyte support + +0.2.1 / 2013-04-01 +================== + + * add .component + +0.2.0 / 2012-10-28 +================== + + * bytes(200).should.eql('200b') + +0.1.0 / 2012-07-04 +================== + + * add bytes to string conversion [yields] diff --git a/node_modules/bytes/LICENSE b/node_modules/bytes/LICENSE new file mode 100644 index 0000000..63e95a9 --- /dev/null +++ b/node_modules/bytes/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012-2014 TJ Holowaychuk +Copyright (c) 2015 Jed Watson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/bytes/Readme.md b/node_modules/bytes/Readme.md new file mode 100644 index 0000000..5790e23 --- /dev/null +++ b/node_modules/bytes/Readme.md @@ -0,0 +1,152 @@ +# Bytes utility + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Utility to parse a string bytes (ex: `1TB`) to bytes (`1099511627776`) and vice-versa. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +$ npm install bytes +``` + +## Usage + +```js +var bytes = require('bytes'); +``` + +#### bytes(number|string value, [options]): number|string|null + +Default export function. Delegates to either `bytes.format` or `bytes.parse` based on the type of `value`. + +**Arguments** + +| Name | Type | Description | +|---------|----------|--------------------| +| value | `number`|`string` | Number value to format or string value to parse | +| options | `Object` | Conversion options for `format` | + +**Returns** + +| Name | Type | Description | +|---------|------------------|-------------------------------------------------| +| results | `string`|`number`|`null` | Return null upon error. Numeric value in bytes, or string value otherwise. | + +**Example** + +```js +bytes(1024); +// output: '1KB' + +bytes('1KB'); +// output: 1024 +``` + +#### bytes.format(number value, [options]): string|null + +Format the given value in bytes into a string. If the value is negative, it is kept as such. If it is a float, it is + rounded. + +**Arguments** + +| Name | Type | Description | +|---------|----------|--------------------| +| value | `number` | Value in bytes | +| options | `Object` | Conversion options | + +**Options** + +| Property | Type | Description | +|-------------------|--------|-----------------------------------------------------------------------------------------| +| decimalPlaces | `number`|`null` | Maximum number of decimal places to include in output. Default value to `2`. | +| fixedDecimals | `boolean`|`null` | Whether to always display the maximum number of decimal places. Default value to `false` | +| thousandsSeparator | `string`|`null` | Example of values: `' '`, `','` and `'.'`... Default value to `''`. | +| unit | `string`|`null` | The unit in which the result will be returned (B/KB/MB/GB/TB). Default value to `''` (which means auto detect). | +| unitSeparator | `string`|`null` | Separator to use between number and unit. Default value to `''`. | + +**Returns** + +| Name | Type | Description | +|---------|------------------|-------------------------------------------------| +| results | `string`|`null` | Return null upon error. String value otherwise. | + +**Example** + +```js +bytes.format(1024); +// output: '1KB' + +bytes.format(1000); +// output: '1000B' + +bytes.format(1000, {thousandsSeparator: ' '}); +// output: '1 000B' + +bytes.format(1024 * 1.7, {decimalPlaces: 0}); +// output: '2KB' + +bytes.format(1024, {unitSeparator: ' '}); +// output: '1 KB' +``` + +#### bytes.parse(string|number value): number|null + +Parse the string value into an integer in bytes. If no unit is given, or `value` +is a number, it is assumed the value is in bytes. + +Supported units and abbreviations are as follows and are case-insensitive: + + * `b` for bytes + * `kb` for kilobytes + * `mb` for megabytes + * `gb` for gigabytes + * `tb` for terabytes + * `pb` for petabytes + +The units are in powers of two, not ten. This means 1kb = 1024b according to this parser. + +**Arguments** + +| Name | Type | Description | +|---------------|--------|--------------------| +| value | `string`|`number` | String to parse, or number in bytes. | + +**Returns** + +| Name | Type | Description | +|---------|-------------|-------------------------| +| results | `number`|`null` | Return null upon error. Value in bytes otherwise. | + +**Example** + +```js +bytes.parse('1KB'); +// output: 1024 + +bytes.parse('1024'); +// output: 1024 + +bytes.parse(1024); +// output: 1024 +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/visionmedia/bytes.js/master?label=ci +[ci-url]: https://github.com/visionmedia/bytes.js/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/visionmedia/bytes.js/master +[coveralls-url]: https://coveralls.io/r/visionmedia/bytes.js?branch=master +[downloads-image]: https://badgen.net/npm/dm/bytes +[downloads-url]: https://npmjs.org/package/bytes +[npm-image]: https://badgen.net/npm/v/bytes +[npm-url]: https://npmjs.org/package/bytes diff --git a/node_modules/bytes/index.js b/node_modules/bytes/index.js new file mode 100644 index 0000000..6f2d0f8 --- /dev/null +++ b/node_modules/bytes/index.js @@ -0,0 +1,170 @@ +/*! + * bytes + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015 Jed Watson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = bytes; +module.exports.format = format; +module.exports.parse = parse; + +/** + * Module variables. + * @private + */ + +var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; + +var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; + +var map = { + b: 1, + kb: 1 << 10, + mb: 1 << 20, + gb: 1 << 30, + tb: Math.pow(1024, 4), + pb: Math.pow(1024, 5), +}; + +var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; + +/** + * Convert the given value in bytes into a string or parse to string to an integer in bytes. + * + * @param {string|number} value + * @param {{ + * case: [string], + * decimalPlaces: [number] + * fixedDecimals: [boolean] + * thousandsSeparator: [string] + * unitSeparator: [string] + * }} [options] bytes options. + * + * @returns {string|number|null} + */ + +function bytes(value, options) { + if (typeof value === 'string') { + return parse(value); + } + + if (typeof value === 'number') { + return format(value, options); + } + + return null; +} + +/** + * Format the given value in bytes into a string. + * + * If the value is negative, it is kept as such. If it is a float, + * it is rounded. + * + * @param {number} value + * @param {object} [options] + * @param {number} [options.decimalPlaces=2] + * @param {number} [options.fixedDecimals=false] + * @param {string} [options.thousandsSeparator=] + * @param {string} [options.unit=] + * @param {string} [options.unitSeparator=] + * + * @returns {string|null} + * @public + */ + +function format(value, options) { + if (!Number.isFinite(value)) { + return null; + } + + var mag = Math.abs(value); + var thousandsSeparator = (options && options.thousandsSeparator) || ''; + var unitSeparator = (options && options.unitSeparator) || ''; + var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; + var fixedDecimals = Boolean(options && options.fixedDecimals); + var unit = (options && options.unit) || ''; + + if (!unit || !map[unit.toLowerCase()]) { + if (mag >= map.pb) { + unit = 'PB'; + } else if (mag >= map.tb) { + unit = 'TB'; + } else if (mag >= map.gb) { + unit = 'GB'; + } else if (mag >= map.mb) { + unit = 'MB'; + } else if (mag >= map.kb) { + unit = 'KB'; + } else { + unit = 'B'; + } + } + + var val = value / map[unit.toLowerCase()]; + var str = val.toFixed(decimalPlaces); + + if (!fixedDecimals) { + str = str.replace(formatDecimalsRegExp, '$1'); + } + + if (thousandsSeparator) { + str = str.split('.').map(function (s, i) { + return i === 0 + ? s.replace(formatThousandsRegExp, thousandsSeparator) + : s + }).join('.'); + } + + return str + unitSeparator + unit; +} + +/** + * Parse the string value into an integer in bytes. + * + * If no unit is given, it is assumed the value is in bytes. + * + * @param {number|string} val + * + * @returns {number|null} + * @public + */ + +function parse(val) { + if (typeof val === 'number' && !isNaN(val)) { + return val; + } + + if (typeof val !== 'string') { + return null; + } + + // Test if the string passed is valid + var results = parseRegExp.exec(val); + var floatValue; + var unit = 'b'; + + if (!results) { + // Nothing could be extracted from the given string + floatValue = parseInt(val, 10); + unit = 'b' + } else { + // Retrieve the value and the unit + floatValue = parseFloat(results[1]); + unit = results[4].toLowerCase(); + } + + if (isNaN(floatValue)) { + return null; + } + + return Math.floor(map[unit] * floatValue); +} diff --git a/node_modules/bytes/package.json b/node_modules/bytes/package.json new file mode 100644 index 0000000..f2b6a8b --- /dev/null +++ b/node_modules/bytes/package.json @@ -0,0 +1,42 @@ +{ + "name": "bytes", + "description": "Utility to parse a string bytes to bytes and vice-versa", + "version": "3.1.2", + "author": "TJ Holowaychuk (http://tjholowaychuk.com)", + "contributors": [ + "Jed Watson ", + "Théo FIDRY " + ], + "license": "MIT", + "keywords": [ + "byte", + "bytes", + "utility", + "parse", + "parser", + "convert", + "converter" + ], + "repository": "visionmedia/bytes.js", + "devDependencies": { + "eslint": "7.32.0", + "eslint-plugin-markdown": "2.2.1", + "mocha": "9.2.0", + "nyc": "15.1.0" + }, + "files": [ + "History.md", + "LICENSE", + "Readme.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --check-leaks --reporter spec", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/call-bind-apply-helpers/.eslintrc b/node_modules/call-bind-apply-helpers/.eslintrc new file mode 100644 index 0000000..201e859 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/.eslintrc @@ -0,0 +1,17 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + "id-length": 0, + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + "no-extra-parens": 0, + "no-magic-numbers": 0, + }, +} diff --git a/node_modules/call-bind-apply-helpers/.github/FUNDING.yml b/node_modules/call-bind-apply-helpers/.github/FUNDING.yml new file mode 100644 index 0000000..0011e9d --- /dev/null +++ b/node_modules/call-bind-apply-helpers/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/call-bind-apply-helpers +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/call-bind-apply-helpers/.nycrc b/node_modules/call-bind-apply-helpers/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/call-bind-apply-helpers/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/call-bind-apply-helpers/CHANGELOG.md b/node_modules/call-bind-apply-helpers/CHANGELOG.md new file mode 100644 index 0000000..2484942 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/CHANGELOG.md @@ -0,0 +1,30 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.2](https://github.com/ljharb/call-bind-apply-helpers/compare/v1.0.1...v1.0.2) - 2025-02-12 + +### Commits + +- [types] improve inferred types [`e6f9586`](https://github.com/ljharb/call-bind-apply-helpers/commit/e6f95860a3c72879cb861a858cdfb8138fbedec1) +- [Dev Deps] update `@arethetypeswrong/cli`, `@ljharb/tsconfig`, `@types/tape`, `es-value-fixtures`, `for-each`, `has-strict-mode`, `object-inspect` [`e43d540`](https://github.com/ljharb/call-bind-apply-helpers/commit/e43d5409f97543bfbb11f345d47d8ce4e066d8c1) + +## [v1.0.1](https://github.com/ljharb/call-bind-apply-helpers/compare/v1.0.0...v1.0.1) - 2024-12-08 + +### Commits + +- [types] `reflectApply`: fix types [`4efc396`](https://github.com/ljharb/call-bind-apply-helpers/commit/4efc3965351a4f02cc55e836fa391d3d11ef2ef8) +- [Fix] `reflectApply`: oops, Reflect is not a function [`83cc739`](https://github.com/ljharb/call-bind-apply-helpers/commit/83cc7395de6b79b7730bdf092f1436f0b1263c75) +- [Dev Deps] update `@arethetypeswrong/cli` [`80bd5d3`](https://github.com/ljharb/call-bind-apply-helpers/commit/80bd5d3ae58b4f6b6995ce439dd5a1bcb178a940) + +## v1.0.0 - 2024-12-05 + +### Commits + +- Initial implementation, tests, readme [`7879629`](https://github.com/ljharb/call-bind-apply-helpers/commit/78796290f9b7430c9934d6f33d94ae9bc89fce04) +- Initial commit [`3f1dc16`](https://github.com/ljharb/call-bind-apply-helpers/commit/3f1dc164afc43285631b114a5f9dd9137b2b952f) +- npm init [`081df04`](https://github.com/ljharb/call-bind-apply-helpers/commit/081df048c312fcee400922026f6e97281200a603) +- Only apps should have lockfiles [`5b9ca0f`](https://github.com/ljharb/call-bind-apply-helpers/commit/5b9ca0fe8101ebfaf309c549caac4e0a017ed930) diff --git a/node_modules/call-bind-apply-helpers/LICENSE b/node_modules/call-bind-apply-helpers/LICENSE new file mode 100644 index 0000000..f82f389 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/call-bind-apply-helpers/README.md b/node_modules/call-bind-apply-helpers/README.md new file mode 100644 index 0000000..8fc0dae --- /dev/null +++ b/node_modules/call-bind-apply-helpers/README.md @@ -0,0 +1,62 @@ +# call-bind-apply-helpers [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Helper functions around Function call/apply/bind, for use in `call-bind`. + +The only packages that should likely ever use this package directly are `call-bind` and `get-intrinsic`. +Please use `call-bind` unless you have a very good reason not to. + +## Getting started + +```sh +npm install --save call-bind-apply-helpers +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const callBindBasic = require('call-bind-apply-helpers'); + +function f(a, b) { + assert.equal(this, 1); + assert.equal(a, 2); + assert.equal(b, 3); + assert.equal(arguments.length, 2); +} + +const fBound = callBindBasic([f, 1]); + +delete Function.prototype.call; +delete Function.prototype.bind; + +fBound(2, 3); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/call-bind-apply-helpers +[npm-version-svg]: https://versionbadg.es/ljharb/call-bind-apply-helpers.svg +[deps-svg]: https://david-dm.org/ljharb/call-bind-apply-helpers.svg +[deps-url]: https://david-dm.org/ljharb/call-bind-apply-helpers +[dev-deps-svg]: https://david-dm.org/ljharb/call-bind-apply-helpers/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/call-bind-apply-helpers#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/call-bind-apply-helpers.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/call-bind-apply-helpers.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/call-bind-apply-helpers.svg +[downloads-url]: https://npm-stat.com/charts.html?package=call-bind-apply-helpers +[codecov-image]: https://codecov.io/gh/ljharb/call-bind-apply-helpers/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/call-bind-apply-helpers/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/call-bind-apply-helpers +[actions-url]: https://github.com/ljharb/call-bind-apply-helpers/actions diff --git a/node_modules/call-bind-apply-helpers/actualApply.d.ts b/node_modules/call-bind-apply-helpers/actualApply.d.ts new file mode 100644 index 0000000..b87286a --- /dev/null +++ b/node_modules/call-bind-apply-helpers/actualApply.d.ts @@ -0,0 +1 @@ +export = Reflect.apply; \ No newline at end of file diff --git a/node_modules/call-bind-apply-helpers/actualApply.js b/node_modules/call-bind-apply-helpers/actualApply.js new file mode 100644 index 0000000..ffa5135 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/actualApply.js @@ -0,0 +1,10 @@ +'use strict'; + +var bind = require('function-bind'); + +var $apply = require('./functionApply'); +var $call = require('./functionCall'); +var $reflectApply = require('./reflectApply'); + +/** @type {import('./actualApply')} */ +module.exports = $reflectApply || bind.call($call, $apply); diff --git a/node_modules/call-bind-apply-helpers/applyBind.d.ts b/node_modules/call-bind-apply-helpers/applyBind.d.ts new file mode 100644 index 0000000..d176c1a --- /dev/null +++ b/node_modules/call-bind-apply-helpers/applyBind.d.ts @@ -0,0 +1,19 @@ +import actualApply from './actualApply'; + +type TupleSplitHead = T['length'] extends N + ? T + : T extends [...infer R, any] + ? TupleSplitHead + : never + +type TupleSplitTail = O['length'] extends N + ? T + : T extends [infer F, ...infer R] + ? TupleSplitTail<[...R], N, [...O, F]> + : never + +type TupleSplit = [TupleSplitHead, TupleSplitTail] + +declare function applyBind(...args: TupleSplit, 2>[1]): ReturnType; + +export = applyBind; \ No newline at end of file diff --git a/node_modules/call-bind-apply-helpers/applyBind.js b/node_modules/call-bind-apply-helpers/applyBind.js new file mode 100644 index 0000000..d2b7723 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/applyBind.js @@ -0,0 +1,10 @@ +'use strict'; + +var bind = require('function-bind'); +var $apply = require('./functionApply'); +var actualApply = require('./actualApply'); + +/** @type {import('./applyBind')} */ +module.exports = function applyBind() { + return actualApply(bind, $apply, arguments); +}; diff --git a/node_modules/call-bind-apply-helpers/functionApply.d.ts b/node_modules/call-bind-apply-helpers/functionApply.d.ts new file mode 100644 index 0000000..1f6e11b --- /dev/null +++ b/node_modules/call-bind-apply-helpers/functionApply.d.ts @@ -0,0 +1 @@ +export = Function.prototype.apply; \ No newline at end of file diff --git a/node_modules/call-bind-apply-helpers/functionApply.js b/node_modules/call-bind-apply-helpers/functionApply.js new file mode 100644 index 0000000..c71df9c --- /dev/null +++ b/node_modules/call-bind-apply-helpers/functionApply.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./functionApply')} */ +module.exports = Function.prototype.apply; diff --git a/node_modules/call-bind-apply-helpers/functionCall.d.ts b/node_modules/call-bind-apply-helpers/functionCall.d.ts new file mode 100644 index 0000000..15e93df --- /dev/null +++ b/node_modules/call-bind-apply-helpers/functionCall.d.ts @@ -0,0 +1 @@ +export = Function.prototype.call; \ No newline at end of file diff --git a/node_modules/call-bind-apply-helpers/functionCall.js b/node_modules/call-bind-apply-helpers/functionCall.js new file mode 100644 index 0000000..7a8d873 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/functionCall.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./functionCall')} */ +module.exports = Function.prototype.call; diff --git a/node_modules/call-bind-apply-helpers/index.d.ts b/node_modules/call-bind-apply-helpers/index.d.ts new file mode 100644 index 0000000..541516b --- /dev/null +++ b/node_modules/call-bind-apply-helpers/index.d.ts @@ -0,0 +1,64 @@ +type RemoveFromTuple< + Tuple extends readonly unknown[], + RemoveCount extends number, + Index extends 1[] = [] +> = Index["length"] extends RemoveCount + ? Tuple + : Tuple extends [infer First, ...infer Rest] + ? RemoveFromTuple + : Tuple; + +type ConcatTuples< + Prefix extends readonly unknown[], + Suffix extends readonly unknown[] +> = [...Prefix, ...Suffix]; + +type ExtractFunctionParams = T extends (this: infer TThis, ...args: infer P extends readonly unknown[]) => infer R + ? { thisArg: TThis; params: P; returnType: R } + : never; + +type BindFunction< + T extends (this: any, ...args: any[]) => any, + TThis, + TBoundArgs extends readonly unknown[], + ReceiverBound extends boolean +> = ExtractFunctionParams extends { + thisArg: infer OrigThis; + params: infer P extends readonly unknown[]; + returnType: infer R; +} + ? ReceiverBound extends true + ? (...args: RemoveFromTuple>) => R extends [OrigThis, ...infer Rest] + ? [TThis, ...Rest] // Replace `this` with `thisArg` + : R + : >>( + thisArg: U, + ...args: RemainingArgs + ) => R extends [OrigThis, ...infer Rest] + ? [U, ...ConcatTuples] // Preserve bound args in return type + : R + : never; + +declare function callBind< + const T extends (this: any, ...args: any[]) => any, + Extracted extends ExtractFunctionParams, + const TBoundArgs extends Partial & readonly unknown[], + const TThis extends Extracted["thisArg"] +>( + args: [fn: T, thisArg: TThis, ...boundArgs: TBoundArgs] +): BindFunction; + +declare function callBind< + const T extends (this: any, ...args: any[]) => any, + Extracted extends ExtractFunctionParams, + const TBoundArgs extends Partial & readonly unknown[] +>( + args: [fn: T, ...boundArgs: TBoundArgs] +): BindFunction; + +declare function callBind( + args: [fn: Exclude, ...rest: TArgs] +): never; + +// export as namespace callBind; +export = callBind; diff --git a/node_modules/call-bind-apply-helpers/index.js b/node_modules/call-bind-apply-helpers/index.js new file mode 100644 index 0000000..2f6dab4 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/index.js @@ -0,0 +1,15 @@ +'use strict'; + +var bind = require('function-bind'); +var $TypeError = require('es-errors/type'); + +var $call = require('./functionCall'); +var $actualApply = require('./actualApply'); + +/** @type {(args: [Function, thisArg?: unknown, ...args: unknown[]]) => Function} TODO FIXME, find a way to use import('.') */ +module.exports = function callBindBasic(args) { + if (args.length < 1 || typeof args[0] !== 'function') { + throw new $TypeError('a function is required'); + } + return $actualApply(bind, $call, args); +}; diff --git a/node_modules/call-bind-apply-helpers/package.json b/node_modules/call-bind-apply-helpers/package.json new file mode 100644 index 0000000..923b8be --- /dev/null +++ b/node_modules/call-bind-apply-helpers/package.json @@ -0,0 +1,85 @@ +{ + "name": "call-bind-apply-helpers", + "version": "1.0.2", + "description": "Helper functions around Function call/apply/bind, for use in `call-bind`", + "main": "index.js", + "exports": { + ".": "./index.js", + "./actualApply": "./actualApply.js", + "./applyBind": "./applyBind.js", + "./functionApply": "./functionApply.js", + "./functionCall": "./functionCall.js", + "./reflectApply": "./reflectApply.js", + "./package.json": "./package.json" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=auto", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=.js,.mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/call-bind-apply-helpers.git" + }, + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/call-bind-apply-helpers/issues" + }, + "homepage": "https://github.com/ljharb/call-bind-apply-helpers#readme", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.3", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.3", + "@types/for-each": "^0.3.3", + "@types/function-bind": "^1.1.10", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.8.1", + "auto-changelog": "^2.5.0", + "encoding": "^0.1.13", + "es-value-fixtures": "^1.7.1", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.5", + "has-strict-mode": "^1.1.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.4", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/call-bind-apply-helpers/reflectApply.d.ts b/node_modules/call-bind-apply-helpers/reflectApply.d.ts new file mode 100644 index 0000000..6b2ae76 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/reflectApply.d.ts @@ -0,0 +1,3 @@ +declare const reflectApply: false | typeof Reflect.apply; + +export = reflectApply; diff --git a/node_modules/call-bind-apply-helpers/reflectApply.js b/node_modules/call-bind-apply-helpers/reflectApply.js new file mode 100644 index 0000000..3d03caa --- /dev/null +++ b/node_modules/call-bind-apply-helpers/reflectApply.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./reflectApply')} */ +module.exports = typeof Reflect !== 'undefined' && Reflect && Reflect.apply; diff --git a/node_modules/call-bind-apply-helpers/test/index.js b/node_modules/call-bind-apply-helpers/test/index.js new file mode 100644 index 0000000..1cdc89e --- /dev/null +++ b/node_modules/call-bind-apply-helpers/test/index.js @@ -0,0 +1,63 @@ +'use strict'; + +var callBind = require('../'); +var hasStrictMode = require('has-strict-mode')(); +var forEach = require('for-each'); +var inspect = require('object-inspect'); +var v = require('es-value-fixtures'); + +var test = require('tape'); + +test('callBindBasic', function (t) { + forEach(v.nonFunctions, function (nonFunction) { + t['throws']( + // @ts-expect-error + function () { callBind([nonFunction]); }, + TypeError, + inspect(nonFunction) + ' is not a function' + ); + }); + + var sentinel = { sentinel: true }; + /** @type {(this: T, a: A, b: B) => [T | undefined, A, B]} */ + var func = function (a, b) { + // eslint-disable-next-line no-invalid-this + return [!hasStrictMode && this === global ? undefined : this, a, b]; + }; + t.equal(func.length, 2, 'original function length is 2'); + + /** type {(thisArg: unknown, a: number, b: number) => [unknown, number, number]} */ + var bound = callBind([func]); + /** type {((a: number, b: number) => [typeof sentinel, typeof a, typeof b])} */ + var boundR = callBind([func, sentinel]); + /** type {((b: number) => [typeof sentinel, number, typeof b])} */ + var boundArg = callBind([func, sentinel, /** @type {const} */ (1)]); + + // @ts-expect-error + t.deepEqual(bound(), [undefined, undefined, undefined], 'bound func with no args'); + + // @ts-expect-error + t.deepEqual(func(), [undefined, undefined, undefined], 'unbound func with too few args'); + // @ts-expect-error + t.deepEqual(bound(1, 2), [hasStrictMode ? 1 : Object(1), 2, undefined], 'bound func too few args'); + // @ts-expect-error + t.deepEqual(boundR(), [sentinel, undefined, undefined], 'bound func with receiver, with too few args'); + // @ts-expect-error + t.deepEqual(boundArg(), [sentinel, 1, undefined], 'bound func with receiver and arg, with too few args'); + + t.deepEqual(func(1, 2), [undefined, 1, 2], 'unbound func with right args'); + t.deepEqual(bound(1, 2, 3), [hasStrictMode ? 1 : Object(1), 2, 3], 'bound func with right args'); + t.deepEqual(boundR(1, 2), [sentinel, 1, 2], 'bound func with receiver, with right args'); + t.deepEqual(boundArg(2), [sentinel, 1, 2], 'bound func with receiver and arg, with right arg'); + + // @ts-expect-error + t.deepEqual(func(1, 2, 3), [undefined, 1, 2], 'unbound func with too many args'); + // @ts-expect-error + t.deepEqual(bound(1, 2, 3, 4), [hasStrictMode ? 1 : Object(1), 2, 3], 'bound func with too many args'); + // @ts-expect-error + t.deepEqual(boundR(1, 2, 3), [sentinel, 1, 2], 'bound func with receiver, with too many args'); + // @ts-expect-error + t.deepEqual(boundArg(2, 3), [sentinel, 1, 2], 'bound func with receiver and arg, with too many args'); + + t.end(); +}); diff --git a/node_modules/call-bind-apply-helpers/tsconfig.json b/node_modules/call-bind-apply-helpers/tsconfig.json new file mode 100644 index 0000000..aef9993 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} \ No newline at end of file diff --git a/node_modules/call-bound/.eslintrc b/node_modules/call-bound/.eslintrc new file mode 100644 index 0000000..2612ed8 --- /dev/null +++ b/node_modules/call-bound/.eslintrc @@ -0,0 +1,13 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, +} diff --git a/node_modules/call-bound/.github/FUNDING.yml b/node_modules/call-bound/.github/FUNDING.yml new file mode 100644 index 0000000..2a2a135 --- /dev/null +++ b/node_modules/call-bound/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/call-bound +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/call-bound/.nycrc b/node_modules/call-bound/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/call-bound/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/call-bound/CHANGELOG.md b/node_modules/call-bound/CHANGELOG.md new file mode 100644 index 0000000..8bde4e9 --- /dev/null +++ b/node_modules/call-bound/CHANGELOG.md @@ -0,0 +1,42 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.4](https://github.com/ljharb/call-bound/compare/v1.0.3...v1.0.4) - 2025-03-03 + +### Commits + +- [types] improve types [`e648922`](https://github.com/ljharb/call-bound/commit/e6489222a9e54f350fbf952ceabe51fd8b6027ff) +- [Dev Deps] update `@arethetypeswrong/cli`, `@ljharb/tsconfig`, `@types/tape`, `es-value-fixtures`, `for-each`, `has-strict-mode`, `object-inspect` [`a42a5eb`](https://github.com/ljharb/call-bound/commit/a42a5ebe6c1b54fcdc7997c7dc64fdca9e936719) +- [Deps] update `call-bind-apply-helpers`, `get-intrinsic` [`f529eac`](https://github.com/ljharb/call-bound/commit/f529eac132404c17156bbc23ab2297a25d0f20b8) + +## [v1.0.3](https://github.com/ljharb/call-bound/compare/v1.0.2...v1.0.3) - 2024-12-15 + +### Commits + +- [Refactor] use `call-bind-apply-helpers` instead of `call-bind` [`5e0b134`](https://github.com/ljharb/call-bound/commit/5e0b13496df14fb7d05dae9412f088da8d3f75be) +- [Deps] update `get-intrinsic` [`41fc967`](https://github.com/ljharb/call-bound/commit/41fc96732a22c7b7e8f381f93ccc54bb6293be2e) +- [readme] fix example [`79a0137`](https://github.com/ljharb/call-bound/commit/79a0137723f7c6d09c9c05452bbf8d5efb5d6e49) +- [meta] add `sideEffects` flag [`08b07be`](https://github.com/ljharb/call-bound/commit/08b07be7f1c03f67dc6f3cdaf0906259771859f7) + +## [v1.0.2](https://github.com/ljharb/call-bound/compare/v1.0.1...v1.0.2) - 2024-12-10 + +### Commits + +- [Dev Deps] update `@arethetypeswrong/cli`, `@ljharb/tsconfig`, `gopd` [`e6a5ffe`](https://github.com/ljharb/call-bound/commit/e6a5ffe849368fe4f74dfd6cdeca1b9baa39e8d5) +- [Deps] update `call-bind`, `get-intrinsic` [`2aeb5b5`](https://github.com/ljharb/call-bound/commit/2aeb5b521dc2b2683d1345c753ea1161de2d1c14) +- [types] improve return type [`1a0c9fe`](https://github.com/ljharb/call-bound/commit/1a0c9fe3114471e7ca1f57d104e2efe713bb4871) + +## v1.0.1 - 2024-12-05 + +### Commits + +- Initial implementation, tests, readme, types [`6d94121`](https://github.com/ljharb/call-bound/commit/6d94121a9243602e506334069f7a03189fe3363d) +- Initial commit [`0eae867`](https://github.com/ljharb/call-bound/commit/0eae867334ea025c33e6e91cdecfc9df96680cf9) +- npm init [`71b2479`](https://github.com/ljharb/call-bound/commit/71b2479c6723e0b7d91a6b663613067e98b7b275) +- Only apps should have lockfiles [`c3754a9`](https://github.com/ljharb/call-bound/commit/c3754a949b7f9132b47e2d18c1729889736741eb) +- [actions] skip `npm ls` in node < 10 [`74275a5`](https://github.com/ljharb/call-bound/commit/74275a5186b8caf6309b6b97472bdcb0df4683a8) +- [Dev Deps] add missing peer dep [`1354de8`](https://github.com/ljharb/call-bound/commit/1354de8679413e4ae9c523d85f76fa7a5e032d97) diff --git a/node_modules/call-bound/LICENSE b/node_modules/call-bound/LICENSE new file mode 100644 index 0000000..f82f389 --- /dev/null +++ b/node_modules/call-bound/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/call-bound/README.md b/node_modules/call-bound/README.md new file mode 100644 index 0000000..a44e43e --- /dev/null +++ b/node_modules/call-bound/README.md @@ -0,0 +1,53 @@ +# call-bound [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Robust call-bound JavaScript intrinsics, using `call-bind` and `get-intrinsic`. + +## Getting started + +```sh +npm install --save call-bound +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const callBound = require('call-bound'); + +const slice = callBound('Array.prototype.slice'); + +delete Function.prototype.call; +delete Function.prototype.bind; +delete Array.prototype.slice; + +assert.deepEqual(slice([1, 2, 3, 4], 1, -1), [2, 3]); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/call-bound +[npm-version-svg]: https://versionbadg.es/ljharb/call-bound.svg +[deps-svg]: https://david-dm.org/ljharb/call-bound.svg +[deps-url]: https://david-dm.org/ljharb/call-bound +[dev-deps-svg]: https://david-dm.org/ljharb/call-bound/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/call-bound#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/call-bound.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/call-bound.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/call-bound.svg +[downloads-url]: https://npm-stat.com/charts.html?package=call-bound +[codecov-image]: https://codecov.io/gh/ljharb/call-bound/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/call-bound/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/call-bound +[actions-url]: https://github.com/ljharb/call-bound/actions diff --git a/node_modules/call-bound/index.d.ts b/node_modules/call-bound/index.d.ts new file mode 100644 index 0000000..5562f00 --- /dev/null +++ b/node_modules/call-bound/index.d.ts @@ -0,0 +1,94 @@ +type Intrinsic = typeof globalThis; + +type IntrinsicName = keyof Intrinsic | `%${keyof Intrinsic}%`; + +type IntrinsicPath = IntrinsicName | `${StripPercents}.${string}` | `%${StripPercents}.${string}%`; + +type AllowMissing = boolean; + +type StripPercents = T extends `%${infer U}%` ? U : T; + +type BindMethodPrecise = + F extends (this: infer This, ...args: infer Args) => infer R + ? (obj: This, ...args: Args) => R + : F extends { + (this: infer This1, ...args: infer Args1): infer R1; + (this: infer This2, ...args: infer Args2): infer R2 + } + ? { + (obj: This1, ...args: Args1): R1; + (obj: This2, ...args: Args2): R2 + } + : never + +// Extract method type from a prototype +type GetPrototypeMethod = + (typeof globalThis)[T] extends { prototype: any } + ? M extends keyof (typeof globalThis)[T]['prototype'] + ? (typeof globalThis)[T]['prototype'][M] + : never + : never + +// Get static property/method +type GetStaticMember = + P extends keyof (typeof globalThis)[T] ? (typeof globalThis)[T][P] : never + +// Type that maps string path to actual bound function or value with better precision +type BoundIntrinsic = + S extends `${infer Obj}.prototype.${infer Method}` + ? Obj extends keyof typeof globalThis + ? BindMethodPrecise> + : unknown + : S extends `${infer Obj}.${infer Prop}` + ? Obj extends keyof typeof globalThis + ? GetStaticMember + : unknown + : unknown + +declare function arraySlice(array: readonly T[], start?: number, end?: number): T[]; +declare function arraySlice(array: ArrayLike, start?: number, end?: number): T[]; +declare function arraySlice(array: IArguments, start?: number, end?: number): T[]; + +// Special cases for methods that need explicit typing +interface SpecialCases { + '%Object.prototype.isPrototypeOf%': (thisArg: {}, obj: unknown) => boolean; + '%String.prototype.replace%': { + (str: string, searchValue: string | RegExp, replaceValue: string): string; + (str: string, searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string + }; + '%Object.prototype.toString%': (obj: {}) => string; + '%Object.prototype.hasOwnProperty%': (obj: {}, v: PropertyKey) => boolean; + '%Array.prototype.slice%': typeof arraySlice; + '%Array.prototype.map%': (array: readonly T[], callbackfn: (value: T, index: number, array: readonly T[]) => U, thisArg?: any) => U[]; + '%Array.prototype.filter%': (array: readonly T[], predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any) => T[]; + '%Array.prototype.indexOf%': (array: readonly T[], searchElement: T, fromIndex?: number) => number; + '%Function.prototype.apply%': (fn: (...args: A) => R, thisArg: any, args: A) => R; + '%Function.prototype.call%': (fn: (...args: A) => R, thisArg: any, ...args: A) => R; + '%Function.prototype.bind%': (fn: (...args: A) => R, thisArg: any, ...args: A) => (...remainingArgs: A) => R; + '%Promise.prototype.then%': { + (promise: Promise, onfulfilled: (value: T) => R | PromiseLike): Promise; + (promise: Promise, onfulfilled: ((value: T) => R | PromiseLike) | undefined | null, onrejected: (reason: any) => R | PromiseLike): Promise; + }; + '%RegExp.prototype.test%': (regexp: RegExp, str: string) => boolean; + '%RegExp.prototype.exec%': (regexp: RegExp, str: string) => RegExpExecArray | null; + '%Error.prototype.toString%': (error: Error) => string; + '%TypeError.prototype.toString%': (error: TypeError) => string; + '%String.prototype.split%': ( + obj: unknown, + splitter: string | RegExp | { + [Symbol.split](string: string, limit?: number): string[]; + }, + limit?: number | undefined + ) => string[]; +} + +/** + * Returns a bound function for a prototype method, or a value for a static property. + * + * @param name - The name of the intrinsic (e.g. 'Array.prototype.slice') + * @param {AllowMissing} [allowMissing] - Whether to allow missing intrinsics (default: false) + */ +declare function callBound, S extends IntrinsicPath>(name: K, allowMissing?: AllowMissing): SpecialCases[`%${StripPercents}%`]; +declare function callBound, S extends IntrinsicPath>(name: S, allowMissing?: AllowMissing): BoundIntrinsic; + +export = callBound; diff --git a/node_modules/call-bound/index.js b/node_modules/call-bound/index.js new file mode 100644 index 0000000..e9ade74 --- /dev/null +++ b/node_modules/call-bound/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var callBindBasic = require('call-bind-apply-helpers'); + +/** @type {(thisArg: string, searchString: string, position?: number) => number} */ +var $indexOf = callBindBasic([GetIntrinsic('%String.prototype.indexOf%')]); + +/** @type {import('.')} */ +module.exports = function callBoundIntrinsic(name, allowMissing) { + /* eslint no-extra-parens: 0 */ + + var intrinsic = /** @type {(this: unknown, ...args: unknown[]) => unknown} */ (GetIntrinsic(name, !!allowMissing)); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBindBasic(/** @type {const} */ ([intrinsic])); + } + return intrinsic; +}; diff --git a/node_modules/call-bound/package.json b/node_modules/call-bound/package.json new file mode 100644 index 0000000..d542db4 --- /dev/null +++ b/node_modules/call-bound/package.json @@ -0,0 +1,99 @@ +{ + "name": "call-bound", + "version": "1.0.4", + "description": "Robust call-bound JavaScript intrinsics, using `call-bind` and `get-intrinsic`.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=auto", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=.js,.mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/call-bound.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "es", + "js", + "callbind", + "callbound", + "call", + "bind", + "bound", + "call-bind", + "call-bound", + "function", + "es-abstract" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/call-bound/issues" + }, + "homepage": "https://github.com/ljharb/call-bound#readme", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.4", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.3.0", + "@types/call-bind": "^1.0.5", + "@types/get-intrinsic": "^1.2.3", + "@types/tape": "^5.8.1", + "auto-changelog": "^2.5.0", + "encoding": "^0.1.13", + "es-value-fixtures": "^1.7.1", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.5", + "gopd": "^1.2.0", + "has-strict-mode": "^1.1.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.4", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/call-bound/test/index.js b/node_modules/call-bound/test/index.js new file mode 100644 index 0000000..a2fc9f0 --- /dev/null +++ b/node_modules/call-bound/test/index.js @@ -0,0 +1,61 @@ +'use strict'; + +var test = require('tape'); + +var callBound = require('../'); + +/** @template {true} T @template U @typedef {T extends U ? T : never} AssertType */ + +test('callBound', function (t) { + // static primitive + t.equal(callBound('Array.length'), Array.length, 'Array.length yields itself'); + t.equal(callBound('%Array.length%'), Array.length, '%Array.length% yields itself'); + + // static non-function object + t.equal(callBound('Array.prototype'), Array.prototype, 'Array.prototype yields itself'); + t.equal(callBound('%Array.prototype%'), Array.prototype, '%Array.prototype% yields itself'); + t.equal(callBound('Array.constructor'), Array.constructor, 'Array.constructor yields itself'); + t.equal(callBound('%Array.constructor%'), Array.constructor, '%Array.constructor% yields itself'); + + // static function + t.equal(callBound('Date.parse'), Date.parse, 'Date.parse yields itself'); + t.equal(callBound('%Date.parse%'), Date.parse, '%Date.parse% yields itself'); + + // prototype primitive + t.equal(callBound('Error.prototype.message'), Error.prototype.message, 'Error.prototype.message yields itself'); + t.equal(callBound('%Error.prototype.message%'), Error.prototype.message, '%Error.prototype.message% yields itself'); + + var x = callBound('Object.prototype.toString'); + var y = callBound('%Object.prototype.toString%'); + + // prototype function + t.notEqual(x, Object.prototype.toString, 'Object.prototype.toString does not yield itself'); + t.notEqual(y, Object.prototype.toString, '%Object.prototype.toString% does not yield itself'); + t.equal(x(true), Object.prototype.toString.call(true), 'call-bound Object.prototype.toString calls into the original'); + t.equal(y(true), Object.prototype.toString.call(true), 'call-bound %Object.prototype.toString% calls into the original'); + + t['throws']( + // @ts-expect-error + function () { callBound('does not exist'); }, + SyntaxError, + 'nonexistent intrinsic throws' + ); + t['throws']( + // @ts-expect-error + function () { callBound('does not exist', true); }, + SyntaxError, + 'allowMissing arg still throws for unknown intrinsic' + ); + + t.test('real but absent intrinsic', { skip: typeof WeakRef !== 'undefined' }, function (st) { + st['throws']( + function () { callBound('WeakRef'); }, + TypeError, + 'real but absent intrinsic throws' + ); + st.equal(callBound('WeakRef', true), undefined, 'allowMissing arg avoids exception'); + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/call-bound/tsconfig.json b/node_modules/call-bound/tsconfig.json new file mode 100644 index 0000000..8976d98 --- /dev/null +++ b/node_modules/call-bound/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "ESNext", + "lib": ["es2024"], + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/content-disposition/HISTORY.md b/node_modules/content-disposition/HISTORY.md new file mode 100644 index 0000000..ff0b68b --- /dev/null +++ b/node_modules/content-disposition/HISTORY.md @@ -0,0 +1,66 @@ +1.0.0 / 2024-08-31 +================== + + * drop node <18 + * allow utf8 as alias for utf-8 + +0.5.4 / 2021-12-10 +================== + + * deps: safe-buffer@5.2.1 + +0.5.3 / 2018-12-17 +================== + + * Use `safe-buffer` for improved Buffer API + +0.5.2 / 2016-12-08 +================== + + * Fix `parse` to accept any linear whitespace character + +0.5.1 / 2016-01-17 +================== + + * perf: enable strict mode + +0.5.0 / 2014-10-11 +================== + + * Add `parse` function + +0.4.0 / 2014-09-21 +================== + + * Expand non-Unicode `filename` to the full ISO-8859-1 charset + +0.3.0 / 2014-09-20 +================== + + * Add `fallback` option + * Add `type` option + +0.2.0 / 2014-09-19 +================== + + * Reduce ambiguity of file names with hex escape in buggy browsers + +0.1.2 / 2014-09-19 +================== + + * Fix periodic invalid Unicode filename header + +0.1.1 / 2014-09-19 +================== + + * Fix invalid characters appearing in `filename*` parameter + +0.1.0 / 2014-09-18 +================== + + * Make the `filename` argument optional + +0.0.0 / 2014-09-18 +================== + + * Initial release diff --git a/node_modules/content-disposition/LICENSE b/node_modules/content-disposition/LICENSE new file mode 100644 index 0000000..84441fb --- /dev/null +++ b/node_modules/content-disposition/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/content-disposition/README.md b/node_modules/content-disposition/README.md new file mode 100644 index 0000000..3a0bb05 --- /dev/null +++ b/node_modules/content-disposition/README.md @@ -0,0 +1,142 @@ +# content-disposition + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Create and parse HTTP `Content-Disposition` header + +## Installation + +```sh +$ npm install content-disposition +``` + +## API + +```js +var contentDisposition = require('content-disposition') +``` + +### contentDisposition(filename, options) + +Create an attachment `Content-Disposition` header value using the given file name, +if supplied. The `filename` is optional and if no file name is desired, but you +want to specify `options`, set `filename` to `undefined`. + +```js +res.setHeader('Content-Disposition', contentDisposition('∫ maths.pdf')) +``` + +**note** HTTP headers are of the ISO-8859-1 character set. If you are writing this +header through a means different from `setHeader` in Node.js, you'll want to specify +the `'binary'` encoding in Node.js. + +#### Options + +`contentDisposition` accepts these properties in the options object. + +##### fallback + +If the `filename` option is outside ISO-8859-1, then the file name is actually +stored in a supplemental field for clients that support Unicode file names and +a ISO-8859-1 version of the file name is automatically generated. + +This specifies the ISO-8859-1 file name to override the automatic generation or +disables the generation all together, defaults to `true`. + + - A string will specify the ISO-8859-1 file name to use in place of automatic + generation. + - `false` will disable including a ISO-8859-1 file name and only include the + Unicode version (unless the file name is already ISO-8859-1). + - `true` will enable automatic generation if the file name is outside ISO-8859-1. + +If the `filename` option is ISO-8859-1 and this option is specified and has a +different value, then the `filename` option is encoded in the extended field +and this set as the fallback field, even though they are both ISO-8859-1. + +##### type + +Specifies the disposition type, defaults to `"attachment"`. This can also be +`"inline"`, or any other value (all values except inline are treated like +`attachment`, but can convey additional information if both parties agree to +it). The type is normalized to lower-case. + +### contentDisposition.parse(string) + +```js +var disposition = contentDisposition.parse('attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt') +``` + +Parse a `Content-Disposition` header string. This automatically handles extended +("Unicode") parameters by decoding them and providing them under the standard +parameter name. This will return an object with the following properties (examples +are shown for the string `'attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'`): + + - `type`: The disposition type (always lower case). Example: `'attachment'` + + - `parameters`: An object of the parameters in the disposition (name of parameter + always lower case and extended versions replace non-extended versions). Example: + `{filename: "€ rates.txt"}` + +## Examples + +### Send a file for download + +```js +var contentDisposition = require('content-disposition') +var destroy = require('destroy') +var fs = require('fs') +var http = require('http') +var onFinished = require('on-finished') + +var filePath = '/path/to/public/plans.pdf' + +http.createServer(function onRequest (req, res) { + // set headers + res.setHeader('Content-Type', 'application/pdf') + res.setHeader('Content-Disposition', contentDisposition(filePath)) + + // send file + var stream = fs.createReadStream(filePath) + stream.pipe(res) + onFinished(res, function () { + destroy(stream) + }) +}) +``` + +## Testing + +```sh +$ npm test +``` + +## References + +- [RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1][rfc-2616] +- [RFC 5987: Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters][rfc-5987] +- [RFC 6266: Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)][rfc-6266] +- [Test Cases for HTTP Content-Disposition header field (RFC 6266) and the Encodings defined in RFCs 2047, 2231 and 5987][tc-2231] + +[rfc-2616]: https://tools.ietf.org/html/rfc2616 +[rfc-5987]: https://tools.ietf.org/html/rfc5987 +[rfc-6266]: https://tools.ietf.org/html/rfc6266 +[tc-2231]: http://greenbytes.de/tech/tc2231/ + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/content-disposition.svg +[npm-url]: https://npmjs.org/package/content-disposition +[node-version-image]: https://img.shields.io/node/v/content-disposition.svg +[node-version-url]: https://nodejs.org/en/download +[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-disposition.svg +[coveralls-url]: https://coveralls.io/r/jshttp/content-disposition?branch=master +[downloads-image]: https://img.shields.io/npm/dm/content-disposition.svg +[downloads-url]: https://npmjs.org/package/content-disposition +[github-actions-ci-image]: https://img.shields.io/github/workflow/status/jshttp/content-disposition/ci/master?label=ci +[github-actions-ci-url]: https://github.com/jshttp/content-disposition?query=workflow%3Aci diff --git a/node_modules/content-disposition/index.js b/node_modules/content-disposition/index.js new file mode 100644 index 0000000..44f1d51 --- /dev/null +++ b/node_modules/content-disposition/index.js @@ -0,0 +1,459 @@ +/*! + * content-disposition + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = contentDisposition +module.exports.parse = parse + +/** + * Module dependencies. + * @private + */ + +var basename = require('path').basename +var Buffer = require('safe-buffer').Buffer + +/** + * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") + * @private + */ + +var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex + +/** + * RegExp to match percent encoding escape. + * @private + */ + +var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/ +var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g + +/** + * RegExp to match non-latin1 characters. + * @private + */ + +var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g + +/** + * RegExp to match quoted-pair in RFC 2616 + * + * quoted-pair = "\" CHAR + * CHAR = + * @private + */ + +var QESC_REGEXP = /\\([\u0000-\u007f])/g // eslint-disable-line no-control-regex + +/** + * RegExp to match chars that must be quoted-pair in RFC 2616 + * @private + */ + +var QUOTE_REGEXP = /([\\"])/g + +/** + * RegExp for various RFC 2616 grammar + * + * parameter = token "=" ( token | quoted-string ) + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) + * qdtext = > + * quoted-pair = "\" CHAR + * CHAR = + * TEXT = + * LWS = [CRLF] 1*( SP | HT ) + * CRLF = CR LF + * CR = + * LF = + * SP = + * HT = + * CTL = + * OCTET = + * @private + */ + +var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex +var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/ +var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/ + +/** + * RegExp for various RFC 5987 grammar + * + * ext-value = charset "'" [ language ] "'" value-chars + * charset = "UTF-8" / "ISO-8859-1" / mime-charset + * mime-charset = 1*mime-charsetc + * mime-charsetc = ALPHA / DIGIT + * / "!" / "#" / "$" / "%" / "&" + * / "+" / "-" / "^" / "_" / "`" + * / "{" / "}" / "~" + * language = ( 2*3ALPHA [ extlang ] ) + * / 4ALPHA + * / 5*8ALPHA + * extlang = *3( "-" 3ALPHA ) + * value-chars = *( pct-encoded / attr-char ) + * pct-encoded = "%" HEXDIG HEXDIG + * attr-char = ALPHA / DIGIT + * / "!" / "#" / "$" / "&" / "+" / "-" / "." + * / "^" / "_" / "`" / "|" / "~" + * @private + */ + +var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/ + +/** + * RegExp for various RFC 6266 grammar + * + * disposition-type = "inline" | "attachment" | disp-ext-type + * disp-ext-type = token + * disposition-parm = filename-parm | disp-ext-parm + * filename-parm = "filename" "=" value + * | "filename*" "=" ext-value + * disp-ext-parm = token "=" value + * | ext-token "=" ext-value + * ext-token = + * @private + */ + +var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex + +/** + * Create an attachment Content-Disposition header. + * + * @param {string} [filename] + * @param {object} [options] + * @param {string} [options.type=attachment] + * @param {string|boolean} [options.fallback=true] + * @return {string} + * @public + */ + +function contentDisposition (filename, options) { + var opts = options || {} + + // get type + var type = opts.type || 'attachment' + + // get parameters + var params = createparams(filename, opts.fallback) + + // format into string + return format(new ContentDisposition(type, params)) +} + +/** + * Create parameters object from filename and fallback. + * + * @param {string} [filename] + * @param {string|boolean} [fallback=true] + * @return {object} + * @private + */ + +function createparams (filename, fallback) { + if (filename === undefined) { + return + } + + var params = {} + + if (typeof filename !== 'string') { + throw new TypeError('filename must be a string') + } + + // fallback defaults to true + if (fallback === undefined) { + fallback = true + } + + if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { + throw new TypeError('fallback must be a string or boolean') + } + + if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { + throw new TypeError('fallback must be ISO-8859-1 string') + } + + // restrict to file base name + var name = basename(filename) + + // determine if name is suitable for quoted string + var isQuotedString = TEXT_REGEXP.test(name) + + // generate fallback name + var fallbackName = typeof fallback !== 'string' + ? fallback && getlatin1(name) + : basename(fallback) + var hasFallback = typeof fallbackName === 'string' && fallbackName !== name + + // set extended filename parameter + if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) { + params['filename*'] = name + } + + // set filename parameter + if (isQuotedString || hasFallback) { + params.filename = hasFallback + ? fallbackName + : name + } + + return params +} + +/** + * Format object to Content-Disposition header. + * + * @param {object} obj + * @param {string} obj.type + * @param {object} [obj.parameters] + * @return {string} + * @private + */ + +function format (obj) { + var parameters = obj.parameters + var type = obj.type + + if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) { + throw new TypeError('invalid type') + } + + // start with normalized type + var string = String(type).toLowerCase() + + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() + + for (var i = 0; i < params.length; i++) { + param = params[i] + + var val = param.slice(-1) === '*' + ? ustring(parameters[param]) + : qstring(parameters[param]) + + string += '; ' + param + '=' + val + } + } + + return string +} + +/** + * Decode a RFC 5987 field value (gracefully). + * + * @param {string} str + * @return {string} + * @private + */ + +function decodefield (str) { + var match = EXT_VALUE_REGEXP.exec(str) + + if (!match) { + throw new TypeError('invalid extended field value') + } + + var charset = match[1].toLowerCase() + var encoded = match[2] + var value + + // to binary string + var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode) + + switch (charset) { + case 'iso-8859-1': + value = getlatin1(binary) + break + case 'utf-8': + case 'utf8': + value = Buffer.from(binary, 'binary').toString('utf8') + break + default: + throw new TypeError('unsupported charset in extended field') + } + + return value +} + +/** + * Get ISO-8859-1 version of string. + * + * @param {string} val + * @return {string} + * @private + */ + +function getlatin1 (val) { + // simple Unicode -> ISO-8859-1 transformation + return String(val).replace(NON_LATIN1_REGEXP, '?') +} + +/** + * Parse Content-Disposition header string. + * + * @param {string} string + * @return {object} + * @public + */ + +function parse (string) { + if (!string || typeof string !== 'string') { + throw new TypeError('argument string is required') + } + + var match = DISPOSITION_TYPE_REGEXP.exec(string) + + if (!match) { + throw new TypeError('invalid type format') + } + + // normalize type + var index = match[0].length + var type = match[1].toLowerCase() + + var key + var names = [] + var params = {} + var value + + // calculate index to start at + index = PARAM_REGEXP.lastIndex = match[0].slice(-1) === ';' + ? index - 1 + : index + + // match parameters + while ((match = PARAM_REGEXP.exec(string))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } + + index += match[0].length + key = match[1].toLowerCase() + value = match[2] + + if (names.indexOf(key) !== -1) { + throw new TypeError('invalid duplicate parameter') + } + + names.push(key) + + if (key.indexOf('*') + 1 === key.length) { + // decode extended value + key = key.slice(0, -1) + value = decodefield(value) + + // overwrite existing value + params[key] = value + continue + } + + if (typeof params[key] === 'string') { + continue + } + + if (value[0] === '"') { + // remove quotes and escapes + value = value + .slice(1, -1) + .replace(QESC_REGEXP, '$1') + } + + params[key] = value + } + + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') + } + + return new ContentDisposition(type, params) +} + +/** + * Percent decode a single character. + * + * @param {string} str + * @param {string} hex + * @return {string} + * @private + */ + +function pdecode (str, hex) { + return String.fromCharCode(parseInt(hex, 16)) +} + +/** + * Percent encode a single character. + * + * @param {string} char + * @return {string} + * @private + */ + +function pencode (char) { + return '%' + String(char) + .charCodeAt(0) + .toString(16) + .toUpperCase() +} + +/** + * Quote a string for HTTP. + * + * @param {string} val + * @return {string} + * @private + */ + +function qstring (val) { + var str = String(val) + + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' +} + +/** + * Encode a Unicode string for HTTP (RFC 5987). + * + * @param {string} val + * @return {string} + * @private + */ + +function ustring (val) { + var str = String(val) + + // percent encode as UTF-8 + var encoded = encodeURIComponent(str) + .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) + + return 'UTF-8\'\'' + encoded +} + +/** + * Class for parsed Content-Disposition header for v8 optimization + * + * @public + * @param {string} type + * @param {object} parameters + * @constructor + */ + +function ContentDisposition (type, parameters) { + this.type = type + this.parameters = parameters +} diff --git a/node_modules/content-disposition/package.json b/node_modules/content-disposition/package.json new file mode 100644 index 0000000..5cea50b --- /dev/null +++ b/node_modules/content-disposition/package.json @@ -0,0 +1,44 @@ +{ + "name": "content-disposition", + "description": "Create and parse Content-Disposition header", + "version": "1.0.0", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "content-disposition", + "http", + "rfc6266", + "res" + ], + "repository": "jshttp/content-disposition", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "devDependencies": { + "deep-equal": "1.0.1", + "eslint": "7.32.0", + "eslint-config-standard": "13.0.1", + "eslint-plugin-import": "2.25.3", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "^9.2.2", + "nyc": "15.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/content-type/HISTORY.md b/node_modules/content-type/HISTORY.md new file mode 100644 index 0000000..4583671 --- /dev/null +++ b/node_modules/content-type/HISTORY.md @@ -0,0 +1,29 @@ +1.0.5 / 2023-01-29 +================== + + * perf: skip value escaping when unnecessary + +1.0.4 / 2017-09-11 +================== + + * perf: skip parameter parsing when no parameters + +1.0.3 / 2017-09-10 +================== + + * perf: remove argument reassignment + +1.0.2 / 2016-05-09 +================== + + * perf: enable strict mode + +1.0.1 / 2015-02-13 +================== + + * Improve missing `Content-Type` header error message + +1.0.0 / 2015-02-01 +================== + + * Initial implementation, derived from `media-typer@0.3.0` diff --git a/node_modules/content-type/LICENSE b/node_modules/content-type/LICENSE new file mode 100644 index 0000000..34b1a2d --- /dev/null +++ b/node_modules/content-type/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/content-type/README.md b/node_modules/content-type/README.md new file mode 100644 index 0000000..c1a922a --- /dev/null +++ b/node_modules/content-type/README.md @@ -0,0 +1,94 @@ +# content-type + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +Create and parse HTTP Content-Type header according to RFC 7231 + +## Installation + +```sh +$ npm install content-type +``` + +## API + +```js +var contentType = require('content-type') +``` + +### contentType.parse(string) + +```js +var obj = contentType.parse('image/svg+xml; charset=utf-8') +``` + +Parse a `Content-Type` header. This will return an object with the following +properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The media type (the type and subtype, always lower case). + Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of parameter + always lower case). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the string is missing or invalid. + +### contentType.parse(req) + +```js +var obj = contentType.parse(req) +``` + +Parse the `Content-Type` header from the given `req`. Short-cut for +`contentType.parse(req.headers['content-type'])`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.parse(res) + +```js +var obj = contentType.parse(res) +``` + +Parse the `Content-Type` header set on the given `res`. Short-cut for +`contentType.parse(res.getHeader('content-type'))`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.format(obj) + +```js +var str = contentType.format({ + type: 'image/svg+xml', + parameters: { charset: 'utf-8' } +}) +``` + +Format an object into a `Content-Type` header. This will return a string of the +content type for the given object with the following properties (examples are +shown that produce the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The media type (will be lower-cased). Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of the + parameter will be lower-cased). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the object contains an invalid type or parameter names. + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/content-type/master?label=ci +[ci-url]: https://github.com/jshttp/content-type/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/content-type/master +[coveralls-url]: https://coveralls.io/r/jshttp/content-type?branch=master +[node-image]: https://badgen.net/npm/node/content-type +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/content-type +[npm-url]: https://npmjs.org/package/content-type +[npm-version-image]: https://badgen.net/npm/v/content-type diff --git a/node_modules/content-type/index.js b/node_modules/content-type/index.js new file mode 100644 index 0000000..41840e7 --- /dev/null +++ b/node_modules/content-type/index.js @@ -0,0 +1,225 @@ +/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + */ +var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g // eslint-disable-line no-control-regex +var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ // eslint-disable-line no-control-regex +var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ + +/** + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 + * + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF + */ +var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g // eslint-disable-line no-control-regex + +/** + * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 + */ +var QUOTE_REGEXP = /([\\"])/g + +/** + * RegExp to match type in RFC 7231 sec 3.1.1.1 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ +var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ + +/** + * Module exports. + * @public + */ + +exports.format = format +exports.parse = parse + +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @public + */ + +function format (obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } + + var parameters = obj.parameters + var type = obj.type + + if (!type || !TYPE_REGEXP.test(type)) { + throw new TypeError('invalid type') + } + + var string = type + + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() + + for (var i = 0; i < params.length; i++) { + param = params[i] + + if (!TOKEN_REGEXP.test(param)) { + throw new TypeError('invalid parameter name') + } + + string += '; ' + param + '=' + qstring(parameters[param]) + } + } + + return string +} + +/** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @public + */ + +function parse (string) { + if (!string) { + throw new TypeError('argument string is required') + } + + // support req/res-like objects as argument + var header = typeof string === 'object' + ? getcontenttype(string) + : string + + if (typeof header !== 'string') { + throw new TypeError('argument string is required to be a string') + } + + var index = header.indexOf(';') + var type = index !== -1 + ? header.slice(0, index).trim() + : header.trim() + + if (!TYPE_REGEXP.test(type)) { + throw new TypeError('invalid media type') + } + + var obj = new ContentType(type.toLowerCase()) + + // parse parameters + if (index !== -1) { + var key + var match + var value + + PARAM_REGEXP.lastIndex = index + + while ((match = PARAM_REGEXP.exec(header))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } + + index += match[0].length + key = match[1].toLowerCase() + value = match[2] + + if (value.charCodeAt(0) === 0x22 /* " */) { + // remove quotes + value = value.slice(1, -1) + + // remove escapes + if (value.indexOf('\\') !== -1) { + value = value.replace(QESC_REGEXP, '$1') + } + } + + obj.parameters[key] = value + } + + if (index !== header.length) { + throw new TypeError('invalid parameter format') + } + } + + return obj +} + +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @private + */ + +function getcontenttype (obj) { + var header + + if (typeof obj.getHeader === 'function') { + // res-like + header = obj.getHeader('content-type') + } else if (typeof obj.headers === 'object') { + // req-like + header = obj.headers && obj.headers['content-type'] + } + + if (typeof header !== 'string') { + throw new TypeError('content-type header is missing from object') + } + + return header +} + +/** + * Quote a string if necessary. + * + * @param {string} val + * @return {string} + * @private + */ + +function qstring (val) { + var str = String(val) + + // no need to quote tokens + if (TOKEN_REGEXP.test(str)) { + return str + } + + if (str.length > 0 && !TEXT_REGEXP.test(str)) { + throw new TypeError('invalid parameter value') + } + + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' +} + +/** + * Class to represent a content type. + * @private + */ +function ContentType (type) { + this.parameters = Object.create(null) + this.type = type +} diff --git a/node_modules/content-type/package.json b/node_modules/content-type/package.json new file mode 100644 index 0000000..9db19f6 --- /dev/null +++ b/node_modules/content-type/package.json @@ -0,0 +1,42 @@ +{ + "name": "content-type", + "description": "Create and parse HTTP Content-Type header", + "version": "1.0.5", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "content-type", + "http", + "req", + "res", + "rfc7231" + ], + "repository": "jshttp/content-type", + "devDependencies": { + "deep-equal": "1.0.1", + "eslint": "8.32.0", + "eslint-config-standard": "15.0.1", + "eslint-plugin-import": "2.27.5", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "6.1.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "10.2.0", + "nyc": "15.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/cookie-signature/History.md b/node_modules/cookie-signature/History.md new file mode 100644 index 0000000..479211a --- /dev/null +++ b/node_modules/cookie-signature/History.md @@ -0,0 +1,70 @@ +1.2.2 / 2024-10-29 +================== + +* various metadata/documentation tweaks (incl. #51) + + +1.2.1 / 2023-02-27 +================== + +* update annotations for allowed secret key types (#44, thanks @jyasskin!) + + +1.2.0 / 2022-02-17 +================== + +* allow buffer and other node-supported types as key (#33) +* be pickier about extra content after signed portion (#40) +* some internal code clarity/cleanup improvements (#26) + + +1.1.0 / 2018-01-18 +================== + +* switch to built-in `crypto.timingSafeEqual` for validation instead of previous double-hash method (thank you @jodevsa!) + + +1.0.7 / 2023-04-12 +================== + +Later release for older node.js versions. See the [v1.0.x branch notes](https://github.com/tj/node-cookie-signature/blob/v1.0.x/History.md#107--2023-04-12). + + +1.0.6 / 2015-02-03 +================== + +* use `npm test` instead of `make test` to run tests +* clearer assertion messages when checking input + + +1.0.5 / 2014-09-05 +================== + +* add license to package.json + +1.0.4 / 2014-06-25 +================== + + * corrected avoidance of timing attacks (thanks @tenbits!) + +1.0.3 / 2014-01-28 +================== + + * [incorrect] fix for timing attacks + +1.0.2 / 2014-01-28 +================== + + * fix missing repository warning + * fix typo in test + +1.0.1 / 2013-04-15 +================== + + * Revert "Changed underlying HMAC algo. to sha512." + * Revert "Fix for timing attacks on MAC verification." + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/cookie-signature/LICENSE b/node_modules/cookie-signature/LICENSE new file mode 100644 index 0000000..a2671bf --- /dev/null +++ b/node_modules/cookie-signature/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2012–2024 LearnBoost and other contributors; + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/cookie-signature/Readme.md b/node_modules/cookie-signature/Readme.md new file mode 100644 index 0000000..369af15 --- /dev/null +++ b/node_modules/cookie-signature/Readme.md @@ -0,0 +1,23 @@ + +# cookie-signature + + Sign and unsign cookies. + +## Example + +```js +var cookie = require('cookie-signature'); + +var val = cookie.sign('hello', 'tobiiscool'); +val.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI'); + +var val = cookie.sign('hello', 'tobiiscool'); +cookie.unsign(val, 'tobiiscool').should.equal('hello'); +cookie.unsign(val, 'luna').should.be.false; +``` + +## License + +MIT. + +See LICENSE file for details. diff --git a/node_modules/cookie-signature/index.js b/node_modules/cookie-signature/index.js new file mode 100644 index 0000000..3fbbddb --- /dev/null +++ b/node_modules/cookie-signature/index.js @@ -0,0 +1,47 @@ +/** + * Module dependencies. + */ + +var crypto = require('crypto'); + +/** + * Sign the given `val` with `secret`. + * + * @param {String} val + * @param {String|NodeJS.ArrayBufferView|crypto.KeyObject} secret + * @return {String} + * @api private + */ + +exports.sign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string."); + if (null == secret) throw new TypeError("Secret key must be provided."); + return val + '.' + crypto + .createHmac('sha256', secret) + .update(val) + .digest('base64') + .replace(/\=+$/, ''); +}; + +/** + * Unsign and decode the given `input` with `secret`, + * returning `false` if the signature is invalid. + * + * @param {String} input + * @param {String|NodeJS.ArrayBufferView|crypto.KeyObject} secret + * @return {String|Boolean} + * @api private + */ + +exports.unsign = function(input, secret){ + if ('string' != typeof input) throw new TypeError("Signed cookie string must be provided."); + if (null == secret) throw new TypeError("Secret key must be provided."); + var tentativeValue = input.slice(0, input.lastIndexOf('.')), + expectedInput = exports.sign(tentativeValue, secret), + expectedBuffer = Buffer.from(expectedInput), + inputBuffer = Buffer.from(input); + return ( + expectedBuffer.length === inputBuffer.length && + crypto.timingSafeEqual(expectedBuffer, inputBuffer) + ) ? tentativeValue : false; +}; diff --git a/node_modules/cookie-signature/package.json b/node_modules/cookie-signature/package.json new file mode 100644 index 0000000..a160040 --- /dev/null +++ b/node_modules/cookie-signature/package.json @@ -0,0 +1,24 @@ +{ + "name": "cookie-signature", + "version": "1.2.2", + "main": "index.js", + "description": "Sign and unsign cookies", + "keywords": ["cookie", "sign", "unsign"], + "author": "TJ Holowaychuk ", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/visionmedia/node-cookie-signature.git" + }, + "dependencies": {}, + "engines": { + "node": ">=6.6.0" + }, + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "scripts": { + "test": "mocha --require should --reporter spec" + } +} diff --git a/node_modules/cookie/LICENSE b/node_modules/cookie/LICENSE new file mode 100644 index 0000000..058b6b4 --- /dev/null +++ b/node_modules/cookie/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2014 Roman Shtylman +Copyright (c) 2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/cookie/README.md b/node_modules/cookie/README.md new file mode 100644 index 0000000..71fdac1 --- /dev/null +++ b/node_modules/cookie/README.md @@ -0,0 +1,317 @@ +# cookie + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +Basic HTTP cookie parser and serializer for HTTP servers. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install cookie +``` + +## API + +```js +var cookie = require('cookie'); +``` + +### cookie.parse(str, options) + +Parse an HTTP `Cookie` header string and returning an object of all cookie name-value pairs. +The `str` argument is the string representing a `Cookie` header value and `options` is an +optional object containing additional parsing options. + +```js +var cookies = cookie.parse('foo=bar; equation=E%3Dmc%5E2'); +// { foo: 'bar', equation: 'E=mc^2' } +``` + +#### Options + +`cookie.parse` accepts these properties in the options object. + +##### decode + +Specifies a function that will be used to decode a cookie's value. Since the value of a cookie +has a limited character set (and must be a simple string), this function can be used to decode +a previously-encoded cookie value into a JavaScript string or other object. + +The default function is the global `decodeURIComponent`, which will decode any URL-encoded +sequences into their byte representations. + +**note** if an error is thrown from this function, the original, non-decoded cookie value will +be returned as the cookie's value. + +### cookie.serialize(name, value, options) + +Serialize a cookie name-value pair into a `Set-Cookie` header string. The `name` argument is the +name for the cookie, the `value` argument is the value to set the cookie to, and the `options` +argument is an optional object containing additional serialization options. + +```js +var setCookie = cookie.serialize('foo', 'bar'); +// foo=bar +``` + +#### Options + +`cookie.serialize` accepts these properties in the options object. + +##### domain + +Specifies the value for the [`Domain` `Set-Cookie` attribute][rfc-6265-5.2.3]. By default, no +domain is set, and most clients will consider the cookie to apply to only the current domain. + +##### encode + +Specifies a function that will be used to encode a cookie's value. Since value of a cookie +has a limited character set (and must be a simple string), this function can be used to encode +a value into a string suited for a cookie's value. + +The default function is the global `encodeURIComponent`, which will encode a JavaScript string +into UTF-8 byte sequences and then URL-encode any that fall outside of the cookie range. + +##### expires + +Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute][rfc-6265-5.2.1]. +By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and +will delete it on a condition like exiting a web browser application. + +**note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and +`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this, +so if both are set, they should point to the same date and time. + +##### httpOnly + +Specifies the `boolean` value for the [`HttpOnly` `Set-Cookie` attribute][rfc-6265-5.2.6]. When truthy, +the `HttpOnly` attribute is set, otherwise it is not. By default, the `HttpOnly` attribute is not set. + +**note** be careful when setting this to `true`, as compliant clients will not allow client-side +JavaScript to see the cookie in `document.cookie`. + +##### maxAge + +Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute][rfc-6265-5.2.2]. +The given number will be converted to an integer by rounding down. By default, no maximum age is set. + +**note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and +`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this, +so if both are set, they should point to the same date and time. + +##### partitioned + +Specifies the `boolean` value for the [`Partitioned` `Set-Cookie`](rfc-cutler-httpbis-partitioned-cookies) +attribute. When truthy, the `Partitioned` attribute is set, otherwise it is not. By default, the +`Partitioned` attribute is not set. + +**note** This is an attribute that has not yet been fully standardized, and may change in the future. +This also means many clients may ignore this attribute until they understand it. + +More information about can be found in [the proposal](https://github.com/privacycg/CHIPS). + +##### path + +Specifies the value for the [`Path` `Set-Cookie` attribute][rfc-6265-5.2.4]. By default, the path +is considered the ["default path"][rfc-6265-5.1.4]. + +##### priority + +Specifies the `string` to be the value for the [`Priority` `Set-Cookie` attribute][rfc-west-cookie-priority-00-4.1]. + + - `'low'` will set the `Priority` attribute to `Low`. + - `'medium'` will set the `Priority` attribute to `Medium`, the default priority when not set. + - `'high'` will set the `Priority` attribute to `High`. + +More information about the different priority levels can be found in +[the specification][rfc-west-cookie-priority-00-4.1]. + +**note** This is an attribute that has not yet been fully standardized, and may change in the future. +This also means many clients may ignore this attribute until they understand it. + +##### sameSite + +Specifies the `boolean` or `string` to be the value for the [`SameSite` `Set-Cookie` attribute][rfc-6265bis-09-5.4.7]. + + - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement. + - `false` will not set the `SameSite` attribute. + - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement. + - `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie. + - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement. + +More information about the different enforcement levels can be found in +[the specification][rfc-6265bis-09-5.4.7]. + +**note** This is an attribute that has not yet been fully standardized, and may change in the future. +This also means many clients may ignore this attribute until they understand it. + +##### secure + +Specifies the `boolean` value for the [`Secure` `Set-Cookie` attribute][rfc-6265-5.2.5]. When truthy, +the `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set. + +**note** be careful when setting this to `true`, as compliant clients will not send the cookie back to +the server in the future if the browser does not have an HTTPS connection. + +## Example + +The following example uses this module in conjunction with the Node.js core HTTP server +to prompt a user for their name and display it back on future visits. + +```js +var cookie = require('cookie'); +var escapeHtml = require('escape-html'); +var http = require('http'); +var url = require('url'); + +function onRequest(req, res) { + // Parse the query string + var query = url.parse(req.url, true, true).query; + + if (query && query.name) { + // Set a new cookie with the name + res.setHeader('Set-Cookie', cookie.serialize('name', String(query.name), { + httpOnly: true, + maxAge: 60 * 60 * 24 * 7 // 1 week + })); + + // Redirect back after setting cookie + res.statusCode = 302; + res.setHeader('Location', req.headers.referer || '/'); + res.end(); + return; + } + + // Parse the cookies on the request + var cookies = cookie.parse(req.headers.cookie || ''); + + // Get the visitor name set in the cookie + var name = cookies.name; + + res.setHeader('Content-Type', 'text/html; charset=UTF-8'); + + if (name) { + res.write('

Welcome back, ' + escapeHtml(name) + '!

'); + } else { + res.write('

Hello, new visitor!

'); + } + + res.write('
'); + res.write(' '); + res.end('
'); +} + +http.createServer(onRequest).listen(3000); +``` + +## Testing + +```sh +$ npm test +``` + +## Benchmark + +``` +$ npm run bench + +> cookie@0.5.0 bench +> node benchmark/index.js + + node@18.18.2 + acorn@8.10.0 + ada@2.6.0 + ares@1.19.1 + brotli@1.0.9 + cldr@43.1 + icu@73.2 + llhttp@6.0.11 + modules@108 + napi@9 + nghttp2@1.57.0 + nghttp3@0.7.0 + ngtcp2@0.8.1 + openssl@3.0.10+quic + simdutf@3.2.14 + tz@2023c + undici@5.26.3 + unicode@15.0 + uv@1.44.2 + uvwasi@0.0.18 + v8@10.2.154.26-node.26 + zlib@1.2.13.1-motley + +> node benchmark/parse-top.js + + cookie.parse - top sites + + 14 tests completed. + + parse accounts.google.com x 2,588,913 ops/sec ±0.74% (186 runs sampled) + parse apple.com x 2,370,002 ops/sec ±0.69% (186 runs sampled) + parse cloudflare.com x 2,213,102 ops/sec ±0.88% (188 runs sampled) + parse docs.google.com x 2,194,157 ops/sec ±1.03% (184 runs sampled) + parse drive.google.com x 2,265,084 ops/sec ±0.79% (187 runs sampled) + parse en.wikipedia.org x 457,099 ops/sec ±0.81% (186 runs sampled) + parse linkedin.com x 504,407 ops/sec ±0.89% (186 runs sampled) + parse maps.google.com x 1,230,959 ops/sec ±0.98% (186 runs sampled) + parse microsoft.com x 926,294 ops/sec ±0.88% (184 runs sampled) + parse play.google.com x 2,311,338 ops/sec ±0.83% (185 runs sampled) + parse support.google.com x 1,508,850 ops/sec ±0.86% (186 runs sampled) + parse www.google.com x 1,022,582 ops/sec ±1.32% (182 runs sampled) + parse youtu.be x 332,136 ops/sec ±1.02% (185 runs sampled) + parse youtube.com x 323,833 ops/sec ±0.77% (183 runs sampled) + +> node benchmark/parse.js + + cookie.parse - generic + + 6 tests completed. + + simple x 3,214,032 ops/sec ±1.61% (183 runs sampled) + decode x 587,237 ops/sec ±1.16% (187 runs sampled) + unquote x 2,954,618 ops/sec ±1.35% (183 runs sampled) + duplicates x 857,008 ops/sec ±0.89% (187 runs sampled) + 10 cookies x 292,133 ops/sec ±0.89% (187 runs sampled) + 100 cookies x 22,610 ops/sec ±0.68% (187 runs sampled) +``` + +## References + +- [RFC 6265: HTTP State Management Mechanism][rfc-6265] +- [Same-site Cookies][rfc-6265bis-09-5.4.7] + +[rfc-cutler-httpbis-partitioned-cookies]: https://tools.ietf.org/html/draft-cutler-httpbis-partitioned-cookies/ +[rfc-west-cookie-priority-00-4.1]: https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1 +[rfc-6265bis-09-5.4.7]: https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-09#section-5.4.7 +[rfc-6265]: https://tools.ietf.org/html/rfc6265 +[rfc-6265-5.1.4]: https://tools.ietf.org/html/rfc6265#section-5.1.4 +[rfc-6265-5.2.1]: https://tools.ietf.org/html/rfc6265#section-5.2.1 +[rfc-6265-5.2.2]: https://tools.ietf.org/html/rfc6265#section-5.2.2 +[rfc-6265-5.2.3]: https://tools.ietf.org/html/rfc6265#section-5.2.3 +[rfc-6265-5.2.4]: https://tools.ietf.org/html/rfc6265#section-5.2.4 +[rfc-6265-5.2.5]: https://tools.ietf.org/html/rfc6265#section-5.2.5 +[rfc-6265-5.2.6]: https://tools.ietf.org/html/rfc6265#section-5.2.6 +[rfc-6265-5.3]: https://tools.ietf.org/html/rfc6265#section-5.3 + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/cookie/master?label=ci +[ci-url]: https://github.com/jshttp/cookie/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/cookie/master +[coveralls-url]: https://coveralls.io/r/jshttp/cookie?branch=master +[node-image]: https://badgen.net/npm/node/cookie +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/cookie +[npm-url]: https://npmjs.org/package/cookie +[npm-version-image]: https://badgen.net/npm/v/cookie diff --git a/node_modules/cookie/SECURITY.md b/node_modules/cookie/SECURITY.md new file mode 100644 index 0000000..fd4a6c5 --- /dev/null +++ b/node_modules/cookie/SECURITY.md @@ -0,0 +1,25 @@ +# Security Policies and Procedures + +## Reporting a Bug + +The `cookie` team and community take all security bugs seriously. Thank +you for improving the security of the project. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing the current owner(s) of `cookie`. This +information can be found in the npm registry using the command +`npm owner ls cookie`. +If unsure or unable to get the information from the above, open an issue +in the [project issue tracker](https://github.com/jshttp/cookie/issues) +asking for the current contact information. + +To ensure the timely response to your report, please ensure that the entirety +of the report is contained within the email body and not solely behind a web +link or an attachment. + +At least one owner will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. After the initial reply to your report, the owners will +endeavor to keep you informed of the progress towards a fix and full +announcement, and may ask for additional information or guidance. diff --git a/node_modules/cookie/index.js b/node_modules/cookie/index.js new file mode 100644 index 0000000..acd5acd --- /dev/null +++ b/node_modules/cookie/index.js @@ -0,0 +1,335 @@ +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +exports.parse = parse; +exports.serialize = serialize; + +/** + * Module variables. + * @private + */ + +var __toString = Object.prototype.toString +var __hasOwnProperty = Object.prototype.hasOwnProperty + +/** + * RegExp to match cookie-name in RFC 6265 sec 4.1.1 + * This refers out to the obsoleted definition of token in RFC 2616 sec 2.2 + * which has been replaced by the token definition in RFC 7230 appendix B. + * + * cookie-name = token + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / + * "*" / "+" / "-" / "." / "^" / "_" / + * "`" / "|" / "~" / DIGIT / ALPHA + */ + +var cookieNameRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; + +/** + * RegExp to match cookie-value in RFC 6265 sec 4.1.1 + * + * cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) + * cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E + * ; US-ASCII characters excluding CTLs, + * ; whitespace DQUOTE, comma, semicolon, + * ; and backslash + */ + +var cookieValueRegExp = /^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/; + +/** + * RegExp to match domain-value in RFC 6265 sec 4.1.1 + * + * domain-value = + * ; defined in [RFC1034], Section 3.5, as + * ; enhanced by [RFC1123], Section 2.1 + * =
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Sponsors + +Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## License + +(The MIT License) + +Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca> +Copyright (c) 2018-2021 Josh Junon + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/debug/package.json b/node_modules/debug/package.json new file mode 100644 index 0000000..afc2f8b --- /dev/null +++ b/node_modules/debug/package.json @@ -0,0 +1,64 @@ +{ + "name": "debug", + "version": "4.4.1", + "repository": { + "type": "git", + "url": "git://github.com/debug-js/debug.git" + }, + "description": "Lightweight debugging utility for Node.js and the browser", + "keywords": [ + "debug", + "log", + "debugger" + ], + "files": [ + "src", + "LICENSE", + "README.md" + ], + "author": "Josh Junon (https://github.com/qix-)", + "contributors": [ + "TJ Holowaychuk ", + "Nathan Rajlich (http://n8.io)", + "Andrew Rhyne " + ], + "license": "MIT", + "scripts": { + "lint": "xo", + "test": "npm run test:node && npm run test:browser && npm run lint", + "test:node": "mocha test.js test.node.js", + "test:browser": "karma start --single-run", + "test:coverage": "cat ./coverage/lcov.info | coveralls" + }, + "dependencies": { + "ms": "^2.1.3" + }, + "devDependencies": { + "brfs": "^2.0.1", + "browserify": "^16.2.3", + "coveralls": "^3.0.2", + "karma": "^3.1.4", + "karma-browserify": "^6.0.0", + "karma-chrome-launcher": "^2.2.0", + "karma-mocha": "^1.3.0", + "mocha": "^5.2.0", + "mocha-lcov-reporter": "^1.2.0", + "sinon": "^14.0.0", + "xo": "^0.23.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + }, + "main": "./src/index.js", + "browser": "./src/browser.js", + "engines": { + "node": ">=6.0" + }, + "xo": { + "rules": { + "import/extensions": "off" + } + } +} diff --git a/node_modules/debug/src/browser.js b/node_modules/debug/src/browser.js new file mode 100644 index 0000000..5993451 --- /dev/null +++ b/node_modules/debug/src/browser.js @@ -0,0 +1,272 @@ +/* eslint-env browser */ + +/** + * This is the web browser implementation of `debug()`. + */ + +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); + +/** + * Colors. + */ + +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + let m; + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + // eslint-disable-next-line no-return-assign + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ +exports.log = console.debug || console.log || (() => {}); + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +module.exports = require('./common')(exports); + +const {formatters} = module.exports; + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; diff --git a/node_modules/debug/src/common.js b/node_modules/debug/src/common.js new file mode 100644 index 0000000..141cb57 --- /dev/null +++ b/node_modules/debug/src/common.js @@ -0,0 +1,292 @@ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require('ms'); + createDebug.destroy = destroy; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); + + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + return debug; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + + createDebug.names = []; + createDebug.skips = []; + + const split = (typeof namespaces === 'string' ? namespaces : '') + .trim() + .replace(/\s+/g, ',') + .split(',') + .filter(Boolean); + + for (const ns of split) { + if (ns[0] === '-') { + createDebug.skips.push(ns.slice(1)); + } else { + createDebug.names.push(ns); + } + } + } + + /** + * Checks if the given string matches a namespace template, honoring + * asterisks as wildcards. + * + * @param {String} search + * @param {String} template + * @return {Boolean} + */ + function matchesTemplate(search, template) { + let searchIndex = 0; + let templateIndex = 0; + let starIndex = -1; + let matchIndex = 0; + + while (searchIndex < search.length) { + if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) { + // Match character or proceed with wildcard + if (template[templateIndex] === '*') { + starIndex = templateIndex; + matchIndex = searchIndex; + templateIndex++; // Skip the '*' + } else { + searchIndex++; + templateIndex++; + } + } else if (starIndex !== -1) { // eslint-disable-line no-negated-condition + // Backtrack to the last '*' and try to match more characters + templateIndex = starIndex + 1; + matchIndex++; + searchIndex = matchIndex; + } else { + return false; // No match + } + } + + // Handle trailing '*' in template + while (templateIndex < template.length && template[templateIndex] === '*') { + templateIndex++; + } + + return templateIndex === template.length; + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names, + ...createDebug.skips.map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + for (const skip of createDebug.skips) { + if (matchesTemplate(name, skip)) { + return false; + } + } + + for (const ns of createDebug.names) { + if (matchesTemplate(name, ns)) { + return true; + } + } + + return false; + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; +} + +module.exports = setup; diff --git a/node_modules/debug/src/index.js b/node_modules/debug/src/index.js new file mode 100644 index 0000000..bf4c57f --- /dev/null +++ b/node_modules/debug/src/index.js @@ -0,0 +1,10 @@ +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ + +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = require('./browser.js'); +} else { + module.exports = require('./node.js'); +} diff --git a/node_modules/debug/src/node.js b/node_modules/debug/src/node.js new file mode 100644 index 0000000..715560a --- /dev/null +++ b/node_modules/debug/src/node.js @@ -0,0 +1,263 @@ +/** + * Module dependencies. + */ + +const tty = require('tty'); +const util = require('util'); + +/** + * This is the Node.js implementation of `debug()`. + */ + +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = require('supports-color'); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. +} + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; +}, {}); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} + +/** + * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr. + */ + +function log(...args) { + return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init(debug) { + debug.inspectOpts = {}; + + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +module.exports = require('./common')(exports); + +const {formatters} = module.exports; + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; + +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; diff --git a/node_modules/depd/History.md b/node_modules/depd/History.md new file mode 100644 index 0000000..cd9ebaa --- /dev/null +++ b/node_modules/depd/History.md @@ -0,0 +1,103 @@ +2.0.0 / 2018-10-26 +================== + + * Drop support for Node.js 0.6 + * Replace internal `eval` usage with `Function` constructor + * Use instance methods on `process` to check for listeners + +1.1.2 / 2018-01-11 +================== + + * perf: remove argument reassignment + * Support Node.js 0.6 to 9.x + +1.1.1 / 2017-07-27 +================== + + * Remove unnecessary `Buffer` loading + * Support Node.js 0.6 to 8.x + +1.1.0 / 2015-09-14 +================== + + * Enable strict mode in more places + * Support io.js 3.x + * Support io.js 2.x + * Support web browser loading + - Requires bundler like Browserify or webpack + +1.0.1 / 2015-04-07 +================== + + * Fix `TypeError`s when under `'use strict'` code + * Fix useless type name on auto-generated messages + * Support io.js 1.x + * Support Node.js 0.12 + +1.0.0 / 2014-09-17 +================== + + * No changes + +0.4.5 / 2014-09-09 +================== + + * Improve call speed to functions using the function wrapper + * Support Node.js 0.6 + +0.4.4 / 2014-07-27 +================== + + * Work-around v8 generating empty stack traces + +0.4.3 / 2014-07-26 +================== + + * Fix exception when global `Error.stackTraceLimit` is too low + +0.4.2 / 2014-07-19 +================== + + * Correct call site for wrapped functions and properties + +0.4.1 / 2014-07-19 +================== + + * Improve automatic message generation for function properties + +0.4.0 / 2014-07-19 +================== + + * Add `TRACE_DEPRECATION` environment variable + * Remove non-standard grey color from color output + * Support `--no-deprecation` argument + * Support `--trace-deprecation` argument + * Support `deprecate.property(fn, prop, message)` + +0.3.0 / 2014-06-16 +================== + + * Add `NO_DEPRECATION` environment variable + +0.2.0 / 2014-06-15 +================== + + * Add `deprecate.property(obj, prop, message)` + * Remove `supports-color` dependency for node.js 0.8 + +0.1.0 / 2014-06-15 +================== + + * Add `deprecate.function(fn, message)` + * Add `process.on('deprecation', fn)` emitter + * Automatically generate message when omitted from `deprecate()` + +0.0.1 / 2014-06-15 +================== + + * Fix warning for dynamic calls at singe call site + +0.0.0 / 2014-06-15 +================== + + * Initial implementation diff --git a/node_modules/depd/LICENSE b/node_modules/depd/LICENSE new file mode 100644 index 0000000..248de7a --- /dev/null +++ b/node_modules/depd/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2018 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/depd/Readme.md b/node_modules/depd/Readme.md new file mode 100644 index 0000000..043d1ca --- /dev/null +++ b/node_modules/depd/Readme.md @@ -0,0 +1,280 @@ +# depd + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +Deprecate all the things + +> With great modules comes great responsibility; mark things deprecated! + +## Install + +This module is installed directly using `npm`: + +```sh +$ npm install depd +``` + +This module can also be bundled with systems like +[Browserify](http://browserify.org/) or [webpack](https://webpack.github.io/), +though by default this module will alter it's API to no longer display or +track deprecations. + +## API + + + +```js +var deprecate = require('depd')('my-module') +``` + +This library allows you to display deprecation messages to your users. +This library goes above and beyond with deprecation warnings by +introspection of the call stack (but only the bits that it is interested +in). + +Instead of just warning on the first invocation of a deprecated +function and never again, this module will warn on the first invocation +of a deprecated function per unique call site, making it ideal to alert +users of all deprecated uses across the code base, rather than just +whatever happens to execute first. + +The deprecation warnings from this module also include the file and line +information for the call into the module that the deprecated function was +in. + +**NOTE** this library has a similar interface to the `debug` module, and +this module uses the calling file to get the boundary for the call stacks, +so you should always create a new `deprecate` object in each file and not +within some central file. + +### depd(namespace) + +Create a new deprecate function that uses the given namespace name in the +messages and will display the call site prior to the stack entering the +file this function was called from. It is highly suggested you use the +name of your module as the namespace. + +### deprecate(message) + +Call this function from deprecated code to display a deprecation message. +This message will appear once per unique caller site. Caller site is the +first call site in the stack in a different file from the caller of this +function. + +If the message is omitted, a message is generated for you based on the site +of the `deprecate()` call and will display the name of the function called, +similar to the name displayed in a stack trace. + +### deprecate.function(fn, message) + +Call this function to wrap a given function in a deprecation message on any +call to the function. An optional message can be supplied to provide a custom +message. + +### deprecate.property(obj, prop, message) + +Call this function to wrap a given property on object in a deprecation message +on any accessing or setting of the property. An optional message can be supplied +to provide a custom message. + +The method must be called on the object where the property belongs (not +inherited from the prototype). + +If the property is a data descriptor, it will be converted to an accessor +descriptor in order to display the deprecation message. + +### process.on('deprecation', fn) + +This module will allow easy capturing of deprecation errors by emitting the +errors as the type "deprecation" on the global `process`. If there are no +listeners for this type, the errors are written to STDERR as normal, but if +there are any listeners, nothing will be written to STDERR and instead only +emitted. From there, you can write the errors in a different format or to a +logging source. + +The error represents the deprecation and is emitted only once with the same +rules as writing to STDERR. The error has the following properties: + + - `message` - This is the message given by the library + - `name` - This is always `'DeprecationError'` + - `namespace` - This is the namespace the deprecation came from + - `stack` - This is the stack of the call to the deprecated thing + +Example `error.stack` output: + +``` +DeprecationError: my-cool-module deprecated oldfunction + at Object. ([eval]-wrapper:6:22) + at Module._compile (module.js:456:26) + at evalScript (node.js:532:25) + at startup (node.js:80:7) + at node.js:902:3 +``` + +### process.env.NO_DEPRECATION + +As a user of modules that are deprecated, the environment variable `NO_DEPRECATION` +is provided as a quick solution to silencing deprecation warnings from being +output. The format of this is similar to that of `DEBUG`: + +```sh +$ NO_DEPRECATION=my-module,othermod node app.js +``` + +This will suppress deprecations from being output for "my-module" and "othermod". +The value is a list of comma-separated namespaces. To suppress every warning +across all namespaces, use the value `*` for a namespace. + +Providing the argument `--no-deprecation` to the `node` executable will suppress +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not suppress the deperecations given to any "deprecation" +event listeners, just the output to STDERR. + +### process.env.TRACE_DEPRECATION + +As a user of modules that are deprecated, the environment variable `TRACE_DEPRECATION` +is provided as a solution to getting more detailed location information in deprecation +warnings by including the entire stack trace. The format of this is the same as +`NO_DEPRECATION`: + +```sh +$ TRACE_DEPRECATION=my-module,othermod node app.js +``` + +This will include stack traces for deprecations being output for "my-module" and +"othermod". The value is a list of comma-separated namespaces. To trace every +warning across all namespaces, use the value `*` for a namespace. + +Providing the argument `--trace-deprecation` to the `node` executable will trace +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not trace the deperecations silenced by `NO_DEPRECATION`. + +## Display + +![message](files/message.png) + +When a user calls a function in your library that you mark deprecated, they +will see the following written to STDERR (in the given colors, similar colors +and layout to the `debug` module): + +``` +bright cyan bright yellow +| | reset cyan +| | | | +▼ ▼ ▼ ▼ +my-cool-module deprecated oldfunction [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ +| | | | +namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +If the user redirects their STDERR to a file or somewhere that does not support +colors, they see (similar layout to the `debug` module): + +``` +Sun, 15 Jun 2014 05:21:37 GMT my-cool-module deprecated oldfunction at [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ ▲ +| | | | | +timestamp of message namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +## Examples + +### Deprecating all calls to a function + +This will display a deprecated message about "oldfunction" being deprecated +from "my-module" on STDERR. + +```js +var deprecate = require('depd')('my-cool-module') + +// message automatically derived from function name +// Object.oldfunction +exports.oldfunction = deprecate.function(function oldfunction () { + // all calls to function are deprecated +}) + +// specific message +exports.oldfunction = deprecate.function(function () { + // all calls to function are deprecated +}, 'oldfunction') +``` + +### Conditionally deprecating a function call + +This will display a deprecated message about "weirdfunction" being deprecated +from "my-module" on STDERR when called with less than 2 arguments. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } +} +``` + +When calling `deprecate` as a function, the warning is counted per call site +within your own module, so you can display different deprecations depending +on different situations and the users will still get all the warnings: + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } else if (typeof arguments[0] !== 'string') { + // calls with non-string first argument are deprecated + deprecate('weirdfunction non-string first arg') + } +} +``` + +### Deprecating property access + +This will display a deprecated message about "oldprop" being deprecated +from "my-module" on STDERR when accessed. A deprecation will be displayed +when setting the value and when getting the value. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.oldprop = 'something' + +// message automatically derives from property name +deprecate.property(exports, 'oldprop') + +// explicit message +deprecate.property(exports, 'oldprop', 'oldprop >= 0.10') +``` + +## License + +[MIT](LICENSE) + +[appveyor-image]: https://badgen.net/appveyor/ci/dougwilson/nodejs-depd/master?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/nodejs-depd +[coveralls-image]: https://badgen.net/coveralls/c/github/dougwilson/nodejs-depd/master +[coveralls-url]: https://coveralls.io/r/dougwilson/nodejs-depd?branch=master +[node-image]: https://badgen.net/npm/node/depd +[node-url]: https://nodejs.org/en/download/ +[npm-downloads-image]: https://badgen.net/npm/dm/depd +[npm-url]: https://npmjs.org/package/depd +[npm-version-image]: https://badgen.net/npm/v/depd +[travis-image]: https://badgen.net/travis/dougwilson/nodejs-depd/master?label=linux +[travis-url]: https://travis-ci.org/dougwilson/nodejs-depd diff --git a/node_modules/depd/index.js b/node_modules/depd/index.js new file mode 100644 index 0000000..1bf2fcf --- /dev/null +++ b/node_modules/depd/index.js @@ -0,0 +1,538 @@ +/*! + * depd + * Copyright(c) 2014-2018 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var relative = require('path').relative + +/** + * Module exports. + */ + +module.exports = depd + +/** + * Get the path to base files on. + */ + +var basePath = process.cwd() + +/** + * Determine if namespace is contained in the string. + */ + +function containsNamespace (str, namespace) { + var vals = str.split(/[ ,]+/) + var ns = String(namespace).toLowerCase() + + for (var i = 0; i < vals.length; i++) { + var val = vals[i] + + // namespace contained + if (val && (val === '*' || val.toLowerCase() === ns)) { + return true + } + } + + return false +} + +/** + * Convert a data descriptor to accessor descriptor. + */ + +function convertDataDescriptorToAccessor (obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value + + descriptor.get = function getter () { return value } + + if (descriptor.writable) { + descriptor.set = function setter (val) { return (value = val) } + } + + delete descriptor.value + delete descriptor.writable + + Object.defineProperty(obj, prop, descriptor) + + return descriptor +} + +/** + * Create arguments string to keep arity. + */ + +function createArgumentsString (arity) { + var str = '' + + for (var i = 0; i < arity; i++) { + str += ', arg' + i + } + + return str.substr(2) +} + +/** + * Create stack string from stack. + */ + +function createStackString (stack) { + var str = this.name + ': ' + this.namespace + + if (this.message) { + str += ' deprecated ' + this.message + } + + for (var i = 0; i < stack.length; i++) { + str += '\n at ' + stack[i].toString() + } + + return str +} + +/** + * Create deprecate for namespace in caller. + */ + +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] + + function deprecate (message) { + // call to self as log + log.call(deprecate, message) + } + + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Determine if event emitter has listeners of a given type. + * + * The way to do this check is done three different ways in Node.js >= 0.8 + * so this consolidates them into a minimal set using instance methods. + * + * @param {EventEmitter} emitter + * @param {string} type + * @returns {boolean} + * @private + */ + +function eehaslisteners (emitter, type) { + var count = typeof emitter.listenerCount !== 'function' + ? emitter.listeners(type).length + : emitter.listenerCount(type) + + return count > 0 +} + +/** + * Determine if namespace is ignored. + */ + +function isignored (namespace) { + if (process.noDeprecation) { + // --no-deprecation support + return true + } + + var str = process.env.NO_DEPRECATION || '' + + // namespace ignored + return containsNamespace(str, namespace) +} + +/** + * Determine if namespace is traced. + */ + +function istraced (namespace) { + if (process.traceDeprecation) { + // --trace-deprecation support + return true + } + + var str = process.env.TRACE_DEPRECATION || '' + + // namespace traced + return containsNamespace(str, namespace) +} + +/** + * Display deprecation message. + */ + +function log (message, site) { + var haslisteners = eehaslisteners(process, 'deprecation') + + // abort early if no destination + if (!haslisteners && this._ignored) { + return + } + + var caller + var callFile + var callSite + var depSite + var i = 0 + var seen = false + var stack = getStack() + var file = this._file + + if (site) { + // provided site + depSite = site + callSite = callSiteLocation(stack[1]) + callSite.name = depSite.name + file = callSite[0] + } else { + // get call site + i = 2 + depSite = callSiteLocation(stack[i]) + callSite = depSite + } + + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] + + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break + } + } + + var key = caller + ? depSite.join(':') + '__' + caller.join(':') + : undefined + + if (key !== undefined && key in this._warned) { + // already warned + return + } + + this._warned[key] = true + + // generate automatic message from call site + var msg = message + if (!msg) { + msg = callSite === depSite || !callSite.name + ? defaultMessage(depSite) + : defaultMessage(callSite) + } + + // emit deprecation if listeners exist + if (haslisteners) { + var err = DeprecationError(this._namespace, msg, stack.slice(i)) + process.emit('deprecation', err) + return + } + + // format and write message + var format = process.stderr.isTTY + ? formatColor + : formatPlain + var output = format.call(this, msg, caller, stack.slice(i)) + process.stderr.write(output + '\n', 'utf8') +} + +/** + * Get call site location as array. + */ + +function callSiteLocation (callSite) { + var file = callSite.getFileName() || '' + var line = callSite.getLineNumber() + var colm = callSite.getColumnNumber() + + if (callSite.isEval()) { + file = callSite.getEvalOrigin() + ', ' + file + } + + var site = [file, line, colm] + + site.callSite = callSite + site.name = callSite.getFunctionName() + + return site +} + +/** + * Generate a default message from the site. + */ + +function defaultMessage (site) { + var callSite = site.callSite + var funcName = site.name + + // make useful anonymous name + if (!funcName) { + funcName = '' + } + + var context = callSite.getThis() + var typeName = context && callSite.getTypeName() + + // ignore useless type name + if (typeName === 'Object') { + typeName = undefined + } + + // make useful type name + if (typeName === 'Function') { + typeName = context.name || typeName + } + + return typeName && callSite.getMethodName() + ? typeName + '.' + funcName + : funcName +} + +/** + * Format deprecation message without color. + */ + +function formatPlain (msg, caller, stack) { + var timestamp = new Date().toUTCString() + + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + stack[i].toString() + } + + return formatted + } + + if (caller) { + formatted += ' at ' + formatLocation(caller) + } + + return formatted +} + +/** + * Format deprecation message with color. + */ + +function formatColor (msg, caller, stack) { + var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan + ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow + ' \x1b[0m' + msg + '\x1b[39m' // reset + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + stack[i].toString() + '\x1b[39m' // cyan + } + + return formatted + } + + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan + } + + return formatted +} + +/** + * Format call site location. + */ + +function formatLocation (callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] +} + +/** + * Get the stack as array of call sites. + */ + +function getStack () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = Math.max(10, limit) + + // capture the stack + Error.captureStackTrace(obj) + + // slice this function off the top + var stack = obj.stack.slice(1) + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack +} + +/** + * Capture call site stack from v8. + */ + +function prepareObjectStackTrace (obj, stack) { + return stack +} + +/** + * Return a wrapped function in a deprecation message. + */ + +function wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + var args = createArgumentsString(fn.length) + var stack = getStack() + var site = callSiteLocation(stack[1]) + + site.name = fn.name + + // eslint-disable-next-line no-new-func + var deprecatedfn = new Function('fn', 'log', 'deprecate', 'message', 'site', + '"use strict"\n' + + 'return function (' + args + ') {' + + 'log.call(deprecate, message, site)\n' + + 'return fn.apply(this, arguments)\n' + + '}')(fn, log, this, message, site) + + return deprecatedfn +} + +/** + * Wrap property in a deprecation message. + */ + +function wrapproperty (obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } + + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + // set site name + site.name = prop + + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) + } + + var get = descriptor.get + var set = descriptor.set + + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter () { + log.call(deprecate, message, site) + return get.apply(this, arguments) + } + } + + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter () { + log.call(deprecate, message, site) + return set.apply(this, arguments) + } + } + + Object.defineProperty(obj, prop, descriptor) +} + +/** + * Create DeprecationError for deprecation + */ + +function DeprecationError (namespace, message, stack) { + var error = new Error() + var stackString + + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) + + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) + + Object.defineProperty(error, 'name', { + enumerable: false, + configurable: true, + value: 'DeprecationError', + writable: true + }) + + Object.defineProperty(error, 'namespace', { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }) + + Object.defineProperty(error, 'stack', { + configurable: true, + enumerable: false, + get: function () { + if (stackString !== undefined) { + return stackString + } + + // prepare stack trace + return (stackString = createStackString.call(this, stack)) + }, + set: function setter (val) { + stackString = val + } + }) + + return error +} diff --git a/node_modules/depd/lib/browser/index.js b/node_modules/depd/lib/browser/index.js new file mode 100644 index 0000000..6be45cc --- /dev/null +++ b/node_modules/depd/lib/browser/index.js @@ -0,0 +1,77 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = depd + +/** + * Create deprecate for namespace in caller. + */ + +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + function deprecate (message) { + // no-op in browser + } + + deprecate._file = undefined + deprecate._ignored = true + deprecate._namespace = namespace + deprecate._traced = false + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Return a wrapped function in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + return fn +} + +/** + * Wrap property in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapproperty (obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } +} diff --git a/node_modules/depd/package.json b/node_modules/depd/package.json new file mode 100644 index 0000000..3857e19 --- /dev/null +++ b/node_modules/depd/package.json @@ -0,0 +1,45 @@ +{ + "name": "depd", + "description": "Deprecate all the things", + "version": "2.0.0", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "deprecate", + "deprecated" + ], + "repository": "dougwilson/nodejs-depd", + "browser": "lib/browser/index.js", + "devDependencies": { + "benchmark": "2.1.4", + "beautify-benchmark": "0.2.4", + "eslint": "5.7.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.14.0", + "eslint-plugin-markdown": "1.0.0-beta.7", + "eslint-plugin-node": "7.0.1", + "eslint-plugin-promise": "4.0.1", + "eslint-plugin-standard": "4.0.0", + "istanbul": "0.4.5", + "mocha": "5.2.0", + "safe-buffer": "5.1.2", + "uid-safe": "2.1.5" + }, + "files": [ + "lib/", + "History.md", + "LICENSE", + "index.js", + "Readme.md" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail test/", + "test-ci": "istanbul cover --print=none node_modules/mocha/bin/_mocha -- --reporter spec test/ && istanbul report lcovonly text-summary", + "test-cov": "istanbul cover --print=none node_modules/mocha/bin/_mocha -- --reporter dot test/ && istanbul report lcov text-summary" + } +} diff --git a/node_modules/dunder-proto/.eslintrc b/node_modules/dunder-proto/.eslintrc new file mode 100644 index 0000000..3b5d9e9 --- /dev/null +++ b/node_modules/dunder-proto/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/node_modules/dunder-proto/.github/FUNDING.yml b/node_modules/dunder-proto/.github/FUNDING.yml new file mode 100644 index 0000000..8a1d7b0 --- /dev/null +++ b/node_modules/dunder-proto/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/dunder-proto +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/dunder-proto/.nycrc b/node_modules/dunder-proto/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/node_modules/dunder-proto/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/dunder-proto/CHANGELOG.md b/node_modules/dunder-proto/CHANGELOG.md new file mode 100644 index 0000000..9b8b2f8 --- /dev/null +++ b/node_modules/dunder-proto/CHANGELOG.md @@ -0,0 +1,24 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.1](https://github.com/es-shims/dunder-proto/compare/v1.0.0...v1.0.1) - 2024-12-16 + +### Commits + +- [Fix] do not crash when `--disable-proto=throw` [`6c367d9`](https://github.com/es-shims/dunder-proto/commit/6c367d919bc1604778689a297bbdbfea65752847) +- [Tests] ensure noproto tests only use the current version of dunder-proto [`b02365b`](https://github.com/es-shims/dunder-proto/commit/b02365b9cf889c4a2cac7be0c3cfc90a789af36c) +- [Dev Deps] update `@arethetypeswrong/cli`, `@types/tape` [`e3c5c3b`](https://github.com/es-shims/dunder-proto/commit/e3c5c3bd81cf8cef7dff2eca19e558f0e307f666) +- [Deps] update `call-bind-apply-helpers` [`19f1da0`](https://github.com/es-shims/dunder-proto/commit/19f1da028b8dd0d05c85bfd8f7eed2819b686450) + +## v1.0.0 - 2024-12-06 + +### Commits + +- Initial implementation, tests, readme, types [`a5b74b0`](https://github.com/es-shims/dunder-proto/commit/a5b74b0082f5270cb0905cd9a2e533cee7498373) +- Initial commit [`73fb5a3`](https://github.com/es-shims/dunder-proto/commit/73fb5a353b51ac2ab00c9fdeb0114daffd4c07a8) +- npm init [`80152dc`](https://github.com/es-shims/dunder-proto/commit/80152dc98155da4eb046d9f67a87ed96e8280a1d) +- Only apps should have lockfiles [`03e6660`](https://github.com/es-shims/dunder-proto/commit/03e6660a1d70dc401f3e217a031475ec537243dd) diff --git a/node_modules/dunder-proto/LICENSE b/node_modules/dunder-proto/LICENSE new file mode 100644 index 0000000..34995e7 --- /dev/null +++ b/node_modules/dunder-proto/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 ECMAScript Shims + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/dunder-proto/README.md b/node_modules/dunder-proto/README.md new file mode 100644 index 0000000..44b80a2 --- /dev/null +++ b/node_modules/dunder-proto/README.md @@ -0,0 +1,54 @@ +# dunder-proto [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +If available, the `Object.prototype.__proto__` accessor and mutator, call-bound. + +## Getting started + +```sh +npm install --save dunder-proto +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const getDunder = require('dunder-proto/get'); +const setDunder = require('dunder-proto/set'); + +const obj = {}; + +assert.equal('toString' in obj, true); +assert.equal(getDunder(obj), Object.prototype); + +setDunder(obj, null); + +assert.equal('toString' in obj, false); +assert.equal(getDunder(obj), null); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/dunder-proto +[npm-version-svg]: https://versionbadg.es/es-shims/dunder-proto.svg +[deps-svg]: https://david-dm.org/es-shims/dunder-proto.svg +[deps-url]: https://david-dm.org/es-shims/dunder-proto +[dev-deps-svg]: https://david-dm.org/es-shims/dunder-proto/dev-status.svg +[dev-deps-url]: https://david-dm.org/es-shims/dunder-proto#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/dunder-proto.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/dunder-proto.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/dunder-proto.svg +[downloads-url]: https://npm-stat.com/charts.html?package=dunder-proto +[codecov-image]: https://codecov.io/gh/es-shims/dunder-proto/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/es-shims/dunder-proto/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/es-shims/dunder-proto +[actions-url]: https://github.com/es-shims/dunder-proto/actions diff --git a/node_modules/dunder-proto/get.d.ts b/node_modules/dunder-proto/get.d.ts new file mode 100644 index 0000000..c7e14d2 --- /dev/null +++ b/node_modules/dunder-proto/get.d.ts @@ -0,0 +1,5 @@ +declare function getDunderProto(target: {}): object | null; + +declare const x: false | typeof getDunderProto; + +export = x; \ No newline at end of file diff --git a/node_modules/dunder-proto/get.js b/node_modules/dunder-proto/get.js new file mode 100644 index 0000000..45093df --- /dev/null +++ b/node_modules/dunder-proto/get.js @@ -0,0 +1,30 @@ +'use strict'; + +var callBind = require('call-bind-apply-helpers'); +var gOPD = require('gopd'); + +var hasProtoAccessor; +try { + // eslint-disable-next-line no-extra-parens, no-proto + hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ ([]).__proto__ === Array.prototype; +} catch (e) { + if (!e || typeof e !== 'object' || !('code' in e) || e.code !== 'ERR_PROTO_ACCESS') { + throw e; + } +} + +// eslint-disable-next-line no-extra-parens +var desc = !!hasProtoAccessor && gOPD && gOPD(Object.prototype, /** @type {keyof typeof Object.prototype} */ ('__proto__')); + +var $Object = Object; +var $getPrototypeOf = $Object.getPrototypeOf; + +/** @type {import('./get')} */ +module.exports = desc && typeof desc.get === 'function' + ? callBind([desc.get]) + : typeof $getPrototypeOf === 'function' + ? /** @type {import('./get')} */ function getDunder(value) { + // eslint-disable-next-line eqeqeq + return $getPrototypeOf(value == null ? value : $Object(value)); + } + : false; diff --git a/node_modules/dunder-proto/package.json b/node_modules/dunder-proto/package.json new file mode 100644 index 0000000..04a4036 --- /dev/null +++ b/node_modules/dunder-proto/package.json @@ -0,0 +1,76 @@ +{ + "name": "dunder-proto", + "version": "1.0.1", + "description": "If available, the `Object.prototype.__proto__` accessor and mutator, call-bound", + "main": false, + "exports": { + "./get": "./get.js", + "./set": "./set.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=.js,.mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>= 10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/es-shims/dunder-proto.git" + }, + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/es-shims/dunder-proto/issues" + }, + "homepage": "https://github.com/es-shims/dunder-proto#readme", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.1", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.2", + "@types/tape": "^5.7.0", + "auto-changelog": "^2.5.0", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "testling": { + "files": "test/index.js" + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/dunder-proto/set.d.ts b/node_modules/dunder-proto/set.d.ts new file mode 100644 index 0000000..16bfdfe --- /dev/null +++ b/node_modules/dunder-proto/set.d.ts @@ -0,0 +1,5 @@ +declare function setDunderProto

(target: {}, proto: P): P; + +declare const x: false | typeof setDunderProto; + +export = x; \ No newline at end of file diff --git a/node_modules/dunder-proto/set.js b/node_modules/dunder-proto/set.js new file mode 100644 index 0000000..6085b6e --- /dev/null +++ b/node_modules/dunder-proto/set.js @@ -0,0 +1,35 @@ +'use strict'; + +var callBind = require('call-bind-apply-helpers'); +var gOPD = require('gopd'); +var $TypeError = require('es-errors/type'); + +/** @type {{ __proto__?: object | null }} */ +var obj = {}; +try { + obj.__proto__ = null; // eslint-disable-line no-proto +} catch (e) { + if (!e || typeof e !== 'object' || !('code' in e) || e.code !== 'ERR_PROTO_ACCESS') { + throw e; + } +} + +var hasProtoMutator = !('toString' in obj); + +// eslint-disable-next-line no-extra-parens +var desc = gOPD && gOPD(Object.prototype, /** @type {keyof typeof Object.prototype} */ ('__proto__')); + +/** @type {import('./set')} */ +module.exports = hasProtoMutator && ( +// eslint-disable-next-line no-extra-parens + (!!desc && typeof desc.set === 'function' && /** @type {import('./set')} */ (callBind([desc.set]))) + || /** @type {import('./set')} */ function setDunder(object, proto) { + // this is node v0.10 or older, which doesn't have Object.setPrototypeOf and has undeniable __proto__ + if (object == null) { // eslint-disable-line eqeqeq + throw new $TypeError('set Object.prototype.__proto__ called on null or undefined'); + } + // eslint-disable-next-line no-proto, no-param-reassign, no-extra-parens + /** @type {{ __proto__?: object | null }} */ (object).__proto__ = proto; + return proto; + } +); diff --git a/node_modules/dunder-proto/test/get.js b/node_modules/dunder-proto/test/get.js new file mode 100644 index 0000000..253f183 --- /dev/null +++ b/node_modules/dunder-proto/test/get.js @@ -0,0 +1,34 @@ +'use strict'; + +var test = require('tape'); + +var getDunderProto = require('../get'); + +test('getDunderProto', { skip: !getDunderProto }, function (t) { + if (!getDunderProto) { + throw 'should never happen; this is just for type narrowing'; // eslint-disable-line no-throw-literal + } + + // @ts-expect-error + t['throws'](function () { getDunderProto(); }, TypeError, 'throws if no argument'); + // @ts-expect-error + t['throws'](function () { getDunderProto(undefined); }, TypeError, 'throws with undefined'); + // @ts-expect-error + t['throws'](function () { getDunderProto(null); }, TypeError, 'throws with null'); + + t.equal(getDunderProto({}), Object.prototype); + t.equal(getDunderProto([]), Array.prototype); + t.equal(getDunderProto(function () {}), Function.prototype); + t.equal(getDunderProto(/./g), RegExp.prototype); + t.equal(getDunderProto(42), Number.prototype); + t.equal(getDunderProto(true), Boolean.prototype); + t.equal(getDunderProto('foo'), String.prototype); + + t.end(); +}); + +test('no dunder proto', { skip: !!getDunderProto }, function (t) { + t.notOk('__proto__' in Object.prototype, 'no __proto__ in Object.prototype'); + + t.end(); +}); diff --git a/node_modules/dunder-proto/test/index.js b/node_modules/dunder-proto/test/index.js new file mode 100644 index 0000000..08ff36f --- /dev/null +++ b/node_modules/dunder-proto/test/index.js @@ -0,0 +1,4 @@ +'use strict'; + +require('./get'); +require('./set'); diff --git a/node_modules/dunder-proto/test/set.js b/node_modules/dunder-proto/test/set.js new file mode 100644 index 0000000..c3bfe4d --- /dev/null +++ b/node_modules/dunder-proto/test/set.js @@ -0,0 +1,50 @@ +'use strict'; + +var test = require('tape'); + +var setDunderProto = require('../set'); + +test('setDunderProto', { skip: !setDunderProto }, function (t) { + if (!setDunderProto) { + throw 'should never happen; this is just for type narrowing'; // eslint-disable-line no-throw-literal + } + + // @ts-expect-error + t['throws'](function () { setDunderProto(); }, TypeError, 'throws if no arguments'); + // @ts-expect-error + t['throws'](function () { setDunderProto(undefined); }, TypeError, 'throws with undefined and nothing'); + // @ts-expect-error + t['throws'](function () { setDunderProto(undefined, undefined); }, TypeError, 'throws with undefined and undefined'); + // @ts-expect-error + t['throws'](function () { setDunderProto(null); }, TypeError, 'throws with null and undefined'); + // @ts-expect-error + t['throws'](function () { setDunderProto(null, undefined); }, TypeError, 'throws with null and undefined'); + + /** @type {{ inherited?: boolean }} */ + var obj = {}; + t.ok('toString' in obj, 'object initially has toString'); + + setDunderProto(obj, null); + t.notOk('toString' in obj, 'object no longer has toString'); + + t.notOk('inherited' in obj, 'object lacks inherited property'); + setDunderProto(obj, { inherited: true }); + t.equal(obj.inherited, true, 'object has inherited property'); + + t.end(); +}); + +test('no dunder proto', { skip: !!setDunderProto }, function (t) { + if ('__proto__' in Object.prototype) { + t['throws']( + // @ts-expect-error + function () { ({}).__proto__ = null; }, // eslint-disable-line no-proto + Error, + 'throws when setting Object.prototype.__proto__' + ); + } else { + t.notOk('__proto__' in Object.prototype, 'no __proto__ in Object.prototype'); + } + + t.end(); +}); diff --git a/node_modules/dunder-proto/tsconfig.json b/node_modules/dunder-proto/tsconfig.json new file mode 100644 index 0000000..dabbe23 --- /dev/null +++ b/node_modules/dunder-proto/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "ES2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/ecdsa-sig-formatter/CODEOWNERS b/node_modules/ecdsa-sig-formatter/CODEOWNERS new file mode 100644 index 0000000..4451d3d --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/CODEOWNERS @@ -0,0 +1 @@ +* @omsmith diff --git a/node_modules/ecdsa-sig-formatter/LICENSE b/node_modules/ecdsa-sig-formatter/LICENSE new file mode 100644 index 0000000..8754ed6 --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2015 D2L Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/ecdsa-sig-formatter/README.md b/node_modules/ecdsa-sig-formatter/README.md new file mode 100644 index 0000000..daa95d6 --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/README.md @@ -0,0 +1,65 @@ +# ecdsa-sig-formatter + +[![Build Status](https://travis-ci.org/Brightspace/node-ecdsa-sig-formatter.svg?branch=master)](https://travis-ci.org/Brightspace/node-ecdsa-sig-formatter) [![Coverage Status](https://coveralls.io/repos/Brightspace/node-ecdsa-sig-formatter/badge.svg)](https://coveralls.io/r/Brightspace/node-ecdsa-sig-formatter) + +Translate between JOSE and ASN.1/DER encodings for ECDSA signatures + +## Install +```sh +npm install ecdsa-sig-formatter --save +``` + +## Usage +```js +var format = require('ecdsa-sig-formatter'); + +var derSignature = '..'; // asn.1/DER encoded ecdsa signature + +var joseSignature = format.derToJose(derSignature); + +``` + +### API + +--- + +#### `.derToJose(Buffer|String signature, String alg)` -> `String` + +Convert the ASN.1/DER encoded signature to a JOSE-style concatenated signature. +Returns a _base64 url_ encoded `String`. + +* If _signature_ is a `String`, it should be _base64_ encoded +* _alg_ must be one of _ES256_, _ES384_ or _ES512_ + +--- + +#### `.joseToDer(Buffer|String signature, String alg)` -> `Buffer` + +Convert the JOSE-style concatenated signature to an ASN.1/DER encoded +signature. Returns a `Buffer` + +* If _signature_ is a `String`, it should be _base64 url_ encoded +* _alg_ must be one of _ES256_, _ES384_ or _ES512_ + +## Contributing + +1. **Fork** the repository. Committing directly against this repository is + highly discouraged. + +2. Make your modifications in a branch, updating and writing new unit tests + as necessary in the `spec` directory. + +3. Ensure that all tests pass with `npm test` + +4. `rebase` your changes against master. *Do not merge*. + +5. Submit a pull request to this repository. Wait for tests to run and someone + to chime in. + +### Code Style + +This repository is configured with [EditorConfig][EditorConfig] and +[ESLint][ESLint] rules. + +[EditorConfig]: http://editorconfig.org/ +[ESLint]: http://eslint.org diff --git a/node_modules/ecdsa-sig-formatter/package.json b/node_modules/ecdsa-sig-formatter/package.json new file mode 100644 index 0000000..6fb5ebf --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/package.json @@ -0,0 +1,46 @@ +{ + "name": "ecdsa-sig-formatter", + "version": "1.0.11", + "description": "Translate ECDSA signatures between ASN.1/DER and JOSE-style concatenation", + "main": "src/ecdsa-sig-formatter.js", + "scripts": { + "check-style": "eslint .", + "pretest": "npm run check-style", + "test": "istanbul cover --root src _mocha -- spec", + "report-cov": "cat ./coverage/lcov.info | coveralls" + }, + "typings": "./src/ecdsa-sig-formatter.d.ts", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/Brightspace/node-ecdsa-sig-formatter.git" + }, + "keywords": [ + "ecdsa", + "der", + "asn.1", + "jwt", + "jwa", + "jsonwebtoken", + "jose" + ], + "author": "D2L Corporation", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/Brightspace/node-ecdsa-sig-formatter/issues" + }, + "homepage": "https://github.com/Brightspace/node-ecdsa-sig-formatter#readme", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "devDependencies": { + "bench": "^0.3.6", + "chai": "^3.5.0", + "coveralls": "^2.11.9", + "eslint": "^2.12.0", + "eslint-config-brightspace": "^0.2.1", + "istanbul": "^0.4.3", + "jwk-to-pem": "^1.2.5", + "mocha": "^2.5.3", + "native-crypto": "^1.7.0" + } +} diff --git a/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.d.ts b/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.d.ts new file mode 100644 index 0000000..9693aa0 --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.d.ts @@ -0,0 +1,17 @@ +/// + +declare module "ecdsa-sig-formatter" { + /** + * Convert the ASN.1/DER encoded signature to a JOSE-style concatenated signature. Returns a base64 url encoded String. + * If signature is a String, it should be base64 encoded + * alg must be one of ES256, ES384 or ES512 + */ + export function derToJose(signature: Buffer | string, alg: string): string; + + /** + * Convert the JOSE-style concatenated signature to an ASN.1/DER encoded signature. Returns a Buffer + * If signature is a String, it should be base64 url encoded + * alg must be one of ES256, ES384 or ES512 + */ + export function joseToDer(signature: Buffer | string, alg: string): Buffer +} diff --git a/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js b/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js new file mode 100644 index 0000000..38eeb9b --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js @@ -0,0 +1,187 @@ +'use strict'; + +var Buffer = require('safe-buffer').Buffer; + +var getParamBytesForAlg = require('./param-bytes-for-alg'); + +var MAX_OCTET = 0x80, + CLASS_UNIVERSAL = 0, + PRIMITIVE_BIT = 0x20, + TAG_SEQ = 0x10, + TAG_INT = 0x02, + ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6), + ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6); + +function base64Url(base64) { + return base64 + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} + +function signatureAsBuffer(signature) { + if (Buffer.isBuffer(signature)) { + return signature; + } else if ('string' === typeof signature) { + return Buffer.from(signature, 'base64'); + } + + throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); +} + +function derToJose(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); + + // the DER encoded param should at most be the param size, plus a padding + // zero, since due to being a signed integer + var maxEncodedParamLength = paramBytes + 1; + + var inputLength = signature.length; + + var offset = 0; + if (signature[offset++] !== ENCODED_TAG_SEQ) { + throw new Error('Could not find expected "seq"'); + } + + var seqLength = signature[offset++]; + if (seqLength === (MAX_OCTET | 1)) { + seqLength = signature[offset++]; + } + + if (inputLength - offset < seqLength) { + throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); + } + + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "r"'); + } + + var rLength = signature[offset++]; + + if (inputLength - offset - 2 < rLength) { + throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); + } + + if (maxEncodedParamLength < rLength) { + throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } + + var rOffset = offset; + offset += rLength; + + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "s"'); + } + + var sLength = signature[offset++]; + + if (inputLength - offset !== sLength) { + throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); + } + + if (maxEncodedParamLength < sLength) { + throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } + + var sOffset = offset; + offset += sLength; + + if (offset !== inputLength) { + throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); + } + + var rPadding = paramBytes - rLength, + sPadding = paramBytes - sLength; + + var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); + + for (offset = 0; offset < rPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); + + offset = paramBytes; + + for (var o = offset; offset < o + sPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); + + dst = dst.toString('base64'); + dst = base64Url(dst); + + return dst; +} + +function countPadding(buf, start, stop) { + var padding = 0; + while (start + padding < stop && buf[start + padding] === 0) { + ++padding; + } + + var needsSign = buf[start + padding] >= MAX_OCTET; + if (needsSign) { + --padding; + } + + return padding; +} + +function joseToDer(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); + + var signatureBytes = signature.length; + if (signatureBytes !== paramBytes * 2) { + throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); + } + + var rPadding = countPadding(signature, 0, paramBytes); + var sPadding = countPadding(signature, paramBytes, signature.length); + var rLength = paramBytes - rPadding; + var sLength = paramBytes - sPadding; + + var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; + + var shortLength = rsBytes < MAX_OCTET; + + var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); + + var offset = 0; + dst[offset++] = ENCODED_TAG_SEQ; + if (shortLength) { + // Bit 8 has value "0" + // bits 7-1 give the length. + dst[offset++] = rsBytes; + } else { + // Bit 8 of first octet has value "1" + // bits 7-1 give the number of additional length octets. + dst[offset++] = MAX_OCTET | 1; + // length, base 256 + dst[offset++] = rsBytes & 0xff; + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = rLength; + if (rPadding < 0) { + dst[offset++] = 0; + offset += signature.copy(dst, offset, 0, paramBytes); + } else { + offset += signature.copy(dst, offset, rPadding, paramBytes); + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = sLength; + if (sPadding < 0) { + dst[offset++] = 0; + signature.copy(dst, offset, paramBytes); + } else { + signature.copy(dst, offset, paramBytes + sPadding); + } + + return dst; +} + +module.exports = { + derToJose: derToJose, + joseToDer: joseToDer +}; diff --git a/node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js b/node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js new file mode 100644 index 0000000..9fe67ac --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js @@ -0,0 +1,23 @@ +'use strict'; + +function getParamSize(keySize) { + var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); + return result; +} + +var paramBytesForAlg = { + ES256: getParamSize(256), + ES384: getParamSize(384), + ES512: getParamSize(521) +}; + +function getParamBytesForAlg(alg) { + var paramBytes = paramBytesForAlg[alg]; + if (paramBytes) { + return paramBytes; + } + + throw new Error('Unknown algorithm "' + alg + '"'); +} + +module.exports = getParamBytesForAlg; diff --git a/node_modules/ee-first/LICENSE b/node_modules/ee-first/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/node_modules/ee-first/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/ee-first/README.md b/node_modules/ee-first/README.md new file mode 100644 index 0000000..cbd2478 --- /dev/null +++ b/node_modules/ee-first/README.md @@ -0,0 +1,80 @@ +# EE First + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![Gittip][gittip-image]][gittip-url] + +Get the first event in a set of event emitters and event pairs, +then clean up after itself. + +## Install + +```sh +$ npm install ee-first +``` + +## API + +```js +var first = require('ee-first') +``` + +### first(arr, listener) + +Invoke `listener` on the first event from the list specified in `arr`. `arr` is +an array of arrays, with each array in the format `[ee, ...event]`. `listener` +will be called only once, the first time any of the given events are emitted. If +`error` is one of the listened events, then if that fires first, the `listener` +will be given the `err` argument. + +The `listener` is invoked as `listener(err, ee, event, args)`, where `err` is the +first argument emitted from an `error` event, if applicable; `ee` is the event +emitter that fired; `event` is the string event name that fired; and `args` is an +array of the arguments that were emitted on the event. + +```js +var ee1 = new EventEmitter() +var ee2 = new EventEmitter() + +first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) +``` + +#### .cancel() + +The group of listeners can be cancelled before being invoked and have all the event +listeners removed from the underlying event emitters. + +```js +var thunk = first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) + +// cancel and clean up +thunk.cancel() +``` + +[npm-image]: https://img.shields.io/npm/v/ee-first.svg?style=flat-square +[npm-url]: https://npmjs.org/package/ee-first +[github-tag]: http://img.shields.io/github/tag/jonathanong/ee-first.svg?style=flat-square +[github-url]: https://github.com/jonathanong/ee-first/tags +[travis-image]: https://img.shields.io/travis/jonathanong/ee-first.svg?style=flat-square +[travis-url]: https://travis-ci.org/jonathanong/ee-first +[coveralls-image]: https://img.shields.io/coveralls/jonathanong/ee-first.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/jonathanong/ee-first?branch=master +[license-image]: http://img.shields.io/npm/l/ee-first.svg?style=flat-square +[license-url]: LICENSE.md +[downloads-image]: http://img.shields.io/npm/dm/ee-first.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/ee-first +[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square +[gittip-url]: https://www.gittip.com/jonathanong/ diff --git a/node_modules/ee-first/index.js b/node_modules/ee-first/index.js new file mode 100644 index 0000000..501287c --- /dev/null +++ b/node_modules/ee-first/index.js @@ -0,0 +1,95 @@ +/*! + * ee-first + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = first + +/** + * Get the first event in a set of event emitters and event pairs. + * + * @param {array} stuff + * @param {function} done + * @public + */ + +function first(stuff, done) { + if (!Array.isArray(stuff)) + throw new TypeError('arg must be an array of [ee, events...] arrays') + + var cleanups = [] + + for (var i = 0; i < stuff.length; i++) { + var arr = stuff[i] + + if (!Array.isArray(arr) || arr.length < 2) + throw new TypeError('each array member must be [ee, events...]') + + var ee = arr[0] + + for (var j = 1; j < arr.length; j++) { + var event = arr[j] + var fn = listener(event, callback) + + // listen to the event + ee.on(event, fn) + // push this listener to the list of cleanups + cleanups.push({ + ee: ee, + event: event, + fn: fn, + }) + } + } + + function callback() { + cleanup() + done.apply(null, arguments) + } + + function cleanup() { + var x + for (var i = 0; i < cleanups.length; i++) { + x = cleanups[i] + x.ee.removeListener(x.event, x.fn) + } + } + + function thunk(fn) { + done = fn + } + + thunk.cancel = cleanup + + return thunk +} + +/** + * Create the event listener. + * @private + */ + +function listener(event, done) { + return function onevent(arg1) { + var args = new Array(arguments.length) + var ee = this + var err = event === 'error' + ? arg1 + : null + + // copy args to prevent arguments escaping scope + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + done(err, ee, event, args) + } +} diff --git a/node_modules/ee-first/package.json b/node_modules/ee-first/package.json new file mode 100644 index 0000000..b6d0b7d --- /dev/null +++ b/node_modules/ee-first/package.json @@ -0,0 +1,29 @@ +{ + "name": "ee-first", + "description": "return the first event in a set of ee/event pairs", + "version": "1.1.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com", + "twitter": "https://twitter.com/jongleberry" + }, + "contributors": [ + "Douglas Christopher Wilson " + ], + "license": "MIT", + "repository": "jonathanong/ee-first", + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "2.2.5" + }, + "files": [ + "index.js", + "LICENSE" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/node_modules/ejs/LICENSE b/node_modules/ejs/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/ejs/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/ejs/README.md b/node_modules/ejs/README.md new file mode 100644 index 0000000..6daf40c --- /dev/null +++ b/node_modules/ejs/README.md @@ -0,0 +1,358 @@ +Embedded JavaScript templates
+[![Known Vulnerabilities](https://snyk.io/test/npm/ejs/badge.svg?style=flat)](https://snyk.io/test/npm/ejs) +============================= + +## Security + +Security professionals, before reporting any security issues, please reference the +SECURITY.md +in this project, in particular, the following: "EJS is effectively a JavaScript runtime. +Its entire job is to execute JavaScript. If you run the EJS render method without +checking the inputs yourself, you are responsible for the results." + +In short, DO NOT submit 'vulnerabilities' that include this snippet of code: + +```javascript +app.get('/', (req, res) => { + res.render('index', req.query); +}); +``` + +## Installation + +```bash +$ npm install ejs +``` + +## Features + + * Control flow with `<% %>` + * Escaped output with `<%= %>` (escape function configurable) + * Unescaped raw output with `<%- %>` + * Newline-trim mode ('newline slurping') with `-%>` ending tag + * Whitespace-trim mode (slurp all whitespace) for control flow with `<%_ _%>` + * Custom delimiters (e.g. `[? ?]` instead of `<% %>`) + * Includes + * Client-side support + * Static caching of intermediate JavaScript + * Static caching of templates + * Complies with the [Express](http://expressjs.com) view system + +## Example + +```ejs +<% if (user) { %> +

<%= user.name %>

+<% } %> +``` + +Try EJS online at: https://ionicabizau.github.io/ejs-playground/. + +## Basic usage + +```javascript +let template = ejs.compile(str, options); +template(data); +// => Rendered HTML string + +ejs.render(str, data, options); +// => Rendered HTML string + +ejs.renderFile(filename, data, options, function(err, str){ + // str => Rendered HTML string +}); +``` + +It is also possible to use `ejs.render(dataAndOptions);` where you pass +everything in a single object. In that case, you'll end up with local variables +for all the passed options. However, be aware that your code could break if we +add an option with the same name as one of your data object's properties. +Therefore, we do not recommend using this shortcut. + +### Important +You should never give end-users unfettered access to the EJS render method, If you do so you are using EJS in an inherently un-secure way. + +### Options + + - `cache` Compiled functions are cached, requires `filename` + - `filename` The name of the file being rendered. Not required if you + are using `renderFile()`. Used by `cache` to key caches, and for includes. + - `root` Set template root(s) for includes with an absolute path (e.g, /file.ejs). + Can be array to try to resolve include from multiple directories. + - `views` An array of paths to use when resolving includes with relative paths. + - `context` Function execution context + - `compileDebug` When `false` no debug instrumentation is compiled + - `client` When `true`, compiles a function that can be rendered + in the browser without needing to load the EJS Runtime + ([ejs.min.js](https://github.com/mde/ejs/releases/latest)). + - `delimiter` Character to use for inner delimiter, by default '%' + - `openDelimiter` Character to use for opening delimiter, by default '<' + - `closeDelimiter` Character to use for closing delimiter, by default '>' + - `debug` Outputs generated function body + - `strict` When set to `true`, generated function is in strict mode + - `_with` Whether or not to use `with() {}` constructs. If `false` + then the locals will be stored in the `locals` object. Set to `false` in strict mode. + - `destructuredLocals` An array of local variables that are always destructured from + the locals object, available even in strict mode. + - `localsName` Name to use for the object storing local variables when not using + `with` Defaults to `locals` + - `rmWhitespace` Remove all safe-to-remove whitespace, including leading + and trailing whitespace. It also enables a safer version of `-%>` line + slurping for all scriptlet tags (it does not strip new lines of tags in + the middle of a line). + - `escape` The escaping function used with `<%=` construct. It is + used in rendering and is `.toString()`ed in the generation of client functions. + (By default escapes XML). + - `outputFunctionName` Set to a string (e.g., 'echo' or 'print') for a function to print + output inside scriptlet tags. + - `async` When `true`, EJS will use an async function for rendering. (Depends + on async/await support in the JS runtime. + - `includer` Custom function to handle EJS includes, receives `(originalPath, parsedPath)` + parameters, where `originalPath` is the path in include as-is and `parsedPath` is the + previously resolved path. Should return an object `{ filename, template }`, + you may return only one of the properties, where `filename` is the final parsed path and `template` + is the included content. + +This project uses [JSDoc](http://usejsdoc.org/). For the full public API +documentation, clone the repository and run `jake doc`. This will run JSDoc +with the proper options and output the documentation to `out/`. If you want +the both the public & private API docs, run `jake devdoc` instead. + +### Tags + + - `<%` 'Scriptlet' tag, for control-flow, no output + - `<%_` 'Whitespace Slurping' Scriptlet tag, strips all whitespace before it + - `<%=` Outputs the value into the template (escaped) + - `<%-` Outputs the unescaped value into the template + - `<%#` Comment tag, no execution, no output + - `<%%` Outputs a literal '<%' + - `%%>` Outputs a literal '%>' + - `%>` Plain ending tag + - `-%>` Trim-mode ('newline slurp') tag, trims following newline + - `_%>` 'Whitespace Slurping' ending tag, removes all whitespace after it + +For the full syntax documentation, please see [docs/syntax.md](https://github.com/mde/ejs/blob/master/docs/syntax.md). + +### Includes + +Includes either have to be an absolute path, or, if not, are assumed as +relative to the template with the `include` call. For example if you are +including `./views/user/show.ejs` from `./views/users.ejs` you would +use `<%- include('user/show') %>`. + +You must specify the `filename` option for the template with the `include` +call unless you are using `renderFile()`. + +You'll likely want to use the raw output tag (`<%-`) with your include to avoid +double-escaping the HTML output. + +```ejs +
    + <% users.forEach(function(user){ %> + <%- include('user/show', {user: user}) %> + <% }); %> +
+``` + +Includes are inserted at runtime, so you can use variables for the path in the +`include` call (for example `<%- include(somePath) %>`). Variables in your +top-level data object are available to all your includes, but local variables +need to be passed down. + +NOTE: Include preprocessor directives (`<% include user/show %>`) are +not supported in v3.0+. + +## Custom delimiters + +Custom delimiters can be applied on a per-template basis, or globally: + +```javascript +let ejs = require('ejs'), + users = ['geddy', 'neil', 'alex']; + +// Just one template +ejs.render('

[?= users.join(" | "); ?]

', {users: users}, {delimiter: '?', openDelimiter: '[', closeDelimiter: ']'}); +// => '

geddy | neil | alex

' + +// Or globally +ejs.delimiter = '?'; +ejs.openDelimiter = '['; +ejs.closeDelimiter = ']'; +ejs.render('

[?= users.join(" | "); ?]

', {users: users}); +// => '

geddy | neil | alex

' +``` + +### Caching + +EJS ships with a basic in-process cache for caching the intermediate JavaScript +functions used to render templates. It's easy to plug in LRU caching using +Node's `lru-cache` library: + +```javascript +let ejs = require('ejs'), + LRU = require('lru-cache'); +ejs.cache = LRU(100); // LRU cache with 100-item limit +``` + +If you want to clear the EJS cache, call `ejs.clearCache`. If you're using the +LRU cache and need a different limit, simple reset `ejs.cache` to a new instance +of the LRU. + +### Custom file loader + +The default file loader is `fs.readFileSync`, if you want to customize it, you can set ejs.fileLoader. + +```javascript +let ejs = require('ejs'); +let myFileLoad = function (filePath) { + return 'myFileLoad: ' + fs.readFileSync(filePath); +}; + +ejs.fileLoader = myFileLoad; +``` + +With this feature, you can preprocess the template before reading it. + +### Layouts + +EJS does not specifically support blocks, but layouts can be implemented by +including headers and footers, like so: + + +```ejs +<%- include('header') -%> +

+ Title +

+

+ My page +

+<%- include('footer') -%> +``` + +## Client-side support + +Go to the [Latest Release](https://github.com/mde/ejs/releases/latest), download +`./ejs.js` or `./ejs.min.js`. Alternately, you can compile it yourself by cloning +the repository and running `jake build` (or `$(npm bin)/jake build` if jake is +not installed globally). + +Include one of these files on your page, and `ejs` should be available globally. + +### Example + +```html +
+ + +``` + +### Caveats + +Most of EJS will work as expected; however, there are a few things to note: + +1. Obviously, since you do not have access to the filesystem, `ejs.renderFile()` won't work. +2. For the same reason, `include`s do not work unless you use an `include callback`. Here is an example: + ```javascript + let str = "Hello <%= include('file', {person: 'John'}); %>", + fn = ejs.compile(str, {client: true}); + + fn(data, null, function(path, d){ // include callback + // path -> 'file' + // d -> {person: 'John'} + // Put your code here + // Return the contents of file as a string + }); // returns rendered string + ``` + +See the [examples folder](https://github.com/mde/ejs/tree/master/examples) for more details. + +## CLI + +EJS ships with a full-featured CLI. Options are similar to those used in JavaScript code: + + - `-o / --output-file FILE` Write the rendered output to FILE rather than stdout. + - `-f / --data-file FILE` Must be JSON-formatted. Use parsed input from FILE as data for rendering. + - `-i / --data-input STRING` Must be JSON-formatted and URI-encoded. Use parsed input from STRING as data for rendering. + - `-m / --delimiter CHARACTER` Use CHARACTER with angle brackets for open/close (defaults to %). + - `-p / --open-delimiter CHARACTER` Use CHARACTER instead of left angle bracket to open. + - `-c / --close-delimiter CHARACTER` Use CHARACTER instead of right angle bracket to close. + - `-s / --strict` When set to `true`, generated function is in strict mode + - `-n / --no-with` Use 'locals' object for vars rather than using `with` (implies --strict). + - `-l / --locals-name` Name to use for the object storing local variables when not using `with`. + - `-w / --rm-whitespace` Remove all safe-to-remove whitespace, including leading and trailing whitespace. + - `-d / --debug` Outputs generated function body + - `-h / --help` Display this help message. + - `-V/v / --version` Display the EJS version. + +Here are some examples of usage: + +```shell +$ ejs -p [ -c ] ./template_file.ejs -o ./output.html +$ ejs ./test/fixtures/user.ejs name=Lerxst +$ ejs -n -l _ ./some_template.ejs -f ./data_file.json +``` + +### Data input + +There is a variety of ways to pass the CLI data for rendering. + +Stdin: + +```shell +$ ./test/fixtures/user_data.json | ejs ./test/fixtures/user.ejs +$ ejs ./test/fixtures/user.ejs < test/fixtures/user_data.json +``` + +A data file: + +```shell +$ ejs ./test/fixtures/user.ejs -f ./user_data.json +``` + +A command-line option (must be URI-encoded): + +```shell +./bin/cli.js -i %7B%22name%22%3A%20%22foo%22%7D ./test/fixtures/user.ejs +``` + +Or, passing values directly at the end of the invocation: + +```shell +./bin/cli.js -m $ ./test/fixtures/user.ejs name=foo +``` + +### Output + +The CLI by default send output to stdout, but you can use the `-o` or `--output-file` +flag to specify a target file to send the output to. + +## IDE Integration with Syntax Highlighting + +VSCode:Javascript EJS by *DigitalBrainstem* + +## Related projects + +There are a number of implementations of EJS: + + * TJ's implementation, the v1 of this library: https://github.com/tj/ejs + * EJS Embedded JavaScript Framework on Google Code: https://code.google.com/p/embeddedjavascript/ + * Sam Stephenson's Ruby implementation: https://rubygems.org/gems/ejs + * Erubis, an ERB implementation which also runs JavaScript: http://www.kuwata-lab.com/erubis/users-guide.04.html#lang-javascript + * DigitalBrainstem EJS Language support: https://github.com/Digitalbrainstem/ejs-grammar + +## License + +Licensed under the Apache License, Version 2.0 +() + +- - - +EJS Embedded JavaScript templates copyright 2112 +mde@fleegix.org. diff --git a/node_modules/ejs/bin/cli.js b/node_modules/ejs/bin/cli.js new file mode 100755 index 0000000..cb11aa4 --- /dev/null +++ b/node_modules/ejs/bin/cli.js @@ -0,0 +1,211 @@ +#!/usr/bin/env node +/* + * EJS Embedded JavaScript templates + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +let path = require('path'); + +let program = require('jake').program; +delete global.jake; // NO NOT WANT +program.setTaskNames = function (n) { this.taskNames = n; }; + +let ejs = require('../lib/ejs'); +let { hyphenToCamel } = require('../lib/utils'); +let fs = require('fs'); +let args = process.argv.slice(2); +let usage = fs.readFileSync(`${__dirname}/../usage.txt`).toString(); + +const CLI_OPTS = [ + { full: 'output-file', + abbr: 'o', + expectValue: true, + }, + { full: 'data-file', + abbr: 'f', + expectValue: true, + }, + { full: 'data-input', + abbr: 'i', + expectValue: true, + }, + { full: 'delimiter', + abbr: 'm', + expectValue: true, + passThrough: true, + }, + { full: 'open-delimiter', + abbr: 'p', + expectValue: true, + passThrough: true, + }, + { full: 'close-delimiter', + abbr: 'c', + expectValue: true, + passThrough: true, + }, + { full: 'strict', + abbr: 's', + expectValue: false, + allowValue: false, + passThrough: true, + }, + { full: 'no-with', + abbr: 'n', + expectValue: false, + allowValue: false, + }, + { full: 'locals-name', + abbr: 'l', + expectValue: true, + passThrough: true, + }, + { full: 'rm-whitespace', + abbr: 'w', + expectValue: false, + allowValue: false, + passThrough: true, + }, + { full: 'debug', + abbr: 'd', + expectValue: false, + allowValue: false, + passThrough: true, + }, + { full: 'help', + abbr: 'h', + passThrough: true, + }, + { full: 'version', + abbr: 'V', + passThrough: true, + }, + // Alias lowercase v + { full: 'version', + abbr: 'v', + passThrough: true, + }, +]; + +let preempts = { + version: function () { + program.die(ejs.VERSION); + }, + help: function () { + program.die(usage); + } +}; + +let stdin = ''; +process.stdin.setEncoding('utf8'); +process.stdin.on('readable', () => { + let chunk; + while ((chunk = process.stdin.read()) !== null) { + stdin += chunk; + } +}); + +function run() { + + program.availableOpts = CLI_OPTS; + program.parseArgs(args); + + let templatePath = program.taskNames[0]; + let pVals = program.envVars; + let pOpts = {}; + + for (let p in program.opts) { + let name = hyphenToCamel(p); + pOpts[name] = program.opts[p]; + } + + let opts = {}; + let vals = {}; + + // Same-named 'passthrough' opts + CLI_OPTS.forEach((opt) => { + let optName = hyphenToCamel(opt.full); + if (opt.passThrough && typeof pOpts[optName] != 'undefined') { + opts[optName] = pOpts[optName]; + } + }); + + // Bail out for help/version + for (let p in opts) { + if (preempts[p]) { + return preempts[p](); + } + } + + // Ensure there's a template to render + if (!templatePath) { + throw new Error('Please provide a template path. (Run ejs -h for help)'); + } + + if (opts.strict) { + pOpts.noWith = true; + } + if (pOpts.noWith) { + opts._with = false; + } + + // Grab and parse any input data, in order of precedence: + // 1. Stdin + // 2. CLI arg via -i + // 3. Data file via -f + // Any individual vals passed at the end (e.g., foo=bar) will override + // any vals previously set + let input; + let err = new Error('Please do not pass data multiple ways. Pick one of stdin, -f, or -i.'); + if (stdin) { + input = stdin; + } + else if (pOpts.dataInput) { + if (input) { + throw err; + } + input = decodeURIComponent(pOpts.dataInput); + } + else if (pOpts.dataFile) { + if (input) { + throw err; + } + input = fs.readFileSync(pOpts.dataFile).toString(); + } + + if (input) { + vals = JSON.parse(input); + } + + // Override / set any individual values passed from the command line + for (let p in pVals) { + vals[p] = pVals[p]; + } + + opts.filename = path.resolve(process.cwd(), templatePath); + let template = fs.readFileSync(opts.filename).toString(); + let output = ejs.render(template, vals, opts); + if (pOpts.outputFile) { + fs.writeFileSync(pOpts.outputFile, output); + } + else { + process.stdout.write(output); + } + process.exit(); +} + +// Defer execution so that stdin can be read if necessary +setImmediate(run); diff --git a/node_modules/ejs/ejs.js b/node_modules/ejs/ejs.js new file mode 100644 index 0000000..2cbeb57 --- /dev/null +++ b/node_modules/ejs/ejs.js @@ -0,0 +1,1746 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.ejs = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i + * @author Tiancheng "Timothy" Gu + * @project EJS + * @license {@link http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0} + */ + +/** + * EJS internal functions. + * + * Technically this "module" lies in the same file as {@link module:ejs}, for + * the sake of organization all the private functions re grouped into this + * module. + * + * @module ejs-internal + * @private + */ + +/** + * Embedded JavaScript templating engine. + * + * @module ejs + * @public + */ + + +var fs = require('fs'); +var path = require('path'); +var utils = require('./utils'); + +var scopeOptionWarned = false; +/** @type {string} */ +var _VERSION_STRING = require('../package.json').version; +var _DEFAULT_OPEN_DELIMITER = '<'; +var _DEFAULT_CLOSE_DELIMITER = '>'; +var _DEFAULT_DELIMITER = '%'; +var _DEFAULT_LOCALS_NAME = 'locals'; +var _NAME = 'ejs'; +var _REGEX_STRING = '(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)'; +var _OPTS_PASSABLE_WITH_DATA = ['delimiter', 'scope', 'context', 'debug', 'compileDebug', + 'client', '_with', 'rmWhitespace', 'strict', 'filename', 'async']; +// We don't allow 'cache' option to be passed in the data obj for +// the normal `render` call, but this is where Express 2 & 3 put it +// so we make an exception for `renderFile` +var _OPTS_PASSABLE_WITH_DATA_EXPRESS = _OPTS_PASSABLE_WITH_DATA.concat('cache'); +var _BOM = /^\uFEFF/; +var _JS_IDENTIFIER = /^[a-zA-Z_$][0-9a-zA-Z_$]*$/; + +/** + * EJS template function cache. This can be a LRU object from lru-cache NPM + * module. By default, it is {@link module:utils.cache}, a simple in-process + * cache that grows continuously. + * + * @type {Cache} + */ + +exports.cache = utils.cache; + +/** + * Custom file loader. Useful for template preprocessing or restricting access + * to a certain part of the filesystem. + * + * @type {fileLoader} + */ + +exports.fileLoader = fs.readFileSync; + +/** + * Name of the object containing the locals. + * + * This variable is overridden by {@link Options}`.localsName` if it is not + * `undefined`. + * + * @type {String} + * @public + */ + +exports.localsName = _DEFAULT_LOCALS_NAME; + +/** + * Promise implementation -- defaults to the native implementation if available + * This is mostly just for testability + * + * @type {PromiseConstructorLike} + * @public + */ + +exports.promiseImpl = (new Function('return this;'))().Promise; + +/** + * Get the path to the included file from the parent file path and the + * specified path. + * + * @param {String} name specified path + * @param {String} filename parent file path + * @param {Boolean} [isDir=false] whether the parent file path is a directory + * @return {String} + */ +exports.resolveInclude = function(name, filename, isDir) { + var dirname = path.dirname; + var extname = path.extname; + var resolve = path.resolve; + var includePath = resolve(isDir ? filename : dirname(filename), name); + var ext = extname(name); + if (!ext) { + includePath += '.ejs'; + } + return includePath; +}; + +/** + * Try to resolve file path on multiple directories + * + * @param {String} name specified path + * @param {Array} paths list of possible parent directory paths + * @return {String} + */ +function resolvePaths(name, paths) { + var filePath; + if (paths.some(function (v) { + filePath = exports.resolveInclude(name, v, true); + return fs.existsSync(filePath); + })) { + return filePath; + } +} + +/** + * Get the path to the included file by Options + * + * @param {String} path specified path + * @param {Options} options compilation options + * @return {String} + */ +function getIncludePath(path, options) { + var includePath; + var filePath; + var views = options.views; + var match = /^[A-Za-z]+:\\|^\//.exec(path); + + // Abs path + if (match && match.length) { + path = path.replace(/^\/*/, ''); + if (Array.isArray(options.root)) { + includePath = resolvePaths(path, options.root); + } else { + includePath = exports.resolveInclude(path, options.root || '/', true); + } + } + // Relative paths + else { + // Look relative to a passed filename first + if (options.filename) { + filePath = exports.resolveInclude(path, options.filename); + if (fs.existsSync(filePath)) { + includePath = filePath; + } + } + // Then look in any views directories + if (!includePath && Array.isArray(views)) { + includePath = resolvePaths(path, views); + } + if (!includePath && typeof options.includer !== 'function') { + throw new Error('Could not find the include file "' + + options.escapeFunction(path) + '"'); + } + } + return includePath; +} + +/** + * Get the template from a string or a file, either compiled on-the-fly or + * read from cache (if enabled), and cache the template if needed. + * + * If `template` is not set, the file specified in `options.filename` will be + * read. + * + * If `options.cache` is true, this function reads the file from + * `options.filename` so it must be set prior to calling this function. + * + * @memberof module:ejs-internal + * @param {Options} options compilation options + * @param {String} [template] template source + * @return {(TemplateFunction|ClientFunction)} + * Depending on the value of `options.client`, either type might be returned. + * @static + */ + +function handleCache(options, template) { + var func; + var filename = options.filename; + var hasTemplate = arguments.length > 1; + + if (options.cache) { + if (!filename) { + throw new Error('cache option requires a filename'); + } + func = exports.cache.get(filename); + if (func) { + return func; + } + if (!hasTemplate) { + template = fileLoader(filename).toString().replace(_BOM, ''); + } + } + else if (!hasTemplate) { + // istanbul ignore if: should not happen at all + if (!filename) { + throw new Error('Internal EJS error: no file name or template ' + + 'provided'); + } + template = fileLoader(filename).toString().replace(_BOM, ''); + } + func = exports.compile(template, options); + if (options.cache) { + exports.cache.set(filename, func); + } + return func; +} + +/** + * Try calling handleCache with the given options and data and call the + * callback with the result. If an error occurs, call the callback with + * the error. Used by renderFile(). + * + * @memberof module:ejs-internal + * @param {Options} options compilation options + * @param {Object} data template data + * @param {RenderFileCallback} cb callback + * @static + */ + +function tryHandleCache(options, data, cb) { + var result; + if (!cb) { + if (typeof exports.promiseImpl == 'function') { + return new exports.promiseImpl(function (resolve, reject) { + try { + result = handleCache(options)(data); + resolve(result); + } + catch (err) { + reject(err); + } + }); + } + else { + throw new Error('Please provide a callback function'); + } + } + else { + try { + result = handleCache(options)(data); + } + catch (err) { + return cb(err); + } + + cb(null, result); + } +} + +/** + * fileLoader is independent + * + * @param {String} filePath ejs file path. + * @return {String} The contents of the specified file. + * @static + */ + +function fileLoader(filePath){ + return exports.fileLoader(filePath); +} + +/** + * Get the template function. + * + * If `options.cache` is `true`, then the template is cached. + * + * @memberof module:ejs-internal + * @param {String} path path for the specified file + * @param {Options} options compilation options + * @return {(TemplateFunction|ClientFunction)} + * Depending on the value of `options.client`, either type might be returned + * @static + */ + +function includeFile(path, options) { + var opts = utils.shallowCopy(utils.createNullProtoObjWherePossible(), options); + opts.filename = getIncludePath(path, opts); + if (typeof options.includer === 'function') { + var includerResult = options.includer(path, opts.filename); + if (includerResult) { + if (includerResult.filename) { + opts.filename = includerResult.filename; + } + if (includerResult.template) { + return handleCache(opts, includerResult.template); + } + } + } + return handleCache(opts); +} + +/** + * Re-throw the given `err` in context to the `str` of ejs, `filename`, and + * `lineno`. + * + * @implements {RethrowCallback} + * @memberof module:ejs-internal + * @param {Error} err Error object + * @param {String} str EJS source + * @param {String} flnm file name of the EJS file + * @param {Number} lineno line number of the error + * @param {EscapeCallback} esc + * @static + */ + +function rethrow(err, str, flnm, lineno, esc) { + var lines = str.split('\n'); + var start = Math.max(lineno - 3, 0); + var end = Math.min(lines.length, lineno + 3); + var filename = esc(flnm); + // Error context + var context = lines.slice(start, end).map(function (line, i){ + var curr = i + start + 1; + return (curr == lineno ? ' >> ' : ' ') + + curr + + '| ' + + line; + }).join('\n'); + + // Alter exception message + err.path = filename; + err.message = (filename || 'ejs') + ':' + + lineno + '\n' + + context + '\n\n' + + err.message; + + throw err; +} + +function stripSemi(str){ + return str.replace(/;(\s*$)/, '$1'); +} + +/** + * Compile the given `str` of ejs into a template function. + * + * @param {String} template EJS template + * + * @param {Options} [opts] compilation options + * + * @return {(TemplateFunction|ClientFunction)} + * Depending on the value of `opts.client`, either type might be returned. + * Note that the return type of the function also depends on the value of `opts.async`. + * @public + */ + +exports.compile = function compile(template, opts) { + var templ; + + // v1 compat + // 'scope' is 'context' + // FIXME: Remove this in a future version + if (opts && opts.scope) { + if (!scopeOptionWarned){ + console.warn('`scope` option is deprecated and will be removed in EJS 3'); + scopeOptionWarned = true; + } + if (!opts.context) { + opts.context = opts.scope; + } + delete opts.scope; + } + templ = new Template(template, opts); + return templ.compile(); +}; + +/** + * Render the given `template` of ejs. + * + * If you would like to include options but not data, you need to explicitly + * call this function with `data` being an empty object or `null`. + * + * @param {String} template EJS template + * @param {Object} [data={}] template data + * @param {Options} [opts={}] compilation and rendering options + * @return {(String|Promise)} + * Return value type depends on `opts.async`. + * @public + */ + +exports.render = function (template, d, o) { + var data = d || utils.createNullProtoObjWherePossible(); + var opts = o || utils.createNullProtoObjWherePossible(); + + // No options object -- if there are optiony names + // in the data, copy them to options + if (arguments.length == 2) { + utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA); + } + + return handleCache(opts, template)(data); +}; + +/** + * Render an EJS file at the given `path` and callback `cb(err, str)`. + * + * If you would like to include options but not data, you need to explicitly + * call this function with `data` being an empty object or `null`. + * + * @param {String} path path to the EJS file + * @param {Object} [data={}] template data + * @param {Options} [opts={}] compilation and rendering options + * @param {RenderFileCallback} cb callback + * @public + */ + +exports.renderFile = function () { + var args = Array.prototype.slice.call(arguments); + var filename = args.shift(); + var cb; + var opts = {filename: filename}; + var data; + var viewOpts; + + // Do we have a callback? + if (typeof arguments[arguments.length - 1] == 'function') { + cb = args.pop(); + } + // Do we have data/opts? + if (args.length) { + // Should always have data obj + data = args.shift(); + // Normal passed opts (data obj + opts obj) + if (args.length) { + // Use shallowCopy so we don't pollute passed in opts obj with new vals + utils.shallowCopy(opts, args.pop()); + } + // Special casing for Express (settings + opts-in-data) + else { + // Express 3 and 4 + if (data.settings) { + // Pull a few things from known locations + if (data.settings.views) { + opts.views = data.settings.views; + } + if (data.settings['view cache']) { + opts.cache = true; + } + // Undocumented after Express 2, but still usable, esp. for + // items that are unsafe to be passed along with data, like `root` + viewOpts = data.settings['view options']; + if (viewOpts) { + utils.shallowCopy(opts, viewOpts); + } + } + // Express 2 and lower, values set in app.locals, or people who just + // want to pass options in their data. NOTE: These values will override + // anything previously set in settings or settings['view options'] + utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA_EXPRESS); + } + opts.filename = filename; + } + else { + data = utils.createNullProtoObjWherePossible(); + } + + return tryHandleCache(opts, data, cb); +}; + +/** + * Clear intermediate JavaScript cache. Calls {@link Cache#reset}. + * @public + */ + +/** + * EJS template class + * @public + */ +exports.Template = Template; + +exports.clearCache = function () { + exports.cache.reset(); +}; + +function Template(text, optsParam) { + var opts = utils.hasOwnOnlyObject(optsParam); + var options = utils.createNullProtoObjWherePossible(); + this.templateText = text; + /** @type {string | null} */ + this.mode = null; + this.truncate = false; + this.currentLine = 1; + this.source = ''; + options.client = opts.client || false; + options.escapeFunction = opts.escape || opts.escapeFunction || utils.escapeXML; + options.compileDebug = opts.compileDebug !== false; + options.debug = !!opts.debug; + options.filename = opts.filename; + options.openDelimiter = opts.openDelimiter || exports.openDelimiter || _DEFAULT_OPEN_DELIMITER; + options.closeDelimiter = opts.closeDelimiter || exports.closeDelimiter || _DEFAULT_CLOSE_DELIMITER; + options.delimiter = opts.delimiter || exports.delimiter || _DEFAULT_DELIMITER; + options.strict = opts.strict || false; + options.context = opts.context; + options.cache = opts.cache || false; + options.rmWhitespace = opts.rmWhitespace; + options.root = opts.root; + options.includer = opts.includer; + options.outputFunctionName = opts.outputFunctionName; + options.localsName = opts.localsName || exports.localsName || _DEFAULT_LOCALS_NAME; + options.views = opts.views; + options.async = opts.async; + options.destructuredLocals = opts.destructuredLocals; + options.legacyInclude = typeof opts.legacyInclude != 'undefined' ? !!opts.legacyInclude : true; + + if (options.strict) { + options._with = false; + } + else { + options._with = typeof opts._with != 'undefined' ? opts._with : true; + } + + this.opts = options; + + this.regex = this.createRegex(); +} + +Template.modes = { + EVAL: 'eval', + ESCAPED: 'escaped', + RAW: 'raw', + COMMENT: 'comment', + LITERAL: 'literal' +}; + +Template.prototype = { + createRegex: function () { + var str = _REGEX_STRING; + var delim = utils.escapeRegExpChars(this.opts.delimiter); + var open = utils.escapeRegExpChars(this.opts.openDelimiter); + var close = utils.escapeRegExpChars(this.opts.closeDelimiter); + str = str.replace(/%/g, delim) + .replace(//g, close); + return new RegExp(str); + }, + + compile: function () { + /** @type {string} */ + var src; + /** @type {ClientFunction} */ + var fn; + var opts = this.opts; + var prepended = ''; + var appended = ''; + /** @type {EscapeCallback} */ + var escapeFn = opts.escapeFunction; + /** @type {FunctionConstructor} */ + var ctor; + /** @type {string} */ + var sanitizedFilename = opts.filename ? JSON.stringify(opts.filename) : 'undefined'; + + if (!this.source) { + this.generateSource(); + prepended += + ' var __output = "";\n' + + ' function __append(s) { if (s !== undefined && s !== null) __output += s }\n'; + if (opts.outputFunctionName) { + if (!_JS_IDENTIFIER.test(opts.outputFunctionName)) { + throw new Error('outputFunctionName is not a valid JS identifier.'); + } + prepended += ' var ' + opts.outputFunctionName + ' = __append;' + '\n'; + } + if (opts.localsName && !_JS_IDENTIFIER.test(opts.localsName)) { + throw new Error('localsName is not a valid JS identifier.'); + } + if (opts.destructuredLocals && opts.destructuredLocals.length) { + var destructuring = ' var __locals = (' + opts.localsName + ' || {}),\n'; + for (var i = 0; i < opts.destructuredLocals.length; i++) { + var name = opts.destructuredLocals[i]; + if (!_JS_IDENTIFIER.test(name)) { + throw new Error('destructuredLocals[' + i + '] is not a valid JS identifier.'); + } + if (i > 0) { + destructuring += ',\n '; + } + destructuring += name + ' = __locals.' + name; + } + prepended += destructuring + ';\n'; + } + if (opts._with !== false) { + prepended += ' with (' + opts.localsName + ' || {}) {' + '\n'; + appended += ' }' + '\n'; + } + appended += ' return __output;' + '\n'; + this.source = prepended + this.source + appended; + } + + if (opts.compileDebug) { + src = 'var __line = 1' + '\n' + + ' , __lines = ' + JSON.stringify(this.templateText) + '\n' + + ' , __filename = ' + sanitizedFilename + ';' + '\n' + + 'try {' + '\n' + + this.source + + '} catch (e) {' + '\n' + + ' rethrow(e, __lines, __filename, __line, escapeFn);' + '\n' + + '}' + '\n'; + } + else { + src = this.source; + } + + if (opts.client) { + src = 'escapeFn = escapeFn || ' + escapeFn.toString() + ';' + '\n' + src; + if (opts.compileDebug) { + src = 'rethrow = rethrow || ' + rethrow.toString() + ';' + '\n' + src; + } + } + + if (opts.strict) { + src = '"use strict";\n' + src; + } + if (opts.debug) { + console.log(src); + } + if (opts.compileDebug && opts.filename) { + src = src + '\n' + + '//# sourceURL=' + sanitizedFilename + '\n'; + } + + try { + if (opts.async) { + // Have to use generated function for this, since in envs without support, + // it breaks in parsing + try { + ctor = (new Function('return (async function(){}).constructor;'))(); + } + catch(e) { + if (e instanceof SyntaxError) { + throw new Error('This environment does not support async/await'); + } + else { + throw e; + } + } + } + else { + ctor = Function; + } + fn = new ctor(opts.localsName + ', escapeFn, include, rethrow', src); + } + catch(e) { + // istanbul ignore else + if (e instanceof SyntaxError) { + if (opts.filename) { + e.message += ' in ' + opts.filename; + } + e.message += ' while compiling ejs\n\n'; + e.message += 'If the above error is not helpful, you may want to try EJS-Lint:\n'; + e.message += 'https://github.com/RyanZim/EJS-Lint'; + if (!opts.async) { + e.message += '\n'; + e.message += 'Or, if you meant to create an async function, pass `async: true` as an option.'; + } + } + throw e; + } + + // Return a callable function which will execute the function + // created by the source-code, with the passed data as locals + // Adds a local `include` function which allows full recursive include + var returnedFn = opts.client ? fn : function anonymous(data) { + var include = function (path, includeData) { + var d = utils.shallowCopy(utils.createNullProtoObjWherePossible(), data); + if (includeData) { + d = utils.shallowCopy(d, includeData); + } + return includeFile(path, opts)(d); + }; + return fn.apply(opts.context, + [data || utils.createNullProtoObjWherePossible(), escapeFn, include, rethrow]); + }; + if (opts.filename && typeof Object.defineProperty === 'function') { + var filename = opts.filename; + var basename = path.basename(filename, path.extname(filename)); + try { + Object.defineProperty(returnedFn, 'name', { + value: basename, + writable: false, + enumerable: false, + configurable: true + }); + } catch (e) {/* ignore */} + } + return returnedFn; + }, + + generateSource: function () { + var opts = this.opts; + + if (opts.rmWhitespace) { + // Have to use two separate replace here as `^` and `$` operators don't + // work well with `\r` and empty lines don't work well with the `m` flag. + this.templateText = + this.templateText.replace(/[\r\n]+/g, '\n').replace(/^\s+|\s+$/gm, ''); + } + + // Slurp spaces and tabs before <%_ and after _%> + this.templateText = + this.templateText.replace(/[ \t]*<%_/gm, '<%_').replace(/_%>[ \t]*/gm, '_%>'); + + var self = this; + var matches = this.parseTemplateText(); + var d = this.opts.delimiter; + var o = this.opts.openDelimiter; + var c = this.opts.closeDelimiter; + + if (matches && matches.length) { + matches.forEach(function (line, index) { + var closing; + // If this is an opening tag, check for closing tags + // FIXME: May end up with some false positives here + // Better to store modes as k/v with openDelimiter + delimiter as key + // Then this can simply check against the map + if ( line.indexOf(o + d) === 0 // If it is a tag + && line.indexOf(o + d + d) !== 0) { // and is not escaped + closing = matches[index + 2]; + if (!(closing == d + c || closing == '-' + d + c || closing == '_' + d + c)) { + throw new Error('Could not find matching close tag for "' + line + '".'); + } + } + self.scanLine(line); + }); + } + + }, + + parseTemplateText: function () { + var str = this.templateText; + var pat = this.regex; + var result = pat.exec(str); + var arr = []; + var firstPos; + + while (result) { + firstPos = result.index; + + if (firstPos !== 0) { + arr.push(str.substring(0, firstPos)); + str = str.slice(firstPos); + } + + arr.push(result[0]); + str = str.slice(result[0].length); + result = pat.exec(str); + } + + if (str) { + arr.push(str); + } + + return arr; + }, + + _addOutput: function (line) { + if (this.truncate) { + // Only replace single leading linebreak in the line after + // -%> tag -- this is the single, trailing linebreak + // after the tag that the truncation mode replaces + // Handle Win / Unix / old Mac linebreaks -- do the \r\n + // combo first in the regex-or + line = line.replace(/^(?:\r\n|\r|\n)/, ''); + this.truncate = false; + } + if (!line) { + return line; + } + + // Preserve literal slashes + line = line.replace(/\\/g, '\\\\'); + + // Convert linebreaks + line = line.replace(/\n/g, '\\n'); + line = line.replace(/\r/g, '\\r'); + + // Escape double-quotes + // - this will be the delimiter during execution + line = line.replace(/"/g, '\\"'); + this.source += ' ; __append("' + line + '")' + '\n'; + }, + + scanLine: function (line) { + var self = this; + var d = this.opts.delimiter; + var o = this.opts.openDelimiter; + var c = this.opts.closeDelimiter; + var newLineCount = 0; + + newLineCount = (line.split('\n').length - 1); + + switch (line) { + case o + d: + case o + d + '_': + this.mode = Template.modes.EVAL; + break; + case o + d + '=': + this.mode = Template.modes.ESCAPED; + break; + case o + d + '-': + this.mode = Template.modes.RAW; + break; + case o + d + '#': + this.mode = Template.modes.COMMENT; + break; + case o + d + d: + this.mode = Template.modes.LITERAL; + this.source += ' ; __append("' + line.replace(o + d + d, o + d) + '")' + '\n'; + break; + case d + d + c: + this.mode = Template.modes.LITERAL; + this.source += ' ; __append("' + line.replace(d + d + c, d + c) + '")' + '\n'; + break; + case d + c: + case '-' + d + c: + case '_' + d + c: + if (this.mode == Template.modes.LITERAL) { + this._addOutput(line); + } + + this.mode = null; + this.truncate = line.indexOf('-') === 0 || line.indexOf('_') === 0; + break; + default: + // In script mode, depends on type of tag + if (this.mode) { + // If '//' is found without a line break, add a line break. + switch (this.mode) { + case Template.modes.EVAL: + case Template.modes.ESCAPED: + case Template.modes.RAW: + if (line.lastIndexOf('//') > line.lastIndexOf('\n')) { + line += '\n'; + } + } + switch (this.mode) { + // Just executing code + case Template.modes.EVAL: + this.source += ' ; ' + line + '\n'; + break; + // Exec, esc, and output + case Template.modes.ESCAPED: + this.source += ' ; __append(escapeFn(' + stripSemi(line) + '))' + '\n'; + break; + // Exec and output + case Template.modes.RAW: + this.source += ' ; __append(' + stripSemi(line) + ')' + '\n'; + break; + case Template.modes.COMMENT: + // Do nothing + break; + // Literal <%% mode, append as raw output + case Template.modes.LITERAL: + this._addOutput(line); + break; + } + } + // In string mode, just add the output + else { + this._addOutput(line); + } + } + + if (self.opts.compileDebug && newLineCount) { + this.currentLine += newLineCount; + this.source += ' ; __line = ' + this.currentLine + '\n'; + } + } +}; + +/** + * Escape characters reserved in XML. + * + * This is simply an export of {@link module:utils.escapeXML}. + * + * If `markup` is `undefined` or `null`, the empty string is returned. + * + * @param {String} markup Input string + * @return {String} Escaped string + * @public + * @func + * */ +exports.escapeXML = utils.escapeXML; + +/** + * Express.js support. + * + * This is an alias for {@link module:ejs.renderFile}, in order to support + * Express.js out-of-the-box. + * + * @func + */ + +exports.__express = exports.renderFile; + +/** + * Version of EJS. + * + * @readonly + * @type {String} + * @public + */ + +exports.VERSION = _VERSION_STRING; + +/** + * Name for detection of EJS. + * + * @readonly + * @type {String} + * @public + */ + +exports.name = _NAME; + +/* istanbul ignore if */ +if (typeof window != 'undefined') { + window.ejs = exports; +} + + +},{"../package.json":6,"./utils":2,"fs":3,"path":4}],2:[function(require,module,exports){ +/* + * EJS Embedded JavaScript templates + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +/** + * Private utility functions + * @module utils + * @private + */ + +'use strict'; + +var regExpChars = /[|\\{}()[\]^$+*?.]/g; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var hasOwn = function (obj, key) { return hasOwnProperty.apply(obj, [key]); }; + +/** + * Escape characters reserved in regular expressions. + * + * If `string` is `undefined` or `null`, the empty string is returned. + * + * @param {String} string Input string + * @return {String} Escaped string + * @static + * @private + */ +exports.escapeRegExpChars = function (string) { + // istanbul ignore if + if (!string) { + return ''; + } + return String(string).replace(regExpChars, '\\$&'); +}; + +var _ENCODE_HTML_RULES = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' +}; +var _MATCH_HTML = /[&<>'"]/g; + +function encode_char(c) { + return _ENCODE_HTML_RULES[c] || c; +} + +/** + * Stringified version of constants used by {@link module:utils.escapeXML}. + * + * It is used in the process of generating {@link ClientFunction}s. + * + * @readonly + * @type {String} + */ + +var escapeFuncStr = + 'var _ENCODE_HTML_RULES = {\n' ++ ' "&": "&"\n' ++ ' , "<": "<"\n' ++ ' , ">": ">"\n' ++ ' , \'"\': """\n' ++ ' , "\'": "'"\n' ++ ' }\n' ++ ' , _MATCH_HTML = /[&<>\'"]/g;\n' ++ 'function encode_char(c) {\n' ++ ' return _ENCODE_HTML_RULES[c] || c;\n' ++ '};\n'; + +/** + * Escape characters reserved in XML. + * + * If `markup` is `undefined` or `null`, the empty string is returned. + * + * @implements {EscapeCallback} + * @param {String} markup Input string + * @return {String} Escaped string + * @static + * @private + */ + +exports.escapeXML = function (markup) { + return markup == undefined + ? '' + : String(markup) + .replace(_MATCH_HTML, encode_char); +}; + +function escapeXMLToString() { + return Function.prototype.toString.call(this) + ';\n' + escapeFuncStr; +} + +try { + if (typeof Object.defineProperty === 'function') { + // If the Function prototype is frozen, the "toString" property is non-writable. This means that any objects which inherit this property + // cannot have the property changed using an assignment. If using strict mode, attempting that will cause an error. If not using strict + // mode, attempting that will be silently ignored. + // However, we can still explicitly shadow the prototype's "toString" property by defining a new "toString" property on this object. + Object.defineProperty(exports.escapeXML, 'toString', { value: escapeXMLToString }); + } else { + // If Object.defineProperty() doesn't exist, attempt to shadow this property using the assignment operator. + exports.escapeXML.toString = escapeXMLToString; + } +} catch (err) { + console.warn('Unable to set escapeXML.toString (is the Function prototype frozen?)'); +} + +/** + * Naive copy of properties from one object to another. + * Does not recurse into non-scalar properties + * Does not check to see if the property has a value before copying + * + * @param {Object} to Destination object + * @param {Object} from Source object + * @return {Object} Destination object + * @static + * @private + */ +exports.shallowCopy = function (to, from) { + from = from || {}; + if ((to !== null) && (to !== undefined)) { + for (var p in from) { + if (!hasOwn(from, p)) { + continue; + } + if (p === '__proto__' || p === 'constructor') { + continue; + } + to[p] = from[p]; + } + } + return to; +}; + +/** + * Naive copy of a list of key names, from one object to another. + * Only copies property if it is actually defined + * Does not recurse into non-scalar properties + * + * @param {Object} to Destination object + * @param {Object} from Source object + * @param {Array} list List of properties to copy + * @return {Object} Destination object + * @static + * @private + */ +exports.shallowCopyFromList = function (to, from, list) { + list = list || []; + from = from || {}; + if ((to !== null) && (to !== undefined)) { + for (var i = 0; i < list.length; i++) { + var p = list[i]; + if (typeof from[p] != 'undefined') { + if (!hasOwn(from, p)) { + continue; + } + if (p === '__proto__' || p === 'constructor') { + continue; + } + to[p] = from[p]; + } + } + } + return to; +}; + +/** + * Simple in-process cache implementation. Does not implement limits of any + * sort. + * + * @implements {Cache} + * @static + * @private + */ +exports.cache = { + _data: {}, + set: function (key, val) { + this._data[key] = val; + }, + get: function (key) { + return this._data[key]; + }, + remove: function (key) { + delete this._data[key]; + }, + reset: function () { + this._data = {}; + } +}; + +/** + * Transforms hyphen case variable into camel case. + * + * @param {String} string Hyphen case string + * @return {String} Camel case string + * @static + * @private + */ +exports.hyphenToCamel = function (str) { + return str.replace(/-[a-z]/g, function (match) { return match[1].toUpperCase(); }); +}; + +/** + * Returns a null-prototype object in runtimes that support it + * + * @return {Object} Object, prototype will be set to null where possible + * @static + * @private + */ +exports.createNullProtoObjWherePossible = (function () { + if (typeof Object.create == 'function') { + return function () { + return Object.create(null); + }; + } + if (!({__proto__: null} instanceof Object)) { + return function () { + return {__proto__: null}; + }; + } + // Not possible, just pass through + return function () { + return {}; + }; +})(); + +exports.hasOwnOnlyObject = function (obj) { + var o = exports.createNullProtoObjWherePossible(); + for (var p in obj) { + if (hasOwn(obj, p)) { + o[p] = obj[p]; + } + } + return o; +}; + + +},{}],3:[function(require,module,exports){ + +},{}],4:[function(require,module,exports){ +(function (process){ +// .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1, +// backported and transplited with Babel, with backwards-compat fixes + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function (path) { + if (typeof path !== 'string') path = path + ''; + if (path.length === 0) return '.'; + var code = path.charCodeAt(0); + var hasRoot = code === 47 /*/*/; + var end = -1; + var matchedSlash = true; + for (var i = path.length - 1; i >= 1; --i) { + code = path.charCodeAt(i); + if (code === 47 /*/*/) { + if (!matchedSlash) { + end = i; + break; + } + } else { + // We saw the first non-path separator + matchedSlash = false; + } + } + + if (end === -1) return hasRoot ? '/' : '.'; + if (hasRoot && end === 1) { + // return '//'; + // Backwards-compat fix: + return '/'; + } + return path.slice(0, end); +}; + +function basename(path) { + if (typeof path !== 'string') path = path + ''; + + var start = 0; + var end = -1; + var matchedSlash = true; + var i; + + for (i = path.length - 1; i >= 0; --i) { + if (path.charCodeAt(i) === 47 /*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } else if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // path component + matchedSlash = false; + end = i + 1; + } + } + + if (end === -1) return ''; + return path.slice(start, end); +} + +// Uses a mixed approach for backwards-compatibility, as ext behavior changed +// in new Node.js versions, so only basename() above is backported here +exports.basename = function (path, ext) { + var f = basename(path); + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + +exports.extname = function (path) { + if (typeof path !== 'string') path = path + ''; + var startDot = -1; + var startPart = 0; + var end = -1; + var matchedSlash = true; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + var preDotState = 0; + for (var i = path.length - 1; i >= 0; --i) { + var code = path.charCodeAt(i); + if (code === 47 /*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === 46 /*.*/) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) + startDot = i; + else if (preDotState !== 1) + preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + + if (startDot === -1 || end === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + return ''; + } + return path.slice(startDot, end); +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +}).call(this,require('_process')) +},{"_process":5}],5:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],6:[function(require,module,exports){ +module.exports={ + "name": "ejs", + "description": "Embedded JavaScript templates", + "keywords": [ + "template", + "engine", + "ejs" + ], + "version": "3.1.9", + "author": "Matthew Eernisse (http://fleegix.org)", + "license": "Apache-2.0", + "bin": { + "ejs": "./bin/cli.js" + }, + "main": "./lib/ejs.js", + "jsdelivr": "ejs.min.js", + "unpkg": "ejs.min.js", + "repository": { + "type": "git", + "url": "git://github.com/mde/ejs.git" + }, + "bugs": "https://github.com/mde/ejs/issues", + "homepage": "https://github.com/mde/ejs", + "dependencies": { + "jake": "^10.8.5" + }, + "devDependencies": { + "browserify": "^16.5.1", + "eslint": "^6.8.0", + "git-directory-deploy": "^1.5.1", + "jsdoc": "^4.0.2", + "lru-cache": "^4.0.1", + "mocha": "^10.2.0", + "uglify-js": "^3.3.16" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "npx jake test" + } +} + +},{}]},{},[1])(1) +}); diff --git a/node_modules/ejs/ejs.min.js b/node_modules/ejs/ejs.min.js new file mode 100644 index 0000000..ef65bd3 --- /dev/null +++ b/node_modules/ejs/ejs.min.js @@ -0,0 +1 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.ejs=f()}})(function(){var define,module,exports;return function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i1;if(options.cache){if(!filename){throw new Error("cache option requires a filename")}func=exports.cache.get(filename);if(func){return func}if(!hasTemplate){template=fileLoader(filename).toString().replace(_BOM,"")}}else if(!hasTemplate){if(!filename){throw new Error("Internal EJS error: no file name or template "+"provided")}template=fileLoader(filename).toString().replace(_BOM,"")}func=exports.compile(template,options);if(options.cache){exports.cache.set(filename,func)}return func}function tryHandleCache(options,data,cb){var result;if(!cb){if(typeof exports.promiseImpl=="function"){return new exports.promiseImpl(function(resolve,reject){try{result=handleCache(options)(data);resolve(result)}catch(err){reject(err)}})}else{throw new Error("Please provide a callback function")}}else{try{result=handleCache(options)(data)}catch(err){return cb(err)}cb(null,result)}}function fileLoader(filePath){return exports.fileLoader(filePath)}function includeFile(path,options){var opts=utils.shallowCopy(utils.createNullProtoObjWherePossible(),options);opts.filename=getIncludePath(path,opts);if(typeof options.includer==="function"){var includerResult=options.includer(path,opts.filename);if(includerResult){if(includerResult.filename){opts.filename=includerResult.filename}if(includerResult.template){return handleCache(opts,includerResult.template)}}}return handleCache(opts)}function rethrow(err,str,flnm,lineno,esc){var lines=str.split("\n");var start=Math.max(lineno-3,0);var end=Math.min(lines.length,lineno+3);var filename=esc(flnm);var context=lines.slice(start,end).map(function(line,i){var curr=i+start+1;return(curr==lineno?" >> ":" ")+curr+"| "+line}).join("\n");err.path=filename;err.message=(filename||"ejs")+":"+lineno+"\n"+context+"\n\n"+err.message;throw err}function stripSemi(str){return str.replace(/;(\s*$)/,"$1")}exports.compile=function compile(template,opts){var templ;if(opts&&opts.scope){if(!scopeOptionWarned){console.warn("`scope` option is deprecated and will be removed in EJS 3");scopeOptionWarned=true}if(!opts.context){opts.context=opts.scope}delete opts.scope}templ=new Template(template,opts);return templ.compile()};exports.render=function(template,d,o){var data=d||utils.createNullProtoObjWherePossible();var opts=o||utils.createNullProtoObjWherePossible();if(arguments.length==2){utils.shallowCopyFromList(opts,data,_OPTS_PASSABLE_WITH_DATA)}return handleCache(opts,template)(data)};exports.renderFile=function(){var args=Array.prototype.slice.call(arguments);var filename=args.shift();var cb;var opts={filename:filename};var data;var viewOpts;if(typeof arguments[arguments.length-1]=="function"){cb=args.pop()}if(args.length){data=args.shift();if(args.length){utils.shallowCopy(opts,args.pop())}else{if(data.settings){if(data.settings.views){opts.views=data.settings.views}if(data.settings["view cache"]){opts.cache=true}viewOpts=data.settings["view options"];if(viewOpts){utils.shallowCopy(opts,viewOpts)}}utils.shallowCopyFromList(opts,data,_OPTS_PASSABLE_WITH_DATA_EXPRESS)}opts.filename=filename}else{data=utils.createNullProtoObjWherePossible()}return tryHandleCache(opts,data,cb)};exports.Template=Template;exports.clearCache=function(){exports.cache.reset()};function Template(text,optsParam){var opts=utils.hasOwnOnlyObject(optsParam);var options=utils.createNullProtoObjWherePossible();this.templateText=text;this.mode=null;this.truncate=false;this.currentLine=1;this.source="";options.client=opts.client||false;options.escapeFunction=opts.escape||opts.escapeFunction||utils.escapeXML;options.compileDebug=opts.compileDebug!==false;options.debug=!!opts.debug;options.filename=opts.filename;options.openDelimiter=opts.openDelimiter||exports.openDelimiter||_DEFAULT_OPEN_DELIMITER;options.closeDelimiter=opts.closeDelimiter||exports.closeDelimiter||_DEFAULT_CLOSE_DELIMITER;options.delimiter=opts.delimiter||exports.delimiter||_DEFAULT_DELIMITER;options.strict=opts.strict||false;options.context=opts.context;options.cache=opts.cache||false;options.rmWhitespace=opts.rmWhitespace;options.root=opts.root;options.includer=opts.includer;options.outputFunctionName=opts.outputFunctionName;options.localsName=opts.localsName||exports.localsName||_DEFAULT_LOCALS_NAME;options.views=opts.views;options.async=opts.async;options.destructuredLocals=opts.destructuredLocals;options.legacyInclude=typeof opts.legacyInclude!="undefined"?!!opts.legacyInclude:true;if(options.strict){options._with=false}else{options._with=typeof opts._with!="undefined"?opts._with:true}this.opts=options;this.regex=this.createRegex()}Template.modes={EVAL:"eval",ESCAPED:"escaped",RAW:"raw",COMMENT:"comment",LITERAL:"literal"};Template.prototype={createRegex:function(){var str=_REGEX_STRING;var delim=utils.escapeRegExpChars(this.opts.delimiter);var open=utils.escapeRegExpChars(this.opts.openDelimiter);var close=utils.escapeRegExpChars(this.opts.closeDelimiter);str=str.replace(/%/g,delim).replace(//g,close);return new RegExp(str)},compile:function(){var src;var fn;var opts=this.opts;var prepended="";var appended="";var escapeFn=opts.escapeFunction;var ctor;var sanitizedFilename=opts.filename?JSON.stringify(opts.filename):"undefined";if(!this.source){this.generateSource();prepended+=' var __output = "";\n'+" function __append(s) { if (s !== undefined && s !== null) __output += s }\n";if(opts.outputFunctionName){if(!_JS_IDENTIFIER.test(opts.outputFunctionName)){throw new Error("outputFunctionName is not a valid JS identifier.")}prepended+=" var "+opts.outputFunctionName+" = __append;"+"\n"}if(opts.localsName&&!_JS_IDENTIFIER.test(opts.localsName)){throw new Error("localsName is not a valid JS identifier.")}if(opts.destructuredLocals&&opts.destructuredLocals.length){var destructuring=" var __locals = ("+opts.localsName+" || {}),\n";for(var i=0;i0){destructuring+=",\n "}destructuring+=name+" = __locals."+name}prepended+=destructuring+";\n"}if(opts._with!==false){prepended+=" with ("+opts.localsName+" || {}) {"+"\n";appended+=" }"+"\n"}appended+=" return __output;"+"\n";this.source=prepended+this.source+appended}if(opts.compileDebug){src="var __line = 1"+"\n"+" , __lines = "+JSON.stringify(this.templateText)+"\n"+" , __filename = "+sanitizedFilename+";"+"\n"+"try {"+"\n"+this.source+"} catch (e) {"+"\n"+" rethrow(e, __lines, __filename, __line, escapeFn);"+"\n"+"}"+"\n"}else{src=this.source}if(opts.client){src="escapeFn = escapeFn || "+escapeFn.toString()+";"+"\n"+src;if(opts.compileDebug){src="rethrow = rethrow || "+rethrow.toString()+";"+"\n"+src}}if(opts.strict){src='"use strict";\n'+src}if(opts.debug){console.log(src)}if(opts.compileDebug&&opts.filename){src=src+"\n"+"//# sourceURL="+sanitizedFilename+"\n"}try{if(opts.async){try{ctor=new Function("return (async function(){}).constructor;")()}catch(e){if(e instanceof SyntaxError){throw new Error("This environment does not support async/await")}else{throw e}}}else{ctor=Function}fn=new ctor(opts.localsName+", escapeFn, include, rethrow",src)}catch(e){if(e instanceof SyntaxError){if(opts.filename){e.message+=" in "+opts.filename}e.message+=" while compiling ejs\n\n";e.message+="If the above error is not helpful, you may want to try EJS-Lint:\n";e.message+="https://github.com/RyanZim/EJS-Lint";if(!opts.async){e.message+="\n";e.message+="Or, if you meant to create an async function, pass `async: true` as an option."}}throw e}var returnedFn=opts.client?fn:function anonymous(data){var include=function(path,includeData){var d=utils.shallowCopy(utils.createNullProtoObjWherePossible(),data);if(includeData){d=utils.shallowCopy(d,includeData)}return includeFile(path,opts)(d)};return fn.apply(opts.context,[data||utils.createNullProtoObjWherePossible(),escapeFn,include,rethrow])};if(opts.filename&&typeof Object.defineProperty==="function"){var filename=opts.filename;var basename=path.basename(filename,path.extname(filename));try{Object.defineProperty(returnedFn,"name",{value:basename,writable:false,enumerable:false,configurable:true})}catch(e){}}return returnedFn},generateSource:function(){var opts=this.opts;if(opts.rmWhitespace){this.templateText=this.templateText.replace(/[\r\n]+/g,"\n").replace(/^\s+|\s+$/gm,"")}this.templateText=this.templateText.replace(/[ \t]*<%_/gm,"<%_").replace(/_%>[ \t]*/gm,"_%>");var self=this;var matches=this.parseTemplateText();var d=this.opts.delimiter;var o=this.opts.openDelimiter;var c=this.opts.closeDelimiter;if(matches&&matches.length){matches.forEach(function(line,index){var closing;if(line.indexOf(o+d)===0&&line.indexOf(o+d+d)!==0){closing=matches[index+2];if(!(closing==d+c||closing=="-"+d+c||closing=="_"+d+c)){throw new Error('Could not find matching close tag for "'+line+'".')}}self.scanLine(line)})}},parseTemplateText:function(){var str=this.templateText;var pat=this.regex;var result=pat.exec(str);var arr=[];var firstPos;while(result){firstPos=result.index;if(firstPos!==0){arr.push(str.substring(0,firstPos));str=str.slice(firstPos)}arr.push(result[0]);str=str.slice(result[0].length);result=pat.exec(str)}if(str){arr.push(str)}return arr},_addOutput:function(line){if(this.truncate){line=line.replace(/^(?:\r\n|\r|\n)/,"");this.truncate=false}if(!line){return line}line=line.replace(/\\/g,"\\\\");line=line.replace(/\n/g,"\\n");line=line.replace(/\r/g,"\\r");line=line.replace(/"/g,'\\"');this.source+=' ; __append("'+line+'")'+"\n"},scanLine:function(line){var self=this;var d=this.opts.delimiter;var o=this.opts.openDelimiter;var c=this.opts.closeDelimiter;var newLineCount=0;newLineCount=line.split("\n").length-1;switch(line){case o+d:case o+d+"_":this.mode=Template.modes.EVAL;break;case o+d+"=":this.mode=Template.modes.ESCAPED;break;case o+d+"-":this.mode=Template.modes.RAW;break;case o+d+"#":this.mode=Template.modes.COMMENT;break;case o+d+d:this.mode=Template.modes.LITERAL;this.source+=' ; __append("'+line.replace(o+d+d,o+d)+'")'+"\n";break;case d+d+c:this.mode=Template.modes.LITERAL;this.source+=' ; __append("'+line.replace(d+d+c,d+c)+'")'+"\n";break;case d+c:case"-"+d+c:case"_"+d+c:if(this.mode==Template.modes.LITERAL){this._addOutput(line)}this.mode=null;this.truncate=line.indexOf("-")===0||line.indexOf("_")===0;break;default:if(this.mode){switch(this.mode){case Template.modes.EVAL:case Template.modes.ESCAPED:case Template.modes.RAW:if(line.lastIndexOf("//")>line.lastIndexOf("\n")){line+="\n"}}switch(this.mode){case Template.modes.EVAL:this.source+=" ; "+line+"\n";break;case Template.modes.ESCAPED:this.source+=" ; __append(escapeFn("+stripSemi(line)+"))"+"\n";break;case Template.modes.RAW:this.source+=" ; __append("+stripSemi(line)+")"+"\n";break;case Template.modes.COMMENT:break;case Template.modes.LITERAL:this._addOutput(line);break}}else{this._addOutput(line)}}if(self.opts.compileDebug&&newLineCount){this.currentLine+=newLineCount;this.source+=" ; __line = "+this.currentLine+"\n"}}};exports.escapeXML=utils.escapeXML;exports.__express=exports.renderFile;exports.VERSION=_VERSION_STRING;exports.name=_NAME;if(typeof window!="undefined"){window.ejs=exports}},{"../package.json":6,"./utils":2,fs:3,path:4}],2:[function(require,module,exports){"use strict";var regExpChars=/[|\\{}()[\]^$+*?.]/g;var hasOwnProperty=Object.prototype.hasOwnProperty;var hasOwn=function(obj,key){return hasOwnProperty.apply(obj,[key])};exports.escapeRegExpChars=function(string){if(!string){return""}return String(string).replace(regExpChars,"\\$&")};var _ENCODE_HTML_RULES={"&":"&","<":"<",">":">",'"':""","'":"'"};var _MATCH_HTML=/[&<>'"]/g;function encode_char(c){return _ENCODE_HTML_RULES[c]||c}var escapeFuncStr="var _ENCODE_HTML_RULES = {\n"+' "&": "&"\n'+' , "<": "<"\n'+' , ">": ">"\n'+' , \'"\': """\n'+' , "\'": "'"\n'+" }\n"+" , _MATCH_HTML = /[&<>'\"]/g;\n"+"function encode_char(c) {\n"+" return _ENCODE_HTML_RULES[c] || c;\n"+"};\n";exports.escapeXML=function(markup){return markup==undefined?"":String(markup).replace(_MATCH_HTML,encode_char)};function escapeXMLToString(){return Function.prototype.toString.call(this)+";\n"+escapeFuncStr}try{if(typeof Object.defineProperty==="function"){Object.defineProperty(exports.escapeXML,"toString",{value:escapeXMLToString})}else{exports.escapeXML.toString=escapeXMLToString}}catch(err){console.warn("Unable to set escapeXML.toString (is the Function prototype frozen?)")}exports.shallowCopy=function(to,from){from=from||{};if(to!==null&&to!==undefined){for(var p in from){if(!hasOwn(from,p)){continue}if(p==="__proto__"||p==="constructor"){continue}to[p]=from[p]}}return to};exports.shallowCopyFromList=function(to,from,list){list=list||[];from=from||{};if(to!==null&&to!==undefined){for(var i=0;i=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up--;up){parts.unshift("..")}}return parts}exports.resolve=function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:process.cwd();if(typeof path!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){continue}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=path.charAt(0)==="/"}resolvedPath=normalizeArray(filter(resolvedPath.split("/"),function(p){return!!p}),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."};exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash=substr(path,-1)==="/";path=normalizeArray(filter(path.split("/"),function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path};exports.isAbsolute=function(path){return path.charAt(0)==="/"};exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p,index){if(typeof p!=="string"){throw new TypeError("Arguments to path.join must be strings")}return p}).join("/"))};exports.relative=function(from,to){from=exports.resolve(from).substr(1);to=exports.resolve(to).substr(1);function trim(arr){var start=0;for(;start=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i=1;--i){code=path.charCodeAt(i);if(code===47){if(!matchedSlash){end=i;break}}else{matchedSlash=false}}if(end===-1)return hasRoot?"/":".";if(hasRoot&&end===1){return"/"}return path.slice(0,end)};function basename(path){if(typeof path!=="string")path=path+"";var start=0;var end=-1;var matchedSlash=true;var i;for(i=path.length-1;i>=0;--i){if(path.charCodeAt(i)===47){if(!matchedSlash){start=i+1;break}}else if(end===-1){matchedSlash=false;end=i+1}}if(end===-1)return"";return path.slice(start,end)}exports.basename=function(path,ext){var f=basename(path);if(ext&&f.substr(-1*ext.length)===ext){f=f.substr(0,f.length-ext.length)}return f};exports.extname=function(path){if(typeof path!=="string")path=path+"";var startDot=-1;var startPart=0;var end=-1;var matchedSlash=true;var preDotState=0;for(var i=path.length-1;i>=0;--i){var code=path.charCodeAt(i);if(code===47){if(!matchedSlash){startPart=i+1;break}continue}if(end===-1){matchedSlash=false;end=i+1}if(code===46){if(startDot===-1)startDot=i;else if(preDotState!==1)preDotState=1}else if(startDot!==-1){preDotState=-1}}if(startDot===-1||end===-1||preDotState===0||preDotState===1&&startDot===end-1&&startDot===startPart+1){return""}return path.slice(startDot,end)};function filter(xs,f){if(xs.filter)return xs.filter(f);var res=[];for(var i=0;i1){for(var i=1;i (http://fleegix.org)",license:"Apache-2.0",bin:{ejs:"./bin/cli.js"},main:"./lib/ejs.js",jsdelivr:"ejs.min.js",unpkg:"ejs.min.js",repository:{type:"git",url:"git://github.com/mde/ejs.git"},bugs:"https://github.com/mde/ejs/issues",homepage:"https://github.com/mde/ejs",dependencies:{jake:"^10.8.5"},devDependencies:{browserify:"^16.5.1",eslint:"^6.8.0","git-directory-deploy":"^1.5.1",jsdoc:"^4.0.2","lru-cache":"^4.0.1",mocha:"^10.2.0","uglify-js":"^3.3.16"},engines:{node:">=0.10.0"},scripts:{test:"npx jake test"}}},{}]},{},[1])(1)}); diff --git a/node_modules/ejs/jakefile.js b/node_modules/ejs/jakefile.js new file mode 100644 index 0000000..0d6b6ab --- /dev/null +++ b/node_modules/ejs/jakefile.js @@ -0,0 +1,88 @@ +var fs = require('fs'); +var path = require('path'); +var execSync = require('child_process').execSync; +var exec = function (cmd) { + execSync(cmd, {stdio: 'inherit'}); +}; + +/* global jake, task, desc, publishTask */ + +task('build', ['lint', 'clean', 'browserify', 'minify'], function () { + console.log('Build completed.'); +}); + +desc('Cleans browerified/minified files and package files'); +task('clean', ['clobber'], function () { + jake.rmRf('./ejs.js'); + jake.rmRf('./ejs.min.js'); + console.log('Cleaned up compiled files.'); +}); + +desc('Lints the source code'); +task('lint', ['clean'], function () { + var epath = path.join('./node_modules/.bin/eslint'); + exec(epath+' "**/*.js"'); + console.log('Linting completed.'); +}); + +task('browserify', function () { + var epath = path.join('./node_modules/browserify/bin/cmd.js'); + exec(epath+' --standalone ejs lib/ejs.js > ejs.js'); + console.log('Browserification completed.'); +}); + +task('minify', function () { + var epath = path.join('./node_modules/uglify-js/bin/uglifyjs'); + exec(epath+' ejs.js > ejs.min.js'); + console.log('Minification completed.'); +}); + +desc('Generates the EJS API docs for the public API'); +task('doc', function () { + jake.rmRf('out'); + var epath = path.join('./node_modules/.bin/jsdoc'); + exec(epath+' --verbose -c jsdoc.json lib/* docs/jsdoc/*'); + console.log('Documentation generated in ./out.'); +}); + +desc('Generates the EJS API docs for the public and private API'); +task('devdoc', function () { + jake.rmRf('out'); + var epath = path.join('./node_modules/.bin/jsdoc'); + exec(epath+' --verbose -p -c jsdoc.json lib/* docs/jsdoc/*'); + console.log('Documentation generated in ./out.'); +}); + +desc('Publishes the EJS API docs'); +task('docPublish', ['doc'], function () { + fs.writeFileSync('out/CNAME', 'api.ejs.co'); + console.log('Pushing docs to gh-pages...'); + var epath = path.join('./node_modules/.bin/git-directory-deploy'); + exec(epath+' --directory out/'); + console.log('Docs published to gh-pages.'); +}); + +desc('Runs the EJS test suite'); +task('test', ['lint'], function () { + exec(path.join('./node_modules/.bin/mocha --u tdd')); +}); + +publishTask('ejs', ['build'], function () { + this.packageFiles.include([ + 'jakefile.js', + 'README.md', + 'LICENSE', + 'package.json', + 'ejs.js', + 'ejs.min.js', + 'lib/**', + 'bin/**', + 'usage.txt' + ]); +}); + +jake.Task.publish.on('complete', function () { + console.log('Updating hosted docs...'); + console.log('If this fails, run jake docPublish to re-try.'); + jake.Task.docPublish.invoke(); +}); diff --git a/node_modules/ejs/lib/ejs.js b/node_modules/ejs/lib/ejs.js new file mode 100755 index 0000000..1153b53 --- /dev/null +++ b/node_modules/ejs/lib/ejs.js @@ -0,0 +1,952 @@ +/* + * EJS Embedded JavaScript templates + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +'use strict'; + +/** + * @file Embedded JavaScript templating engine. {@link http://ejs.co} + * @author Matthew Eernisse + * @author Tiancheng "Timothy" Gu + * @project EJS + * @license {@link http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0} + */ + +/** + * EJS internal functions. + * + * Technically this "module" lies in the same file as {@link module:ejs}, for + * the sake of organization all the private functions re grouped into this + * module. + * + * @module ejs-internal + * @private + */ + +/** + * Embedded JavaScript templating engine. + * + * @module ejs + * @public + */ + + +var fs = require('fs'); +var path = require('path'); +var utils = require('./utils'); + +var scopeOptionWarned = false; +/** @type {string} */ +var _VERSION_STRING = require('../package.json').version; +var _DEFAULT_OPEN_DELIMITER = '<'; +var _DEFAULT_CLOSE_DELIMITER = '>'; +var _DEFAULT_DELIMITER = '%'; +var _DEFAULT_LOCALS_NAME = 'locals'; +var _NAME = 'ejs'; +var _REGEX_STRING = '(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)'; +var _OPTS_PASSABLE_WITH_DATA = ['delimiter', 'scope', 'context', 'debug', 'compileDebug', + 'client', '_with', 'rmWhitespace', 'strict', 'filename', 'async']; +// We don't allow 'cache' option to be passed in the data obj for +// the normal `render` call, but this is where Express 2 & 3 put it +// so we make an exception for `renderFile` +var _OPTS_PASSABLE_WITH_DATA_EXPRESS = _OPTS_PASSABLE_WITH_DATA.concat('cache'); +var _BOM = /^\uFEFF/; +var _JS_IDENTIFIER = /^[a-zA-Z_$][0-9a-zA-Z_$]*$/; + +/** + * EJS template function cache. This can be a LRU object from lru-cache NPM + * module. By default, it is {@link module:utils.cache}, a simple in-process + * cache that grows continuously. + * + * @type {Cache} + */ + +exports.cache = utils.cache; + +/** + * Custom file loader. Useful for template preprocessing or restricting access + * to a certain part of the filesystem. + * + * @type {fileLoader} + */ + +exports.fileLoader = fs.readFileSync; + +/** + * Name of the object containing the locals. + * + * This variable is overridden by {@link Options}`.localsName` if it is not + * `undefined`. + * + * @type {String} + * @public + */ + +exports.localsName = _DEFAULT_LOCALS_NAME; + +/** + * Promise implementation -- defaults to the native implementation if available + * This is mostly just for testability + * + * @type {PromiseConstructorLike} + * @public + */ + +exports.promiseImpl = (new Function('return this;'))().Promise; + +/** + * Get the path to the included file from the parent file path and the + * specified path. + * + * @param {String} name specified path + * @param {String} filename parent file path + * @param {Boolean} [isDir=false] whether the parent file path is a directory + * @return {String} + */ +exports.resolveInclude = function(name, filename, isDir) { + var dirname = path.dirname; + var extname = path.extname; + var resolve = path.resolve; + var includePath = resolve(isDir ? filename : dirname(filename), name); + var ext = extname(name); + if (!ext) { + includePath += '.ejs'; + } + return includePath; +}; + +/** + * Try to resolve file path on multiple directories + * + * @param {String} name specified path + * @param {Array} paths list of possible parent directory paths + * @return {String} + */ +function resolvePaths(name, paths) { + var filePath; + if (paths.some(function (v) { + filePath = exports.resolveInclude(name, v, true); + return fs.existsSync(filePath); + })) { + return filePath; + } +} + +/** + * Get the path to the included file by Options + * + * @param {String} path specified path + * @param {Options} options compilation options + * @return {String} + */ +function getIncludePath(path, options) { + var includePath; + var filePath; + var views = options.views; + var match = /^[A-Za-z]+:\\|^\//.exec(path); + + // Abs path + if (match && match.length) { + path = path.replace(/^\/*/, ''); + if (Array.isArray(options.root)) { + includePath = resolvePaths(path, options.root); + } else { + includePath = exports.resolveInclude(path, options.root || '/', true); + } + } + // Relative paths + else { + // Look relative to a passed filename first + if (options.filename) { + filePath = exports.resolveInclude(path, options.filename); + if (fs.existsSync(filePath)) { + includePath = filePath; + } + } + // Then look in any views directories + if (!includePath && Array.isArray(views)) { + includePath = resolvePaths(path, views); + } + if (!includePath && typeof options.includer !== 'function') { + throw new Error('Could not find the include file "' + + options.escapeFunction(path) + '"'); + } + } + return includePath; +} + +/** + * Get the template from a string or a file, either compiled on-the-fly or + * read from cache (if enabled), and cache the template if needed. + * + * If `template` is not set, the file specified in `options.filename` will be + * read. + * + * If `options.cache` is true, this function reads the file from + * `options.filename` so it must be set prior to calling this function. + * + * @memberof module:ejs-internal + * @param {Options} options compilation options + * @param {String} [template] template source + * @return {(TemplateFunction|ClientFunction)} + * Depending on the value of `options.client`, either type might be returned. + * @static + */ + +function handleCache(options, template) { + var func; + var filename = options.filename; + var hasTemplate = arguments.length > 1; + + if (options.cache) { + if (!filename) { + throw new Error('cache option requires a filename'); + } + func = exports.cache.get(filename); + if (func) { + return func; + } + if (!hasTemplate) { + template = fileLoader(filename).toString().replace(_BOM, ''); + } + } + else if (!hasTemplate) { + // istanbul ignore if: should not happen at all + if (!filename) { + throw new Error('Internal EJS error: no file name or template ' + + 'provided'); + } + template = fileLoader(filename).toString().replace(_BOM, ''); + } + func = exports.compile(template, options); + if (options.cache) { + exports.cache.set(filename, func); + } + return func; +} + +/** + * Try calling handleCache with the given options and data and call the + * callback with the result. If an error occurs, call the callback with + * the error. Used by renderFile(). + * + * @memberof module:ejs-internal + * @param {Options} options compilation options + * @param {Object} data template data + * @param {RenderFileCallback} cb callback + * @static + */ + +function tryHandleCache(options, data, cb) { + var result; + if (!cb) { + if (typeof exports.promiseImpl == 'function') { + return new exports.promiseImpl(function (resolve, reject) { + try { + result = handleCache(options)(data); + resolve(result); + } + catch (err) { + reject(err); + } + }); + } + else { + throw new Error('Please provide a callback function'); + } + } + else { + try { + result = handleCache(options)(data); + } + catch (err) { + return cb(err); + } + + cb(null, result); + } +} + +/** + * fileLoader is independent + * + * @param {String} filePath ejs file path. + * @return {String} The contents of the specified file. + * @static + */ + +function fileLoader(filePath){ + return exports.fileLoader(filePath); +} + +/** + * Get the template function. + * + * If `options.cache` is `true`, then the template is cached. + * + * @memberof module:ejs-internal + * @param {String} path path for the specified file + * @param {Options} options compilation options + * @return {(TemplateFunction|ClientFunction)} + * Depending on the value of `options.client`, either type might be returned + * @static + */ + +function includeFile(path, options) { + var opts = utils.shallowCopy(utils.createNullProtoObjWherePossible(), options); + opts.filename = getIncludePath(path, opts); + if (typeof options.includer === 'function') { + var includerResult = options.includer(path, opts.filename); + if (includerResult) { + if (includerResult.filename) { + opts.filename = includerResult.filename; + } + if (includerResult.template) { + return handleCache(opts, includerResult.template); + } + } + } + return handleCache(opts); +} + +/** + * Re-throw the given `err` in context to the `str` of ejs, `filename`, and + * `lineno`. + * + * @implements {RethrowCallback} + * @memberof module:ejs-internal + * @param {Error} err Error object + * @param {String} str EJS source + * @param {String} flnm file name of the EJS file + * @param {Number} lineno line number of the error + * @param {EscapeCallback} esc + * @static + */ + +function rethrow(err, str, flnm, lineno, esc) { + var lines = str.split('\n'); + var start = Math.max(lineno - 3, 0); + var end = Math.min(lines.length, lineno + 3); + var filename = esc(flnm); + // Error context + var context = lines.slice(start, end).map(function (line, i){ + var curr = i + start + 1; + return (curr == lineno ? ' >> ' : ' ') + + curr + + '| ' + + line; + }).join('\n'); + + // Alter exception message + err.path = filename; + err.message = (filename || 'ejs') + ':' + + lineno + '\n' + + context + '\n\n' + + err.message; + + throw err; +} + +function stripSemi(str){ + return str.replace(/;(\s*$)/, '$1'); +} + +/** + * Compile the given `str` of ejs into a template function. + * + * @param {String} template EJS template + * + * @param {Options} [opts] compilation options + * + * @return {(TemplateFunction|ClientFunction)} + * Depending on the value of `opts.client`, either type might be returned. + * Note that the return type of the function also depends on the value of `opts.async`. + * @public + */ + +exports.compile = function compile(template, opts) { + var templ; + + // v1 compat + // 'scope' is 'context' + // FIXME: Remove this in a future version + if (opts && opts.scope) { + if (!scopeOptionWarned){ + console.warn('`scope` option is deprecated and will be removed in EJS 3'); + scopeOptionWarned = true; + } + if (!opts.context) { + opts.context = opts.scope; + } + delete opts.scope; + } + templ = new Template(template, opts); + return templ.compile(); +}; + +/** + * Render the given `template` of ejs. + * + * If you would like to include options but not data, you need to explicitly + * call this function with `data` being an empty object or `null`. + * + * @param {String} template EJS template + * @param {Object} [data={}] template data + * @param {Options} [opts={}] compilation and rendering options + * @return {(String|Promise)} + * Return value type depends on `opts.async`. + * @public + */ + +exports.render = function (template, d, o) { + var data = d || utils.createNullProtoObjWherePossible(); + var opts = o || utils.createNullProtoObjWherePossible(); + + // No options object -- if there are optiony names + // in the data, copy them to options + if (arguments.length == 2) { + utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA); + } + + return handleCache(opts, template)(data); +}; + +/** + * Render an EJS file at the given `path` and callback `cb(err, str)`. + * + * If you would like to include options but not data, you need to explicitly + * call this function with `data` being an empty object or `null`. + * + * @param {String} path path to the EJS file + * @param {Object} [data={}] template data + * @param {Options} [opts={}] compilation and rendering options + * @param {RenderFileCallback} cb callback + * @public + */ + +exports.renderFile = function () { + var args = Array.prototype.slice.call(arguments); + var filename = args.shift(); + var cb; + var opts = {filename: filename}; + var data; + var viewOpts; + + // Do we have a callback? + if (typeof arguments[arguments.length - 1] == 'function') { + cb = args.pop(); + } + // Do we have data/opts? + if (args.length) { + // Should always have data obj + data = args.shift(); + // Normal passed opts (data obj + opts obj) + if (args.length) { + // Use shallowCopy so we don't pollute passed in opts obj with new vals + utils.shallowCopy(opts, args.pop()); + } + // Special casing for Express (settings + opts-in-data) + else { + // Express 3 and 4 + if (data.settings) { + // Pull a few things from known locations + if (data.settings.views) { + opts.views = data.settings.views; + } + if (data.settings['view cache']) { + opts.cache = true; + } + // Undocumented after Express 2, but still usable, esp. for + // items that are unsafe to be passed along with data, like `root` + viewOpts = data.settings['view options']; + if (viewOpts) { + utils.shallowCopy(opts, viewOpts); + } + } + // Express 2 and lower, values set in app.locals, or people who just + // want to pass options in their data. NOTE: These values will override + // anything previously set in settings or settings['view options'] + utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA_EXPRESS); + } + opts.filename = filename; + } + else { + data = utils.createNullProtoObjWherePossible(); + } + + return tryHandleCache(opts, data, cb); +}; + +/** + * Clear intermediate JavaScript cache. Calls {@link Cache#reset}. + * @public + */ + +/** + * EJS template class + * @public + */ +exports.Template = Template; + +exports.clearCache = function () { + exports.cache.reset(); +}; + +function Template(text, optsParam) { + var opts = utils.hasOwnOnlyObject(optsParam); + var options = utils.createNullProtoObjWherePossible(); + this.templateText = text; + /** @type {string | null} */ + this.mode = null; + this.truncate = false; + this.currentLine = 1; + this.source = ''; + options.client = opts.client || false; + options.escapeFunction = opts.escape || opts.escapeFunction || utils.escapeXML; + options.compileDebug = opts.compileDebug !== false; + options.debug = !!opts.debug; + options.filename = opts.filename; + options.openDelimiter = opts.openDelimiter || exports.openDelimiter || _DEFAULT_OPEN_DELIMITER; + options.closeDelimiter = opts.closeDelimiter || exports.closeDelimiter || _DEFAULT_CLOSE_DELIMITER; + options.delimiter = opts.delimiter || exports.delimiter || _DEFAULT_DELIMITER; + options.strict = opts.strict || false; + options.context = opts.context; + options.cache = opts.cache || false; + options.rmWhitespace = opts.rmWhitespace; + options.root = opts.root; + options.includer = opts.includer; + options.outputFunctionName = opts.outputFunctionName; + options.localsName = opts.localsName || exports.localsName || _DEFAULT_LOCALS_NAME; + options.views = opts.views; + options.async = opts.async; + options.destructuredLocals = opts.destructuredLocals; + options.legacyInclude = typeof opts.legacyInclude != 'undefined' ? !!opts.legacyInclude : true; + + if (options.strict) { + options._with = false; + } + else { + options._with = typeof opts._with != 'undefined' ? opts._with : true; + } + + this.opts = options; + + this.regex = this.createRegex(); +} + +Template.modes = { + EVAL: 'eval', + ESCAPED: 'escaped', + RAW: 'raw', + COMMENT: 'comment', + LITERAL: 'literal' +}; + +Template.prototype = { + createRegex: function () { + var str = _REGEX_STRING; + var delim = utils.escapeRegExpChars(this.opts.delimiter); + var open = utils.escapeRegExpChars(this.opts.openDelimiter); + var close = utils.escapeRegExpChars(this.opts.closeDelimiter); + str = str.replace(/%/g, delim) + .replace(//g, close); + return new RegExp(str); + }, + + compile: function () { + /** @type {string} */ + var src; + /** @type {ClientFunction} */ + var fn; + var opts = this.opts; + var prepended = ''; + var appended = ''; + /** @type {EscapeCallback} */ + var escapeFn = opts.escapeFunction; + /** @type {FunctionConstructor} */ + var ctor; + /** @type {string} */ + var sanitizedFilename = opts.filename ? JSON.stringify(opts.filename) : 'undefined'; + + if (!this.source) { + this.generateSource(); + prepended += + ' var __output = "";\n' + + ' function __append(s) { if (s !== undefined && s !== null) __output += s }\n'; + if (opts.outputFunctionName) { + if (!_JS_IDENTIFIER.test(opts.outputFunctionName)) { + throw new Error('outputFunctionName is not a valid JS identifier.'); + } + prepended += ' var ' + opts.outputFunctionName + ' = __append;' + '\n'; + } + if (opts.localsName && !_JS_IDENTIFIER.test(opts.localsName)) { + throw new Error('localsName is not a valid JS identifier.'); + } + if (opts.destructuredLocals && opts.destructuredLocals.length) { + var destructuring = ' var __locals = (' + opts.localsName + ' || {}),\n'; + for (var i = 0; i < opts.destructuredLocals.length; i++) { + var name = opts.destructuredLocals[i]; + if (!_JS_IDENTIFIER.test(name)) { + throw new Error('destructuredLocals[' + i + '] is not a valid JS identifier.'); + } + if (i > 0) { + destructuring += ',\n '; + } + destructuring += name + ' = __locals.' + name; + } + prepended += destructuring + ';\n'; + } + if (opts._with !== false) { + prepended += ' with (' + opts.localsName + ' || {}) {' + '\n'; + appended += ' }' + '\n'; + } + appended += ' return __output;' + '\n'; + this.source = prepended + this.source + appended; + } + + if (opts.compileDebug) { + src = 'var __line = 1' + '\n' + + ' , __lines = ' + JSON.stringify(this.templateText) + '\n' + + ' , __filename = ' + sanitizedFilename + ';' + '\n' + + 'try {' + '\n' + + this.source + + '} catch (e) {' + '\n' + + ' rethrow(e, __lines, __filename, __line, escapeFn);' + '\n' + + '}' + '\n'; + } + else { + src = this.source; + } + + if (opts.client) { + src = 'escapeFn = escapeFn || ' + escapeFn.toString() + ';' + '\n' + src; + if (opts.compileDebug) { + src = 'rethrow = rethrow || ' + rethrow.toString() + ';' + '\n' + src; + } + } + + if (opts.strict) { + src = '"use strict";\n' + src; + } + if (opts.debug) { + console.log(src); + } + if (opts.compileDebug && opts.filename) { + src = src + '\n' + + '//# sourceURL=' + sanitizedFilename + '\n'; + } + + try { + if (opts.async) { + // Have to use generated function for this, since in envs without support, + // it breaks in parsing + try { + ctor = (new Function('return (async function(){}).constructor;'))(); + } + catch(e) { + if (e instanceof SyntaxError) { + throw new Error('This environment does not support async/await'); + } + else { + throw e; + } + } + } + else { + ctor = Function; + } + fn = new ctor(opts.localsName + ', escapeFn, include, rethrow', src); + } + catch(e) { + // istanbul ignore else + if (e instanceof SyntaxError) { + if (opts.filename) { + e.message += ' in ' + opts.filename; + } + e.message += ' while compiling ejs\n\n'; + e.message += 'If the above error is not helpful, you may want to try EJS-Lint:\n'; + e.message += 'https://github.com/RyanZim/EJS-Lint'; + if (!opts.async) { + e.message += '\n'; + e.message += 'Or, if you meant to create an async function, pass `async: true` as an option.'; + } + } + throw e; + } + + // Return a callable function which will execute the function + // created by the source-code, with the passed data as locals + // Adds a local `include` function which allows full recursive include + var returnedFn = opts.client ? fn : function anonymous(data) { + var include = function (path, includeData) { + var d = utils.shallowCopy(utils.createNullProtoObjWherePossible(), data); + if (includeData) { + d = utils.shallowCopy(d, includeData); + } + return includeFile(path, opts)(d); + }; + return fn.apply(opts.context, + [data || utils.createNullProtoObjWherePossible(), escapeFn, include, rethrow]); + }; + if (opts.filename && typeof Object.defineProperty === 'function') { + var filename = opts.filename; + var basename = path.basename(filename, path.extname(filename)); + try { + Object.defineProperty(returnedFn, 'name', { + value: basename, + writable: false, + enumerable: false, + configurable: true + }); + } catch (e) {/* ignore */} + } + return returnedFn; + }, + + generateSource: function () { + var opts = this.opts; + + if (opts.rmWhitespace) { + // Have to use two separate replace here as `^` and `$` operators don't + // work well with `\r` and empty lines don't work well with the `m` flag. + this.templateText = + this.templateText.replace(/[\r\n]+/g, '\n').replace(/^\s+|\s+$/gm, ''); + } + + // Slurp spaces and tabs before <%_ and after _%> + this.templateText = + this.templateText.replace(/[ \t]*<%_/gm, '<%_').replace(/_%>[ \t]*/gm, '_%>'); + + var self = this; + var matches = this.parseTemplateText(); + var d = this.opts.delimiter; + var o = this.opts.openDelimiter; + var c = this.opts.closeDelimiter; + + if (matches && matches.length) { + matches.forEach(function (line, index) { + var closing; + // If this is an opening tag, check for closing tags + // FIXME: May end up with some false positives here + // Better to store modes as k/v with openDelimiter + delimiter as key + // Then this can simply check against the map + if ( line.indexOf(o + d) === 0 // If it is a tag + && line.indexOf(o + d + d) !== 0) { // and is not escaped + closing = matches[index + 2]; + if (!(closing == d + c || closing == '-' + d + c || closing == '_' + d + c)) { + throw new Error('Could not find matching close tag for "' + line + '".'); + } + } + self.scanLine(line); + }); + } + + }, + + parseTemplateText: function () { + var str = this.templateText; + var pat = this.regex; + var result = pat.exec(str); + var arr = []; + var firstPos; + + while (result) { + firstPos = result.index; + + if (firstPos !== 0) { + arr.push(str.substring(0, firstPos)); + str = str.slice(firstPos); + } + + arr.push(result[0]); + str = str.slice(result[0].length); + result = pat.exec(str); + } + + if (str) { + arr.push(str); + } + + return arr; + }, + + _addOutput: function (line) { + if (this.truncate) { + // Only replace single leading linebreak in the line after + // -%> tag -- this is the single, trailing linebreak + // after the tag that the truncation mode replaces + // Handle Win / Unix / old Mac linebreaks -- do the \r\n + // combo first in the regex-or + line = line.replace(/^(?:\r\n|\r|\n)/, ''); + this.truncate = false; + } + if (!line) { + return line; + } + + // Preserve literal slashes + line = line.replace(/\\/g, '\\\\'); + + // Convert linebreaks + line = line.replace(/\n/g, '\\n'); + line = line.replace(/\r/g, '\\r'); + + // Escape double-quotes + // - this will be the delimiter during execution + line = line.replace(/"/g, '\\"'); + this.source += ' ; __append("' + line + '")' + '\n'; + }, + + scanLine: function (line) { + var self = this; + var d = this.opts.delimiter; + var o = this.opts.openDelimiter; + var c = this.opts.closeDelimiter; + var newLineCount = 0; + + newLineCount = (line.split('\n').length - 1); + + switch (line) { + case o + d: + case o + d + '_': + this.mode = Template.modes.EVAL; + break; + case o + d + '=': + this.mode = Template.modes.ESCAPED; + break; + case o + d + '-': + this.mode = Template.modes.RAW; + break; + case o + d + '#': + this.mode = Template.modes.COMMENT; + break; + case o + d + d: + this.mode = Template.modes.LITERAL; + this.source += ' ; __append("' + line.replace(o + d + d, o + d) + '")' + '\n'; + break; + case d + d + c: + this.mode = Template.modes.LITERAL; + this.source += ' ; __append("' + line.replace(d + d + c, d + c) + '")' + '\n'; + break; + case d + c: + case '-' + d + c: + case '_' + d + c: + if (this.mode == Template.modes.LITERAL) { + this._addOutput(line); + } + + this.mode = null; + this.truncate = line.indexOf('-') === 0 || line.indexOf('_') === 0; + break; + default: + // In script mode, depends on type of tag + if (this.mode) { + // If '//' is found without a line break, add a line break. + switch (this.mode) { + case Template.modes.EVAL: + case Template.modes.ESCAPED: + case Template.modes.RAW: + if (line.lastIndexOf('//') > line.lastIndexOf('\n')) { + line += '\n'; + } + } + switch (this.mode) { + // Just executing code + case Template.modes.EVAL: + this.source += ' ; ' + line + '\n'; + break; + // Exec, esc, and output + case Template.modes.ESCAPED: + this.source += ' ; __append(escapeFn(' + stripSemi(line) + '))' + '\n'; + break; + // Exec and output + case Template.modes.RAW: + this.source += ' ; __append(' + stripSemi(line) + ')' + '\n'; + break; + case Template.modes.COMMENT: + // Do nothing + break; + // Literal <%% mode, append as raw output + case Template.modes.LITERAL: + this._addOutput(line); + break; + } + } + // In string mode, just add the output + else { + this._addOutput(line); + } + } + + if (self.opts.compileDebug && newLineCount) { + this.currentLine += newLineCount; + this.source += ' ; __line = ' + this.currentLine + '\n'; + } + } +}; + +/** + * Escape characters reserved in XML. + * + * This is simply an export of {@link module:utils.escapeXML}. + * + * If `markup` is `undefined` or `null`, the empty string is returned. + * + * @param {String} markup Input string + * @return {String} Escaped string + * @public + * @func + * */ +exports.escapeXML = utils.escapeXML; + +/** + * Express.js support. + * + * This is an alias for {@link module:ejs.renderFile}, in order to support + * Express.js out-of-the-box. + * + * @func + */ + +exports.__express = exports.renderFile; + +/** + * Version of EJS. + * + * @readonly + * @type {String} + * @public + */ + +exports.VERSION = _VERSION_STRING; + +/** + * Name for detection of EJS. + * + * @readonly + * @type {String} + * @public + */ + +exports.name = _NAME; + +/* istanbul ignore if */ +if (typeof window != 'undefined') { + window.ejs = exports; +} + diff --git a/node_modules/ejs/lib/utils.js b/node_modules/ejs/lib/utils.js new file mode 100644 index 0000000..396edb3 --- /dev/null +++ b/node_modules/ejs/lib/utils.js @@ -0,0 +1,250 @@ +/* + * EJS Embedded JavaScript templates + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +/** + * Private utility functions + * @module utils + * @private + */ + +'use strict'; + +var regExpChars = /[|\\{}()[\]^$+*?.]/g; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var hasOwn = function (obj, key) { return hasOwnProperty.apply(obj, [key]); }; + +/** + * Escape characters reserved in regular expressions. + * + * If `string` is `undefined` or `null`, the empty string is returned. + * + * @param {String} string Input string + * @return {String} Escaped string + * @static + * @private + */ +exports.escapeRegExpChars = function (string) { + // istanbul ignore if + if (!string) { + return ''; + } + return String(string).replace(regExpChars, '\\$&'); +}; + +var _ENCODE_HTML_RULES = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' +}; +var _MATCH_HTML = /[&<>'"]/g; + +function encode_char(c) { + return _ENCODE_HTML_RULES[c] || c; +} + +/** + * Stringified version of constants used by {@link module:utils.escapeXML}. + * + * It is used in the process of generating {@link ClientFunction}s. + * + * @readonly + * @type {String} + */ + +var escapeFuncStr = + 'var _ENCODE_HTML_RULES = {\n' ++ ' "&": "&"\n' ++ ' , "<": "<"\n' ++ ' , ">": ">"\n' ++ ' , \'"\': """\n' ++ ' , "\'": "'"\n' ++ ' }\n' ++ ' , _MATCH_HTML = /[&<>\'"]/g;\n' ++ 'function encode_char(c) {\n' ++ ' return _ENCODE_HTML_RULES[c] || c;\n' ++ '};\n'; + +/** + * Escape characters reserved in XML. + * + * If `markup` is `undefined` or `null`, the empty string is returned. + * + * @implements {EscapeCallback} + * @param {String} markup Input string + * @return {String} Escaped string + * @static + * @private + */ + +exports.escapeXML = function (markup) { + return markup == undefined + ? '' + : String(markup) + .replace(_MATCH_HTML, encode_char); +}; + +function escapeXMLToString() { + return Function.prototype.toString.call(this) + ';\n' + escapeFuncStr; +} + +try { + if (typeof Object.defineProperty === 'function') { + // If the Function prototype is frozen, the "toString" property is non-writable. This means that any objects which inherit this property + // cannot have the property changed using an assignment. If using strict mode, attempting that will cause an error. If not using strict + // mode, attempting that will be silently ignored. + // However, we can still explicitly shadow the prototype's "toString" property by defining a new "toString" property on this object. + Object.defineProperty(exports.escapeXML, 'toString', { value: escapeXMLToString }); + } else { + // If Object.defineProperty() doesn't exist, attempt to shadow this property using the assignment operator. + exports.escapeXML.toString = escapeXMLToString; + } +} catch (err) { + console.warn('Unable to set escapeXML.toString (is the Function prototype frozen?)'); +} + +/** + * Naive copy of properties from one object to another. + * Does not recurse into non-scalar properties + * Does not check to see if the property has a value before copying + * + * @param {Object} to Destination object + * @param {Object} from Source object + * @return {Object} Destination object + * @static + * @private + */ +exports.shallowCopy = function (to, from) { + from = from || {}; + if ((to !== null) && (to !== undefined)) { + for (var p in from) { + if (!hasOwn(from, p)) { + continue; + } + if (p === '__proto__' || p === 'constructor') { + continue; + } + to[p] = from[p]; + } + } + return to; +}; + +/** + * Naive copy of a list of key names, from one object to another. + * Only copies property if it is actually defined + * Does not recurse into non-scalar properties + * + * @param {Object} to Destination object + * @param {Object} from Source object + * @param {Array} list List of properties to copy + * @return {Object} Destination object + * @static + * @private + */ +exports.shallowCopyFromList = function (to, from, list) { + list = list || []; + from = from || {}; + if ((to !== null) && (to !== undefined)) { + for (var i = 0; i < list.length; i++) { + var p = list[i]; + if (typeof from[p] != 'undefined') { + if (!hasOwn(from, p)) { + continue; + } + if (p === '__proto__' || p === 'constructor') { + continue; + } + to[p] = from[p]; + } + } + } + return to; +}; + +/** + * Simple in-process cache implementation. Does not implement limits of any + * sort. + * + * @implements {Cache} + * @static + * @private + */ +exports.cache = { + _data: {}, + set: function (key, val) { + this._data[key] = val; + }, + get: function (key) { + return this._data[key]; + }, + remove: function (key) { + delete this._data[key]; + }, + reset: function () { + this._data = {}; + } +}; + +/** + * Transforms hyphen case variable into camel case. + * + * @param {String} string Hyphen case string + * @return {String} Camel case string + * @static + * @private + */ +exports.hyphenToCamel = function (str) { + return str.replace(/-[a-z]/g, function (match) { return match[1].toUpperCase(); }); +}; + +/** + * Returns a null-prototype object in runtimes that support it + * + * @return {Object} Object, prototype will be set to null where possible + * @static + * @private + */ +exports.createNullProtoObjWherePossible = (function () { + if (typeof Object.create == 'function') { + return function () { + return Object.create(null); + }; + } + if (!({__proto__: null} instanceof Object)) { + return function () { + return {__proto__: null}; + }; + } + // Not possible, just pass through + return function () { + return {}; + }; +})(); + +exports.hasOwnOnlyObject = function (obj) { + var o = exports.createNullProtoObjWherePossible(); + for (var p in obj) { + if (hasOwn(obj, p)) { + o[p] = obj[p]; + } + } + return o; +}; + diff --git a/node_modules/ejs/package.json b/node_modules/ejs/package.json new file mode 100644 index 0000000..a229989 --- /dev/null +++ b/node_modules/ejs/package.json @@ -0,0 +1,42 @@ +{ + "name": "ejs", + "description": "Embedded JavaScript templates", + "keywords": [ + "template", + "engine", + "ejs" + ], + "version": "3.1.10", + "author": "Matthew Eernisse (http://fleegix.org)", + "license": "Apache-2.0", + "bin": { + "ejs": "./bin/cli.js" + }, + "main": "./lib/ejs.js", + "jsdelivr": "ejs.min.js", + "unpkg": "ejs.min.js", + "repository": { + "type": "git", + "url": "git://github.com/mde/ejs.git" + }, + "bugs": "https://github.com/mde/ejs/issues", + "homepage": "https://github.com/mde/ejs", + "dependencies": { + "jake": "^10.8.5" + }, + "devDependencies": { + "browserify": "^16.5.1", + "eslint": "^6.8.0", + "git-directory-deploy": "^1.5.1", + "jsdoc": "^4.0.2", + "lru-cache": "^4.0.1", + "mocha": "^10.2.0", + "uglify-js": "^3.3.16" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "npx jake test" + } +} diff --git a/node_modules/ejs/usage.txt b/node_modules/ejs/usage.txt new file mode 100644 index 0000000..7469f7f --- /dev/null +++ b/node_modules/ejs/usage.txt @@ -0,0 +1,24 @@ +EJS Embedded JavaScript templates +{Usage}: ejs [options ...] template-file [data variables ...] + +{Options}: + -o, --output-file FILE Write the rendered output to FILE rather than stdout. + -f, --data-file FILE Must be JSON-formatted. Use parsed input from FILE as data for rendering. + -i, --data-input STRING Must be JSON-formatted and URI-encoded. Use parsed input from STRING as data for rendering. + -m, --delimiter CHARACTER Use CHARACTER with angle brackets for open/close (defaults to %). + -p, --open-delimiter CHARACTER Use CHARACTER instead of left angle bracket to open. + -c, --close-delimiter CHARACTER Use CHARACTER instead of right angle bracket to close. + -s, --strict When set to `true`, generated function is in strict mode + -n --no-with Use 'locals' object for vars rather than using `with` (implies --strict). + -l --locals-name Name to use for the object storing local variables when not using `with`. + -w --rm-whitespace Remove all safe-to-remove whitespace, including leading and trailing whitespace. + -d --debug Outputs generated function body + -h, --help Display this help message. + -V/v, --version Display the EJS version. + +{Examples}: + ejs -m $ ./test/fixtures/user.ejs -f ./user_data.json + ejs -m $ ./test/fixtures/user.ejs name=Lerxst + ejs -p [ -c ] ./template_file.ejs -o ./output.html + ejs -n -l _ ./some_template.ejs -f ./data_file.json + ejs -w ./template_with_whitspace.ejs -o ./output_file.html diff --git a/node_modules/encodeurl/LICENSE b/node_modules/encodeurl/LICENSE new file mode 100644 index 0000000..8812229 --- /dev/null +++ b/node_modules/encodeurl/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2016 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/encodeurl/README.md b/node_modules/encodeurl/README.md new file mode 100644 index 0000000..3842493 --- /dev/null +++ b/node_modules/encodeurl/README.md @@ -0,0 +1,109 @@ +# Encode URL + +Encode a URL to a percent-encoded form, excluding already-encoded sequences. + +## Installation + +```sh +npm install encodeurl +``` + +## API + +```js +var encodeUrl = require('encodeurl') +``` + +### encodeUrl(url) + +Encode a URL to a percent-encoded form, excluding already-encoded sequences. + +This function accepts a URL and encodes all the non-URL code points (as UTF-8 byte sequences). It will not encode the "%" character unless it is not part of a valid sequence (`%20` will be left as-is, but `%foo` will be encoded as `%25foo`). + +This encode is meant to be "safe" and does not throw errors. It will try as hard as it can to properly encode the given URL, including replacing any raw, unpaired surrogate pairs with the Unicode replacement character prior to encoding. + +## Examples + +### Encode a URL containing user-controlled data + +```js +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') + +http.createServer(function onRequest (req, res) { + // get encoded form of inbound url + var url = encodeUrl(req.url) + + // create html message + var body = '

Location ' + escapeHtml(url) + ' not found

' + + // send a 404 + res.statusCode = 404 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', String(Buffer.byteLength(body, 'utf-8'))) + res.end(body, 'utf-8') +}) +``` + +### Encode a URL for use in a header field + +```js +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') +var url = require('url') + +http.createServer(function onRequest (req, res) { + // parse inbound url + var href = url.parse(req) + + // set new host for redirect + href.host = 'localhost' + href.protocol = 'https:' + href.slashes = true + + // create location header + var location = encodeUrl(url.format(href)) + + // create html message + var body = '

Redirecting to new site: ' + escapeHtml(location) + '

' + + // send a 301 + res.statusCode = 301 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', String(Buffer.byteLength(body, 'utf-8'))) + res.setHeader('Location', location) + res.end(body, 'utf-8') +}) +``` + +## Similarities + +This function is _similar_ to the intrinsic function `encodeURI`. However, it will not encode: + +* The `\`, `^`, or `|` characters +* The `%` character when it's part of a valid sequence +* `[` and `]` (for IPv6 hostnames) +* Replaces raw, unpaired surrogate pairs with the Unicode replacement character + +As a result, the encoding aligns closely with the behavior in the [WHATWG URL specification][whatwg-url]. However, this package only encodes strings and does not do any URL parsing or formatting. + +It is expected that any output from `new URL(url)` will not change when used with this package, as the output has already been encoded. Additionally, if we were to encode before `new URL(url)`, we do not expect the before and after encoded formats to be parsed any differently. + +## Testing + +```sh +$ npm test +$ npm run lint +``` + +## References + +- [RFC 3986: Uniform Resource Identifier (URI): Generic Syntax][rfc-3986] +- [WHATWG URL Living Standard][whatwg-url] + +[rfc-3986]: https://tools.ietf.org/html/rfc3986 +[whatwg-url]: https://url.spec.whatwg.org/ + +## License + +[MIT](LICENSE) diff --git a/node_modules/encodeurl/index.js b/node_modules/encodeurl/index.js new file mode 100644 index 0000000..a49ee5a --- /dev/null +++ b/node_modules/encodeurl/index.js @@ -0,0 +1,60 @@ +/*! + * encodeurl + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = encodeUrl + +/** + * RegExp to match non-URL code points, *after* encoding (i.e. not including "%") + * and including invalid escape sequences. + * @private + */ + +var ENCODE_CHARS_REGEXP = /(?:[^\x21\x23-\x3B\x3D\x3F-\x5F\x61-\x7A\x7C\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g + +/** + * RegExp to match unmatched surrogate pair. + * @private + */ + +var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g + +/** + * String to replace unmatched surrogate pair with. + * @private + */ + +var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2' + +/** + * Encode a URL to a percent-encoded form, excluding already-encoded sequences. + * + * This function will take an already-encoded URL and encode all the non-URL + * code points. This function will not encode the "%" character unless it is + * not part of a valid sequence (`%20` will be left as-is, but `%foo` will + * be encoded as `%25foo`). + * + * This encode is meant to be "safe" and does not throw errors. It will try as + * hard as it can to properly encode the given URL, including replacing any raw, + * unpaired surrogate pairs with the Unicode replacement character prior to + * encoding. + * + * @param {string} url + * @return {string} + * @public + */ + +function encodeUrl (url) { + return String(url) + .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE) + .replace(ENCODE_CHARS_REGEXP, encodeURI) +} diff --git a/node_modules/encodeurl/package.json b/node_modules/encodeurl/package.json new file mode 100644 index 0000000..3133822 --- /dev/null +++ b/node_modules/encodeurl/package.json @@ -0,0 +1,40 @@ +{ + "name": "encodeurl", + "description": "Encode a URL to a percent-encoded form, excluding already-encoded sequences", + "version": "2.0.0", + "contributors": [ + "Douglas Christopher Wilson " + ], + "license": "MIT", + "keywords": [ + "encode", + "encodeurl", + "url" + ], + "repository": "pillarjs/encodeurl", + "devDependencies": { + "eslint": "5.11.1", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.14.0", + "eslint-plugin-node": "7.0.1", + "eslint-plugin-promise": "4.0.1", + "eslint-plugin-standard": "4.0.0", + "istanbul": "0.4.5", + "mocha": "2.5.3" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/node_modules/es-define-property/.eslintrc b/node_modules/es-define-property/.eslintrc new file mode 100644 index 0000000..46f3b12 --- /dev/null +++ b/node_modules/es-define-property/.eslintrc @@ -0,0 +1,13 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "new-cap": ["error", { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, +} diff --git a/node_modules/es-define-property/.github/FUNDING.yml b/node_modules/es-define-property/.github/FUNDING.yml new file mode 100644 index 0000000..4445451 --- /dev/null +++ b/node_modules/es-define-property/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/es-define-property +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/es-define-property/.nycrc b/node_modules/es-define-property/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/es-define-property/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/es-define-property/CHANGELOG.md b/node_modules/es-define-property/CHANGELOG.md new file mode 100644 index 0000000..5f60cc0 --- /dev/null +++ b/node_modules/es-define-property/CHANGELOG.md @@ -0,0 +1,29 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.1](https://github.com/ljharb/es-define-property/compare/v1.0.0...v1.0.1) - 2024-12-06 + +### Commits + +- [types] use shared tsconfig [`954a663`](https://github.com/ljharb/es-define-property/commit/954a66360326e508a0e5daa4b07493d58f5e110e) +- [actions] split out node 10-20, and 20+ [`3a8e84b`](https://github.com/ljharb/es-define-property/commit/3a8e84b23883f26ff37b3e82ff283834228e18c6) +- [Dev Deps] update `@ljharb/eslint-config`, `@ljharb/tsconfig`, `@types/get-intrinsic`, `@types/tape`, `auto-changelog`, `gopd`, `tape` [`86ae27b`](https://github.com/ljharb/es-define-property/commit/86ae27bb8cc857b23885136fad9cbe965ae36612) +- [Refactor] avoid using `get-intrinsic` [`02480c0`](https://github.com/ljharb/es-define-property/commit/02480c0353ef6118965282977c3864aff53d98b1) +- [Tests] replace `aud` with `npm audit` [`f6093ff`](https://github.com/ljharb/es-define-property/commit/f6093ff74ab51c98015c2592cd393bd42478e773) +- [Tests] configure testling [`7139e66`](https://github.com/ljharb/es-define-property/commit/7139e66959247a56086d9977359caef27c6849e7) +- [Dev Deps] update `tape` [`b901b51`](https://github.com/ljharb/es-define-property/commit/b901b511a75e001a40ce1a59fef7d9ffcfc87482) +- [Tests] fix types in tests [`469d269`](https://github.com/ljharb/es-define-property/commit/469d269fd141b1e773ec053a9fa35843493583e0) +- [Dev Deps] add missing peer dep [`733acfb`](https://github.com/ljharb/es-define-property/commit/733acfb0c4c96edf337e470b89a25a5b3724c352) + +## v1.0.0 - 2024-02-12 + +### Commits + +- Initial implementation, tests, readme, types [`3e154e1`](https://github.com/ljharb/es-define-property/commit/3e154e11a2fee09127220f5e503bf2c0a31dd480) +- Initial commit [`07d98de`](https://github.com/ljharb/es-define-property/commit/07d98de34a4dc31ff5e83a37c0c3f49e0d85cd50) +- npm init [`c4eb634`](https://github.com/ljharb/es-define-property/commit/c4eb6348b0d3886aac36cef34ad2ee0665ea6f3e) +- Only apps should have lockfiles [`7af86ec`](https://github.com/ljharb/es-define-property/commit/7af86ec1d311ec0b17fdfe616a25f64276903856) diff --git a/node_modules/es-define-property/LICENSE b/node_modules/es-define-property/LICENSE new file mode 100644 index 0000000..f82f389 --- /dev/null +++ b/node_modules/es-define-property/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/es-define-property/README.md b/node_modules/es-define-property/README.md new file mode 100644 index 0000000..9b291bd --- /dev/null +++ b/node_modules/es-define-property/README.md @@ -0,0 +1,49 @@ +# es-define-property [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +`Object.defineProperty`, but not IE 8's broken one. + +## Example + +```js +const assert = require('assert'); + +const $defineProperty = require('es-define-property'); + +if ($defineProperty) { + assert.equal($defineProperty, Object.defineProperty); +} else if (Object.defineProperty) { + assert.equal($defineProperty, false, 'this is IE 8'); +} else { + assert.equal($defineProperty, false, 'this is an ES3 engine'); +} +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +[package-url]: https://npmjs.org/package/es-define-property +[npm-version-svg]: https://versionbadg.es/ljharb/es-define-property.svg +[deps-svg]: https://david-dm.org/ljharb/es-define-property.svg +[deps-url]: https://david-dm.org/ljharb/es-define-property +[dev-deps-svg]: https://david-dm.org/ljharb/es-define-property/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/es-define-property#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/es-define-property.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/es-define-property.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/es-define-property.svg +[downloads-url]: https://npm-stat.com/charts.html?package=es-define-property +[codecov-image]: https://codecov.io/gh/ljharb/es-define-property/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/es-define-property/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/es-define-property +[actions-url]: https://github.com/ljharb/es-define-property/actions diff --git a/node_modules/es-define-property/index.d.ts b/node_modules/es-define-property/index.d.ts new file mode 100644 index 0000000..6012247 --- /dev/null +++ b/node_modules/es-define-property/index.d.ts @@ -0,0 +1,3 @@ +declare const defineProperty: false | typeof Object.defineProperty; + +export = defineProperty; \ No newline at end of file diff --git a/node_modules/es-define-property/index.js b/node_modules/es-define-property/index.js new file mode 100644 index 0000000..e0a2925 --- /dev/null +++ b/node_modules/es-define-property/index.js @@ -0,0 +1,14 @@ +'use strict'; + +/** @type {import('.')} */ +var $defineProperty = Object.defineProperty || false; +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = false; + } +} + +module.exports = $defineProperty; diff --git a/node_modules/es-define-property/package.json b/node_modules/es-define-property/package.json new file mode 100644 index 0000000..fbed187 --- /dev/null +++ b/node_modules/es-define-property/package.json @@ -0,0 +1,81 @@ +{ + "name": "es-define-property", + "version": "1.0.1", + "description": "`Object.defineProperty`, but not IE 8's broken one.", + "main": "index.js", + "types": "./index.d.ts", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>= 10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/es-define-property.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "object", + "define", + "property", + "defineProperty", + "Object.defineProperty" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/es-define-property/issues" + }, + "homepage": "https://github.com/ljharb/es-define-property#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.2", + "@types/gopd": "^1.0.3", + "@types/tape": "^5.6.5", + "auto-changelog": "^2.5.0", + "encoding": "^0.1.13", + "eslint": "^8.8.0", + "evalmd": "^0.0.19", + "gopd": "^1.2.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/es-define-property/test/index.js b/node_modules/es-define-property/test/index.js new file mode 100644 index 0000000..b4b4688 --- /dev/null +++ b/node_modules/es-define-property/test/index.js @@ -0,0 +1,56 @@ +'use strict'; + +var $defineProperty = require('../'); + +var test = require('tape'); +var gOPD = require('gopd'); + +test('defineProperty: supported', { skip: !$defineProperty }, function (t) { + t.plan(4); + + t.equal(typeof $defineProperty, 'function', 'defineProperty is supported'); + if ($defineProperty && gOPD) { // this `if` check is just to shut TS up + /** @type {{ a: number, b?: number, c?: number }} */ + var o = { a: 1 }; + + $defineProperty(o, 'b', { enumerable: true, value: 2 }); + t.deepEqual( + gOPD(o, 'b'), + { + configurable: false, + enumerable: true, + value: 2, + writable: false + }, + 'property descriptor is as expected' + ); + + $defineProperty(o, 'c', { enumerable: false, value: 3, writable: true }); + t.deepEqual( + gOPD(o, 'c'), + { + configurable: false, + enumerable: false, + value: 3, + writable: true + }, + 'property descriptor is as expected' + ); + } + + t.equal($defineProperty, Object.defineProperty, 'defineProperty is Object.defineProperty'); + + t.end(); +}); + +test('defineProperty: not supported', { skip: !!$defineProperty }, function (t) { + t.notOk($defineProperty, 'defineProperty is not supported'); + + t.match( + typeof $defineProperty, + /^(?:undefined|boolean)$/, + '`typeof defineProperty` is `undefined` or `boolean`' + ); + + t.end(); +}); diff --git a/node_modules/es-define-property/tsconfig.json b/node_modules/es-define-property/tsconfig.json new file mode 100644 index 0000000..5a49992 --- /dev/null +++ b/node_modules/es-define-property/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2022", + }, + "exclude": [ + "coverage", + "test/list-exports" + ], +} diff --git a/node_modules/es-errors/.eslintrc b/node_modules/es-errors/.eslintrc new file mode 100644 index 0000000..3b5d9e9 --- /dev/null +++ b/node_modules/es-errors/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/node_modules/es-errors/.github/FUNDING.yml b/node_modules/es-errors/.github/FUNDING.yml new file mode 100644 index 0000000..f1b8805 --- /dev/null +++ b/node_modules/es-errors/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/es-errors +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/es-errors/CHANGELOG.md b/node_modules/es-errors/CHANGELOG.md new file mode 100644 index 0000000..204a9e9 --- /dev/null +++ b/node_modules/es-errors/CHANGELOG.md @@ -0,0 +1,40 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.3.0](https://github.com/ljharb/es-errors/compare/v1.2.1...v1.3.0) - 2024-02-05 + +### Commits + +- [New] add `EvalError` and `URIError` [`1927627`](https://github.com/ljharb/es-errors/commit/1927627ba68cb6c829d307231376c967db53acdf) + +## [v1.2.1](https://github.com/ljharb/es-errors/compare/v1.2.0...v1.2.1) - 2024-02-04 + +### Commits + +- [Fix] add missing `exports` entry [`5bb5f28`](https://github.com/ljharb/es-errors/commit/5bb5f280f98922701109d6ebb82eea2257cecc7e) + +## [v1.2.0](https://github.com/ljharb/es-errors/compare/v1.1.0...v1.2.0) - 2024-02-04 + +### Commits + +- [New] add `ReferenceError` [`6d8cf5b`](https://github.com/ljharb/es-errors/commit/6d8cf5bbb6f3f598d02cf6f30e468ba2caa8e143) + +## [v1.1.0](https://github.com/ljharb/es-errors/compare/v1.0.0...v1.1.0) - 2024-02-04 + +### Commits + +- [New] add base Error [`2983ab6`](https://github.com/ljharb/es-errors/commit/2983ab65f7bc5441276cb021dc3aa03c78881698) + +## v1.0.0 - 2024-02-03 + +### Commits + +- Initial implementation, tests, readme, type [`8f47631`](https://github.com/ljharb/es-errors/commit/8f476317e9ad76f40ad648081829b1a1a3a1288b) +- Initial commit [`ea5d099`](https://github.com/ljharb/es-errors/commit/ea5d099ef18e550509ab9e2be000526afd81c385) +- npm init [`6f5ebf9`](https://github.com/ljharb/es-errors/commit/6f5ebf9cead474dadd72b9e63dad315820a089ae) +- Only apps should have lockfiles [`e1a0aeb`](https://github.com/ljharb/es-errors/commit/e1a0aeb7b80f5cfc56be54d6b2100e915d47def8) +- [meta] add `sideEffects` flag [`a9c7d46`](https://github.com/ljharb/es-errors/commit/a9c7d460a492f1d8a241c836bc25a322a19cc043) diff --git a/node_modules/es-errors/LICENSE b/node_modules/es-errors/LICENSE new file mode 100644 index 0000000..f82f389 --- /dev/null +++ b/node_modules/es-errors/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/es-errors/README.md b/node_modules/es-errors/README.md new file mode 100644 index 0000000..8dbfacf --- /dev/null +++ b/node_modules/es-errors/README.md @@ -0,0 +1,55 @@ +# es-errors [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +A simple cache for a few of the JS Error constructors. + +## Example + +```js +const assert = require('assert'); + +const Base = require('es-errors'); +const Eval = require('es-errors/eval'); +const Range = require('es-errors/range'); +const Ref = require('es-errors/ref'); +const Syntax = require('es-errors/syntax'); +const Type = require('es-errors/type'); +const URI = require('es-errors/uri'); + +assert.equal(Base, Error); +assert.equal(Eval, EvalError); +assert.equal(Range, RangeError); +assert.equal(Ref, ReferenceError); +assert.equal(Syntax, SyntaxError); +assert.equal(Type, TypeError); +assert.equal(URI, URIError); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +[package-url]: https://npmjs.org/package/es-errors +[npm-version-svg]: https://versionbadg.es/ljharb/es-errors.svg +[deps-svg]: https://david-dm.org/ljharb/es-errors.svg +[deps-url]: https://david-dm.org/ljharb/es-errors +[dev-deps-svg]: https://david-dm.org/ljharb/es-errors/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/es-errors#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/es-errors.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/es-errors.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/es-errors.svg +[downloads-url]: https://npm-stat.com/charts.html?package=es-errors +[codecov-image]: https://codecov.io/gh/ljharb/es-errors/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/es-errors/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/es-errors +[actions-url]: https://github.com/ljharb/es-errors/actions diff --git a/node_modules/es-errors/eval.d.ts b/node_modules/es-errors/eval.d.ts new file mode 100644 index 0000000..e4210e0 --- /dev/null +++ b/node_modules/es-errors/eval.d.ts @@ -0,0 +1,3 @@ +declare const EvalError: EvalErrorConstructor; + +export = EvalError; diff --git a/node_modules/es-errors/eval.js b/node_modules/es-errors/eval.js new file mode 100644 index 0000000..725ccb6 --- /dev/null +++ b/node_modules/es-errors/eval.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./eval')} */ +module.exports = EvalError; diff --git a/node_modules/es-errors/index.d.ts b/node_modules/es-errors/index.d.ts new file mode 100644 index 0000000..69bdbc9 --- /dev/null +++ b/node_modules/es-errors/index.d.ts @@ -0,0 +1,3 @@ +declare const Error: ErrorConstructor; + +export = Error; diff --git a/node_modules/es-errors/index.js b/node_modules/es-errors/index.js new file mode 100644 index 0000000..cc0c521 --- /dev/null +++ b/node_modules/es-errors/index.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('.')} */ +module.exports = Error; diff --git a/node_modules/es-errors/package.json b/node_modules/es-errors/package.json new file mode 100644 index 0000000..ff8c2a5 --- /dev/null +++ b/node_modules/es-errors/package.json @@ -0,0 +1,80 @@ +{ + "name": "es-errors", + "version": "1.3.0", + "description": "A simple cache for a few of the JS Error constructors.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./eval": "./eval.js", + "./range": "./range.js", + "./ref": "./ref.js", + "./syntax": "./syntax.js", + "./type": "./type.js", + "./uri": "./uri.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/**/*.js'", + "posttest": "aud --production", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git' | grep -v dist/)", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/es-errors.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "error", + "typeerror", + "syntaxerror", + "rangeerror" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/es-errors/issues" + }, + "homepage": "https://github.com/ljharb/es-errors#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "eclint": "^2.8.1", + "eslint": "^8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.4", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/es-errors/range.d.ts b/node_modules/es-errors/range.d.ts new file mode 100644 index 0000000..3a12e86 --- /dev/null +++ b/node_modules/es-errors/range.d.ts @@ -0,0 +1,3 @@ +declare const RangeError: RangeErrorConstructor; + +export = RangeError; diff --git a/node_modules/es-errors/range.js b/node_modules/es-errors/range.js new file mode 100644 index 0000000..2044fe0 --- /dev/null +++ b/node_modules/es-errors/range.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./range')} */ +module.exports = RangeError; diff --git a/node_modules/es-errors/ref.d.ts b/node_modules/es-errors/ref.d.ts new file mode 100644 index 0000000..a13107e --- /dev/null +++ b/node_modules/es-errors/ref.d.ts @@ -0,0 +1,3 @@ +declare const ReferenceError: ReferenceErrorConstructor; + +export = ReferenceError; diff --git a/node_modules/es-errors/ref.js b/node_modules/es-errors/ref.js new file mode 100644 index 0000000..d7c430f --- /dev/null +++ b/node_modules/es-errors/ref.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./ref')} */ +module.exports = ReferenceError; diff --git a/node_modules/es-errors/syntax.d.ts b/node_modules/es-errors/syntax.d.ts new file mode 100644 index 0000000..6a0c53c --- /dev/null +++ b/node_modules/es-errors/syntax.d.ts @@ -0,0 +1,3 @@ +declare const SyntaxError: SyntaxErrorConstructor; + +export = SyntaxError; diff --git a/node_modules/es-errors/syntax.js b/node_modules/es-errors/syntax.js new file mode 100644 index 0000000..5f5fdde --- /dev/null +++ b/node_modules/es-errors/syntax.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./syntax')} */ +module.exports = SyntaxError; diff --git a/node_modules/es-errors/test/index.js b/node_modules/es-errors/test/index.js new file mode 100644 index 0000000..1ff0277 --- /dev/null +++ b/node_modules/es-errors/test/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var test = require('tape'); + +var E = require('../'); +var R = require('../range'); +var Ref = require('../ref'); +var S = require('../syntax'); +var T = require('../type'); + +test('errors', function (t) { + t.equal(E, Error); + t.equal(R, RangeError); + t.equal(Ref, ReferenceError); + t.equal(S, SyntaxError); + t.equal(T, TypeError); + + t.end(); +}); diff --git a/node_modules/es-errors/tsconfig.json b/node_modules/es-errors/tsconfig.json new file mode 100644 index 0000000..99dfeb6 --- /dev/null +++ b/node_modules/es-errors/tsconfig.json @@ -0,0 +1,49 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + + /* Projects */ + + /* Language and Environment */ + "target": "es5", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": ["types"], /* Specify multiple folders that act like `./node_modules/@types`. */ + "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ + "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ + + /* Emit */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + "declarationMap": true, /* Create sourcemaps for d.ts files. */ + "noEmit": true, /* Disable emitting files from a compilation. */ + + /* Interop Constraints */ + "allowSyntheticDefaultImports": true, /* Allow `import x from y` when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + + /* Completeness */ + // "skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/es-errors/type.d.ts b/node_modules/es-errors/type.d.ts new file mode 100644 index 0000000..576fb51 --- /dev/null +++ b/node_modules/es-errors/type.d.ts @@ -0,0 +1,3 @@ +declare const TypeError: TypeErrorConstructor + +export = TypeError; diff --git a/node_modules/es-errors/type.js b/node_modules/es-errors/type.js new file mode 100644 index 0000000..9769e44 --- /dev/null +++ b/node_modules/es-errors/type.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./type')} */ +module.exports = TypeError; diff --git a/node_modules/es-errors/uri.d.ts b/node_modules/es-errors/uri.d.ts new file mode 100644 index 0000000..c3261c9 --- /dev/null +++ b/node_modules/es-errors/uri.d.ts @@ -0,0 +1,3 @@ +declare const URIError: URIErrorConstructor; + +export = URIError; diff --git a/node_modules/es-errors/uri.js b/node_modules/es-errors/uri.js new file mode 100644 index 0000000..e9cd1c7 --- /dev/null +++ b/node_modules/es-errors/uri.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./uri')} */ +module.exports = URIError; diff --git a/node_modules/es-object-atoms/.eslintrc b/node_modules/es-object-atoms/.eslintrc new file mode 100644 index 0000000..d90a1bc --- /dev/null +++ b/node_modules/es-object-atoms/.eslintrc @@ -0,0 +1,16 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "eqeqeq": ["error", "allow-null"], + "id-length": "off", + "new-cap": ["error", { + "capIsNewExceptions": [ + "RequireObjectCoercible", + "ToObject", + ], + }], + }, +} diff --git a/node_modules/es-object-atoms/.github/FUNDING.yml b/node_modules/es-object-atoms/.github/FUNDING.yml new file mode 100644 index 0000000..352bfda --- /dev/null +++ b/node_modules/es-object-atoms/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/es-object +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/es-object-atoms/CHANGELOG.md b/node_modules/es-object-atoms/CHANGELOG.md new file mode 100644 index 0000000..fdd2abe --- /dev/null +++ b/node_modules/es-object-atoms/CHANGELOG.md @@ -0,0 +1,37 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.1](https://github.com/ljharb/es-object-atoms/compare/v1.1.0...v1.1.1) - 2025-01-14 + +### Commits + +- [types] `ToObject`: improve types [`cfe8c8a`](https://github.com/ljharb/es-object-atoms/commit/cfe8c8a105c44820cb22e26f62d12ef0ad9715c8) + +## [v1.1.0](https://github.com/ljharb/es-object-atoms/compare/v1.0.1...v1.1.0) - 2025-01-14 + +### Commits + +- [New] add `isObject` [`51e4042`](https://github.com/ljharb/es-object-atoms/commit/51e4042df722eb3165f40dc5f4bf33d0197ecb07) + +## [v1.0.1](https://github.com/ljharb/es-object-atoms/compare/v1.0.0...v1.0.1) - 2025-01-13 + +### Commits + +- [Dev Deps] update `@ljharb/eslint-config`, `@ljharb/tsconfig`, `@types/tape`, `auto-changelog`, `tape` [`38ab9eb`](https://github.com/ljharb/es-object-atoms/commit/38ab9eb00b62c2f4668644f5e513d9b414ebd595) +- [types] improve types [`7d1beb8`](https://github.com/ljharb/es-object-atoms/commit/7d1beb887958b78b6a728a210a1c8370ab7e2aa1) +- [Tests] replace `aud` with `npm audit` [`25863ba`](https://github.com/ljharb/es-object-atoms/commit/25863baf99178f1d1ad33d1120498db28631907e) +- [Dev Deps] add missing peer dep [`c012309`](https://github.com/ljharb/es-object-atoms/commit/c0123091287e6132d6f4240496340c427433df28) + +## v1.0.0 - 2024-03-16 + +### Commits + +- Initial implementation, tests, readme, types [`f1499db`](https://github.com/ljharb/es-object-atoms/commit/f1499db7d3e1741e64979c61d645ab3137705e82) +- Initial commit [`99eedc7`](https://github.com/ljharb/es-object-atoms/commit/99eedc7b5fde38a50a28d3c8b724706e3e4c5f6a) +- [meta] rename repo [`fc851fa`](https://github.com/ljharb/es-object-atoms/commit/fc851fa70616d2d182aaf0bd02c2ed7084dea8fa) +- npm init [`b909377`](https://github.com/ljharb/es-object-atoms/commit/b909377c50049bd0ec575562d20b0f9ebae8947f) +- Only apps should have lockfiles [`7249edd`](https://github.com/ljharb/es-object-atoms/commit/7249edd2178c1b9ddfc66ffcc6d07fdf0d28efc1) diff --git a/node_modules/es-object-atoms/LICENSE b/node_modules/es-object-atoms/LICENSE new file mode 100644 index 0000000..f82f389 --- /dev/null +++ b/node_modules/es-object-atoms/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/es-object-atoms/README.md b/node_modules/es-object-atoms/README.md new file mode 100644 index 0000000..447695b --- /dev/null +++ b/node_modules/es-object-atoms/README.md @@ -0,0 +1,63 @@ +# es-object-atoms [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +ES Object-related atoms: Object, ToObject, RequireObjectCoercible. + +## Example + +```js +const assert = require('assert'); + +const $Object = require('es-object-atoms'); +const isObject = require('es-object-atoms/isObject'); +const ToObject = require('es-object-atoms/ToObject'); +const RequireObjectCoercible = require('es-object-atoms/RequireObjectCoercible'); + +assert.equal($Object, Object); +assert.throws(() => ToObject(null), TypeError); +assert.throws(() => ToObject(undefined), TypeError); +assert.throws(() => RequireObjectCoercible(null), TypeError); +assert.throws(() => RequireObjectCoercible(undefined), TypeError); + +assert.equal(isObject(undefined), false); +assert.equal(isObject(null), false); +assert.equal(isObject({}), true); +assert.equal(isObject([]), true); +assert.equal(isObject(function () {}), true); + +assert.deepEqual(RequireObjectCoercible(true), true); +assert.deepEqual(ToObject(true), Object(true)); + +const obj = {}; +assert.equal(RequireObjectCoercible(obj), obj); +assert.equal(ToObject(obj), obj); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +[package-url]: https://npmjs.org/package/es-object-atoms +[npm-version-svg]: https://versionbadg.es/ljharb/es-object-atoms.svg +[deps-svg]: https://david-dm.org/ljharb/es-object-atoms.svg +[deps-url]: https://david-dm.org/ljharb/es-object-atoms +[dev-deps-svg]: https://david-dm.org/ljharb/es-object-atoms/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/es-object-atoms#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/es-object-atoms.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/es-object-atoms.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/es-object.svg +[downloads-url]: https://npm-stat.com/charts.html?package=es-object-atoms +[codecov-image]: https://codecov.io/gh/ljharb/es-object-atoms/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/es-object-atoms/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/es-object-atoms +[actions-url]: https://github.com/ljharb/es-object-atoms/actions diff --git a/node_modules/es-object-atoms/RequireObjectCoercible.d.ts b/node_modules/es-object-atoms/RequireObjectCoercible.d.ts new file mode 100644 index 0000000..7e26c45 --- /dev/null +++ b/node_modules/es-object-atoms/RequireObjectCoercible.d.ts @@ -0,0 +1,3 @@ +declare function RequireObjectCoercible(value: T, optMessage?: string): T; + +export = RequireObjectCoercible; diff --git a/node_modules/es-object-atoms/RequireObjectCoercible.js b/node_modules/es-object-atoms/RequireObjectCoercible.js new file mode 100644 index 0000000..8e191c6 --- /dev/null +++ b/node_modules/es-object-atoms/RequireObjectCoercible.js @@ -0,0 +1,11 @@ +'use strict'; + +var $TypeError = require('es-errors/type'); + +/** @type {import('./RequireObjectCoercible')} */ +module.exports = function RequireObjectCoercible(value) { + if (value == null) { + throw new $TypeError((arguments.length > 0 && arguments[1]) || ('Cannot call method on ' + value)); + } + return value; +}; diff --git a/node_modules/es-object-atoms/ToObject.d.ts b/node_modules/es-object-atoms/ToObject.d.ts new file mode 100644 index 0000000..d6dd302 --- /dev/null +++ b/node_modules/es-object-atoms/ToObject.d.ts @@ -0,0 +1,7 @@ +declare function ToObject(value: number): Number; +declare function ToObject(value: boolean): Boolean; +declare function ToObject(value: string): String; +declare function ToObject(value: bigint): BigInt; +declare function ToObject(value: T): T; + +export = ToObject; diff --git a/node_modules/es-object-atoms/ToObject.js b/node_modules/es-object-atoms/ToObject.js new file mode 100644 index 0000000..2b99a7d --- /dev/null +++ b/node_modules/es-object-atoms/ToObject.js @@ -0,0 +1,10 @@ +'use strict'; + +var $Object = require('./'); +var RequireObjectCoercible = require('./RequireObjectCoercible'); + +/** @type {import('./ToObject')} */ +module.exports = function ToObject(value) { + RequireObjectCoercible(value); + return $Object(value); +}; diff --git a/node_modules/es-object-atoms/index.d.ts b/node_modules/es-object-atoms/index.d.ts new file mode 100644 index 0000000..8bdbfc8 --- /dev/null +++ b/node_modules/es-object-atoms/index.d.ts @@ -0,0 +1,3 @@ +declare const Object: ObjectConstructor; + +export = Object; diff --git a/node_modules/es-object-atoms/index.js b/node_modules/es-object-atoms/index.js new file mode 100644 index 0000000..1d33cef --- /dev/null +++ b/node_modules/es-object-atoms/index.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('.')} */ +module.exports = Object; diff --git a/node_modules/es-object-atoms/isObject.d.ts b/node_modules/es-object-atoms/isObject.d.ts new file mode 100644 index 0000000..43bee3b --- /dev/null +++ b/node_modules/es-object-atoms/isObject.d.ts @@ -0,0 +1,3 @@ +declare function isObject(x: unknown): x is object; + +export = isObject; diff --git a/node_modules/es-object-atoms/isObject.js b/node_modules/es-object-atoms/isObject.js new file mode 100644 index 0000000..ec49bf1 --- /dev/null +++ b/node_modules/es-object-atoms/isObject.js @@ -0,0 +1,6 @@ +'use strict'; + +/** @type {import('./isObject')} */ +module.exports = function isObject(x) { + return !!x && (typeof x === 'function' || typeof x === 'object'); +}; diff --git a/node_modules/es-object-atoms/package.json b/node_modules/es-object-atoms/package.json new file mode 100644 index 0000000..f4cec71 --- /dev/null +++ b/node_modules/es-object-atoms/package.json @@ -0,0 +1,80 @@ +{ + "name": "es-object-atoms", + "version": "1.1.1", + "description": "ES Object-related atoms: Object, ToObject, RequireObjectCoercible", + "main": "index.js", + "exports": { + ".": "./index.js", + "./RequireObjectCoercible": "./RequireObjectCoercible.js", + "./isObject": "./isObject.js", + "./ToObject": "./ToObject.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/**/*.js'", + "posttest": "npx npm@\">= 10.2\" audit --production", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git' | grep -v dist/)", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/es-object-atoms.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "object", + "toobject", + "coercible" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/es-object-atoms/issues" + }, + "homepage": "https://github.com/ljharb/es-object-atoms#readme", + "dependencies": { + "es-errors": "^1.3.0" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.3", + "@types/tape": "^5.8.1", + "auto-changelog": "^2.5.0", + "eclint": "^2.8.1", + "encoding": "^0.1.13", + "eslint": "^8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/es-object-atoms/test/index.js b/node_modules/es-object-atoms/test/index.js new file mode 100644 index 0000000..430b705 --- /dev/null +++ b/node_modules/es-object-atoms/test/index.js @@ -0,0 +1,38 @@ +'use strict'; + +var test = require('tape'); + +var $Object = require('../'); +var isObject = require('../isObject'); +var ToObject = require('../ToObject'); +var RequireObjectCoercible = require('..//RequireObjectCoercible'); + +test('errors', function (t) { + t.equal($Object, Object); + // @ts-expect-error + t['throws'](function () { ToObject(null); }, TypeError); + // @ts-expect-error + t['throws'](function () { ToObject(undefined); }, TypeError); + // @ts-expect-error + t['throws'](function () { RequireObjectCoercible(null); }, TypeError); + // @ts-expect-error + t['throws'](function () { RequireObjectCoercible(undefined); }, TypeError); + + t.deepEqual(RequireObjectCoercible(true), true); + t.deepEqual(ToObject(true), Object(true)); + t.deepEqual(ToObject(42), Object(42)); + var f = function () {}; + t.equal(ToObject(f), f); + + t.equal(isObject(undefined), false); + t.equal(isObject(null), false); + t.equal(isObject({}), true); + t.equal(isObject([]), true); + t.equal(isObject(function () {}), true); + + var obj = {}; + t.equal(RequireObjectCoercible(obj), obj); + t.equal(ToObject(obj), obj); + + t.end(); +}); diff --git a/node_modules/es-object-atoms/tsconfig.json b/node_modules/es-object-atoms/tsconfig.json new file mode 100644 index 0000000..1f73cb7 --- /dev/null +++ b/node_modules/es-object-atoms/tsconfig.json @@ -0,0 +1,6 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es5", + }, +} diff --git a/node_modules/escape-html/LICENSE b/node_modules/escape-html/LICENSE new file mode 100644 index 0000000..2e70de9 --- /dev/null +++ b/node_modules/escape-html/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2013 TJ Holowaychuk +Copyright (c) 2015 Andreas Lubbe +Copyright (c) 2015 Tiancheng "Timothy" Gu + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/escape-html/Readme.md b/node_modules/escape-html/Readme.md new file mode 100644 index 0000000..653d9ea --- /dev/null +++ b/node_modules/escape-html/Readme.md @@ -0,0 +1,43 @@ + +# escape-html + + Escape string for use in HTML + +## Example + +```js +var escape = require('escape-html'); +var html = escape('foo & bar'); +// -> foo & bar +``` + +## Benchmark + +``` +$ npm run-script bench + +> escape-html@1.0.3 bench nodejs-escape-html +> node benchmark/index.js + + + http_parser@1.0 + node@0.10.33 + v8@3.14.5.9 + ares@1.9.0-DEV + uv@0.10.29 + zlib@1.2.3 + modules@11 + openssl@1.0.1j + + 1 test completed. + 2 tests completed. + 3 tests completed. + + no special characters x 19,435,271 ops/sec ±0.85% (187 runs sampled) + single special character x 6,132,421 ops/sec ±0.67% (194 runs sampled) + many special characters x 3,175,826 ops/sec ±0.65% (193 runs sampled) +``` + +## License + + MIT \ No newline at end of file diff --git a/node_modules/escape-html/index.js b/node_modules/escape-html/index.js new file mode 100644 index 0000000..bf9e226 --- /dev/null +++ b/node_modules/escape-html/index.js @@ -0,0 +1,78 @@ +/*! + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu + * MIT Licensed + */ + +'use strict'; + +/** + * Module variables. + * @private + */ + +var matchHtmlRegExp = /["'&<>]/; + +/** + * Module exports. + * @public + */ + +module.exports = escapeHtml; + +/** + * Escape special characters in the given string of html. + * + * @param {string} string The string to escape for inserting into HTML + * @return {string} + * @public + */ + +function escapeHtml(string) { + var str = '' + string; + var match = matchHtmlRegExp.exec(str); + + if (!match) { + return str; + } + + var escape; + var html = ''; + var index = 0; + var lastIndex = 0; + + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: // " + escape = '"'; + break; + case 38: // & + escape = '&'; + break; + case 39: // ' + escape = '''; + break; + case 60: // < + escape = '<'; + break; + case 62: // > + escape = '>'; + break; + default: + continue; + } + + if (lastIndex !== index) { + html += str.substring(lastIndex, index); + } + + lastIndex = index + 1; + html += escape; + } + + return lastIndex !== index + ? html + str.substring(lastIndex, index) + : html; +} diff --git a/node_modules/escape-html/package.json b/node_modules/escape-html/package.json new file mode 100644 index 0000000..57ec7bd --- /dev/null +++ b/node_modules/escape-html/package.json @@ -0,0 +1,24 @@ +{ + "name": "escape-html", + "description": "Escape string for use in HTML", + "version": "1.0.3", + "license": "MIT", + "keywords": [ + "escape", + "html", + "utility" + ], + "repository": "component/escape-html", + "devDependencies": { + "benchmark": "1.0.0", + "beautify-benchmark": "0.2.4" + }, + "files": [ + "LICENSE", + "Readme.md", + "index.js" + ], + "scripts": { + "bench": "node benchmark/index.js" + } +} diff --git a/node_modules/etag/HISTORY.md b/node_modules/etag/HISTORY.md new file mode 100644 index 0000000..222b293 --- /dev/null +++ b/node_modules/etag/HISTORY.md @@ -0,0 +1,83 @@ +1.8.1 / 2017-09-12 +================== + + * perf: replace regular expression with substring + +1.8.0 / 2017-02-18 +================== + + * Use SHA1 instead of MD5 for ETag hashing + - Improves performance for larger entities + - Works with FIPS 140-2 OpenSSL configuration + +1.7.0 / 2015-06-08 +================== + + * Always include entity length in ETags for hash length extensions + * Generate non-Stats ETags using MD5 only (no longer CRC32) + * Improve stat performance by removing hashing + * Remove base64 padding in ETags to shorten + * Use MD5 instead of MD4 in weak ETags over 1KB + +1.6.0 / 2015-05-10 +================== + + * Improve support for JXcore + * Remove requirement of `atime` in the stats object + * Support "fake" stats objects in environments without `fs` + +1.5.1 / 2014-11-19 +================== + + * deps: crc@3.2.1 + - Minor fixes + +1.5.0 / 2014-10-14 +================== + + * Improve string performance + * Slightly improve speed for weak ETags over 1KB + +1.4.0 / 2014-09-21 +================== + + * Support "fake" stats objects + * Support Node.js 0.6 + +1.3.1 / 2014-09-14 +================== + + * Use the (new and improved) `crc` for crc32 + +1.3.0 / 2014-08-29 +================== + + * Default strings to strong ETags + * Improve speed for weak ETags over 1KB + +1.2.1 / 2014-08-29 +================== + + * Use the (much faster) `buffer-crc32` for crc32 + +1.2.0 / 2014-08-24 +================== + + * Add support for file stat objects + +1.1.0 / 2014-08-24 +================== + + * Add fast-path for empty entity + * Add weak ETag generation + * Shrink size of generated ETags + +1.0.1 / 2014-08-24 +================== + + * Fix behavior of string containing Unicode + +1.0.0 / 2014-05-18 +================== + + * Initial release diff --git a/node_modules/etag/LICENSE b/node_modules/etag/LICENSE new file mode 100644 index 0000000..cab251c --- /dev/null +++ b/node_modules/etag/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2016 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/etag/README.md b/node_modules/etag/README.md new file mode 100644 index 0000000..09c2169 --- /dev/null +++ b/node_modules/etag/README.md @@ -0,0 +1,159 @@ +# etag + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Create simple HTTP ETags + +This module generates HTTP ETags (as defined in RFC 7232) for use in +HTTP responses. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install etag +``` + +## API + + + +```js +var etag = require('etag') +``` + +### etag(entity, [options]) + +Generate a strong ETag for the given entity. This should be the complete +body of the entity. Strings, `Buffer`s, and `fs.Stats` are accepted. By +default, a strong ETag is generated except for `fs.Stats`, which will +generate a weak ETag (this can be overwritten by `options.weak`). + + + +```js +res.setHeader('ETag', etag(body)) +``` + +#### Options + +`etag` accepts these properties in the options object. + +##### weak + +Specifies if the generated ETag will include the weak validator mark (that +is, the leading `W/`). The actual entity tag is the same. The default value +is `false`, unless the `entity` is `fs.Stats`, in which case it is `true`. + +## Testing + +```sh +$ npm test +``` + +## Benchmark + +```bash +$ npm run-script bench + +> etag@1.8.1 bench nodejs-etag +> node benchmark/index.js + + http_parser@2.7.0 + node@6.11.1 + v8@5.1.281.103 + uv@1.11.0 + zlib@1.2.11 + ares@1.10.1-DEV + icu@58.2 + modules@48 + openssl@1.0.2k + +> node benchmark/body0-100b.js + + 100B body + + 4 tests completed. + + buffer - strong x 258,647 ops/sec ±1.07% (180 runs sampled) + buffer - weak x 263,812 ops/sec ±0.61% (184 runs sampled) + string - strong x 259,955 ops/sec ±1.19% (185 runs sampled) + string - weak x 264,356 ops/sec ±1.09% (184 runs sampled) + +> node benchmark/body1-1kb.js + + 1KB body + + 4 tests completed. + + buffer - strong x 189,018 ops/sec ±1.12% (182 runs sampled) + buffer - weak x 190,586 ops/sec ±0.81% (186 runs sampled) + string - strong x 144,272 ops/sec ±0.96% (188 runs sampled) + string - weak x 145,380 ops/sec ±1.43% (187 runs sampled) + +> node benchmark/body2-5kb.js + + 5KB body + + 4 tests completed. + + buffer - strong x 92,435 ops/sec ±0.42% (188 runs sampled) + buffer - weak x 92,373 ops/sec ±0.58% (189 runs sampled) + string - strong x 48,850 ops/sec ±0.56% (186 runs sampled) + string - weak x 49,380 ops/sec ±0.56% (190 runs sampled) + +> node benchmark/body3-10kb.js + + 10KB body + + 4 tests completed. + + buffer - strong x 55,989 ops/sec ±0.93% (188 runs sampled) + buffer - weak x 56,148 ops/sec ±0.55% (190 runs sampled) + string - strong x 27,345 ops/sec ±0.43% (188 runs sampled) + string - weak x 27,496 ops/sec ±0.45% (190 runs sampled) + +> node benchmark/body4-100kb.js + + 100KB body + + 4 tests completed. + + buffer - strong x 7,083 ops/sec ±0.22% (190 runs sampled) + buffer - weak x 7,115 ops/sec ±0.26% (191 runs sampled) + string - strong x 3,068 ops/sec ±0.34% (190 runs sampled) + string - weak x 3,096 ops/sec ±0.35% (190 runs sampled) + +> node benchmark/stats.js + + stat + + 4 tests completed. + + real - strong x 871,642 ops/sec ±0.34% (189 runs sampled) + real - weak x 867,613 ops/sec ±0.39% (190 runs sampled) + fake - strong x 401,051 ops/sec ±0.40% (189 runs sampled) + fake - weak x 400,100 ops/sec ±0.47% (188 runs sampled) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/etag.svg +[npm-url]: https://npmjs.org/package/etag +[node-version-image]: https://img.shields.io/node/v/etag.svg +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/etag/master.svg +[travis-url]: https://travis-ci.org/jshttp/etag +[coveralls-image]: https://img.shields.io/coveralls/jshttp/etag/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/etag?branch=master +[downloads-image]: https://img.shields.io/npm/dm/etag.svg +[downloads-url]: https://npmjs.org/package/etag diff --git a/node_modules/etag/index.js b/node_modules/etag/index.js new file mode 100644 index 0000000..2a585c9 --- /dev/null +++ b/node_modules/etag/index.js @@ -0,0 +1,131 @@ +/*! + * etag + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = etag + +/** + * Module dependencies. + * @private + */ + +var crypto = require('crypto') +var Stats = require('fs').Stats + +/** + * Module variables. + * @private + */ + +var toString = Object.prototype.toString + +/** + * Generate an entity tag. + * + * @param {Buffer|string} entity + * @return {string} + * @private + */ + +function entitytag (entity) { + if (entity.length === 0) { + // fast-path empty + return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' + } + + // compute hash of entity + var hash = crypto + .createHash('sha1') + .update(entity, 'utf8') + .digest('base64') + .substring(0, 27) + + // compute length of entity + var len = typeof entity === 'string' + ? Buffer.byteLength(entity, 'utf8') + : entity.length + + return '"' + len.toString(16) + '-' + hash + '"' +} + +/** + * Create a simple ETag. + * + * @param {string|Buffer|Stats} entity + * @param {object} [options] + * @param {boolean} [options.weak] + * @return {String} + * @public + */ + +function etag (entity, options) { + if (entity == null) { + throw new TypeError('argument entity is required') + } + + // support fs.Stats object + var isStats = isstats(entity) + var weak = options && typeof options.weak === 'boolean' + ? options.weak + : isStats + + // validate argument + if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { + throw new TypeError('argument entity must be string, Buffer, or fs.Stats') + } + + // generate entity tag + var tag = isStats + ? stattag(entity) + : entitytag(entity) + + return weak + ? 'W/' + tag + : tag +} + +/** + * Determine if object is a Stats object. + * + * @param {object} obj + * @return {boolean} + * @api private + */ + +function isstats (obj) { + // genuine fs.Stats + if (typeof Stats === 'function' && obj instanceof Stats) { + return true + } + + // quack quack + return obj && typeof obj === 'object' && + 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' && + 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' && + 'ino' in obj && typeof obj.ino === 'number' && + 'size' in obj && typeof obj.size === 'number' +} + +/** + * Generate a tag for a stat. + * + * @param {object} stat + * @return {string} + * @private + */ + +function stattag (stat) { + var mtime = stat.mtime.getTime().toString(16) + var size = stat.size.toString(16) + + return '"' + size + '-' + mtime + '"' +} diff --git a/node_modules/etag/package.json b/node_modules/etag/package.json new file mode 100644 index 0000000..b06ab80 --- /dev/null +++ b/node_modules/etag/package.json @@ -0,0 +1,47 @@ +{ + "name": "etag", + "description": "Create simple HTTP ETags", + "version": "1.8.1", + "contributors": [ + "Douglas Christopher Wilson ", + "David Björklund " + ], + "license": "MIT", + "keywords": [ + "etag", + "http", + "res" + ], + "repository": "jshttp/etag", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "1.21.5", + "safe-buffer": "5.1.1", + "seedrandom": "2.4.3" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/node_modules/express/History.md b/node_modules/express/History.md new file mode 100644 index 0000000..5b6cba5 --- /dev/null +++ b/node_modules/express/History.md @@ -0,0 +1,3858 @@ +5.1.0 / 2025-03-31 +======================== + +* Add support for `Uint8Array` in `res.send()` +* Add support for ETag option in `res.sendFile()` +* Add support for multiple links with the same rel in `res.links()` +* Add funding field to package.json +* perf: use loop for acceptParams +* refactor: prefix built-in node module imports +* deps: remove `setprototypeof` +* deps: remove `safe-buffer` +* deps: remove `utils-merge` +* deps: remove `methods` +* deps: remove `depd` +* deps: `debug@^4.4.0` +* deps: `body-parser@^2.2.0` +* deps: `router@^2.2.0` +* deps: `content-type@^1.0.5` +* deps: `finalhandler@^2.1.0` +* deps: `qs@^6.14.0` +* deps: `server-static@2.2.0` +* deps: `type-is@2.0.1` + +5.0.1 / 2024-10-08 +========== + +* Update `cookie` semver lock to address [CVE-2024-47764](https://nvd.nist.gov/vuln/detail/CVE-2024-47764) + +5.0.0 / 2024-09-10 +========================= +* remove: + - `path-is-absolute` dependency - use `path.isAbsolute` instead +* breaking: + * `res.status()` accepts only integers, and input must be greater than 99 and less than 1000 + * will throw a `RangeError: Invalid status code: ${code}. Status code must be greater than 99 and less than 1000.` for inputs outside this range + * will throw a `TypeError: Invalid status code: ${code}. Status code must be an integer.` for non integer inputs + * deps: send@1.0.0 + * `res.redirect('back')` and `res.location('back')` is no longer a supported magic string, explicitly use `req.get('Referrer') || '/'`. +* change: + - `res.clearCookie` will ignore user provided `maxAge` and `expires` options +* deps: cookie-signature@^1.2.1 +* deps: debug@4.3.6 +* deps: merge-descriptors@^2.0.0 +* deps: serve-static@^2.1.0 +* deps: qs@6.13.0 +* deps: accepts@^2.0.0 +* deps: mime-types@^3.0.0 + - `application/javascript` => `text/javascript` +* deps: type-is@^2.0.0 +* deps: content-disposition@^1.0.0 +* deps: finalhandler@^2.0.0 +* deps: fresh@^2.0.0 +* deps: body-parser@^2.0.1 +* deps: send@^1.1.0 + +5.0.0-beta.3 / 2024-03-25 +========================= + +This incorporates all changes after 4.19.1 up to 4.19.2. + +5.0.0-beta.2 / 2024-03-20 +========================= + +This incorporates all changes after 4.17.2 up to 4.19.1. + +5.0.0-beta.1 / 2022-02-14 +========================= + +This is the first Express 5.0 beta release, based off 4.17.2 and includes +changes from 5.0.0-alpha.8. + + * change: + - Default "query parser" setting to `'simple'` + - Requires Node.js 4+ + - Use `mime-types` for file to content type mapping + * deps: array-flatten@3.0.0 + * deps: body-parser@2.0.0-beta.1 + - `req.body` is no longer always initialized to `{}` + - `urlencoded` parser now defaults `extended` to `false` + - Use `on-finished` to determine when body read + * deps: router@2.0.0-beta.1 + - Add new `?`, `*`, and `+` parameter modifiers + - Internalize private `router.process_params` method + - Matching group expressions are only RegExp syntax + - Named matching groups no longer available by position in `req.params` + - Regular expressions can only be used in a matching group + - Remove `debug` dependency + - Special `*` path segment behavior removed + - deps: array-flatten@3.0.0 + - deps: parseurl@~1.3.3 + - deps: path-to-regexp@3.2.0 + - deps: setprototypeof@1.2.0 + * deps: send@1.0.0-beta.1 + - Change `dotfiles` option default to `'ignore'` + - Remove `hidden` option; use `dotfiles` option instead + - Use `mime-types` for file to content type mapping + - deps: debug@3.1.0 + * deps: serve-static@2.0.0-beta.1 + - Change `dotfiles` option default to `'ignore'` + - Remove `hidden` option; use `dotfiles` option instead + - Use `mime-types` for file to content type mapping + - Remove `express.static.mime` export; use `mime-types` package instead + - deps: send@1.0.0-beta.1 + +5.0.0-alpha.8 / 2020-03-25 +========================== + +This is the eighth Express 5.0 alpha release, based off 4.17.1 and includes +changes from 5.0.0-alpha.7. + +5.0.0-alpha.7 / 2018-10-26 +========================== + +This is the seventh Express 5.0 alpha release, based off 4.16.4 and includes +changes from 5.0.0-alpha.6. + +The major change with this alpha is the basic support for returned, rejected +Promises in the router. + + * remove: + - `path-to-regexp` dependency + * deps: debug@3.1.0 + - Add `DEBUG_HIDE_DATE` environment variable + - Change timer to per-namespace instead of global + - Change non-TTY date format + - Remove `DEBUG_FD` environment variable support + - Support 256 namespace colors + * deps: router@2.0.0-alpha.1 + - Add basic support for returned, rejected Promises + - Fix JSDoc for `Router` constructor + - deps: debug@3.1.0 + - deps: parseurl@~1.3.2 + - deps: setprototypeof@1.1.0 + - deps: utils-merge@1.0.1 + +5.0.0-alpha.6 / 2017-09-24 +========================== + +This is the sixth Express 5.0 alpha release, based off 4.15.5 and includes +changes from 5.0.0-alpha.5. + + * remove: + - `res.redirect(url, status)` signature - use `res.redirect(status, url)` + - `res.send(status, body)` signature - use `res.status(status).send(body)` + * deps: router@~1.3.1 + - deps: debug@2.6.8 + +5.0.0-alpha.5 / 2017-03-06 +========================== + +This is the fifth Express 5.0 alpha release, based off 4.15.2 and includes +changes from 5.0.0-alpha.4. + +5.0.0-alpha.4 / 2017-03-01 +========================== + +This is the fourth Express 5.0 alpha release, based off 4.15.0 and includes +changes from 5.0.0-alpha.3. + + * remove: + - Remove Express 3.x middleware error stubs + * deps: router@~1.3.0 + - Add `next("router")` to exit from router + - Fix case where `router.use` skipped requests routes did not + - Skip routing when `req.url` is not set + - Use `%o` in path debug to tell types apart + - deps: debug@2.6.1 + - deps: setprototypeof@1.0.3 + - perf: add fast match path for `*` route + +5.0.0-alpha.3 / 2017-01-28 +========================== + +This is the third Express 5.0 alpha release, based off 4.14.1 and includes +changes from 5.0.0-alpha.2. + + * remove: + - `res.json(status, obj)` signature - use `res.status(status).json(obj)` + - `res.jsonp(status, obj)` signature - use `res.status(status).jsonp(obj)` + - `res.vary()` (no arguments) -- provide a field name as an argument + * deps: array-flatten@2.1.1 + * deps: path-is-absolute@1.0.1 + * deps: router@~1.1.5 + - deps: array-flatten@2.0.1 + - deps: methods@~1.1.2 + - deps: parseurl@~1.3.1 + - deps: setprototypeof@1.0.2 + +5.0.0-alpha.2 / 2015-07-06 +========================== + +This is the second Express 5.0 alpha release, based off 4.13.1 and includes +changes from 5.0.0-alpha.1. + + * remove: + - `app.param(fn)` + - `req.param()` -- use `req.params`, `req.body`, or `req.query` instead + * change: + - `res.render` callback is always async, even for sync view engines + - The leading `:` character in `name` for `app.param(name, fn)` is no longer removed + - Use `router` module for routing + - Use `path-is-absolute` module for absolute path detection + +5.0.0-alpha.1 / 2014-11-06 +========================== + +This is the first Express 5.0 alpha release, based off 4.10.1. + + * remove: + - `app.del` - use `app.delete` + - `req.acceptsCharset` - use `req.acceptsCharsets` + - `req.acceptsEncoding` - use `req.acceptsEncodings` + - `req.acceptsLanguage` - use `req.acceptsLanguages` + - `res.json(obj, status)` signature - use `res.json(status, obj)` + - `res.jsonp(obj, status)` signature - use `res.jsonp(status, obj)` + - `res.send(body, status)` signature - use `res.send(status, body)` + - `res.send(status)` signature - use `res.sendStatus(status)` + - `res.sendfile` - use `res.sendFile` instead + - `express.query` middleware + * change: + - `req.host` now returns host (`hostname:port`) - use `req.hostname` for only hostname + - `req.query` is now a getter instead of a plain property + * add: + - `app.router` is a reference to the base router + +4.20.0 / 2024-09-10 +========== + * deps: serve-static@0.16.0 + * Remove link renderization in html while redirecting + * deps: send@0.19.0 + * Remove link renderization in html while redirecting + * deps: body-parser@0.6.0 + * add `depth` option to customize the depth level in the parser + * IMPORTANT: The default `depth` level for parsing URL-encoded data is now `32` (previously was `Infinity`) + * Remove link renderization in html while using `res.redirect` + * deps: path-to-regexp@0.1.10 + - Adds support for named matching groups in the routes using a regex + - Adds backtracking protection to parameters without regexes defined + * deps: encodeurl@~2.0.0 + - Removes encoding of `\`, `|`, and `^` to align better with URL spec + * Deprecate passing `options.maxAge` and `options.expires` to `res.clearCookie` + - Will be ignored in v5, clearCookie will set a cookie with an expires in the past to instruct clients to delete the cookie + +4.19.2 / 2024-03-25 +========== + + * Improved fix for open redirect allow list bypass + +4.19.1 / 2024-03-20 +========== + + * Allow passing non-strings to res.location with new encoding handling checks + +4.19.0 / 2024-03-20 +========== + + * Prevent open redirect allow list bypass due to encodeurl + * deps: cookie@0.6.0 + +4.18.3 / 2024-02-29 +========== + + * Fix routing requests without method + * deps: body-parser@1.20.2 + - Fix strict json error message on Node.js 19+ + - deps: content-type@~1.0.5 + - deps: raw-body@2.5.2 + * deps: cookie@0.6.0 + - Add `partitioned` option + +4.18.2 / 2022-10-08 +=================== + + * Fix regression routing a large stack in a single route + * deps: body-parser@1.20.1 + - deps: qs@6.11.0 + - perf: remove unnecessary object clone + * deps: qs@6.11.0 + +4.18.1 / 2022-04-29 +=================== + + * Fix hanging on large stack of sync routes + +4.18.0 / 2022-04-25 +=================== + + * Add "root" option to `res.download` + * Allow `options` without `filename` in `res.download` + * Deprecate string and non-integer arguments to `res.status` + * Fix behavior of `null`/`undefined` as `maxAge` in `res.cookie` + * Fix handling very large stacks of sync middleware + * Ignore `Object.prototype` values in settings through `app.set`/`app.get` + * Invoke `default` with same arguments as types in `res.format` + * Support proper 205 responses using `res.send` + * Use `http-errors` for `res.format` error + * deps: body-parser@1.20.0 + - Fix error message for json parse whitespace in `strict` + - Fix internal error when inflated body exceeds limit + - Prevent loss of async hooks context + - Prevent hanging when request already read + - deps: depd@2.0.0 + - deps: http-errors@2.0.0 + - deps: on-finished@2.4.1 + - deps: qs@6.10.3 + - deps: raw-body@2.5.1 + * deps: cookie@0.5.0 + - Add `priority` option + - Fix `expires` option to reject invalid dates + * deps: depd@2.0.0 + - Replace internal `eval` usage with `Function` constructor + - Use instance methods on `process` to check for listeners + * deps: finalhandler@1.2.0 + - Remove set content headers that break response + - deps: on-finished@2.4.1 + - deps: statuses@2.0.1 + * deps: on-finished@2.4.1 + - Prevent loss of async hooks context + * deps: qs@6.10.3 + * deps: send@0.18.0 + - Fix emitted 416 error missing headers property + - Limit the headers removed for 304 response + - deps: depd@2.0.0 + - deps: destroy@1.2.0 + - deps: http-errors@2.0.0 + - deps: on-finished@2.4.1 + - deps: statuses@2.0.1 + * deps: serve-static@1.15.0 + - deps: send@0.18.0 + * deps: statuses@2.0.1 + - Remove code 306 + - Rename `425 Unordered Collection` to standard `425 Too Early` + +4.17.3 / 2022-02-16 +=================== + + * deps: accepts@~1.3.8 + - deps: mime-types@~2.1.34 + - deps: negotiator@0.6.3 + * deps: body-parser@1.19.2 + - deps: bytes@3.1.2 + - deps: qs@6.9.7 + - deps: raw-body@2.4.3 + * deps: cookie@0.4.2 + * deps: qs@6.9.7 + * Fix handling of `__proto__` keys + * pref: remove unnecessary regexp for trust proxy + +4.17.2 / 2021-12-16 +=================== + + * Fix handling of `undefined` in `res.jsonp` + * Fix handling of `undefined` when `"json escape"` is enabled + * Fix incorrect middleware execution with unanchored `RegExp`s + * Fix `res.jsonp(obj, status)` deprecation message + * Fix typo in `res.is` JSDoc + * deps: body-parser@1.19.1 + - deps: bytes@3.1.1 + - deps: http-errors@1.8.1 + - deps: qs@6.9.6 + - deps: raw-body@2.4.2 + - deps: safe-buffer@5.2.1 + - deps: type-is@~1.6.18 + * deps: content-disposition@0.5.4 + - deps: safe-buffer@5.2.1 + * deps: cookie@0.4.1 + - Fix `maxAge` option to reject invalid values + * deps: proxy-addr@~2.0.7 + - Use `req.socket` over deprecated `req.connection` + - deps: forwarded@0.2.0 + - deps: ipaddr.js@1.9.1 + * deps: qs@6.9.6 + * deps: safe-buffer@5.2.1 + * deps: send@0.17.2 + - deps: http-errors@1.8.1 + - deps: ms@2.1.3 + - pref: ignore empty http tokens + * deps: serve-static@1.14.2 + - deps: send@0.17.2 + * deps: setprototypeof@1.2.0 + +4.17.1 / 2019-05-25 +=================== + + * Revert "Improve error message for `null`/`undefined` to `res.status`" + +4.17.0 / 2019-05-16 +=================== + + * Add `express.raw` to parse bodies into `Buffer` + * Add `express.text` to parse bodies into string + * Improve error message for non-strings to `res.sendFile` + * Improve error message for `null`/`undefined` to `res.status` + * Support multiple hosts in `X-Forwarded-Host` + * deps: accepts@~1.3.7 + * deps: body-parser@1.19.0 + - Add encoding MIK + - Add petabyte (`pb`) support + - Fix parsing array brackets after index + - deps: bytes@3.1.0 + - deps: http-errors@1.7.2 + - deps: iconv-lite@0.4.24 + - deps: qs@6.7.0 + - deps: raw-body@2.4.0 + - deps: type-is@~1.6.17 + * deps: content-disposition@0.5.3 + * deps: cookie@0.4.0 + - Add `SameSite=None` support + * deps: finalhandler@~1.1.2 + - Set stricter `Content-Security-Policy` header + - deps: parseurl@~1.3.3 + - deps: statuses@~1.5.0 + * deps: parseurl@~1.3.3 + * deps: proxy-addr@~2.0.5 + - deps: ipaddr.js@1.9.0 + * deps: qs@6.7.0 + - Fix parsing array brackets after index + * deps: range-parser@~1.2.1 + * deps: send@0.17.1 + - Set stricter CSP header in redirect & error responses + - deps: http-errors@~1.7.2 + - deps: mime@1.6.0 + - deps: ms@2.1.1 + - deps: range-parser@~1.2.1 + - deps: statuses@~1.5.0 + - perf: remove redundant `path.normalize` call + * deps: serve-static@1.14.1 + - Set stricter CSP header in redirect response + - deps: parseurl@~1.3.3 + - deps: send@0.17.1 + * deps: setprototypeof@1.1.1 + * deps: statuses@~1.5.0 + - Add `103 Early Hints` + * deps: type-is@~1.6.18 + - deps: mime-types@~2.1.24 + - perf: prevent internal `throw` on invalid type + +4.16.4 / 2018-10-10 +=================== + + * Fix issue where `"Request aborted"` may be logged in `res.sendfile` + * Fix JSDoc for `Router` constructor + * deps: body-parser@1.18.3 + - Fix deprecation warnings on Node.js 10+ + - Fix stack trace for strict json parse error + - deps: depd@~1.1.2 + - deps: http-errors@~1.6.3 + - deps: iconv-lite@0.4.23 + - deps: qs@6.5.2 + - deps: raw-body@2.3.3 + - deps: type-is@~1.6.16 + * deps: proxy-addr@~2.0.4 + - deps: ipaddr.js@1.8.0 + * deps: qs@6.5.2 + * deps: safe-buffer@5.1.2 + +4.16.3 / 2018-03-12 +=================== + + * deps: accepts@~1.3.5 + - deps: mime-types@~2.1.18 + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: finalhandler@1.1.1 + - Fix 404 output for bad / missing pathnames + - deps: encodeurl@~1.0.2 + - deps: statuses@~1.4.0 + * deps: proxy-addr@~2.0.3 + - deps: ipaddr.js@1.6.0 + * deps: send@0.16.2 + - Fix incorrect end tag in default error & redirects + - deps: depd@~1.1.2 + - deps: encodeurl@~1.0.2 + - deps: statuses@~1.4.0 + * deps: serve-static@1.13.2 + - Fix incorrect end tag in redirects + - deps: encodeurl@~1.0.2 + - deps: send@0.16.2 + * deps: statuses@~1.4.0 + * deps: type-is@~1.6.16 + - deps: mime-types@~2.1.18 + +4.16.2 / 2017-10-09 +=================== + + * Fix `TypeError` in `res.send` when given `Buffer` and `ETag` header set + * perf: skip parsing of entire `X-Forwarded-Proto` header + +4.16.1 / 2017-09-29 +=================== + + * deps: send@0.16.1 + * deps: serve-static@1.13.1 + - Fix regression when `root` is incorrectly set to a file + - deps: send@0.16.1 + +4.16.0 / 2017-09-28 +=================== + + * Add `"json escape"` setting for `res.json` and `res.jsonp` + * Add `express.json` and `express.urlencoded` to parse bodies + * Add `options` argument to `res.download` + * Improve error message when autoloading invalid view engine + * Improve error messages when non-function provided as middleware + * Skip `Buffer` encoding when not generating ETag for small response + * Use `safe-buffer` for improved Buffer API + * deps: accepts@~1.3.4 + - deps: mime-types@~2.1.16 + * deps: content-type@~1.0.4 + - perf: remove argument reassignment + - perf: skip parameter parsing when no parameters + * deps: etag@~1.8.1 + - perf: replace regular expression with substring + * deps: finalhandler@1.1.0 + - Use `res.headersSent` when available + * deps: parseurl@~1.3.2 + - perf: reduce overhead for full URLs + - perf: unroll the "fast-path" `RegExp` + * deps: proxy-addr@~2.0.2 + - Fix trimming leading / trailing OWS in `X-Forwarded-For` + - deps: forwarded@~0.1.2 + - deps: ipaddr.js@1.5.2 + - perf: reduce overhead when no `X-Forwarded-For` header + * deps: qs@6.5.1 + - Fix parsing & compacting very deep objects + * deps: send@0.16.0 + - Add 70 new types for file extensions + - Add `immutable` option + - Fix missing `` in default error & redirects + - Set charset as "UTF-8" for .js and .json + - Use instance methods on steam to check for listeners + - deps: mime@1.4.1 + - perf: improve path validation speed + * deps: serve-static@1.13.0 + - Add 70 new types for file extensions + - Add `immutable` option + - Set charset as "UTF-8" for .js and .json + - deps: send@0.16.0 + * deps: setprototypeof@1.1.0 + * deps: utils-merge@1.0.1 + * deps: vary@~1.1.2 + - perf: improve header token parsing speed + * perf: re-use options object when generating ETags + * perf: remove dead `.charset` set in `res.jsonp` + +4.15.5 / 2017-09-24 +=================== + + * deps: debug@2.6.9 + * deps: finalhandler@~1.0.6 + - deps: debug@2.6.9 + - deps: parseurl@~1.3.2 + * deps: fresh@0.5.2 + - Fix handling of modified headers with invalid dates + - perf: improve ETag match loop + - perf: improve `If-None-Match` token parsing + * deps: send@0.15.6 + - Fix handling of modified headers with invalid dates + - deps: debug@2.6.9 + - deps: etag@~1.8.1 + - deps: fresh@0.5.2 + - perf: improve `If-Match` token parsing + * deps: serve-static@1.12.6 + - deps: parseurl@~1.3.2 + - deps: send@0.15.6 + - perf: improve slash collapsing + +4.15.4 / 2017-08-06 +=================== + + * deps: debug@2.6.8 + * deps: depd@~1.1.1 + - Remove unnecessary `Buffer` loading + * deps: finalhandler@~1.0.4 + - deps: debug@2.6.8 + * deps: proxy-addr@~1.1.5 + - Fix array argument being altered + - deps: ipaddr.js@1.4.0 + * deps: qs@6.5.0 + * deps: send@0.15.4 + - deps: debug@2.6.8 + - deps: depd@~1.1.1 + - deps: http-errors@~1.6.2 + * deps: serve-static@1.12.4 + - deps: send@0.15.4 + +4.15.3 / 2017-05-16 +=================== + + * Fix error when `res.set` cannot add charset to `Content-Type` + * deps: debug@2.6.7 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@2.0.0 + * deps: finalhandler@~1.0.3 + - Fix missing `` in HTML document + - deps: debug@2.6.7 + * deps: proxy-addr@~1.1.4 + - deps: ipaddr.js@1.3.0 + * deps: send@0.15.3 + - deps: debug@2.6.7 + - deps: ms@2.0.0 + * deps: serve-static@1.12.3 + - deps: send@0.15.3 + * deps: type-is@~1.6.15 + - deps: mime-types@~2.1.15 + * deps: vary@~1.1.1 + - perf: hoist regular expression + +4.15.2 / 2017-03-06 +=================== + + * deps: qs@6.4.0 + - Fix regression parsing keys starting with `[` + +4.15.1 / 2017-03-05 +=================== + + * deps: send@0.15.1 + - Fix issue when `Date.parse` does not return `NaN` on invalid date + - Fix strict violation in broken environments + * deps: serve-static@1.12.1 + - Fix issue when `Date.parse` does not return `NaN` on invalid date + - deps: send@0.15.1 + +4.15.0 / 2017-03-01 +=================== + + * Add debug message when loading view engine + * Add `next("router")` to exit from router + * Fix case where `router.use` skipped requests routes did not + * Remove usage of `res._headers` private field + - Improves compatibility with Node.js 8 nightly + * Skip routing when `req.url` is not set + * Use `%o` in path debug to tell types apart + * Use `Object.create` to setup request & response prototypes + * Use `setprototypeof` module to replace `__proto__` setting + * Use `statuses` instead of `http` module for status messages + * deps: debug@2.6.1 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable set to `3` or higher + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + * deps: etag@~1.8.0 + - Use SHA1 instead of MD5 for ETag hashing + - Works with FIPS 140-2 OpenSSL configuration + * deps: finalhandler@~1.0.0 + - Fix exception when `err` cannot be converted to a string + - Fully URL-encode the pathname in the 404 + - Only include the pathname in the 404 message + - Send complete HTML document + - Set `Content-Security-Policy: default-src 'self'` header + - deps: debug@2.6.1 + * deps: fresh@0.5.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - perf: delay reading header values until needed + - perf: enable strict mode + - perf: hoist regular expressions + - perf: remove duplicate conditional + - perf: remove unnecessary boolean coercions + - perf: skip checking modified time if ETag check failed + - perf: skip parsing `If-None-Match` when no `ETag` header + - perf: use `Date.parse` instead of `new Date` + * deps: qs@6.3.1 + - Fix array parsing from skipping empty values + - Fix compacting nested arrays + * deps: send@0.15.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - Remove usage of `res._headers` private field + - Support `If-Match` and `If-Unmodified-Since` headers + - Use `res.getHeaderNames()` when available + - Use `res.headersSent` when available + - deps: debug@2.6.1 + - deps: etag@~1.8.0 + - deps: fresh@0.5.0 + - deps: http-errors@~1.6.1 + * deps: serve-static@1.12.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - Remove usage of `res._headers` private field + - Send complete HTML document in redirect response + - Set default CSP header in redirect response + - Support `If-Match` and `If-Unmodified-Since` headers + - Use `res.getHeaderNames()` when available + - Use `res.headersSent` when available + - deps: send@0.15.0 + * perf: add fast match path for `*` route + * perf: improve `req.ips` performance + +4.14.1 / 2017-01-28 +=================== + + * deps: content-disposition@0.5.2 + * deps: finalhandler@0.5.1 + - Fix exception when `err.headers` is not an object + - deps: statuses@~1.3.1 + - perf: hoist regular expressions + - perf: remove duplicate validation path + * deps: proxy-addr@~1.1.3 + - deps: ipaddr.js@1.2.0 + * deps: send@0.14.2 + - deps: http-errors@~1.5.1 + - deps: ms@0.7.2 + - deps: statuses@~1.3.1 + * deps: serve-static@~1.11.2 + - deps: send@0.14.2 + * deps: type-is@~1.6.14 + - deps: mime-types@~2.1.13 + +4.14.0 / 2016-06-16 +=================== + + * Add `acceptRanges` option to `res.sendFile`/`res.sendfile` + * Add `cacheControl` option to `res.sendFile`/`res.sendfile` + * Add `options` argument to `req.range` + - Includes the `combine` option + * Encode URL in `res.location`/`res.redirect` if not already encoded + * Fix some redirect handling in `res.sendFile`/`res.sendfile` + * Fix Windows absolute path check using forward slashes + * Improve error with invalid arguments to `req.get()` + * Improve performance for `res.json`/`res.jsonp` in most cases + * Improve `Range` header handling in `res.sendFile`/`res.sendfile` + * deps: accepts@~1.3.3 + - Fix including type extensions in parameters in `Accept` parsing + - Fix parsing `Accept` parameters with quoted equals + - Fix parsing `Accept` parameters with quoted semicolons + - Many performance improvements + - deps: mime-types@~2.1.11 + - deps: negotiator@0.6.1 + * deps: content-type@~1.0.2 + - perf: enable strict mode + * deps: cookie@0.3.1 + - Add `sameSite` option + - Fix cookie `Max-Age` to never be a floating point number + - Improve error message when `encode` is not a function + - Improve error message when `expires` is not a `Date` + - Throw better error for invalid argument to parse + - Throw on invalid values provided to `serialize` + - perf: enable strict mode + - perf: hoist regular expression + - perf: use for loop in parse + - perf: use string concatenation for serialization + * deps: finalhandler@0.5.0 + - Change invalid or non-numeric status code to 500 + - Overwrite status message to match set status code + - Prefer `err.statusCode` if `err.status` is invalid + - Set response headers from `err.headers` object + - Use `statuses` instead of `http` module for status messages + * deps: proxy-addr@~1.1.2 + - Fix accepting various invalid netmasks + - Fix IPv6-mapped IPv4 validation edge cases + - IPv4 netmasks must be contiguous + - IPv6 addresses cannot be used as a netmask + - deps: ipaddr.js@1.1.1 + * deps: qs@6.2.0 + - Add `decoder` option in `parse` function + * deps: range-parser@~1.2.0 + - Add `combine` option to combine overlapping ranges + - Fix incorrectly returning -1 when there is at least one valid range + - perf: remove internal function + * deps: send@0.14.1 + - Add `acceptRanges` option + - Add `cacheControl` option + - Attempt to combine multiple ranges into single range + - Correctly inherit from `Stream` class + - Fix `Content-Range` header in 416 responses when using `start`/`end` options + - Fix `Content-Range` header missing from default 416 responses + - Fix redirect error when `path` contains raw non-URL characters + - Fix redirect when `path` starts with multiple forward slashes + - Ignore non-byte `Range` headers + - deps: http-errors@~1.5.0 + - deps: range-parser@~1.2.0 + - deps: statuses@~1.3.0 + - perf: remove argument reassignment + * deps: serve-static@~1.11.1 + - Add `acceptRanges` option + - Add `cacheControl` option + - Attempt to combine multiple ranges into single range + - Fix redirect error when `req.url` contains raw non-URL characters + - Ignore non-byte `Range` headers + - Use status code 301 for redirects + - deps: send@0.14.1 + * deps: type-is@~1.6.13 + - Fix type error when given invalid type to match against + - deps: mime-types@~2.1.11 + * deps: vary@~1.1.0 + - Only accept valid field names in the `field` argument + * perf: use strict equality when possible + +4.13.4 / 2016-01-21 +=================== + + * deps: content-disposition@0.5.1 + - perf: enable strict mode + * deps: cookie@0.1.5 + - Throw on invalid values provided to `serialize` + * deps: depd@~1.1.0 + - Support web browser loading + - perf: enable strict mode + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: finalhandler@0.4.1 + - deps: escape-html@~1.0.3 + * deps: merge-descriptors@1.0.1 + - perf: enable strict mode + * deps: methods@~1.1.2 + - perf: enable strict mode + * deps: parseurl@~1.3.1 + - perf: enable strict mode + * deps: proxy-addr@~1.0.10 + - deps: ipaddr.js@1.0.5 + - perf: enable strict mode + * deps: range-parser@~1.0.3 + - perf: enable strict mode + * deps: send@0.13.1 + - deps: depd@~1.1.0 + - deps: destroy@~1.0.4 + - deps: escape-html@~1.0.3 + - deps: range-parser@~1.0.3 + * deps: serve-static@~1.10.2 + - deps: escape-html@~1.0.3 + - deps: parseurl@~1.3.0 + - deps: send@0.13.1 + +4.13.3 / 2015-08-02 +=================== + + * Fix infinite loop condition using `mergeParams: true` + * Fix inner numeric indices incorrectly altering parent `req.params` + +4.13.2 / 2015-07-31 +=================== + + * deps: accepts@~1.2.12 + - deps: mime-types@~2.1.4 + * deps: array-flatten@1.1.1 + - perf: enable strict mode + * deps: path-to-regexp@0.1.7 + - Fix regression with escaped round brackets and matching groups + * deps: type-is@~1.6.6 + - deps: mime-types@~2.1.4 + +4.13.1 / 2015-07-05 +=================== + + * deps: accepts@~1.2.10 + - deps: mime-types@~2.1.2 + * deps: qs@4.0.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix various parsing edge cases + * deps: type-is@~1.6.4 + - deps: mime-types@~2.1.2 + - perf: enable strict mode + - perf: remove argument reassignment + +4.13.0 / 2015-06-20 +=================== + + * Add settings to debug output + * Fix `res.format` error when only `default` provided + * Fix issue where `next('route')` in `app.param` would incorrectly skip values + * Fix hiding platform issues with `decodeURIComponent` + - Only `URIError`s are a 400 + * Fix using `*` before params in routes + * Fix using capture groups before params in routes + * Simplify `res.cookie` to call `res.append` + * Use `array-flatten` module for flattening arrays + * deps: accepts@~1.2.9 + - deps: mime-types@~2.1.1 + - perf: avoid argument reassignment & argument slice + - perf: avoid negotiator recursive construction + - perf: enable strict mode + - perf: remove unnecessary bitwise operator + * deps: cookie@0.1.3 + - perf: deduce the scope of try-catch deopt + - perf: remove argument reassignments + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Always include entity length in ETags for hash length extensions + - Generate non-Stats ETags using MD5 only (no longer CRC32) + - Improve stat performance by removing hashing + - Improve support for JXcore + - Remove base64 padding in ETags to shorten + - Support "fake" stats objects in environments without fs + - Use MD5 instead of MD4 in weak ETags over 1KB + * deps: finalhandler@0.4.0 + - Fix a false-positive when unpiping in Node.js 0.8 + - Support `statusCode` property on `Error` objects + - Use `unpipe` module for unpiping requests + - deps: escape-html@1.0.2 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove argument reassignment + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * deps: path-to-regexp@0.1.6 + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + * deps: serve-static@~1.10.0 + - Add `fallthrough` option + - Fix reading options from options prototype + - Improve the default redirect response headers + - Malformed URLs now `next()` instead of 400 + - deps: escape-html@1.0.2 + - deps: send@0.13.0 + - perf: enable strict mode + - perf: remove argument reassignment + * deps: type-is@~1.6.3 + - deps: mime-types@~2.1.1 + - perf: reduce try block size + - perf: remove bitwise operations + * perf: enable strict mode + * perf: isolate `app.render` try block + * perf: remove argument reassignments in application + * perf: remove argument reassignments in request prototype + * perf: remove argument reassignments in response prototype + * perf: remove argument reassignments in routing + * perf: remove argument reassignments in `View` + * perf: skip attempting to decode zero length string + * perf: use saved reference to `http.STATUS_CODES` + +4.12.4 / 2015-05-17 +=================== + + * deps: accepts@~1.2.7 + - deps: mime-types@~2.0.11 + - deps: negotiator@0.5.3 + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: etag@~1.6.0 + - Improve support for JXcore + - Support "fake" stats objects in environments without `fs` + * deps: finalhandler@0.3.6 + - deps: debug@~2.2.0 + - deps: on-finished@~2.2.1 + * deps: on-finished@~2.2.1 + - Fix `isFinished(req)` when data buffered + * deps: proxy-addr@~1.0.8 + - deps: ipaddr.js@1.0.1 + * deps: qs@2.4.2 + - Fix allowing parameters like `constructor` + * deps: send@0.12.3 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: etag@~1.6.0 + - deps: ms@0.7.1 + - deps: on-finished@~2.2.1 + * deps: serve-static@~1.9.3 + - deps: send@0.12.3 + * deps: type-is@~1.6.2 + - deps: mime-types@~2.0.11 + +4.12.3 / 2015-03-17 +=================== + + * deps: accepts@~1.2.5 + - deps: mime-types@~2.0.10 + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: finalhandler@0.3.4 + - deps: debug@~2.1.3 + * deps: proxy-addr@~1.0.7 + - deps: ipaddr.js@0.1.9 + * deps: qs@2.4.1 + - Fix error when parameter `hasOwnProperty` is present + * deps: send@0.12.2 + - Throw errors early for invalid `extensions` or `index` options + - deps: debug@~2.1.3 + * deps: serve-static@~1.9.2 + - deps: send@0.12.2 + * deps: type-is@~1.6.1 + - deps: mime-types@~2.0.10 + +4.12.2 / 2015-03-02 +=================== + + * Fix regression where `"Request aborted"` is logged using `res.sendFile` + +4.12.1 / 2015-03-01 +=================== + + * Fix constructing application with non-configurable prototype properties + * Fix `ECONNRESET` errors from `res.sendFile` usage + * Fix `req.host` when using "trust proxy" hops count + * Fix `req.protocol`/`req.secure` when using "trust proxy" hops count + * Fix wrong `code` on aborted connections from `res.sendFile` + * deps: merge-descriptors@1.0.0 + +4.12.0 / 2015-02-23 +=================== + + * Fix `"trust proxy"` setting to inherit when app is mounted + * Generate `ETag`s for all request responses + - No longer restricted to only responses for `GET` and `HEAD` requests + * Use `content-type` to parse `Content-Type` headers + * deps: accepts@~1.2.4 + - Fix preference sorting to be stable for long acceptable lists + - deps: mime-types@~2.0.9 + - deps: negotiator@0.5.1 + * deps: cookie-signature@1.0.6 + * deps: send@0.12.1 + - Always read the stat size from the file + - Fix mutating passed-in `options` + - deps: mime@1.3.4 + * deps: serve-static@~1.9.1 + - deps: send@0.12.1 + * deps: type-is@~1.6.0 + - fix argument reassignment + - fix false-positives in `hasBody` `Transfer-Encoding` check + - support wildcard for both type and subtype (`*/*`) + - deps: mime-types@~2.0.9 + +4.11.2 / 2015-02-01 +=================== + + * Fix `res.redirect` double-calling `res.end` for `HEAD` requests + * deps: accepts@~1.2.3 + - deps: mime-types@~2.0.8 + * deps: proxy-addr@~1.0.6 + - deps: ipaddr.js@0.1.8 + * deps: type-is@~1.5.6 + - deps: mime-types@~2.0.8 + +4.11.1 / 2015-01-20 +=================== + + * deps: send@0.11.1 + - Fix root path disclosure + * deps: serve-static@~1.8.1 + - Fix redirect loop in Node.js 0.11.14 + - Fix root path disclosure + - deps: send@0.11.1 + +4.11.0 / 2015-01-13 +=================== + + * Add `res.append(field, val)` to append headers + * Deprecate leading `:` in `name` for `app.param(name, fn)` + * Deprecate `req.param()` -- use `req.params`, `req.body`, or `req.query` instead + * Deprecate `app.param(fn)` + * Fix `OPTIONS` responses to include the `HEAD` method properly + * Fix `res.sendFile` not always detecting aborted connection + * Match routes iteratively to prevent stack overflows + * deps: accepts@~1.2.2 + - deps: mime-types@~2.0.7 + - deps: negotiator@0.5.0 + * deps: send@0.11.0 + - deps: debug@~2.1.1 + - deps: etag@~1.5.1 + - deps: ms@0.7.0 + - deps: on-finished@~2.2.0 + * deps: serve-static@~1.8.0 + - deps: send@0.11.0 + +4.10.8 / 2015-01-13 +=================== + + * Fix crash from error within `OPTIONS` response handler + * deps: proxy-addr@~1.0.5 + - deps: ipaddr.js@0.1.6 + +4.10.7 / 2015-01-04 +=================== + + * Fix `Allow` header for `OPTIONS` to not contain duplicate methods + * Fix incorrect "Request aborted" for `res.sendFile` when `HEAD` or 304 + * deps: debug@~2.1.1 + * deps: finalhandler@0.3.3 + - deps: debug@~2.1.1 + - deps: on-finished@~2.2.0 + * deps: methods@~1.1.1 + * deps: on-finished@~2.2.0 + * deps: serve-static@~1.7.2 + - Fix potential open redirect when mounted at root + * deps: type-is@~1.5.5 + - deps: mime-types@~2.0.7 + +4.10.6 / 2014-12-12 +=================== + + * Fix exception in `req.fresh`/`req.stale` without response headers + +4.10.5 / 2014-12-10 +=================== + + * Fix `res.send` double-calling `res.end` for `HEAD` requests + * deps: accepts@~1.1.4 + - deps: mime-types@~2.0.4 + * deps: type-is@~1.5.4 + - deps: mime-types@~2.0.4 + +4.10.4 / 2014-11-24 +=================== + + * Fix `res.sendfile` logging standard write errors + +4.10.3 / 2014-11-23 +=================== + + * Fix `res.sendFile` logging standard write errors + * deps: etag@~1.5.1 + * deps: proxy-addr@~1.0.4 + - deps: ipaddr.js@0.1.5 + * deps: qs@2.3.3 + - Fix `arrayLimit` behavior + +4.10.2 / 2014-11-09 +=================== + + * Correctly invoke async router callback asynchronously + * deps: accepts@~1.1.3 + - deps: mime-types@~2.0.3 + * deps: type-is@~1.5.3 + - deps: mime-types@~2.0.3 + +4.10.1 / 2014-10-28 +=================== + + * Fix handling of URLs containing `://` in the path + * deps: qs@2.3.2 + - Fix parsing of mixed objects and values + +4.10.0 / 2014-10-23 +=================== + + * Add support for `app.set('views', array)` + - Views are looked up in sequence in array of directories + * Fix `res.send(status)` to mention `res.sendStatus(status)` + * Fix handling of invalid empty URLs + * Use `content-disposition` module for `res.attachment`/`res.download` + - Sends standards-compliant `Content-Disposition` header + - Full Unicode support + * Use `path.resolve` in view lookup + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: etag@~1.5.0 + - Improve string performance + - Slightly improve speed for weak ETags over 1KB + * deps: finalhandler@0.3.2 + - Terminate in progress response only on error + - Use `on-finished` to determine request status + - deps: debug@~2.1.0 + - deps: on-finished@~2.1.1 + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + * deps: qs@2.3.0 + - Fix parsing of mixed implicit and explicit arrays + * deps: send@0.10.1 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + - deps: on-finished@~2.1.1 + * deps: serve-static@~1.7.1 + - deps: send@0.10.1 + +4.9.8 / 2014-10-17 +================== + + * Fix `res.redirect` body when redirect status specified + * deps: accepts@~1.1.2 + - Fix error when media type has invalid parameter + - deps: negotiator@0.4.9 + +4.9.7 / 2014-10-10 +================== + + * Fix using same param name in array of paths + +4.9.6 / 2014-10-08 +================== + + * deps: accepts@~1.1.1 + - deps: mime-types@~2.0.2 + - deps: negotiator@0.4.8 + * deps: serve-static@~1.6.4 + - Fix redirect loop when index file serving disabled + * deps: type-is@~1.5.2 + - deps: mime-types@~2.0.2 + +4.9.5 / 2014-09-24 +================== + + * deps: etag@~1.4.0 + * deps: proxy-addr@~1.0.3 + - Use `forwarded` npm module + * deps: send@0.9.3 + - deps: etag@~1.4.0 + * deps: serve-static@~1.6.3 + - deps: send@0.9.3 + +4.9.4 / 2014-09-19 +================== + + * deps: qs@2.2.4 + - Fix issue with object keys starting with numbers truncated + +4.9.3 / 2014-09-18 +================== + + * deps: proxy-addr@~1.0.2 + - Fix a global leak when multiple subnets are trusted + - deps: ipaddr.js@0.1.3 + +4.9.2 / 2014-09-17 +================== + + * Fix regression for empty string `path` in `app.use` + * Fix `router.use` to accept array of middleware without path + * Improve error message for bad `app.use` arguments + +4.9.1 / 2014-09-16 +================== + + * Fix `app.use` to accept array of middleware without path + * deps: depd@0.4.5 + * deps: etag@~1.3.1 + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + * deps: serve-static@~1.6.2 + - deps: send@0.9.2 + +4.9.0 / 2014-09-08 +================== + + * Add `res.sendStatus` + * Invoke callback for sendfile when client aborts + - Applies to `res.sendFile`, `res.sendfile`, and `res.download` + - `err` will be populated with request aborted error + * Support IP address host in `req.subdomains` + * Use `etag` to generate `ETag` headers + * deps: accepts@~1.1.0 + - update `mime-types` + * deps: cookie-signature@1.0.5 + * deps: debug@~2.0.0 + * deps: finalhandler@0.2.0 + - Set `X-Content-Type-Options: nosniff` header + - deps: debug@~2.0.0 + * deps: fresh@0.2.4 + * deps: media-typer@0.3.0 + - Throw error when parameter format invalid on parse + * deps: qs@2.2.3 + - Fix issue where first empty value in array is discarded + * deps: range-parser@~1.0.2 + * deps: send@0.9.1 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + - deps: fresh@0.2.4 + * deps: serve-static@~1.6.1 + - Add `lastModified` option + - deps: send@0.9.1 + * deps: type-is@~1.5.1 + - fix `hasbody` to be true for `content-length: 0` + - deps: media-typer@0.3.0 + - deps: mime-types@~2.0.1 + * deps: vary@~1.0.0 + - Accept valid `Vary` header string as `field` + +4.8.8 / 2014-09-04 +================== + + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + * deps: serve-static@~1.5.4 + - deps: send@0.8.5 + +4.8.7 / 2014-08-29 +================== + + * deps: qs@2.2.2 + - Remove unnecessary cloning + +4.8.6 / 2014-08-27 +================== + + * deps: qs@2.2.0 + - Array parsing fix + - Performance improvements + +4.8.5 / 2014-08-18 +================== + + * deps: send@0.8.3 + - deps: destroy@1.0.3 + - deps: on-finished@2.1.0 + * deps: serve-static@~1.5.3 + - deps: send@0.8.3 + +4.8.4 / 2014-08-14 +================== + + * deps: qs@1.2.2 + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + * deps: serve-static@~1.5.2 + - deps: send@0.8.2 + +4.8.3 / 2014-08-10 +================== + + * deps: parseurl@~1.3.0 + * deps: qs@1.2.1 + * deps: serve-static@~1.5.1 + - Fix parsing of weird `req.originalUrl` values + - deps: parseurl@~1.3.0 + - deps: utils-merge@1.0.0 + +4.8.2 / 2014-08-07 +================== + + * deps: qs@1.2.0 + - Fix parsing array of objects + +4.8.1 / 2014-08-06 +================== + + * fix incorrect deprecation warnings on `res.download` + * deps: qs@1.1.0 + - Accept urlencoded square brackets + - Accept empty values in implicit array notation + +4.8.0 / 2014-08-05 +================== + + * add `res.sendFile` + - accepts a file system path instead of a URL + - requires an absolute path or `root` option specified + * deprecate `res.sendfile` -- use `res.sendFile` instead + * support mounted app as any argument to `app.use()` + * deps: qs@1.0.2 + - Complete rewrite + - Limits array length to 20 + - Limits object depth to 5 + - Limits parameters to 1,000 + * deps: send@0.8.1 + - Add `extensions` option + * deps: serve-static@~1.5.0 + - Add `extensions` option + - deps: send@0.8.1 + +4.7.4 / 2014-08-04 +================== + + * fix `res.sendfile` regression for serving directory index files + * deps: send@0.7.4 + - Fix incorrect 403 on Windows and Node.js 0.11 + - Fix serving index files without root dir + * deps: serve-static@~1.4.4 + - deps: send@0.7.4 + +4.7.3 / 2014-08-04 +================== + + * deps: send@0.7.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + * deps: serve-static@~1.4.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + - deps: send@0.7.3 + +4.7.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + * deps: send@0.7.2 + - deps: depd@0.4.4 + * deps: serve-static@~1.4.2 + +4.7.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + * deps: send@0.7.1 + - deps: depd@0.4.3 + * deps: serve-static@~1.4.1 + +4.7.0 / 2014-07-25 +================== + + * fix `req.protocol` for proxy-direct connections + * configurable query parser with `app.set('query parser', parser)` + - `app.set('query parser', 'extended')` parse with "qs" module + - `app.set('query parser', 'simple')` parse with "querystring" core module + - `app.set('query parser', false)` disable query string parsing + - `app.set('query parser', true)` enable simple parsing + * deprecate `res.json(status, obj)` -- use `res.status(status).json(obj)` instead + * deprecate `res.jsonp(status, obj)` -- use `res.status(status).jsonp(obj)` instead + * deprecate `res.send(status, body)` -- use `res.status(status).send(body)` instead + * deps: debug@1.0.4 + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: finalhandler@0.1.0 + - Respond after request fully read + - deps: debug@1.0.4 + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - Cap `maxAge` value to 1 year + - deps: debug@1.0.4 + - deps: depd@0.4.2 + * deps: serve-static@~1.4.0 + - deps: parseurl@~1.2.0 + - deps: send@0.7.0 + * perf: prevent multiple `Buffer` creation in `res.send` + +4.6.1 / 2014-07-12 +================== + + * fix `subapp.mountpath` regression for `app.use(subapp)` + +4.6.0 / 2014-07-11 +================== + + * accept multiple callbacks to `app.use()` + * add explicit "Rosetta Flash JSONP abuse" protection + - previous versions are not vulnerable; this is just explicit protection + * catch errors in multiple `req.param(name, fn)` handlers + * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead + * fix `res.send(status, num)` to send `num` as json (not error) + * remove unnecessary escaping when `res.jsonp` returns JSON response + * support non-string `path` in `app.use(path, fn)` + - supports array of paths + - supports `RegExp` + * router: fix optimization on router exit + * router: refactor location of `try` blocks + * router: speed up standard `app.use(fn)` + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + * deps: finalhandler@0.0.3 + - deps: debug@1.0.3 + * deps: methods@1.1.0 + - add `CONNECT` + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + * deps: path-to-regexp@0.1.3 + * deps: send@0.6.0 + - deps: debug@1.0.3 + * deps: serve-static@~1.3.2 + - deps: parseurl@~1.1.3 + - deps: send@0.6.0 + * perf: fix arguments reassign deopt in some `res` methods + +4.5.1 / 2014-07-06 +================== + + * fix routing regression when altering `req.method` + +4.5.0 / 2014-07-04 +================== + + * add deprecation message to non-plural `req.accepts*` + * add deprecation message to `res.send(body, status)` + * add deprecation message to `res.vary()` + * add `headers` option to `res.sendfile` + - use to set headers on successful file transfer + * add `mergeParams` option to `Router` + - merges `req.params` from parent routes + * add `req.hostname` -- correct name for what `req.host` returns + * deprecate things with `depd` module + * deprecate `req.host` -- use `req.hostname` instead + * fix behavior when handling request without routes + * fix handling when `route.all` is only route + * invoke `router.param()` only when route matches + * restore `req.params` after invoking router + * use `finalhandler` for final response handling + * use `media-typer` to alter content-type charset + * deps: accepts@~1.0.7 + * deps: send@0.5.0 + - Accept string for `maxage` (converted by `ms`) + - Include link in default redirect response + * deps: serve-static@~1.3.0 + - Accept string for `maxAge` (converted by `ms`) + - Add `setHeaders` option + - Include HTML link in redirect response + - deps: send@0.5.0 + * deps: type-is@~1.3.2 + +4.4.5 / 2014-06-26 +================== + + * deps: cookie-signature@1.0.4 + - fix for timing attacks + +4.4.4 / 2014-06-20 +================== + + * fix `res.attachment` Unicode filenames in Safari + * fix "trim prefix" debug message in `express:router` + * deps: accepts@~1.0.5 + * deps: buffer-crc32@0.2.3 + +4.4.3 / 2014-06-11 +================== + + * fix persistence of modified `req.params[name]` from `app.param()` + * deps: accepts@1.0.3 + - deps: negotiator@0.4.6 + * deps: debug@1.0.2 + * deps: send@0.4.3 + - Do not throw uncatchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + * deps: serve-static@1.2.3 + - Do not throw uncatchable error on file open race condition + - deps: send@0.4.3 + +4.4.2 / 2014-06-09 +================== + + * fix catching errors from top-level handlers + * use `vary` module for `res.vary` + * deps: debug@1.0.1 + * deps: proxy-addr@1.0.1 + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: debug@1.0.1 + - deps: finished@1.2.1 + * deps: serve-static@1.2.2 + - fix "event emitter leak" warnings + - deps: send@0.4.2 + * deps: type-is@1.2.1 + +4.4.1 / 2014-06-02 +================== + + * deps: methods@1.0.1 + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + * deps: serve-static@1.2.1 + - use `escape-html` for escaping + - deps: send@0.4.1 + +4.4.0 / 2014-05-30 +================== + + * custom etag control with `app.set('etag', val)` + - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation + - `app.set('etag', 'weak')` weak tag + - `app.set('etag', 'strong')` strong etag + - `app.set('etag', false)` turn off + - `app.set('etag', true)` standard etag + * mark `res.send` ETag as weak and reduce collisions + * update accepts to 1.0.2 + - Fix interpretation when header not in request + * update send to 0.4.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: debug@0.8.1 + * update serve-static to 1.2.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: send@0.4.0 + +4.3.2 / 2014-05-28 +================== + + * fix handling of errors from `router.param()` callbacks + +4.3.1 / 2014-05-23 +================== + + * revert "fix behavior of multiple `app.VERB` for the same path" + - this caused a regression in the order of route execution + +4.3.0 / 2014-05-21 +================== + + * add `req.baseUrl` to access the path stripped from `req.url` in routes + * fix behavior of multiple `app.VERB` for the same path + * fix issue routing requests among sub routers + * invoke `router.param()` only when necessary instead of every match + * proper proxy trust with `app.set('trust proxy', trust)` + - `app.set('trust proxy', 1)` trust first hop + - `app.set('trust proxy', 'loopback')` trust loopback addresses + - `app.set('trust proxy', '10.0.0.1')` trust single IP + - `app.set('trust proxy', '10.0.0.1/16')` trust subnet + - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list + - `app.set('trust proxy', false)` turn off + - `app.set('trust proxy', true)` trust everything + * set proper `charset` in `Content-Type` for `res.send` + * update type-is to 1.2.0 + - support suffix matching + +4.2.0 / 2014-05-11 +================== + + * deprecate `app.del()` -- use `app.delete()` instead + * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead + - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` + * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead + - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` + * fix `req.next` when inside router instance + * include `ETag` header in `HEAD` requests + * keep previous `Content-Type` for `res.jsonp` + * support PURGE method + - add `app.purge` + - add `router.purge` + - include PURGE in `app.all` + * update debug to 0.8.0 + - add `enable()` method + - change from stderr to stdout + * update methods to 1.0.0 + - add PURGE + +4.1.2 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +4.1.1 / 2014-04-27 +================== + + * fix package.json to reflect supported node version + +4.1.0 / 2014-04-24 +================== + + * pass options from `res.sendfile` to `send` + * preserve casing of headers in `res.header` and `res.set` + * support unicode file names in `res.attachment` and `res.download` + * update accepts to 1.0.1 + - deps: negotiator@0.4.0 + * update cookie to 0.1.2 + - Fix for maxAge == 0 + - made compat with expires field + * update send to 0.3.0 + - Accept API options in options object + - Coerce option types + - Control whether to generate etags + - Default directory access to 403 when index disabled + - Fix sending files with dots without root set + - Include file path in etag + - Make "Can't set headers after they are sent." catchable + - Send full entity-body for multi range requests + - Set etags to "weak" + - Support "If-Range" header + - Support multiple index paths + - deps: mime@1.2.11 + * update serve-static to 1.1.0 + - Accept options directly to `send` module + - Resolve relative paths at middleware setup + - Use parseurl to parse the URL from request + - deps: send@0.3.0 + * update type-is to 1.1.0 + - add non-array values support + - add `multipart` as a shorthand + +4.0.0 / 2014-04-09 +================== + + * remove: + - node 0.8 support + - connect and connect's patches except for charset handling + - express(1) - moved to [express-generator](https://github.com/expressjs/generator) + - `express.createServer()` - it has been deprecated for a long time. Use `express()` + - `app.configure` - use logic in your own app code + - `app.router` - is removed + - `req.auth` - use `basic-auth` instead + - `req.accepted*` - use `req.accepts*()` instead + - `res.location` - relative URL resolution is removed + - `res.charset` - include the charset in the content type when using `res.set()` + - all bundled middleware except `static` + * change: + - `app.route` -> `app.mountpath` when mounting an express app in another express app + - `json spaces` no longer enabled by default in development + - `req.accepts*` -> `req.accepts*s` - i.e. `req.acceptsEncoding` -> `req.acceptsEncodings` + - `req.params` is now an object instead of an array + - `res.locals` is no longer a function. It is a plain js object. Treat it as such. + - `res.headerSent` -> `res.headersSent` to match node.js ServerResponse object + * refactor: + - `req.accepts*` with [accepts](https://github.com/expressjs/accepts) + - `req.is` with [type-is](https://github.com/expressjs/type-is) + - [path-to-regexp](https://github.com/component/path-to-regexp) + * add: + - `app.router()` - returns the app Router instance + - `app.route()` - Proxy to the app's `Router#route()` method to create a new route + - Router & Route - public API + +3.21.2 / 2015-07-31 +=================== + + * deps: connect@2.30.2 + - deps: body-parser@~1.13.3 + - deps: compression@~1.5.2 + - deps: errorhandler@~1.4.2 + - deps: method-override@~2.3.5 + - deps: serve-index@~1.7.2 + - deps: type-is@~1.6.6 + - deps: vhost@~3.0.1 + * deps: vary@~1.0.1 + - Fix setting empty header from empty `field` + - perf: enable strict mode + - perf: remove argument reassignments + +3.21.1 / 2015-07-05 +=================== + + * deps: basic-auth@~1.0.3 + * deps: connect@2.30.1 + - deps: body-parser@~1.13.2 + - deps: compression@~1.5.1 + - deps: errorhandler@~1.4.1 + - deps: morgan@~1.6.1 + - deps: pause@0.1.0 + - deps: qs@4.0.0 + - deps: serve-index@~1.7.1 + - deps: type-is@~1.6.4 + +3.21.0 / 2015-06-18 +=================== + + * deps: basic-auth@1.0.2 + - perf: enable strict mode + - perf: hoist regular expression + - perf: parse with regular expressions + - perf: remove argument reassignment + * deps: connect@2.30.0 + - deps: body-parser@~1.13.1 + - deps: bytes@2.1.0 + - deps: compression@~1.5.0 + - deps: cookie@0.1.3 + - deps: cookie-parser@~1.3.5 + - deps: csurf@~1.8.3 + - deps: errorhandler@~1.4.0 + - deps: express-session@~1.11.3 + - deps: finalhandler@0.4.0 + - deps: fresh@0.3.0 + - deps: morgan@~1.6.0 + - deps: serve-favicon@~2.3.0 + - deps: serve-index@~1.7.0 + - deps: serve-static@~1.10.0 + - deps: type-is@~1.6.3 + * deps: cookie@0.1.3 + - perf: deduce the scope of try-catch deopt + - perf: remove argument reassignments + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Always include entity length in ETags for hash length extensions + - Generate non-Stats ETags using MD5 only (no longer CRC32) + - Improve stat performance by removing hashing + - Improve support for JXcore + - Remove base64 padding in ETags to shorten + - Support "fake" stats objects in environments without fs + - Use MD5 instead of MD4 in weak ETags over 1KB + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: mkdirp@0.5.1 + - Work in global strict mode + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + +3.20.3 / 2015-05-17 +=================== + + * deps: connect@2.29.2 + - deps: body-parser@~1.12.4 + - deps: compression@~1.4.4 + - deps: connect-timeout@~1.6.2 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: errorhandler@~1.3.6 + - deps: finalhandler@0.3.6 + - deps: method-override@~2.3.3 + - deps: morgan@~1.5.3 + - deps: qs@2.4.2 + - deps: response-time@~2.3.1 + - deps: serve-favicon@~2.2.1 + - deps: serve-index@~1.6.4 + - deps: serve-static@~1.9.3 + - deps: type-is@~1.6.2 + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: proxy-addr@~1.0.8 + - deps: ipaddr.js@1.0.1 + * deps: send@0.12.3 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: etag@~1.6.0 + - deps: ms@0.7.1 + - deps: on-finished@~2.2.1 + +3.20.2 / 2015-03-16 +=================== + + * deps: connect@2.29.1 + - deps: body-parser@~1.12.2 + - deps: compression@~1.4.3 + - deps: connect-timeout@~1.6.1 + - deps: debug@~2.1.3 + - deps: errorhandler@~1.3.5 + - deps: express-session@~1.10.4 + - deps: finalhandler@0.3.4 + - deps: method-override@~2.3.2 + - deps: morgan@~1.5.2 + - deps: qs@2.4.1 + - deps: serve-index@~1.6.3 + - deps: serve-static@~1.9.2 + - deps: type-is@~1.6.1 + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: merge-descriptors@1.0.0 + * deps: proxy-addr@~1.0.7 + - deps: ipaddr.js@0.1.9 + * deps: send@0.12.2 + - Throw errors early for invalid `extensions` or `index` options + - deps: debug@~2.1.3 + +3.20.1 / 2015-02-28 +=================== + + * Fix `req.host` when using "trust proxy" hops count + * Fix `req.protocol`/`req.secure` when using "trust proxy" hops count + +3.20.0 / 2015-02-18 +=================== + + * Fix `"trust proxy"` setting to inherit when app is mounted + * Generate `ETag`s for all request responses + - No longer restricted to only responses for `GET` and `HEAD` requests + * Use `content-type` to parse `Content-Type` headers + * deps: connect@2.29.0 + - Use `content-type` to parse `Content-Type` headers + - deps: body-parser@~1.12.0 + - deps: compression@~1.4.1 + - deps: connect-timeout@~1.6.0 + - deps: cookie-parser@~1.3.4 + - deps: cookie-signature@1.0.6 + - deps: csurf@~1.7.0 + - deps: errorhandler@~1.3.4 + - deps: express-session@~1.10.3 + - deps: http-errors@~1.3.1 + - deps: response-time@~2.3.0 + - deps: serve-index@~1.6.2 + - deps: serve-static@~1.9.1 + - deps: type-is@~1.6.0 + * deps: cookie-signature@1.0.6 + * deps: send@0.12.1 + - Always read the stat size from the file + - Fix mutating passed-in `options` + - deps: mime@1.3.4 + +3.19.2 / 2015-02-01 +=================== + + * deps: connect@2.28.3 + - deps: compression@~1.3.1 + - deps: csurf@~1.6.6 + - deps: errorhandler@~1.3.3 + - deps: express-session@~1.10.2 + - deps: serve-index@~1.6.1 + - deps: type-is@~1.5.6 + * deps: proxy-addr@~1.0.6 + - deps: ipaddr.js@0.1.8 + +3.19.1 / 2015-01-20 +=================== + + * deps: connect@2.28.2 + - deps: body-parser@~1.10.2 + - deps: serve-static@~1.8.1 + * deps: send@0.11.1 + - Fix root path disclosure + +3.19.0 / 2015-01-09 +=================== + + * Fix `OPTIONS` responses to include the `HEAD` method property + * Use `readline` for prompt in `express(1)` + * deps: commander@2.6.0 + * deps: connect@2.28.1 + - deps: body-parser@~1.10.1 + - deps: compression@~1.3.0 + - deps: connect-timeout@~1.5.0 + - deps: csurf@~1.6.4 + - deps: debug@~2.1.1 + - deps: errorhandler@~1.3.2 + - deps: express-session@~1.10.1 + - deps: finalhandler@0.3.3 + - deps: method-override@~2.3.1 + - deps: morgan@~1.5.1 + - deps: serve-favicon@~2.2.0 + - deps: serve-index@~1.6.0 + - deps: serve-static@~1.8.0 + - deps: type-is@~1.5.5 + * deps: debug@~2.1.1 + * deps: methods@~1.1.1 + * deps: proxy-addr@~1.0.5 + - deps: ipaddr.js@0.1.6 + * deps: send@0.11.0 + - deps: debug@~2.1.1 + - deps: etag@~1.5.1 + - deps: ms@0.7.0 + - deps: on-finished@~2.2.0 + +3.18.6 / 2014-12-12 +=================== + + * Fix exception in `req.fresh`/`req.stale` without response headers + +3.18.5 / 2014-12-11 +=================== + + * deps: connect@2.27.6 + - deps: compression@~1.2.2 + - deps: express-session@~1.9.3 + - deps: http-errors@~1.2.8 + - deps: serve-index@~1.5.3 + - deps: type-is@~1.5.4 + +3.18.4 / 2014-11-23 +=================== + + * deps: connect@2.27.4 + - deps: body-parser@~1.9.3 + - deps: compression@~1.2.1 + - deps: errorhandler@~1.2.3 + - deps: express-session@~1.9.2 + - deps: qs@2.3.3 + - deps: serve-favicon@~2.1.7 + - deps: serve-static@~1.5.1 + - deps: type-is@~1.5.3 + * deps: etag@~1.5.1 + * deps: proxy-addr@~1.0.4 + - deps: ipaddr.js@0.1.5 + +3.18.3 / 2014-11-09 +=================== + + * deps: connect@2.27.3 + - Correctly invoke async callback asynchronously + - deps: csurf@~1.6.3 + +3.18.2 / 2014-10-28 +=================== + + * deps: connect@2.27.2 + - Fix handling of URLs containing `://` in the path + - deps: body-parser@~1.9.2 + - deps: qs@2.3.2 + +3.18.1 / 2014-10-22 +=================== + + * Fix internal `utils.merge` deprecation warnings + * deps: connect@2.27.1 + - deps: body-parser@~1.9.1 + - deps: express-session@~1.9.1 + - deps: finalhandler@0.3.2 + - deps: morgan@~1.4.1 + - deps: qs@2.3.0 + - deps: serve-static@~1.7.1 + * deps: send@0.10.1 + - deps: on-finished@~2.1.1 + +3.18.0 / 2014-10-17 +=================== + + * Use `content-disposition` module for `res.attachment`/`res.download` + - Sends standards-compliant `Content-Disposition` header + - Full Unicode support + * Use `etag` module to generate `ETag` headers + * deps: connect@2.27.0 + - Use `http-errors` module for creating errors + - Use `utils-merge` module for merging objects + - deps: body-parser@~1.9.0 + - deps: compression@~1.2.0 + - deps: connect-timeout@~1.4.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: express-session@~1.9.0 + - deps: finalhandler@0.3.1 + - deps: method-override@~2.3.0 + - deps: morgan@~1.4.0 + - deps: response-time@~2.2.0 + - deps: serve-favicon@~2.1.6 + - deps: serve-index@~1.5.0 + - deps: serve-static@~1.7.0 + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: send@0.10.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + +3.17.8 / 2014-10-15 +=================== + + * deps: connect@2.26.6 + - deps: compression@~1.1.2 + - deps: csurf@~1.6.2 + - deps: errorhandler@~1.2.2 + +3.17.7 / 2014-10-08 +=================== + + * deps: connect@2.26.5 + - Fix accepting non-object arguments to `logger` + - deps: serve-static@~1.6.4 + +3.17.6 / 2014-10-02 +=================== + + * deps: connect@2.26.4 + - deps: morgan@~1.3.2 + - deps: type-is@~1.5.2 + +3.17.5 / 2014-09-24 +=================== + + * deps: connect@2.26.3 + - deps: body-parser@~1.8.4 + - deps: serve-favicon@~2.1.5 + - deps: serve-static@~1.6.3 + * deps: proxy-addr@~1.0.3 + - Use `forwarded` npm module + * deps: send@0.9.3 + - deps: etag@~1.4.0 + +3.17.4 / 2014-09-19 +=================== + + * deps: connect@2.26.2 + - deps: body-parser@~1.8.3 + - deps: qs@2.2.4 + +3.17.3 / 2014-09-18 +=================== + + * deps: proxy-addr@~1.0.2 + - Fix a global leak when multiple subnets are trusted + - deps: ipaddr.js@0.1.3 + +3.17.2 / 2014-09-15 +=================== + + * Use `crc` instead of `buffer-crc32` for speed + * deps: connect@2.26.1 + - deps: body-parser@~1.8.2 + - deps: depd@0.4.5 + - deps: express-session@~1.8.2 + - deps: morgan@~1.3.1 + - deps: serve-favicon@~2.1.3 + - deps: serve-static@~1.6.2 + * deps: depd@0.4.5 + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + +3.17.1 / 2014-09-08 +=================== + + * Fix error in `req.subdomains` on empty host + +3.17.0 / 2014-09-08 +=================== + + * Support `X-Forwarded-Host` in `req.subdomains` + * Support IP address host in `req.subdomains` + * deps: connect@2.26.0 + - deps: body-parser@~1.8.1 + - deps: compression@~1.1.0 + - deps: connect-timeout@~1.3.0 + - deps: cookie-parser@~1.3.3 + - deps: cookie-signature@1.0.5 + - deps: csurf@~1.6.1 + - deps: debug@~2.0.0 + - deps: errorhandler@~1.2.0 + - deps: express-session@~1.8.1 + - deps: finalhandler@0.2.0 + - deps: fresh@0.2.4 + - deps: media-typer@0.3.0 + - deps: method-override@~2.2.0 + - deps: morgan@~1.3.0 + - deps: qs@2.2.3 + - deps: serve-favicon@~2.1.3 + - deps: serve-index@~1.2.1 + - deps: serve-static@~1.6.1 + - deps: type-is@~1.5.1 + - deps: vhost@~3.0.0 + * deps: cookie-signature@1.0.5 + * deps: debug@~2.0.0 + * deps: fresh@0.2.4 + * deps: media-typer@0.3.0 + - Throw error when parameter format invalid on parse + * deps: range-parser@~1.0.2 + * deps: send@0.9.1 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + - deps: fresh@0.2.4 + * deps: vary@~1.0.0 + - Accept valid `Vary` header string as `field` + +3.16.10 / 2014-09-04 +==================== + + * deps: connect@2.25.10 + - deps: serve-static@~1.5.4 + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + +3.16.9 / 2014-08-29 +=================== + + * deps: connect@2.25.9 + - deps: body-parser@~1.6.7 + - deps: qs@2.2.2 + +3.16.8 / 2014-08-27 +=================== + + * deps: connect@2.25.8 + - deps: body-parser@~1.6.6 + - deps: csurf@~1.4.1 + - deps: qs@2.2.0 + +3.16.7 / 2014-08-18 +=================== + + * deps: connect@2.25.7 + - deps: body-parser@~1.6.5 + - deps: express-session@~1.7.6 + - deps: morgan@~1.2.3 + - deps: serve-static@~1.5.3 + * deps: send@0.8.3 + - deps: destroy@1.0.3 + - deps: on-finished@2.1.0 + +3.16.6 / 2014-08-14 +=================== + + * deps: connect@2.25.6 + - deps: body-parser@~1.6.4 + - deps: qs@1.2.2 + - deps: serve-static@~1.5.2 + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + +3.16.5 / 2014-08-11 +=================== + + * deps: connect@2.25.5 + - Fix backwards compatibility in `logger` + +3.16.4 / 2014-08-10 +=================== + + * Fix original URL parsing in `res.location` + * deps: connect@2.25.4 + - Fix `query` middleware breaking with argument + - deps: body-parser@~1.6.3 + - deps: compression@~1.0.11 + - deps: connect-timeout@~1.2.2 + - deps: express-session@~1.7.5 + - deps: method-override@~2.1.3 + - deps: on-headers@~1.0.0 + - deps: parseurl@~1.3.0 + - deps: qs@1.2.1 + - deps: response-time@~2.0.1 + - deps: serve-index@~1.1.6 + - deps: serve-static@~1.5.1 + * deps: parseurl@~1.3.0 + +3.16.3 / 2014-08-07 +=================== + + * deps: connect@2.25.3 + - deps: multiparty@3.3.2 + +3.16.2 / 2014-08-07 +=================== + + * deps: connect@2.25.2 + - deps: body-parser@~1.6.2 + - deps: qs@1.2.0 + +3.16.1 / 2014-08-06 +=================== + + * deps: connect@2.25.1 + - deps: body-parser@~1.6.1 + - deps: qs@1.1.0 + +3.16.0 / 2014-08-05 +=================== + + * deps: connect@2.25.0 + - deps: body-parser@~1.6.0 + - deps: compression@~1.0.10 + - deps: csurf@~1.4.0 + - deps: express-session@~1.7.4 + - deps: qs@1.0.2 + - deps: serve-static@~1.5.0 + * deps: send@0.8.1 + - Add `extensions` option + +3.15.3 / 2014-08-04 +=================== + + * fix `res.sendfile` regression for serving directory index files + * deps: connect@2.24.3 + - deps: serve-index@~1.1.5 + - deps: serve-static@~1.4.4 + * deps: send@0.7.4 + - Fix incorrect 403 on Windows and Node.js 0.11 + - Fix serving index files without root dir + +3.15.2 / 2014-07-27 +=================== + + * deps: connect@2.24.2 + - deps: body-parser@~1.5.2 + - deps: depd@0.4.4 + - deps: express-session@~1.7.2 + - deps: morgan@~1.2.2 + - deps: serve-static@~1.4.2 + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + * deps: send@0.7.2 + - deps: depd@0.4.4 + +3.15.1 / 2014-07-26 +=================== + + * deps: connect@2.24.1 + - deps: body-parser@~1.5.1 + - deps: depd@0.4.3 + - deps: express-session@~1.7.1 + - deps: morgan@~1.2.1 + - deps: serve-index@~1.1.4 + - deps: serve-static@~1.4.1 + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + * deps: send@0.7.1 + - deps: depd@0.4.3 + +3.15.0 / 2014-07-22 +=================== + + * Fix `req.protocol` for proxy-direct connections + * Pass options from `res.sendfile` to `send` + * deps: connect@2.24.0 + - deps: body-parser@~1.5.0 + - deps: compression@~1.0.9 + - deps: connect-timeout@~1.2.1 + - deps: debug@1.0.4 + - deps: depd@0.4.2 + - deps: express-session@~1.7.0 + - deps: finalhandler@0.1.0 + - deps: method-override@~2.1.2 + - deps: morgan@~1.2.0 + - deps: multiparty@3.3.1 + - deps: parseurl@~1.2.0 + - deps: serve-static@~1.4.0 + * deps: debug@1.0.4 + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - Cap `maxAge` value to 1 year + - deps: debug@1.0.4 + - deps: depd@0.4.2 + +3.14.0 / 2014-07-11 +=================== + + * add explicit "Rosetta Flash JSONP abuse" protection + - previous versions are not vulnerable; this is just explicit protection + * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead + * fix `res.send(status, num)` to send `num` as json (not error) + * remove unnecessary escaping when `res.jsonp` returns JSON response + * deps: basic-auth@1.0.0 + - support empty password + - support empty username + * deps: connect@2.23.0 + - deps: debug@1.0.3 + - deps: express-session@~1.6.4 + - deps: method-override@~2.1.0 + - deps: parseurl@~1.1.3 + - deps: serve-static@~1.3.1 + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + * deps: methods@1.1.0 + - add `CONNECT` + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + +3.13.0 / 2014-07-03 +=================== + + * add deprecation message to `app.configure` + * add deprecation message to `req.auth` + * use `basic-auth` to parse `Authorization` header + * deps: connect@2.22.0 + - deps: csurf@~1.3.0 + - deps: express-session@~1.6.1 + - deps: multiparty@3.3.0 + - deps: serve-static@~1.3.0 + * deps: send@0.5.0 + - Accept string for `maxage` (converted by `ms`) + - Include link in default redirect response + +3.12.1 / 2014-06-26 +=================== + + * deps: connect@2.21.1 + - deps: cookie-parser@1.3.2 + - deps: cookie-signature@1.0.4 + - deps: express-session@~1.5.2 + - deps: type-is@~1.3.2 + * deps: cookie-signature@1.0.4 + - fix for timing attacks + +3.12.0 / 2014-06-21 +=================== + + * use `media-typer` to alter content-type charset + * deps: connect@2.21.0 + - deprecate `connect(middleware)` -- use `app.use(middleware)` instead + - deprecate `connect.createServer()` -- use `connect()` instead + - fix `res.setHeader()` patch to work with get -> append -> set pattern + - deps: compression@~1.0.8 + - deps: errorhandler@~1.1.1 + - deps: express-session@~1.5.0 + - deps: serve-index@~1.1.3 + +3.11.0 / 2014-06-19 +=================== + + * deprecate things with `depd` module + * deps: buffer-crc32@0.2.3 + * deps: connect@2.20.2 + - deprecate `verify` option to `json` -- use `body-parser` npm module instead + - deprecate `verify` option to `urlencoded` -- use `body-parser` npm module instead + - deprecate things with `depd` module + - use `finalhandler` for final response handling + - use `media-typer` to parse `content-type` for charset + - deps: body-parser@1.4.3 + - deps: connect-timeout@1.1.1 + - deps: cookie-parser@1.3.1 + - deps: csurf@1.2.2 + - deps: errorhandler@1.1.0 + - deps: express-session@1.4.0 + - deps: multiparty@3.2.9 + - deps: serve-index@1.1.2 + - deps: type-is@1.3.1 + - deps: vhost@2.0.0 + +3.10.5 / 2014-06-11 +=================== + + * deps: connect@2.19.6 + - deps: body-parser@1.3.1 + - deps: compression@1.0.7 + - deps: debug@1.0.2 + - deps: serve-index@1.1.1 + - deps: serve-static@1.2.3 + * deps: debug@1.0.2 + * deps: send@0.4.3 + - Do not throw uncatchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + +3.10.4 / 2014-06-09 +=================== + + * deps: connect@2.19.5 + - fix "event emitter leak" warnings + - deps: csurf@1.2.1 + - deps: debug@1.0.1 + - deps: serve-static@1.2.2 + - deps: type-is@1.2.1 + * deps: debug@1.0.1 + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: finished@1.2.1 + - deps: debug@1.0.1 + +3.10.3 / 2014-06-05 +=================== + + * use `vary` module for `res.vary` + * deps: connect@2.19.4 + - deps: errorhandler@1.0.2 + - deps: method-override@2.0.2 + - deps: serve-favicon@2.0.1 + * deps: debug@1.0.0 + +3.10.2 / 2014-06-03 +=================== + + * deps: connect@2.19.3 + - deps: compression@1.0.6 + +3.10.1 / 2014-06-03 +=================== + + * deps: connect@2.19.2 + - deps: compression@1.0.4 + * deps: proxy-addr@1.0.1 + +3.10.0 / 2014-06-02 +=================== + + * deps: connect@2.19.1 + - deprecate `methodOverride()` -- use `method-override` npm module instead + - deps: body-parser@1.3.0 + - deps: method-override@2.0.1 + - deps: multiparty@3.2.8 + - deps: response-time@2.0.0 + - deps: serve-static@1.2.1 + * deps: methods@1.0.1 + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + +3.9.0 / 2014-05-30 +================== + + * custom etag control with `app.set('etag', val)` + - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation + - `app.set('etag', 'weak')` weak tag + - `app.set('etag', 'strong')` strong etag + - `app.set('etag', false)` turn off + - `app.set('etag', true)` standard etag + * Include ETag in HEAD requests + * mark `res.send` ETag as weak and reduce collisions + * update connect to 2.18.0 + - deps: compression@1.0.3 + - deps: serve-index@1.1.0 + - deps: serve-static@1.2.0 + * update send to 0.4.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: debug@0.8.1 + +3.8.1 / 2014-05-27 +================== + + * update connect to 2.17.3 + - deps: body-parser@1.2.2 + - deps: express-session@1.2.1 + - deps: method-override@1.0.2 + +3.8.0 / 2014-05-21 +================== + + * keep previous `Content-Type` for `res.jsonp` + * set proper `charset` in `Content-Type` for `res.send` + * update connect to 2.17.1 + - fix `res.charset` appending charset when `content-type` has one + - deps: express-session@1.2.0 + - deps: morgan@1.1.1 + - deps: serve-index@1.0.3 + +3.7.0 / 2014-05-18 +================== + + * proper proxy trust with `app.set('trust proxy', trust)` + - `app.set('trust proxy', 1)` trust first hop + - `app.set('trust proxy', 'loopback')` trust loopback addresses + - `app.set('trust proxy', '10.0.0.1')` trust single IP + - `app.set('trust proxy', '10.0.0.1/16')` trust subnet + - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list + - `app.set('trust proxy', false)` turn off + - `app.set('trust proxy', true)` trust everything + * update connect to 2.16.2 + - deprecate `res.headerSent` -- use `res.headersSent` + - deprecate `res.on("header")` -- use on-headers module instead + - fix edge-case in `res.appendHeader` that would append in wrong order + - json: use body-parser + - urlencoded: use body-parser + - dep: bytes@1.0.0 + - dep: cookie-parser@1.1.0 + - dep: csurf@1.2.0 + - dep: express-session@1.1.0 + - dep: method-override@1.0.1 + +3.6.0 / 2014-05-09 +================== + + * deprecate `app.del()` -- use `app.delete()` instead + * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead + - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` + * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead + - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` + * support PURGE method + - add `app.purge` + - add `router.purge` + - include PURGE in `app.all` + * update connect to 2.15.0 + * Add `res.appendHeader` + * Call error stack even when response has been sent + * Patch `res.headerSent` to return Boolean + * Patch `res.headersSent` for node.js 0.8 + * Prevent default 404 handler after response sent + * dep: compression@1.0.2 + * dep: connect-timeout@1.1.0 + * dep: debug@^0.8.0 + * dep: errorhandler@1.0.1 + * dep: express-session@1.0.4 + * dep: morgan@1.0.1 + * dep: serve-favicon@2.0.0 + * dep: serve-index@1.0.2 + * update debug to 0.8.0 + * add `enable()` method + * change from stderr to stdout + * update methods to 1.0.0 + - add PURGE + * update mkdirp to 0.5.0 + +3.5.3 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +3.5.2 / 2014-04-24 +================== + + * update connect to 2.14.5 + * update cookie to 0.1.2 + * update mkdirp to 0.4.0 + * update send to 0.3.0 + +3.5.1 / 2014-03-25 +================== + + * pin less-middleware in generated app + +3.5.0 / 2014-03-06 +================== + + * bump deps + +3.4.8 / 2014-01-13 +================== + + * prevent incorrect automatic OPTIONS responses #1868 @dpatti + * update binary and examples for jade 1.0 #1876 @yossi, #1877 @reqshark, #1892 @matheusazzi + * throw 400 in case of malformed paths @rlidwka + +3.4.7 / 2013-12-10 +================== + + * update connect + +3.4.6 / 2013-12-01 +================== + + * update connect (raw-body) + +3.4.5 / 2013-11-27 +================== + + * update connect + * res.location: remove leading ./ #1802 @kapouer + * res.redirect: fix `res.redirect('toString') #1829 @michaelficarra + * res.send: always send ETag when content-length > 0 + * router: add Router.all() method + +3.4.4 / 2013-10-29 +================== + + * update connect + * update supertest + * update methods + * express(1): replace bodyParser() with urlencoded() and json() #1795 @chirag04 + +3.4.3 / 2013-10-23 +================== + + * update connect + +3.4.2 / 2013-10-18 +================== + + * update connect + * downgrade commander + +3.4.1 / 2013-10-15 +================== + + * update connect + * update commander + * jsonp: check if callback is a function + * router: wrap encodeURIComponent in a try/catch #1735 (@lxe) + * res.format: now includes charset @1747 (@sorribas) + * res.links: allow multiple calls @1746 (@sorribas) + +3.4.0 / 2013-09-07 +================== + + * add res.vary(). Closes #1682 + * update connect + +3.3.8 / 2013-09-02 +================== + + * update connect + +3.3.7 / 2013-08-28 +================== + + * update connect + +3.3.6 / 2013-08-27 +================== + + * Revert "remove charset from json responses. Closes #1631" (causes issues in some clients) + * add: req.accepts take an argument list + +3.3.4 / 2013-07-08 +================== + + * update send and connect + +3.3.3 / 2013-07-04 +================== + + * update connect + +3.3.2 / 2013-07-03 +================== + + * update connect + * update send + * remove .version export + +3.3.1 / 2013-06-27 +================== + + * update connect + +3.3.0 / 2013-06-26 +================== + + * update connect + * add support for multiple X-Forwarded-Proto values. Closes #1646 + * change: remove charset from json responses. Closes #1631 + * change: return actual booleans from req.accept* functions + * fix jsonp callback array throw + +3.2.6 / 2013-06-02 +================== + + * update connect + +3.2.5 / 2013-05-21 +================== + + * update connect + * update node-cookie + * add: throw a meaningful error when there is no default engine + * change generation of ETags with res.send() to GET requests only. Closes #1619 + +3.2.4 / 2013-05-09 +================== + + * fix `req.subdomains` when no Host is present + * fix `req.host` when no Host is present, return undefined + +3.2.3 / 2013-05-07 +================== + + * update connect / qs + +3.2.2 / 2013-05-03 +================== + + * update qs + +3.2.1 / 2013-04-29 +================== + + * add app.VERB() paths array deprecation warning + * update connect + * update qs and remove all ~ semver crap + * fix: accept number as value of Signed Cookie + +3.2.0 / 2013-04-15 +================== + + * add "view" constructor setting to override view behaviour + * add req.acceptsEncoding(name) + * add req.acceptedEncodings + * revert cookie signature change causing session race conditions + * fix sorting of Accept values of the same quality + +3.1.2 / 2013-04-12 +================== + + * add support for custom Accept parameters + * update cookie-signature + +3.1.1 / 2013-04-01 +================== + + * add X-Forwarded-Host support to `req.host` + * fix relative redirects + * update mkdirp + * update buffer-crc32 + * remove legacy app.configure() method from app template. + +3.1.0 / 2013-01-25 +================== + + * add support for leading "." in "view engine" setting + * add array support to `res.set()` + * add node 0.8.x to travis.yml + * add "subdomain offset" setting for tweaking `req.subdomains` + * add `res.location(url)` implementing `res.redirect()`-like setting of Location + * use app.get() for x-powered-by setting for inheritance + * fix colons in passwords for `req.auth` + +3.0.6 / 2013-01-04 +================== + + * add http verb methods to Router + * update connect + * fix mangling of the `res.cookie()` options object + * fix jsonp whitespace escape. Closes #1132 + +3.0.5 / 2012-12-19 +================== + + * add throwing when a non-function is passed to a route + * fix: explicitly remove Transfer-Encoding header from 204 and 304 responses + * revert "add 'etag' option" + +3.0.4 / 2012-12-05 +================== + + * add 'etag' option to disable `res.send()` Etags + * add escaping of urls in text/plain in `res.redirect()` + for old browsers interpreting as html + * change crc32 module for a more liberal license + * update connect + +3.0.3 / 2012-11-13 +================== + + * update connect + * update cookie module + * fix cookie max-age + +3.0.2 / 2012-11-08 +================== + + * add OPTIONS to cors example. Closes #1398 + * fix route chaining regression. Closes #1397 + +3.0.1 / 2012-11-01 +================== + + * update connect + +3.0.0 / 2012-10-23 +================== + + * add `make clean` + * add "Basic" check to req.auth + * add `req.auth` test coverage + * add cb && cb(payload) to `res.jsonp()`. Closes #1374 + * add backwards compat for `res.redirect()` status. Closes #1336 + * add support for `res.json()` to retain previously defined Content-Types. Closes #1349 + * update connect + * change `res.redirect()` to utilize a pathname-relative Location again. Closes #1382 + * remove non-primitive string support for `res.send()` + * fix view-locals example. Closes #1370 + * fix route-separation example + +3.0.0rc5 / 2012-09-18 +================== + + * update connect + * add redis search example + * add static-files example + * add "x-powered-by" setting (`app.disable('x-powered-by')`) + * add "application/octet-stream" redirect Accept test case. Closes #1317 + +3.0.0rc4 / 2012-08-30 +================== + + * add `res.jsonp()`. Closes #1307 + * add "verbose errors" option to error-pages example + * add another route example to express(1) so people are not so confused + * add redis online user activity tracking example + * update connect dep + * fix etag quoting. Closes #1310 + * fix error-pages 404 status + * fix jsonp callback char restrictions + * remove old OPTIONS default response + +3.0.0rc3 / 2012-08-13 +================== + + * update connect dep + * fix signed cookies to work with `connect.cookieParser()` ("s:" prefix was missing) [tnydwrds] + * fix `res.render()` clobbering of "locals" + +3.0.0rc2 / 2012-08-03 +================== + + * add CORS example + * update connect dep + * deprecate `.createServer()` & remove old stale examples + * fix: escape `res.redirect()` link + * fix vhost example + +3.0.0rc1 / 2012-07-24 +================== + + * add more examples to view-locals + * add scheme-relative redirects (`res.redirect("//foo.com")`) support + * update cookie dep + * update connect dep + * update send dep + * fix `express(1)` -h flag, use -H for hogan. Closes #1245 + * fix `res.sendfile()` socket error handling regression + +3.0.0beta7 / 2012-07-16 +================== + + * update connect dep for `send()` root normalization regression + +3.0.0beta6 / 2012-07-13 +================== + + * add `err.view` property for view errors. Closes #1226 + * add "jsonp callback name" setting + * add support for "/foo/:bar*" non-greedy matches + * change `res.sendfile()` to use `send()` module + * change `res.send` to use "response-send" module + * remove `app.locals.use` and `res.locals.use`, use regular middleware + +3.0.0beta5 / 2012-07-03 +================== + + * add "make check" support + * add route-map example + * add `res.json(obj, status)` support back for BC + * add "methods" dep, remove internal methods module + * update connect dep + * update auth example to utilize cores pbkdf2 + * updated tests to use "supertest" + +3.0.0beta4 / 2012-06-25 +================== + + * Added `req.auth` + * Added `req.range(size)` + * Added `res.links(obj)` + * Added `res.send(body, status)` support back for backwards compat + * Added `.default()` support to `res.format()` + * Added 2xx / 304 check to `req.fresh` + * Revert "Added + support to the router" + * Fixed `res.send()` freshness check, respect res.statusCode + +3.0.0beta3 / 2012-06-15 +================== + + * Added hogan `--hjs` to express(1) [nullfirm] + * Added another example to content-negotiation + * Added `fresh` dep + * Changed: `res.send()` always checks freshness + * Fixed: expose connects mime module. Closes #1165 + +3.0.0beta2 / 2012-06-06 +================== + + * Added `+` support to the router + * Added `req.host` + * Changed `req.param()` to check route first + * Update connect dep + +3.0.0beta1 / 2012-06-01 +================== + + * Added `res.format()` callback to override default 406 behaviour + * Fixed `res.redirect()` 406. Closes #1154 + +3.0.0alpha5 / 2012-05-30 +================== + + * Added `req.ip` + * Added `{ signed: true }` option to `res.cookie()` + * Removed `res.signedCookie()` + * Changed: dont reverse `req.ips` + * Fixed "trust proxy" setting check for `req.ips` + +3.0.0alpha4 / 2012-05-09 +================== + + * Added: allow `[]` in jsonp callback. Closes #1128 + * Added `PORT` env var support in generated template. Closes #1118 [benatkin] + * Updated: connect 2.2.2 + +3.0.0alpha3 / 2012-05-04 +================== + + * Added public `app.routes`. Closes #887 + * Added _view-locals_ example + * Added _mvc_ example + * Added `res.locals.use()`. Closes #1120 + * Added conditional-GET support to `res.send()` + * Added: coerce `res.set()` values to strings + * Changed: moved `static()` in generated apps below router + * Changed: `res.send()` only set ETag when not previously set + * Changed connect 2.2.1 dep + * Changed: `make test` now runs unit / acceptance tests + * Fixed req/res proto inheritance + +3.0.0alpha2 / 2012-04-26 +================== + + * Added `make benchmark` back + * Added `res.send()` support for `String` objects + * Added client-side data exposing example + * Added `res.header()` and `req.header()` aliases for BC + * Added `express.createServer()` for BC + * Perf: memoize parsed urls + * Perf: connect 2.2.0 dep + * Changed: make `expressInit()` middleware self-aware + * Fixed: use app.get() for all core settings + * Fixed redis session example + * Fixed session example. Closes #1105 + * Fixed generated express dep. Closes #1078 + +3.0.0alpha1 / 2012-04-15 +================== + + * Added `app.locals.use(callback)` + * Added `app.locals` object + * Added `app.locals(obj)` + * Added `res.locals` object + * Added `res.locals(obj)` + * Added `res.format()` for content-negotiation + * Added `app.engine()` + * Added `res.cookie()` JSON cookie support + * Added "trust proxy" setting + * Added `req.subdomains` + * Added `req.protocol` + * Added `req.secure` + * Added `req.path` + * Added `req.ips` + * Added `req.fresh` + * Added `req.stale` + * Added comma-delimited / array support for `req.accepts()` + * Added debug instrumentation + * Added `res.set(obj)` + * Added `res.set(field, value)` + * Added `res.get(field)` + * Added `app.get(setting)`. Closes #842 + * Added `req.acceptsLanguage()` + * Added `req.acceptsCharset()` + * Added `req.accepted` + * Added `req.acceptedLanguages` + * Added `req.acceptedCharsets` + * Added "json replacer" setting + * Added "json spaces" setting + * Added X-Forwarded-Proto support to `res.redirect()`. Closes #92 + * Added `--less` support to express(1) + * Added `express.response` prototype + * Added `express.request` prototype + * Added `express.application` prototype + * Added `app.path()` + * Added `app.render()` + * Added `res.type()` to replace `res.contentType()` + * Changed: `res.redirect()` to add relative support + * Changed: enable "jsonp callback" by default + * Changed: renamed "case sensitive routes" to "case sensitive routing" + * Rewrite of all tests with mocha + * Removed "root" setting + * Removed `res.redirect('home')` support + * Removed `req.notify()` + * Removed `app.register()` + * Removed `app.redirect()` + * Removed `app.is()` + * Removed `app.helpers()` + * Removed `app.dynamicHelpers()` + * Fixed `res.sendfile()` with non-GET. Closes #723 + * Fixed express(1) public dir for windows. Closes #866 + +2.5.9/ 2012-04-02 +================== + + * Added support for PURGE request method [pbuyle] + * Fixed `express(1)` generated app `app.address()` before `listening` [mmalecki] + +2.5.8 / 2012-02-08 +================== + + * Update mkdirp dep. Closes #991 + +2.5.7 / 2012-02-06 +================== + + * Fixed `app.all` duplicate DELETE requests [mscdex] + +2.5.6 / 2012-01-13 +================== + + * Updated hamljs dev dep. Closes #953 + +2.5.5 / 2012-01-08 +================== + + * Fixed: set `filename` on cached templates [matthewleon] + +2.5.4 / 2012-01-02 +================== + + * Fixed `express(1)` eol on 0.4.x. Closes #947 + +2.5.3 / 2011-12-30 +================== + + * Fixed `req.is()` when a charset is present + +2.5.2 / 2011-12-10 +================== + + * Fixed: express(1) LF -> CRLF for windows + +2.5.1 / 2011-11-17 +================== + + * Changed: updated connect to 1.8.x + * Removed sass.js support from express(1) + +2.5.0 / 2011-10-24 +================== + + * Added ./routes dir for generated app by default + * Added npm install reminder to express(1) app gen + * Added 0.5.x support + * Removed `make test-cov` since it wont work with node 0.5.x + * Fixed express(1) public dir for windows. Closes #866 + +2.4.7 / 2011-10-05 +================== + + * Added mkdirp to express(1). Closes #795 + * Added simple _json-config_ example + * Added shorthand for the parsed request's pathname via `req.path` + * Changed connect dep to 1.7.x to fix npm issue... + * Fixed `res.redirect()` __HEAD__ support. [reported by xerox] + * Fixed `req.flash()`, only escape args + * Fixed absolute path checking on windows. Closes #829 [reported by andrewpmckenzie] + +2.4.6 / 2011-08-22 +================== + + * Fixed multiple param callback regression. Closes #824 [reported by TroyGoode] + +2.4.5 / 2011-08-19 +================== + + * Added support for routes to handle errors. Closes #809 + * Added `app.routes.all()`. Closes #803 + * Added "basepath" setting to work in conjunction with reverse proxies etc. + * Refactored `Route` to use a single array of callbacks + * Added support for multiple callbacks for `app.param()`. Closes #801 +Closes #805 + * Changed: removed .call(self) for route callbacks + * Dependency: `qs >= 0.3.1` + * Fixed `res.redirect()` on windows due to `join()` usage. Closes #808 + +2.4.4 / 2011-08-05 +================== + + * Fixed `res.header()` intention of a set, even when `undefined` + * Fixed `*`, value no longer required + * Fixed `res.send(204)` support. Closes #771 + +2.4.3 / 2011-07-14 +================== + + * Added docs for `status` option special-case. Closes #739 + * Fixed `options.filename`, exposing the view path to template engines + +2.4.2. / 2011-07-06 +================== + + * Revert "removed jsonp stripping" for XSS + +2.4.1 / 2011-07-06 +================== + + * Added `res.json()` JSONP support. Closes #737 + * Added _extending-templates_ example. Closes #730 + * Added "strict routing" setting for trailing slashes + * Added support for multiple envs in `app.configure()` calls. Closes #735 + * Changed: `res.send()` using `res.json()` + * Changed: when cookie `path === null` don't default it + * Changed; default cookie path to "home" setting. Closes #731 + * Removed _pids/logs_ creation from express(1) + +2.4.0 / 2011-06-28 +================== + + * Added chainable `res.status(code)` + * Added `res.json()`, an explicit version of `res.send(obj)` + * Added simple web-service example + +2.3.12 / 2011-06-22 +================== + + * \#express is now on freenode! come join! + * Added `req.get(field, param)` + * Added links to Japanese documentation, thanks @hideyukisaito! + * Added; the `express(1)` generated app outputs the env + * Added `content-negotiation` example + * Dependency: connect >= 1.5.1 < 2.0.0 + * Fixed view layout bug. Closes #720 + * Fixed; ignore body on 304. Closes #701 + +2.3.11 / 2011-06-04 +================== + + * Added `npm test` + * Removed generation of dummy test file from `express(1)` + * Fixed; `express(1)` adds express as a dep + * Fixed; prune on `prepublish` + +2.3.10 / 2011-05-27 +================== + + * Added `req.route`, exposing the current route + * Added _package.json_ generation support to `express(1)` + * Fixed call to `app.param()` function for optional params. Closes #682 + +2.3.9 / 2011-05-25 +================== + + * Fixed bug-ish with `../' in `res.partial()` calls + +2.3.8 / 2011-05-24 +================== + + * Fixed `app.options()` + +2.3.7 / 2011-05-23 +================== + + * Added route `Collection`, ex: `app.get('/user/:id').remove();` + * Added support for `app.param(fn)` to define param logic + * Removed `app.param()` support for callback with return value + * Removed module.parent check from express(1) generated app. Closes #670 + * Refactored router. Closes #639 + +2.3.6 / 2011-05-20 +================== + + * Changed; using devDependencies instead of git submodules + * Fixed redis session example + * Fixed markdown example + * Fixed view caching, should not be enabled in development + +2.3.5 / 2011-05-20 +================== + + * Added export `.view` as alias for `.View` + +2.3.4 / 2011-05-08 +================== + + * Added `./examples/say` + * Fixed `res.sendfile()` bug preventing the transfer of files with spaces + +2.3.3 / 2011-05-03 +================== + + * Added "case sensitive routes" option. + * Changed; split methods supported per rfc [slaskis] + * Fixed route-specific middleware when using the same callback function several times + +2.3.2 / 2011-04-27 +================== + + * Fixed view hints + +2.3.1 / 2011-04-26 +================== + + * Added `app.match()` as `app.match.all()` + * Added `app.lookup()` as `app.lookup.all()` + * Added `app.remove()` for `app.remove.all()` + * Added `app.remove.VERB()` + * Fixed template caching collision issue. Closes #644 + * Moved router over from connect and started refactor + +2.3.0 / 2011-04-25 +================== + + * Added options support to `res.clearCookie()` + * Added `res.helpers()` as alias of `res.locals()` + * Added; json defaults to UTF-8 with `res.send()`. Closes #632. [Daniel * Dependency `connect >= 1.4.0` + * Changed; auto set Content-Type in res.attachement [Aaron Heckmann] + * Renamed "cache views" to "view cache". Closes #628 + * Fixed caching of views when using several apps. Closes #637 + * Fixed gotcha invoking `app.param()` callbacks once per route middleware. +Closes #638 + * Fixed partial lookup precedence. Closes #631 +Shaw] + +2.2.2 / 2011-04-12 +================== + + * Added second callback support for `res.download()` connection errors + * Fixed `filename` option passing to template engine + +2.2.1 / 2011-04-04 +================== + + * Added `layout(path)` helper to change the layout within a view. Closes #610 + * Fixed `partial()` collection object support. + Previously only anything with `.length` would work. + When `.length` is present one must still be aware of holes, + however now `{ collection: {foo: 'bar'}}` is valid, exposes + `keyInCollection` and `keysInCollection`. + + * Performance improved with better view caching + * Removed `request` and `response` locals + * Changed; errorHandler page title is now `Express` instead of `Connect` + +2.2.0 / 2011-03-30 +================== + + * Added `app.lookup.VERB()`, ex `app.lookup.put('/user/:id')`. Closes #606 + * Added `app.match.VERB()`, ex `app.match.put('/user/12')`. Closes #606 + * Added `app.VERB(path)` as alias of `app.lookup.VERB()`. + * Dependency `connect >= 1.2.0` + +2.1.1 / 2011-03-29 +================== + + * Added; expose `err.view` object when failing to locate a view + * Fixed `res.partial()` call `next(err)` when no callback is given [reported by aheckmann] + * Fixed; `res.send(undefined)` responds with 204 [aheckmann] + +2.1.0 / 2011-03-24 +================== + + * Added `/_?` partial lookup support. Closes #447 + * Added `request`, `response`, and `app` local variables + * Added `settings` local variable, containing the app's settings + * Added `req.flash()` exception if `req.session` is not available + * Added `res.send(bool)` support (json response) + * Fixed stylus example for latest version + * Fixed; wrap try/catch around `res.render()` + +2.0.0 / 2011-03-17 +================== + + * Fixed up index view path alternative. + * Changed; `res.locals()` without object returns the locals + +2.0.0rc3 / 2011-03-17 +================== + + * Added `res.locals(obj)` to compliment `res.local(key, val)` + * Added `res.partial()` callback support + * Fixed recursive error reporting issue in `res.render()` + +2.0.0rc2 / 2011-03-17 +================== + + * Changed; `partial()` "locals" are now optional + * Fixed `SlowBuffer` support. Closes #584 [reported by tyrda01] + * Fixed .filename view engine option [reported by drudge] + * Fixed blog example + * Fixed `{req,res}.app` reference when mounting [Ben Weaver] + +2.0.0rc / 2011-03-14 +================== + + * Fixed; expose `HTTPSServer` constructor + * Fixed express(1) default test charset. Closes #579 [reported by secoif] + * Fixed; default charset to utf-8 instead of utf8 for lame IE [reported by NickP] + +2.0.0beta3 / 2011-03-09 +================== + + * Added support for `res.contentType()` literal + The original `res.contentType('.json')`, + `res.contentType('application/json')`, and `res.contentType('json')` + will work now. + * Added `res.render()` status option support back + * Added charset option for `res.render()` + * Added `.charset` support (via connect 1.0.4) + * Added view resolution hints when in development and a lookup fails + * Added layout lookup support relative to the page view. + For example while rendering `./views/user/index.jade` if you create + `./views/user/layout.jade` it will be used in favour of the root layout. + * Fixed `res.redirect()`. RFC states absolute url [reported by unlink] + * Fixed; default `res.send()` string charset to utf8 + * Removed `Partial` constructor (not currently used) + +2.0.0beta2 / 2011-03-07 +================== + + * Added res.render() `.locals` support back to aid in migration process + * Fixed flash example + +2.0.0beta / 2011-03-03 +================== + + * Added HTTPS support + * Added `res.cookie()` maxAge support + * Added `req.header()` _Referrer_ / _Referer_ special-case, either works + * Added mount support for `res.redirect()`, now respects the mount-point + * Added `union()` util, taking place of `merge(clone())` combo + * Added stylus support to express(1) generated app + * Added secret to session middleware used in examples and generated app + * Added `res.local(name, val)` for progressive view locals + * Added default param support to `req.param(name, default)` + * Added `app.disabled()` and `app.enabled()` + * Added `app.register()` support for omitting leading ".", either works + * Added `res.partial()`, using the same interface as `partial()` within a view. Closes #539 + * Added `app.param()` to map route params to async/sync logic + * Added; aliased `app.helpers()` as `app.locals()`. Closes #481 + * Added extname with no leading "." support to `res.contentType()` + * Added `cache views` setting, defaulting to enabled in "production" env + * Added index file partial resolution, eg: partial('user') may try _views/user/index.jade_. + * Added `req.accepts()` support for extensions + * Changed; `res.download()` and `res.sendfile()` now utilize Connect's + static file server `connect.static.send()`. + * Changed; replaced `connect.utils.mime()` with npm _mime_ module + * Changed; allow `req.query` to be pre-defined (via middleware or other parent + * Changed view partial resolution, now relative to parent view + * Changed view engine signature. no longer `engine.render(str, options, callback)`, now `engine.compile(str, options) -> Function`, the returned function accepts `fn(locals)`. + * Fixed `req.param()` bug returning Array.prototype methods. Closes #552 + * Fixed; using `Stream#pipe()` instead of `sys.pump()` in `res.sendfile()` + * Fixed; using _qs_ module instead of _querystring_ + * Fixed; strip unsafe chars from jsonp callbacks + * Removed "stream threshold" setting + +1.0.8 / 2011-03-01 +================== + + * Allow `req.query` to be pre-defined (via middleware or other parent app) + * "connect": ">= 0.5.0 < 1.0.0". Closes #547 + * Removed the long deprecated __EXPRESS_ENV__ support + +1.0.7 / 2011-02-07 +================== + + * Fixed `render()` setting inheritance. + Mounted apps would not inherit "view engine" + +1.0.6 / 2011-02-07 +================== + + * Fixed `view engine` setting bug when period is in dirname + +1.0.5 / 2011-02-05 +================== + + * Added secret to generated app `session()` call + +1.0.4 / 2011-02-05 +================== + + * Added `qs` dependency to _package.json_ + * Fixed namespaced `require()`s for latest connect support + +1.0.3 / 2011-01-13 +================== + + * Remove unsafe characters from JSONP callback names [Ryan Grove] + +1.0.2 / 2011-01-10 +================== + + * Removed nested require, using `connect.router` + +1.0.1 / 2010-12-29 +================== + + * Fixed for middleware stacked via `createServer()` + previously the `foo` middleware passed to `createServer(foo)` + would not have access to Express methods such as `res.send()` + or props like `req.query` etc. + +1.0.0 / 2010-11-16 +================== + + * Added; deduce partial object names from the last segment. + For example by default `partial('forum/post', postObject)` will + give you the _post_ object, providing a meaningful default. + * Added http status code string representation to `res.redirect()` body + * Added; `res.redirect()` supporting _text/plain_ and _text/html_ via __Accept__. + * Added `req.is()` to aid in content negotiation + * Added partial local inheritance [suggested by masylum]. Closes #102 + providing access to parent template locals. + * Added _-s, --session[s]_ flag to express(1) to add session related middleware + * Added _--template_ flag to express(1) to specify the + template engine to use. + * Added _--css_ flag to express(1) to specify the + stylesheet engine to use (or just plain css by default). + * Added `app.all()` support [thanks aheckmann] + * Added partial direct object support. + You may now `partial('user', user)` providing the "user" local, + vs previously `partial('user', { object: user })`. + * Added _route-separation_ example since many people question ways + to do this with CommonJS modules. Also view the _blog_ example for + an alternative. + * Performance; caching view path derived partial object names + * Fixed partial local inheritance precedence. [reported by Nick Poulden] Closes #454 + * Fixed jsonp support; _text/javascript_ as per mailinglist discussion + +1.0.0rc4 / 2010-10-14 +================== + + * Added _NODE_ENV_ support, _EXPRESS_ENV_ is deprecated and will be removed in 1.0.0 + * Added route-middleware support (very helpful, see the [docs](http://expressjs.com/guide.html#Route-Middleware)) + * Added _jsonp callback_ setting to enable/disable jsonp autowrapping [Dav Glass] + * Added callback query check on response.send to autowrap JSON objects for simple webservice implementations [Dav Glass] + * Added `partial()` support for array-like collections. Closes #434 + * Added support for swappable querystring parsers + * Added session usage docs. Closes #443 + * Added dynamic helper caching. Closes #439 [suggested by maritz] + * Added authentication example + * Added basic Range support to `res.sendfile()` (and `res.download()` etc) + * Changed; `express(1)` generated app using 2 spaces instead of 4 + * Default env to "development" again [aheckmann] + * Removed _context_ option is no more, use "scope" + * Fixed; exposing _./support_ libs to examples so they can run without installs + * Fixed mvc example + +1.0.0rc3 / 2010-09-20 +================== + + * Added confirmation for `express(1)` app generation. Closes #391 + * Added extending of flash formatters via `app.flashFormatters` + * Added flash formatter support. Closes #411 + * Added streaming support to `res.sendfile()` using `sys.pump()` when >= "stream threshold" + * Added _stream threshold_ setting for `res.sendfile()` + * Added `res.send()` __HEAD__ support + * Added `res.clearCookie()` + * Added `res.cookie()` + * Added `res.render()` headers option + * Added `res.redirect()` response bodies + * Added `res.render()` status option support. Closes #425 [thanks aheckmann] + * Fixed `res.sendfile()` responding with 403 on malicious path + * Fixed `res.download()` bug; when an error occurs remove _Content-Disposition_ + * Fixed; mounted apps settings now inherit from parent app [aheckmann] + * Fixed; stripping Content-Length / Content-Type when 204 + * Fixed `res.send()` 204. Closes #419 + * Fixed multiple _Set-Cookie_ headers via `res.header()`. Closes #402 + * Fixed bug messing with error handlers when `listenFD()` is called instead of `listen()`. [thanks guillermo] + + +1.0.0rc2 / 2010-08-17 +================== + + * Added `app.register()` for template engine mapping. Closes #390 + * Added `res.render()` callback support as second argument (no options) + * Added callback support to `res.download()` + * Added callback support for `res.sendfile()` + * Added support for middleware access via `express.middlewareName()` vs `connect.middlewareName()` + * Added "partials" setting to docs + * Added default expresso tests to `express(1)` generated app. Closes #384 + * Fixed `res.sendfile()` error handling, defer via `next()` + * Fixed `res.render()` callback when a layout is used [thanks guillermo] + * Fixed; `make install` creating ~/.node_libraries when not present + * Fixed issue preventing error handlers from being defined anywhere. Closes #387 + +1.0.0rc / 2010-07-28 +================== + + * Added mounted hook. Closes #369 + * Added connect dependency to _package.json_ + + * Removed "reload views" setting and support code + development env never caches, production always caches. + + * Removed _param_ in route callbacks, signature is now + simply (req, res, next), previously (req, res, params, next). + Use _req.params_ for path captures, _req.query_ for GET params. + + * Fixed "home" setting + * Fixed middleware/router precedence issue. Closes #366 + * Fixed; _configure()_ callbacks called immediately. Closes #368 + +1.0.0beta2 / 2010-07-23 +================== + + * Added more examples + * Added; exporting `Server` constructor + * Added `Server#helpers()` for view locals + * Added `Server#dynamicHelpers()` for dynamic view locals. Closes #349 + * Added support for absolute view paths + * Added; _home_ setting defaults to `Server#route` for mounted apps. Closes #363 + * Added Guillermo Rauch to the contributor list + * Added support for "as" for non-collection partials. Closes #341 + * Fixed _install.sh_, ensuring _~/.node_libraries_ exists. Closes #362 [thanks jf] + * Fixed `res.render()` exceptions, now passed to `next()` when no callback is given [thanks guillermo] + * Fixed instanceof `Array` checks, now `Array.isArray()` + * Fixed express(1) expansion of public dirs. Closes #348 + * Fixed middleware precedence. Closes #345 + * Fixed view watcher, now async [thanks aheckmann] + +1.0.0beta / 2010-07-15 +================== + + * Re-write + - much faster + - much lighter + - Check [ExpressJS.com](http://expressjs.com) for migration guide and updated docs + +0.14.0 / 2010-06-15 +================== + + * Utilize relative requires + * Added Static bufferSize option [aheckmann] + * Fixed caching of view and partial subdirectories [aheckmann] + * Fixed mime.type() comments now that ".ext" is not supported + * Updated haml submodule + * Updated class submodule + * Removed bin/express + +0.13.0 / 2010-06-01 +================== + + * Added node v0.1.97 compatibility + * Added support for deleting cookies via Request#cookie('key', null) + * Updated haml submodule + * Fixed not-found page, now using charset utf-8 + * Fixed show-exceptions page, now using charset utf-8 + * Fixed view support due to fs.readFile Buffers + * Changed; mime.type() no longer accepts ".type" due to node extname() changes + +0.12.0 / 2010-05-22 +================== + + * Added node v0.1.96 compatibility + * Added view `helpers` export which act as additional local variables + * Updated haml submodule + * Changed ETag; removed inode, modified time only + * Fixed LF to CRLF for setting multiple cookies + * Fixed cookie compilation; values are now urlencoded + * Fixed cookies parsing; accepts quoted values and url escaped cookies + +0.11.0 / 2010-05-06 +================== + + * Added support for layouts using different engines + - this.render('page.html.haml', { layout: 'super-cool-layout.html.ejs' }) + - this.render('page.html.haml', { layout: 'foo' }) // assumes 'foo.html.haml' + - this.render('page.html.haml', { layout: false }) // no layout + * Updated ext submodule + * Updated haml submodule + * Fixed EJS partial support by passing along the context. Issue #307 + +0.10.1 / 2010-05-03 +================== + + * Fixed binary uploads. + +0.10.0 / 2010-04-30 +================== + + * Added charset support via Request#charset (automatically assigned to 'UTF-8' when respond()'s + encoding is set to 'utf8' or 'utf-8'). + * Added "encoding" option to Request#render(). Closes #299 + * Added "dump exceptions" setting, which is enabled by default. + * Added simple ejs template engine support + * Added error response support for text/plain, application/json. Closes #297 + * Added callback function param to Request#error() + * Added Request#sendHead() + * Added Request#stream() + * Added support for Request#respond(304, null) for empty response bodies + * Added ETag support to Request#sendfile() + * Added options to Request#sendfile(), passed to fs.createReadStream() + * Added filename arg to Request#download() + * Performance enhanced due to pre-reversing plugins so that plugins.reverse() is not called on each request + * Performance enhanced by preventing several calls to toLowerCase() in Router#match() + * Changed; Request#sendfile() now streams + * Changed; Renamed Request#halt() to Request#respond(). Closes #289 + * Changed; Using sys.inspect() instead of JSON.encode() for error output + * Changed; run() returns the http.Server instance. Closes #298 + * Changed; Defaulting Server#host to null (INADDR_ANY) + * Changed; Logger "common" format scale of 0.4f + * Removed Logger "request" format + * Fixed; Catching ENOENT in view caching, preventing error when "views/partials" is not found + * Fixed several issues with http client + * Fixed Logger Content-Length output + * Fixed bug preventing Opera from retaining the generated session id. Closes #292 + +0.9.0 / 2010-04-14 +================== + + * Added DSL level error() route support + * Added DSL level notFound() route support + * Added Request#error() + * Added Request#notFound() + * Added Request#render() callback function. Closes #258 + * Added "max upload size" setting + * Added "magic" variables to collection partials (\_\_index\_\_, \_\_length\_\_, \_\_isFirst\_\_, \_\_isLast\_\_). Closes #254 + * Added [haml.js](http://github.com/visionmedia/haml.js) submodule; removed haml-js + * Added callback function support to Request#halt() as 3rd/4th arg + * Added preprocessing of route param wildcards using param(). Closes #251 + * Added view partial support (with collections etc.) + * Fixed bug preventing falsey params (such as ?page=0). Closes #286 + * Fixed setting of multiple cookies. Closes #199 + * Changed; view naming convention is now NAME.TYPE.ENGINE (for example page.html.haml) + * Changed; session cookie is now httpOnly + * Changed; Request is no longer global + * Changed; Event is no longer global + * Changed; "sys" module is no longer global + * Changed; moved Request#download to Static plugin where it belongs + * Changed; Request instance created before body parsing. Closes #262 + * Changed; Pre-caching views in memory when "cache view contents" is enabled. Closes #253 + * Changed; Pre-caching view partials in memory when "cache view partials" is enabled + * Updated support to node --version 0.1.90 + * Updated dependencies + * Removed set("session cookie") in favour of use(Session, { cookie: { ... }}) + * Removed utils.mixin(); use Object#mergeDeep() + +0.8.0 / 2010-03-19 +================== + + * Added coffeescript example app. Closes #242 + * Changed; cache api now async friendly. Closes #240 + * Removed deprecated 'express/static' support. Use 'express/plugins/static' + +0.7.6 / 2010-03-19 +================== + + * Added Request#isXHR. Closes #229 + * Added `make install` (for the executable) + * Added `express` executable for setting up simple app templates + * Added "GET /public/*" to Static plugin, defaulting to /public + * Added Static plugin + * Fixed; Request#render() only calls cache.get() once + * Fixed; Namespacing View caches with "view:" + * Fixed; Namespacing Static caches with "static:" + * Fixed; Both example apps now use the Static plugin + * Fixed set("views"). Closes #239 + * Fixed missing space for combined log format + * Deprecated Request#sendfile() and 'express/static' + * Removed Server#running + +0.7.5 / 2010-03-16 +================== + + * Added Request#flash() support without args, now returns all flashes + * Updated ext submodule + +0.7.4 / 2010-03-16 +================== + + * Fixed session reaper + * Changed; class.js replacing js-oo Class implementation (quite a bit faster, no browser cruft) + +0.7.3 / 2010-03-16 +================== + + * Added package.json + * Fixed requiring of haml / sass due to kiwi removal + +0.7.2 / 2010-03-16 +================== + + * Fixed GIT submodules (HAH!) + +0.7.1 / 2010-03-16 +================== + + * Changed; Express now using submodules again until a PM is adopted + * Changed; chat example using millisecond conversions from ext + +0.7.0 / 2010-03-15 +================== + + * Added Request#pass() support (finds the next matching route, or the given path) + * Added Logger plugin (default "common" format replaces CommonLogger) + * Removed Profiler plugin + * Removed CommonLogger plugin + +0.6.0 / 2010-03-11 +================== + + * Added seed.yml for kiwi package management support + * Added HTTP client query string support when method is GET. Closes #205 + + * Added support for arbitrary view engines. + For example "foo.engine.html" will now require('engine'), + the exports from this module are cached after the first require(). + + * Added async plugin support + + * Removed usage of RESTful route funcs as http client + get() etc, use http.get() and friends + + * Removed custom exceptions + +0.5.0 / 2010-03-10 +================== + + * Added ext dependency (library of js extensions) + * Removed extname() / basename() utils. Use path module + * Removed toArray() util. Use arguments.values + * Removed escapeRegexp() util. Use RegExp.escape() + * Removed process.mixin() dependency. Use utils.mixin() + * Removed Collection + * Removed ElementCollection + * Shameless self promotion of ebook "Advanced JavaScript" (http://dev-mag.com) ;) + +0.4.0 / 2010-02-11 +================== + + * Added flash() example to sample upload app + * Added high level restful http client module (express/http) + * Changed; RESTful route functions double as HTTP clients. Closes #69 + * Changed; throwing error when routes are added at runtime + * Changed; defaulting render() context to the current Request. Closes #197 + * Updated haml submodule + +0.3.0 / 2010-02-11 +================== + + * Updated haml / sass submodules. Closes #200 + * Added flash message support. Closes #64 + * Added accepts() now allows multiple args. fixes #117 + * Added support for plugins to halt. Closes #189 + * Added alternate layout support. Closes #119 + * Removed Route#run(). Closes #188 + * Fixed broken specs due to use(Cookie) missing + +0.2.1 / 2010-02-05 +================== + + * Added "plot" format option for Profiler (for gnuplot processing) + * Added request number to Profiler plugin + * Fixed binary encoding for multipart file uploads, was previously defaulting to UTF8 + * Fixed issue with routes not firing when not files are present. Closes #184 + * Fixed process.Promise -> events.Promise + +0.2.0 / 2010-02-03 +================== + + * Added parseParam() support for name[] etc. (allows for file inputs with "multiple" attr) Closes #180 + * Added Both Cache and Session option "reapInterval" may be "reapEvery". Closes #174 + * Added expiration support to cache api with reaper. Closes #133 + * Added cache Store.Memory#reap() + * Added Cache; cache api now uses first class Cache instances + * Added abstract session Store. Closes #172 + * Changed; cache Memory.Store#get() utilizing Collection + * Renamed MemoryStore -> Store.Memory + * Fixed use() of the same plugin several time will always use latest options. Closes #176 + +0.1.0 / 2010-02-03 +================== + + * Changed; Hooks (before / after) pass request as arg as well as evaluated in their context + * Updated node support to 0.1.27 Closes #169 + * Updated dirname(__filename) -> __dirname + * Updated libxmljs support to v0.2.0 + * Added session support with memory store / reaping + * Added quick uid() helper + * Added multi-part upload support + * Added Sass.js support / submodule + * Added production env caching view contents and static files + * Added static file caching. Closes #136 + * Added cache plugin with memory stores + * Added support to StaticFile so that it works with non-textual files. + * Removed dirname() helper + * Removed several globals (now their modules must be required) + +0.0.2 / 2010-01-10 +================== + + * Added view benchmarks; currently haml vs ejs + * Added Request#attachment() specs. Closes #116 + * Added use of node's parseQuery() util. Closes #123 + * Added `make init` for submodules + * Updated Haml + * Updated sample chat app to show messages on load + * Updated libxmljs parseString -> parseHtmlString + * Fixed `make init` to work with older versions of git + * Fixed specs can now run independent specs for those who can't build deps. Closes #127 + * Fixed issues introduced by the node url module changes. Closes 126. + * Fixed two assertions failing due to Collection#keys() returning strings + * Fixed faulty Collection#toArray() spec due to keys() returning strings + * Fixed `make test` now builds libxmljs.node before testing + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/express/LICENSE b/node_modules/express/LICENSE new file mode 100644 index 0000000..aa927e4 --- /dev/null +++ b/node_modules/express/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2009-2014 TJ Holowaychuk +Copyright (c) 2013-2014 Roman Shtylman +Copyright (c) 2014-2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/express/Readme.md b/node_modules/express/Readme.md new file mode 100644 index 0000000..7443b81 --- /dev/null +++ b/node_modules/express/Readme.md @@ -0,0 +1,266 @@ +[![Express Logo](https://i.cloudup.com/zfY6lL7eFa-3000x3000.png)](https://expressjs.com/) + +**Fast, unopinionated, minimalist web framework for [Node.js](https://nodejs.org).** + +**This project has a [Code of Conduct][].** + +## Table of contents + +* [Installation](#Installation) +* [Features](#Features) +* [Docs & Community](#docs--community) +* [Quick Start](#Quick-Start) +* [Running Tests](#Running-Tests) +* [Philosophy](#Philosophy) +* [Examples](#Examples) +* [Contributing to Express](#Contributing) +* [TC (Technical Committee)](#tc-technical-committee) +* [Triagers](#triagers) +* [License](#license) + + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-downloads-url] +[![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer] + + +```js +import express from 'express' + +const app = express() + +app.get('/', (req, res) => { + res.send('Hello World') +}) + +app.listen(3000) +``` + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). + +Before installing, [download and install Node.js](https://nodejs.org/en/download/). +Node.js 18 or higher is required. + +If this is a brand new project, make sure to create a `package.json` first with +the [`npm init` command](https://docs.npmjs.com/creating-a-package-json-file). + +Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +npm install express +``` + +Follow [our installing guide](https://expressjs.com/en/starter/installing.html) +for more information. + +## Features + + * Robust routing + * Focus on high performance + * Super-high test coverage + * HTTP helpers (redirection, caching, etc) + * View system supporting 14+ template engines + * Content negotiation + * Executable for generating applications quickly + +## Docs & Community + + * [Website and Documentation](https://expressjs.com/) - [[website repo](https://github.com/expressjs/expressjs.com)] + * [GitHub Organization](https://github.com/expressjs) for Official Middleware & Modules + * [Github Discussions](https://github.com/expressjs/discussions) for discussion on the development and usage of Express + +**PROTIP** Be sure to read the [migration guide to v5](https://expressjs.com/en/guide/migrating-5) + +## Quick Start + + The quickest way to get started with express is to utilize the executable [`express(1)`](https://github.com/expressjs/generator) to generate an application as shown below: + + Install the executable. The executable's major version will match Express's: + +```bash +npm install -g express-generator@4 +``` + + Create the app: + +```bash +express /tmp/foo && cd /tmp/foo +``` + + Install dependencies: + +```bash +npm install +``` + + Start the server: + +```bash +npm start +``` + + View the website at: http://localhost:3000 + +## Philosophy + + The Express philosophy is to provide small, robust tooling for HTTP servers, making + it a great solution for single page applications, websites, hybrids, or public + HTTP APIs. + + Express does not force you to use any specific ORM or template engine. With support for over + 14 template engines via [@ladjs/consolidate](https://github.com/ladjs/consolidate), + you can quickly craft your perfect framework. + +## Examples + + To view the examples, clone the Express repository: + +```bash +git clone https://github.com/expressjs/express.git --depth 1 && cd express +``` + + Then install the dependencies: + +```bash +npm install +``` + + Then run whichever example you want: + +```bash +node examples/content-negotiation +``` + +## Contributing + + [![Linux Build][github-actions-ci-image]][github-actions-ci-url] + [![Test Coverage][coveralls-image]][coveralls-url] + +The Express.js project welcomes all constructive contributions. Contributions take many forms, +from code for bug fixes and enhancements, to additions and fixes to documentation, additional +tests, triaging incoming pull requests and issues, and more! + +See the [Contributing Guide](Contributing.md) for more technical details on contributing. + +### Security Issues + +If you discover a security vulnerability in Express, please see [Security Policies and Procedures](Security.md). + +### Running Tests + +To run the test suite, first install the dependencies: + +```bash +npm install +``` + +Then run `npm test`: + +```bash +npm test +``` + +## People + +The original author of Express is [TJ Holowaychuk](https://github.com/tj) + +[List of all contributors](https://github.com/expressjs/express/graphs/contributors) + +### TC (Technical Committee) + +* [UlisesGascon](https://github.com/UlisesGascon) - **Ulises Gascón** (he/him) +* [jonchurch](https://github.com/jonchurch) - **Jon Church** +* [wesleytodd](https://github.com/wesleytodd) - **Wes Todd** +* [LinusU](https://github.com/LinusU) - **Linus Unnebäck** +* [blakeembrey](https://github.com/blakeembrey) - **Blake Embrey** +* [sheplu](https://github.com/sheplu) - **Jean Burellier** +* [crandmck](https://github.com/crandmck) - **Rand McKinney** +* [ctcpip](https://github.com/ctcpip) - **Chris de Almeida** + +
+TC emeriti members + +#### TC emeriti members + + * [dougwilson](https://github.com/dougwilson) - **Douglas Wilson** + * [hacksparrow](https://github.com/hacksparrow) - **Hage Yaapa** + * [jonathanong](https://github.com/jonathanong) - **jongleberry** + * [niftylettuce](https://github.com/niftylettuce) - **niftylettuce** + * [troygoode](https://github.com/troygoode) - **Troy Goode** +
+ + +### Triagers + +* [aravindvnair99](https://github.com/aravindvnair99) - **Aravind Nair** +* [bjohansebas](https://github.com/bjohansebas) - **Sebastian Beltran** +* [carpasse](https://github.com/carpasse) - **Carlos Serrano** +* [CBID2](https://github.com/CBID2) - **Christine Belzie** +* [dpopp07](https://github.com/dpopp07) - **Dustin Popp** +* [UlisesGascon](https://github.com/UlisesGascon) - **Ulises Gascón** (he/him) +* [3imed-jaberi](https://github.com/3imed-jaberi) - **Imed Jaberi** +* [IamLizu](https://github.com/IamLizu) - **S M Mahmudul Hasan** (he/him) +* [Phillip9587](https://github.com/Phillip9587) - **Phillip Barta** +* [Sushmeet](https://github.com/Sushmeet) - **Sushmeet Sunger** +* [rxmarbles](https://github.com/rxmarbles) **Rick Markins** (He/him) + +
+Triagers emeriti members + +#### Emeritus Triagers + + * [AuggieH](https://github.com/AuggieH) - **Auggie Hudak** + * [G-Rath](https://github.com/G-Rath) - **Gareth Jones** + * [MohammadXroid](https://github.com/MohammadXroid) - **Mohammad Ayashi** + * [NawafSwe](https://github.com/NawafSwe) - **Nawaf Alsharqi** + * [NotMoni](https://github.com/NotMoni) - **Moni** + * [VigneshMurugan](https://github.com/VigneshMurugan) - **Vignesh Murugan** + * [davidmashe](https://github.com/davidmashe) - **David Ashe** + * [digitaIfabric](https://github.com/digitaIfabric) - **David** + * [e-l-i-s-e](https://github.com/e-l-i-s-e) - **Elise Bonner** + * [fed135](https://github.com/fed135) - **Frederic Charette** + * [firmanJS](https://github.com/firmanJS) - **Firman Abdul Hakim** + * [getspooky](https://github.com/getspooky) - **Yasser Ameur** + * [ghinks](https://github.com/ghinks) - **Glenn** + * [ghousemohamed](https://github.com/ghousemohamed) - **Ghouse Mohamed** + * [gireeshpunathil](https://github.com/gireeshpunathil) - **Gireesh Punathil** + * [jake32321](https://github.com/jake32321) - **Jake Reed** + * [jonchurch](https://github.com/jonchurch) - **Jon Church** + * [lekanikotun](https://github.com/lekanikotun) - **Troy Goode** + * [marsonya](https://github.com/marsonya) - **Lekan Ikotun** + * [mastermatt](https://github.com/mastermatt) - **Matt R. Wilson** + * [maxakuru](https://github.com/maxakuru) - **Max Edell** + * [mlrawlings](https://github.com/mlrawlings) - **Michael Rawlings** + * [rodion-arr](https://github.com/rodion-arr) - **Rodion Abdurakhimov** + * [sheplu](https://github.com/sheplu) - **Jean Burellier** + * [tarunyadav1](https://github.com/tarunyadav1) - **Tarun yadav** + * [tunniclm](https://github.com/tunniclm) - **Mike Tunnicliffe** + * [enyoghasim](https://github.com/enyoghasim) - **David Enyoghasim** + * [0ss](https://github.com/0ss) - **Salah** + * [import-brain](https://github.com/import-brain) - **Eric Cheng** (he/him) + * [dakshkhetan](https://github.com/dakshkhetan) - **Daksh Khetan** (he/him) + * [lucasraziel](https://github.com/lucasraziel) - **Lucas Soares Do Rego** + * [mertcanaltin](https://github.com/mertcanaltin) - **Mert Can Altin** + +
+ + +## License + + [MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/express/master +[coveralls-url]: https://coveralls.io/r/expressjs/express?branch=master +[github-actions-ci-image]: https://badgen.net/github/checks/expressjs/express/master?label=CI +[github-actions-ci-url]: https://github.com/expressjs/express/actions/workflows/ci.yml +[npm-downloads-image]: https://badgen.net/npm/dm/express +[npm-downloads-url]: https://npmcharts.com/compare/express?minimal=true +[npm-url]: https://npmjs.org/package/express +[npm-version-image]: https://badgen.net/npm/v/express +[ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/express/badge +[ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/express +[Code of Conduct]: https://github.com/expressjs/express/blob/master/Code-Of-Conduct.md diff --git a/node_modules/express/index.js b/node_modules/express/index.js new file mode 100644 index 0000000..d219b0c --- /dev/null +++ b/node_modules/express/index.js @@ -0,0 +1,11 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +module.exports = require('./lib/express'); diff --git a/node_modules/express/lib/application.js b/node_modules/express/lib/application.js new file mode 100644 index 0000000..cf6d78c --- /dev/null +++ b/node_modules/express/lib/application.js @@ -0,0 +1,631 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var finalhandler = require('finalhandler'); +var debug = require('debug')('express:application'); +var View = require('./view'); +var http = require('node:http'); +var methods = require('./utils').methods; +var compileETag = require('./utils').compileETag; +var compileQueryParser = require('./utils').compileQueryParser; +var compileTrust = require('./utils').compileTrust; +var resolve = require('node:path').resolve; +var once = require('once') +var Router = require('router'); + +/** + * Module variables. + * @private + */ + +var slice = Array.prototype.slice; +var flatten = Array.prototype.flat; + +/** + * Application prototype. + */ + +var app = exports = module.exports = {}; + +/** + * Variable for trust proxy inheritance back-compat + * @private + */ + +var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; + +/** + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + * + * @private + */ + +app.init = function init() { + var router = null; + + this.cache = Object.create(null); + this.engines = Object.create(null); + this.settings = Object.create(null); + + this.defaultConfiguration(); + + // Setup getting to lazily add base router + Object.defineProperty(this, 'router', { + configurable: true, + enumerable: true, + get: function getrouter() { + if (router === null) { + router = new Router({ + caseSensitive: this.enabled('case sensitive routing'), + strict: this.enabled('strict routing') + }); + } + + return router; + } + }); +}; + +/** + * Initialize application configuration. + * @private + */ + +app.defaultConfiguration = function defaultConfiguration() { + var env = process.env.NODE_ENV || 'development'; + + // default settings + this.enable('x-powered-by'); + this.set('etag', 'weak'); + this.set('env', env); + this.set('query parser', 'simple') + this.set('subdomain offset', 2); + this.set('trust proxy', false); + + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: true + }); + + debug('booting in %s mode', env); + + this.on('mount', function onmount(parent) { + // inherit trust proxy + if (this.settings[trustProxyDefaultSymbol] === true + && typeof parent.settings['trust proxy fn'] === 'function') { + delete this.settings['trust proxy']; + delete this.settings['trust proxy fn']; + } + + // inherit protos + Object.setPrototypeOf(this.request, parent.request) + Object.setPrototypeOf(this.response, parent.response) + Object.setPrototypeOf(this.engines, parent.engines) + Object.setPrototypeOf(this.settings, parent.settings) + }); + + // setup locals + this.locals = Object.create(null); + + // top-most app is mounted at / + this.mountpath = '/'; + + // default locals + this.locals.settings = this.settings; + + // default configuration + this.set('view', View); + this.set('views', resolve('views')); + this.set('jsonp callback name', 'callback'); + + if (env === 'production') { + this.enable('view cache'); + } +}; + +/** + * Dispatch a req, res pair into the application. Starts pipeline processing. + * + * If no callback is provided, then default error handlers will respond + * in the event of an error bubbling through the stack. + * + * @private + */ + +app.handle = function handle(req, res, callback) { + // final handler + var done = callback || finalhandler(req, res, { + env: this.get('env'), + onerror: logerror.bind(this) + }); + + // set powered by header + if (this.enabled('x-powered-by')) { + res.setHeader('X-Powered-By', 'Express'); + } + + // set circular references + req.res = res; + res.req = req; + + // alter the prototypes + Object.setPrototypeOf(req, this.request) + Object.setPrototypeOf(res, this.response) + + // setup locals + if (!res.locals) { + res.locals = Object.create(null); + } + + this.router.handle(req, res, done); +}; + +/** + * Proxy `Router#use()` to add middleware to the app router. + * See Router#use() documentation for details. + * + * If the _fn_ parameter is an express app, then it will be + * mounted at the _route_ specified. + * + * @public + */ + +app.use = function use(fn) { + var offset = 0; + var path = '/'; + + // default path to '/' + // disambiguate app.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } + + var fns = flatten.call(slice.call(arguments, offset), Infinity); + + if (fns.length === 0) { + throw new TypeError('app.use() requires a middleware function') + } + + // get router + var router = this.router; + + fns.forEach(function (fn) { + // non-express app + if (!fn || !fn.handle || !fn.set) { + return router.use(path, fn); + } + + debug('.use app under %s', path); + fn.mountpath = path; + fn.parent = this; + + // restore .app property on req and res + router.use(path, function mounted_app(req, res, next) { + var orig = req.app; + fn.handle(req, res, function (err) { + Object.setPrototypeOf(req, orig.request) + Object.setPrototypeOf(res, orig.response) + next(err); + }); + }); + + // mounted an app + fn.emit('mount', this); + }, this); + + return this; +}; + +/** + * Proxy to the app `Router#route()` + * Returns a new `Route` instance for the _path_. + * + * Routes are isolated middleware stacks for specific paths. + * See the Route api docs for details. + * + * @public + */ + +app.route = function route(path) { + return this.router.route(path); +}; + +/** + * Register the given template engine callback `fn` + * as `ext`. + * + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.ejs" file Express will invoke the following internally: + * + * app.engine('ejs', require('ejs').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you don't need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/tj/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + * + * @param {String} ext + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +app.engine = function engine(ext, fn) { + if (typeof fn !== 'function') { + throw new Error('callback function required'); + } + + // get file extension + var extension = ext[0] !== '.' + ? '.' + ext + : ext; + + // store engine + this.engines[extension] = fn; + + return this; +}; + +/** + * Proxy to `Router#param()` with one added api feature. The _name_ parameter + * can be an array of names. + * + * See the Router#param() docs for more details. + * + * @param {String|Array} name + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +app.param = function param(name, fn) { + if (Array.isArray(name)) { + for (var i = 0; i < name.length; i++) { + this.param(name[i], fn); + } + + return this; + } + + this.router.param(name, fn); + + return this; +}; + +/** + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.set('foo'); + * // => "bar" + * + * Mounted servers inherit their parent server's settings. + * + * @param {String} setting + * @param {*} [val] + * @return {Server} for chaining + * @public + */ + +app.set = function set(setting, val) { + if (arguments.length === 1) { + // app.get(setting) + return this.settings[setting]; + } + + debug('set "%s" to %o', setting, val); + + // set value + this.settings[setting] = val; + + // trigger matched settings + switch (setting) { + case 'etag': + this.set('etag fn', compileETag(val)); + break; + case 'query parser': + this.set('query parser fn', compileQueryParser(val)); + break; + case 'trust proxy': + this.set('trust proxy fn', compileTrust(val)); + + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: false + }); + + break; + } + + return this; +}; + +/** + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". + * + * @return {String} + * @private + */ + +app.path = function path() { + return this.parent + ? this.parent.path() + this.mountpath + : ''; +}; + +/** + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + * + * @param {String} setting + * @return {Boolean} + * @public + */ + +app.enabled = function enabled(setting) { + return Boolean(this.set(setting)); +}; + +/** + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + * + * @param {String} setting + * @return {Boolean} + * @public + */ + +app.disabled = function disabled(setting) { + return !this.set(setting); +}; + +/** + * Enable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.enable = function enable(setting) { + return this.set(setting, true); +}; + +/** + * Disable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.disable = function disable(setting) { + return this.set(setting, false); +}; + +/** + * Delegate `.VERB(...)` calls to `router.VERB(...)`. + */ + +methods.forEach(function (method) { + app[method] = function (path) { + if (method === 'get' && arguments.length === 1) { + // app.get(setting) + return this.set(path); + } + + var route = this.route(path); + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); + +/** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + * + * @param {String} path + * @param {Function} ... + * @return {app} for chaining + * @public + */ + +app.all = function all(path) { + var route = this.route(path); + var args = slice.call(arguments, 1); + + for (var i = 0; i < methods.length; i++) { + route[methods[i]].apply(route, args); + } + + return this; +}; + +/** + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. + * + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + * + * @param {String} name + * @param {Object|Function} options or fn + * @param {Function} callback + * @public + */ + +app.render = function render(name, options, callback) { + var cache = this.cache; + var done = callback; + var engines = this.engines; + var opts = options; + var view; + + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // merge options + var renderOptions = { ...this.locals, ...opts._locals, ...opts }; + + // set .cache unless explicitly provided + if (renderOptions.cache == null) { + renderOptions.cache = this.enabled('view cache'); + } + + // primed cache + if (renderOptions.cache) { + view = cache[name]; + } + + // view + if (!view) { + var View = this.get('view'); + + view = new View(name, { + defaultEngine: this.get('view engine'), + root: this.get('views'), + engines: engines + }); + + if (!view.path) { + var dirs = Array.isArray(view.root) && view.root.length > 1 + ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' + : 'directory "' + view.root + '"' + var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); + err.view = view; + return done(err); + } + + // prime the cache + if (renderOptions.cache) { + cache[name] = view; + } + } + + // render + tryRender(view, renderOptions, done); +}; + +/** + * Listen for connections. + * + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('node:http') + * , https = require('node:https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + * + * @return {http.Server} + * @public + */ + +app.listen = function listen() { + var server = http.createServer(this) + var args = Array.prototype.slice.call(arguments) + if (typeof args[args.length - 1] === 'function') { + var done = args[args.length - 1] = once(args[args.length - 1]) + server.once('error', done) + } + return server.listen.apply(server, args) +} + +/** + * Log error using console.error. + * + * @param {Error} err + * @private + */ + +function logerror(err) { + /* istanbul ignore next */ + if (this.get('env') !== 'test') console.error(err.stack || err.toString()); +} + +/** + * Try rendering a view. + * @private + */ + +function tryRender(view, options, callback) { + try { + view.render(options, callback); + } catch (err) { + callback(err); + } +} diff --git a/node_modules/express/lib/express.js b/node_modules/express/lib/express.js new file mode 100644 index 0000000..2d502eb --- /dev/null +++ b/node_modules/express/lib/express.js @@ -0,0 +1,81 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + */ + +var bodyParser = require('body-parser') +var EventEmitter = require('node:events').EventEmitter; +var mixin = require('merge-descriptors'); +var proto = require('./application'); +var Router = require('router'); +var req = require('./request'); +var res = require('./response'); + +/** + * Expose `createApplication()`. + */ + +exports = module.exports = createApplication; + +/** + * Create an express application. + * + * @return {Function} + * @api public + */ + +function createApplication() { + var app = function(req, res, next) { + app.handle(req, res, next); + }; + + mixin(app, EventEmitter.prototype, false); + mixin(app, proto, false); + + // expose the prototype that will get set on requests + app.request = Object.create(req, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) + + // expose the prototype that will get set on responses + app.response = Object.create(res, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) + + app.init(); + return app; +} + +/** + * Expose the prototypes. + */ + +exports.application = proto; +exports.request = req; +exports.response = res; + +/** + * Expose constructors. + */ + +exports.Route = Router.Route; +exports.Router = Router; + +/** + * Expose middleware + */ + +exports.json = bodyParser.json +exports.raw = bodyParser.raw +exports.static = require('serve-static'); +exports.text = bodyParser.text +exports.urlencoded = bodyParser.urlencoded diff --git a/node_modules/express/lib/request.js b/node_modules/express/lib/request.js new file mode 100644 index 0000000..d8e5263 --- /dev/null +++ b/node_modules/express/lib/request.js @@ -0,0 +1,515 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var accepts = require('accepts'); +var isIP = require('node:net').isIP; +var typeis = require('type-is'); +var http = require('node:http'); +var fresh = require('fresh'); +var parseRange = require('range-parser'); +var parse = require('parseurl'); +var proxyaddr = require('proxy-addr'); + +/** + * Request prototype. + * @public + */ + +var req = Object.create(http.IncomingMessage.prototype) + +/** + * Module exports. + * @public + */ + +module.exports = req + +/** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + * + * @param {String} name + * @return {String} + * @public + */ + +req.get = +req.header = function header(name) { + if (!name) { + throw new TypeError('name argument is required to req.get'); + } + + if (typeof name !== 'string') { + throw new TypeError('name must be a string to req.get'); + } + + var lc = name.toLowerCase(); + + switch (lc) { + case 'referer': + case 'referrer': + return this.headers.referrer + || this.headers.referer; + default: + return this.headers[lc]; + } +}; + +/** + * To do: update docs. + * + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single MIME type string + * such as "application/json", an extension name + * such as "json", a comma-delimited list such as "json, html, text/plain", + * an argument list such as `"json", "html", "text/plain"`, + * or an array `["json", "html", "text/plain"]`. When a list + * or array is given, the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html', 'json'); + * req.accepts('html, json'); + * // => "json" + * + * @param {String|Array} type(s) + * @return {String|Array|Boolean} + * @public + */ + +req.accepts = function(){ + var accept = accepts(this); + return accept.types.apply(accept, arguments); +}; + +/** + * Check if the given `encoding`s are accepted. + * + * @param {String} ...encoding + * @return {String|Array} + * @public + */ + +req.acceptsEncodings = function(){ + var accept = accepts(this); + return accept.encodings.apply(accept, arguments); +}; + +/** + * Check if the given `charset`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...charset + * @return {String|Array} + * @public + */ + +req.acceptsCharsets = function(){ + var accept = accepts(this); + return accept.charsets.apply(accept, arguments); +}; + +/** + * Check if the given `lang`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...lang + * @return {String|Array} + * @public + */ + +req.acceptsLanguages = function(){ + var accept = accepts(this); + return accept.languages.apply(accept, arguments); +}; + +/** + * Parse Range header field, capping to the given `size`. + * + * Unspecified ranges such as "0-" require knowledge of your resource length. In + * the case of a byte range this is of course the total number of bytes. If the + * Range header field is not given `undefined` is returned, `-1` when unsatisfiable, + * and `-2` when syntactically invalid. + * + * When ranges are returned, the array has a "type" property which is the type of + * range that is required (most commonly, "bytes"). Each array element is an object + * with a "start" and "end" property for the portion of the range. + * + * The "combine" option can be set to `true` and overlapping & adjacent ranges + * will be combined into a single range. + * + * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" + * should respond with 4 users when available, not 3. + * + * @param {number} size + * @param {object} [options] + * @param {boolean} [options.combine=false] + * @return {number|array} + * @public + */ + +req.range = function range(size, options) { + var range = this.get('Range'); + if (!range) return; + return parseRange(size, range, options); +}; + +/** + * Parse the query string of `req.url`. + * + * This uses the "query parser" setting to parse the raw + * string into an object. + * + * @return {String} + * @api public + */ + +defineGetter(req, 'query', function query(){ + var queryparse = this.app.get('query parser fn'); + + if (!queryparse) { + // parsing is disabled + return Object.create(null); + } + + var querystring = parse(this).query; + + return queryparse(querystring); +}); + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the given mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public + */ + +req.is = function is(types) { + var arr = types; + + // support flattened arguments + if (!Array.isArray(types)) { + arr = new Array(arguments.length); + for (var i = 0; i < arr.length; i++) { + arr[i] = arguments[i]; + } + } + + return typeis(this, arr); +}; + +/** + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting trusts the socket address, the + * "X-Forwarded-Proto" header field will be trusted + * and used if present. + * + * If you're running behind a reverse proxy that + * supplies https for you this may be enabled. + * + * @return {String} + * @public + */ + +defineGetter(req, 'protocol', function protocol(){ + var proto = this.connection.encrypted + ? 'https' + : 'http'; + var trust = this.app.get('trust proxy fn'); + + if (!trust(this.connection.remoteAddress, 0)) { + return proto; + } + + // Note: X-Forwarded-Proto is normally only ever a + // single value, but this is to be safe. + var header = this.get('X-Forwarded-Proto') || proto + var index = header.indexOf(',') + + return index !== -1 + ? header.substring(0, index).trim() + : header.trim() +}); + +/** + * Short-hand for: + * + * req.protocol === 'https' + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'secure', function secure(){ + return this.protocol === 'https'; +}); + +/** + * Return the remote address from the trusted proxy. + * + * The is the remote address on the socket unless + * "trust proxy" is set. + * + * @return {String} + * @public + */ + +defineGetter(req, 'ip', function ip(){ + var trust = this.app.get('trust proxy fn'); + return proxyaddr(this, trust); +}); + +/** + * When "trust proxy" is set, trusted proxy addresses + client. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream and "proxy1" and + * "proxy2" were trusted. + * + * @return {Array} + * @public + */ + +defineGetter(req, 'ips', function ips() { + var trust = this.app.get('trust proxy fn'); + var addrs = proxyaddr.all(this, trust); + + // reverse the order (to farthest -> closest) + // and remove socket address + addrs.reverse().pop() + + return addrs +}); + +/** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + * + * @return {Array} + * @public + */ + +defineGetter(req, 'subdomains', function subdomains() { + var hostname = this.hostname; + + if (!hostname) return []; + + var offset = this.app.get('subdomain offset'); + var subdomains = !isIP(hostname) + ? hostname.split('.').reverse() + : [hostname]; + + return subdomains.slice(offset); +}); + +/** + * Short-hand for `url.parse(req.url).pathname`. + * + * @return {String} + * @public + */ + +defineGetter(req, 'path', function path() { + return parse(this).pathname; +}); + +/** + * Parse the "Host" header field to a host. + * + * When the "trust proxy" setting trusts the socket + * address, the "X-Forwarded-Host" header field will + * be trusted. + * + * @return {String} + * @public + */ + +defineGetter(req, 'host', function host(){ + var trust = this.app.get('trust proxy fn'); + var val = this.get('X-Forwarded-Host'); + + if (!val || !trust(this.connection.remoteAddress, 0)) { + val = this.get('Host'); + } else if (val.indexOf(',') !== -1) { + // Note: X-Forwarded-Host is normally only ever a + // single value, but this is to be safe. + val = val.substring(0, val.indexOf(',')).trimRight() + } + + return val || undefined; +}); + +/** + * Parse the "Host" header field to a hostname. + * + * When the "trust proxy" setting trusts the socket + * address, the "X-Forwarded-Host" header field will + * be trusted. + * + * @return {String} + * @api public + */ + +defineGetter(req, 'hostname', function hostname(){ + var host = this.host; + + if (!host) return; + + // IPv6 literal support + var offset = host[0] === '[' + ? host.indexOf(']') + 1 + : 0; + var index = host.indexOf(':', offset); + + return index !== -1 + ? host.substring(0, index) + : host; +}); + +/** + * Check if the request is fresh, aka + * Last-Modified or the ETag + * still match. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'fresh', function(){ + var method = this.method; + var res = this.res + var status = res.statusCode + + // GET or HEAD for weak freshness validation only + if ('GET' !== method && 'HEAD' !== method) return false; + + // 2xx or 304 as per rfc2616 14.26 + if ((status >= 200 && status < 300) || 304 === status) { + return fresh(this.headers, { + 'etag': res.get('ETag'), + 'last-modified': res.get('Last-Modified') + }) + } + + return false; +}); + +/** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'stale', function stale(){ + return !this.fresh; +}); + +/** + * Check if the request was an _XMLHttpRequest_. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'xhr', function xhr(){ + var val = this.get('X-Requested-With') || ''; + return val.toLowerCase() === 'xmlhttprequest'; +}); + +/** + * Helper function for creating a getter on an object. + * + * @param {Object} obj + * @param {String} name + * @param {Function} getter + * @private + */ +function defineGetter(obj, name, getter) { + Object.defineProperty(obj, name, { + configurable: true, + enumerable: true, + get: getter + }); +} diff --git a/node_modules/express/lib/response.js b/node_modules/express/lib/response.js new file mode 100644 index 0000000..9362d0e --- /dev/null +++ b/node_modules/express/lib/response.js @@ -0,0 +1,1039 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var contentDisposition = require('content-disposition'); +var createError = require('http-errors') +var encodeUrl = require('encodeurl'); +var escapeHtml = require('escape-html'); +var http = require('node:http'); +var onFinished = require('on-finished'); +var mime = require('mime-types') +var path = require('node:path'); +var pathIsAbsolute = require('node:path').isAbsolute; +var statuses = require('statuses') +var sign = require('cookie-signature').sign; +var normalizeType = require('./utils').normalizeType; +var normalizeTypes = require('./utils').normalizeTypes; +var setCharset = require('./utils').setCharset; +var cookie = require('cookie'); +var send = require('send'); +var extname = path.extname; +var resolve = path.resolve; +var vary = require('vary'); + +/** + * Response prototype. + * @public + */ + +var res = Object.create(http.ServerResponse.prototype) + +/** + * Module exports. + * @public + */ + +module.exports = res + +/** + * Set the HTTP status code for the response. + * + * Expects an integer value between 100 and 999 inclusive. + * Throws an error if the provided status code is not an integer or if it's outside the allowable range. + * + * @param {number} code - The HTTP status code to set. + * @return {ServerResponse} - Returns itself for chaining methods. + * @throws {TypeError} If `code` is not an integer. + * @throws {RangeError} If `code` is outside the range 100 to 999. + * @public + */ + +res.status = function status(code) { + // Check if the status code is not an integer + if (!Number.isInteger(code)) { + throw new TypeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be an integer.`); + } + // Check if the status code is outside of Node's valid range + if (code < 100 || code > 999) { + throw new RangeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be greater than 99 and less than 1000.`); + } + + this.statusCode = code; + return this; +}; + +/** + * Set Link header field with the given `links`. + * + * Examples: + * + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5', + * pages: [ + * 'http://api.example.com/users?page=1', + * 'http://api.example.com/users?page=2' + * ] + * }); + * + * @param {Object} links + * @return {ServerResponse} + * @public + */ + +res.links = function(links) { + var link = this.get('Link') || ''; + if (link) link += ', '; + return this.set('Link', link + Object.keys(links).map(function(rel) { + // Allow multiple links if links[rel] is an array + if (Array.isArray(links[rel])) { + return links[rel].map(function (singleLink) { + return `<${singleLink}>; rel="${rel}"`; + }).join(', '); + } else { + return `<${links[rel]}>; rel="${rel}"`; + } + }).join(', ')); +}; + +/** + * Send a response. + * + * Examples: + * + * res.send(Buffer.from('wahoo')); + * res.send({ some: 'json' }); + * res.send('

some html

'); + * + * @param {string|number|boolean|object|Buffer} body + * @public + */ + +res.send = function send(body) { + var chunk = body; + var encoding; + var req = this.req; + var type; + + // settings + var app = this.app; + + switch (typeof chunk) { + // string defaulting to html + case 'string': + if (!this.get('Content-Type')) { + this.type('html'); + } + break; + case 'boolean': + case 'number': + case 'object': + if (chunk === null) { + chunk = ''; + } else if (ArrayBuffer.isView(chunk)) { + if (!this.get('Content-Type')) { + this.type('bin'); + } + } else { + return this.json(chunk); + } + break; + } + + // write strings in utf-8 + if (typeof chunk === 'string') { + encoding = 'utf8'; + type = this.get('Content-Type'); + + // reflect this in content-type + if (typeof type === 'string') { + this.set('Content-Type', setCharset(type, 'utf-8')); + } + } + + // determine if ETag should be generated + var etagFn = app.get('etag fn') + var generateETag = !this.get('ETag') && typeof etagFn === 'function' + + // populate Content-Length + var len + if (chunk !== undefined) { + if (Buffer.isBuffer(chunk)) { + // get length of Buffer + len = chunk.length + } else if (!generateETag && chunk.length < 1000) { + // just calculate length when no ETag + small chunk + len = Buffer.byteLength(chunk, encoding) + } else { + // convert chunk to Buffer and calculate + chunk = Buffer.from(chunk, encoding) + encoding = undefined; + len = chunk.length + } + + this.set('Content-Length', len); + } + + // populate ETag + var etag; + if (generateETag && len !== undefined) { + if ((etag = etagFn(chunk, encoding))) { + this.set('ETag', etag); + } + } + + // freshness + if (req.fresh) this.status(304); + + // strip irrelevant headers + if (204 === this.statusCode || 304 === this.statusCode) { + this.removeHeader('Content-Type'); + this.removeHeader('Content-Length'); + this.removeHeader('Transfer-Encoding'); + chunk = ''; + } + + // alter headers for 205 + if (this.statusCode === 205) { + this.set('Content-Length', '0') + this.removeHeader('Transfer-Encoding') + chunk = '' + } + + if (req.method === 'HEAD') { + // skip body for HEAD + this.end(); + } else { + // respond + this.end(chunk, encoding); + } + + return this; +}; + +/** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ + +res.json = function json(obj) { + // settings + var app = this.app; + var escape = app.get('json escape') + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = stringify(obj, replacer, spaces, escape) + + // content-type + if (!this.get('Content-Type')) { + this.set('Content-Type', 'application/json'); + } + + return this.send(body); +}; + +/** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ + +res.jsonp = function jsonp(obj) { + // settings + var app = this.app; + var escape = app.get('json escape') + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = stringify(obj, replacer, spaces, escape) + var callback = this.req.query[app.get('jsonp callback name')]; + + // content-type + if (!this.get('Content-Type')) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'application/json'); + } + + // fixup callback + if (Array.isArray(callback)) { + callback = callback[0]; + } + + // jsonp + if (typeof callback === 'string' && callback.length !== 0) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'text/javascript'); + + // restrict callback charset + callback = callback.replace(/[^\[\]\w$.]/g, ''); + + if (body === undefined) { + // empty argument + body = '' + } else if (typeof body === 'string') { + // replace chars not allowed in JavaScript that are in JSON + body = body + .replace(/\u2028/g, '\\u2028') + .replace(/\u2029/g, '\\u2029') + } + + // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" + // the typeof check is just to reduce client error noise + body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; + } + + return this.send(body); +}; + +/** + * Send given HTTP status code. + * + * Sets the response status to `statusCode` and the body of the + * response to the standard description from node's http.STATUS_CODES + * or the statusCode number if no description. + * + * Examples: + * + * res.sendStatus(200); + * + * @param {number} statusCode + * @public + */ + +res.sendStatus = function sendStatus(statusCode) { + var body = statuses.message[statusCode] || String(statusCode) + + this.status(statusCode); + this.type('txt'); + + return this.send(body); +}; + +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.headersSent` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendFile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendFile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendFile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public + */ + +res.sendFile = function sendFile(path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; + + if (!path) { + throw new TypeError('path argument is required to res.sendFile'); + } + + if (typeof path !== 'string') { + throw new TypeError('path must be a string to res.sendFile') + } + + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + if (!opts.root && !pathIsAbsolute(path)) { + throw new TypeError('path must be absolute or specify root to res.sendFile'); + } + + // create file stream + var pathname = encodeURI(path); + + // wire application etag option to send + opts.etag = this.app.enabled('etag'); + var file = send(req, pathname, opts); + + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); + + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); + } + }); +}; + +/** + * Transfer the file at the given `path` as an attachment. + * + * Optionally providing an alternate attachment `filename`, + * and optional callback `callback(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * occurred. Be sure to check `res.headersSent` if you plan to respond. + * + * Optionally providing an `options` object to use with `res.sendFile()`. + * This function will set the `Content-Disposition` header, overriding + * any `Content-Disposition` header passed as header options in order + * to set the attachment and filename. + * + * This method uses `res.sendFile()`. + * + * @public + */ + +res.download = function download (path, filename, options, callback) { + var done = callback; + var name = filename; + var opts = options || null + + // support function as second or third arg + if (typeof filename === 'function') { + done = filename; + name = null; + opts = null + } else if (typeof options === 'function') { + done = options + opts = null + } + + // support optional filename, where options may be in it's place + if (typeof filename === 'object' && + (typeof options === 'function' || options === undefined)) { + name = null + opts = filename + } + + // set Content-Disposition when file is sent + var headers = { + 'Content-Disposition': contentDisposition(name || path) + }; + + // merge user-provided headers + if (opts && opts.headers) { + var keys = Object.keys(opts.headers) + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + if (key.toLowerCase() !== 'content-disposition') { + headers[key] = opts.headers[key] + } + } + } + + // merge user-provided options + opts = Object.create(opts) + opts.headers = headers + + // Resolve the full path for sendFile + var fullPath = !opts.root + ? resolve(path) + : path + + // send file + return this.sendFile(fullPath, opts, done) +}; + +/** + * Set _Content-Type_ response header with `type` through `mime.contentType()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * When no mapping is found though `mime.contentType()`, the type is set to + * "application/octet-stream". + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param {String} type + * @return {ServerResponse} for chaining + * @public + */ + +res.contentType = +res.type = function contentType(type) { + var ct = type.indexOf('/') === -1 + ? (mime.contentType(type) || 'application/octet-stream') + : type; + + return this.set('Content-Type', ct); +}; + +/** + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. + * + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". + * + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. + * + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, + * + * 'text/html': function(){ + * res.send('

hey

'); + * }, + * + * 'application/json': function () { + * res.send({ message: 'hey' }); + * } + * }); + * + * In addition to canonicalized MIME types you may + * also use extnames mapped to these types: + * + * res.format({ + * text: function(){ + * res.send('hey'); + * }, + * + * html: function(){ + * res.send('

hey

'); + * }, + * + * json: function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * By default Express passes an `Error` + * with a `.status` of 406 to `next(err)` + * if a match is not made. If you provide + * a `.default` callback it will be invoked + * instead. + * + * @param {Object} obj + * @return {ServerResponse} for chaining + * @public + */ + +res.format = function(obj){ + var req = this.req; + var next = req.next; + + var keys = Object.keys(obj) + .filter(function (v) { return v !== 'default' }) + + var key = keys.length > 0 + ? req.accepts(keys) + : false; + + this.vary("Accept"); + + if (key) { + this.set('Content-Type', normalizeType(key).value); + obj[key](req, this, next); + } else if (obj.default) { + obj.default(req, this, next) + } else { + next(createError(406, { + types: normalizeTypes(keys).map(function (o) { return o.value }) + })) + } + + return this; +}; + +/** + * Set _Content-Disposition_ header to _attachment_ with optional `filename`. + * + * @param {String} filename + * @return {ServerResponse} + * @public + */ + +res.attachment = function attachment(filename) { + if (filename) { + this.type(extname(filename)); + } + + this.set('Content-Disposition', contentDisposition(filename)); + + return this; +}; + +/** + * Append additional header `field` with value `val`. + * + * Example: + * + * res.append('Link', ['', '']); + * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); + * res.append('Warning', '199 Miscellaneous warning'); + * + * @param {String} field + * @param {String|Array} val + * @return {ServerResponse} for chaining + * @public + */ + +res.append = function append(field, val) { + var prev = this.get(field); + var value = val; + + if (prev) { + // concat the new and prev vals + value = Array.isArray(prev) ? prev.concat(val) + : Array.isArray(val) ? [prev].concat(val) + : [prev, val] + } + + return this.set(field, value); +}; + +/** + * Set header `field` to `val`, or pass + * an object of header fields. + * + * Examples: + * + * res.set('Foo', ['bar', 'baz']); + * res.set('Accept', 'application/json'); + * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + * + * Aliased as `res.header()`. + * + * When the set header is "Content-Type", the type is expanded to include + * the charset if not present using `mime.contentType()`. + * + * @param {String|Object} field + * @param {String|Array} val + * @return {ServerResponse} for chaining + * @public + */ + +res.set = +res.header = function header(field, val) { + if (arguments.length === 2) { + var value = Array.isArray(val) + ? val.map(String) + : String(val); + + // add charset to content-type + if (field.toLowerCase() === 'content-type') { + if (Array.isArray(value)) { + throw new TypeError('Content-Type cannot be set to an Array'); + } + value = mime.contentType(value) + } + + this.setHeader(field, value); + } else { + for (var key in field) { + this.set(key, field[key]); + } + } + return this; +}; + +/** + * Get value for header `field`. + * + * @param {String} field + * @return {String} + * @public + */ + +res.get = function(field){ + return this.getHeader(field); +}; + +/** + * Clear cookie `name`. + * + * @param {String} name + * @param {Object} [options] + * @return {ServerResponse} for chaining + * @public + */ + +res.clearCookie = function clearCookie(name, options) { + // Force cookie expiration by setting expires to the past + const opts = { path: '/', ...options, expires: new Date(1)}; + // ensure maxAge is not passed + delete opts.maxAge + + return this.cookie(name, '', opts); +}; + +/** + * Set cookie `name` to `value`, with the given `options`. + * + * Options: + * + * - `maxAge` max-age in milliseconds, converted to `expires` + * - `signed` sign the cookie + * - `path` defaults to "/" + * + * Examples: + * + * // "Remember Me" for 15 minutes + * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + * + * // same as above + * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) + * + * @param {String} name + * @param {String|Object} value + * @param {Object} [options] + * @return {ServerResponse} for chaining + * @public + */ + +res.cookie = function (name, value, options) { + var opts = { ...options }; + var secret = this.req.secret; + var signed = opts.signed; + + if (signed && !secret) { + throw new Error('cookieParser("secret") required for signed cookies'); + } + + var val = typeof value === 'object' + ? 'j:' + JSON.stringify(value) + : String(value); + + if (signed) { + val = 's:' + sign(val, secret); + } + + if (opts.maxAge != null) { + var maxAge = opts.maxAge - 0 + + if (!isNaN(maxAge)) { + opts.expires = new Date(Date.now() + maxAge) + opts.maxAge = Math.floor(maxAge / 1000) + } + } + + if (opts.path == null) { + opts.path = '/'; + } + + this.append('Set-Cookie', cookie.serialize(name, String(val), opts)); + + return this; +}; + +/** + * Set the location header to `url`. + * + * The given `url` can also be "back", which redirects + * to the _Referrer_ or _Referer_ headers or "/". + * + * Examples: + * + * res.location('/foo/bar').; + * res.location('http://example.com'); + * res.location('../login'); + * + * @param {String} url + * @return {ServerResponse} for chaining + * @public + */ + +res.location = function location(url) { + return this.set('Location', encodeUrl(url)); +}; + +/** + * Redirect to the given `url` with optional response `status` + * defaulting to 302. + * + * Examples: + * + * res.redirect('/foo/bar'); + * res.redirect('http://example.com'); + * res.redirect(301, 'http://example.com'); + * res.redirect('../login'); // /blog/post/1 -> /blog/login + * + * @public + */ + +res.redirect = function redirect(url) { + var address = url; + var body; + var status = 302; + + // allow status / url + if (arguments.length === 2) { + status = arguments[0] + address = arguments[1] + } + + // Set location header + address = this.location(address).get('Location'); + + // Support text/{plain,html} by default + this.format({ + text: function(){ + body = statuses.message[status] + '. Redirecting to ' + address + }, + + html: function(){ + var u = escapeHtml(address); + body = '

' + statuses.message[status] + '. Redirecting to ' + u + '

' + }, + + default: function(){ + body = ''; + } + }); + + // Respond + this.status(status); + this.set('Content-Length', Buffer.byteLength(body)); + + if (this.req.method === 'HEAD') { + this.end(); + } else { + this.end(body); + } +}; + +/** + * Add `field` to Vary. If already present in the Vary set, then + * this call is simply ignored. + * + * @param {Array|String} field + * @return {ServerResponse} for chaining + * @public + */ + +res.vary = function(field){ + vary(this, field); + + return this; +}; + +/** + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. + * + * Options: + * + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered + * + * @public + */ + +res.render = function render(view, options, callback) { + var app = this.req.app; + var done = callback; + var opts = options || {}; + var req = this.req; + var self = this; + + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // merge res.locals + opts._locals = self.locals; + + // default callback to respond + done = done || function (err, str) { + if (err) return req.next(err); + self.send(str); + }; + + // render + app.render(view, opts, done); +}; + +// pipe the send file stream +function sendfile(res, file, options, callback) { + var done = false; + var streaming; + + // request aborted + function onaborted() { + if (done) return; + done = true; + + var err = new Error('Request aborted'); + err.code = 'ECONNABORTED'; + callback(err); + } + + // directory + function ondirectory() { + if (done) return; + done = true; + + var err = new Error('EISDIR, read'); + err.code = 'EISDIR'; + callback(err); + } + + // errors + function onerror(err) { + if (done) return; + done = true; + callback(err); + } + + // ended + function onend() { + if (done) return; + done = true; + callback(); + } + + // file + function onfile() { + streaming = false; + } + + // finished + function onfinish(err) { + if (err && err.code === 'ECONNRESET') return onaborted(); + if (err) return onerror(err); + if (done) return; + + setImmediate(function () { + if (streaming !== false && !done) { + onaborted(); + return; + } + + if (done) return; + done = true; + callback(); + }); + } + + // streaming + function onstream() { + streaming = true; + } + + file.on('directory', ondirectory); + file.on('end', onend); + file.on('error', onerror); + file.on('file', onfile); + file.on('stream', onstream); + onFinished(res, onfinish); + + if (options.headers) { + // set headers on successful transfer + file.on('headers', function headers(res) { + var obj = options.headers; + var keys = Object.keys(obj); + + for (var i = 0; i < keys.length; i++) { + var k = keys[i]; + res.setHeader(k, obj[k]); + } + }); + } + + // pipe + file.pipe(res); +} + +/** + * Stringify JSON, like JSON.stringify, but v8 optimized, with the + * ability to escape characters that can trigger HTML sniffing. + * + * @param {*} value + * @param {function} replacer + * @param {number} spaces + * @param {boolean} escape + * @returns {string} + * @private + */ + +function stringify (value, replacer, spaces, escape) { + // v8 checks arguments.length for optimizing simple call + // https://bugs.chromium.org/p/v8/issues/detail?id=4730 + var json = replacer || spaces + ? JSON.stringify(value, replacer, spaces) + : JSON.stringify(value); + + if (escape && typeof json === 'string') { + json = json.replace(/[<>&]/g, function (c) { + switch (c.charCodeAt(0)) { + case 0x3c: + return '\\u003c' + case 0x3e: + return '\\u003e' + case 0x26: + return '\\u0026' + /* istanbul ignore next: unreachable default */ + default: + return c + } + }) + } + + return json +} diff --git a/node_modules/express/lib/utils.js b/node_modules/express/lib/utils.js new file mode 100644 index 0000000..d53c5a1 --- /dev/null +++ b/node_modules/express/lib/utils.js @@ -0,0 +1,269 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @api private + */ + +var { METHODS } = require('node:http'); +var contentType = require('content-type'); +var etag = require('etag'); +var mime = require('mime-types') +var proxyaddr = require('proxy-addr'); +var qs = require('qs'); +var querystring = require('querystring'); + +/** + * A list of lowercased HTTP methods that are supported by Node.js. + * @api private + */ +exports.methods = METHODS.map((method) => method.toLowerCase()); + +/** + * Return strong ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.etag = createETagGenerator({ weak: false }) + +/** + * Return weak ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.wetag = createETagGenerator({ weak: true }) + +/** + * Normalize the given `type`, for example "html" becomes "text/html". + * + * @param {String} type + * @return {Object} + * @api private + */ + +exports.normalizeType = function(type){ + return ~type.indexOf('/') + ? acceptParams(type) + : { value: (mime.lookup(type) || 'application/octet-stream'), params: {} } +}; + +/** + * Normalize `types`, for example "html" becomes "text/html". + * + * @param {Array} types + * @return {Array} + * @api private + */ + +exports.normalizeTypes = function(types) { + return types.map(exports.normalizeType); +}; + + +/** + * Parse accept params `str` returning an + * object with `.value`, `.quality` and `.params`. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function acceptParams (str) { + var length = str.length; + var colonIndex = str.indexOf(';'); + var index = colonIndex === -1 ? length : colonIndex; + var ret = { value: str.slice(0, index).trim(), quality: 1, params: {} }; + + while (index < length) { + var splitIndex = str.indexOf('=', index); + if (splitIndex === -1) break; + + var colonIndex = str.indexOf(';', index); + var endIndex = colonIndex === -1 ? length : colonIndex; + + if (splitIndex > endIndex) { + index = str.lastIndexOf(';', splitIndex - 1) + 1; + continue; + } + + var key = str.slice(index, splitIndex).trim(); + var value = str.slice(splitIndex + 1, endIndex).trim(); + + if (key === 'q') { + ret.quality = parseFloat(value); + } else { + ret.params[key] = value; + } + + index = endIndex + 1; + } + + return ret; +} + +/** + * Compile "etag" value to function. + * + * @param {Boolean|String|Function} val + * @return {Function} + * @api private + */ + +exports.compileETag = function(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + case 'weak': + fn = exports.wetag; + break; + case false: + break; + case 'strong': + fn = exports.etag; + break; + default: + throw new TypeError('unknown value for etag function: ' + val); + } + + return fn; +} + +/** + * Compile "query parser" value to function. + * + * @param {String|Function} val + * @return {Function} + * @api private + */ + +exports.compileQueryParser = function compileQueryParser(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + case 'simple': + fn = querystring.parse; + break; + case false: + break; + case 'extended': + fn = parseExtendedQueryString; + break; + default: + throw new TypeError('unknown value for query parser function: ' + val); + } + + return fn; +} + +/** + * Compile "proxy trust" value to function. + * + * @param {Boolean|String|Number|Array|Function} val + * @return {Function} + * @api private + */ + +exports.compileTrust = function(val) { + if (typeof val === 'function') return val; + + if (val === true) { + // Support plain true/false + return function(){ return true }; + } + + if (typeof val === 'number') { + // Support trusting hop count + return function(a, i){ return i < val }; + } + + if (typeof val === 'string') { + // Support comma-separated values + val = val.split(',') + .map(function (v) { return v.trim() }) + } + + return proxyaddr.compile(val || []); +} + +/** + * Set the charset in a given Content-Type string. + * + * @param {String} type + * @param {String} charset + * @return {String} + * @api private + */ + +exports.setCharset = function setCharset(type, charset) { + if (!type || !charset) { + return type; + } + + // parse type + var parsed = contentType.parse(type); + + // set charset + parsed.parameters.charset = charset; + + // format type + return contentType.format(parsed); +}; + +/** + * Create an ETag generator function, generating ETags with + * the given options. + * + * @param {object} options + * @return {function} + * @private + */ + +function createETagGenerator (options) { + return function generateETag (body, encoding) { + var buf = !Buffer.isBuffer(body) + ? Buffer.from(body, encoding) + : body + + return etag(buf, options) + } +} + +/** + * Parse an extended query string with qs. + * + * @param {String} str + * @return {Object} + * @private + */ + +function parseExtendedQueryString(str) { + return qs.parse(str, { + allowPrototypes: true + }); +} diff --git a/node_modules/express/lib/view.js b/node_modules/express/lib/view.js new file mode 100644 index 0000000..d66b4a2 --- /dev/null +++ b/node_modules/express/lib/view.js @@ -0,0 +1,205 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('express:view'); +var path = require('node:path'); +var fs = require('node:fs'); + +/** + * Module variables. + * @private + */ + +var dirname = path.dirname; +var basename = path.basename; +var extname = path.extname; +var join = path.join; +var resolve = path.resolve; + +/** + * Module exports. + * @public + */ + +module.exports = View; + +/** + * Initialize a new `View` with the given `name`. + * + * Options: + * + * - `defaultEngine` the default template engine name + * - `engines` template engine require() cache + * - `root` root path for view lookup + * + * @param {string} name + * @param {object} options + * @public + */ + +function View(name, options) { + var opts = options || {}; + + this.defaultEngine = opts.defaultEngine; + this.ext = extname(name); + this.name = name; + this.root = opts.root; + + if (!this.ext && !this.defaultEngine) { + throw new Error('No default engine was specified and no extension was provided.'); + } + + var fileName = name; + + if (!this.ext) { + // get extension from default engine name + this.ext = this.defaultEngine[0] !== '.' + ? '.' + this.defaultEngine + : this.defaultEngine; + + fileName += this.ext; + } + + if (!opts.engines[this.ext]) { + // load engine + var mod = this.ext.slice(1) + debug('require "%s"', mod) + + // default engine export + var fn = require(mod).__express + + if (typeof fn !== 'function') { + throw new Error('Module "' + mod + '" does not provide a view engine.') + } + + opts.engines[this.ext] = fn + } + + // store loaded engine + this.engine = opts.engines[this.ext]; + + // lookup path + this.path = this.lookup(fileName); +} + +/** + * Lookup view by the given `name` + * + * @param {string} name + * @private + */ + +View.prototype.lookup = function lookup(name) { + var path; + var roots = [].concat(this.root); + + debug('lookup "%s"', name); + + for (var i = 0; i < roots.length && !path; i++) { + var root = roots[i]; + + // resolve the path + var loc = resolve(root, name); + var dir = dirname(loc); + var file = basename(loc); + + // resolve the file + path = this.resolve(dir, file); + } + + return path; +}; + +/** + * Render with the given options. + * + * @param {object} options + * @param {function} callback + * @private + */ + +View.prototype.render = function render(options, callback) { + var sync = true; + + debug('render "%s"', this.path); + + // render, normalizing sync callbacks + this.engine(this.path, options, function onRender() { + if (!sync) { + return callback.apply(this, arguments); + } + + // copy arguments + var args = new Array(arguments.length); + var cntx = this; + + for (var i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + + // force callback to be async + return process.nextTick(function renderTick() { + return callback.apply(cntx, args); + }); + }); + + sync = false; +}; + +/** + * Resolve the file within the given directory. + * + * @param {string} dir + * @param {string} file + * @private + */ + +View.prototype.resolve = function resolve(dir, file) { + var ext = this.ext; + + // . + var path = join(dir, file); + var stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; + } + + // /index. + path = join(dir, basename(file, ext), 'index' + ext); + stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; + } +}; + +/** + * Return a stat, maybe. + * + * @param {string} path + * @return {fs.Stats} + * @private + */ + +function tryStat(path) { + debug('stat "%s"', path); + + try { + return fs.statSync(path); + } catch (e) { + return undefined; + } +} diff --git a/node_modules/express/package.json b/node_modules/express/package.json new file mode 100644 index 0000000..bdcd25e --- /dev/null +++ b/node_modules/express/package.json @@ -0,0 +1,98 @@ +{ + "name": "express", + "description": "Fast, unopinionated, minimalist web framework", + "version": "5.1.0", + "author": "TJ Holowaychuk ", + "contributors": [ + "Aaron Heckmann ", + "Ciaran Jessup ", + "Douglas Christopher Wilson ", + "Guillermo Rauch ", + "Jonathan Ong ", + "Roman Shtylman ", + "Young Jae Sim " + ], + "license": "MIT", + "repository": "expressjs/express", + "homepage": "https://expressjs.com/", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + }, + "keywords": [ + "express", + "framework", + "sinatra", + "web", + "http", + "rest", + "restful", + "router", + "app", + "api" + ], + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.0", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "devDependencies": { + "after": "0.8.2", + "connect-redis": "^8.0.1", + "cookie-parser": "1.4.7", + "cookie-session": "2.1.0", + "ejs": "^3.1.10", + "eslint": "8.47.0", + "express-session": "^1.18.1", + "hbs": "4.2.0", + "marked": "^15.0.3", + "method-override": "3.0.0", + "mocha": "^10.7.3", + "morgan": "1.10.0", + "nyc": "^17.1.0", + "pbkdf2-password": "1.2.1", + "supertest": "^6.3.0", + "vhost": "~3.0.2" + }, + "engines": { + "node": ">= 18" + }, + "files": [ + "LICENSE", + "History.md", + "Readme.md", + "index.js", + "lib/" + ], + "scripts": { + "lint": "eslint .", + "test": "mocha --require test/support/env --reporter spec --check-leaks test/ test/acceptance/", + "test-ci": "nyc --exclude examples --exclude test --exclude benchmarks --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --exclude examples --exclude test --exclude benchmarks --reporter=html --reporter=text npm test", + "test-tap": "mocha --require test/support/env --reporter tap --check-leaks test/ test/acceptance/" + } +} diff --git a/node_modules/filelist/README.md b/node_modules/filelist/README.md new file mode 100644 index 0000000..b52ebe7 --- /dev/null +++ b/node_modules/filelist/README.md @@ -0,0 +1,84 @@ +## FileList + +A FileList is a lazy-evaluated list of files. When given a list +of glob patterns for possible files to be included in the file +list, instead of searching the file structures to find the files, +a FileList holds the pattern for latter use. + +This allows you to define a FileList to match any number of +files, but only search out the actual files when then FileList +itself is actually used. The key is that the first time an +element of the FileList/Array is requested, the pending patterns +are resolved into a real list of file names. + +### Usage + +Add files to the list with the `include` method. You can add glob +patterns, individual files, or RegExp objects. When the Array +methods are invoked on the FileList, these items are resolved to +an actual list of files. + +```javascript +var fl = new FileList(); +fl.include('test/*.js'); +fl.exclude('test/helpers.js'); +``` + +Use the `exclude` method to override inclusions. You can use this +when your inclusions are too broad. + +### Array methods + +FileList has lazy-evaluated versions of most of the array +methods, including the following: + +* join +* pop +* push +* concat +* reverse +* shift +* unshift +* slice +* splice +* sort +* filter +* forEach +* some +* every +* map +* indexOf +* lastIndexOf +* reduce +* reduceRight + +When you call one of these methods, the items in the FileList +will be resolved to the full list of files, and the method will +be invoked on that result. + +### Special `length` method + +`length`: FileList includes a length *method* (instead of a +property) which returns the number of actual files in the list +once it's been resolved. + +### FileList-specific methods + +`include`: Add a filename/glob/regex to the list + +`exclude`: Override inclusions by excluding a filename/glob/regex + +`resolve`: Resolve the items in the FileList to the full list of +files. This method is invoked automatically when one of the array +methods is called. + +`toArray`: Immediately resolves the list of items, and returns an +actual array of filepaths. + +`clearInclusions`: Clears any pending items -- must be used +before resolving the list. + +`clearExclusions`: Clears the list of exclusions rules. + + + diff --git a/node_modules/filelist/index.d.ts b/node_modules/filelist/index.d.ts new file mode 100644 index 0000000..a6addf2 --- /dev/null +++ b/node_modules/filelist/index.d.ts @@ -0,0 +1,110 @@ +// IncludeOptions definitions copied from minimatch (https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/minimatch/index.d.ts) +interface IncludeOptions { + /** + * Dump a ton of stuff to stderr. + * + * @default false + */ + debug?: boolean; + + /** + * Do not expand {a,b} and {1..3} brace sets. + * + * @default false + */ + nobrace?: boolean; + + /** + * Disable ** matching against multiple folder names. + * + * @default false + */ + noglobstar?: boolean; + + /** + * Allow patterns to match filenames starting with a period, + * even if the pattern does not explicitly have a period in that spot. + * + * @default false + */ + dot?: boolean; + + /** + * Disable "extglob" style patterns like +(a|b). + * + * @default false + */ + noext?: boolean; + + /** + * Perform a case-insensitive match. + * + * @default false + */ + nocase?: boolean; + + /** + * When a match is not found by minimatch.match, + * return a list containing the pattern itself if this option is set. + * Otherwise, an empty list is returned if there are no matches. + * + * @default false + */ + nonull?: boolean; + + /** + * If set, then patterns without slashes will be matched against + * the basename of the path if it contains slashes. + * + * @default false + */ + matchBase?: boolean; + + /** + * Suppress the behavior of treating # + * at the start of a pattern as a comment. + * + * @default false + */ + nocomment?: boolean; + + /** + * Suppress the behavior of treating a leading ! character as negation. + * + * @default false + */ + nonegate?: boolean; + + /** + * Returns from negate expressions the same as if they were not negated. + * (Ie, true on a hit, false on a miss.) + * + * @default false + */ + flipNegate?: boolean; +} + +export class FileList { + static clone(): FileList + static verbose: boolean +} + +export interface FileList extends Omit, "length"> { + pendingAdd: string[] + pending: boolean + excludes: { + pats: RegExp[], + funcs: Function[], + regex: null | RegExp + } + items: string[] + toArray(): string[] + include(...items: string[]): this + include(...items: (IncludeOptions | string)[]): this + exclude(...items: string[]): this + shouldExclude(item: string): boolean + resolve(): this + clearInclusions(): this + clearExclusions(): this + length(): number +} \ No newline at end of file diff --git a/node_modules/filelist/index.js b/node_modules/filelist/index.js new file mode 100644 index 0000000..34ca389 --- /dev/null +++ b/node_modules/filelist/index.js @@ -0,0 +1,495 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +var fs = require('fs') +, path = require('path') +, minimatch = require('minimatch') +, escapeRegExpChars +, merge +, basedir +, _readDir +, readdirR +, globSync; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var hasOwn = function (obj, key) { return hasOwnProperty.apply(obj, [key]); }; + + /** + @name escapeRegExpChars + @function + @return {String} A string of escaped characters + @description Escapes regex control-characters in strings + used to build regexes dynamically + @param {String} string The string of chars to escape + */ + escapeRegExpChars = (function () { + var specials = [ '^', '$', '/', '.', '*', '+', '?', '|', '(', ')', + '[', ']', '{', '}', '\\' ]; + var sRE = new RegExp('(\\' + specials.join('|\\') + ')', 'g'); + return function (string) { + var str = string || ''; + str = String(str); + return str.replace(sRE, '\\$1'); + }; + })(); + + /** + @name merge + @function + @return {Object} Returns the merged object + @description Merge merges `otherObject` into `object` and takes care of deep + merging of objects + @param {Object} object Object to merge into + @param {Object} otherObject Object to read from + */ + merge = function (object, otherObject) { + var obj = object || {} + , otherObj = otherObject || {} + , key, value; + + for (key in otherObj) { + + if (!hasOwn(otherObj, key)) { + continue; + } + if (key === '__proto__' || key === 'constructor') { + continue; + } + + value = otherObj[key]; + // Check if a value is an Object, if so recursively add it's key/values + if (typeof value === 'object' && !(value instanceof Array)) { + // Update value of object to the one from otherObj + obj[key] = merge(obj[key], value); + } + // Value is anything other than an Object, so just add it + else { + obj[key] = value; + } + } + + return obj; + }; + /** + Given a patern, return the base directory of it (ie. the folder + that will contain all the files matching the path). + eg. file.basedir('/test/**') => '/test/' + Path ending by '/' are considerd as folder while other are considerd + as files, eg.: + file.basedir('/test/a/') => '/test/a' + file.basedir('/test/a') => '/test' + The returned path always end with a '/' so we have: + file.basedir(file.basedir(x)) == file.basedir(x) + */ + basedir = function (pathParam) { + var bd = '' + , parts + , part + , pos = 0 + , p = pathParam || ''; + + // If the path has a leading asterisk, basedir is the current dir + if (p.indexOf('*') == 0 || p.indexOf('**') == 0) { + return '.'; + } + + // always consider .. at the end as a folder and not a filename + if (/(?:^|\/|\\)\.\.$/.test(p.slice(-3))) { + p += '/'; + } + + parts = p.split(/\\|\//); + for (var i = 0, l = parts.length - 1; i < l; i++) { + part = parts[i]; + if (part.indexOf('*') > -1 || part.indexOf('**') > -1) { + break; + } + pos += part.length + 1; + bd += part + p[pos - 1]; + } + if (!bd) { + bd = '.'; + } + // Strip trailing slashes + if (!(bd == '\\' || bd == '/')) { + bd = bd.replace(/\\$|\/$/, ''); + } + return bd; + + }; + + // Return the contents of a given directory + _readDir = function (dirPath) { + var dir = path.normalize(dirPath) + , paths = [] + , ret = [dir] + , msg; + + try { + paths = fs.readdirSync(dir); + } + catch (e) { + msg = 'Could not read path ' + dir + '\n'; + if (e.stack) { + msg += e.stack; + } + throw new Error(msg); + } + + paths.forEach(function (p) { + var curr = path.join(dir, p); + var stat = fs.statSync(curr); + if (stat.isDirectory()) { + ret = ret.concat(_readDir(curr)); + } + else { + ret.push(curr); + } + }); + + return ret; + }; + + /** + @name file#readdirR + @function + @return {Array} Returns the contents as an Array, can be configured via opts.format + @description Reads the given directory returning it's contents + @param {String} dir The directory to read + @param {Object} opts Options to use + @param {String} [opts.format] Set the format to return(Default: Array) + */ + readdirR = function (dir, opts) { + var options = opts || {} + , format = options.format || 'array' + , ret; + ret = _readDir(dir); + return format == 'string' ? ret.join('\n') : ret; + }; + + +globSync = function (pat, opts) { + var dirname = basedir(pat) + , files + , matches; + + try { + files = readdirR(dirname).map(function(file){ + return file.replace(/\\/g, '/'); + }); + } + // Bail if path doesn't exist -- assume no files + catch(e) { + if (FileList.verbose) console.error(e.message); + } + + if (files) { + pat = path.normalize(pat); + matches = minimatch.match(files, pat, opts || {}); + } + return matches || []; +}; + +// Constants +// --------------- +// List of all the builtin Array methods we want to override +var ARRAY_METHODS = Object.getOwnPropertyNames(Array.prototype) +// Array methods that return a copy instead of affecting the original + , SPECIAL_RETURN = { + 'concat': true + , 'slice': true + , 'filter': true + , 'map': true + } +// Default file-patterns we want to ignore + , DEFAULT_IGNORE_PATTERNS = [ + /(^|[\/\\])CVS([\/\\]|$)/ + , /(^|[\/\\])\.svn([\/\\]|$)/ + , /(^|[\/\\])\.git([\/\\]|$)/ + , /\.bak$/ + , /~$/ + ] +// Ignore core files + , DEFAULT_IGNORE_FUNCS = [ + function (name) { + var isDir = false + , stats; + try { + stats = fs.statSync(name); + isDir = stats.isDirectory(); + } + catch(e) {} + return (/(^|[\/\\])core$/).test(name) && !isDir; + } + ]; + +var FileList = function () { + var self = this + , wrap; + + // List of glob-patterns or specific filenames + this.pendingAdd = []; + // Switched to false after lazy-eval of files + this.pending = true; + // Used to calculate exclusions from the list of files + this.excludes = { + pats: DEFAULT_IGNORE_PATTERNS.slice() + , funcs: DEFAULT_IGNORE_FUNCS.slice() + , regex: null + }; + this.items = []; + + // Wrap the array methods with the delegates + wrap = function (prop) { + var arr; + self[prop] = function () { + if (self.pending) { + self.resolve(); + } + if (typeof self.items[prop] == 'function') { + // Special method that return a copy + if (SPECIAL_RETURN[prop]) { + arr = self.items[prop].apply(self.items, arguments); + return FileList.clone(self, arr); + } + else { + return self.items[prop].apply(self.items, arguments); + } + } + else { + return self.items[prop]; + } + }; + }; + for (var i = 0, ii = ARRAY_METHODS.length; i < ii; i++) { + wrap(ARRAY_METHODS[i]); + } + + // Include whatever files got passed to the constructor + this.include.apply(this, arguments); + + // Fix constructor linkage + this.constructor = FileList; +}; + +FileList.prototype = new (function () { + var globPattern = /[*?\[\{]/; + + var _addMatching = function (item) { + var matches = globSync(item.path, item.options); + this.items = this.items.concat(matches); + } + + , _resolveAdd = function (item) { + if (globPattern.test(item.path)) { + _addMatching.call(this, item); + } + else { + this.push(item.path); + } + } + + , _calculateExcludeRe = function () { + var pats = this.excludes.pats + , pat + , excl = [] + , matches = []; + + for (var i = 0, ii = pats.length; i < ii; i++) { + pat = pats[i]; + if (typeof pat == 'string') { + // Glob, look up files + if (/[*?]/.test(pat)) { + matches = globSync(pat); + matches = matches.map(function (m) { + return escapeRegExpChars(m); + }); + excl = excl.concat(matches); + } + // String for regex + else { + excl.push(escapeRegExpChars(pat)); + } + } + // Regex, grab the string-representation + else if (pat instanceof RegExp) { + excl.push(pat.toString().replace(/^\/|\/$/g, '')); + } + } + if (excl.length) { + this.excludes.regex = new RegExp('(' + excl.join(')|(') + ')'); + } + else { + this.excludes.regex = /^$/; + } + } + + , _resolveExclude = function () { + var self = this; + _calculateExcludeRe.call(this); + // No `reject` method, so use reverse-filter + this.items = this.items.filter(function (name) { + return !self.shouldExclude(name); + }); + }; + + /** + * Includes file-patterns in the FileList. Should be called with one or more + * pattern for finding file to include in the list. Arguments should be strings + * for either a glob-pattern or a specific file-name, or an array of them + */ + this.include = function () { + var args = Array.prototype.slice.call(arguments) + , arg + , includes = { items: [], options: {} }; + + for (var i = 0, ilen = args.length; i < ilen; i++) { + arg = args[i]; + + if (typeof arg === 'object' && !Array.isArray(arg)) { + merge(includes.options, arg); + } else { + includes.items = includes.items.concat(arg).filter(function (item) { + return !!item; + }); + } + } + + var items = includes.items.map(function(item) { + return { path: item, options: includes.options }; + }); + + this.pendingAdd = this.pendingAdd.concat(items); + + return this; + }; + + /** + * Indicates whether a particular file would be filtered out by the current + * exclusion rules for this FileList. + * @param {String} name The filename to check + * @return {Boolean} Whether or not the file should be excluded + */ + this.shouldExclude = function (name) { + if (!this.excludes.regex) { + _calculateExcludeRe.call(this); + } + var excl = this.excludes; + return excl.regex.test(name) || excl.funcs.some(function (f) { + return !!f(name); + }); + }; + + /** + * Excludes file-patterns from the FileList. Should be called with one or more + * pattern for finding file to include in the list. Arguments can be: + * 1. Strings for either a glob-pattern or a specific file-name + * 2. Regular expression literals + * 3. Functions to be run on the filename that return a true/false + */ + this.exclude = function () { + var args = Array.isArray(arguments[0]) ? arguments[0] : arguments + , arg; + for (var i = 0, ii = args.length; i < ii; i++) { + arg = args[i]; + if (typeof arg == 'function' && !(arg instanceof RegExp)) { + this.excludes.funcs.push(arg); + } + else { + this.excludes.pats.push(arg); + } + } + if (!this.pending) { + _resolveExclude.call(this); + } + return this; + }; + + /** + * Populates the FileList from the include/exclude rules with a list of + * actual files + */ + this.resolve = function () { + var item + , uniqueFunc = function (p, c) { + if (p.indexOf(c) < 0) { + p.push(c); + } + return p; + }; + if (this.pending) { + this.pending = false; + while ((item = this.pendingAdd.shift())) { + _resolveAdd.call(this, item); + } + // Reduce to a unique list + this.items = this.items.reduce(uniqueFunc, []); + // Remove exclusions + _resolveExclude.call(this); + } + return this; + }; + + /** + * Convert to a plain-jane array + */ + this.toArray = function () { + // Call slice to ensure lazy-resolution before slicing items + var ret = this.slice().items.slice(); + return ret; + }; + + /** + * Clear any pending items -- only useful before + * calling `resolve` + */ + this.clearInclusions = function () { + this.pendingAdd = []; + return this; + }; + + /** + * Clear any current exclusion rules + */ + this.clearExclusions = function () { + this.excludes = { + pats: [] + , funcs: [] + , regex: null + }; + return this; + }; + +})(); + +// Static method, used to create copy returned by special +// array methods +FileList.clone = function (list, items) { + var clone = new FileList(); + if (items) { + clone.items = items; + } + clone.pendingAdd = list.pendingAdd; + clone.pending = list.pending; + for (var p in list.excludes) { + clone.excludes[p] = list.excludes[p]; + } + return clone; +}; + +FileList.verbose = true + +exports.FileList = FileList; diff --git a/node_modules/filelist/jakefile.js b/node_modules/filelist/jakefile.js new file mode 100644 index 0000000..18d4d7d --- /dev/null +++ b/node_modules/filelist/jakefile.js @@ -0,0 +1,15 @@ +testTask('FileList', function () { + this.testFiles.include('test/*.js'); +}); + +publishTask('FileList', function () { + this.packageFiles.include([ + 'jakefile.js', + 'README.md', + 'package.json', + 'index.js', + 'index.d.ts' + ]); +}); + + diff --git a/node_modules/filelist/package.json b/node_modules/filelist/package.json new file mode 100644 index 0000000..8a90586 --- /dev/null +++ b/node_modules/filelist/package.json @@ -0,0 +1,28 @@ +{ + "name": "filelist", + "version": "1.0.4", + "description": "Lazy-evaluating list of files, based on globs or regex patterns", + "main": "index.js", + "types": "index.d.ts", + "scripts": { + "test": "jake test" + }, + "repository": { + "type": "git", + "url": "git://github.com/mde/filelist.git" + }, + "keywords": [ + "file", + "utility", + "glob" + ], + "author": "Matthew Eernisse (http://fleegix.org)", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/mde/filelist/issues" + }, + "homepage": "https://github.com/mde/filelist", + "dependencies": { + "minimatch": "^5.0.1" + } +} diff --git a/node_modules/finalhandler/HISTORY.md b/node_modules/finalhandler/HISTORY.md new file mode 100644 index 0000000..4bc1850 --- /dev/null +++ b/node_modules/finalhandler/HISTORY.md @@ -0,0 +1,233 @@ +v2.1.0 / 2025-03-05 +================== + + * deps: + * use caret notation for dependency versions + * encodeurl@^2.0.0 + * debug@^4.4.0 + * remove `ServerResponse.headersSent` support check + * remove setImmediate support check + * update test dependencies + * remove unnecessary devDependency `safe-buffer` + * remove `unpipe` package and use native `unpipe()` method + * remove unnecessary devDependency `readable-stream` + * refactor: use object spread to copy error headers + * refactor: use replaceAll instead of replace with a regex + * refactor: replace setHeaders function with optimized inline header setting + +v2.0.0 / 2024-09-02 +================== + + * drop support for node <18 + * ignore status message for HTTP/2 (#53) + +v1.3.1 / 2024-09-11 +================== + + * deps: encodeurl@~2.0.0 + +v1.3.0 / 2024-09-03 +================== + + * ignore status message for HTTP/2 (#53) + +v1.2.1 / 2024-09-02 +================== + + * Gracefully handle when handling an error and socket is null + +1.2.0 / 2022-03-22 +================== + + * Remove set content headers that break response + * deps: on-finished@2.4.1 + * deps: statuses@2.0.1 + - Rename `425 Unordered Collection` to standard `425 Too Early` + +1.1.2 / 2019-05-09 +================== + + * Set stricter `Content-Security-Policy` header + * deps: parseurl@~1.3.3 + * deps: statuses@~1.5.0 + +1.1.1 / 2018-03-06 +================== + + * Fix 404 output for bad / missing pathnames + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: statuses@~1.4.0 + +1.1.0 / 2017-09-24 +================== + + * Use `res.headersSent` when available + +1.0.6 / 2017-09-22 +================== + + * deps: debug@2.6.9 + +1.0.5 / 2017-09-15 +================== + + * deps: parseurl@~1.3.2 + - perf: reduce overhead for full URLs + - perf: unroll the "fast-path" `RegExp` + +1.0.4 / 2017-08-03 +================== + + * deps: debug@2.6.8 + +1.0.3 / 2017-05-16 +================== + + * deps: debug@2.6.7 + - deps: ms@2.0.0 + +1.0.2 / 2017-04-22 +================== + + * deps: debug@2.6.4 + - deps: ms@0.7.3 + +1.0.1 / 2017-03-21 +================== + + * Fix missing `` in HTML document + * deps: debug@2.6.3 + - Fix: `DEBUG_MAX_ARRAY_LENGTH` + +1.0.0 / 2017-02-15 +================== + + * Fix exception when `err` cannot be converted to a string + * Fully URL-encode the pathname in the 404 message + * Only include the pathname in the 404 message + * Send complete HTML document + * Set `Content-Security-Policy: default-src 'self'` header + * deps: debug@2.6.1 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable set to `3` or higher + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + +0.5.1 / 2016-11-12 +================== + + * Fix exception when `err.headers` is not an object + * deps: statuses@~1.3.1 + * perf: hoist regular expressions + * perf: remove duplicate validation path + +0.5.0 / 2016-06-15 +================== + + * Change invalid or non-numeric status code to 500 + * Overwrite status message to match set status code + * Prefer `err.statusCode` if `err.status` is invalid + * Set response headers from `err.headers` object + * Use `statuses` instead of `http` module for status messages + - Includes all defined status messages + +0.4.1 / 2015-12-02 +================== + + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + +0.4.0 / 2015-06-14 +================== + + * Fix a false-positive when unpiping in Node.js 0.8 + * Support `statusCode` property on `Error` objects + * Use `unpipe` module for unpiping requests + * deps: escape-html@1.0.2 + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * perf: enable strict mode + * perf: remove argument reassignment + +0.3.6 / 2015-05-11 +================== + + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + +0.3.5 / 2015-04-22 +================== + + * deps: on-finished@~2.2.1 + - Fix `isFinished(req)` when data buffered + +0.3.4 / 2015-03-15 +================== + + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + +0.3.3 / 2015-01-01 +================== + + * deps: debug@~2.1.1 + * deps: on-finished@~2.2.0 + +0.3.2 / 2014-10-22 +================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + +0.3.1 / 2014-10-16 +================== + + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + +0.3.0 / 2014-09-17 +================== + + * Terminate in progress response only on error + * Use `on-finished` to determine request status + +0.2.0 / 2014-09-03 +================== + + * Set `X-Content-Type-Options: nosniff` header + * deps: debug@~2.0.0 + +0.1.0 / 2014-07-16 +================== + + * Respond after request fully read + - prevents hung responses and socket hang ups + * deps: debug@1.0.4 + +0.0.3 / 2014-07-11 +================== + + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + +0.0.2 / 2014-06-19 +================== + + * Handle invalid status codes + +0.0.1 / 2014-06-05 +================== + + * deps: debug@1.0.2 + +0.0.0 / 2014-06-05 +================== + + * Extracted from connect/express diff --git a/node_modules/finalhandler/LICENSE b/node_modules/finalhandler/LICENSE new file mode 100644 index 0000000..6022106 --- /dev/null +++ b/node_modules/finalhandler/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2022 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/finalhandler/README.md b/node_modules/finalhandler/README.md new file mode 100644 index 0000000..6244a13 --- /dev/null +++ b/node_modules/finalhandler/README.md @@ -0,0 +1,147 @@ +# finalhandler + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Node.js function to invoke as the final step to respond to HTTP request. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install finalhandler +``` + +## API + +```js +var finalhandler = require('finalhandler') +``` + +### finalhandler(req, res, [options]) + +Returns function to be invoked as the final step for the given `req` and `res`. +This function is to be invoked as `fn(err)`. If `err` is falsy, the handler will +write out a 404 response to the `res`. If it is truthy, an error response will +be written out to the `res` or `res` will be terminated if a response has already +started. + +When an error is written, the following information is added to the response: + + * The `res.statusCode` is set from `err.status` (or `err.statusCode`). If + this value is outside the 4xx or 5xx range, it will be set to 500. + * The `res.statusMessage` is set according to the status code. + * The body will be the HTML of the status code message if `env` is + `'production'`, otherwise will be `err.stack`. + * Any headers specified in an `err.headers` object. + +The final handler will also unpipe anything from `req` when it is invoked. + +#### options.env + +By default, the environment is determined by `NODE_ENV` variable, but it can be +overridden by this option. + +#### options.onerror + +Provide a function to be called with the `err` when it exists. Can be used for +writing errors to a central location without excessive function generation. Called +as `onerror(err, req, res)`. + +## Examples + +### always 404 + +```js +var finalhandler = require('finalhandler') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + done() +}) + +server.listen(3000) +``` + +### perform simple action + +```js +var finalhandler = require('finalhandler') +var fs = require('fs') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + + fs.readFile('index.html', function (err, buf) { + if (err) return done(err) + res.setHeader('Content-Type', 'text/html') + res.end(buf) + }) +}) + +server.listen(3000) +``` + +### use with middleware-style functions + +```js +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +var serve = serveStatic('public') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + serve(req, res, done) +}) + +server.listen(3000) +``` + +### keep log of all errors + +```js +var finalhandler = require('finalhandler') +var fs = require('fs') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res, { onerror: logerror }) + + fs.readFile('index.html', function (err, buf) { + if (err) return done(err) + res.setHeader('Content-Type', 'text/html') + res.end(buf) + }) +}) + +server.listen(3000) + +function logerror (err) { + console.error(err.stack || err.toString()) +} +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/finalhandler.svg +[npm-url]: https://npmjs.org/package/finalhandler +[node-image]: https://img.shields.io/node/v/finalhandler.svg +[node-url]: https://nodejs.org/en/download +[coveralls-image]: https://img.shields.io/coveralls/pillarjs/finalhandler.svg +[coveralls-url]: https://coveralls.io/r/pillarjs/finalhandler?branch=master +[downloads-image]: https://img.shields.io/npm/dm/finalhandler.svg +[downloads-url]: https://npmjs.org/package/finalhandler +[github-actions-ci-image]: https://github.com/pillarjs/finalhandler/actions/workflows/ci.yml/badge.svg +[github-actions-ci-url]: https://github.com/pillarjs/finalhandler/actions/workflows/ci.yml diff --git a/node_modules/finalhandler/index.js b/node_modules/finalhandler/index.js new file mode 100644 index 0000000..bf15e48 --- /dev/null +++ b/node_modules/finalhandler/index.js @@ -0,0 +1,293 @@ +/*! + * finalhandler + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('finalhandler') +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') +var onFinished = require('on-finished') +var parseUrl = require('parseurl') +var statuses = require('statuses') + +/** + * Module variables. + * @private + */ + +var isFinished = onFinished.isFinished + +/** + * Create a minimal HTML document. + * + * @param {string} message + * @private + */ + +function createHtmlDocument (message) { + var body = escapeHtml(message) + .replaceAll('\n', '
') + .replaceAll(' ', '  ') + + return '\n' + + '\n' + + '\n' + + '\n' + + 'Error\n' + + '\n' + + '\n' + + '
' + body + '
\n' + + '\n' + + '\n' +} + +/** + * Module exports. + * @public + */ + +module.exports = finalhandler + +/** + * Create a function to handle the final response. + * + * @param {Request} req + * @param {Response} res + * @param {Object} [options] + * @return {Function} + * @public + */ + +function finalhandler (req, res, options) { + var opts = options || {} + + // get environment + var env = opts.env || process.env.NODE_ENV || 'development' + + // get error callback + var onerror = opts.onerror + + return function (err) { + var headers + var msg + var status + + // ignore 404 on in-flight response + if (!err && res.headersSent) { + debug('cannot 404 after headers sent') + return + } + + // unhandled error + if (err) { + // respect status code from error + status = getErrorStatusCode(err) + + if (status === undefined) { + // fallback to status code on response + status = getResponseStatusCode(res) + } else { + // respect headers from error + headers = getErrorHeaders(err) + } + + // get error message + msg = getErrorMessage(err, status, env) + } else { + // not found + status = 404 + msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req)) + } + + debug('default %s', status) + + // schedule onerror callback + if (err && onerror) { + setImmediate(onerror, err, req, res) + } + + // cannot actually respond + if (res.headersSent) { + debug('cannot %d after headers sent', status) + if (req.socket) { + req.socket.destroy() + } + return + } + + // send response + send(req, res, status, headers, msg) + } +} + +/** + * Get headers from Error object. + * + * @param {Error} err + * @return {object} + * @private + */ + +function getErrorHeaders (err) { + if (!err.headers || typeof err.headers !== 'object') { + return undefined + } + + return { ...err.headers } +} + +/** + * Get message from Error object, fallback to status message. + * + * @param {Error} err + * @param {number} status + * @param {string} env + * @return {string} + * @private + */ + +function getErrorMessage (err, status, env) { + var msg + + if (env !== 'production') { + // use err.stack, which typically includes err.message + msg = err.stack + + // fallback to err.toString() when possible + if (!msg && typeof err.toString === 'function') { + msg = err.toString() + } + } + + return msg || statuses.message[status] +} + +/** + * Get status code from Error object. + * + * @param {Error} err + * @return {number} + * @private + */ + +function getErrorStatusCode (err) { + // check err.status + if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) { + return err.status + } + + // check err.statusCode + if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) { + return err.statusCode + } + + return undefined +} + +/** + * Get resource name for the request. + * + * This is typically just the original pathname of the request + * but will fallback to "resource" is that cannot be determined. + * + * @param {IncomingMessage} req + * @return {string} + * @private + */ + +function getResourceName (req) { + try { + return parseUrl.original(req).pathname + } catch (e) { + return 'resource' + } +} + +/** + * Get status code from response. + * + * @param {OutgoingMessage} res + * @return {number} + * @private + */ + +function getResponseStatusCode (res) { + var status = res.statusCode + + // default status code to 500 if outside valid range + if (typeof status !== 'number' || status < 400 || status > 599) { + status = 500 + } + + return status +} + +/** + * Send response. + * + * @param {IncomingMessage} req + * @param {OutgoingMessage} res + * @param {number} status + * @param {object} headers + * @param {string} message + * @private + */ + +function send (req, res, status, headers, message) { + function write () { + // response body + var body = createHtmlDocument(message) + + // response status + res.statusCode = status + + if (req.httpVersionMajor < 2) { + res.statusMessage = statuses.message[status] + } + + // remove any content headers + res.removeHeader('Content-Encoding') + res.removeHeader('Content-Language') + res.removeHeader('Content-Range') + + // response headers + for (const [key, value] of Object.entries(headers ?? {})) { + res.setHeader(key, value) + } + + // security headers + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') + + // standard headers + res.setHeader('Content-Type', 'text/html; charset=utf-8') + res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8')) + + if (req.method === 'HEAD') { + res.end() + return + } + + res.end(body, 'utf8') + } + + if (isFinished(req)) { + write() + return + } + + // unpipe everything from the request + req.unpipe() + + // flush the request + onFinished(req, write) + req.resume() +} diff --git a/node_modules/finalhandler/package.json b/node_modules/finalhandler/package.json new file mode 100644 index 0000000..992b306 --- /dev/null +++ b/node_modules/finalhandler/package.json @@ -0,0 +1,43 @@ +{ + "name": "finalhandler", + "description": "Node.js final http responder", + "version": "2.1.0", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "repository": "pillarjs/finalhandler", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.26.0", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "^11.0.1", + "nyc": "^17.1.0", + "supertest": "^7.0.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "test-inspect": "mocha --reporter spec --inspect --inspect-brk test/" + } +} diff --git a/node_modules/forwarded/HISTORY.md b/node_modules/forwarded/HISTORY.md new file mode 100644 index 0000000..381e6aa --- /dev/null +++ b/node_modules/forwarded/HISTORY.md @@ -0,0 +1,21 @@ +0.2.0 / 2021-05-31 +================== + + * Use `req.socket` over deprecated `req.connection` + +0.1.2 / 2017-09-14 +================== + + * perf: improve header parsing + * perf: reduce overhead when no `X-Forwarded-For` header + +0.1.1 / 2017-09-10 +================== + + * Fix trimming leading / trailing OWS + * perf: hoist regular expression + +0.1.0 / 2014-09-21 +================== + + * Initial release diff --git a/node_modules/forwarded/LICENSE b/node_modules/forwarded/LICENSE new file mode 100644 index 0000000..84441fb --- /dev/null +++ b/node_modules/forwarded/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/forwarded/README.md b/node_modules/forwarded/README.md new file mode 100644 index 0000000..fdd220b --- /dev/null +++ b/node_modules/forwarded/README.md @@ -0,0 +1,57 @@ +# forwarded + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Parse HTTP X-Forwarded-For header + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install forwarded +``` + +## API + +```js +var forwarded = require('forwarded') +``` + +### forwarded(req) + +```js +var addresses = forwarded(req) +``` + +Parse the `X-Forwarded-For` header from the request. Returns an array +of the addresses, including the socket address for the `req`, in reverse +order (i.e. index `0` is the socket address and the last index is the +furthest address, typically the end-user). + +## Testing + +```sh +$ npm test +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/forwarded/master?label=ci +[ci-url]: https://github.com/jshttp/forwarded/actions?query=workflow%3Aci +[npm-image]: https://img.shields.io/npm/v/forwarded.svg +[npm-url]: https://npmjs.org/package/forwarded +[node-version-image]: https://img.shields.io/node/v/forwarded.svg +[node-version-url]: https://nodejs.org/en/download/ +[coveralls-image]: https://img.shields.io/coveralls/jshttp/forwarded/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/forwarded?branch=master +[downloads-image]: https://img.shields.io/npm/dm/forwarded.svg +[downloads-url]: https://npmjs.org/package/forwarded diff --git a/node_modules/forwarded/index.js b/node_modules/forwarded/index.js new file mode 100644 index 0000000..b2b6bdd --- /dev/null +++ b/node_modules/forwarded/index.js @@ -0,0 +1,90 @@ +/*! + * forwarded + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = forwarded + +/** + * Get all addresses in the request, using the `X-Forwarded-For` header. + * + * @param {object} req + * @return {array} + * @public + */ + +function forwarded (req) { + if (!req) { + throw new TypeError('argument req is required') + } + + // simple header parsing + var proxyAddrs = parse(req.headers['x-forwarded-for'] || '') + var socketAddr = getSocketAddr(req) + var addrs = [socketAddr].concat(proxyAddrs) + + // return all addresses + return addrs +} + +/** + * Get the socket address for a request. + * + * @param {object} req + * @return {string} + * @private + */ + +function getSocketAddr (req) { + return req.socket + ? req.socket.remoteAddress + : req.connection.remoteAddress +} + +/** + * Parse the X-Forwarded-For header. + * + * @param {string} header + * @private + */ + +function parse (header) { + var end = header.length + var list = [] + var start = header.length + + // gather addresses, backwards + for (var i = header.length - 1; i >= 0; i--) { + switch (header.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + } + break + case 0x2c: /* , */ + if (start !== end) { + list.push(header.substring(start, end)) + } + start = end = i + break + default: + start = i + break + } + } + + // final address + if (start !== end) { + list.push(header.substring(start, end)) + } + + return list +} diff --git a/node_modules/forwarded/package.json b/node_modules/forwarded/package.json new file mode 100644 index 0000000..bf9c7d6 --- /dev/null +++ b/node_modules/forwarded/package.json @@ -0,0 +1,45 @@ +{ + "name": "forwarded", + "description": "Parse HTTP X-Forwarded-For header", + "version": "0.2.0", + "contributors": [ + "Douglas Christopher Wilson " + ], + "license": "MIT", + "keywords": [ + "x-forwarded-for", + "http", + "req" + ], + "repository": "jshttp/forwarded", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "deep-equal": "1.0.1", + "eslint": "7.27.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.23.4", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "4.3.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "8.4.0", + "nyc": "15.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/fresh/HISTORY.md b/node_modules/fresh/HISTORY.md new file mode 100644 index 0000000..fd3888a --- /dev/null +++ b/node_modules/fresh/HISTORY.md @@ -0,0 +1,80 @@ +2.0.0 - 2024-09-04 +========== + * Drop support for Node.js <18 + +1.0.0 - 2024-09-04 +========== + + * Drop support for Node.js below 0.8 + * Fix: Ignore `If-Modified-Since` in the presence of `If-None-Match`, according to [spec](https://www.rfc-editor.org/rfc/rfc9110.html#section-13.1.3-5). Fixes [#35](https://github.com/jshttp/fresh/issues/35) + +0.5.2 / 2017-09-13 +================== + + * Fix regression matching multiple ETags in `If-None-Match` + * perf: improve `If-None-Match` token parsing + +0.5.1 / 2017-09-11 +================== + + * Fix handling of modified headers with invalid dates + * perf: improve ETag match loop + +0.5.0 / 2017-02-21 +================== + + * Fix incorrect result when `If-None-Match` has both `*` and ETags + * Fix weak `ETag` matching to match spec + * perf: delay reading header values until needed + * perf: skip checking modified time if ETag check failed + * perf: skip parsing `If-None-Match` when no `ETag` header + * perf: use `Date.parse` instead of `new Date` + +0.4.0 / 2017-02-05 +================== + + * Fix false detection of `no-cache` request directive + * perf: enable strict mode + * perf: hoist regular expressions + * perf: remove duplicate conditional + * perf: remove unnecessary boolean coercions + +0.3.0 / 2015-05-12 +================== + + * Add weak `ETag` matching support + +0.2.4 / 2014-09-07 +================== + + * Support Node.js 0.6 + +0.2.3 / 2014-09-07 +================== + + * Move repository to jshttp + +0.2.2 / 2014-02-19 +================== + + * Revert "Fix for blank page on Safari reload" + +0.2.1 / 2014-01-29 +================== + + * Fix for blank page on Safari reload + +0.2.0 / 2013-08-11 +================== + + * Return stale for `Cache-Control: no-cache` + +0.1.0 / 2012-06-15 +================== + + * Add `If-None-Match: *` support + +0.0.1 / 2012-06-10 +================== + + * Initial release diff --git a/node_modules/fresh/LICENSE b/node_modules/fresh/LICENSE new file mode 100644 index 0000000..1434ade --- /dev/null +++ b/node_modules/fresh/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk +Copyright (c) 2016-2017 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/fresh/README.md b/node_modules/fresh/README.md new file mode 100644 index 0000000..fd79c5b --- /dev/null +++ b/node_modules/fresh/README.md @@ -0,0 +1,117 @@ +# fresh + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +HTTP response freshness testing + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +``` +$ npm install fresh +``` + +## API + +```js +var fresh = require('fresh') +``` + +### fresh(reqHeaders, resHeaders) + +Check freshness of the response using request and response headers. + +When the response is still "fresh" in the client's cache `true` is +returned, otherwise `false` is returned to indicate that the client +cache is now stale and the full response should be sent. + +When a client sends the `Cache-Control: no-cache` request header to +indicate an end-to-end reload request, this module will return `false` +to make handling these requests transparent. + +## Known Issues + +This module is designed to only follow the HTTP specifications, not +to work-around all kinda of client bugs (especially since this module +typically does not receive enough information to understand what the +client actually is). + +There is a known issue that in certain versions of Safari, Safari +will incorrectly make a request that allows this module to validate +freshness of the resource even when Safari does not have a +representation of the resource in the cache. The module +[jumanji](https://www.npmjs.com/package/jumanji) can be used in +an Express application to work-around this issue and also provides +links to further reading on this Safari bug. + +## Example + +### API usage + + + +```js +var reqHeaders = { 'if-none-match': '"foo"' } +var resHeaders = { etag: '"bar"' } +fresh(reqHeaders, resHeaders) +// => false + +var reqHeaders = { 'if-none-match': '"foo"' } +var resHeaders = { etag: '"foo"' } +fresh(reqHeaders, resHeaders) +// => true +``` + +### Using with Node.js http server + +```js +var fresh = require('fresh') +var http = require('http') + +var server = http.createServer(function (req, res) { + // perform server logic + // ... including adding ETag / Last-Modified response headers + + if (isFresh(req, res)) { + // client has a fresh copy of resource + res.statusCode = 304 + res.end() + return + } + + // send the resource + res.statusCode = 200 + res.end('hello, world!') +}) + +function isFresh (req, res) { + return fresh(req.headers, { + etag: res.getHeader('ETag'), + 'last-modified': res.getHeader('Last-Modified') + }) +} + +server.listen(3000) +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://img.shields.io/github/workflow/status/jshttp/fresh/ci/master?label=ci +[ci-url]: https://github.com/jshttp/fresh/actions/workflows/ci.yml +[npm-image]: https://img.shields.io/npm/v/fresh.svg +[npm-url]: https://npmjs.org/package/fresh +[node-version-image]: https://img.shields.io/node/v/fresh.svg +[node-version-url]: https://nodejs.org/en/ +[coveralls-image]: https://img.shields.io/coveralls/jshttp/fresh/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/fresh?branch=master +[downloads-image]: https://img.shields.io/npm/dm/fresh.svg +[downloads-url]: https://npmjs.org/package/fresh diff --git a/node_modules/fresh/index.js b/node_modules/fresh/index.js new file mode 100644 index 0000000..fc3dea7 --- /dev/null +++ b/node_modules/fresh/index.js @@ -0,0 +1,136 @@ +/*! + * fresh + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2016-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * RegExp to check for no-cache token in Cache-Control. + * @private + */ + +var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/ + +/** + * Module exports. + * @public + */ + +module.exports = fresh + +/** + * Check freshness of the response using request and response headers. + * + * @param {Object} reqHeaders + * @param {Object} resHeaders + * @return {Boolean} + * @public + */ + +function fresh (reqHeaders, resHeaders) { + // fields + var modifiedSince = reqHeaders['if-modified-since'] + var noneMatch = reqHeaders['if-none-match'] + + // unconditional request + if (!modifiedSince && !noneMatch) { + return false + } + + // Always return stale when Cache-Control: no-cache + // to support end-to-end reload requests + // https://tools.ietf.org/html/rfc2616#section-14.9.4 + var cacheControl = reqHeaders['cache-control'] + if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) { + return false + } + + // if-none-match takes precedent over if-modified-since + if (noneMatch) { + if (noneMatch === '*') { + return true + } + var etag = resHeaders.etag + + if (!etag) { + return false + } + + var matches = parseTokenList(noneMatch) + for (var i = 0; i < matches.length; i++) { + var match = matches[i] + if (match === etag || match === 'W/' + etag || 'W/' + match === etag) { + return true + } + } + + return false + } + + // if-modified-since + if (modifiedSince) { + var lastModified = resHeaders['last-modified'] + var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince)) + + if (modifiedStale) { + return false + } + } + + return true +} + +/** + * Parse an HTTP Date into a number. + * + * @param {string} date + * @private + */ + +function parseHttpDate (date) { + var timestamp = date && Date.parse(date) + + // istanbul ignore next: guard against date.js Date.parse patching + return typeof timestamp === 'number' + ? timestamp + : NaN +} + +/** + * Parse a HTTP token list. + * + * @param {string} str + * @private + */ + +function parseTokenList (str) { + var end = 0 + var list = [] + var start = 0 + + // gather tokens + for (var i = 0, len = str.length; i < len; i++) { + switch (str.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1 + } + break + case 0x2c: /* , */ + list.push(str.substring(start, end)) + start = end = i + 1 + break + default: + end = i + 1 + break + } + } + + // final token + list.push(str.substring(start, end)) + + return list +} diff --git a/node_modules/fresh/package.json b/node_modules/fresh/package.json new file mode 100644 index 0000000..5d7e215 --- /dev/null +++ b/node_modules/fresh/package.json @@ -0,0 +1,46 @@ +{ + "name": "fresh", + "description": "HTTP response freshness testing", + "version": "2.0.0", + "author": "TJ Holowaychuk (http://tjholowaychuk.com)", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "keywords": [ + "fresh", + "http", + "conditional", + "cache" + ], + "repository": "jshttp/fresh", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "8.12.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "6.0.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.0", + "nyc": "15.1.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/function-bind/.eslintrc b/node_modules/function-bind/.eslintrc new file mode 100644 index 0000000..71a054f --- /dev/null +++ b/node_modules/function-bind/.eslintrc @@ -0,0 +1,21 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + "indent": [2, 4], + "no-new-func": [1], + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "max-lines-per-function": 0, + "strict": [0] + }, + }, + ], +} diff --git a/node_modules/function-bind/.github/FUNDING.yml b/node_modules/function-bind/.github/FUNDING.yml new file mode 100644 index 0000000..7448219 --- /dev/null +++ b/node_modules/function-bind/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/function-bind +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/function-bind/.github/SECURITY.md b/node_modules/function-bind/.github/SECURITY.md new file mode 100644 index 0000000..82e4285 --- /dev/null +++ b/node_modules/function-bind/.github/SECURITY.md @@ -0,0 +1,3 @@ +# Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. diff --git a/node_modules/function-bind/.nycrc b/node_modules/function-bind/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/node_modules/function-bind/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/function-bind/CHANGELOG.md b/node_modules/function-bind/CHANGELOG.md new file mode 100644 index 0000000..f9e6cc0 --- /dev/null +++ b/node_modules/function-bind/CHANGELOG.md @@ -0,0 +1,136 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.2](https://github.com/ljharb/function-bind/compare/v1.1.1...v1.1.2) - 2023-10-12 + +### Merged + +- Point to the correct file [`#16`](https://github.com/ljharb/function-bind/pull/16) + +### Commits + +- [Tests] migrate tests to Github Actions [`4f8b57c`](https://github.com/ljharb/function-bind/commit/4f8b57c02f2011fe9ae353d5e74e8745f0988af8) +- [Tests] remove `jscs` [`90eb2ed`](https://github.com/ljharb/function-bind/commit/90eb2edbeefd5b76cd6c3a482ea3454db169b31f) +- [meta] update `.gitignore` [`53fcdc3`](https://github.com/ljharb/function-bind/commit/53fcdc371cd66634d6e9b71c836a50f437e89fed) +- [Tests] up to `node` `v11.10`, `v10.15`, `v9.11`, `v8.15`, `v6.16`, `v4.9`; use `nvm install-latest-npm`; run audit script in tests [`1fe8f6e`](https://github.com/ljharb/function-bind/commit/1fe8f6e9aed0dfa8d8b3cdbd00c7f5ea0cd2b36e) +- [meta] add `auto-changelog` [`1921fcb`](https://github.com/ljharb/function-bind/commit/1921fcb5b416b63ffc4acad051b6aad5722f777d) +- [Robustness] remove runtime dependency on all builtins except `.apply` [`f743e61`](https://github.com/ljharb/function-bind/commit/f743e61aa6bb2360358c04d4884c9db853d118b7) +- Docs: enable badges; update wording [`503cb12`](https://github.com/ljharb/function-bind/commit/503cb12d998b5f91822776c73332c7adcd6355dd) +- [readme] update badges [`290c5db`](https://github.com/ljharb/function-bind/commit/290c5dbbbda7264efaeb886552a374b869a4bb48) +- [Tests] switch to nyc for coverage [`ea360ba`](https://github.com/ljharb/function-bind/commit/ea360ba907fc2601ed18d01a3827fa2d3533cdf8) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`cae5e9e`](https://github.com/ljharb/function-bind/commit/cae5e9e07a5578dc6df26c03ee22851ce05b943c) +- [meta] add `funding` field; create FUNDING.yml [`c9f4274`](https://github.com/ljharb/function-bind/commit/c9f4274aa80ea3aae9657a3938fdba41a3b04ca6) +- [Tests] fix eslint errors from #15 [`f69aaa2`](https://github.com/ljharb/function-bind/commit/f69aaa2beb2fdab4415bfb885760a699d0b9c964) +- [actions] fix permissions [`99a0cd9`](https://github.com/ljharb/function-bind/commit/99a0cd9f3b5bac223a0d572f081834cd73314be7) +- [meta] use `npmignore` to autogenerate an npmignore file [`f03b524`](https://github.com/ljharb/function-bind/commit/f03b524ca91f75a109a5d062f029122c86ecd1ae) +- [Dev Deps] update `@ljharb/eslint‑config`, `eslint`, `tape` [`7af9300`](https://github.com/ljharb/function-bind/commit/7af930023ae2ce7645489532821e4fbbcd7a2280) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape` [`64a9127`](https://github.com/ljharb/function-bind/commit/64a9127ab0bd331b93d6572eaf6e9971967fc08c) +- [Tests] use `aud` instead of `npm audit` [`e75069c`](https://github.com/ljharb/function-bind/commit/e75069c50010a8fcce2a9ce2324934c35fdb4386) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`d03555c`](https://github.com/ljharb/function-bind/commit/d03555ca59dea3b71ce710045e4303b9e2619e28) +- [meta] add `safe-publish-latest` [`9c8f809`](https://github.com/ljharb/function-bind/commit/9c8f8092aed027d7e80c94f517aa892385b64f09) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`baf6893`](https://github.com/ljharb/function-bind/commit/baf6893e27f5b59abe88bc1995e6f6ed1e527397) +- [meta] create SECURITY.md [`4db1779`](https://github.com/ljharb/function-bind/commit/4db17799f1f28ae294cb95e0081ca2b591c3911b) +- [Tests] add `npm run audit` [`c8b38ec`](https://github.com/ljharb/function-bind/commit/c8b38ec40ed3f85dabdee40ed4148f1748375bc2) +- Revert "Point to the correct file" [`05cdf0f`](https://github.com/ljharb/function-bind/commit/05cdf0fa205c6a3c5ba40bbedd1dfa9874f915c9) + +## [v1.1.1](https://github.com/ljharb/function-bind/compare/v1.1.0...v1.1.1) - 2017-08-28 + +### Commits + +- [Tests] up to `node` `v8`; newer npm breaks on older node; fix scripts [`817f7d2`](https://github.com/ljharb/function-bind/commit/817f7d28470fdbff8ef608d4d565dd4d1430bc5e) +- [Dev Deps] update `eslint`, `jscs`, `tape`, `@ljharb/eslint-config` [`854288b`](https://github.com/ljharb/function-bind/commit/854288b1b6f5c555f89aceb9eff1152510262084) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`83e639f`](https://github.com/ljharb/function-bind/commit/83e639ff74e6cd6921285bccec22c1bcf72311bd) +- Only apps should have lockfiles [`5ed97f5`](https://github.com/ljharb/function-bind/commit/5ed97f51235c17774e0832e122abda0f3229c908) +- Use a SPDX-compliant “license” field. [`5feefea`](https://github.com/ljharb/function-bind/commit/5feefea0dc0193993e83e5df01ded424403a5381) + +## [v1.1.0](https://github.com/ljharb/function-bind/compare/v1.0.2...v1.1.0) - 2016-02-14 + +### Commits + +- Update `eslint`, `tape`; use my personal shared `eslint` config [`9c9062a`](https://github.com/ljharb/function-bind/commit/9c9062abbe9dd70b59ea2c3a3c3a81f29b457097) +- Add `npm run eslint` [`dd96c56`](https://github.com/ljharb/function-bind/commit/dd96c56720034a3c1ffee10b8a59a6f7c53e24ad) +- [New] return the native `bind` when available. [`82186e0`](https://github.com/ljharb/function-bind/commit/82186e03d73e580f95ff167e03f3582bed90ed72) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`a3dd767`](https://github.com/ljharb/function-bind/commit/a3dd76720c795cb7f4586b0544efabf8aa107b8b) +- Update `eslint` [`3dae2f7`](https://github.com/ljharb/function-bind/commit/3dae2f7423de30a2d20313ddb1edc19660142fe9) +- Update `tape`, `covert`, `jscs` [`a181eee`](https://github.com/ljharb/function-bind/commit/a181eee0cfa24eb229c6e843a971f36e060a2f6a) +- [Tests] up to `node` `v5.6`, `v4.3` [`964929a`](https://github.com/ljharb/function-bind/commit/964929a6a4ddb36fb128de2bcc20af5e4f22e1ed) +- Test up to `io.js` `v2.1` [`2be7310`](https://github.com/ljharb/function-bind/commit/2be7310f2f74886a7124ca925be411117d41d5ea) +- Update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`45f3d68`](https://github.com/ljharb/function-bind/commit/45f3d6865c6ca93726abcef54febe009087af101) +- [Dev Deps] update `tape`, `jscs` [`6e1340d`](https://github.com/ljharb/function-bind/commit/6e1340d94642deaecad3e717825db641af4f8b1f) +- [Tests] up to `io.js` `v3.3`, `node` `v4.1` [`d9bad2b`](https://github.com/ljharb/function-bind/commit/d9bad2b778b1b3a6dd2876087b88b3acf319f8cc) +- Update `eslint` [`935590c`](https://github.com/ljharb/function-bind/commit/935590caa024ab356102e4858e8fc315b2ccc446) +- [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` [`8c9a1ef`](https://github.com/ljharb/function-bind/commit/8c9a1efd848e5167887aa8501857a0940a480c57) +- Test on `io.js` `v2.2` [`9a3a38c`](https://github.com/ljharb/function-bind/commit/9a3a38c92013aed6e108666e7bd40969b84ac86e) +- Run `travis-ci` tests on `iojs` and `node` v0.12; speed up builds; allow 0.8 failures. [`69afc26`](https://github.com/ljharb/function-bind/commit/69afc2617405b147dd2a8d8ae73ca9e9283f18b4) +- [Dev Deps] Update `tape`, `eslint` [`36c1be0`](https://github.com/ljharb/function-bind/commit/36c1be0ab12b45fe5df6b0fdb01a5d5137fd0115) +- Update `tape`, `jscs` [`98d8303`](https://github.com/ljharb/function-bind/commit/98d8303cd5ca1c6b8f985469f86b0d44d7d45f6e) +- Update `jscs` [`9633a4e`](https://github.com/ljharb/function-bind/commit/9633a4e9fbf82051c240855166e468ba8ba0846f) +- Update `tape`, `jscs` [`c80ef0f`](https://github.com/ljharb/function-bind/commit/c80ef0f46efc9791e76fa50de4414092ac147831) +- Test up to `io.js` `v3.0` [`7e2c853`](https://github.com/ljharb/function-bind/commit/7e2c8537d52ab9cf5a655755561d8917684c0df4) +- Test on `io.js` `v2.4` [`5a199a2`](https://github.com/ljharb/function-bind/commit/5a199a27ba46795ba5eaf0845d07d4b8232895c9) +- Test on `io.js` `v2.3` [`a511b88`](https://github.com/ljharb/function-bind/commit/a511b8896de0bddf3b56862daa416c701f4d0453) +- Fixing a typo from 822b4e1938db02dc9584aa434fd3a45cb20caf43 [`732d6b6`](https://github.com/ljharb/function-bind/commit/732d6b63a9b33b45230e630dbcac7a10855d3266) +- Update `jscs` [`da52a48`](https://github.com/ljharb/function-bind/commit/da52a4886c06d6490f46ae30b15e4163ba08905d) +- Lock covert to v1.0.0. [`d6150fd`](https://github.com/ljharb/function-bind/commit/d6150fda1e6f486718ebdeff823333d9e48e7430) + +## [v1.0.2](https://github.com/ljharb/function-bind/compare/v1.0.1...v1.0.2) - 2014-10-04 + +## [v1.0.1](https://github.com/ljharb/function-bind/compare/v1.0.0...v1.0.1) - 2014-10-03 + +### Merged + +- make CI build faster [`#3`](https://github.com/ljharb/function-bind/pull/3) + +### Commits + +- Using my standard jscs.json [`d8ee94c`](https://github.com/ljharb/function-bind/commit/d8ee94c993eff0a84cf5744fe6a29627f5cffa1a) +- Adding `npm run lint` [`7571ab7`](https://github.com/ljharb/function-bind/commit/7571ab7dfdbd99b25a1dbb2d232622bd6f4f9c10) +- Using consistent indentation [`e91a1b1`](https://github.com/ljharb/function-bind/commit/e91a1b13a61e99ec1e530e299b55508f74218a95) +- Updating jscs [`7e17892`](https://github.com/ljharb/function-bind/commit/7e1789284bc629bc9c1547a61c9b227bbd8c7a65) +- Using consistent quotes [`c50b57f`](https://github.com/ljharb/function-bind/commit/c50b57fcd1c5ec38320979c837006069ebe02b77) +- Adding keywords [`cb94631`](https://github.com/ljharb/function-bind/commit/cb946314eed35f21186a25fb42fc118772f9ee00) +- Directly export a function expression instead of using a declaration, and relying on hoisting. [`5a33c5f`](https://github.com/ljharb/function-bind/commit/5a33c5f45642de180e0d207110bf7d1843ceb87c) +- Naming npm URL and badge in README; use SVG [`2aef8fc`](https://github.com/ljharb/function-bind/commit/2aef8fcb79d54e63a58ae557c4e60949e05d5e16) +- Naming deps URLs in README [`04228d7`](https://github.com/ljharb/function-bind/commit/04228d766670ee45ca24e98345c1f6a7621065b5) +- Naming travis-ci URLs in README; using SVG [`62c810c`](https://github.com/ljharb/function-bind/commit/62c810c2f54ced956cd4d4ab7b793055addfe36e) +- Make sure functions are invoked correctly (also passing coverage tests) [`2b289b4`](https://github.com/ljharb/function-bind/commit/2b289b4dfbf037ffcfa4dc95eb540f6165e9e43a) +- Removing the strict mode pragmas; they make tests fail. [`1aa701d`](https://github.com/ljharb/function-bind/commit/1aa701d199ddc3782476e8f7eef82679be97b845) +- Adding myself as a contributor [`85fd57b`](https://github.com/ljharb/function-bind/commit/85fd57b0860e5a7af42de9a287f3f265fc6d72fc) +- Adding strict mode pragmas [`915b08e`](https://github.com/ljharb/function-bind/commit/915b08e084c86a722eafe7245e21db74aa21ca4c) +- Adding devDeps URLs to README [`4ccc731`](https://github.com/ljharb/function-bind/commit/4ccc73112c1769859e4ca3076caf4086b3cba2cd) +- Fixing the description. [`a7a472c`](https://github.com/ljharb/function-bind/commit/a7a472cf649af515c635cf560fc478fbe48999c8) +- Using a function expression instead of a function declaration. [`b5d3e4e`](https://github.com/ljharb/function-bind/commit/b5d3e4ea6aaffc63888953eeb1fbc7ff45f1fa14) +- Updating tape [`f086be6`](https://github.com/ljharb/function-bind/commit/f086be6029fb56dde61a258c1340600fa174d1e0) +- Updating jscs [`5f9bdb3`](https://github.com/ljharb/function-bind/commit/5f9bdb375ab13ba48f30852aab94029520c54d71) +- Updating jscs [`9b409ba`](https://github.com/ljharb/function-bind/commit/9b409ba6118e23395a4e5d83ef39152aab9d3bfc) +- Run coverage as part of tests. [`8e1b6d4`](https://github.com/ljharb/function-bind/commit/8e1b6d459f047d1bd4fee814e01247c984c80bd0) +- Run linter as part of tests [`c1ca83f`](https://github.com/ljharb/function-bind/commit/c1ca83f832df94587d09e621beba682fabfaa987) +- Updating covert [`701e837`](https://github.com/ljharb/function-bind/commit/701e83774b57b4d3ef631e1948143f43a72f4bb9) + +## [v1.0.0](https://github.com/ljharb/function-bind/compare/v0.2.0...v1.0.0) - 2014-08-09 + +### Commits + +- Make sure old and unstable nodes don't fail Travis [`27adca3`](https://github.com/ljharb/function-bind/commit/27adca34a4ab6ad67b6dfde43942a1b103ce4d75) +- Fixing an issue when the bound function is called as a constructor in ES3. [`e20122d`](https://github.com/ljharb/function-bind/commit/e20122d267d92ce553859b280cbbea5d27c07731) +- Adding `npm run coverage` [`a2e29c4`](https://github.com/ljharb/function-bind/commit/a2e29c4ecaef9e2f6cd1603e868c139073375502) +- Updating tape [`b741168`](https://github.com/ljharb/function-bind/commit/b741168b12b235b1717ff696087645526b69213c) +- Upgrading tape [`63631a0`](https://github.com/ljharb/function-bind/commit/63631a04c7fbe97cc2fa61829cc27246d6986f74) +- Updating tape [`363cb46`](https://github.com/ljharb/function-bind/commit/363cb46dafb23cb3e347729a22f9448051d78464) + +## v0.2.0 - 2014-03-23 + +### Commits + +- Updating test coverage to match es5-shim. [`aa94d44`](https://github.com/ljharb/function-bind/commit/aa94d44b8f9d7f69f10e060db7709aa7a694e5d4) +- initial [`942ee07`](https://github.com/ljharb/function-bind/commit/942ee07e94e542d91798137bc4b80b926137e066) +- Setting the bound function's length properly. [`079f46a`](https://github.com/ljharb/function-bind/commit/079f46a2d3515b7c0b308c2c13fceb641f97ca25) +- Ensuring that some older browsers will throw when given a regex. [`36ac55b`](https://github.com/ljharb/function-bind/commit/36ac55b87f460d4330253c92870aa26fbfe8227f) +- Removing npm scripts that don't have dependencies [`9d2be60`](https://github.com/ljharb/function-bind/commit/9d2be600002cb8bc8606f8f3585ad3e05868c750) +- Updating tape [`297a4ac`](https://github.com/ljharb/function-bind/commit/297a4acc5464db381940aafb194d1c88f4e678f3) +- Skipping length tests for now. [`d9891ea`](https://github.com/ljharb/function-bind/commit/d9891ea4d2aaffa69f408339cdd61ff740f70565) +- don't take my tea [`dccd930`](https://github.com/ljharb/function-bind/commit/dccd930bfd60ea10cb178d28c97550c3bc8c1e07) diff --git a/node_modules/function-bind/LICENSE b/node_modules/function-bind/LICENSE new file mode 100644 index 0000000..62d6d23 --- /dev/null +++ b/node_modules/function-bind/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2013 Raynos. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/node_modules/function-bind/README.md b/node_modules/function-bind/README.md new file mode 100644 index 0000000..814c20b --- /dev/null +++ b/node_modules/function-bind/README.md @@ -0,0 +1,46 @@ +# function-bind [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] + +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Implementation of function.prototype.bind + +Old versions of phantomjs, Internet Explorer < 9, and node < 0.6 don't support `Function.prototype.bind`. + +## Example + +```js +Function.prototype.bind = require("function-bind") +``` + +## Installation + +`npm install function-bind` + +## Contributors + + - Raynos + +## MIT Licenced + +[package-url]: https://npmjs.org/package/function-bind +[npm-version-svg]: https://versionbadg.es/Raynos/function-bind.svg +[deps-svg]: https://david-dm.org/Raynos/function-bind.svg +[deps-url]: https://david-dm.org/Raynos/function-bind +[dev-deps-svg]: https://david-dm.org/Raynos/function-bind/dev-status.svg +[dev-deps-url]: https://david-dm.org/Raynos/function-bind#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/function-bind.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/function-bind.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/function-bind.svg +[downloads-url]: https://npm-stat.com/charts.html?package=function-bind +[codecov-image]: https://codecov.io/gh/Raynos/function-bind/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/Raynos/function-bind/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/Raynos/function-bind +[actions-url]: https://github.com/Raynos/function-bind/actions diff --git a/node_modules/function-bind/implementation.js b/node_modules/function-bind/implementation.js new file mode 100644 index 0000000..fd4384c --- /dev/null +++ b/node_modules/function-bind/implementation.js @@ -0,0 +1,84 @@ +'use strict'; + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var toStr = Object.prototype.toString; +var max = Math.max; +var funcType = '[object Function]'; + +var concatty = function concatty(a, b) { + var arr = []; + + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b.length; j += 1) { + arr[j + a.length] = b[j]; + } + + return arr; +}; + +var slicy = function slicy(arrLike, offset) { + var arr = []; + for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; +}; + +var joiny = function (arr, joiner) { + var str = ''; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; +}; + +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + + }; + + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = '$' + i; + } + + bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; diff --git a/node_modules/function-bind/index.js b/node_modules/function-bind/index.js new file mode 100644 index 0000000..3bb6b96 --- /dev/null +++ b/node_modules/function-bind/index.js @@ -0,0 +1,5 @@ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = Function.prototype.bind || implementation; diff --git a/node_modules/function-bind/package.json b/node_modules/function-bind/package.json new file mode 100644 index 0000000..6185963 --- /dev/null +++ b/node_modules/function-bind/package.json @@ -0,0 +1,87 @@ +{ + "name": "function-bind", + "version": "1.1.2", + "description": "Implementation of Function.prototype.bind", + "keywords": [ + "function", + "bind", + "shim", + "es5" + ], + "author": "Raynos ", + "repository": { + "type": "git", + "url": "https://github.com/Raynos/function-bind.git" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "main": "index", + "homepage": "https://github.com/Raynos/function-bind", + "contributors": [ + { + "name": "Raynos" + }, + { + "name": "Jordan Harband", + "url": "https://github.com/ljharb" + } + ], + "bugs": { + "url": "https://github.com/Raynos/function-bind/issues", + "email": "raynos2@gmail.com" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.3", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.1" + }, + "license": "MIT", + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepack": "npmignore --auto --commentLines=autogenerated", + "pretest": "npm run lint", + "test": "npm run tests-only", + "posttest": "aud --production", + "tests-only": "nyc tape 'test/**/*.js'", + "lint": "eslint --ext=js,mjs .", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "ie/8..latest", + "firefox/16..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/function-bind/test/.eslintrc b/node_modules/function-bind/test/.eslintrc new file mode 100644 index 0000000..8a56d5b --- /dev/null +++ b/node_modules/function-bind/test/.eslintrc @@ -0,0 +1,9 @@ +{ + "rules": { + "array-bracket-newline": 0, + "array-element-newline": 0, + "max-statements-per-line": [2, { "max": 2 }], + "no-invalid-this": 0, + "no-magic-numbers": 0, + } +} diff --git a/node_modules/function-bind/test/index.js b/node_modules/function-bind/test/index.js new file mode 100644 index 0000000..2edecce --- /dev/null +++ b/node_modules/function-bind/test/index.js @@ -0,0 +1,252 @@ +// jscs:disable requireUseStrict + +var test = require('tape'); + +var functionBind = require('../implementation'); +var getCurrentContext = function () { return this; }; + +test('functionBind is a function', function (t) { + t.equal(typeof functionBind, 'function'); + t.end(); +}); + +test('non-functions', function (t) { + var nonFunctions = [true, false, [], {}, 42, 'foo', NaN, /a/g]; + t.plan(nonFunctions.length); + for (var i = 0; i < nonFunctions.length; ++i) { + try { functionBind.call(nonFunctions[i]); } catch (ex) { + t.ok(ex instanceof TypeError, 'throws when given ' + String(nonFunctions[i])); + } + } + t.end(); +}); + +test('without a context', function (t) { + t.test('binds properly', function (st) { + var args, context; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }) + }; + namespace.func(1, 2, 3); + st.deepEqual(args, [1, 2, 3]); + st.equal(context, getCurrentContext.call()); + st.end(); + }); + + t.test('binds properly, and still supplies bound arguments', function (st) { + var args, context; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, undefined, 1, 2, 3) + }; + namespace.func(4, 5, 6); + st.deepEqual(args, [1, 2, 3, 4, 5, 6]); + st.equal(context, getCurrentContext.call()); + st.end(); + }); + + t.test('returns properly', function (st) { + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, null) + }; + var context = namespace.func(1, 2, 3); + st.equal(context, getCurrentContext.call(), 'returned context is namespaced context'); + st.deepEqual(args, [1, 2, 3], 'passed arguments are correct'); + st.end(); + }); + + t.test('returns properly with bound arguments', function (st) { + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, null, 1, 2, 3) + }; + var context = namespace.func(4, 5, 6); + st.equal(context, getCurrentContext.call(), 'returned context is namespaced context'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct'); + st.end(); + }); + + t.test('called as a constructor', function (st) { + var thunkify = function (value) { + return function () { return value; }; + }; + st.test('returns object value', function (sst) { + var expectedReturnValue = [1, 2, 3]; + var Constructor = functionBind.call(thunkify(expectedReturnValue), null); + var result = new Constructor(); + sst.equal(result, expectedReturnValue); + sst.end(); + }); + + st.test('does not return primitive value', function (sst) { + var Constructor = functionBind.call(thunkify(42), null); + var result = new Constructor(); + sst.notEqual(result, 42); + sst.end(); + }); + + st.test('object from bound constructor is instance of original and bound constructor', function (sst) { + var A = function (x) { + this.name = x || 'A'; + }; + var B = functionBind.call(A, null, 'B'); + + var result = new B(); + sst.ok(result instanceof B, 'result is instance of bound constructor'); + sst.ok(result instanceof A, 'result is instance of original constructor'); + sst.end(); + }); + + st.end(); + }); + + t.end(); +}); + +test('with a context', function (t) { + t.test('with no bound arguments', function (st) { + var args, context; + var boundContext = {}; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, boundContext) + }; + namespace.func(1, 2, 3); + st.equal(context, boundContext, 'binds a context properly'); + st.deepEqual(args, [1, 2, 3], 'supplies passed arguments'); + st.end(); + }); + + t.test('with bound arguments', function (st) { + var args, context; + var boundContext = {}; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, boundContext, 1, 2, 3) + }; + namespace.func(4, 5, 6); + st.equal(context, boundContext, 'binds a context properly'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'supplies bound and passed arguments'); + st.end(); + }); + + t.test('returns properly', function (st) { + var boundContext = {}; + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, boundContext) + }; + var context = namespace.func(1, 2, 3); + st.equal(context, boundContext, 'returned context is bound context'); + st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context'); + st.deepEqual(args, [1, 2, 3], 'passed arguments are correct'); + st.end(); + }); + + t.test('returns properly with bound arguments', function (st) { + var boundContext = {}; + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, boundContext, 1, 2, 3) + }; + var context = namespace.func(4, 5, 6); + st.equal(context, boundContext, 'returned context is bound context'); + st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct'); + st.end(); + }); + + t.test('passes the correct arguments when called as a constructor', function (st) { + var expected = { name: 'Correct' }; + var namespace = { + Func: functionBind.call(function (arg) { + return arg; + }, { name: 'Incorrect' }) + }; + var returned = new namespace.Func(expected); + st.equal(returned, expected, 'returns the right arg when called as a constructor'); + st.end(); + }); + + t.test('has the new instance\'s context when called as a constructor', function (st) { + var actualContext; + var expectedContext = { foo: 'bar' }; + var namespace = { + Func: functionBind.call(function () { + actualContext = this; + }, expectedContext) + }; + var result = new namespace.Func(); + st.equal(result instanceof namespace.Func, true); + st.notEqual(actualContext, expectedContext); + st.end(); + }); + + t.end(); +}); + +test('bound function length', function (t) { + t.test('sets a correct length without thisArg', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }); + st.equal(subject.length, 3); + st.equal(subject(1, 2, 3), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}); + st.equal(subject.length, 3); + st.equal(subject(1, 2, 3), 6); + st.end(); + }); + + t.test('sets a correct length without thisArg and first argument', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1); + st.equal(subject.length, 2); + st.equal(subject(2, 3), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg and first argument', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1); + st.equal(subject.length, 2); + st.equal(subject(2, 3), 6); + st.end(); + }); + + t.test('sets a correct length without thisArg and too many arguments', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1, 2, 3, 4); + st.equal(subject.length, 0); + st.equal(subject(), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg and too many arguments', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1, 2, 3, 4); + st.equal(subject.length, 0); + st.equal(subject(), 6); + st.end(); + }); +}); diff --git a/node_modules/get-intrinsic/.eslintrc b/node_modules/get-intrinsic/.eslintrc new file mode 100644 index 0000000..235fb79 --- /dev/null +++ b/node_modules/get-intrinsic/.eslintrc @@ -0,0 +1,42 @@ +{ + "root": true, + + "extends": "@ljharb", + + "env": { + "es6": true, + "es2017": true, + "es2020": true, + "es2021": true, + "es2022": true, + }, + + "globals": { + "Float16Array": false, + }, + + "rules": { + "array-bracket-newline": 0, + "complexity": 0, + "eqeqeq": [2, "allow-null"], + "func-name-matching": 0, + "id-length": 0, + "max-lines": 0, + "max-lines-per-function": [2, 90], + "max-params": [2, 4], + "max-statements": 0, + "max-statements-per-line": [2, { "max": 2 }], + "multiline-comment-style": 0, + "no-magic-numbers": 0, + "sort-keys": 0, + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "new-cap": 0, + }, + }, + ], +} diff --git a/node_modules/get-intrinsic/.github/FUNDING.yml b/node_modules/get-intrinsic/.github/FUNDING.yml new file mode 100644 index 0000000..8e8da0d --- /dev/null +++ b/node_modules/get-intrinsic/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/get-intrinsic +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/get-intrinsic/.nycrc b/node_modules/get-intrinsic/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/get-intrinsic/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/get-intrinsic/CHANGELOG.md b/node_modules/get-intrinsic/CHANGELOG.md new file mode 100644 index 0000000..ce1dd98 --- /dev/null +++ b/node_modules/get-intrinsic/CHANGELOG.md @@ -0,0 +1,186 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.3.0](https://github.com/ljharb/get-intrinsic/compare/v1.2.7...v1.3.0) - 2025-02-22 + +### Commits + +- [Dev Deps] update `es-abstract`, `es-value-fixtures`, `for-each`, `object-inspect` [`9b61553`](https://github.com/ljharb/get-intrinsic/commit/9b61553c587f1c1edbd435597e88c7d387da97dd) +- [Deps] update `call-bind-apply-helpers`, `es-object-atoms`, `get-proto` [`a341fee`](https://github.com/ljharb/get-intrinsic/commit/a341fee0f39a403b0f0069e82c97642d5eb11043) +- [New] add `Float16Array` [`de22116`](https://github.com/ljharb/get-intrinsic/commit/de22116b492fb989a0341bceb6e573abfaed73dc) + +## [v1.2.7](https://github.com/ljharb/get-intrinsic/compare/v1.2.6...v1.2.7) - 2025-01-02 + +### Commits + +- [Refactor] use `get-proto` directly [`00ab955`](https://github.com/ljharb/get-intrinsic/commit/00ab95546a0980c8ad42a84253daaa8d2adcedf9) +- [Deps] update `math-intrinsics` [`c716cdd`](https://github.com/ljharb/get-intrinsic/commit/c716cdd6bbe36b438057025561b8bb5a879ac8a0) +- [Dev Deps] update `call-bound`, `es-abstract` [`dc648a6`](https://github.com/ljharb/get-intrinsic/commit/dc648a67eb359037dff8d8619bfa71d86debccb1) + +## [v1.2.6](https://github.com/ljharb/get-intrinsic/compare/v1.2.5...v1.2.6) - 2024-12-11 + +### Commits + +- [Refactor] use `math-intrinsics` [`841be86`](https://github.com/ljharb/get-intrinsic/commit/841be8641a9254c4c75483b30c8871b5d5065926) +- [Refactor] use `es-object-atoms` [`42057df`](https://github.com/ljharb/get-intrinsic/commit/42057dfa16f66f64787e66482af381cc6f31d2c1) +- [Deps] update `call-bind-apply-helpers` [`45afa24`](https://github.com/ljharb/get-intrinsic/commit/45afa24a9ee4d6d3c172db1f555b16cb27843ef4) +- [Dev Deps] update `call-bound` [`9cba9c6`](https://github.com/ljharb/get-intrinsic/commit/9cba9c6e70212bc163b7a5529cb25df46071646f) + +## [v1.2.5](https://github.com/ljharb/get-intrinsic/compare/v1.2.4...v1.2.5) - 2024-12-06 + +### Commits + +- [actions] split out node 10-20, and 20+ [`6e2b9dd`](https://github.com/ljharb/get-intrinsic/commit/6e2b9dd23902665681ebe453256ccfe21d7966f0) +- [Refactor] use `dunder-proto` and `call-bind-apply-helpers` instead of `has-proto` [`c095d17`](https://github.com/ljharb/get-intrinsic/commit/c095d179ad0f4fbfff20c8a3e0cb4fe668018998) +- [Refactor] use `gopd` [`9841d5b`](https://github.com/ljharb/get-intrinsic/commit/9841d5b35f7ab4fd2d193f0c741a50a077920e90) +- [Dev Deps] update `@ljharb/eslint-config`, `auto-changelog`, `es-abstract`, `es-value-fixtures`, `gopd`, `mock-property`, `object-inspect`, `tape` [`2d07e01`](https://github.com/ljharb/get-intrinsic/commit/2d07e01310cee2cbaedfead6903df128b1f5d425) +- [Deps] update `gopd`, `has-proto`, `has-symbols`, `hasown` [`974d8bf`](https://github.com/ljharb/get-intrinsic/commit/974d8bf5baad7939eef35c25cc1dd88c10a30fa6) +- [Dev Deps] update `call-bind`, `es-abstract`, `tape` [`df9dde1`](https://github.com/ljharb/get-intrinsic/commit/df9dde178186631ab8a3165ede056549918ce4bc) +- [Refactor] cache `es-define-property` as well [`43ef543`](https://github.com/ljharb/get-intrinsic/commit/43ef543cb02194401420e3a914a4ca9168691926) +- [Deps] update `has-proto`, `has-symbols`, `hasown` [`ad4949d`](https://github.com/ljharb/get-intrinsic/commit/ad4949d5467316505aad89bf75f9417ed782f7af) +- [Tests] use `call-bound` directly [`ad5c406`](https://github.com/ljharb/get-intrinsic/commit/ad5c4069774bfe90e520a35eead5fe5ca9d69e80) +- [Deps] update `has-proto`, `hasown` [`45414ca`](https://github.com/ljharb/get-intrinsic/commit/45414caa312333a2798953682c68f85c550627dd) +- [Tests] replace `aud` with `npm audit` [`18d3509`](https://github.com/ljharb/get-intrinsic/commit/18d3509f79460e7924da70409ee81e5053087523) +- [Deps] update `es-define-property` [`aadaa3b`](https://github.com/ljharb/get-intrinsic/commit/aadaa3b2188d77ad9bff394ce5d4249c49eb21f5) +- [Dev Deps] add missing peer dep [`c296a16`](https://github.com/ljharb/get-intrinsic/commit/c296a16246d0c9a5981944f4cc5cf61fbda0cf6a) + +## [v1.2.4](https://github.com/ljharb/get-intrinsic/compare/v1.2.3...v1.2.4) - 2024-02-05 + +### Commits + +- [Refactor] use all 7 <+ ES6 Errors from `es-errors` [`bcac811`](https://github.com/ljharb/get-intrinsic/commit/bcac811abdc1c982e12abf848a410d6aae148d14) + +## [v1.2.3](https://github.com/ljharb/get-intrinsic/compare/v1.2.2...v1.2.3) - 2024-02-03 + +### Commits + +- [Refactor] use `es-errors`, so things that only need those do not need `get-intrinsic` [`f11db9c`](https://github.com/ljharb/get-intrinsic/commit/f11db9c4fb97d87bbd53d3c73ac6b3db3613ad3b) +- [Dev Deps] update `aud`, `es-abstract`, `mock-property`, `npmignore` [`b7ac7d1`](https://github.com/ljharb/get-intrinsic/commit/b7ac7d1616fefb03877b1aed0c8f8d61aad32b6c) +- [meta] simplify `exports` [`faa0cc6`](https://github.com/ljharb/get-intrinsic/commit/faa0cc618e2830ffb51a8202490b0c215d965cbc) +- [meta] add missing `engines.node` [`774dd0b`](https://github.com/ljharb/get-intrinsic/commit/774dd0b3e8f741c3f05a6322d124d6087f146af1) +- [Dev Deps] update `tape` [`5828e8e`](https://github.com/ljharb/get-intrinsic/commit/5828e8e4a04e69312e87a36c0ea39428a7a4c3d8) +- [Robustness] use null objects for lookups [`eb9a11f`](https://github.com/ljharb/get-intrinsic/commit/eb9a11fa9eb3e13b193fcc05a7fb814341b1a7b7) +- [meta] add `sideEffects` flag [`89bcc7a`](https://github.com/ljharb/get-intrinsic/commit/89bcc7a42e19bf07b7c21e3094d5ab177109e6d2) + +## [v1.2.2](https://github.com/ljharb/get-intrinsic/compare/v1.2.1...v1.2.2) - 2023-10-20 + +### Commits + +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `call-bind`, `es-abstract`, `mock-property`, `object-inspect`, `tape` [`f51bcf2`](https://github.com/ljharb/get-intrinsic/commit/f51bcf26412d58d17ce17c91c9afd0ad271f0762) +- [Refactor] use `hasown` instead of `has` [`18d14b7`](https://github.com/ljharb/get-intrinsic/commit/18d14b799bea6b5765e1cec91890830cbcdb0587) +- [Deps] update `function-bind` [`6e109c8`](https://github.com/ljharb/get-intrinsic/commit/6e109c81e03804cc5e7824fb64353cdc3d8ee2c7) + +## [v1.2.1](https://github.com/ljharb/get-intrinsic/compare/v1.2.0...v1.2.1) - 2023-05-13 + +### Commits + +- [Fix] avoid a crash in envs without `__proto__` [`7bad8d0`](https://github.com/ljharb/get-intrinsic/commit/7bad8d061bf8721733b58b73a2565af2b6756b64) +- [Dev Deps] update `es-abstract` [`c60e6b7`](https://github.com/ljharb/get-intrinsic/commit/c60e6b7b4cf9660c7f27ed970970fd55fac48dc5) + +## [v1.2.0](https://github.com/ljharb/get-intrinsic/compare/v1.1.3...v1.2.0) - 2023-01-19 + +### Commits + +- [actions] update checkout action [`ca6b12f`](https://github.com/ljharb/get-intrinsic/commit/ca6b12f31eaacea4ea3b055e744cd61623385ffb) +- [Dev Deps] update `@ljharb/eslint-config`, `es-abstract`, `object-inspect`, `tape` [`41a3727`](https://github.com/ljharb/get-intrinsic/commit/41a3727d0026fa04273ae216a5f8e12eefd72da8) +- [Fix] ensure `Error.prototype` is undeniable [`c511e97`](https://github.com/ljharb/get-intrinsic/commit/c511e97ae99c764c4524b540dee7a70757af8da3) +- [Dev Deps] update `aud`, `es-abstract`, `tape` [`1bef8a8`](https://github.com/ljharb/get-intrinsic/commit/1bef8a8fd439ebb80863199b6189199e0851ac67) +- [Dev Deps] update `aud`, `es-abstract` [`0d41f16`](https://github.com/ljharb/get-intrinsic/commit/0d41f16bcd500bc28b7bfc98043ebf61ea081c26) +- [New] add `BigInt64Array` and `BigUint64Array` [`a6cca25`](https://github.com/ljharb/get-intrinsic/commit/a6cca25f29635889b7e9bd669baf9e04be90e48c) +- [Tests] use `gopd` [`ecf7722`](https://github.com/ljharb/get-intrinsic/commit/ecf7722240d15cfd16edda06acf63359c10fb9bd) + +## [v1.1.3](https://github.com/ljharb/get-intrinsic/compare/v1.1.2...v1.1.3) - 2022-09-12 + +### Commits + +- [Dev Deps] update `es-abstract`, `es-value-fixtures`, `tape` [`07ff291`](https://github.com/ljharb/get-intrinsic/commit/07ff291816406ebe5a12d7f16965bde0942dd688) +- [Fix] properly check for % signs [`50ac176`](https://github.com/ljharb/get-intrinsic/commit/50ac1760fe99c227e64eabde76e9c0e44cd881b5) + +## [v1.1.2](https://github.com/ljharb/get-intrinsic/compare/v1.1.1...v1.1.2) - 2022-06-08 + +### Fixed + +- [Fix] properly validate against extra % signs [`#16`](https://github.com/ljharb/get-intrinsic/issues/16) + +### Commits + +- [actions] reuse common workflows [`0972547`](https://github.com/ljharb/get-intrinsic/commit/0972547efd0abc863fe4c445a6ca7eb4f8c6901d) +- [meta] use `npmignore` to autogenerate an npmignore file [`5ba0b51`](https://github.com/ljharb/get-intrinsic/commit/5ba0b51d8d8d4f1c31d426d74abc0770fd106bad) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`c364492`](https://github.com/ljharb/get-intrinsic/commit/c364492af4af51333e6f81c0bf21fd3d602c3661) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `es-abstract`, `object-inspect`, `tape` [`dc04dad`](https://github.com/ljharb/get-intrinsic/commit/dc04dad86f6e5608775a2640cb0db5927ae29ed9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `es-abstract`, `object-inspect`, `safe-publish-latest`, `tape` [`1c14059`](https://github.com/ljharb/get-intrinsic/commit/1c1405984e86dd2dc9366c15d8a0294a96a146a5) +- [Tests] use `mock-property` [`b396ef0`](https://github.com/ljharb/get-intrinsic/commit/b396ef05bb73b1d699811abd64b0d9b97997fdda) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `object-inspect`, `tape` [`c2c758d`](https://github.com/ljharb/get-intrinsic/commit/c2c758d3b90af4fef0a76910d8d3c292ec8d1d3e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `es-abstract`, `es-value-fixtures`, `object-inspect`, `tape` [`29e3c09`](https://github.com/ljharb/get-intrinsic/commit/29e3c091c2bf3e17099969847e8729d0e46896de) +- [actions] update codecov uploader [`8cbc141`](https://github.com/ljharb/get-intrinsic/commit/8cbc1418940d7a8941f3a7985cbc4ac095c5e13d) +- [Dev Deps] update `@ljharb/eslint-config`, `es-abstract`, `es-value-fixtures`, `object-inspect`, `tape` [`10b6f5c`](https://github.com/ljharb/get-intrinsic/commit/10b6f5c02593fb3680c581d696ac124e30652932) +- [readme] add github actions/codecov badges [`4e25400`](https://github.com/ljharb/get-intrinsic/commit/4e25400d9f51ae9eb059cbe22d9144e70ea214e8) +- [Tests] use `for-each` instead of `foreach` [`c05b957`](https://github.com/ljharb/get-intrinsic/commit/c05b957ad9a7bc7721af7cc9e9be1edbfe057496) +- [Dev Deps] update `es-abstract` [`29b05ae`](https://github.com/ljharb/get-intrinsic/commit/29b05aec3e7330e9ad0b8e0f685a9112c20cdd97) +- [meta] use `prepublishOnly` script for npm 7+ [`95c285d`](https://github.com/ljharb/get-intrinsic/commit/95c285da810516057d3bbfa871176031af38f05d) +- [Deps] update `has-symbols` [`593cb4f`](https://github.com/ljharb/get-intrinsic/commit/593cb4fb38e7922e40e42c183f45274b636424cd) +- [readme] fix repo URLs [`1c8305b`](https://github.com/ljharb/get-intrinsic/commit/1c8305b5365827c9b6fc785434aac0e1328ff2f5) +- [Deps] update `has-symbols` [`c7138b6`](https://github.com/ljharb/get-intrinsic/commit/c7138b6c6d73132d859471fb8c13304e1e7c8b20) +- [Dev Deps] remove unused `has-bigints` [`bd63aff`](https://github.com/ljharb/get-intrinsic/commit/bd63aff6ad8f3a986c557fcda2914187bdaab359) + +## [v1.1.1](https://github.com/ljharb/get-intrinsic/compare/v1.1.0...v1.1.1) - 2021-02-03 + +### Fixed + +- [meta] export `./package.json` [`#9`](https://github.com/ljharb/get-intrinsic/issues/9) + +### Commits + +- [readme] flesh out the readme; use `evalmd` [`d12f12c`](https://github.com/ljharb/get-intrinsic/commit/d12f12c15345a0a0772cc65a7c64369529abd614) +- [eslint] set up proper globals config [`5a8c098`](https://github.com/ljharb/get-intrinsic/commit/5a8c0984e3319d1ac0e64b102f8ec18b64e79f36) +- [Dev Deps] update `eslint` [`7b9a5c0`](https://github.com/ljharb/get-intrinsic/commit/7b9a5c0d31a90ca1a1234181c74988fb046701cd) + +## [v1.1.0](https://github.com/ljharb/get-intrinsic/compare/v1.0.2...v1.1.0) - 2021-01-25 + +### Fixed + +- [Refactor] delay `Function` eval until syntax-derived values are requested [`#3`](https://github.com/ljharb/get-intrinsic/issues/3) + +### Commits + +- [Tests] migrate tests to Github Actions [`2ab762b`](https://github.com/ljharb/get-intrinsic/commit/2ab762b48164aea8af37a40ba105bbc8246ab8c4) +- [meta] do not publish github action workflow files [`5e7108e`](https://github.com/ljharb/get-intrinsic/commit/5e7108e4768b244d48d9567ba4f8a6cab9c65b8e) +- [Tests] add some coverage [`01ac7a8`](https://github.com/ljharb/get-intrinsic/commit/01ac7a87ac29738567e8524cd8c9e026b1fa8cb3) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `call-bind`, `es-abstract`, `tape`; add `call-bind` [`911b672`](https://github.com/ljharb/get-intrinsic/commit/911b672fbffae433a96924c6ce013585e425f4b7) +- [Refactor] rearrange evalled constructors a bit [`7e7e4bf`](https://github.com/ljharb/get-intrinsic/commit/7e7e4bf583f3799c8ac1c6c5e10d2cb553957347) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`0199968`](https://github.com/ljharb/get-intrinsic/commit/01999687a263ffce0a3cb011dfbcb761754aedbc) + +## [v1.0.2](https://github.com/ljharb/get-intrinsic/compare/v1.0.1...v1.0.2) - 2020-12-17 + +### Commits + +- [Fix] Throw for non‑existent intrinsics [`68f873b`](https://github.com/ljharb/get-intrinsic/commit/68f873b013c732a05ad6f5fc54f697e55515461b) +- [Fix] Throw for non‑existent segments in the intrinsic path [`8325dee`](https://github.com/ljharb/get-intrinsic/commit/8325deee43128f3654d3399aa9591741ebe17b21) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `has-bigints`, `object-inspect` [`0c227a7`](https://github.com/ljharb/get-intrinsic/commit/0c227a7d8b629166f25715fd242553892e458525) +- [meta] do not lint coverage output [`70d2419`](https://github.com/ljharb/get-intrinsic/commit/70d24199b620043cd9110fc5f426d214ebe21dc9) + +## [v1.0.1](https://github.com/ljharb/get-intrinsic/compare/v1.0.0...v1.0.1) - 2020-10-30 + +### Commits + +- [Tests] gather coverage data on every job [`d1d280d`](https://github.com/ljharb/get-intrinsic/commit/d1d280dec714e3f0519cc877dbcb193057d9cac6) +- [Fix] add missing dependencies [`5031771`](https://github.com/ljharb/get-intrinsic/commit/5031771bb1095b38be88ce7c41d5de88718e432e) +- [Tests] use `es-value-fixtures` [`af48765`](https://github.com/ljharb/get-intrinsic/commit/af48765a23c5323fb0b6b38dbf00eb5099c7bebc) + +## v1.0.0 - 2020-10-29 + +### Commits + +- Implementation [`bbce57c`](https://github.com/ljharb/get-intrinsic/commit/bbce57c6f33d05b2d8d3efa273ceeb3ee01127bb) +- Tests [`17b4f0d`](https://github.com/ljharb/get-intrinsic/commit/17b4f0d56dea6b4059b56fc30ef3ee4d9500ebc2) +- Initial commit [`3153294`](https://github.com/ljharb/get-intrinsic/commit/31532948de363b0a27dd9fd4649e7b7028ec4b44) +- npm init [`fb326c4`](https://github.com/ljharb/get-intrinsic/commit/fb326c4d2817c8419ec31de1295f06bb268a7902) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`48862fb`](https://github.com/ljharb/get-intrinsic/commit/48862fb2508c8f6a57968e6d08b7c883afc9d550) +- [meta] add `auto-changelog` [`5f28ad0`](https://github.com/ljharb/get-intrinsic/commit/5f28ad019e060a353d8028f9f2591a9cc93074a1) +- [meta] add "funding"; create `FUNDING.yml` [`c2bbdde`](https://github.com/ljharb/get-intrinsic/commit/c2bbddeba73a875be61484ee4680b129a6d4e0a1) +- [Tests] add `npm run lint` [`0a84b98`](https://github.com/ljharb/get-intrinsic/commit/0a84b98b22b7cf7a748666f705b0003a493c35fd) +- Only apps should have lockfiles [`9586c75`](https://github.com/ljharb/get-intrinsic/commit/9586c75866c1ee678e4d5d4dbbdef6997e511b05) diff --git a/node_modules/get-intrinsic/LICENSE b/node_modules/get-intrinsic/LICENSE new file mode 100644 index 0000000..48f05d0 --- /dev/null +++ b/node_modules/get-intrinsic/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/get-intrinsic/README.md b/node_modules/get-intrinsic/README.md new file mode 100644 index 0000000..3aa0bba --- /dev/null +++ b/node_modules/get-intrinsic/README.md @@ -0,0 +1,71 @@ +# get-intrinsic [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Get and robustly cache all JS language-level intrinsics at first require time. + +See the syntax described [in the JS spec](https://tc39.es/ecma262/#sec-well-known-intrinsic-objects) for reference. + +## Example + +```js +var GetIntrinsic = require('get-intrinsic'); +var assert = require('assert'); + +// static methods +assert.equal(GetIntrinsic('%Math.pow%'), Math.pow); +assert.equal(Math.pow(2, 3), 8); +assert.equal(GetIntrinsic('%Math.pow%')(2, 3), 8); +delete Math.pow; +assert.equal(GetIntrinsic('%Math.pow%')(2, 3), 8); + +// instance methods +var arr = [1]; +assert.equal(GetIntrinsic('%Array.prototype.push%'), Array.prototype.push); +assert.deepEqual(arr, [1]); + +arr.push(2); +assert.deepEqual(arr, [1, 2]); + +GetIntrinsic('%Array.prototype.push%').call(arr, 3); +assert.deepEqual(arr, [1, 2, 3]); + +delete Array.prototype.push; +GetIntrinsic('%Array.prototype.push%').call(arr, 4); +assert.deepEqual(arr, [1, 2, 3, 4]); + +// missing features +delete JSON.parse; // to simulate a real intrinsic that is missing in the environment +assert.throws(() => GetIntrinsic('%JSON.parse%')); +assert.equal(undefined, GetIntrinsic('%JSON.parse%', true)); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +[package-url]: https://npmjs.org/package/get-intrinsic +[npm-version-svg]: https://versionbadg.es/ljharb/get-intrinsic.svg +[deps-svg]: https://david-dm.org/ljharb/get-intrinsic.svg +[deps-url]: https://david-dm.org/ljharb/get-intrinsic +[dev-deps-svg]: https://david-dm.org/ljharb/get-intrinsic/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/get-intrinsic#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/get-intrinsic.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/get-intrinsic.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/get-intrinsic.svg +[downloads-url]: https://npm-stat.com/charts.html?package=get-intrinsic +[codecov-image]: https://codecov.io/gh/ljharb/get-intrinsic/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/get-intrinsic/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/get-intrinsic +[actions-url]: https://github.com/ljharb/get-intrinsic/actions diff --git a/node_modules/get-intrinsic/index.js b/node_modules/get-intrinsic/index.js new file mode 100644 index 0000000..bd1d94b --- /dev/null +++ b/node_modules/get-intrinsic/index.js @@ -0,0 +1,378 @@ +'use strict'; + +var undefined; + +var $Object = require('es-object-atoms'); + +var $Error = require('es-errors'); +var $EvalError = require('es-errors/eval'); +var $RangeError = require('es-errors/range'); +var $ReferenceError = require('es-errors/ref'); +var $SyntaxError = require('es-errors/syntax'); +var $TypeError = require('es-errors/type'); +var $URIError = require('es-errors/uri'); + +var abs = require('math-intrinsics/abs'); +var floor = require('math-intrinsics/floor'); +var max = require('math-intrinsics/max'); +var min = require('math-intrinsics/min'); +var pow = require('math-intrinsics/pow'); +var round = require('math-intrinsics/round'); +var sign = require('math-intrinsics/sign'); + +var $Function = Function; + +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; + +var $gOPD = require('gopd'); +var $defineProperty = require('es-define-property'); + +var throwTypeError = function () { + throw new $TypeError(); +}; +var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + +var hasSymbols = require('has-symbols')(); + +var getProto = require('get-proto'); +var $ObjectGPO = require('get-proto/Object.getPrototypeOf'); +var $ReflectGPO = require('get-proto/Reflect.getPrototypeOf'); + +var $apply = require('call-bind-apply-helpers/functionApply'); +var $call = require('call-bind-apply-helpers/functionCall'); + +var needsEval = {}; + +var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); + +var INTRINSICS = { + __proto__: null, + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, + '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, + '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': $Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': $EvalError, + '%Float16Array%': typeof Float16Array === 'undefined' ? undefined : Float16Array, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': $Object, + '%Object.getOwnPropertyDescriptor%': $gOPD, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': $RangeError, + '%ReferenceError%': $ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%URIError%': $URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet, + + '%Function.prototype.call%': $call, + '%Function.prototype.apply%': $apply, + '%Object.defineProperty%': $defineProperty, + '%Object.getPrototypeOf%': $ObjectGPO, + '%Math.abs%': abs, + '%Math.floor%': floor, + '%Math.max%': max, + '%Math.min%': min, + '%Math.pow%': pow, + '%Math.round%': round, + '%Math.sign%': sign, + '%Reflect.getPrototypeOf%': $ReflectGPO +}; + +if (getProto) { + try { + null.error; // eslint-disable-line no-unused-expressions + } catch (e) { + // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 + var errorProto = getProto(getProto(e)); + INTRINSICS['%Error.prototype%'] = errorProto; + } +} + +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } + + INTRINSICS[name] = value; + + return value; +}; + +var LEGACY_ALIASES = { + __proto__: null, + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] +}; + +var bind = require('function-bind'); +var hasOwn = require('hasown'); +var $concat = bind.call($call, Array.prototype.concat); +var $spliceApply = bind.call($apply, Array.prototype.splice); +var $replace = bind.call($call, String.prototype.replace); +var $strSlice = bind.call($call, String.prototype.slice); +var $exec = bind.call($call, RegExp.prototype.exec); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ + +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } + + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return { + alias: alias, + name: intrinsicName, + value: value + }; + } + + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); +}; + +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; diff --git a/node_modules/get-intrinsic/package.json b/node_modules/get-intrinsic/package.json new file mode 100644 index 0000000..2828e73 --- /dev/null +++ b/node_modules/get-intrinsic/package.json @@ -0,0 +1,97 @@ +{ + "name": "get-intrinsic", + "version": "1.3.0", + "description": "Get and robustly cache all JS language-level intrinsics at first require time", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=.js,.mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>= 10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/get-intrinsic.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "es", + "js", + "intrinsic", + "getintrinsic", + "es-abstract" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/get-intrinsic/issues" + }, + "homepage": "https://github.com/ljharb/get-intrinsic#readme", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.1", + "auto-changelog": "^2.5.0", + "call-bound": "^1.0.3", + "encoding": "^0.1.13", + "es-abstract": "^1.23.9", + "es-value-fixtures": "^1.7.1", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.5", + "make-async-function": "^1.0.0", + "make-async-generator-function": "^1.0.0", + "make-generator-function": "^2.0.0", + "mock-property": "^1.1.0", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.4", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "testling": { + "files": "test/GetIntrinsic.js" + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/get-intrinsic/test/GetIntrinsic.js b/node_modules/get-intrinsic/test/GetIntrinsic.js new file mode 100644 index 0000000..d9c0f30 --- /dev/null +++ b/node_modules/get-intrinsic/test/GetIntrinsic.js @@ -0,0 +1,274 @@ +'use strict'; + +var GetIntrinsic = require('../'); + +var test = require('tape'); +var forEach = require('for-each'); +var debug = require('object-inspect'); +var generatorFns = require('make-generator-function')(); +var asyncFns = require('make-async-function').list(); +var asyncGenFns = require('make-async-generator-function')(); +var mockProperty = require('mock-property'); + +var callBound = require('call-bound'); +var v = require('es-value-fixtures'); +var $gOPD = require('gopd'); +var DefinePropertyOrThrow = require('es-abstract/2023/DefinePropertyOrThrow'); + +var $isProto = callBound('%Object.prototype.isPrototypeOf%'); + +test('export', function (t) { + t.equal(typeof GetIntrinsic, 'function', 'it is a function'); + t.equal(GetIntrinsic.length, 2, 'function has length of 2'); + + t.end(); +}); + +test('throws', function (t) { + t['throws']( + function () { GetIntrinsic('not an intrinsic'); }, + SyntaxError, + 'nonexistent intrinsic throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic(''); }, + TypeError, + 'empty string intrinsic throws a type error' + ); + + t['throws']( + function () { GetIntrinsic('.'); }, + SyntaxError, + '"just a dot" intrinsic throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic('%String'); }, + SyntaxError, + 'Leading % without trailing % throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic('String%'); }, + SyntaxError, + 'Trailing % without leading % throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic("String['prototype]"); }, + SyntaxError, + 'Dynamic property access is disallowed for intrinsics (unterminated string)' + ); + + t['throws']( + function () { GetIntrinsic('%Proxy.prototype.undefined%'); }, + TypeError, + "Throws when middle part doesn't exist (%Proxy.prototype.undefined%)" + ); + + t['throws']( + function () { GetIntrinsic('%Array.prototype%garbage%'); }, + SyntaxError, + 'Throws with extra percent signs' + ); + + t['throws']( + function () { GetIntrinsic('%Array.prototype%push%'); }, + SyntaxError, + 'Throws with extra percent signs, even on an existing intrinsic' + ); + + forEach(v.nonStrings, function (nonString) { + t['throws']( + function () { GetIntrinsic(nonString); }, + TypeError, + debug(nonString) + ' is not a String' + ); + }); + + forEach(v.nonBooleans, function (nonBoolean) { + t['throws']( + function () { GetIntrinsic('%', nonBoolean); }, + TypeError, + debug(nonBoolean) + ' is not a Boolean' + ); + }); + + forEach([ + 'toString', + 'propertyIsEnumerable', + 'hasOwnProperty' + ], function (objectProtoMember) { + t['throws']( + function () { GetIntrinsic(objectProtoMember); }, + SyntaxError, + debug(objectProtoMember) + ' is not an intrinsic' + ); + }); + + t.end(); +}); + +test('base intrinsics', function (t) { + t.equal(GetIntrinsic('%Object%'), Object, '%Object% yields Object'); + t.equal(GetIntrinsic('Object'), Object, 'Object yields Object'); + t.equal(GetIntrinsic('%Array%'), Array, '%Array% yields Array'); + t.equal(GetIntrinsic('Array'), Array, 'Array yields Array'); + + t.end(); +}); + +test('dotted paths', function (t) { + t.equal(GetIntrinsic('%Object.prototype.toString%'), Object.prototype.toString, '%Object.prototype.toString% yields Object.prototype.toString'); + t.equal(GetIntrinsic('Object.prototype.toString'), Object.prototype.toString, 'Object.prototype.toString yields Object.prototype.toString'); + t.equal(GetIntrinsic('%Array.prototype.push%'), Array.prototype.push, '%Array.prototype.push% yields Array.prototype.push'); + t.equal(GetIntrinsic('Array.prototype.push'), Array.prototype.push, 'Array.prototype.push yields Array.prototype.push'); + + test('underscore paths are aliases for dotted paths', { skip: !Object.isFrozen || Object.isFrozen(Object.prototype) }, function (st) { + var original = GetIntrinsic('%ObjProto_toString%'); + + forEach([ + '%Object.prototype.toString%', + 'Object.prototype.toString', + '%ObjectPrototype.toString%', + 'ObjectPrototype.toString', + '%ObjProto_toString%', + 'ObjProto_toString' + ], function (name) { + DefinePropertyOrThrow(Object.prototype, 'toString', { + '[[Value]]': function toString() { + return original.apply(this, arguments); + } + }); + st.equal(GetIntrinsic(name), original, name + ' yields original Object.prototype.toString'); + }); + + DefinePropertyOrThrow(Object.prototype, 'toString', { '[[Value]]': original }); + st.end(); + }); + + test('dotted paths cache', { skip: !Object.isFrozen || Object.isFrozen(Object.prototype) }, function (st) { + var original = GetIntrinsic('%Object.prototype.propertyIsEnumerable%'); + + forEach([ + '%Object.prototype.propertyIsEnumerable%', + 'Object.prototype.propertyIsEnumerable', + '%ObjectPrototype.propertyIsEnumerable%', + 'ObjectPrototype.propertyIsEnumerable' + ], function (name) { + var restore = mockProperty(Object.prototype, 'propertyIsEnumerable', { + value: function propertyIsEnumerable() { + return original.apply(this, arguments); + } + }); + st.equal(GetIntrinsic(name), original, name + ' yields cached Object.prototype.propertyIsEnumerable'); + + restore(); + }); + + st.end(); + }); + + test('dotted path reports correct error', function (st) { + st['throws'](function () { + GetIntrinsic('%NonExistentIntrinsic.prototype.property%'); + }, /%NonExistentIntrinsic%/, 'The base intrinsic of %NonExistentIntrinsic.prototype.property% is %NonExistentIntrinsic%'); + + st['throws'](function () { + GetIntrinsic('%NonExistentIntrinsicPrototype.property%'); + }, /%NonExistentIntrinsicPrototype%/, 'The base intrinsic of %NonExistentIntrinsicPrototype.property% is %NonExistentIntrinsicPrototype%'); + + st.end(); + }); + + t.end(); +}); + +test('accessors', { skip: !$gOPD || typeof Map !== 'function' }, function (t) { + var actual = $gOPD(Map.prototype, 'size'); + t.ok(actual, 'Map.prototype.size has a descriptor'); + t.equal(typeof actual.get, 'function', 'Map.prototype.size has a getter function'); + t.equal(GetIntrinsic('%Map.prototype.size%'), actual.get, '%Map.prototype.size% yields the getter for it'); + t.equal(GetIntrinsic('Map.prototype.size'), actual.get, 'Map.prototype.size yields the getter for it'); + + t.end(); +}); + +test('generator functions', { skip: !generatorFns.length }, function (t) { + var $GeneratorFunction = GetIntrinsic('%GeneratorFunction%'); + var $GeneratorFunctionPrototype = GetIntrinsic('%Generator%'); + var $GeneratorPrototype = GetIntrinsic('%GeneratorPrototype%'); + + forEach(generatorFns, function (genFn) { + var fnName = genFn.name; + fnName = fnName ? "'" + fnName + "'" : 'genFn'; + + t.ok(genFn instanceof $GeneratorFunction, fnName + ' instanceof %GeneratorFunction%'); + t.ok($isProto($GeneratorFunctionPrototype, genFn), '%Generator% is prototype of ' + fnName); + t.ok($isProto($GeneratorPrototype, genFn.prototype), '%GeneratorPrototype% is prototype of ' + fnName + '.prototype'); + }); + + t.end(); +}); + +test('async functions', { skip: !asyncFns.length }, function (t) { + var $AsyncFunction = GetIntrinsic('%AsyncFunction%'); + var $AsyncFunctionPrototype = GetIntrinsic('%AsyncFunctionPrototype%'); + + forEach(asyncFns, function (asyncFn) { + var fnName = asyncFn.name; + fnName = fnName ? "'" + fnName + "'" : 'asyncFn'; + + t.ok(asyncFn instanceof $AsyncFunction, fnName + ' instanceof %AsyncFunction%'); + t.ok($isProto($AsyncFunctionPrototype, asyncFn), '%AsyncFunctionPrototype% is prototype of ' + fnName); + }); + + t.end(); +}); + +test('async generator functions', { skip: asyncGenFns.length === 0 }, function (t) { + var $AsyncGeneratorFunction = GetIntrinsic('%AsyncGeneratorFunction%'); + var $AsyncGeneratorFunctionPrototype = GetIntrinsic('%AsyncGenerator%'); + var $AsyncGeneratorPrototype = GetIntrinsic('%AsyncGeneratorPrototype%'); + + forEach(asyncGenFns, function (asyncGenFn) { + var fnName = asyncGenFn.name; + fnName = fnName ? "'" + fnName + "'" : 'asyncGenFn'; + + t.ok(asyncGenFn instanceof $AsyncGeneratorFunction, fnName + ' instanceof %AsyncGeneratorFunction%'); + t.ok($isProto($AsyncGeneratorFunctionPrototype, asyncGenFn), '%AsyncGenerator% is prototype of ' + fnName); + t.ok($isProto($AsyncGeneratorPrototype, asyncGenFn.prototype), '%AsyncGeneratorPrototype% is prototype of ' + fnName + '.prototype'); + }); + + t.end(); +}); + +test('%ThrowTypeError%', function (t) { + var $ThrowTypeError = GetIntrinsic('%ThrowTypeError%'); + + t.equal(typeof $ThrowTypeError, 'function', 'is a function'); + t['throws']( + $ThrowTypeError, + TypeError, + '%ThrowTypeError% throws a TypeError' + ); + + t.end(); +}); + +test('allowMissing', { skip: asyncGenFns.length > 0 }, function (t) { + t['throws']( + function () { GetIntrinsic('%AsyncGeneratorPrototype%'); }, + TypeError, + 'throws when missing' + ); + + t.equal( + GetIntrinsic('%AsyncGeneratorPrototype%', true), + undefined, + 'does not throw when allowMissing' + ); + + t.end(); +}); diff --git a/node_modules/get-proto/.eslintrc b/node_modules/get-proto/.eslintrc new file mode 100644 index 0000000..1d21a8a --- /dev/null +++ b/node_modules/get-proto/.eslintrc @@ -0,0 +1,10 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": "off", + "sort-keys": "off", + }, +} diff --git a/node_modules/get-proto/.github/FUNDING.yml b/node_modules/get-proto/.github/FUNDING.yml new file mode 100644 index 0000000..93183ef --- /dev/null +++ b/node_modules/get-proto/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/get-proto +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/get-proto/.nycrc b/node_modules/get-proto/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/get-proto/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/get-proto/CHANGELOG.md b/node_modules/get-proto/CHANGELOG.md new file mode 100644 index 0000000..5860229 --- /dev/null +++ b/node_modules/get-proto/CHANGELOG.md @@ -0,0 +1,21 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.1](https://github.com/ljharb/get-proto/compare/v1.0.0...v1.0.1) - 2025-01-02 + +### Commits + +- [Fix] for the `Object.getPrototypeOf` window, throw for non-objects [`7fe6508`](https://github.com/ljharb/get-proto/commit/7fe6508b71419ebe1976bedb86001d1feaeaa49a) + +## v1.0.0 - 2025-01-01 + +### Commits + +- Initial implementation, tests, readme, types [`5c70775`](https://github.com/ljharb/get-proto/commit/5c707751e81c3deeb2cf980d185fc7fd43611415) +- Initial commit [`7c65c2a`](https://github.com/ljharb/get-proto/commit/7c65c2ad4e33d5dae2f219ebe1a046ae2256972c) +- npm init [`0b8cf82`](https://github.com/ljharb/get-proto/commit/0b8cf824c9634e4a34ef7dd2a2cdc5be6ac79518) +- Only apps should have lockfiles [`a6d1bff`](https://github.com/ljharb/get-proto/commit/a6d1bffc364f5828377cea7194558b2dbef7aea2) diff --git a/node_modules/get-proto/LICENSE b/node_modules/get-proto/LICENSE new file mode 100644 index 0000000..eeabd1c --- /dev/null +++ b/node_modules/get-proto/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/get-proto/Object.getPrototypeOf.d.ts b/node_modules/get-proto/Object.getPrototypeOf.d.ts new file mode 100644 index 0000000..028b3ff --- /dev/null +++ b/node_modules/get-proto/Object.getPrototypeOf.d.ts @@ -0,0 +1,5 @@ +declare function getProto(object: O): object | null; + +declare const x: typeof getProto | null; + +export = x; \ No newline at end of file diff --git a/node_modules/get-proto/Object.getPrototypeOf.js b/node_modules/get-proto/Object.getPrototypeOf.js new file mode 100644 index 0000000..c2cbbdf --- /dev/null +++ b/node_modules/get-proto/Object.getPrototypeOf.js @@ -0,0 +1,6 @@ +'use strict'; + +var $Object = require('es-object-atoms'); + +/** @type {import('./Object.getPrototypeOf')} */ +module.exports = $Object.getPrototypeOf || null; diff --git a/node_modules/get-proto/README.md b/node_modules/get-proto/README.md new file mode 100644 index 0000000..f8b4cce --- /dev/null +++ b/node_modules/get-proto/README.md @@ -0,0 +1,50 @@ +# get-proto [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Robustly get the [[Prototype]] of an object. Uses the best available method. + +## Getting started + +```sh +npm install --save get-proto +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const getProto = require('get-proto'); + +const a = { a: 1, b: 2, [Symbol.toStringTag]: 'foo' }; +const b = { c: 3, __proto__: a }; + +assert.equal(getProto(b), a); +assert.equal(getProto(a), Object.prototype); +assert.equal(getProto({ __proto__: null }), null); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/get-proto +[npm-version-svg]: https://versionbadg.es/ljharb/get-proto.svg +[deps-svg]: https://david-dm.org/ljharb/get-proto.svg +[deps-url]: https://david-dm.org/ljharb/get-proto +[dev-deps-svg]: https://david-dm.org/ljharb/get-proto/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/get-proto#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/get-proto.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/get-proto.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/get-proto.svg +[downloads-url]: https://npm-stat.com/charts.html?package=get-proto +[codecov-image]: https://codecov.io/gh/ljharb/get-proto/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/get-proto/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/get-proto +[actions-url]: https://github.com/ljharb/get-proto/actions diff --git a/node_modules/get-proto/Reflect.getPrototypeOf.d.ts b/node_modules/get-proto/Reflect.getPrototypeOf.d.ts new file mode 100644 index 0000000..2388fe0 --- /dev/null +++ b/node_modules/get-proto/Reflect.getPrototypeOf.d.ts @@ -0,0 +1,3 @@ +declare const x: typeof Reflect.getPrototypeOf | null; + +export = x; \ No newline at end of file diff --git a/node_modules/get-proto/Reflect.getPrototypeOf.js b/node_modules/get-proto/Reflect.getPrototypeOf.js new file mode 100644 index 0000000..e6c51be --- /dev/null +++ b/node_modules/get-proto/Reflect.getPrototypeOf.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./Reflect.getPrototypeOf')} */ +module.exports = (typeof Reflect !== 'undefined' && Reflect.getPrototypeOf) || null; diff --git a/node_modules/get-proto/index.d.ts b/node_modules/get-proto/index.d.ts new file mode 100644 index 0000000..2c021f3 --- /dev/null +++ b/node_modules/get-proto/index.d.ts @@ -0,0 +1,5 @@ +declare function getProto(object: O): object | null; + +declare const x: typeof getProto | null; + +export = x; diff --git a/node_modules/get-proto/index.js b/node_modules/get-proto/index.js new file mode 100644 index 0000000..7e5747b --- /dev/null +++ b/node_modules/get-proto/index.js @@ -0,0 +1,27 @@ +'use strict'; + +var reflectGetProto = require('./Reflect.getPrototypeOf'); +var originalGetProto = require('./Object.getPrototypeOf'); + +var getDunderProto = require('dunder-proto/get'); + +/** @type {import('.')} */ +module.exports = reflectGetProto + ? function getProto(O) { + // @ts-expect-error TS can't narrow inside a closure, for some reason + return reflectGetProto(O); + } + : originalGetProto + ? function getProto(O) { + if (!O || (typeof O !== 'object' && typeof O !== 'function')) { + throw new TypeError('getProto: not an object'); + } + // @ts-expect-error TS can't narrow inside a closure, for some reason + return originalGetProto(O); + } + : getDunderProto + ? function getProto(O) { + // @ts-expect-error TS can't narrow inside a closure, for some reason + return getDunderProto(O); + } + : null; diff --git a/node_modules/get-proto/package.json b/node_modules/get-proto/package.json new file mode 100644 index 0000000..9c35cec --- /dev/null +++ b/node_modules/get-proto/package.json @@ -0,0 +1,81 @@ +{ + "name": "get-proto", + "version": "1.0.1", + "description": "Robustly get the [[Prototype]] of an object", + "main": "index.js", + "exports": { + ".": "./index.js", + "./Reflect.getPrototypeOf": "./Reflect.getPrototypeOf.js", + "./Object.getPrototypeOf": "./Object.getPrototypeOf.js", + "./package.json": "./package.json" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "pretest": "npm run --silent lint", + "test": "npm run tests-only", + "posttest": "npx npm@\">=10.2\" audit --production", + "tests-only": "nyc tape 'test/**/*.js'", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc && attw -P", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/get-proto.git" + }, + "keywords": [ + "get", + "proto", + "prototype", + "getPrototypeOf", + "[[Prototype]]" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/get-proto/issues" + }, + "homepage": "https://github.com/ljharb/get-proto#readme", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.2", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.3", + "@types/tape": "^5.8.0", + "auto-changelog": "^2.5.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "testling": { + "files": "test/index.js" + } +} diff --git a/node_modules/get-proto/test/index.js b/node_modules/get-proto/test/index.js new file mode 100644 index 0000000..5a2ece2 --- /dev/null +++ b/node_modules/get-proto/test/index.js @@ -0,0 +1,68 @@ +'use strict'; + +var test = require('tape'); + +var getProto = require('../'); + +test('getProto', function (t) { + t.equal(typeof getProto, 'function', 'is a function'); + + t.test('can get', { skip: !getProto }, function (st) { + if (getProto) { // TS doesn't understand tape's skip + var proto = { b: 2 }; + st.equal(getProto(proto), Object.prototype, 'proto: returns the [[Prototype]]'); + + st.test('nullish value', function (s2t) { + // @ts-expect-error + s2t['throws'](function () { return getProto(undefined); }, TypeError, 'undefined is not an object'); + // @ts-expect-error + s2t['throws'](function () { return getProto(null); }, TypeError, 'null is not an object'); + s2t.end(); + }); + + // @ts-expect-error + st['throws'](function () { getProto(true); }, 'throws for true'); + // @ts-expect-error + st['throws'](function () { getProto(false); }, 'throws for false'); + // @ts-expect-error + st['throws'](function () { getProto(42); }, 'throws for 42'); + // @ts-expect-error + st['throws'](function () { getProto(NaN); }, 'throws for NaN'); + // @ts-expect-error + st['throws'](function () { getProto(0); }, 'throws for +0'); + // @ts-expect-error + st['throws'](function () { getProto(-0); }, 'throws for -0'); + // @ts-expect-error + st['throws'](function () { getProto(Infinity); }, 'throws for ∞'); + // @ts-expect-error + st['throws'](function () { getProto(-Infinity); }, 'throws for -∞'); + // @ts-expect-error + st['throws'](function () { getProto(''); }, 'throws for empty string'); + // @ts-expect-error + st['throws'](function () { getProto('foo'); }, 'throws for non-empty string'); + st.equal(getProto(/a/g), RegExp.prototype); + st.equal(getProto(new Date()), Date.prototype); + st.equal(getProto(function () {}), Function.prototype); + st.equal(getProto([]), Array.prototype); + st.equal(getProto({}), Object.prototype); + + var nullObject = { __proto__: null }; + if ('toString' in nullObject) { + st.comment('no null objects in this engine'); + st.equal(getProto(nullObject), Object.prototype, '"null" object has Object.prototype as [[Prototype]]'); + } else { + st.equal(getProto(nullObject), null, 'null object has null [[Prototype]]'); + } + } + + st.end(); + }); + + t.test('can not get', { skip: !!getProto }, function (st) { + st.equal(getProto, null); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/get-proto/tsconfig.json b/node_modules/get-proto/tsconfig.json new file mode 100644 index 0000000..60fb90e --- /dev/null +++ b/node_modules/get-proto/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + //"target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/gopd/.eslintrc b/node_modules/gopd/.eslintrc new file mode 100644 index 0000000..e2550c0 --- /dev/null +++ b/node_modules/gopd/.eslintrc @@ -0,0 +1,16 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-style": [2, "declaration"], + "id-length": 0, + "multiline-comment-style": 0, + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, +} diff --git a/node_modules/gopd/.github/FUNDING.yml b/node_modules/gopd/.github/FUNDING.yml new file mode 100644 index 0000000..94a44a8 --- /dev/null +++ b/node_modules/gopd/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/gopd +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/gopd/CHANGELOG.md b/node_modules/gopd/CHANGELOG.md new file mode 100644 index 0000000..87f5727 --- /dev/null +++ b/node_modules/gopd/CHANGELOG.md @@ -0,0 +1,45 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.2.0](https://github.com/ljharb/gopd/compare/v1.1.0...v1.2.0) - 2024-12-03 + +### Commits + +- [New] add `gOPD` entry point; remove `get-intrinsic` [`5b61232`](https://github.com/ljharb/gopd/commit/5b61232dedea4591a314bcf16101b1961cee024e) + +## [v1.1.0](https://github.com/ljharb/gopd/compare/v1.0.1...v1.1.0) - 2024-11-29 + +### Commits + +- [New] add types [`f585e39`](https://github.com/ljharb/gopd/commit/f585e397886d270e4ba84e53d226e4f9ca2eb0e6) +- [Dev Deps] update `@ljharb/eslint-config`, `auto-changelog`, `tape` [`0b8e4fd`](https://github.com/ljharb/gopd/commit/0b8e4fded64397a7726a9daa144a6cc9a5e2edfa) +- [Dev Deps] update `aud`, `npmignore`, `tape` [`48378b2`](https://github.com/ljharb/gopd/commit/48378b2443f09a4f7efbd0fb6c3ee845a6cabcf3) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`78099ee`](https://github.com/ljharb/gopd/commit/78099eeed41bfdc134c912280483689cc8861c31) +- [Tests] replace `aud` with `npm audit` [`4e0d0ac`](https://github.com/ljharb/gopd/commit/4e0d0ac47619d24a75318a8e1f543ee04b2a2632) +- [meta] add missing `engines.node` [`1443316`](https://github.com/ljharb/gopd/commit/14433165d07835c680155b3dfd62d9217d735eca) +- [Deps] update `get-intrinsic` [`eee5f51`](https://github.com/ljharb/gopd/commit/eee5f51769f3dbaf578b70e2a3199116b01aa670) +- [Deps] update `get-intrinsic` [`550c378`](https://github.com/ljharb/gopd/commit/550c3780e3a9c77b62565712a001b4ed64ea61f5) +- [Dev Deps] add missing peer dep [`8c2ecf8`](https://github.com/ljharb/gopd/commit/8c2ecf848122e4e30abfc5b5086fb48b390dce75) + +## [v1.0.1](https://github.com/ljharb/gopd/compare/v1.0.0...v1.0.1) - 2022-11-01 + +### Commits + +- [Fix] actually export gOPD instead of dP [`4b624bf`](https://github.com/ljharb/gopd/commit/4b624bfbeff788c5e3ff16d9443a83627847234f) + +## v1.0.0 - 2022-11-01 + +### Commits + +- Initial implementation, tests, readme [`0911e01`](https://github.com/ljharb/gopd/commit/0911e012cd642092bd88b732c161c58bf4f20bea) +- Initial commit [`b84e33f`](https://github.com/ljharb/gopd/commit/b84e33f5808a805ac57ff88d4247ad935569acbe) +- [actions] add reusable workflows [`12ae28a`](https://github.com/ljharb/gopd/commit/12ae28ae5f50f86e750215b6e2188901646d0119) +- npm init [`280118b`](https://github.com/ljharb/gopd/commit/280118badb45c80b4483836b5cb5315bddf6e582) +- [meta] add `auto-changelog` [`bb78de5`](https://github.com/ljharb/gopd/commit/bb78de5639a180747fb290c28912beaaf1615709) +- [meta] create FUNDING.yml; add `funding` in package.json [`11c22e6`](https://github.com/ljharb/gopd/commit/11c22e6355bb01f24e7fac4c9bb3055eb5b25002) +- [meta] use `npmignore` to autogenerate an npmignore file [`4f4537a`](https://github.com/ljharb/gopd/commit/4f4537a843b39f698c52f072845092e6fca345bb) +- Only apps should have lockfiles [`c567022`](https://github.com/ljharb/gopd/commit/c567022a18573aa7951cf5399445d9840e23e98b) diff --git a/node_modules/gopd/LICENSE b/node_modules/gopd/LICENSE new file mode 100644 index 0000000..6abfe14 --- /dev/null +++ b/node_modules/gopd/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/gopd/README.md b/node_modules/gopd/README.md new file mode 100644 index 0000000..784e56a --- /dev/null +++ b/node_modules/gopd/README.md @@ -0,0 +1,40 @@ +# gopd [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +`Object.getOwnPropertyDescriptor`, but accounts for IE's broken implementation. + +## Usage + +```javascript +var gOPD = require('gopd'); +var assert = require('assert'); + +if (gOPD) { + assert.equal(typeof gOPD, 'function', 'descriptors supported'); + // use gOPD like Object.getOwnPropertyDescriptor here +} else { + assert.ok(!gOPD, 'descriptors not supported'); +} +``` + +[package-url]: https://npmjs.org/package/gopd +[npm-version-svg]: https://versionbadg.es/ljharb/gopd.svg +[deps-svg]: https://david-dm.org/ljharb/gopd.svg +[deps-url]: https://david-dm.org/ljharb/gopd +[dev-deps-svg]: https://david-dm.org/ljharb/gopd/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/gopd#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/gopd.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/gopd.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/gopd.svg +[downloads-url]: https://npm-stat.com/charts.html?package=gopd +[codecov-image]: https://codecov.io/gh/ljharb/gopd/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/gopd/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/gopd +[actions-url]: https://github.com/ljharb/gopd/actions diff --git a/node_modules/gopd/gOPD.d.ts b/node_modules/gopd/gOPD.d.ts new file mode 100644 index 0000000..def48a3 --- /dev/null +++ b/node_modules/gopd/gOPD.d.ts @@ -0,0 +1 @@ +export = Object.getOwnPropertyDescriptor; diff --git a/node_modules/gopd/gOPD.js b/node_modules/gopd/gOPD.js new file mode 100644 index 0000000..cf9616c --- /dev/null +++ b/node_modules/gopd/gOPD.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./gOPD')} */ +module.exports = Object.getOwnPropertyDescriptor; diff --git a/node_modules/gopd/index.d.ts b/node_modules/gopd/index.d.ts new file mode 100644 index 0000000..e228065 --- /dev/null +++ b/node_modules/gopd/index.d.ts @@ -0,0 +1,5 @@ +declare function gOPD(obj: O, prop: K): PropertyDescriptor | undefined; + +declare const fn: typeof gOPD | undefined | null; + +export = fn; \ No newline at end of file diff --git a/node_modules/gopd/index.js b/node_modules/gopd/index.js new file mode 100644 index 0000000..a4081b0 --- /dev/null +++ b/node_modules/gopd/index.js @@ -0,0 +1,15 @@ +'use strict'; + +/** @type {import('.')} */ +var $gOPD = require('./gOPD'); + +if ($gOPD) { + try { + $gOPD([], 'length'); + } catch (e) { + // IE 8 has a broken gOPD + $gOPD = null; + } +} + +module.exports = $gOPD; diff --git a/node_modules/gopd/package.json b/node_modules/gopd/package.json new file mode 100644 index 0000000..01c5ffa --- /dev/null +++ b/node_modules/gopd/package.json @@ -0,0 +1,77 @@ +{ + "name": "gopd", + "version": "1.2.0", + "description": "`Object.getOwnPropertyDescriptor`, but accounts for IE's broken implementation.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./gOPD": "./gOPD.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "tsc -p . && attw -P", + "lint": "eslint --ext=js,mjs .", + "postlint": "evalmd README.md", + "pretest": "npm run lint", + "tests-only": "tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/gopd.git" + }, + "keywords": [ + "ecmascript", + "javascript", + "getownpropertydescriptor", + "property", + "descriptor" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/gopd/issues" + }, + "homepage": "https://github.com/ljharb/gopd#readme", + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.0", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.0", + "@types/tape": "^5.6.5", + "auto-changelog": "^2.5.0", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/gopd/test/index.js b/node_modules/gopd/test/index.js new file mode 100644 index 0000000..6f43453 --- /dev/null +++ b/node_modules/gopd/test/index.js @@ -0,0 +1,36 @@ +'use strict'; + +var test = require('tape'); +var gOPD = require('../'); + +test('gOPD', function (t) { + t.test('supported', { skip: !gOPD }, function (st) { + st.equal(typeof gOPD, 'function', 'is a function'); + + var obj = { x: 1 }; + st.ok('x' in obj, 'property exists'); + + // @ts-expect-error TS can't figure out narrowing from `skip` + var desc = gOPD(obj, 'x'); + st.deepEqual( + desc, + { + configurable: true, + enumerable: true, + value: 1, + writable: true + }, + 'descriptor is as expected' + ); + + st.end(); + }); + + t.test('not supported', { skip: !!gOPD }, function (st) { + st.notOk(gOPD, 'is falsy'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/gopd/tsconfig.json b/node_modules/gopd/tsconfig.json new file mode 100644 index 0000000..d9a6668 --- /dev/null +++ b/node_modules/gopd/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/has-symbols/.eslintrc b/node_modules/has-symbols/.eslintrc new file mode 100644 index 0000000..2d9a66a --- /dev/null +++ b/node_modules/has-symbols/.eslintrc @@ -0,0 +1,11 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-statements-per-line": [2, { "max": 2 }], + "no-magic-numbers": 0, + "multiline-comment-style": 0, + } +} diff --git a/node_modules/has-symbols/.github/FUNDING.yml b/node_modules/has-symbols/.github/FUNDING.yml new file mode 100644 index 0000000..04cf87e --- /dev/null +++ b/node_modules/has-symbols/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/has-symbols +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/has-symbols/.nycrc b/node_modules/has-symbols/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/has-symbols/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/has-symbols/CHANGELOG.md b/node_modules/has-symbols/CHANGELOG.md new file mode 100644 index 0000000..cc3cf83 --- /dev/null +++ b/node_modules/has-symbols/CHANGELOG.md @@ -0,0 +1,91 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.0](https://github.com/inspect-js/has-symbols/compare/v1.0.3...v1.1.0) - 2024-12-02 + +### Commits + +- [actions] update workflows [`548c0bf`](https://github.com/inspect-js/has-symbols/commit/548c0bf8c9b1235458df7a1c0490b0064647a282) +- [actions] further shard; update action deps [`bec56bb`](https://github.com/inspect-js/has-symbols/commit/bec56bb0fb44b43a786686b944875a3175cf3ff3) +- [meta] use `npmignore` to autogenerate an npmignore file [`ac81032`](https://github.com/inspect-js/has-symbols/commit/ac81032809157e0a079e5264e9ce9b6f1275777e) +- [New] add types [`6469cbf`](https://github.com/inspect-js/has-symbols/commit/6469cbff1866cfe367b2b3d181d9296ec14b2a3d) +- [actions] update rebase action to use reusable workflow [`9c9d4d0`](https://github.com/inspect-js/has-symbols/commit/9c9d4d0d8938e4b267acdf8e421f4e92d1716d72) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`adb5887`](https://github.com/inspect-js/has-symbols/commit/adb5887ca9444849b08beb5caaa9e1d42320cdfb) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`13ec198`](https://github.com/inspect-js/has-symbols/commit/13ec198ec80f1993a87710af1606a1970b22c7cb) +- [Dev Deps] update `auto-changelog`, `core-js`, `tape` [`941be52`](https://github.com/inspect-js/has-symbols/commit/941be5248387cab1da72509b22acf3fdb223f057) +- [Tests] replace `aud` with `npm audit` [`74f49e9`](https://github.com/inspect-js/has-symbols/commit/74f49e9a9d17a443020784234a1c53ce765b3559) +- [Dev Deps] update `npmignore` [`9c0ac04`](https://github.com/inspect-js/has-symbols/commit/9c0ac0452a834f4c2a4b54044f2d6a89f17e9a70) +- [Dev Deps] add missing peer dep [`52337a5`](https://github.com/inspect-js/has-symbols/commit/52337a5621cced61f846f2afdab7707a8132cc12) + +## [v1.0.3](https://github.com/inspect-js/has-symbols/compare/v1.0.2...v1.0.3) - 2022-03-01 + +### Commits + +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`518b28f`](https://github.com/inspect-js/has-symbols/commit/518b28f6c5a516cbccae30794e40aa9f738b1693) +- [meta] add `bugs` and `homepage` fields; reorder package.json [`c480b13`](https://github.com/inspect-js/has-symbols/commit/c480b13fd6802b557e1cef9749872cb5fdeef744) +- [actions] reuse common workflows [`01d0ee0`](https://github.com/inspect-js/has-symbols/commit/01d0ee0a8d97c0947f5edb73eb722027a77b2b07) +- [actions] update codecov uploader [`6424ebe`](https://github.com/inspect-js/has-symbols/commit/6424ebe86b2c9c7c3d2e9bd4413a4e4f168cb275) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`dfa7e7f`](https://github.com/inspect-js/has-symbols/commit/dfa7e7ff38b594645d8c8222aab895157fa7e282) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`0c8d436`](https://github.com/inspect-js/has-symbols/commit/0c8d43685c45189cea9018191d4fd7eca91c9d02) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`9026554`](https://github.com/inspect-js/has-symbols/commit/902655442a1bf88e72b42345494ef0c60f5d36ab) +- [readme] add actions and codecov badges [`eaa9682`](https://github.com/inspect-js/has-symbols/commit/eaa9682f990f481d3acf7a1c7600bec36f7b3adc) +- [Dev Deps] update `eslint`, `tape` [`bc7a3ba`](https://github.com/inspect-js/has-symbols/commit/bc7a3ba46f27b7743f8a2579732d59d1b9ac791e) +- [Dev Deps] update `eslint`, `auto-changelog` [`0ace00a`](https://github.com/inspect-js/has-symbols/commit/0ace00af08a88cdd1e6ce0d60357d941c60c2d9f) +- [meta] use `prepublishOnly` script for npm 7+ [`093f72b`](https://github.com/inspect-js/has-symbols/commit/093f72bc2b0ed00c781f444922a5034257bf561d) +- [Tests] test on all 16 minors [`9b80d3d`](https://github.com/inspect-js/has-symbols/commit/9b80d3d9102529f04c20ec5b1fcc6e38426c6b03) + +## [v1.0.2](https://github.com/inspect-js/has-symbols/compare/v1.0.1...v1.0.2) - 2021-02-27 + +### Fixed + +- [Fix] use a universal way to get the original Symbol [`#11`](https://github.com/inspect-js/has-symbols/issues/11) + +### Commits + +- [Tests] migrate tests to Github Actions [`90ae798`](https://github.com/inspect-js/has-symbols/commit/90ae79820bdfe7bc703d67f5f3c5e205f98556d3) +- [meta] do not publish github action workflow files [`29e60a1`](https://github.com/inspect-js/has-symbols/commit/29e60a1b7c25c7f1acf7acff4a9320d0d10c49b4) +- [Tests] run `nyc` on all tests [`8476b91`](https://github.com/inspect-js/has-symbols/commit/8476b915650d360915abe2522505abf4b0e8f0ae) +- [readme] fix repo URLs, remove defunct badges [`126288e`](https://github.com/inspect-js/has-symbols/commit/126288ecc1797c0a40247a6b78bcb2e0bc5d7036) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `core-js`, `get-own-property-symbols` [`d84bdfa`](https://github.com/inspect-js/has-symbols/commit/d84bdfa48ac5188abbb4904b42614cd6c030940a) +- [Tests] fix linting errors [`0df3070`](https://github.com/inspect-js/has-symbols/commit/0df3070b981b6c9f2ee530c09189a7f5c6def839) +- [actions] add "Allow Edits" workflow [`1e6bc29`](https://github.com/inspect-js/has-symbols/commit/1e6bc29b188f32b9648657b07eda08504be5aa9c) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`36cea2a`](https://github.com/inspect-js/has-symbols/commit/36cea2addd4e6ec435f35a2656b4e9ef82498e9b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`1278338`](https://github.com/inspect-js/has-symbols/commit/127833801865fbc2cc8979beb9ca869c7bfe8222) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`1493254`](https://github.com/inspect-js/has-symbols/commit/1493254eda13db5fb8fc5e4a3e8324b3d196029d) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js` [`b090bf2`](https://github.com/inspect-js/has-symbols/commit/b090bf214d3679a30edc1e2d729d466ab5183e1d) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`4addb7a`](https://github.com/inspect-js/has-symbols/commit/4addb7ab4dc73f927ae99928d68817554fc21dc0) +- [Dev Deps] update `auto-changelog`, `tape` [`81d0baf`](https://github.com/inspect-js/has-symbols/commit/81d0baf3816096a89a8558e8043895f7a7d10d8b) +- [Dev Deps] update `auto-changelog`; add `aud` [`1a4e561`](https://github.com/inspect-js/has-symbols/commit/1a4e5612c25d91c3a03d509721d02630bc4fe3da) +- [readme] remove unused testling URLs [`3000941`](https://github.com/inspect-js/has-symbols/commit/3000941f958046e923ed8152edb1ef4a599e6fcc) +- [Tests] only audit prod deps [`692e974`](https://github.com/inspect-js/has-symbols/commit/692e9743c912410e9440207631a643a34b4741a1) +- [Dev Deps] update `@ljharb/eslint-config` [`51c946c`](https://github.com/inspect-js/has-symbols/commit/51c946c7f6baa793ec5390bb5a45cdce16b4ba76) + +## [v1.0.1](https://github.com/inspect-js/has-symbols/compare/v1.0.0...v1.0.1) - 2019-11-16 + +### Commits + +- [Tests] use shared travis-ci configs [`ce396c9`](https://github.com/inspect-js/has-symbols/commit/ce396c9419ff11c43d0da5d05cdbb79f7fb42229) +- [Tests] up to `node` `v12.4`, `v11.15`, `v10.15`, `v9.11`, `v8.15`, `v7.10`, `v6.17`, `v4.9`; use `nvm install-latest-npm` [`0690732`](https://github.com/inspect-js/has-symbols/commit/0690732801f47ab429f39ba1962f522d5c462d6b) +- [meta] add `auto-changelog` [`2163d0b`](https://github.com/inspect-js/has-symbols/commit/2163d0b7f36343076b8f947cd1667dd1750f26fc) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `safe-publish-latest`, `tape` [`8e0951f`](https://github.com/inspect-js/has-symbols/commit/8e0951f1a7a2e52068222b7bb73511761e6e4d9c) +- [actions] add automatic rebasing / merge commit blocking [`b09cdb7`](https://github.com/inspect-js/has-symbols/commit/b09cdb7cd7ee39e7a769878f56e2d6066f5ccd1d) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `core-js`, `get-own-property-symbols`, `tape` [`1dd42cd`](https://github.com/inspect-js/has-symbols/commit/1dd42cd86183ed0c50f99b1062345c458babca91) +- [meta] create FUNDING.yml [`aa57a17`](https://github.com/inspect-js/has-symbols/commit/aa57a17b19708906d1927f821ea8e73394d84ca4) +- Only apps should have lockfiles [`a2d8bea`](https://github.com/inspect-js/has-symbols/commit/a2d8bea23a97d15c09eaf60f5b107fcf9a4d57aa) +- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`9e96cb7`](https://github.com/inspect-js/has-symbols/commit/9e96cb783746cbed0c10ef78e599a8eaa7ebe193) +- [meta] add `funding` field [`a0b32cf`](https://github.com/inspect-js/has-symbols/commit/a0b32cf68e803f963c1639b6d47b0a9d6440bab0) +- [Dev Deps] update `safe-publish-latest` [`cb9f0a5`](https://github.com/inspect-js/has-symbols/commit/cb9f0a521a3a1790f1064d437edd33bb6c3d6af0) + +## v1.0.0 - 2016-09-19 + +### Commits + +- Tests. [`ecb6eb9`](https://github.com/inspect-js/has-symbols/commit/ecb6eb934e4883137f3f93b965ba5e0a98df430d) +- package.json [`88a337c`](https://github.com/inspect-js/has-symbols/commit/88a337cee0864a0da35f5d19e69ff0ef0150e46a) +- Initial commit [`42e1e55`](https://github.com/inspect-js/has-symbols/commit/42e1e5502536a2b8ac529c9443984acd14836b1c) +- Initial implementation. [`33f5cc6`](https://github.com/inspect-js/has-symbols/commit/33f5cc6cdff86e2194b081ee842bfdc63caf43fb) +- read me [`01f1170`](https://github.com/inspect-js/has-symbols/commit/01f1170188ff7cb1558aa297f6ba5b516c6d7b0c) diff --git a/node_modules/has-symbols/LICENSE b/node_modules/has-symbols/LICENSE new file mode 100644 index 0000000..df31cbf --- /dev/null +++ b/node_modules/has-symbols/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/has-symbols/README.md b/node_modules/has-symbols/README.md new file mode 100644 index 0000000..33905f0 --- /dev/null +++ b/node_modules/has-symbols/README.md @@ -0,0 +1,46 @@ +# has-symbols [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Determine if the JS environment has Symbol support. Supports spec, or shams. + +## Example + +```js +var hasSymbols = require('has-symbols'); + +hasSymbols() === true; // if the environment has native Symbol support. Not polyfillable, not forgeable. + +var hasSymbolsKinda = require('has-symbols/shams'); +hasSymbolsKinda() === true; // if the environment has a Symbol sham that mostly follows the spec. +``` + +## Supported Symbol shams + - get-own-property-symbols [npm](https://www.npmjs.com/package/get-own-property-symbols) | [github](https://github.com/WebReflection/get-own-property-symbols) + - core-js [npm](https://www.npmjs.com/package/core-js) | [github](https://github.com/zloirock/core-js) + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/has-symbols +[2]: https://versionbadg.es/inspect-js/has-symbols.svg +[5]: https://david-dm.org/inspect-js/has-symbols.svg +[6]: https://david-dm.org/inspect-js/has-symbols +[7]: https://david-dm.org/inspect-js/has-symbols/dev-status.svg +[8]: https://david-dm.org/inspect-js/has-symbols#info=devDependencies +[11]: https://nodei.co/npm/has-symbols.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/has-symbols.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/has-symbols.svg +[downloads-url]: https://npm-stat.com/charts.html?package=has-symbols +[codecov-image]: https://codecov.io/gh/inspect-js/has-symbols/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/has-symbols/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/has-symbols +[actions-url]: https://github.com/inspect-js/has-symbols/actions diff --git a/node_modules/has-symbols/index.d.ts b/node_modules/has-symbols/index.d.ts new file mode 100644 index 0000000..9b98595 --- /dev/null +++ b/node_modules/has-symbols/index.d.ts @@ -0,0 +1,3 @@ +declare function hasNativeSymbols(): boolean; + +export = hasNativeSymbols; \ No newline at end of file diff --git a/node_modules/has-symbols/index.js b/node_modules/has-symbols/index.js new file mode 100644 index 0000000..fa65265 --- /dev/null +++ b/node_modules/has-symbols/index.js @@ -0,0 +1,14 @@ +'use strict'; + +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = require('./shams'); + +/** @type {import('.')} */ +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); +}; diff --git a/node_modules/has-symbols/package.json b/node_modules/has-symbols/package.json new file mode 100644 index 0000000..d835e20 --- /dev/null +++ b/node_modules/has-symbols/package.json @@ -0,0 +1,111 @@ +{ + "name": "has-symbols", + "version": "1.1.0", + "description": "Determine if the JS environment has Symbol support. Supports spec, or shams.", + "main": "index.js", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run --silent lint", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "tests-only": "npm run test:stock && npm run test:shams", + "test:stock": "nyc node test", + "test:staging": "nyc node --harmony --es-staging test", + "test:shams": "npm run --silent test:shams:getownpropertysymbols && npm run --silent test:shams:corejs", + "test:shams:corejs": "nyc node test/shams/core-js.js", + "test:shams:getownpropertysymbols": "nyc node test/shams/get-own-property-symbols.js", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && attw -P", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/has-symbols.git" + }, + "keywords": [ + "Symbol", + "symbols", + "typeof", + "sham", + "polyfill", + "native", + "core-js", + "ES6" + ], + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/has-symbols/issues" + }, + "homepage": "https://github.com/ljharb/has-symbols#readme", + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.0", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.0", + "@types/core-js": "^2.5.8", + "@types/tape": "^5.6.5", + "auto-changelog": "^2.5.0", + "core-js": "^2.6.12", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "get-own-property-symbols": "^0.9.5", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "types" + ] + } +} diff --git a/node_modules/has-symbols/shams.d.ts b/node_modules/has-symbols/shams.d.ts new file mode 100644 index 0000000..8d0bf24 --- /dev/null +++ b/node_modules/has-symbols/shams.d.ts @@ -0,0 +1,3 @@ +declare function hasSymbolShams(): boolean; + +export = hasSymbolShams; \ No newline at end of file diff --git a/node_modules/has-symbols/shams.js b/node_modules/has-symbols/shams.js new file mode 100644 index 0000000..f97b474 --- /dev/null +++ b/node_modules/has-symbols/shams.js @@ -0,0 +1,45 @@ +'use strict'; + +/** @type {import('./shams')} */ +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + /** @type {{ [k in symbol]?: unknown }} */ + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (var _ in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + // eslint-disable-next-line no-extra-parens + var descriptor = /** @type {PropertyDescriptor} */ (Object.getOwnPropertyDescriptor(obj, sym)); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; diff --git a/node_modules/has-symbols/test/index.js b/node_modules/has-symbols/test/index.js new file mode 100644 index 0000000..352129c --- /dev/null +++ b/node_modules/has-symbols/test/index.js @@ -0,0 +1,22 @@ +'use strict'; + +var test = require('tape'); +var hasSymbols = require('../'); +var runSymbolTests = require('./tests'); + +test('interface', function (t) { + t.equal(typeof hasSymbols, 'function', 'is a function'); + t.equal(typeof hasSymbols(), 'boolean', 'returns a boolean'); + t.end(); +}); + +test('Symbols are supported', { skip: !hasSymbols() }, function (t) { + runSymbolTests(t); + t.end(); +}); + +test('Symbols are not supported', { skip: hasSymbols() }, function (t) { + t.equal(typeof Symbol, 'undefined', 'global Symbol is undefined'); + t.equal(typeof Object.getOwnPropertySymbols, 'undefined', 'Object.getOwnPropertySymbols does not exist'); + t.end(); +}); diff --git a/node_modules/has-symbols/test/shams/core-js.js b/node_modules/has-symbols/test/shams/core-js.js new file mode 100644 index 0000000..1a29024 --- /dev/null +++ b/node_modules/has-symbols/test/shams/core-js.js @@ -0,0 +1,29 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { + test('has native Symbol support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol(), 'symbol'); + t.end(); + }); + // @ts-expect-error TS is stupid and doesn't know about top level return + return; +} + +var hasSymbols = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbols(), false, 'hasSymbols is false before polyfilling'); + require('core-js/fn/symbol'); + require('core-js/fn/symbol/to-string-tag'); + + require('../tests')(t); + + var hasSymbolsAfter = hasSymbols(); + t.equal(hasSymbolsAfter, true, 'hasSymbols is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/node_modules/has-symbols/test/shams/get-own-property-symbols.js b/node_modules/has-symbols/test/shams/get-own-property-symbols.js new file mode 100644 index 0000000..e0296f8 --- /dev/null +++ b/node_modules/has-symbols/test/shams/get-own-property-symbols.js @@ -0,0 +1,29 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { + test('has native Symbol support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol(), 'symbol'); + t.end(); + }); + // @ts-expect-error TS is stupid and doesn't know about top level return + return; +} + +var hasSymbols = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbols(), false, 'hasSymbols is false before polyfilling'); + + require('get-own-property-symbols'); + + require('../tests')(t); + + var hasSymbolsAfter = hasSymbols(); + t.equal(hasSymbolsAfter, true, 'hasSymbols is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/node_modules/has-symbols/test/tests.js b/node_modules/has-symbols/test/tests.js new file mode 100644 index 0000000..66a2cb8 --- /dev/null +++ b/node_modules/has-symbols/test/tests.js @@ -0,0 +1,58 @@ +'use strict'; + +/** @type {(t: import('tape').Test) => false | void} */ +// eslint-disable-next-line consistent-return +module.exports = function runSymbolTests(t) { + t.equal(typeof Symbol, 'function', 'global Symbol is a function'); + + if (typeof Symbol !== 'function') { return false; } + + t.notEqual(Symbol(), Symbol(), 'two symbols are not equal'); + + /* + t.equal( + Symbol.prototype.toString.call(Symbol('foo')), + Symbol.prototype.toString.call(Symbol('foo')), + 'two symbols with the same description stringify the same' + ); + */ + + /* + var foo = Symbol('foo'); + + t.notEqual( + String(foo), + String(Symbol('bar')), + 'two symbols with different descriptions do not stringify the same' + ); + */ + + t.equal(typeof Symbol.prototype.toString, 'function', 'Symbol#toString is a function'); + // t.equal(String(foo), Symbol.prototype.toString.call(foo), 'Symbol#toString equals String of the same symbol'); + + t.equal(typeof Object.getOwnPropertySymbols, 'function', 'Object.getOwnPropertySymbols is a function'); + + /** @type {{ [k in symbol]?: unknown }} */ + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + t.notEqual(typeof sym, 'string', 'Symbol is not a string'); + t.equal(Object.prototype.toString.call(sym), '[object Symbol]', 'symbol primitive Object#toStrings properly'); + t.equal(Object.prototype.toString.call(symObj), '[object Symbol]', 'symbol primitive Object#toStrings properly'); + + var symVal = 42; + obj[sym] = symVal; + // eslint-disable-next-line no-restricted-syntax, no-unused-vars + for (var _ in obj) { t.fail('symbol property key was found in for..in of object'); } + + t.deepEqual(Object.keys(obj), [], 'no enumerable own keys on symbol-valued object'); + t.deepEqual(Object.getOwnPropertyNames(obj), [], 'no own names on symbol-valued object'); + t.deepEqual(Object.getOwnPropertySymbols(obj), [sym], 'one own symbol on symbol-valued object'); + t.equal(Object.prototype.propertyIsEnumerable.call(obj, sym), true, 'symbol is enumerable'); + t.deepEqual(Object.getOwnPropertyDescriptor(obj, sym), { + configurable: true, + enumerable: true, + value: 42, + writable: true + }, 'property descriptor is correct'); +}; diff --git a/node_modules/has-symbols/tsconfig.json b/node_modules/has-symbols/tsconfig.json new file mode 100644 index 0000000..ba99af4 --- /dev/null +++ b/node_modules/has-symbols/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "ES2021", + "maxNodeModuleJsDepth": 0, + }, + "exclude": [ + "coverage" + ] +} diff --git a/node_modules/hasown/.eslintrc b/node_modules/hasown/.eslintrc new file mode 100644 index 0000000..3b5d9e9 --- /dev/null +++ b/node_modules/hasown/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/node_modules/hasown/.github/FUNDING.yml b/node_modules/hasown/.github/FUNDING.yml new file mode 100644 index 0000000..d68c8b7 --- /dev/null +++ b/node_modules/hasown/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/hasown +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/hasown/.nycrc b/node_modules/hasown/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/node_modules/hasown/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/hasown/CHANGELOG.md b/node_modules/hasown/CHANGELOG.md new file mode 100644 index 0000000..2b0a980 --- /dev/null +++ b/node_modules/hasown/CHANGELOG.md @@ -0,0 +1,40 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v2.0.2](https://github.com/inspect-js/hasOwn/compare/v2.0.1...v2.0.2) - 2024-03-10 + +### Commits + +- [types] use shared config [`68e9d4d`](https://github.com/inspect-js/hasOwn/commit/68e9d4dab6facb4f05f02c6baea94a3f2a4e44b2) +- [actions] remove redundant finisher; use reusable workflow [`241a68e`](https://github.com/inspect-js/hasOwn/commit/241a68e13ea1fe52bec5ba7f74144befc31fae7b) +- [Tests] increase coverage [`4125c0d`](https://github.com/inspect-js/hasOwn/commit/4125c0d6121db56ae30e38346dfb0c000b04f0a7) +- [Tests] skip `npm ls` in old node due to TS [`01b9282`](https://github.com/inspect-js/hasOwn/commit/01b92822f9971dea031eafdd14767df41d61c202) +- [types] improve predicate type [`d340f85`](https://github.com/inspect-js/hasOwn/commit/d340f85ce02e286ef61096cbbb6697081d40a12b) +- [Dev Deps] update `tape` [`70089fc`](https://github.com/inspect-js/hasOwn/commit/70089fcf544e64acc024cbe60f5a9b00acad86de) +- [Tests] use `@arethetypeswrong/cli` [`50b272c`](https://github.com/inspect-js/hasOwn/commit/50b272c829f40d053a3dd91c9796e0ac0b2af084) + +## [v2.0.1](https://github.com/inspect-js/hasOwn/compare/v2.0.0...v2.0.1) - 2024-02-10 + +### Commits + +- [types] use a handwritten d.ts file; fix exported type [`012b989`](https://github.com/inspect-js/hasOwn/commit/012b9898ccf91dc441e2ebf594ff70270a5fda58) +- [Dev Deps] update `@types/function-bind`, `@types/mock-property`, `@types/tape`, `aud`, `mock-property`, `npmignore`, `tape`, `typescript` [`977a56f`](https://github.com/inspect-js/hasOwn/commit/977a56f51a1f8b20566f3c471612137894644025) +- [meta] add `sideEffects` flag [`3a60b7b`](https://github.com/inspect-js/hasOwn/commit/3a60b7bf42fccd8c605e5f145a6fcc83b13cb46f) + +## [v2.0.0](https://github.com/inspect-js/hasOwn/compare/v1.0.1...v2.0.0) - 2023-10-19 + +### Commits + +- revamped implementation, tests, readme [`72bf8b3`](https://github.com/inspect-js/hasOwn/commit/72bf8b338e77a638f0a290c63ffaed18339c36b4) +- [meta] revamp package.json [`079775f`](https://github.com/inspect-js/hasOwn/commit/079775fb1ec72c1c6334069593617a0be3847458) +- Only apps should have lockfiles [`6640e23`](https://github.com/inspect-js/hasOwn/commit/6640e233d1bb8b65260880f90787637db157d215) + +## v1.0.1 - 2023-10-10 + +### Commits + +- Initial commit [`8dbfde6`](https://github.com/inspect-js/hasOwn/commit/8dbfde6e8fb0ebb076fab38d138f2984eb340a62) diff --git a/node_modules/hasown/LICENSE b/node_modules/hasown/LICENSE new file mode 100644 index 0000000..0314929 --- /dev/null +++ b/node_modules/hasown/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Jordan Harband and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/hasown/README.md b/node_modules/hasown/README.md new file mode 100644 index 0000000..f759b8a --- /dev/null +++ b/node_modules/hasown/README.md @@ -0,0 +1,40 @@ +# hasown [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +A robust, ES3 compatible, "has own property" predicate. + +## Example + +```js +const assert = require('assert'); +const hasOwn = require('hasown'); + +assert.equal(hasOwn({}, 'toString'), false); +assert.equal(hasOwn([], 'length'), true); +assert.equal(hasOwn({ a: 42 }, 'a'), true); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/hasown +[npm-version-svg]: https://versionbadg.es/inspect-js/hasown.svg +[deps-svg]: https://david-dm.org/inspect-js/hasOwn.svg +[deps-url]: https://david-dm.org/inspect-js/hasOwn +[dev-deps-svg]: https://david-dm.org/inspect-js/hasOwn/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/hasOwn#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/hasown.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/hasown.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/hasown.svg +[downloads-url]: https://npm-stat.com/charts.html?package=hasown +[codecov-image]: https://codecov.io/gh/inspect-js/hasOwn/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/hasOwn/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/hasOwn +[actions-url]: https://github.com/inspect-js/hasOwn/actions diff --git a/node_modules/hasown/index.d.ts b/node_modules/hasown/index.d.ts new file mode 100644 index 0000000..aafdf3b --- /dev/null +++ b/node_modules/hasown/index.d.ts @@ -0,0 +1,3 @@ +declare function hasOwn(o: O, p: K): o is O & Record; + +export = hasOwn; diff --git a/node_modules/hasown/index.js b/node_modules/hasown/index.js new file mode 100644 index 0000000..34e6059 --- /dev/null +++ b/node_modules/hasown/index.js @@ -0,0 +1,8 @@ +'use strict'; + +var call = Function.prototype.call; +var $hasOwn = Object.prototype.hasOwnProperty; +var bind = require('function-bind'); + +/** @type {import('.')} */ +module.exports = bind.call(call, $hasOwn); diff --git a/node_modules/hasown/package.json b/node_modules/hasown/package.json new file mode 100644 index 0000000..8502e13 --- /dev/null +++ b/node_modules/hasown/package.json @@ -0,0 +1,92 @@ +{ + "name": "hasown", + "version": "2.0.2", + "description": "A robust, ES3 compatible, \"has own property\" predicate.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "types": "index.d.ts", + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "npm run tsc", + "pretest": "npm run lint", + "tsc": "tsc -p .", + "posttsc": "attw -P", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/hasOwn.git" + }, + "keywords": [ + "has", + "hasOwnProperty", + "hasOwn", + "has-own", + "own", + "has", + "property", + "in", + "javascript", + "ecmascript" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/hasOwn/issues" + }, + "homepage": "https://github.com/inspect-js/hasOwn#readme", + "dependencies": { + "function-bind": "^1.1.2" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.15.1", + "@ljharb/eslint-config": "^21.1.0", + "@ljharb/tsconfig": "^0.2.0", + "@types/function-bind": "^1.1.10", + "@types/mock-property": "^1.0.2", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "mock-property": "^1.0.3", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.5", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "test" + ] + } +} diff --git a/node_modules/hasown/tsconfig.json b/node_modules/hasown/tsconfig.json new file mode 100644 index 0000000..0930c56 --- /dev/null +++ b/node_modules/hasown/tsconfig.json @@ -0,0 +1,6 @@ +{ + "extends": "@ljharb/tsconfig", + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/http-errors/HISTORY.md b/node_modules/http-errors/HISTORY.md new file mode 100644 index 0000000..7228684 --- /dev/null +++ b/node_modules/http-errors/HISTORY.md @@ -0,0 +1,180 @@ +2.0.0 / 2021-12-17 +================== + + * Drop support for Node.js 0.6 + * Remove `I'mateapot` export; use `ImATeapot` instead + * Remove support for status being non-first argument + * Rename `UnorderedCollection` constructor to `TooEarly` + * deps: depd@2.0.0 + - Replace internal `eval` usage with `Function` constructor + - Use instance methods on `process` to check for listeners + * deps: statuses@2.0.1 + - Fix messaging casing of `418 I'm a Teapot` + - Remove code 306 + - Rename `425 Unordered Collection` to standard `425 Too Early` + +2021-11-14 / 1.8.1 +================== + + * deps: toidentifier@1.0.1 + +2020-06-29 / 1.8.0 +================== + + * Add `isHttpError` export to determine if value is an HTTP error + * deps: setprototypeof@1.2.0 + +2019-06-24 / 1.7.3 +================== + + * deps: inherits@2.0.4 + +2019-02-18 / 1.7.2 +================== + + * deps: setprototypeof@1.1.1 + +2018-09-08 / 1.7.1 +================== + + * Fix error creating objects in some environments + +2018-07-30 / 1.7.0 +================== + + * Set constructor name when possible + * Use `toidentifier` module to make class names + * deps: statuses@'>= 1.5.0 < 2' + +2018-03-29 / 1.6.3 +================== + + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: setprototypeof@1.1.0 + * deps: statuses@'>= 1.4.0 < 2' + +2017-08-04 / 1.6.2 +================== + + * deps: depd@1.1.1 + - Remove unnecessary `Buffer` loading + +2017-02-20 / 1.6.1 +================== + + * deps: setprototypeof@1.0.3 + - Fix shim for old browsers + +2017-02-14 / 1.6.0 +================== + + * Accept custom 4xx and 5xx status codes in factory + * Add deprecation message to `"I'mateapot"` export + * Deprecate passing status code as anything except first argument in factory + * Deprecate using non-error status codes + * Make `message` property enumerable for `HttpError`s + +2016-11-16 / 1.5.1 +================== + + * deps: inherits@2.0.3 + - Fix issue loading in browser + * deps: setprototypeof@1.0.2 + * deps: statuses@'>= 1.3.1 < 2' + +2016-05-18 / 1.5.0 +================== + + * Support new code `421 Misdirected Request` + * Use `setprototypeof` module to replace `__proto__` setting + * deps: statuses@'>= 1.3.0 < 2' + - Add `421 Misdirected Request` + - perf: enable strict mode + * perf: enable strict mode + +2016-01-28 / 1.4.0 +================== + + * Add `HttpError` export, for `err instanceof createError.HttpError` + * deps: inherits@2.0.1 + * deps: statuses@'>= 1.2.1 < 2' + - Fix message for status 451 + - Remove incorrect nginx status code + +2015-02-02 / 1.3.1 +================== + + * Fix regression where status can be overwritten in `createError` `props` + +2015-02-01 / 1.3.0 +================== + + * Construct errors using defined constructors from `createError` + * Fix error names that are not identifiers + - `createError["I'mateapot"]` is now `createError.ImATeapot` + * Set a meaningful `name` property on constructed errors + +2014-12-09 / 1.2.8 +================== + + * Fix stack trace from exported function + * Remove `arguments.callee` usage + +2014-10-14 / 1.2.7 +================== + + * Remove duplicate line + +2014-10-02 / 1.2.6 +================== + + * Fix `expose` to be `true` for `ClientError` constructor + +2014-09-28 / 1.2.5 +================== + + * deps: statuses@1 + +2014-09-21 / 1.2.4 +================== + + * Fix dependency version to work with old `npm`s + +2014-09-21 / 1.2.3 +================== + + * deps: statuses@~1.1.0 + +2014-09-21 / 1.2.2 +================== + + * Fix publish error + +2014-09-21 / 1.2.1 +================== + + * Support Node.js 0.6 + * Use `inherits` instead of `util` + +2014-09-09 / 1.2.0 +================== + + * Fix the way inheriting functions + * Support `expose` being provided in properties argument + +2014-09-08 / 1.1.0 +================== + + * Default status to 500 + * Support provided `error` to extend + +2014-09-08 / 1.0.1 +================== + + * Fix accepting string message + +2014-09-08 / 1.0.0 +================== + + * Initial release diff --git a/node_modules/http-errors/LICENSE b/node_modules/http-errors/LICENSE new file mode 100644 index 0000000..82af4df --- /dev/null +++ b/node_modules/http-errors/LICENSE @@ -0,0 +1,23 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com +Copyright (c) 2016 Douglas Christopher Wilson doug@somethingdoug.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/http-errors/README.md b/node_modules/http-errors/README.md new file mode 100644 index 0000000..a8b7330 --- /dev/null +++ b/node_modules/http-errors/README.md @@ -0,0 +1,169 @@ +# http-errors + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][node-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Create HTTP errors for Express, Koa, Connect, etc. with ease. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```console +$ npm install http-errors +``` + +## Example + +```js +var createError = require('http-errors') +var express = require('express') +var app = express() + +app.use(function (req, res, next) { + if (!req.user) return next(createError(401, 'Please login to view this page.')) + next() +}) +``` + +## API + +This is the current API, currently extracted from Koa and subject to change. + +### Error Properties + +- `expose` - can be used to signal if `message` should be sent to the client, + defaulting to `false` when `status` >= 500 +- `headers` - can be an object of header names to values to be sent to the + client, defaulting to `undefined`. When defined, the key names should all + be lower-cased +- `message` - the traditional error message, which should be kept short and all + single line +- `status` - the status code of the error, mirroring `statusCode` for general + compatibility +- `statusCode` - the status code of the error, defaulting to `500` + +### createError([status], [message], [properties]) + +Create a new error object with the given message `msg`. +The error object inherits from `createError.HttpError`. + +```js +var err = createError(404, 'This video does not exist!') +``` + +- `status: 500` - the status code as a number +- `message` - the message of the error, defaulting to node's text for that status code. +- `properties` - custom properties to attach to the object + +### createError([status], [error], [properties]) + +Extend the given `error` object with `createError.HttpError` +properties. This will not alter the inheritance of the given +`error` object, and the modified `error` object is the +return value. + + + +```js +fs.readFile('foo.txt', function (err, buf) { + if (err) { + if (err.code === 'ENOENT') { + var httpError = createError(404, err, { expose: false }) + } else { + var httpError = createError(500, err) + } + } +}) +``` + +- `status` - the status code as a number +- `error` - the error object to extend +- `properties` - custom properties to attach to the object + +### createError.isHttpError(val) + +Determine if the provided `val` is an `HttpError`. This will return `true` +if the error inherits from the `HttpError` constructor of this module or +matches the "duck type" for an error this module creates. All outputs from +the `createError` factory will return `true` for this function, including +if an non-`HttpError` was passed into the factory. + +### new createError\[code || name\](\[msg]\)) + +Create a new error object with the given message `msg`. +The error object inherits from `createError.HttpError`. + +```js +var err = new createError.NotFound() +``` + +- `code` - the status code as a number +- `name` - the name of the error as a "bumpy case", i.e. `NotFound` or `InternalServerError`. + +#### List of all constructors + +|Status Code|Constructor Name | +|-----------|-----------------------------| +|400 |BadRequest | +|401 |Unauthorized | +|402 |PaymentRequired | +|403 |Forbidden | +|404 |NotFound | +|405 |MethodNotAllowed | +|406 |NotAcceptable | +|407 |ProxyAuthenticationRequired | +|408 |RequestTimeout | +|409 |Conflict | +|410 |Gone | +|411 |LengthRequired | +|412 |PreconditionFailed | +|413 |PayloadTooLarge | +|414 |URITooLong | +|415 |UnsupportedMediaType | +|416 |RangeNotSatisfiable | +|417 |ExpectationFailed | +|418 |ImATeapot | +|421 |MisdirectedRequest | +|422 |UnprocessableEntity | +|423 |Locked | +|424 |FailedDependency | +|425 |TooEarly | +|426 |UpgradeRequired | +|428 |PreconditionRequired | +|429 |TooManyRequests | +|431 |RequestHeaderFieldsTooLarge | +|451 |UnavailableForLegalReasons | +|500 |InternalServerError | +|501 |NotImplemented | +|502 |BadGateway | +|503 |ServiceUnavailable | +|504 |GatewayTimeout | +|505 |HTTPVersionNotSupported | +|506 |VariantAlsoNegotiates | +|507 |InsufficientStorage | +|508 |LoopDetected | +|509 |BandwidthLimitExceeded | +|510 |NotExtended | +|511 |NetworkAuthenticationRequired| + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/http-errors/master?label=ci +[ci-url]: https://github.com/jshttp/http-errors/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/http-errors/master +[coveralls-url]: https://coveralls.io/r/jshttp/http-errors?branch=master +[node-image]: https://badgen.net/npm/node/http-errors +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/http-errors +[npm-url]: https://npmjs.org/package/http-errors +[npm-version-image]: https://badgen.net/npm/v/http-errors +[travis-image]: https://badgen.net/travis/jshttp/http-errors/master +[travis-url]: https://travis-ci.org/jshttp/http-errors diff --git a/node_modules/http-errors/index.js b/node_modules/http-errors/index.js new file mode 100644 index 0000000..c425f1e --- /dev/null +++ b/node_modules/http-errors/index.js @@ -0,0 +1,289 @@ +/*! + * http-errors + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var deprecate = require('depd')('http-errors') +var setPrototypeOf = require('setprototypeof') +var statuses = require('statuses') +var inherits = require('inherits') +var toIdentifier = require('toidentifier') + +/** + * Module exports. + * @public + */ + +module.exports = createError +module.exports.HttpError = createHttpErrorConstructor() +module.exports.isHttpError = createIsHttpErrorFunction(module.exports.HttpError) + +// Populate exports for all constructors +populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError) + +/** + * Get the code class of a status code. + * @private + */ + +function codeClass (status) { + return Number(String(status).charAt(0) + '00') +} + +/** + * Create a new HTTP Error. + * + * @returns {Error} + * @public + */ + +function createError () { + // so much arity going on ~_~ + var err + var msg + var status = 500 + var props = {} + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i] + var type = typeof arg + if (type === 'object' && arg instanceof Error) { + err = arg + status = err.status || err.statusCode || status + } else if (type === 'number' && i === 0) { + status = arg + } else if (type === 'string') { + msg = arg + } else if (type === 'object') { + props = arg + } else { + throw new TypeError('argument #' + (i + 1) + ' unsupported type ' + type) + } + } + + if (typeof status === 'number' && (status < 400 || status >= 600)) { + deprecate('non-error status code; use only 4xx or 5xx status codes') + } + + if (typeof status !== 'number' || + (!statuses.message[status] && (status < 400 || status >= 600))) { + status = 500 + } + + // constructor + var HttpError = createError[status] || createError[codeClass(status)] + + if (!err) { + // create error + err = HttpError + ? new HttpError(msg) + : new Error(msg || statuses.message[status]) + Error.captureStackTrace(err, createError) + } + + if (!HttpError || !(err instanceof HttpError) || err.status !== status) { + // add properties to generic error + err.expose = status < 500 + err.status = err.statusCode = status + } + + for (var key in props) { + if (key !== 'status' && key !== 'statusCode') { + err[key] = props[key] + } + } + + return err +} + +/** + * Create HTTP error abstract base class. + * @private + */ + +function createHttpErrorConstructor () { + function HttpError () { + throw new TypeError('cannot construct abstract class') + } + + inherits(HttpError, Error) + + return HttpError +} + +/** + * Create a constructor for a client error. + * @private + */ + +function createClientErrorConstructor (HttpError, name, code) { + var className = toClassName(name) + + function ClientError (message) { + // create the error object + var msg = message != null ? message : statuses.message[code] + var err = new Error(msg) + + // capture a stack trace to the construction point + Error.captureStackTrace(err, ClientError) + + // adjust the [[Prototype]] + setPrototypeOf(err, ClientError.prototype) + + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) + + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + + return err + } + + inherits(ClientError, HttpError) + nameFunc(ClientError, className) + + ClientError.prototype.status = code + ClientError.prototype.statusCode = code + ClientError.prototype.expose = true + + return ClientError +} + +/** + * Create function to test is a value is a HttpError. + * @private + */ + +function createIsHttpErrorFunction (HttpError) { + return function isHttpError (val) { + if (!val || typeof val !== 'object') { + return false + } + + if (val instanceof HttpError) { + return true + } + + return val instanceof Error && + typeof val.expose === 'boolean' && + typeof val.statusCode === 'number' && val.status === val.statusCode + } +} + +/** + * Create a constructor for a server error. + * @private + */ + +function createServerErrorConstructor (HttpError, name, code) { + var className = toClassName(name) + + function ServerError (message) { + // create the error object + var msg = message != null ? message : statuses.message[code] + var err = new Error(msg) + + // capture a stack trace to the construction point + Error.captureStackTrace(err, ServerError) + + // adjust the [[Prototype]] + setPrototypeOf(err, ServerError.prototype) + + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) + + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + + return err + } + + inherits(ServerError, HttpError) + nameFunc(ServerError, className) + + ServerError.prototype.status = code + ServerError.prototype.statusCode = code + ServerError.prototype.expose = false + + return ServerError +} + +/** + * Set the name of a function, if possible. + * @private + */ + +function nameFunc (func, name) { + var desc = Object.getOwnPropertyDescriptor(func, 'name') + + if (desc && desc.configurable) { + desc.value = name + Object.defineProperty(func, 'name', desc) + } +} + +/** + * Populate the exports object with constructors for every error class. + * @private + */ + +function populateConstructorExports (exports, codes, HttpError) { + codes.forEach(function forEachCode (code) { + var CodeError + var name = toIdentifier(statuses.message[code]) + + switch (codeClass(code)) { + case 400: + CodeError = createClientErrorConstructor(HttpError, name, code) + break + case 500: + CodeError = createServerErrorConstructor(HttpError, name, code) + break + } + + if (CodeError) { + // export the constructor + exports[code] = CodeError + exports[name] = CodeError + } + }) +} + +/** + * Get a class name from a name identifier. + * @private + */ + +function toClassName (name) { + return name.substr(-5) !== 'Error' + ? name + 'Error' + : name +} diff --git a/node_modules/http-errors/node_modules/statuses/HISTORY.md b/node_modules/http-errors/node_modules/statuses/HISTORY.md new file mode 100644 index 0000000..fa4556e --- /dev/null +++ b/node_modules/http-errors/node_modules/statuses/HISTORY.md @@ -0,0 +1,82 @@ +2.0.1 / 2021-01-03 +================== + + * Fix returning values from `Object.prototype` + +2.0.0 / 2020-04-19 +================== + + * Drop support for Node.js 0.6 + * Fix messaging casing of `418 I'm a Teapot` + * Remove code 306 + * Remove `status[code]` exports; use `status.message[code]` + * Remove `status[msg]` exports; use `status.code[msg]` + * Rename `425 Unordered Collection` to standard `425 Too Early` + * Rename `STATUS_CODES` export to `message` + * Return status message for `statuses(code)` when given code + +1.5.0 / 2018-03-27 +================== + + * Add `103 Early Hints` + +1.4.0 / 2017-10-20 +================== + + * Add `STATUS_CODES` export + +1.3.1 / 2016-11-11 +================== + + * Fix return type in JSDoc + +1.3.0 / 2016-05-17 +================== + + * Add `421 Misdirected Request` + * perf: enable strict mode + +1.2.1 / 2015-02-01 +================== + + * Fix message for status 451 + - `451 Unavailable For Legal Reasons` + +1.2.0 / 2014-09-28 +================== + + * Add `208 Already Repored` + * Add `226 IM Used` + * Add `306 (Unused)` + * Add `415 Unable For Legal Reasons` + * Add `508 Loop Detected` + +1.1.1 / 2014-09-24 +================== + + * Add missing 308 to `codes.json` + +1.1.0 / 2014-09-21 +================== + + * Add `codes.json` for universal support + +1.0.4 / 2014-08-20 +================== + + * Package cleanup + +1.0.3 / 2014-06-08 +================== + + * Add 308 to `.redirect` category + +1.0.2 / 2014-03-13 +================== + + * Add `.retry` category + +1.0.1 / 2014-03-12 +================== + + * Initial release diff --git a/node_modules/http-errors/node_modules/statuses/LICENSE b/node_modules/http-errors/node_modules/statuses/LICENSE new file mode 100644 index 0000000..28a3161 --- /dev/null +++ b/node_modules/http-errors/node_modules/statuses/LICENSE @@ -0,0 +1,23 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2016 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/http-errors/node_modules/statuses/README.md b/node_modules/http-errors/node_modules/statuses/README.md new file mode 100644 index 0000000..57967e6 --- /dev/null +++ b/node_modules/http-errors/node_modules/statuses/README.md @@ -0,0 +1,136 @@ +# statuses + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +HTTP status utility for node. + +This module provides a list of status codes and messages sourced from +a few different projects: + + * The [IANA Status Code Registry](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml) + * The [Node.js project](https://nodejs.org/) + * The [NGINX project](https://www.nginx.com/) + * The [Apache HTTP Server project](https://httpd.apache.org/) + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install statuses +``` + +## API + + + +```js +var status = require('statuses') +``` + +### status(code) + +Returns the status message string for a known HTTP status code. The code +may be a number or a string. An error is thrown for an unknown status code. + + + +```js +status(403) // => 'Forbidden' +status('403') // => 'Forbidden' +status(306) // throws +``` + +### status(msg) + +Returns the numeric status code for a known HTTP status message. The message +is case-insensitive. An error is thrown for an unknown status message. + + + +```js +status('forbidden') // => 403 +status('Forbidden') // => 403 +status('foo') // throws +``` + +### status.codes + +Returns an array of all the status codes as `Integer`s. + +### status.code[msg] + +Returns the numeric status code for a known status message (in lower-case), +otherwise `undefined`. + + + +```js +status['not found'] // => 404 +``` + +### status.empty[code] + +Returns `true` if a status code expects an empty body. + + + +```js +status.empty[200] // => undefined +status.empty[204] // => true +status.empty[304] // => true +``` + +### status.message[code] + +Returns the string message for a known numeric status code, otherwise +`undefined`. This object is the same format as the +[Node.js http module `http.STATUS_CODES`](https://nodejs.org/dist/latest/docs/api/http.html#http_http_status_codes). + + + +```js +status.message[404] // => 'Not Found' +``` + +### status.redirect[code] + +Returns `true` if a status code is a valid redirect status. + + + +```js +status.redirect[200] // => undefined +status.redirect[301] // => true +``` + +### status.retry[code] + +Returns `true` if you should retry the rest. + + + +```js +status.retry[501] // => undefined +status.retry[503] // => true +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/statuses/master?label=ci +[ci-url]: https://github.com/jshttp/statuses/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/statuses/master +[coveralls-url]: https://coveralls.io/r/jshttp/statuses?branch=master +[node-version-image]: https://badgen.net/npm/node/statuses +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/statuses +[npm-url]: https://npmjs.org/package/statuses +[npm-version-image]: https://badgen.net/npm/v/statuses diff --git a/node_modules/http-errors/node_modules/statuses/codes.json b/node_modules/http-errors/node_modules/statuses/codes.json new file mode 100644 index 0000000..1333ed1 --- /dev/null +++ b/node_modules/http-errors/node_modules/statuses/codes.json @@ -0,0 +1,65 @@ +{ + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "103": "Early Hints", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a Teapot", + "421": "Misdirected Request", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Too Early", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "510": "Not Extended", + "511": "Network Authentication Required" +} diff --git a/node_modules/http-errors/node_modules/statuses/index.js b/node_modules/http-errors/node_modules/statuses/index.js new file mode 100644 index 0000000..ea351c5 --- /dev/null +++ b/node_modules/http-errors/node_modules/statuses/index.js @@ -0,0 +1,146 @@ +/*! + * statuses + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var codes = require('./codes.json') + +/** + * Module exports. + * @public + */ + +module.exports = status + +// status code to message map +status.message = codes + +// status message (lower-case) to code map +status.code = createMessageToStatusCodeMap(codes) + +// array of status codes +status.codes = createStatusCodeList(codes) + +// status codes for redirects +status.redirect = { + 300: true, + 301: true, + 302: true, + 303: true, + 305: true, + 307: true, + 308: true +} + +// status codes for empty bodies +status.empty = { + 204: true, + 205: true, + 304: true +} + +// status codes for when you should retry the request +status.retry = { + 502: true, + 503: true, + 504: true +} + +/** + * Create a map of message to status code. + * @private + */ + +function createMessageToStatusCodeMap (codes) { + var map = {} + + Object.keys(codes).forEach(function forEachCode (code) { + var message = codes[code] + var status = Number(code) + + // populate map + map[message.toLowerCase()] = status + }) + + return map +} + +/** + * Create a list of all status codes. + * @private + */ + +function createStatusCodeList (codes) { + return Object.keys(codes).map(function mapCode (code) { + return Number(code) + }) +} + +/** + * Get the status code for given message. + * @private + */ + +function getStatusCode (message) { + var msg = message.toLowerCase() + + if (!Object.prototype.hasOwnProperty.call(status.code, msg)) { + throw new Error('invalid status message: "' + message + '"') + } + + return status.code[msg] +} + +/** + * Get the status message for given code. + * @private + */ + +function getStatusMessage (code) { + if (!Object.prototype.hasOwnProperty.call(status.message, code)) { + throw new Error('invalid status code: ' + code) + } + + return status.message[code] +} + +/** + * Get the status code. + * + * Given a number, this will throw if it is not a known status + * code, otherwise the code will be returned. Given a string, + * the string will be parsed for a number and return the code + * if valid, otherwise will lookup the code assuming this is + * the status message. + * + * @param {string|number} code + * @returns {number} + * @public + */ + +function status (code) { + if (typeof code === 'number') { + return getStatusMessage(code) + } + + if (typeof code !== 'string') { + throw new TypeError('code must be a number or string') + } + + // '403' + var n = parseInt(code, 10) + if (!isNaN(n)) { + return getStatusMessage(n) + } + + return getStatusCode(code) +} diff --git a/node_modules/http-errors/node_modules/statuses/package.json b/node_modules/http-errors/node_modules/statuses/package.json new file mode 100644 index 0000000..8c3e719 --- /dev/null +++ b/node_modules/http-errors/node_modules/statuses/package.json @@ -0,0 +1,49 @@ +{ + "name": "statuses", + "description": "HTTP status utility", + "version": "2.0.1", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "repository": "jshttp/statuses", + "license": "MIT", + "keywords": [ + "http", + "status", + "code" + ], + "files": [ + "HISTORY.md", + "index.js", + "codes.json", + "LICENSE" + ], + "devDependencies": { + "csv-parse": "4.14.2", + "eslint": "7.17.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.22.1", + "eslint-plugin-markdown": "1.0.2", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "4.2.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "8.2.1", + "nyc": "15.1.0", + "raw-body": "2.4.1", + "stream-to-array": "2.3.0" + }, + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "build": "node scripts/build.js", + "fetch": "node scripts/fetch-apache.js && node scripts/fetch-iana.js && node scripts/fetch-nginx.js && node scripts/fetch-node.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "update": "npm run fetch && npm run build", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/http-errors/package.json b/node_modules/http-errors/package.json new file mode 100644 index 0000000..4cb6d7e --- /dev/null +++ b/node_modules/http-errors/package.json @@ -0,0 +1,50 @@ +{ + "name": "http-errors", + "description": "Create HTTP error objects", + "version": "2.0.0", + "author": "Jonathan Ong (http://jongleberry.com)", + "contributors": [ + "Alan Plum ", + "Douglas Christopher Wilson " + ], + "license": "MIT", + "repository": "jshttp/http-errors", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.3", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.1.3", + "nyc": "15.1.0" + }, + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint . && node ./scripts/lint-readme-list.js", + "test": "mocha --reporter spec --bail", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "version": "node scripts/version-history.js && git add HISTORY.md" + }, + "keywords": [ + "http", + "error" + ], + "files": [ + "index.js", + "HISTORY.md", + "LICENSE", + "README.md" + ] +} diff --git a/node_modules/iconv-lite/.github/dependabot.yml b/node_modules/iconv-lite/.github/dependabot.yml new file mode 100644 index 0000000..e4a0e0a --- /dev/null +++ b/node_modules/iconv-lite/.github/dependabot.yml @@ -0,0 +1,11 @@ +# Please see the documentation for all configuration options: +# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "daily" + allow: + - dependency-type: production diff --git a/node_modules/iconv-lite/.idea/codeStyles/Project.xml b/node_modules/iconv-lite/.idea/codeStyles/Project.xml new file mode 100644 index 0000000..3f2688c --- /dev/null +++ b/node_modules/iconv-lite/.idea/codeStyles/Project.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/iconv-lite/.idea/codeStyles/codeStyleConfig.xml b/node_modules/iconv-lite/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..79ee123 --- /dev/null +++ b/node_modules/iconv-lite/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/node_modules/iconv-lite/.idea/iconv-lite.iml b/node_modules/iconv-lite/.idea/iconv-lite.iml new file mode 100644 index 0000000..0c8867d --- /dev/null +++ b/node_modules/iconv-lite/.idea/iconv-lite.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/iconv-lite/.idea/inspectionProfiles/Project_Default.xml b/node_modules/iconv-lite/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..03d9549 --- /dev/null +++ b/node_modules/iconv-lite/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/node_modules/iconv-lite/.idea/modules.xml b/node_modules/iconv-lite/.idea/modules.xml new file mode 100644 index 0000000..5d24f2e --- /dev/null +++ b/node_modules/iconv-lite/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/node_modules/iconv-lite/.idea/vcs.xml b/node_modules/iconv-lite/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/node_modules/iconv-lite/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/node_modules/iconv-lite/Changelog.md b/node_modules/iconv-lite/Changelog.md new file mode 100644 index 0000000..464549b --- /dev/null +++ b/node_modules/iconv-lite/Changelog.md @@ -0,0 +1,212 @@ +## 0.6.3 / 2021-05-23 + * Fix HKSCS encoding to prefer Big5 codes if both Big5 and HKSCS codes are possible (#264) + + +## 0.6.2 / 2020-07-08 + * Support Uint8Array-s decoding without conversion to Buffers, plus fix an edge case. + + +## 0.6.1 / 2020-06-28 + * Support Uint8Array-s directly when decoding (#246, by @gyzerok) + * Unify package.json version ranges to be strictly semver-compatible (#241) + * Fix minor issue in UTF-32 decoder's endianness detection code. + + +## 0.6.0 / 2020-06-08 + * Updated 'gb18030' encoding to :2005 edition (see https://github.com/whatwg/encoding/issues/22). + * Removed `iconv.extendNodeEncodings()` mechanism. It was deprecated 5 years ago and didn't work + in recent Node versions. + * Reworked Streaming API behavior in browser environments to fix #204. Streaming API will be + excluded by default in browser packs, saving ~100Kb bundle size, unless enabled explicitly using + `iconv.enableStreamingAPI(require('stream'))`. + * Updates to development environment & tests: + * Added ./test/webpack private package to test complex new use cases that need custom environment. + It's tested as a separate job in Travis CI. + * Updated generation code for the new EUC-KR index file format from Encoding Standard. + * Removed Buffer() constructor in tests (#197 by @gabrielschulhof). + + +## 0.5.2 / 2020-06-08 + * Added `iconv.getEncoder()` and `iconv.getDecoder()` methods to typescript definitions (#229). + * Fixed semver version to 6.1.2 to support Node 8.x (by @tanandara). + * Capped iconv version to 2.x as 3.x has dropped support for older Node versions. + * Switched from instanbul to c8 for code coverage. + + +## 0.5.1 / 2020-01-18 + + * Added cp720 encoding (#221, by @kr-deps) + * (minor) Changed Changelog.md formatting to use h2. + + +## 0.5.0 / 2019-06-26 + + * Added UTF-32 encoding, both little-endian and big-endian variants (UTF-32LE, UTF32-BE). If endianness + is not provided for decoding, it's deduced automatically from the stream using a heuristic similar to + what we use in UTF-16. (great work in #216 by @kshetline) + * Several minor updates to README (#217 by @oldj, plus some more) + * Added Node versions 10 and 12 to Travis test harness. + + +## 0.4.24 / 2018-08-22 + + * Added MIK encoding (#196, by @Ivan-Kalatchev) + + +## 0.4.23 / 2018-05-07 + + * Fix deprecation warning in Node v10 due to the last usage of `new Buffer` (#185, by @felixbuenemann) + * Switched from NodeBuffer to Buffer in typings (#155 by @felixfbecker, #186 by @larssn) + + +## 0.4.22 / 2018-05-05 + + * Use older semver style for dependencies to be compatible with Node version 0.10 (#182, by @dougwilson) + * Fix tests to accomodate fixes in Node v10 (#182, by @dougwilson) + + +## 0.4.21 / 2018-04-06 + + * Fix encoding canonicalization (#156) + * Fix the paths in the "browser" field in package.json (#174 by @LMLB) + * Removed "contributors" section in package.json - see Git history instead. + + +## 0.4.20 / 2018-04-06 + + * Updated `new Buffer()` usages with recommended replacements as it's being deprecated in Node v10 (#176, #178 by @ChALkeR) + + +## 0.4.19 / 2017-09-09 + + * Fixed iso8859-1 codec regression in handling untranslatable characters (#162, caused by #147) + * Re-generated windows1255 codec, because it was updated in iconv project + * Fixed grammar in error message when iconv-lite is loaded with encoding other than utf8 + + +## 0.4.18 / 2017-06-13 + + * Fixed CESU-8 regression in Node v8. + + +## 0.4.17 / 2017-04-22 + + * Updated typescript definition file to support Angular 2 AoT mode (#153 by @larssn) + + +## 0.4.16 / 2017-04-22 + + * Added support for React Native (#150) + * Changed iso8859-1 encoding to usine internal 'binary' encoding, as it's the same thing (#147 by @mscdex) + * Fixed typo in Readme (#138 by @jiangzhuo) + * Fixed build for Node v6.10+ by making correct version comparison + * Added a warning if iconv-lite is loaded not as utf-8 (see #142) + + +## 0.4.15 / 2016-11-21 + + * Fixed typescript type definition (#137) + + +## 0.4.14 / 2016-11-20 + + * Preparation for v1.0 + * Added Node v6 and latest Node versions to Travis CI test rig + * Deprecated Node v0.8 support + * Typescript typings (@larssn) + * Fix encoding of Euro character in GB 18030 (inspired by @lygstate) + * Add ms prefix to dbcs windows encodings (@rokoroku) + + +## 0.4.13 / 2015-10-01 + + * Fix silly mistake in deprecation notice. + + +## 0.4.12 / 2015-09-26 + + * Node v4 support: + * Added CESU-8 decoding (#106) + * Added deprecation notice for `extendNodeEncodings` + * Added Travis tests for Node v4 and io.js latest (#105 by @Mithgol) + + +## 0.4.11 / 2015-07-03 + + * Added CESU-8 encoding. + + +## 0.4.10 / 2015-05-26 + + * Changed UTF-16 endianness heuristic to take into account any ASCII chars, not + just spaces. This should minimize the importance of "default" endianness. + + +## 0.4.9 / 2015-05-24 + + * Streamlined BOM handling: strip BOM by default, add BOM when encoding if + addBOM: true. Added docs to Readme. + * UTF16 now uses UTF16-LE by default. + * Fixed minor issue with big5 encoding. + * Added io.js testing on Travis; updated node-iconv version to test against. + Now we just skip testing SBCS encodings that node-iconv doesn't support. + * (internal refactoring) Updated codec interface to use classes. + * Use strict mode in all files. + + +## 0.4.8 / 2015-04-14 + + * added alias UNICODE-1-1-UTF-7 for UTF-7 encoding (#94) + + +## 0.4.7 / 2015-02-05 + + * stop official support of Node.js v0.8. Should still work, but no guarantees. + reason: Packages needed for testing are hard to get on Travis CI. + * work in environment where Object.prototype is monkey patched with enumerable + props (#89). + + +## 0.4.6 / 2015-01-12 + + * fix rare aliases of single-byte encodings (thanks @mscdex) + * double the timeout for dbcs tests to make them less flaky on travis + + +## 0.4.5 / 2014-11-20 + + * fix windows-31j and x-sjis encoding support (@nleush) + * minor fix: undefined variable reference when internal error happens + + +## 0.4.4 / 2014-07-16 + + * added encodings UTF-7 (RFC2152) and UTF-7-IMAP (RFC3501 Section 5.1.3) + * fixed streaming base64 encoding + + +## 0.4.3 / 2014-06-14 + + * added encodings UTF-16BE and UTF-16 with BOM + + +## 0.4.2 / 2014-06-12 + + * don't throw exception if `extendNodeEncodings()` is called more than once + + +## 0.4.1 / 2014-06-11 + + * codepage 808 added + + +## 0.4.0 / 2014-06-10 + + * code is rewritten from scratch + * all widespread encodings are supported + * streaming interface added + * browserify compatibility added + * (optional) extend core primitive encodings to make usage even simpler + * moved from vows to mocha as the testing framework + + diff --git a/node_modules/iconv-lite/LICENSE b/node_modules/iconv-lite/LICENSE new file mode 100644 index 0000000..d518d83 --- /dev/null +++ b/node_modules/iconv-lite/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2011 Alexander Shtuchkin + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/iconv-lite/README.md b/node_modules/iconv-lite/README.md new file mode 100644 index 0000000..3c97f87 --- /dev/null +++ b/node_modules/iconv-lite/README.md @@ -0,0 +1,130 @@ +## iconv-lite: Pure JS character encoding conversion + + * No need for native code compilation. Quick to install, works on Windows and in sandboxed environments like [Cloud9](http://c9.io). + * Used in popular projects like [Express.js (body_parser)](https://github.com/expressjs/body-parser), + [Grunt](http://gruntjs.com/), [Nodemailer](http://www.nodemailer.com/), [Yeoman](http://yeoman.io/) and others. + * Faster than [node-iconv](https://github.com/bnoordhuis/node-iconv) (see below for performance comparison). + * Intuitive encode/decode API, including Streaming support. + * In-browser usage via [browserify](https://github.com/substack/node-browserify) or [webpack](https://webpack.js.org/) (~180kb gzip compressed with Buffer shim included). + * Typescript [type definition file](https://github.com/ashtuchkin/iconv-lite/blob/master/lib/index.d.ts) included. + * React Native is supported (need to install `stream` module to enable Streaming API). + * License: MIT. + +[![NPM Stats](https://nodei.co/npm/iconv-lite.png)](https://npmjs.org/package/iconv-lite/) +[![Build Status](https://travis-ci.org/ashtuchkin/iconv-lite.svg?branch=master)](https://travis-ci.org/ashtuchkin/iconv-lite) +[![npm](https://img.shields.io/npm/v/iconv-lite.svg)](https://npmjs.org/package/iconv-lite/) +[![npm downloads](https://img.shields.io/npm/dm/iconv-lite.svg)](https://npmjs.org/package/iconv-lite/) +[![npm bundle size](https://img.shields.io/bundlephobia/min/iconv-lite.svg)](https://npmjs.org/package/iconv-lite/) + +## Usage +### Basic API +```javascript +var iconv = require('iconv-lite'); + +// Convert from an encoded buffer to a js string. +str = iconv.decode(Buffer.from([0x68, 0x65, 0x6c, 0x6c, 0x6f]), 'win1251'); + +// Convert from a js string to an encoded buffer. +buf = iconv.encode("Sample input string", 'win1251'); + +// Check if encoding is supported +iconv.encodingExists("us-ascii") +``` + +### Streaming API +```javascript + +// Decode stream (from binary data stream to js strings) +http.createServer(function(req, res) { + var converterStream = iconv.decodeStream('win1251'); + req.pipe(converterStream); + + converterStream.on('data', function(str) { + console.log(str); // Do something with decoded strings, chunk-by-chunk. + }); +}); + +// Convert encoding streaming example +fs.createReadStream('file-in-win1251.txt') + .pipe(iconv.decodeStream('win1251')) + .pipe(iconv.encodeStream('ucs2')) + .pipe(fs.createWriteStream('file-in-ucs2.txt')); + +// Sugar: all encode/decode streams have .collect(cb) method to accumulate data. +http.createServer(function(req, res) { + req.pipe(iconv.decodeStream('win1251')).collect(function(err, body) { + assert(typeof body == 'string'); + console.log(body); // full request body string + }); +}); +``` + +## Supported encodings + + * All node.js native encodings: utf8, ucs2 / utf16-le, ascii, binary, base64, hex. + * Additional unicode encodings: utf16, utf16-be, utf-7, utf-7-imap, utf32, utf32-le, and utf32-be. + * All widespread singlebyte encodings: Windows 125x family, ISO-8859 family, + IBM/DOS codepages, Macintosh family, KOI8 family, all others supported by iconv library. + Aliases like 'latin1', 'us-ascii' also supported. + * All widespread multibyte encodings: CP932, CP936, CP949, CP950, GB2312, GBK, GB18030, Big5, Shift_JIS, EUC-JP. + +See [all supported encodings on wiki](https://github.com/ashtuchkin/iconv-lite/wiki/Supported-Encodings). + +Most singlebyte encodings are generated automatically from [node-iconv](https://github.com/bnoordhuis/node-iconv). Thank you Ben Noordhuis and libiconv authors! + +Multibyte encodings are generated from [Unicode.org mappings](http://www.unicode.org/Public/MAPPINGS/) and [WHATWG Encoding Standard mappings](http://encoding.spec.whatwg.org/). Thank you, respective authors! + + +## Encoding/decoding speed + +Comparison with node-iconv module (1000x256kb, on MacBook Pro, Core i5/2.6 GHz, Node v0.12.0). +Note: your results may vary, so please always check on your hardware. + + operation iconv@2.1.4 iconv-lite@0.4.7 + ---------------------------------------------------------- + encode('win1251') ~96 Mb/s ~320 Mb/s + decode('win1251') ~95 Mb/s ~246 Mb/s + +## BOM handling + + * Decoding: BOM is stripped by default, unless overridden by passing `stripBOM: false` in options + (f.ex. `iconv.decode(buf, enc, {stripBOM: false})`). + A callback might also be given as a `stripBOM` parameter - it'll be called if BOM character was actually found. + * If you want to detect UTF-8 BOM when decoding other encodings, use [node-autodetect-decoder-stream](https://github.com/danielgindi/node-autodetect-decoder-stream) module. + * Encoding: No BOM added, unless overridden by `addBOM: true` option. + +## UTF-16 Encodings + +This library supports UTF-16LE, UTF-16BE and UTF-16 encodings. First two are straightforward, but UTF-16 is trying to be +smart about endianness in the following ways: + * Decoding: uses BOM and 'spaces heuristic' to determine input endianness. Default is UTF-16LE, but can be + overridden with `defaultEncoding: 'utf-16be'` option. Strips BOM unless `stripBOM: false`. + * Encoding: uses UTF-16LE and writes BOM by default. Use `addBOM: false` to override. + +## UTF-32 Encodings + +This library supports UTF-32LE, UTF-32BE and UTF-32 encodings. Like the UTF-16 encoding above, UTF-32 defaults to UTF-32LE, but uses BOM and 'spaces heuristics' to determine input endianness. + * The default of UTF-32LE can be overridden with the `defaultEncoding: 'utf-32be'` option. Strips BOM unless `stripBOM: false`. + * Encoding: uses UTF-32LE and writes BOM by default. Use `addBOM: false` to override. (`defaultEncoding: 'utf-32be'` can also be used here to change encoding.) + +## Other notes + +When decoding, be sure to supply a Buffer to decode() method, otherwise [bad things usually happen](https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding). +Untranslatable characters are set to � or ?. No transliteration is currently supported. +Node versions 0.10.31 and 0.11.13 are buggy, don't use them (see #65, #77). + +## Testing + +```bash +$ git clone git@github.com:ashtuchkin/iconv-lite.git +$ cd iconv-lite +$ npm install +$ npm test + +$ # To view performance: +$ node test/performance.js + +$ # To view test coverage: +$ npm run coverage +$ open coverage/lcov-report/index.html +``` diff --git a/node_modules/iconv-lite/encodings/dbcs-codec.js b/node_modules/iconv-lite/encodings/dbcs-codec.js new file mode 100644 index 0000000..fa83917 --- /dev/null +++ b/node_modules/iconv-lite/encodings/dbcs-codec.js @@ -0,0 +1,597 @@ +"use strict"; +var Buffer = require("safer-buffer").Buffer; + +// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. +// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. +// To save memory and loading time, we read table files only when requested. + +exports._dbcs = DBCSCodec; + +var UNASSIGNED = -1, + GB18030_CODE = -2, + SEQ_START = -10, + NODE_START = -1000, + UNASSIGNED_NODE = new Array(0x100), + DEF_CHAR = -1; + +for (var i = 0; i < 0x100; i++) + UNASSIGNED_NODE[i] = UNASSIGNED; + + +// Class DBCSCodec reads and initializes mapping tables. +function DBCSCodec(codecOptions, iconv) { + this.encodingName = codecOptions.encodingName; + if (!codecOptions) + throw new Error("DBCS codec is called without the data.") + if (!codecOptions.table) + throw new Error("Encoding '" + this.encodingName + "' has no data."); + + // Load tables. + var mappingTable = codecOptions.table(); + + + // Decode tables: MBCS -> Unicode. + + // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. + // Trie root is decodeTables[0]. + // Values: >= 0 -> unicode character code. can be > 0xFFFF + // == UNASSIGNED -> unknown/unassigned sequence. + // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. + // <= NODE_START -> index of the next node in our trie to process next byte. + // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. + this.decodeTables = []; + this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. + + // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. + this.decodeTableSeq = []; + + // Actual mapping tables consist of chunks. Use them to fill up decode tables. + for (var i = 0; i < mappingTable.length; i++) + this._addDecodeChunk(mappingTable[i]); + + // Load & create GB18030 tables when needed. + if (typeof codecOptions.gb18030 === 'function') { + this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. + + // Add GB18030 common decode nodes. + var commonThirdByteNodeIdx = this.decodeTables.length; + this.decodeTables.push(UNASSIGNED_NODE.slice(0)); + + var commonFourthByteNodeIdx = this.decodeTables.length; + this.decodeTables.push(UNASSIGNED_NODE.slice(0)); + + // Fill out the tree + var firstByteNode = this.decodeTables[0]; + for (var i = 0x81; i <= 0xFE; i++) { + var secondByteNode = this.decodeTables[NODE_START - firstByteNode[i]]; + for (var j = 0x30; j <= 0x39; j++) { + if (secondByteNode[j] === UNASSIGNED) { + secondByteNode[j] = NODE_START - commonThirdByteNodeIdx; + } else if (secondByteNode[j] > NODE_START) { + throw new Error("gb18030 decode tables conflict at byte 2"); + } + + var thirdByteNode = this.decodeTables[NODE_START - secondByteNode[j]]; + for (var k = 0x81; k <= 0xFE; k++) { + if (thirdByteNode[k] === UNASSIGNED) { + thirdByteNode[k] = NODE_START - commonFourthByteNodeIdx; + } else if (thirdByteNode[k] === NODE_START - commonFourthByteNodeIdx) { + continue; + } else if (thirdByteNode[k] > NODE_START) { + throw new Error("gb18030 decode tables conflict at byte 3"); + } + + var fourthByteNode = this.decodeTables[NODE_START - thirdByteNode[k]]; + for (var l = 0x30; l <= 0x39; l++) { + if (fourthByteNode[l] === UNASSIGNED) + fourthByteNode[l] = GB18030_CODE; + } + } + } + } + } + + this.defaultCharUnicode = iconv.defaultCharUnicode; + + + // Encode tables: Unicode -> DBCS. + + // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. + // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. + // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). + // == UNASSIGNED -> no conversion found. Output a default char. + // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. + this.encodeTable = []; + + // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of + // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key + // means end of sequence (needed when one sequence is a strict subsequence of another). + // Objects are kept separately from encodeTable to increase performance. + this.encodeTableSeq = []; + + // Some chars can be decoded, but need not be encoded. + var skipEncodeChars = {}; + if (codecOptions.encodeSkipVals) + for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { + var val = codecOptions.encodeSkipVals[i]; + if (typeof val === 'number') + skipEncodeChars[val] = true; + else + for (var j = val.from; j <= val.to; j++) + skipEncodeChars[j] = true; + } + + // Use decode trie to recursively fill out encode tables. + this._fillEncodeTable(0, 0, skipEncodeChars); + + // Add more encoding pairs when needed. + if (codecOptions.encodeAdd) { + for (var uChar in codecOptions.encodeAdd) + if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) + this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); + } + + this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; + if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; + if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); +} + +DBCSCodec.prototype.encoder = DBCSEncoder; +DBCSCodec.prototype.decoder = DBCSDecoder; + +// Decoder helpers +DBCSCodec.prototype._getDecodeTrieNode = function(addr) { + var bytes = []; + for (; addr > 0; addr >>>= 8) + bytes.push(addr & 0xFF); + if (bytes.length == 0) + bytes.push(0); + + var node = this.decodeTables[0]; + for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. + var val = node[bytes[i]]; + + if (val == UNASSIGNED) { // Create new node. + node[bytes[i]] = NODE_START - this.decodeTables.length; + this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); + } + else if (val <= NODE_START) { // Existing node. + node = this.decodeTables[NODE_START - val]; + } + else + throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); + } + return node; +} + + +DBCSCodec.prototype._addDecodeChunk = function(chunk) { + // First element of chunk is the hex mbcs code where we start. + var curAddr = parseInt(chunk[0], 16); + + // Choose the decoding node where we'll write our chars. + var writeTable = this._getDecodeTrieNode(curAddr); + curAddr = curAddr & 0xFF; + + // Write all other elements of the chunk to the table. + for (var k = 1; k < chunk.length; k++) { + var part = chunk[k]; + if (typeof part === "string") { // String, write as-is. + for (var l = 0; l < part.length;) { + var code = part.charCodeAt(l++); + if (0xD800 <= code && code < 0xDC00) { // Decode surrogate + var codeTrail = part.charCodeAt(l++); + if (0xDC00 <= codeTrail && codeTrail < 0xE000) + writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); + else + throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); + } + else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) + var len = 0xFFF - code + 2; + var seq = []; + for (var m = 0; m < len; m++) + seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. + + writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; + this.decodeTableSeq.push(seq); + } + else + writeTable[curAddr++] = code; // Basic char + } + } + else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. + var charCode = writeTable[curAddr - 1] + 1; + for (var l = 0; l < part; l++) + writeTable[curAddr++] = charCode++; + } + else + throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); + } + if (curAddr > 0xFF) + throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); +} + +// Encoder helpers +DBCSCodec.prototype._getEncodeBucket = function(uCode) { + var high = uCode >> 8; // This could be > 0xFF because of astral characters. + if (this.encodeTable[high] === undefined) + this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. + return this.encodeTable[high]; +} + +DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + if (bucket[low] <= SEQ_START) + this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. + else if (bucket[low] == UNASSIGNED) + bucket[low] = dbcsCode; +} + +DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { + + // Get the root of character tree according to first character of the sequence. + var uCode = seq[0]; + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + + var node; + if (bucket[low] <= SEQ_START) { + // There's already a sequence with - use it. + node = this.encodeTableSeq[SEQ_START-bucket[low]]; + } + else { + // There was no sequence object - allocate a new one. + node = {}; + if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. + bucket[low] = SEQ_START - this.encodeTableSeq.length; + this.encodeTableSeq.push(node); + } + + // Traverse the character tree, allocating new nodes as needed. + for (var j = 1; j < seq.length-1; j++) { + var oldVal = node[uCode]; + if (typeof oldVal === 'object') + node = oldVal; + else { + node = node[uCode] = {} + if (oldVal !== undefined) + node[DEF_CHAR] = oldVal + } + } + + // Set the leaf to given dbcsCode. + uCode = seq[seq.length-1]; + node[uCode] = dbcsCode; +} + +DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { + var node = this.decodeTables[nodeIdx]; + var hasValues = false; + var subNodeEmpty = {}; + for (var i = 0; i < 0x100; i++) { + var uCode = node[i]; + var mbCode = prefix + i; + if (skipEncodeChars[mbCode]) + continue; + + if (uCode >= 0) { + this._setEncodeChar(uCode, mbCode); + hasValues = true; + } else if (uCode <= NODE_START) { + var subNodeIdx = NODE_START - uCode; + if (!subNodeEmpty[subNodeIdx]) { // Skip empty subtrees (they are too large in gb18030). + var newPrefix = (mbCode << 8) >>> 0; // NOTE: '>>> 0' keeps 32-bit num positive. + if (this._fillEncodeTable(subNodeIdx, newPrefix, skipEncodeChars)) + hasValues = true; + else + subNodeEmpty[subNodeIdx] = true; + } + } else if (uCode <= SEQ_START) { + this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); + hasValues = true; + } + } + return hasValues; +} + + + +// == Encoder ================================================================== + +function DBCSEncoder(options, codec) { + // Encoder state + this.leadSurrogate = -1; + this.seqObj = undefined; + + // Static data + this.encodeTable = codec.encodeTable; + this.encodeTableSeq = codec.encodeTableSeq; + this.defaultCharSingleByte = codec.defCharSB; + this.gb18030 = codec.gb18030; +} + +DBCSEncoder.prototype.write = function(str) { + var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)), + leadSurrogate = this.leadSurrogate, + seqObj = this.seqObj, nextChar = -1, + i = 0, j = 0; + + while (true) { + // 0. Get next character. + if (nextChar === -1) { + if (i == str.length) break; + var uCode = str.charCodeAt(i++); + } + else { + var uCode = nextChar; + nextChar = -1; + } + + // 1. Handle surrogates. + if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. + if (uCode < 0xDC00) { // We've got lead surrogate. + if (leadSurrogate === -1) { + leadSurrogate = uCode; + continue; + } else { + leadSurrogate = uCode; + // Double lead surrogate found. + uCode = UNASSIGNED; + } + } else { // We've got trail surrogate. + if (leadSurrogate !== -1) { + uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); + leadSurrogate = -1; + } else { + // Incomplete surrogate pair - only trail surrogate found. + uCode = UNASSIGNED; + } + + } + } + else if (leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. + leadSurrogate = -1; + } + + // 2. Convert uCode character. + var dbcsCode = UNASSIGNED; + if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence + var resCode = seqObj[uCode]; + if (typeof resCode === 'object') { // Sequence continues. + seqObj = resCode; + continue; + + } else if (typeof resCode == 'number') { // Sequence finished. Write it. + dbcsCode = resCode; + + } else if (resCode == undefined) { // Current character is not part of the sequence. + + // Try default character for this sequence + resCode = seqObj[DEF_CHAR]; + if (resCode !== undefined) { + dbcsCode = resCode; // Found. Write it. + nextChar = uCode; // Current character will be written too in the next iteration. + + } else { + // TODO: What if we have no default? (resCode == undefined) + // Then, we should write first char of the sequence as-is and try the rest recursively. + // Didn't do it for now because no encoding has this situation yet. + // Currently, just skip the sequence and write current char. + } + } + seqObj = undefined; + } + else if (uCode >= 0) { // Regular character + var subtable = this.encodeTable[uCode >> 8]; + if (subtable !== undefined) + dbcsCode = subtable[uCode & 0xFF]; + + if (dbcsCode <= SEQ_START) { // Sequence start + seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; + continue; + } + + if (dbcsCode == UNASSIGNED && this.gb18030) { + // Use GB18030 algorithm to find character(s) to write. + var idx = findIdx(this.gb18030.uChars, uCode); + if (idx != -1) { + var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; + newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; + newBuf[j++] = 0x30 + dbcsCode; + continue; + } + } + } + + // 3. Write dbcsCode character. + if (dbcsCode === UNASSIGNED) + dbcsCode = this.defaultCharSingleByte; + + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else if (dbcsCode < 0x10000) { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + else if (dbcsCode < 0x1000000) { + newBuf[j++] = dbcsCode >> 16; + newBuf[j++] = (dbcsCode >> 8) & 0xFF; + newBuf[j++] = dbcsCode & 0xFF; + } else { + newBuf[j++] = dbcsCode >>> 24; + newBuf[j++] = (dbcsCode >>> 16) & 0xFF; + newBuf[j++] = (dbcsCode >>> 8) & 0xFF; + newBuf[j++] = dbcsCode & 0xFF; + } + } + + this.seqObj = seqObj; + this.leadSurrogate = leadSurrogate; + return newBuf.slice(0, j); +} + +DBCSEncoder.prototype.end = function() { + if (this.leadSurrogate === -1 && this.seqObj === undefined) + return; // All clean. Most often case. + + var newBuf = Buffer.alloc(10), j = 0; + + if (this.seqObj) { // We're in the sequence. + var dbcsCode = this.seqObj[DEF_CHAR]; + if (dbcsCode !== undefined) { // Write beginning of the sequence. + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + } else { + // See todo above. + } + this.seqObj = undefined; + } + + if (this.leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + newBuf[j++] = this.defaultCharSingleByte; + this.leadSurrogate = -1; + } + + return newBuf.slice(0, j); +} + +// Export for testing +DBCSEncoder.prototype.findIdx = findIdx; + + +// == Decoder ================================================================== + +function DBCSDecoder(options, codec) { + // Decoder state + this.nodeIdx = 0; + this.prevBytes = []; + + // Static data + this.decodeTables = codec.decodeTables; + this.decodeTableSeq = codec.decodeTableSeq; + this.defaultCharUnicode = codec.defaultCharUnicode; + this.gb18030 = codec.gb18030; +} + +DBCSDecoder.prototype.write = function(buf) { + var newBuf = Buffer.alloc(buf.length*2), + nodeIdx = this.nodeIdx, + prevBytes = this.prevBytes, prevOffset = this.prevBytes.length, + seqStart = -this.prevBytes.length, // idx of the start of current parsed sequence. + uCode; + + for (var i = 0, j = 0; i < buf.length; i++) { + var curByte = (i >= 0) ? buf[i] : prevBytes[i + prevOffset]; + + // Lookup in current trie node. + var uCode = this.decodeTables[nodeIdx][curByte]; + + if (uCode >= 0) { + // Normal character, just use it. + } + else if (uCode === UNASSIGNED) { // Unknown char. + // TODO: Callback with seq. + uCode = this.defaultCharUnicode.charCodeAt(0); + i = seqStart; // Skip one byte ('i' will be incremented by the for loop) and try to parse again. + } + else if (uCode === GB18030_CODE) { + if (i >= 3) { + var ptr = (buf[i-3]-0x81)*12600 + (buf[i-2]-0x30)*1260 + (buf[i-1]-0x81)*10 + (curByte-0x30); + } else { + var ptr = (prevBytes[i-3+prevOffset]-0x81)*12600 + + (((i-2 >= 0) ? buf[i-2] : prevBytes[i-2+prevOffset])-0x30)*1260 + + (((i-1 >= 0) ? buf[i-1] : prevBytes[i-1+prevOffset])-0x81)*10 + + (curByte-0x30); + } + var idx = findIdx(this.gb18030.gbChars, ptr); + uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; + } + else if (uCode <= NODE_START) { // Go to next trie node. + nodeIdx = NODE_START - uCode; + continue; + } + else if (uCode <= SEQ_START) { // Output a sequence of chars. + var seq = this.decodeTableSeq[SEQ_START - uCode]; + for (var k = 0; k < seq.length - 1; k++) { + uCode = seq[k]; + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + } + uCode = seq[seq.length-1]; + } + else + throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); + + // Write the character to buffer, handling higher planes using surrogate pair. + if (uCode >= 0x10000) { + uCode -= 0x10000; + var uCodeLead = 0xD800 | (uCode >> 10); + newBuf[j++] = uCodeLead & 0xFF; + newBuf[j++] = uCodeLead >> 8; + + uCode = 0xDC00 | (uCode & 0x3FF); + } + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + + // Reset trie node. + nodeIdx = 0; seqStart = i+1; + } + + this.nodeIdx = nodeIdx; + this.prevBytes = (seqStart >= 0) + ? Array.prototype.slice.call(buf, seqStart) + : prevBytes.slice(seqStart + prevOffset).concat(Array.prototype.slice.call(buf)); + + return newBuf.slice(0, j).toString('ucs2'); +} + +DBCSDecoder.prototype.end = function() { + var ret = ''; + + // Try to parse all remaining chars. + while (this.prevBytes.length > 0) { + // Skip 1 character in the buffer. + ret += this.defaultCharUnicode; + var bytesArr = this.prevBytes.slice(1); + + // Parse remaining as usual. + this.prevBytes = []; + this.nodeIdx = 0; + if (bytesArr.length > 0) + ret += this.write(bytesArr); + } + + this.prevBytes = []; + this.nodeIdx = 0; + return ret; +} + +// Binary search for GB18030. Returns largest i such that table[i] <= val. +function findIdx(table, val) { + if (table[0] > val) + return -1; + + var l = 0, r = table.length; + while (l < r-1) { // always table[l] <= val < table[r] + var mid = l + ((r-l+1) >> 1); + if (table[mid] <= val) + l = mid; + else + r = mid; + } + return l; +} + diff --git a/node_modules/iconv-lite/encodings/dbcs-data.js b/node_modules/iconv-lite/encodings/dbcs-data.js new file mode 100644 index 0000000..0d17e58 --- /dev/null +++ b/node_modules/iconv-lite/encodings/dbcs-data.js @@ -0,0 +1,188 @@ +"use strict"; + +// Description of supported double byte encodings and aliases. +// Tables are not require()-d until they are needed to speed up library load. +// require()-s are direct to support Browserify. + +module.exports = { + + // == Japanese/ShiftJIS ==================================================== + // All japanese encodings are based on JIS X set of standards: + // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. + // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. + // Has several variations in 1978, 1983, 1990 and 1997. + // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. + // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. + // 2 planes, first is superset of 0208, second - revised 0212. + // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) + + // Byte encodings are: + // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte + // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. + // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. + // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. + // 0x00-0x7F - lower part of 0201 + // 0x8E, 0xA1-0xDF - upper part of 0201 + // (0xA1-0xFE)x2 - 0208 plane (94x94). + // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). + // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. + // Used as-is in ISO2022 family. + // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, + // 0201-1976 Roman, 0208-1978, 0208-1983. + // * ISO2022-JP-1: Adds esc seq for 0212-1990. + // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. + // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. + // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. + // + // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. + // + // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html + + 'shiftjis': { + type: '_dbcs', + table: function() { return require('./tables/shiftjis.json') }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + encodeSkipVals: [{from: 0xED40, to: 0xF940}], + }, + 'csshiftjis': 'shiftjis', + 'mskanji': 'shiftjis', + 'sjis': 'shiftjis', + 'windows31j': 'shiftjis', + 'ms31j': 'shiftjis', + 'xsjis': 'shiftjis', + 'windows932': 'shiftjis', + 'ms932': 'shiftjis', + '932': 'shiftjis', + 'cp932': 'shiftjis', + + 'eucjp': { + type: '_dbcs', + table: function() { return require('./tables/eucjp.json') }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + }, + + // TODO: KDDI extension to Shift_JIS + // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. + // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. + + + // == Chinese/GBK ========================================================== + // http://en.wikipedia.org/wiki/GBK + // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder + + // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 + 'gb2312': 'cp936', + 'gb231280': 'cp936', + 'gb23121980': 'cp936', + 'csgb2312': 'cp936', + 'csiso58gb231280': 'cp936', + 'euccn': 'cp936', + + // Microsoft's CP936 is a subset and approximation of GBK. + 'windows936': 'cp936', + 'ms936': 'cp936', + '936': 'cp936', + 'cp936': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json') }, + }, + + // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. + 'gbk': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) }, + }, + 'xgbk': 'gbk', + 'isoir58': 'gbk', + + // GB18030 is an algorithmic extension of GBK. + // Main source: https://www.w3.org/TR/encoding/#gbk-encoder + // http://icu-project.org/docs/papers/gb18030.html + // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml + // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 + 'gb18030': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) }, + gb18030: function() { return require('./tables/gb18030-ranges.json') }, + encodeSkipVals: [0x80], + encodeAdd: {'€': 0xA2E3}, + }, + + 'chinese': 'gb18030', + + + // == Korean =============================================================== + // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. + 'windows949': 'cp949', + 'ms949': 'cp949', + '949': 'cp949', + 'cp949': { + type: '_dbcs', + table: function() { return require('./tables/cp949.json') }, + }, + + 'cseuckr': 'cp949', + 'csksc56011987': 'cp949', + 'euckr': 'cp949', + 'isoir149': 'cp949', + 'korean': 'cp949', + 'ksc56011987': 'cp949', + 'ksc56011989': 'cp949', + 'ksc5601': 'cp949', + + + // == Big5/Taiwan/Hong Kong ================================================ + // There are lots of tables for Big5 and cp950. Please see the following links for history: + // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html + // Variations, in roughly number of defined chars: + // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT + // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ + // * Big5-2003 (Taiwan standard) almost superset of cp950. + // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. + // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. + // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. + // Plus, it has 4 combining sequences. + // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 + // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. + // Implementations are not consistent within browsers; sometimes labeled as just big5. + // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. + // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 + // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. + // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt + // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt + // + // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder + // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. + + 'windows950': 'cp950', + 'ms950': 'cp950', + '950': 'cp950', + 'cp950': { + type: '_dbcs', + table: function() { return require('./tables/cp950.json') }, + }, + + // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. + 'big5': 'big5hkscs', + 'big5hkscs': { + type: '_dbcs', + table: function() { return require('./tables/cp950.json').concat(require('./tables/big5-added.json')) }, + encodeSkipVals: [ + // Although Encoding Standard says we should avoid encoding to HKSCS area (See Step 1 of + // https://encoding.spec.whatwg.org/#index-big5-pointer), we still do it to increase compatibility with ICU. + // But if a single unicode point can be encoded both as HKSCS and regular Big5, we prefer the latter. + 0x8e69, 0x8e6f, 0x8e7e, 0x8eab, 0x8eb4, 0x8ecd, 0x8ed0, 0x8f57, 0x8f69, 0x8f6e, 0x8fcb, 0x8ffe, + 0x906d, 0x907a, 0x90c4, 0x90dc, 0x90f1, 0x91bf, 0x92af, 0x92b0, 0x92b1, 0x92b2, 0x92d1, 0x9447, 0x94ca, + 0x95d9, 0x96fc, 0x9975, 0x9b76, 0x9b78, 0x9b7b, 0x9bc6, 0x9bde, 0x9bec, 0x9bf6, 0x9c42, 0x9c53, 0x9c62, + 0x9c68, 0x9c6b, 0x9c77, 0x9cbc, 0x9cbd, 0x9cd0, 0x9d57, 0x9d5a, 0x9dc4, 0x9def, 0x9dfb, 0x9ea9, 0x9eef, + 0x9efd, 0x9f60, 0x9fcb, 0xa077, 0xa0dc, 0xa0df, 0x8fcc, 0x92c8, 0x9644, 0x96ed, + + // Step 2 of https://encoding.spec.whatwg.org/#index-big5-pointer: Use last pointer for U+2550, U+255E, U+2561, U+256A, U+5341, or U+5345 + 0xa2a4, 0xa2a5, 0xa2a7, 0xa2a6, 0xa2cc, 0xa2ce, + ], + }, + + 'cnbig5': 'big5hkscs', + 'csbig5': 'big5hkscs', + 'xxbig5': 'big5hkscs', +}; diff --git a/node_modules/iconv-lite/encodings/index.js b/node_modules/iconv-lite/encodings/index.js new file mode 100644 index 0000000..d95c244 --- /dev/null +++ b/node_modules/iconv-lite/encodings/index.js @@ -0,0 +1,23 @@ +"use strict"; + +// Update this array if you add/rename/remove files in this directory. +// We support Browserify by skipping automatic module discovery and requiring modules directly. +var modules = [ + require("./internal"), + require("./utf32"), + require("./utf16"), + require("./utf7"), + require("./sbcs-codec"), + require("./sbcs-data"), + require("./sbcs-data-generated"), + require("./dbcs-codec"), + require("./dbcs-data"), +]; + +// Put all encoding/alias/codec definitions to single object and export it. +for (var i = 0; i < modules.length; i++) { + var module = modules[i]; + for (var enc in module) + if (Object.prototype.hasOwnProperty.call(module, enc)) + exports[enc] = module[enc]; +} diff --git a/node_modules/iconv-lite/encodings/internal.js b/node_modules/iconv-lite/encodings/internal.js new file mode 100644 index 0000000..dc1074f --- /dev/null +++ b/node_modules/iconv-lite/encodings/internal.js @@ -0,0 +1,198 @@ +"use strict"; +var Buffer = require("safer-buffer").Buffer; + +// Export Node.js internal encodings. + +module.exports = { + // Encodings + utf8: { type: "_internal", bomAware: true}, + cesu8: { type: "_internal", bomAware: true}, + unicode11utf8: "utf8", + + ucs2: { type: "_internal", bomAware: true}, + utf16le: "ucs2", + + binary: { type: "_internal" }, + base64: { type: "_internal" }, + hex: { type: "_internal" }, + + // Codec. + _internal: InternalCodec, +}; + +//------------------------------------------------------------------------------ + +function InternalCodec(codecOptions, iconv) { + this.enc = codecOptions.encodingName; + this.bomAware = codecOptions.bomAware; + + if (this.enc === "base64") + this.encoder = InternalEncoderBase64; + else if (this.enc === "cesu8") { + this.enc = "utf8"; // Use utf8 for decoding. + this.encoder = InternalEncoderCesu8; + + // Add decoder for versions of Node not supporting CESU-8 + if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { + this.decoder = InternalDecoderCesu8; + this.defaultCharUnicode = iconv.defaultCharUnicode; + } + } +} + +InternalCodec.prototype.encoder = InternalEncoder; +InternalCodec.prototype.decoder = InternalDecoder; + +//------------------------------------------------------------------------------ + +// We use node.js internal decoder. Its signature is the same as ours. +var StringDecoder = require('string_decoder').StringDecoder; + +if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. + StringDecoder.prototype.end = function() {}; + + +function InternalDecoder(options, codec) { + this.decoder = new StringDecoder(codec.enc); +} + +InternalDecoder.prototype.write = function(buf) { + if (!Buffer.isBuffer(buf)) { + buf = Buffer.from(buf); + } + + return this.decoder.write(buf); +} + +InternalDecoder.prototype.end = function() { + return this.decoder.end(); +} + + +//------------------------------------------------------------------------------ +// Encoder is mostly trivial + +function InternalEncoder(options, codec) { + this.enc = codec.enc; +} + +InternalEncoder.prototype.write = function(str) { + return Buffer.from(str, this.enc); +} + +InternalEncoder.prototype.end = function() { +} + + +//------------------------------------------------------------------------------ +// Except base64 encoder, which must keep its state. + +function InternalEncoderBase64(options, codec) { + this.prevStr = ''; +} + +InternalEncoderBase64.prototype.write = function(str) { + str = this.prevStr + str; + var completeQuads = str.length - (str.length % 4); + this.prevStr = str.slice(completeQuads); + str = str.slice(0, completeQuads); + + return Buffer.from(str, "base64"); +} + +InternalEncoderBase64.prototype.end = function() { + return Buffer.from(this.prevStr, "base64"); +} + + +//------------------------------------------------------------------------------ +// CESU-8 encoder is also special. + +function InternalEncoderCesu8(options, codec) { +} + +InternalEncoderCesu8.prototype.write = function(str) { + var buf = Buffer.alloc(str.length * 3), bufIdx = 0; + for (var i = 0; i < str.length; i++) { + var charCode = str.charCodeAt(i); + // Naive implementation, but it works because CESU-8 is especially easy + // to convert from UTF-16 (which all JS strings are encoded in). + if (charCode < 0x80) + buf[bufIdx++] = charCode; + else if (charCode < 0x800) { + buf[bufIdx++] = 0xC0 + (charCode >>> 6); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); + } + else { // charCode will always be < 0x10000 in javascript. + buf[bufIdx++] = 0xE0 + (charCode >>> 12); + buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); + } + } + return buf.slice(0, bufIdx); +} + +InternalEncoderCesu8.prototype.end = function() { +} + +//------------------------------------------------------------------------------ +// CESU-8 decoder is not implemented in Node v4.0+ + +function InternalDecoderCesu8(options, codec) { + this.acc = 0; + this.contBytes = 0; + this.accBytes = 0; + this.defaultCharUnicode = codec.defaultCharUnicode; +} + +InternalDecoderCesu8.prototype.write = function(buf) { + var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, + res = ''; + for (var i = 0; i < buf.length; i++) { + var curByte = buf[i]; + if ((curByte & 0xC0) !== 0x80) { // Leading byte + if (contBytes > 0) { // Previous code is invalid + res += this.defaultCharUnicode; + contBytes = 0; + } + + if (curByte < 0x80) { // Single-byte code + res += String.fromCharCode(curByte); + } else if (curByte < 0xE0) { // Two-byte code + acc = curByte & 0x1F; + contBytes = 1; accBytes = 1; + } else if (curByte < 0xF0) { // Three-byte code + acc = curByte & 0x0F; + contBytes = 2; accBytes = 1; + } else { // Four or more are not supported for CESU-8. + res += this.defaultCharUnicode; + } + } else { // Continuation byte + if (contBytes > 0) { // We're waiting for it. + acc = (acc << 6) | (curByte & 0x3f); + contBytes--; accBytes++; + if (contBytes === 0) { + // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) + if (accBytes === 2 && acc < 0x80 && acc > 0) + res += this.defaultCharUnicode; + else if (accBytes === 3 && acc < 0x800) + res += this.defaultCharUnicode; + else + // Actually add character. + res += String.fromCharCode(acc); + } + } else { // Unexpected continuation byte + res += this.defaultCharUnicode; + } + } + } + this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; + return res; +} + +InternalDecoderCesu8.prototype.end = function() { + var res = 0; + if (this.contBytes > 0) + res += this.defaultCharUnicode; + return res; +} diff --git a/node_modules/iconv-lite/encodings/sbcs-codec.js b/node_modules/iconv-lite/encodings/sbcs-codec.js new file mode 100644 index 0000000..abac5ff --- /dev/null +++ b/node_modules/iconv-lite/encodings/sbcs-codec.js @@ -0,0 +1,72 @@ +"use strict"; +var Buffer = require("safer-buffer").Buffer; + +// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that +// correspond to encoded bytes (if 128 - then lower half is ASCII). + +exports._sbcs = SBCSCodec; +function SBCSCodec(codecOptions, iconv) { + if (!codecOptions) + throw new Error("SBCS codec is called without the data.") + + // Prepare char buffer for decoding. + if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) + throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); + + if (codecOptions.chars.length === 128) { + var asciiString = ""; + for (var i = 0; i < 128; i++) + asciiString += String.fromCharCode(i); + codecOptions.chars = asciiString + codecOptions.chars; + } + + this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); + + // Encoding buffer. + var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); + + for (var i = 0; i < codecOptions.chars.length; i++) + encodeBuf[codecOptions.chars.charCodeAt(i)] = i; + + this.encodeBuf = encodeBuf; +} + +SBCSCodec.prototype.encoder = SBCSEncoder; +SBCSCodec.prototype.decoder = SBCSDecoder; + + +function SBCSEncoder(options, codec) { + this.encodeBuf = codec.encodeBuf; +} + +SBCSEncoder.prototype.write = function(str) { + var buf = Buffer.alloc(str.length); + for (var i = 0; i < str.length; i++) + buf[i] = this.encodeBuf[str.charCodeAt(i)]; + + return buf; +} + +SBCSEncoder.prototype.end = function() { +} + + +function SBCSDecoder(options, codec) { + this.decodeBuf = codec.decodeBuf; +} + +SBCSDecoder.prototype.write = function(buf) { + // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. + var decodeBuf = this.decodeBuf; + var newBuf = Buffer.alloc(buf.length*2); + var idx1 = 0, idx2 = 0; + for (var i = 0; i < buf.length; i++) { + idx1 = buf[i]*2; idx2 = i*2; + newBuf[idx2] = decodeBuf[idx1]; + newBuf[idx2+1] = decodeBuf[idx1+1]; + } + return newBuf.toString('ucs2'); +} + +SBCSDecoder.prototype.end = function() { +} diff --git a/node_modules/iconv-lite/encodings/sbcs-data-generated.js b/node_modules/iconv-lite/encodings/sbcs-data-generated.js new file mode 100644 index 0000000..9b48236 --- /dev/null +++ b/node_modules/iconv-lite/encodings/sbcs-data-generated.js @@ -0,0 +1,451 @@ +"use strict"; + +// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. +module.exports = { + "437": "cp437", + "737": "cp737", + "775": "cp775", + "850": "cp850", + "852": "cp852", + "855": "cp855", + "856": "cp856", + "857": "cp857", + "858": "cp858", + "860": "cp860", + "861": "cp861", + "862": "cp862", + "863": "cp863", + "864": "cp864", + "865": "cp865", + "866": "cp866", + "869": "cp869", + "874": "windows874", + "922": "cp922", + "1046": "cp1046", + "1124": "cp1124", + "1125": "cp1125", + "1129": "cp1129", + "1133": "cp1133", + "1161": "cp1161", + "1162": "cp1162", + "1163": "cp1163", + "1250": "windows1250", + "1251": "windows1251", + "1252": "windows1252", + "1253": "windows1253", + "1254": "windows1254", + "1255": "windows1255", + "1256": "windows1256", + "1257": "windows1257", + "1258": "windows1258", + "28591": "iso88591", + "28592": "iso88592", + "28593": "iso88593", + "28594": "iso88594", + "28595": "iso88595", + "28596": "iso88596", + "28597": "iso88597", + "28598": "iso88598", + "28599": "iso88599", + "28600": "iso885910", + "28601": "iso885911", + "28603": "iso885913", + "28604": "iso885914", + "28605": "iso885915", + "28606": "iso885916", + "windows874": { + "type": "_sbcs", + "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "win874": "windows874", + "cp874": "windows874", + "windows1250": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "win1250": "windows1250", + "cp1250": "windows1250", + "windows1251": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "win1251": "windows1251", + "cp1251": "windows1251", + "windows1252": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "win1252": "windows1252", + "cp1252": "windows1252", + "windows1253": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "win1253": "windows1253", + "cp1253": "windows1253", + "windows1254": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "win1254": "windows1254", + "cp1254": "windows1254", + "windows1255": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "win1255": "windows1255", + "cp1255": "windows1255", + "windows1256": { + "type": "_sbcs", + "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" + }, + "win1256": "windows1256", + "cp1256": "windows1256", + "windows1257": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" + }, + "win1257": "windows1257", + "cp1257": "windows1257", + "windows1258": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "win1258": "windows1258", + "cp1258": "windows1258", + "iso88591": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28591": "iso88591", + "iso88592": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "cp28592": "iso88592", + "iso88593": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�ݰħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" + }, + "cp28593": "iso88593", + "iso88594": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤Ĩϧ¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩšēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖרŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" + }, + "cp28594": "iso88594", + "iso88595": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" + }, + "cp28595": "iso88595", + "iso88596": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" + }, + "cp28596": "iso88596", + "iso88597": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "cp28597": "iso88597", + "iso88598": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "cp28598": "iso88598", + "iso88599": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "cp28599": "iso88599", + "iso885910": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨͧĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" + }, + "cp28600": "iso885910", + "iso885911": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "cp28601": "iso885911", + "iso885913": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" + }, + "cp28603": "iso885913", + "iso885914": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" + }, + "cp28604": "iso885914", + "iso885915": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28605": "iso885915", + "iso885916": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Чš©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" + }, + "cp28606": "iso885916", + "cp437": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm437": "cp437", + "csibm437": "cp437", + "cp737": { + "type": "_sbcs", + "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " + }, + "ibm737": "cp737", + "csibm737": "cp737", + "cp775": { + "type": "_sbcs", + "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£Ø×¤ĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " + }, + "ibm775": "cp775", + "csibm775": "cp775", + "cp850": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm850": "cp850", + "csibm850": "cp850", + "cp852": { + "type": "_sbcs", + "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " + }, + "ibm852": "cp852", + "csibm852": "cp852", + "cp855": { + "type": "_sbcs", + "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " + }, + "ibm855": "cp855", + "csibm855": "cp855", + "cp856": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm856": "cp856", + "csibm856": "cp856", + "cp857": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " + }, + "ibm857": "cp857", + "csibm857": "cp857", + "cp858": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm858": "cp858", + "csibm858": "cp858", + "cp860": { + "type": "_sbcs", + "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm860": "cp860", + "csibm860": "cp860", + "cp861": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm861": "cp861", + "csibm861": "cp861", + "cp862": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm862": "cp862", + "csibm862": "cp862", + "cp863": { + "type": "_sbcs", + "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm863": "cp863", + "csibm863": "cp863", + "cp864": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" + }, + "ibm864": "cp864", + "csibm864": "cp864", + "cp865": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm865": "cp865", + "csibm865": "cp865", + "cp866": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " + }, + "ibm866": "cp866", + "csibm866": "cp866", + "cp869": { + "type": "_sbcs", + "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " + }, + "ibm869": "cp869", + "csibm869": "cp869", + "cp922": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖרÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" + }, + "ibm922": "cp922", + "csibm922": "cp922", + "cp1046": { + "type": "_sbcs", + "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" + }, + "ibm1046": "cp1046", + "csibm1046": "cp1046", + "cp1124": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" + }, + "ibm1124": "cp1124", + "csibm1124": "cp1124", + "cp1125": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " + }, + "ibm1125": "cp1125", + "csibm1125": "cp1125", + "cp1129": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1129": "cp1129", + "csibm1129": "cp1129", + "cp1133": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" + }, + "ibm1133": "cp1133", + "csibm1133": "cp1133", + "cp1161": { + "type": "_sbcs", + "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " + }, + "ibm1161": "cp1161", + "csibm1161": "cp1161", + "cp1162": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "ibm1162": "cp1162", + "csibm1162": "cp1162", + "cp1163": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1163": "cp1163", + "csibm1163": "cp1163", + "maccroatian": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" + }, + "maccyrillic": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "macgreek": { + "type": "_sbcs", + "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" + }, + "maciceland": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macroman": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macromania": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macthai": { + "type": "_sbcs", + "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" + }, + "macturkish": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macukraine": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "koi8r": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8u": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8ru": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8t": { + "type": "_sbcs", + "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "armscii8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" + }, + "rk1048": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "tcvn": { + "type": "_sbcs", + "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" + }, + "georgianacademy": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "georgianps": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "pt154": { + "type": "_sbcs", + "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "viscii": { + "type": "_sbcs", + "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" + }, + "iso646cn": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "iso646jp": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "hproman8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" + }, + "macintosh": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "ascii": { + "type": "_sbcs", + "chars": "��������������������������������������������������������������������������������������������������������������������������������" + }, + "tis620": { + "type": "_sbcs", + "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + } +} \ No newline at end of file diff --git a/node_modules/iconv-lite/encodings/sbcs-data.js b/node_modules/iconv-lite/encodings/sbcs-data.js new file mode 100644 index 0000000..066f904 --- /dev/null +++ b/node_modules/iconv-lite/encodings/sbcs-data.js @@ -0,0 +1,179 @@ +"use strict"; + +// Manually added data to be used by sbcs codec in addition to generated one. + +module.exports = { + // Not supported by iconv, not sure why. + "10029": "maccenteuro", + "maccenteuro": { + "type": "_sbcs", + "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" + }, + + "808": "cp808", + "ibm808": "cp808", + "cp808": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " + }, + + "mik": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + + "cp720": { + "type": "_sbcs", + "chars": "\x80\x81éâ\x84à\x86çêëèïî\x8d\x8e\x8f\x90\u0651\u0652ô¤ـûùءآأؤ£إئابةتثجحخدذرزسشص«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ضطظعغفµقكلمنهوىي≡\u064b\u064c\u064d\u064e\u064f\u0650≈°∙·√ⁿ²■\u00a0" + }, + + // Aliases of generated encodings. + "ascii8bit": "ascii", + "usascii": "ascii", + "ansix34": "ascii", + "ansix341968": "ascii", + "ansix341986": "ascii", + "csascii": "ascii", + "cp367": "ascii", + "ibm367": "ascii", + "isoir6": "ascii", + "iso646us": "ascii", + "iso646irv": "ascii", + "us": "ascii", + + "latin1": "iso88591", + "latin2": "iso88592", + "latin3": "iso88593", + "latin4": "iso88594", + "latin5": "iso88599", + "latin6": "iso885910", + "latin7": "iso885913", + "latin8": "iso885914", + "latin9": "iso885915", + "latin10": "iso885916", + + "csisolatin1": "iso88591", + "csisolatin2": "iso88592", + "csisolatin3": "iso88593", + "csisolatin4": "iso88594", + "csisolatincyrillic": "iso88595", + "csisolatinarabic": "iso88596", + "csisolatingreek" : "iso88597", + "csisolatinhebrew": "iso88598", + "csisolatin5": "iso88599", + "csisolatin6": "iso885910", + + "l1": "iso88591", + "l2": "iso88592", + "l3": "iso88593", + "l4": "iso88594", + "l5": "iso88599", + "l6": "iso885910", + "l7": "iso885913", + "l8": "iso885914", + "l9": "iso885915", + "l10": "iso885916", + + "isoir14": "iso646jp", + "isoir57": "iso646cn", + "isoir100": "iso88591", + "isoir101": "iso88592", + "isoir109": "iso88593", + "isoir110": "iso88594", + "isoir144": "iso88595", + "isoir127": "iso88596", + "isoir126": "iso88597", + "isoir138": "iso88598", + "isoir148": "iso88599", + "isoir157": "iso885910", + "isoir166": "tis620", + "isoir179": "iso885913", + "isoir199": "iso885914", + "isoir203": "iso885915", + "isoir226": "iso885916", + + "cp819": "iso88591", + "ibm819": "iso88591", + + "cyrillic": "iso88595", + + "arabic": "iso88596", + "arabic8": "iso88596", + "ecma114": "iso88596", + "asmo708": "iso88596", + + "greek" : "iso88597", + "greek8" : "iso88597", + "ecma118" : "iso88597", + "elot928" : "iso88597", + + "hebrew": "iso88598", + "hebrew8": "iso88598", + + "turkish": "iso88599", + "turkish8": "iso88599", + + "thai": "iso885911", + "thai8": "iso885911", + + "celtic": "iso885914", + "celtic8": "iso885914", + "isoceltic": "iso885914", + + "tis6200": "tis620", + "tis62025291": "tis620", + "tis62025330": "tis620", + + "10000": "macroman", + "10006": "macgreek", + "10007": "maccyrillic", + "10079": "maciceland", + "10081": "macturkish", + + "cspc8codepage437": "cp437", + "cspc775baltic": "cp775", + "cspc850multilingual": "cp850", + "cspcp852": "cp852", + "cspc862latinhebrew": "cp862", + "cpgr": "cp869", + + "msee": "cp1250", + "mscyrl": "cp1251", + "msansi": "cp1252", + "msgreek": "cp1253", + "msturk": "cp1254", + "mshebr": "cp1255", + "msarab": "cp1256", + "winbaltrim": "cp1257", + + "cp20866": "koi8r", + "20866": "koi8r", + "ibm878": "koi8r", + "cskoi8r": "koi8r", + + "cp21866": "koi8u", + "21866": "koi8u", + "ibm1168": "koi8u", + + "strk10482002": "rk1048", + + "tcvn5712": "tcvn", + "tcvn57121": "tcvn", + + "gb198880": "iso646cn", + "cn": "iso646cn", + + "csiso14jisc6220ro": "iso646jp", + "jisc62201969ro": "iso646jp", + "jp": "iso646jp", + + "cshproman8": "hproman8", + "r8": "hproman8", + "roman8": "hproman8", + "xroman8": "hproman8", + "ibm1051": "hproman8", + + "mac": "macintosh", + "csmacintosh": "macintosh", +}; + diff --git a/node_modules/iconv-lite/encodings/tables/big5-added.json b/node_modules/iconv-lite/encodings/tables/big5-added.json new file mode 100644 index 0000000..3c3d3c2 --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/big5-added.json @@ -0,0 +1,122 @@ +[ +["8740","䏰䰲䘃䖦䕸𧉧䵷䖳𧲱䳢𧳅㮕䜶䝄䱇䱀𤊿𣘗𧍒𦺋𧃒䱗𪍑䝏䗚䲅𧱬䴇䪤䚡𦬣爥𥩔𡩣𣸆𣽡晍囻"], +["8767","綕夝𨮹㷴霴𧯯寛𡵞媤㘥𩺰嫑宷峼杮薓𩥅瑡璝㡵𡵓𣚞𦀡㻬"], +["87a1","𥣞㫵竼龗𤅡𨤍𣇪𠪊𣉞䌊蒄龖鐯䤰蘓墖靊鈘秐稲晠権袝瑌篅枂稬剏遆㓦珄𥶹瓆鿇垳䤯呌䄱𣚎堘穲𧭥讏䚮𦺈䆁𥶙箮𢒼鿈𢓁𢓉𢓌鿉蔄𣖻䂴鿊䓡𪷿拁灮鿋"], +["8840","㇀",4,"𠄌㇅𠃑𠃍㇆㇇𠃋𡿨㇈𠃊㇉㇊㇋㇌𠄎㇍㇎ĀÁǍÀĒÉĚÈŌÓǑÒ࿿Ê̄Ế࿿Ê̌ỀÊāáǎàɑēéěèīíǐìōóǒòūúǔùǖǘǚ"], +["88a1","ǜü࿿ê̄ế࿿ê̌ềêɡ⏚⏛"], +["8940","𪎩𡅅"], +["8943","攊"], +["8946","丽滝鵎釟"], +["894c","𧜵撑会伨侨兖兴农凤务动医华发变团声处备夲头学实実岚庆总斉柾栄桥济炼电纤纬纺织经统缆缷艺苏药视设询车轧轮"], +["89a1","琑糼緍楆竉刧"], +["89ab","醌碸酞肼"], +["89b0","贋胶𠧧"], +["89b5","肟黇䳍鷉鸌䰾𩷶𧀎鸊𪄳㗁"], +["89c1","溚舾甙"], +["89c5","䤑马骏龙禇𨑬𡷊𠗐𢫦两亁亀亇亿仫伷㑌侽㹈倃傈㑽㒓㒥円夅凛凼刅争剹劐匧㗇厩㕑厰㕓参吣㕭㕲㚁咓咣咴咹哐哯唘唣唨㖘唿㖥㖿嗗㗅"], +["8a40","𧶄唥"], +["8a43","𠱂𠴕𥄫喐𢳆㧬𠍁蹆𤶸𩓥䁓𨂾睺𢰸㨴䟕𨅝𦧲𤷪擝𠵼𠾴𠳕𡃴撍蹾𠺖𠰋𠽤𢲩𨉖𤓓"], +["8a64","𠵆𩩍𨃩䟴𤺧𢳂骲㩧𩗴㿭㔆𥋇𩟔𧣈𢵄鵮頕"], +["8a76","䏙𦂥撴哣𢵌𢯊𡁷㧻𡁯"], +["8aa1","𦛚𦜖𧦠擪𥁒𠱃蹨𢆡𨭌𠜱"], +["8aac","䠋𠆩㿺塳𢶍"], +["8ab2","𤗈𠓼𦂗𠽌𠶖啹䂻䎺"], +["8abb","䪴𢩦𡂝膪飵𠶜捹㧾𢝵跀嚡摼㹃"], +["8ac9","𪘁𠸉𢫏𢳉"], +["8ace","𡃈𣧂㦒㨆𨊛㕸𥹉𢃇噒𠼱𢲲𩜠㒼氽𤸻"], +["8adf","𧕴𢺋𢈈𪙛𨳍𠹺𠰴𦠜羓𡃏𢠃𢤹㗻𥇣𠺌𠾍𠺪㾓𠼰𠵇𡅏𠹌"], +["8af6","𠺫𠮩𠵈𡃀𡄽㿹𢚖搲𠾭"], +["8b40","𣏴𧘹𢯎𠵾𠵿𢱑𢱕㨘𠺘𡃇𠼮𪘲𦭐𨳒𨶙𨳊閪哌苄喹"], +["8b55","𩻃鰦骶𧝞𢷮煀腭胬尜𦕲脴㞗卟𨂽醶𠻺𠸏𠹷𠻻㗝𤷫㘉𠳖嚯𢞵𡃉𠸐𠹸𡁸𡅈𨈇𡑕𠹹𤹐𢶤婔𡀝𡀞𡃵𡃶垜𠸑"], +["8ba1","𧚔𨋍𠾵𠹻𥅾㜃𠾶𡆀𥋘𪊽𤧚𡠺𤅷𨉼墙剨㘚𥜽箲孨䠀䬬鼧䧧鰟鮍𥭴𣄽嗻㗲嚉丨夂𡯁屮靑𠂆乛亻㔾尣彑忄㣺扌攵歺氵氺灬爫丬犭𤣩罒礻糹罓𦉪㓁"], +["8bde","𦍋耂肀𦘒𦥑卝衤见𧢲讠贝钅镸长门𨸏韦页风飞饣𩠐鱼鸟黄歯龜丷𠂇阝户钢"], +["8c40","倻淾𩱳龦㷉袏𤅎灷峵䬠𥇍㕙𥴰愢𨨲辧釶熑朙玺𣊁𪄇㲋𡦀䬐磤琂冮𨜏䀉橣𪊺䈣蘏𠩯稪𩥇𨫪靕灍匤𢁾鏴盙𨧣龧矝亣俰傼丯众龨吴綋墒壐𡶶庒庙忂𢜒斋"], +["8ca1","𣏹椙橃𣱣泿"], +["8ca7","爀𤔅玌㻛𤨓嬕璹讃𥲤𥚕窓篬糃繬苸薗龩袐龪躹龫迏蕟駠鈡龬𨶹𡐿䁱䊢娚"], +["8cc9","顨杫䉶圽"], +["8cce","藖𤥻芿𧄍䲁𦵴嵻𦬕𦾾龭龮宖龯曧繛湗秊㶈䓃𣉖𢞖䎚䔶"], +["8ce6","峕𣬚諹屸㴒𣕑嵸龲煗䕘𤃬𡸣䱷㥸㑊𠆤𦱁諌侴𠈹妿腬顖𩣺弻"], +["8d40","𠮟"], +["8d42","𢇁𨥭䄂䚻𩁹㼇龳𪆵䃸㟖䛷𦱆䅼𨚲𧏿䕭㣔𥒚䕡䔛䶉䱻䵶䗪㿈𤬏㙡䓞䒽䇭崾嵈嵖㷼㠏嶤嶹㠠㠸幂庽弥徃㤈㤔㤿㥍惗愽峥㦉憷憹懏㦸戬抐拥挘㧸嚱"], +["8da1","㨃揢揻搇摚㩋擀崕嘡龟㪗斆㪽旿晓㫲暒㬢朖㭂枤栀㭘桊梄㭲㭱㭻椉楃牜楤榟榅㮼槖㯝橥橴橱檂㯬檙㯲檫檵櫔櫶殁毁毪汵沪㳋洂洆洦涁㳯涤涱渕渘温溆𨧀溻滢滚齿滨滩漤漴㵆𣽁澁澾㵪㵵熷岙㶊瀬㶑灐灔灯灿炉𠌥䏁㗱𠻘"], +["8e40","𣻗垾𦻓焾𥟠㙎榢𨯩孴穉𥣡𩓙穥穽𥦬窻窰竂竃燑𦒍䇊竚竝竪䇯咲𥰁笋筕笩𥌎𥳾箢筯莜𥮴𦱿篐萡箒箸𥴠㶭𥱥蒒篺簆簵𥳁籄粃𤢂粦晽𤕸糉糇糦籴糳糵糎"], +["8ea1","繧䔝𦹄絝𦻖璍綉綫焵綳緒𤁗𦀩緤㴓緵𡟹緥𨍭縝𦄡𦅚繮纒䌫鑬縧罀罁罇礶𦋐駡羗𦍑羣𡙡𠁨䕜𣝦䔃𨌺翺𦒉者耈耝耨耯𪂇𦳃耻耼聡𢜔䦉𦘦𣷣𦛨朥肧𨩈脇脚墰𢛶汿𦒘𤾸擧𡒊舘𡡞橓𤩥𤪕䑺舩𠬍𦩒𣵾俹𡓽蓢荢𦬊𤦧𣔰𡝳𣷸芪椛芳䇛"], +["8f40","蕋苐茚𠸖𡞴㛁𣅽𣕚艻苢茘𣺋𦶣𦬅𦮗𣗎㶿茝嗬莅䔋𦶥莬菁菓㑾𦻔橗蕚㒖𦹂𢻯葘𥯤葱㷓䓤檧葊𣲵祘蒨𦮖𦹷𦹃蓞萏莑䒠蒓蓤𥲑䉀𥳀䕃蔴嫲𦺙䔧蕳䔖枿蘖"], +["8fa1","𨘥𨘻藁𧂈蘂𡖂𧃍䕫䕪蘨㙈𡢢号𧎚虾蝱𪃸蟮𢰧螱蟚蠏噡虬桖䘏衅衆𧗠𣶹𧗤衞袜䙛袴袵揁装睷𧜏覇覊覦覩覧覼𨨥觧𧤤𧪽誜瞓釾誐𧩙竩𧬺𣾏䜓𧬸煼謌謟𥐰𥕥謿譌譍誩𤩺讐讛誯𡛟䘕衏貛𧵔𧶏貫㜥𧵓賖𧶘𧶽贒贃𡤐賛灜贑𤳉㻐起"], +["9040","趩𨀂𡀔𤦊㭼𨆼𧄌竧躭躶軃鋔輙輭𨍥𨐒辥錃𪊟𠩐辳䤪𨧞𨔽𣶻廸𣉢迹𪀔𨚼𨔁𢌥㦀𦻗逷𨔼𧪾遡𨕬𨘋邨𨜓郄𨛦邮都酧㫰醩釄粬𨤳𡺉鈎沟鉁鉢𥖹銹𨫆𣲛𨬌𥗛"], +["90a1","𠴱錬鍫𨫡𨯫炏嫃𨫢𨫥䥥鉄𨯬𨰹𨯿鍳鑛躼閅閦鐦閠濶䊹𢙺𨛘𡉼𣸮䧟氜陻隖䅬隣𦻕懚隶磵𨫠隽双䦡𦲸𠉴𦐐𩂯𩃥𤫑𡤕𣌊霱虂霶䨏䔽䖅𤫩灵孁霛靜𩇕靗孊𩇫靟鐥僐𣂷𣂼鞉鞟鞱鞾韀韒韠𥑬韮琜𩐳響韵𩐝𧥺䫑頴頳顋顦㬎𧅵㵑𠘰𤅜"], +["9140","𥜆飊颷飈飇䫿𦴧𡛓喰飡飦飬鍸餹𤨩䭲𩡗𩤅駵騌騻騐驘𥜥㛄𩂱𩯕髠髢𩬅髴䰎鬔鬭𨘀倴鬴𦦨㣃𣁽魐魀𩴾婅𡡣鮎𤉋鰂鯿鰌𩹨鷔𩾷𪆒𪆫𪃡𪄣𪇟鵾鶃𪄴鸎梈"], +["91a1","鷄𢅛𪆓𪈠𡤻𪈳鴹𪂹𪊴麐麕麞麢䴴麪麯𤍤黁㭠㧥㴝伲㞾𨰫鼂鼈䮖鐤𦶢鼗鼖鼹嚟嚊齅馸𩂋韲葿齢齩竜龎爖䮾𤥵𤦻煷𤧸𤍈𤩑玞𨯚𡣺禟𨥾𨸶鍩鏳𨩄鋬鎁鏋𨥬𤒹爗㻫睲穃烐𤑳𤏸煾𡟯炣𡢾𣖙㻇𡢅𥐯𡟸㜢𡛻𡠹㛡𡝴𡣑𥽋㜣𡛀坛𤨥𡏾𡊨"], +["9240","𡏆𡒶蔃𣚦蔃葕𤦔𧅥𣸱𥕜𣻻𧁒䓴𣛮𩦝𦼦柹㜳㰕㷧塬𡤢栐䁗𣜿𤃡𤂋𤄏𦰡哋嚞𦚱嚒𠿟𠮨𠸍鏆𨬓鎜仸儫㠙𤐶亼𠑥𠍿佋侊𥙑婨𠆫𠏋㦙𠌊𠐔㐵伩𠋀𨺳𠉵諚𠈌亘"], +["92a1","働儍侢伃𤨎𣺊佂倮偬傁俌俥偘僼兙兛兝兞湶𣖕𣸹𣺿浲𡢄𣺉冨凃𠗠䓝𠒣𠒒𠒑赺𨪜𠜎剙劤𠡳勡鍮䙺熌𤎌𠰠𤦬𡃤槑𠸝瑹㻞璙琔瑖玘䮎𤪼𤂍叐㖄爏𤃉喴𠍅响𠯆圝鉝雴鍦埝垍坿㘾壋媙𨩆𡛺𡝯𡜐娬妸銏婾嫏娒𥥆𡧳𡡡𤊕㛵洅瑃娡𥺃"], +["9340","媁𨯗𠐓鏠璌𡌃焅䥲鐈𨧻鎽㞠尞岞幞幈𡦖𡥼𣫮廍孏𡤃𡤄㜁𡢠㛝𡛾㛓脪𨩇𡶺𣑲𨦨弌弎𡤧𡞫婫𡜻孄蘔𧗽衠恾𢡠𢘫忛㺸𢖯𢖾𩂈𦽳懀𠀾𠁆𢘛憙憘恵𢲛𢴇𤛔𩅍"], +["93a1","摱𤙥𢭪㨩𢬢𣑐𩣪𢹸挷𪑛撶挱揑𤧣𢵧护𢲡搻敫楲㯴𣂎𣊭𤦉𣊫唍𣋠𡣙𩐿曎𣊉𣆳㫠䆐𥖄𨬢𥖏𡛼𥕛𥐥磮𣄃𡠪𣈴㑤𣈏𣆂𤋉暎𦴤晫䮓昰𧡰𡷫晣𣋒𣋡昞𥡲㣑𣠺𣞼㮙𣞢𣏾瓐㮖枏𤘪梶栞㯄檾㡣𣟕𤒇樳橒櫉欅𡤒攑梘橌㯗橺歗𣿀𣲚鎠鋲𨯪𨫋"], +["9440","銉𨀞𨧜鑧涥漋𤧬浧𣽿㶏渄𤀼娽渊塇洤硂焻𤌚𤉶烱牐犇犔𤞏𤜥兹𤪤𠗫瑺𣻸𣙟𤩊𤤗𥿡㼆㺱𤫟𨰣𣼵悧㻳瓌琼鎇琷䒟𦷪䕑疃㽣𤳙𤴆㽘畕癳𪗆㬙瑨𨫌𤦫𤦎㫻"], +["94a1","㷍𤩎㻿𤧅𤣳釺圲鍂𨫣𡡤僟𥈡𥇧睸𣈲眎眏睻𤚗𣞁㩞𤣰琸璛㺿𤪺𤫇䃈𤪖𦆮錇𥖁砞碍碈磒珐祙𧝁𥛣䄎禛蒖禥樭𣻺稺秴䅮𡛦䄲鈵秱𠵌𤦌𠊙𣶺𡝮㖗啫㕰㚪𠇔𠰍竢婙𢛵𥪯𥪜娍𠉛磰娪𥯆竾䇹籝籭䈑𥮳𥺼𥺦糍𤧹𡞰粎籼粮檲緜縇緓罎𦉡"], +["9540","𦅜𧭈綗𥺂䉪𦭵𠤖柖𠁎𣗏埄𦐒𦏸𤥢翝笧𠠬𥫩𥵃笌𥸎駦虅驣樜𣐿㧢𤧷𦖭騟𦖠蒀𧄧𦳑䓪脷䐂胆脉腂𦞴飃𦩂艢艥𦩑葓𦶧蘐𧈛媆䅿𡡀嬫𡢡嫤𡣘蚠蜨𣶏蠭𧐢娂"], +["95a1","衮佅袇袿裦襥襍𥚃襔𧞅𧞄𨯵𨯙𨮜𨧹㺭蒣䛵䛏㟲訽訜𩑈彍鈫𤊄旔焩烄𡡅鵭貟賩𧷜妚矃姰䍮㛔踪躧𤰉輰轊䋴汘澻𢌡䢛潹溋𡟚鯩㚵𤤯邻邗啱䤆醻鐄𨩋䁢𨫼鐧𨰝𨰻蓥訫閙閧閗閖𨴴瑅㻂𤣿𤩂𤏪㻧𣈥随𨻧𨹦𨹥㻌𤧭𤩸𣿮琒瑫㻼靁𩂰"], +["9640","桇䨝𩂓𥟟靝鍨𨦉𨰦𨬯𦎾銺嬑譩䤼珹𤈛鞛靱餸𠼦巁𨯅𤪲頟𩓚鋶𩗗釥䓀𨭐𤩧𨭤飜𨩅㼀鈪䤥萔餻饍𧬆㷽馛䭯馪驜𨭥𥣈檏騡嫾騯𩣱䮐𩥈馼䮽䮗鍽塲𡌂堢𤦸"], +["96a1","𡓨硄𢜟𣶸棅㵽鑘㤧慐𢞁𢥫愇鱏鱓鱻鰵鰐魿鯏𩸭鮟𪇵𪃾鴡䲮𤄄鸘䲰鴌𪆴𪃭𪃳𩤯鶥蒽𦸒𦿟𦮂藼䔳𦶤𦺄𦷰萠藮𦸀𣟗𦁤秢𣖜𣙀䤭𤧞㵢鏛銾鍈𠊿碹鉷鑍俤㑀遤𥕝砽硔碶硋𡝗𣇉𤥁㚚佲濚濙瀞瀞吔𤆵垻壳垊鴖埗焴㒯𤆬燫𦱀𤾗嬨𡞵𨩉"], +["9740","愌嫎娋䊼𤒈㜬䭻𨧼鎻鎸𡣖𠼝葲𦳀𡐓𤋺𢰦𤏁妔𣶷𦝁綨𦅛𦂤𤦹𤦋𨧺鋥珢㻩璴𨭣𡢟㻡𤪳櫘珳珻㻖𤨾𤪔𡟙𤩦𠎧𡐤𤧥瑈𤤖炥𤥶銄珦鍟𠓾錱𨫎𨨖鎆𨯧𥗕䤵𨪂煫"], +["97a1","𤥃𠳿嚤𠘚𠯫𠲸唂秄𡟺緾𡛂𤩐𡡒䔮鐁㜊𨫀𤦭妰𡢿𡢃𧒄媡㛢𣵛㚰鉟婹𨪁𡡢鍴㳍𠪴䪖㦊僴㵩㵌𡎜煵䋻𨈘渏𩃤䓫浗𧹏灧沯㳖𣿭𣸭渂漌㵯𠏵畑㚼㓈䚀㻚䡱姄鉮䤾轁𨰜𦯀堒埈㛖𡑒烾𤍢𤩱𢿣𡊰𢎽梹楧𡎘𣓥𧯴𣛟𨪃𣟖𣏺𤲟樚𣚭𦲷萾䓟䓎"], +["9840","𦴦𦵑𦲂𦿞漗𧄉茽𡜺菭𦲀𧁓𡟛妉媂𡞳婡婱𡤅𤇼㜭姯𡜼㛇熎鎐暚𤊥婮娫𤊓樫𣻹𧜶𤑛𤋊焝𤉙𨧡侰𦴨峂𤓎𧹍𤎽樌𤉖𡌄炦焳𤏩㶥泟勇𤩏繥姫崯㷳彜𤩝𡟟綤萦"], +["98a1","咅𣫺𣌀𠈔坾𠣕𠘙㿥𡾞𪊶瀃𩅛嵰玏糓𨩙𩐠俈翧狍猐𧫴猸猹𥛶獁獈㺩𧬘遬燵𤣲珡臶㻊県㻑沢国琙琞琟㻢㻰㻴㻺瓓㼎㽓畂畭畲疍㽼痈痜㿀癍㿗癴㿜発𤽜熈嘣覀塩䀝睃䀹条䁅㗛瞘䁪䁯属瞾矋売砘点砜䂨砹硇硑硦葈𥔵礳栃礲䄃"], +["9940","䄉禑禙辻稆込䅧窑䆲窼艹䇄竏竛䇏両筢筬筻簒簛䉠䉺类粜䊌粸䊔糭输烀𠳏総緔緐緽羮羴犟䎗耠耥笹耮耱联㷌垴炠肷胩䏭脌猪脎脒畠脔䐁㬹腖腙腚"], +["99a1","䐓堺腼膄䐥膓䐭膥埯臁臤艔䒏芦艶苊苘苿䒰荗险榊萅烵葤惣蒈䔄蒾蓡蓸蔐蔸蕒䔻蕯蕰藠䕷虲蚒蚲蛯际螋䘆䘗袮裿褤襇覑𧥧訩訸誔誴豑賔賲贜䞘塟跃䟭仮踺嗘坔蹱嗵躰䠷軎転軤軭軲辷迁迊迌逳駄䢭飠鈓䤞鈨鉘鉫銱銮銿"], +["9a40","鋣鋫鋳鋴鋽鍃鎄鎭䥅䥑麿鐗匁鐝鐭鐾䥪鑔鑹锭関䦧间阳䧥枠䨤靀䨵鞲韂噔䫤惨颹䬙飱塄餎餙冴餜餷饂饝饢䭰駅䮝騼鬏窃魩鮁鯝鯱鯴䱭鰠㝯𡯂鵉鰺"], +["9aa1","黾噐鶓鶽鷀鷼银辶鹻麬麱麽黆铜黢黱黸竈齄𠂔𠊷𠎠椚铃妬𠓗塀铁㞹𠗕𠘕𠙶𡚺块煳𠫂𠫍𠮿呪吆𠯋咞𠯻𠰻𠱓𠱥𠱼惧𠲍噺𠲵𠳝𠳭𠵯𠶲𠷈楕鰯螥𠸄𠸎𠻗𠾐𠼭𠹳尠𠾼帋𡁜𡁏𡁶朞𡁻𡂈𡂖㙇𡂿𡃓𡄯𡄻卤蒭𡋣𡍵𡌶讁𡕷𡘙𡟃𡟇乸炻𡠭𡥪"], +["9b40","𡨭𡩅𡰪𡱰𡲬𡻈拃𡻕𡼕熘桕𢁅槩㛈𢉼𢏗𢏺𢜪𢡱𢥏苽𢥧𢦓𢫕覥𢫨辠𢬎鞸𢬿顇骽𢱌"], +["9b62","𢲈𢲷𥯨𢴈𢴒𢶷𢶕𢹂𢽴𢿌𣀳𣁦𣌟𣏞徱晈暿𧩹𣕧𣗳爁𤦺矗𣘚𣜖纇𠍆墵朎"], +["9ba1","椘𣪧𧙗𥿢𣸑𣺹𧗾𢂚䣐䪸𤄙𨪚𤋮𤌍𤀻𤌴𤎖𤩅𠗊凒𠘑妟𡺨㮾𣳿𤐄𤓖垈𤙴㦛𤜯𨗨𩧉㝢𢇃譞𨭎駖𤠒𤣻𤨕爉𤫀𠱸奥𤺥𤾆𠝹軚𥀬劏圿煱𥊙𥐙𣽊𤪧喼𥑆𥑮𦭒釔㑳𥔿𧘲𥕞䜘𥕢𥕦𥟇𤤿𥡝偦㓻𣏌惞𥤃䝼𨥈𥪮𥮉𥰆𡶐垡煑澶𦄂𧰒遖𦆲𤾚譢𦐂𦑊"], +["9c40","嵛𦯷輶𦒄𡤜諪𤧶𦒈𣿯𦔒䯀𦖿𦚵𢜛鑥𥟡憕娧晉侻嚹𤔡𦛼乪𤤴陖涏𦲽㘘襷𦞙𦡮𦐑𦡞營𦣇筂𩃀𠨑𦤦鄄𦤹穅鷰𦧺騦𦨭㙟𦑩𠀡禃𦨴𦭛崬𣔙菏𦮝䛐𦲤画补𦶮墶"], +["9ca1","㜜𢖍𧁋𧇍㱔𧊀𧊅銁𢅺𧊋錰𧋦𤧐氹钟𧑐𠻸蠧裵𢤦𨑳𡞱溸𤨪𡠠㦤㚹尐秣䔿暶𩲭𩢤襃𧟌𧡘囖䃟𡘊㦡𣜯𨃨𡏅熭荦𧧝𩆨婧䲷𧂯𨦫𧧽𧨊𧬋𧵦𤅺筃祾𨀉澵𪋟樃𨌘厢𦸇鎿栶靝𨅯𨀣𦦵𡏭𣈯𨁈嶅𨰰𨂃圕頣𨥉嶫𤦈斾槕叒𤪥𣾁㰑朶𨂐𨃴𨄮𡾡𨅏"], +["9d40","𨆉𨆯𨈚𨌆𨌯𨎊㗊𨑨𨚪䣺揦𨥖砈鉕𨦸䏲𨧧䏟𨧨𨭆𨯔姸𨰉輋𨿅𩃬筑𩄐𩄼㷷𩅞𤫊运犏嚋𩓧𩗩𩖰𩖸𩜲𩣑𩥉𩥪𩧃𩨨𩬎𩵚𩶛纟𩻸𩼣䲤镇𪊓熢𪋿䶑递𪗋䶜𠲜达嗁"], +["9da1","辺𢒰边𤪓䔉繿潖檱仪㓤𨬬𧢝㜺躀𡟵𨀤𨭬𨮙𧨾𦚯㷫𧙕𣲷𥘵𥥖亚𥺁𦉘嚿𠹭踎孭𣺈𤲞揞拐𡟶𡡻攰嘭𥱊吚𥌑㷆𩶘䱽嘢嘞罉𥻘奵𣵀蝰东𠿪𠵉𣚺脗鵞贘瘻鱅癎瞹鍅吲腈苷嘥脲萘肽嗪祢噃吖𠺝㗎嘅嗱曱𨋢㘭甴嗰喺咗啲𠱁𠲖廐𥅈𠹶𢱢"], +["9e40","𠺢麫絚嗞𡁵抝靭咔賍燶酶揼掹揾啩𢭃鱲𢺳冚㓟𠶧冧呍唞唓癦踭𦢊疱肶蠄螆裇膶萜𡃁䓬猄𤜆宐茋𦢓噻𢛴𧴯𤆣𧵳𦻐𧊶酰𡇙鈈𣳼𪚩𠺬𠻹牦𡲢䝎𤿂𧿹𠿫䃺"], +["9ea1","鱝攟𢶠䣳𤟠𩵼𠿬𠸊恢𧖣𠿭"], +["9ead","𦁈𡆇熣纎鵐业丄㕷嬍沲卧㚬㧜卽㚥𤘘墚𤭮舭呋垪𥪕𠥹"], +["9ec5","㩒𢑥獴𩺬䴉鯭𣳾𩼰䱛𤾩𩖞𩿞葜𣶶𧊲𦞳𣜠挮紥𣻷𣸬㨪逈勌㹴㙺䗩𠒎癀嫰𠺶硺𧼮墧䂿噼鮋嵴癔𪐴麅䳡痹㟻愙𣃚𤏲"], +["9ef5","噝𡊩垧𤥣𩸆刴𧂮㖭汊鵼"], +["9f40","籖鬹埞𡝬屓擓𩓐𦌵𧅤蚭𠴨𦴢𤫢𠵱"], +["9f4f","凾𡼏嶎霃𡷑麁遌笟鬂峑箣扨挵髿篏鬪籾鬮籂粆鰕篼鬉鼗鰛𤤾齚啳寃俽麘俲剠㸆勑坧偖妷帒韈鶫轜呩鞴饀鞺匬愰"], +["9fa1","椬叚鰊鴂䰻陁榀傦畆𡝭駚剳"], +["9fae","酙隁酜"], +["9fb2","酑𨺗捿𦴣櫊嘑醎畺抅𠏼獏籰𥰡𣳽"], +["9fc1","𤤙盖鮝个𠳔莾衂"], +["9fc9","届槀僭坺刟巵从氱𠇲伹咜哚劚趂㗾弌㗳"], +["9fdb","歒酼龥鮗頮颴骺麨麄煺笔"], +["9fe7","毺蠘罸"], +["9feb","嘠𪙊蹷齓"], +["9ff0","跔蹏鸜踁抂𨍽踨蹵竓𤩷稾磘泪詧瘇"], +["a040","𨩚鼦泎蟖痃𪊲硓咢贌狢獱謭猂瓱賫𤪻蘯徺袠䒷"], +["a055","𡠻𦸅"], +["a058","詾𢔛"], +["a05b","惽癧髗鵄鍮鮏蟵"], +["a063","蠏賷猬霡鮰㗖犲䰇籑饊𦅙慙䰄麖慽"], +["a073","坟慯抦戹拎㩜懢厪𣏵捤栂㗒"], +["a0a1","嵗𨯂迚𨸹"], +["a0a6","僙𡵆礆匲阸𠼻䁥"], +["a0ae","矾"], +["a0b0","糂𥼚糚稭聦聣絍甅瓲覔舚朌聢𧒆聛瓰脃眤覉𦟌畓𦻑螩蟎臈螌詉貭譃眫瓸蓚㘵榲趦"], +["a0d4","覩瑨涹蟁𤀑瓧㷛煶悤憜㳑煢恷"], +["a0e2","罱𨬭牐惩䭾删㰘𣳇𥻗𧙖𥔱𡥄𡋾𩤃𦷜𧂭峁𦆭𨨏𣙷𠃮𦡆𤼎䕢嬟𦍌齐麦𦉫"], +["a3c0","␀",31,"␡"], +["c6a1","①",9,"⑴",9,"ⅰ",9,"丶丿亅亠冂冖冫勹匸卩厶夊宀巛⼳广廴彐彡攴无疒癶辵隶¨ˆヽヾゝゞ〃仝々〆〇ー[]✽ぁ",23], +["c740","す",58,"ァアィイ"], +["c7a1","ゥ",81,"А",5,"ЁЖ",4], +["c840","Л",26,"ёж",25,"⇧↸↹㇏𠃌乚𠂊刂䒑"], +["c8a1","龰冈龱𧘇"], +["c8cd","¬¦'"㈱№℡゛゜⺀⺄⺆⺇⺈⺊⺌⺍⺕⺜⺝⺥⺧⺪⺬⺮⺶⺼⺾⻆⻊⻌⻍⻏⻖⻗⻞⻣"], +["c8f5","ʃɐɛɔɵœøŋʊɪ"], +["f9fe","■"], +["fa40","𠕇鋛𠗟𣿅蕌䊵珯况㙉𤥂𨧤鍄𡧛苮𣳈砼杄拟𤤳𨦪𠊠𦮳𡌅侫𢓭倈𦴩𧪄𣘀𤪱𢔓倩𠍾徤𠎀𠍇滛𠐟偽儁㑺儎顬㝃萖𤦤𠒇兠𣎴兪𠯿𢃼𠋥𢔰𠖎𣈳𡦃宂蝽𠖳𣲙冲冸"], +["faa1","鴴凉减凑㳜凓𤪦决凢卂凭菍椾𣜭彻刋刦刼劵剗劔効勅簕蕂勠蘍𦬓包𨫞啉滙𣾀𠥔𣿬匳卄𠯢泋𡜦栛珕恊㺪㣌𡛨燝䒢卭却𨚫卾卿𡖖𡘓矦厓𨪛厠厫厮玧𥝲㽙玜叁叅汉义埾叙㪫𠮏叠𣿫𢶣叶𠱷吓灹唫晗浛呭𦭓𠵴啝咏咤䞦𡜍𠻝㶴𠵍"], +["fb40","𨦼𢚘啇䳭启琗喆喩嘅𡣗𤀺䕒𤐵暳𡂴嘷曍𣊊暤暭噍噏磱囱鞇叾圀囯园𨭦㘣𡉏坆𤆥汮炋坂㚱𦱾埦𡐖堃𡑔𤍣堦𤯵塜墪㕡壠壜𡈼壻寿坃𪅐𤉸鏓㖡够梦㛃湙"], +["fba1","𡘾娤啓𡚒蔅姉𠵎𦲁𦴪𡟜姙𡟻𡞲𦶦浱𡠨𡛕姹𦹅媫婣㛦𤦩婷㜈媖瑥嫓𦾡𢕔㶅𡤑㜲𡚸広勐孶斈孼𧨎䀄䡝𠈄寕慠𡨴𥧌𠖥寳宝䴐尅𡭄尓珎尔𡲥𦬨屉䣝岅峩峯嶋𡷹𡸷崐崘嵆𡺤岺巗苼㠭𤤁𢁉𢅳芇㠶㯂帮檊幵幺𤒼𠳓厦亷廐厨𡝱帉廴𨒂"], +["fc40","廹廻㢠廼栾鐛弍𠇁弢㫞䢮𡌺强𦢈𢏐彘𢑱彣鞽𦹮彲鍀𨨶徧嶶㵟𥉐𡽪𧃸𢙨釖𠊞𨨩怱暅𡡷㥣㷇㘹垐𢞴祱㹀悞悤悳𤦂𤦏𧩓璤僡媠慤萤慂慈𦻒憁凴𠙖憇宪𣾷"], +["fca1","𢡟懓𨮝𩥝懐㤲𢦀𢣁怣慜攞掋𠄘担𡝰拕𢸍捬𤧟㨗搸揸𡎎𡟼撐澊𢸶頔𤂌𥜝擡擥鑻㩦携㩗敍漖𤨨𤨣斅敭敟𣁾斵𤥀䬷旑䃘𡠩无旣忟𣐀昘𣇷𣇸晄𣆤𣆥晋𠹵晧𥇦晳晴𡸽𣈱𨗴𣇈𥌓矅𢣷馤朂𤎜𤨡㬫槺𣟂杞杧杢𤇍𩃭柗䓩栢湐鈼栁𣏦𦶠桝"], +["fd40","𣑯槡樋𨫟楳棃𣗍椁椀㴲㨁𣘼㮀枬楡𨩊䋼椶榘㮡𠏉荣傐槹𣙙𢄪橅𣜃檝㯳枱櫈𩆜㰍欝𠤣惞欵歴𢟍溵𣫛𠎵𡥘㝀吡𣭚毡𣻼毜氷𢒋𤣱𦭑汚舦汹𣶼䓅𣶽𤆤𤤌𤤀"], +["fda1","𣳉㛥㳫𠴲鮃𣇹𢒑羏样𦴥𦶡𦷫涖浜湼漄𤥿𤂅𦹲蔳𦽴凇沜渝萮𨬡港𣸯瑓𣾂秌湏媑𣁋濸㜍澝𣸰滺𡒗𤀽䕕鏰潄潜㵎潴𩅰㴻澟𤅄濓𤂑𤅕𤀹𣿰𣾴𤄿凟𤅖𤅗𤅀𦇝灋灾炧炁烌烕烖烟䄄㷨熴熖𤉷焫煅媈煊煮岜𤍥煏鍢𤋁焬𤑚𤨧𤨢熺𨯨炽爎"], +["fe40","鑂爕夑鑃爤鍁𥘅爮牀𤥴梽牕牗㹕𣁄栍漽犂猪猫𤠣𨠫䣭𨠄猨献珏玪𠰺𦨮珉瑉𤇢𡛧𤨤昣㛅𤦷𤦍𤧻珷琕椃𤨦琹𠗃㻗瑜𢢭瑠𨺲瑇珤瑶莹瑬㜰瑴鏱樬璂䥓𤪌"], +["fea1","𤅟𤩹𨮏孆𨰃𡢞瓈𡦈甎瓩甞𨻙𡩋寗𨺬鎅畍畊畧畮𤾂㼄𤴓疎瑝疞疴瘂瘬癑癏癯癶𦏵皐臯㟸𦤑𦤎皡皥皷盌𦾟葢𥂝𥅽𡸜眞眦着撯𥈠睘𣊬瞯𨥤𨥨𡛁矴砉𡍶𤨒棊碯磇磓隥礮𥗠磗礴碱𧘌辸袄𨬫𦂃𢘜禆褀椂禀𥡗禝𧬹礼禩渪𧄦㺨秆𩄍秔"] +] diff --git a/node_modules/iconv-lite/encodings/tables/cp936.json b/node_modules/iconv-lite/encodings/tables/cp936.json new file mode 100644 index 0000000..49ddb9a --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/cp936.json @@ -0,0 +1,264 @@ +[ +["0","\u0000",127,"€"], +["8140","丂丄丅丆丏丒丗丟丠両丣並丩丮丯丱丳丵丷丼乀乁乂乄乆乊乑乕乗乚乛乢乣乤乥乧乨乪",5,"乲乴",9,"乿",6,"亇亊"], +["8180","亐亖亗亙亜亝亞亣亪亯亰亱亴亶亷亸亹亼亽亾仈仌仏仐仒仚仛仜仠仢仦仧仩仭仮仯仱仴仸仹仺仼仾伀伂",6,"伋伌伒",4,"伜伝伡伣伨伩伬伭伮伱伳伵伷伹伻伾",4,"佄佅佇",5,"佒佔佖佡佢佦佨佪佫佭佮佱佲併佷佸佹佺佽侀侁侂侅來侇侊侌侎侐侒侓侕侖侘侙侚侜侞侟価侢"], +["8240","侤侫侭侰",4,"侶",8,"俀俁係俆俇俈俉俋俌俍俒",4,"俙俛俠俢俤俥俧俫俬俰俲俴俵俶俷俹俻俼俽俿",11], +["8280","個倎倐們倓倕倖倗倛倝倞倠倢倣値倧倫倯",10,"倻倽倿偀偁偂偄偅偆偉偊偋偍偐",4,"偖偗偘偙偛偝",7,"偦",5,"偭",8,"偸偹偺偼偽傁傂傃傄傆傇傉傊傋傌傎",20,"傤傦傪傫傭",4,"傳",6,"傼"], +["8340","傽",17,"僐",5,"僗僘僙僛",10,"僨僩僪僫僯僰僱僲僴僶",4,"僼",9,"儈"], +["8380","儉儊儌",5,"儓",13,"儢",28,"兂兇兊兌兎兏児兒兓兗兘兙兛兝",4,"兣兤兦內兩兪兯兲兺兾兿冃冄円冇冊冋冎冏冐冑冓冔冘冚冝冞冟冡冣冦",4,"冭冮冴冸冹冺冾冿凁凂凃凅凈凊凍凎凐凒",5], +["8440","凘凙凚凜凞凟凢凣凥",5,"凬凮凱凲凴凷凾刄刅刉刋刌刏刐刓刔刕刜刞刟刡刢刣別刦刧刪刬刯刱刲刴刵刼刾剄",5,"剋剎剏剒剓剕剗剘"], +["8480","剙剚剛剝剟剠剢剣剤剦剨剫剬剭剮剰剱剳",9,"剾劀劃",4,"劉",6,"劑劒劔",6,"劜劤劥劦劧劮劯劰労",9,"勀勁勂勄勅勆勈勊勌勍勎勏勑勓勔動勗務",5,"勠勡勢勣勥",10,"勱",7,"勻勼勽匁匂匃匄匇匉匊匋匌匎"], +["8540","匑匒匓匔匘匛匜匞匟匢匤匥匧匨匩匫匬匭匯",9,"匼匽區卂卄卆卋卌卍卐協単卙卛卝卥卨卪卬卭卲卶卹卻卼卽卾厀厁厃厇厈厊厎厏"], +["8580","厐",4,"厖厗厙厛厜厞厠厡厤厧厪厫厬厭厯",6,"厷厸厹厺厼厽厾叀參",4,"収叏叐叒叓叕叚叜叝叞叡叢叧叴叺叾叿吀吂吅吇吋吔吘吙吚吜吢吤吥吪吰吳吶吷吺吽吿呁呂呄呅呇呉呌呍呎呏呑呚呝",4,"呣呥呧呩",7,"呴呹呺呾呿咁咃咅咇咈咉咊咍咑咓咗咘咜咞咟咠咡"], +["8640","咢咥咮咰咲咵咶咷咹咺咼咾哃哅哊哋哖哘哛哠",4,"哫哬哯哰哱哴",5,"哻哾唀唂唃唄唅唈唊",4,"唒唓唕",5,"唜唝唞唟唡唥唦"], +["8680","唨唩唫唭唲唴唵唶唸唹唺唻唽啀啂啅啇啈啋",4,"啑啒啓啔啗",4,"啝啞啟啠啢啣啨啩啫啯",5,"啹啺啽啿喅喆喌喍喎喐喒喓喕喖喗喚喛喞喠",6,"喨",8,"喲喴営喸喺喼喿",4,"嗆嗇嗈嗊嗋嗎嗏嗐嗕嗗",4,"嗞嗠嗢嗧嗩嗭嗮嗰嗱嗴嗶嗸",4,"嗿嘂嘃嘄嘅"], +["8740","嘆嘇嘊嘋嘍嘐",7,"嘙嘚嘜嘝嘠嘡嘢嘥嘦嘨嘩嘪嘫嘮嘯嘰嘳嘵嘷嘸嘺嘼嘽嘾噀",11,"噏",4,"噕噖噚噛噝",4], +["8780","噣噥噦噧噭噮噯噰噲噳噴噵噷噸噹噺噽",7,"嚇",6,"嚐嚑嚒嚔",14,"嚤",10,"嚰",6,"嚸嚹嚺嚻嚽",12,"囋",8,"囕囖囘囙囜団囥",5,"囬囮囯囲図囶囷囸囻囼圀圁圂圅圇國",6], +["8840","園",9,"圝圞圠圡圢圤圥圦圧圫圱圲圴",4,"圼圽圿坁坃坄坅坆坈坉坋坒",4,"坘坙坢坣坥坧坬坮坰坱坲坴坵坸坹坺坽坾坿垀"], +["8880","垁垇垈垉垊垍",4,"垔",6,"垜垝垞垟垥垨垪垬垯垰垱垳垵垶垷垹",8,"埄",6,"埌埍埐埑埓埖埗埛埜埞埡埢埣埥",7,"埮埰埱埲埳埵埶執埻埼埾埿堁堃堄堅堈堉堊堌堎堏堐堒堓堔堖堗堘堚堛堜堝堟堢堣堥",4,"堫",4,"報堲堳場堶",7], +["8940","堾",5,"塅",6,"塎塏塐塒塓塕塖塗塙",4,"塟",5,"塦",4,"塭",16,"塿墂墄墆墇墈墊墋墌"], +["8980","墍",4,"墔",4,"墛墜墝墠",7,"墪",17,"墽墾墿壀壂壃壄壆",10,"壒壓壔壖",13,"壥",5,"壭壯壱売壴壵壷壸壺",7,"夃夅夆夈",4,"夎夐夑夒夓夗夘夛夝夞夠夡夢夣夦夨夬夰夲夳夵夶夻"], +["8a40","夽夾夿奀奃奅奆奊奌奍奐奒奓奙奛",4,"奡奣奤奦",12,"奵奷奺奻奼奾奿妀妅妉妋妌妎妏妐妑妔妕妘妚妛妜妝妟妠妡妢妦"], +["8a80","妧妬妭妰妱妳",5,"妺妼妽妿",6,"姇姈姉姌姍姎姏姕姖姙姛姞",4,"姤姦姧姩姪姫姭",11,"姺姼姽姾娀娂娊娋娍娎娏娐娒娔娕娖娗娙娚娛娝娞娡娢娤娦娧娨娪",6,"娳娵娷",4,"娽娾娿婁",4,"婇婈婋",9,"婖婗婘婙婛",5], +["8b40","婡婣婤婥婦婨婩婫",8,"婸婹婻婼婽婾媀",17,"媓",6,"媜",13,"媫媬"], +["8b80","媭",4,"媴媶媷媹",4,"媿嫀嫃",5,"嫊嫋嫍",4,"嫓嫕嫗嫙嫚嫛嫝嫞嫟嫢嫤嫥嫧嫨嫪嫬",4,"嫲",22,"嬊",11,"嬘",25,"嬳嬵嬶嬸",7,"孁",6], +["8c40","孈",7,"孒孖孞孠孡孧孨孫孭孮孯孲孴孶孷學孹孻孼孾孿宂宆宊宍宎宐宑宒宔宖実宧宨宩宬宭宮宯宱宲宷宺宻宼寀寁寃寈寉寊寋寍寎寏"], +["8c80","寑寔",8,"寠寢寣實寧審",4,"寯寱",6,"寽対尀専尃尅將專尋尌對導尐尒尓尗尙尛尞尟尠尡尣尦尨尩尪尫尭尮尯尰尲尳尵尶尷屃屄屆屇屌屍屒屓屔屖屗屘屚屛屜屝屟屢層屧",6,"屰屲",6,"屻屼屽屾岀岃",4,"岉岊岋岎岏岒岓岕岝",4,"岤",4], +["8d40","岪岮岯岰岲岴岶岹岺岻岼岾峀峂峃峅",5,"峌",5,"峓",5,"峚",6,"峢峣峧峩峫峬峮峯峱",9,"峼",4], +["8d80","崁崄崅崈",5,"崏",4,"崕崗崘崙崚崜崝崟",4,"崥崨崪崫崬崯",4,"崵",7,"崿",7,"嵈嵉嵍",10,"嵙嵚嵜嵞",10,"嵪嵭嵮嵰嵱嵲嵳嵵",12,"嶃",21,"嶚嶛嶜嶞嶟嶠"], +["8e40","嶡",21,"嶸",12,"巆",6,"巎",12,"巜巟巠巣巤巪巬巭"], +["8e80","巰巵巶巸",4,"巿帀帄帇帉帊帋帍帎帒帓帗帞",7,"帨",4,"帯帰帲",4,"帹帺帾帿幀幁幃幆",5,"幍",6,"幖",4,"幜幝幟幠幣",14,"幵幷幹幾庁庂広庅庈庉庌庍庎庒庘庛庝庡庢庣庤庨",4,"庮",4,"庴庺庻庼庽庿",6], +["8f40","廆廇廈廋",5,"廔廕廗廘廙廚廜",11,"廩廫",8,"廵廸廹廻廼廽弅弆弇弉弌弍弎弐弒弔弖弙弚弜弝弞弡弢弣弤"], +["8f80","弨弫弬弮弰弲",6,"弻弽弾弿彁",14,"彑彔彙彚彛彜彞彟彠彣彥彧彨彫彮彯彲彴彵彶彸彺彽彾彿徃徆徍徎徏徑従徔徖徚徛徝從徟徠徢",5,"復徫徬徯",5,"徶徸徹徺徻徾",4,"忇忈忊忋忎忓忔忕忚忛応忞忟忢忣忥忦忨忩忬忯忰忲忳忴忶忷忹忺忼怇"], +["9040","怈怉怋怌怐怑怓怗怘怚怞怟怢怣怤怬怭怮怰",4,"怶",4,"怽怾恀恄",6,"恌恎恏恑恓恔恖恗恘恛恜恞恟恠恡恥恦恮恱恲恴恵恷恾悀"], +["9080","悁悂悅悆悇悈悊悋悎悏悐悑悓悕悗悘悙悜悞悡悢悤悥悧悩悪悮悰悳悵悶悷悹悺悽",7,"惇惈惉惌",4,"惒惓惔惖惗惙惛惞惡",4,"惪惱惲惵惷惸惻",4,"愂愃愄愅愇愊愋愌愐",4,"愖愗愘愙愛愜愝愞愡愢愥愨愩愪愬",18,"慀",6], +["9140","慇慉態慍慏慐慒慓慔慖",6,"慞慟慠慡慣慤慥慦慩",6,"慱慲慳慴慶慸",18,"憌憍憏",4,"憕"], +["9180","憖",6,"憞",8,"憪憫憭",9,"憸",5,"憿懀懁懃",4,"應懌",4,"懓懕",16,"懧",13,"懶",8,"戀",5,"戇戉戓戔戙戜戝戞戠戣戦戧戨戩戫戭戯戰戱戲戵戶戸",4,"扂扄扅扆扊"], +["9240","扏扐払扖扗扙扚扜",6,"扤扥扨扱扲扴扵扷扸扺扻扽抁抂抃抅抆抇抈抋",5,"抔抙抜抝択抣抦抧抩抪抭抮抯抰抲抳抴抶抷抸抺抾拀拁"], +["9280","拃拋拏拑拕拝拞拠拡拤拪拫拰拲拵拸拹拺拻挀挃挄挅挆挊挋挌挍挏挐挒挓挔挕挗挘挙挜挦挧挩挬挭挮挰挱挳",5,"挻挼挾挿捀捁捄捇捈捊捑捒捓捔捖",7,"捠捤捥捦捨捪捫捬捯捰捲捳捴捵捸捹捼捽捾捿掁掃掄掅掆掋掍掑掓掔掕掗掙",6,"採掤掦掫掯掱掲掵掶掹掻掽掿揀"], +["9340","揁揂揃揅揇揈揊揋揌揑揓揔揕揗",6,"揟揢揤",4,"揫揬揮揯揰揱揳揵揷揹揺揻揼揾搃搄搆",4,"損搎搑搒搕",5,"搝搟搢搣搤"], +["9380","搥搧搨搩搫搮",5,"搵",4,"搻搼搾摀摂摃摉摋",6,"摓摕摖摗摙",4,"摟",7,"摨摪摫摬摮",9,"摻",6,"撃撆撈",8,"撓撔撗撘撚撛撜撝撟",4,"撥撦撧撨撪撫撯撱撲撳撴撶撹撻撽撾撿擁擃擄擆",6,"擏擑擓擔擕擖擙據"], +["9440","擛擜擝擟擠擡擣擥擧",24,"攁",7,"攊",7,"攓",4,"攙",8], +["9480","攢攣攤攦",4,"攬攭攰攱攲攳攷攺攼攽敀",4,"敆敇敊敋敍敎敐敒敓敔敗敘敚敜敟敠敡敤敥敧敨敩敪敭敮敯敱敳敵敶數",14,"斈斉斊斍斎斏斒斔斕斖斘斚斝斞斠斢斣斦斨斪斬斮斱",7,"斺斻斾斿旀旂旇旈旉旊旍旐旑旓旔旕旘",7,"旡旣旤旪旫"], +["9540","旲旳旴旵旸旹旻",4,"昁昄昅昇昈昉昋昍昐昑昒昖昗昘昚昛昜昞昡昢昣昤昦昩昪昫昬昮昰昲昳昷",4,"昽昿晀時晄",6,"晍晎晐晑晘"], +["9580","晙晛晜晝晞晠晢晣晥晧晩",4,"晱晲晳晵晸晹晻晼晽晿暀暁暃暅暆暈暉暊暋暍暎暏暐暒暓暔暕暘",4,"暞",8,"暩",4,"暯",4,"暵暶暷暸暺暻暼暽暿",25,"曚曞",7,"曧曨曪",5,"曱曵曶書曺曻曽朁朂會"], +["9640","朄朅朆朇朌朎朏朑朒朓朖朘朙朚朜朞朠",5,"朧朩朮朰朲朳朶朷朸朹朻朼朾朿杁杄杅杇杊杋杍杒杔杕杗",4,"杝杢杣杤杦杧杫杬杮東杴杶"], +["9680","杸杹杺杻杽枀枂枃枅枆枈枊枌枍枎枏枑枒枓枔枖枙枛枟枠枡枤枦枩枬枮枱枲枴枹",7,"柂柅",9,"柕柖柗柛柟柡柣柤柦柧柨柪柫柭柮柲柵",7,"柾栁栂栃栄栆栍栐栒栔栕栘",4,"栞栟栠栢",6,"栫",6,"栴栵栶栺栻栿桇桋桍桏桒桖",5], +["9740","桜桝桞桟桪桬",7,"桵桸",8,"梂梄梇",7,"梐梑梒梔梕梖梘",9,"梣梤梥梩梪梫梬梮梱梲梴梶梷梸"], +["9780","梹",6,"棁棃",5,"棊棌棎棏棐棑棓棔棖棗棙棛",4,"棡棢棤",9,"棯棲棳棴棶棷棸棻棽棾棿椀椂椃椄椆",4,"椌椏椑椓",11,"椡椢椣椥",7,"椮椯椱椲椳椵椶椷椸椺椻椼椾楀楁楃",16,"楕楖楘楙楛楜楟"], +["9840","楡楢楤楥楧楨楩楪楬業楯楰楲",4,"楺楻楽楾楿榁榃榅榊榋榌榎",5,"榖榗榙榚榝",9,"榩榪榬榮榯榰榲榳榵榶榸榹榺榼榽"], +["9880","榾榿槀槂",7,"構槍槏槑槒槓槕",5,"槜槝槞槡",11,"槮槯槰槱槳",9,"槾樀",9,"樋",11,"標",5,"樠樢",5,"権樫樬樭樮樰樲樳樴樶",6,"樿",4,"橅橆橈",7,"橑",6,"橚"], +["9940","橜",4,"橢橣橤橦",10,"橲",6,"橺橻橽橾橿檁檂檃檅",8,"檏檒",4,"檘",7,"檡",5], +["9980","檧檨檪檭",114,"欥欦欨",6], +["9a40","欯欰欱欳欴欵欶欸欻欼欽欿歀歁歂歄歅歈歊歋歍",11,"歚",7,"歨歩歫",13,"歺歽歾歿殀殅殈"], +["9a80","殌殎殏殐殑殔殕殗殘殙殜",4,"殢",7,"殫",7,"殶殸",6,"毀毃毄毆",4,"毌毎毐毑毘毚毜",4,"毢",7,"毬毭毮毰毱毲毴毶毷毸毺毻毼毾",6,"氈",4,"氎氒気氜氝氞氠氣氥氫氬氭氱氳氶氷氹氺氻氼氾氿汃汄汅汈汋",4,"汑汒汓汖汘"], +["9b40","汙汚汢汣汥汦汧汫",4,"汱汳汵汷汸決汻汼汿沀沄沇沊沋沍沎沑沒沕沖沗沘沚沜沝沞沠沢沨沬沯沰沴沵沶沷沺泀況泂泃泆泇泈泋泍泎泏泑泒泘"], +["9b80","泙泚泜泝泟泤泦泧泩泬泭泲泴泹泿洀洂洃洅洆洈洉洊洍洏洐洑洓洔洕洖洘洜洝洟",5,"洦洨洩洬洭洯洰洴洶洷洸洺洿浀浂浄浉浌浐浕浖浗浘浛浝浟浡浢浤浥浧浨浫浬浭浰浱浲浳浵浶浹浺浻浽",4,"涃涄涆涇涊涋涍涏涐涒涖",4,"涜涢涥涬涭涰涱涳涴涶涷涹",5,"淁淂淃淈淉淊"], +["9c40","淍淎淏淐淒淓淔淕淗淚淛淜淟淢淣淥淧淨淩淪淭淯淰淲淴淵淶淸淺淽",7,"渆渇済渉渋渏渒渓渕渘渙減渜渞渟渢渦渧渨渪測渮渰渱渳渵"], +["9c80","渶渷渹渻",7,"湅",7,"湏湐湑湒湕湗湙湚湜湝湞湠",10,"湬湭湯",14,"満溁溂溄溇溈溊",4,"溑",6,"溙溚溛溝溞溠溡溣溤溦溨溩溫溬溭溮溰溳溵溸溹溼溾溿滀滃滄滅滆滈滉滊滌滍滎滐滒滖滘滙滛滜滝滣滧滪",5], +["9d40","滰滱滲滳滵滶滷滸滺",7,"漃漄漅漇漈漊",4,"漐漑漒漖",9,"漡漢漣漥漦漧漨漬漮漰漲漴漵漷",6,"漿潀潁潂"], +["9d80","潃潄潅潈潉潊潌潎",9,"潙潚潛潝潟潠潡潣潤潥潧",5,"潯潰潱潳潵潶潷潹潻潽",6,"澅澆澇澊澋澏",12,"澝澞澟澠澢",4,"澨",10,"澴澵澷澸澺",5,"濁濃",5,"濊",6,"濓",10,"濟濢濣濤濥"], +["9e40","濦",7,"濰",32,"瀒",7,"瀜",6,"瀤",6], +["9e80","瀫",9,"瀶瀷瀸瀺",17,"灍灎灐",13,"灟",11,"灮灱灲灳灴灷灹灺灻災炁炂炃炄炆炇炈炋炌炍炏炐炑炓炗炘炚炛炞",12,"炰炲炴炵炶為炾炿烄烅烆烇烉烋",12,"烚"], +["9f40","烜烝烞烠烡烢烣烥烪烮烰",6,"烸烺烻烼烾",10,"焋",4,"焑焒焔焗焛",10,"焧",7,"焲焳焴"], +["9f80","焵焷",13,"煆煇煈煉煋煍煏",12,"煝煟",4,"煥煩",4,"煯煰煱煴煵煶煷煹煻煼煾",5,"熅",4,"熋熌熍熎熐熑熒熓熕熖熗熚",4,"熡",6,"熩熪熫熭",5,"熴熶熷熸熺",8,"燄",9,"燏",4], +["a040","燖",9,"燡燢燣燤燦燨",5,"燯",9,"燺",11,"爇",19], +["a080","爛爜爞",9,"爩爫爭爮爯爲爳爴爺爼爾牀",6,"牉牊牋牎牏牐牑牓牔牕牗牘牚牜牞牠牣牤牥牨牪牫牬牭牰牱牳牴牶牷牸牻牼牽犂犃犅",4,"犌犎犐犑犓",11,"犠",11,"犮犱犲犳犵犺",6,"狅狆狇狉狊狋狌狏狑狓狔狕狖狘狚狛"], +["a1a1"," 、。·ˉˇ¨〃々—~‖…‘’“”〔〕〈",7,"〖〗【】±×÷∶∧∨∑∏∪∩∈∷√⊥∥∠⌒⊙∫∮≡≌≈∽∝≠≮≯≤≥∞∵∴♂♀°′″℃$¤¢£‰§№☆★○●◎◇◆□■△▲※→←↑↓〓"], +["a2a1","ⅰ",9], +["a2b1","⒈",19,"⑴",19,"①",9], +["a2e5","㈠",9], +["a2f1","Ⅰ",11], +["a3a1","!"#¥%",88," ̄"], +["a4a1","ぁ",82], +["a5a1","ァ",85], +["a6a1","Α",16,"Σ",6], +["a6c1","α",16,"σ",6], +["a6e0","︵︶︹︺︿﹀︽︾﹁﹂﹃﹄"], +["a6ee","︻︼︷︸︱"], +["a6f4","︳︴"], +["a7a1","А",5,"ЁЖ",25], +["a7d1","а",5,"ёж",25], +["a840","ˊˋ˙–―‥‵℅℉↖↗↘↙∕∟∣≒≦≧⊿═",35,"▁",6], +["a880","█",7,"▓▔▕▼▽◢◣◤◥☉⊕〒〝〞"], +["a8a1","āáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜüêɑ"], +["a8bd","ńň"], +["a8c0","ɡ"], +["a8c5","ㄅ",36], +["a940","〡",8,"㊣㎎㎏㎜㎝㎞㎡㏄㏎㏑㏒㏕︰¬¦"], +["a959","℡㈱"], +["a95c","‐"], +["a960","ー゛゜ヽヾ〆ゝゞ﹉",9,"﹔﹕﹖﹗﹙",8], +["a980","﹢",4,"﹨﹩﹪﹫"], +["a996","〇"], +["a9a4","─",75], +["aa40","狜狝狟狢",5,"狪狫狵狶狹狽狾狿猀猂猄",5,"猋猌猍猏猐猑猒猔猘猙猚猟猠猣猤猦猧猨猭猯猰猲猳猵猶猺猻猼猽獀",8], +["aa80","獉獊獋獌獎獏獑獓獔獕獖獘",7,"獡",10,"獮獰獱"], +["ab40","獲",11,"獿",4,"玅玆玈玊玌玍玏玐玒玓玔玕玗玘玙玚玜玝玞玠玡玣",5,"玪玬玭玱玴玵玶玸玹玼玽玾玿珁珃",4], +["ab80","珋珌珎珒",6,"珚珛珜珝珟珡珢珣珤珦珨珪珫珬珮珯珰珱珳",4], +["ac40","珸",10,"琄琇琈琋琌琍琎琑",8,"琜",5,"琣琤琧琩琫琭琯琱琲琷",4,"琽琾琿瑀瑂",11], +["ac80","瑎",6,"瑖瑘瑝瑠",12,"瑮瑯瑱",4,"瑸瑹瑺"], +["ad40","瑻瑼瑽瑿璂璄璅璆璈璉璊璌璍璏璑",10,"璝璟",7,"璪",15,"璻",12], +["ad80","瓈",9,"瓓",8,"瓝瓟瓡瓥瓧",6,"瓰瓱瓲"], +["ae40","瓳瓵瓸",6,"甀甁甂甃甅",7,"甎甐甒甔甕甖甗甛甝甞甠",4,"甦甧甪甮甴甶甹甼甽甿畁畂畃畄畆畇畉畊畍畐畑畒畓畕畖畗畘"], +["ae80","畝",7,"畧畨畩畫",6,"畳畵當畷畺",4,"疀疁疂疄疅疇"], +["af40","疈疉疊疌疍疎疐疓疕疘疛疜疞疢疦",4,"疭疶疷疺疻疿痀痁痆痋痌痎痏痐痑痓痗痙痚痜痝痟痠痡痥痩痬痭痮痯痲痳痵痶痷痸痺痻痽痾瘂瘄瘆瘇"], +["af80","瘈瘉瘋瘍瘎瘏瘑瘒瘓瘔瘖瘚瘜瘝瘞瘡瘣瘧瘨瘬瘮瘯瘱瘲瘶瘷瘹瘺瘻瘽癁療癄"], +["b040","癅",6,"癎",5,"癕癗",4,"癝癟癠癡癢癤",6,"癬癭癮癰",7,"癹発發癿皀皁皃皅皉皊皌皍皏皐皒皔皕皗皘皚皛"], +["b080","皜",7,"皥",8,"皯皰皳皵",9,"盀盁盃啊阿埃挨哎唉哀皑癌蔼矮艾碍爱隘鞍氨安俺按暗岸胺案肮昂盎凹敖熬翱袄傲奥懊澳芭捌扒叭吧笆八疤巴拔跋靶把耙坝霸罢爸白柏百摆佰败拜稗斑班搬扳般颁板版扮拌伴瓣半办绊邦帮梆榜膀绑棒磅蚌镑傍谤苞胞包褒剥"], +["b140","盄盇盉盋盌盓盕盙盚盜盝盞盠",4,"盦",7,"盰盳盵盶盷盺盻盽盿眀眂眃眅眆眊県眎",10,"眛眜眝眞眡眣眤眥眧眪眫"], +["b180","眬眮眰",4,"眹眻眽眾眿睂睄睅睆睈",7,"睒",7,"睜薄雹保堡饱宝抱报暴豹鲍爆杯碑悲卑北辈背贝钡倍狈备惫焙被奔苯本笨崩绷甭泵蹦迸逼鼻比鄙笔彼碧蓖蔽毕毙毖币庇痹闭敝弊必辟壁臂避陛鞭边编贬扁便变卞辨辩辫遍标彪膘表鳖憋别瘪彬斌濒滨宾摈兵冰柄丙秉饼炳"], +["b240","睝睞睟睠睤睧睩睪睭",11,"睺睻睼瞁瞂瞃瞆",5,"瞏瞐瞓",11,"瞡瞣瞤瞦瞨瞫瞭瞮瞯瞱瞲瞴瞶",4], +["b280","瞼瞾矀",12,"矎",8,"矘矙矚矝",4,"矤病并玻菠播拨钵波博勃搏铂箔伯帛舶脖膊渤泊驳捕卜哺补埠不布步簿部怖擦猜裁材才财睬踩采彩菜蔡餐参蚕残惭惨灿苍舱仓沧藏操糙槽曹草厕策侧册测层蹭插叉茬茶查碴搽察岔差诧拆柴豺搀掺蝉馋谗缠铲产阐颤昌猖"], +["b340","矦矨矪矯矰矱矲矴矵矷矹矺矻矼砃",5,"砊砋砎砏砐砓砕砙砛砞砠砡砢砤砨砪砫砮砯砱砲砳砵砶砽砿硁硂硃硄硆硈硉硊硋硍硏硑硓硔硘硙硚"], +["b380","硛硜硞",11,"硯",7,"硸硹硺硻硽",6,"场尝常长偿肠厂敞畅唱倡超抄钞朝嘲潮巢吵炒车扯撤掣彻澈郴臣辰尘晨忱沉陈趁衬撑称城橙成呈乘程惩澄诚承逞骋秤吃痴持匙池迟弛驰耻齿侈尺赤翅斥炽充冲虫崇宠抽酬畴踌稠愁筹仇绸瞅丑臭初出橱厨躇锄雏滁除楚"], +["b440","碄碅碆碈碊碋碏碐碒碔碕碖碙碝碞碠碢碤碦碨",7,"碵碶碷碸確碻碼碽碿磀磂磃磄磆磇磈磌磍磎磏磑磒磓磖磗磘磚",9], +["b480","磤磥磦磧磩磪磫磭",4,"磳磵磶磸磹磻",5,"礂礃礄礆",6,"础储矗搐触处揣川穿椽传船喘串疮窗幢床闯创吹炊捶锤垂春椿醇唇淳纯蠢戳绰疵茨磁雌辞慈瓷词此刺赐次聪葱囱匆从丛凑粗醋簇促蹿篡窜摧崔催脆瘁粹淬翠村存寸磋撮搓措挫错搭达答瘩打大呆歹傣戴带殆代贷袋待逮"], +["b540","礍",5,"礔",9,"礟",4,"礥",14,"礵",4,"礽礿祂祃祄祅祇祊",8,"祔祕祘祙祡祣"], +["b580","祤祦祩祪祫祬祮祰",6,"祹祻",4,"禂禃禆禇禈禉禋禌禍禎禐禑禒怠耽担丹单郸掸胆旦氮但惮淡诞弹蛋当挡党荡档刀捣蹈倒岛祷导到稻悼道盗德得的蹬灯登等瞪凳邓堤低滴迪敌笛狄涤翟嫡抵底地蒂第帝弟递缔颠掂滇碘点典靛垫电佃甸店惦奠淀殿碉叼雕凋刁掉吊钓调跌爹碟蝶迭谍叠"], +["b640","禓",6,"禛",11,"禨",10,"禴",4,"禼禿秂秄秅秇秈秊秌秎秏秐秓秔秖秗秙",5,"秠秡秢秥秨秪"], +["b680","秬秮秱",6,"秹秺秼秾秿稁稄稅稇稈稉稊稌稏",4,"稕稖稘稙稛稜丁盯叮钉顶鼎锭定订丢东冬董懂动栋侗恫冻洞兜抖斗陡豆逗痘都督毒犊独读堵睹赌杜镀肚度渡妒端短锻段断缎堆兑队对墩吨蹲敦顿囤钝盾遁掇哆多夺垛躲朵跺舵剁惰堕蛾峨鹅俄额讹娥恶厄扼遏鄂饿恩而儿耳尔饵洱二"], +["b740","稝稟稡稢稤",14,"稴稵稶稸稺稾穀",5,"穇",9,"穒",4,"穘",16], +["b780","穩",6,"穱穲穳穵穻穼穽穾窂窅窇窉窊窋窌窎窏窐窓窔窙窚窛窞窡窢贰发罚筏伐乏阀法珐藩帆番翻樊矾钒繁凡烦反返范贩犯饭泛坊芳方肪房防妨仿访纺放菲非啡飞肥匪诽吠肺废沸费芬酚吩氛分纷坟焚汾粉奋份忿愤粪丰封枫蜂峰锋风疯烽逢冯缝讽奉凤佛否夫敷肤孵扶拂辐幅氟符伏俘服"], +["b840","窣窤窧窩窪窫窮",4,"窴",10,"竀",10,"竌",9,"竗竘竚竛竜竝竡竢竤竧",5,"竮竰竱竲竳"], +["b880","竴",4,"竻竼竾笀笁笂笅笇笉笌笍笎笐笒笓笖笗笘笚笜笝笟笡笢笣笧笩笭浮涪福袱弗甫抚辅俯釜斧脯腑府腐赴副覆赋复傅付阜父腹负富讣附妇缚咐噶嘎该改概钙盖溉干甘杆柑竿肝赶感秆敢赣冈刚钢缸肛纲岗港杠篙皋高膏羔糕搞镐稿告哥歌搁戈鸽胳疙割革葛格蛤阁隔铬个各给根跟耕更庚羹"], +["b940","笯笰笲笴笵笶笷笹笻笽笿",5,"筆筈筊筍筎筓筕筗筙筜筞筟筡筣",10,"筯筰筳筴筶筸筺筼筽筿箁箂箃箄箆",6,"箎箏"], +["b980","箑箒箓箖箘箙箚箛箞箟箠箣箤箥箮箯箰箲箳箵箶箷箹",7,"篂篃範埂耿梗工攻功恭龚供躬公宫弓巩汞拱贡共钩勾沟苟狗垢构购够辜菇咕箍估沽孤姑鼓古蛊骨谷股故顾固雇刮瓜剐寡挂褂乖拐怪棺关官冠观管馆罐惯灌贯光广逛瑰规圭硅归龟闺轨鬼诡癸桂柜跪贵刽辊滚棍锅郭国果裹过哈"], +["ba40","篅篈築篊篋篍篎篏篐篒篔",4,"篛篜篞篟篠篢篣篤篧篨篩篫篬篭篯篰篲",4,"篸篹篺篻篽篿",7,"簈簉簊簍簎簐",5,"簗簘簙"], +["ba80","簚",4,"簠",5,"簨簩簫",12,"簹",5,"籂骸孩海氦亥害骇酣憨邯韩含涵寒函喊罕翰撼捍旱憾悍焊汗汉夯杭航壕嚎豪毫郝好耗号浩呵喝荷菏核禾和何合盒貉阂河涸赫褐鹤贺嘿黑痕很狠恨哼亨横衡恒轰哄烘虹鸿洪宏弘红喉侯猴吼厚候后呼乎忽瑚壶葫胡蝴狐糊湖"], +["bb40","籃",9,"籎",36,"籵",5,"籾",9], +["bb80","粈粊",6,"粓粔粖粙粚粛粠粡粣粦粧粨粩粫粬粭粯粰粴",4,"粺粻弧虎唬护互沪户花哗华猾滑画划化话槐徊怀淮坏欢环桓还缓换患唤痪豢焕涣宦幻荒慌黄磺蝗簧皇凰惶煌晃幌恍谎灰挥辉徽恢蛔回毁悔慧卉惠晦贿秽会烩汇讳诲绘荤昏婚魂浑混豁活伙火获或惑霍货祸击圾基机畸稽积箕"], +["bc40","粿糀糂糃糄糆糉糋糎",6,"糘糚糛糝糞糡",6,"糩",5,"糰",7,"糹糺糼",13,"紋",5], +["bc80","紑",14,"紡紣紤紥紦紨紩紪紬紭紮細",6,"肌饥迹激讥鸡姬绩缉吉极棘辑籍集及急疾汲即嫉级挤几脊己蓟技冀季伎祭剂悸济寄寂计记既忌际妓继纪嘉枷夹佳家加荚颊贾甲钾假稼价架驾嫁歼监坚尖笺间煎兼肩艰奸缄茧检柬碱硷拣捡简俭剪减荐槛鉴践贱见键箭件"], +["bd40","紷",54,"絯",7], +["bd80","絸",32,"健舰剑饯渐溅涧建僵姜将浆江疆蒋桨奖讲匠酱降蕉椒礁焦胶交郊浇骄娇嚼搅铰矫侥脚狡角饺缴绞剿教酵轿较叫窖揭接皆秸街阶截劫节桔杰捷睫竭洁结解姐戒藉芥界借介疥诫届巾筋斤金今津襟紧锦仅谨进靳晋禁近烬浸"], +["be40","継",12,"綧",6,"綯",42], +["be80","線",32,"尽劲荆兢茎睛晶鲸京惊精粳经井警景颈静境敬镜径痉靖竟竞净炯窘揪究纠玖韭久灸九酒厩救旧臼舅咎就疚鞠拘狙疽居驹菊局咀矩举沮聚拒据巨具距踞锯俱句惧炬剧捐鹃娟倦眷卷绢撅攫抉掘倔爵觉决诀绝均菌钧军君峻"], +["bf40","緻",62], +["bf80","縺縼",4,"繂",4,"繈",21,"俊竣浚郡骏喀咖卡咯开揩楷凯慨刊堪勘坎砍看康慷糠扛抗亢炕考拷烤靠坷苛柯棵磕颗科壳咳可渴克刻客课肯啃垦恳坑吭空恐孔控抠口扣寇枯哭窟苦酷库裤夸垮挎跨胯块筷侩快宽款匡筐狂框矿眶旷况亏盔岿窥葵奎魁傀"], +["c040","繞",35,"纃",23,"纜纝纞"], +["c080","纮纴纻纼绖绤绬绹缊缐缞缷缹缻",6,"罃罆",9,"罒罓馈愧溃坤昆捆困括扩廓阔垃拉喇蜡腊辣啦莱来赖蓝婪栏拦篮阑兰澜谰揽览懒缆烂滥琅榔狼廊郎朗浪捞劳牢老佬姥酪烙涝勒乐雷镭蕾磊累儡垒擂肋类泪棱楞冷厘梨犁黎篱狸离漓理李里鲤礼莉荔吏栗丽厉励砾历利傈例俐"], +["c140","罖罙罛罜罝罞罠罣",4,"罫罬罭罯罰罳罵罶罷罸罺罻罼罽罿羀羂",7,"羋羍羏",4,"羕",4,"羛羜羠羢羣羥羦羨",6,"羱"], +["c180","羳",4,"羺羻羾翀翂翃翄翆翇翈翉翋翍翏",4,"翖翗翙",5,"翢翣痢立粒沥隶力璃哩俩联莲连镰廉怜涟帘敛脸链恋炼练粮凉梁粱良两辆量晾亮谅撩聊僚疗燎寥辽潦了撂镣廖料列裂烈劣猎琳林磷霖临邻鳞淋凛赁吝拎玲菱零龄铃伶羚凌灵陵岭领另令溜琉榴硫馏留刘瘤流柳六龙聋咙笼窿"], +["c240","翤翧翨翪翫翬翭翯翲翴",6,"翽翾翿耂耇耈耉耊耎耏耑耓耚耛耝耞耟耡耣耤耫",5,"耲耴耹耺耼耾聀聁聄聅聇聈聉聎聏聐聑聓聕聖聗"], +["c280","聙聛",13,"聫",5,"聲",11,"隆垄拢陇楼娄搂篓漏陋芦卢颅庐炉掳卤虏鲁麓碌露路赂鹿潞禄录陆戮驴吕铝侣旅履屡缕虑氯律率滤绿峦挛孪滦卵乱掠略抡轮伦仑沦纶论萝螺罗逻锣箩骡裸落洛骆络妈麻玛码蚂马骂嘛吗埋买麦卖迈脉瞒馒蛮满蔓曼慢漫"], +["c340","聾肁肂肅肈肊肍",5,"肔肕肗肙肞肣肦肧肨肬肰肳肵肶肸肹肻胅胇",4,"胏",6,"胘胟胠胢胣胦胮胵胷胹胻胾胿脀脁脃脄脅脇脈脋"], +["c380","脌脕脗脙脛脜脝脟",12,"脭脮脰脳脴脵脷脹",4,"脿谩芒茫盲氓忙莽猫茅锚毛矛铆卯茂冒帽貌贸么玫枚梅酶霉煤没眉媒镁每美昧寐妹媚门闷们萌蒙檬盟锰猛梦孟眯醚靡糜迷谜弥米秘觅泌蜜密幂棉眠绵冕免勉娩缅面苗描瞄藐秒渺庙妙蔑灭民抿皿敏悯闽明螟鸣铭名命谬摸"], +["c440","腀",5,"腇腉腍腎腏腒腖腗腘腛",4,"腡腢腣腤腦腨腪腫腬腯腲腳腵腶腷腸膁膃",4,"膉膋膌膍膎膐膒",5,"膙膚膞",4,"膤膥"], +["c480","膧膩膫",7,"膴",5,"膼膽膾膿臄臅臇臈臉臋臍",6,"摹蘑模膜磨摩魔抹末莫墨默沫漠寞陌谋牟某拇牡亩姆母墓暮幕募慕木目睦牧穆拿哪呐钠那娜纳氖乃奶耐奈南男难囊挠脑恼闹淖呢馁内嫩能妮霓倪泥尼拟你匿腻逆溺蔫拈年碾撵捻念娘酿鸟尿捏聂孽啮镊镍涅您柠狞凝宁"], +["c540","臔",14,"臤臥臦臨臩臫臮",4,"臵",5,"臽臿舃與",4,"舎舏舑舓舕",5,"舝舠舤舥舦舧舩舮舲舺舼舽舿"], +["c580","艀艁艂艃艅艆艈艊艌艍艎艐",7,"艙艛艜艝艞艠",7,"艩拧泞牛扭钮纽脓浓农弄奴努怒女暖虐疟挪懦糯诺哦欧鸥殴藕呕偶沤啪趴爬帕怕琶拍排牌徘湃派攀潘盘磐盼畔判叛乓庞旁耪胖抛咆刨炮袍跑泡呸胚培裴赔陪配佩沛喷盆砰抨烹澎彭蓬棚硼篷膨朋鹏捧碰坯砒霹批披劈琵毗"], +["c640","艪艫艬艭艱艵艶艷艸艻艼芀芁芃芅芆芇芉芌芐芓芔芕芖芚芛芞芠芢芣芧芲芵芶芺芻芼芿苀苂苃苅苆苉苐苖苙苚苝苢苧苨苩苪苬苭苮苰苲苳苵苶苸"], +["c680","苺苼",4,"茊茋茍茐茒茓茖茘茙茝",9,"茩茪茮茰茲茷茻茽啤脾疲皮匹痞僻屁譬篇偏片骗飘漂瓢票撇瞥拼频贫品聘乒坪苹萍平凭瓶评屏坡泼颇婆破魄迫粕剖扑铺仆莆葡菩蒲埔朴圃普浦谱曝瀑期欺栖戚妻七凄漆柒沏其棋奇歧畦崎脐齐旗祈祁骑起岂乞企启契砌器气迄弃汽泣讫掐"], +["c740","茾茿荁荂荄荅荈荊",4,"荓荕",4,"荝荢荰",6,"荹荺荾",6,"莇莈莊莋莌莍莏莐莑莔莕莖莗莙莚莝莟莡",6,"莬莭莮"], +["c780","莯莵莻莾莿菂菃菄菆菈菉菋菍菎菐菑菒菓菕菗菙菚菛菞菢菣菤菦菧菨菫菬菭恰洽牵扦钎铅千迁签仟谦乾黔钱钳前潜遣浅谴堑嵌欠歉枪呛腔羌墙蔷强抢橇锹敲悄桥瞧乔侨巧鞘撬翘峭俏窍切茄且怯窃钦侵亲秦琴勤芹擒禽寝沁青轻氢倾卿清擎晴氰情顷请庆琼穷秋丘邱球求囚酋泅趋区蛆曲躯屈驱渠"], +["c840","菮華菳",4,"菺菻菼菾菿萀萂萅萇萈萉萊萐萒",5,"萙萚萛萞",5,"萩",7,"萲",5,"萹萺萻萾",7,"葇葈葉"], +["c880","葊",6,"葒",4,"葘葝葞葟葠葢葤",4,"葪葮葯葰葲葴葷葹葻葼取娶龋趣去圈颧权醛泉全痊拳犬券劝缺炔瘸却鹊榷确雀裙群然燃冉染瓤壤攘嚷让饶扰绕惹热壬仁人忍韧任认刃妊纫扔仍日戎茸蓉荣融熔溶容绒冗揉柔肉茹蠕儒孺如辱乳汝入褥软阮蕊瑞锐闰润若弱撒洒萨腮鳃塞赛三叁"], +["c940","葽",4,"蒃蒄蒅蒆蒊蒍蒏",7,"蒘蒚蒛蒝蒞蒟蒠蒢",12,"蒰蒱蒳蒵蒶蒷蒻蒼蒾蓀蓂蓃蓅蓆蓇蓈蓋蓌蓎蓏蓒蓔蓕蓗"], +["c980","蓘",4,"蓞蓡蓢蓤蓧",4,"蓭蓮蓯蓱",10,"蓽蓾蔀蔁蔂伞散桑嗓丧搔骚扫嫂瑟色涩森僧莎砂杀刹沙纱傻啥煞筛晒珊苫杉山删煽衫闪陕擅赡膳善汕扇缮墒伤商赏晌上尚裳梢捎稍烧芍勺韶少哨邵绍奢赊蛇舌舍赦摄射慑涉社设砷申呻伸身深娠绅神沈审婶甚肾慎渗声生甥牲升绳"], +["ca40","蔃",8,"蔍蔎蔏蔐蔒蔔蔕蔖蔘蔙蔛蔜蔝蔞蔠蔢",8,"蔭",9,"蔾",4,"蕄蕅蕆蕇蕋",10], +["ca80","蕗蕘蕚蕛蕜蕝蕟",4,"蕥蕦蕧蕩",8,"蕳蕵蕶蕷蕸蕼蕽蕿薀薁省盛剩胜圣师失狮施湿诗尸虱十石拾时什食蚀实识史矢使屎驶始式示士世柿事拭誓逝势是嗜噬适仕侍释饰氏市恃室视试收手首守寿授售受瘦兽蔬枢梳殊抒输叔舒淑疏书赎孰熟薯暑曙署蜀黍鼠属术述树束戍竖墅庶数漱"], +["cb40","薂薃薆薈",6,"薐",10,"薝",6,"薥薦薧薩薫薬薭薱",5,"薸薺",6,"藂",6,"藊",4,"藑藒"], +["cb80","藔藖",5,"藝",6,"藥藦藧藨藪",14,"恕刷耍摔衰甩帅栓拴霜双爽谁水睡税吮瞬顺舜说硕朔烁斯撕嘶思私司丝死肆寺嗣四伺似饲巳松耸怂颂送宋讼诵搜艘擞嗽苏酥俗素速粟僳塑溯宿诉肃酸蒜算虽隋随绥髓碎岁穗遂隧祟孙损笋蓑梭唆缩琐索锁所塌他它她塔"], +["cc40","藹藺藼藽藾蘀",4,"蘆",10,"蘒蘓蘔蘕蘗",15,"蘨蘪",13,"蘹蘺蘻蘽蘾蘿虀"], +["cc80","虁",11,"虒虓處",4,"虛虜虝號虠虡虣",7,"獭挞蹋踏胎苔抬台泰酞太态汰坍摊贪瘫滩坛檀痰潭谭谈坦毯袒碳探叹炭汤塘搪堂棠膛唐糖倘躺淌趟烫掏涛滔绦萄桃逃淘陶讨套特藤腾疼誊梯剔踢锑提题蹄啼体替嚏惕涕剃屉天添填田甜恬舔腆挑条迢眺跳贴铁帖厅听烃"], +["cd40","虭虯虰虲",6,"蚃",6,"蚎",4,"蚔蚖",5,"蚞",4,"蚥蚦蚫蚭蚮蚲蚳蚷蚸蚹蚻",4,"蛁蛂蛃蛅蛈蛌蛍蛒蛓蛕蛖蛗蛚蛜"], +["cd80","蛝蛠蛡蛢蛣蛥蛦蛧蛨蛪蛫蛬蛯蛵蛶蛷蛺蛻蛼蛽蛿蜁蜄蜅蜆蜋蜌蜎蜏蜐蜑蜔蜖汀廷停亭庭挺艇通桐酮瞳同铜彤童桶捅筒统痛偷投头透凸秃突图徒途涂屠土吐兔湍团推颓腿蜕褪退吞屯臀拖托脱鸵陀驮驼椭妥拓唾挖哇蛙洼娃瓦袜歪外豌弯湾玩顽丸烷完碗挽晚皖惋宛婉万腕汪王亡枉网往旺望忘妄威"], +["ce40","蜙蜛蜝蜟蜠蜤蜦蜧蜨蜪蜫蜬蜭蜯蜰蜲蜳蜵蜶蜸蜹蜺蜼蜽蝀",6,"蝊蝋蝍蝏蝐蝑蝒蝔蝕蝖蝘蝚",5,"蝡蝢蝦",7,"蝯蝱蝲蝳蝵"], +["ce80","蝷蝸蝹蝺蝿螀螁螄螆螇螉螊螌螎",4,"螔螕螖螘",6,"螠",4,"巍微危韦违桅围唯惟为潍维苇萎委伟伪尾纬未蔚味畏胃喂魏位渭谓尉慰卫瘟温蚊文闻纹吻稳紊问嗡翁瓮挝蜗涡窝我斡卧握沃巫呜钨乌污诬屋无芜梧吾吴毋武五捂午舞伍侮坞戊雾晤物勿务悟误昔熙析西硒矽晰嘻吸锡牺"], +["cf40","螥螦螧螩螪螮螰螱螲螴螶螷螸螹螻螼螾螿蟁",4,"蟇蟈蟉蟌",4,"蟔",6,"蟜蟝蟞蟟蟡蟢蟣蟤蟦蟧蟨蟩蟫蟬蟭蟯",9], +["cf80","蟺蟻蟼蟽蟿蠀蠁蠂蠄",5,"蠋",7,"蠔蠗蠘蠙蠚蠜",4,"蠣稀息希悉膝夕惜熄烯溪汐犀檄袭席习媳喜铣洗系隙戏细瞎虾匣霞辖暇峡侠狭下厦夏吓掀锨先仙鲜纤咸贤衔舷闲涎弦嫌显险现献县腺馅羡宪陷限线相厢镶香箱襄湘乡翔祥详想响享项巷橡像向象萧硝霄削哮嚣销消宵淆晓"], +["d040","蠤",13,"蠳",5,"蠺蠻蠽蠾蠿衁衂衃衆",5,"衎",5,"衕衖衘衚",6,"衦衧衪衭衯衱衳衴衵衶衸衹衺"], +["d080","衻衼袀袃袆袇袉袊袌袎袏袐袑袓袔袕袗",4,"袝",4,"袣袥",5,"小孝校肖啸笑效楔些歇蝎鞋协挟携邪斜胁谐写械卸蟹懈泄泻谢屑薪芯锌欣辛新忻心信衅星腥猩惺兴刑型形邢行醒幸杏性姓兄凶胸匈汹雄熊休修羞朽嗅锈秀袖绣墟戌需虚嘘须徐许蓄酗叙旭序畜恤絮婿绪续轩喧宣悬旋玄"], +["d140","袬袮袯袰袲",4,"袸袹袺袻袽袾袿裀裃裄裇裈裊裋裌裍裏裐裑裓裖裗裚",4,"裠裡裦裧裩",6,"裲裵裶裷裺裻製裿褀褁褃",5], +["d180","褉褋",4,"褑褔",4,"褜",4,"褢褣褤褦褧褨褩褬褭褮褯褱褲褳褵褷选癣眩绚靴薛学穴雪血勋熏循旬询寻驯巡殉汛训讯逊迅压押鸦鸭呀丫芽牙蚜崖衙涯雅哑亚讶焉咽阉烟淹盐严研蜒岩延言颜阎炎沿奄掩眼衍演艳堰燕厌砚雁唁彦焰宴谚验殃央鸯秧杨扬佯疡羊洋阳氧仰痒养样漾邀腰妖瑶"], +["d240","褸",8,"襂襃襅",24,"襠",5,"襧",19,"襼"], +["d280","襽襾覀覂覄覅覇",26,"摇尧遥窑谣姚咬舀药要耀椰噎耶爷野冶也页掖业叶曳腋夜液一壹医揖铱依伊衣颐夷遗移仪胰疑沂宜姨彝椅蚁倚已乙矣以艺抑易邑屹亿役臆逸肄疫亦裔意毅忆义益溢诣议谊译异翼翌绎茵荫因殷音阴姻吟银淫寅饮尹引隐"], +["d340","覢",30,"觃觍觓觔觕觗觘觙觛觝觟觠觡觢觤觧觨觩觪觬觭觮觰觱觲觴",6], +["d380","觻",4,"訁",5,"計",21,"印英樱婴鹰应缨莹萤营荧蝇迎赢盈影颖硬映哟拥佣臃痈庸雍踊蛹咏泳涌永恿勇用幽优悠忧尤由邮铀犹油游酉有友右佑釉诱又幼迂淤于盂榆虞愚舆余俞逾鱼愉渝渔隅予娱雨与屿禹宇语羽玉域芋郁吁遇喻峪御愈欲狱育誉"], +["d440","訞",31,"訿",8,"詉",21], +["d480","詟",25,"詺",6,"浴寓裕预豫驭鸳渊冤元垣袁原援辕园员圆猿源缘远苑愿怨院曰约越跃钥岳粤月悦阅耘云郧匀陨允运蕴酝晕韵孕匝砸杂栽哉灾宰载再在咱攒暂赞赃脏葬遭糟凿藻枣早澡蚤躁噪造皂灶燥责择则泽贼怎增憎曾赠扎喳渣札轧"], +["d540","誁",7,"誋",7,"誔",46], +["d580","諃",32,"铡闸眨栅榨咋乍炸诈摘斋宅窄债寨瞻毡詹粘沾盏斩辗崭展蘸栈占战站湛绽樟章彰漳张掌涨杖丈帐账仗胀瘴障招昭找沼赵照罩兆肇召遮折哲蛰辙者锗蔗这浙珍斟真甄砧臻贞针侦枕疹诊震振镇阵蒸挣睁征狰争怔整拯正政"], +["d640","諤",34,"謈",27], +["d680","謤謥謧",30,"帧症郑证芝枝支吱蜘知肢脂汁之织职直植殖执值侄址指止趾只旨纸志挚掷至致置帜峙制智秩稚质炙痔滞治窒中盅忠钟衷终种肿重仲众舟周州洲诌粥轴肘帚咒皱宙昼骤珠株蛛朱猪诸诛逐竹烛煮拄瞩嘱主著柱助蛀贮铸筑"], +["d740","譆",31,"譧",4,"譭",25], +["d780","讇",24,"讬讱讻诇诐诪谉谞住注祝驻抓爪拽专砖转撰赚篆桩庄装妆撞壮状椎锥追赘坠缀谆准捉拙卓桌琢茁酌啄着灼浊兹咨资姿滋淄孜紫仔籽滓子自渍字鬃棕踪宗综总纵邹走奏揍租足卒族祖诅阻组钻纂嘴醉最罪尊遵昨左佐柞做作坐座"], +["d840","谸",8,"豂豃豄豅豈豊豋豍",7,"豖豗豘豙豛",5,"豣",6,"豬",6,"豴豵豶豷豻",6,"貃貄貆貇"], +["d880","貈貋貍",6,"貕貖貗貙",20,"亍丌兀丐廿卅丕亘丞鬲孬噩丨禺丿匕乇夭爻卮氐囟胤馗毓睾鼗丶亟鼐乜乩亓芈孛啬嘏仄厍厝厣厥厮靥赝匚叵匦匮匾赜卦卣刂刈刎刭刳刿剀剌剞剡剜蒯剽劂劁劐劓冂罔亻仃仉仂仨仡仫仞伛仳伢佤仵伥伧伉伫佞佧攸佚佝"], +["d940","貮",62], +["d980","賭",32,"佟佗伲伽佶佴侑侉侃侏佾佻侪佼侬侔俦俨俪俅俚俣俜俑俟俸倩偌俳倬倏倮倭俾倜倌倥倨偾偃偕偈偎偬偻傥傧傩傺僖儆僭僬僦僮儇儋仝氽佘佥俎龠汆籴兮巽黉馘冁夔勹匍訇匐凫夙兕亠兖亳衮袤亵脔裒禀嬴蠃羸冫冱冽冼"], +["da40","贎",14,"贠赑赒赗赟赥赨赩赪赬赮赯赱赲赸",8,"趂趃趆趇趈趉趌",4,"趒趓趕",9,"趠趡"], +["da80","趢趤",12,"趲趶趷趹趻趽跀跁跂跅跇跈跉跊跍跐跒跓跔凇冖冢冥讠讦讧讪讴讵讷诂诃诋诏诎诒诓诔诖诘诙诜诟诠诤诨诩诮诰诳诶诹诼诿谀谂谄谇谌谏谑谒谔谕谖谙谛谘谝谟谠谡谥谧谪谫谮谯谲谳谵谶卩卺阝阢阡阱阪阽阼陂陉陔陟陧陬陲陴隈隍隗隰邗邛邝邙邬邡邴邳邶邺"], +["db40","跕跘跙跜跠跡跢跥跦跧跩跭跮跰跱跲跴跶跼跾",6,"踆踇踈踋踍踎踐踑踒踓踕",7,"踠踡踤",4,"踫踭踰踲踳踴踶踷踸踻踼踾"], +["db80","踿蹃蹅蹆蹌",4,"蹓",5,"蹚",11,"蹧蹨蹪蹫蹮蹱邸邰郏郅邾郐郄郇郓郦郢郜郗郛郫郯郾鄄鄢鄞鄣鄱鄯鄹酃酆刍奂劢劬劭劾哿勐勖勰叟燮矍廴凵凼鬯厶弁畚巯坌垩垡塾墼壅壑圩圬圪圳圹圮圯坜圻坂坩垅坫垆坼坻坨坭坶坳垭垤垌垲埏垧垴垓垠埕埘埚埙埒垸埴埯埸埤埝"], +["dc40","蹳蹵蹷",4,"蹽蹾躀躂躃躄躆躈",6,"躑躒躓躕",6,"躝躟",11,"躭躮躰躱躳",6,"躻",7], +["dc80","軃",10,"軏",21,"堋堍埽埭堀堞堙塄堠塥塬墁墉墚墀馨鼙懿艹艽艿芏芊芨芄芎芑芗芙芫芸芾芰苈苊苣芘芷芮苋苌苁芩芴芡芪芟苄苎芤苡茉苷苤茏茇苜苴苒苘茌苻苓茑茚茆茔茕苠苕茜荑荛荜茈莒茼茴茱莛荞茯荏荇荃荟荀茗荠茭茺茳荦荥"], +["dd40","軥",62], +["dd80","輤",32,"荨茛荩荬荪荭荮莰荸莳莴莠莪莓莜莅荼莶莩荽莸荻莘莞莨莺莼菁萁菥菘堇萘萋菝菽菖萜萸萑萆菔菟萏萃菸菹菪菅菀萦菰菡葜葑葚葙葳蒇蒈葺蒉葸萼葆葩葶蒌蒎萱葭蓁蓍蓐蓦蒽蓓蓊蒿蒺蓠蒡蒹蒴蒗蓥蓣蔌甍蔸蓰蔹蔟蔺"], +["de40","轅",32,"轪辀辌辒辝辠辡辢辤辥辦辧辪辬辭辮辯農辳辴辵辷辸辺辻込辿迀迃迆"], +["de80","迉",4,"迏迒迖迗迚迠迡迣迧迬迯迱迲迴迵迶迺迻迼迾迿逇逈逌逎逓逕逘蕖蔻蓿蓼蕙蕈蕨蕤蕞蕺瞢蕃蕲蕻薤薨薇薏蕹薮薜薅薹薷薰藓藁藜藿蘧蘅蘩蘖蘼廾弈夼奁耷奕奚奘匏尢尥尬尴扌扪抟抻拊拚拗拮挢拶挹捋捃掭揶捱捺掎掴捭掬掊捩掮掼揲揸揠揿揄揞揎摒揆掾摅摁搋搛搠搌搦搡摞撄摭撖"], +["df40","這逜連逤逥逧",5,"逰",4,"逷逹逺逽逿遀遃遅遆遈",4,"過達違遖遙遚遜",5,"遤遦遧適遪遫遬遯",4,"遶",6,"遾邁"], +["df80","還邅邆邇邉邊邌",4,"邒邔邖邘邚邜邞邟邠邤邥邧邨邩邫邭邲邷邼邽邿郀摺撷撸撙撺擀擐擗擤擢攉攥攮弋忒甙弑卟叱叽叩叨叻吒吖吆呋呒呓呔呖呃吡呗呙吣吲咂咔呷呱呤咚咛咄呶呦咝哐咭哂咴哒咧咦哓哔呲咣哕咻咿哌哙哚哜咩咪咤哝哏哞唛哧唠哽唔哳唢唣唏唑唧唪啧喏喵啉啭啁啕唿啐唼"], +["e040","郂郃郆郈郉郋郌郍郒郔郕郖郘郙郚郞郟郠郣郤郥郩郪郬郮郰郱郲郳郵郶郷郹郺郻郼郿鄀鄁鄃鄅",19,"鄚鄛鄜"], +["e080","鄝鄟鄠鄡鄤",10,"鄰鄲",6,"鄺",8,"酄唷啖啵啶啷唳唰啜喋嗒喃喱喹喈喁喟啾嗖喑啻嗟喽喾喔喙嗪嗷嗉嘟嗑嗫嗬嗔嗦嗝嗄嗯嗥嗲嗳嗌嗍嗨嗵嗤辔嘞嘈嘌嘁嘤嘣嗾嘀嘧嘭噘嘹噗嘬噍噢噙噜噌噔嚆噤噱噫噻噼嚅嚓嚯囔囗囝囡囵囫囹囿圄圊圉圜帏帙帔帑帱帻帼"], +["e140","酅酇酈酑酓酔酕酖酘酙酛酜酟酠酦酧酨酫酭酳酺酻酼醀",4,"醆醈醊醎醏醓",6,"醜",5,"醤",5,"醫醬醰醱醲醳醶醷醸醹醻"], +["e180","醼",10,"釈釋釐釒",9,"針",8,"帷幄幔幛幞幡岌屺岍岐岖岈岘岙岑岚岜岵岢岽岬岫岱岣峁岷峄峒峤峋峥崂崃崧崦崮崤崞崆崛嵘崾崴崽嵬嵛嵯嵝嵫嵋嵊嵩嵴嶂嶙嶝豳嶷巅彳彷徂徇徉後徕徙徜徨徭徵徼衢彡犭犰犴犷犸狃狁狎狍狒狨狯狩狲狴狷猁狳猃狺"], +["e240","釦",62], +["e280","鈥",32,"狻猗猓猡猊猞猝猕猢猹猥猬猸猱獐獍獗獠獬獯獾舛夥飧夤夂饣饧",5,"饴饷饽馀馄馇馊馍馐馑馓馔馕庀庑庋庖庥庠庹庵庾庳赓廒廑廛廨廪膺忄忉忖忏怃忮怄忡忤忾怅怆忪忭忸怙怵怦怛怏怍怩怫怊怿怡恸恹恻恺恂"], +["e340","鉆",45,"鉵",16], +["e380","銆",7,"銏",24,"恪恽悖悚悭悝悃悒悌悛惬悻悱惝惘惆惚悴愠愦愕愣惴愀愎愫慊慵憬憔憧憷懔懵忝隳闩闫闱闳闵闶闼闾阃阄阆阈阊阋阌阍阏阒阕阖阗阙阚丬爿戕氵汔汜汊沣沅沐沔沌汨汩汴汶沆沩泐泔沭泷泸泱泗沲泠泖泺泫泮沱泓泯泾"], +["e440","銨",5,"銯",24,"鋉",31], +["e480","鋩",32,"洹洧洌浃浈洇洄洙洎洫浍洮洵洚浏浒浔洳涑浯涞涠浞涓涔浜浠浼浣渚淇淅淞渎涿淠渑淦淝淙渖涫渌涮渫湮湎湫溲湟溆湓湔渲渥湄滟溱溘滠漭滢溥溧溽溻溷滗溴滏溏滂溟潢潆潇漤漕滹漯漶潋潴漪漉漩澉澍澌潸潲潼潺濑"], +["e540","錊",51,"錿",10], +["e580","鍊",31,"鍫濉澧澹澶濂濡濮濞濠濯瀚瀣瀛瀹瀵灏灞宀宄宕宓宥宸甯骞搴寤寮褰寰蹇謇辶迓迕迥迮迤迩迦迳迨逅逄逋逦逑逍逖逡逵逶逭逯遄遑遒遐遨遘遢遛暹遴遽邂邈邃邋彐彗彖彘尻咫屐屙孱屣屦羼弪弩弭艴弼鬻屮妁妃妍妩妪妣"], +["e640","鍬",34,"鎐",27], +["e680","鎬",29,"鏋鏌鏍妗姊妫妞妤姒妲妯姗妾娅娆姝娈姣姘姹娌娉娲娴娑娣娓婀婧婊婕娼婢婵胬媪媛婷婺媾嫫媲嫒嫔媸嫠嫣嫱嫖嫦嫘嫜嬉嬗嬖嬲嬷孀尕尜孚孥孳孑孓孢驵驷驸驺驿驽骀骁骅骈骊骐骒骓骖骘骛骜骝骟骠骢骣骥骧纟纡纣纥纨纩"], +["e740","鏎",7,"鏗",54], +["e780","鐎",32,"纭纰纾绀绁绂绉绋绌绐绔绗绛绠绡绨绫绮绯绱绲缍绶绺绻绾缁缂缃缇缈缋缌缏缑缒缗缙缜缛缟缡",6,"缪缫缬缭缯",4,"缵幺畿巛甾邕玎玑玮玢玟珏珂珑玷玳珀珉珈珥珙顼琊珩珧珞玺珲琏琪瑛琦琥琨琰琮琬"], +["e840","鐯",14,"鐿",43,"鑬鑭鑮鑯"], +["e880","鑰",20,"钑钖钘铇铏铓铔铚铦铻锜锠琛琚瑁瑜瑗瑕瑙瑷瑭瑾璜璎璀璁璇璋璞璨璩璐璧瓒璺韪韫韬杌杓杞杈杩枥枇杪杳枘枧杵枨枞枭枋杷杼柰栉柘栊柩枰栌柙枵柚枳柝栀柃枸柢栎柁柽栲栳桠桡桎桢桄桤梃栝桕桦桁桧桀栾桊桉栩梵梏桴桷梓桫棂楮棼椟椠棹"], +["e940","锧锳锽镃镈镋镕镚镠镮镴镵長",7,"門",42], +["e980","閫",32,"椤棰椋椁楗棣椐楱椹楠楂楝榄楫榀榘楸椴槌榇榈槎榉楦楣楹榛榧榻榫榭槔榱槁槊槟榕槠榍槿樯槭樗樘橥槲橄樾檠橐橛樵檎橹樽樨橘橼檑檐檩檗檫猷獒殁殂殇殄殒殓殍殚殛殡殪轫轭轱轲轳轵轶轸轷轹轺轼轾辁辂辄辇辋"], +["ea40","闌",27,"闬闿阇阓阘阛阞阠阣",6,"阫阬阭阯阰阷阸阹阺阾陁陃陊陎陏陑陒陓陖陗"], +["ea80","陘陙陚陜陝陞陠陣陥陦陫陭",4,"陳陸",12,"隇隉隊辍辎辏辘辚軎戋戗戛戟戢戡戥戤戬臧瓯瓴瓿甏甑甓攴旮旯旰昊昙杲昃昕昀炅曷昝昴昱昶昵耆晟晔晁晏晖晡晗晷暄暌暧暝暾曛曜曦曩贲贳贶贻贽赀赅赆赈赉赇赍赕赙觇觊觋觌觎觏觐觑牮犟牝牦牯牾牿犄犋犍犏犒挈挲掰"], +["eb40","隌階隑隒隓隕隖隚際隝",9,"隨",7,"隱隲隴隵隷隸隺隻隿雂雃雈雊雋雐雑雓雔雖",9,"雡",6,"雫"], +["eb80","雬雭雮雰雱雲雴雵雸雺電雼雽雿霂霃霅霊霋霌霐霑霒霔霕霗",4,"霝霟霠搿擘耄毪毳毽毵毹氅氇氆氍氕氘氙氚氡氩氤氪氲攵敕敫牍牒牖爰虢刖肟肜肓肼朊肽肱肫肭肴肷胧胨胩胪胛胂胄胙胍胗朐胝胫胱胴胭脍脎胲胼朕脒豚脶脞脬脘脲腈腌腓腴腙腚腱腠腩腼腽腭腧塍媵膈膂膑滕膣膪臌朦臊膻"], +["ec40","霡",8,"霫霬霮霯霱霳",4,"霺霻霼霽霿",18,"靔靕靗靘靚靜靝靟靣靤靦靧靨靪",7], +["ec80","靲靵靷",4,"靽",7,"鞆",4,"鞌鞎鞏鞐鞓鞕鞖鞗鞙",4,"臁膦欤欷欹歃歆歙飑飒飓飕飙飚殳彀毂觳斐齑斓於旆旄旃旌旎旒旖炀炜炖炝炻烀炷炫炱烨烊焐焓焖焯焱煳煜煨煅煲煊煸煺熘熳熵熨熠燠燔燧燹爝爨灬焘煦熹戾戽扃扈扉礻祀祆祉祛祜祓祚祢祗祠祯祧祺禅禊禚禧禳忑忐"], +["ed40","鞞鞟鞡鞢鞤",6,"鞬鞮鞰鞱鞳鞵",46], +["ed80","韤韥韨韮",4,"韴韷",23,"怼恝恚恧恁恙恣悫愆愍慝憩憝懋懑戆肀聿沓泶淼矶矸砀砉砗砘砑斫砭砜砝砹砺砻砟砼砥砬砣砩硎硭硖硗砦硐硇硌硪碛碓碚碇碜碡碣碲碹碥磔磙磉磬磲礅磴礓礤礞礴龛黹黻黼盱眄眍盹眇眈眚眢眙眭眦眵眸睐睑睇睃睚睨"], +["ee40","頏",62], +["ee80","顎",32,"睢睥睿瞍睽瞀瞌瞑瞟瞠瞰瞵瞽町畀畎畋畈畛畲畹疃罘罡罟詈罨罴罱罹羁罾盍盥蠲钅钆钇钋钊钌钍钏钐钔钗钕钚钛钜钣钤钫钪钭钬钯钰钲钴钶",4,"钼钽钿铄铈",6,"铐铑铒铕铖铗铙铘铛铞铟铠铢铤铥铧铨铪"], +["ef40","顯",5,"颋颎颒颕颙颣風",37,"飏飐飔飖飗飛飜飝飠",4], +["ef80","飥飦飩",30,"铩铫铮铯铳铴铵铷铹铼铽铿锃锂锆锇锉锊锍锎锏锒",4,"锘锛锝锞锟锢锪锫锩锬锱锲锴锶锷锸锼锾锿镂锵镄镅镆镉镌镎镏镒镓镔镖镗镘镙镛镞镟镝镡镢镤",8,"镯镱镲镳锺矧矬雉秕秭秣秫稆嵇稃稂稞稔"], +["f040","餈",4,"餎餏餑",28,"餯",26], +["f080","饊",9,"饖",12,"饤饦饳饸饹饻饾馂馃馉稹稷穑黏馥穰皈皎皓皙皤瓞瓠甬鸠鸢鸨",4,"鸲鸱鸶鸸鸷鸹鸺鸾鹁鹂鹄鹆鹇鹈鹉鹋鹌鹎鹑鹕鹗鹚鹛鹜鹞鹣鹦",6,"鹱鹭鹳疒疔疖疠疝疬疣疳疴疸痄疱疰痃痂痖痍痣痨痦痤痫痧瘃痱痼痿瘐瘀瘅瘌瘗瘊瘥瘘瘕瘙"], +["f140","馌馎馚",10,"馦馧馩",47], +["f180","駙",32,"瘛瘼瘢瘠癀瘭瘰瘿瘵癃瘾瘳癍癞癔癜癖癫癯翊竦穸穹窀窆窈窕窦窠窬窨窭窳衤衩衲衽衿袂袢裆袷袼裉裢裎裣裥裱褚裼裨裾裰褡褙褓褛褊褴褫褶襁襦襻疋胥皲皴矜耒耔耖耜耠耢耥耦耧耩耨耱耋耵聃聆聍聒聩聱覃顸颀颃"], +["f240","駺",62], +["f280","騹",32,"颉颌颍颏颔颚颛颞颟颡颢颥颦虍虔虬虮虿虺虼虻蚨蚍蚋蚬蚝蚧蚣蚪蚓蚩蚶蛄蚵蛎蚰蚺蚱蚯蛉蛏蚴蛩蛱蛲蛭蛳蛐蜓蛞蛴蛟蛘蛑蜃蜇蛸蜈蜊蜍蜉蜣蜻蜞蜥蜮蜚蜾蝈蜴蜱蜩蜷蜿螂蜢蝽蝾蝻蝠蝰蝌蝮螋蝓蝣蝼蝤蝙蝥螓螯螨蟒"], +["f340","驚",17,"驲骃骉骍骎骔骕骙骦骩",6,"骲骳骴骵骹骻骽骾骿髃髄髆",4,"髍髎髏髐髒體髕髖髗髙髚髛髜"], +["f380","髝髞髠髢髣髤髥髧髨髩髪髬髮髰",8,"髺髼",6,"鬄鬅鬆蟆螈螅螭螗螃螫蟥螬螵螳蟋蟓螽蟑蟀蟊蟛蟪蟠蟮蠖蠓蟾蠊蠛蠡蠹蠼缶罂罄罅舐竺竽笈笃笄笕笊笫笏筇笸笪笙笮笱笠笥笤笳笾笞筘筚筅筵筌筝筠筮筻筢筲筱箐箦箧箸箬箝箨箅箪箜箢箫箴篑篁篌篝篚篥篦篪簌篾篼簏簖簋"], +["f440","鬇鬉",5,"鬐鬑鬒鬔",10,"鬠鬡鬢鬤",10,"鬰鬱鬳",7,"鬽鬾鬿魀魆魊魋魌魎魐魒魓魕",5], +["f480","魛",32,"簟簪簦簸籁籀臾舁舂舄臬衄舡舢舣舭舯舨舫舸舻舳舴舾艄艉艋艏艚艟艨衾袅袈裘裟襞羝羟羧羯羰羲籼敉粑粝粜粞粢粲粼粽糁糇糌糍糈糅糗糨艮暨羿翎翕翥翡翦翩翮翳糸絷綦綮繇纛麸麴赳趄趔趑趱赧赭豇豉酊酐酎酏酤"], +["f540","魼",62], +["f580","鮻",32,"酢酡酰酩酯酽酾酲酴酹醌醅醐醍醑醢醣醪醭醮醯醵醴醺豕鹾趸跫踅蹙蹩趵趿趼趺跄跖跗跚跞跎跏跛跆跬跷跸跣跹跻跤踉跽踔踝踟踬踮踣踯踺蹀踹踵踽踱蹉蹁蹂蹑蹒蹊蹰蹶蹼蹯蹴躅躏躔躐躜躞豸貂貊貅貘貔斛觖觞觚觜"], +["f640","鯜",62], +["f680","鰛",32,"觥觫觯訾謦靓雩雳雯霆霁霈霏霎霪霭霰霾龀龃龅",5,"龌黾鼋鼍隹隼隽雎雒瞿雠銎銮鋈錾鍪鏊鎏鐾鑫鱿鲂鲅鲆鲇鲈稣鲋鲎鲐鲑鲒鲔鲕鲚鲛鲞",5,"鲥",4,"鲫鲭鲮鲰",7,"鲺鲻鲼鲽鳄鳅鳆鳇鳊鳋"], +["f740","鰼",62], +["f780","鱻鱽鱾鲀鲃鲄鲉鲊鲌鲏鲓鲖鲗鲘鲙鲝鲪鲬鲯鲹鲾",4,"鳈鳉鳑鳒鳚鳛鳠鳡鳌",4,"鳓鳔鳕鳗鳘鳙鳜鳝鳟鳢靼鞅鞑鞒鞔鞯鞫鞣鞲鞴骱骰骷鹘骶骺骼髁髀髅髂髋髌髑魅魃魇魉魈魍魑飨餍餮饕饔髟髡髦髯髫髻髭髹鬈鬏鬓鬟鬣麽麾縻麂麇麈麋麒鏖麝麟黛黜黝黠黟黢黩黧黥黪黯鼢鼬鼯鼹鼷鼽鼾齄"], +["f840","鳣",62], +["f880","鴢",32], +["f940","鵃",62], +["f980","鶂",32], +["fa40","鶣",62], +["fa80","鷢",32], +["fb40","鸃",27,"鸤鸧鸮鸰鸴鸻鸼鹀鹍鹐鹒鹓鹔鹖鹙鹝鹟鹠鹡鹢鹥鹮鹯鹲鹴",9,"麀"], +["fb80","麁麃麄麅麆麉麊麌",5,"麔",8,"麞麠",5,"麧麨麩麪"], +["fc40","麫",8,"麵麶麷麹麺麼麿",4,"黅黆黇黈黊黋黌黐黒黓黕黖黗黙黚點黡黣黤黦黨黫黬黭黮黰",8,"黺黽黿",6], +["fc80","鼆",4,"鼌鼏鼑鼒鼔鼕鼖鼘鼚",5,"鼡鼣",8,"鼭鼮鼰鼱"], +["fd40","鼲",4,"鼸鼺鼼鼿",4,"齅",10,"齒",38], +["fd80","齹",5,"龁龂龍",11,"龜龝龞龡",4,"郎凉秊裏隣"], +["fe40","兀嗀﨎﨏﨑﨓﨔礼﨟蘒﨡﨣﨤﨧﨨﨩"] +] diff --git a/node_modules/iconv-lite/encodings/tables/cp949.json b/node_modules/iconv-lite/encodings/tables/cp949.json new file mode 100644 index 0000000..2022a00 --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/cp949.json @@ -0,0 +1,273 @@ +[ +["0","\u0000",127], +["8141","갂갃갅갆갋",4,"갘갞갟갡갢갣갥",6,"갮갲갳갴"], +["8161","갵갶갷갺갻갽갾갿걁",9,"걌걎",5,"걕"], +["8181","걖걗걙걚걛걝",18,"걲걳걵걶걹걻",4,"겂겇겈겍겎겏겑겒겓겕",6,"겞겢",5,"겫겭겮겱",6,"겺겾겿곀곂곃곅곆곇곉곊곋곍",7,"곖곘",7,"곢곣곥곦곩곫곭곮곲곴곷",4,"곾곿괁괂괃괅괇",4,"괎괐괒괓"], +["8241","괔괕괖괗괙괚괛괝괞괟괡",7,"괪괫괮",5], +["8261","괶괷괹괺괻괽",6,"굆굈굊",5,"굑굒굓굕굖굗"], +["8281","굙",7,"굢굤",7,"굮굯굱굲굷굸굹굺굾궀궃",4,"궊궋궍궎궏궑",10,"궞",5,"궥",17,"궸",7,"귂귃귅귆귇귉",6,"귒귔",7,"귝귞귟귡귢귣귥",18], +["8341","귺귻귽귾긂",5,"긊긌긎",5,"긕",7], +["8361","긝",18,"긲긳긵긶긹긻긼"], +["8381","긽긾긿깂깄깇깈깉깋깏깑깒깓깕깗",4,"깞깢깣깤깦깧깪깫깭깮깯깱",6,"깺깾",5,"꺆",5,"꺍",46,"꺿껁껂껃껅",6,"껎껒",5,"껚껛껝",8], +["8441","껦껧껩껪껬껮",5,"껵껶껷껹껺껻껽",8], +["8461","꼆꼉꼊꼋꼌꼎꼏꼑",18], +["8481","꼤",7,"꼮꼯꼱꼳꼵",6,"꼾꽀꽄꽅꽆꽇꽊",5,"꽑",10,"꽞",5,"꽦",18,"꽺",5,"꾁꾂꾃꾅꾆꾇꾉",6,"꾒꾓꾔꾖",5,"꾝",26,"꾺꾻꾽꾾"], +["8541","꾿꿁",5,"꿊꿌꿏",4,"꿕",6,"꿝",4], +["8561","꿢",5,"꿪",5,"꿲꿳꿵꿶꿷꿹",6,"뀂뀃"], +["8581","뀅",6,"뀍뀎뀏뀑뀒뀓뀕",6,"뀞",9,"뀩",26,"끆끇끉끋끍끏끐끑끒끖끘끚끛끜끞",29,"끾끿낁낂낃낅",6,"낎낐낒",5,"낛낝낞낣낤"], +["8641","낥낦낧낪낰낲낶낷낹낺낻낽",6,"냆냊",5,"냒"], +["8661","냓냕냖냗냙",6,"냡냢냣냤냦",10], +["8681","냱",22,"넊넍넎넏넑넔넕넖넗넚넞",4,"넦넧넩넪넫넭",6,"넶넺",5,"녂녃녅녆녇녉",6,"녒녓녖녗녙녚녛녝녞녟녡",22,"녺녻녽녾녿놁놃",4,"놊놌놎놏놐놑놕놖놗놙놚놛놝"], +["8741","놞",9,"놩",15], +["8761","놹",18,"뇍뇎뇏뇑뇒뇓뇕"], +["8781","뇖",5,"뇞뇠",7,"뇪뇫뇭뇮뇯뇱",7,"뇺뇼뇾",5,"눆눇눉눊눍",6,"눖눘눚",5,"눡",18,"눵",6,"눽",26,"뉙뉚뉛뉝뉞뉟뉡",6,"뉪",4], +["8841","뉯",4,"뉶",5,"뉽",6,"늆늇늈늊",4], +["8861","늏늒늓늕늖늗늛",4,"늢늤늧늨늩늫늭늮늯늱늲늳늵늶늷"], +["8881","늸",15,"닊닋닍닎닏닑닓",4,"닚닜닞닟닠닡닣닧닩닪닰닱닲닶닼닽닾댂댃댅댆댇댉",6,"댒댖",5,"댝",54,"덗덙덚덝덠덡덢덣"], +["8941","덦덨덪덬덭덯덲덳덵덶덷덹",6,"뎂뎆",5,"뎍"], +["8961","뎎뎏뎑뎒뎓뎕",10,"뎢",5,"뎩뎪뎫뎭"], +["8981","뎮",21,"돆돇돉돊돍돏돑돒돓돖돘돚돜돞돟돡돢돣돥돦돧돩",18,"돽",18,"됑",6,"됙됚됛됝됞됟됡",6,"됪됬",7,"됵",15], +["8a41","둅",10,"둒둓둕둖둗둙",6,"둢둤둦"], +["8a61","둧",4,"둭",18,"뒁뒂"], +["8a81","뒃",4,"뒉",19,"뒞",5,"뒥뒦뒧뒩뒪뒫뒭",7,"뒶뒸뒺",5,"듁듂듃듅듆듇듉",6,"듑듒듓듔듖",5,"듞듟듡듢듥듧",4,"듮듰듲",5,"듹",26,"딖딗딙딚딝"], +["8b41","딞",5,"딦딫",4,"딲딳딵딶딷딹",6,"땂땆"], +["8b61","땇땈땉땊땎땏땑땒땓땕",6,"땞땢",8], +["8b81","땫",52,"떢떣떥떦떧떩떬떭떮떯떲떶",4,"떾떿뗁뗂뗃뗅",6,"뗎뗒",5,"뗙",18,"뗭",18], +["8c41","똀",15,"똒똓똕똖똗똙",4], +["8c61","똞",6,"똦",5,"똭",6,"똵",5], +["8c81","똻",12,"뙉",26,"뙥뙦뙧뙩",50,"뚞뚟뚡뚢뚣뚥",5,"뚭뚮뚯뚰뚲",16], +["8d41","뛃",16,"뛕",8], +["8d61","뛞",17,"뛱뛲뛳뛵뛶뛷뛹뛺"], +["8d81","뛻",4,"뜂뜃뜄뜆",33,"뜪뜫뜭뜮뜱",6,"뜺뜼",7,"띅띆띇띉띊띋띍",6,"띖",9,"띡띢띣띥띦띧띩",6,"띲띴띶",5,"띾띿랁랂랃랅",6,"랎랓랔랕랚랛랝랞"], +["8e41","랟랡",6,"랪랮",5,"랶랷랹",8], +["8e61","럂",4,"럈럊",19], +["8e81","럞",13,"럮럯럱럲럳럵",6,"럾렂",4,"렊렋렍렎렏렑",6,"렚렜렞",5,"렦렧렩렪렫렭",6,"렶렺",5,"롁롂롃롅",11,"롒롔",7,"롞롟롡롢롣롥",6,"롮롰롲",5,"롹롺롻롽",7], +["8f41","뢅",7,"뢎",17], +["8f61","뢠",7,"뢩",6,"뢱뢲뢳뢵뢶뢷뢹",4], +["8f81","뢾뢿룂룄룆",5,"룍룎룏룑룒룓룕",7,"룞룠룢",5,"룪룫룭룮룯룱",6,"룺룼룾",5,"뤅",18,"뤙",6,"뤡",26,"뤾뤿륁륂륃륅",6,"륍륎륐륒",5], +["9041","륚륛륝륞륟륡",6,"륪륬륮",5,"륶륷륹륺륻륽"], +["9061","륾",5,"릆릈릋릌릏",15], +["9081","릟",12,"릮릯릱릲릳릵",6,"릾맀맂",5,"맊맋맍맓",4,"맚맜맟맠맢맦맧맩맪맫맭",6,"맶맻",4,"먂",5,"먉",11,"먖",33,"먺먻먽먾먿멁멃멄멅멆"], +["9141","멇멊멌멏멐멑멒멖멗멙멚멛멝",6,"멦멪",5], +["9161","멲멳멵멶멷멹",9,"몆몈몉몊몋몍",5], +["9181","몓",20,"몪몭몮몯몱몳",4,"몺몼몾",5,"뫅뫆뫇뫉",14,"뫚",33,"뫽뫾뫿묁묂묃묅",7,"묎묐묒",5,"묙묚묛묝묞묟묡",6], +["9241","묨묪묬",7,"묷묹묺묿",4,"뭆뭈뭊뭋뭌뭎뭑뭒"], +["9261","뭓뭕뭖뭗뭙",7,"뭢뭤",7,"뭭",4], +["9281","뭲",21,"뮉뮊뮋뮍뮎뮏뮑",18,"뮥뮦뮧뮩뮪뮫뮭",6,"뮵뮶뮸",7,"믁믂믃믅믆믇믉",6,"믑믒믔",35,"믺믻믽믾밁"], +["9341","밃",4,"밊밎밐밒밓밙밚밠밡밢밣밦밨밪밫밬밮밯밲밳밵"], +["9361","밶밷밹",6,"뱂뱆뱇뱈뱊뱋뱎뱏뱑",8], +["9381","뱚뱛뱜뱞",37,"벆벇벉벊벍벏",4,"벖벘벛",4,"벢벣벥벦벩",6,"벲벶",5,"벾벿볁볂볃볅",7,"볎볒볓볔볖볗볙볚볛볝",22,"볷볹볺볻볽"], +["9441","볾",5,"봆봈봊",5,"봑봒봓봕",8], +["9461","봞",5,"봥",6,"봭",12], +["9481","봺",5,"뵁",6,"뵊뵋뵍뵎뵏뵑",6,"뵚",9,"뵥뵦뵧뵩",22,"붂붃붅붆붋",4,"붒붔붖붗붘붛붝",6,"붥",10,"붱",6,"붹",24], +["9541","뷒뷓뷖뷗뷙뷚뷛뷝",11,"뷪",5,"뷱"], +["9561","뷲뷳뷵뷶뷷뷹",6,"븁븂븄븆",5,"븎븏븑븒븓"], +["9581","븕",6,"븞븠",35,"빆빇빉빊빋빍빏",4,"빖빘빜빝빞빟빢빣빥빦빧빩빫",4,"빲빶",4,"빾빿뺁뺂뺃뺅",6,"뺎뺒",5,"뺚",13,"뺩",14], +["9641","뺸",23,"뻒뻓"], +["9661","뻕뻖뻙",6,"뻡뻢뻦",5,"뻭",8], +["9681","뻶",10,"뼂",5,"뼊",13,"뼚뼞",33,"뽂뽃뽅뽆뽇뽉",6,"뽒뽓뽔뽖",44], +["9741","뾃",16,"뾕",8], +["9761","뾞",17,"뾱",7], +["9781","뾹",11,"뿆",5,"뿎뿏뿑뿒뿓뿕",6,"뿝뿞뿠뿢",89,"쀽쀾쀿"], +["9841","쁀",16,"쁒",5,"쁙쁚쁛"], +["9861","쁝쁞쁟쁡",6,"쁪",15], +["9881","쁺",21,"삒삓삕삖삗삙",6,"삢삤삦",5,"삮삱삲삷",4,"삾샂샃샄샆샇샊샋샍샎샏샑",6,"샚샞",5,"샦샧샩샪샫샭",6,"샶샸샺",5,"섁섂섃섅섆섇섉",6,"섑섒섓섔섖",5,"섡섢섥섨섩섪섫섮"], +["9941","섲섳섴섵섷섺섻섽섾섿셁",6,"셊셎",5,"셖셗"], +["9961","셙셚셛셝",6,"셦셪",5,"셱셲셳셵셶셷셹셺셻"], +["9981","셼",8,"솆",5,"솏솑솒솓솕솗",4,"솞솠솢솣솤솦솧솪솫솭솮솯솱",11,"솾",5,"쇅쇆쇇쇉쇊쇋쇍",6,"쇕쇖쇙",6,"쇡쇢쇣쇥쇦쇧쇩",6,"쇲쇴",7,"쇾쇿숁숂숃숅",6,"숎숐숒",5,"숚숛숝숞숡숢숣"], +["9a41","숤숥숦숧숪숬숮숰숳숵",16], +["9a61","쉆쉇쉉",6,"쉒쉓쉕쉖쉗쉙",6,"쉡쉢쉣쉤쉦"], +["9a81","쉧",4,"쉮쉯쉱쉲쉳쉵",6,"쉾슀슂",5,"슊",5,"슑",6,"슙슚슜슞",5,"슦슧슩슪슫슮",5,"슶슸슺",33,"싞싟싡싢싥",5,"싮싰싲싳싴싵싷싺싽싾싿쌁",6,"쌊쌋쌎쌏"], +["9b41","쌐쌑쌒쌖쌗쌙쌚쌛쌝",6,"쌦쌧쌪",8], +["9b61","쌳",17,"썆",7], +["9b81","썎",25,"썪썫썭썮썯썱썳",4,"썺썻썾",5,"쎅쎆쎇쎉쎊쎋쎍",50,"쏁",22,"쏚"], +["9c41","쏛쏝쏞쏡쏣",4,"쏪쏫쏬쏮",5,"쏶쏷쏹",5], +["9c61","쏿",8,"쐉",6,"쐑",9], +["9c81","쐛",8,"쐥",6,"쐭쐮쐯쐱쐲쐳쐵",6,"쐾",9,"쑉",26,"쑦쑧쑩쑪쑫쑭",6,"쑶쑷쑸쑺",5,"쒁",18,"쒕",6,"쒝",12], +["9d41","쒪",13,"쒹쒺쒻쒽",8], +["9d61","쓆",25], +["9d81","쓠",8,"쓪",5,"쓲쓳쓵쓶쓷쓹쓻쓼쓽쓾씂",9,"씍씎씏씑씒씓씕",6,"씝",10,"씪씫씭씮씯씱",6,"씺씼씾",5,"앆앇앋앏앐앑앒앖앚앛앜앟앢앣앥앦앧앩",6,"앲앶",5,"앾앿얁얂얃얅얆얈얉얊얋얎얐얒얓얔"], +["9e41","얖얙얚얛얝얞얟얡",7,"얪",9,"얶"], +["9e61","얷얺얿",4,"엋엍엏엒엓엕엖엗엙",6,"엢엤엦엧"], +["9e81","엨엩엪엫엯엱엲엳엵엸엹엺엻옂옃옄옉옊옋옍옎옏옑",6,"옚옝",6,"옦옧옩옪옫옯옱옲옶옸옺옼옽옾옿왂왃왅왆왇왉",6,"왒왖",5,"왞왟왡",10,"왭왮왰왲",5,"왺왻왽왾왿욁",6,"욊욌욎",5,"욖욗욙욚욛욝",6,"욦"], +["9f41","욨욪",5,"욲욳욵욶욷욻",4,"웂웄웆",5,"웎"], +["9f61","웏웑웒웓웕",6,"웞웟웢",5,"웪웫웭웮웯웱웲"], +["9f81","웳",4,"웺웻웼웾",5,"윆윇윉윊윋윍",6,"윖윘윚",5,"윢윣윥윦윧윩",6,"윲윴윶윸윹윺윻윾윿읁읂읃읅",4,"읋읎읐읙읚읛읝읞읟읡",6,"읩읪읬",7,"읶읷읹읺읻읿잀잁잂잆잋잌잍잏잒잓잕잙잛",4,"잢잧",4,"잮잯잱잲잳잵잶잷"], +["a041","잸잹잺잻잾쟂",5,"쟊쟋쟍쟏쟑",6,"쟙쟚쟛쟜"], +["a061","쟞",5,"쟥쟦쟧쟩쟪쟫쟭",13], +["a081","쟻",4,"젂젃젅젆젇젉젋",4,"젒젔젗",4,"젞젟젡젢젣젥",6,"젮젰젲",5,"젹젺젻젽젾젿졁",6,"졊졋졎",5,"졕",26,"졲졳졵졶졷졹졻",4,"좂좄좈좉좊좎",5,"좕",7,"좞좠좢좣좤"], +["a141","좥좦좧좩",18,"좾좿죀죁"], +["a161","죂죃죅죆죇죉죊죋죍",6,"죖죘죚",5,"죢죣죥"], +["a181","죦",14,"죶",5,"죾죿줁줂줃줇",4,"줎 、。·‥…¨〃­―∥\∼‘’“”〔〕〈",9,"±×÷≠≤≥∞∴°′″℃Å¢£¥♂♀∠⊥⌒∂∇≡≒§※☆★○●◎◇◆□■△▲▽▼→←↑↓↔〓≪≫√∽∝∵∫∬∈∋⊆⊇⊂⊃∪∩∧∨¬"], +["a241","줐줒",5,"줙",18], +["a261","줭",6,"줵",18], +["a281","쥈",7,"쥒쥓쥕쥖쥗쥙",6,"쥢쥤",7,"쥭쥮쥯⇒⇔∀∃´~ˇ˘˝˚˙¸˛¡¿ː∮∑∏¤℉‰◁◀▷▶♤♠♡♥♧♣⊙◈▣◐◑▒▤▥▨▧▦▩♨☏☎☜☞¶†‡↕↗↙↖↘♭♩♪♬㉿㈜№㏇™㏂㏘℡€®"], +["a341","쥱쥲쥳쥵",6,"쥽",10,"즊즋즍즎즏"], +["a361","즑",6,"즚즜즞",16], +["a381","즯",16,"짂짃짅짆짉짋",4,"짒짔짗짘짛!",58,"₩]",32," ̄"], +["a441","짞짟짡짣짥짦짨짩짪짫짮짲",5,"짺짻짽짾짿쨁쨂쨃쨄"], +["a461","쨅쨆쨇쨊쨎",5,"쨕쨖쨗쨙",12], +["a481","쨦쨧쨨쨪",28,"ㄱ",93], +["a541","쩇",4,"쩎쩏쩑쩒쩓쩕",6,"쩞쩢",5,"쩩쩪"], +["a561","쩫",17,"쩾",5,"쪅쪆"], +["a581","쪇",16,"쪙",14,"ⅰ",9], +["a5b0","Ⅰ",9], +["a5c1","Α",16,"Σ",6], +["a5e1","α",16,"σ",6], +["a641","쪨",19,"쪾쪿쫁쫂쫃쫅"], +["a661","쫆",5,"쫎쫐쫒쫔쫕쫖쫗쫚",5,"쫡",6], +["a681","쫨쫩쫪쫫쫭",6,"쫵",18,"쬉쬊─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂┒┑┚┙┖┕┎┍┞┟┡┢┦┧┩┪┭┮┱┲┵┶┹┺┽┾╀╁╃",7], +["a741","쬋",4,"쬑쬒쬓쬕쬖쬗쬙",6,"쬢",7], +["a761","쬪",22,"쭂쭃쭄"], +["a781","쭅쭆쭇쭊쭋쭍쭎쭏쭑",6,"쭚쭛쭜쭞",5,"쭥",7,"㎕㎖㎗ℓ㎘㏄㎣㎤㎥㎦㎙",9,"㏊㎍㎎㎏㏏㎈㎉㏈㎧㎨㎰",9,"㎀",4,"㎺",5,"㎐",4,"Ω㏀㏁㎊㎋㎌㏖㏅㎭㎮㎯㏛㎩㎪㎫㎬㏝㏐㏓㏃㏉㏜㏆"], +["a841","쭭",10,"쭺",14], +["a861","쮉",18,"쮝",6], +["a881","쮤",19,"쮹",11,"ÆÐªĦ"], +["a8a6","IJ"], +["a8a8","ĿŁØŒºÞŦŊ"], +["a8b1","㉠",27,"ⓐ",25,"①",14,"½⅓⅔¼¾⅛⅜⅝⅞"], +["a941","쯅",14,"쯕",10], +["a961","쯠쯡쯢쯣쯥쯦쯨쯪",18], +["a981","쯽",14,"찎찏찑찒찓찕",6,"찞찟찠찣찤æđðħıijĸŀłøœßþŧŋʼn㈀",27,"⒜",25,"⑴",14,"¹²³⁴ⁿ₁₂₃₄"], +["aa41","찥찦찪찫찭찯찱",6,"찺찿",4,"챆챇챉챊챋챍챎"], +["aa61","챏",4,"챖챚",5,"챡챢챣챥챧챩",6,"챱챲"], +["aa81","챳챴챶",29,"ぁ",82], +["ab41","첔첕첖첗첚첛첝첞첟첡",6,"첪첮",5,"첶첷첹"], +["ab61","첺첻첽",6,"쳆쳈쳊",5,"쳑쳒쳓쳕",5], +["ab81","쳛",8,"쳥",6,"쳭쳮쳯쳱",12,"ァ",85], +["ac41","쳾쳿촀촂",5,"촊촋촍촎촏촑",6,"촚촜촞촟촠"], +["ac61","촡촢촣촥촦촧촩촪촫촭",11,"촺",4], +["ac81","촿",28,"쵝쵞쵟А",5,"ЁЖ",25], +["acd1","а",5,"ёж",25], +["ad41","쵡쵢쵣쵥",6,"쵮쵰쵲",5,"쵹",7], +["ad61","춁",6,"춉",10,"춖춗춙춚춛춝춞춟"], +["ad81","춠춡춢춣춦춨춪",5,"춱",18,"췅"], +["ae41","췆",5,"췍췎췏췑",16], +["ae61","췢",5,"췩췪췫췭췮췯췱",6,"췺췼췾",4], +["ae81","츃츅츆츇츉츊츋츍",6,"츕츖츗츘츚",5,"츢츣츥츦츧츩츪츫"], +["af41","츬츭츮츯츲츴츶",19], +["af61","칊",13,"칚칛칝칞칢",5,"칪칬"], +["af81","칮",5,"칶칷칹칺칻칽",6,"캆캈캊",5,"캒캓캕캖캗캙"], +["b041","캚",5,"캢캦",5,"캮",12], +["b061","캻",5,"컂",19], +["b081","컖",13,"컦컧컩컪컭",6,"컶컺",5,"가각간갇갈갉갊감",7,"같",4,"갠갤갬갭갯갰갱갸갹갼걀걋걍걔걘걜거걱건걷걸걺검겁것겄겅겆겉겊겋게겐겔겜겝겟겠겡겨격겪견겯결겸겹겻겼경곁계곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆"], +["b141","켂켃켅켆켇켉",6,"켒켔켖",5,"켝켞켟켡켢켣"], +["b161","켥",6,"켮켲",5,"켹",11], +["b181","콅",14,"콖콗콙콚콛콝",6,"콦콨콪콫콬괌괍괏광괘괜괠괩괬괭괴괵괸괼굄굅굇굉교굔굘굡굣구국군굳굴굵굶굻굼굽굿궁궂궈궉권궐궜궝궤궷귀귁귄귈귐귑귓규균귤그극근귿글긁금급긋긍긔기긱긴긷길긺김깁깃깅깆깊까깍깎깐깔깖깜깝깟깠깡깥깨깩깬깰깸"], +["b241","콭콮콯콲콳콵콶콷콹",6,"쾁쾂쾃쾄쾆",5,"쾍"], +["b261","쾎",18,"쾢",5,"쾩"], +["b281","쾪",5,"쾱",18,"쿅",6,"깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄껌껍껏껐껑께껙껜껨껫껭껴껸껼꼇꼈꼍꼐꼬꼭꼰꼲꼴꼼꼽꼿꽁꽂꽃꽈꽉꽐꽜꽝꽤꽥꽹꾀꾄꾈꾐꾑꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿔꿜꿨꿩꿰꿱꿴꿸뀀뀁뀄뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끕끗끙"], +["b341","쿌",19,"쿢쿣쿥쿦쿧쿩"], +["b361","쿪",5,"쿲쿴쿶",5,"쿽쿾쿿퀁퀂퀃퀅",5], +["b381","퀋",5,"퀒",5,"퀙",19,"끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남납낫",4,"낱낳내낵낸낼냄냅냇냈냉냐냑냔냘냠냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녑녔녕녘녜녠노녹논놀놂놈놉놋농높놓놔놘놜놨뇌뇐뇔뇜뇝"], +["b441","퀮",5,"퀶퀷퀹퀺퀻퀽",6,"큆큈큊",5], +["b461","큑큒큓큕큖큗큙",6,"큡",10,"큮큯"], +["b481","큱큲큳큵",6,"큾큿킀킂",18,"뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨뉩뉴뉵뉼늄늅늉느늑는늘늙늚늠늡늣능늦늪늬늰늴니닉닌닐닒님닙닛닝닢다닥닦단닫",4,"닳담답닷",4,"닿대댁댄댈댐댑댓댔댕댜더덕덖던덛덜덞덟덤덥"], +["b541","킕",14,"킦킧킩킪킫킭",5], +["b561","킳킶킸킺",5,"탂탃탅탆탇탊",5,"탒탖",4], +["b581","탛탞탟탡탢탣탥",6,"탮탲",5,"탹",11,"덧덩덫덮데덱덴델뎀뎁뎃뎄뎅뎌뎐뎔뎠뎡뎨뎬도독돈돋돌돎돐돔돕돗동돛돝돠돤돨돼됐되된될됨됩됫됴두둑둔둘둠둡둣둥둬뒀뒈뒝뒤뒨뒬뒵뒷뒹듀듄듈듐듕드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸"], +["b641","턅",7,"턎",17], +["b661","턠",15,"턲턳턵턶턷턹턻턼턽턾"], +["b681","턿텂텆",5,"텎텏텑텒텓텕",6,"텞텠텢",5,"텩텪텫텭땀땁땃땄땅땋때땍땐땔땜땝땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌뗍뗏뗐뗑뗘뗬또똑똔똘똥똬똴뙈뙤뙨뚜뚝뚠뚤뚫뚬뚱뛔뛰뛴뛸뜀뜁뜅뜨뜩뜬뜯뜰뜸뜹뜻띄띈띌띔띕띠띤띨띰띱띳띵라락란랄람랍랏랐랑랒랖랗"], +["b741","텮",13,"텽",6,"톅톆톇톉톊"], +["b761","톋",20,"톢톣톥톦톧"], +["b781","톩",6,"톲톴톶톷톸톹톻톽톾톿퇁",14,"래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀렁렇레렉렌렐렘렙렛렝려력련렬렴렵렷렸령례롄롑롓로록론롤롬롭롯롱롸롼뢍뢨뢰뢴뢸룀룁룃룅료룐룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륏륑류륙륜률륨륩"], +["b841","퇐",7,"퇙",17], +["b861","퇫",8,"퇵퇶퇷퇹",13], +["b881","툈툊",5,"툑",24,"륫륭르륵른를름릅릇릉릊릍릎리릭린릴림립릿링마막만많",4,"맘맙맛망맞맡맣매맥맨맬맴맵맷맸맹맺먀먁먈먕머먹먼멀멂멈멉멋멍멎멓메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼"], +["b941","툪툫툮툯툱툲툳툵",6,"툾퉀퉂",5,"퉉퉊퉋퉌"], +["b961","퉍",14,"퉝",6,"퉥퉦퉧퉨"], +["b981","퉩",22,"튂튃튅튆튇튉튊튋튌묀묄묍묏묑묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭬뮈뮌뮐뮤뮨뮬뮴뮷므믄믈믐믓미믹민믿밀밂밈밉밋밌밍및밑바",4,"받",4,"밤밥밧방밭배백밴밸뱀뱁뱃뱄뱅뱉뱌뱍뱐뱝버벅번벋벌벎범법벗"], +["ba41","튍튎튏튒튓튔튖",5,"튝튞튟튡튢튣튥",6,"튭"], +["ba61","튮튯튰튲",5,"튺튻튽튾틁틃",4,"틊틌",5], +["ba81","틒틓틕틖틗틙틚틛틝",6,"틦",9,"틲틳틵틶틷틹틺벙벚베벡벤벧벨벰벱벳벴벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봔봤봬뵀뵈뵉뵌뵐뵘뵙뵤뵨부북분붇불붉붊붐붑붓붕붙붚붜붤붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브븍븐블븜븝븟비빅빈빌빎빔빕빗빙빚빛빠빡빤"], +["bb41","틻",4,"팂팄팆",5,"팏팑팒팓팕팗",4,"팞팢팣"], +["bb61","팤팦팧팪팫팭팮팯팱",6,"팺팾",5,"퍆퍇퍈퍉"], +["bb81","퍊",31,"빨빪빰빱빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺙뺨뻐뻑뻔뻗뻘뻠뻣뻤뻥뻬뼁뼈뼉뼘뼙뼛뼜뼝뽀뽁뽄뽈뽐뽑뽕뾔뾰뿅뿌뿍뿐뿔뿜뿟뿡쀼쁑쁘쁜쁠쁨쁩삐삑삔삘삠삡삣삥사삭삯산삳살삵삶삼삽삿샀상샅새색샌샐샘샙샛샜생샤"], +["bc41","퍪",17,"퍾퍿펁펂펃펅펆펇"], +["bc61","펈펉펊펋펎펒",5,"펚펛펝펞펟펡",6,"펪펬펮"], +["bc81","펯",4,"펵펶펷펹펺펻펽",6,"폆폇폊",5,"폑",5,"샥샨샬샴샵샷샹섀섄섈섐섕서",4,"섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌셍셔셕션셜셤셥셧셨셩셰셴셸솅소속솎손솔솖솜솝솟송솥솨솩솬솰솽쇄쇈쇌쇔쇗쇘쇠쇤쇨쇰쇱쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭"], +["bd41","폗폙",7,"폢폤",7,"폮폯폱폲폳폵폶폷"], +["bd61","폸폹폺폻폾퐀퐂",5,"퐉",13], +["bd81","퐗",5,"퐞",25,"숯숱숲숴쉈쉐쉑쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슐슘슛슝스슥슨슬슭슴습슷승시식신싣실싫심십싯싱싶싸싹싻싼쌀쌈쌉쌌쌍쌓쌔쌕쌘쌜쌤쌥쌨쌩썅써썩썬썰썲썸썹썼썽쎄쎈쎌쏀쏘쏙쏜쏟쏠쏢쏨쏩쏭쏴쏵쏸쐈쐐쐤쐬쐰"], +["be41","퐸",7,"푁푂푃푅",14], +["be61","푔",7,"푝푞푟푡푢푣푥",7,"푮푰푱푲"], +["be81","푳",4,"푺푻푽푾풁풃",4,"풊풌풎",5,"풕",8,"쐴쐼쐽쑈쑤쑥쑨쑬쑴쑵쑹쒀쒔쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀씁씌씐씔씜씨씩씬씰씸씹씻씽아악안앉않알앍앎앓암압앗았앙앝앞애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얕얗얘얜얠얩어억언얹얻얼얽얾엄",6,"엌엎"], +["bf41","풞",10,"풪",14], +["bf61","풹",18,"퓍퓎퓏퓑퓒퓓퓕"], +["bf81","퓖",5,"퓝퓞퓠",7,"퓩퓪퓫퓭퓮퓯퓱",6,"퓹퓺퓼에엑엔엘엠엡엣엥여역엮연열엶엷염",5,"옅옆옇예옌옐옘옙옛옜오옥온올옭옮옰옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왯왱외왹왼욀욈욉욋욍요욕욘욜욤욥욧용우욱운울욹욺움웁웃웅워웍원월웜웝웠웡웨"], +["c041","퓾",5,"픅픆픇픉픊픋픍",6,"픖픘",5], +["c061","픞",25], +["c081","픸픹픺픻픾픿핁핂핃핅",6,"핎핐핒",5,"핚핛핝핞핟핡핢핣웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽은을읊음읍읏응",7,"읜읠읨읫이익인일읽읾잃임입잇있잉잊잎자작잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟎쟐쟘쟝쟤쟨쟬저적전절젊"], +["c141","핤핦핧핪핬핮",5,"핶핷핹핺핻핽",6,"햆햊햋"], +["c161","햌햍햎햏햑",19,"햦햧"], +["c181","햨",31,"점접젓정젖제젝젠젤젬젭젯젱져젼졀졈졉졌졍졔조족존졸졺좀좁좃종좆좇좋좌좍좔좝좟좡좨좼좽죄죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌줍줏중줘줬줴쥐쥑쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌즐즘즙즛증지직진짇질짊짐집짓"], +["c241","헊헋헍헎헏헑헓",4,"헚헜헞",5,"헦헧헩헪헫헭헮"], +["c261","헯",4,"헶헸헺",5,"혂혃혅혆혇혉",6,"혒"], +["c281","혖",5,"혝혞혟혡혢혣혥",7,"혮",9,"혺혻징짖짙짚짜짝짠짢짤짧짬짭짯짰짱째짹짼쨀쨈쨉쨋쨌쨍쨔쨘쨩쩌쩍쩐쩔쩜쩝쩟쩠쩡쩨쩽쪄쪘쪼쪽쫀쫄쫌쫍쫏쫑쫓쫘쫙쫠쫬쫴쬈쬐쬔쬘쬠쬡쭁쭈쭉쭌쭐쭘쭙쭝쭤쭸쭹쮜쮸쯔쯤쯧쯩찌찍찐찔찜찝찡찢찧차착찬찮찰참찹찻"], +["c341","혽혾혿홁홂홃홄홆홇홊홌홎홏홐홒홓홖홗홙홚홛홝",4], +["c361","홢",4,"홨홪",5,"홲홳홵",11], +["c381","횁횂횄횆",5,"횎횏횑횒횓횕",7,"횞횠횢",5,"횩횪찼창찾채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳬쳰촁초촉촌촐촘촙촛총촤촨촬촹최쵠쵤쵬쵭쵯쵱쵸춈추축춘출춤춥춧충춰췄췌췐취췬췰췸췹췻췽츄츈츌츔츙츠측츤츨츰츱츳층"], +["c441","횫횭횮횯횱",7,"횺횼",7,"훆훇훉훊훋"], +["c461","훍훎훏훐훒훓훕훖훘훚",5,"훡훢훣훥훦훧훩",4], +["c481","훮훯훱훲훳훴훶",5,"훾훿휁휂휃휅",11,"휒휓휔치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑캔캘캠캡캣캤캥캬캭컁커컥컨컫컬컴컵컷컸컹케켁켄켈켐켑켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼"], +["c541","휕휖휗휚휛휝휞휟휡",6,"휪휬휮",5,"휶휷휹"], +["c561","휺휻휽",6,"흅흆흈흊",5,"흒흓흕흚",4], +["c581","흟흢흤흦흧흨흪흫흭흮흯흱흲흳흵",6,"흾흿힀힂",5,"힊힋큄큅큇큉큐큔큘큠크큭큰클큼큽킁키킥킨킬킴킵킷킹타탁탄탈탉탐탑탓탔탕태택탠탤탬탭탯탰탱탸턍터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉툐투툭툰툴툼툽툿퉁퉈퉜"], +["c641","힍힎힏힑",6,"힚힜힞",5], +["c6a1","퉤튀튁튄튈튐튑튕튜튠튤튬튱트특튼튿틀틂틈틉틋틔틘틜틤틥티틱틴틸팀팁팃팅파팍팎판팔팖팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍅퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폅폈평폐폘폡폣포폭폰폴폼폽폿퐁"], +["c7a1","퐈퐝푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋풍풔풩퓌퓐퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗피픽핀필핌핍핏핑하학한할핥함합핫항해핵핸핼햄햅햇했행햐향허헉헌헐헒험헙헛헝헤헥헨헬헴헵헷헹혀혁현혈혐협혓혔형혜혠"], +["c8a1","혤혭호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱홴횃횅회획횐횔횝횟횡효횬횰횹횻후훅훈훌훑훔훗훙훠훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼흄흇흉흐흑흔흖흗흘흙흠흡흣흥흩희흰흴흼흽힁히힉힌힐힘힙힛힝"], +["caa1","伽佳假價加可呵哥嘉嫁家暇架枷柯歌珂痂稼苛茄街袈訶賈跏軻迦駕刻却各恪慤殼珏脚覺角閣侃刊墾奸姦干幹懇揀杆柬桿澗癎看磵稈竿簡肝艮艱諫間乫喝曷渴碣竭葛褐蝎鞨勘坎堪嵌感憾戡敢柑橄減甘疳監瞰紺邯鑑鑒龕"], +["cba1","匣岬甲胛鉀閘剛堈姜岡崗康强彊慷江畺疆糠絳綱羌腔舡薑襁講鋼降鱇介价個凱塏愷愾慨改槪漑疥皆盖箇芥蓋豈鎧開喀客坑更粳羹醵倨去居巨拒据據擧渠炬祛距踞車遽鉅鋸乾件健巾建愆楗腱虔蹇鍵騫乞傑杰桀儉劍劒檢"], +["cca1","瞼鈐黔劫怯迲偈憩揭擊格檄激膈覡隔堅牽犬甄絹繭肩見譴遣鵑抉決潔結缺訣兼慊箝謙鉗鎌京俓倞傾儆勁勍卿坰境庚徑慶憬擎敬景暻更梗涇炅烱璟璥瓊痙硬磬竟競絅經耕耿脛莖警輕逕鏡頃頸驚鯨係啓堺契季屆悸戒桂械"], +["cda1","棨溪界癸磎稽系繫繼計誡谿階鷄古叩告呱固姑孤尻庫拷攷故敲暠枯槁沽痼皐睾稿羔考股膏苦苽菰藁蠱袴誥賈辜錮雇顧高鼓哭斛曲梏穀谷鵠困坤崑昆梱棍滾琨袞鯤汨滑骨供公共功孔工恐恭拱控攻珙空蚣貢鞏串寡戈果瓜"], +["cea1","科菓誇課跨過鍋顆廓槨藿郭串冠官寬慣棺款灌琯瓘管罐菅觀貫關館刮恝括适侊光匡壙廣曠洸炚狂珖筐胱鑛卦掛罫乖傀塊壞怪愧拐槐魁宏紘肱轟交僑咬喬嬌嶠巧攪敎校橋狡皎矯絞翹膠蕎蛟較轎郊餃驕鮫丘久九仇俱具勾"], +["cfa1","區口句咎嘔坵垢寇嶇廐懼拘救枸柩構歐毆毬求溝灸狗玖球瞿矩究絿耉臼舅舊苟衢謳購軀逑邱鉤銶駒驅鳩鷗龜國局菊鞠鞫麴君窘群裙軍郡堀屈掘窟宮弓穹窮芎躬倦券勸卷圈拳捲權淃眷厥獗蕨蹶闕机櫃潰詭軌饋句晷歸貴"], +["d0a1","鬼龜叫圭奎揆槻珪硅窺竅糾葵規赳逵閨勻均畇筠菌鈞龜橘克剋劇戟棘極隙僅劤勤懃斤根槿瑾筋芹菫覲謹近饉契今妗擒昑檎琴禁禽芩衾衿襟金錦伋及急扱汲級給亘兢矜肯企伎其冀嗜器圻基埼夔奇妓寄岐崎己幾忌技旗旣"], +["d1a1","朞期杞棋棄機欺氣汽沂淇玘琦琪璂璣畸畿碁磯祁祇祈祺箕紀綺羈耆耭肌記譏豈起錡錤飢饑騎騏驥麒緊佶吉拮桔金喫儺喇奈娜懦懶拏拿癩",5,"那樂",4,"諾酪駱亂卵暖欄煖爛蘭難鸞捏捺南嵐枏楠湳濫男藍襤拉"], +["d2a1","納臘蠟衲囊娘廊",4,"乃來內奈柰耐冷女年撚秊念恬拈捻寧寗努勞奴弩怒擄櫓爐瑙盧",5,"駑魯",10,"濃籠聾膿農惱牢磊腦賂雷尿壘",7,"嫩訥杻紐勒",5,"能菱陵尼泥匿溺多茶"], +["d3a1","丹亶但單團壇彖斷旦檀段湍短端簞緞蛋袒鄲鍛撻澾獺疸達啖坍憺擔曇淡湛潭澹痰聃膽蕁覃談譚錟沓畓答踏遝唐堂塘幢戇撞棠當糖螳黨代垈坮大對岱帶待戴擡玳臺袋貸隊黛宅德悳倒刀到圖堵塗導屠島嶋度徒悼挑掉搗桃"], +["d4a1","棹櫂淘渡滔濤燾盜睹禱稻萄覩賭跳蹈逃途道都鍍陶韜毒瀆牘犢獨督禿篤纛讀墩惇敦旽暾沌焞燉豚頓乭突仝冬凍動同憧東桐棟洞潼疼瞳童胴董銅兜斗杜枓痘竇荳讀豆逗頭屯臀芚遁遯鈍得嶝橙燈登等藤謄鄧騰喇懶拏癩羅"], +["d5a1","蘿螺裸邏樂洛烙珞絡落諾酪駱丹亂卵欄欒瀾爛蘭鸞剌辣嵐擥攬欖濫籃纜藍襤覽拉臘蠟廊朗浪狼琅瑯螂郞來崍徠萊冷掠略亮倆兩凉梁樑粮粱糧良諒輛量侶儷勵呂廬慮戾旅櫚濾礪藜蠣閭驢驪麗黎力曆歷瀝礫轢靂憐戀攣漣"], +["d6a1","煉璉練聯蓮輦連鍊冽列劣洌烈裂廉斂殮濂簾獵令伶囹寧岺嶺怜玲笭羚翎聆逞鈴零靈領齡例澧禮醴隷勞怒撈擄櫓潞瀘爐盧老蘆虜路輅露魯鷺鹵碌祿綠菉錄鹿麓論壟弄朧瀧瓏籠聾儡瀨牢磊賂賚賴雷了僚寮廖料燎療瞭聊蓼"], +["d7a1","遼鬧龍壘婁屢樓淚漏瘻累縷蔞褸鏤陋劉旒柳榴流溜瀏琉瑠留瘤硫謬類六戮陸侖倫崙淪綸輪律慄栗率隆勒肋凜凌楞稜綾菱陵俚利厘吏唎履悧李梨浬犁狸理璃異痢籬罹羸莉裏裡里釐離鯉吝潾燐璘藺躪隣鱗麟林淋琳臨霖砬"], +["d8a1","立笠粒摩瑪痲碼磨馬魔麻寞幕漠膜莫邈万卍娩巒彎慢挽晩曼滿漫灣瞞萬蔓蠻輓饅鰻唜抹末沫茉襪靺亡妄忘忙望網罔芒茫莽輞邙埋妹媒寐昧枚梅每煤罵買賣邁魅脈貊陌驀麥孟氓猛盲盟萌冪覓免冕勉棉沔眄眠綿緬面麵滅"], +["d9a1","蔑冥名命明暝椧溟皿瞑茗蓂螟酩銘鳴袂侮冒募姆帽慕摸摹暮某模母毛牟牡瑁眸矛耗芼茅謀謨貌木沐牧目睦穆鶩歿沒夢朦蒙卯墓妙廟描昴杳渺猫竗苗錨務巫憮懋戊拇撫无楙武毋無珷畝繆舞茂蕪誣貿霧鵡墨默們刎吻問文"], +["daa1","汶紊紋聞蚊門雯勿沕物味媚尾嵋彌微未梶楣渼湄眉米美薇謎迷靡黴岷悶愍憫敏旻旼民泯玟珉緡閔密蜜謐剝博拍搏撲朴樸泊珀璞箔粕縛膊舶薄迫雹駁伴半反叛拌搬攀斑槃泮潘班畔瘢盤盼磐磻礬絆般蟠返頒飯勃拔撥渤潑"], +["dba1","發跋醱鉢髮魃倣傍坊妨尨幇彷房放方旁昉枋榜滂磅紡肪膀舫芳蒡蚌訪謗邦防龐倍俳北培徘拜排杯湃焙盃背胚裴裵褙賠輩配陪伯佰帛柏栢白百魄幡樊煩燔番磻繁蕃藩飜伐筏罰閥凡帆梵氾汎泛犯範范法琺僻劈壁擘檗璧癖"], +["dca1","碧蘗闢霹便卞弁變辨辯邊別瞥鱉鼈丙倂兵屛幷昞昺柄棅炳甁病秉竝輧餠騈保堡報寶普步洑湺潽珤甫菩補褓譜輔伏僕匐卜宓復服福腹茯蔔複覆輹輻馥鰒本乶俸奉封峯峰捧棒烽熢琫縫蓬蜂逢鋒鳳不付俯傅剖副否咐埠夫婦"], +["dda1","孚孵富府復扶敷斧浮溥父符簿缶腐腑膚艀芙莩訃負賦賻赴趺部釜阜附駙鳧北分吩噴墳奔奮忿憤扮昐汾焚盆粉糞紛芬賁雰不佛弗彿拂崩朋棚硼繃鵬丕備匕匪卑妃婢庇悲憊扉批斐枇榧比毖毗毘沸泌琵痺砒碑秕秘粃緋翡肥"], +["dea1","脾臂菲蜚裨誹譬費鄙非飛鼻嚬嬪彬斌檳殯浜濱瀕牝玭貧賓頻憑氷聘騁乍事些仕伺似使俟僿史司唆嗣四士奢娑寫寺射巳師徙思捨斜斯柶査梭死沙泗渣瀉獅砂社祀祠私篩紗絲肆舍莎蓑蛇裟詐詞謝賜赦辭邪飼駟麝削數朔索"], +["dfa1","傘刪山散汕珊産疝算蒜酸霰乷撒殺煞薩三參杉森渗芟蔘衫揷澁鈒颯上傷像償商喪嘗孀尙峠常床庠廂想桑橡湘爽牀狀相祥箱翔裳觴詳象賞霜塞璽賽嗇塞穡索色牲生甥省笙墅壻嶼序庶徐恕抒捿敍暑曙書栖棲犀瑞筮絮緖署"], +["e0a1","胥舒薯西誓逝鋤黍鼠夕奭席惜昔晳析汐淅潟石碩蓆釋錫仙僊先善嬋宣扇敾旋渲煽琁瑄璇璿癬禪線繕羨腺膳船蘚蟬詵跣選銑鐥饍鮮卨屑楔泄洩渫舌薛褻設說雪齧剡暹殲纖蟾贍閃陝攝涉燮葉城姓宬性惺成星晟猩珹盛省筬"], +["e1a1","聖聲腥誠醒世勢歲洗稅笹細說貰召嘯塑宵小少巢所掃搔昭梳沼消溯瀟炤燒甦疏疎瘙笑篠簫素紹蔬蕭蘇訴逍遡邵銷韶騷俗屬束涑粟續謖贖速孫巽損蓀遜飡率宋悚松淞訟誦送頌刷殺灑碎鎖衰釗修受嗽囚垂壽嫂守岫峀帥愁"], +["e2a1","戍手授搜收數樹殊水洙漱燧狩獸琇璲瘦睡秀穗竪粹綏綬繡羞脩茱蒐蓚藪袖誰讐輸遂邃酬銖銹隋隧隨雖需須首髓鬚叔塾夙孰宿淑潚熟琡璹肅菽巡徇循恂旬栒楯橓殉洵淳珣盾瞬筍純脣舜荀蓴蕣詢諄醇錞順馴戌術述鉥崇崧"], +["e3a1","嵩瑟膝蝨濕拾習褶襲丞乘僧勝升承昇繩蠅陞侍匙嘶始媤尸屎屍市弑恃施是時枾柴猜矢示翅蒔蓍視試詩諡豕豺埴寔式息拭植殖湜熄篒蝕識軾食飾伸侁信呻娠宸愼新晨燼申神紳腎臣莘薪藎蜃訊身辛辰迅失室實悉審尋心沁"], +["e4a1","沈深瀋甚芯諶什十拾雙氏亞俄兒啞娥峨我牙芽莪蛾衙訝阿雅餓鴉鵝堊岳嶽幄惡愕握樂渥鄂鍔顎鰐齷安岸按晏案眼雁鞍顔鮟斡謁軋閼唵岩巖庵暗癌菴闇壓押狎鴨仰央怏昻殃秧鴦厓哀埃崖愛曖涯碍艾隘靄厄扼掖液縊腋額"], +["e5a1","櫻罌鶯鸚也倻冶夜惹揶椰爺耶若野弱掠略約若葯蒻藥躍亮佯兩凉壤孃恙揚攘敭暘梁楊樣洋瀁煬痒瘍禳穰糧羊良襄諒讓釀陽量養圄御於漁瘀禦語馭魚齬億憶抑檍臆偃堰彦焉言諺孼蘖俺儼嚴奄掩淹嶪業円予余勵呂女如廬"], +["e6a1","旅歟汝濾璵礖礪與艅茹輿轝閭餘驪麗黎亦力域役易曆歷疫繹譯轢逆驛嚥堧姸娟宴年延憐戀捐挻撚椽沇沿涎涓淵演漣烟然煙煉燃燕璉硏硯秊筵緣練縯聯衍軟輦蓮連鉛鍊鳶列劣咽悅涅烈熱裂說閱厭廉念捻染殮炎焰琰艶苒"], +["e7a1","簾閻髥鹽曄獵燁葉令囹塋寧嶺嶸影怜映暎楹榮永泳渶潁濚瀛瀯煐營獰玲瑛瑩瓔盈穎纓羚聆英詠迎鈴鍈零霙靈領乂倪例刈叡曳汭濊猊睿穢芮藝蘂禮裔詣譽豫醴銳隸霓預五伍俉傲午吾吳嗚塢墺奧娛寤悟惡懊敖旿晤梧汚澳"], +["e8a1","烏熬獒筽蜈誤鰲鼇屋沃獄玉鈺溫瑥瘟穩縕蘊兀壅擁瓮甕癰翁邕雍饔渦瓦窩窪臥蛙蝸訛婉完宛梡椀浣玩琓琬碗緩翫脘腕莞豌阮頑曰往旺枉汪王倭娃歪矮外嵬巍猥畏了僚僥凹堯夭妖姚寥寮尿嶢拗搖撓擾料曜樂橈燎燿瑤療"], +["e9a1","窈窯繇繞耀腰蓼蟯要謠遙遼邀饒慾欲浴縟褥辱俑傭冗勇埇墉容庸慂榕涌湧溶熔瑢用甬聳茸蓉踊鎔鏞龍于佑偶優又友右宇寓尤愚憂旴牛玗瑀盂祐禑禹紆羽芋藕虞迂遇郵釪隅雨雩勖彧旭昱栯煜稶郁頊云暈橒殞澐熉耘芸蕓"], +["eaa1","運隕雲韻蔚鬱亐熊雄元原員圓園垣媛嫄寃怨愿援沅洹湲源爰猿瑗苑袁轅遠阮院願鴛月越鉞位偉僞危圍委威尉慰暐渭爲瑋緯胃萎葦蔿蝟衛褘謂違韋魏乳侑儒兪劉唯喩孺宥幼幽庾悠惟愈愉揄攸有杻柔柚柳楡楢油洧流游溜"], +["eba1","濡猶猷琉瑜由留癒硫紐維臾萸裕誘諛諭踰蹂遊逾遺酉釉鍮類六堉戮毓肉育陸倫允奫尹崙淪潤玧胤贇輪鈗閏律慄栗率聿戎瀜絨融隆垠恩慇殷誾銀隱乙吟淫蔭陰音飮揖泣邑凝應膺鷹依倚儀宜意懿擬椅毅疑矣義艤薏蟻衣誼"], +["eca1","議醫二以伊利吏夷姨履已弛彛怡易李梨泥爾珥理異痍痢移罹而耳肄苡荑裏裡貽貳邇里離飴餌匿溺瀷益翊翌翼謚人仁刃印吝咽因姻寅引忍湮燐璘絪茵藺蚓認隣靭靷鱗麟一佚佾壹日溢逸鎰馹任壬妊姙恁林淋稔臨荏賃入卄"], +["eda1","立笠粒仍剩孕芿仔刺咨姉姿子字孜恣慈滋炙煮玆瓷疵磁紫者自茨蔗藉諮資雌作勺嚼斫昨灼炸爵綽芍酌雀鵲孱棧殘潺盞岑暫潛箴簪蠶雜丈仗匠場墻壯奬將帳庄張掌暲杖樟檣欌漿牆狀獐璋章粧腸臟臧莊葬蔣薔藏裝贓醬長"], +["eea1","障再哉在宰才材栽梓渽滓災縡裁財載齋齎爭箏諍錚佇低儲咀姐底抵杵楮樗沮渚狙猪疽箸紵苧菹著藷詛貯躇這邸雎齟勣吊嫡寂摘敵滴狄炙的積笛籍績翟荻謫賊赤跡蹟迪迹適鏑佃佺傳全典前剪塡塼奠專展廛悛戰栓殿氈澱"], +["efa1","煎琠田甸畑癲筌箋箭篆纏詮輾轉鈿銓錢鐫電顚顫餞切截折浙癤竊節絶占岾店漸点粘霑鮎點接摺蝶丁井亭停偵呈姃定幀庭廷征情挺政整旌晶晸柾楨檉正汀淀淨渟湞瀞炡玎珽町睛碇禎程穽精綎艇訂諪貞鄭酊釘鉦鋌錠霆靖"], +["f0a1","靜頂鼎制劑啼堤帝弟悌提梯濟祭第臍薺製諸蹄醍除際霽題齊俎兆凋助嘲弔彫措操早晁曺曹朝條棗槽漕潮照燥爪璪眺祖祚租稠窕粗糟組繰肇藻蚤詔調趙躁造遭釣阻雕鳥族簇足鏃存尊卒拙猝倧宗從悰慫棕淙琮種終綜縱腫"], +["f1a1","踪踵鍾鐘佐坐左座挫罪主住侏做姝胄呪周嗾奏宙州廚晝朱柱株注洲湊澍炷珠疇籌紂紬綢舟蛛註誅走躊輳週酎酒鑄駐竹粥俊儁准埈寯峻晙樽浚準濬焌畯竣蠢逡遵雋駿茁中仲衆重卽櫛楫汁葺增憎曾拯烝甑症繒蒸證贈之只"], +["f2a1","咫地址志持指摯支旨智枝枳止池沚漬知砥祉祗紙肢脂至芝芷蜘誌識贄趾遲直稙稷織職唇嗔塵振搢晉晋桭榛殄津溱珍瑨璡畛疹盡眞瞋秦縉縝臻蔯袗診賑軫辰進鎭陣陳震侄叱姪嫉帙桎瓆疾秩窒膣蛭質跌迭斟朕什執潗緝輯"], +["f3a1","鏶集徵懲澄且侘借叉嗟嵯差次此磋箚茶蹉車遮捉搾着窄錯鑿齪撰澯燦璨瓚竄簒纂粲纘讚贊鑽餐饌刹察擦札紮僭參塹慘慙懺斬站讒讖倉倡創唱娼廠彰愴敞昌昶暢槍滄漲猖瘡窓脹艙菖蒼債埰寀寨彩採砦綵菜蔡采釵冊柵策"], +["f4a1","責凄妻悽處倜刺剔尺慽戚拓擲斥滌瘠脊蹠陟隻仟千喘天川擅泉淺玔穿舛薦賤踐遷釧闡阡韆凸哲喆徹撤澈綴輟轍鐵僉尖沾添甛瞻簽籤詹諂堞妾帖捷牒疊睫諜貼輒廳晴淸聽菁請靑鯖切剃替涕滯締諦逮遞體初剿哨憔抄招梢"], +["f5a1","椒楚樵炒焦硝礁礎秒稍肖艸苕草蕉貂超酢醋醮促囑燭矗蜀觸寸忖村邨叢塚寵悤憁摠總聰蔥銃撮催崔最墜抽推椎楸樞湫皺秋芻萩諏趨追鄒酋醜錐錘鎚雛騶鰍丑畜祝竺筑築縮蓄蹙蹴軸逐春椿瑃出朮黜充忠沖蟲衝衷悴膵萃"], +["f6a1","贅取吹嘴娶就炊翠聚脆臭趣醉驟鷲側仄厠惻測層侈値嗤峙幟恥梔治淄熾痔痴癡稚穉緇緻置致蚩輜雉馳齒則勅飭親七柒漆侵寢枕沈浸琛砧針鍼蟄秤稱快他咤唾墮妥惰打拖朶楕舵陀馱駝倬卓啄坼度托拓擢晫柝濁濯琢琸託"], +["f7a1","鐸呑嘆坦彈憚歎灘炭綻誕奪脫探眈耽貪塔搭榻宕帑湯糖蕩兌台太怠態殆汰泰笞胎苔跆邰颱宅擇澤撑攄兎吐土討慟桶洞痛筒統通堆槌腿褪退頹偸套妬投透鬪慝特闖坡婆巴把播擺杷波派爬琶破罷芭跛頗判坂板版瓣販辦鈑"], +["f8a1","阪八叭捌佩唄悖敗沛浿牌狽稗覇貝彭澎烹膨愎便偏扁片篇編翩遍鞭騙貶坪平枰萍評吠嬖幣廢弊斃肺蔽閉陛佈包匍匏咆哺圃布怖抛抱捕暴泡浦疱砲胞脯苞葡蒲袍褒逋鋪飽鮑幅暴曝瀑爆輻俵剽彪慓杓標漂瓢票表豹飇飄驃"], +["f9a1","品稟楓諷豊風馮彼披疲皮被避陂匹弼必泌珌畢疋筆苾馝乏逼下何厦夏廈昰河瑕荷蝦賀遐霞鰕壑學虐謔鶴寒恨悍旱汗漢澣瀚罕翰閑閒限韓割轄函含咸啣喊檻涵緘艦銜陷鹹合哈盒蛤閤闔陜亢伉姮嫦巷恒抗杭桁沆港缸肛航"], +["faa1","行降項亥偕咳垓奚孩害懈楷海瀣蟹解該諧邂駭骸劾核倖幸杏荇行享向嚮珦鄕響餉饗香噓墟虛許憲櫶獻軒歇險驗奕爀赫革俔峴弦懸晛泫炫玄玹現眩睍絃絢縣舷衒見賢鉉顯孑穴血頁嫌俠協夾峽挾浹狹脅脇莢鋏頰亨兄刑型"], +["fba1","形泂滎瀅灐炯熒珩瑩荊螢衡逈邢鎣馨兮彗惠慧暳蕙蹊醯鞋乎互呼壕壺好岵弧戶扈昊晧毫浩淏湖滸澔濠濩灝狐琥瑚瓠皓祜糊縞胡芦葫蒿虎號蝴護豪鎬頀顥惑或酷婚昏混渾琿魂忽惚笏哄弘汞泓洪烘紅虹訌鴻化和嬅樺火畵"], +["fca1","禍禾花華話譁貨靴廓擴攫確碻穫丸喚奐宦幻患換歡晥桓渙煥環紈還驩鰥活滑猾豁闊凰幌徨恍惶愰慌晃晄榥況湟滉潢煌璜皇篁簧荒蝗遑隍黃匯回廻徊恢悔懷晦會檜淮澮灰獪繪膾茴蛔誨賄劃獲宖橫鐄哮嚆孝效斅曉梟涍淆"], +["fda1","爻肴酵驍侯候厚后吼喉嗅帿後朽煦珝逅勛勳塤壎焄熏燻薰訓暈薨喧暄煊萱卉喙毁彙徽揮暉煇諱輝麾休携烋畦虧恤譎鷸兇凶匈洶胸黑昕欣炘痕吃屹紇訖欠欽歆吸恰洽翕興僖凞喜噫囍姬嬉希憙憘戱晞曦熙熹熺犧禧稀羲詰"] +] diff --git a/node_modules/iconv-lite/encodings/tables/cp950.json b/node_modules/iconv-lite/encodings/tables/cp950.json new file mode 100644 index 0000000..d8bc871 --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/cp950.json @@ -0,0 +1,177 @@ +[ +["0","\u0000",127], +["a140"," ,、。.‧;:?!︰…‥﹐﹑﹒·﹔﹕﹖﹗|–︱—︳╴︴﹏()︵︶{}︷︸〔〕︹︺【】︻︼《》︽︾〈〉︿﹀「」﹁﹂『』﹃﹄﹙﹚"], +["a1a1","﹛﹜﹝﹞‘’“”〝〞‵′#&*※§〃○●△▲◎☆★◇◆□■▽▼㊣℅¯ ̄_ˍ﹉﹊﹍﹎﹋﹌﹟﹠﹡+-×÷±√<>=≦≧≠∞≒≡﹢",4,"~∩∪⊥∠∟⊿㏒㏑∫∮∵∴♀♂⊕⊙↑↓←→↖↗↙↘∥∣/"], +["a240","\∕﹨$¥〒¢£%@℃℉﹩﹪﹫㏕㎜㎝㎞㏎㎡㎎㎏㏄°兙兛兞兝兡兣嗧瓩糎▁",7,"▏▎▍▌▋▊▉┼┴┬┤├▔─│▕┌┐└┘╭"], +["a2a1","╮╰╯═╞╪╡◢◣◥◤╱╲╳0",9,"Ⅰ",9,"〡",8,"十卄卅A",25,"a",21], +["a340","wxyzΑ",16,"Σ",6,"α",16,"σ",6,"ㄅ",10], +["a3a1","ㄐ",25,"˙ˉˊˇˋ"], +["a3e1","€"], +["a440","一乙丁七乃九了二人儿入八几刀刁力匕十卜又三下丈上丫丸凡久么也乞于亡兀刃勺千叉口土士夕大女子孑孓寸小尢尸山川工己已巳巾干廾弋弓才"], +["a4a1","丑丐不中丰丹之尹予云井互五亢仁什仃仆仇仍今介仄元允內六兮公冗凶分切刈勻勾勿化匹午升卅卞厄友及反壬天夫太夭孔少尤尺屯巴幻廿弔引心戈戶手扎支文斗斤方日曰月木欠止歹毋比毛氏水火爪父爻片牙牛犬王丙"], +["a540","世丕且丘主乍乏乎以付仔仕他仗代令仙仞充兄冉冊冬凹出凸刊加功包匆北匝仟半卉卡占卯卮去可古右召叮叩叨叼司叵叫另只史叱台句叭叻四囚外"], +["a5a1","央失奴奶孕它尼巨巧左市布平幼弁弘弗必戊打扔扒扑斥旦朮本未末札正母民氐永汁汀氾犯玄玉瓜瓦甘生用甩田由甲申疋白皮皿目矛矢石示禾穴立丞丟乒乓乩亙交亦亥仿伉伙伊伕伍伐休伏仲件任仰仳份企伋光兇兆先全"], +["a640","共再冰列刑划刎刖劣匈匡匠印危吉吏同吊吐吁吋各向名合吃后吆吒因回囝圳地在圭圬圯圩夙多夷夸妄奸妃好她如妁字存宇守宅安寺尖屹州帆并年"], +["a6a1","式弛忙忖戎戌戍成扣扛托收早旨旬旭曲曳有朽朴朱朵次此死氖汝汗汙江池汐汕污汛汍汎灰牟牝百竹米糸缶羊羽老考而耒耳聿肉肋肌臣自至臼舌舛舟艮色艾虫血行衣西阡串亨位住佇佗佞伴佛何估佐佑伽伺伸佃佔似但佣"], +["a740","作你伯低伶余佝佈佚兌克免兵冶冷別判利刪刨劫助努劬匣即卵吝吭吞吾否呎吧呆呃吳呈呂君吩告吹吻吸吮吵吶吠吼呀吱含吟听囪困囤囫坊坑址坍"], +["a7a1","均坎圾坐坏圻壯夾妝妒妨妞妣妙妖妍妤妓妊妥孝孜孚孛完宋宏尬局屁尿尾岐岑岔岌巫希序庇床廷弄弟彤形彷役忘忌志忍忱快忸忪戒我抄抗抖技扶抉扭把扼找批扳抒扯折扮投抓抑抆改攻攸旱更束李杏材村杜杖杞杉杆杠"], +["a840","杓杗步每求汞沙沁沈沉沅沛汪決沐汰沌汨沖沒汽沃汲汾汴沆汶沍沔沘沂灶灼災灸牢牡牠狄狂玖甬甫男甸皂盯矣私秀禿究系罕肖肓肝肘肛肚育良芒"], +["a8a1","芋芍見角言谷豆豕貝赤走足身車辛辰迂迆迅迄巡邑邢邪邦那酉釆里防阮阱阪阬並乖乳事些亞享京佯依侍佳使佬供例來侃佰併侈佩佻侖佾侏侑佺兔兒兕兩具其典冽函刻券刷刺到刮制剁劾劻卒協卓卑卦卷卸卹取叔受味呵"], +["a940","咖呸咕咀呻呷咄咒咆呼咐呱呶和咚呢周咋命咎固垃坷坪坩坡坦坤坼夜奉奇奈奄奔妾妻委妹妮姑姆姐姍始姓姊妯妳姒姅孟孤季宗定官宜宙宛尚屈居"], +["a9a1","屆岷岡岸岩岫岱岳帘帚帖帕帛帑幸庚店府底庖延弦弧弩往征彿彼忝忠忽念忿怏怔怯怵怖怪怕怡性怩怫怛或戕房戾所承拉拌拄抿拂抹拒招披拓拔拋拈抨抽押拐拙拇拍抵拚抱拘拖拗拆抬拎放斧於旺昔易昌昆昂明昀昏昕昊"], +["aa40","昇服朋杭枋枕東果杳杷枇枝林杯杰板枉松析杵枚枓杼杪杲欣武歧歿氓氛泣注泳沱泌泥河沽沾沼波沫法泓沸泄油況沮泗泅泱沿治泡泛泊沬泯泜泖泠"], +["aaa1","炕炎炒炊炙爬爭爸版牧物狀狎狙狗狐玩玨玟玫玥甽疝疙疚的盂盲直知矽社祀祁秉秈空穹竺糾罔羌羋者肺肥肢肱股肫肩肴肪肯臥臾舍芳芝芙芭芽芟芹花芬芥芯芸芣芰芾芷虎虱初表軋迎返近邵邸邱邶采金長門阜陀阿阻附"], +["ab40","陂隹雨青非亟亭亮信侵侯便俠俑俏保促侶俘俟俊俗侮俐俄係俚俎俞侷兗冒冑冠剎剃削前剌剋則勇勉勃勁匍南卻厚叛咬哀咨哎哉咸咦咳哇哂咽咪品"], +["aba1","哄哈咯咫咱咻咩咧咿囿垂型垠垣垢城垮垓奕契奏奎奐姜姘姿姣姨娃姥姪姚姦威姻孩宣宦室客宥封屎屏屍屋峙峒巷帝帥帟幽庠度建弈弭彥很待徊律徇後徉怒思怠急怎怨恍恰恨恢恆恃恬恫恪恤扁拜挖按拼拭持拮拽指拱拷"], +["ac40","拯括拾拴挑挂政故斫施既春昭映昧是星昨昱昤曷柿染柱柔某柬架枯柵柩柯柄柑枴柚查枸柏柞柳枰柙柢柝柒歪殃殆段毒毗氟泉洋洲洪流津洌洱洞洗"], +["aca1","活洽派洶洛泵洹洧洸洩洮洵洎洫炫為炳炬炯炭炸炮炤爰牲牯牴狩狠狡玷珊玻玲珍珀玳甚甭畏界畎畋疫疤疥疢疣癸皆皇皈盈盆盃盅省盹相眉看盾盼眇矜砂研砌砍祆祉祈祇禹禺科秒秋穿突竿竽籽紂紅紀紉紇約紆缸美羿耄"], +["ad40","耐耍耑耶胖胥胚胃胄背胡胛胎胞胤胝致舢苧范茅苣苛苦茄若茂茉苒苗英茁苜苔苑苞苓苟苯茆虐虹虻虺衍衫要觔計訂訃貞負赴赳趴軍軌述迦迢迪迥"], +["ada1","迭迫迤迨郊郎郁郃酋酊重閂限陋陌降面革韋韭音頁風飛食首香乘亳倌倍倣俯倦倥俸倩倖倆值借倚倒們俺倀倔倨俱倡個候倘俳修倭倪俾倫倉兼冤冥冢凍凌准凋剖剜剔剛剝匪卿原厝叟哨唐唁唷哼哥哲唆哺唔哩哭員唉哮哪"], +["ae40","哦唧唇哽唏圃圄埂埔埋埃堉夏套奘奚娑娘娜娟娛娓姬娠娣娩娥娌娉孫屘宰害家宴宮宵容宸射屑展屐峭峽峻峪峨峰島崁峴差席師庫庭座弱徒徑徐恙"], +["aea1","恣恥恐恕恭恩息悄悟悚悍悔悌悅悖扇拳挈拿捎挾振捕捂捆捏捉挺捐挽挪挫挨捍捌效敉料旁旅時晉晏晃晒晌晅晁書朔朕朗校核案框桓根桂桔栩梳栗桌桑栽柴桐桀格桃株桅栓栘桁殊殉殷氣氧氨氦氤泰浪涕消涇浦浸海浙涓"], +["af40","浬涉浮浚浴浩涌涊浹涅浥涔烊烘烤烙烈烏爹特狼狹狽狸狷玆班琉珮珠珪珞畔畝畜畚留疾病症疲疳疽疼疹痂疸皋皰益盍盎眩真眠眨矩砰砧砸砝破砷"], +["afa1","砥砭砠砟砲祕祐祠祟祖神祝祗祚秤秣秧租秦秩秘窄窈站笆笑粉紡紗紋紊素索純紐紕級紜納紙紛缺罟羔翅翁耆耘耕耙耗耽耿胱脂胰脅胭胴脆胸胳脈能脊胼胯臭臬舀舐航舫舨般芻茫荒荔荊茸荐草茵茴荏茲茹茶茗荀茱茨荃"], +["b040","虔蚊蚪蚓蚤蚩蚌蚣蚜衰衷袁袂衽衹記訐討訌訕訊託訓訖訏訑豈豺豹財貢起躬軒軔軏辱送逆迷退迺迴逃追逅迸邕郡郝郢酒配酌釘針釗釜釙閃院陣陡"], +["b0a1","陛陝除陘陞隻飢馬骨高鬥鬲鬼乾偺偽停假偃偌做偉健偶偎偕偵側偷偏倏偯偭兜冕凰剪副勒務勘動匐匏匙匿區匾參曼商啪啦啄啞啡啃啊唱啖問啕唯啤唸售啜唬啣唳啁啗圈國圉域堅堊堆埠埤基堂堵執培夠奢娶婁婉婦婪婀"], +["b140","娼婢婚婆婊孰寇寅寄寂宿密尉專將屠屜屝崇崆崎崛崖崢崑崩崔崙崤崧崗巢常帶帳帷康庸庶庵庾張強彗彬彩彫得徙從徘御徠徜恿患悉悠您惋悴惦悽"], +["b1a1","情悻悵惜悼惘惕惆惟悸惚惇戚戛扈掠控捲掖探接捷捧掘措捱掩掉掃掛捫推掄授掙採掬排掏掀捻捩捨捺敝敖救教敗啟敏敘敕敔斜斛斬族旋旌旎晝晚晤晨晦晞曹勗望梁梯梢梓梵桿桶梱梧梗械梃棄梭梆梅梔條梨梟梡梂欲殺"], +["b240","毫毬氫涎涼淳淙液淡淌淤添淺清淇淋涯淑涮淞淹涸混淵淅淒渚涵淚淫淘淪深淮淨淆淄涪淬涿淦烹焉焊烽烯爽牽犁猜猛猖猓猙率琅琊球理現琍瓠瓶"], +["b2a1","瓷甜產略畦畢異疏痔痕疵痊痍皎盔盒盛眷眾眼眶眸眺硫硃硎祥票祭移窒窕笠笨笛第符笙笞笮粒粗粕絆絃統紮紹紼絀細紳組累終紲紱缽羞羚翌翎習耜聊聆脯脖脣脫脩脰脤舂舵舷舶船莎莞莘荸莢莖莽莫莒莊莓莉莠荷荻荼"], +["b340","莆莧處彪蛇蛀蚶蛄蚵蛆蛋蚱蚯蛉術袞袈被袒袖袍袋覓規訪訝訣訥許設訟訛訢豉豚販責貫貨貪貧赧赦趾趺軛軟這逍通逗連速逝逐逕逞造透逢逖逛途"], +["b3a1","部郭都酗野釵釦釣釧釭釩閉陪陵陳陸陰陴陶陷陬雀雪雩章竟頂頃魚鳥鹵鹿麥麻傢傍傅備傑傀傖傘傚最凱割剴創剩勞勝勛博厥啻喀喧啼喊喝喘喂喜喪喔喇喋喃喳單喟唾喲喚喻喬喱啾喉喫喙圍堯堪場堤堰報堡堝堠壹壺奠"], +["b440","婷媚婿媒媛媧孳孱寒富寓寐尊尋就嵌嵐崴嵇巽幅帽幀幃幾廊廁廂廄弼彭復循徨惑惡悲悶惠愜愣惺愕惰惻惴慨惱愎惶愉愀愒戟扉掣掌描揀揩揉揆揍"], +["b4a1","插揣提握揖揭揮捶援揪換摒揚揹敞敦敢散斑斐斯普晰晴晶景暑智晾晷曾替期朝棺棕棠棘棗椅棟棵森棧棹棒棲棣棋棍植椒椎棉棚楮棻款欺欽殘殖殼毯氮氯氬港游湔渡渲湧湊渠渥渣減湛湘渤湖湮渭渦湯渴湍渺測湃渝渾滋"], +["b540","溉渙湎湣湄湲湩湟焙焚焦焰無然煮焜牌犄犀猶猥猴猩琺琪琳琢琥琵琶琴琯琛琦琨甥甦畫番痢痛痣痙痘痞痠登發皖皓皴盜睏短硝硬硯稍稈程稅稀窘"], +["b5a1","窗窖童竣等策筆筐筒答筍筋筏筑粟粥絞結絨絕紫絮絲絡給絢絰絳善翔翕耋聒肅腕腔腋腑腎脹腆脾腌腓腴舒舜菩萃菸萍菠菅萋菁華菱菴著萊菰萌菌菽菲菊萸萎萄菜萇菔菟虛蛟蛙蛭蛔蛛蛤蛐蛞街裁裂袱覃視註詠評詞証詁"], +["b640","詔詛詐詆訴診訶詖象貂貯貼貳貽賁費賀貴買貶貿貸越超趁跎距跋跚跑跌跛跆軻軸軼辜逮逵週逸進逶鄂郵鄉郾酣酥量鈔鈕鈣鈉鈞鈍鈐鈇鈑閔閏開閑"], +["b6a1","間閒閎隊階隋陽隅隆隍陲隄雁雅雄集雇雯雲韌項順須飧飪飯飩飲飭馮馭黃黍黑亂傭債傲傳僅傾催傷傻傯僇剿剷剽募勦勤勢勣匯嗟嗨嗓嗦嗎嗜嗇嗑嗣嗤嗯嗚嗡嗅嗆嗥嗉園圓塞塑塘塗塚塔填塌塭塊塢塒塋奧嫁嫉嫌媾媽媼"], +["b740","媳嫂媲嵩嵯幌幹廉廈弒彙徬微愚意慈感想愛惹愁愈慎慌慄慍愾愴愧愍愆愷戡戢搓搾搞搪搭搽搬搏搜搔損搶搖搗搆敬斟新暗暉暇暈暖暄暘暍會榔業"], +["b7a1","楚楷楠楔極椰概楊楨楫楞楓楹榆楝楣楛歇歲毀殿毓毽溢溯滓溶滂源溝滇滅溥溘溼溺溫滑準溜滄滔溪溧溴煎煙煩煤煉照煜煬煦煌煥煞煆煨煖爺牒猷獅猿猾瑯瑚瑕瑟瑞瑁琿瑙瑛瑜當畸瘀痰瘁痲痱痺痿痴痳盞盟睛睫睦睞督"], +["b840","睹睪睬睜睥睨睢矮碎碰碗碘碌碉硼碑碓硿祺祿禁萬禽稜稚稠稔稟稞窟窠筷節筠筮筧粱粳粵經絹綑綁綏絛置罩罪署義羨群聖聘肆肄腱腰腸腥腮腳腫"], +["b8a1","腹腺腦舅艇蒂葷落萱葵葦葫葉葬葛萼萵葡董葩葭葆虞虜號蛹蜓蜈蜇蜀蛾蛻蜂蜃蜆蜊衙裟裔裙補裘裝裡裊裕裒覜解詫該詳試詩詰誇詼詣誠話誅詭詢詮詬詹詻訾詨豢貊貉賊資賈賄貲賃賂賅跡跟跨路跳跺跪跤跦躲較載軾輊"], +["b940","辟農運遊道遂達逼違遐遇遏過遍遑逾遁鄒鄗酬酪酩釉鈷鉗鈸鈽鉀鈾鉛鉋鉤鉑鈴鉉鉍鉅鈹鈿鉚閘隘隔隕雍雋雉雊雷電雹零靖靴靶預頑頓頊頒頌飼飴"], +["b9a1","飽飾馳馱馴髡鳩麂鼎鼓鼠僧僮僥僖僭僚僕像僑僱僎僩兢凳劃劂匱厭嗾嘀嘛嘗嗽嘔嘆嘉嘍嘎嗷嘖嘟嘈嘐嗶團圖塵塾境墓墊塹墅塽壽夥夢夤奪奩嫡嫦嫩嫗嫖嫘嫣孵寞寧寡寥實寨寢寤察對屢嶄嶇幛幣幕幗幔廓廖弊彆彰徹慇"], +["ba40","愿態慷慢慣慟慚慘慵截撇摘摔撤摸摟摺摑摧搴摭摻敲斡旗旖暢暨暝榜榨榕槁榮槓構榛榷榻榫榴槐槍榭槌榦槃榣歉歌氳漳演滾漓滴漩漾漠漬漏漂漢"], +["baa1","滿滯漆漱漸漲漣漕漫漯澈漪滬漁滲滌滷熔熙煽熊熄熒爾犒犖獄獐瑤瑣瑪瑰瑭甄疑瘧瘍瘋瘉瘓盡監瞄睽睿睡磁碟碧碳碩碣禎福禍種稱窪窩竭端管箕箋筵算箝箔箏箸箇箄粹粽精綻綰綜綽綾綠緊綴網綱綺綢綿綵綸維緒緇綬"], +["bb40","罰翠翡翟聞聚肇腐膀膏膈膊腿膂臧臺與舔舞艋蓉蒿蓆蓄蒙蒞蒲蒜蓋蒸蓀蓓蒐蒼蓑蓊蜿蜜蜻蜢蜥蜴蜘蝕蜷蜩裳褂裴裹裸製裨褚裯誦誌語誣認誡誓誤"], +["bba1","說誥誨誘誑誚誧豪貍貌賓賑賒赫趙趕跼輔輒輕輓辣遠遘遜遣遙遞遢遝遛鄙鄘鄞酵酸酷酴鉸銀銅銘銖鉻銓銜銨鉼銑閡閨閩閣閥閤隙障際雌雒需靼鞅韶頗領颯颱餃餅餌餉駁骯骰髦魁魂鳴鳶鳳麼鼻齊億儀僻僵價儂儈儉儅凜"], +["bc40","劇劈劉劍劊勰厲嘮嘻嘹嘲嘿嘴嘩噓噎噗噴嘶嘯嘰墀墟增墳墜墮墩墦奭嬉嫻嬋嫵嬌嬈寮寬審寫層履嶝嶔幢幟幡廢廚廟廝廣廠彈影德徵慶慧慮慝慕憂"], +["bca1","慼慰慫慾憧憐憫憎憬憚憤憔憮戮摩摯摹撞撲撈撐撰撥撓撕撩撒撮播撫撚撬撙撢撳敵敷數暮暫暴暱樣樟槨樁樞標槽模樓樊槳樂樅槭樑歐歎殤毅毆漿潼澄潑潦潔澆潭潛潸潮澎潺潰潤澗潘滕潯潠潟熟熬熱熨牖犛獎獗瑩璋璃"], +["bd40","瑾璀畿瘠瘩瘟瘤瘦瘡瘢皚皺盤瞎瞇瞌瞑瞋磋磅確磊碾磕碼磐稿稼穀稽稷稻窯窮箭箱範箴篆篇篁箠篌糊締練緯緻緘緬緝編緣線緞緩綞緙緲緹罵罷羯"], +["bda1","翩耦膛膜膝膠膚膘蔗蔽蔚蓮蔬蔭蔓蔑蔣蔡蔔蓬蔥蓿蔆螂蝴蝶蝠蝦蝸蝨蝙蝗蝌蝓衛衝褐複褒褓褕褊誼諒談諄誕請諸課諉諂調誰論諍誶誹諛豌豎豬賠賞賦賤賬賭賢賣賜質賡赭趟趣踫踐踝踢踏踩踟踡踞躺輝輛輟輩輦輪輜輞"], +["be40","輥適遮遨遭遷鄰鄭鄧鄱醇醉醋醃鋅銻銷鋪銬鋤鋁銳銼鋒鋇鋰銲閭閱霄霆震霉靠鞍鞋鞏頡頫頜颳養餓餒餘駝駐駟駛駑駕駒駙骷髮髯鬧魅魄魷魯鴆鴉"], +["bea1","鴃麩麾黎墨齒儒儘儔儐儕冀冪凝劑劓勳噙噫噹噩噤噸噪器噥噱噯噬噢噶壁墾壇壅奮嬝嬴學寰導彊憲憑憩憊懍憶憾懊懈戰擅擁擋撻撼據擄擇擂操撿擒擔撾整曆曉暹曄曇暸樽樸樺橙橫橘樹橄橢橡橋橇樵機橈歙歷氅濂澱澡"], +["bf40","濃澤濁澧澳激澹澶澦澠澴熾燉燐燒燈燕熹燎燙燜燃燄獨璜璣璘璟璞瓢甌甍瘴瘸瘺盧盥瞠瞞瞟瞥磨磚磬磧禦積穎穆穌穋窺篙簑築篤篛篡篩篦糕糖縊"], +["bfa1","縑縈縛縣縞縝縉縐罹羲翰翱翮耨膳膩膨臻興艘艙蕊蕙蕈蕨蕩蕃蕉蕭蕪蕞螃螟螞螢融衡褪褲褥褫褡親覦諦諺諫諱謀諜諧諮諾謁謂諷諭諳諶諼豫豭貓賴蹄踱踴蹂踹踵輻輯輸輳辨辦遵遴選遲遼遺鄴醒錠錶鋸錳錯錢鋼錫錄錚"], +["c040","錐錦錡錕錮錙閻隧隨險雕霎霑霖霍霓霏靛靜靦鞘頰頸頻頷頭頹頤餐館餞餛餡餚駭駢駱骸骼髻髭鬨鮑鴕鴣鴦鴨鴒鴛默黔龍龜優償儡儲勵嚎嚀嚐嚅嚇"], +["c0a1","嚏壕壓壑壎嬰嬪嬤孺尷屨嶼嶺嶽嶸幫彌徽應懂懇懦懋戲戴擎擊擘擠擰擦擬擱擢擭斂斃曙曖檀檔檄檢檜櫛檣橾檗檐檠歜殮毚氈濘濱濟濠濛濤濫濯澀濬濡濩濕濮濰燧營燮燦燥燭燬燴燠爵牆獰獲璩環璦璨癆療癌盪瞳瞪瞰瞬"], +["c140","瞧瞭矯磷磺磴磯礁禧禪穗窿簇簍篾篷簌篠糠糜糞糢糟糙糝縮績繆縷縲繃縫總縱繅繁縴縹繈縵縿縯罄翳翼聱聲聰聯聳臆臃膺臂臀膿膽臉膾臨舉艱薪"], +["c1a1","薄蕾薜薑薔薯薛薇薨薊虧蟀蟑螳蟒蟆螫螻螺蟈蟋褻褶襄褸褽覬謎謗謙講謊謠謝謄謐豁谿豳賺賽購賸賻趨蹉蹋蹈蹊轄輾轂轅輿避遽還邁邂邀鄹醣醞醜鍍鎂錨鍵鍊鍥鍋錘鍾鍬鍛鍰鍚鍔闊闋闌闈闆隱隸雖霜霞鞠韓顆颶餵騁"], +["c240","駿鮮鮫鮪鮭鴻鴿麋黏點黜黝黛鼾齋叢嚕嚮壙壘嬸彝懣戳擴擲擾攆擺擻擷斷曜朦檳檬櫃檻檸櫂檮檯歟歸殯瀉瀋濾瀆濺瀑瀏燻燼燾燸獷獵璧璿甕癖癘"], +["c2a1","癒瞽瞿瞻瞼礎禮穡穢穠竄竅簫簧簪簞簣簡糧織繕繞繚繡繒繙罈翹翻職聶臍臏舊藏薩藍藐藉薰薺薹薦蟯蟬蟲蟠覆覲觴謨謹謬謫豐贅蹙蹣蹦蹤蹟蹕軀轉轍邇邃邈醫醬釐鎔鎊鎖鎢鎳鎮鎬鎰鎘鎚鎗闔闖闐闕離雜雙雛雞霤鞣鞦"], +["c340","鞭韹額顏題顎顓颺餾餿餽餮馥騎髁鬃鬆魏魎魍鯊鯉鯽鯈鯀鵑鵝鵠黠鼕鼬儳嚥壞壟壢寵龐廬懲懷懶懵攀攏曠曝櫥櫝櫚櫓瀛瀟瀨瀚瀝瀕瀘爆爍牘犢獸"], +["c3a1","獺璽瓊瓣疇疆癟癡矇礙禱穫穩簾簿簸簽簷籀繫繭繹繩繪羅繳羶羹羸臘藩藝藪藕藤藥藷蟻蠅蠍蟹蟾襠襟襖襞譁譜識證譚譎譏譆譙贈贊蹼蹲躇蹶蹬蹺蹴轔轎辭邊邋醱醮鏡鏑鏟鏃鏈鏜鏝鏖鏢鏍鏘鏤鏗鏨關隴難霪霧靡韜韻類"], +["c440","願顛颼饅饉騖騙鬍鯨鯧鯖鯛鶉鵡鵲鵪鵬麒麗麓麴勸嚨嚷嚶嚴嚼壤孀孃孽寶巉懸懺攘攔攙曦朧櫬瀾瀰瀲爐獻瓏癢癥礦礪礬礫竇競籌籃籍糯糰辮繽繼"], +["c4a1","纂罌耀臚艦藻藹蘑藺蘆蘋蘇蘊蠔蠕襤覺觸議譬警譯譟譫贏贍躉躁躅躂醴釋鐘鐃鏽闡霰飄饒饑馨騫騰騷騵鰓鰍鹹麵黨鼯齟齣齡儷儸囁囀囂夔屬巍懼懾攝攜斕曩櫻欄櫺殲灌爛犧瓖瓔癩矓籐纏續羼蘗蘭蘚蠣蠢蠡蠟襪襬覽譴"], +["c540","護譽贓躊躍躋轟辯醺鐮鐳鐵鐺鐸鐲鐫闢霸霹露響顧顥饗驅驃驀騾髏魔魑鰭鰥鶯鶴鷂鶸麝黯鼙齜齦齧儼儻囈囊囉孿巔巒彎懿攤權歡灑灘玀瓤疊癮癬"], +["c5a1","禳籠籟聾聽臟襲襯觼讀贖贗躑躓轡酈鑄鑑鑒霽霾韃韁顫饕驕驍髒鬚鱉鰱鰾鰻鷓鷗鼴齬齪龔囌巖戀攣攫攪曬欐瓚竊籤籣籥纓纖纔臢蘸蘿蠱變邐邏鑣鑠鑤靨顯饜驚驛驗髓體髑鱔鱗鱖鷥麟黴囑壩攬灞癱癲矗罐羈蠶蠹衢讓讒"], +["c640","讖艷贛釀鑪靂靈靄韆顰驟鬢魘鱟鷹鷺鹼鹽鼇齷齲廳欖灣籬籮蠻觀躡釁鑲鑰顱饞髖鬣黌灤矚讚鑷韉驢驥纜讜躪釅鑽鑾鑼鱷鱸黷豔鑿鸚爨驪鬱鸛鸞籲"], +["c940","乂乜凵匚厂万丌乇亍囗兀屮彳丏冇与丮亓仂仉仈冘勼卬厹圠夃夬尐巿旡殳毌气爿丱丼仨仜仩仡仝仚刌匜卌圢圣夗夯宁宄尒尻屴屳帄庀庂忉戉扐氕"], +["c9a1","氶汃氿氻犮犰玊禸肊阞伎优伬仵伔仱伀价伈伝伂伅伢伓伄仴伒冱刓刉刐劦匢匟卍厊吇囡囟圮圪圴夼妀奼妅奻奾奷奿孖尕尥屼屺屻屾巟幵庄异弚彴忕忔忏扜扞扤扡扦扢扙扠扚扥旯旮朾朹朸朻机朿朼朳氘汆汒汜汏汊汔汋"], +["ca40","汌灱牞犴犵玎甪癿穵网艸艼芀艽艿虍襾邙邗邘邛邔阢阤阠阣佖伻佢佉体佤伾佧佒佟佁佘伭伳伿佡冏冹刜刞刡劭劮匉卣卲厎厏吰吷吪呔呅吙吜吥吘"], +["caa1","吽呏呁吨吤呇囮囧囥坁坅坌坉坋坒夆奀妦妘妠妗妎妢妐妏妧妡宎宒尨尪岍岏岈岋岉岒岊岆岓岕巠帊帎庋庉庌庈庍弅弝彸彶忒忑忐忭忨忮忳忡忤忣忺忯忷忻怀忴戺抃抌抎抏抔抇扱扻扺扰抁抈扷扽扲扴攷旰旴旳旲旵杅杇"], +["cb40","杙杕杌杈杝杍杚杋毐氙氚汸汧汫沄沋沏汱汯汩沚汭沇沕沜汦汳汥汻沎灴灺牣犿犽狃狆狁犺狅玕玗玓玔玒町甹疔疕皁礽耴肕肙肐肒肜芐芏芅芎芑芓"], +["cba1","芊芃芄豸迉辿邟邡邥邞邧邠阰阨阯阭丳侘佼侅佽侀侇佶佴侉侄佷佌侗佪侚佹侁佸侐侜侔侞侒侂侕佫佮冞冼冾刵刲刳剆刱劼匊匋匼厒厔咇呿咁咑咂咈呫呺呾呥呬呴呦咍呯呡呠咘呣呧呤囷囹坯坲坭坫坱坰坶垀坵坻坳坴坢"], +["cc40","坨坽夌奅妵妺姏姎妲姌姁妶妼姃姖妱妽姀姈妴姇孢孥宓宕屄屇岮岤岠岵岯岨岬岟岣岭岢岪岧岝岥岶岰岦帗帔帙弨弢弣弤彔徂彾彽忞忥怭怦怙怲怋"], +["cca1","怴怊怗怳怚怞怬怢怍怐怮怓怑怌怉怜戔戽抭抴拑抾抪抶拊抮抳抯抻抩抰抸攽斨斻昉旼昄昒昈旻昃昋昍昅旽昑昐曶朊枅杬枎枒杶杻枘枆构杴枍枌杺枟枑枙枃杽极杸杹枔欥殀歾毞氝沓泬泫泮泙沶泔沭泧沷泐泂沺泃泆泭泲"], +["cd40","泒泝沴沊沝沀泞泀洰泍泇沰泹泏泩泑炔炘炅炓炆炄炑炖炂炚炃牪狖狋狘狉狜狒狔狚狌狑玤玡玭玦玢玠玬玝瓝瓨甿畀甾疌疘皯盳盱盰盵矸矼矹矻矺"], +["cda1","矷祂礿秅穸穻竻籵糽耵肏肮肣肸肵肭舠芠苀芫芚芘芛芵芧芮芼芞芺芴芨芡芩苂芤苃芶芢虰虯虭虮豖迒迋迓迍迖迕迗邲邴邯邳邰阹阽阼阺陃俍俅俓侲俉俋俁俔俜俙侻侳俛俇俖侺俀侹俬剄剉勀勂匽卼厗厖厙厘咺咡咭咥哏"], +["ce40","哃茍咷咮哖咶哅哆咠呰咼咢咾呲哞咰垵垞垟垤垌垗垝垛垔垘垏垙垥垚垕壴复奓姡姞姮娀姱姝姺姽姼姶姤姲姷姛姩姳姵姠姾姴姭宨屌峐峘峌峗峋峛"], +["cea1","峞峚峉峇峊峖峓峔峏峈峆峎峟峸巹帡帢帣帠帤庰庤庢庛庣庥弇弮彖徆怷怹恔恲恞恅恓恇恉恛恌恀恂恟怤恄恘恦恮扂扃拏挍挋拵挎挃拫拹挏挌拸拶挀挓挔拺挕拻拰敁敃斪斿昶昡昲昵昜昦昢昳昫昺昝昴昹昮朏朐柁柲柈枺"], +["cf40","柜枻柸柘柀枷柅柫柤柟枵柍枳柷柶柮柣柂枹柎柧柰枲柼柆柭柌枮柦柛柺柉柊柃柪柋欨殂殄殶毖毘毠氠氡洨洴洭洟洼洿洒洊泚洳洄洙洺洚洑洀洝浂"], +["cfa1","洁洘洷洃洏浀洇洠洬洈洢洉洐炷炟炾炱炰炡炴炵炩牁牉牊牬牰牳牮狊狤狨狫狟狪狦狣玅珌珂珈珅玹玶玵玴珫玿珇玾珃珆玸珋瓬瓮甮畇畈疧疪癹盄眈眃眄眅眊盷盻盺矧矨砆砑砒砅砐砏砎砉砃砓祊祌祋祅祄秕种秏秖秎窀"], +["d040","穾竑笀笁籺籸籹籿粀粁紃紈紁罘羑羍羾耇耎耏耔耷胘胇胠胑胈胂胐胅胣胙胜胊胕胉胏胗胦胍臿舡芔苙苾苹茇苨茀苕茺苫苖苴苬苡苲苵茌苻苶苰苪"], +["d0a1","苤苠苺苳苭虷虴虼虳衁衎衧衪衩觓訄訇赲迣迡迮迠郱邽邿郕郅邾郇郋郈釔釓陔陏陑陓陊陎倞倅倇倓倢倰倛俵俴倳倷倬俶俷倗倜倠倧倵倯倱倎党冔冓凊凄凅凈凎剡剚剒剞剟剕剢勍匎厞唦哢唗唒哧哳哤唚哿唄唈哫唑唅哱"], +["d140","唊哻哷哸哠唎唃唋圁圂埌堲埕埒垺埆垽垼垸垶垿埇埐垹埁夎奊娙娖娭娮娕娏娗娊娞娳孬宧宭宬尃屖屔峬峿峮峱峷崀峹帩帨庨庮庪庬弳弰彧恝恚恧"], +["d1a1","恁悢悈悀悒悁悝悃悕悛悗悇悜悎戙扆拲挐捖挬捄捅挶捃揤挹捋捊挼挩捁挴捘捔捙挭捇挳捚捑挸捗捀捈敊敆旆旃旄旂晊晟晇晑朒朓栟栚桉栲栳栻桋桏栖栱栜栵栫栭栯桎桄栴栝栒栔栦栨栮桍栺栥栠欬欯欭欱欴歭肂殈毦毤"], +["d240","毨毣毢毧氥浺浣浤浶洍浡涒浘浢浭浯涑涍淯浿涆浞浧浠涗浰浼浟涂涘洯浨涋浾涀涄洖涃浻浽浵涐烜烓烑烝烋缹烢烗烒烞烠烔烍烅烆烇烚烎烡牂牸"], +["d2a1","牷牶猀狺狴狾狶狳狻猁珓珙珥珖玼珧珣珩珜珒珛珔珝珚珗珘珨瓞瓟瓴瓵甡畛畟疰痁疻痄痀疿疶疺皊盉眝眛眐眓眒眣眑眕眙眚眢眧砣砬砢砵砯砨砮砫砡砩砳砪砱祔祛祏祜祓祒祑秫秬秠秮秭秪秜秞秝窆窉窅窋窌窊窇竘笐"], +["d340","笄笓笅笏笈笊笎笉笒粄粑粊粌粈粍粅紞紝紑紎紘紖紓紟紒紏紌罜罡罞罠罝罛羖羒翃翂翀耖耾耹胺胲胹胵脁胻脀舁舯舥茳茭荄茙荑茥荖茿荁茦茜茢"], +["d3a1","荂荎茛茪茈茼荍茖茤茠茷茯茩荇荅荌荓茞茬荋茧荈虓虒蚢蚨蚖蚍蚑蚞蚇蚗蚆蚋蚚蚅蚥蚙蚡蚧蚕蚘蚎蚝蚐蚔衃衄衭衵衶衲袀衱衿衯袃衾衴衼訒豇豗豻貤貣赶赸趵趷趶軑軓迾迵适迿迻逄迼迶郖郠郙郚郣郟郥郘郛郗郜郤酐"], +["d440","酎酏釕釢釚陜陟隼飣髟鬯乿偰偪偡偞偠偓偋偝偲偈偍偁偛偊偢倕偅偟偩偫偣偤偆偀偮偳偗偑凐剫剭剬剮勖勓匭厜啵啶唼啍啐唴唪啑啢唶唵唰啒啅"], +["d4a1","唌唲啥啎唹啈唭唻啀啋圊圇埻堔埢埶埜埴堀埭埽堈埸堋埳埏堇埮埣埲埥埬埡堎埼堐埧堁堌埱埩埰堍堄奜婠婘婕婧婞娸娵婭婐婟婥婬婓婤婗婃婝婒婄婛婈媎娾婍娹婌婰婩婇婑婖婂婜孲孮寁寀屙崞崋崝崚崠崌崨崍崦崥崏"], +["d540","崰崒崣崟崮帾帴庱庴庹庲庳弶弸徛徖徟悊悐悆悾悰悺惓惔惏惤惙惝惈悱惛悷惊悿惃惍惀挲捥掊掂捽掽掞掭掝掗掫掎捯掇掐据掯捵掜捭掮捼掤挻掟"], +["d5a1","捸掅掁掑掍捰敓旍晥晡晛晙晜晢朘桹梇梐梜桭桮梮梫楖桯梣梬梩桵桴梲梏桷梒桼桫桲梪梀桱桾梛梖梋梠梉梤桸桻梑梌梊桽欶欳欷欸殑殏殍殎殌氪淀涫涴涳湴涬淩淢涷淶淔渀淈淠淟淖涾淥淜淝淛淴淊涽淭淰涺淕淂淏淉"], +["d640","淐淲淓淽淗淍淣涻烺焍烷焗烴焌烰焄烳焐烼烿焆焓焀烸烶焋焂焎牾牻牼牿猝猗猇猑猘猊猈狿猏猞玈珶珸珵琄琁珽琇琀珺珼珿琌琋珴琈畤畣痎痒痏"], +["d6a1","痋痌痑痐皏皉盓眹眯眭眱眲眴眳眽眥眻眵硈硒硉硍硊硌砦硅硐祤祧祩祪祣祫祡离秺秸秶秷窏窔窐笵筇笴笥笰笢笤笳笘笪笝笱笫笭笯笲笸笚笣粔粘粖粣紵紽紸紶紺絅紬紩絁絇紾紿絊紻紨罣羕羜羝羛翊翋翍翐翑翇翏翉耟"], +["d740","耞耛聇聃聈脘脥脙脛脭脟脬脞脡脕脧脝脢舑舸舳舺舴舲艴莐莣莨莍荺荳莤荴莏莁莕莙荵莔莩荽莃莌莝莛莪莋荾莥莯莈莗莰荿莦莇莮荶莚虙虖蚿蚷"], +["d7a1","蛂蛁蛅蚺蚰蛈蚹蚳蚸蛌蚴蚻蚼蛃蚽蚾衒袉袕袨袢袪袚袑袡袟袘袧袙袛袗袤袬袌袓袎覂觖觙觕訰訧訬訞谹谻豜豝豽貥赽赻赹趼跂趹趿跁軘軞軝軜軗軠軡逤逋逑逜逌逡郯郪郰郴郲郳郔郫郬郩酖酘酚酓酕釬釴釱釳釸釤釹釪"], +["d840","釫釷釨釮镺閆閈陼陭陫陱陯隿靪頄飥馗傛傕傔傞傋傣傃傌傎傝偨傜傒傂傇兟凔匒匑厤厧喑喨喥喭啷噅喢喓喈喏喵喁喣喒喤啽喌喦啿喕喡喎圌堩堷"], +["d8a1","堙堞堧堣堨埵塈堥堜堛堳堿堶堮堹堸堭堬堻奡媯媔媟婺媢媞婸媦婼媥媬媕媮娷媄媊媗媃媋媩婻婽媌媜媏媓媝寪寍寋寔寑寊寎尌尰崷嵃嵫嵁嵋崿崵嵑嵎嵕崳崺嵒崽崱嵙嵂崹嵉崸崼崲崶嵀嵅幄幁彘徦徥徫惉悹惌惢惎惄愔"], +["d940","惲愊愖愅惵愓惸惼惾惁愃愘愝愐惿愄愋扊掔掱掰揎揥揨揯揃撝揳揊揠揶揕揲揵摡揟掾揝揜揄揘揓揂揇揌揋揈揰揗揙攲敧敪敤敜敨敥斌斝斞斮旐旒"], +["d9a1","晼晬晻暀晱晹晪晲朁椌棓椄棜椪棬棪棱椏棖棷棫棤棶椓椐棳棡椇棌椈楰梴椑棯棆椔棸棐棽棼棨椋椊椗棎棈棝棞棦棴棑椆棔棩椕椥棇欹欻欿欼殔殗殙殕殽毰毲毳氰淼湆湇渟湉溈渼渽湅湢渫渿湁湝湳渜渳湋湀湑渻渃渮湞"], +["da40","湨湜湡渱渨湠湱湫渹渢渰湓湥渧湸湤湷湕湹湒湦渵渶湚焠焞焯烻焮焱焣焥焢焲焟焨焺焛牋牚犈犉犆犅犋猒猋猰猢猱猳猧猲猭猦猣猵猌琮琬琰琫琖"], +["daa1","琚琡琭琱琤琣琝琩琠琲瓻甯畯畬痧痚痡痦痝痟痤痗皕皒盚睆睇睄睍睅睊睎睋睌矞矬硠硤硥硜硭硱硪确硰硩硨硞硢祴祳祲祰稂稊稃稌稄窙竦竤筊笻筄筈筌筎筀筘筅粢粞粨粡絘絯絣絓絖絧絪絏絭絜絫絒絔絩絑絟絎缾缿罥"], +["db40","罦羢羠羡翗聑聏聐胾胔腃腊腒腏腇脽腍脺臦臮臷臸臹舄舼舽舿艵茻菏菹萣菀菨萒菧菤菼菶萐菆菈菫菣莿萁菝菥菘菿菡菋菎菖菵菉萉萏菞萑萆菂菳"], +["dba1","菕菺菇菑菪萓菃菬菮菄菻菗菢萛菛菾蛘蛢蛦蛓蛣蛚蛪蛝蛫蛜蛬蛩蛗蛨蛑衈衖衕袺裗袹袸裀袾袶袼袷袽袲褁裉覕覘覗觝觚觛詎詍訹詙詀詗詘詄詅詒詈詑詊詌詏豟貁貀貺貾貰貹貵趄趀趉跘跓跍跇跖跜跏跕跙跈跗跅軯軷軺"], +["dc40","軹軦軮軥軵軧軨軶軫軱軬軴軩逭逴逯鄆鄬鄄郿郼鄈郹郻鄁鄀鄇鄅鄃酡酤酟酢酠鈁鈊鈥鈃鈚鈦鈏鈌鈀鈒釿釽鈆鈄鈧鈂鈜鈤鈙鈗鈅鈖镻閍閌閐隇陾隈"], +["dca1","隉隃隀雂雈雃雱雰靬靰靮頇颩飫鳦黹亃亄亶傽傿僆傮僄僊傴僈僂傰僁傺傱僋僉傶傸凗剺剸剻剼嗃嗛嗌嗐嗋嗊嗝嗀嗔嗄嗩喿嗒喍嗏嗕嗢嗖嗈嗲嗍嗙嗂圔塓塨塤塏塍塉塯塕塎塝塙塥塛堽塣塱壼嫇嫄嫋媺媸媱媵媰媿嫈媻嫆"], +["dd40","媷嫀嫊媴媶嫍媹媐寖寘寙尟尳嵱嵣嵊嵥嵲嵬嵞嵨嵧嵢巰幏幎幊幍幋廅廌廆廋廇彀徯徭惷慉慊愫慅愶愲愮慆愯慏愩慀戠酨戣戥戤揅揱揫搐搒搉搠搤"], +["dda1","搳摃搟搕搘搹搷搢搣搌搦搰搨摁搵搯搊搚摀搥搧搋揧搛搮搡搎敯斒旓暆暌暕暐暋暊暙暔晸朠楦楟椸楎楢楱椿楅楪椹楂楗楙楺楈楉椵楬椳椽楥棰楸椴楩楀楯楄楶楘楁楴楌椻楋椷楜楏楑椲楒椯楻椼歆歅歃歂歈歁殛嗀毻毼"], +["de40","毹毷毸溛滖滈溏滀溟溓溔溠溱溹滆滒溽滁溞滉溷溰滍溦滏溲溾滃滜滘溙溒溎溍溤溡溿溳滐滊溗溮溣煇煔煒煣煠煁煝煢煲煸煪煡煂煘煃煋煰煟煐煓"], +["dea1","煄煍煚牏犍犌犑犐犎猼獂猻猺獀獊獉瑄瑊瑋瑒瑑瑗瑀瑏瑐瑎瑂瑆瑍瑔瓡瓿瓾瓽甝畹畷榃痯瘏瘃痷痾痼痹痸瘐痻痶痭痵痽皙皵盝睕睟睠睒睖睚睩睧睔睙睭矠碇碚碔碏碄碕碅碆碡碃硹碙碀碖硻祼禂祽祹稑稘稙稒稗稕稢稓"], +["df40","稛稐窣窢窞竫筦筤筭筴筩筲筥筳筱筰筡筸筶筣粲粴粯綈綆綀綍絿綅絺綎絻綃絼綌綔綄絽綒罭罫罧罨罬羦羥羧翛翜耡腤腠腷腜腩腛腢腲朡腞腶腧腯"], +["dfa1","腄腡舝艉艄艀艂艅蓱萿葖葶葹蒏蒍葥葑葀蒆葧萰葍葽葚葙葴葳葝蔇葞萷萺萴葺葃葸萲葅萩菙葋萯葂萭葟葰萹葎葌葒葯蓅蒎萻葇萶萳葨葾葄萫葠葔葮葐蜋蜄蛷蜌蛺蛖蛵蝍蛸蜎蜉蜁蛶蜍蜅裖裋裍裎裞裛裚裌裐覅覛觟觥觤"], +["e040","觡觠觢觜触詶誆詿詡訿詷誂誄詵誃誁詴詺谼豋豊豥豤豦貆貄貅賌赨赩趑趌趎趏趍趓趔趐趒跰跠跬跱跮跐跩跣跢跧跲跫跴輆軿輁輀輅輇輈輂輋遒逿"], +["e0a1","遄遉逽鄐鄍鄏鄑鄖鄔鄋鄎酮酯鉈鉒鈰鈺鉦鈳鉥鉞銃鈮鉊鉆鉭鉬鉏鉠鉧鉯鈶鉡鉰鈱鉔鉣鉐鉲鉎鉓鉌鉖鈲閟閜閞閛隒隓隑隗雎雺雽雸雵靳靷靸靲頏頍頎颬飶飹馯馲馰馵骭骫魛鳪鳭鳧麀黽僦僔僗僨僳僛僪僝僤僓僬僰僯僣僠"], +["e140","凘劀劁勩勫匰厬嘧嘕嘌嘒嗼嘏嘜嘁嘓嘂嗺嘝嘄嗿嗹墉塼墐墘墆墁塿塴墋塺墇墑墎塶墂墈塻墔墏壾奫嫜嫮嫥嫕嫪嫚嫭嫫嫳嫢嫠嫛嫬嫞嫝嫙嫨嫟孷寠"], +["e1a1","寣屣嶂嶀嵽嶆嵺嶁嵷嶊嶉嶈嵾嵼嶍嵹嵿幘幙幓廘廑廗廎廜廕廙廒廔彄彃彯徶愬愨慁慞慱慳慒慓慲慬憀慴慔慺慛慥愻慪慡慖戩戧戫搫摍摛摝摴摶摲摳摽摵摦撦摎撂摞摜摋摓摠摐摿搿摬摫摙摥摷敳斠暡暠暟朅朄朢榱榶槉"], +["e240","榠槎榖榰榬榼榑榙榎榧榍榩榾榯榿槄榽榤槔榹槊榚槏榳榓榪榡榞槙榗榐槂榵榥槆歊歍歋殞殟殠毃毄毾滎滵滱漃漥滸漷滻漮漉潎漙漚漧漘漻漒滭漊"], +["e2a1","漶潳滹滮漭潀漰漼漵滫漇漎潃漅滽滶漹漜滼漺漟漍漞漈漡熇熐熉熀熅熂熏煻熆熁熗牄牓犗犕犓獃獍獑獌瑢瑳瑱瑵瑲瑧瑮甀甂甃畽疐瘖瘈瘌瘕瘑瘊瘔皸瞁睼瞅瞂睮瞀睯睾瞃碲碪碴碭碨硾碫碞碥碠碬碢碤禘禊禋禖禕禔禓"], +["e340","禗禈禒禐稫穊稰稯稨稦窨窫窬竮箈箜箊箑箐箖箍箌箛箎箅箘劄箙箤箂粻粿粼粺綧綷緂綣綪緁緀緅綝緎緄緆緋緌綯綹綖綼綟綦綮綩綡緉罳翢翣翥翞"], +["e3a1","耤聝聜膉膆膃膇膍膌膋舕蒗蒤蒡蒟蒺蓎蓂蒬蒮蒫蒹蒴蓁蓍蒪蒚蒱蓐蒝蒧蒻蒢蒔蓇蓌蒛蒩蒯蒨蓖蒘蒶蓏蒠蓗蓔蓒蓛蒰蒑虡蜳蜣蜨蝫蝀蜮蜞蜡蜙蜛蝃蜬蝁蜾蝆蜠蜲蜪蜭蜼蜒蜺蜱蜵蝂蜦蜧蜸蜤蜚蜰蜑裷裧裱裲裺裾裮裼裶裻"], +["e440","裰裬裫覝覡覟覞觩觫觨誫誙誋誒誏誖谽豨豩賕賏賗趖踉踂跿踍跽踊踃踇踆踅跾踀踄輐輑輎輍鄣鄜鄠鄢鄟鄝鄚鄤鄡鄛酺酲酹酳銥銤鉶銛鉺銠銔銪銍"], +["e4a1","銦銚銫鉹銗鉿銣鋮銎銂銕銢鉽銈銡銊銆銌銙銧鉾銇銩銝銋鈭隞隡雿靘靽靺靾鞃鞀鞂靻鞄鞁靿韎韍頖颭颮餂餀餇馝馜駃馹馻馺駂馽駇骱髣髧鬾鬿魠魡魟鳱鳲鳵麧僿儃儰僸儆儇僶僾儋儌僽儊劋劌勱勯噈噂噌嘵噁噊噉噆噘"], +["e540","噚噀嘳嘽嘬嘾嘸嘪嘺圚墫墝墱墠墣墯墬墥墡壿嫿嫴嫽嫷嫶嬃嫸嬂嫹嬁嬇嬅嬏屧嶙嶗嶟嶒嶢嶓嶕嶠嶜嶡嶚嶞幩幝幠幜緳廛廞廡彉徲憋憃慹憱憰憢憉"], +["e5a1","憛憓憯憭憟憒憪憡憍慦憳戭摮摰撖撠撅撗撜撏撋撊撌撣撟摨撱撘敶敺敹敻斲斳暵暰暩暲暷暪暯樀樆樗槥槸樕槱槤樠槿槬槢樛樝槾樧槲槮樔槷槧橀樈槦槻樍槼槫樉樄樘樥樏槶樦樇槴樖歑殥殣殢殦氁氀毿氂潁漦潾澇濆澒"], +["e640","澍澉澌潢潏澅潚澖潶潬澂潕潲潒潐潗澔澓潝漀潡潫潽潧澐潓澋潩潿澕潣潷潪潻熲熯熛熰熠熚熩熵熝熥熞熤熡熪熜熧熳犘犚獘獒獞獟獠獝獛獡獚獙"], +["e6a1","獢璇璉璊璆璁瑽璅璈瑼瑹甈甇畾瘥瘞瘙瘝瘜瘣瘚瘨瘛皜皝皞皛瞍瞏瞉瞈磍碻磏磌磑磎磔磈磃磄磉禚禡禠禜禢禛歶稹窲窴窳箷篋箾箬篎箯箹篊箵糅糈糌糋緷緛緪緧緗緡縃緺緦緶緱緰緮緟罶羬羰羭翭翫翪翬翦翨聤聧膣膟"], +["e740","膞膕膢膙膗舖艏艓艒艐艎艑蔤蔻蔏蔀蔩蔎蔉蔍蔟蔊蔧蔜蓻蔫蓺蔈蔌蓴蔪蓲蔕蓷蓫蓳蓼蔒蓪蓩蔖蓾蔨蔝蔮蔂蓽蔞蓶蔱蔦蓧蓨蓰蓯蓹蔘蔠蔰蔋蔙蔯虢"], +["e7a1","蝖蝣蝤蝷蟡蝳蝘蝔蝛蝒蝡蝚蝑蝞蝭蝪蝐蝎蝟蝝蝯蝬蝺蝮蝜蝥蝏蝻蝵蝢蝧蝩衚褅褌褔褋褗褘褙褆褖褑褎褉覢覤覣觭觰觬諏諆誸諓諑諔諕誻諗誾諀諅諘諃誺誽諙谾豍貏賥賟賙賨賚賝賧趠趜趡趛踠踣踥踤踮踕踛踖踑踙踦踧"], +["e840","踔踒踘踓踜踗踚輬輤輘輚輠輣輖輗遳遰遯遧遫鄯鄫鄩鄪鄲鄦鄮醅醆醊醁醂醄醀鋐鋃鋄鋀鋙銶鋏鋱鋟鋘鋩鋗鋝鋌鋯鋂鋨鋊鋈鋎鋦鋍鋕鋉鋠鋞鋧鋑鋓"], +["e8a1","銵鋡鋆銴镼閬閫閮閰隤隢雓霅霈霂靚鞊鞎鞈韐韏頞頝頦頩頨頠頛頧颲餈飺餑餔餖餗餕駜駍駏駓駔駎駉駖駘駋駗駌骳髬髫髳髲髱魆魃魧魴魱魦魶魵魰魨魤魬鳼鳺鳽鳿鳷鴇鴀鳹鳻鴈鴅鴄麃黓鼏鼐儜儓儗儚儑凞匴叡噰噠噮"], +["e940","噳噦噣噭噲噞噷圜圛壈墽壉墿墺壂墼壆嬗嬙嬛嬡嬔嬓嬐嬖嬨嬚嬠嬞寯嶬嶱嶩嶧嶵嶰嶮嶪嶨嶲嶭嶯嶴幧幨幦幯廩廧廦廨廥彋徼憝憨憖懅憴懆懁懌憺"], +["e9a1","憿憸憌擗擖擐擏擉撽撉擃擛擳擙攳敿敼斢曈暾曀曊曋曏暽暻暺曌朣樴橦橉橧樲橨樾橝橭橶橛橑樨橚樻樿橁橪橤橐橏橔橯橩橠樼橞橖橕橍橎橆歕歔歖殧殪殫毈毇氄氃氆澭濋澣濇澼濎濈潞濄澽澞濊澨瀄澥澮澺澬澪濏澿澸"], +["ea40","澢濉澫濍澯澲澰燅燂熿熸燖燀燁燋燔燊燇燏熽燘熼燆燚燛犝犞獩獦獧獬獥獫獪瑿璚璠璔璒璕璡甋疀瘯瘭瘱瘽瘳瘼瘵瘲瘰皻盦瞚瞝瞡瞜瞛瞢瞣瞕瞙"], +["eaa1","瞗磝磩磥磪磞磣磛磡磢磭磟磠禤穄穈穇窶窸窵窱窷篞篣篧篝篕篥篚篨篹篔篪篢篜篫篘篟糒糔糗糐糑縒縡縗縌縟縠縓縎縜縕縚縢縋縏縖縍縔縥縤罃罻罼罺羱翯耪耩聬膱膦膮膹膵膫膰膬膴膲膷膧臲艕艖艗蕖蕅蕫蕍蕓蕡蕘"], +["eb40","蕀蕆蕤蕁蕢蕄蕑蕇蕣蔾蕛蕱蕎蕮蕵蕕蕧蕠薌蕦蕝蕔蕥蕬虣虥虤螛螏螗螓螒螈螁螖螘蝹螇螣螅螐螑螝螄螔螜螚螉褞褦褰褭褮褧褱褢褩褣褯褬褟觱諠"], +["eba1","諢諲諴諵諝謔諤諟諰諈諞諡諨諿諯諻貑貒貐賵賮賱賰賳赬赮趥趧踳踾踸蹀蹅踶踼踽蹁踰踿躽輶輮輵輲輹輷輴遶遹遻邆郺鄳鄵鄶醓醐醑醍醏錧錞錈錟錆錏鍺錸錼錛錣錒錁鍆錭錎錍鋋錝鋺錥錓鋹鋷錴錂錤鋿錩錹錵錪錔錌"], +["ec40","錋鋾錉錀鋻錖閼闍閾閹閺閶閿閵閽隩雔霋霒霐鞙鞗鞔韰韸頵頯頲餤餟餧餩馞駮駬駥駤駰駣駪駩駧骹骿骴骻髶髺髹髷鬳鮀鮅鮇魼魾魻鮂鮓鮒鮐魺鮕"], +["eca1","魽鮈鴥鴗鴠鴞鴔鴩鴝鴘鴢鴐鴙鴟麈麆麇麮麭黕黖黺鼒鼽儦儥儢儤儠儩勴嚓嚌嚍嚆嚄嚃噾嚂噿嚁壖壔壏壒嬭嬥嬲嬣嬬嬧嬦嬯嬮孻寱寲嶷幬幪徾徻懃憵憼懧懠懥懤懨懞擯擩擣擫擤擨斁斀斶旚曒檍檖檁檥檉檟檛檡檞檇檓檎"], +["ed40","檕檃檨檤檑橿檦檚檅檌檒歛殭氉濌澩濴濔濣濜濭濧濦濞濲濝濢濨燡燱燨燲燤燰燢獳獮獯璗璲璫璐璪璭璱璥璯甐甑甒甏疄癃癈癉癇皤盩瞵瞫瞲瞷瞶"], +["eda1","瞴瞱瞨矰磳磽礂磻磼磲礅磹磾礄禫禨穜穛穖穘穔穚窾竀竁簅簏篲簀篿篻簎篴簋篳簂簉簃簁篸篽簆篰篱簐簊糨縭縼繂縳顈縸縪繉繀繇縩繌縰縻縶繄縺罅罿罾罽翴翲耬膻臄臌臊臅臇膼臩艛艚艜薃薀薏薧薕薠薋薣蕻薤薚薞"], +["ee40","蕷蕼薉薡蕺蕸蕗薎薖薆薍薙薝薁薢薂薈薅蕹蕶薘薐薟虨螾螪螭蟅螰螬螹螵螼螮蟉蟃蟂蟌螷螯蟄蟊螴螶螿螸螽蟞螲褵褳褼褾襁襒褷襂覭覯覮觲觳謞"], +["eea1","謘謖謑謅謋謢謏謒謕謇謍謈謆謜謓謚豏豰豲豱豯貕貔賹赯蹎蹍蹓蹐蹌蹇轃轀邅遾鄸醚醢醛醙醟醡醝醠鎡鎃鎯鍤鍖鍇鍼鍘鍜鍶鍉鍐鍑鍠鍭鎏鍌鍪鍹鍗鍕鍒鍏鍱鍷鍻鍡鍞鍣鍧鎀鍎鍙闇闀闉闃闅閷隮隰隬霠霟霘霝霙鞚鞡鞜"], +["ef40","鞞鞝韕韔韱顁顄顊顉顅顃餥餫餬餪餳餲餯餭餱餰馘馣馡騂駺駴駷駹駸駶駻駽駾駼騃骾髾髽鬁髼魈鮚鮨鮞鮛鮦鮡鮥鮤鮆鮢鮠鮯鴳鵁鵧鴶鴮鴯鴱鴸鴰"], +["efa1","鵅鵂鵃鴾鴷鵀鴽翵鴭麊麉麍麰黈黚黻黿鼤鼣鼢齔龠儱儭儮嚘嚜嚗嚚嚝嚙奰嬼屩屪巀幭幮懘懟懭懮懱懪懰懫懖懩擿攄擽擸攁攃擼斔旛曚曛曘櫅檹檽櫡櫆檺檶檷櫇檴檭歞毉氋瀇瀌瀍瀁瀅瀔瀎濿瀀濻瀦濼濷瀊爁燿燹爃燽獶"], +["f040","璸瓀璵瓁璾璶璻瓂甔甓癜癤癙癐癓癗癚皦皽盬矂瞺磿礌礓礔礉礐礒礑禭禬穟簜簩簙簠簟簭簝簦簨簢簥簰繜繐繖繣繘繢繟繑繠繗繓羵羳翷翸聵臑臒"], +["f0a1","臐艟艞薴藆藀藃藂薳薵薽藇藄薿藋藎藈藅薱薶藒蘤薸薷薾虩蟧蟦蟢蟛蟫蟪蟥蟟蟳蟤蟔蟜蟓蟭蟘蟣螤蟗蟙蠁蟴蟨蟝襓襋襏襌襆襐襑襉謪謧謣謳謰謵譇謯謼謾謱謥謷謦謶謮謤謻謽謺豂豵貙貘貗賾贄贂贀蹜蹢蹠蹗蹖蹞蹥蹧"], +["f140","蹛蹚蹡蹝蹩蹔轆轇轈轋鄨鄺鄻鄾醨醥醧醯醪鎵鎌鎒鎷鎛鎝鎉鎧鎎鎪鎞鎦鎕鎈鎙鎟鎍鎱鎑鎲鎤鎨鎴鎣鎥闒闓闑隳雗雚巂雟雘雝霣霢霥鞬鞮鞨鞫鞤鞪"], +["f1a1","鞢鞥韗韙韖韘韺顐顑顒颸饁餼餺騏騋騉騍騄騑騊騅騇騆髀髜鬈鬄鬅鬩鬵魊魌魋鯇鯆鯃鮿鯁鮵鮸鯓鮶鯄鮹鮽鵜鵓鵏鵊鵛鵋鵙鵖鵌鵗鵒鵔鵟鵘鵚麎麌黟鼁鼀鼖鼥鼫鼪鼩鼨齌齕儴儵劖勷厴嚫嚭嚦嚧嚪嚬壚壝壛夒嬽嬾嬿巃幰"], +["f240","徿懻攇攐攍攉攌攎斄旞旝曞櫧櫠櫌櫑櫙櫋櫟櫜櫐櫫櫏櫍櫞歠殰氌瀙瀧瀠瀖瀫瀡瀢瀣瀩瀗瀤瀜瀪爌爊爇爂爅犥犦犤犣犡瓋瓅璷瓃甖癠矉矊矄矱礝礛"], +["f2a1","礡礜礗礞禰穧穨簳簼簹簬簻糬糪繶繵繸繰繷繯繺繲繴繨罋罊羃羆羷翽翾聸臗臕艤艡艣藫藱藭藙藡藨藚藗藬藲藸藘藟藣藜藑藰藦藯藞藢蠀蟺蠃蟶蟷蠉蠌蠋蠆蟼蠈蟿蠊蠂襢襚襛襗襡襜襘襝襙覈覷覶觶譐譈譊譀譓譖譔譋譕"], +["f340","譑譂譒譗豃豷豶貚贆贇贉趬趪趭趫蹭蹸蹳蹪蹯蹻軂轒轑轏轐轓辴酀鄿醰醭鏞鏇鏏鏂鏚鏐鏹鏬鏌鏙鎩鏦鏊鏔鏮鏣鏕鏄鏎鏀鏒鏧镽闚闛雡霩霫霬霨霦"], +["f3a1","鞳鞷鞶韝韞韟顜顙顝顗颿颽颻颾饈饇饃馦馧騚騕騥騝騤騛騢騠騧騣騞騜騔髂鬋鬊鬎鬌鬷鯪鯫鯠鯞鯤鯦鯢鯰鯔鯗鯬鯜鯙鯥鯕鯡鯚鵷鶁鶊鶄鶈鵱鶀鵸鶆鶋鶌鵽鵫鵴鵵鵰鵩鶅鵳鵻鶂鵯鵹鵿鶇鵨麔麑黀黼鼭齀齁齍齖齗齘匷嚲"], +["f440","嚵嚳壣孅巆巇廮廯忀忁懹攗攖攕攓旟曨曣曤櫳櫰櫪櫨櫹櫱櫮櫯瀼瀵瀯瀷瀴瀱灂瀸瀿瀺瀹灀瀻瀳灁爓爔犨獽獼璺皫皪皾盭矌矎矏矍矲礥礣礧礨礤礩"], +["f4a1","禲穮穬穭竷籉籈籊籇籅糮繻繾纁纀羺翿聹臛臙舋艨艩蘢藿蘁藾蘛蘀藶蘄蘉蘅蘌藽蠙蠐蠑蠗蠓蠖襣襦覹觷譠譪譝譨譣譥譧譭趮躆躈躄轙轖轗轕轘轚邍酃酁醷醵醲醳鐋鐓鏻鐠鐏鐔鏾鐕鐐鐨鐙鐍鏵鐀鏷鐇鐎鐖鐒鏺鐉鏸鐊鏿"], +["f540","鏼鐌鏶鐑鐆闞闠闟霮霯鞹鞻韽韾顠顢顣顟飁飂饐饎饙饌饋饓騲騴騱騬騪騶騩騮騸騭髇髊髆鬐鬒鬑鰋鰈鯷鰅鰒鯸鱀鰇鰎鰆鰗鰔鰉鶟鶙鶤鶝鶒鶘鶐鶛"], +["f5a1","鶠鶔鶜鶪鶗鶡鶚鶢鶨鶞鶣鶿鶩鶖鶦鶧麙麛麚黥黤黧黦鼰鼮齛齠齞齝齙龑儺儹劘劗囃嚽嚾孈孇巋巏廱懽攛欂櫼欃櫸欀灃灄灊灈灉灅灆爝爚爙獾甗癪矐礭礱礯籔籓糲纊纇纈纋纆纍罍羻耰臝蘘蘪蘦蘟蘣蘜蘙蘧蘮蘡蘠蘩蘞蘥"], +["f640","蠩蠝蠛蠠蠤蠜蠫衊襭襩襮襫觺譹譸譅譺譻贐贔趯躎躌轞轛轝酆酄酅醹鐿鐻鐶鐩鐽鐼鐰鐹鐪鐷鐬鑀鐱闥闤闣霵霺鞿韡顤飉飆飀饘饖騹騽驆驄驂驁騺"], +["f6a1","騿髍鬕鬗鬘鬖鬺魒鰫鰝鰜鰬鰣鰨鰩鰤鰡鶷鶶鶼鷁鷇鷊鷏鶾鷅鷃鶻鶵鷎鶹鶺鶬鷈鶱鶭鷌鶳鷍鶲鹺麜黫黮黭鼛鼘鼚鼱齎齥齤龒亹囆囅囋奱孋孌巕巑廲攡攠攦攢欋欈欉氍灕灖灗灒爞爟犩獿瓘瓕瓙瓗癭皭礵禴穰穱籗籜籙籛籚"], +["f740","糴糱纑罏羇臞艫蘴蘵蘳蘬蘲蘶蠬蠨蠦蠪蠥襱覿覾觻譾讄讂讆讅譿贕躕躔躚躒躐躖躗轠轢酇鑌鑐鑊鑋鑏鑇鑅鑈鑉鑆霿韣顪顩飋饔饛驎驓驔驌驏驈驊"], +["f7a1","驉驒驐髐鬙鬫鬻魖魕鱆鱈鰿鱄鰹鰳鱁鰼鰷鰴鰲鰽鰶鷛鷒鷞鷚鷋鷐鷜鷑鷟鷩鷙鷘鷖鷵鷕鷝麶黰鼵鼳鼲齂齫龕龢儽劙壨壧奲孍巘蠯彏戁戃戄攩攥斖曫欑欒欏毊灛灚爢玂玁玃癰矔籧籦纕艬蘺虀蘹蘼蘱蘻蘾蠰蠲蠮蠳襶襴襳觾"], +["f840","讌讎讋讈豅贙躘轤轣醼鑢鑕鑝鑗鑞韄韅頀驖驙鬞鬟鬠鱒鱘鱐鱊鱍鱋鱕鱙鱌鱎鷻鷷鷯鷣鷫鷸鷤鷶鷡鷮鷦鷲鷰鷢鷬鷴鷳鷨鷭黂黐黲黳鼆鼜鼸鼷鼶齃齏"], +["f8a1","齱齰齮齯囓囍孎屭攭曭曮欓灟灡灝灠爣瓛瓥矕礸禷禶籪纗羉艭虃蠸蠷蠵衋讔讕躞躟躠躝醾醽釂鑫鑨鑩雥靆靃靇韇韥驞髕魙鱣鱧鱦鱢鱞鱠鸂鷾鸇鸃鸆鸅鸀鸁鸉鷿鷽鸄麠鼞齆齴齵齶囔攮斸欘欙欗欚灢爦犪矘矙礹籩籫糶纚"], +["f940","纘纛纙臠臡虆虇虈襹襺襼襻觿讘讙躥躤躣鑮鑭鑯鑱鑳靉顲饟鱨鱮鱭鸋鸍鸐鸏鸒鸑麡黵鼉齇齸齻齺齹圞灦籯蠼趲躦釃鑴鑸鑶鑵驠鱴鱳鱱鱵鸔鸓黶鼊"], +["f9a1","龤灨灥糷虪蠾蠽蠿讞貜躩軉靋顳顴飌饡馫驤驦驧鬤鸕鸗齈戇欞爧虌躨钂钀钁驩驨鬮鸙爩虋讟钃鱹麷癵驫鱺鸝灩灪麤齾齉龘碁銹裏墻恒粧嫺╔╦╗╠╬╣╚╩╝╒╤╕╞╪╡╘╧╛╓╥╖╟╫╢╙╨╜║═╭╮╰╯▓"] +] diff --git a/node_modules/iconv-lite/encodings/tables/eucjp.json b/node_modules/iconv-lite/encodings/tables/eucjp.json new file mode 100644 index 0000000..4fa61ca --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/eucjp.json @@ -0,0 +1,182 @@ +[ +["0","\u0000",127], +["8ea1","。",62], +["a1a1"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇"], +["a2a1","◆□■△▲▽▼※〒→←↑↓〓"], +["a2ba","∈∋⊆⊇⊂⊃∪∩"], +["a2ca","∧∨¬⇒⇔∀∃"], +["a2dc","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"], +["a2f2","ʼn♯♭♪†‡¶"], +["a2fe","◯"], +["a3b0","0",9], +["a3c1","A",25], +["a3e1","a",25], +["a4a1","ぁ",82], +["a5a1","ァ",85], +["a6a1","Α",16,"Σ",6], +["a6c1","α",16,"σ",6], +["a7a1","А",5,"ЁЖ",25], +["a7d1","а",5,"ёж",25], +["a8a1","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"], +["ada1","①",19,"Ⅰ",9], +["adc0","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"], +["addf","㍻〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"], +["b0a1","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"], +["b1a1","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応"], +["b2a1","押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"], +["b3a1","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱"], +["b4a1","粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"], +["b5a1","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京"], +["b6a1","供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"], +["b7a1","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲"], +["b8a1","検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"], +["b9a1","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込"], +["baa1","此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"], +["bba1","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時"], +["bca1","次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"], +["bda1","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償"], +["bea1","勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"], +["bfa1","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾"], +["c0a1","澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"], +["c1a1","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎"], +["c2a1","臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"], +["c3a1","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵"], +["c4a1","帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"], +["c5a1","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到"], +["c6a1","董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"], +["c7a1","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦"], +["c8a1","函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"], +["c9a1","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服"], +["caa1","福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"], +["cba1","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満"], +["cca1","漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"], +["cda1","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃"], +["cea1","痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"], +["cfa1","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"], +["d0a1","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"], +["d1a1","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨"], +["d2a1","辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"], +["d3a1","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉"], +["d4a1","圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"], +["d5a1","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓"], +["d6a1","屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"], +["d7a1","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚"], +["d8a1","悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"], +["d9a1","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼"], +["daa1","據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"], +["dba1","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍"], +["dca1","棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"], +["dda1","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾"], +["dea1","沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"], +["dfa1","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼"], +["e0a1","燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"], +["e1a1","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰"], +["e2a1","癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], +["e3a1","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐"], +["e4a1","筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"], +["e5a1","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺"], +["e6a1","罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"], +["e7a1","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙"], +["e8a1","茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], +["e9a1","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙"], +["eaa1","蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"], +["eba1","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫"], +["eca1","譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"], +["eda1","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸"], +["eea1","遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"], +["efa1","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞"], +["f0a1","陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"], +["f1a1","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷"], +["f2a1","髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"], +["f3a1","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠"], +["f4a1","堯槇遙瑤凜熙"], +["f9a1","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德"], +["faa1","忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"], +["fba1","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚"], +["fca1","釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"], +["fcf1","ⅰ",9,"¬¦'""], +["8fa2af","˘ˇ¸˙˝¯˛˚~΄΅"], +["8fa2c2","¡¦¿"], +["8fa2eb","ºª©®™¤№"], +["8fa6e1","ΆΈΉΊΪ"], +["8fa6e7","Ό"], +["8fa6e9","ΎΫ"], +["8fa6ec","Ώ"], +["8fa6f1","άέήίϊΐόςύϋΰώ"], +["8fa7c2","Ђ",10,"ЎЏ"], +["8fa7f2","ђ",10,"ўџ"], +["8fa9a1","ÆĐ"], +["8fa9a4","Ħ"], +["8fa9a6","IJ"], +["8fa9a8","ŁĿ"], +["8fa9ab","ŊØŒ"], +["8fa9af","ŦÞ"], +["8fa9c1","æđðħıijĸłŀʼnŋøœßŧþ"], +["8faaa1","ÁÀÄÂĂǍĀĄÅÃĆĈČÇĊĎÉÈËÊĚĖĒĘ"], +["8faaba","ĜĞĢĠĤÍÌÏÎǏİĪĮĨĴĶĹĽĻŃŇŅÑÓÒÖÔǑŐŌÕŔŘŖŚŜŠŞŤŢÚÙÜÛŬǓŰŪŲŮŨǗǛǙǕŴÝŸŶŹŽŻ"], +["8faba1","áàäâăǎāąåãćĉčçċďéèëêěėēęǵĝğ"], +["8fabbd","ġĥíìïîǐ"], +["8fabc5","īįĩĵķĺľļńňņñóòöôǒőōõŕřŗśŝšşťţúùüûŭǔűūųůũǘǜǚǖŵýÿŷźžż"], +["8fb0a1","丂丄丅丌丒丟丣两丨丫丮丯丰丵乀乁乄乇乑乚乜乣乨乩乴乵乹乿亍亖亗亝亯亹仃仐仚仛仠仡仢仨仯仱仳仵份仾仿伀伂伃伈伋伌伒伕伖众伙伮伱你伳伵伷伹伻伾佀佂佈佉佋佌佒佔佖佘佟佣佪佬佮佱佷佸佹佺佽佾侁侂侄"], +["8fb1a1","侅侉侊侌侎侐侒侓侔侗侙侚侞侟侲侷侹侻侼侽侾俀俁俅俆俈俉俋俌俍俏俒俜俠俢俰俲俼俽俿倀倁倄倇倊倌倎倐倓倗倘倛倜倝倞倢倧倮倰倲倳倵偀偁偂偅偆偊偌偎偑偒偓偗偙偟偠偢偣偦偧偪偭偰偱倻傁傃傄傆傊傎傏傐"], +["8fb2a1","傒傓傔傖傛傜傞",4,"傪傯傰傹傺傽僀僃僄僇僌僎僐僓僔僘僜僝僟僢僤僦僨僩僯僱僶僺僾儃儆儇儈儋儌儍儎僲儐儗儙儛儜儝儞儣儧儨儬儭儯儱儳儴儵儸儹兂兊兏兓兕兗兘兟兤兦兾冃冄冋冎冘冝冡冣冭冸冺冼冾冿凂"], +["8fb3a1","凈减凑凒凓凕凘凞凢凥凮凲凳凴凷刁刂刅划刓刕刖刘刢刨刱刲刵刼剅剉剕剗剘剚剜剟剠剡剦剮剷剸剹劀劂劅劊劌劓劕劖劗劘劚劜劤劥劦劧劯劰劶劷劸劺劻劽勀勄勆勈勌勏勑勔勖勛勜勡勥勨勩勪勬勰勱勴勶勷匀匃匊匋"], +["8fb4a1","匌匑匓匘匛匜匞匟匥匧匨匩匫匬匭匰匲匵匼匽匾卂卌卋卙卛卡卣卥卬卭卲卹卾厃厇厈厎厓厔厙厝厡厤厪厫厯厲厴厵厷厸厺厽叀叅叏叒叓叕叚叝叞叠另叧叵吂吓吚吡吧吨吪启吱吴吵呃呄呇呍呏呞呢呤呦呧呩呫呭呮呴呿"], +["8fb5a1","咁咃咅咈咉咍咑咕咖咜咟咡咦咧咩咪咭咮咱咷咹咺咻咿哆哊响哎哠哪哬哯哶哼哾哿唀唁唅唈唉唌唍唎唕唪唫唲唵唶唻唼唽啁啇啉啊啍啐啑啘啚啛啞啠啡啤啦啿喁喂喆喈喎喏喑喒喓喔喗喣喤喭喲喿嗁嗃嗆嗉嗋嗌嗎嗑嗒"], +["8fb6a1","嗓嗗嗘嗛嗞嗢嗩嗶嗿嘅嘈嘊嘍",5,"嘙嘬嘰嘳嘵嘷嘹嘻嘼嘽嘿噀噁噃噄噆噉噋噍噏噔噞噠噡噢噣噦噩噭噯噱噲噵嚄嚅嚈嚋嚌嚕嚙嚚嚝嚞嚟嚦嚧嚨嚩嚫嚬嚭嚱嚳嚷嚾囅囉囊囋囏囐囌囍囙囜囝囟囡囤",4,"囱囫园"], +["8fb7a1","囶囷圁圂圇圊圌圑圕圚圛圝圠圢圣圤圥圩圪圬圮圯圳圴圽圾圿坅坆坌坍坒坢坥坧坨坫坭",4,"坳坴坵坷坹坺坻坼坾垁垃垌垔垗垙垚垜垝垞垟垡垕垧垨垩垬垸垽埇埈埌埏埕埝埞埤埦埧埩埭埰埵埶埸埽埾埿堃堄堈堉埡"], +["8fb8a1","堌堍堛堞堟堠堦堧堭堲堹堿塉塌塍塏塐塕塟塡塤塧塨塸塼塿墀墁墇墈墉墊墌墍墏墐墔墖墝墠墡墢墦墩墱墲壄墼壂壈壍壎壐壒壔壖壚壝壡壢壩壳夅夆夋夌夒夓夔虁夝夡夣夤夨夯夰夳夵夶夿奃奆奒奓奙奛奝奞奟奡奣奫奭"], +["8fb9a1","奯奲奵奶她奻奼妋妌妎妒妕妗妟妤妧妭妮妯妰妳妷妺妼姁姃姄姈姊姍姒姝姞姟姣姤姧姮姯姱姲姴姷娀娄娌娍娎娒娓娞娣娤娧娨娪娭娰婄婅婇婈婌婐婕婞婣婥婧婭婷婺婻婾媋媐媓媖媙媜媞媟媠媢媧媬媱媲媳媵媸媺媻媿"], +["8fbaa1","嫄嫆嫈嫏嫚嫜嫠嫥嫪嫮嫵嫶嫽嬀嬁嬈嬗嬴嬙嬛嬝嬡嬥嬭嬸孁孋孌孒孖孞孨孮孯孼孽孾孿宁宄宆宊宎宐宑宓宔宖宨宩宬宭宯宱宲宷宺宼寀寁寍寏寖",4,"寠寯寱寴寽尌尗尞尟尣尦尩尫尬尮尰尲尵尶屙屚屜屢屣屧屨屩"], +["8fbba1","屭屰屴屵屺屻屼屽岇岈岊岏岒岝岟岠岢岣岦岪岲岴岵岺峉峋峒峝峗峮峱峲峴崁崆崍崒崫崣崤崦崧崱崴崹崽崿嵂嵃嵆嵈嵕嵑嵙嵊嵟嵠嵡嵢嵤嵪嵭嵰嵹嵺嵾嵿嶁嶃嶈嶊嶒嶓嶔嶕嶙嶛嶟嶠嶧嶫嶰嶴嶸嶹巃巇巋巐巎巘巙巠巤"], +["8fbca1","巩巸巹帀帇帍帒帔帕帘帟帠帮帨帲帵帾幋幐幉幑幖幘幛幜幞幨幪",4,"幰庀庋庎庢庤庥庨庪庬庱庳庽庾庿廆廌廋廎廑廒廔廕廜廞廥廫异弆弇弈弎弙弜弝弡弢弣弤弨弫弬弮弰弴弶弻弽弿彀彄彅彇彍彐彔彘彛彠彣彤彧"], +["8fbda1","彯彲彴彵彸彺彽彾徉徍徏徖徜徝徢徧徫徤徬徯徰徱徸忄忇忈忉忋忐",4,"忞忡忢忨忩忪忬忭忮忯忲忳忶忺忼怇怊怍怓怔怗怘怚怟怤怭怳怵恀恇恈恉恌恑恔恖恗恝恡恧恱恾恿悂悆悈悊悎悑悓悕悘悝悞悢悤悥您悰悱悷"], +["8fbea1","悻悾惂惄惈惉惊惋惎惏惔惕惙惛惝惞惢惥惲惵惸惼惽愂愇愊愌愐",4,"愖愗愙愜愞愢愪愫愰愱愵愶愷愹慁慅慆慉慞慠慬慲慸慻慼慿憀憁憃憄憋憍憒憓憗憘憜憝憟憠憥憨憪憭憸憹憼懀懁懂懎懏懕懜懝懞懟懡懢懧懩懥"], +["8fbfa1","懬懭懯戁戃戄戇戓戕戜戠戢戣戧戩戫戹戽扂扃扄扆扌扐扑扒扔扖扚扜扤扭扯扳扺扽抍抎抏抐抦抨抳抶抷抺抾抿拄拎拕拖拚拪拲拴拼拽挃挄挊挋挍挐挓挖挘挩挪挭挵挶挹挼捁捂捃捄捆捊捋捎捒捓捔捘捛捥捦捬捭捱捴捵"], +["8fc0a1","捸捼捽捿掂掄掇掊掐掔掕掙掚掞掤掦掭掮掯掽揁揅揈揎揑揓揔揕揜揠揥揪揬揲揳揵揸揹搉搊搐搒搔搘搞搠搢搤搥搩搪搯搰搵搽搿摋摏摑摒摓摔摚摛摜摝摟摠摡摣摭摳摴摻摽撅撇撏撐撑撘撙撛撝撟撡撣撦撨撬撳撽撾撿"], +["8fc1a1","擄擉擊擋擌擎擐擑擕擗擤擥擩擪擭擰擵擷擻擿攁攄攈攉攊攏攓攔攖攙攛攞攟攢攦攩攮攱攺攼攽敃敇敉敐敒敔敟敠敧敫敺敽斁斅斊斒斕斘斝斠斣斦斮斲斳斴斿旂旈旉旎旐旔旖旘旟旰旲旴旵旹旾旿昀昄昈昉昍昑昒昕昖昝"], +["8fc2a1","昞昡昢昣昤昦昩昪昫昬昮昰昱昳昹昷晀晅晆晊晌晑晎晗晘晙晛晜晠晡曻晪晫晬晾晳晵晿晷晸晹晻暀晼暋暌暍暐暒暙暚暛暜暟暠暤暭暱暲暵暻暿曀曂曃曈曌曎曏曔曛曟曨曫曬曮曺朅朇朎朓朙朜朠朢朳朾杅杇杈杌杔杕杝"], +["8fc3a1","杦杬杮杴杶杻极构枎枏枑枓枖枘枙枛枰枱枲枵枻枼枽柹柀柂柃柅柈柉柒柗柙柜柡柦柰柲柶柷桒栔栙栝栟栨栧栬栭栯栰栱栳栻栿桄桅桊桌桕桗桘桛桫桮",4,"桵桹桺桻桼梂梄梆梈梖梘梚梜梡梣梥梩梪梮梲梻棅棈棌棏"], +["8fc4a1","棐棑棓棖棙棜棝棥棨棪棫棬棭棰棱棵棶棻棼棽椆椉椊椐椑椓椖椗椱椳椵椸椻楂楅楉楎楗楛楣楤楥楦楨楩楬楰楱楲楺楻楿榀榍榒榖榘榡榥榦榨榫榭榯榷榸榺榼槅槈槑槖槗槢槥槮槯槱槳槵槾樀樁樃樏樑樕樚樝樠樤樨樰樲"], +["8fc5a1","樴樷樻樾樿橅橆橉橊橎橐橑橒橕橖橛橤橧橪橱橳橾檁檃檆檇檉檋檑檛檝檞檟檥檫檯檰檱檴檽檾檿櫆櫉櫈櫌櫐櫔櫕櫖櫜櫝櫤櫧櫬櫰櫱櫲櫼櫽欂欃欆欇欉欏欐欑欗欛欞欤欨欫欬欯欵欶欻欿歆歊歍歒歖歘歝歠歧歫歮歰歵歽"], +["8fc6a1","歾殂殅殗殛殟殠殢殣殨殩殬殭殮殰殸殹殽殾毃毄毉毌毖毚毡毣毦毧毮毱毷毹毿氂氄氅氉氍氎氐氒氙氟氦氧氨氬氮氳氵氶氺氻氿汊汋汍汏汒汔汙汛汜汫汭汯汴汶汸汹汻沅沆沇沉沔沕沗沘沜沟沰沲沴泂泆泍泏泐泑泒泔泖"], +["8fc7a1","泚泜泠泧泩泫泬泮泲泴洄洇洊洎洏洑洓洚洦洧洨汧洮洯洱洹洼洿浗浞浟浡浥浧浯浰浼涂涇涑涒涔涖涗涘涪涬涴涷涹涽涿淄淈淊淎淏淖淛淝淟淠淢淥淩淯淰淴淶淼渀渄渞渢渧渲渶渹渻渼湄湅湈湉湋湏湑湒湓湔湗湜湝湞"], +["8fc8a1","湢湣湨湳湻湽溍溓溙溠溧溭溮溱溳溻溿滀滁滃滇滈滊滍滎滏滫滭滮滹滻滽漄漈漊漌漍漖漘漚漛漦漩漪漯漰漳漶漻漼漭潏潑潒潓潗潙潚潝潞潡潢潨潬潽潾澃澇澈澋澌澍澐澒澓澔澖澚澟澠澥澦澧澨澮澯澰澵澶澼濅濇濈濊"], +["8fc9a1","濚濞濨濩濰濵濹濼濽瀀瀅瀆瀇瀍瀗瀠瀣瀯瀴瀷瀹瀼灃灄灈灉灊灋灔灕灝灞灎灤灥灬灮灵灶灾炁炅炆炔",4,"炛炤炫炰炱炴炷烊烑烓烔烕烖烘烜烤烺焃",4,"焋焌焏焞焠焫焭焯焰焱焸煁煅煆煇煊煋煐煒煗煚煜煞煠"], +["8fcaa1","煨煹熀熅熇熌熒熚熛熠熢熯熰熲熳熺熿燀燁燄燋燌燓燖燙燚燜燸燾爀爇爈爉爓爗爚爝爟爤爫爯爴爸爹牁牂牃牅牎牏牐牓牕牖牚牜牞牠牣牨牫牮牯牱牷牸牻牼牿犄犉犍犎犓犛犨犭犮犱犴犾狁狇狉狌狕狖狘狟狥狳狴狺狻"], +["8fcba1","狾猂猄猅猇猋猍猒猓猘猙猞猢猤猧猨猬猱猲猵猺猻猽獃獍獐獒獖獘獝獞獟獠獦獧獩獫獬獮獯獱獷獹獼玀玁玃玅玆玎玐玓玕玗玘玜玞玟玠玢玥玦玪玫玭玵玷玹玼玽玿珅珆珉珋珌珏珒珓珖珙珝珡珣珦珧珩珴珵珷珹珺珻珽"], +["8fcca1","珿琀琁琄琇琊琑琚琛琤琦琨",9,"琹瑀瑃瑄瑆瑇瑋瑍瑑瑒瑗瑝瑢瑦瑧瑨瑫瑭瑮瑱瑲璀璁璅璆璇璉璏璐璑璒璘璙璚璜璟璠璡璣璦璨璩璪璫璮璯璱璲璵璹璻璿瓈瓉瓌瓐瓓瓘瓚瓛瓞瓟瓤瓨瓪瓫瓯瓴瓺瓻瓼瓿甆"], +["8fcda1","甒甖甗甠甡甤甧甩甪甯甶甹甽甾甿畀畃畇畈畎畐畒畗畞畟畡畯畱畹",5,"疁疅疐疒疓疕疙疜疢疤疴疺疿痀痁痄痆痌痎痏痗痜痟痠痡痤痧痬痮痯痱痹瘀瘂瘃瘄瘇瘈瘊瘌瘏瘒瘓瘕瘖瘙瘛瘜瘝瘞瘣瘥瘦瘩瘭瘲瘳瘵瘸瘹"], +["8fcea1","瘺瘼癊癀癁癃癄癅癉癋癕癙癟癤癥癭癮癯癱癴皁皅皌皍皕皛皜皝皟皠皢",6,"皪皭皽盁盅盉盋盌盎盔盙盠盦盨盬盰盱盶盹盼眀眆眊眎眒眔眕眗眙眚眜眢眨眭眮眯眴眵眶眹眽眾睂睅睆睊睍睎睏睒睖睗睜睞睟睠睢"], +["8fcfa1","睤睧睪睬睰睲睳睴睺睽瞀瞄瞌瞍瞔瞕瞖瞚瞟瞢瞧瞪瞮瞯瞱瞵瞾矃矉矑矒矕矙矞矟矠矤矦矪矬矰矱矴矸矻砅砆砉砍砎砑砝砡砢砣砭砮砰砵砷硃硄硇硈硌硎硒硜硞硠硡硣硤硨硪确硺硾碊碏碔碘碡碝碞碟碤碨碬碭碰碱碲碳"], +["8fd0a1","碻碽碿磇磈磉磌磎磒磓磕磖磤磛磟磠磡磦磪磲磳礀磶磷磺磻磿礆礌礐礚礜礞礟礠礥礧礩礭礱礴礵礻礽礿祄祅祆祊祋祏祑祔祘祛祜祧祩祫祲祹祻祼祾禋禌禑禓禔禕禖禘禛禜禡禨禩禫禯禱禴禸离秂秄秇秈秊秏秔秖秚秝秞"], +["8fd1a1","秠秢秥秪秫秭秱秸秼稂稃稇稉稊稌稑稕稛稞稡稧稫稭稯稰稴稵稸稹稺穄穅穇穈穌穕穖穙穜穝穟穠穥穧穪穭穵穸穾窀窂窅窆窊窋窐窑窔窞窠窣窬窳窵窹窻窼竆竉竌竎竑竛竨竩竫竬竱竴竻竽竾笇笔笟笣笧笩笪笫笭笮笯笰"], +["8fd2a1","笱笴笽笿筀筁筇筎筕筠筤筦筩筪筭筯筲筳筷箄箉箎箐箑箖箛箞箠箥箬箯箰箲箵箶箺箻箼箽篂篅篈篊篔篖篗篙篚篛篨篪篲篴篵篸篹篺篼篾簁簂簃簄簆簉簋簌簎簏簙簛簠簥簦簨簬簱簳簴簶簹簺籆籊籕籑籒籓籙",5], +["8fd3a1","籡籣籧籩籭籮籰籲籹籼籽粆粇粏粔粞粠粦粰粶粷粺粻粼粿糄糇糈糉糍糏糓糔糕糗糙糚糝糦糩糫糵紃紇紈紉紏紑紒紓紖紝紞紣紦紪紭紱紼紽紾絀絁絇絈絍絑絓絗絙絚絜絝絥絧絪絰絸絺絻絿綁綂綃綅綆綈綋綌綍綑綖綗綝"], +["8fd4a1","綞綦綧綪綳綶綷綹緂",4,"緌緍緎緗緙縀緢緥緦緪緫緭緱緵緶緹緺縈縐縑縕縗縜縝縠縧縨縬縭縯縳縶縿繄繅繇繎繐繒繘繟繡繢繥繫繮繯繳繸繾纁纆纇纊纍纑纕纘纚纝纞缼缻缽缾缿罃罄罇罏罒罓罛罜罝罡罣罤罥罦罭"], +["8fd5a1","罱罽罾罿羀羋羍羏羐羑羖羗羜羡羢羦羪羭羴羼羿翀翃翈翎翏翛翟翣翥翨翬翮翯翲翺翽翾翿耇耈耊耍耎耏耑耓耔耖耝耞耟耠耤耦耬耮耰耴耵耷耹耺耼耾聀聄聠聤聦聭聱聵肁肈肎肜肞肦肧肫肸肹胈胍胏胒胔胕胗胘胠胭胮"], +["8fd6a1","胰胲胳胶胹胺胾脃脋脖脗脘脜脞脠脤脧脬脰脵脺脼腅腇腊腌腒腗腠腡腧腨腩腭腯腷膁膐膄膅膆膋膎膖膘膛膞膢膮膲膴膻臋臃臅臊臎臏臕臗臛臝臞臡臤臫臬臰臱臲臵臶臸臹臽臿舀舃舏舓舔舙舚舝舡舢舨舲舴舺艃艄艅艆"], +["8fd7a1","艋艎艏艑艖艜艠艣艧艭艴艻艽艿芀芁芃芄芇芉芊芎芑芔芖芘芚芛芠芡芣芤芧芨芩芪芮芰芲芴芷芺芼芾芿苆苐苕苚苠苢苤苨苪苭苯苶苷苽苾茀茁茇茈茊茋荔茛茝茞茟茡茢茬茭茮茰茳茷茺茼茽荂荃荄荇荍荎荑荕荖荗荰荸"], +["8fd8a1","荽荿莀莂莄莆莍莒莔莕莘莙莛莜莝莦莧莩莬莾莿菀菇菉菏菐菑菔菝荓菨菪菶菸菹菼萁萆萊萏萑萕萙莭萯萹葅葇葈葊葍葏葑葒葖葘葙葚葜葠葤葥葧葪葰葳葴葶葸葼葽蒁蒅蒒蒓蒕蒞蒦蒨蒩蒪蒯蒱蒴蒺蒽蒾蓀蓂蓇蓈蓌蓏蓓"], +["8fd9a1","蓜蓧蓪蓯蓰蓱蓲蓷蔲蓺蓻蓽蔂蔃蔇蔌蔎蔐蔜蔞蔢蔣蔤蔥蔧蔪蔫蔯蔳蔴蔶蔿蕆蕏",4,"蕖蕙蕜",6,"蕤蕫蕯蕹蕺蕻蕽蕿薁薅薆薉薋薌薏薓薘薝薟薠薢薥薧薴薶薷薸薼薽薾薿藂藇藊藋藎薭藘藚藟藠藦藨藭藳藶藼"], +["8fdaa1","藿蘀蘄蘅蘍蘎蘐蘑蘒蘘蘙蘛蘞蘡蘧蘩蘶蘸蘺蘼蘽虀虂虆虒虓虖虗虘虙虝虠",4,"虩虬虯虵虶虷虺蚍蚑蚖蚘蚚蚜蚡蚦蚧蚨蚭蚱蚳蚴蚵蚷蚸蚹蚿蛀蛁蛃蛅蛑蛒蛕蛗蛚蛜蛠蛣蛥蛧蚈蛺蛼蛽蜄蜅蜇蜋蜎蜏蜐蜓蜔蜙蜞蜟蜡蜣"], +["8fdba1","蜨蜮蜯蜱蜲蜹蜺蜼蜽蜾蝀蝃蝅蝍蝘蝝蝡蝤蝥蝯蝱蝲蝻螃",6,"螋螌螐螓螕螗螘螙螞螠螣螧螬螭螮螱螵螾螿蟁蟈蟉蟊蟎蟕蟖蟙蟚蟜蟟蟢蟣蟤蟪蟫蟭蟱蟳蟸蟺蟿蠁蠃蠆蠉蠊蠋蠐蠙蠒蠓蠔蠘蠚蠛蠜蠞蠟蠨蠭蠮蠰蠲蠵"], +["8fdca1","蠺蠼衁衃衅衈衉衊衋衎衑衕衖衘衚衜衟衠衤衩衱衹衻袀袘袚袛袜袟袠袨袪袺袽袾裀裊",4,"裑裒裓裛裞裧裯裰裱裵裷褁褆褍褎褏褕褖褘褙褚褜褠褦褧褨褰褱褲褵褹褺褾襀襂襅襆襉襏襒襗襚襛襜襡襢襣襫襮襰襳襵襺"], +["8fdda1","襻襼襽覉覍覐覔覕覛覜覟覠覥覰覴覵覶覷覼觔",4,"觥觩觫觭觱觳觶觹觽觿訄訅訇訏訑訒訔訕訞訠訢訤訦訫訬訯訵訷訽訾詀詃詅詇詉詍詎詓詖詗詘詜詝詡詥詧詵詶詷詹詺詻詾詿誀誃誆誋誏誐誒誖誗誙誟誧誩誮誯誳"], +["8fdea1","誶誷誻誾諃諆諈諉諊諑諓諔諕諗諝諟諬諰諴諵諶諼諿謅謆謋謑謜謞謟謊謭謰謷謼譂",4,"譈譒譓譔譙譍譞譣譭譶譸譹譼譾讁讄讅讋讍讏讔讕讜讞讟谸谹谽谾豅豇豉豋豏豑豓豔豗豘豛豝豙豣豤豦豨豩豭豳豵豶豻豾貆"], +["8fdfa1","貇貋貐貒貓貙貛貜貤貹貺賅賆賉賋賏賖賕賙賝賡賨賬賯賰賲賵賷賸賾賿贁贃贉贒贗贛赥赩赬赮赿趂趄趈趍趐趑趕趞趟趠趦趫趬趯趲趵趷趹趻跀跅跆跇跈跊跎跑跔跕跗跙跤跥跧跬跰趼跱跲跴跽踁踄踅踆踋踑踔踖踠踡踢"], +["8fe0a1","踣踦踧踱踳踶踷踸踹踽蹀蹁蹋蹍蹎蹏蹔蹛蹜蹝蹞蹡蹢蹩蹬蹭蹯蹰蹱蹹蹺蹻躂躃躉躐躒躕躚躛躝躞躢躧躩躭躮躳躵躺躻軀軁軃軄軇軏軑軔軜軨軮軰軱軷軹軺軭輀輂輇輈輏輐輖輗輘輞輠輡輣輥輧輨輬輭輮輴輵輶輷輺轀轁"], +["8fe1a1","轃轇轏轑",4,"轘轝轞轥辝辠辡辤辥辦辵辶辸达迀迁迆迊迋迍运迒迓迕迠迣迤迨迮迱迵迶迻迾适逄逈逌逘逛逨逩逯逪逬逭逳逴逷逿遃遄遌遛遝遢遦遧遬遰遴遹邅邈邋邌邎邐邕邗邘邙邛邠邡邢邥邰邲邳邴邶邽郌邾郃"], +["8fe2a1","郄郅郇郈郕郗郘郙郜郝郟郥郒郶郫郯郰郴郾郿鄀鄄鄅鄆鄈鄍鄐鄔鄖鄗鄘鄚鄜鄞鄠鄥鄢鄣鄧鄩鄮鄯鄱鄴鄶鄷鄹鄺鄼鄽酃酇酈酏酓酗酙酚酛酡酤酧酭酴酹酺酻醁醃醅醆醊醎醑醓醔醕醘醞醡醦醨醬醭醮醰醱醲醳醶醻醼醽醿"], +["8fe3a1","釂釃釅釓釔釗釙釚釞釤釥釩釪釬",5,"釷釹釻釽鈀鈁鈄鈅鈆鈇鈉鈊鈌鈐鈒鈓鈖鈘鈜鈝鈣鈤鈥鈦鈨鈮鈯鈰鈳鈵鈶鈸鈹鈺鈼鈾鉀鉂鉃鉆鉇鉊鉍鉎鉏鉑鉘鉙鉜鉝鉠鉡鉥鉧鉨鉩鉮鉯鉰鉵",4,"鉻鉼鉽鉿銈銉銊銍銎銒銗"], +["8fe4a1","銙銟銠銤銥銧銨銫銯銲銶銸銺銻銼銽銿",4,"鋅鋆鋇鋈鋋鋌鋍鋎鋐鋓鋕鋗鋘鋙鋜鋝鋟鋠鋡鋣鋥鋧鋨鋬鋮鋰鋹鋻鋿錀錂錈錍錑錔錕錜錝錞錟錡錤錥錧錩錪錳錴錶錷鍇鍈鍉鍐鍑鍒鍕鍗鍘鍚鍞鍤鍥鍧鍩鍪鍭鍯鍰鍱鍳鍴鍶"], +["8fe5a1","鍺鍽鍿鎀鎁鎂鎈鎊鎋鎍鎏鎒鎕鎘鎛鎞鎡鎣鎤鎦鎨鎫鎴鎵鎶鎺鎩鏁鏄鏅鏆鏇鏉",4,"鏓鏙鏜鏞鏟鏢鏦鏧鏹鏷鏸鏺鏻鏽鐁鐂鐄鐈鐉鐍鐎鐏鐕鐖鐗鐟鐮鐯鐱鐲鐳鐴鐻鐿鐽鑃鑅鑈鑊鑌鑕鑙鑜鑟鑡鑣鑨鑫鑭鑮鑯鑱鑲钄钃镸镹"], +["8fe6a1","镾閄閈閌閍閎閝閞閟閡閦閩閫閬閴閶閺閽閿闆闈闉闋闐闑闒闓闙闚闝闞闟闠闤闦阝阞阢阤阥阦阬阱阳阷阸阹阺阼阽陁陒陔陖陗陘陡陮陴陻陼陾陿隁隂隃隄隉隑隖隚隝隟隤隥隦隩隮隯隳隺雊雒嶲雘雚雝雞雟雩雯雱雺霂"], +["8fe7a1","霃霅霉霚霛霝霡霢霣霨霱霳靁靃靊靎靏靕靗靘靚靛靣靧靪靮靳靶靷靸靻靽靿鞀鞉鞕鞖鞗鞙鞚鞞鞟鞢鞬鞮鞱鞲鞵鞶鞸鞹鞺鞼鞾鞿韁韄韅韇韉韊韌韍韎韐韑韔韗韘韙韝韞韠韛韡韤韯韱韴韷韸韺頇頊頙頍頎頔頖頜頞頠頣頦"], +["8fe8a1","頫頮頯頰頲頳頵頥頾顄顇顊顑顒顓顖顗顙顚顢顣顥顦顪顬颫颭颮颰颴颷颸颺颻颿飂飅飈飌飡飣飥飦飧飪飳飶餂餇餈餑餕餖餗餚餛餜餟餢餦餧餫餱",4,"餹餺餻餼饀饁饆饇饈饍饎饔饘饙饛饜饞饟饠馛馝馟馦馰馱馲馵"], +["8fe9a1","馹馺馽馿駃駉駓駔駙駚駜駞駧駪駫駬駰駴駵駹駽駾騂騃騄騋騌騐騑騖騞騠騢騣騤騧騭騮騳騵騶騸驇驁驄驊驋驌驎驑驔驖驝骪骬骮骯骲骴骵骶骹骻骾骿髁髃髆髈髎髐髒髕髖髗髛髜髠髤髥髧髩髬髲髳髵髹髺髽髿",4], +["8feaa1","鬄鬅鬈鬉鬋鬌鬍鬎鬐鬒鬖鬙鬛鬜鬠鬦鬫鬭鬳鬴鬵鬷鬹鬺鬽魈魋魌魕魖魗魛魞魡魣魥魦魨魪",4,"魳魵魷魸魹魿鮀鮄鮅鮆鮇鮉鮊鮋鮍鮏鮐鮔鮚鮝鮞鮦鮧鮩鮬鮰鮱鮲鮷鮸鮻鮼鮾鮿鯁鯇鯈鯎鯐鯗鯘鯝鯟鯥鯧鯪鯫鯯鯳鯷鯸"], +["8feba1","鯹鯺鯽鯿鰀鰂鰋鰏鰑鰖鰘鰙鰚鰜鰞鰢鰣鰦",4,"鰱鰵鰶鰷鰽鱁鱃鱄鱅鱉鱊鱎鱏鱐鱓鱔鱖鱘鱛鱝鱞鱟鱣鱩鱪鱜鱫鱨鱮鱰鱲鱵鱷鱻鳦鳲鳷鳹鴋鴂鴑鴗鴘鴜鴝鴞鴯鴰鴲鴳鴴鴺鴼鵅鴽鵂鵃鵇鵊鵓鵔鵟鵣鵢鵥鵩鵪鵫鵰鵶鵷鵻"], +["8feca1","鵼鵾鶃鶄鶆鶊鶍鶎鶒鶓鶕鶖鶗鶘鶡鶪鶬鶮鶱鶵鶹鶼鶿鷃鷇鷉鷊鷔鷕鷖鷗鷚鷞鷟鷠鷥鷧鷩鷫鷮鷰鷳鷴鷾鸊鸂鸇鸎鸐鸑鸒鸕鸖鸙鸜鸝鹺鹻鹼麀麂麃麄麅麇麎麏麖麘麛麞麤麨麬麮麯麰麳麴麵黆黈黋黕黟黤黧黬黭黮黰黱黲黵"], +["8feda1","黸黿鼂鼃鼉鼏鼐鼑鼒鼔鼖鼗鼙鼚鼛鼟鼢鼦鼪鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃",4,"齓齕齖齗齘齚齝齞齨齩齭",4,"齳齵齺齽龏龐龑龒龔龖龗龞龡龢龣龥"] +] diff --git a/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json b/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json new file mode 100644 index 0000000..85c6934 --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json @@ -0,0 +1 @@ +{"uChars":[128,165,169,178,184,216,226,235,238,244,248,251,253,258,276,284,300,325,329,334,364,463,465,467,469,471,473,475,477,506,594,610,712,716,730,930,938,962,970,1026,1104,1106,8209,8215,8218,8222,8231,8241,8244,8246,8252,8365,8452,8454,8458,8471,8482,8556,8570,8596,8602,8713,8720,8722,8726,8731,8737,8740,8742,8748,8751,8760,8766,8777,8781,8787,8802,8808,8816,8854,8858,8870,8896,8979,9322,9372,9548,9588,9616,9622,9634,9652,9662,9672,9676,9680,9702,9735,9738,9793,9795,11906,11909,11913,11917,11928,11944,11947,11951,11956,11960,11964,11979,12284,12292,12312,12319,12330,12351,12436,12447,12535,12543,12586,12842,12850,12964,13200,13215,13218,13253,13263,13267,13270,13384,13428,13727,13839,13851,14617,14703,14801,14816,14964,15183,15471,15585,16471,16736,17208,17325,17330,17374,17623,17997,18018,18212,18218,18301,18318,18760,18811,18814,18820,18823,18844,18848,18872,19576,19620,19738,19887,40870,59244,59336,59367,59413,59417,59423,59431,59437,59443,59452,59460,59478,59493,63789,63866,63894,63976,63986,64016,64018,64021,64025,64034,64037,64042,65074,65093,65107,65112,65127,65132,65375,65510,65536],"gbChars":[0,36,38,45,50,81,89,95,96,100,103,104,105,109,126,133,148,172,175,179,208,306,307,308,309,310,311,312,313,341,428,443,544,545,558,741,742,749,750,805,819,820,7922,7924,7925,7927,7934,7943,7944,7945,7950,8062,8148,8149,8152,8164,8174,8236,8240,8262,8264,8374,8380,8381,8384,8388,8390,8392,8393,8394,8396,8401,8406,8416,8419,8424,8437,8439,8445,8482,8485,8496,8521,8603,8936,8946,9046,9050,9063,9066,9076,9092,9100,9108,9111,9113,9131,9162,9164,9218,9219,11329,11331,11334,11336,11346,11361,11363,11366,11370,11372,11375,11389,11682,11686,11687,11692,11694,11714,11716,11723,11725,11730,11736,11982,11989,12102,12336,12348,12350,12384,12393,12395,12397,12510,12553,12851,12962,12973,13738,13823,13919,13933,14080,14298,14585,14698,15583,15847,16318,16434,16438,16481,16729,17102,17122,17315,17320,17402,17418,17859,17909,17911,17915,17916,17936,17939,17961,18664,18703,18814,18962,19043,33469,33470,33471,33484,33485,33490,33497,33501,33505,33513,33520,33536,33550,37845,37921,37948,38029,38038,38064,38065,38066,38069,38075,38076,38078,39108,39109,39113,39114,39115,39116,39265,39394,189000]} \ No newline at end of file diff --git a/node_modules/iconv-lite/encodings/tables/gbk-added.json b/node_modules/iconv-lite/encodings/tables/gbk-added.json new file mode 100644 index 0000000..b742e36 --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/gbk-added.json @@ -0,0 +1,56 @@ +[ +["a140","",62], +["a180","",32], +["a240","",62], +["a280","",32], +["a2ab","",5], +["a2e3","€"], +["a2ef",""], +["a2fd",""], +["a340","",62], +["a380","",31," "], +["a440","",62], +["a480","",32], +["a4f4","",10], +["a540","",62], +["a580","",32], +["a5f7","",7], +["a640","",62], +["a680","",32], +["a6b9","",7], +["a6d9","",6], +["a6ec",""], +["a6f3",""], +["a6f6","",8], +["a740","",62], +["a780","",32], +["a7c2","",14], +["a7f2","",12], +["a896","",10], +["a8bc","ḿ"], +["a8bf","ǹ"], +["a8c1",""], +["a8ea","",20], +["a958",""], +["a95b",""], +["a95d",""], +["a989","〾⿰",11], +["a997","",12], +["a9f0","",14], +["aaa1","",93], +["aba1","",93], +["aca1","",93], +["ada1","",93], +["aea1","",93], +["afa1","",93], +["d7fa","",4], +["f8a1","",93], +["f9a1","",93], +["faa1","",93], +["fba1","",93], +["fca1","",93], +["fda1","",93], +["fe50","⺁⺄㑳㑇⺈⺋㖞㘚㘎⺌⺗㥮㤘㧏㧟㩳㧐㭎㱮㳠⺧⺪䁖䅟⺮䌷⺳⺶⺷䎱䎬⺻䏝䓖䙡䙌"], +["fe80","䜣䜩䝼䞍⻊䥇䥺䥽䦂䦃䦅䦆䦟䦛䦷䦶䲣䲟䲠䲡䱷䲢䴓",6,"䶮",93], +["8135f437",""] +] diff --git a/node_modules/iconv-lite/encodings/tables/shiftjis.json b/node_modules/iconv-lite/encodings/tables/shiftjis.json new file mode 100644 index 0000000..5a3a43c --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/shiftjis.json @@ -0,0 +1,125 @@ +[ +["0","\u0000",128], +["a1","。",62], +["8140"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×"], +["8180","÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇◆□■△▲▽▼※〒→←↑↓〓"], +["81b8","∈∋⊆⊇⊂⊃∪∩"], +["81c8","∧∨¬⇒⇔∀∃"], +["81da","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"], +["81f0","ʼn♯♭♪†‡¶"], +["81fc","◯"], +["824f","0",9], +["8260","A",25], +["8281","a",25], +["829f","ぁ",82], +["8340","ァ",62], +["8380","ム",22], +["839f","Α",16,"Σ",6], +["83bf","α",16,"σ",6], +["8440","А",5,"ЁЖ",25], +["8470","а",5,"ёж",7], +["8480","о",17], +["849f","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"], +["8740","①",19,"Ⅰ",9], +["875f","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"], +["877e","㍻"], +["8780","〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"], +["889f","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"], +["8940","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円"], +["8980","園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"], +["8a40","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫"], +["8a80","橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"], +["8b40","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救"], +["8b80","朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"], +["8c40","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨"], +["8c80","劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"], +["8d40","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降"], +["8d80","項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"], +["8e40","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止"], +["8e80","死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"], +["8f40","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳"], +["8f80","準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"], +["9040","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨"], +["9080","逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"], +["9140","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻"], +["9180","操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"], +["9240","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄"], +["9280","逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"], +["9340","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬"], +["9380","凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"], +["9440","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅"], +["9480","楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"], +["9540","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷"], +["9580","斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"], +["9640","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆"], +["9680","摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"], +["9740","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲"], +["9780","沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"], +["9840","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"], +["989f","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"], +["9940","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭"], +["9980","凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"], +["9a40","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸"], +["9a80","噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"], +["9b40","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀"], +["9b80","它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"], +["9c40","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠"], +["9c80","怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"], +["9d40","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫"], +["9d80","捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"], +["9e40","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎"], +["9e80","梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"], +["9f40","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯"], +["9f80","麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"], +["e040","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝"], +["e080","烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"], +["e140","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿"], +["e180","痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], +["e240","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰"], +["e280","窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"], +["e340","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷"], +["e380","縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"], +["e440","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤"], +["e480","艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], +["e540","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬"], +["e580","蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"], +["e640","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧"], +["e680","諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"], +["e740","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜"], +["e780","轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"], +["e840","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙"], +["e880","閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"], +["e940","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃"], +["e980","騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"], +["ea40","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯"], +["ea80","黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙"], +["ed40","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏"], +["ed80","塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"], +["ee40","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙"], +["ee80","蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"], +["eeef","ⅰ",9,"¬¦'""], +["f040","",62], +["f080","",124], +["f140","",62], +["f180","",124], +["f240","",62], +["f280","",124], +["f340","",62], +["f380","",124], +["f440","",62], +["f480","",124], +["f540","",62], +["f580","",124], +["f640","",62], +["f680","",124], +["f740","",62], +["f780","",124], +["f840","",62], +["f880","",124], +["f940",""], +["fa40","ⅰ",9,"Ⅰ",9,"¬¦'"㈱№℡∵纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊"], +["fa80","兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯"], +["fb40","涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神"], +["fb80","祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙"], +["fc40","髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"] +] diff --git a/node_modules/iconv-lite/encodings/utf16.js b/node_modules/iconv-lite/encodings/utf16.js new file mode 100644 index 0000000..97d0669 --- /dev/null +++ b/node_modules/iconv-lite/encodings/utf16.js @@ -0,0 +1,197 @@ +"use strict"; +var Buffer = require("safer-buffer").Buffer; + +// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js + +// == UTF16-BE codec. ========================================================== + +exports.utf16be = Utf16BECodec; +function Utf16BECodec() { +} + +Utf16BECodec.prototype.encoder = Utf16BEEncoder; +Utf16BECodec.prototype.decoder = Utf16BEDecoder; +Utf16BECodec.prototype.bomAware = true; + + +// -- Encoding + +function Utf16BEEncoder() { +} + +Utf16BEEncoder.prototype.write = function(str) { + var buf = Buffer.from(str, 'ucs2'); + for (var i = 0; i < buf.length; i += 2) { + var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; + } + return buf; +} + +Utf16BEEncoder.prototype.end = function() { +} + + +// -- Decoding + +function Utf16BEDecoder() { + this.overflowByte = -1; +} + +Utf16BEDecoder.prototype.write = function(buf) { + if (buf.length == 0) + return ''; + + var buf2 = Buffer.alloc(buf.length + 1), + i = 0, j = 0; + + if (this.overflowByte !== -1) { + buf2[0] = buf[0]; + buf2[1] = this.overflowByte; + i = 1; j = 2; + } + + for (; i < buf.length-1; i += 2, j+= 2) { + buf2[j] = buf[i+1]; + buf2[j+1] = buf[i]; + } + + this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; + + return buf2.slice(0, j).toString('ucs2'); +} + +Utf16BEDecoder.prototype.end = function() { + this.overflowByte = -1; +} + + +// == UTF-16 codec ============================================================= +// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. +// Defaults to UTF-16LE, as it's prevalent and default in Node. +// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le +// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); + +// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). + +exports.utf16 = Utf16Codec; +function Utf16Codec(codecOptions, iconv) { + this.iconv = iconv; +} + +Utf16Codec.prototype.encoder = Utf16Encoder; +Utf16Codec.prototype.decoder = Utf16Decoder; + + +// -- Encoding (pass-through) + +function Utf16Encoder(options, codec) { + options = options || {}; + if (options.addBOM === undefined) + options.addBOM = true; + this.encoder = codec.iconv.getEncoder('utf-16le', options); +} + +Utf16Encoder.prototype.write = function(str) { + return this.encoder.write(str); +} + +Utf16Encoder.prototype.end = function() { + return this.encoder.end(); +} + + +// -- Decoding + +function Utf16Decoder(options, codec) { + this.decoder = null; + this.initialBufs = []; + this.initialBufsLen = 0; + + this.options = options || {}; + this.iconv = codec.iconv; +} + +Utf16Decoder.prototype.write = function(buf) { + if (!this.decoder) { + // Codec is not chosen yet. Accumulate initial bytes. + this.initialBufs.push(buf); + this.initialBufsLen += buf.length; + + if (this.initialBufsLen < 16) // We need more bytes to use space heuristic (see below) + return ''; + + // We have enough bytes -> detect endianness. + var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + + var resStr = ''; + for (var i = 0; i < this.initialBufs.length; i++) + resStr += this.decoder.write(this.initialBufs[i]); + + this.initialBufs.length = this.initialBufsLen = 0; + return resStr; + } + + return this.decoder.write(buf); +} + +Utf16Decoder.prototype.end = function() { + if (!this.decoder) { + var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + + var resStr = ''; + for (var i = 0; i < this.initialBufs.length; i++) + resStr += this.decoder.write(this.initialBufs[i]); + + var trail = this.decoder.end(); + if (trail) + resStr += trail; + + this.initialBufs.length = this.initialBufsLen = 0; + return resStr; + } + return this.decoder.end(); +} + +function detectEncoding(bufs, defaultEncoding) { + var b = []; + var charsProcessed = 0; + var asciiCharsLE = 0, asciiCharsBE = 0; // Number of ASCII chars when decoded as LE or BE. + + outer_loop: + for (var i = 0; i < bufs.length; i++) { + var buf = bufs[i]; + for (var j = 0; j < buf.length; j++) { + b.push(buf[j]); + if (b.length === 2) { + if (charsProcessed === 0) { + // Check BOM first. + if (b[0] === 0xFF && b[1] === 0xFE) return 'utf-16le'; + if (b[0] === 0xFE && b[1] === 0xFF) return 'utf-16be'; + } + + if (b[0] === 0 && b[1] !== 0) asciiCharsBE++; + if (b[0] !== 0 && b[1] === 0) asciiCharsLE++; + + b.length = 0; + charsProcessed++; + + if (charsProcessed >= 100) { + break outer_loop; + } + } + } + } + + // Make decisions. + // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. + // So, we count ASCII as if it was LE or BE, and decide from that. + if (asciiCharsBE > asciiCharsLE) return 'utf-16be'; + if (asciiCharsBE < asciiCharsLE) return 'utf-16le'; + + // Couldn't decide (likely all zeros or not enough data). + return defaultEncoding || 'utf-16le'; +} + + diff --git a/node_modules/iconv-lite/encodings/utf32.js b/node_modules/iconv-lite/encodings/utf32.js new file mode 100644 index 0000000..2fa900a --- /dev/null +++ b/node_modules/iconv-lite/encodings/utf32.js @@ -0,0 +1,319 @@ +'use strict'; + +var Buffer = require('safer-buffer').Buffer; + +// == UTF32-LE/BE codec. ========================================================== + +exports._utf32 = Utf32Codec; + +function Utf32Codec(codecOptions, iconv) { + this.iconv = iconv; + this.bomAware = true; + this.isLE = codecOptions.isLE; +} + +exports.utf32le = { type: '_utf32', isLE: true }; +exports.utf32be = { type: '_utf32', isLE: false }; + +// Aliases +exports.ucs4le = 'utf32le'; +exports.ucs4be = 'utf32be'; + +Utf32Codec.prototype.encoder = Utf32Encoder; +Utf32Codec.prototype.decoder = Utf32Decoder; + +// -- Encoding + +function Utf32Encoder(options, codec) { + this.isLE = codec.isLE; + this.highSurrogate = 0; +} + +Utf32Encoder.prototype.write = function(str) { + var src = Buffer.from(str, 'ucs2'); + var dst = Buffer.alloc(src.length * 2); + var write32 = this.isLE ? dst.writeUInt32LE : dst.writeUInt32BE; + var offset = 0; + + for (var i = 0; i < src.length; i += 2) { + var code = src.readUInt16LE(i); + var isHighSurrogate = (0xD800 <= code && code < 0xDC00); + var isLowSurrogate = (0xDC00 <= code && code < 0xE000); + + if (this.highSurrogate) { + if (isHighSurrogate || !isLowSurrogate) { + // There shouldn't be two high surrogates in a row, nor a high surrogate which isn't followed by a low + // surrogate. If this happens, keep the pending high surrogate as a stand-alone semi-invalid character + // (technically wrong, but expected by some applications, like Windows file names). + write32.call(dst, this.highSurrogate, offset); + offset += 4; + } + else { + // Create 32-bit value from high and low surrogates; + var codepoint = (((this.highSurrogate - 0xD800) << 10) | (code - 0xDC00)) + 0x10000; + + write32.call(dst, codepoint, offset); + offset += 4; + this.highSurrogate = 0; + + continue; + } + } + + if (isHighSurrogate) + this.highSurrogate = code; + else { + // Even if the current character is a low surrogate, with no previous high surrogate, we'll + // encode it as a semi-invalid stand-alone character for the same reasons expressed above for + // unpaired high surrogates. + write32.call(dst, code, offset); + offset += 4; + this.highSurrogate = 0; + } + } + + if (offset < dst.length) + dst = dst.slice(0, offset); + + return dst; +}; + +Utf32Encoder.prototype.end = function() { + // Treat any leftover high surrogate as a semi-valid independent character. + if (!this.highSurrogate) + return; + + var buf = Buffer.alloc(4); + + if (this.isLE) + buf.writeUInt32LE(this.highSurrogate, 0); + else + buf.writeUInt32BE(this.highSurrogate, 0); + + this.highSurrogate = 0; + + return buf; +}; + +// -- Decoding + +function Utf32Decoder(options, codec) { + this.isLE = codec.isLE; + this.badChar = codec.iconv.defaultCharUnicode.charCodeAt(0); + this.overflow = []; +} + +Utf32Decoder.prototype.write = function(src) { + if (src.length === 0) + return ''; + + var i = 0; + var codepoint = 0; + var dst = Buffer.alloc(src.length + 4); + var offset = 0; + var isLE = this.isLE; + var overflow = this.overflow; + var badChar = this.badChar; + + if (overflow.length > 0) { + for (; i < src.length && overflow.length < 4; i++) + overflow.push(src[i]); + + if (overflow.length === 4) { + // NOTE: codepoint is a signed int32 and can be negative. + // NOTE: We copied this block from below to help V8 optimize it (it works with array, not buffer). + if (isLE) { + codepoint = overflow[i] | (overflow[i+1] << 8) | (overflow[i+2] << 16) | (overflow[i+3] << 24); + } else { + codepoint = overflow[i+3] | (overflow[i+2] << 8) | (overflow[i+1] << 16) | (overflow[i] << 24); + } + overflow.length = 0; + + offset = _writeCodepoint(dst, offset, codepoint, badChar); + } + } + + // Main loop. Should be as optimized as possible. + for (; i < src.length - 3; i += 4) { + // NOTE: codepoint is a signed int32 and can be negative. + if (isLE) { + codepoint = src[i] | (src[i+1] << 8) | (src[i+2] << 16) | (src[i+3] << 24); + } else { + codepoint = src[i+3] | (src[i+2] << 8) | (src[i+1] << 16) | (src[i] << 24); + } + offset = _writeCodepoint(dst, offset, codepoint, badChar); + } + + // Keep overflowing bytes. + for (; i < src.length; i++) { + overflow.push(src[i]); + } + + return dst.slice(0, offset).toString('ucs2'); +}; + +function _writeCodepoint(dst, offset, codepoint, badChar) { + // NOTE: codepoint is signed int32 and can be negative. We keep it that way to help V8 with optimizations. + if (codepoint < 0 || codepoint > 0x10FFFF) { + // Not a valid Unicode codepoint + codepoint = badChar; + } + + // Ephemeral Planes: Write high surrogate. + if (codepoint >= 0x10000) { + codepoint -= 0x10000; + + var high = 0xD800 | (codepoint >> 10); + dst[offset++] = high & 0xff; + dst[offset++] = high >> 8; + + // Low surrogate is written below. + var codepoint = 0xDC00 | (codepoint & 0x3FF); + } + + // Write BMP char or low surrogate. + dst[offset++] = codepoint & 0xff; + dst[offset++] = codepoint >> 8; + + return offset; +}; + +Utf32Decoder.prototype.end = function() { + this.overflow.length = 0; +}; + +// == UTF-32 Auto codec ============================================================= +// Decoder chooses automatically from UTF-32LE and UTF-32BE using BOM and space-based heuristic. +// Defaults to UTF-32LE. http://en.wikipedia.org/wiki/UTF-32 +// Encoder/decoder default can be changed: iconv.decode(buf, 'utf32', {defaultEncoding: 'utf-32be'}); + +// Encoder prepends BOM (which can be overridden with (addBOM: false}). + +exports.utf32 = Utf32AutoCodec; +exports.ucs4 = 'utf32'; + +function Utf32AutoCodec(options, iconv) { + this.iconv = iconv; +} + +Utf32AutoCodec.prototype.encoder = Utf32AutoEncoder; +Utf32AutoCodec.prototype.decoder = Utf32AutoDecoder; + +// -- Encoding + +function Utf32AutoEncoder(options, codec) { + options = options || {}; + + if (options.addBOM === undefined) + options.addBOM = true; + + this.encoder = codec.iconv.getEncoder(options.defaultEncoding || 'utf-32le', options); +} + +Utf32AutoEncoder.prototype.write = function(str) { + return this.encoder.write(str); +}; + +Utf32AutoEncoder.prototype.end = function() { + return this.encoder.end(); +}; + +// -- Decoding + +function Utf32AutoDecoder(options, codec) { + this.decoder = null; + this.initialBufs = []; + this.initialBufsLen = 0; + this.options = options || {}; + this.iconv = codec.iconv; +} + +Utf32AutoDecoder.prototype.write = function(buf) { + if (!this.decoder) { + // Codec is not chosen yet. Accumulate initial bytes. + this.initialBufs.push(buf); + this.initialBufsLen += buf.length; + + if (this.initialBufsLen < 32) // We need more bytes to use space heuristic (see below) + return ''; + + // We have enough bytes -> detect endianness. + var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + + var resStr = ''; + for (var i = 0; i < this.initialBufs.length; i++) + resStr += this.decoder.write(this.initialBufs[i]); + + this.initialBufs.length = this.initialBufsLen = 0; + return resStr; + } + + return this.decoder.write(buf); +}; + +Utf32AutoDecoder.prototype.end = function() { + if (!this.decoder) { + var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + + var resStr = ''; + for (var i = 0; i < this.initialBufs.length; i++) + resStr += this.decoder.write(this.initialBufs[i]); + + var trail = this.decoder.end(); + if (trail) + resStr += trail; + + this.initialBufs.length = this.initialBufsLen = 0; + return resStr; + } + + return this.decoder.end(); +}; + +function detectEncoding(bufs, defaultEncoding) { + var b = []; + var charsProcessed = 0; + var invalidLE = 0, invalidBE = 0; // Number of invalid chars when decoded as LE or BE. + var bmpCharsLE = 0, bmpCharsBE = 0; // Number of BMP chars when decoded as LE or BE. + + outer_loop: + for (var i = 0; i < bufs.length; i++) { + var buf = bufs[i]; + for (var j = 0; j < buf.length; j++) { + b.push(buf[j]); + if (b.length === 4) { + if (charsProcessed === 0) { + // Check BOM first. + if (b[0] === 0xFF && b[1] === 0xFE && b[2] === 0 && b[3] === 0) { + return 'utf-32le'; + } + if (b[0] === 0 && b[1] === 0 && b[2] === 0xFE && b[3] === 0xFF) { + return 'utf-32be'; + } + } + + if (b[0] !== 0 || b[1] > 0x10) invalidBE++; + if (b[3] !== 0 || b[2] > 0x10) invalidLE++; + + if (b[0] === 0 && b[1] === 0 && (b[2] !== 0 || b[3] !== 0)) bmpCharsBE++; + if ((b[0] !== 0 || b[1] !== 0) && b[2] === 0 && b[3] === 0) bmpCharsLE++; + + b.length = 0; + charsProcessed++; + + if (charsProcessed >= 100) { + break outer_loop; + } + } + } + } + + // Make decisions. + if (bmpCharsBE - invalidBE > bmpCharsLE - invalidLE) return 'utf-32be'; + if (bmpCharsBE - invalidBE < bmpCharsLE - invalidLE) return 'utf-32le'; + + // Couldn't decide (likely all zeros or not enough data). + return defaultEncoding || 'utf-32le'; +} diff --git a/node_modules/iconv-lite/encodings/utf7.js b/node_modules/iconv-lite/encodings/utf7.js new file mode 100644 index 0000000..eacae34 --- /dev/null +++ b/node_modules/iconv-lite/encodings/utf7.js @@ -0,0 +1,290 @@ +"use strict"; +var Buffer = require("safer-buffer").Buffer; + +// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 +// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 + +exports.utf7 = Utf7Codec; +exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 +function Utf7Codec(codecOptions, iconv) { + this.iconv = iconv; +}; + +Utf7Codec.prototype.encoder = Utf7Encoder; +Utf7Codec.prototype.decoder = Utf7Decoder; +Utf7Codec.prototype.bomAware = true; + + +// -- Encoding + +var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; + +function Utf7Encoder(options, codec) { + this.iconv = codec.iconv; +} + +Utf7Encoder.prototype.write = function(str) { + // Naive implementation. + // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". + return Buffer.from(str.replace(nonDirectChars, function(chunk) { + return "+" + (chunk === '+' ? '' : + this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) + + "-"; + }.bind(this))); +} + +Utf7Encoder.prototype.end = function() { +} + + +// -- Decoding + +function Utf7Decoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} + +var base64Regex = /[A-Za-z0-9\/+]/; +var base64Chars = []; +for (var i = 0; i < 256; i++) + base64Chars[i] = base64Regex.test(String.fromCharCode(i)); + +var plusChar = '+'.charCodeAt(0), + minusChar = '-'.charCodeAt(0), + andChar = '&'.charCodeAt(0); + +Utf7Decoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; + + // The decoder is more involved as we must handle chunks in stream. + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '+' + if (buf[i] == plusChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; + } + } else { // We decode base64. + if (!base64Chars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" + res += "+"; + } else { + var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), "ascii"); + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus is absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; + } + } + } + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii"); + + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); + + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + + return res; +} + +Utf7Decoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; +} + + +// UTF-7-IMAP codec. +// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) +// Differences: +// * Base64 part is started by "&" instead of "+" +// * Direct characters are 0x20-0x7E, except "&" (0x26) +// * In Base64, "," is used instead of "/" +// * Base64 must not be used to represent direct characters. +// * No implicit shift back from Base64 (should always end with '-') +// * String must end in non-shifted position. +// * "-&" while in base64 is not allowed. + + +exports.utf7imap = Utf7IMAPCodec; +function Utf7IMAPCodec(codecOptions, iconv) { + this.iconv = iconv; +}; + +Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; +Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; +Utf7IMAPCodec.prototype.bomAware = true; + + +// -- Encoding + +function Utf7IMAPEncoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = Buffer.alloc(6); + this.base64AccumIdx = 0; +} + +Utf7IMAPEncoder.prototype.write = function(str) { + var inBase64 = this.inBase64, + base64Accum = this.base64Accum, + base64AccumIdx = this.base64AccumIdx, + buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0; + + for (var i = 0; i < str.length; i++) { + var uChar = str.charCodeAt(i); + if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'. + if (inBase64) { + if (base64AccumIdx > 0) { + bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + base64AccumIdx = 0; + } + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + inBase64 = false; + } + + if (!inBase64) { + buf[bufIdx++] = uChar; // Write direct character + + if (uChar === andChar) // Ampersand -> '&-' + buf[bufIdx++] = minusChar; + } + + } else { // Non-direct character + if (!inBase64) { + buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. + inBase64 = true; + } + if (inBase64) { + base64Accum[base64AccumIdx++] = uChar >> 8; + base64Accum[base64AccumIdx++] = uChar & 0xFF; + + if (base64AccumIdx == base64Accum.length) { + bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); + base64AccumIdx = 0; + } + } + } + } + + this.inBase64 = inBase64; + this.base64AccumIdx = base64AccumIdx; + + return buf.slice(0, bufIdx); +} + +Utf7IMAPEncoder.prototype.end = function() { + var buf = Buffer.alloc(10), bufIdx = 0; + if (this.inBase64) { + if (this.base64AccumIdx > 0) { + bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + this.base64AccumIdx = 0; + } + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + this.inBase64 = false; + } + + return buf.slice(0, bufIdx); +} + + +// -- Decoding + +function Utf7IMAPDecoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} + +var base64IMAPChars = base64Chars.slice(); +base64IMAPChars[','.charCodeAt(0)] = true; + +Utf7IMAPDecoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; + + // The decoder is more involved as we must handle chunks in stream. + // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '&' + if (buf[i] == andChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; + } + } else { // We decode base64. + if (!base64IMAPChars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" + res += "&"; + } else { + var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), "ascii").replace(/,/g, '/'); + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus may be absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; + } + } + } + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii").replace(/,/g, '/'); + + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); + + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + + return res; +} + +Utf7IMAPDecoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; +} + + diff --git a/node_modules/iconv-lite/lib/bom-handling.js b/node_modules/iconv-lite/lib/bom-handling.js new file mode 100644 index 0000000..1050872 --- /dev/null +++ b/node_modules/iconv-lite/lib/bom-handling.js @@ -0,0 +1,52 @@ +"use strict"; + +var BOMChar = '\uFEFF'; + +exports.PrependBOM = PrependBOMWrapper +function PrependBOMWrapper(encoder, options) { + this.encoder = encoder; + this.addBOM = true; +} + +PrependBOMWrapper.prototype.write = function(str) { + if (this.addBOM) { + str = BOMChar + str; + this.addBOM = false; + } + + return this.encoder.write(str); +} + +PrependBOMWrapper.prototype.end = function() { + return this.encoder.end(); +} + + +//------------------------------------------------------------------------------ + +exports.StripBOM = StripBOMWrapper; +function StripBOMWrapper(decoder, options) { + this.decoder = decoder; + this.pass = false; + this.options = options || {}; +} + +StripBOMWrapper.prototype.write = function(buf) { + var res = this.decoder.write(buf); + if (this.pass || !res) + return res; + + if (res[0] === BOMChar) { + res = res.slice(1); + if (typeof this.options.stripBOM === 'function') + this.options.stripBOM(); + } + + this.pass = true; + return res; +} + +StripBOMWrapper.prototype.end = function() { + return this.decoder.end(); +} + diff --git a/node_modules/iconv-lite/lib/index.d.ts b/node_modules/iconv-lite/lib/index.d.ts new file mode 100644 index 0000000..99f200f --- /dev/null +++ b/node_modules/iconv-lite/lib/index.d.ts @@ -0,0 +1,41 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + * REQUIREMENT: This definition is dependent on the @types/node definition. + * Install with `npm install @types/node --save-dev` + *--------------------------------------------------------------------------------------------*/ + +declare module 'iconv-lite' { + // Basic API + export function decode(buffer: Buffer, encoding: string, options?: Options): string; + + export function encode(content: string, encoding: string, options?: Options): Buffer; + + export function encodingExists(encoding: string): boolean; + + // Stream API + export function decodeStream(encoding: string, options?: Options): NodeJS.ReadWriteStream; + + export function encodeStream(encoding: string, options?: Options): NodeJS.ReadWriteStream; + + // Low-level stream APIs + export function getEncoder(encoding: string, options?: Options): EncoderStream; + + export function getDecoder(encoding: string, options?: Options): DecoderStream; +} + +export interface Options { + stripBOM?: boolean; + addBOM?: boolean; + defaultEncoding?: string; +} + +export interface EncoderStream { + write(str: string): Buffer; + end(): Buffer | undefined; +} + +export interface DecoderStream { + write(buf: Buffer): string; + end(): string | undefined; +} diff --git a/node_modules/iconv-lite/lib/index.js b/node_modules/iconv-lite/lib/index.js new file mode 100644 index 0000000..657701c --- /dev/null +++ b/node_modules/iconv-lite/lib/index.js @@ -0,0 +1,180 @@ +"use strict"; + +var Buffer = require("safer-buffer").Buffer; + +var bomHandling = require("./bom-handling"), + iconv = module.exports; + +// All codecs and aliases are kept here, keyed by encoding name/alias. +// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. +iconv.encodings = null; + +// Characters emitted in case of error. +iconv.defaultCharUnicode = '�'; +iconv.defaultCharSingleByte = '?'; + +// Public API. +iconv.encode = function encode(str, encoding, options) { + str = "" + (str || ""); // Ensure string. + + var encoder = iconv.getEncoder(encoding, options); + + var res = encoder.write(str); + var trail = encoder.end(); + + return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; +} + +iconv.decode = function decode(buf, encoding, options) { + if (typeof buf === 'string') { + if (!iconv.skipDecodeWarning) { + console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); + iconv.skipDecodeWarning = true; + } + + buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. + } + + var decoder = iconv.getDecoder(encoding, options); + + var res = decoder.write(buf); + var trail = decoder.end(); + + return trail ? (res + trail) : res; +} + +iconv.encodingExists = function encodingExists(enc) { + try { + iconv.getCodec(enc); + return true; + } catch (e) { + return false; + } +} + +// Legacy aliases to convert functions +iconv.toEncoding = iconv.encode; +iconv.fromEncoding = iconv.decode; + +// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. +iconv._codecDataCache = {}; +iconv.getCodec = function getCodec(encoding) { + if (!iconv.encodings) + iconv.encodings = require("../encodings"); // Lazy load all encoding definitions. + + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + var enc = iconv._canonicalizeEncoding(encoding); + + // Traverse iconv.encodings to find actual codec. + var codecOptions = {}; + while (true) { + var codec = iconv._codecDataCache[enc]; + if (codec) + return codec; + + var codecDef = iconv.encodings[enc]; + + switch (typeof codecDef) { + case "string": // Direct alias to other encoding. + enc = codecDef; + break; + + case "object": // Alias with options. Can be layered. + for (var key in codecDef) + codecOptions[key] = codecDef[key]; + + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; + + enc = codecDef.type; + break; + + case "function": // Codec itself. + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; + + // The codec function must load all tables and return object with .encoder and .decoder methods. + // It'll be called only once (for each different options object). + codec = new codecDef(codecOptions, iconv); + + iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. + return codec; + + default: + throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); + } + } +} + +iconv._canonicalizeEncoding = function(encoding) { + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, ""); +} + +iconv.getEncoder = function getEncoder(encoding, options) { + var codec = iconv.getCodec(encoding), + encoder = new codec.encoder(options, codec); + + if (codec.bomAware && options && options.addBOM) + encoder = new bomHandling.PrependBOM(encoder, options); + + return encoder; +} + +iconv.getDecoder = function getDecoder(encoding, options) { + var codec = iconv.getCodec(encoding), + decoder = new codec.decoder(options, codec); + + if (codec.bomAware && !(options && options.stripBOM === false)) + decoder = new bomHandling.StripBOM(decoder, options); + + return decoder; +} + +// Streaming API +// NOTE: Streaming API naturally depends on 'stream' module from Node.js. Unfortunately in browser environments this module can add +// up to 100Kb to the output bundle. To avoid unnecessary code bloat, we don't enable Streaming API in browser by default. +// If you would like to enable it explicitly, please add the following code to your app: +// > iconv.enableStreamingAPI(require('stream')); +iconv.enableStreamingAPI = function enableStreamingAPI(stream_module) { + if (iconv.supportsStreams) + return; + + // Dependency-inject stream module to create IconvLite stream classes. + var streams = require("./streams")(stream_module); + + // Not public API yet, but expose the stream classes. + iconv.IconvLiteEncoderStream = streams.IconvLiteEncoderStream; + iconv.IconvLiteDecoderStream = streams.IconvLiteDecoderStream; + + // Streaming API. + iconv.encodeStream = function encodeStream(encoding, options) { + return new iconv.IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); + } + + iconv.decodeStream = function decodeStream(encoding, options) { + return new iconv.IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); + } + + iconv.supportsStreams = true; +} + +// Enable Streaming API automatically if 'stream' module is available and non-empty (the majority of environments). +var stream_module; +try { + stream_module = require("stream"); +} catch (e) {} + +if (stream_module && stream_module.Transform) { + iconv.enableStreamingAPI(stream_module); + +} else { + // In rare cases where 'stream' module is not available by default, throw a helpful exception. + iconv.encodeStream = iconv.decodeStream = function() { + throw new Error("iconv-lite Streaming API is not enabled. Use iconv.enableStreamingAPI(require('stream')); to enable it."); + }; +} + +if ("Ā" != "\u0100") { + console.error("iconv-lite warning: js files use non-utf8 encoding. See https://github.com/ashtuchkin/iconv-lite/wiki/Javascript-source-file-encodings for more info."); +} diff --git a/node_modules/iconv-lite/lib/streams.js b/node_modules/iconv-lite/lib/streams.js new file mode 100644 index 0000000..a150648 --- /dev/null +++ b/node_modules/iconv-lite/lib/streams.js @@ -0,0 +1,109 @@ +"use strict"; + +var Buffer = require("safer-buffer").Buffer; + +// NOTE: Due to 'stream' module being pretty large (~100Kb, significant in browser environments), +// we opt to dependency-inject it instead of creating a hard dependency. +module.exports = function(stream_module) { + var Transform = stream_module.Transform; + + // == Encoder stream ======================================================= + + function IconvLiteEncoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.decodeStrings = false; // We accept only strings, so we don't need to decode them. + Transform.call(this, options); + } + + IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteEncoderStream } + }); + + IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { + if (typeof chunk != 'string') + return done(new Error("Iconv encoding stream needs strings as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res); + done(); + } + catch (e) { + done(e); + } + } + + IconvLiteEncoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res); + done(); + } + catch (e) { + done(e); + } + } + + IconvLiteEncoderStream.prototype.collect = function(cb) { + var chunks = []; + this.on('error', cb); + this.on('data', function(chunk) { chunks.push(chunk); }); + this.on('end', function() { + cb(null, Buffer.concat(chunks)); + }); + return this; + } + + + // == Decoder stream ======================================================= + + function IconvLiteDecoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.encoding = this.encoding = 'utf8'; // We output strings. + Transform.call(this, options); + } + + IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteDecoderStream } + }); + + IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { + if (!Buffer.isBuffer(chunk) && !(chunk instanceof Uint8Array)) + return done(new Error("Iconv decoding stream needs buffers as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res, this.encoding); + done(); + } + catch (e) { + done(e); + } + } + + IconvLiteDecoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res, this.encoding); + done(); + } + catch (e) { + done(e); + } + } + + IconvLiteDecoderStream.prototype.collect = function(cb) { + var res = ''; + this.on('error', cb); + this.on('data', function(chunk) { res += chunk; }); + this.on('end', function() { + cb(null, res); + }); + return this; + } + + return { + IconvLiteEncoderStream: IconvLiteEncoderStream, + IconvLiteDecoderStream: IconvLiteDecoderStream, + }; +}; diff --git a/node_modules/iconv-lite/package.json b/node_modules/iconv-lite/package.json new file mode 100644 index 0000000..d351115 --- /dev/null +++ b/node_modules/iconv-lite/package.json @@ -0,0 +1,44 @@ +{ + "name": "iconv-lite", + "description": "Convert character encodings in pure javascript.", + "version": "0.6.3", + "license": "MIT", + "keywords": [ + "iconv", + "convert", + "charset", + "icu" + ], + "author": "Alexander Shtuchkin ", + "main": "./lib/index.js", + "typings": "./lib/index.d.ts", + "homepage": "https://github.com/ashtuchkin/iconv-lite", + "bugs": "https://github.com/ashtuchkin/iconv-lite/issues", + "repository": { + "type": "git", + "url": "git://github.com/ashtuchkin/iconv-lite.git" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "coverage": "c8 _mocha --grep .", + "test": "mocha --reporter spec --grep ." + }, + "browser": { + "stream": false + }, + "devDependencies": { + "async": "^3.2.0", + "c8": "^7.2.0", + "errto": "^0.2.1", + "iconv": "^2.3.5", + "mocha": "^3.5.3", + "request": "^2.88.2", + "semver": "^6.3.0", + "unorm": "^1.6.0" + }, + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + } +} diff --git a/node_modules/inherits/LICENSE b/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/inherits/README.md b/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/inherits/inherits.js b/node_modules/inherits/inherits.js new file mode 100644 index 0000000..f71f2d9 --- /dev/null +++ b/node_modules/inherits/inherits.js @@ -0,0 +1,9 @@ +try { + var util = require('util'); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = require('./inherits_browser.js'); +} diff --git a/node_modules/inherits/inherits_browser.js b/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..86bbb3d --- /dev/null +++ b/node_modules/inherits/inherits_browser.js @@ -0,0 +1,27 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} diff --git a/node_modules/inherits/package.json b/node_modules/inherits/package.json new file mode 100644 index 0000000..37b4366 --- /dev/null +++ b/node_modules/inherits/package.json @@ -0,0 +1,29 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.4", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": "git://github.com/isaacs/inherits", + "license": "ISC", + "scripts": { + "test": "tap" + }, + "devDependencies": { + "tap": "^14.2.4" + }, + "files": [ + "inherits.js", + "inherits_browser.js" + ] +} diff --git a/node_modules/ipaddr.js/LICENSE b/node_modules/ipaddr.js/LICENSE new file mode 100644 index 0000000..f6b37b5 --- /dev/null +++ b/node_modules/ipaddr.js/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2011-2017 whitequark + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/ipaddr.js/README.md b/node_modules/ipaddr.js/README.md new file mode 100644 index 0000000..f57725b --- /dev/null +++ b/node_modules/ipaddr.js/README.md @@ -0,0 +1,233 @@ +# ipaddr.js — an IPv6 and IPv4 address manipulation library [![Build Status](https://travis-ci.org/whitequark/ipaddr.js.svg)](https://travis-ci.org/whitequark/ipaddr.js) + +ipaddr.js is a small (1.9K minified and gzipped) library for manipulating +IP addresses in JavaScript environments. It runs on both CommonJS runtimes +(e.g. [nodejs]) and in a web browser. + +ipaddr.js allows you to verify and parse string representation of an IP +address, match it against a CIDR range or range list, determine if it falls +into some reserved ranges (examples include loopback and private ranges), +and convert between IPv4 and IPv4-mapped IPv6 addresses. + +[nodejs]: http://nodejs.org + +## Installation + +`npm install ipaddr.js` + +or + +`bower install ipaddr.js` + +## API + +ipaddr.js defines one object in the global scope: `ipaddr`. In CommonJS, +it is exported from the module: + +```js +var ipaddr = require('ipaddr.js'); +``` + +The API consists of several global methods and two classes: ipaddr.IPv6 and ipaddr.IPv4. + +### Global methods + +There are three global methods defined: `ipaddr.isValid`, `ipaddr.parse` and +`ipaddr.process`. All of them receive a string as a single parameter. + +The `ipaddr.isValid` method returns `true` if the address is a valid IPv4 or +IPv6 address, and `false` otherwise. It does not throw any exceptions. + +The `ipaddr.parse` method returns an object representing the IP address, +or throws an `Error` if the passed string is not a valid representation of an +IP address. + +The `ipaddr.process` method works just like the `ipaddr.parse` one, but it +automatically converts IPv4-mapped IPv6 addresses to their IPv4 counterparts +before returning. It is useful when you have a Node.js instance listening +on an IPv6 socket, and the `net.ivp6.bindv6only` sysctl parameter (or its +equivalent on non-Linux OS) is set to 0. In this case, you can accept IPv4 +connections on your IPv6-only socket, but the remote address will be mangled. +Use `ipaddr.process` method to automatically demangle it. + +### Object representation + +Parsing methods return an object which descends from `ipaddr.IPv6` or +`ipaddr.IPv4`. These objects share some properties, but most of them differ. + +#### Shared properties + +One can determine the type of address by calling `addr.kind()`. It will return +either `"ipv6"` or `"ipv4"`. + +An address can be converted back to its string representation with `addr.toString()`. +Note that this method: + * does not return the original string used to create the object (in fact, there is + no way of getting that string) + * returns a compact representation (when it is applicable) + +A `match(range, bits)` method can be used to check if the address falls into a +certain CIDR range. +Note that an address can be (obviously) matched only against an address of the same type. + +For example: + +```js +var addr = ipaddr.parse("2001:db8:1234::1"); +var range = ipaddr.parse("2001:db8::"); + +addr.match(range, 32); // => true +``` + +Alternatively, `match` can also be called as `match([range, bits])`. In this way, +it can be used together with the `parseCIDR(string)` method, which parses an IP +address together with a CIDR range. + +For example: + +```js +var addr = ipaddr.parse("2001:db8:1234::1"); + +addr.match(ipaddr.parseCIDR("2001:db8::/32")); // => true +``` + +A `range()` method returns one of predefined names for several special ranges defined +by IP protocols. The exact names (and their respective CIDR ranges) can be looked up +in the source: [IPv6 ranges] and [IPv4 ranges]. Some common ones include `"unicast"` +(the default one) and `"reserved"`. + +You can match against your own range list by using +`ipaddr.subnetMatch(address, rangeList, defaultName)` method. It can work with a mix of IPv6 or IPv4 addresses, and accepts a name-to-subnet map as the range list. For example: + +```js +var rangeList = { + documentationOnly: [ ipaddr.parse('2001:db8::'), 32 ], + tunnelProviders: [ + [ ipaddr.parse('2001:470::'), 32 ], // he.net + [ ipaddr.parse('2001:5c0::'), 32 ] // freenet6 + ] +}; +ipaddr.subnetMatch(ipaddr.parse('2001:470:8:66::1'), rangeList, 'unknown'); // => "tunnelProviders" +``` + +The addresses can be converted to their byte representation with `toByteArray()`. +(Actually, JavaScript mostly does not know about byte buffers. They are emulated with +arrays of numbers, each in range of 0..255.) + +```js +var bytes = ipaddr.parse('2a00:1450:8007::68').toByteArray(); // ipv6.google.com +bytes // => [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, , 0x00, 0x68 ] +``` + +The `ipaddr.IPv4` and `ipaddr.IPv6` objects have some methods defined, too. All of them +have the same interface for both protocols, and are similar to global methods. + +`ipaddr.IPvX.isValid(string)` can be used to check if the string is a valid address +for particular protocol, and `ipaddr.IPvX.parse(string)` is the error-throwing parser. + +`ipaddr.IPvX.isValid(string)` uses the same format for parsing as the POSIX `inet_ntoa` function, which accepts unusual formats like `0xc0.168.1.1` or `0x10000000`. The function `ipaddr.IPv4.isValidFourPartDecimal(string)` validates the IPv4 address and also ensures that it is written in four-part decimal format. + +[IPv6 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L186 +[IPv4 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L71 + +#### IPv6 properties + +Sometimes you will want to convert IPv6 not to a compact string representation (with +the `::` substitution); the `toNormalizedString()` method will return an address where +all zeroes are explicit. + +For example: + +```js +var addr = ipaddr.parse("2001:0db8::0001"); +addr.toString(); // => "2001:db8::1" +addr.toNormalizedString(); // => "2001:db8:0:0:0:0:0:1" +``` + +The `isIPv4MappedAddress()` method will return `true` if this address is an IPv4-mapped +one, and `toIPv4Address()` will return an IPv4 object address. + +To access the underlying binary representation of the address, use `addr.parts`. + +```js +var addr = ipaddr.parse("2001:db8:10::1234:DEAD"); +addr.parts // => [0x2001, 0xdb8, 0x10, 0, 0, 0, 0x1234, 0xdead] +``` + +A IPv6 zone index can be accessed via `addr.zoneId`: + +```js +var addr = ipaddr.parse("2001:db8::%eth0"); +addr.zoneId // => 'eth0' +``` + +#### IPv4 properties + +`toIPv4MappedAddress()` will return a corresponding IPv4-mapped IPv6 address. + +To access the underlying representation of the address, use `addr.octets`. + +```js +var addr = ipaddr.parse("192.168.1.1"); +addr.octets // => [192, 168, 1, 1] +``` + +`prefixLengthFromSubnetMask()` will return a CIDR prefix length for a valid IPv4 netmask or +null if the netmask is not valid. + +```js +ipaddr.IPv4.parse('255.255.255.240').prefixLengthFromSubnetMask() == 28 +ipaddr.IPv4.parse('255.192.164.0').prefixLengthFromSubnetMask() == null +``` + +`subnetMaskFromPrefixLength()` will return an IPv4 netmask for a valid CIDR prefix length. + +```js +ipaddr.IPv4.subnetMaskFromPrefixLength(24) == "255.255.255.0" +ipaddr.IPv4.subnetMaskFromPrefixLength(29) == "255.255.255.248" +``` + +`broadcastAddressFromCIDR()` will return the broadcast address for a given IPv4 interface and netmask in CIDR notation. +```js +ipaddr.IPv4.broadcastAddressFromCIDR("172.0.0.1/24") == "172.0.0.255" +``` +`networkAddressFromCIDR()` will return the network address for a given IPv4 interface and netmask in CIDR notation. +```js +ipaddr.IPv4.networkAddressFromCIDR("172.0.0.1/24") == "172.0.0.0" +``` + +#### Conversion + +IPv4 and IPv6 can be converted bidirectionally to and from network byte order (MSB) byte arrays. + +The `fromByteArray()` method will take an array and create an appropriate IPv4 or IPv6 object +if the input satisfies the requirements. For IPv4 it has to be an array of four 8-bit values, +while for IPv6 it has to be an array of sixteen 8-bit values. + +For example: +```js +var addr = ipaddr.fromByteArray([0x7f, 0, 0, 1]); +addr.toString(); // => "127.0.0.1" +``` + +or + +```js +var addr = ipaddr.fromByteArray([0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]) +addr.toString(); // => "2001:db8::1" +``` + +Both objects also offer a `toByteArray()` method, which returns an array in network byte order (MSB). + +For example: +```js +var addr = ipaddr.parse("127.0.0.1"); +addr.toByteArray(); // => [0x7f, 0, 0, 1] +``` + +or + +```js +var addr = ipaddr.parse("2001:db8::1"); +addr.toByteArray(); // => [0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] +``` diff --git a/node_modules/ipaddr.js/ipaddr.min.js b/node_modules/ipaddr.js/ipaddr.min.js new file mode 100644 index 0000000..b54a7cc --- /dev/null +++ b/node_modules/ipaddr.js/ipaddr.min.js @@ -0,0 +1 @@ +(function(){var r,t,n,e,i,o,a,s;t={},s=this,"undefined"!=typeof module&&null!==module&&module.exports?module.exports=t:s.ipaddr=t,a=function(r,t,n,e){var i,o;if(r.length!==t.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");for(i=0;e>0;){if((o=n-e)<0&&(o=0),r[i]>>o!=t[i]>>o)return!1;e-=n,i+=1}return!0},t.subnetMatch=function(r,t,n){var e,i,o,a,s;null==n&&(n="unicast");for(o in t)for(!(a=t[o])[0]||a[0]instanceof Array||(a=[a]),e=0,i=a.length;e=0;t=n+=-1){if(!((e=this.octets[t])in a))return null;if(o=a[e],i&&0!==o)return null;8!==o&&(i=!0),r+=o}return 32-r},r}(),n="(0?\\d+|0x[a-f0-9]+)",e={fourOctet:new RegExp("^"+n+"\\."+n+"\\."+n+"\\."+n+"$","i"),longValue:new RegExp("^"+n+"$","i")},t.IPv4.parser=function(r){var t,n,i,o,a;if(n=function(r){return"0"===r[0]&&"x"!==r[1]?parseInt(r,8):parseInt(r)},t=r.match(e.fourOctet))return function(){var r,e,o,a;for(a=[],r=0,e=(o=t.slice(1,6)).length;r4294967295||a<0)throw new Error("ipaddr: address outside defined range");return function(){var r,t;for(t=[],o=r=0;r<=24;o=r+=8)t.push(a>>o&255);return t}().reverse()}return null},t.IPv6=function(){function r(r,t){var n,e,i,o,a,s;if(16===r.length)for(this.parts=[],n=e=0;e<=14;n=e+=2)this.parts.push(r[n]<<8|r[n+1]);else{if(8!==r.length)throw new Error("ipaddr: ipv6 part count should be 8 or 16");this.parts=r}for(i=0,o=(s=this.parts).length;it&&(r=n.index,t=n[0].length);return t<0?i:i.substring(0,r)+"::"+i.substring(r+t)},r.prototype.toByteArray=function(){var r,t,n,e,i;for(r=[],t=0,n=(i=this.parts).length;t>8),r.push(255&e);return r},r.prototype.toNormalizedString=function(){var r,t,n;return r=function(){var r,n,e,i;for(i=[],r=0,n=(e=this.parts).length;r>8,255&r,n>>8,255&n])},r.prototype.prefixLengthFromSubnetMask=function(){var r,t,n,e,i,o,a;for(a={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},r=0,i=!1,t=n=7;n>=0;t=n+=-1){if(!((e=this.parts[t])in a))return null;if(o=a[e],i&&0!==o)return null;16!==o&&(i=!0),r+=o}return 128-r},r}(),i="(?:[0-9a-f]+::?)+",o={zoneIndex:new RegExp("%[0-9a-z]{1,}","i"),native:new RegExp("^(::)?("+i+")?([0-9a-f]+)?(::)?(%[0-9a-z]{1,})?$","i"),transitional:new RegExp("^((?:"+i+")|(?:::)(?:"+i+")?)"+n+"\\."+n+"\\."+n+"\\."+n+"(%[0-9a-z]{1,})?$","i")},r=function(r,t){var n,e,i,a,s,p;if(r.indexOf("::")!==r.lastIndexOf("::"))return null;for((p=(r.match(o.zoneIndex)||[])[0])&&(p=p.substring(1),r=r.replace(/%.+$/,"")),n=0,e=-1;(e=r.indexOf(":",e+1))>=0;)n++;if("::"===r.substr(0,2)&&n--,"::"===r.substr(-2,2)&&n--,n>t)return null;for(s=t-n,a=":";s--;)a+="0:";return":"===(r=r.replace("::",a))[0]&&(r=r.slice(1)),":"===r[r.length-1]&&(r=r.slice(0,-1)),t=function(){var t,n,e,o;for(o=[],t=0,n=(e=r.split(":")).length;t=0&&t<=32)return e=[this.parse(n[1]),t],Object.defineProperty(e,"toString",{value:function(){return this.join("/")}}),e;throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},t.IPv4.subnetMaskFromPrefixLength=function(r){var t,n,e;if((r=parseInt(r))<0||r>32)throw new Error("ipaddr: invalid IPv4 prefix length");for(e=[0,0,0,0],n=0,t=Math.floor(r/8);n=0&&t<=128)return e=[this.parse(n[1]),t],Object.defineProperty(e,"toString",{value:function(){return this.join("/")}}),e;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},t.isValid=function(r){return t.IPv6.isValid(r)||t.IPv4.isValid(r)},t.parse=function(r){if(t.IPv6.isValid(r))return t.IPv6.parse(r);if(t.IPv4.isValid(r))return t.IPv4.parse(r);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},t.parseCIDR=function(r){try{return t.IPv6.parseCIDR(r)}catch(n){n;try{return t.IPv4.parseCIDR(r)}catch(r){throw r,new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},t.fromByteArray=function(r){var n;if(4===(n=r.length))return new t.IPv4(r);if(16===n)return new t.IPv6(r);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},t.process=function(r){var t;return t=this.parse(r),"ipv6"===t.kind()&&t.isIPv4MappedAddress()?t.toIPv4Address():t}}).call(this); \ No newline at end of file diff --git a/node_modules/ipaddr.js/lib/ipaddr.js b/node_modules/ipaddr.js/lib/ipaddr.js new file mode 100644 index 0000000..18bd93b --- /dev/null +++ b/node_modules/ipaddr.js/lib/ipaddr.js @@ -0,0 +1,673 @@ +(function() { + var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex; + + ipaddr = {}; + + root = this; + + if ((typeof module !== "undefined" && module !== null) && module.exports) { + module.exports = ipaddr; + } else { + root['ipaddr'] = ipaddr; + } + + matchCIDR = function(first, second, partSize, cidrBits) { + var part, shift; + if (first.length !== second.length) { + throw new Error("ipaddr: cannot match CIDR for objects with different lengths"); + } + part = 0; + while (cidrBits > 0) { + shift = partSize - cidrBits; + if (shift < 0) { + shift = 0; + } + if (first[part] >> shift !== second[part] >> shift) { + return false; + } + cidrBits -= partSize; + part += 1; + } + return true; + }; + + ipaddr.subnetMatch = function(address, rangeList, defaultName) { + var k, len, rangeName, rangeSubnets, subnet; + if (defaultName == null) { + defaultName = 'unicast'; + } + for (rangeName in rangeList) { + rangeSubnets = rangeList[rangeName]; + if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) { + rangeSubnets = [rangeSubnets]; + } + for (k = 0, len = rangeSubnets.length; k < len; k++) { + subnet = rangeSubnets[k]; + if (address.kind() === subnet[0].kind()) { + if (address.match.apply(address, subnet)) { + return rangeName; + } + } + } + } + return defaultName; + }; + + ipaddr.IPv4 = (function() { + function IPv4(octets) { + var k, len, octet; + if (octets.length !== 4) { + throw new Error("ipaddr: ipv4 octet count should be 4"); + } + for (k = 0, len = octets.length; k < len; k++) { + octet = octets[k]; + if (!((0 <= octet && octet <= 255))) { + throw new Error("ipaddr: ipv4 octet should fit in 8 bits"); + } + } + this.octets = octets; + } + + IPv4.prototype.kind = function() { + return 'ipv4'; + }; + + IPv4.prototype.toString = function() { + return this.octets.join("."); + }; + + IPv4.prototype.toNormalizedString = function() { + return this.toString(); + }; + + IPv4.prototype.toByteArray = function() { + return this.octets.slice(0); + }; + + IPv4.prototype.match = function(other, cidrRange) { + var ref; + if (cidrRange === void 0) { + ref = other, other = ref[0], cidrRange = ref[1]; + } + if (other.kind() !== 'ipv4') { + throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one"); + } + return matchCIDR(this.octets, other.octets, 8, cidrRange); + }; + + IPv4.prototype.SpecialRanges = { + unspecified: [[new IPv4([0, 0, 0, 0]), 8]], + broadcast: [[new IPv4([255, 255, 255, 255]), 32]], + multicast: [[new IPv4([224, 0, 0, 0]), 4]], + linkLocal: [[new IPv4([169, 254, 0, 0]), 16]], + loopback: [[new IPv4([127, 0, 0, 0]), 8]], + carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]], + "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]], + reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]] + }; + + IPv4.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + + IPv4.prototype.toIPv4MappedAddress = function() { + return ipaddr.IPv6.parse("::ffff:" + (this.toString())); + }; + + IPv4.prototype.prefixLengthFromSubnetMask = function() { + var cidr, i, k, octet, stop, zeros, zerotable; + zerotable = { + 0: 8, + 128: 7, + 192: 6, + 224: 5, + 240: 4, + 248: 3, + 252: 2, + 254: 1, + 255: 0 + }; + cidr = 0; + stop = false; + for (i = k = 3; k >= 0; i = k += -1) { + octet = this.octets[i]; + if (octet in zerotable) { + zeros = zerotable[octet]; + if (stop && zeros !== 0) { + return null; + } + if (zeros !== 8) { + stop = true; + } + cidr += zeros; + } else { + return null; + } + } + return 32 - cidr; + }; + + return IPv4; + + })(); + + ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; + + ipv4Regexes = { + fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'), + longValue: new RegExp("^" + ipv4Part + "$", 'i') + }; + + ipaddr.IPv4.parser = function(string) { + var match, parseIntAuto, part, shift, value; + parseIntAuto = function(string) { + if (string[0] === "0" && string[1] !== "x") { + return parseInt(string, 8); + } else { + return parseInt(string); + } + }; + if (match = string.match(ipv4Regexes.fourOctet)) { + return (function() { + var k, len, ref, results; + ref = match.slice(1, 6); + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(parseIntAuto(part)); + } + return results; + })(); + } else if (match = string.match(ipv4Regexes.longValue)) { + value = parseIntAuto(match[1]); + if (value > 0xffffffff || value < 0) { + throw new Error("ipaddr: address outside defined range"); + } + return ((function() { + var k, results; + results = []; + for (shift = k = 0; k <= 24; shift = k += 8) { + results.push((value >> shift) & 0xff); + } + return results; + })()).reverse(); + } else { + return null; + } + }; + + ipaddr.IPv6 = (function() { + function IPv6(parts, zoneId) { + var i, k, l, len, part, ref; + if (parts.length === 16) { + this.parts = []; + for (i = k = 0; k <= 14; i = k += 2) { + this.parts.push((parts[i] << 8) | parts[i + 1]); + } + } else if (parts.length === 8) { + this.parts = parts; + } else { + throw new Error("ipaddr: ipv6 part count should be 8 or 16"); + } + ref = this.parts; + for (l = 0, len = ref.length; l < len; l++) { + part = ref[l]; + if (!((0 <= part && part <= 0xffff))) { + throw new Error("ipaddr: ipv6 part should fit in 16 bits"); + } + } + if (zoneId) { + this.zoneId = zoneId; + } + } + + IPv6.prototype.kind = function() { + return 'ipv6'; + }; + + IPv6.prototype.toString = function() { + return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, '::'); + }; + + IPv6.prototype.toRFC5952String = function() { + var bestMatchIndex, bestMatchLength, match, regex, string; + regex = /((^|:)(0(:|$)){2,})/g; + string = this.toNormalizedString(); + bestMatchIndex = 0; + bestMatchLength = -1; + while ((match = regex.exec(string))) { + if (match[0].length > bestMatchLength) { + bestMatchIndex = match.index; + bestMatchLength = match[0].length; + } + } + if (bestMatchLength < 0) { + return string; + } + return string.substring(0, bestMatchIndex) + '::' + string.substring(bestMatchIndex + bestMatchLength); + }; + + IPv6.prototype.toByteArray = function() { + var bytes, k, len, part, ref; + bytes = []; + ref = this.parts; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + bytes.push(part >> 8); + bytes.push(part & 0xff); + } + return bytes; + }; + + IPv6.prototype.toNormalizedString = function() { + var addr, part, suffix; + addr = ((function() { + var k, len, ref, results; + ref = this.parts; + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(part.toString(16)); + } + return results; + }).call(this)).join(":"); + suffix = ''; + if (this.zoneId) { + suffix = '%' + this.zoneId; + } + return addr + suffix; + }; + + IPv6.prototype.toFixedLengthString = function() { + var addr, part, suffix; + addr = ((function() { + var k, len, ref, results; + ref = this.parts; + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(part.toString(16).padStart(4, '0')); + } + return results; + }).call(this)).join(":"); + suffix = ''; + if (this.zoneId) { + suffix = '%' + this.zoneId; + } + return addr + suffix; + }; + + IPv6.prototype.match = function(other, cidrRange) { + var ref; + if (cidrRange === void 0) { + ref = other, other = ref[0], cidrRange = ref[1]; + } + if (other.kind() !== 'ipv6') { + throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one"); + } + return matchCIDR(this.parts, other.parts, 16, cidrRange); + }; + + IPv6.prototype.SpecialRanges = { + unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128], + linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10], + multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8], + loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128], + uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7], + ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96], + rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96], + rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96], + '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16], + teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32], + reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]] + }; + + IPv6.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + + IPv6.prototype.isIPv4MappedAddress = function() { + return this.range() === 'ipv4Mapped'; + }; + + IPv6.prototype.toIPv4Address = function() { + var high, low, ref; + if (!this.isIPv4MappedAddress()) { + throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4"); + } + ref = this.parts.slice(-2), high = ref[0], low = ref[1]; + return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]); + }; + + IPv6.prototype.prefixLengthFromSubnetMask = function() { + var cidr, i, k, part, stop, zeros, zerotable; + zerotable = { + 0: 16, + 32768: 15, + 49152: 14, + 57344: 13, + 61440: 12, + 63488: 11, + 64512: 10, + 65024: 9, + 65280: 8, + 65408: 7, + 65472: 6, + 65504: 5, + 65520: 4, + 65528: 3, + 65532: 2, + 65534: 1, + 65535: 0 + }; + cidr = 0; + stop = false; + for (i = k = 7; k >= 0; i = k += -1) { + part = this.parts[i]; + if (part in zerotable) { + zeros = zerotable[part]; + if (stop && zeros !== 0) { + return null; + } + if (zeros !== 16) { + stop = true; + } + cidr += zeros; + } else { + return null; + } + } + return 128 - cidr; + }; + + return IPv6; + + })(); + + ipv6Part = "(?:[0-9a-f]+::?)+"; + + zoneIndex = "%[0-9a-z]{1,}"; + + ipv6Regexes = { + zoneIndex: new RegExp(zoneIndex, 'i'), + "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?(" + zoneIndex + ")?$", 'i'), + transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + (ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part) + ("(" + zoneIndex + ")?$"), 'i') + }; + + expandIPv6 = function(string, parts) { + var colonCount, lastColon, part, replacement, replacementCount, zoneId; + if (string.indexOf('::') !== string.lastIndexOf('::')) { + return null; + } + zoneId = (string.match(ipv6Regexes['zoneIndex']) || [])[0]; + if (zoneId) { + zoneId = zoneId.substring(1); + string = string.replace(/%.+$/, ''); + } + colonCount = 0; + lastColon = -1; + while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) { + colonCount++; + } + if (string.substr(0, 2) === '::') { + colonCount--; + } + if (string.substr(-2, 2) === '::') { + colonCount--; + } + if (colonCount > parts) { + return null; + } + replacementCount = parts - colonCount; + replacement = ':'; + while (replacementCount--) { + replacement += '0:'; + } + string = string.replace('::', replacement); + if (string[0] === ':') { + string = string.slice(1); + } + if (string[string.length - 1] === ':') { + string = string.slice(0, -1); + } + parts = (function() { + var k, len, ref, results; + ref = string.split(":"); + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(parseInt(part, 16)); + } + return results; + })(); + return { + parts: parts, + zoneId: zoneId + }; + }; + + ipaddr.IPv6.parser = function(string) { + var addr, k, len, match, octet, octets, zoneId; + if (ipv6Regexes['native'].test(string)) { + return expandIPv6(string, 8); + } else if (match = string.match(ipv6Regexes['transitional'])) { + zoneId = match[6] || ''; + addr = expandIPv6(match[1].slice(0, -1) + zoneId, 6); + if (addr.parts) { + octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])]; + for (k = 0, len = octets.length; k < len; k++) { + octet = octets[k]; + if (!((0 <= octet && octet <= 255))) { + return null; + } + } + addr.parts.push(octets[0] << 8 | octets[1]); + addr.parts.push(octets[2] << 8 | octets[3]); + return { + parts: addr.parts, + zoneId: addr.zoneId + }; + } + } + return null; + }; + + ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) { + return this.parser(string) !== null; + }; + + ipaddr.IPv4.isValid = function(string) { + var e; + try { + new this(this.parser(string)); + return true; + } catch (error1) { + e = error1; + return false; + } + }; + + ipaddr.IPv4.isValidFourPartDecimal = function(string) { + if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) { + return true; + } else { + return false; + } + }; + + ipaddr.IPv6.isValid = function(string) { + var addr, e; + if (typeof string === "string" && string.indexOf(":") === -1) { + return false; + } + try { + addr = this.parser(string); + new this(addr.parts, addr.zoneId); + return true; + } catch (error1) { + e = error1; + return false; + } + }; + + ipaddr.IPv4.parse = function(string) { + var parts; + parts = this.parser(string); + if (parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); + } + return new this(parts); + }; + + ipaddr.IPv6.parse = function(string) { + var addr; + addr = this.parser(string); + if (addr.parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); + } + return new this(addr.parts, addr.zoneId); + }; + + ipaddr.IPv4.parseCIDR = function(string) { + var maskLength, match, parsed; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 32) { + parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, 'toString', { + value: function() { + return this.join('/'); + } + }); + return parsed; + } + } + throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range"); + }; + + ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) { + var filledOctetCount, j, octets; + prefix = parseInt(prefix); + if (prefix < 0 || prefix > 32) { + throw new Error('ipaddr: invalid IPv4 prefix length'); + } + octets = [0, 0, 0, 0]; + j = 0; + filledOctetCount = Math.floor(prefix / 8); + while (j < filledOctetCount) { + octets[j] = 255; + j++; + } + if (filledOctetCount < 4) { + octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8); + } + return new this(octets); + }; + + ipaddr.IPv4.broadcastAddressFromCIDR = function(string) { + var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; + try { + cidr = this.parseCIDR(string); + ipInterfaceOctets = cidr[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); + octets = []; + i = 0; + while (i < 4) { + octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255); + i++; + } + return new this(octets); + } catch (error1) { + error = error1; + throw new Error('ipaddr: the address does not have IPv4 CIDR format'); + } + }; + + ipaddr.IPv4.networkAddressFromCIDR = function(string) { + var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; + try { + cidr = this.parseCIDR(string); + ipInterfaceOctets = cidr[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); + octets = []; + i = 0; + while (i < 4) { + octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10)); + i++; + } + return new this(octets); + } catch (error1) { + error = error1; + throw new Error('ipaddr: the address does not have IPv4 CIDR format'); + } + }; + + ipaddr.IPv6.parseCIDR = function(string) { + var maskLength, match, parsed; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 128) { + parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, 'toString', { + value: function() { + return this.join('/'); + } + }); + return parsed; + } + } + throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range"); + }; + + ipaddr.isValid = function(string) { + return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string); + }; + + ipaddr.parse = function(string) { + if (ipaddr.IPv6.isValid(string)) { + return ipaddr.IPv6.parse(string); + } else if (ipaddr.IPv4.isValid(string)) { + return ipaddr.IPv4.parse(string); + } else { + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format"); + } + }; + + ipaddr.parseCIDR = function(string) { + var e; + try { + return ipaddr.IPv6.parseCIDR(string); + } catch (error1) { + e = error1; + try { + return ipaddr.IPv4.parseCIDR(string); + } catch (error1) { + e = error1; + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format"); + } + } + }; + + ipaddr.fromByteArray = function(bytes) { + var length; + length = bytes.length; + if (length === 4) { + return new ipaddr.IPv4(bytes); + } else if (length === 16) { + return new ipaddr.IPv6(bytes); + } else { + throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address"); + } + }; + + ipaddr.process = function(string) { + var addr; + addr = this.parse(string); + if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) { + return addr.toIPv4Address(); + } else { + return addr; + } + }; + +}).call(this); diff --git a/node_modules/ipaddr.js/lib/ipaddr.js.d.ts b/node_modules/ipaddr.js/lib/ipaddr.js.d.ts new file mode 100644 index 0000000..52174b6 --- /dev/null +++ b/node_modules/ipaddr.js/lib/ipaddr.js.d.ts @@ -0,0 +1,68 @@ +declare module "ipaddr.js" { + type IPv4Range = 'unicast' | 'unspecified' | 'broadcast' | 'multicast' | 'linkLocal' | 'loopback' | 'carrierGradeNat' | 'private' | 'reserved'; + type IPv6Range = 'unicast' | 'unspecified' | 'linkLocal' | 'multicast' | 'loopback' | 'uniqueLocal' | 'ipv4Mapped' | 'rfc6145' | 'rfc6052' | '6to4' | 'teredo' | 'reserved'; + + interface RangeList { + [name: string]: [T, number] | [T, number][]; + } + + // Common methods/properties for IPv4 and IPv6 classes. + class IP { + prefixLengthFromSubnetMask(): number | null; + toByteArray(): number[]; + toNormalizedString(): string; + toString(): string; + } + + namespace Address { + export function isValid(addr: string): boolean; + export function fromByteArray(bytes: number[]): IPv4 | IPv6; + export function parse(addr: string): IPv4 | IPv6; + export function parseCIDR(mask: string): [IPv4 | IPv6, number]; + export function process(addr: string): IPv4 | IPv6; + export function subnetMatch(addr: IPv4, rangeList: RangeList, defaultName?: string): string; + export function subnetMatch(addr: IPv6, rangeList: RangeList, defaultName?: string): string; + + export class IPv4 extends IP { + static broadcastAddressFromCIDR(addr: string): IPv4; + static isIPv4(addr: string): boolean; + static isValidFourPartDecimal(addr: string): boolean; + static isValid(addr: string): boolean; + static networkAddressFromCIDR(addr: string): IPv4; + static parse(addr: string): IPv4; + static parseCIDR(addr: string): [IPv4, number]; + static subnetMaskFromPrefixLength(prefix: number): IPv4; + constructor(octets: number[]); + octets: number[] + + kind(): 'ipv4'; + match(addr: IPv4, bits: number): boolean; + match(mask: [IPv4, number]): boolean; + range(): IPv4Range; + subnetMatch(rangeList: RangeList, defaultName?: string): string; + toIPv4MappedAddress(): IPv6; + } + + export class IPv6 extends IP { + static broadcastAddressFromCIDR(addr: string): IPv6; + static isIPv6(addr: string): boolean; + static isValid(addr: string): boolean; + static parse(addr: string): IPv6; + static parseCIDR(addr: string): [IPv6, number]; + static subnetMaskFromPrefixLength(prefix: number): IPv6; + constructor(parts: number[]); + parts: number[] + zoneId?: string + + isIPv4MappedAddress(): boolean; + kind(): 'ipv6'; + match(addr: IPv6, bits: number): boolean; + match(mask: [IPv6, number]): boolean; + range(): IPv6Range; + subnetMatch(rangeList: RangeList, defaultName?: string): string; + toIPv4Address(): IPv4; + } + } + + export = Address; +} diff --git a/node_modules/ipaddr.js/package.json b/node_modules/ipaddr.js/package.json new file mode 100644 index 0000000..f4d3547 --- /dev/null +++ b/node_modules/ipaddr.js/package.json @@ -0,0 +1,35 @@ +{ + "name": "ipaddr.js", + "description": "A library for manipulating IPv4 and IPv6 addresses in JavaScript.", + "version": "1.9.1", + "author": "whitequark ", + "directories": { + "lib": "./lib" + }, + "dependencies": {}, + "devDependencies": { + "coffee-script": "~1.12.6", + "nodeunit": "^0.11.3", + "uglify-js": "~3.0.19" + }, + "scripts": { + "test": "cake build test" + }, + "files": [ + "lib/", + "LICENSE", + "ipaddr.min.js" + ], + "keywords": [ + "ip", + "ipv4", + "ipv6" + ], + "repository": "git://github.com/whitequark/ipaddr.js", + "main": "./lib/ipaddr.js", + "engines": { + "node": ">= 0.10" + }, + "license": "MIT", + "types": "./lib/ipaddr.js.d.ts" +} diff --git a/node_modules/is-promise/LICENSE b/node_modules/is-promise/LICENSE new file mode 100644 index 0000000..27cc9f3 --- /dev/null +++ b/node_modules/is-promise/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 Forbes Lindesay + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/is-promise/index.d.ts b/node_modules/is-promise/index.d.ts new file mode 100644 index 0000000..2107b42 --- /dev/null +++ b/node_modules/is-promise/index.d.ts @@ -0,0 +1,2 @@ +declare function isPromise(obj: PromiseLike | S): obj is PromiseLike; +export default isPromise; diff --git a/node_modules/is-promise/index.js b/node_modules/is-promise/index.js new file mode 100644 index 0000000..1bed087 --- /dev/null +++ b/node_modules/is-promise/index.js @@ -0,0 +1,6 @@ +module.exports = isPromise; +module.exports.default = isPromise; + +function isPromise(obj) { + return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; +} diff --git a/node_modules/is-promise/index.mjs b/node_modules/is-promise/index.mjs new file mode 100644 index 0000000..bf9e99b --- /dev/null +++ b/node_modules/is-promise/index.mjs @@ -0,0 +1,3 @@ +export default function isPromise(obj) { + return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; +} diff --git a/node_modules/is-promise/package.json b/node_modules/is-promise/package.json new file mode 100644 index 0000000..2a3c540 --- /dev/null +++ b/node_modules/is-promise/package.json @@ -0,0 +1,30 @@ +{ + "name": "is-promise", + "version": "4.0.0", + "description": "Test whether an object looks like a promises-a+ promise", + "main": "./index.js", + "scripts": { + "test": "node test" + }, + "files": [ + "index.js", + "index.mjs", + "index.d.ts" + ], + "exports": { + ".": [ + { + "import": "./index.mjs", + "require": "./index.js", + "default": "./index.js" + }, + "./index.js" + ] + }, + "repository": { + "type": "git", + "url": "https://github.com/then/is-promise.git" + }, + "author": "ForbesLindesay", + "license": "MIT" +} diff --git a/node_modules/is-promise/readme.md b/node_modules/is-promise/readme.md new file mode 100644 index 0000000..d53d34b --- /dev/null +++ b/node_modules/is-promise/readme.md @@ -0,0 +1,33 @@ + + +# is-promise + + Test whether an object looks like a promises-a+ promise + + [![Build Status](https://img.shields.io/travis/then/is-promise/master.svg)](https://travis-ci.org/then/is-promise) + [![Dependency Status](https://img.shields.io/david/then/is-promise.svg)](https://david-dm.org/then/is-promise) + [![NPM version](https://img.shields.io/npm/v/is-promise.svg)](https://www.npmjs.org/package/is-promise) + + + +## Installation + + $ npm install is-promise + +You can also use it client side via npm. + +## API + +```typescript +import isPromise from 'is-promise'; + +isPromise(Promise.resolve());//=>true +isPromise({then:function () {...}});//=>true +isPromise(null);//=>false +isPromise({});//=>false +isPromise({then: true})//=>false +``` + +## License + + MIT diff --git a/node_modules/jake/Makefile b/node_modules/jake/Makefile new file mode 100644 index 0000000..3d0574e --- /dev/null +++ b/node_modules/jake/Makefile @@ -0,0 +1,44 @@ +# +# Jake JavaScript build tool +# Copyright 2112 Matthew Eernisse (mde@fleegix.org) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +.PHONY: all build install clean uninstall + +PREFIX=/usr/local +DESTDIR= + +all: build + +build: + @echo 'Jake built.' + +install: + @mkdir -p $(DESTDIR)$(PREFIX)/bin && \ + mkdir -p $(DESTDIR)$(PREFIX)/lib/node_modules/jake && \ + mkdir -p ./node_modules && \ + npm install utilities minimatch && \ + cp -R ./* $(DESTDIR)$(PREFIX)/lib/node_modules/jake/ && \ + ln -snf ../lib/node_modules/jake/bin/cli.js $(DESTDIR)$(PREFIX)/bin/jake && \ + chmod 755 $(DESTDIR)$(PREFIX)/lib/node_modules/jake/bin/cli.js && \ + echo 'Jake installed.' + +clean: + @true + +uninstall: + @rm -f $(DESTDIR)$(PREFIX)/bin/jake && \ + rm -fr $(DESTDIR)$(PREFIX)/lib/node_modules/jake/ && \ + echo 'Jake uninstalled.' diff --git a/node_modules/jake/README.md b/node_modules/jake/README.md new file mode 100644 index 0000000..e938850 --- /dev/null +++ b/node_modules/jake/README.md @@ -0,0 +1,17 @@ +### Jake -- the JavaScript build tool for Node.js + +[![Build Status](https://travis-ci.org/jakejs/jake.svg?branch=master)](https://travis-ci.org/jakejs/jake) + +Documentation site at [http://jakejs.com](http://jakejs.com/) + +### Contributing +1. [Install node](http://nodejs.org/#download). +2. Clone this repository `$ git clone git@github.com:jakejs/jake.git`. +3. Install dependencies `$ npm install`. +4. Run tests with `$ npm test`. +5. Start Hacking! + +### License + +Licensed under the Apache License, Version 2.0 +() diff --git a/node_modules/jake/bin/bash_completion.sh b/node_modules/jake/bin/bash_completion.sh new file mode 100755 index 0000000..bb25995 --- /dev/null +++ b/node_modules/jake/bin/bash_completion.sh @@ -0,0 +1,41 @@ +#!/bin/bash + +# http://stackoverflow.com/a/246128 +SOURCE="${BASH_SOURCE[0]}" +while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink + DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" + SOURCE="$(readlink "$SOURCE")" + [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located +done +JAKE_BIN_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" + +# http://stackoverflow.com/a/12495480 +# http://stackoverflow.com/a/28647824 +_auto_jake() +{ + local cur + local -a COMPGEN=() + _get_comp_words_by_ref -n : -c cur + + # run auto-completions in jake via our auto_complete.js wrapper + local -a auto_complete_info=( $(export COMP_LINE="${COMP_LINE}" && ${JAKE_BIN_DIR}/auto_complete.js "$cur" "${3}") ) + # check reply flag + local reply_flag="${auto_complete_info[0]}" + if [[ "${reply_flag}" == "no-complete" ]]; then + return 1 + fi + local auto_completions=("${auto_complete_info[@]:1}") + COMPGEN=( $(compgen -W "${auto_completions[*]}" -- "$cur") ) + COMPREPLY=( "${COMPGEN[@]}" ) + + __ltrim_colon_completions "$cur" + + # do we need another space?? + if [[ "${reply_flag}" == "yes-space" ]]; then + COMPREPLY=( "${COMPGEN[@]}" " " ) + fi + + return 0 +} + +complete -o default -F _auto_jake jake diff --git a/node_modules/jake/bin/cli.js b/node_modules/jake/bin/cli.js new file mode 100755 index 0000000..9f68abb --- /dev/null +++ b/node_modules/jake/bin/cli.js @@ -0,0 +1,31 @@ +#!/usr/bin/env node +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +// Try to load a local jake +try { + require(`${ process.cwd() }/node_modules/jake`); +} +// If that fails, likely running globally +catch(e) { + require('../lib/jake'); +} + +var args = process.argv.slice(2); + +jake.run.apply(jake, args); diff --git a/node_modules/jake/jakefile.js b/node_modules/jake/jakefile.js new file mode 100644 index 0000000..5a5a55e --- /dev/null +++ b/node_modules/jake/jakefile.js @@ -0,0 +1,112 @@ +let proc = require('child_process'); + +const PROJECT_DIR = process.cwd(); +process.env.PROJECT_DIR = PROJECT_DIR; + +namespace('doc', function () { + task('generate', ['doc:clobber'], function () { + var cmd = '../node-jsdoc-toolkit/app/run.js -n -r=100 ' + + '-t=../node-jsdoc-toolkit/templates/codeview -d=./doc/ ./lib'; + jake.logger.log('Generating docs ...'); + jake.exec([cmd], function () { + jake.logger.log('Done.'); + complete(); + }); + }, {async: true}); + + task('clobber', function () { + var cmd = 'rm -fr ./doc/*'; + jake.exec([cmd], function () { + jake.logger.log('Clobbered old docs.'); + complete(); + }); + }, {async: true}); + +}); + +desc('Generate docs for Jake'); +task('doc', ['doc:generate']); + +npmPublishTask('jake', function () { + this.packageFiles.include([ + 'Makefile', + 'jakefile.js', + 'README.md', + 'package.json', + 'usage.txt', + 'lib/**', + 'bin/**', + 'test/**' + ]); + this.packageFiles.exclude([ + 'test/tmp' + ]); +}); + +jake.Task['publish:package'].directory = PROJECT_DIR; + +namespace('test', function () { + + let integrationTest = task('integration', async function () { + let testArgs = []; + if (process.env.filter) { + testArgs.push(process.env.filter); + } + else { + testArgs.push('*.js'); + } + let spawned = proc.spawn(`${PROJECT_DIR}/node_modules/.bin/mocha`, testArgs, { + stdio: 'inherit' + }); + return new Promise((resolve, reject) => { + spawned.on('exit', () => { + resolve(); + }); + }); + + }); + integrationTest.directory = `${PROJECT_DIR}/test/integration`; + + let integrationClobber = task('integrationClobber', function () { + proc.execSync('rm -rf package.json pkg tmp_publish'); + }); + integrationClobber.directory = `${PROJECT_DIR}/test/integration`; + + let unitTest = task('unit', async function () { + let testArgs = []; + if (process.env.filter) { + testArgs.push(process.env.filter); + } + else { + testArgs.push('*.js'); + } + let spawned = proc.spawn(`${PROJECT_DIR}/node_modules/.bin/mocha`, testArgs, { + stdio: 'inherit' + }); + }); + unitTest.directory = `${PROJECT_DIR}/test/unit`; + +}); + +desc('Runs all tests'); +task('test', ['test:unit', 'test:integration', 'test:integrationClobber']); + +desc('Runs eslint for both lib and test directories'); +task('lint', function (doFix) { + + let cmd = 'eslint --format codeframe "lib/**/*.js" "test/**/*.js"'; + if (doFix) { + cmd += ' --fix'; + } + try { + proc.execSync(cmd); + } + catch (err) { + console.log(err.message); + console.log(err.stderr.toString()); + console.log(err.stdout.toString()); + fail('eslint failed'); + } +}); + + diff --git a/node_modules/jake/lib/api.js b/node_modules/jake/lib/api.js new file mode 100644 index 0000000..9f09140 --- /dev/null +++ b/node_modules/jake/lib/api.js @@ -0,0 +1,409 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +let { uuid } = require('./utils'); + +let api = new (function () { + /** + @name task + @static + @function + @description Creates a Jake Task + ` + @param {String} name The name of the Task + @param {Array} [prereqs] Prerequisites to be run before this task + @param {Function} [action] The action to perform for this task + @param {Object} [opts] + @param {Boolean} [opts.asyc=false] Perform this task asynchronously. + If you flag a task with this option, you must call the global + `complete` method inside the task's action, for execution to proceed + to the next task. + + @example + desc('This is the default task.'); + task('default', function (params) { + console.log('This is the default task.'); + }); + + desc('This task has prerequisites.'); + task('hasPrereqs', ['foo', 'bar', 'baz'], function (params) { + console.log('Ran some prereqs first.'); + }); + + desc('This is an asynchronous task.'); + task('asyncTask', function () { + setTimeout(complete, 1000); + }, {async: true}); + */ + this.task = function (name, prereqs, action, opts) { + let args = Array.prototype.slice.call(arguments); + let createdTask; + args.unshift('task'); + createdTask = jake.createTask.apply(global, args); + jake.currentTaskDescription = null; + return createdTask; + }; + + /** + @name rule + @static + @function + @description Creates a Jake Suffix Rule + ` + @param {String} pattern The suffix name of the objective + @param {String} source The suffix name of the objective + @param {Array} [prereqs] Prerequisites to be run before this task + @param {Function} [action] The action to perform for this task + @param {Object} [opts] + @param {Boolean} [opts.asyc=false] Perform this task asynchronously. + If you flag a task with this option, you must call the global + `complete` method inside the task's action, for execution to proceed + to the next task. + @example + desc('This is a rule, which does not support namespace or pattern.'); + rule('.o', '.c', {async: true}, function () { + let cmd = util.format('gcc -o %s %s', this.name, this.source); + jake.exec([cmd], function () { + complete(); + }, {printStdout: true}); + }); + + desc('This rule has prerequisites.'); + rule('.o', '.c', ['util.h'], {async: true}, function () { + let cmd = util.format('gcc -o %s %s', this.name, this.source); + jake.exec([cmd], function () { + complete(); + }, {printStdout: true}); + }); + + desc('This is a rule with patterns.'); + rule('%.o', '%.c', {async: true}, function () { + let cmd = util.format('gcc -o %s %s', this.name, this.source); + jake.exec([cmd], function () { + complete(); + }, {printStdout: true}); + }); + + desc('This is another rule with patterns.'); + rule('obj/%.o', 'src/%.c', {async: true}, function () { + let cmd = util.format('gcc -o %s %s', this.name, this.source); + jake.exec([cmd], function () { + complete(); + }, {printStdout: true}); + }); + + desc('This is an example with chain rules.'); + rule('%.pdf', '%.dvi', {async: true}, function () { + let cmd = util.format('dvipdfm %s',this.source); + jake.exec([cmd], function () { + complete(); + }, {printStdout: true}); + }); + + rule('%.dvi', '%.tex', {async: true}, function () { + let cmd = util.format('latex %s',this.source); + jake.exec([cmd], function () { + complete(); + }, {printStdout: true}); + }); + + desc('This rule has a namespace.'); + task('default', ['debug:obj/main.o]); + + namespace('debug', {async: true}, function() { + rule('obj/%.o', 'src/%.c', function () { + // ... + }); + } + */ + this.rule = function () { + let args = Array.prototype.slice.call(arguments); + let arg; + let pattern = args.shift(); + let source = args.shift(); + let prereqs = []; + let action = function () {}; + let opts = {}; + let key = pattern.toString(); // May be a RegExp + + while ((arg = args.shift())) { + if (typeof arg == 'function') { + action = arg; + } + else if (Array.isArray(arg)) { + prereqs = arg; + } + else { + opts = arg; + } + } + + jake.currentNamespace.rules[key] = new jake.Rule({ + pattern: pattern, + source: source, + prereqs: prereqs, + action: action, + opts: opts, + desc: jake.currentTaskDescription, + ns: jake.currentNamespace + }); + jake.currentTaskDescription = null; + }; + + /** + @name directory + @static + @function + @description Creates a Jake DirectoryTask. Can be used as a prerequisite + for FileTasks, or for simply ensuring a directory exists for use with a + Task's action. + ` + @param {String} name The name of the DiretoryTask + + @example + + // Creates the package directory for distribution + directory('pkg'); + */ + this.directory = function (name) { + let args = Array.prototype.slice.call(arguments); + let createdTask; + args.unshift('directory'); + createdTask = jake.createTask.apply(global, args); + jake.currentTaskDescription = null; + return createdTask; + }; + + /** + @name file + @static + @function + @description Creates a Jake FileTask. + ` + @param {String} name The name of the FileTask + @param {Array} [prereqs] Prerequisites to be run before this task + @param {Function} [action] The action to create this file, if it doesn't + exist already. + @param {Object} [opts] + @param {Array} [opts.asyc=false] Perform this task asynchronously. + If you flag a task with this option, you must call the global + `complete` method inside the task's action, for execution to proceed + to the next task. + + */ + this.file = function (name, prereqs, action, opts) { + let args = Array.prototype.slice.call(arguments); + let createdTask; + args.unshift('file'); + createdTask = jake.createTask.apply(global, args); + jake.currentTaskDescription = null; + return createdTask; + }; + + /** + @name desc + @static + @function + @description Creates a description for a Jake Task (or FileTask, + DirectoryTask). When invoked, the description that iscreated will + be associated with whatever Task is created next. + ` + @param {String} description The description for the Task + */ + this.desc = function (description) { + jake.currentTaskDescription = description; + }; + + /** + @name namespace + @static + @function + @description Creates a namespace which allows logical grouping + of tasks, and prevents name-collisions with task-names. Namespaces + can be nested inside of other namespaces. + ` + @param {String} name The name of the namespace + @param {Function} scope The enclosing scope for the namespaced tasks + + @example + namespace('doc', function () { + task('generate', ['doc:clobber'], function () { + // Generate some docs + }); + + task('clobber', function () { + // Clobber the doc directory first + }); + }); + */ + this.namespace = function (name, closure) { + let curr = jake.currentNamespace; + let ns = curr.childNamespaces[name] || new jake.Namespace(name, curr); + let fn = closure || function () {}; + curr.childNamespaces[name] = ns; + jake.currentNamespace = ns; + fn(); + jake.currentNamespace = curr; + jake.currentTaskDescription = null; + return ns; + }; + + /** + @name complete + @static + @function + @description Completes an asynchronous task, allowing Jake's + execution to proceed to the next task. Calling complete globally or without + arguments completes the last task on the invocationChain. If you use parallel + execution of prereqs this will probably complete a wrong task. You should call this + function with this task as the first argument, before the optional return value. + Alternatively you can call task.complete() + ` + @example + task('generate', ['doc:clobber'], function () { + exec('./generate_docs.sh', function (err, stdout, stderr) { + if (err || stderr) { + fail(err || stderr); + } + else { + console.log(stdout); + complete(); + } + }); + }, {async: true}); + */ + this.complete = function (task, val) { + //this should detect if the first arg is a task, but I guess it should be more thorough + if(task && task. _currentPrereqIndex >=0 ) { + task.complete(val); + } + else { + val = task; + if(jake._invocationChain.length > 0) { + jake._invocationChain[jake._invocationChain.length-1].complete(val); + } + } + }; + + /** + @name fail + @static + @function + @description Causes Jake execution to abort with an error. + Allows passing an optional error code, which will be used to + set the exit-code of exiting process. + ` + @param {Error|String} err The error to thow when aborting execution. + If this argument is an Error object, it will simply be thrown. If + a String, it will be used as the error-message. (If it is a multi-line + String, the first line will be used as the Error message, and the + remaining lines will be used as the error-stack.) + + @example + task('createTests, function () { + if (!fs.existsSync('./tests')) { + fail('Test directory does not exist.'); + } + else { + // Do some testing stuff ... + } + }); + */ + this.fail = function (err, code) { + let msg; + let errObj; + if (code) { + jake.errorCode = code; + } + if (err) { + if (typeof err == 'string') { + // Use the initial or only line of the error as the error-message + // If there was a multi-line error, use the rest as the stack + msg = err.split('\n'); + errObj = new Error(msg.shift()); + if (msg.length) { + errObj.stack = msg.join('\n'); + } + throw errObj; + } + else if (err instanceof Error) { + throw err; + } + else { + throw new Error(err.toString()); + } + } + else { + throw new Error(); + } + }; + + this.packageTask = function (name, version, prereqs, definition) { + return new jake.PackageTask(name, version, prereqs, definition); + }; + + this.publishTask = function (name, prereqs, opts, definition) { + return new jake.PublishTask(name, prereqs, opts, definition); + }; + + // Backward-compat + this.npmPublishTask = function (name, prereqs, opts, definition) { + return new jake.PublishTask(name, prereqs, opts, definition); + }; + + this.testTask = function () { + let ctor = function () {}; + let t; + ctor.prototype = jake.TestTask.prototype; + t = new ctor(); + jake.TestTask.apply(t, arguments); + return t; + }; + + this.setTaskTimeout = function (t) { + this._taskTimeout = t; + }; + + this.setSeriesAutoPrefix = function (prefix) { + this._seriesAutoPrefix = prefix; + }; + + this.series = function (...args) { + let prereqs = args.map((arg) => { + let name = (this._seriesAutoPrefix || '') + arg.name; + jake.task(name, arg); + return name; + }); + let seriesName = uuid(); + let seriesTask = jake.task(seriesName, prereqs); + seriesTask._internal = true; + let res = function () { + return new Promise((resolve) => { + seriesTask.invoke(); + seriesTask.on('complete', (val) => { + resolve(val); + }); + }); + }; + Object.defineProperty(res, 'name', {value: uuid(), + writable: false}); + return res; + }; + +})(); + +module.exports = api; diff --git a/node_modules/jake/lib/jake.js b/node_modules/jake/lib/jake.js new file mode 100644 index 0000000..b395ab9 --- /dev/null +++ b/node_modules/jake/lib/jake.js @@ -0,0 +1,330 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +if (!global.jake) { + + let EventEmitter = require('events').EventEmitter; + // And so it begins + global.jake = new EventEmitter(); + + let fs = require('fs'); + let pc = require('picocolors'); + let taskNs = require('./task'); + let Task = taskNs.Task; + let FileTask = taskNs.FileTask; + let DirectoryTask = taskNs.DirectoryTask; + let Rule = require('./rule').Rule; + let Namespace = require('./namespace').Namespace; + let RootNamespace = require('./namespace').RootNamespace; + let api = require('./api'); + let utils = require('./utils'); + let Program = require('./program').Program; + let loader = require('./loader')(); + let pkg = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString()); + + const MAX_RULE_RECURSION_LEVEL = 16; + + // Globalize jake and top-level API methods (e.g., `task`, `desc`) + Object.assign(global, api); + + // Copy utils onto base jake + jake.logger = utils.logger; + jake.exec = utils.exec; + + // File utils should be aliased directly on base jake as well + Object.assign(jake, utils.file); + + // Also add top-level API methods to exported object for those who don't want to + // use the globals (`file` here will overwrite the 'file' utils namespace) + Object.assign(jake, api); + + Object.assign(jake, new (function () { + + this._invocationChain = []; + this._taskTimeout = 30000; + + // Public properties + // ================= + this.version = pkg.version; + // Used when Jake exits with a specific error-code + this.errorCode = null; + // Loads Jakefiles/jakelibdirs + this.loader = loader; + // The root of all ... namespaces + this.rootNamespace = new RootNamespace(); + // Non-namespaced tasks are placed into the default + this.defaultNamespace = this.rootNamespace; + // Start in the default + this.currentNamespace = this.defaultNamespace; + // Saves the description created by a 'desc' call that prefaces a + // 'task' call that defines a task. + this.currentTaskDescription = null; + this.program = new Program(); + this.FileList = require('filelist').FileList; + this.PackageTask = require('./package_task').PackageTask; + this.PublishTask = require('./publish_task').PublishTask; + this.TestTask = require('./test_task').TestTask; + this.Task = Task; + this.FileTask = FileTask; + this.DirectoryTask = DirectoryTask; + this.Namespace = Namespace; + this.Rule = Rule; + + this.parseAllTasks = function () { + let _parseNs = function (ns) { + let nsTasks = ns.tasks; + let nsNamespaces = ns.childNamespaces; + for (let q in nsTasks) { + let nsTask = nsTasks[q]; + jake.Task[nsTask.fullName] = nsTask; + } + for (let p in nsNamespaces) { + let nsNamespace = nsNamespaces[p]; + _parseNs(nsNamespace); + } + }; + _parseNs(jake.defaultNamespace); + }; + + /** + * Displays the list of descriptions available for tasks defined in + * a Jakefile + */ + this.showAllTaskDescriptions = function (f) { + let p; + let maxTaskNameLength = 0; + let task; + let padding; + let name; + let descr; + let filter = typeof f == 'string' ? f : null; + let taskParams; + let len; + + for (p in jake.Task) { + if (!Object.prototype.hasOwnProperty.call(jake.Task, p)) { + continue; + } + if (filter && p.indexOf(filter) == -1) { + continue; + } + task = jake.Task[p]; + taskParams = task.params; + + // Record the length of the longest task name -- used for + // pretty alignment of the task descriptions + if (task.description) { + len = p.length + taskParams.length; + maxTaskNameLength = len > maxTaskNameLength ? + len : maxTaskNameLength; + } + } + + // Print out each entry with descriptions neatly aligned + for (p in jake.Task) { + if (!Object.prototype.hasOwnProperty.call(jake.Task, p)) { + continue; + } + if (filter && p.indexOf(filter) == -1) { + continue; + } + task = jake.Task[p]; + + taskParams = ""; + if (task.params != "") { + taskParams = "[" + task.params + "]"; + } + + //name = '\033[32m' + p + '\033[39m '; + name = pc.green(p); + + descr = task.description; + if (descr) { + descr = pc.gray('# ' + descr); + + // Create padding-string with calculated length + padding = ' '.repeat(maxTaskNameLength - p.length - taskParams.length + 4); + + console.log('jake ' + name + taskParams + padding + descr); + } + } + }; + + this.createTask = function () { + let args = Array.prototype.slice.call(arguments); + let arg; + let obj; + let task; + let type; + let name; + let action; + let opts = {}; + let prereqs = []; + + type = args.shift(); + + // name, [deps], [action] + // Name (string) + deps (array) format + if (typeof args[0] == 'string') { + name = args.shift(); + if (Array.isArray(args[0])) { + prereqs = args.shift(); + } + } + // name:deps, [action] + // Legacy object-literal syntax, e.g.: {'name': ['depA', 'depB']} + else { + obj = args.shift(); + for (let p in obj) { + prereqs = prereqs.concat(obj[p]); + name = p; + } + } + + // Optional opts/callback or callback/opts + while ((arg = args.shift())) { + if (typeof arg == 'function') { + action = arg; + } + else { + opts = Object.assign(Object.create(null), arg); + } + } + + task = jake.currentNamespace.resolveTask(name); + if (task && !action) { + // Task already exists and no action, just update prereqs, and return it. + task.prereqs = task.prereqs.concat(prereqs); + return task; + } + + switch (type) { + case 'directory': + action = function action() { + jake.mkdirP(name); + }; + task = new DirectoryTask(name, prereqs, action, opts); + break; + case 'file': + task = new FileTask(name, prereqs, action, opts); + break; + default: + task = new Task(name, prereqs, action, opts); + } + + jake.currentNamespace.addTask(task); + + if (jake.currentTaskDescription) { + task.description = jake.currentTaskDescription; + jake.currentTaskDescription = null; + } + + // FIXME: Should only need to add a new entry for the current + // task-definition, not reparse the entire structure + jake.parseAllTasks(); + + return task; + }; + + this.attemptRule = function (name, ns, level) { + let prereqRule; + let prereq; + if (level > MAX_RULE_RECURSION_LEVEL) { + return null; + } + // Check Rule + prereqRule = ns.matchRule(name); + if (prereqRule) { + prereq = prereqRule.createTask(name, level); + } + return prereq || null; + }; + + this.createPlaceholderFileTask = function (name, namespace) { + let parsed = name.split(':'); + let filePath = parsed.pop(); // Strip any namespace + let task; + + task = namespace.resolveTask(name); + + // If there's not already an existing dummy FileTask for it, + // create one + if (!task) { + // Create a dummy FileTask only if file actually exists + if (fs.existsSync(filePath)) { + task = new jake.FileTask(filePath); + task.dummy = true; + let ns; + if (parsed.length) { + ns = namespace.resolveNamespace(parsed.join(':')); + } + else { + ns = namespace; + } + if (!namespace) { + throw new Error('Invalid namespace, cannot add FileTask'); + } + ns.addTask(task); + // Put this dummy Task in the global Tasks list so + // modTime will be eval'd correctly + jake.Task[`${ns.path}:${filePath}`] = task; + } + } + + return task || null; + }; + + + this.run = function () { + let args = Array.prototype.slice.call(arguments); + let program = this.program; + let loader = this.loader; + let preempt; + let opts; + + program.parseArgs(args); + program.init(); + + preempt = program.firstPreemptiveOption(); + if (preempt) { + preempt(); + } + else { + opts = program.opts; + // jakefile flag set but no jakefile yet + if (opts.autocomplete && opts.jakefile === true) { + process.stdout.write('no-complete'); + return; + } + // Load Jakefile and jakelibdir files + let jakefileLoaded = loader.loadFile(opts.jakefile); + let jakelibdirLoaded = loader.loadDirectory(opts.jakelibdir); + + if(!jakefileLoaded && !jakelibdirLoaded && !opts.autocomplete) { + fail('No Jakefile. Specify a valid path with -f/--jakefile, ' + + 'or place one in the current directory.'); + } + + program.run(); + } + }; + + })()); +} + +module.exports = jake; diff --git a/node_modules/jake/lib/loader.js b/node_modules/jake/lib/loader.js new file mode 100644 index 0000000..28e0a3d --- /dev/null +++ b/node_modules/jake/lib/loader.js @@ -0,0 +1,174 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +let path = require('path'); +let fs = require('fs'); +let existsSync = fs.existsSync; +let utils = require('./utils'); + +// Files like jakelib/foobar.jake.js +const JAKELIB_FILE_PAT = /\.jake$|\.js$/; +const SUPPORTED_EXTENSIONS = { + 'js': null, + 'cjs': null, + 'coffee': function () { + try { + let cs = require('coffeescript'); + if (typeof cs.register == 'function') { + cs.register(); + } + } + catch(e) { + throw new Error('You have a CoffeeScript Jakefile, but have not installed CoffeeScript'); + } + }, + 'ls': function () { + try { + require('livescript'); + } + catch (e) { + throw new Error('You have a LiveScript Jakefile, but have not installed LiveScript'); + } + }, + 'ts': function () { + try { + require('ts-node/register/transpile-only'); + } + catch (e) { + throw new Error('You have a TypeScript Jakefile, but have not installed TypeScript and ts-node'); + } + } +}; +const IMPLICIT_JAKEFILE_NAMES = [ + 'Jakefile', + 'Gulpfile' +]; + +let Loader = function () { + // Load a Jakefile, running the code inside -- this may result in + // tasks getting defined using the original Jake API, e.g., + // `task('foo' ['bar', 'baz']);`, or can also auto-create tasks + // from any functions exported from the file + function loadFile(filePath) { + let exported = require(filePath); + for (let [key, value] of Object.entries(exported)) { + let t; + if (typeof value == 'function') { + t = jake.task(key, value); + t.description = '(Exported function)'; + } + } + } + + function fileExists(name) { + let nameWithExt = null; + // Support no file extension as well + let exts = Object.keys(SUPPORTED_EXTENSIONS).concat(['']); + exts.some((ext) => { + let fname = ext ? `${name}.${ext}` : name; + if (existsSync(fname)) { + nameWithExt = fname; + return true; + } + }); + return nameWithExt; + } + + // Recursive + function findImplicitJakefile() { + let cwd = process.cwd(); + let names = IMPLICIT_JAKEFILE_NAMES; + let found = null; + names.some((name) => { + let n; + // Prefer all-lowercase + n = name.toLowerCase(); + if ((found = fileExists(n))) { + return found; + } + // Check mixed-case as well + n = name; + if ((found = fileExists(n))) { + return found; + } + }); + if (found) { + return found; + } + else { + process.chdir(".."); + // If we've walked all the way up the directory tree, + // bail out with no result + if (cwd === process.cwd()) { + return null; + } + return findImplicitJakefile(); + } + } + + this.loadFile = function (fileSpecified) { + let jakefile; + let origCwd = process.cwd(); + + if (fileSpecified) { + if (existsSync(fileSpecified)) { + jakefile = fileSpecified; + } + } + else { + jakefile = findImplicitJakefile(); + } + + if (jakefile) { + let ext = jakefile.split('.')[1]; + let loaderFunc = SUPPORTED_EXTENSIONS[ext]; + loaderFunc && loaderFunc(); + + loadFile(utils.file.absolutize(jakefile)); + return true; + } + else { + if (!fileSpecified) { + // Restore the working directory on failure + process.chdir(origCwd); + } + return false; + } + }; + + this.loadDirectory = function (d) { + let dirname = d || 'jakelib'; + let dirlist; + dirname = utils.file.absolutize(dirname); + if (existsSync(dirname)) { + dirlist = fs.readdirSync(dirname); + dirlist.forEach(function (filePath) { + if (JAKELIB_FILE_PAT.test(filePath)) { + loadFile(path.join(dirname, filePath)); + } + }); + return true; + } + return false; + }; + +}; + +module.exports = function () { + return new Loader(); +}; diff --git a/node_modules/jake/lib/namespace.js b/node_modules/jake/lib/namespace.js new file mode 100644 index 0000000..a3c2787 --- /dev/null +++ b/node_modules/jake/lib/namespace.js @@ -0,0 +1,115 @@ +const ROOT_NAMESPACE_NAME = '__rootNamespace__'; + +class Namespace { + constructor(name, parentNamespace) { + this.name = name; + this.parentNamespace = parentNamespace; + this.childNamespaces = {}; + this.tasks = {}; + this.rules = {}; + this.path = this.getPath(); + } + + get fullName() { + return this._getFullName(); + } + + addTask(task) { + this.tasks[task.name] = task; + task.namespace = this; + } + + resolveTask(name) { + if (!name) { + return; + } + + let taskPath = name.split(':'); + let taskName = taskPath.pop(); + let task; + let ns; + + // Namespaced, return either relative to current, or from root + if (taskPath.length) { + taskPath = taskPath.join(':'); + ns = this.resolveNamespace(taskPath) || + Namespace.ROOT_NAMESPACE.resolveNamespace(taskPath); + task = (ns && ns.resolveTask(taskName)); + } + // Bare task, return either local, or top-level + else { + task = this.tasks[name] || Namespace.ROOT_NAMESPACE.tasks[name]; + } + + return task || null; + } + + + resolveNamespace(relativeName) { + if (!relativeName) { + return this; + } + + let parts = relativeName.split(':'); + let ns = this; + + for (let i = 0, ii = parts.length; (ns && i < ii); i++) { + ns = ns.childNamespaces[parts[i]]; + } + + return ns || null; + } + + matchRule(relativeName) { + let parts = relativeName.split(':'); + parts.pop(); + let ns = this.resolveNamespace(parts.join(':')); + let rules = ns ? ns.rules : []; + let r; + let match; + + for (let p in rules) { + r = rules[p]; + if (r.match(relativeName)) { + match = r; + } + } + + return (ns && match) || + (this.parentNamespace && + this.parentNamespace.matchRule(relativeName)); + } + + getPath() { + let parts = []; + let next = this.parentNamespace; + while (next) { + parts.push(next.name); + next = next.parentNamespace; + } + parts.pop(); // Remove '__rootNamespace__' + return parts.reverse().join(':'); + } + + _getFullName() { + let path = this.path; + path = (path && path.split(':')) || []; + path.push(this.name); + return path.join(':'); + } + + isRootNamespace() { + return !this.parentNamespace; + } +} + +class RootNamespace extends Namespace { + constructor() { + super(ROOT_NAMESPACE_NAME, null); + Namespace.ROOT_NAMESPACE = this; + } +} + +module.exports.Namespace = Namespace; +module.exports.RootNamespace = RootNamespace; + diff --git a/node_modules/jake/lib/package_task.js b/node_modules/jake/lib/package_task.js new file mode 100644 index 0000000..527aca7 --- /dev/null +++ b/node_modules/jake/lib/package_task.js @@ -0,0 +1,406 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +let path = require('path'); +let fs = require('fs'); +let exec = require('child_process').exec; +let FileList = require('filelist').FileList; + +/** + @name jake + @namespace jake +*/ +/** + @name jake.PackageTask + @constructor + @description Instantiating a PackageTask creates a number of Jake + Tasks that make packaging and distributing your software easy. + + @param {String} name The name of the project + @param {String} version The current project version (will be + appended to the project-name in the package-archive + @param {Function} definition Defines the contents of the package, + and format of the package-archive. Will be executed on the instantiated + PackageTask (i.e., 'this', will be the PackageTask instance), + to set the various instance-propertiess. + + @example + let t = new jake.PackageTask('rous', 'v' + version, function () { + let files = [ + 'Capfile' + , 'Jakefile' + , 'README.md' + , 'package.json' + , 'app/*' + , 'bin/*' + , 'config/*' + , 'lib/*' + , 'node_modules/*' + ]; + this.packageFiles.include(files); + this.packageFiles.exclude('node_modules/foobar'); + this.needTarGz = true; + }); + + */ +let PackageTask = function () { + let args = Array.prototype.slice.call(arguments); + let name = args.shift(); + let version = args.shift(); + let definition = args.pop(); + let prereqs = args.pop() || []; // Optional + + prereqs = [].concat(prereqs); // Accept string or list + + /** + @name jake.PackageTask#name + @public + @type {String} + @description The name of the project + */ + this.name = name; + /** + @name jake.PackageTask#version + @public + @type {String} + @description The project version-string + */ + this.version = version; + /** + @name jake.PackageTask#prereqs + @public + @type {Array} + @description Tasks to run before packaging + */ + this.prereqs = prereqs; + /** + @name jake.PackageTask#packageDir + @public + @type {String='pkg'} + @description The directory-name to use for packaging the software + */ + this.packageDir = 'pkg'; + /** + @name jake.PackageTask#packageFiles + @public + @type {jake.FileList} + @description The list of files and directories to include in the + package-archive + */ + this.packageFiles = new FileList(); + /** + @name jake.PackageTask#needTar + @public + @type {Boolean=false} + @description If set to true, uses the `tar` utility to create + a gzip .tgz archive of the package + */ + this.needTar = false; + /** + @name jake.PackageTask#needTarGz + @public + @type {Boolean=false} + @description If set to true, uses the `tar` utility to create + a gzip .tar.gz archive of the package + */ + this.needTarGz = false; + /** + @name jake.PackageTask#needTarBz2 + @public + @type {Boolean=false} + @description If set to true, uses the `tar` utility to create + a bzip2 .bz2 archive of the package + */ + this.needTarBz2 = false; + /** + @name jake.PackageTask#needJar + @public + @type {Boolean=false} + @description If set to true, uses the `jar` utility to create + a .jar archive of the package + */ + this.needJar = false; + /** + @name jake.PackageTask#needZip + @public + @type {Boolean=false} + @description If set to true, uses the `zip` utility to create + a .zip archive of the package + */ + this.needZip = false; + /** + @name jake.PackageTask#manifestFile + @public + @type {String=null} + @description Can be set to point the `jar` utility at a manifest + file to use in a .jar archive. If unset, one will be automatically + created by the `jar` utility. This path should be relative to the + root of the package directory (this.packageDir above, likely 'pkg') + */ + this.manifestFile = null; + /** + @name jake.PackageTask#tarCommand + @public + @type {String='tar'} + @description The shell-command to use for creating tar archives. + */ + this.tarCommand = 'tar'; + /** + @name jake.PackageTask#jarCommand + @public + @type {String='jar'} + @description The shell-command to use for creating jar archives. + */ + this.jarCommand = 'jar'; + /** + @name jake.PackageTask#zipCommand + @public + @type {String='zip'} + @description The shell-command to use for creating zip archives. + */ + this.zipCommand = 'zip'; + /** + @name jake.PackageTask#archiveNoBaseDir + @public + @type {Boolean=false} + @description Simple option for performing the archive on the + contents of the directory instead of the directory itself + */ + this.archiveNoBaseDir = false; + /** + @name jake.PackageTask#archiveChangeDir + @public + @type {String=null} + @description Equivalent to the '-C' command for the `tar` and `jar` + commands. ("Change to this directory before adding files.") + */ + this.archiveChangeDir = null; + /** + @name jake.PackageTask#archiveContentDir + @public + @type {String=null} + @description Specifies the files and directories to include in the + package-archive. If unset, this will default to the main package + directory -- i.e., name + version. + */ + this.archiveContentDir = null; + + if (typeof definition == 'function') { + definition.call(this); + } + this.define(); +}; + +PackageTask.prototype = new (function () { + + let _compressOpts = { + Tar: { + ext: '.tgz', + flags: 'czf', + cmd: 'tar' + }, + TarGz: { + ext: '.tar.gz', + flags: 'czf', + cmd: 'tar' + }, + TarBz2: { + ext: '.tar.bz2', + flags: 'cjf', + cmd: 'tar' + }, + Jar: { + ext: '.jar', + flags: 'cf', + cmd: 'jar' + }, + Zip: { + ext: '.zip', + flags: 'qr', + cmd: 'zip' + } + }; + + this.define = function () { + let self = this; + let packageDirPath = this.packageDirPath(); + let compressTaskArr = []; + + desc('Build the package for distribution'); + task('package', self.prereqs.concat(['clobberPackage', 'buildPackage'])); + // Backward-compat alias + task('repackage', ['package']); + + task('clobberPackage', function () { + jake.rmRf(self.packageDir, {silent: true}); + }); + + desc('Remove the package'); + task('clobber', ['clobberPackage']); + + let doCommand = function (p) { + let filename = path.resolve(self.packageDir + '/' + self.packageName() + + _compressOpts[p].ext); + if (process.platform == 'win32') { + // Windows full path may have drive letter, which is going to cause + // namespace problems, so strip it. + if (filename.length > 2 && filename[1] == ':') { + filename = filename.substr(2); + } + } + compressTaskArr.push(filename); + + file(filename, [packageDirPath], function () { + let cmd; + let opts = _compressOpts[p]; + // Directory to move to when doing the compression-task + // Changes in the case of zip for emulating -C option + let chdir = self.packageDir; + // Save the current dir so it's possible to pop back up + // after compressing + let currDir = process.cwd(); + let archiveChangeDir; + let archiveContentDir; + + if (self.archiveNoBaseDir) { + archiveChangeDir = self.packageName(); + archiveContentDir = '.'; + } + else { + archiveChangeDir = self.archiveChangeDir; + archiveContentDir = self.archiveContentDir; + } + + cmd = self[opts.cmd + 'Command']; + cmd += ' -' + opts.flags; + if (opts.cmd == 'jar' && self.manifestFile) { + cmd += 'm'; + } + + // The name of the archive to create -- use full path + // so compression can be performed from a different dir + // if needed + cmd += ' ' + filename; + + if (opts.cmd == 'jar' && self.manifestFile) { + cmd += ' ' + self.manifestFile; + } + + // Where to perform the compression -- -C option isn't + // supported in zip, so actually do process.chdir for this + if (archiveChangeDir) { + if (opts.cmd == 'zip') { + chdir = path.join(chdir, archiveChangeDir); + } + else { + cmd += ' -C ' + archiveChangeDir; + } + } + + // Where to get the archive content + if (archiveContentDir) { + cmd += ' ' + archiveContentDir; + } + else { + cmd += ' ' + self.packageName(); + } + + // Move into the desired dir (usually packageDir) to compress + // Return back up to the current dir after the exec + process.chdir(chdir); + + exec(cmd, function (err, stdout, stderr) { + if (err) { throw err; } + + // Return back up to the starting directory (see above, + // before exec) + process.chdir(currDir); + + complete(); + }); + }, {async: true}); + }; + + for (let p in _compressOpts) { + if (this['need' + p]) { + doCommand(p); + } + } + + task('buildPackage', compressTaskArr, function () {}); + + directory(this.packageDir); + + file(packageDirPath, this.packageFiles, function () { + jake.mkdirP(packageDirPath); + let fileList = []; + self.packageFiles.forEach(function (name) { + let f = path.join(self.packageDirPath(), name); + let fDir = path.dirname(f); + jake.mkdirP(fDir, {silent: true}); + + // Add both files and directories + fileList.push({ + from: name, + to: f + }); + }); + let _copyFile = function () { + let file = fileList.pop(); + let stat; + if (file) { + stat = fs.statSync(file.from); + // Target is a directory, just create it + if (stat.isDirectory()) { + jake.mkdirP(file.to, {silent: true}); + _copyFile(); + } + // Otherwise copy the file + else { + jake.cpR(file.from, file.to, {silent: true}); + _copyFile(); + } + } + else { + complete(); + } + }; + _copyFile(); + }, {async: true}); + + + }; + + this.packageName = function () { + if (this.version) { + return this.name + '-' + this.version; + } + else { + return this.name; + } + }; + + this.packageDirPath = function () { + return this.packageDir + '/' + this.packageName(); + }; + +})(); + +jake.PackageTask = PackageTask; +exports.PackageTask = PackageTask; + diff --git a/node_modules/jake/lib/parseargs.js b/node_modules/jake/lib/parseargs.js new file mode 100644 index 0000000..1a00733 --- /dev/null +++ b/node_modules/jake/lib/parseargs.js @@ -0,0 +1,134 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +let parseargs = {}; +let isOpt = function (arg) { return arg.indexOf('-') === 0; }; +let removeOptPrefix = function (opt) { return opt.replace(/^--/, '').replace(/^-/, ''); }; + +/** + * @constructor + * Parses a list of command-line args into a key/value object of + * options and an array of positional commands. + * @ param {Array} opts A list of options in the following format: + * [{full: 'foo', abbr: 'f'}, {full: 'bar', abbr: 'b'}]] + */ +parseargs.Parser = function (opts) { + // A key/value object of matching options parsed out of the args + this.opts = {}; + this.taskNames = null; + this.envVars = null; + + // Data structures used for parsing + this.reg = opts; + this.shortOpts = {}; + this.longOpts = {}; + + let self = this; + [].forEach.call(opts, function (item) { + self.shortOpts[item.abbr] = item; + self.longOpts[item.full] = item; + }); +}; + +parseargs.Parser.prototype = new function () { + + let _trueOrNextVal = function (argParts, args) { + if (argParts[1]) { + return argParts[1]; + } + else { + return (!args[0] || isOpt(args[0])) ? + true : args.shift(); + } + }; + + /** + * Parses an array of arguments into options and positional commands + * @param {Array} args The command-line args to parse + */ + this.parse = function (args) { + let cmds = []; + let cmd; + let envVars = {}; + let opts = {}; + let arg; + let argItem; + let argParts; + let cmdItems; + let taskNames = []; + let preempt; + + while (args.length) { + arg = args.shift(); + + if (isOpt(arg)) { + arg = removeOptPrefix(arg); + argParts = arg.split('='); + argItem = this.longOpts[argParts[0]] || this.shortOpts[argParts[0]]; + if (argItem) { + // First-encountered preemptive opt takes precedence -- no further opts + // or possibility of ambiguity, so just look for a value, or set to + // true and then bail + if (argItem.preempts) { + opts[argItem.full] = _trueOrNextVal(argParts, args); + preempt = true; + break; + } + // If the opt requires a value, see if we can get a value from the + // next arg, or infer true from no-arg -- if it's followed by another + // opt, throw an error + if (argItem.expectValue || argItem.allowValue) { + opts[argItem.full] = _trueOrNextVal(argParts, args); + if (argItem.expectValue && !opts[argItem.full]) { + throw new Error(argItem.full + ' option expects a value.'); + } + } + else { + opts[argItem.full] = true; + } + } + } + else { + cmds.unshift(arg); + } + } + + if (!preempt) { + // Parse out any env-vars and task-name + while ((cmd = cmds.pop())) { + cmdItems = cmd.split('='); + if (cmdItems.length > 1) { + envVars[cmdItems[0]] = cmdItems[1]; + } + else { + taskNames.push(cmd); + } + } + + } + + return { + opts: opts, + envVars: envVars, + taskNames: taskNames + }; + }; + +}; + +module.exports = parseargs; diff --git a/node_modules/jake/lib/program.js b/node_modules/jake/lib/program.js new file mode 100644 index 0000000..121632f --- /dev/null +++ b/node_modules/jake/lib/program.js @@ -0,0 +1,282 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +let fs = require('fs'); +let parseargs = require('./parseargs'); +let utils = require('./utils'); +let Program; +let usage = require('fs').readFileSync(`${__dirname}/../usage.txt`).toString(); +let { Task } = require('./task/task'); + +function die(msg) { + console.log(msg); + process.stdout.write('', function () { + process.stderr.write('', function () { + process.exit(); + }); + }); +} + +let preempts = { + version: function () { + die(jake.version); + }, + help: function () { + die(usage); + } +}; + +let AVAILABLE_OPTS = [ + { full: 'jakefile', + abbr: 'f', + expectValue: true + }, + { full: 'quiet', + abbr: 'q', + expectValue: false + }, + { full: 'directory', + abbr: 'C', + expectValue: true + }, + { full: 'always-make', + abbr: 'B', + expectValue: false + }, + { full: 'tasks', + abbr: 'T', + expectValue: false, + allowValue: true + }, + // Alias t + { full: 'tasks', + abbr: 't', + expectValue: false, + allowValue: true + }, + // Alias ls + { full: 'tasks', + abbr: 'ls', + expectValue: false, + allowValue: true + }, + { full: 'help', + abbr: 'h', + }, + { full: 'version', + abbr: 'V', + }, + // Alias lowercase v + { full: 'version', + abbr: 'v', + }, + { full: 'jakelibdir', + abbr: 'J', + expectValue: true + }, + { full: 'allow-rejection', + abbr: 'ar', + expectValue: false + } +]; + +Program = function () { + this.availableOpts = AVAILABLE_OPTS; + this.opts = {}; + this.taskNames = null; + this.taskArgs = null; + this.envVars = null; + this.die = die; +}; + +Program.prototype = new (function () { + + this.handleErr = function (err) { + if (jake.listeners('error').length !== 0) { + jake.emit('error', err); + return; + } + + if (jake.listeners('error').length) { + jake.emit('error', err); + return; + } + + utils.logger.error('jake aborted.'); + if (err.stack) { + utils.logger.error(err.stack); + } + else { + utils.logger.error(err.message); + } + + process.stdout.write('', function () { + process.stderr.write('', function () { + jake.errorCode = jake.errorCode || 1; + process.exit(jake.errorCode); + }); + }); + }; + + this.parseArgs = function (args) { + let result = (new parseargs.Parser(this.availableOpts)).parse(args); + this.setOpts(result.opts); + this.setTaskNames(result.taskNames); + this.setEnvVars(result.envVars); + }; + + this.setOpts = function (options) { + let opts = options || {}; + Object.assign(this.opts, opts); + }; + + this.internalOpts = function (options) { + this.availableOpts = this.availableOpts.concat(options); + }; + + this.autocompletions = function (cur) { + let p; let i; let task; + let commonPrefix = ''; + let matches = []; + + for (p in jake.Task) { + task = jake.Task[p]; + if ( + 'fullName' in task + && ( + // if empty string, program converts to true + cur === true || + task.fullName.indexOf(cur) === 0 + ) + ) { + if (matches.length === 0) { + commonPrefix = task.fullName; + } + else { + for (i = commonPrefix.length; i > -1; --i) { + commonPrefix = commonPrefix.substr(0, i); + if (task.fullName.indexOf(commonPrefix) === 0) { + break; + } + } + } + matches.push(task.fullName); + } + } + + if (matches.length > 1 && commonPrefix === cur) { + matches.unshift('yes-space'); + } + else { + matches.unshift('no-space'); + } + + process.stdout.write(matches.join(' ')); + }; + + this.setTaskNames = function (names) { + if (names && !Array.isArray(names)) { + throw new Error('Task names must be an array'); + } + this.taskNames = (names && names.length) ? names : ['default']; + }; + + this.setEnvVars = function (vars) { + this.envVars = vars || null; + }; + + this.firstPreemptiveOption = function () { + let opts = this.opts; + for (let p in opts) { + if (preempts[p]) { + return preempts[p]; + } + } + return false; + }; + + this.init = function (configuration) { + let self = this; + let config = configuration || {}; + if (config.options) { + this.setOpts(config.options); + } + if (config.taskNames) { + this.setTaskNames(config.taskNames); + } + if (config.envVars) { + this.setEnvVars(config.envVars); + } + process.addListener('uncaughtException', function (err) { + self.handleErr(err); + }); + if (!this.opts['allow-rejection']) { + process.addListener('unhandledRejection', (reason, promise) => { + utils.logger.error('Unhandled rejection at:', promise, 'reason:', reason); + self.handleErr(reason); + }); + } + if (this.envVars) { + Object.assign(process.env, this.envVars); + } + }; + + this.run = function () { + let rootTask; + let taskNames; + let dirname; + let opts = this.opts; + + if (opts.autocomplete) { + return this.autocompletions(opts['autocomplete-cur'], opts['autocomplete-prev']); + } + // Run with `jake -T`, just show descriptions + if (opts.tasks) { + return jake.showAllTaskDescriptions(opts.tasks); + } + + taskNames = this.taskNames; + if (!(Array.isArray(taskNames) && taskNames.length)) { + throw new Error('Please pass jake.runTasks an array of task-names'); + } + + // Set working dir + dirname = opts.directory; + if (dirname) { + if (fs.existsSync(dirname) && + fs.statSync(dirname).isDirectory()) { + process.chdir(dirname); + } + else { + throw new Error(dirname + ' is not a valid directory path'); + } + } + + rootTask = task(Task.ROOT_TASK_NAME, taskNames, function () {}); + rootTask._internal = true; + + rootTask.once('complete', function () { + jake.emit('complete'); + }); + jake.emit('start'); + rootTask.invoke(); + }; + +})(); + +module.exports.Program = Program; diff --git a/node_modules/jake/lib/publish_task.js b/node_modules/jake/lib/publish_task.js new file mode 100644 index 0000000..9aa8985 --- /dev/null +++ b/node_modules/jake/lib/publish_task.js @@ -0,0 +1,290 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +let fs = require('fs'); +let path = require('path'); +let exec = require('child_process').execSync; +let FileList = require('filelist').FileList; + +let PublishTask = function () { + let args = Array.prototype.slice.call(arguments).filter(function (item) { + return typeof item != 'undefined'; + }); + let arg; + let opts = {}; + let definition; + let prereqs = []; + let createDef = function (arg) { + return function () { + this.packageFiles.include(arg); + }; + }; + + this.name = args.shift(); + + // Old API, just name + list of files + if (args.length == 1 && (Array.isArray(args[0]) || typeof args[0] == 'string')) { + definition = createDef(args.pop()); + } + // Current API, name + [prereqs] + [opts] + definition + else { + while ((arg = args.pop())) { + // Definition func + if (typeof arg == 'function') { + definition = arg; + } + // Prereqs + else if (Array.isArray(arg) || typeof arg == 'string') { + prereqs = arg; + } + // Opts + else { + opts = arg; + } + } + } + + this.prereqs = prereqs; + this.packageFiles = new FileList(); + this.publishCmd = opts.publishCmd || 'npm publish %filename'; + this.publishMessage = opts.publishMessage || 'BOOM! Published.'; + this.gitCmd = opts.gitCmd || 'git'; + this.versionFiles = opts.versionFiles || ['package.json']; + this.scheduleDelay = 5000; + + // Override utility funcs for testing + this._ensureRepoClean = function (stdout) { + if (stdout.length) { + fail(new Error('Git repository is not clean.')); + } + }; + this._getCurrentBranch = function (stdout) { + return String(stdout).trim(); + }; + + if (typeof definition == 'function') { + definition.call(this); + } + this.define(); +}; + + +PublishTask.prototype = new (function () { + + let _currentBranch = null; + + let getPackage = function () { + let pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(), + '/package.json')).toString()); + return pkg; + }; + let getPackageVersionNumber = function () { + return getPackage().version; + }; + + this.define = function () { + let self = this; + + namespace('publish', function () { + task('fetchTags', function () { + // Make sure local tags are up to date + exec(self.gitCmd + ' fetch --tags'); + console.log('Fetched remote tags.'); + }); + + task('getCurrentBranch', function () { + // Figure out what branch to push to + let stdout = exec(self.gitCmd + ' symbolic-ref --short HEAD').toString(); + if (!stdout) { + throw new Error('No current Git branch found'); + } + _currentBranch = self._getCurrentBranch(stdout); + console.log('On branch ' + _currentBranch); + }); + + task('ensureClean', function () { + // Only bump, push, and tag if the Git repo is clean + let stdout = exec(self.gitCmd + ' status --porcelain --untracked-files=no').toString(); + // Throw if there's output + self._ensureRepoClean(stdout); + }); + + task('updateVersionFiles', function () { + let pkg; + let version; + let arr; + let patch; + + // Grab the current version-string + pkg = getPackage(); + version = pkg.version; + // Increment the patch-number for the version + arr = version.split('.'); + patch = parseInt(arr.pop(), 10) + 1; + arr.push(patch); + version = arr.join('.'); + + // Update package.json or other files with the new version-info + self.versionFiles.forEach(function (file) { + let p = path.join(process.cwd(), file); + let data = JSON.parse(fs.readFileSync(p).toString()); + data.version = version; + fs.writeFileSync(p, JSON.stringify(data, true, 2) + '\n'); + }); + // Return the version string so that listeners for the 'complete' event + // for this task can use it (e.g., to update other files before pushing + // to Git) + return version; + }); + + task('pushVersion', ['ensureClean', 'updateVersionFiles'], function () { + let version = getPackageVersionNumber(); + let message = 'Version ' + version; + let cmds = [ + self.gitCmd + ' commit -a -m "' + message + '"', + self.gitCmd + ' push origin ' + _currentBranch, + self.gitCmd + ' tag -a v' + version + ' -m "' + message + '"', + self.gitCmd + ' push --tags' + ]; + cmds.forEach((cmd) => { + exec(cmd); + }); + version = getPackageVersionNumber(); + console.log('Bumped version number to v' + version + '.'); + }); + + let defineTask = task('definePackage', function () { + let version = getPackageVersionNumber(); + new jake.PackageTask(self.name, 'v' + version, self.prereqs, function () { + // Replace the PackageTask's FileList with the PublishTask's FileList + this.packageFiles = self.packageFiles; + this.needTarGz = true; // Default to tar.gz + // If any of the need or archive opts are set + // proxy them to the PackageTask + for (let p in this) { + if (p.indexOf('need') === 0 || p.indexOf('archive') === 0) { + if (typeof self[p] != 'undefined') { + this[p] = self[p]; + } + } + } + }); + }); + defineTask._internal = true; + + task('package', function () { + let definePack = jake.Task['publish:definePackage']; + let pack = jake.Task['package']; + let version = getPackageVersionNumber(); + + // May have already been run + if (definePack.taskStatus == jake.Task.runStatuses.DONE) { + definePack.reenable(true); + } + definePack.execute(); + definePack.on('complete', function () { + pack.invoke(); + console.log('Created package for ' + self.name + ' v' + version); + }); + }); + + task('publish', function () { + return new Promise((resolve) => { + let version = getPackageVersionNumber(); + let filename; + let cmd; + + console.log('Publishing ' + self.name + ' v' + version); + + if (typeof self.createPublishCommand == 'function') { + cmd = self.createPublishCommand(version); + } + else { + filename = './pkg/' + self.name + '-v' + version + '.tar.gz'; + cmd = self.publishCmd.replace(/%filename/gi, filename); + } + + if (typeof cmd == 'function') { + cmd(function (err) { + if (err) { + throw err; + } + console.log(self.publishMessage); + resolve(); + }); + } + else { + // Hackity hack -- NPM publish sometimes returns errror like: + // Error sending version data\nnpm ERR! + // Error: forbidden 0.2.4 is modified, should match modified time + setTimeout(function () { + let stdout = exec(cmd).toString() || ''; + stdout = stdout.trim(); + if (stdout) { + console.log(stdout); + } + console.log(self.publishMessage); + resolve(); + }, self.scheduleDelay); + } + }); + }); + + task('cleanup', function () { + return new Promise((resolve) => { + let clobber = jake.Task.clobber; + clobber.reenable(true); + clobber.on('complete', function () { + console.log('Cleaned up package'); + resolve(); + }); + clobber.invoke(); + }); + }); + + }); + + let prefixNs = function (item) { + return 'publish:' + item; + }; + + // Create aliases in the default namespace + desc('Create a new version and release.'); + task('publish', self.prereqs.concat(['version', 'release'] + .map(prefixNs))); + + desc('Release the existing version.'); + task('publishExisting', self.prereqs.concat(['release'] + .map(prefixNs))); + + task('version', ['fetchTags', 'getCurrentBranch', 'pushVersion'] + .map(prefixNs)); + + task('release', ['package', 'publish', 'cleanup'] + .map(prefixNs)); + + // Invoke proactively so there will be a callable 'package' task + // which can be used apart from 'publish' + jake.Task['publish:definePackage'].invoke(); + }; + +})(); + +jake.PublishTask = PublishTask; +exports.PublishTask = PublishTask; + diff --git a/node_modules/jake/lib/rule.js b/node_modules/jake/lib/rule.js new file mode 100644 index 0000000..25f51ae --- /dev/null +++ b/node_modules/jake/lib/rule.js @@ -0,0 +1,311 @@ +let path = require('path'); +let fs = require('fs'); +let Task = require('./task/task').Task; + +// Split a task to two parts, name space and task name. +// For example, given 'foo:bin/a%.c', return an object with +// - 'ns' : foo +// - 'name' : bin/a%.c +function splitNs(task) { + let parts = task.split(':'); + let name = parts.pop(); + let ns = resolveNs(parts); + return { + 'name' : name, + 'ns' : ns + }; +} + +// Return the namespace based on an array of names. +// For example, given ['foo', 'baz' ], return the namespace +// +// default -> foo -> baz +// +// where default is the global root namespace +// and -> means child namespace. +function resolveNs(parts) { + let ns = jake.defaultNamespace; + for(let i = 0, l = parts.length; ns && i < l; i++) { + ns = ns.childNamespaces[parts[i]]; + } + return ns; +} + +// Given a pattern p, say 'foo:bin/a%.c' +// Return an object with +// - 'ns' : foo +// - 'dir' : bin +// - 'prefix' : a +// - 'suffix' : .c +function resolve(p) { + let task = splitNs(p); + let name = task.name; + let ns = task.ns; + let split = path.basename(name).split('%'); + return { + ns: ns, + dir: path.dirname(name), + prefix: split[0], + suffix: split[1] + }; +} + +// Test whether string a is a suffix of string b +function stringEndWith(a, b) { + let l; + return (l = b.lastIndexOf(a)) == -1 ? false : l + a.length == b.length; +} + +// Replace the suffix a of the string s with b. +// Note that, it is assumed a is a suffix of s. +function stringReplaceSuffix(s, a, b) { + return s.slice(0, s.lastIndexOf(a)) + b; +} + +class Rule { + constructor(opts) { + this.pattern = opts.pattern; + this.source = opts.source; + this.prereqs = opts.prereqs; + this.action = opts.action; + this.opts = opts.opts; + this.desc = opts.desc; + this.ns = opts.ns; + } + + // Create a file task based on this rule for the specified + // task-name + // ====== + // FIXME: Right now this just throws away any passed-in args + // for the synthsized task (taskArgs param) + // ====== + createTask(fullName, level) { + let self = this; + let pattern; + let source; + let action; + let opts; + let prereqs; + let valid; + let src; + let tNs; + let createdTask; + let name = Task.getBaseTaskName(fullName); + let nsPath = Task.getBaseNamespacePath(fullName); + let ns = this.ns.resolveNamespace(nsPath); + + pattern = this.pattern; + source = this.source; + + if (typeof source == 'string') { + src = Rule.getSource(name, pattern, source); + } + else { + src = source(name); + } + + // TODO: Write a utility function that appends a + // taskname to a namespace path + src = nsPath.split(':').filter(function (item) { + return !!item; + }).concat(src).join(':'); + + // Generate the prerequisite for the matching task. + // It is the original prerequisites plus the prerequisite + // representing source file, i.e., + // + // rule( '%.o', '%.c', ['some.h'] ... + // + // If the objective is main.o, then new task should be + // + // file( 'main.o', ['main.c', 'some.h' ] ... + prereqs = this.prereqs.slice(); // Get a copy to work with + prereqs.unshift(src); + + // Prereq should be: + // 1. an existing task + // 2. an existing file on disk + // 3. a valid rule (i.e., not at too deep a level) + valid = prereqs.some(function (p) { + let ns = self.ns; + return ns.resolveTask(p) || + fs.existsSync(Task.getBaseTaskName(p)) || + jake.attemptRule(p, ns, level + 1); + }); + + // If any of the prereqs aren't valid, the rule isn't valid + if (!valid) { + return null; + } + // Otherwise, hunky-dory, finish creating the task for the rule + else { + // Create the action for the task + action = function () { + let task = this; + self.action.apply(task); + }; + + opts = this.opts; + + // Insert the file task into Jake + // + // Since createTask function stores the task as a child task + // of currentNamespace. Here we temporariliy switch the namespace. + // FIXME: Should allow optional ns passed in instead of this hack + tNs = jake.currentNamespace; + jake.currentNamespace = ns; + createdTask = jake.createTask('file', name, prereqs, action, opts); + createdTask.source = src.split(':').pop(); + jake.currentNamespace = tNs; + + return createdTask; + } + } + + match(name) { + return Rule.match(this.pattern, name); + } + + // Test wether the a prerequisite matchs the pattern. + // The arg 'pattern' does not have namespace as prefix. + // For example, the following tests are true + // + // pattern | name + // bin/%.o | bin/main.o + // bin/%.o | foo:bin/main.o + // + // The following tests are false (trivally) + // + // pattern | name + // bin/%.o | foobin/main.o + // bin/%.o | bin/main.oo + static match(pattern, name) { + let p; + let task; + let obj; + let filename; + + if (pattern instanceof RegExp) { + return pattern.test(name); + } + else if (pattern.indexOf('%') == -1) { + // No Pattern. No Folder. No Namespace. + // A Simple Suffix Rule. Just test suffix + return stringEndWith(pattern, name); + } + else { + // Resolve the dir, prefix and suffix of pattern + p = resolve(pattern); + + // Resolve the namespace and task-name + task = splitNs(name); + name = task.name; + + // Set the objective as the task-name + obj = name; + + // Namespace is already matched. + + // Check dir + if (path.dirname(obj) != p.dir) { + return false; + } + + filename = path.basename(obj); + + // Check file name length + if ((p.prefix.length + p.suffix.length + 1) > filename.length) { + // Length does not match. + return false; + } + + // Check prefix + if (filename.indexOf(p.prefix) !== 0) { + return false; + } + + // Check suffix + if (!stringEndWith(p.suffix, filename)) { + return false; + } + + // OK. Find a match. + return true; + } + } + + // Generate the source based on + // - name name for the synthesized task + // - pattern pattern for the objective + // - source pattern for the source + // + // Return the source with properties + // - dep the prerequisite of source + // (with the namespace) + // + // - file the file name of source + // (without the namespace) + // + // For example, given + // + // - name foo:bin/main.o + // - pattern bin/%.o + // - source src/%.c + // + // return 'foo:src/main.c', + // + static getSource(name, pattern, source) { + let dep; + let pat; + let match; + let file; + let src; + + // Regex pattern -- use to look up the extension + if (pattern instanceof RegExp) { + match = pattern.exec(name); + if (match) { + if (typeof source == 'function') { + src = source(name); + } + else { + src = stringReplaceSuffix(name, match[0], source); + } + } + } + // Assume string + else { + // Simple string suffix replacement + if (pattern.indexOf('%') == -1) { + if (typeof source == 'function') { + src = source(name); + } + else { + src = stringReplaceSuffix(name, pattern, source); + } + } + // Percent-based substitution + else { + pat = pattern.replace('%', '(.*?)'); + pat = new RegExp(pat); + match = pat.exec(name); + if (match) { + if (typeof source == 'function') { + src = source(name); + } + else { + file = match[1]; + file = source.replace('%', file); + dep = match[0]; + src = name.replace(dep, file); + } + } + } + } + + return src; + } +} + + +exports.Rule = Rule; diff --git a/node_modules/jake/lib/task/directory_task.js b/node_modules/jake/lib/task/directory_task.js new file mode 100644 index 0000000..b17b624 --- /dev/null +++ b/node_modules/jake/lib/task/directory_task.js @@ -0,0 +1,30 @@ +let fs = require('fs'); +let FileTask = require('./file_task').FileTask; + +/** + @name jake + @namespace jake +*/ +/** + @name jake.DirectoryTask + @constructor + @augments EventEmitter + @augments jake.Task + @augments jake.FileTask + @description A Jake DirectoryTask + + @param {String} name The name of the directory to create. + */ +class DirectoryTask extends FileTask { + constructor(...args) { + super(...args); + if (fs.existsSync(this.name)) { + this.updateModTime(); + } + else { + this.modTime = null; + } + } +} + +exports.DirectoryTask = DirectoryTask; diff --git a/node_modules/jake/lib/task/file_task.js b/node_modules/jake/lib/task/file_task.js new file mode 100644 index 0000000..d23aba8 --- /dev/null +++ b/node_modules/jake/lib/task/file_task.js @@ -0,0 +1,126 @@ +let fs = require('fs'); +let Task = require('./task').Task; + +function isFileOrDirectory(t) { + return (t instanceof FileTask || + t instanceof DirectoryTask); +} + +function isFile(t) { + return (t instanceof FileTask && !(t instanceof DirectoryTask)); +} + +/** + @name jake + @namespace jake +*/ +/** + @name jake.FileTask + @class` + @extentds Task + @description A Jake FileTask + + @param {String} name The name of the Task + @param {Array} [prereqs] Prerequisites to be run before this task + @param {Function} [action] The action to perform to create this file + @param {Object} [opts] + @param {Array} [opts.asyc=false] Perform this task asynchronously. + If you flag a task with this option, you must call the global + `complete` method inside the task's action, for execution to proceed + to the next task. + */ +class FileTask extends Task { + constructor(...args) { + super(...args); + this.dummy = false; + if (fs.existsSync(this.name)) { + this.updateModTime(); + } + else { + this.modTime = null; + } + } + + isNeeded() { + let prereqs = this.prereqs; + let prereqName; + let prereqTask; + + // No repeatsies + if (this.taskStatus == Task.runStatuses.DONE) { + return false; + } + // The always-make override + else if (jake.program.opts['always-make']) { + return true; + } + // Default case + else { + + // We need either an existing file, or an action to create one. + // First try grabbing the actual mod-time of the file + try { + this.updateModTime(); + } + // Then fall back to looking for an action + catch(e) { + if (typeof this.action == 'function') { + return true; + } + else { + throw new Error('File-task ' + this.fullName + ' has no ' + + 'existing file, and no action to create one.'); + } + } + + // Compare mod-time of all the prereqs with its mod-time + // If any prereqs are newer, need to run the action to update + if (prereqs && prereqs.length) { + for (let i = 0, ii = prereqs.length; i < ii; i++) { + prereqName = prereqs[i]; + prereqTask = this.namespace.resolveTask(prereqName) || + jake.createPlaceholderFileTask(prereqName, this.namespace); + // Run the action if: + // 1. The prereq is a normal task (not file/dir) + // 2. The prereq is a file-task with a mod-date more recent than + // the one for this file/dir + if (prereqTask) { + if (!isFileOrDirectory(prereqTask) || + (isFile(prereqTask) && prereqTask.modTime > this.modTime)) { + return true; + } + } + } + this.taskStatus = Task.runStatuses.DONE; + return false; + } + // File/dir has no prereqs, and exists -- no need to run + else { + // Effectively done + this.taskStatus = Task.runStatuses.DONE; + return false; + } + } + } + + updateModTime() { + let stats = fs.statSync(this.name); + this.modTime = stats.mtime; + } + + complete() { + if (!this.dummy) { + this.updateModTime(); + } + // Hackity hack + Task.prototype.complete.apply(this, arguments); + } + +} + +exports.FileTask = FileTask; + +// DirectoryTask is a subclass of FileTask, depends on it +// being defined +let DirectoryTask = require('./directory_task').DirectoryTask; + diff --git a/node_modules/jake/lib/task/index.js b/node_modules/jake/lib/task/index.js new file mode 100644 index 0000000..bc93f41 --- /dev/null +++ b/node_modules/jake/lib/task/index.js @@ -0,0 +1,9 @@ + +let Task = require('./task').Task; +let FileTask = require('./file_task').FileTask; +let DirectoryTask = require('./directory_task').DirectoryTask; + +exports.Task = Task; +exports.FileTask = FileTask; +exports.DirectoryTask = DirectoryTask; + diff --git a/node_modules/jake/lib/task/task.js b/node_modules/jake/lib/task/task.js new file mode 100644 index 0000000..7833b50 --- /dev/null +++ b/node_modules/jake/lib/task/task.js @@ -0,0 +1,458 @@ +let EventEmitter = require('events').EventEmitter; +let async = require('async'); +let pc = require('picocolors'); +// 'rule' module is required at the bottom because circular deps + +// Used for task value, so better not to use +// null, since value should be unset/uninitialized +let UNDEFINED_VALUE; + +const ROOT_TASK_NAME = '__rootTask__'; +const POLLING_INTERVAL = 100; + +// Parse any positional args attached to the task-name +function parsePrereqName(name) { + let taskArr = name.split('['); + let taskName = taskArr[0]; + let taskArgs = []; + if (taskArr[1]) { + taskArgs = taskArr[1].replace(/\]$/, ''); + taskArgs = taskArgs.split(','); + } + return { + name: taskName, + args: taskArgs + }; +} + +/** + @name jake.Task + @class + @extends EventEmitter + @description A Jake Task + + @param {String} name The name of the Task + @param {Array} [prereqs] Prerequisites to be run before this task + @param {Function} [action] The action to perform for this task + @param {Object} [opts] + @param {Array} [opts.asyc=false] Perform this task asynchronously. + If you flag a task with this option, you must call the global + `complete` method inside the task's action, for execution to proceed + to the next task. + */ +class Task extends EventEmitter { + + constructor(name, prereqs, action, options) { + // EventEmitter ctor takes no args + super(); + + if (name.indexOf(':') > -1) { + throw new Error('Task name cannot include a colon. It is used internally as namespace delimiter.'); + } + let opts = options || {}; + + this._currentPrereqIndex = 0; + this._internal = false; + this._skipped = false; + + this.name = name; + this.prereqs = prereqs; + this.action = action; + this.async = false; + this.taskStatus = Task.runStatuses.UNSTARTED; + this.description = null; + this.args = []; + this.value = UNDEFINED_VALUE; + this.concurrency = 1; + this.startTime = null; + this.endTime = null; + this.directory = null; + this.namespace = null; + + // Support legacy async-flag -- if not explicitly passed or falsy, will + // be set to empty-object + if (typeof opts == 'boolean' && opts === true) { + this.async = true; + } + else { + if (opts.async) { + this.async = true; + } + if (opts.concurrency) { + this.concurrency = opts.concurrency; + } + } + + //Do a test on self dependencies for this task + if(Array.isArray(this.prereqs) && this.prereqs.indexOf(this.name) !== -1) { + throw new Error("Cannot use prereq " + this.name + " as a dependency of itself"); + } + } + + get fullName() { + return this._getFullName(); + } + + get params() { + return this._getParams(); + } + + _initInvocationChain() { + // Legacy global invocation chain + jake._invocationChain.push(this); + + // New root chain + if (!this._invocationChain) { + this._invocationChainRoot = true; + this._invocationChain = []; + if (jake.currentRunningTask) { + jake.currentRunningTask._waitForChains = jake.currentRunningTask._waitForChains || []; + jake.currentRunningTask._waitForChains.push(this._invocationChain); + } + } + } + + /** + @name jake.Task#invoke + @function + @description Runs prerequisites, then this task. If the task has already + been run, will not run the task again. + */ + invoke() { + this._initInvocationChain(); + + this.args = Array.prototype.slice.call(arguments); + this.reenabled = false; + this.runPrereqs(); + } + + /** + @name jake.Task#execute + @function + @description Run only this task, without prereqs. If the task has already + been run, *will* run the task again. + */ + execute() { + this._initInvocationChain(); + + this.args = Array.prototype.slice.call(arguments); + this.reenable(); + this.reenabled = true; + this.run(); + } + + runPrereqs() { + if (this.prereqs && this.prereqs.length) { + + if (this.concurrency > 1) { + async.eachLimit(this.prereqs, this.concurrency, + + (name, cb) => { + let parsed = parsePrereqName(name); + + let prereq = this.namespace.resolveTask(parsed.name) || + jake.attemptRule(name, this.namespace, 0) || + jake.createPlaceholderFileTask(name, this.namespace); + + if (!prereq) { + throw new Error('Unknown task "' + name + '"'); + } + + //Test for circular invocation + if(prereq === this) { + setImmediate(function () { + cb(new Error("Cannot use prereq " + prereq.name + " as a dependency of itself")); + }); + } + + if (prereq.taskStatus == Task.runStatuses.DONE) { + //prereq already done, return + setImmediate(cb); + } + else { + //wait for complete before calling cb + prereq.once('_done', () => { + prereq.removeAllListeners('_done'); + setImmediate(cb); + }); + // Start the prereq if we are the first to encounter it + if (prereq.taskStatus === Task.runStatuses.UNSTARTED) { + prereq.taskStatus = Task.runStatuses.STARTED; + prereq.invoke.apply(prereq, parsed.args); + } + } + }, + + (err) => { + //async callback is called after all prereqs have run. + if (err) { + throw err; + } + else { + setImmediate(this.run.bind(this)); + } + } + ); + } + else { + setImmediate(this.nextPrereq.bind(this)); + } + } + else { + setImmediate(this.run.bind(this)); + } + } + + nextPrereq() { + let self = this; + let index = this._currentPrereqIndex; + let name = this.prereqs[index]; + let prereq; + let parsed; + + if (name) { + + parsed = parsePrereqName(name); + + prereq = this.namespace.resolveTask(parsed.name) || + jake.attemptRule(name, this.namespace, 0) || + jake.createPlaceholderFileTask(name, this.namespace); + + if (!prereq) { + throw new Error('Unknown task "' + name + '"'); + } + + // Do when done + if (prereq.taskStatus == Task.runStatuses.DONE) { + self.handlePrereqDone(prereq); + } + else { + prereq.once('_done', () => { + this.handlePrereqDone(prereq); + prereq.removeAllListeners('_done'); + }); + if (prereq.taskStatus == Task.runStatuses.UNSTARTED) { + prereq.taskStatus = Task.runStatuses.STARTED; + prereq._invocationChain = this._invocationChain; + prereq.invoke.apply(prereq, parsed.args); + } + } + } + } + + /** + @name jake.Task#reenable + @function + @description Reenables a task so that it can be run again. + */ + reenable(deep) { + let prereqs; + let prereq; + this._skipped = false; + this.taskStatus = Task.runStatuses.UNSTARTED; + this.value = UNDEFINED_VALUE; + if (deep && this.prereqs) { + prereqs = this.prereqs; + for (let i = 0, ii = prereqs.length; i < ii; i++) { + prereq = jake.Task[prereqs[i]]; + if (prereq) { + prereq.reenable(deep); + } + } + } + } + + handlePrereqDone(prereq) { + this._currentPrereqIndex++; + if (this._currentPrereqIndex < this.prereqs.length) { + setImmediate(this.nextPrereq.bind(this)); + } + else { + setImmediate(this.run.bind(this)); + } + } + + isNeeded() { + let needed = true; + if (this.taskStatus == Task.runStatuses.DONE) { + needed = false; + } + return needed; + } + + run() { + let val, previous; + let hasAction = typeof this.action == 'function'; + + if (!this.isNeeded()) { + this.emit('skip'); + this.emit('_done'); + } + else { + if (this._invocationChain.length) { + previous = this._invocationChain[this._invocationChain.length - 1]; + // If this task is repeating and its previous is equal to this, don't check its status because it was set to UNSTARTED by the reenable() method + if (!(this.reenabled && previous == this)) { + if (previous.taskStatus != Task.runStatuses.DONE) { + let now = (new Date()).getTime(); + if (now - this.startTime > jake._taskTimeout) { + return jake.fail(`Timed out waiting for task: ${previous.name} with status of ${previous.taskStatus}`); + } + setTimeout(this.run.bind(this), POLLING_INTERVAL); + return; + } + } + } + if (!(this.reenabled && previous == this)) { + this._invocationChain.push(this); + } + + if (!(this._internal || jake.program.opts.quiet)) { + jake.emit('started', { + name: this.fullName, + task: this, + }); + console.log("Starting '" + pc.green(this.fullName) + "'..."); + } + + this.startTime = (new Date()).getTime(); + this.emit('start'); + + jake.currentRunningTask = this; + + if (hasAction) { + try { + if (this.directory) { + process.chdir(this.directory); + } + + val = this.action.apply(this, this.args); + + if (typeof val == 'object' && typeof val.then == 'function') { + this.async = true; + + val.then( + (result) => { + setImmediate(() => { + this.complete(result); + }); + }, + (err) => { + setImmediate(() => { + this.errorOut(err); + }); + }); + } + } + catch (err) { + this.errorOut(err); + return; // Bail out, not complete + } + } + + if (!(hasAction && this.async)) { + setImmediate(() => { + this.complete(val); + }); + } + } + } + + errorOut(err) { + this.taskStatus = Task.runStatuses.ERROR; + this._invocationChain.chainStatus = Task.runStatuses.ERROR; + this.emit('error', err); + } + + complete(val) { + + if (Array.isArray(this._waitForChains)) { + let stillWaiting = this._waitForChains.some((chain) => { + return !(chain.chainStatus == Task.runStatuses.DONE || + chain.chainStatus == Task.runStatuses.ERROR); + }); + if (stillWaiting) { + let now = (new Date()).getTime(); + let elapsed = now - this.startTime; + if (elapsed > jake._taskTimeout) { + return jake.fail(`Timed out waiting for task: ${this.name} with status of ${this.taskStatus}. Elapsed: ${elapsed}`); + } + setTimeout(() => { + this.complete(val); + }, POLLING_INTERVAL); + return; + } + } + + jake._invocationChain.splice(jake._invocationChain.indexOf(this), 1); + + if (this._invocationChainRoot) { + this._invocationChain.chainStatus = Task.runStatuses.DONE; + } + + this._currentPrereqIndex = 0; + + // If 'complete' getting called because task has been + // run already, value will not be passed -- leave in place + if (!this._skipped) { + this.taskStatus = Task.runStatuses.DONE; + this.value = val; + + this.emit('complete', this.value); + this.emit('_done'); + + this.endTime = (new Date()).getTime(); + let taskTime = this.endTime - this.startTime; + + if (!(this._internal || jake.program.opts.quiet)) { + jake.emit('finished', { + name: this.fullName, + task: this, + time: taskTime, + }); + console.log("Finished '" + pc.green(this.fullName) + "' after " + pc.magenta(taskTime + ' ms')); + } + + } + } + + _getFullName() { + let ns = this.namespace; + let path = (ns && ns.path) || ''; + path = (path && path.split(':')) || []; + if (this.namespace !== jake.defaultNamespace) { + path.push(this.namespace.name); + } + path.push(this.name); + return path.join(':'); + } + + _getParams() { + if (!this.action) return ""; + let params = (new RegExp('(?:'+this.action.name+'\\s*|^)\\s*\\((.*?)\\)').exec(this.action.toString().replace(/\n/g, '')) || [''])[1].replace(/\/\*.*?\*\//g, '').replace(/ /g, ''); + return params; + } + + static getBaseNamespacePath(fullName) { + return fullName.split(':').slice(0, -1).join(':'); + } + + static getBaseTaskName(fullName) { + return fullName.split(':').pop(); + } +} + +Task.runStatuses = { + UNSTARTED: 'unstarted', + DONE: 'done', + STARTED: 'started', + ERROR: 'error' +}; + +Task.ROOT_TASK_NAME = ROOT_TASK_NAME; + +exports.Task = Task; + +// Required here because circular deps +require('../rule'); + diff --git a/node_modules/jake/lib/test_task.js b/node_modules/jake/lib/test_task.js new file mode 100644 index 0000000..6482bf1 --- /dev/null +++ b/node_modules/jake/lib/test_task.js @@ -0,0 +1,270 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +let path = require('path'); +let currDir = process.cwd(); + +/** + @name jake + @namespace jake +*/ +/** + @name jake.TestTask + @constructor + @description Instantiating a TestTask creates a number of Jake + Tasks that make running tests for your software easy. + + @param {String} name The name of the project + @param {Function} definition Defines the list of files containing the tests, + and the name of the namespace/task for running them. Will be executed on the + instantiated TestTask (i.e., 'this', will be the TestTask instance), to set + the various instance-propertiess. + + @example + let t = new jake.TestTask('bij-js', function () { + this.testName = 'testSpecial'; + this.testFiles.include('test/**'); + }); + + */ +let TestTask = function () { + let self = this; + let args = Array.prototype.slice.call(arguments); + let name = args.shift(); + let definition = args.pop(); + let prereqs = args.pop() || []; + + /** + @name jake.TestTask#testNam + @public + @type {String} + @description The name of the namespace to place the tests in, and + the top-level task for running tests. Defaults to "test" + */ + this.testName = 'test'; + + /** + @name jake.TestTask#testFiles + @public + @type {jake.FileList} + @description The list of files containing tests to load + */ + this.testFiles = new jake.FileList(); + + /** + @name jake.TestTask#showDescription + @public + @type {Boolean} + @description Show the created task when doing Jake -T + */ + this.showDescription = true; + + /* + @name jake.TestTask#totalTests + @public + @type {Number} + @description The total number of tests to run + */ + this.totalTests = 0; + + /* + @name jake.TestTask#executedTests + @public + @type {Number} + @description The number of tests successfully run + */ + this.executedTests = 0; + + if (typeof definition == 'function') { + definition.call(this); + } + + if (this.showDescription) { + desc('Run the tests for ' + name); + } + + task(this.testName, prereqs, {async: true}, function () { + let t = jake.Task[this.fullName + ':run']; + t.on('complete', function () { + complete(); + }); + // Pass args to the namespaced test + t.invoke.apply(t, arguments); + }); + + namespace(self.testName, function () { + + let runTask = task('run', {async: true}, function (pat) { + let re; + let testFiles; + + // Don't nest; make a top-level namespace. Don't want + // re-calling from inside to nest infinitely + jake.currentNamespace = jake.defaultNamespace; + + re = new RegExp(pat); + // Get test files that match the passed-in pattern + testFiles = self.testFiles.toArray() + .filter(function (f) { + return (re).test(f); + }) // Don't load the same file multiple times -- should this be in FileList? + .reduce(function (p, c) { + if (p.indexOf(c) < 0) { + p.push(c); + } + return p; + }, []); + + // Create a namespace for all the testing tasks to live in + namespace(self.testName + 'Exec', function () { + // Each test will be a prereq for the dummy top-level task + let prereqs = []; + // Continuation to pass to the async tests, wrapping `continune` + let next = function () { + complete(); + }; + // Create the task for this test-function + let createTask = function (name, action) { + // If the test-function is defined with a continuation + // param, flag the task as async + let t; + let isAsync = !!action.length; + + // Define the actual namespaced task with the name, the + // wrapped action, and the correc async-flag + t = task(name, createAction(name, action), { + async: isAsync + }); + t.once('complete', function () { + self.executedTests++; + }); + t._internal = true; + return t; + }; + // Used as the action for the defined task for each test. + let createAction = function (n, a) { + // A wrapped function that passes in the `next` function + // for any tasks that run asynchronously + return function () { + let cb; + if (a.length) { + cb = next; + } + if (!(n == 'before' || n == 'after' || + /_beforeEach$/.test(n) || /_afterEach$/.test(n))) { + jake.logger.log(n); + } + // 'this' will be the task when action is run + return a.call(this, cb); + }; + }; + // Dummy top-level task for everything to be prereqs for + let topLevel; + + // Pull in each test-file, and iterate over any exported + // test-functions. Register each test-function as a prereq task + testFiles.forEach(function (file) { + let exp = require(path.join(currDir, file)); + + // Create a namespace for each filename, so test-name collisions + // won't be a problem + namespace(file, function () { + let testPrefix = self.testName + 'Exec:' + file + ':'; + let testName; + // Dummy task for displaying file banner + testName = '*** Running ' + file + ' ***'; + prereqs.push(testPrefix + testName); + createTask(testName, function () {}); + + // 'before' setup + if (typeof exp.before == 'function') { + prereqs.push(testPrefix + 'before'); + // Create the task + createTask('before', exp.before); + } + + // Walk each exported function, and create a task for each + for (let p in exp) { + if (p == 'before' || p == 'after' || + p == 'beforeEach' || p == 'afterEach') { + continue; + } + + if (typeof exp.beforeEach == 'function') { + prereqs.push(testPrefix + p + '_beforeEach'); + // Create the task + createTask(p + '_beforeEach', exp.beforeEach); + } + + // Add the namespace:name of this test to the list of prereqs + // for the dummy top-level task + prereqs.push(testPrefix + p); + // Create the task + createTask(p, exp[p]); + + if (typeof exp.afterEach == 'function') { + prereqs.push(testPrefix + p + '_afterEach'); + // Create the task + createTask(p + '_afterEach', exp.afterEach); + } + } + + // 'after' teardown + if (typeof exp.after == 'function') { + prereqs.push(testPrefix + 'after'); + // Create the task + let afterTask = createTask('after', exp.after); + afterTask._internal = true; + } + + }); + }); + + self.totalTests = prereqs.length; + process.on('exit', function () { + // Throw in the case where the process exits without + // finishing tests, but no error was thrown + if (!jake.errorCode && (self.totalTests > self.executedTests)) { + throw new Error('Process exited without all tests completing.'); + } + }); + + // Create the dummy top-level task. When calling a task internally + // with `invoke` that is async (or has async prereqs), have to listen + // for the 'complete' event to know when it's done + topLevel = task('__top__', prereqs); + topLevel._internal = true; + topLevel.addListener('complete', function () { + jake.logger.log('All tests ran successfully'); + complete(); + }); + + topLevel.invoke(); // Do the thing! + }); + + }); + runTask._internal = true; + + }); + + +}; + +jake.TestTask = TestTask; +exports.TestTask = TestTask; + diff --git a/node_modules/jake/lib/utils/file.js b/node_modules/jake/lib/utils/file.js new file mode 100644 index 0000000..d7163f3 --- /dev/null +++ b/node_modules/jake/lib/utils/file.js @@ -0,0 +1,286 @@ +/* + * Utilities: A classic collection of JavaScript utilities + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +let fs = require('fs'); +let path = require('path'); + +/** + @name file + @namespace file +*/ + +let fileUtils = new (function () { + + // Recursively copy files and directories + let _copyFile = function (fromPath, toPath, opts) { + let from = path.normalize(fromPath); + let to = path.normalize(toPath); + let options = opts || {}; + let fromStat; + let toStat; + let destExists; + let destDoesNotExistErr; + let content; + let filename; + let dirContents; + let targetDir; + + fromStat = fs.statSync(from); + + try { + //console.dir(to + ' destExists'); + toStat = fs.statSync(to); + destExists = true; + } + catch(e) { + //console.dir(to + ' does not exist'); + destDoesNotExistErr = e; + destExists = false; + } + // Destination dir or file exists, copy into (directory) + // or overwrite (file) + if (destExists) { + + // If there's a rename-via-copy file/dir name passed, use it. + // Otherwise use the actual file/dir name + filename = options.rename || path.basename(from); + + // Copying a directory + if (fromStat.isDirectory()) { + dirContents = fs.readdirSync(from); + targetDir = path.join(to, filename); + // We don't care if the target dir already exists + try { + fs.mkdirSync(targetDir, {mode: fromStat.mode & 0o777}); + } + catch(e) { + if (e.code !== 'EEXIST') { + throw e; + } + } + for (let i = 0, ii = dirContents.length; i < ii; i++) { + _copyFile(path.join(from, dirContents[i]), targetDir, {preserveMode: options.preserveMode}); + } + } + // Copying a file + else { + content = fs.readFileSync(from); + let mode = fromStat.mode & 0o777; + let targetFile = to; + + if (toStat.isDirectory()) { + targetFile = path.join(to, filename); + } + + let fileExists = fs.existsSync(targetFile); + fs.writeFileSync(targetFile, content); + + // If the file didn't already exist, use the original file mode. + // Otherwise, only update the mode if preserverMode is true. + if(!fileExists || options.preserveMode) { + fs.chmodSync(targetFile, mode); + } + } + } + // Dest doesn't exist, can't create it + else { + throw destDoesNotExistErr; + } + }; + + // Remove the given directory + let _rmDir = function (dirPath) { + let dir = path.normalize(dirPath); + let paths = []; + paths = fs.readdirSync(dir); + paths.forEach(function (p) { + let curr = path.join(dir, p); + let stat = fs.lstatSync(curr); + if (stat.isDirectory()) { + _rmDir(curr); + } + else { + try { + fs.unlinkSync(curr); + } catch(e) { + if (e.code === 'EPERM') { + fs.chmodSync(curr, parseInt(666, 8)); + fs.unlinkSync(curr); + } else { + throw e; + } + } + } + }); + fs.rmdirSync(dir); + }; + + /** + @name file#cpR + @public + @function + @description Copies a directory/file to a destination + @param {String} fromPath The source path to copy from + @param {String} toPath The destination path to copy to + @param {Object} opts Options to use + @param {Boolean} [opts.preserveMode] If target file already exists, this + determines whether the original file's mode is copied over. The default of + false mimics the behavior of the `cp` command line tool. (Default: false) + */ + this.cpR = function (fromPath, toPath, options) { + let from = path.normalize(fromPath); + let to = path.normalize(toPath); + let toStat; + let doesNotExistErr; + let filename; + let opts = options || {}; + + if (from == to) { + throw new Error('Cannot copy ' + from + ' to itself.'); + } + + // Handle rename-via-copy + try { + toStat = fs.statSync(to); + } + catch(e) { + doesNotExistErr = e; + + // Get abs path so it's possible to check parent dir + if (!this.isAbsolute(to)) { + to = path.join(process.cwd(), to); + } + + // Save the file/dir name + filename = path.basename(to); + // See if a parent dir exists, so there's a place to put the + /// renamed file/dir (resets the destination for the copy) + to = path.dirname(to); + try { + toStat = fs.statSync(to); + } + catch(e) {} + if (toStat && toStat.isDirectory()) { + // Set the rename opt to pass to the copy func, will be used + // as the new file/dir name + opts.rename = filename; + //console.log('filename ' + filename); + } + else { + throw doesNotExistErr; + } + } + + _copyFile(from, to, opts); + }; + + /** + @name file#mkdirP + @public + @function + @description Create the given directory(ies) using the given mode permissions + @param {String} dir The directory to create + @param {Number} mode The mode to give the created directory(ies)(Default: 0755) + */ + this.mkdirP = function (dir, mode) { + let dirPath = path.normalize(dir); + let paths = dirPath.split(/\/|\\/); + let currPath = ''; + let next; + + if (paths[0] == '' || /^[A-Za-z]+:/.test(paths[0])) { + currPath = paths.shift() || '/'; + currPath = path.join(currPath, paths.shift()); + //console.log('basedir'); + } + while ((next = paths.shift())) { + if (next == '..') { + currPath = path.join(currPath, next); + continue; + } + currPath = path.join(currPath, next); + try { + //console.log('making ' + currPath); + fs.mkdirSync(currPath, mode || parseInt(755, 8)); + } + catch(e) { + if (e.code != 'EEXIST') { + throw e; + } + } + } + }; + + /** + @name file#rmRf + @public + @function + @description Deletes the given directory/file + @param {String} p The path to delete, can be a directory or file + */ + this.rmRf = function (p, options) { + let stat; + try { + stat = fs.lstatSync(p); + if (stat.isDirectory()) { + _rmDir(p); + } + else { + fs.unlinkSync(p); + } + } + catch (e) {} + }; + + /** + @name file#isAbsolute + @public + @function + @return {Boolean/String} If it's absolute the first character is returned otherwise false + @description Checks if a given path is absolute or relative + @param {String} p Path to check + */ + this.isAbsolute = function (p) { + let match = /^[A-Za-z]+:\\|^\//.exec(p); + if (match && match.length) { + return match[0]; + } + return false; + }; + + /** + @name file#absolutize + @public + @function + @return {String} Returns the absolute path for the given path + @description Returns the absolute path for the given path + @param {String} p The path to get the absolute path for + */ + this.absolutize = function (p) { + if (this.isAbsolute(p)) { + return p; + } + else { + return path.join(process.cwd(), p); + } + }; + +})(); + +module.exports = fileUtils; + diff --git a/node_modules/jake/lib/utils/index.js b/node_modules/jake/lib/utils/index.js new file mode 100644 index 0000000..17d686b --- /dev/null +++ b/node_modules/jake/lib/utils/index.js @@ -0,0 +1,297 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + + +let util = require('util'); // Native Node util module +let spawn = require('child_process').spawn; +let EventEmitter = require('events').EventEmitter; +let logger = require('./logger'); +let file = require('./file'); +let Exec; + +const _UUID_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); + +let parseArgs = function (argumentsObj) { + let args; + let arg; + let cmds; + let callback; + let opts = { + interactive: false, + printStdout: false, + printStderr: false, + breakOnError: true + }; + + args = Array.prototype.slice.call(argumentsObj); + + cmds = args.shift(); + // Arrayize if passed a single string command + if (typeof cmds == 'string') { + cmds = [cmds]; + } + // Make a copy if it's an actual list + else { + cmds = cmds.slice(); + } + + // Get optional callback or opts + while((arg = args.shift())) { + if (typeof arg == 'function') { + callback = arg; + } + else if (typeof arg == 'object') { + opts = Object.assign(opts, arg); + } + } + + // Backward-compat shim + if (typeof opts.stdout != 'undefined') { + opts.printStdout = opts.stdout; + delete opts.stdout; + } + if (typeof opts.stderr != 'undefined') { + opts.printStderr = opts.stderr; + delete opts.stderr; + } + + return { + cmds: cmds, + opts: opts, + callback: callback + }; +}; + +/** + @name jake + @namespace jake +*/ +let utils = new (function () { + /** + @name jake.exec + @static + @function + @description Executes shell-commands asynchronously with an optional + final callback. + ` + @param {String[]} cmds The list of shell-commands to execute + @param {Object} [opts] + @param {Boolean} [opts.printStdout=false] Print stdout from each command + @param {Boolean} [opts.printStderr=false] Print stderr from each command + @param {Boolean} [opts.breakOnError=true] Stop further execution on + the first error. + @param {Boolean} [opts.windowsVerbatimArguments=false] Don't translate + arguments on Windows. + @param {Function} [callback] Callback to run after executing the + commands + + @example + let cmds = [ + 'echo "showing directories"' + , 'ls -al | grep ^d' + , 'echo "moving up a directory"' + , 'cd ../' + ] + , callback = function () { + console.log('Finished running commands.'); + } + jake.exec(cmds, {stdout: true}, callback); + */ + this.exec = function (a, b, c) { + let parsed = parseArgs(arguments); + let cmds = parsed.cmds; + let opts = parsed.opts; + let callback = parsed.callback; + + let ex = new Exec(cmds, opts, callback); + + ex.addListener('error', function (msg, code) { + if (opts.breakOnError) { + fail(msg, code); + } + }); + ex.run(); + + return ex; + }; + + this.createExec = function (a, b, c) { + return new Exec(a, b, c); + }; + + // From Math.uuid.js, https://github.com/broofa/node-uuid + // Robert Kieffer (robert@broofa.com), MIT license + this.uuid = function (length, radix) { + var chars = _UUID_CHARS + , uuid = [] + , r + , i; + + radix = radix || chars.length; + + if (length) { + // Compact form + i = -1; + while (++i < length) { + uuid[i] = chars[0 | Math.random()*radix]; + } + } else { + // rfc4122, version 4 form + + // rfc4122 requires these characters + uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'; + uuid[14] = '4'; + + // Fill in random data. At i==19 set the high bits of clock sequence as + // per rfc4122, sec. 4.1.5 + i = -1; + while (++i < 36) { + if (!uuid[i]) { + r = 0 | Math.random()*16; + uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]; + } + } + } + + return uuid.join(''); + }; + +})(); + +Exec = function () { + let parsed = parseArgs(arguments); + let cmds = parsed.cmds; + let opts = parsed.opts; + let callback = parsed.callback; + + this._cmds = cmds; + this._callback = callback; + this._config = opts; +}; + +util.inherits(Exec, EventEmitter); + +Object.assign(Exec.prototype, new (function () { + + let _run = function () { + let self = this; + let sh; + let cmd; + let args; + let next = this._cmds.shift(); + let config = this._config; + let errData = ''; + let shStdio; + let handleStdoutData = function (data) { + self.emit('stdout', data); + }; + let handleStderrData = function (data) { + let d = data.toString(); + self.emit('stderr', data); + // Accumulate the error-data so we can use it as the + // stack if the process exits with an error + errData += d; + }; + + // Keep running as long as there are commands in the array + if (next) { + let spawnOpts = {}; + this.emit('cmdStart', next); + + // Ganking part of Node's child_process.exec to get cmdline args parsed + if (process.platform == 'win32') { + cmd = 'cmd'; + args = ['/c', next]; + if (config.windowsVerbatimArguments) { + spawnOpts.windowsVerbatimArguments = true; + } + } + else { + cmd = '/bin/sh'; + args = ['-c', next]; + } + + if (config.interactive) { + spawnOpts.stdio = 'inherit'; + sh = spawn(cmd, args, spawnOpts); + } + else { + shStdio = [ + process.stdin + ]; + if (config.printStdout) { + shStdio.push(process.stdout); + } + else { + shStdio.push('pipe'); + } + if (config.printStderr) { + shStdio.push(process.stderr); + } + else { + shStdio.push('pipe'); + } + spawnOpts.stdio = shStdio; + sh = spawn(cmd, args, spawnOpts); + if (!config.printStdout) { + sh.stdout.addListener('data', handleStdoutData); + } + if (!config.printStderr) { + sh.stderr.addListener('data', handleStderrData); + } + } + + // Exit, handle err or run next + sh.on('exit', function (code) { + let msg; + if (code !== 0) { + msg = errData || 'Process exited with error.'; + msg = msg.trim(); + self.emit('error', msg, code); + } + if (code === 0 || !config.breakOnError) { + self.emit('cmdEnd', next); + setTimeout(function () { _run.call(self); }, 0); + } + }); + + } + else { + self.emit('end'); + if (typeof self._callback == 'function') { + self._callback(); + } + } + }; + + this.append = function (cmd) { + this._cmds.push(cmd); + }; + + this.run = function () { + _run.call(this); + }; + +})()); + +utils.Exec = Exec; +utils.file = file; +utils.logger = logger; + +module.exports = utils; + diff --git a/node_modules/jake/lib/utils/logger.js b/node_modules/jake/lib/utils/logger.js new file mode 100644 index 0000000..8f72686 --- /dev/null +++ b/node_modules/jake/lib/utils/logger.js @@ -0,0 +1,24 @@ +let util = require('util'); + +let logger = new (function () { + let _output = function (type, out) { + let quiet = typeof jake != 'undefined' && jake.program && + jake.program.opts && jake.program.opts.quiet; + let msg; + if (!quiet) { + msg = typeof out == 'string' ? out : util.inspect(out); + console[type](msg); + } + }; + + this.log = function (out) { + _output('log', out); + }; + + this.error = function (out) { + _output('error', out); + }; + +})(); + +module.exports = logger; diff --git a/node_modules/jake/package.json b/node_modules/jake/package.json new file mode 100644 index 0000000..d9d3e9e --- /dev/null +++ b/node_modules/jake/package.json @@ -0,0 +1,44 @@ +{ + "name": "jake", + "description": "JavaScript build tool, similar to Make or Rake", + "keywords": [ + "build", + "cli", + "make", + "rake" + ], + "version": "10.9.4", + "author": "Matthew Eernisse (http://fleegix.org)", + "license": "Apache-2.0", + "bin": { + "jake": "./bin/cli.js" + }, + "main": "./lib/jake.js", + "scripts": { + "lint": "eslint --format codeframe \"lib/**/*.js\" \"test/**/*.js\"", + "lint:fix": "eslint --fix \"lib/**/*.js\" \"test/**/*.js\"", + "test": "./bin/cli.js test", + "test:ci": "npm run lint && npm run test" + }, + "repository": { + "type": "git", + "url": "git://github.com/jakejs/jake.git" + }, + "preferGlobal": true, + "dependencies": { + "async": "^3.2.6", + "filelist": "^1.0.4", + "picocolors": "^1.1.1" + }, + "devDependencies": { + "@eslint/js": "^9.16.0", + "eslint": "^9.16.0", + "eslint-formatter-codeframe": "^7.32.1", + "globals": "^15.13.0", + "mocha": "^11.0.1", + "q": "^1.5.1" + }, + "engines": { + "node": ">=10" + } +} diff --git a/node_modules/jake/test/integration/concurrent.js b/node_modules/jake/test/integration/concurrent.js new file mode 100644 index 0000000..ab649b9 --- /dev/null +++ b/node_modules/jake/test/integration/concurrent.js @@ -0,0 +1,45 @@ +let assert = require('assert'); +let exec = require('child_process').execSync; + +const PROJECT_DIR = process.env.PROJECT_DIR; +const JAKE_CMD = `${PROJECT_DIR}/bin/cli.js`; + +suite('concurrent', function () { + + this.timeout(7000); + + test(' simple concurrent prerequisites 1', function () { + let out = exec(`${JAKE_CMD} -q concurrent:simple1`).toString().trim(); + assert.equal('Started A\nStarted B\nFinished B\nFinished A', out); + }); + + test(' simple concurrent prerequisites 2', function () { + let out = exec(`${JAKE_CMD} -q concurrent:simple2`).toString().trim(); + assert.equal('Started C\nStarted D\nFinished C\nFinished D', out); + }); + + test(' sequential concurrent prerequisites', function () { + let out = exec(`${JAKE_CMD} -q concurrent:seqconcurrent`).toString().trim(); + assert.equal('Started A\nStarted B\nFinished B\nFinished A\nStarted C\nStarted D\nFinished C\nFinished D', out); + }); + + test(' concurrent concurrent prerequisites', function () { + let out = exec(`${JAKE_CMD} -q concurrent:concurrentconcurrent`).toString().trim(); + assert.equal('Started A\nStarted B\nStarted C\nStarted D\nFinished B\nFinished C\nFinished A\nFinished D', out); + }); + + test(' concurrent prerequisites with subdependency', function () { + let out = exec(`${JAKE_CMD} -q concurrent:subdep`).toString().trim(); + assert.equal('Started A\nFinished A\nStarted Ba\nFinished Ba', out); + }); + + test(' failing in concurrent prerequisites', function () { + try { + exec(`${JAKE_CMD} -q concurrent:Cfail`); + } + catch(err) { + assert(err.message.indexOf('Command failed') > -1); + } + }); + +}); diff --git a/node_modules/jake/test/integration/file.js b/node_modules/jake/test/integration/file.js new file mode 100644 index 0000000..97ed0d6 --- /dev/null +++ b/node_modules/jake/test/integration/file.js @@ -0,0 +1,228 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +const PROJECT_DIR = process.env.PROJECT_DIR; + +let assert = require('assert'); +let fs = require('fs'); +let path = require('path'); +let file = require(`${PROJECT_DIR}/lib/utils/file`); +let existsSync = fs.existsSync || path.existsSync; +let exec = require('child_process').execSync; + +suite('fileUtils', function () { + + test('mkdirP', function () { + let expected = [ + ['foo'], + ['foo', 'bar'], + ['foo', 'bar', 'baz'], + ['foo', 'bar', 'baz', 'qux'] + ]; + file.mkdirP('foo/bar/baz/qux'); + let res = exec('find foo').toString().trim().split('\n'); + for (let i = 0, ii = res.length; i < ii; i++) { + assert.equal(path.join.apply(path, expected[i]), res[i]); + } + file.rmRf('foo'); + }); + + test('rmRf', function () { + file.mkdirP('foo/bar/baz/qux'); + file.rmRf('foo/bar'); + let res = exec('find foo').toString().trim().split('\n'); + assert.equal(1, res.length); + assert.equal('foo', res[0]); + fs.rmdirSync('foo'); + }); + + test('rmRf with symlink subdir', function () { + file.mkdirP('foo'); + file.mkdirP('bar'); + fs.writeFileSync('foo/hello.txt', 'hello, it\'s me'); + fs.symlinkSync('../foo', 'bar/foo'); file.rmRf('bar'); + + // Make sure the bar directory was successfully deleted + let barDeleted = false; + try { + fs.statSync('bar'); + } catch(err) { + if(err.code == 'ENOENT') { + barDeleted = true; + } + } + assert.equal(true, barDeleted); + + // Make sure that the file inside the linked folder wasn't deleted + let res = fs.readdirSync('foo'); + assert.equal(1, res.length); + assert.equal('hello.txt', res[0]); + + // Cleanup + fs.unlinkSync('foo/hello.txt'); + fs.rmdirSync('foo'); + }); + + test('rmRf with symlinked dir', function () { + file.mkdirP('foo'); + fs.writeFileSync('foo/hello.txt', 'hello!'); + fs.symlinkSync('foo', 'bar'); + file.rmRf('bar'); + + // Make sure the bar directory was successfully deleted + let barDeleted = false; + try { + fs.statSync('bar'); + } catch(err) { + if(err.code == 'ENOENT') { + barDeleted = true; + } + } + assert.equal(true, barDeleted); + + // Make sure that the file inside the linked folder wasn't deleted + let res = fs.readdirSync('foo'); + assert.equal(1, res.length); + assert.equal('hello.txt', res[0]); + + // Cleanup + fs.unlinkSync('foo/hello.txt'); + fs.rmdirSync('foo'); + }); + + test('cpR with same name and different directory', function () { + file.mkdirP('foo'); + fs.writeFileSync('foo/bar.txt', 'w00t'); + file.cpR('foo', 'bar'); + assert.ok(existsSync('bar/bar.txt')); + file.rmRf('foo'); + file.rmRf('bar'); + }); + + test('cpR with same to and from will throw', function () { + assert.throws(function () { + file.cpR('foo.txt', 'foo.txt'); + }); + }); + + test('cpR rename via copy in directory', function () { + file.mkdirP('foo'); + fs.writeFileSync('foo/bar.txt', 'w00t'); + file.cpR('foo/bar.txt', 'foo/baz.txt'); + assert.ok(existsSync('foo/baz.txt')); + file.rmRf('foo'); + }); + + test('cpR rename via copy in base', function () { + fs.writeFileSync('bar.txt', 'w00t'); + file.cpR('bar.txt', 'baz.txt'); + assert.ok(existsSync('baz.txt')); + file.rmRf('bar.txt'); + file.rmRf('baz.txt'); + }); + + test('cpR keeps file mode', function () { + fs.writeFileSync('bar.txt', 'w00t', {mode: 0o750}); + fs.writeFileSync('bar1.txt', 'w00t!', {mode: 0o744}); + file.cpR('bar.txt', 'baz.txt'); + file.cpR('bar1.txt', 'baz1.txt'); + + assert.ok(existsSync('baz.txt')); + assert.ok(existsSync('baz1.txt')); + let bazStat = fs.statSync('baz.txt'); + let bazStat1 = fs.statSync('baz1.txt'); + assert.equal(0o750, bazStat.mode & 0o7777); + assert.equal(0o744, bazStat1.mode & 0o7777); + + file.rmRf('bar.txt'); + file.rmRf('baz.txt'); + file.rmRf('bar1.txt'); + file.rmRf('baz1.txt'); + }); + + test('cpR keeps file mode when overwriting with preserveMode', function () { + fs.writeFileSync('bar.txt', 'w00t', {mode: 0o755}); + fs.writeFileSync('baz.txt', 'w00t!', {mode: 0o744}); + file.cpR('bar.txt', 'baz.txt', {silent: true, preserveMode: true}); + + assert.ok(existsSync('baz.txt')); + let bazStat = fs.statSync('baz.txt'); + assert.equal(0o755, bazStat.mode & 0o777); + + file.rmRf('bar.txt'); + file.rmRf('baz.txt'); + }); + + test('cpR does not keep file mode when overwriting', function () { + fs.writeFileSync('bar.txt', 'w00t', {mode: 0o766}); + fs.writeFileSync('baz.txt', 'w00t!', {mode: 0o744}); + file.cpR('bar.txt', 'baz.txt'); + + assert.ok(existsSync('baz.txt')); + let bazStat = fs.statSync('baz.txt'); + assert.equal(0o744, bazStat.mode & 0o777); + + file.rmRf('bar.txt'); + file.rmRf('baz.txt'); + }); + + test('cpR copies file mode recursively', function () { + fs.mkdirSync('foo'); + fs.writeFileSync('foo/bar.txt', 'w00t', {mode: 0o740}); + file.cpR('foo', 'baz'); + + assert.ok(existsSync('baz')); + let barStat = fs.statSync('baz/bar.txt'); + assert.equal(0o740, barStat.mode & 0o777); + + file.rmRf('foo'); + file.rmRf('baz'); + }); + + test('cpR keeps file mode recursively', function () { + fs.mkdirSync('foo'); + fs.writeFileSync('foo/bar.txt', 'w00t', {mode: 0o740}); + fs.mkdirSync('baz'); + fs.mkdirSync('baz/foo'); + fs.writeFileSync('baz/foo/bar.txt', 'w00t!', {mode: 0o755}); + file.cpR('foo', 'baz', {silent: true, preserveMode: true}); + + assert.ok(existsSync('baz')); + let barStat = fs.statSync('baz/foo/bar.txt'); + assert.equal(0o740, barStat.mode & 0o777); + + file.rmRf('foo'); + file.rmRf('baz'); + }); + + test('cpR copies directory mode recursively', function () { + fs.mkdirSync('foo', 0o755); + fs.mkdirSync('foo/bar', 0o700); + file.cpR('foo', 'bar'); + + assert.ok(existsSync('foo')); + let fooBarStat = fs.statSync('bar/bar'); + assert.equal(0o700, fooBarStat.mode & 0o777); + + file.rmRf('foo'); + file.rmRf('bar'); + }); + +}); + + diff --git a/node_modules/jake/test/integration/file_task.js b/node_modules/jake/test/integration/file_task.js new file mode 100644 index 0000000..4b5608e --- /dev/null +++ b/node_modules/jake/test/integration/file_task.js @@ -0,0 +1,141 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +const PROJECT_DIR = process.env.PROJECT_DIR; +const JAKE_CMD = `${PROJECT_DIR}/bin/cli.js`; + +let assert = require('assert'); +let fs = require('fs'); +let exec = require('child_process').execSync; +let { rmRf } = require(`${PROJECT_DIR}/lib/jake`); + +let cleanUpAndNext = function (callback) { + rmRf('./foo', { + silent: true + }); + callback && callback(); +}; + +suite('fileTask', function () { + this.timeout(7000); + + setup(function () { + cleanUpAndNext(); + }); + + test('where a file-task prereq does not change with --always-make', function () { + let out; + out = exec(`${JAKE_CMD} -q fileTest:foo/from-src1.txt`).toString().trim(); + assert.equal('fileTest:foo/src1.txt task\nfileTest:foo/from-src1.txt task', + out); + out = exec(`${JAKE_CMD} -q -B fileTest:foo/from-src1.txt`).toString().trim(); + assert.equal('fileTest:foo/src1.txt task\nfileTest:foo/from-src1.txt task', + out); + cleanUpAndNext(); + }); + + test('concating two files', function () { + let out; + out = exec(`${JAKE_CMD} -q fileTest:foo/concat.txt`).toString().trim(); + assert.equal('fileTest:foo/src1.txt task\ndefault task\nfileTest:foo/src2.txt task\n' + + 'fileTest:foo/concat.txt task', out); + // Check to see the two files got concat'd + let data = fs.readFileSync(process.cwd() + '/foo/concat.txt'); + assert.equal('src1src2', data.toString()); + cleanUpAndNext(); + }); + + test('where a file-task prereq does not change', function () { + let out; + out = exec(`${JAKE_CMD} -q fileTest:foo/from-src1.txt`).toString().trim(); + assert.equal('fileTest:foo/src1.txt task\nfileTest:foo/from-src1.txt task', out); + out = exec(`${JAKE_CMD} -q fileTest:foo/from-src1.txt`).toString().trim(); + // Second time should be a no-op + assert.equal('', out); + cleanUpAndNext(); + }); + + test('where a file-task prereq does change, then does not', function (next) { + exec('mkdir -p ./foo'); + exec('touch ./foo/from-src1.txt'); + setTimeout(() => { + fs.writeFileSync('./foo/src1.txt', '-SRC'); + // Task should run the first time + let out; + out = exec(`${JAKE_CMD} -q fileTest:foo/from-src1.txt`).toString().trim(); + assert.equal('fileTest:foo/from-src1.txt task', out); + // Task should not run on subsequent invocation + out = exec(`${JAKE_CMD} -q fileTest:foo/from-src1.txt`).toString().trim(); + assert.equal('', out); + cleanUpAndNext(next); + }, 1000); + }); + + test('a preexisting file', function () { + let prereqData = 'howdy'; + exec('mkdir -p ./foo'); + fs.writeFileSync('foo/prereq.txt', prereqData); + let out; + out = exec(`${JAKE_CMD} -q fileTest:foo/from-prereq.txt`).toString().trim(); + assert.equal('fileTest:foo/from-prereq.txt task', out); + let data = fs.readFileSync(process.cwd() + '/foo/from-prereq.txt'); + assert.equal(prereqData, data.toString()); + out = exec(`${JAKE_CMD} -q fileTest:foo/from-prereq.txt`).toString().trim(); + // Second time should be a no-op + assert.equal('', out); + cleanUpAndNext(); + }); + + test('a preexisting file with --always-make flag', function () { + let prereqData = 'howdy'; + exec('mkdir -p ./foo'); + fs.writeFileSync('foo/prereq.txt', prereqData); + let out; + out = exec(`${JAKE_CMD} -q fileTest:foo/from-prereq.txt`).toString().trim(); + assert.equal('fileTest:foo/from-prereq.txt task', out); + let data = fs.readFileSync(process.cwd() + '/foo/from-prereq.txt'); + assert.equal(prereqData, data.toString()); + out = exec(`${JAKE_CMD} -q -B fileTest:foo/from-prereq.txt`).toString().trim(); + assert.equal('fileTest:foo/from-prereq.txt task', out); + cleanUpAndNext(); + }); + + test('nested directory-task', function () { + exec(`${JAKE_CMD} -q fileTest:foo/bar/baz/bamf.txt`); + let data = fs.readFileSync(process.cwd() + '/foo/bar/baz/bamf.txt'); + assert.equal('w00t', data); + cleanUpAndNext(); + }); + + test('partially existing prereqs', function () { + /* + dependency graph: + /-- foo/output2a.txt --\ + foo -- foo/output1.txt --+ +-- output3.txt + \-- foo/output2b.txt --/ + */ + // build part of the prereqs + exec(`${JAKE_CMD} -q fileTest:foo/output2a.txt`); + // verify the final target gets built + exec(`${JAKE_CMD} -q fileTest:foo/output3.txt`); + let data = fs.readFileSync(process.cwd() + '/foo/output3.txt'); + assert.equal('w00t', data); + cleanUpAndNext(); + }); +}); + diff --git a/node_modules/jake/test/integration/helpers.js b/node_modules/jake/test/integration/helpers.js new file mode 100644 index 0000000..9caaa4e --- /dev/null +++ b/node_modules/jake/test/integration/helpers.js @@ -0,0 +1,80 @@ +var exec = require('child_process').exec; + +var helpers = new (function () { + var _tests; + var _names = []; + var _name; + var _callback; + var _runner = function () { + if ((_name = _names.shift())) { + console.log('Running ' + _name); + _tests[_name](); + } + else { + _callback(); + } + }; + + this.exec = function () { + var args = Array.prototype.slice.call(arguments); + var arg; + var cmd = args.shift(); + var opts = {}; + var callback; + // Optional opts/callback or callback/opts + while ((arg = args.shift())) { + if (typeof arg == 'function') { + callback = arg; + } + else { + opts = arg; + } + } + + cmd += ' --trace'; + var execOpts = opts.execOpts ? opts.execOpts : {}; + exec(cmd, execOpts, function (err, stdout, stderr) { + var out = helpers.trim(stdout); + if (err) { + if (opts.breakOnError === false) { + return callback(err); + } + else { + throw err; + } + } + if (stderr) { + callback(stderr); + } + else { + callback(out); + } + }); + }; + + this.trim = function (s) { + var str = s || ''; + return str.replace(/^\s*|\s*$/g, ''); + }; + + this.parse = function (s) { + var str = s || ''; + str = helpers.trim(str); + str = str.replace(/'/g, '"'); + return JSON.parse(str); + }; + + this.run = function (tests, callback) { + _tests = tests; + _names = Object.keys(tests); + _callback = callback; + _runner(); + }; + + this.next = function () { + _runner(); + }; + +})(); + +module.exports = helpers; diff --git a/node_modules/jake/test/integration/jakefile.js b/node_modules/jake/test/integration/jakefile.js new file mode 100644 index 0000000..9d57d0a --- /dev/null +++ b/node_modules/jake/test/integration/jakefile.js @@ -0,0 +1,352 @@ +let fs = require('fs'); +let Q = require('q'); + +desc('The default t.'); +task('default', function () { + console.log('default task'); +}); + +desc('No action.'); +task({'noAction': ['default']}); + +desc('No action, no prereqs.'); +task('noActionNoPrereqs'); + +desc('Top-level zerbofrangazoomy task'); +task('zerbofrangazoomy', function () { + console.log('Whaaaaaaaa? Ran the zerbofrangazoomy task!'); +}); + +desc('Task that throws'); +task('throwy', function () { + let errorListener = function (err) { + console.log('Emitted'); + console.log(err.toString()); + + jake.removeListener('error', errorListener); + }; + + jake.on('error', errorListener); + + throw new Error('I am bad'); +}); + +desc('Task that rejects a Promise'); +task('promiseRejecter', function () { + const originalOption = jake.program.opts['allow-rejection']; + + const errorListener = function (err) { + console.log(err.toString()); + jake.removeListener('error', errorListener); + jake.program.opts['allow-rejection'] = originalOption; // Restore original 'allow-rejection' option + }; + jake.on('error', errorListener); + + jake.program.opts['allow-rejection'] = false; // Do not allow rejection so the rejection is passed to error handlers + + Promise.reject(''); +}); + +desc('Accepts args and env vars.'); +task('argsEnvVars', function () { + let res = { + args: arguments + , env: { + foo: process.env.foo + , baz: process.env.baz + } + }; + console.log(JSON.stringify(res)); +}); + +namespace('foo', function () { + desc('The foo:bar t.'); + task('bar', function () { + if (arguments.length) { + console.log('foo:bar[' + + Array.prototype.join.call(arguments, ',') + + '] task'); + } + else { + console.log('foo:bar task'); + } + }); + + desc('The foo:baz task, calls foo:bar as a prerequisite.'); + task('baz', ['foo:bar'], function () { + console.log('foo:baz task'); + }); + + desc('The foo:qux task, calls foo:bar with cmdline args as a prerequisite.'); + task('qux', ['foo:bar[asdf,qwer]'], function () { + console.log('foo:qux task'); + }); + + desc('The foo:frang task,`invokes` foo:bar with passed args as a prerequisite.'); + task('frang', function () { + let t = jake.Task['foo:bar']; + // Do args pass-through + t.invoke.apply(t, arguments); + t.on('complete', () => { + console.log('foo:frang task'); + }); + }); + + desc('The foo:zerb task, `executes` foo:bar with passed args as a prerequisite.'); + task('zerb', function () { + let t = jake.Task['foo:bar']; + // Do args pass-through + t.execute.apply(t, arguments); + t.on('complete', () => { + console.log('foo:zerb task'); + }); + }); + + desc('The foo:zoobie task, has no prerequisites.'); + task('zoobie', function () { + console.log('foo:zoobie task'); + }); + + desc('The foo:voom task, run the foo:zoobie task repeatedly.'); + task('voom', function () { + let t = jake.Task['foo:bar']; + t.on('complete', function () { + console.log('complete'); + }); + t.execute.apply(t); + t.execute.apply(t); + }); + + desc('The foo:asdf task, has the same prereq twice.'); + task('asdf', ['foo:bar', 'foo:baz'], function () { + console.log('foo:asdf task'); + }); + +}); + +namespace('bar', function () { + desc('The bar:foo task, has no prerequisites, is async, returns Promise which resolves.'); + task('foo', async function () { + return new Promise((resolve, reject) => { + console.log('bar:foo task'); + resolve(); + }); + }); + + desc('The bar:promise task has no prerequisites, is async, returns Q-based promise.'); + task('promise', function () { + return Q() + .then(function () { + console.log('bar:promise task'); + return 123654; + }); + }); + + desc('The bar:dependOnpromise task waits for a promise based async test'); + task('dependOnpromise', ['promise'], function () { + console.log('bar:dependOnpromise task saw value', jake.Task["bar:promise"].value); + }); + + desc('The bar:brokenPromise task is a failing Q-promise based async task.'); + task('brokenPromise', function () { + return Q() + .then(function () { + throw new Error("nom nom nom"); + }); + }); + + desc('The bar:bar task, has the async bar:foo task as a prerequisite.'); + task('bar', ['bar:foo'], function () { + console.log('bar:bar task'); + }); + +}); + +namespace('hoge', function () { + desc('The hoge:hoge task, has no prerequisites.'); + task('hoge', function () { + console.log('hoge:hoge task'); + }); + + desc('The hoge:piyo task, has no prerequisites.'); + task('piyo', function () { + console.log('hoge:piyo task'); + }); + + desc('The hoge:fuga task, has hoge:hoge and hoge:piyo as prerequisites.'); + task('fuga', ['hoge:hoge', 'hoge:piyo'], function () { + console.log('hoge:fuga task'); + }); + + desc('The hoge:charan task, has hoge:fuga as a prerequisite.'); + task('charan', ['hoge:fuga'], function () { + console.log('hoge:charan task'); + }); + + desc('The hoge:gero task, has hoge:fuga as a prerequisite.'); + task('gero', ['hoge:fuga'], function () { + console.log('hoge:gero task'); + }); + + desc('The hoge:kira task, has hoge:charan and hoge:gero as prerequisites.'); + task('kira', ['hoge:charan', 'hoge:gero'], function () { + console.log('hoge:kira task'); + }); + +}); + +namespace('fileTest', function () { + directory('foo'); + + desc('File task, concatenating two files together'); + file('foo/concat.txt', ['fileTest:foo', 'fileTest:foo/src1.txt', 'fileTest:foo/src2.txt'], function () { + console.log('fileTest:foo/concat.txt task'); + let data1 = fs.readFileSync('foo/src1.txt'); + let data2 = fs.readFileSync('foo/src2.txt'); + fs.writeFileSync('foo/concat.txt', data1 + data2); + }); + + desc('File task, async creation with writeFile'); + file('foo/src1.txt', function () { + return new Promise(function (resolve, reject) { + fs.writeFile('foo/src1.txt', 'src1', function (err) { + if (err) { + reject(err); + } + else { + console.log('fileTest:foo/src1.txt task'); + resolve(); + } + }); + }); + }); + + desc('File task, sync creation with writeFileSync'); + file('foo/src2.txt', ['default'], function () { + fs.writeFileSync('foo/src2.txt', 'src2'); + console.log('fileTest:foo/src2.txt task'); + }); + + desc('File task, do not run unless the prereq file changes'); + file('foo/from-src1.txt', ['fileTest:foo', 'fileTest:foo/src1.txt'], function () { + let data = fs.readFileSync('foo/src1.txt').toString(); + fs.writeFileSync('foo/from-src1.txt', data); + console.log('fileTest:foo/from-src1.txt task'); + }); + + desc('File task, run if the prereq file changes'); + task('touch-prereq', function () { + fs.writeFileSync('foo/prereq.txt', 'UPDATED'); + }); + + desc('File task, has a preexisting file (with no associated task) as a prereq'); + file('foo/from-prereq.txt', ['fileTest:foo', 'foo/prereq.txt'], function () { + let data = fs.readFileSync('foo/prereq.txt'); + fs.writeFileSync('foo/from-prereq.txt', data); + console.log('fileTest:foo/from-prereq.txt task'); + }); + + directory('foo/bar/baz'); + + desc('Write a file in a nested subdirectory'); + file('foo/bar/baz/bamf.txt', ['foo/bar/baz'], function () { + fs.writeFileSync('foo/bar/baz/bamf.txt', 'w00t'); + }); + + file('foo/output1.txt', ['foo'], () => { + fs.writeFileSync('foo/output1.txt', 'Contents of foo/output1.txt'); + }); + + file('foo/output2a.txt', ['foo/output1.txt'], () => { + fs.writeFileSync('foo/output2a.txt', 'Contents of foo/output2a.txt'); + }); + + file('foo/output2b.txt', ['foo/output1.txt'], () => { + fs.writeFileSync('foo/output2b.txt', 'Contents of foo/output2b.txt'); + }); + + file('foo/output3.txt', [ 'foo/output2a.txt', 'foo/output2b.txt'], () => { + fs.writeFileSync('foo/output3.txt', 'w00t'); + }); +}); + +task('blammo'); +// Define task +task('voom', ['blammo'], function () { + console.log(this.prereqs.length); +}); + +// Modify, add a prereq +task('voom', ['noActionNoPrereqs']); + +namespace('vronk', function () { + task('groo', function () { + let t = jake.Task['vronk:zong']; + t.addListener('error', function (e) { + console.log(e.message); + }); + t.invoke(); + }); + task('zong', function () { + throw new Error('OMFGZONG'); + }); +}); + +// define namespace +namespace('one', function () { + task('one', function () { + console.log('one:one'); + }); +}); + +// modify namespace (add task) +namespace('one', function () { + task('two', ['one:one'], function () { + console.log('one:two'); + }); +}); + +task('selfdepconst', [], function () { + task('selfdep', ['selfdep'], function () { + console.log("I made a task that depends on itself"); + }); +}); +task('selfdepdyn', function () { + task('selfdeppar', [], {concurrency: 2}, function () { + console.log("I will depend on myself and will fail at runtime"); + }); + task('selfdeppar', ['selfdeppar']); + jake.Task['selfdeppar'].invoke(); +}); + +namespace("large", function () { + task("leaf", function () { + console.log("large:leaf"); + }); + + const same = []; + for (let i = 0; i < 2000; i++) { + same.push("leaf"); + } + + desc("Task with a large number of same prereqs"); + task("same", same, { concurrency: 2 }, function () { + console.log("large:same"); + }); + + const different = []; + for (let i = 0; i < 2000; i++) { + const name = "leaf-" + i; + task(name, function () { + if (name === "leaf-12" || name === "leaf-123") { + console.log(name); + } + }); + different.push(name); + } + + desc("Task with a large number of different prereqs"); + task("different", different, { concurrency: 2 } , function () { + console.log("large:different"); + }); +}); diff --git a/node_modules/jake/test/integration/jakelib/concurrent.jake.js b/node_modules/jake/test/integration/jakelib/concurrent.jake.js new file mode 100644 index 0000000..684c86f --- /dev/null +++ b/node_modules/jake/test/integration/jakelib/concurrent.jake.js @@ -0,0 +1,113 @@ + +namespace('concurrent', function () { + task('A', function () { + console.log('Started A'); + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log('Finished A'); + resolve(); + }, 200); + }); + }); + + task('B', function () { + console.log('Started B'); + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log('Finished B'); + resolve(); + }, 50); + }); + }); + + task('C', function () { + console.log('Started C'); + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log('Finished C'); + resolve(); + }, 100); + }); + }); + + task('D', function () { + console.log('Started D'); + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log('Finished D'); + resolve(); + }, 300); + }); + }); + + task('Ba', ['A'], function () { + console.log('Started Ba'); + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log('Finished Ba'); + resolve(); + }, 50); + }); + }); + + task('Afail', function () { + console.log('Started failing task'); + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log('Failing B with error'); + throw new Error('I failed'); + }, 50); + }); + }); + + task('simple1', ['A','B'], {concurrency: 2}, function () { + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve(); + }, 50); + }); + }); + + task('simple2', ['C','D'], {concurrency: 2}, function () { + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve(); + }, 50); + }); + }); + + task('seqconcurrent', ['simple1','simple2'], function () { + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve(); + }, 50); + }); + }); + + task('concurrentconcurrent', ['simple1','simple2'], {concurrency: 2}, function () { + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve(); + }, 50); + }); + }); + + task('subdep', ['A','Ba'], {concurrency: 2}, function () { + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve(); + }, 50); + }); + }); + + task('fail', ['A', 'B', 'Afail'], {concurrency: 3}, function () { + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve(); + }, 50); + }); + }); + +}); + + diff --git a/node_modules/jake/test/integration/jakelib/publish.jake.js b/node_modules/jake/test/integration/jakelib/publish.jake.js new file mode 100644 index 0000000..f8485d1 --- /dev/null +++ b/node_modules/jake/test/integration/jakelib/publish.jake.js @@ -0,0 +1,49 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +const PROJECT_DIR = process.env.PROJECT_DIR; + +let fs = require('fs'); +let { publishTask, rmRf, mkdirP } = require(`${PROJECT_DIR}/lib/jake`); + +fs.writeFileSync('package.json', '{"version": "0.0.1"}'); +mkdirP('tmp_publish'); +fs.writeFileSync('tmp_publish/foo.txt', 'FOO'); + +publishTask('zerb', function () { + this.packageFiles.include([ + 'package.json' + , 'tmp_publish/**' + ]); + this.publishCmd = 'node -p -e "\'%filename\'"'; + this.gitCmd = 'echo'; + this.scheduleDelay = 0; + + this._ensureRepoClean = function () {}; + this._getCurrentBranch = function () { + return 'v0.0'; + }; +}); + +jake.setTaskTimeout(5000); + +jake.Task['publish'].on('complete', function () { + rmRf('tmp_publish', {silent: true}); + rmRf('package.json', {silent: true}); +}); + diff --git a/node_modules/jake/test/integration/jakelib/required_module.jake.js b/node_modules/jake/test/integration/jakelib/required_module.jake.js new file mode 100644 index 0000000..eae666b --- /dev/null +++ b/node_modules/jake/test/integration/jakelib/required_module.jake.js @@ -0,0 +1,10 @@ +let { task, namespace } = require(`${process.env.PROJECT_DIR}/lib/jake`); + +namespace('usingRequire', function () { + task('test', () => { + console.log('howdy test'); + }); +}); + + + diff --git a/node_modules/jake/test/integration/jakelib/rule.jake.js b/node_modules/jake/test/integration/jakelib/rule.jake.js new file mode 100644 index 0000000..8e977dd --- /dev/null +++ b/node_modules/jake/test/integration/jakelib/rule.jake.js @@ -0,0 +1,222 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +const PROJECT_DIR = process.env.PROJECT_DIR; + +let exec = require('child_process').execSync; +let fs = require('fs'); +let util = require('util'); +let { rule, rmRf } = require(`${PROJECT_DIR}/lib/jake`); + +directory('tmpsrc'); +directory('tmpbin'); + +//////////////////////////////////////////////////////////// +// Simple Suffix Rule +file('tmp', ['tmp_init', 'tmp_dep1.o', 'tmp_dep2.o'], function (params) { + console.log('tmp task'); + let data1 = fs.readFileSync('tmp_dep1.o'); + let data2 = fs.readFileSync('tmp_dep2.o'); + fs.writeFileSync('tmp', data1 + data2); +}); + +rule('.o', '.c', function () { + let cmd = util.format('cp %s %s', this.source, this.name); + console.log(cmd + ' task'); + exec(cmd); +}); + +file('tmp_dep1.c', function () { + fs.writeFileSync('tmp_dep1.c', 'src_1'); + console.log('tmp_dep1.c task'); +}); + +// note that tmp_dep2.o depends on tmp_dep2.c, which is a +// static file. +task('tmp_init', function () { + fs.writeFileSync('tmp_dep2.c', 'src_2'); + console.log('tmp_dep2.c task'); +}); +//////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////// +// Pattern Rule +file('tmp_p', ['tmp_init', 'tmp_dep1.oo', 'tmp_dep2.oo'], function (params) { + console.log('tmp pattern task'); + let data1 = fs.readFileSync('tmp_dep1.oo'); + let data2 = fs.readFileSync('tmp_dep2.oo'); + fs.writeFileSync('tmp_p', data1 + data2 + ' pattern'); +}); + +rule('%.oo', '%.c', function () { + let cmd = util.format('cp %s %s', this.source, this.name); + console.log(cmd + ' task'); + exec(cmd); +}); +//////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////// +// Pattern Rule with Folder +// i.e. rule('tmpbin/%.oo', 'tmpsrc/%.c', ... +file('tmp_pf', [ + 'tmp_src_init' + , 'tmpbin' + , 'tmpbin/tmp_dep1.oo' + , 'tmpbin/tmp_dep2.oo' ], function (params) { + console.log('tmp pattern folder task'); + let data1 = fs.readFileSync('tmpbin/tmp_dep1.oo'); + let data2 = fs.readFileSync('tmpbin/tmp_dep2.oo'); + fs.writeFileSync('tmp_pf', data1 + data2 + ' pattern folder'); +}); + +rule('tmpbin/%.oo', 'tmpsrc/%.c', function () { + let cmd = util.format('cp %s %s', this.source, this.name); + console.log(cmd + ' task'); + exec(cmd); +}); + +file('tmpsrc/tmp_dep2.c',['tmpsrc'], function () { + fs.writeFileSync('tmpsrc/tmp_dep2.c', 'src/src_2'); + console.log('tmpsrc/tmp_dep2.c task'); +}); + +// Create static files in folder tmpsrc. +task('tmp_src_init', ['tmpsrc'], function () { + fs.writeFileSync('tmpsrc/tmp_dep1.c', 'src/src_1'); + console.log('tmpsrc/tmp_dep1.c task'); +}); +//////////////////////////////////////////////////////////// + + +//////////////////////////////////////////////////////////// +// Namespace Test. This is a Mixed Test. +// Test for +// - rules belonging to different namespace. +// - rules with folder and pattern +task('tmp_ns', [ + 'tmpbin' + , 'rule:init' + , 'tmpbin/tmp_dep2.oo' // *** This relies on a rule defined before. + , 'rule:tmpbin/dep1.oo' + , 'rule:tmpbin/file2.oo' ], function () { + console.log('tmp pattern folder namespace task'); + let data1 = fs.readFileSync('tmpbin/dep1.oo'); + let data2 = fs.readFileSync('tmpbin/tmp_dep2.oo'); + let data3 = fs.readFileSync('tmpbin/file2.oo'); + fs.writeFileSync('tmp_ns', data1 + data2 + data3 + ' pattern folder namespace'); +}); + +namespace('rule', function () { + task('init', ['tmpsrc'], function () { + fs.writeFileSync('tmpsrc/file2.c', 'src/src_3'); + console.log('tmpsrc/file2.c init task'); + }); + + file('tmpsrc/dep1.c',['tmpsrc'], function () { + fs.writeFileSync('tmpsrc/dep1.c', 'src/src_1'); + console.log('tmpsrc/dep1.c task'); + }, {async: true}); + + rule('tmpbin/%.oo', 'tmpsrc/%.c', function () { + let cmd = util.format('cp %s %s', this.source, this.name); + console.log(cmd + ' ns task'); + exec(cmd); + }); +}); +//////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////// +// Chain rule +// rule('tmpbin/%.pdf', 'tmpbin/%.dvi', function() { ... +// rule('tmpbin/%.dvi', 'tmpsrc/%.tex', ['tmpbin'], function() { ... +task('tmp_cr', [ + 'chainrule:init' + , 'chainrule:tmpbin/file1.pdf' + , 'chainrule:tmpbin/file2.pdf' ], function () { + console.log('tmp chainrule namespace task'); + let data1 = fs.readFileSync('tmpbin/file1.pdf'); + let data2 = fs.readFileSync('tmpbin/file2.pdf'); + fs.writeFileSync('tmp_cr', data1 + data2 + ' chainrule namespace'); +}); + +namespace('chainrule', function () { + task('init', ['tmpsrc', 'tmpbin'], function () { + fs.writeFileSync('tmpsrc/file1.tex', 'tex1 '); + fs.writeFileSync('tmpsrc/file2.tex', 'tex2 '); + console.log('chainrule init task'); + }); + + rule('tmpbin/%.pdf', 'tmpbin/%.dvi', function () { + let cmd = util.format('cp %s %s', this.source, this.name); + console.log(cmd + ' dvi->pdf task'); + exec(cmd); + }); + + rule('tmpbin/%.dvi', 'tmpsrc/%.tex', ['tmpbin'], function () { + let cmd = util.format('cp %s %s', this.source, this.name); + console.log(cmd + ' tex->dvi task'); + exec(cmd); + }); +}); +//////////////////////////////////////////////////////////// +namespace('precedence', function () { + task('test', ['foo.html'], function () { + console.log('ran test'); + }); + + rule('.html', '.txt', function () { + console.log('created html'); + let data = fs.readFileSync(this.source); + fs.writeFileSync(this.name, data.toString()); + }); +}); + +namespace('regexPattern', function () { + task('test', ['foo.html'], function () { + console.log('ran test'); + }); + + rule(/\.html$/, '.txt', function () { + console.log('created html'); + let data = fs.readFileSync(this.source); + fs.writeFileSync(this.name, data.toString()); + }); +}); + +namespace('sourceFunction', function () { + + let srcFunc = function (taskName) { + return taskName.replace(/\.[^.]+$/, '.txt'); + }; + + task('test', ['foo.html'], function () { + console.log('ran test'); + }); + + rule('.html', srcFunc, function () { + console.log('created html'); + let data = fs.readFileSync(this.source); + fs.writeFileSync(this.name, data.toString()); + }); +}); + +//////////////////////////////////////////////////////////// +task('clean', function () { + rmRf('./foo'); + rmRf('./tmp'); +}); diff --git a/node_modules/jake/test/integration/list_tasks.js b/node_modules/jake/test/integration/list_tasks.js new file mode 100644 index 0000000..c21d030 --- /dev/null +++ b/node_modules/jake/test/integration/list_tasks.js @@ -0,0 +1,15 @@ +const PROJECT_DIR = process.env.PROJECT_DIR; +const JAKE_CMD = `${PROJECT_DIR}/bin/cli.js`; + +let assert = require('assert'); +let proc = require('child_process'); + +suite('listTasks', function () { + test('execute "jake -T" without any errors', function () { + let message = 'cannot run "jake -T" command'; + let listTasks = function () { + proc.execFileSync(JAKE_CMD, ['-T']); + }; + assert.doesNotThrow(listTasks, TypeError, message); + }); +}); diff --git a/node_modules/jake/test/integration/publish_task.js b/node_modules/jake/test/integration/publish_task.js new file mode 100644 index 0000000..a941b30 --- /dev/null +++ b/node_modules/jake/test/integration/publish_task.js @@ -0,0 +1,27 @@ +let assert = require('assert'); +let exec = require('child_process').execSync; + +const PROJECT_DIR = process.env.PROJECT_DIR; +const JAKE_CMD = `${PROJECT_DIR}/bin/cli.js`; + +suite('publishTask', function () { + + this.timeout(7000); + + test('default task', function () { + let out = exec(`${JAKE_CMD} -q publish`).toString().trim(); + let expected = [ + 'Fetched remote tags.' + , 'On branch v0.0' + , 'Bumped version number to v0.0.2.' + , 'Created package for zerb v0.0.2' + , 'Publishing zerb v0.0.2' + , './pkg/zerb-v0.0.2.tar.gz' + , 'BOOM! Published.' + , 'Cleaned up package' + ].join('\n'); + assert.equal(expected, out); + }); + +}); + diff --git a/node_modules/jake/test/integration/rule.js b/node_modules/jake/test/integration/rule.js new file mode 100644 index 0000000..468db01 --- /dev/null +++ b/node_modules/jake/test/integration/rule.js @@ -0,0 +1,217 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +const PROJECT_DIR = process.env.PROJECT_DIR; +const JAKE_CMD = `${PROJECT_DIR}/bin/cli.js`; + +let assert = require('assert'); +let exec = require('child_process').execSync; +let fs = require('fs'); +let { Rule } = require(`${PROJECT_DIR}/lib/rule`); +let { rmRf } = require(`${PROJECT_DIR}/lib/jake`); + +let cleanUpAndNext = function (callback) { + // Gotta add globbing to file utils rmRf + let tmpFiles = [ + 'tmp' + , 'tmp_ns' + , 'tmp_cr' + , 'tmp_p' + , 'tmp_pf' + , 'tmpbin' + , 'tmpsrc' + , 'tmp_dep1.c' + , 'tmp_dep1.o' + , 'tmp_dep1.oo' + , 'tmp_dep2.c' + , 'tmp_dep2.o' + , 'tmp_dep2.oo' + , 'foo' + , 'foo.html' + ]; + tmpFiles.forEach(function (f) { + rmRf(f, { + silent: true + }); + }); + callback && callback(); +}; + +suite('rule', function () { + + this.timeout(7000); + + setup(function (next) { + cleanUpAndNext(next); + }); + + + // - name foo:bin/main.o + // - pattern bin/%.o + // - source src/%.c + // + // return { + // 'dep' : 'foo:src/main.c', + // 'file': 'src/main.c' + // }; + test('Rule.getSource', function () { + let src = Rule.getSource('foo:bin/main.o', 'bin/%.o', 'src/%.c'); + assert.equal('foo:src/main.c', src); + }); + + test('rule w/o pattern', function () { + let out = exec( `${JAKE_CMD} -q tmp`).toString().trim(); + let output = [ + "tmp_dep2.c task" + , "tmp_dep1.c task" + , "cp tmp_dep1.c tmp_dep1.o task" + , "cp tmp_dep2.c tmp_dep2.o task" + , "tmp task"]; + assert.equal( output.join('\n'), out); + let data = fs.readFileSync(process.cwd() + '/tmp'); + assert.equal('src_1src_2', data.toString()); + cleanUpAndNext(); + }); + + test('rule w pattern w/o folder w/o namespace', function () { + let out = exec( `${JAKE_CMD} -q tmp_p`).toString().trim(); + let output = [ + "tmp_dep2.c task" + , "tmp_dep1.c task" + , "cp tmp_dep1.c tmp_dep1.oo task" + , "cp tmp_dep2.c tmp_dep2.oo task" + , "tmp pattern task"]; + let data; + assert.equal( output.join('\n'), out); + data = fs.readFileSync(process.cwd() + '/tmp_p'); + assert.equal('src_1src_2 pattern', data.toString()); + cleanUpAndNext(); + }); + + test('rule w pattern w folder w/o namespace', function () { + let out = exec( `${JAKE_CMD} -q tmp_pf`).toString().trim(); + let output = [ + "tmpsrc/tmp_dep1.c task" + , "cp tmpsrc/tmp_dep1.c tmpbin/tmp_dep1.oo task" + , "tmpsrc/tmp_dep2.c task" + , "cp tmpsrc/tmp_dep2.c tmpbin/tmp_dep2.oo task" + , "tmp pattern folder task"]; + let data; + assert.equal( output.join('\n'), out); + data = fs.readFileSync(process.cwd() + '/tmp_pf'); + assert.equal('src/src_1src/src_2 pattern folder', data.toString()); + cleanUpAndNext(); + }); + + test.skip('rule w pattern w folder w namespace', function () { + let out = exec( `${JAKE_CMD} -q tmp_ns`).toString().trim(); + let output = [ + "tmpsrc/file2.c init task" // yes + , "tmpsrc/tmp_dep2.c task" // no + , "cp tmpsrc/tmp_dep2.c tmpbin/tmp_dep2.oo task" // no + , "tmpsrc/dep1.c task" // no + , "cp tmpsrc/dep1.c tmpbin/dep1.oo ns task" // no + , "cp tmpsrc/file2.c tmpbin/file2.oo ns task" // yes + , "tmp pattern folder namespace task"]; // yes + let data; + assert.equal( output.join('\n'), out); + data = fs.readFileSync(process.cwd() + '/tmp_ns'); + assert.equal('src/src_1src/src_2src/src_3 pattern folder namespace', data.toString()); + cleanUpAndNext(); + }); + + test.skip('rule w chain w pattern w folder w namespace', function () { + let out = exec( `${JAKE_CMD} -q tmp_cr`).toString().trim(); + let output = [ + "chainrule init task" + , "cp tmpsrc/file1.tex tmpbin/file1.dvi tex->dvi task" + , "cp tmpbin/file1.dvi tmpbin/file1.pdf dvi->pdf task" + , "cp tmpsrc/file2.tex tmpbin/file2.dvi tex->dvi task" + , "cp tmpbin/file2.dvi tmpbin/file2.pdf dvi->pdf task" + , "tmp chainrule namespace task"]; + let data; + assert.equal( output.join('\n'), out); + data = fs.readFileSync(process.cwd() + '/tmp_cr'); + assert.equal('tex1 tex2 chainrule namespace', data.toString()); + cleanUpAndNext(); + }); + + + ['precedence', 'regexPattern', 'sourceFunction'].forEach(function (key) { + + test('rule with source file not created yet (' + key + ')', function () { + let write = process.stderr.write; + process.stderr.write = () => {}; + rmRf('foo.txt', {silent: true}); + rmRf('foo.html', {silent: true}); + try { + exec(`${JAKE_CMD} ` + key + ':test'); + } + catch(err) { + // foo.txt prereq doesn't exist yet + assert.ok(err.message.indexOf('Unknown task "foo.html"') > -1); + } + process.stderr.write = write; + }); + + test('rule with source file now created (' + key + ')', function () { + fs.writeFileSync('foo.txt', ''); + let out = exec(`${JAKE_CMD} -q ` + key + ':test').toString().trim(); + // Should run prereq and test task + let output = [ + 'created html' + , 'ran test' + ]; + assert.equal(output.join('\n'), out); + }); + + test('rule with source file modified (' + key + ')', function (next) { + setTimeout(function () { + fs.writeFileSync('foo.txt', ''); + let out = exec(`${JAKE_CMD} -q ` + key + ':test').toString().trim(); + // Should again run both prereq and test task + let output = [ + 'created html' + , 'ran test' + ]; + assert.equal(output.join('\n'), out); + //next(); + cleanUpAndNext(next); + }, 1000); // Wait to do the touch to ensure mod-time is different + }); + + test('rule with existing objective file and no source ' + + ' (should be normal file-task) (' + key + ')', function () { + // Remove just the source file + fs.writeFileSync('foo.html', ''); + rmRf('foo.txt', {silent: true}); + let out = exec(`${JAKE_CMD} -q ` + key + ':test').toString().trim(); + // Should treat existing objective file as plain file-task, + // and just run test-task + let output = [ + 'ran test' + ]; + assert.equal(output.join('\n'), out); + cleanUpAndNext(); + }); + + }); + +}); + + diff --git a/node_modules/jake/test/integration/selfdep.js b/node_modules/jake/test/integration/selfdep.js new file mode 100644 index 0000000..3195d08 --- /dev/null +++ b/node_modules/jake/test/integration/selfdep.js @@ -0,0 +1,42 @@ +let assert = require('assert'); +let exec = require('child_process').execSync; + +const PROJECT_DIR = process.env.PROJECT_DIR; +const JAKE_CMD = `${PROJECT_DIR}/bin/cli.js`; + +suite('selfDep', function () { + + this.timeout(7000); + + let origStderrWrite; + + setup(function () { + origStderrWrite = process.stderr.write; + process.stderr.write = function () {}; + }); + + teardown(function () { + process.stderr.write = origStderrWrite; + }); + + test('self dep const', function () { + try { + exec(`${JAKE_CMD} selfdepconst`); + } + catch(e) { + assert(e.message.indexOf('dependency of itself') > -1); + } + }); + + test('self dep dyn', function () { + try { + exec(`${JAKE_CMD} selfdepdyn`); + } + catch(e) { + assert(e.message.indexOf('dependency of itself') > -1); + } + }); + +}); + + diff --git a/node_modules/jake/test/integration/task_base.js b/node_modules/jake/test/integration/task_base.js new file mode 100644 index 0000000..9aa501d --- /dev/null +++ b/node_modules/jake/test/integration/task_base.js @@ -0,0 +1,167 @@ +let assert = require('assert'); +let h = require('./helpers'); +let exec = require('child_process').execSync; + +const PROJECT_DIR = process.env.PROJECT_DIR; +const JAKE_CMD = `${PROJECT_DIR}/bin/cli.js`; + +suite('taskBase', function () { + + this.timeout(7000); + + test('default task', function () { + let out; + out = exec(`${JAKE_CMD} -q`).toString().trim(); + assert.equal(out, 'default task'); + out = exec(`${JAKE_CMD} -q default`).toString().trim(); + assert.equal(out, 'default task'); + }); + + test('task with no action', function () { + let out = exec(`${JAKE_CMD} -q noAction`).toString().trim(); + assert.equal(out, 'default task'); + }); + + test('a task with no action and no prereqs', function () { + exec(`${JAKE_CMD} noActionNoPrereqs`); + }); + + test('a task that exists at the top-level, and not in the specified namespace, should error', function () { + let res = require('child_process').spawnSync(`${JAKE_CMD}`, + ['asdfasdfasdf:zerbofrangazoomy']); + let err = res.stderr.toString(); + assert.ok(err.indexOf('Unknown task' > -1)); + }); + + test('passing args to a task', function () { + let out = exec(`${JAKE_CMD} -q argsEnvVars[foo,bar]`).toString().trim(); + let parsed = h.parse(out); + let args = parsed.args; + assert.equal(args[0], 'foo'); + assert.equal(args[1], 'bar'); + }); + + test('a task with environment vars', function () { + let out = exec(`${JAKE_CMD} -q argsEnvVars foo=bar baz=qux`).toString().trim(); + let parsed = h.parse(out); + let env = parsed.env; + assert.equal(env.foo, 'bar'); + assert.equal(env.baz, 'qux'); + }); + + test('passing args and using environment vars', function () { + let out = exec(`${JAKE_CMD} -q argsEnvVars[foo,bar] foo=bar baz=qux`).toString().trim(); + let parsed = h.parse(out); + let args = parsed.args; + let env = parsed.env; + assert.equal(args[0], 'foo'); + assert.equal(args[1], 'bar'); + assert.equal(env.foo, 'bar'); + assert.equal(env.baz, 'qux'); + }); + + test('a simple prereq', function () { + let out = exec(`${JAKE_CMD} -q foo:baz`).toString().trim(); + assert.equal(out, 'foo:bar task\nfoo:baz task'); + }); + + test('a duplicate prereq only runs once', function () { + let out = exec(`${JAKE_CMD} -q foo:asdf`).toString().trim(); + assert.equal(out, 'foo:bar task\nfoo:baz task\nfoo:asdf task'); + }); + + test('a prereq with command-line args', function () { + let out = exec(`${JAKE_CMD} -q foo:qux`).toString().trim(); + assert.equal(out, 'foo:bar[asdf,qwer] task\nfoo:qux task'); + }); + + test('a prereq with args via invoke', function () { + let out = exec(`${JAKE_CMD} -q foo:frang[zxcv,uiop]`).toString().trim(); + assert.equal(out, 'foo:bar[zxcv,uiop] task\nfoo:frang task'); + }); + + test('a prereq with args via execute', function () { + let out = exec(`${JAKE_CMD} -q foo:zerb[zxcv,uiop]`).toString().trim(); + assert.equal(out, 'foo:bar[zxcv,uiop] task\nfoo:zerb task'); + }); + + test('repeating the task via execute', function () { + let out = exec(`${JAKE_CMD} -q foo:voom`).toString().trim(); + assert.equal(out, 'foo:bar task\nfoo:bar task\ncomplete\ncomplete'); + }); + + test('prereq execution-order', function () { + let out = exec(`${JAKE_CMD} -q hoge:fuga`).toString().trim(); + assert.equal(out, 'hoge:hoge task\nhoge:piyo task\nhoge:fuga task'); + }); + + test('basic async task', function () { + let out = exec(`${JAKE_CMD} -q bar:bar`).toString().trim(); + assert.equal(out, 'bar:foo task\nbar:bar task'); + }); + + test('promise async task', function () { + let out = exec(`${JAKE_CMD} -q bar:dependOnpromise`).toString().trim(); + assert.equal(out, 'bar:promise task\nbar:dependOnpromise task saw value 123654'); + }); + + test('failing promise async task', function () { + try { + exec(`${JAKE_CMD} -q bar:brokenPromise`); + } + catch(e) { + assert(e.message.indexOf('Command failed') > -1); + } + }); + + test('that current-prereq index gets reset', function () { + let out = exec(`${JAKE_CMD} -q hoge:kira`).toString().trim(); + assert.equal(out, 'hoge:hoge task\nhoge:piyo task\nhoge:fuga task\n' + + 'hoge:charan task\nhoge:gero task\nhoge:kira task'); + }); + + test('modifying a task by adding prereq during execution', function () { + let out = exec(`${JAKE_CMD} -q voom`).toString().trim(); + assert.equal(out, 2); + }); + + test('listening for task error-event', function () { + try { + exec(`${JAKE_CMD} -q vronk:groo`).toString().trim(); + } + catch(e) { + assert(e.message.indexOf('OMFGZONG') > -1); + } + }); + + test('listening for jake error-event', function () { + let out = exec(`${JAKE_CMD} -q throwy`).toString().trim(); + assert(out.indexOf('Emitted\nError: I am bad') > -1); + }); + + test('listening for jake unhandledRejection-event', function () { + let out = exec(`${JAKE_CMD} -q promiseRejecter`).toString().trim(); + assert.equal(out, ''); + }); + + test('large number of same prereqs', function () { + let out = exec(`${JAKE_CMD} -q large:same`).toString().trim(); + assert.equal(out, 'large:leaf\nlarge:same'); + }); + + test('large number of different prereqs', function () { + let out = exec(`${JAKE_CMD} -q large:different`).toString().trim(); + assert.equal(out, 'leaf-12\nleaf-123\nlarge:different'); + }); + + test('large number of different prereqs', function () { + let out = exec(`${JAKE_CMD} -q usingRequire:test`).toString().trim(); + assert.equal(out, 'howdy test'); + }); + + test('modifying a namespace by adding a new task', function () { + let out = exec(`${JAKE_CMD} -q one:two`).toString().trim(); + assert.equal('one:one\none:two', out); + }); + +}); diff --git a/node_modules/jake/test/unit/jakefile.js b/node_modules/jake/test/unit/jakefile.js new file mode 100644 index 0000000..89ff523 --- /dev/null +++ b/node_modules/jake/test/unit/jakefile.js @@ -0,0 +1,36 @@ + +task('foo', function () { + console.log('ran top-level foo'); +}); + +task('bar', function () { + console.log('ran top-level bar'); +}); + +task('zerb', function () { + console.log('ran zerb'); +}); + +namespace('zooby', function () { + task('zerp', function () {}); + + task('derp', ['zerp'], function () {}); + + namespace('frang', function () { + + namespace('w00t', function () { + task('bar', function () { + console.log('ran zooby:frang:w00t:bar'); + }); + }); + + task('asdf', function () {}); + }); + +}); + +namespace('hurr', function () { + namespace('durr'); +}); + + diff --git a/node_modules/jake/test/unit/namespace.js b/node_modules/jake/test/unit/namespace.js new file mode 100644 index 0000000..c6b3ff5 --- /dev/null +++ b/node_modules/jake/test/unit/namespace.js @@ -0,0 +1,77 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +const PROJECT_DIR = process.env.PROJECT_DIR; + +// Load the jake global +require(`${PROJECT_DIR}/lib/jake`); +let { Namespace } = require(`${PROJECT_DIR}/lib/namespace`); + +require('./jakefile'); + +let assert = require('assert'); + +suite('namespace', function () { + + this.timeout(7000); + + test('resolve namespace by relative name', function () { + let aaa, bbb, ccc; + aaa = namespace('aaa', function () { + bbb = namespace('bbb', function () { + ccc = namespace('ccc', function () { + }); + }); + }); + + assert.ok(aaa, Namespace.ROOT_NAMESPACE.resolveNamespace('aaa')); + assert.ok(bbb === aaa.resolveNamespace('bbb')); + assert.ok(ccc === aaa.resolveNamespace('bbb:ccc')); + }); + + test('resolve task in sub-namespace by relative path', function () { + let curr = Namespace.ROOT_NAMESPACE.resolveNamespace('zooby'); + let task = curr.resolveTask('frang:w00t:bar'); + assert.ok(task.action.toString().indexOf('zooby:frang:w00t:bar') > -1); + }); + + test('prefer local to top-level', function () { + let curr = Namespace.ROOT_NAMESPACE.resolveNamespace('zooby:frang:w00t'); + let task = curr.resolveTask('bar'); + assert.ok(task.action.toString().indexOf('zooby:frang:w00t:bar') > -1); + }); + + test('does resolve top-level', function () { + let curr = Namespace.ROOT_NAMESPACE.resolveNamespace('zooby:frang:w00t'); + let task = curr.resolveTask('foo'); + assert.ok(task.action.toString().indexOf('top-level foo') > -1); + }); + + test('absolute lookup works from sub-namespaces', function () { + let curr = Namespace.ROOT_NAMESPACE.resolveNamespace('hurr:durr'); + let task = curr.resolveTask('zooby:frang:w00t:bar'); + assert.ok(task.action.toString().indexOf('zooby:frang:w00t:bar') > -1); + }); + + test('resolution miss with throw error', function () { + let curr = Namespace.ROOT_NAMESPACE; + let task = curr.resolveTask('asdf:qwer'); + assert.ok(!task); + }); + +}); diff --git a/node_modules/jake/test/unit/parseargs.js b/node_modules/jake/test/unit/parseargs.js new file mode 100644 index 0000000..7a3ddd5 --- /dev/null +++ b/node_modules/jake/test/unit/parseargs.js @@ -0,0 +1,169 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +const PROJECT_DIR = process.env.PROJECT_DIR; + +let parseargs = require(`${PROJECT_DIR}/lib/parseargs`); +let assert = require('assert'); +let optsReg = [ + { full: 'directory', + abbr: 'C', + preempts: false, + expectValue: true + }, + { full: 'jakefile', + abbr: 'f', + preempts: false, + expectValue: true + }, + { full: 'tasks', + abbr: 'T', + preempts: true + }, + { full: 'tasks', + abbr: 'ls', + preempts: true + }, + { full: 'trace', + abbr: 't', + preempts: false, + expectValue: false + }, + { full: 'help', + abbr: 'h', + preempts: true + }, + { full: 'version', + abbr: 'V', + preempts: true + } +]; +let p = new parseargs.Parser(optsReg); +let z = function (s) { return s.split(' '); }; +let res; + +suite('parseargs', function () { + + test('long preemptive opt and val with equal-sign, ignore further opts', function () { + res = p.parse(z('--tasks=foo --jakefile=asdf')); + assert.equal('foo', res.opts.tasks); + assert.equal(undefined, res.opts.jakefile); + }); + + test('long preemptive opt and val without equal-sign, ignore further opts', function () { + res = p.parse(z('--tasks foo --jakefile=asdf')); + assert.equal('foo', res.opts.tasks); + assert.equal(undefined, res.opts.jakefile); + }); + + test('long preemptive opt and no val, ignore further opts', function () { + res = p.parse(z('--tasks --jakefile=asdf')); + assert.equal(true, res.opts.tasks); + assert.equal(undefined, res.opts.jakefile); + }); + + test('preemptive opt with no val, should be true', function () { + res = p.parse(z('-T')); + assert.equal(true, res.opts.tasks); + }); + + test('preemptive opt with no val, should be true and ignore further opts', function () { + res = p.parse(z('-T -f')); + assert.equal(true, res.opts.tasks); + assert.equal(undefined, res.opts.jakefile); + }); + + test('preemptive opt with val, should be val', function () { + res = p.parse(z('-T zoobie -f foo/bar/baz')); + assert.equal('zoobie', res.opts.tasks); + assert.equal(undefined, res.opts.jakefile); + }); + + test('-f expects a value, -t does not (howdy is task-name)', function () { + res = p.parse(z('-f zoobie -t howdy')); + assert.equal('zoobie', res.opts.jakefile); + assert.equal(true, res.opts.trace); + assert.equal('howdy', res.taskNames[0]); + }); + + test('different order, -f expects a value, -t does not (howdy is task-name)', function () { + res = p.parse(z('-f zoobie howdy -t')); + assert.equal('zoobie', res.opts.jakefile); + assert.equal(true, res.opts.trace); + assert.equal('howdy', res.taskNames[0]); + }); + + test('-f expects a value, -t does not (foo=bar is env var)', function () { + res = p.parse(z('-f zoobie -t foo=bar')); + assert.equal('zoobie', res.opts.jakefile); + assert.equal(true, res.opts.trace); + assert.equal('bar', res.envVars.foo); + assert.equal(undefined, res.taskNames[0]); + }); + + test('-f expects a value, -t does not (foo=bar is env-var, task-name follows)', function () { + res = p.parse(z('-f zoobie -t howdy foo=bar')); + assert.equal('zoobie', res.opts.jakefile); + assert.equal(true, res.opts.trace); + assert.equal('bar', res.envVars.foo); + assert.equal('howdy', res.taskNames[0]); + }); + + test('-t does not expect a value, -f does (howdy is task-name)', function () { + res = p.parse(z('-t howdy -f zoobie')); + assert.equal(true, res.opts.trace); + assert.equal('zoobie', res.opts.jakefile); + assert.equal('howdy', res.taskNames[0]); + }); + + test('--trace does not expect a value, -f does (howdy is task-name)', function () { + res = p.parse(z('--trace howdy --jakefile zoobie')); + assert.equal(true, res.opts.trace); + assert.equal('zoobie', res.opts.jakefile); + assert.equal('howdy', res.taskNames[0]); + }); + + test('--trace does not expect a value (equal), -f does (throw howdy away)', function () { + res = p.parse(z('--trace=howdy --jakefile=zoobie')); + assert.equal(true, res.opts.trace); + assert.equal('zoobie', res.opts.jakefile); + assert.equal(undefined, res.taskNames[0]); + }); + + /* +, test('task-name with positional args', function () { + res = p.parse(z('foo:bar[asdf,qwer]')); + assert.equal('asdf', p.taskArgs[0]); + assert.equal('qwer', p.taskArgs[1]); + } + +, test('opts, env vars, task-name with positional args', function () { + res = p.parse(z('-f ./tests/Jakefile -t default[asdf,qwer] foo=bar')); + assert.equal('./tests/Jakefile', res.opts.jakefile); + assert.equal(true, res.opts.trace); + assert.equal('bar', res.envVars.foo); + assert.equal('default', res.taskName); + assert.equal('asdf', p.taskArgs[0]); + assert.equal('qwer', p.taskArgs[1]); + } +*/ + + +}); + + diff --git a/node_modules/jake/usage.txt b/node_modules/jake/usage.txt new file mode 100644 index 0000000..40395c5 --- /dev/null +++ b/node_modules/jake/usage.txt @@ -0,0 +1,17 @@ +Jake JavaScript build tool +******************************************************************************** +If no flags are given, Jake looks for a Jakefile or Jakefile.js in the current directory. +******************************************************************************** +{Usage}: jake [options ...] [env variables ...] target + +{Options}: + -f, --jakefile FILE Use FILE as the Jakefile. + -C, --directory DIRECTORY Change to DIRECTORY before running tasks. + -q, --quiet Do not log messages to standard output. + -B, --always-make Unconditionally make all targets. + -T/-ls, --tasks Display the tasks (matching optional PATTERN) with descriptions, then exit. + -J, --jakelibdir JAKELIBDIR Auto-import any .jake files in JAKELIBDIR. (default is \'jakelib\') + -h, --help Display this help message. + -V/-v, --version Display the Jake version. + -ar, --allow-rejection Keep running even after unhandled promise rejection. + diff --git a/node_modules/jsonwebtoken/LICENSE b/node_modules/jsonwebtoken/LICENSE new file mode 100644 index 0000000..bcd1854 --- /dev/null +++ b/node_modules/jsonwebtoken/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Auth0, Inc. (http://auth0.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jsonwebtoken/README.md b/node_modules/jsonwebtoken/README.md new file mode 100644 index 0000000..4e20dd9 --- /dev/null +++ b/node_modules/jsonwebtoken/README.md @@ -0,0 +1,396 @@ +# jsonwebtoken + +| **Build** | **Dependency** | +|-----------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------| +| [![Build Status](https://secure.travis-ci.org/auth0/node-jsonwebtoken.svg?branch=master)](http://travis-ci.org/auth0/node-jsonwebtoken) | [![Dependency Status](https://david-dm.org/auth0/node-jsonwebtoken.svg)](https://david-dm.org/auth0/node-jsonwebtoken) | + + +An implementation of [JSON Web Tokens](https://tools.ietf.org/html/rfc7519). + +This was developed against `draft-ietf-oauth-json-web-token-08`. It makes use of [node-jws](https://github.com/brianloveswords/node-jws) + +# Install + +```bash +$ npm install jsonwebtoken +``` + +# Migration notes + +* [From v8 to v9](https://github.com/auth0/node-jsonwebtoken/wiki/Migration-Notes:-v8-to-v9) +* [From v7 to v8](https://github.com/auth0/node-jsonwebtoken/wiki/Migration-Notes:-v7-to-v8) + +# Usage + +### jwt.sign(payload, secretOrPrivateKey, [options, callback]) + +(Asynchronous) If a callback is supplied, the callback is called with the `err` or the JWT. + +(Synchronous) Returns the JsonWebToken as string + +`payload` could be an object literal, buffer or string representing valid JSON. +> **Please _note_ that** `exp` or any other claim is only set if the payload is an object literal. Buffer or string payloads are not checked for JSON validity. + +> If `payload` is not a buffer or a string, it will be coerced into a string using `JSON.stringify`. + +`secretOrPrivateKey` is a string (utf-8 encoded), buffer, object, or KeyObject containing either the secret for HMAC algorithms or the PEM +encoded private key for RSA and ECDSA. In case of a private key with passphrase an object `{ key, passphrase }` can be used (based on [crypto documentation](https://nodejs.org/api/crypto.html#crypto_sign_sign_private_key_output_format)), in this case be sure you pass the `algorithm` option. +When signing with RSA algorithms the minimum modulus length is 2048 except when the allowInsecureKeySizes option is set to true. Private keys below this size will be rejected with an error. + +`options`: + +* `algorithm` (default: `HS256`) +* `expiresIn`: expressed in seconds or a string describing a time span [vercel/ms](https://github.com/vercel/ms). + > Eg: `60`, `"2 days"`, `"10h"`, `"7d"`. A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default (`"120"` is equal to `"120ms"`). +* `notBefore`: expressed in seconds or a string describing a time span [vercel/ms](https://github.com/vercel/ms). + > Eg: `60`, `"2 days"`, `"10h"`, `"7d"`. A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default (`"120"` is equal to `"120ms"`). +* `audience` +* `issuer` +* `jwtid` +* `subject` +* `noTimestamp` +* `header` +* `keyid` +* `mutatePayload`: if true, the sign function will modify the payload object directly. This is useful if you need a raw reference to the payload after claims have been applied to it but before it has been encoded into a token. +* `allowInsecureKeySizes`: if true allows private keys with a modulus below 2048 to be used for RSA +* `allowInvalidAsymmetricKeyTypes`: if true, allows asymmetric keys which do not match the specified algorithm. This option is intended only for backwards compatability and should be avoided. + + + +> There are no default values for `expiresIn`, `notBefore`, `audience`, `subject`, `issuer`. These claims can also be provided in the payload directly with `exp`, `nbf`, `aud`, `sub` and `iss` respectively, but you **_can't_** include in both places. + +Remember that `exp`, `nbf` and `iat` are **NumericDate**, see related [Token Expiration (exp claim)](#token-expiration-exp-claim) + + +The header can be customized via the `options.header` object. + +Generated jwts will include an `iat` (issued at) claim by default unless `noTimestamp` is specified. If `iat` is inserted in the payload, it will be used instead of the real timestamp for calculating other things like `exp` given a timespan in `options.expiresIn`. + +Synchronous Sign with default (HMAC SHA256) + +```js +var jwt = require('jsonwebtoken'); +var token = jwt.sign({ foo: 'bar' }, 'shhhhh'); +``` + +Synchronous Sign with RSA SHA256 +```js +// sign with RSA SHA256 +var privateKey = fs.readFileSync('private.key'); +var token = jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256' }); +``` + +Sign asynchronously +```js +jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256' }, function(err, token) { + console.log(token); +}); +``` + +Backdate a jwt 30 seconds +```js +var older_token = jwt.sign({ foo: 'bar', iat: Math.floor(Date.now() / 1000) - 30 }, 'shhhhh'); +``` + +#### Token Expiration (exp claim) + +The standard for JWT defines an `exp` claim for expiration. The expiration is represented as a **NumericDate**: + +> A JSON numeric value representing the number of seconds from 1970-01-01T00:00:00Z UTC until the specified UTC date/time, ignoring leap seconds. This is equivalent to the IEEE Std 1003.1, 2013 Edition [POSIX.1] definition "Seconds Since the Epoch", in which each day is accounted for by exactly 86400 seconds, other than that non-integer values can be represented. See RFC 3339 [RFC3339] for details regarding date/times in general and UTC in particular. + +This means that the `exp` field should contain the number of seconds since the epoch. + +Signing a token with 1 hour of expiration: + +```javascript +jwt.sign({ + exp: Math.floor(Date.now() / 1000) + (60 * 60), + data: 'foobar' +}, 'secret'); +``` + +Another way to generate a token like this with this library is: + +```javascript +jwt.sign({ + data: 'foobar' +}, 'secret', { expiresIn: 60 * 60 }); + +//or even better: + +jwt.sign({ + data: 'foobar' +}, 'secret', { expiresIn: '1h' }); +``` + +### jwt.verify(token, secretOrPublicKey, [options, callback]) + +(Asynchronous) If a callback is supplied, function acts asynchronously. The callback is called with the decoded payload if the signature is valid and optional expiration, audience, or issuer are valid. If not, it will be called with the error. + +(Synchronous) If a callback is not supplied, function acts synchronously. Returns the payload decoded if the signature is valid and optional expiration, audience, or issuer are valid. If not, it will throw the error. + +> __Warning:__ When the token comes from an untrusted source (e.g. user input or external requests), the returned decoded payload should be treated like any other user input; please make sure to sanitize and only work with properties that are expected + +`token` is the JsonWebToken string + +`secretOrPublicKey` is a string (utf-8 encoded), buffer, or KeyObject containing either the secret for HMAC algorithms, or the PEM +encoded public key for RSA and ECDSA. +If `jwt.verify` is called asynchronous, `secretOrPublicKey` can be a function that should fetch the secret or public key. See below for a detailed example + +As mentioned in [this comment](https://github.com/auth0/node-jsonwebtoken/issues/208#issuecomment-231861138), there are other libraries that expect base64 encoded secrets (random bytes encoded using base64), if that is your case you can pass `Buffer.from(secret, 'base64')`, by doing this the secret will be decoded using base64 and the token verification will use the original random bytes. + +`options` + +* `algorithms`: List of strings with the names of the allowed algorithms. For instance, `["HS256", "HS384"]`. + > If not specified a defaults will be used based on the type of key provided + > * secret - ['HS256', 'HS384', 'HS512'] + > * rsa - ['RS256', 'RS384', 'RS512'] + > * ec - ['ES256', 'ES384', 'ES512'] + > * default - ['RS256', 'RS384', 'RS512'] +* `audience`: if you want to check audience (`aud`), provide a value here. The audience can be checked against a string, a regular expression or a list of strings and/or regular expressions. + > Eg: `"urn:foo"`, `/urn:f[o]{2}/`, `[/urn:f[o]{2}/, "urn:bar"]` +* `complete`: return an object with the decoded `{ payload, header, signature }` instead of only the usual content of the payload. +* `issuer` (optional): string or array of strings of valid values for the `iss` field. +* `jwtid` (optional): if you want to check JWT ID (`jti`), provide a string value here. +* `ignoreExpiration`: if `true` do not validate the expiration of the token. +* `ignoreNotBefore`... +* `subject`: if you want to check subject (`sub`), provide a value here +* `clockTolerance`: number of seconds to tolerate when checking the `nbf` and `exp` claims, to deal with small clock differences among different servers +* `maxAge`: the maximum allowed age for tokens to still be valid. It is expressed in seconds or a string describing a time span [vercel/ms](https://github.com/vercel/ms). + > Eg: `1000`, `"2 days"`, `"10h"`, `"7d"`. A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default (`"120"` is equal to `"120ms"`). +* `clockTimestamp`: the time in seconds that should be used as the current time for all necessary comparisons. +* `nonce`: if you want to check `nonce` claim, provide a string value here. It is used on Open ID for the ID Tokens. ([Open ID implementation notes](https://openid.net/specs/openid-connect-core-1_0.html#NonceNotes)) +* `allowInvalidAsymmetricKeyTypes`: if true, allows asymmetric keys which do not match the specified algorithm. This option is intended only for backwards compatability and should be avoided. + +```js +// verify a token symmetric - synchronous +var decoded = jwt.verify(token, 'shhhhh'); +console.log(decoded.foo) // bar + +// verify a token symmetric +jwt.verify(token, 'shhhhh', function(err, decoded) { + console.log(decoded.foo) // bar +}); + +// invalid token - synchronous +try { + var decoded = jwt.verify(token, 'wrong-secret'); +} catch(err) { + // err +} + +// invalid token +jwt.verify(token, 'wrong-secret', function(err, decoded) { + // err + // decoded undefined +}); + +// verify a token asymmetric +var cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, function(err, decoded) { + console.log(decoded.foo) // bar +}); + +// verify audience +var cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, { audience: 'urn:foo' }, function(err, decoded) { + // if audience mismatch, err == invalid audience +}); + +// verify issuer +var cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer' }, function(err, decoded) { + // if issuer mismatch, err == invalid issuer +}); + +// verify jwt id +var cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer', jwtid: 'jwtid' }, function(err, decoded) { + // if jwt id mismatch, err == invalid jwt id +}); + +// verify subject +var cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer', jwtid: 'jwtid', subject: 'subject' }, function(err, decoded) { + // if subject mismatch, err == invalid subject +}); + +// alg mismatch +var cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, { algorithms: ['RS256'] }, function (err, payload) { + // if token alg != RS256, err == invalid signature +}); + +// Verify using getKey callback +// Example uses https://github.com/auth0/node-jwks-rsa as a way to fetch the keys. +var jwksClient = require('jwks-rsa'); +var client = jwksClient({ + jwksUri: 'https://sandrino.auth0.com/.well-known/jwks.json' +}); +function getKey(header, callback){ + client.getSigningKey(header.kid, function(err, key) { + var signingKey = key.publicKey || key.rsaPublicKey; + callback(null, signingKey); + }); +} + +jwt.verify(token, getKey, options, function(err, decoded) { + console.log(decoded.foo) // bar +}); + +``` + +
+Need to peek into a JWT without verifying it? (Click to expand) + +### jwt.decode(token [, options]) + +(Synchronous) Returns the decoded payload without verifying if the signature is valid. + +> __Warning:__ This will __not__ verify whether the signature is valid. You should __not__ use this for untrusted messages. You most likely want to use `jwt.verify` instead. + +> __Warning:__ When the token comes from an untrusted source (e.g. user input or external request), the returned decoded payload should be treated like any other user input; please make sure to sanitize and only work with properties that are expected + + +`token` is the JsonWebToken string + +`options`: + +* `json`: force JSON.parse on the payload even if the header doesn't contain `"typ":"JWT"`. +* `complete`: return an object with the decoded payload and header. + +Example + +```js +// get the decoded payload ignoring signature, no secretOrPrivateKey needed +var decoded = jwt.decode(token); + +// get the decoded payload and header +var decoded = jwt.decode(token, {complete: true}); +console.log(decoded.header); +console.log(decoded.payload) +``` + +
+ +## Errors & Codes +Possible thrown errors during verification. +Error is the first argument of the verification callback. + +### TokenExpiredError + +Thrown error if the token is expired. + +Error object: + +* name: 'TokenExpiredError' +* message: 'jwt expired' +* expiredAt: [ExpDate] + +```js +jwt.verify(token, 'shhhhh', function(err, decoded) { + if (err) { + /* + err = { + name: 'TokenExpiredError', + message: 'jwt expired', + expiredAt: 1408621000 + } + */ + } +}); +``` + +### JsonWebTokenError +Error object: + +* name: 'JsonWebTokenError' +* message: + * 'invalid token' - the header or payload could not be parsed + * 'jwt malformed' - the token does not have three components (delimited by a `.`) + * 'jwt signature is required' + * 'invalid signature' + * 'jwt audience invalid. expected: [OPTIONS AUDIENCE]' + * 'jwt issuer invalid. expected: [OPTIONS ISSUER]' + * 'jwt id invalid. expected: [OPTIONS JWT ID]' + * 'jwt subject invalid. expected: [OPTIONS SUBJECT]' + +```js +jwt.verify(token, 'shhhhh', function(err, decoded) { + if (err) { + /* + err = { + name: 'JsonWebTokenError', + message: 'jwt malformed' + } + */ + } +}); +``` + +### NotBeforeError +Thrown if current time is before the nbf claim. + +Error object: + +* name: 'NotBeforeError' +* message: 'jwt not active' +* date: 2018-10-04T16:10:44.000Z + +```js +jwt.verify(token, 'shhhhh', function(err, decoded) { + if (err) { + /* + err = { + name: 'NotBeforeError', + message: 'jwt not active', + date: 2018-10-04T16:10:44.000Z + } + */ + } +}); +``` + + +## Algorithms supported + +Array of supported algorithms. The following algorithms are currently supported. + +| alg Parameter Value | Digital Signature or MAC Algorithm | +|---------------------|------------------------------------------------------------------------| +| HS256 | HMAC using SHA-256 hash algorithm | +| HS384 | HMAC using SHA-384 hash algorithm | +| HS512 | HMAC using SHA-512 hash algorithm | +| RS256 | RSASSA-PKCS1-v1_5 using SHA-256 hash algorithm | +| RS384 | RSASSA-PKCS1-v1_5 using SHA-384 hash algorithm | +| RS512 | RSASSA-PKCS1-v1_5 using SHA-512 hash algorithm | +| PS256 | RSASSA-PSS using SHA-256 hash algorithm (only node ^6.12.0 OR >=8.0.0) | +| PS384 | RSASSA-PSS using SHA-384 hash algorithm (only node ^6.12.0 OR >=8.0.0) | +| PS512 | RSASSA-PSS using SHA-512 hash algorithm (only node ^6.12.0 OR >=8.0.0) | +| ES256 | ECDSA using P-256 curve and SHA-256 hash algorithm | +| ES384 | ECDSA using P-384 curve and SHA-384 hash algorithm | +| ES512 | ECDSA using P-521 curve and SHA-512 hash algorithm | +| none | No digital signature or MAC value included | + +## Refreshing JWTs + +First of all, we recommend you to think carefully if auto-refreshing a JWT will not introduce any vulnerability in your system. + +We are not comfortable including this as part of the library, however, you can take a look at [this example](https://gist.github.com/ziluvatar/a3feb505c4c0ec37059054537b38fc48) to show how this could be accomplished. +Apart from that example there are [an issue](https://github.com/auth0/node-jsonwebtoken/issues/122) and [a pull request](https://github.com/auth0/node-jsonwebtoken/pull/172) to get more knowledge about this topic. + +# TODO + +* X.509 certificate chain is not checked + +## Issue Reporting + +If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The [Responsible Disclosure Program](https://auth0.com/whitehat) details the procedure for disclosing security issues. + +## Author + +[Auth0](https://auth0.com) + +## License + +This project is licensed under the MIT license. See the [LICENSE](LICENSE) file for more info. diff --git a/node_modules/jsonwebtoken/decode.js b/node_modules/jsonwebtoken/decode.js new file mode 100644 index 0000000..8fe1adc --- /dev/null +++ b/node_modules/jsonwebtoken/decode.js @@ -0,0 +1,30 @@ +var jws = require('jws'); + +module.exports = function (jwt, options) { + options = options || {}; + var decoded = jws.decode(jwt, options); + if (!decoded) { return null; } + var payload = decoded.payload; + + //try parse the payload + if(typeof payload === 'string') { + try { + var obj = JSON.parse(payload); + if(obj !== null && typeof obj === 'object') { + payload = obj; + } + } catch (e) { } + } + + //return header if `complete` option is enabled. header includes claims + //such as `kid` and `alg` used to select the key within a JWKS needed to + //verify the signature + if (options.complete === true) { + return { + header: decoded.header, + payload: payload, + signature: decoded.signature + }; + } + return payload; +}; diff --git a/node_modules/jsonwebtoken/index.js b/node_modules/jsonwebtoken/index.js new file mode 100644 index 0000000..161eb2d --- /dev/null +++ b/node_modules/jsonwebtoken/index.js @@ -0,0 +1,8 @@ +module.exports = { + decode: require('./decode'), + verify: require('./verify'), + sign: require('./sign'), + JsonWebTokenError: require('./lib/JsonWebTokenError'), + NotBeforeError: require('./lib/NotBeforeError'), + TokenExpiredError: require('./lib/TokenExpiredError'), +}; diff --git a/node_modules/jsonwebtoken/lib/JsonWebTokenError.js b/node_modules/jsonwebtoken/lib/JsonWebTokenError.js new file mode 100644 index 0000000..e068222 --- /dev/null +++ b/node_modules/jsonwebtoken/lib/JsonWebTokenError.js @@ -0,0 +1,14 @@ +var JsonWebTokenError = function (message, error) { + Error.call(this, message); + if(Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = 'JsonWebTokenError'; + this.message = message; + if (error) this.inner = error; +}; + +JsonWebTokenError.prototype = Object.create(Error.prototype); +JsonWebTokenError.prototype.constructor = JsonWebTokenError; + +module.exports = JsonWebTokenError; diff --git a/node_modules/jsonwebtoken/lib/NotBeforeError.js b/node_modules/jsonwebtoken/lib/NotBeforeError.js new file mode 100644 index 0000000..7b30084 --- /dev/null +++ b/node_modules/jsonwebtoken/lib/NotBeforeError.js @@ -0,0 +1,13 @@ +var JsonWebTokenError = require('./JsonWebTokenError'); + +var NotBeforeError = function (message, date) { + JsonWebTokenError.call(this, message); + this.name = 'NotBeforeError'; + this.date = date; +}; + +NotBeforeError.prototype = Object.create(JsonWebTokenError.prototype); + +NotBeforeError.prototype.constructor = NotBeforeError; + +module.exports = NotBeforeError; \ No newline at end of file diff --git a/node_modules/jsonwebtoken/lib/TokenExpiredError.js b/node_modules/jsonwebtoken/lib/TokenExpiredError.js new file mode 100644 index 0000000..abb704f --- /dev/null +++ b/node_modules/jsonwebtoken/lib/TokenExpiredError.js @@ -0,0 +1,13 @@ +var JsonWebTokenError = require('./JsonWebTokenError'); + +var TokenExpiredError = function (message, expiredAt) { + JsonWebTokenError.call(this, message); + this.name = 'TokenExpiredError'; + this.expiredAt = expiredAt; +}; + +TokenExpiredError.prototype = Object.create(JsonWebTokenError.prototype); + +TokenExpiredError.prototype.constructor = TokenExpiredError; + +module.exports = TokenExpiredError; \ No newline at end of file diff --git a/node_modules/jsonwebtoken/lib/asymmetricKeyDetailsSupported.js b/node_modules/jsonwebtoken/lib/asymmetricKeyDetailsSupported.js new file mode 100644 index 0000000..a6ede56 --- /dev/null +++ b/node_modules/jsonwebtoken/lib/asymmetricKeyDetailsSupported.js @@ -0,0 +1,3 @@ +const semver = require('semver'); + +module.exports = semver.satisfies(process.version, '>=15.7.0'); diff --git a/node_modules/jsonwebtoken/lib/psSupported.js b/node_modules/jsonwebtoken/lib/psSupported.js new file mode 100644 index 0000000..8c04144 --- /dev/null +++ b/node_modules/jsonwebtoken/lib/psSupported.js @@ -0,0 +1,3 @@ +var semver = require('semver'); + +module.exports = semver.satisfies(process.version, '^6.12.0 || >=8.0.0'); diff --git a/node_modules/jsonwebtoken/lib/rsaPssKeyDetailsSupported.js b/node_modules/jsonwebtoken/lib/rsaPssKeyDetailsSupported.js new file mode 100644 index 0000000..7fcf368 --- /dev/null +++ b/node_modules/jsonwebtoken/lib/rsaPssKeyDetailsSupported.js @@ -0,0 +1,3 @@ +const semver = require('semver'); + +module.exports = semver.satisfies(process.version, '>=16.9.0'); diff --git a/node_modules/jsonwebtoken/lib/timespan.js b/node_modules/jsonwebtoken/lib/timespan.js new file mode 100644 index 0000000..e509869 --- /dev/null +++ b/node_modules/jsonwebtoken/lib/timespan.js @@ -0,0 +1,18 @@ +var ms = require('ms'); + +module.exports = function (time, iat) { + var timestamp = iat || Math.floor(Date.now() / 1000); + + if (typeof time === 'string') { + var milliseconds = ms(time); + if (typeof milliseconds === 'undefined') { + return; + } + return Math.floor(timestamp + milliseconds / 1000); + } else if (typeof time === 'number') { + return timestamp + time; + } else { + return; + } + +}; \ No newline at end of file diff --git a/node_modules/jsonwebtoken/lib/validateAsymmetricKey.js b/node_modules/jsonwebtoken/lib/validateAsymmetricKey.js new file mode 100644 index 0000000..c10340b --- /dev/null +++ b/node_modules/jsonwebtoken/lib/validateAsymmetricKey.js @@ -0,0 +1,66 @@ +const ASYMMETRIC_KEY_DETAILS_SUPPORTED = require('./asymmetricKeyDetailsSupported'); +const RSA_PSS_KEY_DETAILS_SUPPORTED = require('./rsaPssKeyDetailsSupported'); + +const allowedAlgorithmsForKeys = { + 'ec': ['ES256', 'ES384', 'ES512'], + 'rsa': ['RS256', 'PS256', 'RS384', 'PS384', 'RS512', 'PS512'], + 'rsa-pss': ['PS256', 'PS384', 'PS512'] +}; + +const allowedCurves = { + ES256: 'prime256v1', + ES384: 'secp384r1', + ES512: 'secp521r1', +}; + +module.exports = function(algorithm, key) { + if (!algorithm || !key) return; + + const keyType = key.asymmetricKeyType; + if (!keyType) return; + + const allowedAlgorithms = allowedAlgorithmsForKeys[keyType]; + + if (!allowedAlgorithms) { + throw new Error(`Unknown key type "${keyType}".`); + } + + if (!allowedAlgorithms.includes(algorithm)) { + throw new Error(`"alg" parameter for "${keyType}" key type must be one of: ${allowedAlgorithms.join(', ')}.`) + } + + /* + * Ignore the next block from test coverage because it gets executed + * conditionally depending on the Node version. Not ignoring it would + * prevent us from reaching the target % of coverage for versions of + * Node under 15.7.0. + */ + /* istanbul ignore next */ + if (ASYMMETRIC_KEY_DETAILS_SUPPORTED) { + switch (keyType) { + case 'ec': + const keyCurve = key.asymmetricKeyDetails.namedCurve; + const allowedCurve = allowedCurves[algorithm]; + + if (keyCurve !== allowedCurve) { + throw new Error(`"alg" parameter "${algorithm}" requires curve "${allowedCurve}".`); + } + break; + + case 'rsa-pss': + if (RSA_PSS_KEY_DETAILS_SUPPORTED) { + const length = parseInt(algorithm.slice(-3), 10); + const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = key.asymmetricKeyDetails; + + if (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm) { + throw new Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${algorithm}.`); + } + + if (saltLength !== undefined && saltLength > length >> 3) { + throw new Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${algorithm}.`) + } + } + break; + } + } +} diff --git a/node_modules/jsonwebtoken/package.json b/node_modules/jsonwebtoken/package.json new file mode 100644 index 0000000..81f78da --- /dev/null +++ b/node_modules/jsonwebtoken/package.json @@ -0,0 +1,71 @@ +{ + "name": "jsonwebtoken", + "version": "9.0.2", + "description": "JSON Web Token implementation (symmetric and asymmetric)", + "main": "index.js", + "nyc": { + "check-coverage": true, + "lines": 95, + "statements": 95, + "functions": 100, + "branches": 95, + "exclude": [ + "./test/**" + ], + "reporter": [ + "json", + "lcov", + "text-summary" + ] + }, + "scripts": { + "lint": "eslint .", + "coverage": "nyc mocha --use_strict", + "test": "npm run lint && npm run coverage && cost-of-modules" + }, + "repository": { + "type": "git", + "url": "https://github.com/auth0/node-jsonwebtoken" + }, + "keywords": [ + "jwt" + ], + "author": "auth0", + "license": "MIT", + "bugs": { + "url": "https://github.com/auth0/node-jsonwebtoken/issues" + }, + "dependencies": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "devDependencies": { + "atob": "^2.1.2", + "chai": "^4.1.2", + "conventional-changelog": "~1.1.0", + "cost-of-modules": "^1.0.1", + "eslint": "^4.19.1", + "mocha": "^5.2.0", + "nsp": "^2.6.2", + "nyc": "^11.9.0", + "sinon": "^6.0.0" + }, + "engines": { + "npm": ">=6", + "node": ">=12" + }, + "files": [ + "lib", + "decode.js", + "sign.js", + "verify.js" + ] +} diff --git a/node_modules/jsonwebtoken/sign.js b/node_modules/jsonwebtoken/sign.js new file mode 100644 index 0000000..82bf526 --- /dev/null +++ b/node_modules/jsonwebtoken/sign.js @@ -0,0 +1,253 @@ +const timespan = require('./lib/timespan'); +const PS_SUPPORTED = require('./lib/psSupported'); +const validateAsymmetricKey = require('./lib/validateAsymmetricKey'); +const jws = require('jws'); +const includes = require('lodash.includes'); +const isBoolean = require('lodash.isboolean'); +const isInteger = require('lodash.isinteger'); +const isNumber = require('lodash.isnumber'); +const isPlainObject = require('lodash.isplainobject'); +const isString = require('lodash.isstring'); +const once = require('lodash.once'); +const { KeyObject, createSecretKey, createPrivateKey } = require('crypto') + +const SUPPORTED_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512', 'HS256', 'HS384', 'HS512', 'none']; +if (PS_SUPPORTED) { + SUPPORTED_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); +} + +const sign_options_schema = { + expiresIn: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"expiresIn" should be a number of seconds or string representing a timespan' }, + notBefore: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"notBefore" should be a number of seconds or string representing a timespan' }, + audience: { isValid: function(value) { return isString(value) || Array.isArray(value); }, message: '"audience" must be a string or array' }, + algorithm: { isValid: includes.bind(null, SUPPORTED_ALGS), message: '"algorithm" must be a valid string enum value' }, + header: { isValid: isPlainObject, message: '"header" must be an object' }, + encoding: { isValid: isString, message: '"encoding" must be a string' }, + issuer: { isValid: isString, message: '"issuer" must be a string' }, + subject: { isValid: isString, message: '"subject" must be a string' }, + jwtid: { isValid: isString, message: '"jwtid" must be a string' }, + noTimestamp: { isValid: isBoolean, message: '"noTimestamp" must be a boolean' }, + keyid: { isValid: isString, message: '"keyid" must be a string' }, + mutatePayload: { isValid: isBoolean, message: '"mutatePayload" must be a boolean' }, + allowInsecureKeySizes: { isValid: isBoolean, message: '"allowInsecureKeySizes" must be a boolean'}, + allowInvalidAsymmetricKeyTypes: { isValid: isBoolean, message: '"allowInvalidAsymmetricKeyTypes" must be a boolean'} +}; + +const registered_claims_schema = { + iat: { isValid: isNumber, message: '"iat" should be a number of seconds' }, + exp: { isValid: isNumber, message: '"exp" should be a number of seconds' }, + nbf: { isValid: isNumber, message: '"nbf" should be a number of seconds' } +}; + +function validate(schema, allowUnknown, object, parameterName) { + if (!isPlainObject(object)) { + throw new Error('Expected "' + parameterName + '" to be a plain object.'); + } + Object.keys(object) + .forEach(function(key) { + const validator = schema[key]; + if (!validator) { + if (!allowUnknown) { + throw new Error('"' + key + '" is not allowed in "' + parameterName + '"'); + } + return; + } + if (!validator.isValid(object[key])) { + throw new Error(validator.message); + } + }); +} + +function validateOptions(options) { + return validate(sign_options_schema, false, options, 'options'); +} + +function validatePayload(payload) { + return validate(registered_claims_schema, true, payload, 'payload'); +} + +const options_to_payload = { + 'audience': 'aud', + 'issuer': 'iss', + 'subject': 'sub', + 'jwtid': 'jti' +}; + +const options_for_objects = [ + 'expiresIn', + 'notBefore', + 'noTimestamp', + 'audience', + 'issuer', + 'subject', + 'jwtid', +]; + +module.exports = function (payload, secretOrPrivateKey, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } else { + options = options || {}; + } + + const isObjectPayload = typeof payload === 'object' && + !Buffer.isBuffer(payload); + + const header = Object.assign({ + alg: options.algorithm || 'HS256', + typ: isObjectPayload ? 'JWT' : undefined, + kid: options.keyid + }, options.header); + + function failure(err) { + if (callback) { + return callback(err); + } + throw err; + } + + if (!secretOrPrivateKey && options.algorithm !== 'none') { + return failure(new Error('secretOrPrivateKey must have a value')); + } + + if (secretOrPrivateKey != null && !(secretOrPrivateKey instanceof KeyObject)) { + try { + secretOrPrivateKey = createPrivateKey(secretOrPrivateKey) + } catch (_) { + try { + secretOrPrivateKey = createSecretKey(typeof secretOrPrivateKey === 'string' ? Buffer.from(secretOrPrivateKey) : secretOrPrivateKey) + } catch (_) { + return failure(new Error('secretOrPrivateKey is not valid key material')); + } + } + } + + if (header.alg.startsWith('HS') && secretOrPrivateKey.type !== 'secret') { + return failure(new Error((`secretOrPrivateKey must be a symmetric key when using ${header.alg}`))) + } else if (/^(?:RS|PS|ES)/.test(header.alg)) { + if (secretOrPrivateKey.type !== 'private') { + return failure(new Error((`secretOrPrivateKey must be an asymmetric key when using ${header.alg}`))) + } + if (!options.allowInsecureKeySizes && + !header.alg.startsWith('ES') && + secretOrPrivateKey.asymmetricKeyDetails !== undefined && //KeyObject.asymmetricKeyDetails is supported in Node 15+ + secretOrPrivateKey.asymmetricKeyDetails.modulusLength < 2048) { + return failure(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`)); + } + } + + if (typeof payload === 'undefined') { + return failure(new Error('payload is required')); + } else if (isObjectPayload) { + try { + validatePayload(payload); + } + catch (error) { + return failure(error); + } + if (!options.mutatePayload) { + payload = Object.assign({},payload); + } + } else { + const invalid_options = options_for_objects.filter(function (opt) { + return typeof options[opt] !== 'undefined'; + }); + + if (invalid_options.length > 0) { + return failure(new Error('invalid ' + invalid_options.join(',') + ' option for ' + (typeof payload ) + ' payload')); + } + } + + if (typeof payload.exp !== 'undefined' && typeof options.expiresIn !== 'undefined') { + return failure(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.')); + } + + if (typeof payload.nbf !== 'undefined' && typeof options.notBefore !== 'undefined') { + return failure(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.')); + } + + try { + validateOptions(options); + } + catch (error) { + return failure(error); + } + + if (!options.allowInvalidAsymmetricKeyTypes) { + try { + validateAsymmetricKey(header.alg, secretOrPrivateKey); + } catch (error) { + return failure(error); + } + } + + const timestamp = payload.iat || Math.floor(Date.now() / 1000); + + if (options.noTimestamp) { + delete payload.iat; + } else if (isObjectPayload) { + payload.iat = timestamp; + } + + if (typeof options.notBefore !== 'undefined') { + try { + payload.nbf = timespan(options.notBefore, timestamp); + } + catch (err) { + return failure(err); + } + if (typeof payload.nbf === 'undefined') { + return failure(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + } + } + + if (typeof options.expiresIn !== 'undefined' && typeof payload === 'object') { + try { + payload.exp = timespan(options.expiresIn, timestamp); + } + catch (err) { + return failure(err); + } + if (typeof payload.exp === 'undefined') { + return failure(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + } + } + + Object.keys(options_to_payload).forEach(function (key) { + const claim = options_to_payload[key]; + if (typeof options[key] !== 'undefined') { + if (typeof payload[claim] !== 'undefined') { + return failure(new Error('Bad "options.' + key + '" option. The payload already has an "' + claim + '" property.')); + } + payload[claim] = options[key]; + } + }); + + const encoding = options.encoding || 'utf8'; + + if (typeof callback === 'function') { + callback = callback && once(callback); + + jws.createSign({ + header: header, + privateKey: secretOrPrivateKey, + payload: payload, + encoding: encoding + }).once('error', callback) + .once('done', function (signature) { + // TODO: Remove in favor of the modulus length check before signing once node 15+ is the minimum supported version + if(!options.allowInsecureKeySizes && /^(?:RS|PS)/.test(header.alg) && signature.length < 256) { + return callback(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`)) + } + callback(null, signature); + }); + } else { + let signature = jws.sign({header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding}); + // TODO: Remove in favor of the modulus length check before signing once node 15+ is the minimum supported version + if(!options.allowInsecureKeySizes && /^(?:RS|PS)/.test(header.alg) && signature.length < 256) { + throw new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`) + } + return signature + } +}; diff --git a/node_modules/jsonwebtoken/verify.js b/node_modules/jsonwebtoken/verify.js new file mode 100644 index 0000000..cdbfdc4 --- /dev/null +++ b/node_modules/jsonwebtoken/verify.js @@ -0,0 +1,263 @@ +const JsonWebTokenError = require('./lib/JsonWebTokenError'); +const NotBeforeError = require('./lib/NotBeforeError'); +const TokenExpiredError = require('./lib/TokenExpiredError'); +const decode = require('./decode'); +const timespan = require('./lib/timespan'); +const validateAsymmetricKey = require('./lib/validateAsymmetricKey'); +const PS_SUPPORTED = require('./lib/psSupported'); +const jws = require('jws'); +const {KeyObject, createSecretKey, createPublicKey} = require("crypto"); + +const PUB_KEY_ALGS = ['RS256', 'RS384', 'RS512']; +const EC_KEY_ALGS = ['ES256', 'ES384', 'ES512']; +const RSA_KEY_ALGS = ['RS256', 'RS384', 'RS512']; +const HS_ALGS = ['HS256', 'HS384', 'HS512']; + +if (PS_SUPPORTED) { + PUB_KEY_ALGS.splice(PUB_KEY_ALGS.length, 0, 'PS256', 'PS384', 'PS512'); + RSA_KEY_ALGS.splice(RSA_KEY_ALGS.length, 0, 'PS256', 'PS384', 'PS512'); +} + +module.exports = function (jwtString, secretOrPublicKey, options, callback) { + if ((typeof options === 'function') && !callback) { + callback = options; + options = {}; + } + + if (!options) { + options = {}; + } + + //clone this object since we are going to mutate it. + options = Object.assign({}, options); + + let done; + + if (callback) { + done = callback; + } else { + done = function(err, data) { + if (err) throw err; + return data; + }; + } + + if (options.clockTimestamp && typeof options.clockTimestamp !== 'number') { + return done(new JsonWebTokenError('clockTimestamp must be a number')); + } + + if (options.nonce !== undefined && (typeof options.nonce !== 'string' || options.nonce.trim() === '')) { + return done(new JsonWebTokenError('nonce must be a non-empty string')); + } + + if (options.allowInvalidAsymmetricKeyTypes !== undefined && typeof options.allowInvalidAsymmetricKeyTypes !== 'boolean') { + return done(new JsonWebTokenError('allowInvalidAsymmetricKeyTypes must be a boolean')); + } + + const clockTimestamp = options.clockTimestamp || Math.floor(Date.now() / 1000); + + if (!jwtString){ + return done(new JsonWebTokenError('jwt must be provided')); + } + + if (typeof jwtString !== 'string') { + return done(new JsonWebTokenError('jwt must be a string')); + } + + const parts = jwtString.split('.'); + + if (parts.length !== 3){ + return done(new JsonWebTokenError('jwt malformed')); + } + + let decodedToken; + + try { + decodedToken = decode(jwtString, { complete: true }); + } catch(err) { + return done(err); + } + + if (!decodedToken) { + return done(new JsonWebTokenError('invalid token')); + } + + const header = decodedToken.header; + let getSecret; + + if(typeof secretOrPublicKey === 'function') { + if(!callback) { + return done(new JsonWebTokenError('verify must be called asynchronous if secret or public key is provided as a callback')); + } + + getSecret = secretOrPublicKey; + } + else { + getSecret = function(header, secretCallback) { + return secretCallback(null, secretOrPublicKey); + }; + } + + return getSecret(header, function(err, secretOrPublicKey) { + if(err) { + return done(new JsonWebTokenError('error in secret or public key callback: ' + err.message)); + } + + const hasSignature = parts[2].trim() !== ''; + + if (!hasSignature && secretOrPublicKey){ + return done(new JsonWebTokenError('jwt signature is required')); + } + + if (hasSignature && !secretOrPublicKey) { + return done(new JsonWebTokenError('secret or public key must be provided')); + } + + if (!hasSignature && !options.algorithms) { + return done(new JsonWebTokenError('please specify "none" in "algorithms" to verify unsigned tokens')); + } + + if (secretOrPublicKey != null && !(secretOrPublicKey instanceof KeyObject)) { + try { + secretOrPublicKey = createPublicKey(secretOrPublicKey); + } catch (_) { + try { + secretOrPublicKey = createSecretKey(typeof secretOrPublicKey === 'string' ? Buffer.from(secretOrPublicKey) : secretOrPublicKey); + } catch (_) { + return done(new JsonWebTokenError('secretOrPublicKey is not valid key material')) + } + } + } + + if (!options.algorithms) { + if (secretOrPublicKey.type === 'secret') { + options.algorithms = HS_ALGS; + } else if (['rsa', 'rsa-pss'].includes(secretOrPublicKey.asymmetricKeyType)) { + options.algorithms = RSA_KEY_ALGS + } else if (secretOrPublicKey.asymmetricKeyType === 'ec') { + options.algorithms = EC_KEY_ALGS + } else { + options.algorithms = PUB_KEY_ALGS + } + } + + if (options.algorithms.indexOf(decodedToken.header.alg) === -1) { + return done(new JsonWebTokenError('invalid algorithm')); + } + + if (header.alg.startsWith('HS') && secretOrPublicKey.type !== 'secret') { + return done(new JsonWebTokenError((`secretOrPublicKey must be a symmetric key when using ${header.alg}`))) + } else if (/^(?:RS|PS|ES)/.test(header.alg) && secretOrPublicKey.type !== 'public') { + return done(new JsonWebTokenError((`secretOrPublicKey must be an asymmetric key when using ${header.alg}`))) + } + + if (!options.allowInvalidAsymmetricKeyTypes) { + try { + validateAsymmetricKey(header.alg, secretOrPublicKey); + } catch (e) { + return done(e); + } + } + + let valid; + + try { + valid = jws.verify(jwtString, decodedToken.header.alg, secretOrPublicKey); + } catch (e) { + return done(e); + } + + if (!valid) { + return done(new JsonWebTokenError('invalid signature')); + } + + const payload = decodedToken.payload; + + if (typeof payload.nbf !== 'undefined' && !options.ignoreNotBefore) { + if (typeof payload.nbf !== 'number') { + return done(new JsonWebTokenError('invalid nbf value')); + } + if (payload.nbf > clockTimestamp + (options.clockTolerance || 0)) { + return done(new NotBeforeError('jwt not active', new Date(payload.nbf * 1000))); + } + } + + if (typeof payload.exp !== 'undefined' && !options.ignoreExpiration) { + if (typeof payload.exp !== 'number') { + return done(new JsonWebTokenError('invalid exp value')); + } + if (clockTimestamp >= payload.exp + (options.clockTolerance || 0)) { + return done(new TokenExpiredError('jwt expired', new Date(payload.exp * 1000))); + } + } + + if (options.audience) { + const audiences = Array.isArray(options.audience) ? options.audience : [options.audience]; + const target = Array.isArray(payload.aud) ? payload.aud : [payload.aud]; + + const match = target.some(function (targetAudience) { + return audiences.some(function (audience) { + return audience instanceof RegExp ? audience.test(targetAudience) : audience === targetAudience; + }); + }); + + if (!match) { + return done(new JsonWebTokenError('jwt audience invalid. expected: ' + audiences.join(' or '))); + } + } + + if (options.issuer) { + const invalid_issuer = + (typeof options.issuer === 'string' && payload.iss !== options.issuer) || + (Array.isArray(options.issuer) && options.issuer.indexOf(payload.iss) === -1); + + if (invalid_issuer) { + return done(new JsonWebTokenError('jwt issuer invalid. expected: ' + options.issuer)); + } + } + + if (options.subject) { + if (payload.sub !== options.subject) { + return done(new JsonWebTokenError('jwt subject invalid. expected: ' + options.subject)); + } + } + + if (options.jwtid) { + if (payload.jti !== options.jwtid) { + return done(new JsonWebTokenError('jwt jwtid invalid. expected: ' + options.jwtid)); + } + } + + if (options.nonce) { + if (payload.nonce !== options.nonce) { + return done(new JsonWebTokenError('jwt nonce invalid. expected: ' + options.nonce)); + } + } + + if (options.maxAge) { + if (typeof payload.iat !== 'number') { + return done(new JsonWebTokenError('iat required when maxAge is specified')); + } + + const maxAgeTimestamp = timespan(options.maxAge, payload.iat); + if (typeof maxAgeTimestamp === 'undefined') { + return done(new JsonWebTokenError('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + } + if (clockTimestamp >= maxAgeTimestamp + (options.clockTolerance || 0)) { + return done(new TokenExpiredError('maxAge exceeded', new Date(maxAgeTimestamp * 1000))); + } + } + + if (options.complete === true) { + const signature = decodedToken.signature; + + return done(null, { + header: header, + payload: payload, + signature: signature + }); + } + + return done(null, payload); + }); +}; diff --git a/node_modules/jwa/LICENSE b/node_modules/jwa/LICENSE new file mode 100644 index 0000000..caeb849 --- /dev/null +++ b/node_modules/jwa/LICENSE @@ -0,0 +1,17 @@ +Copyright (c) 2013 Brian J. Brennan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the +Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/jwa/README.md b/node_modules/jwa/README.md new file mode 100644 index 0000000..fb433e2 --- /dev/null +++ b/node_modules/jwa/README.md @@ -0,0 +1,150 @@ +# node-jwa [![Build Status](https://travis-ci.org/brianloveswords/node-jwa.svg?branch=master)](https://travis-ci.org/brianloveswords/node-jwa) + +A +[JSON Web Algorithms](http://tools.ietf.org/id/draft-ietf-jose-json-web-algorithms-08.html) +implementation focusing (exclusively, at this point) on the algorithms necessary for +[JSON Web Signatures](http://self-issued.info/docs/draft-ietf-jose-json-web-signature.html). + +This library supports all of the required, recommended and optional cryptographic algorithms for JWS: + +alg Parameter Value | Digital Signature or MAC Algorithm +----------------|---------------------------- +HS256 | HMAC using SHA-256 hash algorithm +HS384 | HMAC using SHA-384 hash algorithm +HS512 | HMAC using SHA-512 hash algorithm +RS256 | RSASSA using SHA-256 hash algorithm +RS384 | RSASSA using SHA-384 hash algorithm +RS512 | RSASSA using SHA-512 hash algorithm +PS256 | RSASSA-PSS using SHA-256 hash algorithm +PS384 | RSASSA-PSS using SHA-384 hash algorithm +PS512 | RSASSA-PSS using SHA-512 hash algorithm +ES256 | ECDSA using P-256 curve and SHA-256 hash algorithm +ES384 | ECDSA using P-384 curve and SHA-384 hash algorithm +ES512 | ECDSA using P-521 curve and SHA-512 hash algorithm +none | No digital signature or MAC value included + +Please note that PS* only works on Node 6.12+ (excluding 7.x). + +# Requirements + +In order to run the tests, a recent version of OpenSSL is +required. **The version that comes with OS X (OpenSSL 0.9.8r 8 Feb +2011) is not recent enough**, as it does not fully support ECDSA +keys. You'll need to use a version > 1.0.0; I tested with OpenSSL 1.0.1c 10 May 2012. + +# Testing + +To run the tests, do + +```bash +$ npm test +``` + +This will generate a bunch of keypairs to use in testing. If you want to +generate new keypairs, do `make clean` before running `npm test` again. + +## Methodology + +I spawn `openssl dgst -sign` to test OpenSSL sign → JS verify and +`openssl dgst -verify` to test JS sign → OpenSSL verify for each of the +RSA and ECDSA algorithms. + +# Usage + +## jwa(algorithm) + +Creates a new `jwa` object with `sign` and `verify` methods for the +algorithm. Valid values for algorithm can be found in the table above +(`'HS256'`, `'HS384'`, etc) and are case-insensitive. Passing an invalid +algorithm value will throw a `TypeError`. + + +## jwa#sign(input, secretOrPrivateKey) + +Sign some input with either a secret for HMAC algorithms, or a private +key for RSA and ECDSA algorithms. + +If input is not already a string or buffer, `JSON.stringify` will be +called on it to attempt to coerce it. + +For the HMAC algorithm, `secretOrPrivateKey` should be a string or a +buffer. For ECDSA and RSA, the value should be a string representing a +PEM encoded **private** key. + +Output [base64url](http://en.wikipedia.org/wiki/Base64#URL_applications) +formatted. This is for convenience as JWS expects the signature in this +format. If your application needs the output in a different format, +[please open an issue](https://github.com/brianloveswords/node-jwa/issues). In +the meantime, you can use +[brianloveswords/base64url](https://github.com/brianloveswords/base64url) +to decode the signature. + +As of nodejs *v0.11.8*, SPKAC support was introduce. If your nodeJs +version satisfies, then you can pass an object `{ key: '..', passphrase: '...' }` + + +## jwa#verify(input, signature, secretOrPublicKey) + +Verify a signature. Returns `true` or `false`. + +`signature` should be a base64url encoded string. + +For the HMAC algorithm, `secretOrPublicKey` should be a string or a +buffer. For ECDSA and RSA, the value should be a string represented a +PEM encoded **public** key. + + +# Example + +HMAC +```js +const jwa = require('jwa'); + +const hmac = jwa('HS256'); +const input = 'super important stuff'; +const secret = 'shhhhhh'; + +const signature = hmac.sign(input, secret); +hmac.verify(input, signature, secret) // === true +hmac.verify(input, signature, 'trickery!') // === false +``` + +With keys +```js +const fs = require('fs'); +const jwa = require('jwa'); +const privateKey = fs.readFileSync(__dirname + '/ecdsa-p521-private.pem'); +const publicKey = fs.readFileSync(__dirname + '/ecdsa-p521-public.pem'); + +const ecdsa = jwa('ES512'); +const input = 'very important stuff'; + +const signature = ecdsa.sign(input, privateKey); +ecdsa.verify(input, signature, publicKey) // === true +``` +## License + +MIT + +``` +Copyright (c) 2013 Brian J. Brennan + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` diff --git a/node_modules/jwa/index.js b/node_modules/jwa/index.js new file mode 100644 index 0000000..5c1b6cf --- /dev/null +++ b/node_modules/jwa/index.js @@ -0,0 +1,266 @@ +var Buffer = require('safe-buffer').Buffer; +var crypto = require('crypto'); +var formatEcdsa = require('ecdsa-sig-formatter'); +var util = require('util'); + +var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".' +var MSG_INVALID_SECRET = 'secret must be a string or buffer'; +var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer'; +var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object'; + +var supportsKeyObjects = typeof crypto.createPublicKey === 'function'; +if (supportsKeyObjects) { + MSG_INVALID_VERIFIER_KEY += ' or a KeyObject'; + MSG_INVALID_SECRET += 'or a KeyObject'; +} + +function checkIsPublicKey(key) { + if (Buffer.isBuffer(key)) { + return; + } + + if (typeof key === 'string') { + return; + } + + if (!supportsKeyObjects) { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key !== 'object') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key.type !== 'string') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key.asymmetricKeyType !== 'string') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key.export !== 'function') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } +}; + +function checkIsPrivateKey(key) { + if (Buffer.isBuffer(key)) { + return; + } + + if (typeof key === 'string') { + return; + } + + if (typeof key === 'object') { + return; + } + + throw typeError(MSG_INVALID_SIGNER_KEY); +}; + +function checkIsSecretKey(key) { + if (Buffer.isBuffer(key)) { + return; + } + + if (typeof key === 'string') { + return key; + } + + if (!supportsKeyObjects) { + throw typeError(MSG_INVALID_SECRET); + } + + if (typeof key !== 'object') { + throw typeError(MSG_INVALID_SECRET); + } + + if (key.type !== 'secret') { + throw typeError(MSG_INVALID_SECRET); + } + + if (typeof key.export !== 'function') { + throw typeError(MSG_INVALID_SECRET); + } +} + +function fromBase64(base64) { + return base64 + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} + +function toBase64(base64url) { + base64url = base64url.toString(); + + var padding = 4 - base64url.length % 4; + if (padding !== 4) { + for (var i = 0; i < padding; ++i) { + base64url += '='; + } + } + + return base64url + .replace(/\-/g, '+') + .replace(/_/g, '/'); +} + +function typeError(template) { + var args = [].slice.call(arguments, 1); + var errMsg = util.format.bind(util, template).apply(null, args); + return new TypeError(errMsg); +} + +function bufferOrString(obj) { + return Buffer.isBuffer(obj) || typeof obj === 'string'; +} + +function normalizeInput(thing) { + if (!bufferOrString(thing)) + thing = JSON.stringify(thing); + return thing; +} + +function createHmacSigner(bits) { + return function sign(thing, secret) { + checkIsSecretKey(secret); + thing = normalizeInput(thing); + var hmac = crypto.createHmac('sha' + bits, secret); + var sig = (hmac.update(thing), hmac.digest('base64')) + return fromBase64(sig); + } +} + +var bufferEqual; +var timingSafeEqual = 'timingSafeEqual' in crypto ? function timingSafeEqual(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + + return crypto.timingSafeEqual(a, b) +} : function timingSafeEqual(a, b) { + if (!bufferEqual) { + bufferEqual = require('buffer-equal-constant-time'); + } + + return bufferEqual(a, b) +} + +function createHmacVerifier(bits) { + return function verify(thing, signature, secret) { + var computedSig = createHmacSigner(bits)(thing, secret); + return timingSafeEqual(Buffer.from(signature), Buffer.from(computedSig)); + } +} + +function createKeySigner(bits) { + return function sign(thing, privateKey) { + checkIsPrivateKey(privateKey); + thing = normalizeInput(thing); + // Even though we are specifying "RSA" here, this works with ECDSA + // keys as well. + var signer = crypto.createSign('RSA-SHA' + bits); + var sig = (signer.update(thing), signer.sign(privateKey, 'base64')); + return fromBase64(sig); + } +} + +function createKeyVerifier(bits) { + return function verify(thing, signature, publicKey) { + checkIsPublicKey(publicKey); + thing = normalizeInput(thing); + signature = toBase64(signature); + var verifier = crypto.createVerify('RSA-SHA' + bits); + verifier.update(thing); + return verifier.verify(publicKey, signature, 'base64'); + } +} + +function createPSSKeySigner(bits) { + return function sign(thing, privateKey) { + checkIsPrivateKey(privateKey); + thing = normalizeInput(thing); + var signer = crypto.createSign('RSA-SHA' + bits); + var sig = (signer.update(thing), signer.sign({ + key: privateKey, + padding: crypto.constants.RSA_PKCS1_PSS_PADDING, + saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST + }, 'base64')); + return fromBase64(sig); + } +} + +function createPSSKeyVerifier(bits) { + return function verify(thing, signature, publicKey) { + checkIsPublicKey(publicKey); + thing = normalizeInput(thing); + signature = toBase64(signature); + var verifier = crypto.createVerify('RSA-SHA' + bits); + verifier.update(thing); + return verifier.verify({ + key: publicKey, + padding: crypto.constants.RSA_PKCS1_PSS_PADDING, + saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST + }, signature, 'base64'); + } +} + +function createECDSASigner(bits) { + var inner = createKeySigner(bits); + return function sign() { + var signature = inner.apply(null, arguments); + signature = formatEcdsa.derToJose(signature, 'ES' + bits); + return signature; + }; +} + +function createECDSAVerifer(bits) { + var inner = createKeyVerifier(bits); + return function verify(thing, signature, publicKey) { + signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64'); + var result = inner(thing, signature, publicKey); + return result; + }; +} + +function createNoneSigner() { + return function sign() { + return ''; + } +} + +function createNoneVerifier() { + return function verify(thing, signature) { + return signature === ''; + } +} + +module.exports = function jwa(algorithm) { + var signerFactories = { + hs: createHmacSigner, + rs: createKeySigner, + ps: createPSSKeySigner, + es: createECDSASigner, + none: createNoneSigner, + } + var verifierFactories = { + hs: createHmacVerifier, + rs: createKeyVerifier, + ps: createPSSKeyVerifier, + es: createECDSAVerifer, + none: createNoneVerifier, + } + var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/i); + if (!match) + throw typeError(MSG_INVALID_ALGORITHM, algorithm); + var algo = (match[1] || match[3]).toLowerCase(); + var bits = match[2]; + + return { + sign: signerFactories[algo](bits), + verify: verifierFactories[algo](bits), + } +}; diff --git a/node_modules/jwa/package.json b/node_modules/jwa/package.json new file mode 100644 index 0000000..be9b11f --- /dev/null +++ b/node_modules/jwa/package.json @@ -0,0 +1,37 @@ +{ + "name": "jwa", + "version": "1.4.2", + "description": "JWA implementation (supports all JWS algorithms)", + "main": "index.js", + "directories": { + "test": "test" + }, + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + }, + "devDependencies": { + "base64url": "^2.0.0", + "jwk-to-pem": "^2.0.1", + "semver": "4.3.6", + "tap": "6.2.0" + }, + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/brianloveswords/node-jwa.git" + }, + "keywords": [ + "jwa", + "jws", + "jwt", + "rsa", + "ecdsa", + "hmac" + ], + "author": "Brian J. Brennan ", + "license": "MIT" +} diff --git a/node_modules/jws/CHANGELOG.md b/node_modules/jws/CHANGELOG.md new file mode 100644 index 0000000..af8fc28 --- /dev/null +++ b/node_modules/jws/CHANGELOG.md @@ -0,0 +1,34 @@ +# Change Log +All notable changes to this project will be documented in this file. + +## [3.0.0] +### Changed +- **BREAKING**: `jwt.verify` now requires an `algorithm` parameter, and + `jws.createVerify` requires an `algorithm` option. The `"alg"` field + signature headers is ignored. This mitigates a critical security flaw + in the library which would allow an attacker to generate signatures with + arbitrary contents that would be accepted by `jwt.verify`. See + https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/ + for details. + +## [2.0.0] - 2015-01-30 +### Changed +- **BREAKING**: Default payload encoding changed from `binary` to + `utf8`. `utf8` is a is a more sensible default than `binary` because + many payloads, as far as I can tell, will contain user-facing + strings that could be in any language. ([6b6de48]) + +- Code reorganization, thanks [@fearphage]! ([7880050]) + +### Added +- Option in all relevant methods for `encoding`. For those few users + that might be depending on a `binary` encoding of the messages, this + is for them. ([6b6de48]) + +[unreleased]: https://github.com/brianloveswords/node-jws/compare/v2.0.0...HEAD +[2.0.0]: https://github.com/brianloveswords/node-jws/compare/v1.0.1...v2.0.0 + +[7880050]: https://github.com/brianloveswords/node-jws/commit/7880050 +[6b6de48]: https://github.com/brianloveswords/node-jws/commit/6b6de48 + +[@fearphage]: https://github.com/fearphage diff --git a/node_modules/jws/LICENSE b/node_modules/jws/LICENSE new file mode 100644 index 0000000..caeb849 --- /dev/null +++ b/node_modules/jws/LICENSE @@ -0,0 +1,17 @@ +Copyright (c) 2013 Brian J. Brennan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the +Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/jws/index.js b/node_modules/jws/index.js new file mode 100644 index 0000000..8c8da93 --- /dev/null +++ b/node_modules/jws/index.js @@ -0,0 +1,22 @@ +/*global exports*/ +var SignStream = require('./lib/sign-stream'); +var VerifyStream = require('./lib/verify-stream'); + +var ALGORITHMS = [ + 'HS256', 'HS384', 'HS512', + 'RS256', 'RS384', 'RS512', + 'PS256', 'PS384', 'PS512', + 'ES256', 'ES384', 'ES512' +]; + +exports.ALGORITHMS = ALGORITHMS; +exports.sign = SignStream.sign; +exports.verify = VerifyStream.verify; +exports.decode = VerifyStream.decode; +exports.isValid = VerifyStream.isValid; +exports.createSign = function createSign(opts) { + return new SignStream(opts); +}; +exports.createVerify = function createVerify(opts) { + return new VerifyStream(opts); +}; diff --git a/node_modules/jws/lib/data-stream.js b/node_modules/jws/lib/data-stream.js new file mode 100644 index 0000000..3535d31 --- /dev/null +++ b/node_modules/jws/lib/data-stream.js @@ -0,0 +1,55 @@ +/*global module, process*/ +var Buffer = require('safe-buffer').Buffer; +var Stream = require('stream'); +var util = require('util'); + +function DataStream(data) { + this.buffer = null; + this.writable = true; + this.readable = true; + + // No input + if (!data) { + this.buffer = Buffer.alloc(0); + return this; + } + + // Stream + if (typeof data.pipe === 'function') { + this.buffer = Buffer.alloc(0); + data.pipe(this); + return this; + } + + // Buffer or String + // or Object (assumedly a passworded key) + if (data.length || typeof data === 'object') { + this.buffer = data; + this.writable = false; + process.nextTick(function () { + this.emit('end', data); + this.readable = false; + this.emit('close'); + }.bind(this)); + return this; + } + + throw new TypeError('Unexpected data type ('+ typeof data + ')'); +} +util.inherits(DataStream, Stream); + +DataStream.prototype.write = function write(data) { + this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]); + this.emit('data', data); +}; + +DataStream.prototype.end = function end(data) { + if (data) + this.write(data); + this.emit('end', data); + this.emit('close'); + this.writable = false; + this.readable = false; +}; + +module.exports = DataStream; diff --git a/node_modules/jws/lib/sign-stream.js b/node_modules/jws/lib/sign-stream.js new file mode 100644 index 0000000..6a7ee42 --- /dev/null +++ b/node_modules/jws/lib/sign-stream.js @@ -0,0 +1,78 @@ +/*global module*/ +var Buffer = require('safe-buffer').Buffer; +var DataStream = require('./data-stream'); +var jwa = require('jwa'); +var Stream = require('stream'); +var toString = require('./tostring'); +var util = require('util'); + +function base64url(string, encoding) { + return Buffer + .from(string, encoding) + .toString('base64') + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} + +function jwsSecuredInput(header, payload, encoding) { + encoding = encoding || 'utf8'; + var encodedHeader = base64url(toString(header), 'binary'); + var encodedPayload = base64url(toString(payload), encoding); + return util.format('%s.%s', encodedHeader, encodedPayload); +} + +function jwsSign(opts) { + var header = opts.header; + var payload = opts.payload; + var secretOrKey = opts.secret || opts.privateKey; + var encoding = opts.encoding; + var algo = jwa(header.alg); + var securedInput = jwsSecuredInput(header, payload, encoding); + var signature = algo.sign(securedInput, secretOrKey); + return util.format('%s.%s', securedInput, signature); +} + +function SignStream(opts) { + var secret = opts.secret||opts.privateKey||opts.key; + var secretStream = new DataStream(secret); + this.readable = true; + this.header = opts.header; + this.encoding = opts.encoding; + this.secret = this.privateKey = this.key = secretStream; + this.payload = new DataStream(opts.payload); + this.secret.once('close', function () { + if (!this.payload.writable && this.readable) + this.sign(); + }.bind(this)); + + this.payload.once('close', function () { + if (!this.secret.writable && this.readable) + this.sign(); + }.bind(this)); +} +util.inherits(SignStream, Stream); + +SignStream.prototype.sign = function sign() { + try { + var signature = jwsSign({ + header: this.header, + payload: this.payload.buffer, + secret: this.secret.buffer, + encoding: this.encoding + }); + this.emit('done', signature); + this.emit('data', signature); + this.emit('end'); + this.readable = false; + return signature; + } catch (e) { + this.readable = false; + this.emit('error', e); + this.emit('close'); + } +}; + +SignStream.sign = jwsSign; + +module.exports = SignStream; diff --git a/node_modules/jws/lib/tostring.js b/node_modules/jws/lib/tostring.js new file mode 100644 index 0000000..f5a49a3 --- /dev/null +++ b/node_modules/jws/lib/tostring.js @@ -0,0 +1,10 @@ +/*global module*/ +var Buffer = require('buffer').Buffer; + +module.exports = function toString(obj) { + if (typeof obj === 'string') + return obj; + if (typeof obj === 'number' || Buffer.isBuffer(obj)) + return obj.toString(); + return JSON.stringify(obj); +}; diff --git a/node_modules/jws/lib/verify-stream.js b/node_modules/jws/lib/verify-stream.js new file mode 100644 index 0000000..39f7c73 --- /dev/null +++ b/node_modules/jws/lib/verify-stream.js @@ -0,0 +1,120 @@ +/*global module*/ +var Buffer = require('safe-buffer').Buffer; +var DataStream = require('./data-stream'); +var jwa = require('jwa'); +var Stream = require('stream'); +var toString = require('./tostring'); +var util = require('util'); +var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/; + +function isObject(thing) { + return Object.prototype.toString.call(thing) === '[object Object]'; +} + +function safeJsonParse(thing) { + if (isObject(thing)) + return thing; + try { return JSON.parse(thing); } + catch (e) { return undefined; } +} + +function headerFromJWS(jwsSig) { + var encodedHeader = jwsSig.split('.', 1)[0]; + return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary')); +} + +function securedInputFromJWS(jwsSig) { + return jwsSig.split('.', 2).join('.'); +} + +function signatureFromJWS(jwsSig) { + return jwsSig.split('.')[2]; +} + +function payloadFromJWS(jwsSig, encoding) { + encoding = encoding || 'utf8'; + var payload = jwsSig.split('.')[1]; + return Buffer.from(payload, 'base64').toString(encoding); +} + +function isValidJws(string) { + return JWS_REGEX.test(string) && !!headerFromJWS(string); +} + +function jwsVerify(jwsSig, algorithm, secretOrKey) { + if (!algorithm) { + var err = new Error("Missing algorithm parameter for jws.verify"); + err.code = "MISSING_ALGORITHM"; + throw err; + } + jwsSig = toString(jwsSig); + var signature = signatureFromJWS(jwsSig); + var securedInput = securedInputFromJWS(jwsSig); + var algo = jwa(algorithm); + return algo.verify(securedInput, signature, secretOrKey); +} + +function jwsDecode(jwsSig, opts) { + opts = opts || {}; + jwsSig = toString(jwsSig); + + if (!isValidJws(jwsSig)) + return null; + + var header = headerFromJWS(jwsSig); + + if (!header) + return null; + + var payload = payloadFromJWS(jwsSig); + if (header.typ === 'JWT' || opts.json) + payload = JSON.parse(payload, opts.encoding); + + return { + header: header, + payload: payload, + signature: signatureFromJWS(jwsSig) + }; +} + +function VerifyStream(opts) { + opts = opts || {}; + var secretOrKey = opts.secret||opts.publicKey||opts.key; + var secretStream = new DataStream(secretOrKey); + this.readable = true; + this.algorithm = opts.algorithm; + this.encoding = opts.encoding; + this.secret = this.publicKey = this.key = secretStream; + this.signature = new DataStream(opts.signature); + this.secret.once('close', function () { + if (!this.signature.writable && this.readable) + this.verify(); + }.bind(this)); + + this.signature.once('close', function () { + if (!this.secret.writable && this.readable) + this.verify(); + }.bind(this)); +} +util.inherits(VerifyStream, Stream); +VerifyStream.prototype.verify = function verify() { + try { + var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer); + var obj = jwsDecode(this.signature.buffer, this.encoding); + this.emit('done', valid, obj); + this.emit('data', valid); + this.emit('end'); + this.readable = false; + return valid; + } catch (e) { + this.readable = false; + this.emit('error', e); + this.emit('close'); + } +}; + +VerifyStream.decode = jwsDecode; +VerifyStream.isValid = isValidJws; +VerifyStream.verify = jwsVerify; + +module.exports = VerifyStream; diff --git a/node_modules/jws/package.json b/node_modules/jws/package.json new file mode 100644 index 0000000..3fb2837 --- /dev/null +++ b/node_modules/jws/package.json @@ -0,0 +1,34 @@ +{ + "name": "jws", + "version": "3.2.2", + "description": "Implementation of JSON Web Signatures", + "main": "index.js", + "directories": { + "test": "test" + }, + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/brianloveswords/node-jws.git" + }, + "keywords": [ + "jws", + "json", + "web", + "signatures" + ], + "author": "Brian J Brennan", + "license": "MIT", + "readmeFilename": "readme.md", + "gitHead": "c0f6b27bcea5a2ad2e304d91c2e842e4076a6b03", + "dependencies": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + }, + "devDependencies": { + "semver": "^5.1.0", + "tape": "~2.14.0" + } +} diff --git a/node_modules/jws/readme.md b/node_modules/jws/readme.md new file mode 100644 index 0000000..1910c9a --- /dev/null +++ b/node_modules/jws/readme.md @@ -0,0 +1,255 @@ +# node-jws [![Build Status](https://secure.travis-ci.org/brianloveswords/node-jws.png)](http://travis-ci.org/brianloveswords/node-jws) + +An implementation of [JSON Web Signatures](http://self-issued.info/docs/draft-ietf-jose-json-web-signature.html). + +This was developed against `draft-ietf-jose-json-web-signature-08` and +implements the entire spec **except** X.509 Certificate Chain +signing/verifying (patches welcome). + +There are both synchronous (`jws.sign`, `jws.verify`) and streaming +(`jws.createSign`, `jws.createVerify`) APIs. + +# Install + +```bash +$ npm install jws +``` + +# Usage + +## jws.ALGORITHMS + +Array of supported algorithms. The following algorithms are currently supported. + +alg Parameter Value | Digital Signature or MAC Algorithm +----------------|---------------------------- +HS256 | HMAC using SHA-256 hash algorithm +HS384 | HMAC using SHA-384 hash algorithm +HS512 | HMAC using SHA-512 hash algorithm +RS256 | RSASSA using SHA-256 hash algorithm +RS384 | RSASSA using SHA-384 hash algorithm +RS512 | RSASSA using SHA-512 hash algorithm +PS256 | RSASSA-PSS using SHA-256 hash algorithm +PS384 | RSASSA-PSS using SHA-384 hash algorithm +PS512 | RSASSA-PSS using SHA-512 hash algorithm +ES256 | ECDSA using P-256 curve and SHA-256 hash algorithm +ES384 | ECDSA using P-384 curve and SHA-384 hash algorithm +ES512 | ECDSA using P-521 curve and SHA-512 hash algorithm +none | No digital signature or MAC value included + +## jws.sign(options) + +(Synchronous) Return a JSON Web Signature for a header and a payload. + +Options: + +* `header` +* `payload` +* `secret` or `privateKey` +* `encoding` (Optional, defaults to 'utf8') + +`header` must be an object with an `alg` property. `header.alg` must be +one a value found in `jws.ALGORITHMS`. See above for a table of +supported algorithms. + +If `payload` is not a buffer or a string, it will be coerced into a string +using `JSON.stringify`. + +Example + +```js +const signature = jws.sign({ + header: { alg: 'HS256' }, + payload: 'h. jon benjamin', + secret: 'has a van', +}); +``` + +## jws.verify(signature, algorithm, secretOrKey) + +(Synchronous) Returns `true` or `false` for whether a signature matches a +secret or key. + +`signature` is a JWS Signature. `header.alg` must be a value found in `jws.ALGORITHMS`. +See above for a table of supported algorithms. `secretOrKey` is a string or +buffer containing either the secret for HMAC algorithms, or the PEM +encoded public key for RSA and ECDSA. + +Note that the `"alg"` value from the signature header is ignored. + + +## jws.decode(signature) + +(Synchronous) Returns the decoded header, decoded payload, and signature +parts of the JWS Signature. + +Returns an object with three properties, e.g. +```js +{ header: { alg: 'HS256' }, + payload: 'h. jon benjamin', + signature: 'YOWPewyGHKu4Y_0M_vtlEnNlqmFOclqp4Hy6hVHfFT4' +} +``` + +## jws.createSign(options) + +Returns a new SignStream object. + +Options: + +* `header` (required) +* `payload` +* `key` || `privateKey` || `secret` +* `encoding` (Optional, defaults to 'utf8') + +Other than `header`, all options expect a string or a buffer when the +value is known ahead of time, or a stream for convenience. +`key`/`privateKey`/`secret` may also be an object when using an encrypted +private key, see the [crypto documentation][encrypted-key-docs]. + +Example: + +```js + +// This... +jws.createSign({ + header: { alg: 'RS256' }, + privateKey: privateKeyStream, + payload: payloadStream, +}).on('done', function(signature) { + // ... +}); + +// is equivalent to this: +const signer = jws.createSign({ + header: { alg: 'RS256' }, +}); +privateKeyStream.pipe(signer.privateKey); +payloadStream.pipe(signer.payload); +signer.on('done', function(signature) { + // ... +}); +``` + +## jws.createVerify(options) + +Returns a new VerifyStream object. + +Options: + +* `signature` +* `algorithm` +* `key` || `publicKey` || `secret` +* `encoding` (Optional, defaults to 'utf8') + +All options expect a string or a buffer when the value is known ahead of +time, or a stream for convenience. + +Example: + +```js + +// This... +jws.createVerify({ + publicKey: pubKeyStream, + signature: sigStream, +}).on('done', function(verified, obj) { + // ... +}); + +// is equivilant to this: +const verifier = jws.createVerify(); +pubKeyStream.pipe(verifier.publicKey); +sigStream.pipe(verifier.signature); +verifier.on('done', function(verified, obj) { + // ... +}); +``` + +## Class: SignStream + +A `Readable Stream` that emits a single data event (the calculated +signature) when done. + +### Event: 'done' +`function (signature) { }` + +### signer.payload + +A `Writable Stream` that expects the JWS payload. Do *not* use if you +passed a `payload` option to the constructor. + +Example: + +```js +payloadStream.pipe(signer.payload); +``` + +### signer.secret
signer.key
signer.privateKey + +A `Writable Stream`. Expects the JWS secret for HMAC, or the privateKey +for ECDSA and RSA. Do *not* use if you passed a `secret` or `key` option +to the constructor. + +Example: + +```js +privateKeyStream.pipe(signer.privateKey); +``` + +## Class: VerifyStream + +This is a `Readable Stream` that emits a single data event, the result +of whether or not that signature was valid. + +### Event: 'done' +`function (valid, obj) { }` + +`valid` is a boolean for whether or not the signature is valid. + +### verifier.signature + +A `Writable Stream` that expects a JWS Signature. Do *not* use if you +passed a `signature` option to the constructor. + +### verifier.secret
verifier.key
verifier.publicKey + +A `Writable Stream` that expects a public key or secret. Do *not* use if you +passed a `key` or `secret` option to the constructor. + +# TODO + +* It feels like there should be some convenience options/APIs for + defining the algorithm rather than having to define a header object + with `{ alg: 'ES512' }` or whatever every time. + +* X.509 support, ugh + +# License + +MIT + +``` +Copyright (c) 2013-2015 Brian J. Brennan + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` + +[encrypted-key-docs]: https://nodejs.org/api/crypto.html#crypto_sign_sign_private_key_output_format diff --git a/node_modules/lodash.includes/LICENSE b/node_modules/lodash.includes/LICENSE new file mode 100644 index 0000000..e0c69d5 --- /dev/null +++ b/node_modules/lodash.includes/LICENSE @@ -0,0 +1,47 @@ +Copyright jQuery Foundation and other contributors + +Based on Underscore.js, copyright Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at https://github.com/lodash/lodash + +The following license applies to all parts of this software except as +documented below: + +==== + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +==== + +Copyright and related rights for sample code are waived via CC0. Sample +code is defined as all source code displayed within the prose of the +documentation. + +CC0: http://creativecommons.org/publicdomain/zero/1.0/ + +==== + +Files located in the node_modules and vendor directories are externally +maintained libraries used by this software which have their own +licenses; we recommend you read them, as their terms may differ from the +terms above. diff --git a/node_modules/lodash.includes/README.md b/node_modules/lodash.includes/README.md new file mode 100644 index 0000000..26e9377 --- /dev/null +++ b/node_modules/lodash.includes/README.md @@ -0,0 +1,18 @@ +# lodash.includes v4.3.0 + +The [lodash](https://lodash.com/) method `_.includes` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.includes +``` + +In Node.js: +```js +var includes = require('lodash.includes'); +``` + +See the [documentation](https://lodash.com/docs#includes) or [package source](https://github.com/lodash/lodash/blob/4.3.0-npm-packages/lodash.includes) for more details. diff --git a/node_modules/lodash.includes/index.js b/node_modules/lodash.includes/index.js new file mode 100644 index 0000000..e88d533 --- /dev/null +++ b/node_modules/lodash.includes/index.js @@ -0,0 +1,745 @@ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + stringTag = '[object String]', + symbolTag = '[object Symbol]'; + +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; + +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; + +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; + +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; + +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; + +/** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function arrayMap(array, iteratee) { + var index = -1, + length = array ? array.length : 0, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; +} + +/** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; +} + +/** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseIndexOf(array, value, fromIndex) { + if (value !== value) { + return baseFindIndex(array, baseIsNaN, fromIndex); + } + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; +} + +/** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ +function baseIsNaN(value) { + return value !== value; +} + +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} + +/** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ +function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); +} + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max; + +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + // Safari 9 makes `arguments.length` enumerable in strict mode. + var result = (isArray(value) || isArguments(value)) + ? baseTimes(value.length, String) + : []; + + var length = result.length, + skipIndexes = !!length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && (key == 'length' || isIndex(key, length)))) { + result.push(key); + } + } + return result; +} + +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; +} + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); +} + +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; +} + +/** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */ +function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) + ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) + : (!!length && baseIndexOf(collection, value, fromIndex) > -1); +} + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} + +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ +function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); +} + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} + +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ +function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; +} + +/** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ +function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; +} + +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} + +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +} + +/** + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ +function values(object) { + return object ? baseValues(object, keys(object)) : []; +} + +module.exports = includes; diff --git a/node_modules/lodash.includes/package.json b/node_modules/lodash.includes/package.json new file mode 100644 index 0000000..a02e645 --- /dev/null +++ b/node_modules/lodash.includes/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.includes", + "version": "4.3.0", + "description": "The lodash method `_.includes` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, includes", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/lodash.isboolean/LICENSE b/node_modules/lodash.isboolean/LICENSE new file mode 100644 index 0000000..b054ca5 --- /dev/null +++ b/node_modules/lodash.isboolean/LICENSE @@ -0,0 +1,22 @@ +Copyright 2012-2016 The Dojo Foundation +Based on Underscore.js, copyright 2009-2016 Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/lodash.isboolean/README.md b/node_modules/lodash.isboolean/README.md new file mode 100644 index 0000000..b3c476b --- /dev/null +++ b/node_modules/lodash.isboolean/README.md @@ -0,0 +1,18 @@ +# lodash.isboolean v3.0.3 + +The [lodash](https://lodash.com/) method `_.isBoolean` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.isboolean +``` + +In Node.js: +```js +var isBoolean = require('lodash.isboolean'); +``` + +See the [documentation](https://lodash.com/docs#isBoolean) or [package source](https://github.com/lodash/lodash/blob/3.0.3-npm-packages/lodash.isboolean) for more details. diff --git a/node_modules/lodash.isboolean/index.js b/node_modules/lodash.isboolean/index.js new file mode 100644 index 0000000..23bbabd --- /dev/null +++ b/node_modules/lodash.isboolean/index.js @@ -0,0 +1,70 @@ +/** + * lodash 3.0.3 (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright 2012-2016 The Dojo Foundation + * Based on Underscore.js 1.8.3 + * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ + +/** `Object#toString` result references. */ +var boolTag = '[object Boolean]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ +function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && objectToString.call(value) == boolTag); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +module.exports = isBoolean; diff --git a/node_modules/lodash.isboolean/package.json b/node_modules/lodash.isboolean/package.json new file mode 100644 index 0000000..01d6e8b --- /dev/null +++ b/node_modules/lodash.isboolean/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.isboolean", + "version": "3.0.3", + "description": "The lodash method `_.isBoolean` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, isboolean", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/lodash.isinteger/LICENSE b/node_modules/lodash.isinteger/LICENSE new file mode 100644 index 0000000..e0c69d5 --- /dev/null +++ b/node_modules/lodash.isinteger/LICENSE @@ -0,0 +1,47 @@ +Copyright jQuery Foundation and other contributors + +Based on Underscore.js, copyright Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at https://github.com/lodash/lodash + +The following license applies to all parts of this software except as +documented below: + +==== + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +==== + +Copyright and related rights for sample code are waived via CC0. Sample +code is defined as all source code displayed within the prose of the +documentation. + +CC0: http://creativecommons.org/publicdomain/zero/1.0/ + +==== + +Files located in the node_modules and vendor directories are externally +maintained libraries used by this software which have their own +licenses; we recommend you read them, as their terms may differ from the +terms above. diff --git a/node_modules/lodash.isinteger/README.md b/node_modules/lodash.isinteger/README.md new file mode 100644 index 0000000..3a78567 --- /dev/null +++ b/node_modules/lodash.isinteger/README.md @@ -0,0 +1,18 @@ +# lodash.isinteger v4.0.4 + +The [lodash](https://lodash.com/) method `_.isInteger` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.isinteger +``` + +In Node.js: +```js +var isInteger = require('lodash.isinteger'); +``` + +See the [documentation](https://lodash.com/docs#isInteger) or [package source](https://github.com/lodash/lodash/blob/4.0.4-npm-packages/lodash.isinteger) for more details. diff --git a/node_modules/lodash.isinteger/index.js b/node_modules/lodash.isinteger/index.js new file mode 100644 index 0000000..3bf06f0 --- /dev/null +++ b/node_modules/lodash.isinteger/index.js @@ -0,0 +1,265 @@ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; + +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; + +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; + +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Checks if `value` is an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @example + * + * _.isInteger(3); + * // => true + * + * _.isInteger(Number.MIN_VALUE); + * // => false + * + * _.isInteger(Infinity); + * // => false + * + * _.isInteger('3'); + * // => false + */ +function isInteger(value) { + return typeof value == 'number' && value == toInteger(value); +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} + +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ +function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; +} + +/** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ +function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; +} + +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} + +module.exports = isInteger; diff --git a/node_modules/lodash.isinteger/package.json b/node_modules/lodash.isinteger/package.json new file mode 100644 index 0000000..92db256 --- /dev/null +++ b/node_modules/lodash.isinteger/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.isinteger", + "version": "4.0.4", + "description": "The lodash method `_.isInteger` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, isinteger", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/lodash.isnumber/LICENSE b/node_modules/lodash.isnumber/LICENSE new file mode 100644 index 0000000..b054ca5 --- /dev/null +++ b/node_modules/lodash.isnumber/LICENSE @@ -0,0 +1,22 @@ +Copyright 2012-2016 The Dojo Foundation +Based on Underscore.js, copyright 2009-2016 Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/lodash.isnumber/README.md b/node_modules/lodash.isnumber/README.md new file mode 100644 index 0000000..a1d434d --- /dev/null +++ b/node_modules/lodash.isnumber/README.md @@ -0,0 +1,18 @@ +# lodash.isnumber v3.0.3 + +The [lodash](https://lodash.com/) method `_.isNumber` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.isnumber +``` + +In Node.js: +```js +var isNumber = require('lodash.isnumber'); +``` + +See the [documentation](https://lodash.com/docs#isNumber) or [package source](https://github.com/lodash/lodash/blob/3.0.3-npm-packages/lodash.isnumber) for more details. diff --git a/node_modules/lodash.isnumber/index.js b/node_modules/lodash.isnumber/index.js new file mode 100644 index 0000000..35a8573 --- /dev/null +++ b/node_modules/lodash.isnumber/index.js @@ -0,0 +1,79 @@ +/** + * lodash 3.0.3 (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright 2012-2016 The Dojo Foundation + * Based on Underscore.js 1.8.3 + * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ + +/** `Object#toString` result references. */ +var numberTag = '[object Number]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified + * as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ +function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && objectToString.call(value) == numberTag); +} + +module.exports = isNumber; diff --git a/node_modules/lodash.isnumber/package.json b/node_modules/lodash.isnumber/package.json new file mode 100644 index 0000000..4c33c2a --- /dev/null +++ b/node_modules/lodash.isnumber/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.isnumber", + "version": "3.0.3", + "description": "The lodash method `_.isNumber` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, isnumber", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/lodash.isplainobject/LICENSE b/node_modules/lodash.isplainobject/LICENSE new file mode 100644 index 0000000..e0c69d5 --- /dev/null +++ b/node_modules/lodash.isplainobject/LICENSE @@ -0,0 +1,47 @@ +Copyright jQuery Foundation and other contributors + +Based on Underscore.js, copyright Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at https://github.com/lodash/lodash + +The following license applies to all parts of this software except as +documented below: + +==== + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +==== + +Copyright and related rights for sample code are waived via CC0. Sample +code is defined as all source code displayed within the prose of the +documentation. + +CC0: http://creativecommons.org/publicdomain/zero/1.0/ + +==== + +Files located in the node_modules and vendor directories are externally +maintained libraries used by this software which have their own +licenses; we recommend you read them, as their terms may differ from the +terms above. diff --git a/node_modules/lodash.isplainobject/README.md b/node_modules/lodash.isplainobject/README.md new file mode 100644 index 0000000..aeefd74 --- /dev/null +++ b/node_modules/lodash.isplainobject/README.md @@ -0,0 +1,18 @@ +# lodash.isplainobject v4.0.6 + +The [lodash](https://lodash.com/) method `_.isPlainObject` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.isplainobject +``` + +In Node.js: +```js +var isPlainObject = require('lodash.isplainobject'); +``` + +See the [documentation](https://lodash.com/docs#isPlainObject) or [package source](https://github.com/lodash/lodash/blob/4.0.6-npm-packages/lodash.isplainobject) for more details. diff --git a/node_modules/lodash.isplainobject/index.js b/node_modules/lodash.isplainobject/index.js new file mode 100644 index 0000000..0f820ee --- /dev/null +++ b/node_modules/lodash.isplainobject/index.js @@ -0,0 +1,139 @@ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** `Object#toString` result references. */ +var objectTag = '[object Object]'; + +/** + * Checks if `value` is a host object in IE < 9. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a host object, else `false`. + */ +function isHostObject(value) { + // Many host objects are `Object` objects that can coerce to strings + // despite having improperly defined `toString` methods. + var result = false; + if (value != null && typeof value.toString != 'function') { + try { + result = !!(value + ''); + } catch (e) {} + } + return result; +} + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +/** Used for built-in method references. */ +var funcProto = Function.prototype, + objectProto = Object.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** Used to infer the `Object` constructor. */ +var objectCtorString = funcToString.call(Object); + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** Built-in value references. */ +var getPrototype = overArg(Object.getPrototypeOf, Object); + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ +function isPlainObject(value) { + if (!isObjectLike(value) || + objectToString.call(value) != objectTag || isHostObject(value)) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return (typeof Ctor == 'function' && + Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); +} + +module.exports = isPlainObject; diff --git a/node_modules/lodash.isplainobject/package.json b/node_modules/lodash.isplainobject/package.json new file mode 100644 index 0000000..86f6a07 --- /dev/null +++ b/node_modules/lodash.isplainobject/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.isplainobject", + "version": "4.0.6", + "description": "The lodash method `_.isPlainObject` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, isplainobject", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/lodash.isstring/LICENSE b/node_modules/lodash.isstring/LICENSE new file mode 100644 index 0000000..b054ca5 --- /dev/null +++ b/node_modules/lodash.isstring/LICENSE @@ -0,0 +1,22 @@ +Copyright 2012-2016 The Dojo Foundation +Based on Underscore.js, copyright 2009-2016 Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/lodash.isstring/README.md b/node_modules/lodash.isstring/README.md new file mode 100644 index 0000000..f184029 --- /dev/null +++ b/node_modules/lodash.isstring/README.md @@ -0,0 +1,18 @@ +# lodash.isstring v4.0.1 + +The [lodash](https://lodash.com/) method `_.isString` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.isstring +``` + +In Node.js: +```js +var isString = require('lodash.isstring'); +``` + +See the [documentation](https://lodash.com/docs#isString) or [package source](https://github.com/lodash/lodash/blob/4.0.1-npm-packages/lodash.isstring) for more details. diff --git a/node_modules/lodash.isstring/index.js b/node_modules/lodash.isstring/index.js new file mode 100644 index 0000000..408225c --- /dev/null +++ b/node_modules/lodash.isstring/index.js @@ -0,0 +1,95 @@ +/** + * lodash 4.0.1 (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright 2012-2016 The Dojo Foundation + * Based on Underscore.js 1.8.3 + * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ + +/** `Object#toString` result references. */ +var stringTag = '[object String]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @type Function + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ +function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); +} + +module.exports = isString; diff --git a/node_modules/lodash.isstring/package.json b/node_modules/lodash.isstring/package.json new file mode 100644 index 0000000..1331535 --- /dev/null +++ b/node_modules/lodash.isstring/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.isstring", + "version": "4.0.1", + "description": "The lodash method `_.isString` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, isstring", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/lodash.once/LICENSE b/node_modules/lodash.once/LICENSE new file mode 100644 index 0000000..e0c69d5 --- /dev/null +++ b/node_modules/lodash.once/LICENSE @@ -0,0 +1,47 @@ +Copyright jQuery Foundation and other contributors + +Based on Underscore.js, copyright Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at https://github.com/lodash/lodash + +The following license applies to all parts of this software except as +documented below: + +==== + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +==== + +Copyright and related rights for sample code are waived via CC0. Sample +code is defined as all source code displayed within the prose of the +documentation. + +CC0: http://creativecommons.org/publicdomain/zero/1.0/ + +==== + +Files located in the node_modules and vendor directories are externally +maintained libraries used by this software which have their own +licenses; we recommend you read them, as their terms may differ from the +terms above. diff --git a/node_modules/lodash.once/README.md b/node_modules/lodash.once/README.md new file mode 100644 index 0000000..c4a2f16 --- /dev/null +++ b/node_modules/lodash.once/README.md @@ -0,0 +1,18 @@ +# lodash.once v4.1.1 + +The [lodash](https://lodash.com/) method `_.once` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.once +``` + +In Node.js: +```js +var once = require('lodash.once'); +``` + +See the [documentation](https://lodash.com/docs#once) or [package source](https://github.com/lodash/lodash/blob/4.1.1-npm-packages/lodash.once) for more details. diff --git a/node_modules/lodash.once/index.js b/node_modules/lodash.once/index.js new file mode 100644 index 0000000..414ceb3 --- /dev/null +++ b/node_modules/lodash.once/index.js @@ -0,0 +1,294 @@ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; + +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; + +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; + +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */ +function before(n, func) { + var result; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; +} + +/** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first invocation. The `func` is + * invoked with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */ +function once(func) { + return before(2, func); +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} + +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ +function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; +} + +/** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ +function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; +} + +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} + +module.exports = once; diff --git a/node_modules/lodash.once/package.json b/node_modules/lodash.once/package.json new file mode 100644 index 0000000..fae782c --- /dev/null +++ b/node_modules/lodash.once/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.once", + "version": "4.1.1", + "description": "The lodash method `_.once` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, once", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/math-intrinsics/.eslintrc b/node_modules/math-intrinsics/.eslintrc new file mode 100644 index 0000000..d90a1bc --- /dev/null +++ b/node_modules/math-intrinsics/.eslintrc @@ -0,0 +1,16 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "eqeqeq": ["error", "allow-null"], + "id-length": "off", + "new-cap": ["error", { + "capIsNewExceptions": [ + "RequireObjectCoercible", + "ToObject", + ], + }], + }, +} diff --git a/node_modules/math-intrinsics/.github/FUNDING.yml b/node_modules/math-intrinsics/.github/FUNDING.yml new file mode 100644 index 0000000..868f4ff --- /dev/null +++ b/node_modules/math-intrinsics/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/math-intrinsics +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/math-intrinsics/CHANGELOG.md b/node_modules/math-intrinsics/CHANGELOG.md new file mode 100644 index 0000000..9cf48f5 --- /dev/null +++ b/node_modules/math-intrinsics/CHANGELOG.md @@ -0,0 +1,24 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.0](https://github.com/es-shims/math-intrinsics/compare/v1.0.0...v1.1.0) - 2024-12-18 + +### Commits + +- [New] add `round` [`7cfb044`](https://github.com/es-shims/math-intrinsics/commit/7cfb04460c0fbdf1ca101eecbac3f59d11994130) +- [Tests] add attw [`e96be8f`](https://github.com/es-shims/math-intrinsics/commit/e96be8fbf58449eafe976446a0470e6ea561ad8d) +- [Dev Deps] update `@types/tape` [`30d0023`](https://github.com/es-shims/math-intrinsics/commit/30d00234ce8a3fa0094a61cd55d6686eb91e36ec) + +## v1.0.0 - 2024-12-11 + +### Commits + +- Initial implementation, tests, readme, types [`b898caa`](https://github.com/es-shims/math-intrinsics/commit/b898caae94e9994a94a42b8740f7bbcfd0a868fe) +- Initial commit [`02745b0`](https://github.com/es-shims/math-intrinsics/commit/02745b03a62255af8a332771987b55d127538d9c) +- [New] add `constants/maxArrayLength`, `mod` [`b978178`](https://github.com/es-shims/math-intrinsics/commit/b978178a57685bd23ed1c7efe2137f3784f5fcc5) +- npm init [`a39fc57`](https://github.com/es-shims/math-intrinsics/commit/a39fc57e5639a645d0bd52a0dc56202480223be2) +- Only apps should have lockfiles [`9451580`](https://github.com/es-shims/math-intrinsics/commit/94515800fb34db4f3cc7e99290042d45609ac7bd) diff --git a/node_modules/math-intrinsics/LICENSE b/node_modules/math-intrinsics/LICENSE new file mode 100644 index 0000000..34995e7 --- /dev/null +++ b/node_modules/math-intrinsics/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 ECMAScript Shims + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/math-intrinsics/README.md b/node_modules/math-intrinsics/README.md new file mode 100644 index 0000000..4a66dcf --- /dev/null +++ b/node_modules/math-intrinsics/README.md @@ -0,0 +1,50 @@ +# math-intrinsics [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +ES Math-related intrinsics and helpers, robustly cached. + + - `abs` + - `floor` + - `isFinite` + - `isInteger` + - `isNaN` + - `isNegativeZero` + - `max` + - `min` + - `mod` + - `pow` + - `round` + - `sign` + - `constants/maxArrayLength` + - `constants/maxSafeInteger` + - `constants/maxValue` + + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +[package-url]: https://npmjs.org/package/math-intrinsics +[npm-version-svg]: https://versionbadg.es/es-shims/math-intrinsics.svg +[deps-svg]: https://david-dm.org/es-shims/math-intrinsics.svg +[deps-url]: https://david-dm.org/es-shims/math-intrinsics +[dev-deps-svg]: https://david-dm.org/es-shims/math-intrinsics/dev-status.svg +[dev-deps-url]: https://david-dm.org/es-shims/math-intrinsics#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/math-intrinsics.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/math-intrinsics.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/es-object.svg +[downloads-url]: https://npm-stat.com/charts.html?package=math-intrinsics +[codecov-image]: https://codecov.io/gh/es-shims/math-intrinsics/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/es-shims/math-intrinsics/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/es-shims/math-intrinsics +[actions-url]: https://github.com/es-shims/math-intrinsics/actions diff --git a/node_modules/math-intrinsics/abs.d.ts b/node_modules/math-intrinsics/abs.d.ts new file mode 100644 index 0000000..14ad9c6 --- /dev/null +++ b/node_modules/math-intrinsics/abs.d.ts @@ -0,0 +1 @@ +export = Math.abs; \ No newline at end of file diff --git a/node_modules/math-intrinsics/abs.js b/node_modules/math-intrinsics/abs.js new file mode 100644 index 0000000..a751424 --- /dev/null +++ b/node_modules/math-intrinsics/abs.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./abs')} */ +module.exports = Math.abs; diff --git a/node_modules/math-intrinsics/constants/maxArrayLength.d.ts b/node_modules/math-intrinsics/constants/maxArrayLength.d.ts new file mode 100644 index 0000000..b92d46b --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxArrayLength.d.ts @@ -0,0 +1,3 @@ +declare const MAX_ARRAY_LENGTH: 4294967295; + +export = MAX_ARRAY_LENGTH; \ No newline at end of file diff --git a/node_modules/math-intrinsics/constants/maxArrayLength.js b/node_modules/math-intrinsics/constants/maxArrayLength.js new file mode 100644 index 0000000..cfc6aff --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxArrayLength.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./maxArrayLength')} */ +module.exports = 4294967295; // Math.pow(2, 32) - 1; diff --git a/node_modules/math-intrinsics/constants/maxSafeInteger.d.ts b/node_modules/math-intrinsics/constants/maxSafeInteger.d.ts new file mode 100644 index 0000000..fee3f62 --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxSafeInteger.d.ts @@ -0,0 +1,3 @@ +declare const MAX_SAFE_INTEGER: 9007199254740991; + +export = MAX_SAFE_INTEGER; \ No newline at end of file diff --git a/node_modules/math-intrinsics/constants/maxSafeInteger.js b/node_modules/math-intrinsics/constants/maxSafeInteger.js new file mode 100644 index 0000000..b568ad3 --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxSafeInteger.js @@ -0,0 +1,5 @@ +'use strict'; + +/** @type {import('./maxSafeInteger')} */ +// eslint-disable-next-line no-extra-parens +module.exports = /** @type {import('./maxSafeInteger')} */ (Number.MAX_SAFE_INTEGER) || 9007199254740991; // Math.pow(2, 53) - 1; diff --git a/node_modules/math-intrinsics/constants/maxValue.d.ts b/node_modules/math-intrinsics/constants/maxValue.d.ts new file mode 100644 index 0000000..292cb82 --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxValue.d.ts @@ -0,0 +1,3 @@ +declare const MAX_VALUE: 1.7976931348623157e+308; + +export = MAX_VALUE; diff --git a/node_modules/math-intrinsics/constants/maxValue.js b/node_modules/math-intrinsics/constants/maxValue.js new file mode 100644 index 0000000..a2202dc --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxValue.js @@ -0,0 +1,5 @@ +'use strict'; + +/** @type {import('./maxValue')} */ +// eslint-disable-next-line no-extra-parens +module.exports = /** @type {import('./maxValue')} */ (Number.MAX_VALUE) || 1.7976931348623157e+308; diff --git a/node_modules/math-intrinsics/floor.d.ts b/node_modules/math-intrinsics/floor.d.ts new file mode 100644 index 0000000..9265236 --- /dev/null +++ b/node_modules/math-intrinsics/floor.d.ts @@ -0,0 +1 @@ +export = Math.floor; \ No newline at end of file diff --git a/node_modules/math-intrinsics/floor.js b/node_modules/math-intrinsics/floor.js new file mode 100644 index 0000000..ab0e5d7 --- /dev/null +++ b/node_modules/math-intrinsics/floor.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./floor')} */ +module.exports = Math.floor; diff --git a/node_modules/math-intrinsics/isFinite.d.ts b/node_modules/math-intrinsics/isFinite.d.ts new file mode 100644 index 0000000..6daae33 --- /dev/null +++ b/node_modules/math-intrinsics/isFinite.d.ts @@ -0,0 +1,3 @@ +declare function isFinite(x: unknown): x is number | bigint; + +export = isFinite; \ No newline at end of file diff --git a/node_modules/math-intrinsics/isFinite.js b/node_modules/math-intrinsics/isFinite.js new file mode 100644 index 0000000..b201a5a --- /dev/null +++ b/node_modules/math-intrinsics/isFinite.js @@ -0,0 +1,12 @@ +'use strict'; + +var $isNaN = require('./isNaN'); + +/** @type {import('./isFinite')} */ +module.exports = function isFinite(x) { + return (typeof x === 'number' || typeof x === 'bigint') + && !$isNaN(x) + && x !== Infinity + && x !== -Infinity; +}; + diff --git a/node_modules/math-intrinsics/isInteger.d.ts b/node_modules/math-intrinsics/isInteger.d.ts new file mode 100644 index 0000000..13935a8 --- /dev/null +++ b/node_modules/math-intrinsics/isInteger.d.ts @@ -0,0 +1,3 @@ +declare function isInteger(argument: unknown): argument is number; + +export = isInteger; \ No newline at end of file diff --git a/node_modules/math-intrinsics/isInteger.js b/node_modules/math-intrinsics/isInteger.js new file mode 100644 index 0000000..4b1b9a5 --- /dev/null +++ b/node_modules/math-intrinsics/isInteger.js @@ -0,0 +1,16 @@ +'use strict'; + +var $abs = require('./abs'); +var $floor = require('./floor'); + +var $isNaN = require('./isNaN'); +var $isFinite = require('./isFinite'); + +/** @type {import('./isInteger')} */ +module.exports = function isInteger(argument) { + if (typeof argument !== 'number' || $isNaN(argument) || !$isFinite(argument)) { + return false; + } + var absValue = $abs(argument); + return $floor(absValue) === absValue; +}; diff --git a/node_modules/math-intrinsics/isNaN.d.ts b/node_modules/math-intrinsics/isNaN.d.ts new file mode 100644 index 0000000..c1d4c55 --- /dev/null +++ b/node_modules/math-intrinsics/isNaN.d.ts @@ -0,0 +1 @@ +export = Number.isNaN; \ No newline at end of file diff --git a/node_modules/math-intrinsics/isNaN.js b/node_modules/math-intrinsics/isNaN.js new file mode 100644 index 0000000..e36475c --- /dev/null +++ b/node_modules/math-intrinsics/isNaN.js @@ -0,0 +1,6 @@ +'use strict'; + +/** @type {import('./isNaN')} */ +module.exports = Number.isNaN || function isNaN(a) { + return a !== a; +}; diff --git a/node_modules/math-intrinsics/isNegativeZero.d.ts b/node_modules/math-intrinsics/isNegativeZero.d.ts new file mode 100644 index 0000000..7ad8819 --- /dev/null +++ b/node_modules/math-intrinsics/isNegativeZero.d.ts @@ -0,0 +1,3 @@ +declare function isNegativeZero(x: unknown): boolean; + +export = isNegativeZero; \ No newline at end of file diff --git a/node_modules/math-intrinsics/isNegativeZero.js b/node_modules/math-intrinsics/isNegativeZero.js new file mode 100644 index 0000000..b69adcc --- /dev/null +++ b/node_modules/math-intrinsics/isNegativeZero.js @@ -0,0 +1,6 @@ +'use strict'; + +/** @type {import('./isNegativeZero')} */ +module.exports = function isNegativeZero(x) { + return x === 0 && 1 / x === 1 / -0; +}; diff --git a/node_modules/math-intrinsics/max.d.ts b/node_modules/math-intrinsics/max.d.ts new file mode 100644 index 0000000..ad6f43e --- /dev/null +++ b/node_modules/math-intrinsics/max.d.ts @@ -0,0 +1 @@ +export = Math.max; \ No newline at end of file diff --git a/node_modules/math-intrinsics/max.js b/node_modules/math-intrinsics/max.js new file mode 100644 index 0000000..edb55df --- /dev/null +++ b/node_modules/math-intrinsics/max.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./max')} */ +module.exports = Math.max; diff --git a/node_modules/math-intrinsics/min.d.ts b/node_modules/math-intrinsics/min.d.ts new file mode 100644 index 0000000..fd90f2d --- /dev/null +++ b/node_modules/math-intrinsics/min.d.ts @@ -0,0 +1 @@ +export = Math.min; \ No newline at end of file diff --git a/node_modules/math-intrinsics/min.js b/node_modules/math-intrinsics/min.js new file mode 100644 index 0000000..5a4a7c7 --- /dev/null +++ b/node_modules/math-intrinsics/min.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./min')} */ +module.exports = Math.min; diff --git a/node_modules/math-intrinsics/mod.d.ts b/node_modules/math-intrinsics/mod.d.ts new file mode 100644 index 0000000..549dbd4 --- /dev/null +++ b/node_modules/math-intrinsics/mod.d.ts @@ -0,0 +1,3 @@ +declare function mod(number: number, modulo: number): number; + +export = mod; \ No newline at end of file diff --git a/node_modules/math-intrinsics/mod.js b/node_modules/math-intrinsics/mod.js new file mode 100644 index 0000000..4a98362 --- /dev/null +++ b/node_modules/math-intrinsics/mod.js @@ -0,0 +1,9 @@ +'use strict'; + +var $floor = require('./floor'); + +/** @type {import('./mod')} */ +module.exports = function mod(number, modulo) { + var remain = number % modulo; + return $floor(remain >= 0 ? remain : remain + modulo); +}; diff --git a/node_modules/math-intrinsics/package.json b/node_modules/math-intrinsics/package.json new file mode 100644 index 0000000..0676273 --- /dev/null +++ b/node_modules/math-intrinsics/package.json @@ -0,0 +1,86 @@ +{ + "name": "math-intrinsics", + "version": "1.1.0", + "description": "ES Math-related intrinsics and helpers, robustly cached.", + "main": false, + "exports": { + "./abs": "./abs.js", + "./floor": "./floor.js", + "./isFinite": "./isFinite.js", + "./isInteger": "./isInteger.js", + "./isNaN": "./isNaN.js", + "./isNegativeZero": "./isNegativeZero.js", + "./max": "./max.js", + "./min": "./min.js", + "./mod": "./mod.js", + "./pow": "./pow.js", + "./sign": "./sign.js", + "./round": "./round.js", + "./constants/maxArrayLength": "./constants/maxArrayLength.js", + "./constants/maxSafeInteger": "./constants/maxSafeInteger.js", + "./constants/maxValue": "./constants/maxValue.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/**/*.js'", + "posttest": "npx npm@'>= 10.2' audit --production", + "prelint": "evalmd README.md && eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git' | grep -v dist/)", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc && attw -P", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/es-shims/math-intrinsics.git" + }, + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/es-shims/math-intrinsics/issues" + }, + "homepage": "https://github.com/es-shims/math-intrinsics#readme", + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.1", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.2", + "@types/for-each": "^0.3.3", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.8.0", + "auto-changelog": "^2.5.0", + "eclint": "^2.8.1", + "es-value-fixtures": "^1.5.0", + "eslint": "^8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.3", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/math-intrinsics/pow.d.ts b/node_modules/math-intrinsics/pow.d.ts new file mode 100644 index 0000000..5873c44 --- /dev/null +++ b/node_modules/math-intrinsics/pow.d.ts @@ -0,0 +1 @@ +export = Math.pow; \ No newline at end of file diff --git a/node_modules/math-intrinsics/pow.js b/node_modules/math-intrinsics/pow.js new file mode 100644 index 0000000..c0a4103 --- /dev/null +++ b/node_modules/math-intrinsics/pow.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./pow')} */ +module.exports = Math.pow; diff --git a/node_modules/math-intrinsics/round.d.ts b/node_modules/math-intrinsics/round.d.ts new file mode 100644 index 0000000..da1fde3 --- /dev/null +++ b/node_modules/math-intrinsics/round.d.ts @@ -0,0 +1 @@ +export = Math.round; \ No newline at end of file diff --git a/node_modules/math-intrinsics/round.js b/node_modules/math-intrinsics/round.js new file mode 100644 index 0000000..b792156 --- /dev/null +++ b/node_modules/math-intrinsics/round.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./round')} */ +module.exports = Math.round; diff --git a/node_modules/math-intrinsics/sign.d.ts b/node_modules/math-intrinsics/sign.d.ts new file mode 100644 index 0000000..c49ceca --- /dev/null +++ b/node_modules/math-intrinsics/sign.d.ts @@ -0,0 +1,3 @@ +declare function sign(x: number): number; + +export = sign; \ No newline at end of file diff --git a/node_modules/math-intrinsics/sign.js b/node_modules/math-intrinsics/sign.js new file mode 100644 index 0000000..9e5173c --- /dev/null +++ b/node_modules/math-intrinsics/sign.js @@ -0,0 +1,11 @@ +'use strict'; + +var $isNaN = require('./isNaN'); + +/** @type {import('./sign')} */ +module.exports = function sign(number) { + if ($isNaN(number) || number === 0) { + return number; + } + return number < 0 ? -1 : +1; +}; diff --git a/node_modules/math-intrinsics/test/index.js b/node_modules/math-intrinsics/test/index.js new file mode 100644 index 0000000..0f90a5d --- /dev/null +++ b/node_modules/math-intrinsics/test/index.js @@ -0,0 +1,192 @@ +'use strict'; + +var test = require('tape'); +var v = require('es-value-fixtures'); +var forEach = require('for-each'); +var inspect = require('object-inspect'); + +var abs = require('../abs'); +var floor = require('../floor'); +var isFinite = require('../isFinite'); +var isInteger = require('../isInteger'); +var isNaN = require('../isNaN'); +var isNegativeZero = require('../isNegativeZero'); +var max = require('../max'); +var min = require('../min'); +var mod = require('../mod'); +var pow = require('../pow'); +var round = require('../round'); +var sign = require('../sign'); + +var maxArrayLength = require('../constants/maxArrayLength'); +var maxSafeInteger = require('../constants/maxSafeInteger'); +var maxValue = require('../constants/maxValue'); + +test('abs', function (t) { + t.equal(abs(-1), 1, 'abs(-1) === 1'); + t.equal(abs(+1), 1, 'abs(+1) === 1'); + t.equal(abs(+0), +0, 'abs(+0) === +0'); + t.equal(abs(-0), +0, 'abs(-0) === +0'); + + t.end(); +}); + +test('floor', function (t) { + t.equal(floor(-1.1), -2, 'floor(-1.1) === -2'); + t.equal(floor(+1.1), 1, 'floor(+1.1) === 1'); + t.equal(floor(+0), +0, 'floor(+0) === +0'); + t.equal(floor(-0), -0, 'floor(-0) === -0'); + t.equal(floor(-Infinity), -Infinity, 'floor(-Infinity) === -Infinity'); + t.equal(floor(Number(Infinity)), Number(Infinity), 'floor(+Infinity) === +Infinity'); + t.equal(floor(NaN), NaN, 'floor(NaN) === NaN'); + t.equal(floor(0), +0, 'floor(0) === +0'); + t.equal(floor(-0), -0, 'floor(-0) === -0'); + t.equal(floor(1), 1, 'floor(1) === 1'); + t.equal(floor(-1), -1, 'floor(-1) === -1'); + t.equal(floor(1.1), 1, 'floor(1.1) === 1'); + t.equal(floor(-1.1), -2, 'floor(-1.1) === -2'); + t.equal(floor(maxValue), maxValue, 'floor(maxValue) === maxValue'); + t.equal(floor(maxSafeInteger), maxSafeInteger, 'floor(maxSafeInteger) === maxSafeInteger'); + + t.end(); +}); + +test('isFinite', function (t) { + t.equal(isFinite(0), true, 'isFinite(+0) === true'); + t.equal(isFinite(-0), true, 'isFinite(-0) === true'); + t.equal(isFinite(1), true, 'isFinite(1) === true'); + t.equal(isFinite(Infinity), false, 'isFinite(Infinity) === false'); + t.equal(isFinite(-Infinity), false, 'isFinite(-Infinity) === false'); + t.equal(isFinite(NaN), false, 'isFinite(NaN) === false'); + + forEach(v.nonNumbers, function (nonNumber) { + t.equal(isFinite(nonNumber), false, 'isFinite(' + inspect(nonNumber) + ') === false'); + }); + + t.end(); +}); + +test('isInteger', function (t) { + forEach([].concat( + // @ts-expect-error TS sucks with concat + v.nonNumbers, + v.nonIntegerNumbers + ), function (nonInteger) { + t.equal(isInteger(nonInteger), false, 'isInteger(' + inspect(nonInteger) + ') === false'); + }); + + t.end(); +}); + +test('isNaN', function (t) { + forEach([].concat( + // @ts-expect-error TS sucks with concat + v.nonNumbers, + v.infinities, + v.zeroes, + v.integerNumbers + ), function (nonNaN) { + t.equal(isNaN(nonNaN), false, 'isNaN(' + inspect(nonNaN) + ') === false'); + }); + + t.equal(isNaN(NaN), true, 'isNaN(NaN) === true'); + + t.end(); +}); + +test('isNegativeZero', function (t) { + t.equal(isNegativeZero(-0), true, 'isNegativeZero(-0) === true'); + t.equal(isNegativeZero(+0), false, 'isNegativeZero(+0) === false'); + t.equal(isNegativeZero(1), false, 'isNegativeZero(1) === false'); + t.equal(isNegativeZero(-1), false, 'isNegativeZero(-1) === false'); + t.equal(isNegativeZero(NaN), false, 'isNegativeZero(NaN) === false'); + t.equal(isNegativeZero(Infinity), false, 'isNegativeZero(Infinity) === false'); + t.equal(isNegativeZero(-Infinity), false, 'isNegativeZero(-Infinity) === false'); + + forEach(v.nonNumbers, function (nonNumber) { + t.equal(isNegativeZero(nonNumber), false, 'isNegativeZero(' + inspect(nonNumber) + ') === false'); + }); + + t.end(); +}); + +test('max', function (t) { + t.equal(max(1, 2), 2, 'max(1, 2) === 2'); + t.equal(max(1, 2, 3), 3, 'max(1, 2, 3) === 3'); + t.equal(max(1, 2, 3, 4), 4, 'max(1, 2, 3, 4) === 4'); + t.equal(max(1, 2, 3, 4, 5), 5, 'max(1, 2, 3, 4, 5) === 5'); + t.equal(max(1, 2, 3, 4, 5, 6), 6, 'max(1, 2, 3, 4, 5, 6) === 6'); + t.equal(max(1, 2, 3, 4, 5, 6, 7), 7, 'max(1, 2, 3, 4, 5, 6, 7) === 7'); + + t.end(); +}); + +test('min', function (t) { + t.equal(min(1, 2), 1, 'min(1, 2) === 1'); + t.equal(min(1, 2, 3), 1, 'min(1, 2, 3) === 1'); + t.equal(min(1, 2, 3, 4), 1, 'min(1, 2, 3, 4) === 1'); + t.equal(min(1, 2, 3, 4, 5), 1, 'min(1, 2, 3, 4, 5) === 1'); + t.equal(min(1, 2, 3, 4, 5, 6), 1, 'min(1, 2, 3, 4, 5, 6) === 1'); + + t.end(); +}); + +test('mod', function (t) { + t.equal(mod(1, 2), 1, 'mod(1, 2) === 1'); + t.equal(mod(2, 2), 0, 'mod(2, 2) === 0'); + t.equal(mod(3, 2), 1, 'mod(3, 2) === 1'); + t.equal(mod(4, 2), 0, 'mod(4, 2) === 0'); + t.equal(mod(5, 2), 1, 'mod(5, 2) === 1'); + t.equal(mod(6, 2), 0, 'mod(6, 2) === 0'); + t.equal(mod(7, 2), 1, 'mod(7, 2) === 1'); + t.equal(mod(8, 2), 0, 'mod(8, 2) === 0'); + t.equal(mod(9, 2), 1, 'mod(9, 2) === 1'); + t.equal(mod(10, 2), 0, 'mod(10, 2) === 0'); + t.equal(mod(11, 2), 1, 'mod(11, 2) === 1'); + + t.end(); +}); + +test('pow', function (t) { + t.equal(pow(2, 2), 4, 'pow(2, 2) === 4'); + t.equal(pow(2, 3), 8, 'pow(2, 3) === 8'); + t.equal(pow(2, 4), 16, 'pow(2, 4) === 16'); + t.equal(pow(2, 5), 32, 'pow(2, 5) === 32'); + t.equal(pow(2, 6), 64, 'pow(2, 6) === 64'); + t.equal(pow(2, 7), 128, 'pow(2, 7) === 128'); + t.equal(pow(2, 8), 256, 'pow(2, 8) === 256'); + t.equal(pow(2, 9), 512, 'pow(2, 9) === 512'); + t.equal(pow(2, 10), 1024, 'pow(2, 10) === 1024'); + + t.end(); +}); + +test('round', function (t) { + t.equal(round(1.1), 1, 'round(1.1) === 1'); + t.equal(round(1.5), 2, 'round(1.5) === 2'); + t.equal(round(1.9), 2, 'round(1.9) === 2'); + + t.end(); +}); + +test('sign', function (t) { + t.equal(sign(-1), -1, 'sign(-1) === -1'); + t.equal(sign(+1), +1, 'sign(+1) === +1'); + t.equal(sign(+0), +0, 'sign(+0) === +0'); + t.equal(sign(-0), -0, 'sign(-0) === -0'); + t.equal(sign(NaN), NaN, 'sign(NaN) === NaN'); + t.equal(sign(Infinity), +1, 'sign(Infinity) === +1'); + t.equal(sign(-Infinity), -1, 'sign(-Infinity) === -1'); + t.equal(sign(maxValue), +1, 'sign(maxValue) === +1'); + t.equal(sign(maxSafeInteger), +1, 'sign(maxSafeInteger) === +1'); + + t.end(); +}); + +test('constants', function (t) { + t.equal(typeof maxArrayLength, 'number', 'typeof maxArrayLength === "number"'); + t.equal(typeof maxSafeInteger, 'number', 'typeof maxSafeInteger === "number"'); + t.equal(typeof maxValue, 'number', 'typeof maxValue === "number"'); + + t.end(); +}); diff --git a/node_modules/math-intrinsics/tsconfig.json b/node_modules/math-intrinsics/tsconfig.json new file mode 100644 index 0000000..b131000 --- /dev/null +++ b/node_modules/math-intrinsics/tsconfig.json @@ -0,0 +1,3 @@ +{ + "extends": "@ljharb/tsconfig", +} diff --git a/node_modules/media-typer/HISTORY.md b/node_modules/media-typer/HISTORY.md new file mode 100644 index 0000000..538ade1 --- /dev/null +++ b/node_modules/media-typer/HISTORY.md @@ -0,0 +1,50 @@ +1.1.0 / 2019-04-24 +================== + + * Add `test(string)` function + +1.0.2 / 2019-04-19 +================== + + * Fix JSDoc comment for `parse` function + +1.0.1 / 2018-10-20 +================== + + * Remove left over `parameters` property from class + +1.0.0 / 2018-10-20 +================== + +This major release brings the module back to it's RFC 6838 roots. If you want +a module to parse the `Content-Type` or similar HTTP headers, use the +`content-type` module instead. + + * Drop support for Node.js below 0.8 + * Remove parameter handling, which is outside RFC 6838 scope + * Remove `parse(req)` and `parse(res)` signatures + * perf: enable strict mode + * perf: use a class for object creation + +0.3.0 / 2014-09-07 +================== + + * Support Node.js 0.6 + * Throw error when parameter format invalid on parse + +0.2.0 / 2014-06-18 +================== + + * Add `typer.format()` to format media types + +0.1.0 / 2014-06-17 +================== + + * Accept `req` as argument to `parse` + * Accept `res` as argument to `parse` + * Parse media type with extra LWS between type and first parameter + +0.0.0 / 2014-06-13 +================== + + * Initial implementation diff --git a/node_modules/media-typer/LICENSE b/node_modules/media-typer/LICENSE new file mode 100644 index 0000000..84441fb --- /dev/null +++ b/node_modules/media-typer/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/media-typer/README.md b/node_modules/media-typer/README.md new file mode 100644 index 0000000..37edad1 --- /dev/null +++ b/node_modules/media-typer/README.md @@ -0,0 +1,93 @@ +# media-typer + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Simple RFC 6838 media type parser. + +This module will parse a given media type into it's component parts, like type, +subtype, and suffix. A formatter is also provided to put them back together and +the two can be combined to normalize media types into a canonical form. + +If you are looking to parse the string that represents a media type and it's +parameters in HTTP (for example, the `Content-Type` header), use the +[content-type module](https://www.npmjs.com/package/content-type). + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install media-typer +``` + +## API + + + +```js +var typer = require('media-typer') +``` + +### typer.parse(string) + + + +```js +var obj = typer.parse('image/svg+xml') +``` + +Parse a media type string. This will return an object with the following +properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The type of the media type (always lower case). Example: `'image'` + + - `subtype`: The subtype of the media type (always lower case). Example: `'svg'` + + - `suffix`: The suffix of the media type (always lower case). Example: `'xml'` + +If the given type string is invalid, then a `TypeError` is thrown. + +### typer.format(obj) + + + +```js +var obj = typer.format({ type: 'image', subtype: 'svg', suffix: 'xml' }) +``` + +Format an object into a media type string. This will return a string of the +mime type for the given object. For the properties of the object, see the +documentation for `typer.parse(string)`. + +If any of the given object values are invalid, then a `TypeError` is thrown. + +### typer.test(string) + + + +```js +var valid = typer.test('image/svg+xml') +``` + +Validate a media type string. This will return `true` is the string is a well- +formatted media type, or `false` otherwise. + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/media-typer/master +[coveralls-url]: https://coveralls.io/r/jshttp/media-typer?branch=master +[node-version-image]: https://badgen.net/npm/node/media-typer +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/media-typer +[npm-url]: https://npmjs.org/package/media-typer +[npm-version-image]: https://badgen.net/npm/v/media-typer +[travis-image]: https://badgen.net/travis/jshttp/media-typer/master +[travis-url]: https://travis-ci.org/jshttp/media-typer diff --git a/node_modules/media-typer/index.js b/node_modules/media-typer/index.js new file mode 100644 index 0000000..897cae1 --- /dev/null +++ b/node_modules/media-typer/index.js @@ -0,0 +1,143 @@ +/*! + * media-typer + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * RegExp to match type in RFC 6838 + * + * type-name = restricted-name + * subtype-name = restricted-name + * restricted-name = restricted-name-first *126restricted-name-chars + * restricted-name-first = ALPHA / DIGIT + * restricted-name-chars = ALPHA / DIGIT / "!" / "#" / + * "$" / "&" / "-" / "^" / "_" + * restricted-name-chars =/ "." ; Characters before first dot always + * ; specify a facet name + * restricted-name-chars =/ "+" ; Characters after last plus always + * ; specify a structured syntax suffix + * ALPHA = %x41-5A / %x61-7A ; A-Z / a-z + * DIGIT = %x30-39 ; 0-9 + */ +var SUBTYPE_NAME_REGEXP = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.-]{0,126}$/ +var TYPE_NAME_REGEXP = /^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}$/ +var TYPE_REGEXP = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/ + +/** + * Module exports. + */ + +exports.format = format +exports.parse = parse +exports.test = test + +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @public + */ + +function format (obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } + + var subtype = obj.subtype + var suffix = obj.suffix + var type = obj.type + + if (!type || !TYPE_NAME_REGEXP.test(type)) { + throw new TypeError('invalid type') + } + + if (!subtype || !SUBTYPE_NAME_REGEXP.test(subtype)) { + throw new TypeError('invalid subtype') + } + + // format as type/subtype + var string = type + '/' + subtype + + // append +suffix + if (suffix) { + if (!TYPE_NAME_REGEXP.test(suffix)) { + throw new TypeError('invalid suffix') + } + + string += '+' + suffix + } + + return string +} + +/** + * Test media type. + * + * @param {string} string + * @return {object} + * @public + */ + +function test (string) { + if (!string) { + throw new TypeError('argument string is required') + } + + if (typeof string !== 'string') { + throw new TypeError('argument string is required to be a string') + } + + return TYPE_REGEXP.test(string.toLowerCase()) +} + +/** + * Parse media type to object. + * + * @param {string} string + * @return {object} + * @public + */ + +function parse (string) { + if (!string) { + throw new TypeError('argument string is required') + } + + if (typeof string !== 'string') { + throw new TypeError('argument string is required to be a string') + } + + var match = TYPE_REGEXP.exec(string.toLowerCase()) + + if (!match) { + throw new TypeError('invalid media type') + } + + var type = match[1] + var subtype = match[2] + var suffix + + // suffix after last + + var index = subtype.lastIndexOf('+') + if (index !== -1) { + suffix = subtype.substr(index + 1) + subtype = subtype.substr(0, index) + } + + return new MediaType(type, subtype, suffix) +} + +/** + * Class for MediaType object. + * @public + */ + +function MediaType (type, subtype, suffix) { + this.type = type + this.subtype = subtype + this.suffix = suffix +} diff --git a/node_modules/media-typer/package.json b/node_modules/media-typer/package.json new file mode 100644 index 0000000..1dca712 --- /dev/null +++ b/node_modules/media-typer/package.json @@ -0,0 +1,33 @@ +{ + "name": "media-typer", + "description": "Simple RFC 6838 media type parser and formatter", + "version": "1.1.0", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "repository": "jshttp/media-typer", + "devDependencies": { + "eslint": "5.16.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.17.2", + "eslint-plugin-markdown": "1.0.0", + "eslint-plugin-node": "8.0.1", + "eslint-plugin-promise": "4.1.1", + "eslint-plugin-standard": "4.0.0", + "mocha": "6.1.4", + "nyc": "14.0.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "test-travis": "nyc --reporter=text npm test" + } +} diff --git a/node_modules/merge-descriptors/index.d.ts b/node_modules/merge-descriptors/index.d.ts new file mode 100644 index 0000000..df8f91f --- /dev/null +++ b/node_modules/merge-descriptors/index.d.ts @@ -0,0 +1,11 @@ +/** +Merges "own" properties from a source to a destination object, including non-enumerable and accessor-defined properties. It retains original values and descriptors, ensuring the destination receives a complete and accurate copy of the source's properties. + +@param destination - The object to receive properties. +@param source - The object providing properties. +@param overwrite - Optional boolean to control overwriting of existing properties. Defaults to true. +@returns The modified destination object. +*/ +declare function mergeDescriptors(destination: T, source: U, overwrite?: boolean): T & U; + +export = mergeDescriptors; diff --git a/node_modules/merge-descriptors/index.js b/node_modules/merge-descriptors/index.js new file mode 100644 index 0000000..51228e5 --- /dev/null +++ b/node_modules/merge-descriptors/index.js @@ -0,0 +1,26 @@ +'use strict'; + +function mergeDescriptors(destination, source, overwrite = true) { + if (!destination) { + throw new TypeError('The `destination` argument is required.'); + } + + if (!source) { + throw new TypeError('The `source` argument is required.'); + } + + for (const name of Object.getOwnPropertyNames(source)) { + if (!overwrite && Object.hasOwn(destination, name)) { + // Skip descriptor + continue; + } + + // Copy descriptor + const descriptor = Object.getOwnPropertyDescriptor(source, name); + Object.defineProperty(destination, name, descriptor); + } + + return destination; +} + +module.exports = mergeDescriptors; diff --git a/node_modules/merge-descriptors/license b/node_modules/merge-descriptors/license new file mode 100644 index 0000000..c509d45 --- /dev/null +++ b/node_modules/merge-descriptors/license @@ -0,0 +1,11 @@ +MIT License + +Copyright (c) Jonathan Ong +Copyright (c) Douglas Christopher Wilson +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/merge-descriptors/package.json b/node_modules/merge-descriptors/package.json new file mode 100644 index 0000000..9bedb25 --- /dev/null +++ b/node_modules/merge-descriptors/package.json @@ -0,0 +1,50 @@ +{ + "name": "merge-descriptors", + "version": "2.0.0", + "description": "Merge objects using their property descriptors", + "license": "MIT", + "repository": "sindresorhus/merge-descriptors", + "funding": "https://github.com/sponsors/sindresorhus", + "contributors": [ + "Jonathan Ong ", + "Douglas Christopher Wilson ", + "Mike Grabowski ", + "Sindre Sorhus " + ], + "exports": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "main": "./index.js", + "types": "./index.d.ts", + "sideEffects": false, + "engines": { + "node": ">=18" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "merge", + "descriptors", + "object", + "property", + "properties", + "merging", + "getter", + "setter" + ], + "devDependencies": { + "ava": "^5.3.1", + "xo": "^0.56.0" + }, + "xo": { + "rules": { + "unicorn/prefer-module": "off" + } + } +} diff --git a/node_modules/merge-descriptors/readme.md b/node_modules/merge-descriptors/readme.md new file mode 100644 index 0000000..1dee67d --- /dev/null +++ b/node_modules/merge-descriptors/readme.md @@ -0,0 +1,55 @@ +# merge-descriptors + +> Merge objects using their property descriptors + +## Install + +```sh +npm install merge-descriptors +``` + +## Usage + +```js +import mergeDescriptors from 'merge-descriptors'; + +const thing = { + get name() { + return 'John' + } +} + +const animal = {}; + +mergeDescriptors(animal, thing); + +console.log(animal.name); +//=> 'John' +``` + +## API + +### merge(destination, source, overwrite?) + +Merges "own" properties from a source to a destination object, including non-enumerable and accessor-defined properties. It retains original values and descriptors, ensuring the destination receives a complete and accurate copy of the source's properties. + +Returns the modified destination object. + +#### destination + +Type: `object` + +The object to receive properties. + +#### source + +Type: `object` + +The object providing properties. + +#### overwrite + +Type: `boolean`\ +Default: `true` + +A boolean to control overwriting of existing properties. diff --git a/node_modules/mime-db/HISTORY.md b/node_modules/mime-db/HISTORY.md new file mode 100644 index 0000000..fb35bec --- /dev/null +++ b/node_modules/mime-db/HISTORY.md @@ -0,0 +1,541 @@ +1.54.0 / 2025-03-17 +=================== + + * Update mime type for DCM format (#362) + * mark application/octet-stream as compressible (#163) + * Fix typo in application/x-zip-compressed mimetype (#359) + * Add mime-type for Jupyter notebooks (#282) + * Add Google Drive MIME types (#311) + * Add .blend file type (#338) + * Add support for the FBX file extension (#342) + * Add Adobe DNG file (#340) + * Add Procreate Brush and Brush Set file Types (#339) + * Add support for Procreate Dreams (#341) + * replace got with undici (#352) + * Added extensions list for model/step (#293) + * Add m4b as a type of audio/mp4 (#357) + * windows 11 application/x-zip-compressed (#346) + * add dotLottie mime type (#351) + * Add some MS-related extensions and types (#336) + +1.53.0 / 2024-07-12 +=================== + + * Add extension `.sql` to `application/sql` + * Add extensions `.aac` and `.adts` to `audio/aac` + * Add extensions `.js` and `.mjs` to `text/javascript` + * Add extensions for `application/mp4` from IANA + * Add extensions from IANA for more MIME types + * Add Microsoft app installer types and extensions + * Add new upstream MIME types + * Fix extensions for `text/markdown` to match IANA + * Remove extension `.mjs` from `application/javascript` + * Remove obsolete MIME types from IANA data + +1.52.0 / 2022-02-21 +=================== + + * Add extensions from IANA for more `image/*` types + * Add extension `.asc` to `application/pgp-keys` + * Add extensions to various XML types + * Add new upstream MIME types + +1.51.0 / 2021-11-08 +=================== + + * Add new upstream MIME types + * Mark `image/vnd.microsoft.icon` as compressible + * Mark `image/vnd.ms-dds` as compressible + +1.50.0 / 2021-09-15 +=================== + + * Add deprecated iWorks mime types and extensions + * Add new upstream MIME types + +1.49.0 / 2021-07-26 +=================== + + * Add extension `.trig` to `application/trig` + * Add new upstream MIME types + +1.48.0 / 2021-05-30 +=================== + + * Add extension `.mvt` to `application/vnd.mapbox-vector-tile` + * Add new upstream MIME types + * Mark `text/yaml` as compressible + +1.47.0 / 2021-04-01 +=================== + + * Add new upstream MIME types + * Remove ambiguous extensions from IANA for `application/*+xml` types + * Update primary extension to `.es` for `application/ecmascript` + +1.46.0 / 2021-02-13 +=================== + + * Add extension `.amr` to `audio/amr` + * Add extension `.m4s` to `video/iso.segment` + * Add extension `.opus` to `audio/ogg` + * Add new upstream MIME types + +1.45.0 / 2020-09-22 +=================== + + * Add `application/ubjson` with extension `.ubj` + * Add `image/avif` with extension `.avif` + * Add `image/ktx2` with extension `.ktx2` + * Add extension `.dbf` to `application/vnd.dbf` + * Add extension `.rar` to `application/vnd.rar` + * Add extension `.td` to `application/urc-targetdesc+xml` + * Add new upstream MIME types + * Fix extension of `application/vnd.apple.keynote` to be `.key` + +1.44.0 / 2020-04-22 +=================== + + * Add charsets from IANA + * Add extension `.cjs` to `application/node` + * Add new upstream MIME types + +1.43.0 / 2020-01-05 +=================== + + * Add `application/x-keepass2` with extension `.kdbx` + * Add extension `.mxmf` to `audio/mobile-xmf` + * Add extensions from IANA for `application/*+xml` types + * Add new upstream MIME types + +1.42.0 / 2019-09-25 +=================== + + * Add `image/vnd.ms-dds` with extension `.dds` + * Add new upstream MIME types + * Remove compressible from `multipart/mixed` + +1.41.0 / 2019-08-30 +=================== + + * Add new upstream MIME types + * Add `application/toml` with extension `.toml` + * Mark `font/ttf` as compressible + +1.40.0 / 2019-04-20 +=================== + + * Add extensions from IANA for `model/*` types + * Add `text/mdx` with extension `.mdx` + +1.39.0 / 2019-04-04 +=================== + + * Add extensions `.siv` and `.sieve` to `application/sieve` + * Add new upstream MIME types + +1.38.0 / 2019-02-04 +=================== + + * Add extension `.nq` to `application/n-quads` + * Add extension `.nt` to `application/n-triples` + * Add new upstream MIME types + * Mark `text/less` as compressible + +1.37.0 / 2018-10-19 +=================== + + * Add extensions to HEIC image types + * Add new upstream MIME types + +1.36.0 / 2018-08-20 +=================== + + * Add Apple file extensions from IANA + * Add extensions from IANA for `image/*` types + * Add new upstream MIME types + +1.35.0 / 2018-07-15 +=================== + + * Add extension `.owl` to `application/rdf+xml` + * Add new upstream MIME types + - Removes extension `.woff` from `application/font-woff` + +1.34.0 / 2018-06-03 +=================== + + * Add extension `.csl` to `application/vnd.citationstyles.style+xml` + * Add extension `.es` to `application/ecmascript` + * Add new upstream MIME types + * Add `UTF-8` as default charset for `text/turtle` + * Mark all XML-derived types as compressible + +1.33.0 / 2018-02-15 +=================== + + * Add extensions from IANA for `message/*` types + * Add new upstream MIME types + * Fix some incorrect OOXML types + * Remove `application/font-woff2` + +1.32.0 / 2017-11-29 +=================== + + * Add new upstream MIME types + * Update `text/hjson` to registered `application/hjson` + * Add `text/shex` with extension `.shex` + +1.31.0 / 2017-10-25 +=================== + + * Add `application/raml+yaml` with extension `.raml` + * Add `application/wasm` with extension `.wasm` + * Add new `font` type from IANA + * Add new upstream font extensions + * Add new upstream MIME types + * Add extensions for JPEG-2000 images + +1.30.0 / 2017-08-27 +=================== + + * Add `application/vnd.ms-outlook` + * Add `application/x-arj` + * Add extension `.mjs` to `application/javascript` + * Add glTF types and extensions + * Add new upstream MIME types + * Add `text/x-org` + * Add VirtualBox MIME types + * Fix `source` records for `video/*` types that are IANA + * Update `font/opentype` to registered `font/otf` + +1.29.0 / 2017-07-10 +=================== + + * Add `application/fido.trusted-apps+json` + * Add extension `.wadl` to `application/vnd.sun.wadl+xml` + * Add new upstream MIME types + * Add `UTF-8` as default charset for `text/css` + +1.28.0 / 2017-05-14 +=================== + + * Add new upstream MIME types + * Add extension `.gz` to `application/gzip` + * Update extensions `.md` and `.markdown` to be `text/markdown` + +1.27.0 / 2017-03-16 +=================== + + * Add new upstream MIME types + * Add `image/apng` with extension `.apng` + +1.26.0 / 2017-01-14 +=================== + + * Add new upstream MIME types + * Add extension `.geojson` to `application/geo+json` + +1.25.0 / 2016-11-11 +=================== + + * Add new upstream MIME types + +1.24.0 / 2016-09-18 +=================== + + * Add `audio/mp3` + * Add new upstream MIME types + +1.23.0 / 2016-05-01 +=================== + + * Add new upstream MIME types + * Add extension `.3gpp` to `audio/3gpp` + +1.22.0 / 2016-02-15 +=================== + + * Add `text/slim` + * Add extension `.rng` to `application/xml` + * Add new upstream MIME types + * Fix extension of `application/dash+xml` to be `.mpd` + * Update primary extension to `.m4a` for `audio/mp4` + +1.21.0 / 2016-01-06 +=================== + + * Add Google document types + * Add new upstream MIME types + +1.20.0 / 2015-11-10 +=================== + + * Add `text/x-suse-ymp` + * Add new upstream MIME types + +1.19.0 / 2015-09-17 +=================== + + * Add `application/vnd.apple.pkpass` + * Add new upstream MIME types + +1.18.0 / 2015-09-03 +=================== + + * Add new upstream MIME types + +1.17.0 / 2015-08-13 +=================== + + * Add `application/x-msdos-program` + * Add `audio/g711-0` + * Add `image/vnd.mozilla.apng` + * Add extension `.exe` to `application/x-msdos-program` + +1.16.0 / 2015-07-29 +=================== + + * Add `application/vnd.uri-map` + +1.15.0 / 2015-07-13 +=================== + + * Add `application/x-httpd-php` + +1.14.0 / 2015-06-25 +=================== + + * Add `application/scim+json` + * Add `application/vnd.3gpp.ussd+xml` + * Add `application/vnd.biopax.rdf+xml` + * Add `text/x-processing` + +1.13.0 / 2015-06-07 +=================== + + * Add nginx as a source + * Add `application/x-cocoa` + * Add `application/x-java-archive-diff` + * Add `application/x-makeself` + * Add `application/x-perl` + * Add `application/x-pilot` + * Add `application/x-redhat-package-manager` + * Add `application/x-sea` + * Add `audio/x-m4a` + * Add `audio/x-realaudio` + * Add `image/x-jng` + * Add `text/mathml` + +1.12.0 / 2015-06-05 +=================== + + * Add `application/bdoc` + * Add `application/vnd.hyperdrive+json` + * Add `application/x-bdoc` + * Add extension `.rtf` to `text/rtf` + +1.11.0 / 2015-05-31 +=================== + + * Add `audio/wav` + * Add `audio/wave` + * Add extension `.litcoffee` to `text/coffeescript` + * Add extension `.sfd-hdstx` to `application/vnd.hydrostatix.sof-data` + * Add extension `.n-gage` to `application/vnd.nokia.n-gage.symbian.install` + +1.10.0 / 2015-05-19 +=================== + + * Add `application/vnd.balsamiq.bmpr` + * Add `application/vnd.microsoft.portable-executable` + * Add `application/x-ns-proxy-autoconfig` + +1.9.1 / 2015-04-19 +================== + + * Remove `.json` extension from `application/manifest+json` + - This is causing bugs downstream + +1.9.0 / 2015-04-19 +================== + + * Add `application/manifest+json` + * Add `application/vnd.micro+json` + * Add `image/vnd.zbrush.pcx` + * Add `image/x-ms-bmp` + +1.8.0 / 2015-03-13 +================== + + * Add `application/vnd.citationstyles.style+xml` + * Add `application/vnd.fastcopy-disk-image` + * Add `application/vnd.gov.sk.xmldatacontainer+xml` + * Add extension `.jsonld` to `application/ld+json` + +1.7.0 / 2015-02-08 +================== + + * Add `application/vnd.gerber` + * Add `application/vnd.msa-disk-image` + +1.6.1 / 2015-02-05 +================== + + * Community extensions ownership transferred from `node-mime` + +1.6.0 / 2015-01-29 +================== + + * Add `application/jose` + * Add `application/jose+json` + * Add `application/json-seq` + * Add `application/jwk+json` + * Add `application/jwk-set+json` + * Add `application/jwt` + * Add `application/rdap+json` + * Add `application/vnd.gov.sk.e-form+xml` + * Add `application/vnd.ims.imsccv1p3` + +1.5.0 / 2014-12-30 +================== + + * Add `application/vnd.oracle.resource+json` + * Fix various invalid MIME type entries + - `application/mbox+xml` + - `application/oscp-response` + - `application/vwg-multiplexed` + - `audio/g721` + +1.4.0 / 2014-12-21 +================== + + * Add `application/vnd.ims.imsccv1p2` + * Fix various invalid MIME type entries + - `application/vnd-acucobol` + - `application/vnd-curl` + - `application/vnd-dart` + - `application/vnd-dxr` + - `application/vnd-fdf` + - `application/vnd-mif` + - `application/vnd-sema` + - `application/vnd-wap-wmlc` + - `application/vnd.adobe.flash-movie` + - `application/vnd.dece-zip` + - `application/vnd.dvb_service` + - `application/vnd.micrografx-igx` + - `application/vnd.sealed-doc` + - `application/vnd.sealed-eml` + - `application/vnd.sealed-mht` + - `application/vnd.sealed-ppt` + - `application/vnd.sealed-tiff` + - `application/vnd.sealed-xls` + - `application/vnd.sealedmedia.softseal-html` + - `application/vnd.sealedmedia.softseal-pdf` + - `application/vnd.wap-slc` + - `application/vnd.wap-wbxml` + - `audio/vnd.sealedmedia.softseal-mpeg` + - `image/vnd-djvu` + - `image/vnd-svf` + - `image/vnd-wap-wbmp` + - `image/vnd.sealed-png` + - `image/vnd.sealedmedia.softseal-gif` + - `image/vnd.sealedmedia.softseal-jpg` + - `model/vnd-dwf` + - `model/vnd.parasolid.transmit-binary` + - `model/vnd.parasolid.transmit-text` + - `text/vnd-a` + - `text/vnd-curl` + - `text/vnd.wap-wml` + * Remove example template MIME types + - `application/example` + - `audio/example` + - `image/example` + - `message/example` + - `model/example` + - `multipart/example` + - `text/example` + - `video/example` + +1.3.1 / 2014-12-16 +================== + + * Fix missing extensions + - `application/json5` + - `text/hjson` + +1.3.0 / 2014-12-07 +================== + + * Add `application/a2l` + * Add `application/aml` + * Add `application/atfx` + * Add `application/atxml` + * Add `application/cdfx+xml` + * Add `application/dii` + * Add `application/json5` + * Add `application/lxf` + * Add `application/mf4` + * Add `application/vnd.apache.thrift.compact` + * Add `application/vnd.apache.thrift.json` + * Add `application/vnd.coffeescript` + * Add `application/vnd.enphase.envoy` + * Add `application/vnd.ims.imsccv1p1` + * Add `text/csv-schema` + * Add `text/hjson` + * Add `text/markdown` + * Add `text/yaml` + +1.2.0 / 2014-11-09 +================== + + * Add `application/cea` + * Add `application/dit` + * Add `application/vnd.gov.sk.e-form+zip` + * Add `application/vnd.tmd.mediaflex.api+xml` + * Type `application/epub+zip` is now IANA-registered + +1.1.2 / 2014-10-23 +================== + + * Rebuild database for `application/x-www-form-urlencoded` change + +1.1.1 / 2014-10-20 +================== + + * Mark `application/x-www-form-urlencoded` as compressible. + +1.1.0 / 2014-09-28 +================== + + * Add `application/font-woff2` + +1.0.3 / 2014-09-25 +================== + + * Fix engine requirement in package + +1.0.2 / 2014-09-25 +================== + + * Add `application/coap-group+json` + * Add `application/dcd` + * Add `application/vnd.apache.thrift.binary` + * Add `image/vnd.tencent.tap` + * Mark all JSON-derived types as compressible + * Update `text/vtt` data + +1.0.1 / 2014-08-30 +================== + + * Fix extension ordering + +1.0.0 / 2014-08-30 +================== + + * Add `application/atf` + * Add `application/merge-patch+json` + * Add `multipart/x-mixed-replace` + * Add `source: 'apache'` metadata + * Add `source: 'iana'` metadata + * Remove badly-assumed charset data diff --git a/node_modules/mime-db/LICENSE b/node_modules/mime-db/LICENSE new file mode 100644 index 0000000..0751cb1 --- /dev/null +++ b/node_modules/mime-db/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015-2022 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mime-db/README.md b/node_modules/mime-db/README.md new file mode 100644 index 0000000..ee93fa0 --- /dev/null +++ b/node_modules/mime-db/README.md @@ -0,0 +1,109 @@ +# mime-db + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +This is a large database of mime types and information about them. +It consists of a single, public JSON file and does not include any logic, +allowing it to remain as un-opinionated as possible with an API. +It aggregates data from the following sources: + +- https://www.iana.org/assignments/media-types/media-types.xhtml +- https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types +- https://hg.nginx.org/nginx/raw-file/default/conf/mime.types + +## Installation + +```bash +npm install mime-db +``` + +### Database Download + +If you intend to use this in a web browser, you can conveniently access the JSON file via [jsDelivr](https://www.jsdelivr.com/), a popular CDN (Content Delivery Network). To ensure stability and compatibility, it is advisable to specify [a release tag](https://github.com/jshttp/mime-db/tags) instead of using the 'master' branch. This is because the JSON file's format might change in future updates, and relying on a specific release tag will prevent potential issues arising from these changes. + +``` +https://cdn.jsdelivr.net/gh/jshttp/mime-db@master/db.json +``` + +## Usage + +```js +var db = require('mime-db') + +// grab data on .js files +var data = db['application/javascript'] +``` + +## Data Structure + +The JSON file is a map lookup for lowercased mime types. +Each mime type has the following properties: + +- `.source` - where the mime type is defined. + If not set, it's probably a custom media type. + - `apache` - [Apache common media types](https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) + - `iana` - [IANA-defined media types](https://www.iana.org/assignments/media-types/media-types.xhtml) + - `nginx` - [nginx media types](https://hg.nginx.org/nginx/raw-file/default/conf/mime.types) +- `.extensions[]` - known extensions associated with this mime type. +- `.compressible` - whether a file of this type can be gzipped. +- `.charset` - the default charset associated with this type, if any. + +If unknown, every property could be `undefined`. + +## Note on MIME Type Data and Semver + +This package considers the programmatic api as the semver compatibility. This means the MIME type resolution is *not* considered +in the semver bumps. This means that if you want to pin your `mime-db` data you will need to do it in your application. While +this expectation was not set in docs until now, it is how the pacakge operated, so we do not feel this is a breaking change. + +## Contributing + +The primary way to contribute to this database is by updating the data in +one of the upstream sources. The database is updated from the upstreams +periodically and will pull in any changes. + +### Registering Media Types + +The best way to get new media types included in this library is to register +them with the IANA. The community registration procedure is outlined in +[RFC 6838 section 5](https://tools.ietf.org/html/rfc6838#section-5). Types +registered with the IANA are automatically pulled into this library. + +### Direct Inclusion + +If that is not possible / feasible, they can be added directly here as a +"custom" type. To do this, it is required to have a primary source that +definitively lists the media type. If an extension is going to be listed as +associated with this media type, the source must definitively link the +media type and extension as well. + +To edit the database, only make PRs against `src/custom-types.json` or +`src/custom-suffix.json`. + +The `src/custom-types.json` file is a JSON object with the MIME type as the +keys and the values being an object with the following keys: + +- `compressible` - leave out if you don't know, otherwise `true`/`false` to + indicate whether the data represented by the type is typically compressible. +- `extensions` - include an array of file extensions that are associated with + the type. +- `notes` - human-readable notes about the type, typically what the type is. +- `sources` - include an array of URLs of where the MIME type and the associated + extensions are sourced from. This needs to be a [primary source](https://en.wikipedia.org/wiki/Primary_source); + links to type aggregating sites and Wikipedia are _not acceptable_. + +To update the build, run `npm run build`. + +[ci-image]: https://badgen.net/github/checks/jshttp/mime-db/master?label=ci +[ci-url]: https://github.com/jshttp/mime-db/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-db/master +[coveralls-url]: https://coveralls.io/r/jshttp/mime-db?branch=master +[node-image]: https://badgen.net/npm/node/mime-db +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/mime-db +[npm-url]: https://npmjs.org/package/mime-db +[npm-version-image]: https://badgen.net/npm/v/mime-db diff --git a/node_modules/mime-db/db.json b/node_modules/mime-db/db.json new file mode 100644 index 0000000..7e74733 --- /dev/null +++ b/node_modules/mime-db/db.json @@ -0,0 +1,9342 @@ +{ + "application/1d-interleaved-parityfec": { + "source": "iana" + }, + "application/3gpdash-qoe-report+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/3gpp-ims+xml": { + "source": "iana", + "compressible": true + }, + "application/3gpphal+json": { + "source": "iana", + "compressible": true + }, + "application/3gpphalforms+json": { + "source": "iana", + "compressible": true + }, + "application/a2l": { + "source": "iana" + }, + "application/ace+cbor": { + "source": "iana" + }, + "application/ace+json": { + "source": "iana", + "compressible": true + }, + "application/ace-groupcomm+cbor": { + "source": "iana" + }, + "application/ace-trl+cbor": { + "source": "iana" + }, + "application/activemessage": { + "source": "iana" + }, + "application/activity+json": { + "source": "iana", + "compressible": true + }, + "application/aif+cbor": { + "source": "iana" + }, + "application/aif+json": { + "source": "iana", + "compressible": true + }, + "application/alto-cdni+json": { + "source": "iana", + "compressible": true + }, + "application/alto-cdnifilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-directory+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcost+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcostparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointprop+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointpropparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-error+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-propmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-propmapparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-tips+json": { + "source": "iana", + "compressible": true + }, + "application/alto-tipsparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-updatestreamcontrol+json": { + "source": "iana", + "compressible": true + }, + "application/alto-updatestreamparams+json": { + "source": "iana", + "compressible": true + }, + "application/aml": { + "source": "iana" + }, + "application/andrew-inset": { + "source": "iana", + "extensions": ["ez"] + }, + "application/appinstaller": { + "compressible": false, + "extensions": ["appinstaller"] + }, + "application/applefile": { + "source": "iana" + }, + "application/applixware": { + "source": "apache", + "extensions": ["aw"] + }, + "application/appx": { + "compressible": false, + "extensions": ["appx"] + }, + "application/appxbundle": { + "compressible": false, + "extensions": ["appxbundle"] + }, + "application/at+jwt": { + "source": "iana" + }, + "application/atf": { + "source": "iana" + }, + "application/atfx": { + "source": "iana" + }, + "application/atom+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atom"] + }, + "application/atomcat+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomcat"] + }, + "application/atomdeleted+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomdeleted"] + }, + "application/atomicmail": { + "source": "iana" + }, + "application/atomsvc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomsvc"] + }, + "application/atsc-dwd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dwd"] + }, + "application/atsc-dynamic-event-message": { + "source": "iana" + }, + "application/atsc-held+xml": { + "source": "iana", + "compressible": true, + "extensions": ["held"] + }, + "application/atsc-rdt+json": { + "source": "iana", + "compressible": true + }, + "application/atsc-rsat+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rsat"] + }, + "application/atxml": { + "source": "iana" + }, + "application/auth-policy+xml": { + "source": "iana", + "compressible": true + }, + "application/automationml-aml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["aml"] + }, + "application/automationml-amlx+zip": { + "source": "iana", + "compressible": false, + "extensions": ["amlx"] + }, + "application/bacnet-xdd+zip": { + "source": "iana", + "compressible": false + }, + "application/batch-smtp": { + "source": "iana" + }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/beep+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/bufr": { + "source": "iana" + }, + "application/c2pa": { + "source": "iana" + }, + "application/calendar+json": { + "source": "iana", + "compressible": true + }, + "application/calendar+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xcs"] + }, + "application/call-completion": { + "source": "iana" + }, + "application/cals-1840": { + "source": "iana" + }, + "application/captive+json": { + "source": "iana", + "compressible": true + }, + "application/cbor": { + "source": "iana" + }, + "application/cbor-seq": { + "source": "iana" + }, + "application/cccex": { + "source": "iana" + }, + "application/ccmp+xml": { + "source": "iana", + "compressible": true + }, + "application/ccxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ccxml"] + }, + "application/cda+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/cdfx+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cdfx"] + }, + "application/cdmi-capability": { + "source": "iana", + "extensions": ["cdmia"] + }, + "application/cdmi-container": { + "source": "iana", + "extensions": ["cdmic"] + }, + "application/cdmi-domain": { + "source": "iana", + "extensions": ["cdmid"] + }, + "application/cdmi-object": { + "source": "iana", + "extensions": ["cdmio"] + }, + "application/cdmi-queue": { + "source": "iana", + "extensions": ["cdmiq"] + }, + "application/cdni": { + "source": "iana" + }, + "application/ce+cbor": { + "source": "iana" + }, + "application/cea": { + "source": "iana" + }, + "application/cea-2018+xml": { + "source": "iana", + "compressible": true + }, + "application/cellml+xml": { + "source": "iana", + "compressible": true + }, + "application/cfw": { + "source": "iana" + }, + "application/cid-edhoc+cbor-seq": { + "source": "iana" + }, + "application/city+json": { + "source": "iana", + "compressible": true + }, + "application/city+json-seq": { + "source": "iana" + }, + "application/clr": { + "source": "iana" + }, + "application/clue+xml": { + "source": "iana", + "compressible": true + }, + "application/clue_info+xml": { + "source": "iana", + "compressible": true + }, + "application/cms": { + "source": "iana" + }, + "application/cnrp+xml": { + "source": "iana", + "compressible": true + }, + "application/coap-eap": { + "source": "iana" + }, + "application/coap-group+json": { + "source": "iana", + "compressible": true + }, + "application/coap-payload": { + "source": "iana" + }, + "application/commonground": { + "source": "iana" + }, + "application/concise-problem-details+cbor": { + "source": "iana" + }, + "application/conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/cose": { + "source": "iana" + }, + "application/cose-key": { + "source": "iana" + }, + "application/cose-key-set": { + "source": "iana" + }, + "application/cose-x509": { + "source": "iana" + }, + "application/cpl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cpl"] + }, + "application/csrattrs": { + "source": "iana" + }, + "application/csta+xml": { + "source": "iana", + "compressible": true + }, + "application/cstadata+xml": { + "source": "iana", + "compressible": true + }, + "application/csvm+json": { + "source": "iana", + "compressible": true + }, + "application/cu-seeme": { + "source": "apache", + "extensions": ["cu"] + }, + "application/cwl": { + "source": "iana", + "extensions": ["cwl"] + }, + "application/cwl+json": { + "source": "iana", + "compressible": true + }, + "application/cwl+yaml": { + "source": "iana" + }, + "application/cwt": { + "source": "iana" + }, + "application/cybercash": { + "source": "iana" + }, + "application/dart": { + "compressible": true + }, + "application/dash+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpd"] + }, + "application/dash-patch+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpp"] + }, + "application/dashdelta": { + "source": "iana" + }, + "application/davmount+xml": { + "source": "iana", + "compressible": true, + "extensions": ["davmount"] + }, + "application/dca-rft": { + "source": "iana" + }, + "application/dcd": { + "source": "iana" + }, + "application/dec-dx": { + "source": "iana" + }, + "application/dialog-info+xml": { + "source": "iana", + "compressible": true + }, + "application/dicom": { + "source": "iana", + "extensions": ["dcm"] + }, + "application/dicom+json": { + "source": "iana", + "compressible": true + }, + "application/dicom+xml": { + "source": "iana", + "compressible": true + }, + "application/dii": { + "source": "iana" + }, + "application/dit": { + "source": "iana" + }, + "application/dns": { + "source": "iana" + }, + "application/dns+json": { + "source": "iana", + "compressible": true + }, + "application/dns-message": { + "source": "iana" + }, + "application/docbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dbk"] + }, + "application/dots+cbor": { + "source": "iana" + }, + "application/dpop+jwt": { + "source": "iana" + }, + "application/dskpp+xml": { + "source": "iana", + "compressible": true + }, + "application/dssc+der": { + "source": "iana", + "extensions": ["dssc"] + }, + "application/dssc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdssc"] + }, + "application/dvcs": { + "source": "iana" + }, + "application/eat+cwt": { + "source": "iana" + }, + "application/eat+jwt": { + "source": "iana" + }, + "application/eat-bun+cbor": { + "source": "iana" + }, + "application/eat-bun+json": { + "source": "iana", + "compressible": true + }, + "application/eat-ucs+cbor": { + "source": "iana" + }, + "application/eat-ucs+json": { + "source": "iana", + "compressible": true + }, + "application/ecmascript": { + "source": "apache", + "compressible": true, + "extensions": ["ecma"] + }, + "application/edhoc+cbor-seq": { + "source": "iana" + }, + "application/edi-consent": { + "source": "iana" + }, + "application/edi-x12": { + "source": "iana", + "compressible": false + }, + "application/edifact": { + "source": "iana", + "compressible": false + }, + "application/efi": { + "source": "iana" + }, + "application/elm+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/elm+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.cap+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/emergencycalldata.comment+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.control+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.deviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.ecall.msd": { + "source": "iana" + }, + "application/emergencycalldata.legacyesn+json": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.providerinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.serviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.subscriberinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.veds+xml": { + "source": "iana", + "compressible": true + }, + "application/emma+xml": { + "source": "iana", + "compressible": true, + "extensions": ["emma"] + }, + "application/emotionml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["emotionml"] + }, + "application/encaprtp": { + "source": "iana" + }, + "application/entity-statement+jwt": { + "source": "iana" + }, + "application/epp+xml": { + "source": "iana", + "compressible": true + }, + "application/epub+zip": { + "source": "iana", + "compressible": false, + "extensions": ["epub"] + }, + "application/eshop": { + "source": "iana" + }, + "application/exi": { + "source": "iana", + "extensions": ["exi"] + }, + "application/expect-ct-report+json": { + "source": "iana", + "compressible": true + }, + "application/express": { + "source": "iana", + "extensions": ["exp"] + }, + "application/fastinfoset": { + "source": "iana" + }, + "application/fastsoap": { + "source": "iana" + }, + "application/fdf": { + "source": "iana", + "extensions": ["fdf"] + }, + "application/fdt+xml": { + "source": "iana", + "compressible": true, + "extensions": ["fdt"] + }, + "application/fhir+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/fhir+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/fido.trusted-apps+json": { + "compressible": true + }, + "application/fits": { + "source": "iana" + }, + "application/flexfec": { + "source": "iana" + }, + "application/font-sfnt": { + "source": "iana" + }, + "application/font-tdpfr": { + "source": "iana", + "extensions": ["pfr"] + }, + "application/font-woff": { + "source": "iana", + "compressible": false + }, + "application/framework-attributes+xml": { + "source": "iana", + "compressible": true + }, + "application/geo+json": { + "source": "iana", + "compressible": true, + "extensions": ["geojson"] + }, + "application/geo+json-seq": { + "source": "iana" + }, + "application/geopackage+sqlite3": { + "source": "iana" + }, + "application/geopose+json": { + "source": "iana", + "compressible": true + }, + "application/geoxacml+json": { + "source": "iana", + "compressible": true + }, + "application/geoxacml+xml": { + "source": "iana", + "compressible": true + }, + "application/gltf-buffer": { + "source": "iana" + }, + "application/gml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["gml"] + }, + "application/gnap-binding-jws": { + "source": "iana" + }, + "application/gnap-binding-jwsd": { + "source": "iana" + }, + "application/gnap-binding-rotation-jws": { + "source": "iana" + }, + "application/gnap-binding-rotation-jwsd": { + "source": "iana" + }, + "application/gpx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["gpx"] + }, + "application/grib": { + "source": "iana" + }, + "application/gxf": { + "source": "apache", + "extensions": ["gxf"] + }, + "application/gzip": { + "source": "iana", + "compressible": false, + "extensions": ["gz"] + }, + "application/h224": { + "source": "iana" + }, + "application/held+xml": { + "source": "iana", + "compressible": true + }, + "application/hjson": { + "extensions": ["hjson"] + }, + "application/hl7v2+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/http": { + "source": "iana" + }, + "application/hyperstudio": { + "source": "iana", + "extensions": ["stk"] + }, + "application/ibe-key-request+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pkg-reply+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pp-data": { + "source": "iana" + }, + "application/iges": { + "source": "iana" + }, + "application/im-iscomposing+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/index": { + "source": "iana" + }, + "application/index.cmd": { + "source": "iana" + }, + "application/index.obj": { + "source": "iana" + }, + "application/index.response": { + "source": "iana" + }, + "application/index.vnd": { + "source": "iana" + }, + "application/inkml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ink","inkml"] + }, + "application/iotp": { + "source": "iana" + }, + "application/ipfix": { + "source": "iana", + "extensions": ["ipfix"] + }, + "application/ipp": { + "source": "iana" + }, + "application/isup": { + "source": "iana" + }, + "application/its+xml": { + "source": "iana", + "compressible": true, + "extensions": ["its"] + }, + "application/java-archive": { + "source": "iana", + "compressible": false, + "extensions": ["jar","war","ear"] + }, + "application/java-serialized-object": { + "source": "apache", + "compressible": false, + "extensions": ["ser"] + }, + "application/java-vm": { + "source": "apache", + "compressible": false, + "extensions": ["class"] + }, + "application/javascript": { + "source": "apache", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js"] + }, + "application/jf2feed+json": { + "source": "iana", + "compressible": true + }, + "application/jose": { + "source": "iana" + }, + "application/jose+json": { + "source": "iana", + "compressible": true + }, + "application/jrd+json": { + "source": "iana", + "compressible": true + }, + "application/jscalendar+json": { + "source": "iana", + "compressible": true + }, + "application/jscontact+json": { + "source": "iana", + "compressible": true + }, + "application/json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["json","map"] + }, + "application/json-patch+json": { + "source": "iana", + "compressible": true + }, + "application/json-seq": { + "source": "iana" + }, + "application/json5": { + "extensions": ["json5"] + }, + "application/jsonml+json": { + "source": "apache", + "compressible": true, + "extensions": ["jsonml"] + }, + "application/jsonpath": { + "source": "iana" + }, + "application/jwk+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+jwt": { + "source": "iana" + }, + "application/jwt": { + "source": "iana" + }, + "application/kpml-request+xml": { + "source": "iana", + "compressible": true + }, + "application/kpml-response+xml": { + "source": "iana", + "compressible": true + }, + "application/ld+json": { + "source": "iana", + "compressible": true, + "extensions": ["jsonld"] + }, + "application/lgr+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lgr"] + }, + "application/link-format": { + "source": "iana" + }, + "application/linkset": { + "source": "iana" + }, + "application/linkset+json": { + "source": "iana", + "compressible": true + }, + "application/load-control+xml": { + "source": "iana", + "compressible": true + }, + "application/logout+jwt": { + "source": "iana" + }, + "application/lost+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lostxml"] + }, + "application/lostsync+xml": { + "source": "iana", + "compressible": true + }, + "application/lpf+zip": { + "source": "iana", + "compressible": false + }, + "application/lxf": { + "source": "iana" + }, + "application/mac-binhex40": { + "source": "iana", + "extensions": ["hqx"] + }, + "application/mac-compactpro": { + "source": "apache", + "extensions": ["cpt"] + }, + "application/macwriteii": { + "source": "iana" + }, + "application/mads+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mads"] + }, + "application/manifest+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, + "application/marc": { + "source": "iana", + "extensions": ["mrc"] + }, + "application/marcxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mrcx"] + }, + "application/mathematica": { + "source": "iana", + "extensions": ["ma","nb","mb"] + }, + "application/mathml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mathml"] + }, + "application/mathml-content+xml": { + "source": "iana", + "compressible": true + }, + "application/mathml-presentation+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-associated-procedure-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-deregister+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-envelope+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-protection-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-reception-report+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-schedule+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-user-service-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbox": { + "source": "iana", + "extensions": ["mbox"] + }, + "application/media-policy-dataset+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpf"] + }, + "application/media_control+xml": { + "source": "iana", + "compressible": true + }, + "application/mediaservercontrol+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mscml"] + }, + "application/merge-patch+json": { + "source": "iana", + "compressible": true + }, + "application/metalink+xml": { + "source": "apache", + "compressible": true, + "extensions": ["metalink"] + }, + "application/metalink4+xml": { + "source": "iana", + "compressible": true, + "extensions": ["meta4"] + }, + "application/mets+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mets"] + }, + "application/mf4": { + "source": "iana" + }, + "application/mikey": { + "source": "iana" + }, + "application/mipc": { + "source": "iana" + }, + "application/missing-blocks+cbor-seq": { + "source": "iana" + }, + "application/mmt-aei+xml": { + "source": "iana", + "compressible": true, + "extensions": ["maei"] + }, + "application/mmt-usd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["musd"] + }, + "application/mods+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mods"] + }, + "application/moss-keys": { + "source": "iana" + }, + "application/moss-signature": { + "source": "iana" + }, + "application/mosskey-data": { + "source": "iana" + }, + "application/mosskey-request": { + "source": "iana" + }, + "application/mp21": { + "source": "iana", + "extensions": ["m21","mp21"] + }, + "application/mp4": { + "source": "iana", + "extensions": ["mp4","mpg4","mp4s","m4p"] + }, + "application/mpeg4-generic": { + "source": "iana" + }, + "application/mpeg4-iod": { + "source": "iana" + }, + "application/mpeg4-iod-xmt": { + "source": "iana" + }, + "application/mrb-consumer+xml": { + "source": "iana", + "compressible": true + }, + "application/mrb-publish+xml": { + "source": "iana", + "compressible": true + }, + "application/msc-ivr+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/msc-mixer+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/msix": { + "compressible": false, + "extensions": ["msix"] + }, + "application/msixbundle": { + "compressible": false, + "extensions": ["msixbundle"] + }, + "application/msword": { + "source": "iana", + "compressible": false, + "extensions": ["doc","dot"] + }, + "application/mud+json": { + "source": "iana", + "compressible": true + }, + "application/multipart-core": { + "source": "iana" + }, + "application/mxf": { + "source": "iana", + "extensions": ["mxf"] + }, + "application/n-quads": { + "source": "iana", + "extensions": ["nq"] + }, + "application/n-triples": { + "source": "iana", + "extensions": ["nt"] + }, + "application/nasdata": { + "source": "iana" + }, + "application/news-checkgroups": { + "source": "iana", + "charset": "US-ASCII" + }, + "application/news-groupinfo": { + "source": "iana", + "charset": "US-ASCII" + }, + "application/news-transmission": { + "source": "iana" + }, + "application/nlsml+xml": { + "source": "iana", + "compressible": true + }, + "application/node": { + "source": "iana", + "extensions": ["cjs"] + }, + "application/nss": { + "source": "iana" + }, + "application/oauth-authz-req+jwt": { + "source": "iana" + }, + "application/oblivious-dns-message": { + "source": "iana" + }, + "application/ocsp-request": { + "source": "iana" + }, + "application/ocsp-response": { + "source": "iana" + }, + "application/octet-stream": { + "source": "iana", + "compressible": true, + "extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"] + }, + "application/oda": { + "source": "iana", + "extensions": ["oda"] + }, + "application/odm+xml": { + "source": "iana", + "compressible": true + }, + "application/odx": { + "source": "iana" + }, + "application/oebps-package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["opf"] + }, + "application/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogx"] + }, + "application/ohttp-keys": { + "source": "iana" + }, + "application/omdoc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["omdoc"] + }, + "application/onenote": { + "source": "apache", + "extensions": ["onetoc","onetoc2","onetmp","onepkg","one","onea"] + }, + "application/opc-nodeset+xml": { + "source": "iana", + "compressible": true + }, + "application/oscore": { + "source": "iana" + }, + "application/oxps": { + "source": "iana", + "extensions": ["oxps"] + }, + "application/p21": { + "source": "iana" + }, + "application/p21+zip": { + "source": "iana", + "compressible": false + }, + "application/p2p-overlay+xml": { + "source": "iana", + "compressible": true, + "extensions": ["relo"] + }, + "application/parityfec": { + "source": "iana" + }, + "application/passport": { + "source": "iana" + }, + "application/patch-ops-error+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xer"] + }, + "application/pdf": { + "source": "iana", + "compressible": false, + "extensions": ["pdf"] + }, + "application/pdx": { + "source": "iana" + }, + "application/pem-certificate-chain": { + "source": "iana" + }, + "application/pgp-encrypted": { + "source": "iana", + "compressible": false, + "extensions": ["pgp"] + }, + "application/pgp-keys": { + "source": "iana", + "extensions": ["asc"] + }, + "application/pgp-signature": { + "source": "iana", + "extensions": ["sig","asc"] + }, + "application/pics-rules": { + "source": "apache", + "extensions": ["prf"] + }, + "application/pidf+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/pidf-diff+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/pkcs10": { + "source": "iana", + "extensions": ["p10"] + }, + "application/pkcs12": { + "source": "iana" + }, + "application/pkcs7-mime": { + "source": "iana", + "extensions": ["p7m","p7c"] + }, + "application/pkcs7-signature": { + "source": "iana", + "extensions": ["p7s"] + }, + "application/pkcs8": { + "source": "iana", + "extensions": ["p8"] + }, + "application/pkcs8-encrypted": { + "source": "iana" + }, + "application/pkix-attr-cert": { + "source": "iana", + "extensions": ["ac"] + }, + "application/pkix-cert": { + "source": "iana", + "extensions": ["cer"] + }, + "application/pkix-crl": { + "source": "iana", + "extensions": ["crl"] + }, + "application/pkix-pkipath": { + "source": "iana", + "extensions": ["pkipath"] + }, + "application/pkixcmp": { + "source": "iana", + "extensions": ["pki"] + }, + "application/pls+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pls"] + }, + "application/poc-settings+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/postscript": { + "source": "iana", + "compressible": true, + "extensions": ["ai","eps","ps"] + }, + "application/ppsp-tracker+json": { + "source": "iana", + "compressible": true + }, + "application/private-token-issuer-directory": { + "source": "iana" + }, + "application/private-token-request": { + "source": "iana" + }, + "application/private-token-response": { + "source": "iana" + }, + "application/problem+json": { + "source": "iana", + "compressible": true + }, + "application/problem+xml": { + "source": "iana", + "compressible": true + }, + "application/provenance+xml": { + "source": "iana", + "compressible": true, + "extensions": ["provx"] + }, + "application/provided-claims+jwt": { + "source": "iana" + }, + "application/prs.alvestrand.titrax-sheet": { + "source": "iana" + }, + "application/prs.cww": { + "source": "iana", + "extensions": ["cww"] + }, + "application/prs.cyn": { + "source": "iana", + "charset": "7-BIT" + }, + "application/prs.hpub+zip": { + "source": "iana", + "compressible": false + }, + "application/prs.implied-document+xml": { + "source": "iana", + "compressible": true + }, + "application/prs.implied-executable": { + "source": "iana" + }, + "application/prs.implied-object+json": { + "source": "iana", + "compressible": true + }, + "application/prs.implied-object+json-seq": { + "source": "iana" + }, + "application/prs.implied-object+yaml": { + "source": "iana" + }, + "application/prs.implied-structure": { + "source": "iana" + }, + "application/prs.mayfile": { + "source": "iana" + }, + "application/prs.nprend": { + "source": "iana" + }, + "application/prs.plucker": { + "source": "iana" + }, + "application/prs.rdf-xml-crypt": { + "source": "iana" + }, + "application/prs.vcfbzip2": { + "source": "iana" + }, + "application/prs.xsf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xsf"] + }, + "application/pskc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pskcxml"] + }, + "application/pvd+json": { + "source": "iana", + "compressible": true + }, + "application/qsig": { + "source": "iana" + }, + "application/raml+yaml": { + "compressible": true, + "extensions": ["raml"] + }, + "application/raptorfec": { + "source": "iana" + }, + "application/rdap+json": { + "source": "iana", + "compressible": true + }, + "application/rdf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rdf","owl"] + }, + "application/reginfo+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rif"] + }, + "application/relax-ng-compact-syntax": { + "source": "iana", + "extensions": ["rnc"] + }, + "application/remote-printing": { + "source": "apache" + }, + "application/reputon+json": { + "source": "iana", + "compressible": true + }, + "application/resolve-response+jwt": { + "source": "iana" + }, + "application/resource-lists+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rl"] + }, + "application/resource-lists-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rld"] + }, + "application/rfc+xml": { + "source": "iana", + "compressible": true + }, + "application/riscos": { + "source": "iana" + }, + "application/rlmi+xml": { + "source": "iana", + "compressible": true + }, + "application/rls-services+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rs"] + }, + "application/route-apd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rapd"] + }, + "application/route-s-tsid+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sls"] + }, + "application/route-usd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rusd"] + }, + "application/rpki-checklist": { + "source": "iana" + }, + "application/rpki-ghostbusters": { + "source": "iana", + "extensions": ["gbr"] + }, + "application/rpki-manifest": { + "source": "iana", + "extensions": ["mft"] + }, + "application/rpki-publication": { + "source": "iana" + }, + "application/rpki-roa": { + "source": "iana", + "extensions": ["roa"] + }, + "application/rpki-signed-tal": { + "source": "iana" + }, + "application/rpki-updown": { + "source": "iana" + }, + "application/rsd+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rsd"] + }, + "application/rss+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rss"] + }, + "application/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "application/rtploopback": { + "source": "iana" + }, + "application/rtx": { + "source": "iana" + }, + "application/samlassertion+xml": { + "source": "iana", + "compressible": true + }, + "application/samlmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/sarif+json": { + "source": "iana", + "compressible": true + }, + "application/sarif-external-properties+json": { + "source": "iana", + "compressible": true + }, + "application/sbe": { + "source": "iana" + }, + "application/sbml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sbml"] + }, + "application/scaip+xml": { + "source": "iana", + "compressible": true + }, + "application/scim+json": { + "source": "iana", + "compressible": true + }, + "application/scvp-cv-request": { + "source": "iana", + "extensions": ["scq"] + }, + "application/scvp-cv-response": { + "source": "iana", + "extensions": ["scs"] + }, + "application/scvp-vp-request": { + "source": "iana", + "extensions": ["spq"] + }, + "application/scvp-vp-response": { + "source": "iana", + "extensions": ["spp"] + }, + "application/sdp": { + "source": "iana", + "extensions": ["sdp"] + }, + "application/secevent+jwt": { + "source": "iana" + }, + "application/senml+cbor": { + "source": "iana" + }, + "application/senml+json": { + "source": "iana", + "compressible": true + }, + "application/senml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["senmlx"] + }, + "application/senml-etch+cbor": { + "source": "iana" + }, + "application/senml-etch+json": { + "source": "iana", + "compressible": true + }, + "application/senml-exi": { + "source": "iana" + }, + "application/sensml+cbor": { + "source": "iana" + }, + "application/sensml+json": { + "source": "iana", + "compressible": true + }, + "application/sensml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sensmlx"] + }, + "application/sensml-exi": { + "source": "iana" + }, + "application/sep+xml": { + "source": "iana", + "compressible": true + }, + "application/sep-exi": { + "source": "iana" + }, + "application/session-info": { + "source": "iana" + }, + "application/set-payment": { + "source": "iana" + }, + "application/set-payment-initiation": { + "source": "iana", + "extensions": ["setpay"] + }, + "application/set-registration": { + "source": "iana" + }, + "application/set-registration-initiation": { + "source": "iana", + "extensions": ["setreg"] + }, + "application/sgml": { + "source": "iana" + }, + "application/sgml-open-catalog": { + "source": "iana" + }, + "application/shf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["shf"] + }, + "application/sieve": { + "source": "iana", + "extensions": ["siv","sieve"] + }, + "application/simple-filter+xml": { + "source": "iana", + "compressible": true + }, + "application/simple-message-summary": { + "source": "iana" + }, + "application/simplesymbolcontainer": { + "source": "iana" + }, + "application/sipc": { + "source": "iana" + }, + "application/slate": { + "source": "iana" + }, + "application/smil": { + "source": "apache" + }, + "application/smil+xml": { + "source": "iana", + "compressible": true, + "extensions": ["smi","smil"] + }, + "application/smpte336m": { + "source": "iana" + }, + "application/soap+fastinfoset": { + "source": "iana" + }, + "application/soap+xml": { + "source": "iana", + "compressible": true + }, + "application/sparql-query": { + "source": "iana", + "extensions": ["rq"] + }, + "application/sparql-results+xml": { + "source": "iana", + "compressible": true, + "extensions": ["srx"] + }, + "application/spdx+json": { + "source": "iana", + "compressible": true + }, + "application/spirits-event+xml": { + "source": "iana", + "compressible": true + }, + "application/sql": { + "source": "iana", + "extensions": ["sql"] + }, + "application/srgs": { + "source": "iana", + "extensions": ["gram"] + }, + "application/srgs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["grxml"] + }, + "application/sru+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sru"] + }, + "application/ssdl+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ssdl"] + }, + "application/sslkeylogfile": { + "source": "iana" + }, + "application/ssml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ssml"] + }, + "application/st2110-41": { + "source": "iana" + }, + "application/stix+json": { + "source": "iana", + "compressible": true + }, + "application/stratum": { + "source": "iana" + }, + "application/swid+cbor": { + "source": "iana" + }, + "application/swid+xml": { + "source": "iana", + "compressible": true, + "extensions": ["swidtag"] + }, + "application/tamp-apex-update": { + "source": "iana" + }, + "application/tamp-apex-update-confirm": { + "source": "iana" + }, + "application/tamp-community-update": { + "source": "iana" + }, + "application/tamp-community-update-confirm": { + "source": "iana" + }, + "application/tamp-error": { + "source": "iana" + }, + "application/tamp-sequence-adjust": { + "source": "iana" + }, + "application/tamp-sequence-adjust-confirm": { + "source": "iana" + }, + "application/tamp-status-query": { + "source": "iana" + }, + "application/tamp-status-response": { + "source": "iana" + }, + "application/tamp-update": { + "source": "iana" + }, + "application/tamp-update-confirm": { + "source": "iana" + }, + "application/tar": { + "compressible": true + }, + "application/taxii+json": { + "source": "iana", + "compressible": true + }, + "application/td+json": { + "source": "iana", + "compressible": true + }, + "application/tei+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tei","teicorpus"] + }, + "application/tetra_isi": { + "source": "iana" + }, + "application/thraud+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tfi"] + }, + "application/timestamp-query": { + "source": "iana" + }, + "application/timestamp-reply": { + "source": "iana" + }, + "application/timestamped-data": { + "source": "iana", + "extensions": ["tsd"] + }, + "application/tlsrpt+gzip": { + "source": "iana" + }, + "application/tlsrpt+json": { + "source": "iana", + "compressible": true + }, + "application/tm+json": { + "source": "iana", + "compressible": true + }, + "application/tnauthlist": { + "source": "iana" + }, + "application/toc+cbor": { + "source": "iana" + }, + "application/token-introspection+jwt": { + "source": "iana" + }, + "application/toml": { + "source": "iana", + "compressible": true, + "extensions": ["toml"] + }, + "application/trickle-ice-sdpfrag": { + "source": "iana" + }, + "application/trig": { + "source": "iana", + "extensions": ["trig"] + }, + "application/trust-chain+json": { + "source": "iana", + "compressible": true + }, + "application/trust-mark+jwt": { + "source": "iana" + }, + "application/trust-mark-delegation+jwt": { + "source": "iana" + }, + "application/ttml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ttml"] + }, + "application/tve-trigger": { + "source": "iana" + }, + "application/tzif": { + "source": "iana" + }, + "application/tzif-leap": { + "source": "iana" + }, + "application/ubjson": { + "compressible": false, + "extensions": ["ubj"] + }, + "application/uccs+cbor": { + "source": "iana" + }, + "application/ujcs+json": { + "source": "iana", + "compressible": true + }, + "application/ulpfec": { + "source": "iana" + }, + "application/urc-grpsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/urc-ressheet+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rsheet"] + }, + "application/urc-targetdesc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["td"] + }, + "application/urc-uisocketdesc+xml": { + "source": "iana", + "compressible": true + }, + "application/vc": { + "source": "iana" + }, + "application/vc+cose": { + "source": "iana" + }, + "application/vc+jwt": { + "source": "iana" + }, + "application/vcard+json": { + "source": "iana", + "compressible": true + }, + "application/vcard+xml": { + "source": "iana", + "compressible": true + }, + "application/vemmi": { + "source": "iana" + }, + "application/vividence.scriptfile": { + "source": "apache" + }, + "application/vnd.1000minds.decision-model+xml": { + "source": "iana", + "compressible": true, + "extensions": ["1km"] + }, + "application/vnd.1ob": { + "source": "iana" + }, + "application/vnd.3gpp-prose+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-prose-pc3a+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-prose-pc3ach+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-prose-pc8+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-v2x-local-service-information": { + "source": "iana" + }, + "application/vnd.3gpp.5gnas": { + "source": "iana" + }, + "application/vnd.3gpp.5gsa2x": { + "source": "iana" + }, + "application/vnd.3gpp.5gsa2x-local-service-information": { + "source": "iana" + }, + "application/vnd.3gpp.5gsv2x": { + "source": "iana" + }, + "application/vnd.3gpp.5gsv2x-local-service-information": { + "source": "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.bsf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.crs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.current-location-discovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.gmop+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.gtpc": { + "source": "iana" + }, + "application/vnd.3gpp.interworking-data": { + "source": "iana" + }, + "application/vnd.3gpp.lpp": { + "source": "iana" + }, + "application/vnd.3gpp.mc-signalling-ear": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-msgstore-ctrl-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-payload": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-regroup+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-signalling": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-floor-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-regroup+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-signed+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-ue-init-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-regroup+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-transmission-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mid-call+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.ngap": { + "source": "iana" + }, + "application/vnd.3gpp.pfcp": { + "source": "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + "source": "iana", + "extensions": ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + "source": "iana", + "extensions": ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + "source": "iana", + "extensions": ["pvb"] + }, + "application/vnd.3gpp.pinapp-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.s1ap": { + "source": "iana" + }, + "application/vnd.3gpp.seal-group-doc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.seal-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.seal-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.seal-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.seal-network-qos-management-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.seal-ue-config-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.seal-unicast-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.seal-user-profile-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.sms": { + "source": "iana" + }, + "application/vnd.3gpp.sms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-ext+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.state-and-event-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.ussd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.v2x": { + "source": "iana" + }, + "application/vnd.3gpp.vae-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.sms": { + "source": "iana" + }, + "application/vnd.3gpp2.tcap": { + "source": "iana", + "extensions": ["tcap"] + }, + "application/vnd.3lightssoftware.imagescal": { + "source": "iana" + }, + "application/vnd.3m.post-it-notes": { + "source": "iana", + "extensions": ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + "source": "iana", + "extensions": ["aso"] + }, + "application/vnd.accpac.simply.imp": { + "source": "iana", + "extensions": ["imp"] + }, + "application/vnd.acm.addressxfer+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.acm.chatbot+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.acucobol": { + "source": "iana", + "extensions": ["acu"] + }, + "application/vnd.acucorp": { + "source": "iana", + "extensions": ["atc","acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + "source": "apache", + "compressible": false, + "extensions": ["air"] + }, + "application/vnd.adobe.flash.movie": { + "source": "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + "source": "iana", + "extensions": ["fcdt"] + }, + "application/vnd.adobe.fxp": { + "source": "iana", + "extensions": ["fxp","fxpl"] + }, + "application/vnd.adobe.partial-upload": { + "source": "iana" + }, + "application/vnd.adobe.xdp+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdp"] + }, + "application/vnd.adobe.xfdf": { + "source": "apache", + "extensions": ["xfdf"] + }, + "application/vnd.aether.imp": { + "source": "iana" + }, + "application/vnd.afpc.afplinedata": { + "source": "iana" + }, + "application/vnd.afpc.afplinedata-pagedef": { + "source": "iana" + }, + "application/vnd.afpc.cmoca-cmresource": { + "source": "iana" + }, + "application/vnd.afpc.foca-charset": { + "source": "iana" + }, + "application/vnd.afpc.foca-codedfont": { + "source": "iana" + }, + "application/vnd.afpc.foca-codepage": { + "source": "iana" + }, + "application/vnd.afpc.modca": { + "source": "iana" + }, + "application/vnd.afpc.modca-cmtable": { + "source": "iana" + }, + "application/vnd.afpc.modca-formdef": { + "source": "iana" + }, + "application/vnd.afpc.modca-mediummap": { + "source": "iana" + }, + "application/vnd.afpc.modca-objectcontainer": { + "source": "iana" + }, + "application/vnd.afpc.modca-overlay": { + "source": "iana" + }, + "application/vnd.afpc.modca-pagesegment": { + "source": "iana" + }, + "application/vnd.age": { + "source": "iana", + "extensions": ["age"] + }, + "application/vnd.ah-barcode": { + "source": "apache" + }, + "application/vnd.ahead.space": { + "source": "iana", + "extensions": ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + "source": "iana", + "extensions": ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + "source": "iana", + "extensions": ["azs"] + }, + "application/vnd.amadeus+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.amazon.ebook": { + "source": "apache", + "extensions": ["azw"] + }, + "application/vnd.amazon.mobi8-ebook": { + "source": "iana" + }, + "application/vnd.americandynamics.acc": { + "source": "iana", + "extensions": ["acc"] + }, + "application/vnd.amiga.ami": { + "source": "iana", + "extensions": ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.android.ota": { + "source": "iana" + }, + "application/vnd.android.package-archive": { + "source": "apache", + "compressible": false, + "extensions": ["apk"] + }, + "application/vnd.anki": { + "source": "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + "source": "iana", + "extensions": ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + "source": "apache", + "extensions": ["fti"] + }, + "application/vnd.antix.game-component": { + "source": "iana", + "extensions": ["atx"] + }, + "application/vnd.apache.arrow.file": { + "source": "iana" + }, + "application/vnd.apache.arrow.stream": { + "source": "iana" + }, + "application/vnd.apache.parquet": { + "source": "iana" + }, + "application/vnd.apache.thrift.binary": { + "source": "iana" + }, + "application/vnd.apache.thrift.compact": { + "source": "iana" + }, + "application/vnd.apache.thrift.json": { + "source": "iana" + }, + "application/vnd.apexlang": { + "source": "iana" + }, + "application/vnd.api+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.aplextor.warrp+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apothekende.reservation+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apple.installer+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpkg"] + }, + "application/vnd.apple.keynote": { + "source": "iana", + "extensions": ["key"] + }, + "application/vnd.apple.mpegurl": { + "source": "iana", + "extensions": ["m3u8"] + }, + "application/vnd.apple.numbers": { + "source": "iana", + "extensions": ["numbers"] + }, + "application/vnd.apple.pages": { + "source": "iana", + "extensions": ["pages"] + }, + "application/vnd.apple.pkpass": { + "compressible": false, + "extensions": ["pkpass"] + }, + "application/vnd.arastra.swi": { + "source": "apache" + }, + "application/vnd.aristanetworks.swi": { + "source": "iana", + "extensions": ["swi"] + }, + "application/vnd.artisan+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.artsquare": { + "source": "iana" + }, + "application/vnd.astraea-software.iota": { + "source": "iana", + "extensions": ["iota"] + }, + "application/vnd.audiograph": { + "source": "iana", + "extensions": ["aep"] + }, + "application/vnd.autodesk.fbx": { + "extensions": ["fbx"] + }, + "application/vnd.autopackage": { + "source": "iana" + }, + "application/vnd.avalon+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.avistar+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.balsamiq.bmml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["bmml"] + }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, + "application/vnd.banana-accounting": { + "source": "iana" + }, + "application/vnd.bbf.usp.error": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bekitzur-stech+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.belightsoft.lhzd+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.belightsoft.lhzl+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.bint.med-content": { + "source": "iana" + }, + "application/vnd.biopax.rdf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.blink-idb-value-wrapper": { + "source": "iana" + }, + "application/vnd.blueice.multipass": { + "source": "iana", + "extensions": ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + "source": "iana" + }, + "application/vnd.bluetooth.le.oob": { + "source": "iana" + }, + "application/vnd.bmi": { + "source": "iana", + "extensions": ["bmi"] + }, + "application/vnd.bpf": { + "source": "iana" + }, + "application/vnd.bpf3": { + "source": "iana" + }, + "application/vnd.businessobjects": { + "source": "iana", + "extensions": ["rep"] + }, + "application/vnd.byu.uapi+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bzip3": { + "source": "iana" + }, + "application/vnd.c3voc.schedule+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cab-jscript": { + "source": "iana" + }, + "application/vnd.canon-cpdl": { + "source": "iana" + }, + "application/vnd.canon-lips": { + "source": "iana" + }, + "application/vnd.capasystems-pg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cendio.thinlinc.clientconf": { + "source": "iana" + }, + "application/vnd.century-systems.tcp_stream": { + "source": "iana" + }, + "application/vnd.chemdraw+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cdxml"] + }, + "application/vnd.chess-pgn": { + "source": "iana" + }, + "application/vnd.chipnuts.karaoke-mmd": { + "source": "iana", + "extensions": ["mmd"] + }, + "application/vnd.ciedi": { + "source": "iana" + }, + "application/vnd.cinderella": { + "source": "iana", + "extensions": ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + "source": "iana" + }, + "application/vnd.citationstyles.style+xml": { + "source": "iana", + "compressible": true, + "extensions": ["csl"] + }, + "application/vnd.claymore": { + "source": "iana", + "extensions": ["cla"] + }, + "application/vnd.cloanto.rp9": { + "source": "iana", + "extensions": ["rp9"] + }, + "application/vnd.clonk.c4group": { + "source": "iana", + "extensions": ["c4g","c4d","c4f","c4p","c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + "source": "iana", + "extensions": ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + "source": "iana", + "extensions": ["c11amz"] + }, + "application/vnd.cncf.helm.chart.content.v1.tar+gzip": { + "source": "iana" + }, + "application/vnd.cncf.helm.chart.provenance.v1.prov": { + "source": "iana" + }, + "application/vnd.cncf.helm.config.v1+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.coffeescript": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet-template": { + "source": "iana" + }, + "application/vnd.collection+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.doc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.next+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.comicbook+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.comicbook-rar": { + "source": "iana" + }, + "application/vnd.commerce-battelle": { + "source": "iana" + }, + "application/vnd.commonspace": { + "source": "iana", + "extensions": ["csp"] + }, + "application/vnd.contact.cmsg": { + "source": "iana", + "extensions": ["cdbcmsg"] + }, + "application/vnd.coreos.ignition+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cosmocaller": { + "source": "iana", + "extensions": ["cmc"] + }, + "application/vnd.crick.clicker": { + "source": "iana", + "extensions": ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + "source": "iana", + "extensions": ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + "source": "iana", + "extensions": ["clkp"] + }, + "application/vnd.crick.clicker.template": { + "source": "iana", + "extensions": ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + "source": "iana", + "extensions": ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wbs"] + }, + "application/vnd.cryptii.pipe+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.crypto-shade-file": { + "source": "iana" + }, + "application/vnd.cryptomator.encrypted": { + "source": "iana" + }, + "application/vnd.cryptomator.vault": { + "source": "iana" + }, + "application/vnd.ctc-posml": { + "source": "iana", + "extensions": ["pml"] + }, + "application/vnd.ctct.ws+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cups-pdf": { + "source": "iana" + }, + "application/vnd.cups-postscript": { + "source": "iana" + }, + "application/vnd.cups-ppd": { + "source": "iana", + "extensions": ["ppd"] + }, + "application/vnd.cups-raster": { + "source": "iana" + }, + "application/vnd.cups-raw": { + "source": "iana" + }, + "application/vnd.curl": { + "source": "iana" + }, + "application/vnd.curl.car": { + "source": "apache", + "extensions": ["car"] + }, + "application/vnd.curl.pcurl": { + "source": "apache", + "extensions": ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cybank": { + "source": "iana" + }, + "application/vnd.cyclonedx+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cyclonedx+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.d2l.coursepackage1p0+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.d3m-dataset": { + "source": "iana" + }, + "application/vnd.d3m-problem": { + "source": "iana" + }, + "application/vnd.dart": { + "source": "iana", + "compressible": true, + "extensions": ["dart"] + }, + "application/vnd.data-vision.rdz": { + "source": "iana", + "extensions": ["rdz"] + }, + "application/vnd.datalog": { + "source": "iana" + }, + "application/vnd.datapackage+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dataresource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dbf": { + "source": "iana", + "extensions": ["dbf"] + }, + "application/vnd.dcmp+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dcmp"] + }, + "application/vnd.debian.binary-package": { + "source": "iana" + }, + "application/vnd.dece.data": { + "source": "iana", + "extensions": ["uvf","uvvf","uvd","uvvd"] + }, + "application/vnd.dece.ttml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uvt","uvvt"] + }, + "application/vnd.dece.unspecified": { + "source": "iana", + "extensions": ["uvx","uvvx"] + }, + "application/vnd.dece.zip": { + "source": "iana", + "extensions": ["uvz","uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + "source": "iana", + "extensions": ["fe_launch"] + }, + "application/vnd.desmume.movie": { + "source": "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + "source": "iana" + }, + "application/vnd.dm.delegation+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dna": { + "source": "iana", + "extensions": ["dna"] + }, + "application/vnd.document+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dolby.mlp": { + "source": "apache", + "extensions": ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + "source": "iana" + }, + "application/vnd.dolby.mobile.2": { + "source": "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + "source": "iana" + }, + "application/vnd.dpgraph": { + "source": "iana", + "extensions": ["dpg"] + }, + "application/vnd.dreamfactory": { + "source": "iana", + "extensions": ["dfac"] + }, + "application/vnd.drive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ds-keypoint": { + "source": "apache", + "extensions": ["kpxx"] + }, + "application/vnd.dtg.local": { + "source": "iana" + }, + "application/vnd.dtg.local.flash": { + "source": "iana" + }, + "application/vnd.dtg.local.html": { + "source": "iana" + }, + "application/vnd.dvb.ait": { + "source": "iana", + "extensions": ["ait"] + }, + "application/vnd.dvb.dvbisl+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.dvbj": { + "source": "iana" + }, + "application/vnd.dvb.esgcontainer": { + "source": "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + "source": "iana" + }, + "application/vnd.dvb.ipdcroaming": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + "source": "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-container+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-generic+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-init+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.pfr": { + "source": "iana" + }, + "application/vnd.dvb.service": { + "source": "iana", + "extensions": ["svc"] + }, + "application/vnd.dxr": { + "source": "iana" + }, + "application/vnd.dynageo": { + "source": "iana", + "extensions": ["geo"] + }, + "application/vnd.dzr": { + "source": "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + "source": "iana" + }, + "application/vnd.ecdis-update": { + "source": "iana" + }, + "application/vnd.ecip.rlp": { + "source": "iana" + }, + "application/vnd.eclipse.ditto+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ecowin.chart": { + "source": "iana", + "extensions": ["mag"] + }, + "application/vnd.ecowin.filerequest": { + "source": "iana" + }, + "application/vnd.ecowin.fileupdate": { + "source": "iana" + }, + "application/vnd.ecowin.series": { + "source": "iana" + }, + "application/vnd.ecowin.seriesrequest": { + "source": "iana" + }, + "application/vnd.ecowin.seriesupdate": { + "source": "iana" + }, + "application/vnd.efi.img": { + "source": "iana" + }, + "application/vnd.efi.iso": { + "source": "iana" + }, + "application/vnd.eln+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.emclient.accessrequest+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.enliven": { + "source": "iana", + "extensions": ["nml"] + }, + "application/vnd.enphase.envoy": { + "source": "iana" + }, + "application/vnd.eprints.data+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.epson.esf": { + "source": "iana", + "extensions": ["esf"] + }, + "application/vnd.epson.msf": { + "source": "iana", + "extensions": ["msf"] + }, + "application/vnd.epson.quickanime": { + "source": "iana", + "extensions": ["qam"] + }, + "application/vnd.epson.salt": { + "source": "iana", + "extensions": ["slt"] + }, + "application/vnd.epson.ssf": { + "source": "iana", + "extensions": ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + "source": "iana" + }, + "application/vnd.erofs": { + "source": "iana" + }, + "application/vnd.espass-espass+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.eszigno3+xml": { + "source": "iana", + "compressible": true, + "extensions": ["es3","et3"] + }, + "application/vnd.etsi.aoc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.asic-e+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.asic-s+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.cug+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvcommand+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-bc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-cod+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvservice+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsync+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mcid+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mheg5": { + "source": "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.pstn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.sci+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.simservs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.timestamp-token": { + "source": "iana" + }, + "application/vnd.etsi.tsl+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.tsl.der": { + "source": "iana" + }, + "application/vnd.eu.kasparian.car+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.eudora.data": { + "source": "iana" + }, + "application/vnd.evolv.ecig.profile": { + "source": "iana" + }, + "application/vnd.evolv.ecig.settings": { + "source": "iana" + }, + "application/vnd.evolv.ecig.theme": { + "source": "iana" + }, + "application/vnd.exstream-empower+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.exstream-package": { + "source": "iana" + }, + "application/vnd.ezpix-album": { + "source": "iana", + "extensions": ["ez2"] + }, + "application/vnd.ezpix-package": { + "source": "iana", + "extensions": ["ez3"] + }, + "application/vnd.f-secure.mobile": { + "source": "iana" + }, + "application/vnd.familysearch.gedcom+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.fastcopy-disk-image": { + "source": "iana" + }, + "application/vnd.fdf": { + "source": "apache", + "extensions": ["fdf"] + }, + "application/vnd.fdsn.mseed": { + "source": "iana", + "extensions": ["mseed"] + }, + "application/vnd.fdsn.seed": { + "source": "iana", + "extensions": ["seed","dataless"] + }, + "application/vnd.fdsn.stationxml+xml": { + "source": "iana", + "charset": "XML-BASED", + "compressible": true + }, + "application/vnd.ffsns": { + "source": "iana" + }, + "application/vnd.ficlab.flb+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.filmit.zfc": { + "source": "iana" + }, + "application/vnd.fints": { + "source": "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + "source": "iana" + }, + "application/vnd.flographit": { + "source": "iana", + "extensions": ["gph"] + }, + "application/vnd.fluxtime.clip": { + "source": "iana", + "extensions": ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + "source": "iana" + }, + "application/vnd.framemaker": { + "source": "iana", + "extensions": ["fm","frame","maker","book"] + }, + "application/vnd.freelog.comic": { + "source": "iana" + }, + "application/vnd.frogans.fnc": { + "source": "apache", + "extensions": ["fnc"] + }, + "application/vnd.frogans.ltf": { + "source": "apache", + "extensions": ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + "source": "iana", + "extensions": ["fsc"] + }, + "application/vnd.fujifilm.fb.docuworks": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.docuworks.binder": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.jfi+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.fujitsu.oasys": { + "source": "iana", + "extensions": ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + "source": "iana", + "extensions": ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + "source": "iana", + "extensions": ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + "source": "iana", + "extensions": ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + "source": "iana", + "extensions": ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + "source": "iana" + }, + "application/vnd.fujixerox.art4": { + "source": "iana" + }, + "application/vnd.fujixerox.ddd": { + "source": "iana", + "extensions": ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + "source": "iana", + "extensions": ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + "source": "iana", + "extensions": ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujixerox.hbpl": { + "source": "iana" + }, + "application/vnd.fut-misnet": { + "source": "iana" + }, + "application/vnd.futoin+cbor": { + "source": "iana" + }, + "application/vnd.futoin+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.fuzzysheet": { + "source": "iana", + "extensions": ["fzs"] + }, + "application/vnd.ga4gh.passport+jwt": { + "source": "iana" + }, + "application/vnd.genomatix.tuxedo": { + "source": "iana", + "extensions": ["txd"] + }, + "application/vnd.genozip": { + "source": "iana" + }, + "application/vnd.gentics.grd+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.gentoo.catmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.gentoo.ebuild": { + "source": "iana" + }, + "application/vnd.gentoo.eclass": { + "source": "iana" + }, + "application/vnd.gentoo.gpkg": { + "source": "iana" + }, + "application/vnd.gentoo.manifest": { + "source": "iana" + }, + "application/vnd.gentoo.pkgmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.gentoo.xpak": { + "source": "iana" + }, + "application/vnd.geo+json": { + "source": "apache", + "compressible": true + }, + "application/vnd.geocube+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.geogebra.file": { + "source": "iana", + "extensions": ["ggb"] + }, + "application/vnd.geogebra.pinboard": { + "source": "iana" + }, + "application/vnd.geogebra.slides": { + "source": "iana", + "extensions": ["ggs"] + }, + "application/vnd.geogebra.tool": { + "source": "iana", + "extensions": ["ggt"] + }, + "application/vnd.geometry-explorer": { + "source": "iana", + "extensions": ["gex","gre"] + }, + "application/vnd.geonext": { + "source": "iana", + "extensions": ["gxt"] + }, + "application/vnd.geoplan": { + "source": "iana", + "extensions": ["g2w"] + }, + "application/vnd.geospace": { + "source": "iana", + "extensions": ["g3w"] + }, + "application/vnd.gerber": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + "source": "iana" + }, + "application/vnd.gmx": { + "source": "iana", + "extensions": ["gmx"] + }, + "application/vnd.gnu.taler.exchange+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.gnu.taler.merchant+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.google-apps.audio": {}, + "application/vnd.google-apps.document": { + "compressible": false, + "extensions": ["gdoc"] + }, + "application/vnd.google-apps.drawing": { + "compressible": false, + "extensions": ["gdraw"] + }, + "application/vnd.google-apps.drive-sdk": { + "compressible": false + }, + "application/vnd.google-apps.file": {}, + "application/vnd.google-apps.folder": { + "compressible": false + }, + "application/vnd.google-apps.form": { + "compressible": false, + "extensions": ["gform"] + }, + "application/vnd.google-apps.fusiontable": {}, + "application/vnd.google-apps.jam": { + "compressible": false, + "extensions": ["gjam"] + }, + "application/vnd.google-apps.mail-layout": {}, + "application/vnd.google-apps.map": { + "compressible": false, + "extensions": ["gmap"] + }, + "application/vnd.google-apps.photo": {}, + "application/vnd.google-apps.presentation": { + "compressible": false, + "extensions": ["gslides"] + }, + "application/vnd.google-apps.script": { + "compressible": false, + "extensions": ["gscript"] + }, + "application/vnd.google-apps.shortcut": {}, + "application/vnd.google-apps.site": { + "compressible": false, + "extensions": ["gsite"] + }, + "application/vnd.google-apps.spreadsheet": { + "compressible": false, + "extensions": ["gsheet"] + }, + "application/vnd.google-apps.unknown": {}, + "application/vnd.google-apps.video": {}, + "application/vnd.google-earth.kml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["kml"] + }, + "application/vnd.google-earth.kmz": { + "source": "iana", + "compressible": false, + "extensions": ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.gov.sk.e-form+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdcf"] + }, + "application/vnd.gpxsee.map+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.grafeq": { + "source": "iana", + "extensions": ["gqf","gqs"] + }, + "application/vnd.gridmp": { + "source": "iana" + }, + "application/vnd.groove-account": { + "source": "iana", + "extensions": ["gac"] + }, + "application/vnd.groove-help": { + "source": "iana", + "extensions": ["ghf"] + }, + "application/vnd.groove-identity-message": { + "source": "iana", + "extensions": ["gim"] + }, + "application/vnd.groove-injector": { + "source": "iana", + "extensions": ["grv"] + }, + "application/vnd.groove-tool-message": { + "source": "iana", + "extensions": ["gtm"] + }, + "application/vnd.groove-tool-template": { + "source": "iana", + "extensions": ["tpl"] + }, + "application/vnd.groove-vcard": { + "source": "iana", + "extensions": ["vcg"] + }, + "application/vnd.hal+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hal+xml": { + "source": "iana", + "compressible": true, + "extensions": ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zmm"] + }, + "application/vnd.hbci": { + "source": "iana", + "extensions": ["hbci"] + }, + "application/vnd.hc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hcl-bireports": { + "source": "iana" + }, + "application/vnd.hdt": { + "source": "iana" + }, + "application/vnd.heroku+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hhe.lesson-player": { + "source": "iana", + "extensions": ["les"] + }, + "application/vnd.hp-hpgl": { + "source": "iana", + "extensions": ["hpgl"] + }, + "application/vnd.hp-hpid": { + "source": "iana", + "extensions": ["hpid"] + }, + "application/vnd.hp-hps": { + "source": "iana", + "extensions": ["hps"] + }, + "application/vnd.hp-jlyt": { + "source": "iana", + "extensions": ["jlt"] + }, + "application/vnd.hp-pcl": { + "source": "iana", + "extensions": ["pcl"] + }, + "application/vnd.hp-pclxl": { + "source": "iana", + "extensions": ["pclxl"] + }, + "application/vnd.hsl": { + "source": "iana" + }, + "application/vnd.httphone": { + "source": "iana" + }, + "application/vnd.hydrostatix.sof-data": { + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyper+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyper-item+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hzn-3d-crossword": { + "source": "iana" + }, + "application/vnd.ibm.afplinedata": { + "source": "apache" + }, + "application/vnd.ibm.electronic-media": { + "source": "iana" + }, + "application/vnd.ibm.minipay": { + "source": "iana", + "extensions": ["mpy"] + }, + "application/vnd.ibm.modcap": { + "source": "apache", + "extensions": ["afp","listafp","list3820"] + }, + "application/vnd.ibm.rights-management": { + "source": "iana", + "extensions": ["irm"] + }, + "application/vnd.ibm.secure-container": { + "source": "iana", + "extensions": ["sc"] + }, + "application/vnd.iccprofile": { + "source": "iana", + "extensions": ["icc","icm"] + }, + "application/vnd.ieee.1905": { + "source": "iana" + }, + "application/vnd.igloader": { + "source": "iana", + "extensions": ["igl"] + }, + "application/vnd.imagemeter.folder+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.imagemeter.image+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.immervision-ivp": { + "source": "iana", + "extensions": ["ivp"] + }, + "application/vnd.immervision-ivu": { + "source": "iana", + "extensions": ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p2": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p3": { + "source": "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.informedcontrol.rms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.informix-visionary": { + "source": "apache" + }, + "application/vnd.infotech.project": { + "source": "iana" + }, + "application/vnd.infotech.project+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.innopath.wamp.notification": { + "source": "iana" + }, + "application/vnd.insors.igm": { + "source": "iana", + "extensions": ["igm"] + }, + "application/vnd.intercon.formnet": { + "source": "iana", + "extensions": ["xpw","xpx"] + }, + "application/vnd.intergeo": { + "source": "iana", + "extensions": ["i2g"] + }, + "application/vnd.intertrust.digibox": { + "source": "iana" + }, + "application/vnd.intertrust.nncp": { + "source": "iana" + }, + "application/vnd.intu.qbo": { + "source": "iana", + "extensions": ["qbo"] + }, + "application/vnd.intu.qfx": { + "source": "iana", + "extensions": ["qfx"] + }, + "application/vnd.ipfs.ipns-record": { + "source": "iana" + }, + "application/vnd.ipld.car": { + "source": "iana" + }, + "application/vnd.ipld.dag-cbor": { + "source": "iana" + }, + "application/vnd.ipld.dag-json": { + "source": "iana" + }, + "application/vnd.ipld.raw": { + "source": "iana" + }, + "application/vnd.iptc.g2.catalogitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.conceptitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.packageitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.planningitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ipunplugged.rcprofile": { + "source": "iana", + "extensions": ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["irp"] + }, + "application/vnd.is-xpr": { + "source": "iana", + "extensions": ["xpr"] + }, + "application/vnd.isac.fcs": { + "source": "iana", + "extensions": ["fcs"] + }, + "application/vnd.iso11783-10+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.jam": { + "source": "iana", + "extensions": ["jam"] + }, + "application/vnd.japannet-directory-service": { + "source": "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-payment-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-registration": { + "source": "iana" + }, + "application/vnd.japannet-registration-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-verification": { + "source": "iana" + }, + "application/vnd.japannet-verification-wakeup": { + "source": "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + "source": "iana", + "extensions": ["rms"] + }, + "application/vnd.jisp": { + "source": "iana", + "extensions": ["jisp"] + }, + "application/vnd.joost.joda-archive": { + "source": "iana", + "extensions": ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + "source": "iana" + }, + "application/vnd.kahootz": { + "source": "iana", + "extensions": ["ktz","ktr"] + }, + "application/vnd.kde.karbon": { + "source": "iana", + "extensions": ["karbon"] + }, + "application/vnd.kde.kchart": { + "source": "iana", + "extensions": ["chrt"] + }, + "application/vnd.kde.kformula": { + "source": "iana", + "extensions": ["kfo"] + }, + "application/vnd.kde.kivio": { + "source": "iana", + "extensions": ["flw"] + }, + "application/vnd.kde.kontour": { + "source": "iana", + "extensions": ["kon"] + }, + "application/vnd.kde.kpresenter": { + "source": "iana", + "extensions": ["kpr","kpt"] + }, + "application/vnd.kde.kspread": { + "source": "iana", + "extensions": ["ksp"] + }, + "application/vnd.kde.kword": { + "source": "iana", + "extensions": ["kwd","kwt"] + }, + "application/vnd.kdl": { + "source": "iana" + }, + "application/vnd.kenameaapp": { + "source": "iana", + "extensions": ["htke"] + }, + "application/vnd.keyman.kmp+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.keyman.kmx": { + "source": "iana" + }, + "application/vnd.kidspiration": { + "source": "iana", + "extensions": ["kia"] + }, + "application/vnd.kinar": { + "source": "iana", + "extensions": ["kne","knp"] + }, + "application/vnd.koan": { + "source": "iana", + "extensions": ["skp","skd","skt","skm"] + }, + "application/vnd.kodak-descriptor": { + "source": "iana", + "extensions": ["sse"] + }, + "application/vnd.las": { + "source": "iana" + }, + "application/vnd.las.las+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.las.las+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lasxml"] + }, + "application/vnd.laszip": { + "source": "iana" + }, + "application/vnd.ldev.productlicensing": { + "source": "iana" + }, + "application/vnd.leap+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.liberty-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.llamagraphics.life-balance.desktop": { + "source": "iana", + "extensions": ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lbe"] + }, + "application/vnd.logipipe.circuit+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.loom": { + "source": "iana" + }, + "application/vnd.lotus-1-2-3": { + "source": "iana", + "extensions": ["123"] + }, + "application/vnd.lotus-approach": { + "source": "iana", + "extensions": ["apr"] + }, + "application/vnd.lotus-freelance": { + "source": "iana", + "extensions": ["pre"] + }, + "application/vnd.lotus-notes": { + "source": "iana", + "extensions": ["nsf"] + }, + "application/vnd.lotus-organizer": { + "source": "iana", + "extensions": ["org"] + }, + "application/vnd.lotus-screencam": { + "source": "iana", + "extensions": ["scm"] + }, + "application/vnd.lotus-wordpro": { + "source": "iana", + "extensions": ["lwp"] + }, + "application/vnd.macports.portpkg": { + "source": "iana", + "extensions": ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + "source": "iana", + "extensions": ["mvt"] + }, + "application/vnd.marlin.drm.actiontoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.conftoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.license+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.mdcf": { + "source": "iana" + }, + "application/vnd.mason+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.maxar.archive.3tz+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.maxmind.maxmind-db": { + "source": "iana" + }, + "application/vnd.mcd": { + "source": "iana", + "extensions": ["mcd"] + }, + "application/vnd.mdl": { + "source": "iana" + }, + "application/vnd.mdl-mbsdf": { + "source": "iana" + }, + "application/vnd.medcalcdata": { + "source": "iana", + "extensions": ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + "source": "iana", + "extensions": ["cdkey"] + }, + "application/vnd.medicalholodeck.recordxr": { + "source": "iana" + }, + "application/vnd.meridian-slingshot": { + "source": "iana" + }, + "application/vnd.mermaid": { + "source": "iana" + }, + "application/vnd.mfer": { + "source": "iana", + "extensions": ["mwf"] + }, + "application/vnd.mfmp": { + "source": "iana", + "extensions": ["mfm"] + }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.micrografx.flo": { + "source": "iana", + "extensions": ["flo"] + }, + "application/vnd.micrografx.igx": { + "source": "iana", + "extensions": ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, + "application/vnd.microsoft.windows.thumbnail-cache": { + "source": "iana" + }, + "application/vnd.miele+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.mif": { + "source": "iana", + "extensions": ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + "source": "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + "source": "iana" + }, + "application/vnd.mobius.daf": { + "source": "iana", + "extensions": ["daf"] + }, + "application/vnd.mobius.dis": { + "source": "iana", + "extensions": ["dis"] + }, + "application/vnd.mobius.mbk": { + "source": "iana", + "extensions": ["mbk"] + }, + "application/vnd.mobius.mqy": { + "source": "iana", + "extensions": ["mqy"] + }, + "application/vnd.mobius.msl": { + "source": "iana", + "extensions": ["msl"] + }, + "application/vnd.mobius.plc": { + "source": "iana", + "extensions": ["plc"] + }, + "application/vnd.mobius.txf": { + "source": "iana", + "extensions": ["txf"] + }, + "application/vnd.modl": { + "source": "iana" + }, + "application/vnd.mophun.application": { + "source": "iana", + "extensions": ["mpn"] + }, + "application/vnd.mophun.certificate": { + "source": "iana", + "extensions": ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + "source": "iana" + }, + "application/vnd.motorola.iprm": { + "source": "iana" + }, + "application/vnd.mozilla.xul+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xul"] + }, + "application/vnd.ms-3mfdocument": { + "source": "iana" + }, + "application/vnd.ms-artgalry": { + "source": "iana", + "extensions": ["cil"] + }, + "application/vnd.ms-asf": { + "source": "iana" + }, + "application/vnd.ms-cab-compressed": { + "source": "iana", + "extensions": ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + "source": "apache" + }, + "application/vnd.ms-excel": { + "source": "iana", + "compressible": false, + "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + "source": "iana", + "extensions": ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + "source": "iana", + "extensions": ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + "source": "iana", + "extensions": ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + "source": "iana", + "extensions": ["xltm"] + }, + "application/vnd.ms-fontobject": { + "source": "iana", + "compressible": true, + "extensions": ["eot"] + }, + "application/vnd.ms-htmlhelp": { + "source": "iana", + "extensions": ["chm"] + }, + "application/vnd.ms-ims": { + "source": "iana", + "extensions": ["ims"] + }, + "application/vnd.ms-lrm": { + "source": "iana", + "extensions": ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-officetheme": { + "source": "iana", + "extensions": ["thmx"] + }, + "application/vnd.ms-opentype": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-outlook": { + "compressible": false, + "extensions": ["msg"] + }, + "application/vnd.ms-package.obfuscated-opentype": { + "source": "apache" + }, + "application/vnd.ms-pki.seccat": { + "source": "apache", + "extensions": ["cat"] + }, + "application/vnd.ms-pki.stl": { + "source": "apache", + "extensions": ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-powerpoint": { + "source": "iana", + "compressible": false, + "extensions": ["ppt","pps","pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + "source": "iana", + "extensions": ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + "source": "iana", + "extensions": ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + "source": "iana", + "extensions": ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + "source": "iana", + "extensions": ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + "source": "iana", + "extensions": ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-printing.printticket+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-printschematicket+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-project": { + "source": "iana", + "extensions": ["mpp","mpt"] + }, + "application/vnd.ms-tnef": { + "source": "iana" + }, + "application/vnd.ms-visio.viewer": { + "extensions": ["vdx"] + }, + "application/vnd.ms-windows.devicepairing": { + "source": "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + "source": "iana" + }, + "application/vnd.ms-windows.printerpairing": { + "source": "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + "source": "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + "source": "iana", + "extensions": ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + "source": "iana", + "extensions": ["dotm"] + }, + "application/vnd.ms-works": { + "source": "iana", + "extensions": ["wps","wks","wcm","wdb"] + }, + "application/vnd.ms-wpl": { + "source": "iana", + "extensions": ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + "source": "iana", + "compressible": false, + "extensions": ["xps"] + }, + "application/vnd.msa-disk-image": { + "source": "iana" + }, + "application/vnd.mseq": { + "source": "iana", + "extensions": ["mseq"] + }, + "application/vnd.msgpack": { + "source": "iana" + }, + "application/vnd.msign": { + "source": "iana" + }, + "application/vnd.multiad.creator": { + "source": "iana" + }, + "application/vnd.multiad.creator.cif": { + "source": "iana" + }, + "application/vnd.music-niff": { + "source": "iana" + }, + "application/vnd.musician": { + "source": "iana", + "extensions": ["mus"] + }, + "application/vnd.muvee.style": { + "source": "iana", + "extensions": ["msty"] + }, + "application/vnd.mynfc": { + "source": "iana", + "extensions": ["taglet"] + }, + "application/vnd.nacamar.ybrid+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.nato.bindingdataobject+cbor": { + "source": "iana" + }, + "application/vnd.nato.bindingdataobject+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.nato.bindingdataobject+xml": { + "source": "iana", + "compressible": true, + "extensions": ["bdo"] + }, + "application/vnd.nato.openxmlformats-package.iepd+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.ncd.control": { + "source": "iana" + }, + "application/vnd.ncd.reference": { + "source": "iana" + }, + "application/vnd.nearst.inv+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.nebumind.line": { + "source": "iana" + }, + "application/vnd.nervana": { + "source": "iana" + }, + "application/vnd.netfpx": { + "source": "iana" + }, + "application/vnd.neurolanguage.nlu": { + "source": "iana", + "extensions": ["nlu"] + }, + "application/vnd.nimn": { + "source": "iana" + }, + "application/vnd.nintendo.nitro.rom": { + "source": "iana" + }, + "application/vnd.nintendo.snes.rom": { + "source": "iana" + }, + "application/vnd.nitf": { + "source": "iana", + "extensions": ["ntf","nitf"] + }, + "application/vnd.noblenet-directory": { + "source": "iana", + "extensions": ["nnd"] + }, + "application/vnd.noblenet-sealer": { + "source": "iana", + "extensions": ["nns"] + }, + "application/vnd.noblenet-web": { + "source": "iana", + "extensions": ["nnw"] + }, + "application/vnd.nokia.catalogs": { + "source": "iana" + }, + "application/vnd.nokia.conml+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.conml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.iptv.config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.isds-radio-presets": { + "source": "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.landmark+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.landmarkcollection+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.n-gage.ac+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ac"] + }, + "application/vnd.nokia.n-gage.data": { + "source": "iana", + "extensions": ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + "source": "apache", + "extensions": ["n-gage"] + }, + "application/vnd.nokia.ncd": { + "source": "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.pcd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.radio-preset": { + "source": "iana", + "extensions": ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + "source": "iana", + "extensions": ["rpss"] + }, + "application/vnd.novadigm.edm": { + "source": "iana", + "extensions": ["edm"] + }, + "application/vnd.novadigm.edx": { + "source": "iana", + "extensions": ["edx"] + }, + "application/vnd.novadigm.ext": { + "source": "iana", + "extensions": ["ext"] + }, + "application/vnd.ntt-local.content-share": { + "source": "iana" + }, + "application/vnd.ntt-local.file-transfer": { + "source": "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + "source": "iana" + }, + "application/vnd.oai.workflows": { + "source": "iana" + }, + "application/vnd.oai.workflows+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oai.workflows+yaml": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.base": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.chart": { + "source": "iana", + "extensions": ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + "source": "iana", + "extensions": ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + "source": "apache", + "extensions": ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + "source": "iana", + "extensions": ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + "source": "iana", + "extensions": ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + "source": "iana", + "compressible": false, + "extensions": ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + "source": "iana", + "extensions": ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + "source": "iana", + "extensions": ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + "source": "iana", + "extensions": ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + "source": "iana", + "extensions": ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + "source": "iana", + "compressible": false, + "extensions": ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + "source": "iana", + "extensions": ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + "source": "iana", + "compressible": false, + "extensions": ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + "source": "iana", + "extensions": ["odm"] + }, + "application/vnd.oasis.opendocument.text-master-template": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.text-template": { + "source": "iana", + "extensions": ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + "source": "iana", + "extensions": ["oth"] + }, + "application/vnd.obn": { + "source": "iana" + }, + "application/vnd.ocf+cbor": { + "source": "iana" + }, + "application/vnd.oci.image.manifest.v1+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oftn.l10n+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.cspg-hexbinary": { + "source": "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.dae.xhtml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.pae.gem": { + "source": "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.spdlist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.ueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.userprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.olpc-sugar": { + "source": "iana", + "extensions": ["xo"] + }, + "application/vnd.oma-scws-config": { + "source": "iana" + }, + "application/vnd.oma-scws-http-request": { + "source": "iana" + }, + "application/vnd.oma-scws-http-response": { + "source": "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.oma.bcast.imd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.ltkm": { + "source": "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.provisioningtrigger": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgboot": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.sgdu": { + "source": "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + "source": "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.oma.bcast.sprov+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.stkm": { + "source": "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-feature-handler+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-pcc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-subs-invite+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-user-prefs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.dcd": { + "source": "iana" + }, + "application/vnd.oma.dcdc": { + "source": "iana" + }, + "application/vnd.oma.dd2+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.group-usage-list+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+cbor": { + "source": "iana" + }, + "application/vnd.oma.lwm2m+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+tlv": { + "source": "iana" + }, + "application/vnd.oma.pal+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.final-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.groups+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.push": { + "source": "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.xcap-directory+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.omads-email+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omads-file+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omads-folder+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omaloc-supl-init": { + "source": "iana" + }, + "application/vnd.onepager": { + "source": "iana" + }, + "application/vnd.onepagertamp": { + "source": "iana" + }, + "application/vnd.onepagertamx": { + "source": "iana" + }, + "application/vnd.onepagertat": { + "source": "iana" + }, + "application/vnd.onepagertatp": { + "source": "iana" + }, + "application/vnd.onepagertatx": { + "source": "iana" + }, + "application/vnd.onvif.metadata": { + "source": "iana" + }, + "application/vnd.openblox.game+xml": { + "source": "iana", + "compressible": true, + "extensions": ["obgx"] + }, + "application/vnd.openblox.game-binary": { + "source": "iana" + }, + "application/vnd.openeye.oeb": { + "source": "iana" + }, + "application/vnd.openofficeorg.extension": { + "source": "apache", + "extensions": ["oxt"] + }, + "application/vnd.openstreetmap.data+xml": { + "source": "iana", + "compressible": true, + "extensions": ["osm"] + }, + "application/vnd.opentimestamps.ots": { + "source": "iana" + }, + "application/vnd.openvpi.dspx+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + "source": "iana", + "extensions": ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + "source": "iana", + "extensions": ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + "source": "iana", + "extensions": ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "source": "iana", + "compressible": false, + "extensions": ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + "source": "iana", + "extensions": ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + "source": "iana", + "compressible": false, + "extensions": ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + "source": "iana", + "extensions": ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.relationships+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oracle.resource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.orange.indata": { + "source": "iana" + }, + "application/vnd.osa.netdeploy": { + "source": "iana" + }, + "application/vnd.osgeo.mapguide.package": { + "source": "iana", + "extensions": ["mgp"] + }, + "application/vnd.osgi.bundle": { + "source": "iana" + }, + "application/vnd.osgi.dp": { + "source": "iana", + "extensions": ["dp"] + }, + "application/vnd.osgi.subsystem": { + "source": "iana", + "extensions": ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oxli.countgraph": { + "source": "iana" + }, + "application/vnd.pagerduty+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.palm": { + "source": "iana", + "extensions": ["pdb","pqa","oprc"] + }, + "application/vnd.panoply": { + "source": "iana" + }, + "application/vnd.paos.xml": { + "source": "iana" + }, + "application/vnd.patentdive": { + "source": "iana" + }, + "application/vnd.patientecommsdoc": { + "source": "iana" + }, + "application/vnd.pawaafile": { + "source": "iana", + "extensions": ["paw"] + }, + "application/vnd.pcos": { + "source": "iana" + }, + "application/vnd.pg.format": { + "source": "iana", + "extensions": ["str"] + }, + "application/vnd.pg.osasli": { + "source": "iana", + "extensions": ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + "source": "iana" + }, + "application/vnd.picsel": { + "source": "iana", + "extensions": ["efif"] + }, + "application/vnd.pmi.widget": { + "source": "iana", + "extensions": ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.pocketlearn": { + "source": "iana", + "extensions": ["plf"] + }, + "application/vnd.powerbuilder6": { + "source": "iana", + "extensions": ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + "source": "iana" + }, + "application/vnd.powerbuilder7": { + "source": "iana" + }, + "application/vnd.powerbuilder7-s": { + "source": "iana" + }, + "application/vnd.powerbuilder75": { + "source": "iana" + }, + "application/vnd.powerbuilder75-s": { + "source": "iana" + }, + "application/vnd.preminet": { + "source": "iana" + }, + "application/vnd.previewsystems.box": { + "source": "iana", + "extensions": ["box"] + }, + "application/vnd.procrate.brushset": { + "extensions": ["brushset"] + }, + "application/vnd.procreate.brush": { + "extensions": ["brush"] + }, + "application/vnd.procreate.dream": { + "extensions": ["drm"] + }, + "application/vnd.proteus.magazine": { + "source": "iana", + "extensions": ["mgz"] + }, + "application/vnd.psfs": { + "source": "iana" + }, + "application/vnd.pt.mundusmundi": { + "source": "iana" + }, + "application/vnd.publishare-delta-tree": { + "source": "iana", + "extensions": ["qps"] + }, + "application/vnd.pvi.ptid1": { + "source": "iana", + "extensions": ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + "source": "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtm"] + }, + "application/vnd.qualcomm.brew-app-res": { + "source": "iana" + }, + "application/vnd.quarantainenet": { + "source": "iana" + }, + "application/vnd.quark.quarkxpress": { + "source": "iana", + "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] + }, + "application/vnd.quobject-quoxdocument": { + "source": "iana" + }, + "application/vnd.radisys.moml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-stream+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-base+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-group+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.rainstor.data": { + "source": "iana" + }, + "application/vnd.rapid": { + "source": "iana" + }, + "application/vnd.rar": { + "source": "iana", + "extensions": ["rar"] + }, + "application/vnd.realvnc.bed": { + "source": "iana", + "extensions": ["bed"] + }, + "application/vnd.recordare.musicxml": { + "source": "iana", + "extensions": ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["musicxml"] + }, + "application/vnd.relpipe": { + "source": "iana" + }, + "application/vnd.renlearn.rlprint": { + "source": "iana" + }, + "application/vnd.resilient.logic": { + "source": "iana" + }, + "application/vnd.restful+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.rig.cryptonote": { + "source": "iana", + "extensions": ["cryptonote"] + }, + "application/vnd.rim.cod": { + "source": "apache", + "extensions": ["cod"] + }, + "application/vnd.rn-realmedia": { + "source": "apache", + "extensions": ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + "source": "apache", + "extensions": ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + "source": "iana", + "compressible": true, + "extensions": ["link66"] + }, + "application/vnd.rs-274x": { + "source": "iana" + }, + "application/vnd.ruckus.download": { + "source": "iana" + }, + "application/vnd.s3sms": { + "source": "iana" + }, + "application/vnd.sailingtracker.track": { + "source": "iana", + "extensions": ["st"] + }, + "application/vnd.sar": { + "source": "iana" + }, + "application/vnd.sbm.cid": { + "source": "iana" + }, + "application/vnd.sbm.mid2": { + "source": "iana" + }, + "application/vnd.scribus": { + "source": "iana" + }, + "application/vnd.sealed.3df": { + "source": "iana" + }, + "application/vnd.sealed.csf": { + "source": "iana" + }, + "application/vnd.sealed.doc": { + "source": "iana" + }, + "application/vnd.sealed.eml": { + "source": "iana" + }, + "application/vnd.sealed.mht": { + "source": "iana" + }, + "application/vnd.sealed.net": { + "source": "iana" + }, + "application/vnd.sealed.ppt": { + "source": "iana" + }, + "application/vnd.sealed.tiff": { + "source": "iana" + }, + "application/vnd.sealed.xls": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + "source": "iana" + }, + "application/vnd.seemail": { + "source": "iana", + "extensions": ["see"] + }, + "application/vnd.seis+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.sema": { + "source": "iana", + "extensions": ["sema"] + }, + "application/vnd.semd": { + "source": "iana", + "extensions": ["semd"] + }, + "application/vnd.semf": { + "source": "iana", + "extensions": ["semf"] + }, + "application/vnd.shade-save-file": { + "source": "iana" + }, + "application/vnd.shana.informed.formdata": { + "source": "iana", + "extensions": ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + "source": "iana", + "extensions": ["itp"] + }, + "application/vnd.shana.informed.interchange": { + "source": "iana", + "extensions": ["iif"] + }, + "application/vnd.shana.informed.package": { + "source": "iana", + "extensions": ["ipk"] + }, + "application/vnd.shootproof+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.shopkick+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.shp": { + "source": "iana" + }, + "application/vnd.shx": { + "source": "iana" + }, + "application/vnd.sigrok.session": { + "source": "iana" + }, + "application/vnd.simtech-mindmapper": { + "source": "iana", + "extensions": ["twd","twds"] + }, + "application/vnd.siren+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.sketchometry": { + "source": "iana" + }, + "application/vnd.smaf": { + "source": "iana", + "extensions": ["mmf"] + }, + "application/vnd.smart.notebook": { + "source": "iana" + }, + "application/vnd.smart.teacher": { + "source": "iana", + "extensions": ["teacher"] + }, + "application/vnd.smintio.portals.archive": { + "source": "iana" + }, + "application/vnd.snesdev-page-table": { + "source": "iana" + }, + "application/vnd.software602.filler.form+xml": { + "source": "iana", + "compressible": true, + "extensions": ["fo"] + }, + "application/vnd.software602.filler.form-xml-zip": { + "source": "iana" + }, + "application/vnd.solent.sdkm+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sdkm","sdkd"] + }, + "application/vnd.spotfire.dxp": { + "source": "iana", + "extensions": ["dxp"] + }, + "application/vnd.spotfire.sfs": { + "source": "iana", + "extensions": ["sfs"] + }, + "application/vnd.sqlite3": { + "source": "iana" + }, + "application/vnd.sss-cod": { + "source": "iana" + }, + "application/vnd.sss-dtf": { + "source": "iana" + }, + "application/vnd.sss-ntf": { + "source": "iana" + }, + "application/vnd.stardivision.calc": { + "source": "apache", + "extensions": ["sdc"] + }, + "application/vnd.stardivision.draw": { + "source": "apache", + "extensions": ["sda"] + }, + "application/vnd.stardivision.impress": { + "source": "apache", + "extensions": ["sdd"] + }, + "application/vnd.stardivision.math": { + "source": "apache", + "extensions": ["smf"] + }, + "application/vnd.stardivision.writer": { + "source": "apache", + "extensions": ["sdw","vor"] + }, + "application/vnd.stardivision.writer-global": { + "source": "apache", + "extensions": ["sgl"] + }, + "application/vnd.stepmania.package": { + "source": "iana", + "extensions": ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + "source": "iana", + "extensions": ["sm"] + }, + "application/vnd.street-stream": { + "source": "iana" + }, + "application/vnd.sun.wadl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wadl"] + }, + "application/vnd.sun.xml.calc": { + "source": "apache", + "extensions": ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + "source": "apache", + "extensions": ["stc"] + }, + "application/vnd.sun.xml.draw": { + "source": "apache", + "extensions": ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + "source": "apache", + "extensions": ["std"] + }, + "application/vnd.sun.xml.impress": { + "source": "apache", + "extensions": ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + "source": "apache", + "extensions": ["sti"] + }, + "application/vnd.sun.xml.math": { + "source": "apache", + "extensions": ["sxm"] + }, + "application/vnd.sun.xml.writer": { + "source": "apache", + "extensions": ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + "source": "apache", + "extensions": ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + "source": "apache", + "extensions": ["stw"] + }, + "application/vnd.sus-calendar": { + "source": "iana", + "extensions": ["sus","susp"] + }, + "application/vnd.svd": { + "source": "iana", + "extensions": ["svd"] + }, + "application/vnd.swiftview-ics": { + "source": "iana" + }, + "application/vnd.sybyl.mol2": { + "source": "iana" + }, + "application/vnd.sycle+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.syft+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.symbian.install": { + "source": "apache", + "extensions": ["sis","sisx"] + }, + "application/vnd.syncml+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["ddf"] + }, + "application/vnd.syncml.dmtnds+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.syncml.ds.notification": { + "source": "iana" + }, + "application/vnd.tableschema+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tao.intent-module-archive": { + "source": "iana", + "extensions": ["tao"] + }, + "application/vnd.tcpdump.pcap": { + "source": "iana", + "extensions": ["pcap","cap","dmp"] + }, + "application/vnd.think-cell.ppttc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tmd.mediaflex.api+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.tml": { + "source": "iana" + }, + "application/vnd.tmobile-livetv": { + "source": "iana", + "extensions": ["tmo"] + }, + "application/vnd.tri.onesource": { + "source": "iana" + }, + "application/vnd.trid.tpt": { + "source": "iana", + "extensions": ["tpt"] + }, + "application/vnd.triscape.mxs": { + "source": "iana", + "extensions": ["mxs"] + }, + "application/vnd.trueapp": { + "source": "iana", + "extensions": ["tra"] + }, + "application/vnd.truedoc": { + "source": "iana" + }, + "application/vnd.ubisoft.webplayer": { + "source": "iana" + }, + "application/vnd.ufdl": { + "source": "iana", + "extensions": ["ufd","ufdl"] + }, + "application/vnd.uic.osdm+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.uiq.theme": { + "source": "iana", + "extensions": ["utz"] + }, + "application/vnd.umajin": { + "source": "iana", + "extensions": ["umj"] + }, + "application/vnd.unity": { + "source": "iana", + "extensions": ["unityweb"] + }, + "application/vnd.uoml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uoml","uo"] + }, + "application/vnd.uplanet.alert": { + "source": "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.channel": { + "source": "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.list": { + "source": "iana" + }, + "application/vnd.uplanet.list-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.signal": { + "source": "iana" + }, + "application/vnd.uri-map": { + "source": "iana" + }, + "application/vnd.valve.source.material": { + "source": "iana" + }, + "application/vnd.vcx": { + "source": "iana", + "extensions": ["vcx"] + }, + "application/vnd.vd-study": { + "source": "iana" + }, + "application/vnd.vectorworks": { + "source": "iana" + }, + "application/vnd.vel+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.veraison.tsm-report+cbor": { + "source": "iana" + }, + "application/vnd.veraison.tsm-report+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.verimatrix.vcas": { + "source": "iana" + }, + "application/vnd.veritone.aion+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.veryant.thin": { + "source": "iana" + }, + "application/vnd.ves.encrypted": { + "source": "iana" + }, + "application/vnd.vidsoft.vidconference": { + "source": "iana" + }, + "application/vnd.visio": { + "source": "iana", + "extensions": ["vsd","vst","vss","vsw","vsdx","vtx"] + }, + "application/vnd.visionary": { + "source": "iana", + "extensions": ["vis"] + }, + "application/vnd.vividence.scriptfile": { + "source": "iana" + }, + "application/vnd.vocalshaper.vsp4": { + "source": "iana" + }, + "application/vnd.vsf": { + "source": "iana", + "extensions": ["vsf"] + }, + "application/vnd.wap.sic": { + "source": "iana" + }, + "application/vnd.wap.slc": { + "source": "iana" + }, + "application/vnd.wap.wbxml": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["wbxml"] + }, + "application/vnd.wap.wmlc": { + "source": "iana", + "extensions": ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + "source": "iana", + "extensions": ["wmlsc"] + }, + "application/vnd.wasmflow.wafl": { + "source": "iana" + }, + "application/vnd.webturbo": { + "source": "iana", + "extensions": ["wtb"] + }, + "application/vnd.wfa.dpp": { + "source": "iana" + }, + "application/vnd.wfa.p2p": { + "source": "iana" + }, + "application/vnd.wfa.wsc": { + "source": "iana" + }, + "application/vnd.windows.devicepairing": { + "source": "iana" + }, + "application/vnd.wmc": { + "source": "iana" + }, + "application/vnd.wmf.bootstrap": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica.package": { + "source": "iana" + }, + "application/vnd.wolfram.player": { + "source": "iana", + "extensions": ["nbp"] + }, + "application/vnd.wordlift": { + "source": "iana" + }, + "application/vnd.wordperfect": { + "source": "iana", + "extensions": ["wpd"] + }, + "application/vnd.wqd": { + "source": "iana", + "extensions": ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + "source": "iana" + }, + "application/vnd.wt.stf": { + "source": "iana", + "extensions": ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + "source": "iana" + }, + "application/vnd.wv.csp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.wv.ssp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xacml+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.xara": { + "source": "iana", + "extensions": ["xar"] + }, + "application/vnd.xarin.cpj": { + "source": "iana" + }, + "application/vnd.xecrets-encrypted": { + "source": "iana" + }, + "application/vnd.xfdl": { + "source": "iana", + "extensions": ["xfdl"] + }, + "application/vnd.xfdl.webform": { + "source": "iana" + }, + "application/vnd.xmi+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xmpie.cpkg": { + "source": "iana" + }, + "application/vnd.xmpie.dpkg": { + "source": "iana" + }, + "application/vnd.xmpie.plan": { + "source": "iana" + }, + "application/vnd.xmpie.ppkg": { + "source": "iana" + }, + "application/vnd.xmpie.xlim": { + "source": "iana" + }, + "application/vnd.yamaha.hv-dic": { + "source": "iana", + "extensions": ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + "source": "iana", + "extensions": ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + "source": "iana", + "extensions": ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + "source": "iana", + "extensions": ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + "source": "iana" + }, + "application/vnd.yamaha.smaf-audio": { + "source": "iana", + "extensions": ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + "source": "iana", + "extensions": ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + "source": "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + "source": "iana" + }, + "application/vnd.yaoweme": { + "source": "iana" + }, + "application/vnd.yellowriver-custom-menu": { + "source": "iana", + "extensions": ["cmp"] + }, + "application/vnd.zul": { + "source": "iana", + "extensions": ["zir","zirz"] + }, + "application/vnd.zzazz.deck+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zaz"] + }, + "application/voicexml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["vxml"] + }, + "application/voucher-cms+json": { + "source": "iana", + "compressible": true + }, + "application/voucher-jws+json": { + "source": "iana", + "compressible": true + }, + "application/vp": { + "source": "iana" + }, + "application/vp+cose": { + "source": "iana" + }, + "application/vp+jwt": { + "source": "iana" + }, + "application/vq-rtcpxr": { + "source": "iana" + }, + "application/wasm": { + "source": "iana", + "compressible": true, + "extensions": ["wasm"] + }, + "application/watcherinfo+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wif"] + }, + "application/webpush-options+json": { + "source": "iana", + "compressible": true + }, + "application/whoispp-query": { + "source": "iana" + }, + "application/whoispp-response": { + "source": "iana" + }, + "application/widget": { + "source": "iana", + "extensions": ["wgt"] + }, + "application/winhlp": { + "source": "apache", + "extensions": ["hlp"] + }, + "application/wita": { + "source": "iana" + }, + "application/wordperfect5.1": { + "source": "iana" + }, + "application/wsdl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wsdl"] + }, + "application/wspolicy+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wspolicy"] + }, + "application/x-7z-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["7z"] + }, + "application/x-abiword": { + "source": "apache", + "extensions": ["abw"] + }, + "application/x-ace-compressed": { + "source": "apache", + "extensions": ["ace"] + }, + "application/x-amf": { + "source": "apache" + }, + "application/x-apple-diskimage": { + "source": "apache", + "extensions": ["dmg"] + }, + "application/x-arj": { + "compressible": false, + "extensions": ["arj"] + }, + "application/x-authorware-bin": { + "source": "apache", + "extensions": ["aab","x32","u32","vox"] + }, + "application/x-authorware-map": { + "source": "apache", + "extensions": ["aam"] + }, + "application/x-authorware-seg": { + "source": "apache", + "extensions": ["aas"] + }, + "application/x-bcpio": { + "source": "apache", + "extensions": ["bcpio"] + }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/x-bittorrent": { + "source": "apache", + "extensions": ["torrent"] + }, + "application/x-blender": { + "extensions": ["blend"] + }, + "application/x-blorb": { + "source": "apache", + "extensions": ["blb","blorb"] + }, + "application/x-bzip": { + "source": "apache", + "compressible": false, + "extensions": ["bz"] + }, + "application/x-bzip2": { + "source": "apache", + "compressible": false, + "extensions": ["bz2","boz"] + }, + "application/x-cbr": { + "source": "apache", + "extensions": ["cbr","cba","cbt","cbz","cb7"] + }, + "application/x-cdlink": { + "source": "apache", + "extensions": ["vcd"] + }, + "application/x-cfs-compressed": { + "source": "apache", + "extensions": ["cfs"] + }, + "application/x-chat": { + "source": "apache", + "extensions": ["chat"] + }, + "application/x-chess-pgn": { + "source": "apache", + "extensions": ["pgn"] + }, + "application/x-chrome-extension": { + "extensions": ["crx"] + }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, + "application/x-compress": { + "source": "apache" + }, + "application/x-compressed": { + "extensions": ["rar"] + }, + "application/x-conference": { + "source": "apache", + "extensions": ["nsc"] + }, + "application/x-cpio": { + "source": "apache", + "extensions": ["cpio"] + }, + "application/x-csh": { + "source": "apache", + "extensions": ["csh"] + }, + "application/x-deb": { + "compressible": false + }, + "application/x-debian-package": { + "source": "apache", + "extensions": ["deb","udeb"] + }, + "application/x-dgc-compressed": { + "source": "apache", + "extensions": ["dgc"] + }, + "application/x-director": { + "source": "apache", + "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] + }, + "application/x-doom": { + "source": "apache", + "extensions": ["wad"] + }, + "application/x-dtbncx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ncx"] + }, + "application/x-dtbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dtb"] + }, + "application/x-dtbresource+xml": { + "source": "apache", + "compressible": true, + "extensions": ["res"] + }, + "application/x-dvi": { + "source": "apache", + "compressible": false, + "extensions": ["dvi"] + }, + "application/x-envoy": { + "source": "apache", + "extensions": ["evy"] + }, + "application/x-eva": { + "source": "apache", + "extensions": ["eva"] + }, + "application/x-font-bdf": { + "source": "apache", + "extensions": ["bdf"] + }, + "application/x-font-dos": { + "source": "apache" + }, + "application/x-font-framemaker": { + "source": "apache" + }, + "application/x-font-ghostscript": { + "source": "apache", + "extensions": ["gsf"] + }, + "application/x-font-libgrx": { + "source": "apache" + }, + "application/x-font-linux-psf": { + "source": "apache", + "extensions": ["psf"] + }, + "application/x-font-pcf": { + "source": "apache", + "extensions": ["pcf"] + }, + "application/x-font-snf": { + "source": "apache", + "extensions": ["snf"] + }, + "application/x-font-speedo": { + "source": "apache" + }, + "application/x-font-sunos-news": { + "source": "apache" + }, + "application/x-font-type1": { + "source": "apache", + "extensions": ["pfa","pfb","pfm","afm"] + }, + "application/x-font-vfont": { + "source": "apache" + }, + "application/x-freearc": { + "source": "apache", + "extensions": ["arc"] + }, + "application/x-futuresplash": { + "source": "apache", + "extensions": ["spl"] + }, + "application/x-gca-compressed": { + "source": "apache", + "extensions": ["gca"] + }, + "application/x-glulx": { + "source": "apache", + "extensions": ["ulx"] + }, + "application/x-gnumeric": { + "source": "apache", + "extensions": ["gnumeric"] + }, + "application/x-gramps-xml": { + "source": "apache", + "extensions": ["gramps"] + }, + "application/x-gtar": { + "source": "apache", + "extensions": ["gtar"] + }, + "application/x-gzip": { + "source": "apache" + }, + "application/x-hdf": { + "source": "apache", + "extensions": ["hdf"] + }, + "application/x-httpd-php": { + "compressible": true, + "extensions": ["php"] + }, + "application/x-install-instructions": { + "source": "apache", + "extensions": ["install"] + }, + "application/x-ipynb+json": { + "compressible": true, + "extensions": ["ipynb"] + }, + "application/x-iso9660-image": { + "source": "apache", + "extensions": ["iso"] + }, + "application/x-iwork-keynote-sffkey": { + "extensions": ["key"] + }, + "application/x-iwork-numbers-sffnumbers": { + "extensions": ["numbers"] + }, + "application/x-iwork-pages-sffpages": { + "extensions": ["pages"] + }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, + "application/x-java-jnlp-file": { + "source": "apache", + "compressible": false, + "extensions": ["jnlp"] + }, + "application/x-javascript": { + "compressible": true + }, + "application/x-keepass2": { + "extensions": ["kdbx"] + }, + "application/x-latex": { + "source": "apache", + "compressible": false, + "extensions": ["latex"] + }, + "application/x-lua-bytecode": { + "extensions": ["luac"] + }, + "application/x-lzh-compressed": { + "source": "apache", + "extensions": ["lzh","lha"] + }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, + "application/x-mie": { + "source": "apache", + "extensions": ["mie"] + }, + "application/x-mobipocket-ebook": { + "source": "apache", + "extensions": ["prc","mobi"] + }, + "application/x-mpegurl": { + "compressible": false + }, + "application/x-ms-application": { + "source": "apache", + "extensions": ["application"] + }, + "application/x-ms-shortcut": { + "source": "apache", + "extensions": ["lnk"] + }, + "application/x-ms-wmd": { + "source": "apache", + "extensions": ["wmd"] + }, + "application/x-ms-wmz": { + "source": "apache", + "extensions": ["wmz"] + }, + "application/x-ms-xbap": { + "source": "apache", + "extensions": ["xbap"] + }, + "application/x-msaccess": { + "source": "apache", + "extensions": ["mdb"] + }, + "application/x-msbinder": { + "source": "apache", + "extensions": ["obd"] + }, + "application/x-mscardfile": { + "source": "apache", + "extensions": ["crd"] + }, + "application/x-msclip": { + "source": "apache", + "extensions": ["clp"] + }, + "application/x-msdos-program": { + "extensions": ["exe"] + }, + "application/x-msdownload": { + "source": "apache", + "extensions": ["exe","dll","com","bat","msi"] + }, + "application/x-msmediaview": { + "source": "apache", + "extensions": ["mvb","m13","m14"] + }, + "application/x-msmetafile": { + "source": "apache", + "extensions": ["wmf","wmz","emf","emz"] + }, + "application/x-msmoney": { + "source": "apache", + "extensions": ["mny"] + }, + "application/x-mspublisher": { + "source": "apache", + "extensions": ["pub"] + }, + "application/x-msschedule": { + "source": "apache", + "extensions": ["scd"] + }, + "application/x-msterminal": { + "source": "apache", + "extensions": ["trm"] + }, + "application/x-mswrite": { + "source": "apache", + "extensions": ["wri"] + }, + "application/x-netcdf": { + "source": "apache", + "extensions": ["nc","cdf"] + }, + "application/x-ns-proxy-autoconfig": { + "compressible": true, + "extensions": ["pac"] + }, + "application/x-nzb": { + "source": "apache", + "extensions": ["nzb"] + }, + "application/x-perl": { + "source": "nginx", + "extensions": ["pl","pm"] + }, + "application/x-pilot": { + "source": "nginx", + "extensions": ["prc","pdb"] + }, + "application/x-pkcs12": { + "source": "apache", + "compressible": false, + "extensions": ["p12","pfx"] + }, + "application/x-pkcs7-certificates": { + "source": "apache", + "extensions": ["p7b","spc"] + }, + "application/x-pkcs7-certreqresp": { + "source": "apache", + "extensions": ["p7r"] + }, + "application/x-pki-message": { + "source": "iana" + }, + "application/x-rar-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["rar"] + }, + "application/x-redhat-package-manager": { + "source": "nginx", + "extensions": ["rpm"] + }, + "application/x-research-info-systems": { + "source": "apache", + "extensions": ["ris"] + }, + "application/x-sea": { + "source": "nginx", + "extensions": ["sea"] + }, + "application/x-sh": { + "source": "apache", + "compressible": true, + "extensions": ["sh"] + }, + "application/x-shar": { + "source": "apache", + "extensions": ["shar"] + }, + "application/x-shockwave-flash": { + "source": "apache", + "compressible": false, + "extensions": ["swf"] + }, + "application/x-silverlight-app": { + "source": "apache", + "extensions": ["xap"] + }, + "application/x-sql": { + "source": "apache", + "extensions": ["sql"] + }, + "application/x-stuffit": { + "source": "apache", + "compressible": false, + "extensions": ["sit"] + }, + "application/x-stuffitx": { + "source": "apache", + "extensions": ["sitx"] + }, + "application/x-subrip": { + "source": "apache", + "extensions": ["srt"] + }, + "application/x-sv4cpio": { + "source": "apache", + "extensions": ["sv4cpio"] + }, + "application/x-sv4crc": { + "source": "apache", + "extensions": ["sv4crc"] + }, + "application/x-t3vm-image": { + "source": "apache", + "extensions": ["t3"] + }, + "application/x-tads": { + "source": "apache", + "extensions": ["gam"] + }, + "application/x-tar": { + "source": "apache", + "compressible": true, + "extensions": ["tar"] + }, + "application/x-tcl": { + "source": "apache", + "extensions": ["tcl","tk"] + }, + "application/x-tex": { + "source": "apache", + "extensions": ["tex"] + }, + "application/x-tex-tfm": { + "source": "apache", + "extensions": ["tfm"] + }, + "application/x-texinfo": { + "source": "apache", + "extensions": ["texinfo","texi"] + }, + "application/x-tgif": { + "source": "apache", + "extensions": ["obj"] + }, + "application/x-ustar": { + "source": "apache", + "extensions": ["ustar"] + }, + "application/x-virtualbox-hdd": { + "compressible": true, + "extensions": ["hdd"] + }, + "application/x-virtualbox-ova": { + "compressible": true, + "extensions": ["ova"] + }, + "application/x-virtualbox-ovf": { + "compressible": true, + "extensions": ["ovf"] + }, + "application/x-virtualbox-vbox": { + "compressible": true, + "extensions": ["vbox"] + }, + "application/x-virtualbox-vbox-extpack": { + "compressible": false, + "extensions": ["vbox-extpack"] + }, + "application/x-virtualbox-vdi": { + "compressible": true, + "extensions": ["vdi"] + }, + "application/x-virtualbox-vhd": { + "compressible": true, + "extensions": ["vhd"] + }, + "application/x-virtualbox-vmdk": { + "compressible": true, + "extensions": ["vmdk"] + }, + "application/x-wais-source": { + "source": "apache", + "extensions": ["src"] + }, + "application/x-web-app-manifest+json": { + "compressible": true, + "extensions": ["webapp"] + }, + "application/x-www-form-urlencoded": { + "source": "iana", + "compressible": true + }, + "application/x-x509-ca-cert": { + "source": "iana", + "extensions": ["der","crt","pem"] + }, + "application/x-x509-ca-ra-cert": { + "source": "iana" + }, + "application/x-x509-next-ca-cert": { + "source": "iana" + }, + "application/x-xfig": { + "source": "apache", + "extensions": ["fig"] + }, + "application/x-xliff+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xlf"] + }, + "application/x-xpinstall": { + "source": "apache", + "compressible": false, + "extensions": ["xpi"] + }, + "application/x-xz": { + "source": "apache", + "extensions": ["xz"] + }, + "application/x-zip-compressed": { + "extensions": ["zip"] + }, + "application/x-zmachine": { + "source": "apache", + "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] + }, + "application/x400-bp": { + "source": "iana" + }, + "application/xacml+xml": { + "source": "iana", + "compressible": true + }, + "application/xaml+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xaml"] + }, + "application/xcap-att+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xav"] + }, + "application/xcap-caps+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xca"] + }, + "application/xcap-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdf"] + }, + "application/xcap-el+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xel"] + }, + "application/xcap-error+xml": { + "source": "iana", + "compressible": true + }, + "application/xcap-ns+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xns"] + }, + "application/xcon-conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/xcon-conference-info-diff+xml": { + "source": "iana", + "compressible": true + }, + "application/xenc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xenc"] + }, + "application/xfdf": { + "source": "iana", + "extensions": ["xfdf"] + }, + "application/xhtml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtml","xht"] + }, + "application/xhtml-voice+xml": { + "source": "apache", + "compressible": true + }, + "application/xliff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xlf"] + }, + "application/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml","xsl","xsd","rng"] + }, + "application/xml-dtd": { + "source": "iana", + "compressible": true, + "extensions": ["dtd"] + }, + "application/xml-external-parsed-entity": { + "source": "iana" + }, + "application/xml-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/xmpp+xml": { + "source": "iana", + "compressible": true + }, + "application/xop+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xop"] + }, + "application/xproc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xpl"] + }, + "application/xslt+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xsl","xslt"] + }, + "application/xspf+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xspf"] + }, + "application/xv+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mxml","xhvml","xvml","xvm"] + }, + "application/yaml": { + "source": "iana" + }, + "application/yang": { + "source": "iana", + "extensions": ["yang"] + }, + "application/yang-data+cbor": { + "source": "iana" + }, + "application/yang-data+json": { + "source": "iana", + "compressible": true + }, + "application/yang-data+xml": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+json": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/yang-sid+json": { + "source": "iana", + "compressible": true + }, + "application/yin+xml": { + "source": "iana", + "compressible": true, + "extensions": ["yin"] + }, + "application/zip": { + "source": "iana", + "compressible": false, + "extensions": ["zip"] + }, + "application/zip+dotlottie": { + "extensions": ["lottie"] + }, + "application/zlib": { + "source": "iana" + }, + "application/zstd": { + "source": "iana" + }, + "audio/1d-interleaved-parityfec": { + "source": "iana" + }, + "audio/32kadpcm": { + "source": "iana" + }, + "audio/3gpp": { + "source": "iana", + "compressible": false, + "extensions": ["3gpp"] + }, + "audio/3gpp2": { + "source": "iana" + }, + "audio/aac": { + "source": "iana", + "extensions": ["adts","aac"] + }, + "audio/ac3": { + "source": "iana" + }, + "audio/adpcm": { + "source": "apache", + "extensions": ["adp"] + }, + "audio/amr": { + "source": "iana", + "extensions": ["amr"] + }, + "audio/amr-wb": { + "source": "iana" + }, + "audio/amr-wb+": { + "source": "iana" + }, + "audio/aptx": { + "source": "iana" + }, + "audio/asc": { + "source": "iana" + }, + "audio/atrac-advanced-lossless": { + "source": "iana" + }, + "audio/atrac-x": { + "source": "iana" + }, + "audio/atrac3": { + "source": "iana" + }, + "audio/basic": { + "source": "iana", + "compressible": false, + "extensions": ["au","snd"] + }, + "audio/bv16": { + "source": "iana" + }, + "audio/bv32": { + "source": "iana" + }, + "audio/clearmode": { + "source": "iana" + }, + "audio/cn": { + "source": "iana" + }, + "audio/dat12": { + "source": "iana" + }, + "audio/dls": { + "source": "iana" + }, + "audio/dsr-es201108": { + "source": "iana" + }, + "audio/dsr-es202050": { + "source": "iana" + }, + "audio/dsr-es202211": { + "source": "iana" + }, + "audio/dsr-es202212": { + "source": "iana" + }, + "audio/dv": { + "source": "iana" + }, + "audio/dvi4": { + "source": "iana" + }, + "audio/eac3": { + "source": "iana" + }, + "audio/encaprtp": { + "source": "iana" + }, + "audio/evrc": { + "source": "iana" + }, + "audio/evrc-qcp": { + "source": "iana" + }, + "audio/evrc0": { + "source": "iana" + }, + "audio/evrc1": { + "source": "iana" + }, + "audio/evrcb": { + "source": "iana" + }, + "audio/evrcb0": { + "source": "iana" + }, + "audio/evrcb1": { + "source": "iana" + }, + "audio/evrcnw": { + "source": "iana" + }, + "audio/evrcnw0": { + "source": "iana" + }, + "audio/evrcnw1": { + "source": "iana" + }, + "audio/evrcwb": { + "source": "iana" + }, + "audio/evrcwb0": { + "source": "iana" + }, + "audio/evrcwb1": { + "source": "iana" + }, + "audio/evs": { + "source": "iana" + }, + "audio/flac": { + "source": "iana" + }, + "audio/flexfec": { + "source": "iana" + }, + "audio/fwdred": { + "source": "iana" + }, + "audio/g711-0": { + "source": "iana" + }, + "audio/g719": { + "source": "iana" + }, + "audio/g722": { + "source": "iana" + }, + "audio/g7221": { + "source": "iana" + }, + "audio/g723": { + "source": "iana" + }, + "audio/g726-16": { + "source": "iana" + }, + "audio/g726-24": { + "source": "iana" + }, + "audio/g726-32": { + "source": "iana" + }, + "audio/g726-40": { + "source": "iana" + }, + "audio/g728": { + "source": "iana" + }, + "audio/g729": { + "source": "iana" + }, + "audio/g7291": { + "source": "iana" + }, + "audio/g729d": { + "source": "iana" + }, + "audio/g729e": { + "source": "iana" + }, + "audio/gsm": { + "source": "iana" + }, + "audio/gsm-efr": { + "source": "iana" + }, + "audio/gsm-hr-08": { + "source": "iana" + }, + "audio/ilbc": { + "source": "iana" + }, + "audio/ip-mr_v2.5": { + "source": "iana" + }, + "audio/isac": { + "source": "apache" + }, + "audio/l16": { + "source": "iana" + }, + "audio/l20": { + "source": "iana" + }, + "audio/l24": { + "source": "iana", + "compressible": false + }, + "audio/l8": { + "source": "iana" + }, + "audio/lpc": { + "source": "iana" + }, + "audio/matroska": { + "source": "iana" + }, + "audio/melp": { + "source": "iana" + }, + "audio/melp1200": { + "source": "iana" + }, + "audio/melp2400": { + "source": "iana" + }, + "audio/melp600": { + "source": "iana" + }, + "audio/mhas": { + "source": "iana" + }, + "audio/midi": { + "source": "apache", + "extensions": ["mid","midi","kar","rmi"] + }, + "audio/midi-clip": { + "source": "iana" + }, + "audio/mobile-xmf": { + "source": "iana", + "extensions": ["mxmf"] + }, + "audio/mp3": { + "compressible": false, + "extensions": ["mp3"] + }, + "audio/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["m4a","mp4a","m4b"] + }, + "audio/mp4a-latm": { + "source": "iana" + }, + "audio/mpa": { + "source": "iana" + }, + "audio/mpa-robust": { + "source": "iana" + }, + "audio/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] + }, + "audio/mpeg4-generic": { + "source": "iana" + }, + "audio/musepack": { + "source": "apache" + }, + "audio/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["oga","ogg","spx","opus"] + }, + "audio/opus": { + "source": "iana" + }, + "audio/parityfec": { + "source": "iana" + }, + "audio/pcma": { + "source": "iana" + }, + "audio/pcma-wb": { + "source": "iana" + }, + "audio/pcmu": { + "source": "iana" + }, + "audio/pcmu-wb": { + "source": "iana" + }, + "audio/prs.sid": { + "source": "iana" + }, + "audio/qcelp": { + "source": "iana" + }, + "audio/raptorfec": { + "source": "iana" + }, + "audio/red": { + "source": "iana" + }, + "audio/rtp-enc-aescm128": { + "source": "iana" + }, + "audio/rtp-midi": { + "source": "iana" + }, + "audio/rtploopback": { + "source": "iana" + }, + "audio/rtx": { + "source": "iana" + }, + "audio/s3m": { + "source": "apache", + "extensions": ["s3m"] + }, + "audio/scip": { + "source": "iana" + }, + "audio/silk": { + "source": "apache", + "extensions": ["sil"] + }, + "audio/smv": { + "source": "iana" + }, + "audio/smv-qcp": { + "source": "iana" + }, + "audio/smv0": { + "source": "iana" + }, + "audio/sofa": { + "source": "iana" + }, + "audio/sp-midi": { + "source": "iana" + }, + "audio/speex": { + "source": "iana" + }, + "audio/t140c": { + "source": "iana" + }, + "audio/t38": { + "source": "iana" + }, + "audio/telephone-event": { + "source": "iana" + }, + "audio/tetra_acelp": { + "source": "iana" + }, + "audio/tetra_acelp_bb": { + "source": "iana" + }, + "audio/tone": { + "source": "iana" + }, + "audio/tsvcis": { + "source": "iana" + }, + "audio/uemclip": { + "source": "iana" + }, + "audio/ulpfec": { + "source": "iana" + }, + "audio/usac": { + "source": "iana" + }, + "audio/vdvi": { + "source": "iana" + }, + "audio/vmr-wb": { + "source": "iana" + }, + "audio/vnd.3gpp.iufp": { + "source": "iana" + }, + "audio/vnd.4sb": { + "source": "iana" + }, + "audio/vnd.audiokoz": { + "source": "iana" + }, + "audio/vnd.celp": { + "source": "iana" + }, + "audio/vnd.cisco.nse": { + "source": "iana" + }, + "audio/vnd.cmles.radio-events": { + "source": "iana" + }, + "audio/vnd.cns.anp1": { + "source": "iana" + }, + "audio/vnd.cns.inf1": { + "source": "iana" + }, + "audio/vnd.dece.audio": { + "source": "iana", + "extensions": ["uva","uvva"] + }, + "audio/vnd.digital-winds": { + "source": "iana", + "extensions": ["eol"] + }, + "audio/vnd.dlna.adts": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.1": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.2": { + "source": "iana" + }, + "audio/vnd.dolby.mlp": { + "source": "iana" + }, + "audio/vnd.dolby.mps": { + "source": "iana" + }, + "audio/vnd.dolby.pl2": { + "source": "iana" + }, + "audio/vnd.dolby.pl2x": { + "source": "iana" + }, + "audio/vnd.dolby.pl2z": { + "source": "iana" + }, + "audio/vnd.dolby.pulse.1": { + "source": "iana" + }, + "audio/vnd.dra": { + "source": "iana", + "extensions": ["dra"] + }, + "audio/vnd.dts": { + "source": "iana", + "extensions": ["dts"] + }, + "audio/vnd.dts.hd": { + "source": "iana", + "extensions": ["dtshd"] + }, + "audio/vnd.dts.uhd": { + "source": "iana" + }, + "audio/vnd.dvb.file": { + "source": "iana" + }, + "audio/vnd.everad.plj": { + "source": "iana" + }, + "audio/vnd.hns.audio": { + "source": "iana" + }, + "audio/vnd.lucent.voice": { + "source": "iana", + "extensions": ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + "source": "iana", + "extensions": ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + "source": "iana" + }, + "audio/vnd.nortel.vbk": { + "source": "iana" + }, + "audio/vnd.nuera.ecelp4800": { + "source": "iana", + "extensions": ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + "source": "iana", + "extensions": ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + "source": "iana", + "extensions": ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + "source": "iana" + }, + "audio/vnd.presonus.multitrack": { + "source": "iana" + }, + "audio/vnd.qcelp": { + "source": "apache" + }, + "audio/vnd.rhetorex.32kadpcm": { + "source": "iana" + }, + "audio/vnd.rip": { + "source": "iana", + "extensions": ["rip"] + }, + "audio/vnd.rn-realaudio": { + "compressible": false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + "source": "iana" + }, + "audio/vnd.vmx.cvsd": { + "source": "iana" + }, + "audio/vnd.wave": { + "compressible": false + }, + "audio/vorbis": { + "source": "iana", + "compressible": false + }, + "audio/vorbis-config": { + "source": "iana" + }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/webm": { + "source": "apache", + "compressible": false, + "extensions": ["weba"] + }, + "audio/x-aac": { + "source": "apache", + "compressible": false, + "extensions": ["aac"] + }, + "audio/x-aiff": { + "source": "apache", + "extensions": ["aif","aiff","aifc"] + }, + "audio/x-caf": { + "source": "apache", + "compressible": false, + "extensions": ["caf"] + }, + "audio/x-flac": { + "source": "apache", + "extensions": ["flac"] + }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, + "audio/x-matroska": { + "source": "apache", + "extensions": ["mka"] + }, + "audio/x-mpegurl": { + "source": "apache", + "extensions": ["m3u"] + }, + "audio/x-ms-wax": { + "source": "apache", + "extensions": ["wax"] + }, + "audio/x-ms-wma": { + "source": "apache", + "extensions": ["wma"] + }, + "audio/x-pn-realaudio": { + "source": "apache", + "extensions": ["ram","ra"] + }, + "audio/x-pn-realaudio-plugin": { + "source": "apache", + "extensions": ["rmp"] + }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, + "audio/x-tta": { + "source": "apache" + }, + "audio/x-wav": { + "source": "apache", + "extensions": ["wav"] + }, + "audio/xm": { + "source": "apache", + "extensions": ["xm"] + }, + "chemical/x-cdx": { + "source": "apache", + "extensions": ["cdx"] + }, + "chemical/x-cif": { + "source": "apache", + "extensions": ["cif"] + }, + "chemical/x-cmdf": { + "source": "apache", + "extensions": ["cmdf"] + }, + "chemical/x-cml": { + "source": "apache", + "extensions": ["cml"] + }, + "chemical/x-csml": { + "source": "apache", + "extensions": ["csml"] + }, + "chemical/x-pdb": { + "source": "apache" + }, + "chemical/x-xyz": { + "source": "apache", + "extensions": ["xyz"] + }, + "font/collection": { + "source": "iana", + "extensions": ["ttc"] + }, + "font/otf": { + "source": "iana", + "compressible": true, + "extensions": ["otf"] + }, + "font/sfnt": { + "source": "iana" + }, + "font/ttf": { + "source": "iana", + "compressible": true, + "extensions": ["ttf"] + }, + "font/woff": { + "source": "iana", + "extensions": ["woff"] + }, + "font/woff2": { + "source": "iana", + "extensions": ["woff2"] + }, + "image/aces": { + "source": "iana", + "extensions": ["exr"] + }, + "image/apng": { + "source": "iana", + "compressible": false, + "extensions": ["apng"] + }, + "image/avci": { + "source": "iana", + "extensions": ["avci"] + }, + "image/avcs": { + "source": "iana", + "extensions": ["avcs"] + }, + "image/avif": { + "source": "iana", + "compressible": false, + "extensions": ["avif"] + }, + "image/bmp": { + "source": "iana", + "compressible": true, + "extensions": ["bmp","dib"] + }, + "image/cgm": { + "source": "iana", + "extensions": ["cgm"] + }, + "image/dicom-rle": { + "source": "iana", + "extensions": ["drle"] + }, + "image/dpx": { + "source": "iana", + "extensions": ["dpx"] + }, + "image/emf": { + "source": "iana", + "extensions": ["emf"] + }, + "image/fits": { + "source": "iana", + "extensions": ["fits"] + }, + "image/g3fax": { + "source": "iana", + "extensions": ["g3"] + }, + "image/gif": { + "source": "iana", + "compressible": false, + "extensions": ["gif"] + }, + "image/heic": { + "source": "iana", + "extensions": ["heic"] + }, + "image/heic-sequence": { + "source": "iana", + "extensions": ["heics"] + }, + "image/heif": { + "source": "iana", + "extensions": ["heif"] + }, + "image/heif-sequence": { + "source": "iana", + "extensions": ["heifs"] + }, + "image/hej2k": { + "source": "iana", + "extensions": ["hej2"] + }, + "image/ief": { + "source": "iana", + "extensions": ["ief"] + }, + "image/j2c": { + "source": "iana" + }, + "image/jaii": { + "source": "iana", + "extensions": ["jaii"] + }, + "image/jais": { + "source": "iana", + "extensions": ["jais"] + }, + "image/jls": { + "source": "iana", + "extensions": ["jls"] + }, + "image/jp2": { + "source": "iana", + "compressible": false, + "extensions": ["jp2","jpg2"] + }, + "image/jpeg": { + "source": "iana", + "compressible": false, + "extensions": ["jpg","jpeg","jpe"] + }, + "image/jph": { + "source": "iana", + "extensions": ["jph"] + }, + "image/jphc": { + "source": "iana", + "extensions": ["jhc"] + }, + "image/jpm": { + "source": "iana", + "compressible": false, + "extensions": ["jpm","jpgm"] + }, + "image/jpx": { + "source": "iana", + "compressible": false, + "extensions": ["jpx","jpf"] + }, + "image/jxl": { + "source": "iana", + "extensions": ["jxl"] + }, + "image/jxr": { + "source": "iana", + "extensions": ["jxr"] + }, + "image/jxra": { + "source": "iana", + "extensions": ["jxra"] + }, + "image/jxrs": { + "source": "iana", + "extensions": ["jxrs"] + }, + "image/jxs": { + "source": "iana", + "extensions": ["jxs"] + }, + "image/jxsc": { + "source": "iana", + "extensions": ["jxsc"] + }, + "image/jxsi": { + "source": "iana", + "extensions": ["jxsi"] + }, + "image/jxss": { + "source": "iana", + "extensions": ["jxss"] + }, + "image/ktx": { + "source": "iana", + "extensions": ["ktx"] + }, + "image/ktx2": { + "source": "iana", + "extensions": ["ktx2"] + }, + "image/naplps": { + "source": "iana" + }, + "image/pjpeg": { + "compressible": false, + "extensions": ["jfif"] + }, + "image/png": { + "source": "iana", + "compressible": false, + "extensions": ["png"] + }, + "image/prs.btif": { + "source": "iana", + "extensions": ["btif","btf"] + }, + "image/prs.pti": { + "source": "iana", + "extensions": ["pti"] + }, + "image/pwg-raster": { + "source": "iana" + }, + "image/sgi": { + "source": "apache", + "extensions": ["sgi"] + }, + "image/svg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["svg","svgz"] + }, + "image/t38": { + "source": "iana", + "extensions": ["t38"] + }, + "image/tiff": { + "source": "iana", + "compressible": false, + "extensions": ["tif","tiff"] + }, + "image/tiff-fx": { + "source": "iana", + "extensions": ["tfx"] + }, + "image/vnd.adobe.photoshop": { + "source": "iana", + "compressible": true, + "extensions": ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + "source": "iana", + "extensions": ["azv"] + }, + "image/vnd.clip": { + "source": "iana" + }, + "image/vnd.cns.inf2": { + "source": "iana" + }, + "image/vnd.dece.graphic": { + "source": "iana", + "extensions": ["uvi","uvvi","uvg","uvvg"] + }, + "image/vnd.djvu": { + "source": "iana", + "extensions": ["djvu","djv"] + }, + "image/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "image/vnd.dwg": { + "source": "iana", + "extensions": ["dwg"] + }, + "image/vnd.dxf": { + "source": "iana", + "extensions": ["dxf"] + }, + "image/vnd.fastbidsheet": { + "source": "iana", + "extensions": ["fbs"] + }, + "image/vnd.fpx": { + "source": "iana", + "extensions": ["fpx"] + }, + "image/vnd.fst": { + "source": "iana", + "extensions": ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + "source": "iana", + "extensions": ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + "source": "iana", + "extensions": ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + "source": "iana" + }, + "image/vnd.microsoft.icon": { + "source": "iana", + "compressible": true, + "extensions": ["ico"] + }, + "image/vnd.mix": { + "source": "iana" + }, + "image/vnd.mozilla.apng": { + "source": "iana" + }, + "image/vnd.ms-dds": { + "compressible": true, + "extensions": ["dds"] + }, + "image/vnd.ms-modi": { + "source": "iana", + "extensions": ["mdi"] + }, + "image/vnd.ms-photo": { + "source": "apache", + "extensions": ["wdp"] + }, + "image/vnd.net-fpx": { + "source": "iana", + "extensions": ["npx"] + }, + "image/vnd.pco.b16": { + "source": "iana", + "extensions": ["b16"] + }, + "image/vnd.radiance": { + "source": "iana" + }, + "image/vnd.sealed.png": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + "source": "iana" + }, + "image/vnd.svf": { + "source": "iana" + }, + "image/vnd.tencent.tap": { + "source": "iana", + "extensions": ["tap"] + }, + "image/vnd.valve.source.texture": { + "source": "iana", + "extensions": ["vtf"] + }, + "image/vnd.wap.wbmp": { + "source": "iana", + "extensions": ["wbmp"] + }, + "image/vnd.xiff": { + "source": "iana", + "extensions": ["xif"] + }, + "image/vnd.zbrush.pcx": { + "source": "iana", + "extensions": ["pcx"] + }, + "image/webp": { + "source": "iana", + "extensions": ["webp"] + }, + "image/wmf": { + "source": "iana", + "extensions": ["wmf"] + }, + "image/x-3ds": { + "source": "apache", + "extensions": ["3ds"] + }, + "image/x-adobe-dng": { + "extensions": ["dng"] + }, + "image/x-cmu-raster": { + "source": "apache", + "extensions": ["ras"] + }, + "image/x-cmx": { + "source": "apache", + "extensions": ["cmx"] + }, + "image/x-emf": { + "source": "iana" + }, + "image/x-freehand": { + "source": "apache", + "extensions": ["fh","fhc","fh4","fh5","fh7"] + }, + "image/x-icon": { + "source": "apache", + "compressible": true, + "extensions": ["ico"] + }, + "image/x-jng": { + "source": "nginx", + "extensions": ["jng"] + }, + "image/x-mrsid-image": { + "source": "apache", + "extensions": ["sid"] + }, + "image/x-ms-bmp": { + "source": "nginx", + "compressible": true, + "extensions": ["bmp"] + }, + "image/x-pcx": { + "source": "apache", + "extensions": ["pcx"] + }, + "image/x-pict": { + "source": "apache", + "extensions": ["pic","pct"] + }, + "image/x-portable-anymap": { + "source": "apache", + "extensions": ["pnm"] + }, + "image/x-portable-bitmap": { + "source": "apache", + "extensions": ["pbm"] + }, + "image/x-portable-graymap": { + "source": "apache", + "extensions": ["pgm"] + }, + "image/x-portable-pixmap": { + "source": "apache", + "extensions": ["ppm"] + }, + "image/x-rgb": { + "source": "apache", + "extensions": ["rgb"] + }, + "image/x-tga": { + "source": "apache", + "extensions": ["tga"] + }, + "image/x-wmf": { + "source": "iana" + }, + "image/x-xbitmap": { + "source": "apache", + "extensions": ["xbm"] + }, + "image/x-xcf": { + "compressible": false + }, + "image/x-xpixmap": { + "source": "apache", + "extensions": ["xpm"] + }, + "image/x-xwindowdump": { + "source": "apache", + "extensions": ["xwd"] + }, + "message/bhttp": { + "source": "iana" + }, + "message/cpim": { + "source": "iana" + }, + "message/delivery-status": { + "source": "iana" + }, + "message/disposition-notification": { + "source": "iana", + "extensions": [ + "disposition-notification" + ] + }, + "message/external-body": { + "source": "iana" + }, + "message/feedback-report": { + "source": "iana" + }, + "message/global": { + "source": "iana", + "extensions": ["u8msg"] + }, + "message/global-delivery-status": { + "source": "iana", + "extensions": ["u8dsn"] + }, + "message/global-disposition-notification": { + "source": "iana", + "extensions": ["u8mdn"] + }, + "message/global-headers": { + "source": "iana", + "extensions": ["u8hdr"] + }, + "message/http": { + "source": "iana", + "compressible": false + }, + "message/imdn+xml": { + "source": "iana", + "compressible": true + }, + "message/mls": { + "source": "iana" + }, + "message/news": { + "source": "apache" + }, + "message/ohttp-req": { + "source": "iana" + }, + "message/ohttp-res": { + "source": "iana" + }, + "message/partial": { + "source": "iana", + "compressible": false + }, + "message/rfc822": { + "source": "iana", + "compressible": true, + "extensions": ["eml","mime","mht","mhtml"] + }, + "message/s-http": { + "source": "apache" + }, + "message/sip": { + "source": "iana" + }, + "message/sipfrag": { + "source": "iana" + }, + "message/tracking-status": { + "source": "iana" + }, + "message/vnd.si.simp": { + "source": "apache" + }, + "message/vnd.wfa.wsc": { + "source": "iana", + "extensions": ["wsc"] + }, + "model/3mf": { + "source": "iana", + "extensions": ["3mf"] + }, + "model/e57": { + "source": "iana" + }, + "model/gltf+json": { + "source": "iana", + "compressible": true, + "extensions": ["gltf"] + }, + "model/gltf-binary": { + "source": "iana", + "compressible": true, + "extensions": ["glb"] + }, + "model/iges": { + "source": "iana", + "compressible": false, + "extensions": ["igs","iges"] + }, + "model/jt": { + "source": "iana", + "extensions": ["jt"] + }, + "model/mesh": { + "source": "iana", + "compressible": false, + "extensions": ["msh","mesh","silo"] + }, + "model/mtl": { + "source": "iana", + "extensions": ["mtl"] + }, + "model/obj": { + "source": "iana", + "extensions": ["obj"] + }, + "model/prc": { + "source": "iana", + "extensions": ["prc"] + }, + "model/step": { + "source": "iana", + "extensions": ["step","stp","stpnc","p21","210"] + }, + "model/step+xml": { + "source": "iana", + "compressible": true, + "extensions": ["stpx"] + }, + "model/step+zip": { + "source": "iana", + "compressible": false, + "extensions": ["stpz"] + }, + "model/step-xml+zip": { + "source": "iana", + "compressible": false, + "extensions": ["stpxz"] + }, + "model/stl": { + "source": "iana", + "extensions": ["stl"] + }, + "model/u3d": { + "source": "iana", + "extensions": ["u3d"] + }, + "model/vnd.bary": { + "source": "iana", + "extensions": ["bary"] + }, + "model/vnd.cld": { + "source": "iana", + "extensions": ["cld"] + }, + "model/vnd.collada+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dae"] + }, + "model/vnd.dwf": { + "source": "iana", + "extensions": ["dwf"] + }, + "model/vnd.flatland.3dml": { + "source": "iana" + }, + "model/vnd.gdl": { + "source": "iana", + "extensions": ["gdl"] + }, + "model/vnd.gs-gdl": { + "source": "apache" + }, + "model/vnd.gs.gdl": { + "source": "iana" + }, + "model/vnd.gtw": { + "source": "iana", + "extensions": ["gtw"] + }, + "model/vnd.moml+xml": { + "source": "iana", + "compressible": true + }, + "model/vnd.mts": { + "source": "iana", + "extensions": ["mts"] + }, + "model/vnd.opengex": { + "source": "iana", + "extensions": ["ogex"] + }, + "model/vnd.parasolid.transmit.binary": { + "source": "iana", + "extensions": ["x_b"] + }, + "model/vnd.parasolid.transmit.text": { + "source": "iana", + "extensions": ["x_t"] + }, + "model/vnd.pytha.pyox": { + "source": "iana", + "extensions": ["pyo","pyox"] + }, + "model/vnd.rosette.annotated-data-model": { + "source": "iana" + }, + "model/vnd.sap.vds": { + "source": "iana", + "extensions": ["vds"] + }, + "model/vnd.usda": { + "source": "iana", + "extensions": ["usda"] + }, + "model/vnd.usdz+zip": { + "source": "iana", + "compressible": false, + "extensions": ["usdz"] + }, + "model/vnd.valve.source.compiled-map": { + "source": "iana", + "extensions": ["bsp"] + }, + "model/vnd.vtu": { + "source": "iana", + "extensions": ["vtu"] + }, + "model/vrml": { + "source": "iana", + "compressible": false, + "extensions": ["wrl","vrml"] + }, + "model/x3d+binary": { + "source": "apache", + "compressible": false, + "extensions": ["x3db","x3dbz"] + }, + "model/x3d+fastinfoset": { + "source": "iana", + "extensions": ["x3db"] + }, + "model/x3d+vrml": { + "source": "apache", + "compressible": false, + "extensions": ["x3dv","x3dvz"] + }, + "model/x3d+xml": { + "source": "iana", + "compressible": true, + "extensions": ["x3d","x3dz"] + }, + "model/x3d-vrml": { + "source": "iana", + "extensions": ["x3dv"] + }, + "multipart/alternative": { + "source": "iana", + "compressible": false + }, + "multipart/appledouble": { + "source": "iana" + }, + "multipart/byteranges": { + "source": "iana" + }, + "multipart/digest": { + "source": "iana" + }, + "multipart/encrypted": { + "source": "iana", + "compressible": false + }, + "multipart/form-data": { + "source": "iana", + "compressible": false + }, + "multipart/header-set": { + "source": "iana" + }, + "multipart/mixed": { + "source": "iana" + }, + "multipart/multilingual": { + "source": "iana" + }, + "multipart/parallel": { + "source": "iana" + }, + "multipart/related": { + "source": "iana", + "compressible": false + }, + "multipart/report": { + "source": "iana" + }, + "multipart/signed": { + "source": "iana", + "compressible": false + }, + "multipart/vnd.bint.med-plus": { + "source": "iana" + }, + "multipart/voice-message": { + "source": "iana" + }, + "multipart/x-mixed-replace": { + "source": "iana" + }, + "text/1d-interleaved-parityfec": { + "source": "iana" + }, + "text/cache-manifest": { + "source": "iana", + "compressible": true, + "extensions": ["appcache","manifest"] + }, + "text/calendar": { + "source": "iana", + "extensions": ["ics","ifb"] + }, + "text/calender": { + "compressible": true + }, + "text/cmd": { + "compressible": true + }, + "text/coffeescript": { + "extensions": ["coffee","litcoffee"] + }, + "text/cql": { + "source": "iana" + }, + "text/cql-expression": { + "source": "iana" + }, + "text/cql-identifier": { + "source": "iana" + }, + "text/css": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["css"] + }, + "text/csv": { + "source": "iana", + "compressible": true, + "extensions": ["csv"] + }, + "text/csv-schema": { + "source": "iana" + }, + "text/directory": { + "source": "iana" + }, + "text/dns": { + "source": "iana" + }, + "text/ecmascript": { + "source": "apache" + }, + "text/encaprtp": { + "source": "iana" + }, + "text/enriched": { + "source": "iana" + }, + "text/fhirpath": { + "source": "iana" + }, + "text/flexfec": { + "source": "iana" + }, + "text/fwdred": { + "source": "iana" + }, + "text/gff3": { + "source": "iana" + }, + "text/grammar-ref-list": { + "source": "iana" + }, + "text/hl7v2": { + "source": "iana" + }, + "text/html": { + "source": "iana", + "compressible": true, + "extensions": ["html","htm","shtml"] + }, + "text/jade": { + "extensions": ["jade"] + }, + "text/javascript": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js","mjs"] + }, + "text/jcr-cnd": { + "source": "iana" + }, + "text/jsx": { + "compressible": true, + "extensions": ["jsx"] + }, + "text/less": { + "compressible": true, + "extensions": ["less"] + }, + "text/markdown": { + "source": "iana", + "compressible": true, + "extensions": ["md","markdown"] + }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, + "text/mdx": { + "compressible": true, + "extensions": ["mdx"] + }, + "text/mizar": { + "source": "iana" + }, + "text/n3": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["n3"] + }, + "text/parameters": { + "source": "iana", + "charset": "UTF-8" + }, + "text/parityfec": { + "source": "iana" + }, + "text/plain": { + "source": "iana", + "compressible": true, + "extensions": ["txt","text","conf","def","list","log","in","ini"] + }, + "text/provenance-notation": { + "source": "iana", + "charset": "UTF-8" + }, + "text/prs.fallenstein.rst": { + "source": "iana" + }, + "text/prs.lines.tag": { + "source": "iana", + "extensions": ["dsc"] + }, + "text/prs.prop.logic": { + "source": "iana" + }, + "text/prs.texi": { + "source": "iana" + }, + "text/raptorfec": { + "source": "iana" + }, + "text/red": { + "source": "iana" + }, + "text/rfc822-headers": { + "source": "iana" + }, + "text/richtext": { + "source": "iana", + "compressible": true, + "extensions": ["rtx"] + }, + "text/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "text/rtp-enc-aescm128": { + "source": "iana" + }, + "text/rtploopback": { + "source": "iana" + }, + "text/rtx": { + "source": "iana" + }, + "text/sgml": { + "source": "iana", + "extensions": ["sgml","sgm"] + }, + "text/shaclc": { + "source": "iana" + }, + "text/shex": { + "source": "iana", + "extensions": ["shex"] + }, + "text/slim": { + "extensions": ["slim","slm"] + }, + "text/spdx": { + "source": "iana", + "extensions": ["spdx"] + }, + "text/strings": { + "source": "iana" + }, + "text/stylus": { + "extensions": ["stylus","styl"] + }, + "text/t140": { + "source": "iana" + }, + "text/tab-separated-values": { + "source": "iana", + "compressible": true, + "extensions": ["tsv"] + }, + "text/troff": { + "source": "iana", + "extensions": ["t","tr","roff","man","me","ms"] + }, + "text/turtle": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["ttl"] + }, + "text/ulpfec": { + "source": "iana" + }, + "text/uri-list": { + "source": "iana", + "compressible": true, + "extensions": ["uri","uris","urls"] + }, + "text/vcard": { + "source": "iana", + "compressible": true, + "extensions": ["vcard"] + }, + "text/vnd.a": { + "source": "iana" + }, + "text/vnd.abc": { + "source": "iana" + }, + "text/vnd.ascii-art": { + "source": "iana" + }, + "text/vnd.curl": { + "source": "iana", + "extensions": ["curl"] + }, + "text/vnd.curl.dcurl": { + "source": "apache", + "extensions": ["dcurl"] + }, + "text/vnd.curl.mcurl": { + "source": "apache", + "extensions": ["mcurl"] + }, + "text/vnd.curl.scurl": { + "source": "apache", + "extensions": ["scurl"] + }, + "text/vnd.debian.copyright": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.dmclientscript": { + "source": "iana" + }, + "text/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.exchangeable": { + "source": "iana" + }, + "text/vnd.familysearch.gedcom": { + "source": "iana", + "extensions": ["ged"] + }, + "text/vnd.ficlab.flt": { + "source": "iana" + }, + "text/vnd.fly": { + "source": "iana", + "extensions": ["fly"] + }, + "text/vnd.fmi.flexstor": { + "source": "iana", + "extensions": ["flx"] + }, + "text/vnd.gml": { + "source": "iana" + }, + "text/vnd.graphviz": { + "source": "iana", + "extensions": ["gv"] + }, + "text/vnd.hans": { + "source": "iana" + }, + "text/vnd.hgl": { + "source": "iana" + }, + "text/vnd.in3d.3dml": { + "source": "iana", + "extensions": ["3dml"] + }, + "text/vnd.in3d.spot": { + "source": "iana", + "extensions": ["spot"] + }, + "text/vnd.iptc.newsml": { + "source": "iana" + }, + "text/vnd.iptc.nitf": { + "source": "iana" + }, + "text/vnd.latex-z": { + "source": "iana" + }, + "text/vnd.motorola.reflex": { + "source": "iana" + }, + "text/vnd.ms-mediapackage": { + "source": "iana" + }, + "text/vnd.net2phone.commcenter.command": { + "source": "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + "source": "iana" + }, + "text/vnd.senx.warpscript": { + "source": "iana" + }, + "text/vnd.si.uricatalogue": { + "source": "apache" + }, + "text/vnd.sosi": { + "source": "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["jad"] + }, + "text/vnd.trolltech.linguist": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.vcf": { + "source": "iana" + }, + "text/vnd.wap.si": { + "source": "iana" + }, + "text/vnd.wap.sl": { + "source": "iana" + }, + "text/vnd.wap.wml": { + "source": "iana", + "extensions": ["wml"] + }, + "text/vnd.wap.wmlscript": { + "source": "iana", + "extensions": ["wmls"] + }, + "text/vnd.zoo.kcl": { + "source": "iana" + }, + "text/vtt": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["vtt"] + }, + "text/wgsl": { + "source": "iana", + "extensions": ["wgsl"] + }, + "text/x-asm": { + "source": "apache", + "extensions": ["s","asm"] + }, + "text/x-c": { + "source": "apache", + "extensions": ["c","cc","cxx","cpp","h","hh","dic"] + }, + "text/x-component": { + "source": "nginx", + "extensions": ["htc"] + }, + "text/x-fortran": { + "source": "apache", + "extensions": ["f","for","f77","f90"] + }, + "text/x-gwt-rpc": { + "compressible": true + }, + "text/x-handlebars-template": { + "extensions": ["hbs"] + }, + "text/x-java-source": { + "source": "apache", + "extensions": ["java"] + }, + "text/x-jquery-tmpl": { + "compressible": true + }, + "text/x-lua": { + "extensions": ["lua"] + }, + "text/x-markdown": { + "compressible": true, + "extensions": ["mkd"] + }, + "text/x-nfo": { + "source": "apache", + "extensions": ["nfo"] + }, + "text/x-opml": { + "source": "apache", + "extensions": ["opml"] + }, + "text/x-org": { + "compressible": true, + "extensions": ["org"] + }, + "text/x-pascal": { + "source": "apache", + "extensions": ["p","pas"] + }, + "text/x-processing": { + "compressible": true, + "extensions": ["pde"] + }, + "text/x-sass": { + "extensions": ["sass"] + }, + "text/x-scss": { + "extensions": ["scss"] + }, + "text/x-setext": { + "source": "apache", + "extensions": ["etx"] + }, + "text/x-sfv": { + "source": "apache", + "extensions": ["sfv"] + }, + "text/x-suse-ymp": { + "compressible": true, + "extensions": ["ymp"] + }, + "text/x-uuencode": { + "source": "apache", + "extensions": ["uu"] + }, + "text/x-vcalendar": { + "source": "apache", + "extensions": ["vcs"] + }, + "text/x-vcard": { + "source": "apache", + "extensions": ["vcf"] + }, + "text/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml"] + }, + "text/xml-external-parsed-entity": { + "source": "iana" + }, + "text/yaml": { + "compressible": true, + "extensions": ["yaml","yml"] + }, + "video/1d-interleaved-parityfec": { + "source": "iana" + }, + "video/3gpp": { + "source": "iana", + "extensions": ["3gp","3gpp"] + }, + "video/3gpp-tt": { + "source": "iana" + }, + "video/3gpp2": { + "source": "iana", + "extensions": ["3g2"] + }, + "video/av1": { + "source": "iana" + }, + "video/bmpeg": { + "source": "iana" + }, + "video/bt656": { + "source": "iana" + }, + "video/celb": { + "source": "iana" + }, + "video/dv": { + "source": "iana" + }, + "video/encaprtp": { + "source": "iana" + }, + "video/evc": { + "source": "iana" + }, + "video/ffv1": { + "source": "iana" + }, + "video/flexfec": { + "source": "iana" + }, + "video/h261": { + "source": "iana", + "extensions": ["h261"] + }, + "video/h263": { + "source": "iana", + "extensions": ["h263"] + }, + "video/h263-1998": { + "source": "iana" + }, + "video/h263-2000": { + "source": "iana" + }, + "video/h264": { + "source": "iana", + "extensions": ["h264"] + }, + "video/h264-rcdo": { + "source": "iana" + }, + "video/h264-svc": { + "source": "iana" + }, + "video/h265": { + "source": "iana" + }, + "video/h266": { + "source": "iana" + }, + "video/iso.segment": { + "source": "iana", + "extensions": ["m4s"] + }, + "video/jpeg": { + "source": "iana", + "extensions": ["jpgv"] + }, + "video/jpeg2000": { + "source": "iana" + }, + "video/jpm": { + "source": "apache", + "extensions": ["jpm","jpgm"] + }, + "video/jxsv": { + "source": "iana" + }, + "video/lottie+json": { + "source": "iana", + "compressible": true + }, + "video/matroska": { + "source": "iana" + }, + "video/matroska-3d": { + "source": "iana" + }, + "video/mj2": { + "source": "iana", + "extensions": ["mj2","mjp2"] + }, + "video/mp1s": { + "source": "iana" + }, + "video/mp2p": { + "source": "iana" + }, + "video/mp2t": { + "source": "iana", + "extensions": ["ts","m2t","m2ts","mts"] + }, + "video/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["mp4","mp4v","mpg4"] + }, + "video/mp4v-es": { + "source": "iana" + }, + "video/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpeg","mpg","mpe","m1v","m2v"] + }, + "video/mpeg4-generic": { + "source": "iana" + }, + "video/mpv": { + "source": "iana" + }, + "video/nv": { + "source": "iana" + }, + "video/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogv"] + }, + "video/parityfec": { + "source": "iana" + }, + "video/pointer": { + "source": "iana" + }, + "video/quicktime": { + "source": "iana", + "compressible": false, + "extensions": ["qt","mov"] + }, + "video/raptorfec": { + "source": "iana" + }, + "video/raw": { + "source": "iana" + }, + "video/rtp-enc-aescm128": { + "source": "iana" + }, + "video/rtploopback": { + "source": "iana" + }, + "video/rtx": { + "source": "iana" + }, + "video/scip": { + "source": "iana" + }, + "video/smpte291": { + "source": "iana" + }, + "video/smpte292m": { + "source": "iana" + }, + "video/ulpfec": { + "source": "iana" + }, + "video/vc1": { + "source": "iana" + }, + "video/vc2": { + "source": "iana" + }, + "video/vnd.cctv": { + "source": "iana" + }, + "video/vnd.dece.hd": { + "source": "iana", + "extensions": ["uvh","uvvh"] + }, + "video/vnd.dece.mobile": { + "source": "iana", + "extensions": ["uvm","uvvm"] + }, + "video/vnd.dece.mp4": { + "source": "iana" + }, + "video/vnd.dece.pd": { + "source": "iana", + "extensions": ["uvp","uvvp"] + }, + "video/vnd.dece.sd": { + "source": "iana", + "extensions": ["uvs","uvvs"] + }, + "video/vnd.dece.video": { + "source": "iana", + "extensions": ["uvv","uvvv"] + }, + "video/vnd.directv.mpeg": { + "source": "iana" + }, + "video/vnd.directv.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dlna.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dvb.file": { + "source": "iana", + "extensions": ["dvb"] + }, + "video/vnd.fvt": { + "source": "iana", + "extensions": ["fvt"] + }, + "video/vnd.hns.video": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsavc": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsmpeg2": { + "source": "iana" + }, + "video/vnd.motorola.video": { + "source": "iana" + }, + "video/vnd.motorola.videop": { + "source": "iana" + }, + "video/vnd.mpegurl": { + "source": "iana", + "extensions": ["mxu","m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + "source": "iana", + "extensions": ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + "source": "iana" + }, + "video/vnd.nokia.mp4vr": { + "source": "iana" + }, + "video/vnd.nokia.videovoip": { + "source": "iana" + }, + "video/vnd.objectvideo": { + "source": "iana" + }, + "video/vnd.planar": { + "source": "iana" + }, + "video/vnd.radgamettools.bink": { + "source": "iana" + }, + "video/vnd.radgamettools.smacker": { + "source": "apache" + }, + "video/vnd.sealed.mpeg1": { + "source": "iana" + }, + "video/vnd.sealed.mpeg4": { + "source": "iana" + }, + "video/vnd.sealed.swf": { + "source": "iana" + }, + "video/vnd.sealedmedia.softseal.mov": { + "source": "iana" + }, + "video/vnd.uvvu.mp4": { + "source": "iana", + "extensions": ["uvu","uvvu"] + }, + "video/vnd.vivo": { + "source": "iana", + "extensions": ["viv"] + }, + "video/vnd.youtube.yt": { + "source": "iana" + }, + "video/vp8": { + "source": "iana" + }, + "video/vp9": { + "source": "iana" + }, + "video/webm": { + "source": "apache", + "compressible": false, + "extensions": ["webm"] + }, + "video/x-f4v": { + "source": "apache", + "extensions": ["f4v"] + }, + "video/x-fli": { + "source": "apache", + "extensions": ["fli"] + }, + "video/x-flv": { + "source": "apache", + "compressible": false, + "extensions": ["flv"] + }, + "video/x-m4v": { + "source": "apache", + "extensions": ["m4v"] + }, + "video/x-matroska": { + "source": "apache", + "compressible": false, + "extensions": ["mkv","mk3d","mks"] + }, + "video/x-mng": { + "source": "apache", + "extensions": ["mng"] + }, + "video/x-ms-asf": { + "source": "apache", + "extensions": ["asf","asx"] + }, + "video/x-ms-vob": { + "source": "apache", + "extensions": ["vob"] + }, + "video/x-ms-wm": { + "source": "apache", + "extensions": ["wm"] + }, + "video/x-ms-wmv": { + "source": "apache", + "compressible": false, + "extensions": ["wmv"] + }, + "video/x-ms-wmx": { + "source": "apache", + "extensions": ["wmx"] + }, + "video/x-ms-wvx": { + "source": "apache", + "extensions": ["wvx"] + }, + "video/x-msvideo": { + "source": "apache", + "extensions": ["avi"] + }, + "video/x-sgi-movie": { + "source": "apache", + "extensions": ["movie"] + }, + "video/x-smv": { + "source": "apache", + "extensions": ["smv"] + }, + "x-conference/x-cooltalk": { + "source": "apache", + "extensions": ["ice"] + }, + "x-shader/x-fragment": { + "compressible": true + }, + "x-shader/x-vertex": { + "compressible": true + } +} diff --git a/node_modules/mime-db/index.js b/node_modules/mime-db/index.js new file mode 100644 index 0000000..ec2be30 --- /dev/null +++ b/node_modules/mime-db/index.js @@ -0,0 +1,12 @@ +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = require('./db.json') diff --git a/node_modules/mime-db/package.json b/node_modules/mime-db/package.json new file mode 100644 index 0000000..289a370 --- /dev/null +++ b/node_modules/mime-db/package.json @@ -0,0 +1,56 @@ +{ + "name": "mime-db", + "description": "Media Type Database", + "version": "1.54.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)", + "Robert Kieffer (http://github.com/broofa)" + ], + "license": "MIT", + "keywords": [ + "mime", + "db", + "type", + "types", + "database", + "charset", + "charsets" + ], + "repository": "jshttp/mime-db", + "devDependencies": { + "csv-parse": "4.16.3", + "eslint": "8.32.0", + "eslint-config-standard": "15.0.1", + "eslint-plugin-import": "2.27.5", + "eslint-plugin-markdown": "3.0.0", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "6.1.1", + "eslint-plugin-standard": "4.1.0", + "media-typer": "1.1.0", + "mocha": "10.2.0", + "nyc": "15.1.0", + "stream-to-array": "2.3.0", + "undici": "7.1.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "db.json", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "build": "node scripts/build", + "fetch": "node scripts/fetch-apache && node scripts/fetch-iana && node scripts/fetch-nginx", + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "update": "npm run fetch && npm run build", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/mime-types/HISTORY.md b/node_modules/mime-types/HISTORY.md new file mode 100644 index 0000000..18473e4 --- /dev/null +++ b/node_modules/mime-types/HISTORY.md @@ -0,0 +1,421 @@ +3.0.1 / 2025-03-26 +=================== + +* deps: mime-db@1.54.0 + +3.0.0 / 2024-08-31 +=================== + +* Drop support for node <18 +* deps: mime-db@1.53.0 +* resolve extension conflicts with mime-score (#119) + * asc -> application/pgp-signature is now application/pgp-keys + * mpp -> application/vnd.ms-project is now application/dash-patch+xml + * ac -> application/vnd.nokia.n-gage.ac+xml is now application/pkix-attr-cert + * bdoc -> application/x-bdoc is now application/bdoc + * wmz -> application/x-msmetafile is now application/x-ms-wmz + * xsl -> application/xslt+xml is now application/xml + * wav -> audio/wave is now audio/wav + * rtf -> text/rtf is now application/rtf + * xml -> text/xml is now application/xml + * mp4 -> video/mp4 is now application/mp4 + * mpg4 -> video/mp4 is now application/mp4 + + +2.1.35 / 2022-03-12 +=================== + + * deps: mime-db@1.52.0 + - Add extensions from IANA for more `image/*` types + - Add extension `.asc` to `application/pgp-keys` + - Add extensions to various XML types + - Add new upstream MIME types + +2.1.34 / 2021-11-08 +=================== + + * deps: mime-db@1.51.0 + - Add new upstream MIME types + +2.1.33 / 2021-10-01 +=================== + + * deps: mime-db@1.50.0 + - Add deprecated iWorks mime types and extensions + - Add new upstream MIME types + +2.1.32 / 2021-07-27 +=================== + + * deps: mime-db@1.49.0 + - Add extension `.trig` to `application/trig` + - Add new upstream MIME types + +2.1.31 / 2021-06-01 +=================== + + * deps: mime-db@1.48.0 + - Add extension `.mvt` to `application/vnd.mapbox-vector-tile` + - Add new upstream MIME types + +2.1.30 / 2021-04-02 +=================== + + * deps: mime-db@1.47.0 + - Add extension `.amr` to `audio/amr` + - Remove ambigious extensions from IANA for `application/*+xml` types + - Update primary extension to `.es` for `application/ecmascript` + +2.1.29 / 2021-02-17 +=================== + + * deps: mime-db@1.46.0 + - Add extension `.amr` to `audio/amr` + - Add extension `.m4s` to `video/iso.segment` + - Add extension `.opus` to `audio/ogg` + - Add new upstream MIME types + +2.1.28 / 2021-01-01 +=================== + + * deps: mime-db@1.45.0 + - Add `application/ubjson` with extension `.ubj` + - Add `image/avif` with extension `.avif` + - Add `image/ktx2` with extension `.ktx2` + - Add extension `.dbf` to `application/vnd.dbf` + - Add extension `.rar` to `application/vnd.rar` + - Add extension `.td` to `application/urc-targetdesc+xml` + - Add new upstream MIME types + - Fix extension of `application/vnd.apple.keynote` to be `.key` + +2.1.27 / 2020-04-23 +=================== + + * deps: mime-db@1.44.0 + - Add charsets from IANA + - Add extension `.cjs` to `application/node` + - Add new upstream MIME types + +2.1.26 / 2020-01-05 +=================== + + * deps: mime-db@1.43.0 + - Add `application/x-keepass2` with extension `.kdbx` + - Add extension `.mxmf` to `audio/mobile-xmf` + - Add extensions from IANA for `application/*+xml` types + - Add new upstream MIME types + +2.1.25 / 2019-11-12 +=================== + + * deps: mime-db@1.42.0 + - Add new upstream MIME types + - Add `application/toml` with extension `.toml` + - Add `image/vnd.ms-dds` with extension `.dds` + +2.1.24 / 2019-04-20 +=================== + + * deps: mime-db@1.40.0 + - Add extensions from IANA for `model/*` types + - Add `text/mdx` with extension `.mdx` + +2.1.23 / 2019-04-17 +=================== + + * deps: mime-db@~1.39.0 + - Add extensions `.siv` and `.sieve` to `application/sieve` + - Add new upstream MIME types + +2.1.22 / 2019-02-14 +=================== + + * deps: mime-db@~1.38.0 + - Add extension `.nq` to `application/n-quads` + - Add extension `.nt` to `application/n-triples` + - Add new upstream MIME types + +2.1.21 / 2018-10-19 +=================== + + * deps: mime-db@~1.37.0 + - Add extensions to HEIC image types + - Add new upstream MIME types + +2.1.20 / 2018-08-26 +=================== + + * deps: mime-db@~1.36.0 + - Add Apple file extensions from IANA + - Add extensions from IANA for `image/*` types + - Add new upstream MIME types + +2.1.19 / 2018-07-17 +=================== + + * deps: mime-db@~1.35.0 + - Add extension `.csl` to `application/vnd.citationstyles.style+xml` + - Add extension `.es` to `application/ecmascript` + - Add extension `.owl` to `application/rdf+xml` + - Add new upstream MIME types + - Add UTF-8 as default charset for `text/turtle` + +2.1.18 / 2018-02-16 +=================== + + * deps: mime-db@~1.33.0 + - Add `application/raml+yaml` with extension `.raml` + - Add `application/wasm` with extension `.wasm` + - Add `text/shex` with extension `.shex` + - Add extensions for JPEG-2000 images + - Add extensions from IANA for `message/*` types + - Add new upstream MIME types + - Update font MIME types + - Update `text/hjson` to registered `application/hjson` + +2.1.17 / 2017-09-01 +=================== + + * deps: mime-db@~1.30.0 + - Add `application/vnd.ms-outlook` + - Add `application/x-arj` + - Add extension `.mjs` to `application/javascript` + - Add glTF types and extensions + - Add new upstream MIME types + - Add `text/x-org` + - Add VirtualBox MIME types + - Fix `source` records for `video/*` types that are IANA + - Update `font/opentype` to registered `font/otf` + +2.1.16 / 2017-07-24 +=================== + + * deps: mime-db@~1.29.0 + - Add `application/fido.trusted-apps+json` + - Add extension `.wadl` to `application/vnd.sun.wadl+xml` + - Add extension `.gz` to `application/gzip` + - Add new upstream MIME types + - Update extensions `.md` and `.markdown` to be `text/markdown` + +2.1.15 / 2017-03-23 +=================== + + * deps: mime-db@~1.27.0 + - Add new mime types + - Add `image/apng` + +2.1.14 / 2017-01-14 +=================== + + * deps: mime-db@~1.26.0 + - Add new mime types + +2.1.13 / 2016-11-18 +=================== + + * deps: mime-db@~1.25.0 + - Add new mime types + +2.1.12 / 2016-09-18 +=================== + + * deps: mime-db@~1.24.0 + - Add new mime types + - Add `audio/mp3` + +2.1.11 / 2016-05-01 +=================== + + * deps: mime-db@~1.23.0 + - Add new mime types + +2.1.10 / 2016-02-15 +=================== + + * deps: mime-db@~1.22.0 + - Add new mime types + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + +2.1.9 / 2016-01-06 +================== + + * deps: mime-db@~1.21.0 + - Add new mime types + +2.1.8 / 2015-11-30 +================== + + * deps: mime-db@~1.20.0 + - Add new mime types + +2.1.7 / 2015-09-20 +================== + + * deps: mime-db@~1.19.0 + - Add new mime types + +2.1.6 / 2015-09-03 +================== + + * deps: mime-db@~1.18.0 + - Add new mime types + +2.1.5 / 2015-08-20 +================== + + * deps: mime-db@~1.17.0 + - Add new mime types + +2.1.4 / 2015-07-30 +================== + + * deps: mime-db@~1.16.0 + - Add new mime types + +2.1.3 / 2015-07-13 +================== + + * deps: mime-db@~1.15.0 + - Add new mime types + +2.1.2 / 2015-06-25 +================== + + * deps: mime-db@~1.14.0 + - Add new mime types + +2.1.1 / 2015-06-08 +================== + + * perf: fix deopt during mapping + +2.1.0 / 2015-06-07 +================== + + * Fix incorrectly treating extension-less file name as extension + - i.e. `'path/to/json'` will no longer return `application/json` + * Fix `.charset(type)` to accept parameters + * Fix `.charset(type)` to match case-insensitive + * Improve generation of extension to MIME mapping + * Refactor internals for readability and no argument reassignment + * Prefer `application/*` MIME types from the same source + * Prefer any type over `application/octet-stream` + * deps: mime-db@~1.13.0 + - Add nginx as a source + - Add new mime types + +2.0.14 / 2015-06-06 +=================== + + * deps: mime-db@~1.12.0 + - Add new mime types + +2.0.13 / 2015-05-31 +=================== + + * deps: mime-db@~1.11.0 + - Add new mime types + +2.0.12 / 2015-05-19 +=================== + + * deps: mime-db@~1.10.0 + - Add new mime types + +2.0.11 / 2015-05-05 +=================== + + * deps: mime-db@~1.9.1 + - Add new mime types + +2.0.10 / 2015-03-13 +=================== + + * deps: mime-db@~1.8.0 + - Add new mime types + +2.0.9 / 2015-02-09 +================== + + * deps: mime-db@~1.7.0 + - Add new mime types + - Community extensions ownership transferred from `node-mime` + +2.0.8 / 2015-01-29 +================== + + * deps: mime-db@~1.6.0 + - Add new mime types + +2.0.7 / 2014-12-30 +================== + + * deps: mime-db@~1.5.0 + - Add new mime types + - Fix various invalid MIME type entries + +2.0.6 / 2014-12-30 +================== + + * deps: mime-db@~1.4.0 + - Add new mime types + - Fix various invalid MIME type entries + - Remove example template MIME types + +2.0.5 / 2014-12-29 +================== + + * deps: mime-db@~1.3.1 + - Fix missing extensions + +2.0.4 / 2014-12-10 +================== + + * deps: mime-db@~1.3.0 + - Add new mime types + +2.0.3 / 2014-11-09 +================== + + * deps: mime-db@~1.2.0 + - Add new mime types + +2.0.2 / 2014-09-28 +================== + + * deps: mime-db@~1.1.0 + - Add new mime types + - Update charsets + +2.0.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + +2.0.0 / 2014-09-02 +================== + + * Use `mime-db` + * Remove `.define()` + +1.0.2 / 2014-08-04 +================== + + * Set charset=utf-8 for `text/javascript` + +1.0.1 / 2014-06-24 +================== + + * Add `text/jsx` type + +1.0.0 / 2014-05-12 +================== + + * Return `false` for unknown types + * Set charset=utf-8 for `application/json` + +0.1.0 / 2014-05-02 +================== + + * Initial release diff --git a/node_modules/mime-types/LICENSE b/node_modules/mime-types/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/node_modules/mime-types/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mime-types/README.md b/node_modules/mime-types/README.md new file mode 100644 index 0000000..222d2b5 --- /dev/null +++ b/node_modules/mime-types/README.md @@ -0,0 +1,126 @@ +# mime-types + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +The ultimate javascript content-type utility. + +Similar to [the `mime@1.x` module](https://www.npmjs.com/package/mime), except: + +- __No fallbacks.__ Instead of naively returning the first available type, + `mime-types` simply returns `false`, so do + `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. +- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. +- No `.define()` functionality +- Bug fixes for `.lookup(path)` + +Otherwise, the API is compatible with `mime` 1.x. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install mime-types +``` + +## Note on MIME Type Data and Semver + +This package considers the programmatic api as the semver compatibility. Additionally, the package which provides the MIME data +for this package (`mime-db`) *also* considers it's programmatic api as the semver contract. This means the MIME type resolution is *not* considered +in the semver bumps. + +In the past the version of `mime-db` was pinned to give two decision points when adopting MIME data changes. This is no longer true. We still update the +`mime-db` package here as a `minor` release when necessary, but will use a `^` range going forward. This means that if you want to pin your `mime-db` data +you will need to do it in your application. While this expectation was not set in docs until now, it is how the pacakge operated, so we do not feel this is +a breaking change. + +If you wish to pin your `mime-db` version you can do that with overrides via your package manager of choice. See their documentation for how to correctly configure that. + +## Adding Types + +All mime types are based on [mime-db](https://www.npmjs.com/package/mime-db), +so open a PR there if you'd like to add mime types. + +## API + +```js +var mime = require('mime-types') +``` + +All functions return `false` if input is invalid or not found. + +### mime.lookup(path) + +Lookup the content-type associated with a file. + +```js +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('folder/.htaccess') // false + +mime.lookup('cats') // false +``` + +### mime.contentType(type) + +Create a full content-type header given a content-type or extension. +When given an extension, `mime.lookup` is used to get the matching +content-type, otherwise the given content-type is used. Then if the +content-type does not already have a `charset` parameter, `mime.charset` +is used to get the default charset and add to the returned content-type. + +```js +mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' +mime.contentType('file.json') // 'application/json; charset=utf-8' +mime.contentType('text/html') // 'text/html; charset=utf-8' +mime.contentType('text/html; charset=iso-8859-1') // 'text/html; charset=iso-8859-1' + +// from a full path +mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' +``` + +### mime.extension(type) + +Get the default extension for a content-type. + +```js +mime.extension('application/octet-stream') // 'bin' +``` + +### mime.charset(type) + +Lookup the implied default charset of a content-type. + +```js +mime.charset('text/markdown') // 'UTF-8' +``` + +### var type = mime.types[extension] + +A map of content-types by extension. + +### [extensions...] = mime.extensions[type] + +A map of extensions by content-type. + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/mime-types/master?label=ci +[ci-url]: https://github.com/jshttp/mime-types/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-types/master +[coveralls-url]: https://coveralls.io/r/jshttp/mime-types?branch=master +[node-version-image]: https://badgen.net/npm/node/mime-types +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/mime-types +[npm-url]: https://npmjs.org/package/mime-types +[npm-version-image]: https://badgen.net/npm/v/mime-types diff --git a/node_modules/mime-types/index.js b/node_modules/mime-types/index.js new file mode 100644 index 0000000..c348cb6 --- /dev/null +++ b/node_modules/mime-types/index.js @@ -0,0 +1,211 @@ +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var db = require('mime-db') +var extname = require('path').extname +var mimeScore = require('./mimeScore') + +/** + * Module variables. + * @private + */ + +var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ +var TEXT_TYPE_REGEXP = /^text\//i + +/** + * Module exports. + * @public + */ + +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension +exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) +exports._extensionConflicts = [] + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function charset (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + var mime = match && db[match[1].toLowerCase()] + + if (mime && mime.charset) { + return mime.charset + } + + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' + } + + return false +} + +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ + +function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } + + var mime = str.indexOf('/') === -1 ? exports.lookup(str) : str + + if (!mime) { + return false + } + + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } + + return mime +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] + + if (!exts || !exts.length) { + return false + } + + return exts[0] +} + +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ + +function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } + + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .slice(1) + + if (!extension) { + return false + } + + return exports.types[extension] || false +} + +/** + * Populate the extensions and types maps. + * @private + */ + +function populateMaps (extensions, types) { + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type] + var exts = mime.extensions + + if (!exts || !exts.length) { + return + } + + // mime -> extensions + extensions[type] = exts + + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] + types[extension] = _preferredType(extension, types[extension], type) + + // DELETE (eventually): Capture extension->type maps that change as a + // result of switching to mime-score. This is just to help make reviewing + // PR #119 easier, and can be removed once that PR is approved. + const legacyType = _preferredTypeLegacy( + extension, + types[extension], + type + ) + if (legacyType !== types[extension]) { + exports._extensionConflicts.push([extension, legacyType, types[extension]]) + } + } + }) +} + +// Resolve type conflict using mime-score +function _preferredType (ext, type0, type1) { + var score0 = type0 ? mimeScore(type0, db[type0].source) : 0 + var score1 = type1 ? mimeScore(type1, db[type1].source) : 0 + + return score0 > score1 ? type0 : type1 +} + +// Resolve type conflict using pre-mime-score logic +function _preferredTypeLegacy (ext, type0, type1) { + var SOURCE_RANK = ['nginx', 'apache', undefined, 'iana'] + + var score0 = type0 ? SOURCE_RANK.indexOf(db[type0].source) : 0 + var score1 = type1 ? SOURCE_RANK.indexOf(db[type1].source) : 0 + + if ( + exports.types[extension] !== 'application/octet-stream' && + (score0 > score1 || + (score0 === score1 && + exports.types[extension]?.slice(0, 12) === 'application/')) + ) { + return type0 + } + + return score0 > score1 ? type0 : type1 +} diff --git a/node_modules/mime-types/mimeScore.js b/node_modules/mime-types/mimeScore.js new file mode 100644 index 0000000..e2ecc66 --- /dev/null +++ b/node_modules/mime-types/mimeScore.js @@ -0,0 +1,52 @@ +// 'mime-score' back-ported to CommonJS + +// Score RFC facets (see https://tools.ietf.org/html/rfc6838#section-3) +var FACET_SCORES = { + 'prs.': 100, + 'x-': 200, + 'x.': 300, + 'vnd.': 400, + default: 900 +} + +// Score mime source (Logic originally from `jshttp/mime-types` module) +var SOURCE_SCORES = { + nginx: 10, + apache: 20, + iana: 40, + default: 30 // definitions added by `jshttp/mime-db` project? +} + +var TYPE_SCORES = { + // prefer application/xml over text/xml + // prefer application/rtf over text/rtf + application: 1, + + // prefer font/woff over application/font-woff + font: 2, + + default: 0 +} + +/** + * Get each component of the score for a mime type. The sum of these is the + * total score. The higher the score, the more "official" the type. + */ +module.exports = function mimeScore (mimeType, source = 'default') { + if (mimeType === 'application/octet-stream') { + return 0 + } + + const [type, subtype] = mimeType.split('/') + + const facet = subtype.replace(/(\.|x-).*/, '$1') + + const facetScore = FACET_SCORES[facet] || FACET_SCORES.default + const sourceScore = SOURCE_SCORES[source] || SOURCE_SCORES.default + const typeScore = TYPE_SCORES[type] || TYPE_SCORES.default + + // All else being equal prefer shorter types + const lengthScore = 1 - mimeType.length / 100 + + return facetScore + sourceScore + typeScore + lengthScore +} diff --git a/node_modules/mime-types/package.json b/node_modules/mime-types/package.json new file mode 100644 index 0000000..79481ae --- /dev/null +++ b/node_modules/mime-types/package.json @@ -0,0 +1,45 @@ +{ + "name": "mime-types", + "description": "The ultimate javascript content-type utility.", + "version": "3.0.1", + "contributors": [ + "Douglas Christopher Wilson ", + "Jeremiah Senkpiel (https://searchbeam.jit.su)", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "keywords": [ + "mime", + "types" + ], + "repository": "jshttp/mime-types", + "dependencies": { + "mime-db": "^1.54.0" + }, + "devDependencies": { + "eslint": "8.33.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.27.5", + "eslint-plugin-markdown": "3.0.0", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "6.1.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "10.2.0", + "nyc": "15.1.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js", + "mimeScore.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec test/test.js", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/minimatch/LICENSE b/node_modules/minimatch/LICENSE new file mode 100644 index 0000000..1493534 --- /dev/null +++ b/node_modules/minimatch/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2011-2023 Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/minimatch/README.md b/node_modules/minimatch/README.md new file mode 100644 index 0000000..a5bdefa --- /dev/null +++ b/node_modules/minimatch/README.md @@ -0,0 +1,259 @@ +# minimatch + +A minimal matching utility. + +[![Build Status](https://travis-ci.org/isaacs/minimatch.svg?branch=master)](http://travis-ci.org/isaacs/minimatch) + + +This is the matching library used internally by npm. + +It works by converting glob expressions into JavaScript `RegExp` +objects. + +## Usage + +```javascript +var minimatch = require("minimatch") + +minimatch("bar.foo", "*.foo") // true! +minimatch("bar.foo", "*.bar") // false! +minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! +``` + +## Features + +Supports these glob features: + +* Brace Expansion +* Extended glob matching +* "Globstar" `**` matching + +See: + +* `man sh` +* `man bash` +* `man 3 fnmatch` +* `man 5 gitignore` + +## Windows + +**Please only use forward-slashes in glob expressions.** + +Though windows uses either `/` or `\` as its path separator, only `/` +characters are used by this glob implementation. You must use +forward-slashes **only** in glob expressions. Back-slashes in patterns +will always be interpreted as escape characters, not path separators. + +Note that `\` or `/` _will_ be interpreted as path separators in paths on +Windows, and will match against `/` in glob expressions. + +So just always use `/` in patterns. + +## Minimatch Class + +Create a minimatch object by instantiating the `minimatch.Minimatch` class. + +```javascript +var Minimatch = require("minimatch").Minimatch +var mm = new Minimatch(pattern, options) +``` + +### Properties + +* `pattern` The original pattern the minimatch object represents. +* `options` The options supplied to the constructor. +* `set` A 2-dimensional array of regexp or string expressions. + Each row in the + array corresponds to a brace-expanded pattern. Each item in the row + corresponds to a single path-part. For example, the pattern + `{a,b/c}/d` would expand to a set of patterns like: + + [ [ a, d ] + , [ b, c, d ] ] + + If a portion of the pattern doesn't have any "magic" in it + (that is, it's something like `"foo"` rather than `fo*o?`), then it + will be left as a string rather than converted to a regular + expression. + +* `regexp` Created by the `makeRe` method. A single regular expression + expressing the entire pattern. This is useful in cases where you wish + to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. +* `negate` True if the pattern is negated. +* `comment` True if the pattern is a comment. +* `empty` True if the pattern is `""`. + +### Methods + +* `makeRe` Generate the `regexp` member if necessary, and return it. + Will return `false` if the pattern is invalid. +* `match(fname)` Return true if the filename matches the pattern, or + false otherwise. +* `matchOne(fileArray, patternArray, partial)` Take a `/`-split + filename, and match it against a single row in the `regExpSet`. This + method is mainly for internal use, but is exposed so that it can be + used by a glob-walker that needs to avoid excessive filesystem calls. + +All other methods are internal, and will be called as necessary. + +### minimatch(path, pattern, options) + +Main export. Tests a path against the pattern using the options. + +```javascript +var isJS = minimatch(file, "*.js", { matchBase: true }) +``` + +### minimatch.filter(pattern, options) + +Returns a function that tests its +supplied argument, suitable for use with `Array.filter`. Example: + +```javascript +var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) +``` + +### minimatch.match(list, pattern, options) + +Match against the list of +files, in the style of fnmatch or glob. If nothing is matched, and +options.nonull is set, then return a list containing the pattern itself. + +```javascript +var javascripts = minimatch.match(fileList, "*.js", {matchBase: true}) +``` + +### minimatch.makeRe(pattern, options) + +Make a regular expression object from the pattern. + +## Options + +All options are `false` by default. + +### debug + +Dump a ton of stuff to stderr. + +### nobrace + +Do not expand `{a,b}` and `{1..3}` brace sets. + +### noglobstar + +Disable `**` matching against multiple folder names. + +### dot + +Allow patterns to match filenames starting with a period, even if +the pattern does not explicitly have a period in that spot. + +Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` +is set. + +### noext + +Disable "extglob" style patterns like `+(a|b)`. + +### nocase + +Perform a case-insensitive match. + +### nonull + +When a match is not found by `minimatch.match`, return a list containing +the pattern itself if this option is set. When not set, an empty list +is returned if there are no matches. + +### matchBase + +If set, then patterns without slashes will be matched +against the basename of the path if it contains slashes. For example, +`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. + +### nocomment + +Suppress the behavior of treating `#` at the start of a pattern as a +comment. + +### nonegate + +Suppress the behavior of treating a leading `!` character as negation. + +### flipNegate + +Returns from negate expressions the same as if they were not negated. +(Ie, true on a hit, false on a miss.) + +### partial + +Compare a partial path to a pattern. As long as the parts of the path that +are present are not contradicted by the pattern, it will be treated as a +match. This is useful in applications where you're walking through a +folder structure, and don't yet have the full path, but want to ensure that +you do not walk down paths that can never be a match. + +For example, + +```js +minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d +minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d +minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a +``` + +### windowsPathsNoEscape + +Use `\\` as a path separator _only_, and _never_ as an escape +character. If set, all `\\` characters are replaced with `/` in +the pattern. Note that this makes it **impossible** to match +against paths containing literal glob pattern characters, but +allows matching with patterns constructed using `path.join()` and +`path.resolve()` on Windows platforms, mimicking the (buggy!) +behavior of earlier versions on Windows. Please use with +caution, and be mindful of [the caveat about Windows +paths](#windows). + +For legacy reasons, this is also set if +`options.allowWindowsEscape` is set to the exact value `false`. + +## Comparisons to other fnmatch/glob implementations + +While strict compliance with the existing standards is a worthwhile +goal, some discrepancies exist between minimatch and other +implementations, and are intentional. + +If the pattern starts with a `!` character, then it is negated. Set the +`nonegate` flag to suppress this behavior, and treat leading `!` +characters normally. This is perhaps relevant if you wish to start the +pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` +characters at the start of a pattern will negate the pattern multiple +times. + +If a pattern starts with `#`, then it is treated as a comment, and +will not match anything. Use `\#` to match a literal `#` at the +start of a line, or set the `nocomment` flag to suppress this behavior. + +The double-star character `**` is supported by default, unless the +`noglobstar` flag is set. This is supported in the manner of bsdglob +and bash 4.1, where `**` only has special significance if it is the only +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but +`a/**b` will not. + +If an escaped pattern has no matches, and the `nonull` flag is set, +then minimatch.match returns the pattern as-provided, rather than +interpreting the character escapes. For example, +`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than +`"*a?"`. This is akin to setting the `nullglob` option in bash, except +that it does not resolve escaped pattern characters. + +If brace expansion is not disabled, then it is performed before any +other interpretation of the glob pattern. Thus, a pattern like +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are +checked for validity. Since those two are valid, matching proceeds. + +Note that `fnmatch(3)` in libc is an extremely naive string comparison +matcher, which does not do anything special for slashes. This library is +designed to be used in glob searching and file walkers, and so it does do +special things with `/`. Thus, `foo*` will not match `foo/bar` in this +library, even though it would in `fnmatch(3)`. diff --git a/node_modules/minimatch/lib/path.js b/node_modules/minimatch/lib/path.js new file mode 100644 index 0000000..ffe453d --- /dev/null +++ b/node_modules/minimatch/lib/path.js @@ -0,0 +1,4 @@ +const isWindows = typeof process === 'object' && + process && + process.platform === 'win32' +module.exports = isWindows ? { sep: '\\' } : { sep: '/' } diff --git a/node_modules/minimatch/minimatch.js b/node_modules/minimatch/minimatch.js new file mode 100644 index 0000000..6c8bfc3 --- /dev/null +++ b/node_modules/minimatch/minimatch.js @@ -0,0 +1,944 @@ +const minimatch = module.exports = (p, pattern, options = {}) => { + assertValidPattern(pattern) + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } + + return new Minimatch(pattern, options).match(p) +} + +module.exports = minimatch + +const path = require('./lib/path.js') +minimatch.sep = path.sep + +const GLOBSTAR = Symbol('globstar **') +minimatch.GLOBSTAR = GLOBSTAR +const expand = require('brace-expansion') + +const plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +} + +// any single thing other than / +// don't need to escape / when using new RegExp() +const qmark = '[^/]' + +// * => any number of characters +const star = qmark + '*?' + +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +const twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' + +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +const twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' + +// "abc" -> { a:true, b:true, c:true } +const charSet = s => s.split('').reduce((set, c) => { + set[c] = true + return set +}, {}) + +// characters that need to be escaped in RegExp. +const reSpecials = charSet('().*{}+?[]^$\\!') + +// characters that indicate we have to add the pattern start +const addPatternStartSet = charSet('[.(') + +// normalizes slashes. +const slashSplit = /\/+/ + +minimatch.filter = (pattern, options = {}) => + (p, i, list) => minimatch(p, pattern, options) + +const ext = (a, b = {}) => { + const t = {} + Object.keys(a).forEach(k => t[k] = a[k]) + Object.keys(b).forEach(k => t[k] = b[k]) + return t +} + +minimatch.defaults = def => { + if (!def || typeof def !== 'object' || !Object.keys(def).length) { + return minimatch + } + + const orig = minimatch + + const m = (p, pattern, options) => orig(p, pattern, ext(def, options)) + m.Minimatch = class Minimatch extends orig.Minimatch { + constructor (pattern, options) { + super(pattern, ext(def, options)) + } + } + m.Minimatch.defaults = options => orig.defaults(ext(def, options)).Minimatch + m.filter = (pattern, options) => orig.filter(pattern, ext(def, options)) + m.defaults = options => orig.defaults(ext(def, options)) + m.makeRe = (pattern, options) => orig.makeRe(pattern, ext(def, options)) + m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext(def, options)) + m.match = (list, pattern, options) => orig.match(list, pattern, ext(def, options)) + + return m +} + + + + + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = (pattern, options) => braceExpand(pattern, options) + +const braceExpand = (pattern, options = {}) => { + assertValidPattern(pattern) + + // Thanks to Yeting Li for + // improving this regexp to avoid a ReDOS vulnerability. + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + // shortcut. no need to expand. + return [pattern] + } + + return expand(pattern) +} + +const MAX_PATTERN_LENGTH = 1024 * 64 +const assertValidPattern = pattern => { + if (typeof pattern !== 'string') { + throw new TypeError('invalid pattern') + } + + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError('pattern is too long') + } +} + +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +const SUBPARSE = Symbol('subparse') + +minimatch.makeRe = (pattern, options) => + new Minimatch(pattern, options || {}).makeRe() + +minimatch.match = (list, pattern, options = {}) => { + const mm = new Minimatch(pattern, options) + list = list.filter(f => mm.match(f)) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list +} + +// replace stuff like \* with * +const globUnescape = s => s.replace(/\\(.)/g, '$1') +const charUnescape = s => s.replace(/\\([^-\]])/g, '$1') +const regExpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +const braExpEscape = s => s.replace(/[[\]\\]/g, '\\$&') + +class Minimatch { + constructor (pattern, options) { + assertValidPattern(pattern) + + if (!options) options = {} + + this.options = options + this.set = [] + this.pattern = pattern + this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || + options.allowWindowsEscape === false + if (this.windowsPathsNoEscape) { + this.pattern = this.pattern.replace(/\\/g, '/') + } + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + this.partial = !!options.partial + + // make the set of regexps etc. + this.make() + } + + debug () {} + + make () { + const pattern = this.pattern + const options = this.options + + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } + + // step 1: figure out negation, etc. + this.parseNegate() + + // step 2: expand braces + let set = this.globSet = this.braceExpand() + + if (options.debug) this.debug = (...args) => console.error(...args) + + this.debug(this.pattern, set) + + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(s => s.split(slashSplit)) + + this.debug(this.pattern, set) + + // glob --> regexps + set = set.map((s, si, set) => s.map(this.parse, this)) + + this.debug(this.pattern, set) + + // filter out everything that didn't compile properly. + set = set.filter(s => s.indexOf(false) === -1) + + this.debug(this.pattern, set) + + this.set = set + } + + parseNegate () { + if (this.options.nonegate) return + + const pattern = this.pattern + let negate = false + let negateOffset = 0 + + for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) { + negate = !negate + negateOffset++ + } + + if (negateOffset) this.pattern = pattern.slice(negateOffset) + this.negate = negate + } + + // set partial to true to test if, for example, + // "/a/b" matches the start of "/*/b/*/d" + // Partial means, if you run out of file before you run + // out of pattern, then that's fine, as long as all + // the parts match. + matchOne (file, pattern, partial) { + var options = this.options + + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) + + this.debug('matchOne', file.length, pattern.length) + + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] + + this.debug(pattern, p, f) + + // should be impossible. + // some invalid regexp stuff in the set. + /* istanbul ignore if */ + if (p === false) return false + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } + + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } + + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + /* istanbul ignore if */ + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } + + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + hit = f === p + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) + } + + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else /* istanbul ignore else */ if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + return (fi === fl - 1) && (file[fi] === '') + } + + // should be unreachable. + /* istanbul ignore next */ + throw new Error('wtf?') + } + + braceExpand () { + return braceExpand(this.pattern, this.options) + } + + parse (pattern, isSub) { + assertValidPattern(pattern) + + const options = this.options + + // shortcuts + if (pattern === '**') { + if (!options.noglobstar) + return GLOBSTAR + else + pattern = '*' + } + if (pattern === '') return '' + + let re = '' + let hasMagic = false + let escaping = false + // ? => one single character + const patternListStack = [] + const negativeLists = [] + let stateChar + let inClass = false + let reClassStart = -1 + let classStart = -1 + let cs + let pl + let sp + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. However, if the pattern + // starts with ., then traversal patterns can match. + let dotTravAllowed = pattern.charAt(0) === '.' + let dotFileAllowed = options.dot || dotTravAllowed + const patternStart = () => + dotTravAllowed + ? '' + : dotFileAllowed + ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))' + : '(?!\\.)' + const subPatternStart = (p) => + p.charAt(0) === '.' + ? '' + : options.dot + ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))' + : '(?!\\.)' + + + const clearStateChar = () => { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + this.debug('clearStateChar %j %j', stateChar, re) + stateChar = false + } + } + + for (let i = 0, c; (i < pattern.length) && (c = pattern.charAt(i)); i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) + + // skip over any that are escaped. + if (escaping) { + /* istanbul ignore next - completely not allowed, even escaped. */ + if (c === '/') { + return false + } + + if (reSpecials[c]) { + re += '\\' + } + re += c + escaping = false + continue + } + + switch (c) { + /* istanbul ignore next */ + case '/': { + // Should already be path-split by now. + return false + } + + case '\\': + if (inClass && pattern.charAt(i + 1) === '-') { + re += c + continue + } + + clearStateChar() + escaping = true + continue + + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) + + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } + + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + this.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue + + case '(': { + if (inClass) { + re += '(' + continue + } + + if (!stateChar) { + re += '\\(' + continue + } + + const plEntry = { + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close, + } + this.debug(this.pattern, '\t', plEntry) + patternListStack.push(plEntry) + // negation is (?:(?!(?:js)(?:))[^/]*) + re += plEntry.open + // next entry starts with a dot maybe? + if (plEntry.start === 0 && plEntry.type !== '!') { + dotTravAllowed = true + re += subPatternStart(pattern.slice(i + 1)) + } + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue + } + + case ')': { + const plEntry = patternListStack[patternListStack.length - 1] + if (inClass || !plEntry) { + re += '\\)' + continue + } + patternListStack.pop() + + // closing an extglob + clearStateChar() + hasMagic = true + pl = plEntry + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close + if (pl.type === '!') { + negativeLists.push(Object.assign(pl, { reEnd: re.length })) + } + continue + } + + case '|': { + const plEntry = patternListStack[patternListStack.length - 1] + if (inClass || !plEntry) { + re += '\\|' + continue + } + + clearStateChar() + re += '|' + // next subpattern can start with a dot? + if (plEntry.start === 0 && plEntry.type !== '!') { + dotTravAllowed = true + re += subPatternStart(pattern.slice(i + 1)) + } + continue + } + + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() + + if (inClass) { + re += '\\' + c + continue + } + + inClass = true + classStart = i + reClassStart = re.length + re += c + continue + + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + continue + } + + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + braExpEscape(charUnescape(cs)) + ']') + // looks good, finish up the class. + re += c + } catch (er) { + // out of order ranges in JS are errors, but in glob syntax, + // they're just a range that matches nothing. + re = re.substring(0, reClassStart) + '(?:$.)' // match nothing ever + } + hasMagic = true + inClass = false + continue + + default: + // swallow any state char that wasn't consumed + clearStateChar() + + if (reSpecials[c] && !(c === '^' && inClass)) { + re += '\\' + } + + re += c + break + + } // switch + } // for + + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.slice(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substring(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] + } + + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + let tail + tail = re.slice(pl.reStart + pl.open.length) + this.debug('setting tail', re, pl) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => { + /* istanbul ignore else - should already be done */ + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) + + this.debug('tail=%j\n %s', tail, tail, pl, re) + const t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type + + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } + + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } + + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + const addPatternStart = addPatternStartSet[re.charAt(0)] + + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (let n = negativeLists.length - 1; n > -1; n--) { + const nl = negativeLists[n] + + const nlBefore = re.slice(0, nl.reStart) + const nlFirst = re.slice(nl.reStart, nl.reEnd - 8) + let nlAfter = re.slice(nl.reEnd) + const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter + + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + const closeParensBefore = nlBefore.split(')').length + const openParensBefore = nlBefore.split('(').length - closeParensBefore + let cleanAfter = nlAfter + for (let i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + } + nlAfter = cleanAfter + + const dollar = nlAfter === '' && isSub !== SUBPARSE ? '(?:$|\\/)' : '' + + re = nlBefore + nlFirst + nlAfter + dollar + nlLast + } + + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re + } + + if (addPatternStart) { + re = patternStart() + re + } + + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } + + // if it's nocase, and the lcase/uppercase don't match, it's magic + if (options.nocase && !hasMagic) { + hasMagic = pattern.toUpperCase() !== pattern.toLowerCase() + } + + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + + const flags = options.nocase ? 'i' : '' + try { + return Object.assign(new RegExp('^' + re + '$', flags), { + _glob: pattern, + _src: re, + }) + } catch (er) /* istanbul ignore next - should be impossible */ { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') + } + } + + makeRe () { + if (this.regexp || this.regexp === false) return this.regexp + + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + const set = this.set + + if (!set.length) { + this.regexp = false + return this.regexp + } + const options = this.options + + const twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + const flags = options.nocase ? 'i' : '' + + // coalesce globstars and regexpify non-globstar patterns + // if it's the only item, then we just do one twoStar + // if it's the first, and there are more, prepend (\/|twoStar\/)? to next + // if it's the last, append (\/twoStar|) to previous + // if it's in the middle, append (\/|\/twoStar\/) to previous + // then filter out GLOBSTAR symbols + let re = set.map(pattern => { + pattern = pattern.map(p => + typeof p === 'string' ? regExpEscape(p) + : p === GLOBSTAR ? GLOBSTAR + : p._src + ).reduce((set, p) => { + if (!(set[set.length - 1] === GLOBSTAR && p === GLOBSTAR)) { + set.push(p) + } + return set + }, []) + pattern.forEach((p, i) => { + if (p !== GLOBSTAR || pattern[i-1] === GLOBSTAR) { + return + } + if (i === 0) { + if (pattern.length > 1) { + pattern[i+1] = '(?:\\\/|' + twoStar + '\\\/)?' + pattern[i+1] + } else { + pattern[i] = twoStar + } + } else if (i === pattern.length - 1) { + pattern[i-1] += '(?:\\\/|' + twoStar + ')?' + } else { + pattern[i-1] += '(?:\\\/|\\\/' + twoStar + '\\\/)' + pattern[i+1] + pattern[i+1] = GLOBSTAR + } + }) + return pattern.filter(p => p !== GLOBSTAR).join('/') + }).join('|') + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' + + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' + + try { + this.regexp = new RegExp(re, flags) + } catch (ex) /* istanbul ignore next - should be impossible */ { + this.regexp = false + } + return this.regexp + } + + match (f, partial = this.partial) { + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' + + if (f === '/' && partial) return true + + const options = this.options + + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } + + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) + + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + + const set = this.set + this.debug(this.pattern, 'set', set) + + // Find the basename of the path by looking for the last non-empty segment + let filename + for (let i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break + } + + for (let i = 0; i < set.length; i++) { + const pattern = set[i] + let file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + const hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate + } + + static defaults (def) { + return minimatch.defaults(def).Minimatch + } +} + +minimatch.Minimatch = Minimatch diff --git a/node_modules/minimatch/package.json b/node_modules/minimatch/package.json new file mode 100644 index 0000000..c8809db --- /dev/null +++ b/node_modules/minimatch/package.json @@ -0,0 +1,35 @@ +{ + "author": "Isaac Z. Schlueter (http://blog.izs.me)", + "name": "minimatch", + "description": "a glob matcher in javascript", + "publishConfig": { + "tag": "legacy-v5" + }, + "version": "5.1.6", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/minimatch.git" + }, + "main": "minimatch.js", + "scripts": { + "test": "tap", + "snap": "tap", + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags" + }, + "engines": { + "node": ">=10" + }, + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "devDependencies": { + "tap": "^16.3.2" + }, + "license": "ISC", + "files": [ + "minimatch.js", + "lib" + ] +} diff --git a/node_modules/ms/index.js b/node_modules/ms/index.js new file mode 100644 index 0000000..ea734fb --- /dev/null +++ b/node_modules/ms/index.js @@ -0,0 +1,162 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function (val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} diff --git a/node_modules/ms/license.md b/node_modules/ms/license.md new file mode 100644 index 0000000..fa5d39b --- /dev/null +++ b/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 Vercel, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/ms/package.json b/node_modules/ms/package.json new file mode 100644 index 0000000..4997189 --- /dev/null +++ b/node_modules/ms/package.json @@ -0,0 +1,38 @@ +{ + "name": "ms", + "version": "2.1.3", + "description": "Tiny millisecond conversion utility", + "repository": "vercel/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "4.18.2", + "expect.js": "0.3.1", + "husky": "0.14.3", + "lint-staged": "5.0.0", + "mocha": "4.0.1", + "prettier": "2.0.5" + } +} diff --git a/node_modules/ms/readme.md b/node_modules/ms/readme.md new file mode 100644 index 0000000..0fc1abb --- /dev/null +++ b/node_modules/ms/readme.md @@ -0,0 +1,59 @@ +# ms + +![CI](https://github.com/vercel/ms/workflows/CI/badge.svg) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +ms('-3 days') // -259200000 +ms('-1h') // -3600000 +ms('-200') // -200 +``` + +### Convert from Milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(-3 * 60000) // "-3m" +ms(ms('10 hours')) // "10h" +``` + +### Time Format Written-Out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(-3 * 60000, { long: true }) // "-3 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [Node.js](https://nodejs.org) and in the browser +- If a number is supplied to `ms`, a string with a unit is returned +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`) +- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned + +## Related Packages + +- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time. + +## Caught a Bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/node_modules/negotiator/HISTORY.md b/node_modules/negotiator/HISTORY.md new file mode 100644 index 0000000..63d537d --- /dev/null +++ b/node_modules/negotiator/HISTORY.md @@ -0,0 +1,114 @@ +1.0.0 / 2024-08-31 +================== + + * Drop support for node <18 + * Added an option preferred encodings array #59 + +0.6.3 / 2022-01-22 +================== + + * Revert "Lazy-load modules from main entry point" + +0.6.2 / 2019-04-29 +================== + + * Fix sorting charset, encoding, and language with extra parameters + +0.6.1 / 2016-05-02 +================== + + * perf: improve `Accept` parsing speed + * perf: improve `Accept-Charset` parsing speed + * perf: improve `Accept-Encoding` parsing speed + * perf: improve `Accept-Language` parsing speed + +0.6.0 / 2015-09-29 +================== + + * Fix including type extensions in parameters in `Accept` parsing + * Fix parsing `Accept` parameters with quoted equals + * Fix parsing `Accept` parameters with quoted semicolons + * Lazy-load modules from main entry point + * perf: delay type concatenation until needed + * perf: enable strict mode + * perf: hoist regular expressions + * perf: remove closures getting spec properties + * perf: remove a closure from media type parsing + * perf: remove property delete from media type parsing + +0.5.3 / 2015-05-10 +================== + + * Fix media type parameter matching to be case-insensitive + +0.5.2 / 2015-05-06 +================== + + * Fix comparing media types with quoted values + * Fix splitting media types with quoted commas + +0.5.1 / 2015-02-14 +================== + + * Fix preference sorting to be stable for long acceptable lists + +0.5.0 / 2014-12-18 +================== + + * Fix list return order when large accepted list + * Fix missing identity encoding when q=0 exists + * Remove dynamic building of Negotiator class + +0.4.9 / 2014-10-14 +================== + + * Fix error when media type has invalid parameter + +0.4.8 / 2014-09-28 +================== + + * Fix all negotiations to be case-insensitive + * Stable sort preferences of same quality according to client order + * Support Node.js 0.6 + +0.4.7 / 2014-06-24 +================== + + * Handle invalid provided languages + * Handle invalid provided media types + +0.4.6 / 2014-06-11 +================== + + * Order by specificity when quality is the same + +0.4.5 / 2014-05-29 +================== + + * Fix regression in empty header handling + +0.4.4 / 2014-05-29 +================== + + * Fix behaviors when headers are not present + +0.4.3 / 2014-04-16 +================== + + * Handle slashes on media params correctly + +0.4.2 / 2014-02-28 +================== + + * Fix media type sorting + * Handle media types params strictly + +0.4.1 / 2014-01-16 +================== + + * Use most specific matches + +0.4.0 / 2014-01-09 +================== + + * Remove preferred prefix from methods diff --git a/node_modules/negotiator/LICENSE b/node_modules/negotiator/LICENSE new file mode 100644 index 0000000..ea6b9e2 --- /dev/null +++ b/node_modules/negotiator/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2014 Federico Romero +Copyright (c) 2012-2014 Isaac Z. Schlueter +Copyright (c) 2014-2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/negotiator/README.md b/node_modules/negotiator/README.md new file mode 100644 index 0000000..6fb7f2d --- /dev/null +++ b/node_modules/negotiator/README.md @@ -0,0 +1,212 @@ +# negotiator + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +An HTTP content negotiator for Node.js + +## Installation + +```sh +$ npm install negotiator +``` + +## API + +```js +var Negotiator = require('negotiator') +``` + +### Accept Negotiation + +```js +availableMediaTypes = ['text/html', 'text/plain', 'application/json'] + +// The negotiator constructor receives a request object +negotiator = new Negotiator(request) + +// Let's say Accept header is 'text/html, application/*;q=0.2, image/jpeg;q=0.8' + +negotiator.mediaTypes() +// -> ['text/html', 'image/jpeg', 'application/*'] + +negotiator.mediaTypes(availableMediaTypes) +// -> ['text/html', 'application/json'] + +negotiator.mediaType(availableMediaTypes) +// -> 'text/html' +``` + +You can check a working example at `examples/accept.js`. + +#### Methods + +##### mediaType() + +Returns the most preferred media type from the client. + +##### mediaType(availableMediaType) + +Returns the most preferred media type from a list of available media types. + +##### mediaTypes() + +Returns an array of preferred media types ordered by the client preference. + +##### mediaTypes(availableMediaTypes) + +Returns an array of preferred media types ordered by priority from a list of +available media types. + +### Accept-Language Negotiation + +```js +negotiator = new Negotiator(request) + +availableLanguages = ['en', 'es', 'fr'] + +// Let's say Accept-Language header is 'en;q=0.8, es, pt' + +negotiator.languages() +// -> ['es', 'pt', 'en'] + +negotiator.languages(availableLanguages) +// -> ['es', 'en'] + +language = negotiator.language(availableLanguages) +// -> 'es' +``` + +You can check a working example at `examples/language.js`. + +#### Methods + +##### language() + +Returns the most preferred language from the client. + +##### language(availableLanguages) + +Returns the most preferred language from a list of available languages. + +##### languages() + +Returns an array of preferred languages ordered by the client preference. + +##### languages(availableLanguages) + +Returns an array of preferred languages ordered by priority from a list of +available languages. + +### Accept-Charset Negotiation + +```js +availableCharsets = ['utf-8', 'iso-8859-1', 'iso-8859-5'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Charset header is 'utf-8, iso-8859-1;q=0.8, utf-7;q=0.2' + +negotiator.charsets() +// -> ['utf-8', 'iso-8859-1', 'utf-7'] + +negotiator.charsets(availableCharsets) +// -> ['utf-8', 'iso-8859-1'] + +negotiator.charset(availableCharsets) +// -> 'utf-8' +``` + +You can check a working example at `examples/charset.js`. + +#### Methods + +##### charset() + +Returns the most preferred charset from the client. + +##### charset(availableCharsets) + +Returns the most preferred charset from a list of available charsets. + +##### charsets() + +Returns an array of preferred charsets ordered by the client preference. + +##### charsets(availableCharsets) + +Returns an array of preferred charsets ordered by priority from a list of +available charsets. + +### Accept-Encoding Negotiation + +```js +availableEncodings = ['identity', 'gzip'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Encoding header is 'gzip, compress;q=0.2, identity;q=0.5' + +negotiator.encodings() +// -> ['gzip', 'identity', 'compress'] + +negotiator.encodings(availableEncodings) +// -> ['gzip', 'identity'] + +negotiator.encoding(availableEncodings) +// -> 'gzip' +``` + +You can check a working example at `examples/encoding.js`. + +#### Methods + +##### encoding() + +Returns the most preferred encoding from the client. + +##### encoding(availableEncodings) + +Returns the most preferred encoding from a list of available encodings. + +##### encoding(availableEncodings, { preferred }) + +Returns the most preferred encoding from a list of available encodings, while prioritizing based on `preferred` array between same-quality encodings. + +##### encodings() + +Returns an array of preferred encodings ordered by the client preference. + +##### encodings(availableEncodings) + +Returns an array of preferred encodings ordered by priority from a list of +available encodings. + +##### encodings(availableEncodings, { preferred }) + +Returns an array of preferred encodings ordered by priority from a list of +available encodings, while prioritizing based on `preferred` array between same-quality encodings. + +## See Also + +The [accepts](https://npmjs.org/package/accepts#readme) module builds on +this module and provides an alternative interface, mime type validation, +and more. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/negotiator.svg +[npm-url]: https://npmjs.org/package/negotiator +[node-version-image]: https://img.shields.io/node/v/negotiator.svg +[node-version-url]: https://nodejs.org/en/download/ +[coveralls-image]: https://img.shields.io/coveralls/jshttp/negotiator/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/negotiator?branch=master +[downloads-image]: https://img.shields.io/npm/dm/negotiator.svg +[downloads-url]: https://npmjs.org/package/negotiator +[github-actions-ci-image]: https://img.shields.io/github/workflow/status/jshttp/negotiator/ci/master?label=ci +[github-actions-ci-url]: https://github.com/jshttp/negotiator/actions/workflows/ci.yml diff --git a/node_modules/negotiator/index.js b/node_modules/negotiator/index.js new file mode 100644 index 0000000..4f51315 --- /dev/null +++ b/node_modules/negotiator/index.js @@ -0,0 +1,83 @@ +/*! + * negotiator + * Copyright(c) 2012 Federico Romero + * Copyright(c) 2012-2014 Isaac Z. Schlueter + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +var preferredCharsets = require('./lib/charset') +var preferredEncodings = require('./lib/encoding') +var preferredLanguages = require('./lib/language') +var preferredMediaTypes = require('./lib/mediaType') + +/** + * Module exports. + * @public + */ + +module.exports = Negotiator; +module.exports.Negotiator = Negotiator; + +/** + * Create a Negotiator instance from a request. + * @param {object} request + * @public + */ + +function Negotiator(request) { + if (!(this instanceof Negotiator)) { + return new Negotiator(request); + } + + this.request = request; +} + +Negotiator.prototype.charset = function charset(available) { + var set = this.charsets(available); + return set && set[0]; +}; + +Negotiator.prototype.charsets = function charsets(available) { + return preferredCharsets(this.request.headers['accept-charset'], available); +}; + +Negotiator.prototype.encoding = function encoding(available, opts) { + var set = this.encodings(available, opts); + return set && set[0]; +}; + +Negotiator.prototype.encodings = function encodings(available, options) { + var opts = options || {}; + return preferredEncodings(this.request.headers['accept-encoding'], available, opts.preferred); +}; + +Negotiator.prototype.language = function language(available) { + var set = this.languages(available); + return set && set[0]; +}; + +Negotiator.prototype.languages = function languages(available) { + return preferredLanguages(this.request.headers['accept-language'], available); +}; + +Negotiator.prototype.mediaType = function mediaType(available) { + var set = this.mediaTypes(available); + return set && set[0]; +}; + +Negotiator.prototype.mediaTypes = function mediaTypes(available) { + return preferredMediaTypes(this.request.headers.accept, available); +}; + +// Backwards compatibility +Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; +Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; +Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; +Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; +Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; +Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; +Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; +Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; diff --git a/node_modules/negotiator/lib/charset.js b/node_modules/negotiator/lib/charset.js new file mode 100644 index 0000000..cdd0148 --- /dev/null +++ b/node_modules/negotiator/lib/charset.js @@ -0,0 +1,169 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredCharsets; +module.exports.preferredCharsets = preferredCharsets; + +/** + * Module variables. + * @private + */ + +var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Charset header. + * @private + */ + +function parseAcceptCharset(accept) { + var accepts = accept.split(','); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var charset = parseCharset(accepts[i].trim(), i); + + if (charset) { + accepts[j++] = charset; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a charset from the Accept-Charset header. + * @private + */ + +function parseCharset(str, i) { + var match = simpleCharsetRegExp.exec(str); + if (!match) return null; + + var charset = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';') + for (var j = 0; j < params.length; j++) { + var p = params[j].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + charset: charset, + q: q, + i: i + }; +} + +/** + * Get the priority of a charset. + * @private + */ + +function getCharsetPriority(charset, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(charset, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the charset. + * @private + */ + +function specify(charset, spec, index) { + var s = 0; + if(spec.charset.toLowerCase() === charset.toLowerCase()){ + s |= 1; + } else if (spec.charset !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +} + +/** + * Get the preferred charsets from an Accept-Charset header. + * @public + */ + +function preferredCharsets(accept, provided) { + // RFC 2616 sec 14.2: no header = * + var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || ''); + + if (!provided) { + // sorted list of all charsets + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullCharset); + } + + var priorities = provided.map(function getPriority(type, index) { + return getCharsetPriority(type, accepts, index); + }); + + // sorted list of accepted charsets + return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full charset string. + * @private + */ + +function getFullCharset(spec) { + return spec.charset; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/node_modules/negotiator/lib/encoding.js b/node_modules/negotiator/lib/encoding.js new file mode 100644 index 0000000..9ebb633 --- /dev/null +++ b/node_modules/negotiator/lib/encoding.js @@ -0,0 +1,205 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredEncodings; +module.exports.preferredEncodings = preferredEncodings; + +/** + * Module variables. + * @private + */ + +var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Encoding header. + * @private + */ + +function parseAcceptEncoding(accept) { + var accepts = accept.split(','); + var hasIdentity = false; + var minQuality = 1; + + for (var i = 0, j = 0; i < accepts.length; i++) { + var encoding = parseEncoding(accepts[i].trim(), i); + + if (encoding) { + accepts[j++] = encoding; + hasIdentity = hasIdentity || specify('identity', encoding); + minQuality = Math.min(minQuality, encoding.q || 1); + } + } + + if (!hasIdentity) { + /* + * If identity doesn't explicitly appear in the accept-encoding header, + * it's added to the list of acceptable encoding with the lowest q + */ + accepts[j++] = { + encoding: 'identity', + q: minQuality, + i: i + }; + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse an encoding from the Accept-Encoding header. + * @private + */ + +function parseEncoding(str, i) { + var match = simpleEncodingRegExp.exec(str); + if (!match) return null; + + var encoding = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';'); + for (var j = 0; j < params.length; j++) { + var p = params[j].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + encoding: encoding, + q: q, + i: i + }; +} + +/** + * Get the priority of an encoding. + * @private + */ + +function getEncodingPriority(encoding, accepted, index) { + var priority = {encoding: encoding, o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(encoding, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the encoding. + * @private + */ + +function specify(encoding, spec, index) { + var s = 0; + if(spec.encoding.toLowerCase() === encoding.toLowerCase()){ + s |= 1; + } else if (spec.encoding !== '*' ) { + return null + } + + return { + encoding: encoding, + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +/** + * Get the preferred encodings from an Accept-Encoding header. + * @public + */ + +function preferredEncodings(accept, provided, preferred) { + var accepts = parseAcceptEncoding(accept || ''); + + var comparator = preferred ? function comparator (a, b) { + if (a.q !== b.q) { + return b.q - a.q // higher quality first + } + + var aPreferred = preferred.indexOf(a.encoding) + var bPreferred = preferred.indexOf(b.encoding) + + if (aPreferred === -1 && bPreferred === -1) { + // consider the original specifity/order + return (b.s - a.s) || (a.o - b.o) || (a.i - b.i) + } + + if (aPreferred !== -1 && bPreferred !== -1) { + return aPreferred - bPreferred // consider the preferred order + } + + return aPreferred === -1 ? 1 : -1 // preferred first + } : compareSpecs; + + if (!provided) { + // sorted list of all encodings + return accepts + .filter(isQuality) + .sort(comparator) + .map(getFullEncoding); + } + + var priorities = provided.map(function getPriority(type, index) { + return getEncodingPriority(type, accepts, index); + }); + + // sorted list of accepted encodings + return priorities.filter(isQuality).sort(comparator).map(function getEncoding(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i); +} + +/** + * Get full encoding string. + * @private + */ + +function getFullEncoding(spec) { + return spec.encoding; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/node_modules/negotiator/lib/language.js b/node_modules/negotiator/lib/language.js new file mode 100644 index 0000000..a231672 --- /dev/null +++ b/node_modules/negotiator/lib/language.js @@ -0,0 +1,179 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredLanguages; +module.exports.preferredLanguages = preferredLanguages; + +/** + * Module variables. + * @private + */ + +var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Language header. + * @private + */ + +function parseAcceptLanguage(accept) { + var accepts = accept.split(','); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var language = parseLanguage(accepts[i].trim(), i); + + if (language) { + accepts[j++] = language; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a language from the Accept-Language header. + * @private + */ + +function parseLanguage(str, i) { + var match = simpleLanguageRegExp.exec(str); + if (!match) return null; + + var prefix = match[1] + var suffix = match[2] + var full = prefix + + if (suffix) full += "-" + suffix; + + var q = 1; + if (match[3]) { + var params = match[3].split(';') + for (var j = 0; j < params.length; j++) { + var p = params[j].split('='); + if (p[0] === 'q') q = parseFloat(p[1]); + } + } + + return { + prefix: prefix, + suffix: suffix, + q: q, + i: i, + full: full + }; +} + +/** + * Get the priority of a language. + * @private + */ + +function getLanguagePriority(language, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(language, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the language. + * @private + */ + +function specify(language, spec, index) { + var p = parseLanguage(language) + if (!p) return null; + var s = 0; + if(spec.full.toLowerCase() === p.full.toLowerCase()){ + s |= 4; + } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) { + s |= 2; + } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) { + s |= 1; + } else if (spec.full !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +/** + * Get the preferred languages from an Accept-Language header. + * @public + */ + +function preferredLanguages(accept, provided) { + // RFC 2616 sec 14.4: no header = * + var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); + + if (!provided) { + // sorted list of all languages + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullLanguage); + } + + var priorities = provided.map(function getPriority(type, index) { + return getLanguagePriority(type, accepts, index); + }); + + // sorted list of accepted languages + return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full language string. + * @private + */ + +function getFullLanguage(spec) { + return spec.full; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/node_modules/negotiator/lib/mediaType.js b/node_modules/negotiator/lib/mediaType.js new file mode 100644 index 0000000..8e402ea --- /dev/null +++ b/node_modules/negotiator/lib/mediaType.js @@ -0,0 +1,294 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredMediaTypes; +module.exports.preferredMediaTypes = preferredMediaTypes; + +/** + * Module variables. + * @private + */ + +var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept header. + * @private + */ + +function parseAccept(accept) { + var accepts = splitMediaTypes(accept); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var mediaType = parseMediaType(accepts[i].trim(), i); + + if (mediaType) { + accepts[j++] = mediaType; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a media type from the Accept header. + * @private + */ + +function parseMediaType(str, i) { + var match = simpleMediaTypeRegExp.exec(str); + if (!match) return null; + + var params = Object.create(null); + var q = 1; + var subtype = match[2]; + var type = match[1]; + + if (match[3]) { + var kvps = splitParameters(match[3]).map(splitKeyValuePair); + + for (var j = 0; j < kvps.length; j++) { + var pair = kvps[j]; + var key = pair[0].toLowerCase(); + var val = pair[1]; + + // get the value, unwrapping quotes + var value = val && val[0] === '"' && val[val.length - 1] === '"' + ? val.slice(1, -1) + : val; + + if (key === 'q') { + q = parseFloat(value); + break; + } + + // store parameter + params[key] = value; + } + } + + return { + type: type, + subtype: subtype, + params: params, + q: q, + i: i + }; +} + +/** + * Get the priority of a media type. + * @private + */ + +function getMediaTypePriority(type, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(type, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the media type. + * @private + */ + +function specify(type, spec, index) { + var p = parseMediaType(type); + var s = 0; + + if (!p) { + return null; + } + + if(spec.type.toLowerCase() == p.type.toLowerCase()) { + s |= 4 + } else if(spec.type != '*') { + return null; + } + + if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) { + s |= 2 + } else if(spec.subtype != '*') { + return null; + } + + var keys = Object.keys(spec.params); + if (keys.length > 0) { + if (keys.every(function (k) { + return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase(); + })) { + s |= 1 + } else { + return null + } + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s, + } +} + +/** + * Get the preferred media types from an Accept header. + * @public + */ + +function preferredMediaTypes(accept, provided) { + // RFC 2616 sec 14.2: no header = */* + var accepts = parseAccept(accept === undefined ? '*/*' : accept || ''); + + if (!provided) { + // sorted list of all types + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullType); + } + + var priorities = provided.map(function getPriority(type, index) { + return getMediaTypePriority(type, accepts, index); + }); + + // sorted list of accepted types + return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full type string. + * @private + */ + +function getFullType(spec) { + return spec.type + '/' + spec.subtype; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} + +/** + * Count the number of quotes in a string. + * @private + */ + +function quoteCount(string) { + var count = 0; + var index = 0; + + while ((index = string.indexOf('"', index)) !== -1) { + count++; + index++; + } + + return count; +} + +/** + * Split a key value pair. + * @private + */ + +function splitKeyValuePair(str) { + var index = str.indexOf('='); + var key; + var val; + + if (index === -1) { + key = str; + } else { + key = str.slice(0, index); + val = str.slice(index + 1); + } + + return [key, val]; +} + +/** + * Split an Accept header into media types. + * @private + */ + +function splitMediaTypes(accept) { + var accepts = accept.split(','); + + for (var i = 1, j = 0; i < accepts.length; i++) { + if (quoteCount(accepts[j]) % 2 == 0) { + accepts[++j] = accepts[i]; + } else { + accepts[j] += ',' + accepts[i]; + } + } + + // trim accepts + accepts.length = j + 1; + + return accepts; +} + +/** + * Split a string of parameters. + * @private + */ + +function splitParameters(str) { + var parameters = str.split(';'); + + for (var i = 1, j = 0; i < parameters.length; i++) { + if (quoteCount(parameters[j]) % 2 == 0) { + parameters[++j] = parameters[i]; + } else { + parameters[j] += ';' + parameters[i]; + } + } + + // trim parameters + parameters.length = j + 1; + + for (var i = 0; i < parameters.length; i++) { + parameters[i] = parameters[i].trim(); + } + + return parameters; +} diff --git a/node_modules/negotiator/package.json b/node_modules/negotiator/package.json new file mode 100644 index 0000000..e4bdc1e --- /dev/null +++ b/node_modules/negotiator/package.json @@ -0,0 +1,43 @@ +{ + "name": "negotiator", + "description": "HTTP content negotiation", + "version": "1.0.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Federico Romero ", + "Isaac Z. Schlueter (http://blog.izs.me/)" + ], + "license": "MIT", + "keywords": [ + "http", + "content negotiation", + "accept", + "accept-language", + "accept-encoding", + "accept-charset" + ], + "repository": "jshttp/negotiator", + "devDependencies": { + "eslint": "7.32.0", + "eslint-plugin-markdown": "2.2.1", + "mocha": "9.1.3", + "nyc": "15.1.0" + }, + "files": [ + "lib/", + "HISTORY.md", + "LICENSE", + "index.js", + "README.md" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test:debug": "mocha --reporter spec --check-leaks --inspect --inspect-brk test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/nostr-tools/LICENSE b/node_modules/nostr-tools/LICENSE new file mode 100644 index 0000000..3c577b0 --- /dev/null +++ b/node_modules/nostr-tools/LICENSE @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to \ No newline at end of file diff --git a/node_modules/nostr-tools/README.md b/node_modules/nostr-tools/README.md new file mode 100644 index 0000000..e2867b1 --- /dev/null +++ b/node_modules/nostr-tools/README.md @@ -0,0 +1,383 @@ +# ![](https://img.shields.io/github/actions/workflow/status/nbd-wtf/nostr-tools/test.yml) [![JSR](https://jsr.io/badges/@nostr/tools)](https://jsr.io/@nostr/tools) nostr-tools + +Tools for developing [Nostr](https://github.com/fiatjaf/nostr) clients. + +Only depends on _@scure_ and _@noble_ packages. + +This package is only providing lower-level functionality. If you want higher-level features, take a look at [@nostr/gadgets](https://jsr.io/@nostr/gadgets) which is based on this library and expands upon it and has other goodies (it's only available on jsr). + +## Installation + +```bash +# npm +npm install --save nostr-tools + +# jsr +npx jsr add @nostr/tools +``` + +If using TypeScript, this package requires TypeScript >= 5.0. + +## Documentation + +https://jsr.io/@nostr/tools/doc + +## Usage + +### Generating a private key and a public key + +```js +import { generateSecretKey, getPublicKey } from 'nostr-tools/pure' + +let sk = generateSecretKey() // `sk` is a Uint8Array +let pk = getPublicKey(sk) // `pk` is a hex string +``` + +To get the secret key in hex format, use + +```js +import { bytesToHex, hexToBytes } from '@noble/hashes/utils' // already an installed dependency + +let skHex = bytesToHex(sk) +let backToBytes = hexToBytes(skHex) +``` + +### Creating, signing and verifying events + +```js +import { finalizeEvent, verifyEvent } from 'nostr-tools/pure' + +let event = finalizeEvent({ + kind: 1, + created_at: Math.floor(Date.now() / 1000), + tags: [], + content: 'hello', +}, sk) + +let isGood = verifyEvent(event) +``` + +### Interacting with one or multiple relays + +Doesn't matter what you do, you always should be using a `SimplePool`: + +```js +import { finalizeEvent, generateSecretKey, getPublicKey } from 'nostr-tools/pure' +import { SimplePool } from 'nostr-tools/pool' + +const pool = new SimplePool() + +const relays = ['wss://relay.example.com', 'wss://relay.example2.com'] + +// let's query for one event that exists +const event = pool.get( + relays, + { + ids: ['d7dd5eb3ab747e16f8d0212d53032ea2a7cadef53837e5a6c66d42849fcb9027'], + }, +) +if (event) { + console.log('it exists indeed on this relay:', event) +} + +// let's query for more than one event that exists +const events = pool.querySync( + relays, + { + kinds: [1], + limit: 10 + }, +) +if (events) { + console.log('it exists indeed on this relay:', events) +} + +// let's publish a new event while simultaneously monitoring the relay for it +let sk = generateSecretKey() +let pk = getPublicKey(sk) + +pool.subscribe( + ['wss://a.com', 'wss://b.com', 'wss://c.com'], + { + kinds: [1], + authors: [pk], + }, + { + onevent(event) { + console.log('got event:', event) + } + } +) + +let eventTemplate = { + kind: 1, + created_at: Math.floor(Date.now() / 1000), + tags: [], + content: 'hello world', +} + +// this assigns the pubkey, calculates the event id and signs the event in a single step +const signedEvent = finalizeEvent(eventTemplate, sk) +await Promise.any(pool.publish(['wss://a.com', 'wss://b.com'], signedEvent)) + +relay.close() +``` + +To use this on Node.js you first must install `ws` and call something like this: + +```js +import { useWebSocketImplementation } from 'nostr-tools/pool' +// or import { useWebSocketImplementation } from 'nostr-tools/relay' if you're using the Relay directly + +import WebSocket from 'ws' +useWebSocketImplementation(WebSocket) +``` + +You can enable regular pings of connected relays with the `enablePing` option. This will set up a heartbeat that closes the websocket if it doesn't receive a response in time. Some platforms don't report websocket disconnections due to network issues, and enabling this can increase reliability. + +```js +import { SimplePool } from 'nostr-tools/pool' + +const pool = new SimplePool({ enablePing: true }) +``` + +### Parsing references (mentions) from a content based on NIP-27 + +```js +import * as nip27 from '@nostr/tools/nip27' + +for (let block of nip27.parse(evt.content)) { + switch (block.type) { + case 'text': + console.log(block.text) + break + case 'reference': { + if ('id' in block.pointer) { + console.log("it's a nevent1 uri", block.pointer) + } else if ('identifier' in block.pointer) { + console.log("it's a naddr1 uri", block.pointer) + } else { + console.log("it's an npub1 or nprofile1 uri", block.pointer) + } + break + } + case 'url': { + console.log("it's a normal url:", block.url) + break + } + case 'image': + case 'video': + case 'audio': + console.log("it's a media url:", block.url) + case 'relay': + console.log("it's a websocket url, probably a relay address:", block.url) + default: + break + } +} +``` + +### Connecting to a bunker using NIP-46 + +```js +import { generateSecretKey, getPublicKey } from '@nostr/tools/pure' +import { BunkerSigner, parseBunkerInput } from '@nostr/tools/nip46' +import { SimplePool } from '@nostr/tools/pool' + +// the client needs a local secret key (which is generally persisted) for communicating with the bunker +const localSecretKey = generateSecretKey() + +// parse a bunker URI +const bunkerPointer = await parseBunkerInput('bunker://abcd...?relay=wss://relay.example.com') +if (!bunkerPointer) { + throw new Error('Invalid bunker input') +} + +// create the bunker instance +const pool = new SimplePool() +const bunker = new BunkerSigner(localSecretKey, bunkerPointer, { pool }) +await bunker.connect() + +// and use it +const pubkey = await bunker.getPublicKey() +const event = await bunker.signEvent({ + kind: 1, + created_at: Math.floor(Date.now() / 1000), + tags: [], + content: 'Hello from bunker!' +}) + +// cleanup +await signer.close() +pool.close([]) +``` + +### Parsing thread from any note based on NIP-10 + +```js +import * as nip10 from '@nostr/tools/nip10' + +// event is a nostr event with tags +const refs = nip10.parse(event) + +// get the root event of the thread +if (refs.root) { + console.log('root event:', refs.root.id) + console.log('root event relay hints:', refs.root.relays) + console.log('root event author:', refs.root.author) +} + +// get the immediate parent being replied to +if (refs.reply) { + console.log('reply to:', refs.reply.id) + console.log('reply relay hints:', refs.reply.relays) + console.log('reply author:', refs.reply.author) +} + +// get any mentioned events +for (let mention of refs.mentions) { + console.log('mentioned event:', mention.id) + console.log('mention relay hints:', mention.relays) + console.log('mention author:', mention.author) +} + +// get any quoted events +for (let quote of refs.quotes) { + console.log('quoted event:', quote.id) + console.log('quote relay hints:', quote.relays) +} + +// get any referenced profiles +for (let profile of refs.profiles) { + console.log('referenced profile:', profile.pubkey) + console.log('profile relay hints:', profile.relays) +} +``` + +### Querying profile data from a NIP-05 address + +```js +import { queryProfile } from 'nostr-tools/nip05' + +let profile = await queryProfile('jb55.com') +console.log(profile.pubkey) +// prints: 32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245 +console.log(profile.relays) +// prints: [wss://relay.damus.io] +``` + +To use this on Node.js < v18, you first must install `node-fetch@2` and call something like this: + +```js +import { useFetchImplementation } from 'nostr-tools/nip05' +useFetchImplementation(require('node-fetch')) +``` + +### Including NIP-07 types +```js +import type { WindowNostr } from 'nostr-tools/nip07' + +declare global { + interface Window { + nostr?: WindowNostr; + } +} +``` + +### Encoding and decoding NIP-19 codes + +```js +import { generateSecretKey, getPublicKey } from 'nostr-tools/pure' +import * as nip19 from 'nostr-tools/nip19' + +let sk = generateSecretKey() +let nsec = nip19.nsecEncode(sk) +let { type, data } = nip19.decode(nsec) +assert(type === 'nsec') +assert(data === sk) + +let pk = getPublicKey(generateSecretKey()) +let npub = nip19.npubEncode(pk) +let { type, data } = nip19.decode(npub) +assert(type === 'npub') +assert(data === pk) + +let pk = getPublicKey(generateSecretKey()) +let relays = ['wss://relay.nostr.example.mydomain.example.com', 'wss://nostr.banana.com'] +let nprofile = nip19.nprofileEncode({ pubkey: pk, relays }) +let { type, data } = nip19.decode(nprofile) +assert(type === 'nprofile') +assert(data.pubkey === pk) +assert(data.relays.length === 2) +``` + +### Using it with `nostr-wasm` + +[`nostr-wasm`](https://github.com/fiatjaf/nostr-wasm) is a thin wrapper over [libsecp256k1](https://github.com/bitcoin-core/secp256k1) compiled to WASM just for hashing, signing and verifying Nostr events. + +```js +import { setNostrWasm, generateSecretKey, finalizeEvent, verifyEvent } from 'nostr-tools/wasm' +import { initNostrWasm } from 'nostr-wasm' + +// make sure this promise resolves before your app starts calling finalizeEvent or verifyEvent +initNostrWasm().then(setNostrWasm) + +// or use 'nostr-wasm/gzipped' or even 'nostr-wasm/headless', +// see https://www.npmjs.com/package/nostr-wasm for options +``` + +If you're going to use `Relay` and `SimplePool` you must also import `nostr-tools/abstract-relay` and/or `nostr-tools/abstract-pool` instead of the defaults and then instantiate them by passing the `verifyEvent`: + +```js +import { setNostrWasm, verifyEvent } from 'nostr-tools/wasm' +import { AbstractRelay } from 'nostr-tools/abstract-relay' +import { AbstractSimplePool } from 'nostr-tools/abstract-pool' +import { initNostrWasm } from 'nostr-wasm' + +initNostrWasm().then(setNostrWasm) + +const relay = AbstractRelay.connect('wss://relayable.org', { verifyEvent }) +const pool = new AbstractSimplePool({ verifyEvent }) +``` + +This may be faster than the pure-JS [noble libraries](https://paulmillr.com/noble/) used by default and in `nostr-tools/pure`. Benchmarks: + +``` +benchmark time (avg) (min … max) p75 p99 p995 +------------------------------------------------- ----------------------------- +• relay read message and verify event (many events) +------------------------------------------------- ----------------------------- +wasm 34.94 ms/iter (34.61 ms … 35.73 ms) 35.07 ms 35.73 ms 35.73 ms +pure js 239.7 ms/iter (235.41 ms … 243.69 ms) 240.51 ms 243.69 ms 243.69 ms +trusted 402.71 µs/iter (344.57 µs … 2.98 ms) 407.39 µs 745.62 µs 812.59 µs + +summary for relay read message and verify event + wasm + 86.77x slower than trusted + 6.86x faster than pure js +``` + +### Using from the browser (if you don't want to use a bundler) + +```html + + +``` + +## Plumbing + +To develop `nostr-tools`, install [`just`](https://just.systems/) and run `just -l` to see commands available. + +## License + +This is free and unencumbered software released into the public domain. By submitting patches to this project, you agree to dedicate any and all copyright interest in this software to the public domain. + +## Contributing to this repository + +Use NIP-34 to send your patches to: + +``` +naddr1qq9kummnw3ez6ar0dak8xqg5waehxw309aex2mrp0yhxummnw3ezucn8qyt8wumn8ghj7un9d3shjtnwdaehgu3wvfskueqpzemhxue69uhhyetvv9ujuurjd9kkzmpwdejhgq3q80cvv07tjdrrgpa0j7j7tmnyl2yr6yr7l8j4s3evf6u64th6gkwsxpqqqpmejdv00jq +``` diff --git a/node_modules/nostr-tools/lib/cjs/abstract-pool.js b/node_modules/nostr-tools/lib/cjs/abstract-pool.js new file mode 100644 index 0000000..490b3f5 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/abstract-pool.js @@ -0,0 +1,793 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// abstract-pool.ts +var abstract_pool_exports = {}; +__export(abstract_pool_exports, { + AbstractSimplePool: () => AbstractSimplePool +}); +module.exports = __toCommonJS(abstract_pool_exports); + +// core.ts +var verifiedSymbol = Symbol("verified"); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); +function normalizeURL(url) { + try { + if (url.indexOf("://") === -1) + url = "wss://" + url; + let p = new URL(url); + p.pathname = p.pathname.replace(/\/+/g, "/"); + if (p.pathname.endsWith("/")) + p.pathname = p.pathname.slice(0, -1); + if (p.port === "80" && p.protocol === "ws:" || p.port === "443" && p.protocol === "wss:") + p.port = ""; + p.searchParams.sort(); + p.hash = ""; + return p.toString(); + } catch (e) { + throw new Error(`Invalid URL: ${url}`); + } +} +var QueueNode = class { + value; + next = null; + prev = null; + constructor(message) { + this.value = message; + } +}; +var Queue = class { + first; + last; + constructor() { + this.first = null; + this.last = null; + } + enqueue(value) { + const newNode = new QueueNode(value); + if (!this.last) { + this.first = newNode; + this.last = newNode; + } else if (this.last === this.first) { + this.last = newNode; + this.last.prev = this.first; + this.first.next = newNode; + } else { + newNode.prev = this.last; + this.last.next = newNode; + this.last = newNode; + } + return true; + } + dequeue() { + if (!this.first) + return null; + if (this.first === this.last) { + const target2 = this.first; + this.first = null; + this.last = null; + return target2.value; + } + const target = this.first; + this.first = target.next; + if (this.first) { + this.first.prev = null; + } + return target.value; + } +}; + +// kinds.ts +var ClientAuth = 22242; + +// filter.ts +function matchFilter(filter, event) { + if (filter.ids && filter.ids.indexOf(event.id) === -1) { + return false; + } + if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) { + return false; + } + if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) { + return false; + } + for (let f in filter) { + if (f[0] === "#") { + let tagName = f.slice(1); + let values = filter[`#${tagName}`]; + if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values.indexOf(v) !== -1)) + return false; + } + } + if (filter.since && event.created_at < filter.since) + return false; + if (filter.until && event.created_at > filter.until) + return false; + return true; +} +function matchFilters(filters, event) { + for (let i = 0; i < filters.length; i++) { + if (matchFilter(filters[i], event)) { + return true; + } + } + return false; +} + +// fakejson.ts +function getHex64(json, field) { + let len = field.length + 3; + let idx = json.indexOf(`"${field}":`) + len; + let s = json.slice(idx).indexOf(`"`) + idx + 1; + return json.slice(s, s + 64); +} +function getSubscriptionId(json) { + let idx = json.slice(0, 22).indexOf(`"EVENT"`); + if (idx === -1) + return null; + let pstart = json.slice(idx + 7 + 1).indexOf(`"`); + if (pstart === -1) + return null; + let start = idx + 7 + 1 + pstart; + let pend = json.slice(start + 1, 80).indexOf(`"`); + if (pend === -1) + return null; + let end = start + 1 + pend; + return json.slice(start + 1, end); +} + +// nip42.ts +function makeAuthEvent(relayURL, challenge) { + return { + kind: ClientAuth, + created_at: Math.floor(Date.now() / 1e3), + tags: [ + ["relay", relayURL], + ["challenge", challenge] + ], + content: "" + }; +} + +// helpers.ts +async function yieldThread() { + return new Promise((resolve) => { + const ch = new MessageChannel(); + const handler = () => { + ch.port1.removeEventListener("message", handler); + resolve(); + }; + ch.port1.addEventListener("message", handler); + ch.port2.postMessage(0); + ch.port1.start(); + }); +} +var alwaysTrue = (t) => { + t[verifiedSymbol] = true; + return true; +}; + +// abstract-relay.ts +var SendingOnClosedConnection = class extends Error { + constructor(message, relay) { + super(`Tried to send message '${message} on a closed connection to ${relay}.`); + this.name = "SendingOnClosedConnection"; + } +}; +var AbstractRelay = class { + url; + _connected = false; + onclose = null; + onnotice = (msg) => console.debug(`NOTICE from ${this.url}: ${msg}`); + baseEoseTimeout = 4400; + connectionTimeout = 4400; + publishTimeout = 4400; + pingFrequency = 2e4; + pingTimeout = 2e4; + openSubs = /* @__PURE__ */ new Map(); + enablePing; + connectionTimeoutHandle; + connectionPromise; + openCountRequests = /* @__PURE__ */ new Map(); + openEventPublishes = /* @__PURE__ */ new Map(); + ws; + incomingMessageQueue = new Queue(); + queueRunning = false; + challenge; + authPromise; + serial = 0; + verifyEvent; + _WebSocket; + constructor(url, opts) { + this.url = normalizeURL(url); + this.verifyEvent = opts.verifyEvent; + this._WebSocket = opts.websocketImplementation || WebSocket; + this.enablePing = opts.enablePing; + } + static async connect(url, opts) { + const relay = new AbstractRelay(url, opts); + await relay.connect(); + return relay; + } + closeAllSubscriptions(reason) { + for (let [_, sub] of this.openSubs) { + sub.close(reason); + } + this.openSubs.clear(); + for (let [_, ep] of this.openEventPublishes) { + ep.reject(new Error(reason)); + } + this.openEventPublishes.clear(); + for (let [_, cr] of this.openCountRequests) { + cr.reject(new Error(reason)); + } + this.openCountRequests.clear(); + } + get connected() { + return this._connected; + } + async connect() { + if (this.connectionPromise) + return this.connectionPromise; + this.challenge = void 0; + this.authPromise = void 0; + this.connectionPromise = new Promise((resolve, reject) => { + this.connectionTimeoutHandle = setTimeout(() => { + reject("connection timed out"); + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection timed out"); + }, this.connectionTimeout); + try { + this.ws = new this._WebSocket(this.url); + } catch (err) { + clearTimeout(this.connectionTimeoutHandle); + reject(err); + return; + } + this.ws.onopen = () => { + clearTimeout(this.connectionTimeoutHandle); + this._connected = true; + if (this.enablePing) { + this.pingpong(); + } + resolve(); + }; + this.ws.onerror = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket error"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection errored"); + } + }; + this.ws.onclose = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket closed"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection closed"); + } + }; + this.ws.onmessage = this._onmessage.bind(this); + }); + return this.connectionPromise; + } + async waitForPingPong() { + return new Promise((res, err) => { + ; + this.ws && this.ws.on && this.ws.on("pong", () => res(true)) || err("ws can't listen for pong"); + this.ws && this.ws.ping && this.ws.ping(); + }); + } + async waitForDummyReq() { + return new Promise((resolve, _) => { + const sub = this.subscribe([{ ids: ["a".repeat(64)] }], { + oneose: () => { + sub.close(); + resolve(true); + }, + eoseTimeout: this.pingTimeout + 1e3 + }); + }); + } + async pingpong() { + if (this.ws?.readyState === 1) { + const result = await Promise.any([ + this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(), + new Promise((res) => setTimeout(() => res(false), this.pingTimeout)) + ]); + if (result) { + setTimeout(() => this.pingpong(), this.pingFrequency); + } else { + this.closeAllSubscriptions("pingpong timed out"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + } + } + async runQueue() { + this.queueRunning = true; + while (true) { + if (false === this.handleNext()) { + break; + } + await yieldThread(); + } + this.queueRunning = false; + } + handleNext() { + const json = this.incomingMessageQueue.dequeue(); + if (!json) { + return false; + } + const subid = getSubscriptionId(json); + if (subid) { + const so = this.openSubs.get(subid); + if (!so) { + return; + } + const id = getHex64(json, "id"); + const alreadyHave = so.alreadyHaveEvent?.(id); + so.receivedEvent?.(this, id); + if (alreadyHave) { + return; + } + } + try { + let data = JSON.parse(json); + switch (data[0]) { + case "EVENT": { + const so = this.openSubs.get(data[1]); + const event = data[2]; + if (this.verifyEvent(event) && matchFilters(so.filters, event)) { + so.onevent(event); + } + return; + } + case "COUNT": { + const id = data[1]; + const payload = data[2]; + const cr = this.openCountRequests.get(id); + if (cr) { + cr.resolve(payload.count); + this.openCountRequests.delete(id); + } + return; + } + case "EOSE": { + const so = this.openSubs.get(data[1]); + if (!so) + return; + so.receivedEose(); + return; + } + case "OK": { + const id = data[1]; + const ok = data[2]; + const reason = data[3]; + const ep = this.openEventPublishes.get(id); + if (ep) { + clearTimeout(ep.timeout); + if (ok) + ep.resolve(reason); + else + ep.reject(new Error(reason)); + this.openEventPublishes.delete(id); + } + return; + } + case "CLOSED": { + const id = data[1]; + const so = this.openSubs.get(id); + if (!so) + return; + so.closed = true; + so.close(data[2]); + return; + } + case "NOTICE": + this.onnotice(data[1]); + return; + case "AUTH": { + this.challenge = data[1]; + return; + } + } + } catch (err) { + return; + } + } + async send(message) { + if (!this.connectionPromise) + throw new SendingOnClosedConnection(message, this.url); + this.connectionPromise.then(() => { + this.ws?.send(message); + }); + } + async auth(signAuthEvent) { + const challenge = this.challenge; + if (!challenge) + throw new Error("can't perform auth, no challenge was received"); + if (this.authPromise) + return this.authPromise; + this.authPromise = new Promise(async (resolve, reject) => { + try { + let evt = await signAuthEvent(makeAuthEvent(this.url, challenge)); + let timeout = setTimeout(() => { + let ep = this.openEventPublishes.get(evt.id); + if (ep) { + ep.reject(new Error("auth timed out")); + this.openEventPublishes.delete(evt.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(evt.id, { resolve, reject, timeout }); + this.send('["AUTH",' + JSON.stringify(evt) + "]"); + } catch (err) { + console.warn("subscribe auth function failed:", err); + } + }); + return this.authPromise; + } + async publish(event) { + const ret = new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + const ep = this.openEventPublishes.get(event.id); + if (ep) { + ep.reject(new Error("publish timed out")); + this.openEventPublishes.delete(event.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(event.id, { resolve, reject, timeout }); + }); + this.send('["EVENT",' + JSON.stringify(event) + "]"); + return ret; + } + async count(filters, params) { + this.serial++; + const id = params?.id || "count:" + this.serial; + const ret = new Promise((resolve, reject) => { + this.openCountRequests.set(id, { resolve, reject }); + }); + this.send('["COUNT","' + id + '",' + JSON.stringify(filters).substring(1)); + return ret; + } + subscribe(filters, params) { + const subscription = this.prepareSubscription(filters, params); + subscription.fire(); + return subscription; + } + prepareSubscription(filters, params) { + this.serial++; + const id = params.id || (params.label ? params.label + ":" : "sub:") + this.serial; + const subscription = new Subscription(this, id, filters, params); + this.openSubs.set(id, subscription); + return subscription; + } + close() { + this.closeAllSubscriptions("relay connection closed by us"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + _onmessage(ev) { + this.incomingMessageQueue.enqueue(ev.data); + if (!this.queueRunning) { + this.runQueue(); + } + } +}; +var Subscription = class { + relay; + id; + closed = false; + eosed = false; + filters; + alreadyHaveEvent; + receivedEvent; + onevent; + oneose; + onclose; + eoseTimeout; + eoseTimeoutHandle; + constructor(relay, id, filters, params) { + this.relay = relay; + this.filters = filters; + this.id = id; + this.alreadyHaveEvent = params.alreadyHaveEvent; + this.receivedEvent = params.receivedEvent; + this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout; + this.oneose = params.oneose; + this.onclose = params.onclose; + this.onevent = params.onevent || ((event) => { + console.warn( + `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`, + event + ); + }); + } + fire() { + this.relay.send('["REQ","' + this.id + '",' + JSON.stringify(this.filters).substring(1)); + this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout); + } + receivedEose() { + if (this.eosed) + return; + clearTimeout(this.eoseTimeoutHandle); + this.eosed = true; + this.oneose?.(); + } + close(reason = "closed by caller") { + if (!this.closed && this.relay.connected) { + try { + this.relay.send('["CLOSE",' + JSON.stringify(this.id) + "]"); + } catch (err) { + if (err instanceof SendingOnClosedConnection) { + } else { + throw err; + } + } + this.closed = true; + } + this.relay.openSubs.delete(this.id); + this.onclose?.(reason); + } +}; + +// abstract-pool.ts +var AbstractSimplePool = class { + relays = /* @__PURE__ */ new Map(); + seenOn = /* @__PURE__ */ new Map(); + trackRelays = false; + verifyEvent; + enablePing; + trustedRelayURLs = /* @__PURE__ */ new Set(); + _WebSocket; + constructor(opts) { + this.verifyEvent = opts.verifyEvent; + this._WebSocket = opts.websocketImplementation; + this.enablePing = opts.enablePing; + } + async ensureRelay(url, params) { + url = normalizeURL(url); + let relay = this.relays.get(url); + if (!relay) { + relay = new AbstractRelay(url, { + verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent, + websocketImplementation: this._WebSocket, + enablePing: this.enablePing + }); + relay.onclose = () => { + this.relays.delete(url); + }; + if (params?.connectionTimeout) + relay.connectionTimeout = params.connectionTimeout; + this.relays.set(url, relay); + } + await relay.connect(); + return relay; + } + close(relays) { + relays.map(normalizeURL).forEach((url) => { + this.relays.get(url)?.close(); + this.relays.delete(url); + }); + } + subscribe(relays, filter, params) { + params.onauth = params.onauth || params.doauth; + const request = []; + for (let i = 0; i < relays.length; i++) { + const url = normalizeURL(relays[i]); + if (!request.find((r) => r.url === url)) { + request.push({ url, filter }); + } + } + return this.subscribeMap(request, params); + } + subscribeMany(relays, filters, params) { + params.onauth = params.onauth || params.doauth; + const request = []; + const uniqUrls = []; + for (let i = 0; i < relays.length; i++) { + const url = normalizeURL(relays[i]); + if (uniqUrls.indexOf(url) === -1) { + for (let f = 0; f < filters.length; f++) { + request.push({ url, filter: filters[f] }); + } + } + } + return this.subscribeMap(request, params); + } + subscribeMap(requests, params) { + params.onauth = params.onauth || params.doauth; + if (this.trackRelays) { + params.receivedEvent = (relay, id) => { + let set = this.seenOn.get(id); + if (!set) { + set = /* @__PURE__ */ new Set(); + this.seenOn.set(id, set); + } + set.add(relay); + }; + } + const _knownIds = /* @__PURE__ */ new Set(); + const subs = []; + const eosesReceived = []; + let handleEose = (i) => { + if (eosesReceived[i]) + return; + eosesReceived[i] = true; + if (eosesReceived.filter((a) => a).length === requests.length) { + params.oneose?.(); + handleEose = () => { + }; + } + }; + const closesReceived = []; + let handleClose = (i, reason) => { + if (closesReceived[i]) + return; + handleEose(i); + closesReceived[i] = reason; + if (closesReceived.filter((a) => a).length === requests.length) { + params.onclose?.(closesReceived); + handleClose = () => { + }; + } + }; + const localAlreadyHaveEventHandler = (id) => { + if (params.alreadyHaveEvent?.(id)) { + return true; + } + const have = _knownIds.has(id); + _knownIds.add(id); + return have; + }; + const allOpened = Promise.all( + requests.map(async ({ url, filter }, i) => { + let relay; + try { + relay = await this.ensureRelay(url, { + connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1e3) : void 0 + }); + } catch (err) { + handleClose(i, err?.message || String(err)); + return; + } + let subscription = relay.subscribe([filter], { + ...params, + oneose: () => handleEose(i), + onclose: (reason) => { + if (reason.startsWith("auth-required: ") && params.onauth) { + relay.auth(params.onauth).then(() => { + relay.subscribe([filter], { + ...params, + oneose: () => handleEose(i), + onclose: (reason2) => { + handleClose(i, reason2); + }, + alreadyHaveEvent: localAlreadyHaveEventHandler, + eoseTimeout: params.maxWait + }); + }).catch((err) => { + handleClose(i, `auth was required and attempted, but failed with: ${err}`); + }); + } else { + handleClose(i, reason); + } + }, + alreadyHaveEvent: localAlreadyHaveEventHandler, + eoseTimeout: params.maxWait + }); + subs.push(subscription); + }) + ); + return { + async close(reason) { + await allOpened; + subs.forEach((sub) => { + sub.close(reason); + }); + } + }; + } + subscribeEose(relays, filter, params) { + params.onauth = params.onauth || params.doauth; + const subcloser = this.subscribe(relays, filter, { + ...params, + oneose() { + subcloser.close("closed automatically on eose"); + } + }); + return subcloser; + } + subscribeManyEose(relays, filters, params) { + params.onauth = params.onauth || params.doauth; + const subcloser = this.subscribeMany(relays, filters, { + ...params, + oneose() { + subcloser.close("closed automatically on eose"); + } + }); + return subcloser; + } + async querySync(relays, filter, params) { + return new Promise(async (resolve) => { + const events = []; + this.subscribeEose(relays, filter, { + ...params, + onevent(event) { + events.push(event); + }, + onclose(_) { + resolve(events); + } + }); + }); + } + async get(relays, filter, params) { + filter.limit = 1; + const events = await this.querySync(relays, filter, params); + events.sort((a, b) => b.created_at - a.created_at); + return events[0] || null; + } + publish(relays, event, options) { + return relays.map(normalizeURL).map(async (url, i, arr) => { + if (arr.indexOf(url) !== i) { + return Promise.reject("duplicate url"); + } + let r = await this.ensureRelay(url); + return r.publish(event).catch(async (err) => { + if (err instanceof Error && err.message.startsWith("auth-required: ") && options?.onauth) { + await r.auth(options.onauth); + return r.publish(event); + } + throw err; + }).then((reason) => { + if (this.trackRelays) { + let set = this.seenOn.get(event.id); + if (!set) { + set = /* @__PURE__ */ new Set(); + this.seenOn.set(event.id, set); + } + set.add(r); + } + return reason; + }); + }); + } + listConnectionStatus() { + const map = /* @__PURE__ */ new Map(); + this.relays.forEach((relay, url) => map.set(url, relay.connected)); + return map; + } + destroy() { + this.relays.forEach((conn) => conn.close()); + this.relays = /* @__PURE__ */ new Map(); + } +}; diff --git a/node_modules/nostr-tools/lib/cjs/abstract-pool.js.map b/node_modules/nostr-tools/lib/cjs/abstract-pool.js.map new file mode 100644 index 0000000..92a7e41 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/abstract-pool.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../abstract-pool.ts", "../../core.ts", "../../utils.ts", "../../kinds.ts", "../../filter.ts", "../../fakejson.ts", "../../nip42.ts", "../../helpers.ts", "../../abstract-relay.ts"], + "sourcesContent": ["/* global WebSocket */\n\nimport {\n AbstractRelay as AbstractRelay,\n SubscriptionParams,\n Subscription,\n type AbstractRelayConstructorOptions,\n} from './abstract-relay.ts'\nimport { normalizeURL } from './utils.ts'\n\nimport type { Event, EventTemplate, Nostr, VerifiedEvent } from './core.ts'\nimport { type Filter } from './filter.ts'\nimport { alwaysTrue } from './helpers.ts'\n\nexport type SubCloser = { close: (reason?: string) => void }\n\nexport type AbstractPoolConstructorOptions = AbstractRelayConstructorOptions & {}\n\nexport type SubscribeManyParams = Omit & {\n maxWait?: number\n onclose?: (reasons: string[]) => void\n onauth?: (event: EventTemplate) => Promise\n // Deprecated: use onauth instead\n doauth?: (event: EventTemplate) => Promise\n id?: string\n label?: string\n}\n\nexport class AbstractSimplePool {\n protected relays: Map = new Map()\n public seenOn: Map> = new Map()\n public trackRelays: boolean = false\n\n public verifyEvent: Nostr['verifyEvent']\n public enablePing: boolean | undefined\n public trustedRelayURLs: Set = new Set()\n\n private _WebSocket?: typeof WebSocket\n\n constructor(opts: AbstractPoolConstructorOptions) {\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation\n this.enablePing = opts.enablePing\n }\n\n async ensureRelay(url: string, params?: { connectionTimeout?: number }): Promise {\n url = normalizeURL(url)\n\n let relay = this.relays.get(url)\n if (!relay) {\n relay = new AbstractRelay(url, {\n verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent,\n websocketImplementation: this._WebSocket,\n enablePing: this.enablePing,\n })\n relay.onclose = () => {\n this.relays.delete(url)\n }\n if (params?.connectionTimeout) relay.connectionTimeout = params.connectionTimeout\n this.relays.set(url, relay)\n }\n await relay.connect()\n\n return relay\n }\n\n close(relays: string[]) {\n relays.map(normalizeURL).forEach(url => {\n this.relays.get(url)?.close()\n this.relays.delete(url)\n })\n }\n\n subscribe(relays: string[], filter: Filter, params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const request: { url: string; filter: Filter }[] = []\n for (let i = 0; i < relays.length; i++) {\n const url = normalizeURL(relays[i])\n if (!request.find(r => r.url === url)) {\n request.push({ url, filter })\n }\n }\n\n return this.subscribeMap(request, params)\n }\n\n subscribeMany(relays: string[], filters: Filter[], params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const request: { url: string; filter: Filter }[] = []\n const uniqUrls: string[] = []\n for (let i = 0; i < relays.length; i++) {\n const url = normalizeURL(relays[i])\n if (uniqUrls.indexOf(url) === -1) {\n for (let f = 0; f < filters.length; f++) {\n request.push({ url, filter: filters[f] })\n }\n }\n }\n\n return this.subscribeMap(request, params)\n }\n\n subscribeMap(requests: { url: string; filter: Filter }[], params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n if (this.trackRelays) {\n params.receivedEvent = (relay: AbstractRelay, id: string) => {\n let set = this.seenOn.get(id)\n if (!set) {\n set = new Set()\n this.seenOn.set(id, set)\n }\n set.add(relay)\n }\n }\n\n const _knownIds = new Set()\n const subs: Subscription[] = []\n\n // batch all EOSEs into a single\n const eosesReceived: boolean[] = []\n let handleEose = (i: number) => {\n if (eosesReceived[i]) return // do not act twice for the same relay\n eosesReceived[i] = true\n if (eosesReceived.filter(a => a).length === requests.length) {\n params.oneose?.()\n handleEose = () => {}\n }\n }\n // batch all closes into a single\n const closesReceived: string[] = []\n let handleClose = (i: number, reason: string) => {\n if (closesReceived[i]) return // do not act twice for the same relay\n handleEose(i)\n closesReceived[i] = reason\n if (closesReceived.filter(a => a).length === requests.length) {\n params.onclose?.(closesReceived)\n handleClose = () => {}\n }\n }\n\n const localAlreadyHaveEventHandler = (id: string) => {\n if (params.alreadyHaveEvent?.(id)) {\n return true\n }\n const have = _knownIds.has(id)\n _knownIds.add(id)\n return have\n }\n\n // open a subscription in all given relays\n const allOpened = Promise.all(\n requests.map(async ({ url, filter }, i) => {\n let relay: AbstractRelay\n try {\n relay = await this.ensureRelay(url, {\n connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1000) : undefined,\n })\n } catch (err) {\n handleClose(i, (err as any)?.message || String(err))\n return\n }\n\n let subscription = relay.subscribe([filter], {\n ...params,\n oneose: () => handleEose(i),\n onclose: reason => {\n if (reason.startsWith('auth-required: ') && params.onauth) {\n relay\n .auth(params.onauth)\n .then(() => {\n relay.subscribe([filter], {\n ...params,\n oneose: () => handleEose(i),\n onclose: reason => {\n handleClose(i, reason) // the second time we won't try to auth anymore\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait,\n })\n })\n .catch(err => {\n handleClose(i, `auth was required and attempted, but failed with: ${err}`)\n })\n } else {\n handleClose(i, reason)\n }\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait,\n })\n\n subs.push(subscription)\n }),\n )\n\n return {\n async close(reason?: string) {\n await allOpened\n subs.forEach(sub => {\n sub.close(reason)\n })\n },\n }\n }\n\n subscribeEose(\n relays: string[],\n filter: Filter,\n params: Pick,\n ): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const subcloser = this.subscribe(relays, filter, {\n ...params,\n oneose() {\n subcloser.close('closed automatically on eose')\n },\n })\n return subcloser\n }\n\n subscribeManyEose(\n relays: string[],\n filters: Filter[],\n params: Pick,\n ): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const subcloser = this.subscribeMany(relays, filters, {\n ...params,\n oneose() {\n subcloser.close('closed automatically on eose')\n },\n })\n return subcloser\n }\n\n async querySync(\n relays: string[],\n filter: Filter,\n params?: Pick,\n ): Promise {\n return new Promise(async resolve => {\n const events: Event[] = []\n this.subscribeEose(relays, filter, {\n ...params,\n onevent(event: Event) {\n events.push(event)\n },\n onclose(_: string[]) {\n resolve(events)\n },\n })\n })\n }\n\n async get(\n relays: string[],\n filter: Filter,\n params?: Pick,\n ): Promise {\n filter.limit = 1\n const events = await this.querySync(relays, filter, params)\n events.sort((a, b) => b.created_at - a.created_at)\n return events[0] || null\n }\n\n publish(\n relays: string[],\n event: Event,\n options?: { onauth?: (evt: EventTemplate) => Promise },\n ): Promise[] {\n return relays.map(normalizeURL).map(async (url, i, arr) => {\n if (arr.indexOf(url) !== i) {\n // duplicate\n return Promise.reject('duplicate url')\n }\n\n let r = await this.ensureRelay(url)\n return r\n .publish(event)\n .catch(async err => {\n if (err instanceof Error && err.message.startsWith('auth-required: ') && options?.onauth) {\n await r.auth(options.onauth)\n return r.publish(event) // retry\n }\n throw err\n })\n .then(reason => {\n if (this.trackRelays) {\n let set = this.seenOn.get(event.id)\n if (!set) {\n set = new Set()\n this.seenOn.set(event.id, set)\n }\n set.add(r)\n }\n return reason\n })\n })\n }\n\n listConnectionStatus(): Map {\n const map = new Map()\n this.relays.forEach((relay, url) => map.set(url, relay.connected))\n\n return map\n }\n\n destroy(): void {\n this.relays.forEach(conn => conn.close())\n this.relays = new Map()\n }\n}\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { Event } from './core.ts'\nimport { isAddressableKind, isReplaceableKind } from './kinds.ts'\n\nexport type Filter = {\n ids?: string[]\n kinds?: number[]\n authors?: string[]\n since?: number\n until?: number\n limit?: number\n search?: string\n [key: `#${string}`]: string[] | undefined\n}\n\nexport function matchFilter(filter: Filter, event: Event): boolean {\n if (filter.ids && filter.ids.indexOf(event.id) === -1) {\n return false\n }\n if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) {\n return false\n }\n if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) {\n return false\n }\n\n for (let f in filter) {\n if (f[0] === '#') {\n let tagName = f.slice(1)\n let values = filter[`#${tagName}`]\n if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values!.indexOf(v) !== -1)) return false\n }\n }\n\n if (filter.since && event.created_at < filter.since) return false\n if (filter.until && event.created_at > filter.until) return false\n\n return true\n}\n\nexport function matchFilters(filters: Filter[], event: Event): boolean {\n for (let i = 0; i < filters.length; i++) {\n if (matchFilter(filters[i], event)) {\n return true\n }\n }\n return false\n}\n\nexport function mergeFilters(...filters: Filter[]): Filter {\n let result: Filter = {}\n for (let i = 0; i < filters.length; i++) {\n let filter = filters[i]\n Object.entries(filter).forEach(([property, values]) => {\n if (property === 'kinds' || property === 'ids' || property === 'authors' || property[0] === '#') {\n // @ts-ignore\n result[property] = result[property] || []\n // @ts-ignore\n for (let v = 0; v < values.length; v++) {\n // @ts-ignore\n let value = values[v]\n // @ts-ignore\n if (!result[property].includes(value)) result[property].push(value)\n }\n }\n })\n\n if (filter.limit && (!result.limit || filter.limit > result.limit)) result.limit = filter.limit\n if (filter.until && (!result.until || filter.until > result.until)) result.until = filter.until\n if (filter.since && (!result.since || filter.since < result.since)) result.since = filter.since\n }\n\n return result\n}\n\n/**\n * Calculate the intrinsic limit of a filter.\n * This function returns a positive integer, or `Infinity` if there is no intrinsic limit.\n */\nexport function getFilterLimit(filter: Filter): number {\n if (filter.ids && !filter.ids.length) return 0\n if (filter.kinds && !filter.kinds.length) return 0\n if (filter.authors && !filter.authors.length) return 0\n\n for (const [key, value] of Object.entries(filter)) {\n if (key[0] === '#' && Array.isArray(value) && !value.length) return 0\n }\n\n return Math.min(\n // The `limit` property creates an artificial limit.\n Math.max(0, filter.limit ?? Infinity),\n\n // There can only be one event per `id`.\n filter.ids?.length ?? Infinity,\n\n // Replaceable events are limited by the number of authors and kinds.\n filter.authors?.length && filter.kinds?.every(kind => isReplaceableKind(kind))\n ? filter.authors.length * filter.kinds.length\n : Infinity,\n\n // Parameterized replaceable events are limited by the number of authors, kinds, and \"d\" tags.\n filter.authors?.length && filter.kinds?.every(kind => isAddressableKind(kind)) && filter['#d']?.length\n ? filter.authors.length * filter.kinds.length * filter['#d'].length\n : Infinity,\n )\n}\n", "export function getHex64(json: string, field: string): string {\n let len = field.length + 3\n let idx = json.indexOf(`\"${field}\":`) + len\n let s = json.slice(idx).indexOf(`\"`) + idx + 1\n return json.slice(s, s + 64)\n}\n\nexport function getInt(json: string, field: string): number {\n let len = field.length\n let idx = json.indexOf(`\"${field}\":`) + len + 3\n let sliced = json.slice(idx)\n let end = Math.min(sliced.indexOf(','), sliced.indexOf('}'))\n return parseInt(sliced.slice(0, end), 10)\n}\n\nexport function getSubscriptionId(json: string): string | null {\n let idx = json.slice(0, 22).indexOf(`\"EVENT\"`)\n if (idx === -1) return null\n\n let pstart = json.slice(idx + 7 + 1).indexOf(`\"`)\n if (pstart === -1) return null\n let start = idx + 7 + 1 + pstart\n\n let pend = json.slice(start + 1, 80).indexOf(`\"`)\n if (pend === -1) return null\n let end = start + 1 + pend\n\n return json.slice(start + 1, end)\n}\n\nexport function matchEventId(json: string, id: string): boolean {\n return id === getHex64(json, 'id')\n}\n\nexport function matchEventPubkey(json: string, pubkey: string): boolean {\n return pubkey === getHex64(json, 'pubkey')\n}\n\nexport function matchEventKind(json: string, kind: number): boolean {\n return kind === getInt(json, 'kind')\n}\n", "import { EventTemplate } from './core.ts'\nimport { ClientAuth } from './kinds.ts'\n\n/**\n * creates an EventTemplate for an AUTH event to be signed.\n */\nexport function makeAuthEvent(relayURL: string, challenge: string): EventTemplate {\n return {\n kind: ClientAuth,\n created_at: Math.floor(Date.now() / 1000),\n tags: [\n ['relay', relayURL],\n ['challenge', challenge],\n ],\n content: '',\n }\n}\n", "import { verifiedSymbol, type Event, type Nostr, VerifiedEvent } from './core.ts'\n\nexport async function yieldThread() {\n return new Promise(resolve => {\n const ch = new MessageChannel()\n const handler = () => {\n // @ts-ignore (typescript thinks this property should be called `removeListener`, but in fact it's `removeEventListener`)\n ch.port1.removeEventListener('message', handler)\n resolve()\n }\n // @ts-ignore (typescript thinks this property should be called `addListener`, but in fact it's `addEventListener`)\n ch.port1.addEventListener('message', handler)\n ch.port2.postMessage(0)\n ch.port1.start()\n })\n}\n\nexport const alwaysTrue: Nostr['verifyEvent'] = (t: Event): t is VerifiedEvent => {\n t[verifiedSymbol] = true\n return true\n}\n", "/* global WebSocket */\n\nimport type { Event, EventTemplate, VerifiedEvent, Nostr, NostrEvent } from './core.ts'\nimport { matchFilters, type Filter } from './filter.ts'\nimport { getHex64, getSubscriptionId } from './fakejson.ts'\nimport { Queue, normalizeURL } from './utils.ts'\nimport { makeAuthEvent } from './nip42.ts'\nimport { yieldThread } from './helpers.ts'\n\ntype RelayWebSocket = WebSocket & {\n ping?(): void\n on?(event: 'pong', listener: () => void): any\n}\n\nexport type AbstractRelayConstructorOptions = {\n verifyEvent: Nostr['verifyEvent']\n websocketImplementation?: typeof WebSocket\n enablePing?: boolean\n}\n\nexport class SendingOnClosedConnection extends Error {\n constructor(message: string, relay: string) {\n super(`Tried to send message '${message} on a closed connection to ${relay}.`)\n this.name = 'SendingOnClosedConnection'\n }\n}\n\nexport class AbstractRelay {\n public readonly url: string\n private _connected: boolean = false\n\n public onclose: (() => void) | null = null\n public onnotice: (msg: string) => void = msg => console.debug(`NOTICE from ${this.url}: ${msg}`)\n\n public baseEoseTimeout: number = 4400\n public connectionTimeout: number = 4400\n public publishTimeout: number = 4400\n public pingFrequency: number = 20000\n public pingTimeout: number = 20000\n public openSubs: Map = new Map()\n public enablePing: boolean | undefined\n private connectionTimeoutHandle: ReturnType | undefined\n\n private connectionPromise: Promise | undefined\n private openCountRequests = new Map()\n private openEventPublishes = new Map()\n private ws: RelayWebSocket | undefined\n private incomingMessageQueue = new Queue()\n private queueRunning = false\n private challenge: string | undefined\n private authPromise: Promise | undefined\n private serial: number = 0\n private verifyEvent: Nostr['verifyEvent']\n\n private _WebSocket: typeof WebSocket\n\n constructor(url: string, opts: AbstractRelayConstructorOptions) {\n this.url = normalizeURL(url)\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation || WebSocket\n this.enablePing = opts.enablePing\n }\n\n static async connect(url: string, opts: AbstractRelayConstructorOptions): Promise {\n const relay = new AbstractRelay(url, opts)\n await relay.connect()\n return relay\n }\n\n private closeAllSubscriptions(reason: string) {\n for (let [_, sub] of this.openSubs) {\n sub.close(reason)\n }\n this.openSubs.clear()\n\n for (let [_, ep] of this.openEventPublishes) {\n ep.reject(new Error(reason))\n }\n this.openEventPublishes.clear()\n\n for (let [_, cr] of this.openCountRequests) {\n cr.reject(new Error(reason))\n }\n this.openCountRequests.clear()\n }\n\n public get connected(): boolean {\n return this._connected\n }\n\n public async connect(): Promise {\n if (this.connectionPromise) return this.connectionPromise\n\n this.challenge = undefined\n this.authPromise = undefined\n this.connectionPromise = new Promise((resolve, reject) => {\n this.connectionTimeoutHandle = setTimeout(() => {\n reject('connection timed out')\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection timed out')\n }, this.connectionTimeout)\n\n try {\n this.ws = new this._WebSocket(this.url)\n } catch (err) {\n clearTimeout(this.connectionTimeoutHandle)\n reject(err)\n return\n }\n\n this.ws.onopen = () => {\n clearTimeout(this.connectionTimeoutHandle)\n this._connected = true\n if (this.enablePing) {\n this.pingpong()\n }\n resolve()\n }\n\n this.ws.onerror = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket error')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection errored')\n }\n }\n\n this.ws.onclose = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket closed')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection closed')\n }\n }\n\n this.ws.onmessage = this._onmessage.bind(this)\n })\n\n return this.connectionPromise\n }\n\n private async waitForPingPong() {\n return new Promise((res, err) => {\n // listen for pong\n ;(this.ws && this.ws.on && this.ws.on('pong', () => res(true))) || err(\"ws can't listen for pong\")\n // send a ping\n this.ws && this.ws.ping && this.ws.ping()\n })\n }\n\n private async waitForDummyReq() {\n return new Promise((resolve, _) => {\n // make a dummy request with expected empty eose reply\n // [\"REQ\", \"_\", {\"ids\":[\"aaaa...aaaa\"]}]\n const sub = this.subscribe([{ ids: ['a'.repeat(64)] }], {\n oneose: () => {\n sub.close()\n resolve(true)\n },\n eoseTimeout: this.pingTimeout + 1000,\n })\n })\n }\n\n // nodejs requires this magic here to ensure connections are closed when internet goes off and stuff\n // in browsers it's done automatically. see https://github.com/nbd-wtf/nostr-tools/issues/491\n private async pingpong() {\n // if the websocket is connected\n if (this.ws?.readyState === 1) {\n // wait for either a ping-pong reply or a timeout\n const result = await Promise.any([\n // browsers don't have ping so use a dummy req\n this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(),\n new Promise(res => setTimeout(() => res(false), this.pingTimeout)),\n ])\n if (result) {\n // schedule another pingpong\n setTimeout(() => this.pingpong(), this.pingFrequency)\n } else {\n // pingpong closing socket\n this.closeAllSubscriptions('pingpong timed out')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n }\n }\n\n private async runQueue() {\n this.queueRunning = true\n while (true) {\n if (false === this.handleNext()) {\n break\n }\n await yieldThread()\n }\n this.queueRunning = false\n }\n\n private handleNext(): undefined | false {\n const json = this.incomingMessageQueue.dequeue()\n if (!json) {\n return false\n }\n\n const subid = getSubscriptionId(json)\n if (subid) {\n const so = this.openSubs.get(subid as string)\n if (!so) {\n // this is an EVENT message, but for a subscription we don't have, so just stop here\n return\n }\n\n // this will be called only when this message is a EVENT message for a subscription we have\n // we do this before parsing the JSON to not have to do that for duplicate events\n // since JSON parsing is slow\n const id = getHex64(json, 'id')\n const alreadyHave = so.alreadyHaveEvent?.(id)\n\n // notify any interested client that the relay has this event\n // (do this after alreadyHaveEvent() because the client may rely on this to answer that)\n so.receivedEvent?.(this, id)\n\n if (alreadyHave) {\n // if we had already seen this event we can just stop here\n return\n }\n }\n\n try {\n let data = JSON.parse(json)\n // we won't do any checks against the data since all failures (i.e. invalid messages from relays)\n // will naturally be caught by the encompassing try..catch block\n\n switch (data[0]) {\n case 'EVENT': {\n const so = this.openSubs.get(data[1] as string) as Subscription\n const event = data[2] as NostrEvent\n if (this.verifyEvent(event) && matchFilters(so.filters, event)) {\n so.onevent(event)\n }\n return\n }\n case 'COUNT': {\n const id: string = data[1]\n const payload = data[2] as { count: number }\n const cr = this.openCountRequests.get(id) as CountResolver\n if (cr) {\n cr.resolve(payload.count)\n this.openCountRequests.delete(id)\n }\n return\n }\n case 'EOSE': {\n const so = this.openSubs.get(data[1] as string)\n if (!so) return\n so.receivedEose()\n return\n }\n case 'OK': {\n const id: string = data[1]\n const ok: boolean = data[2]\n const reason: string = data[3]\n const ep = this.openEventPublishes.get(id) as EventPublishResolver\n if (ep) {\n clearTimeout(ep.timeout)\n if (ok) ep.resolve(reason)\n else ep.reject(new Error(reason))\n this.openEventPublishes.delete(id)\n }\n return\n }\n case 'CLOSED': {\n const id: string = data[1]\n const so = this.openSubs.get(id)\n if (!so) return\n so.closed = true\n so.close(data[2] as string)\n return\n }\n case 'NOTICE':\n this.onnotice(data[1] as string)\n return\n case 'AUTH': {\n this.challenge = data[1] as string\n return\n }\n }\n } catch (err) {\n return\n }\n }\n\n public async send(message: string) {\n if (!this.connectionPromise) throw new SendingOnClosedConnection(message, this.url)\n\n this.connectionPromise.then(() => {\n this.ws?.send(message)\n })\n }\n\n public async auth(signAuthEvent: (evt: EventTemplate) => Promise): Promise {\n const challenge = this.challenge\n if (!challenge) throw new Error(\"can't perform auth, no challenge was received\")\n if (this.authPromise) return this.authPromise\n\n this.authPromise = new Promise(async (resolve, reject) => {\n try {\n let evt = await signAuthEvent(makeAuthEvent(this.url, challenge))\n let timeout = setTimeout(() => {\n let ep = this.openEventPublishes.get(evt.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('auth timed out'))\n this.openEventPublishes.delete(evt.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(evt.id, { resolve, reject, timeout })\n this.send('[\"AUTH\",' + JSON.stringify(evt) + ']')\n } catch (err) {\n console.warn('subscribe auth function failed:', err)\n }\n })\n return this.authPromise\n }\n\n public async publish(event: Event): Promise {\n const ret = new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n const ep = this.openEventPublishes.get(event.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('publish timed out'))\n this.openEventPublishes.delete(event.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(event.id, { resolve, reject, timeout })\n })\n this.send('[\"EVENT\",' + JSON.stringify(event) + ']')\n return ret\n }\n\n public async count(filters: Filter[], params: { id?: string | null }): Promise {\n this.serial++\n const id = params?.id || 'count:' + this.serial\n const ret = new Promise((resolve, reject) => {\n this.openCountRequests.set(id, { resolve, reject })\n })\n this.send('[\"COUNT\",\"' + id + '\",' + JSON.stringify(filters).substring(1))\n return ret\n }\n\n public subscribe(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n const subscription = this.prepareSubscription(filters, params)\n subscription.fire()\n return subscription\n }\n\n public prepareSubscription(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n this.serial++\n const id = params.id || (params.label ? params.label + ':' : 'sub:') + this.serial\n const subscription = new Subscription(this, id, filters, params)\n this.openSubs.set(id, subscription)\n return subscription\n }\n\n public close() {\n this.closeAllSubscriptions('relay connection closed by us')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n\n // this is the function assigned to this.ws.onmessage\n // it's exposed for testing and debugging purposes\n public _onmessage(ev: MessageEvent) {\n this.incomingMessageQueue.enqueue(ev.data as string)\n if (!this.queueRunning) {\n this.runQueue()\n }\n }\n}\n\nexport class Subscription {\n public readonly relay: AbstractRelay\n public readonly id: string\n\n public closed: boolean = false\n public eosed: boolean = false\n public filters: Filter[]\n public alreadyHaveEvent: ((id: string) => boolean) | undefined\n public receivedEvent: ((relay: AbstractRelay, id: string) => void) | undefined\n\n public onevent: (evt: Event) => void\n public oneose: (() => void) | undefined\n public onclose: ((reason: string) => void) | undefined\n\n public eoseTimeout: number\n private eoseTimeoutHandle: ReturnType | undefined\n\n constructor(relay: AbstractRelay, id: string, filters: Filter[], params: SubscriptionParams) {\n this.relay = relay\n this.filters = filters\n this.id = id\n this.alreadyHaveEvent = params.alreadyHaveEvent\n this.receivedEvent = params.receivedEvent\n this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout\n\n this.oneose = params.oneose\n this.onclose = params.onclose\n this.onevent =\n params.onevent ||\n (event => {\n console.warn(\n `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,\n event,\n )\n })\n }\n\n public fire() {\n this.relay.send('[\"REQ\",\"' + this.id + '\",' + JSON.stringify(this.filters).substring(1))\n\n // only now we start counting the eoseTimeout\n this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout)\n }\n\n public receivedEose() {\n if (this.eosed) return\n clearTimeout(this.eoseTimeoutHandle)\n this.eosed = true\n this.oneose?.()\n }\n\n public close(reason: string = 'closed by caller') {\n if (!this.closed && this.relay.connected) {\n // if the connection was closed by the user calling .close() we will send a CLOSE message\n // otherwise this._open will be already set to false so we will skip this\n try {\n this.relay.send('[\"CLOSE\",' + JSON.stringify(this.id) + ']')\n } catch (err) {\n if (err instanceof SendingOnClosedConnection) {\n /* doesn't matter, it's ok */\n } else {\n throw err\n }\n }\n this.closed = true\n }\n this.relay.openSubs.delete(this.id)\n this.onclose?.(reason)\n }\n}\n\nexport type SubscriptionParams = {\n onevent?: (evt: Event) => void\n oneose?: () => void\n onclose?: (reason: string) => void\n alreadyHaveEvent?: (id: string) => boolean\n receivedEvent?: (relay: AbstractRelay, id: string) => void\n eoseTimeout?: number\n}\n\nexport type CountResolver = {\n resolve: (count: number) => void\n reject: (err: Error) => void\n}\n\nexport type EventPublishResolver = {\n resolve: (reason: string) => void\n reject: (err: Error) => void\n timeout: ReturnType\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACQO,IAAM,iBAAiB,OAAO,UAAU;;;ACH/C,mBAAuC;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;AAIjD,SAAS,aAAa,KAAqB;AAChD,MAAI;AACF,QAAI,IAAI,QAAQ,KAAK,MAAM;AAAI,YAAM,WAAW;AAChD,QAAI,IAAI,IAAI,IAAI,GAAG;AACnB,MAAE,WAAW,EAAE,SAAS,QAAQ,QAAQ,GAAG;AAC3C,QAAI,EAAE,SAAS,SAAS,GAAG;AAAG,QAAE,WAAW,EAAE,SAAS,MAAM,GAAG,EAAE;AACjE,QAAK,EAAE,SAAS,QAAQ,EAAE,aAAa,SAAW,EAAE,SAAS,SAAS,EAAE,aAAa;AAAS,QAAE,OAAO;AACvG,MAAE,aAAa,KAAK;AACpB,MAAE,OAAO;AACT,WAAO,EAAE,SAAS;AAAA,EACpB,SAAS,GAAP;AACA,UAAM,IAAI,MAAM,gBAAgB,KAAK;AAAA,EACvC;AACF;AAgDO,IAAM,YAAN,MAAmB;AAAA,EACjB;AAAA,EACA,OAA4B;AAAA,EAC5B,OAA4B;AAAA,EAEnC,YA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AAY,EAAE,IAAI,OAAO,KAAK,GAAG,QAAQ;AACzD,UAAI,IAAI,QAAQ,GAAG,MAAM,GAAG;AAE1B,eAAO,QAAQ,OAAO,eAAe;AAAA,MACvC;AAEA,UAAI,IAAI,MAAM,KAAK,YAAY,GAAG;AAClC,aAAO,EACJ,QAAQ,KAAK,EACb,MAAM,OAAM,QAAO;AAClB,YAAI,eAAe,SAAS,IAAI,QAAQ,WAAW,iBAAiB,KAAK,SAAS,QAAQ;AACxF,gBAAM,EAAE,KAAK,QAAQ,MAAM;AAC3B,iBAAO,EAAE,QAAQ,KAAK;AAAA,QACxB;AACA,cAAM;AAAA,MACR,CAAC,EACA,KAAK,YAAU;AACd,YAAI,KAAK,aAAa;AACpB,cAAI,MAAM,KAAK,OAAO,IAAI,MAAM,EAAE;AAClC,cAAI,CAAC,KAAK;AACR,kBAAM,oBAAI,IAAI;AACd,iBAAK,OAAO,IAAI,MAAM,IAAI,GAAG;AAAA,UAC/B;AACA,cAAI,IAAI,CAAC;AAAA,QACX;AACA,eAAO;AAAA,MACT,CAAC;AAAA,IACL,CAAC;AAAA,EACH;AAAA,EAEA,uBAA6C;AAC3C,UAAM,MAAM,oBAAI,IAAqB;AACrC,SAAK,OAAO,QAAQ,CAAC,OAAO,QAAQ,IAAI,IAAI,KAAK,MAAM,SAAS,CAAC;AAEjE,WAAO;AAAA,EACT;AAAA,EAEA,UAAgB;AACd,SAAK,OAAO,QAAQ,UAAQ,KAAK,MAAM,CAAC;AACxC,SAAK,SAAS,oBAAI,IAAI;AAAA,EACxB;AACF;", + "names": ["target", "reason"] +} diff --git a/node_modules/nostr-tools/lib/cjs/abstract-relay.js b/node_modules/nostr-tools/lib/cjs/abstract-relay.js new file mode 100644 index 0000000..4a5fe68 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/abstract-relay.js @@ -0,0 +1,555 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// abstract-relay.ts +var abstract_relay_exports = {}; +__export(abstract_relay_exports, { + AbstractRelay: () => AbstractRelay, + SendingOnClosedConnection: () => SendingOnClosedConnection, + Subscription: () => Subscription +}); +module.exports = __toCommonJS(abstract_relay_exports); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); +function normalizeURL(url) { + try { + if (url.indexOf("://") === -1) + url = "wss://" + url; + let p = new URL(url); + p.pathname = p.pathname.replace(/\/+/g, "/"); + if (p.pathname.endsWith("/")) + p.pathname = p.pathname.slice(0, -1); + if (p.port === "80" && p.protocol === "ws:" || p.port === "443" && p.protocol === "wss:") + p.port = ""; + p.searchParams.sort(); + p.hash = ""; + return p.toString(); + } catch (e) { + throw new Error(`Invalid URL: ${url}`); + } +} +var QueueNode = class { + value; + next = null; + prev = null; + constructor(message) { + this.value = message; + } +}; +var Queue = class { + first; + last; + constructor() { + this.first = null; + this.last = null; + } + enqueue(value) { + const newNode = new QueueNode(value); + if (!this.last) { + this.first = newNode; + this.last = newNode; + } else if (this.last === this.first) { + this.last = newNode; + this.last.prev = this.first; + this.first.next = newNode; + } else { + newNode.prev = this.last; + this.last.next = newNode; + this.last = newNode; + } + return true; + } + dequeue() { + if (!this.first) + return null; + if (this.first === this.last) { + const target2 = this.first; + this.first = null; + this.last = null; + return target2.value; + } + const target = this.first; + this.first = target.next; + if (this.first) { + this.first.prev = null; + } + return target.value; + } +}; + +// kinds.ts +var ClientAuth = 22242; + +// filter.ts +function matchFilter(filter, event) { + if (filter.ids && filter.ids.indexOf(event.id) === -1) { + return false; + } + if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) { + return false; + } + if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) { + return false; + } + for (let f in filter) { + if (f[0] === "#") { + let tagName = f.slice(1); + let values = filter[`#${tagName}`]; + if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values.indexOf(v) !== -1)) + return false; + } + } + if (filter.since && event.created_at < filter.since) + return false; + if (filter.until && event.created_at > filter.until) + return false; + return true; +} +function matchFilters(filters, event) { + for (let i = 0; i < filters.length; i++) { + if (matchFilter(filters[i], event)) { + return true; + } + } + return false; +} + +// fakejson.ts +function getHex64(json, field) { + let len = field.length + 3; + let idx = json.indexOf(`"${field}":`) + len; + let s = json.slice(idx).indexOf(`"`) + idx + 1; + return json.slice(s, s + 64); +} +function getSubscriptionId(json) { + let idx = json.slice(0, 22).indexOf(`"EVENT"`); + if (idx === -1) + return null; + let pstart = json.slice(idx + 7 + 1).indexOf(`"`); + if (pstart === -1) + return null; + let start = idx + 7 + 1 + pstart; + let pend = json.slice(start + 1, 80).indexOf(`"`); + if (pend === -1) + return null; + let end = start + 1 + pend; + return json.slice(start + 1, end); +} + +// nip42.ts +function makeAuthEvent(relayURL, challenge) { + return { + kind: ClientAuth, + created_at: Math.floor(Date.now() / 1e3), + tags: [ + ["relay", relayURL], + ["challenge", challenge] + ], + content: "" + }; +} + +// helpers.ts +async function yieldThread() { + return new Promise((resolve) => { + const ch = new MessageChannel(); + const handler = () => { + ch.port1.removeEventListener("message", handler); + resolve(); + }; + ch.port1.addEventListener("message", handler); + ch.port2.postMessage(0); + ch.port1.start(); + }); +} + +// abstract-relay.ts +var SendingOnClosedConnection = class extends Error { + constructor(message, relay) { + super(`Tried to send message '${message} on a closed connection to ${relay}.`); + this.name = "SendingOnClosedConnection"; + } +}; +var AbstractRelay = class { + url; + _connected = false; + onclose = null; + onnotice = (msg) => console.debug(`NOTICE from ${this.url}: ${msg}`); + baseEoseTimeout = 4400; + connectionTimeout = 4400; + publishTimeout = 4400; + pingFrequency = 2e4; + pingTimeout = 2e4; + openSubs = /* @__PURE__ */ new Map(); + enablePing; + connectionTimeoutHandle; + connectionPromise; + openCountRequests = /* @__PURE__ */ new Map(); + openEventPublishes = /* @__PURE__ */ new Map(); + ws; + incomingMessageQueue = new Queue(); + queueRunning = false; + challenge; + authPromise; + serial = 0; + verifyEvent; + _WebSocket; + constructor(url, opts) { + this.url = normalizeURL(url); + this.verifyEvent = opts.verifyEvent; + this._WebSocket = opts.websocketImplementation || WebSocket; + this.enablePing = opts.enablePing; + } + static async connect(url, opts) { + const relay = new AbstractRelay(url, opts); + await relay.connect(); + return relay; + } + closeAllSubscriptions(reason) { + for (let [_, sub] of this.openSubs) { + sub.close(reason); + } + this.openSubs.clear(); + for (let [_, ep] of this.openEventPublishes) { + ep.reject(new Error(reason)); + } + this.openEventPublishes.clear(); + for (let [_, cr] of this.openCountRequests) { + cr.reject(new Error(reason)); + } + this.openCountRequests.clear(); + } + get connected() { + return this._connected; + } + async connect() { + if (this.connectionPromise) + return this.connectionPromise; + this.challenge = void 0; + this.authPromise = void 0; + this.connectionPromise = new Promise((resolve, reject) => { + this.connectionTimeoutHandle = setTimeout(() => { + reject("connection timed out"); + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection timed out"); + }, this.connectionTimeout); + try { + this.ws = new this._WebSocket(this.url); + } catch (err) { + clearTimeout(this.connectionTimeoutHandle); + reject(err); + return; + } + this.ws.onopen = () => { + clearTimeout(this.connectionTimeoutHandle); + this._connected = true; + if (this.enablePing) { + this.pingpong(); + } + resolve(); + }; + this.ws.onerror = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket error"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection errored"); + } + }; + this.ws.onclose = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket closed"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection closed"); + } + }; + this.ws.onmessage = this._onmessage.bind(this); + }); + return this.connectionPromise; + } + async waitForPingPong() { + return new Promise((res, err) => { + ; + this.ws && this.ws.on && this.ws.on("pong", () => res(true)) || err("ws can't listen for pong"); + this.ws && this.ws.ping && this.ws.ping(); + }); + } + async waitForDummyReq() { + return new Promise((resolve, _) => { + const sub = this.subscribe([{ ids: ["a".repeat(64)] }], { + oneose: () => { + sub.close(); + resolve(true); + }, + eoseTimeout: this.pingTimeout + 1e3 + }); + }); + } + async pingpong() { + if (this.ws?.readyState === 1) { + const result = await Promise.any([ + this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(), + new Promise((res) => setTimeout(() => res(false), this.pingTimeout)) + ]); + if (result) { + setTimeout(() => this.pingpong(), this.pingFrequency); + } else { + this.closeAllSubscriptions("pingpong timed out"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + } + } + async runQueue() { + this.queueRunning = true; + while (true) { + if (false === this.handleNext()) { + break; + } + await yieldThread(); + } + this.queueRunning = false; + } + handleNext() { + const json = this.incomingMessageQueue.dequeue(); + if (!json) { + return false; + } + const subid = getSubscriptionId(json); + if (subid) { + const so = this.openSubs.get(subid); + if (!so) { + return; + } + const id = getHex64(json, "id"); + const alreadyHave = so.alreadyHaveEvent?.(id); + so.receivedEvent?.(this, id); + if (alreadyHave) { + return; + } + } + try { + let data = JSON.parse(json); + switch (data[0]) { + case "EVENT": { + const so = this.openSubs.get(data[1]); + const event = data[2]; + if (this.verifyEvent(event) && matchFilters(so.filters, event)) { + so.onevent(event); + } + return; + } + case "COUNT": { + const id = data[1]; + const payload = data[2]; + const cr = this.openCountRequests.get(id); + if (cr) { + cr.resolve(payload.count); + this.openCountRequests.delete(id); + } + return; + } + case "EOSE": { + const so = this.openSubs.get(data[1]); + if (!so) + return; + so.receivedEose(); + return; + } + case "OK": { + const id = data[1]; + const ok = data[2]; + const reason = data[3]; + const ep = this.openEventPublishes.get(id); + if (ep) { + clearTimeout(ep.timeout); + if (ok) + ep.resolve(reason); + else + ep.reject(new Error(reason)); + this.openEventPublishes.delete(id); + } + return; + } + case "CLOSED": { + const id = data[1]; + const so = this.openSubs.get(id); + if (!so) + return; + so.closed = true; + so.close(data[2]); + return; + } + case "NOTICE": + this.onnotice(data[1]); + return; + case "AUTH": { + this.challenge = data[1]; + return; + } + } + } catch (err) { + return; + } + } + async send(message) { + if (!this.connectionPromise) + throw new SendingOnClosedConnection(message, this.url); + this.connectionPromise.then(() => { + this.ws?.send(message); + }); + } + async auth(signAuthEvent) { + const challenge = this.challenge; + if (!challenge) + throw new Error("can't perform auth, no challenge was received"); + if (this.authPromise) + return this.authPromise; + this.authPromise = new Promise(async (resolve, reject) => { + try { + let evt = await signAuthEvent(makeAuthEvent(this.url, challenge)); + let timeout = setTimeout(() => { + let ep = this.openEventPublishes.get(evt.id); + if (ep) { + ep.reject(new Error("auth timed out")); + this.openEventPublishes.delete(evt.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(evt.id, { resolve, reject, timeout }); + this.send('["AUTH",' + JSON.stringify(evt) + "]"); + } catch (err) { + console.warn("subscribe auth function failed:", err); + } + }); + return this.authPromise; + } + async publish(event) { + const ret = new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + const ep = this.openEventPublishes.get(event.id); + if (ep) { + ep.reject(new Error("publish timed out")); + this.openEventPublishes.delete(event.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(event.id, { resolve, reject, timeout }); + }); + this.send('["EVENT",' + JSON.stringify(event) + "]"); + return ret; + } + async count(filters, params) { + this.serial++; + const id = params?.id || "count:" + this.serial; + const ret = new Promise((resolve, reject) => { + this.openCountRequests.set(id, { resolve, reject }); + }); + this.send('["COUNT","' + id + '",' + JSON.stringify(filters).substring(1)); + return ret; + } + subscribe(filters, params) { + const subscription = this.prepareSubscription(filters, params); + subscription.fire(); + return subscription; + } + prepareSubscription(filters, params) { + this.serial++; + const id = params.id || (params.label ? params.label + ":" : "sub:") + this.serial; + const subscription = new Subscription(this, id, filters, params); + this.openSubs.set(id, subscription); + return subscription; + } + close() { + this.closeAllSubscriptions("relay connection closed by us"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + _onmessage(ev) { + this.incomingMessageQueue.enqueue(ev.data); + if (!this.queueRunning) { + this.runQueue(); + } + } +}; +var Subscription = class { + relay; + id; + closed = false; + eosed = false; + filters; + alreadyHaveEvent; + receivedEvent; + onevent; + oneose; + onclose; + eoseTimeout; + eoseTimeoutHandle; + constructor(relay, id, filters, params) { + this.relay = relay; + this.filters = filters; + this.id = id; + this.alreadyHaveEvent = params.alreadyHaveEvent; + this.receivedEvent = params.receivedEvent; + this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout; + this.oneose = params.oneose; + this.onclose = params.onclose; + this.onevent = params.onevent || ((event) => { + console.warn( + `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`, + event + ); + }); + } + fire() { + this.relay.send('["REQ","' + this.id + '",' + JSON.stringify(this.filters).substring(1)); + this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout); + } + receivedEose() { + if (this.eosed) + return; + clearTimeout(this.eoseTimeoutHandle); + this.eosed = true; + this.oneose?.(); + } + close(reason = "closed by caller") { + if (!this.closed && this.relay.connected) { + try { + this.relay.send('["CLOSE",' + JSON.stringify(this.id) + "]"); + } catch (err) { + if (err instanceof SendingOnClosedConnection) { + } else { + throw err; + } + } + this.closed = true; + } + this.relay.openSubs.delete(this.id); + this.onclose?.(reason); + } +}; diff --git a/node_modules/nostr-tools/lib/cjs/abstract-relay.js.map b/node_modules/nostr-tools/lib/cjs/abstract-relay.js.map new file mode 100644 index 0000000..d23fa5e --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/abstract-relay.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../abstract-relay.ts", "../../utils.ts", "../../kinds.ts", "../../filter.ts", "../../fakejson.ts", "../../nip42.ts", "../../helpers.ts"], + "sourcesContent": ["/* global WebSocket */\n\nimport type { Event, EventTemplate, VerifiedEvent, Nostr, NostrEvent } from './core.ts'\nimport { matchFilters, type Filter } from './filter.ts'\nimport { getHex64, getSubscriptionId } from './fakejson.ts'\nimport { Queue, normalizeURL } from './utils.ts'\nimport { makeAuthEvent } from './nip42.ts'\nimport { yieldThread } from './helpers.ts'\n\ntype RelayWebSocket = WebSocket & {\n ping?(): void\n on?(event: 'pong', listener: () => void): any\n}\n\nexport type AbstractRelayConstructorOptions = {\n verifyEvent: Nostr['verifyEvent']\n websocketImplementation?: typeof WebSocket\n enablePing?: boolean\n}\n\nexport class SendingOnClosedConnection extends Error {\n constructor(message: string, relay: string) {\n super(`Tried to send message '${message} on a closed connection to ${relay}.`)\n this.name = 'SendingOnClosedConnection'\n }\n}\n\nexport class AbstractRelay {\n public readonly url: string\n private _connected: boolean = false\n\n public onclose: (() => void) | null = null\n public onnotice: (msg: string) => void = msg => console.debug(`NOTICE from ${this.url}: ${msg}`)\n\n public baseEoseTimeout: number = 4400\n public connectionTimeout: number = 4400\n public publishTimeout: number = 4400\n public pingFrequency: number = 20000\n public pingTimeout: number = 20000\n public openSubs: Map = new Map()\n public enablePing: boolean | undefined\n private connectionTimeoutHandle: ReturnType | undefined\n\n private connectionPromise: Promise | undefined\n private openCountRequests = new Map()\n private openEventPublishes = new Map()\n private ws: RelayWebSocket | undefined\n private incomingMessageQueue = new Queue()\n private queueRunning = false\n private challenge: string | undefined\n private authPromise: Promise | undefined\n private serial: number = 0\n private verifyEvent: Nostr['verifyEvent']\n\n private _WebSocket: typeof WebSocket\n\n constructor(url: string, opts: AbstractRelayConstructorOptions) {\n this.url = normalizeURL(url)\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation || WebSocket\n this.enablePing = opts.enablePing\n }\n\n static async connect(url: string, opts: AbstractRelayConstructorOptions): Promise {\n const relay = new AbstractRelay(url, opts)\n await relay.connect()\n return relay\n }\n\n private closeAllSubscriptions(reason: string) {\n for (let [_, sub] of this.openSubs) {\n sub.close(reason)\n }\n this.openSubs.clear()\n\n for (let [_, ep] of this.openEventPublishes) {\n ep.reject(new Error(reason))\n }\n this.openEventPublishes.clear()\n\n for (let [_, cr] of this.openCountRequests) {\n cr.reject(new Error(reason))\n }\n this.openCountRequests.clear()\n }\n\n public get connected(): boolean {\n return this._connected\n }\n\n public async connect(): Promise {\n if (this.connectionPromise) return this.connectionPromise\n\n this.challenge = undefined\n this.authPromise = undefined\n this.connectionPromise = new Promise((resolve, reject) => {\n this.connectionTimeoutHandle = setTimeout(() => {\n reject('connection timed out')\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection timed out')\n }, this.connectionTimeout)\n\n try {\n this.ws = new this._WebSocket(this.url)\n } catch (err) {\n clearTimeout(this.connectionTimeoutHandle)\n reject(err)\n return\n }\n\n this.ws.onopen = () => {\n clearTimeout(this.connectionTimeoutHandle)\n this._connected = true\n if (this.enablePing) {\n this.pingpong()\n }\n resolve()\n }\n\n this.ws.onerror = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket error')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection errored')\n }\n }\n\n this.ws.onclose = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket closed')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection closed')\n }\n }\n\n this.ws.onmessage = this._onmessage.bind(this)\n })\n\n return this.connectionPromise\n }\n\n private async waitForPingPong() {\n return new Promise((res, err) => {\n // listen for pong\n ;(this.ws && this.ws.on && this.ws.on('pong', () => res(true))) || err(\"ws can't listen for pong\")\n // send a ping\n this.ws && this.ws.ping && this.ws.ping()\n })\n }\n\n private async waitForDummyReq() {\n return new Promise((resolve, _) => {\n // make a dummy request with expected empty eose reply\n // [\"REQ\", \"_\", {\"ids\":[\"aaaa...aaaa\"]}]\n const sub = this.subscribe([{ ids: ['a'.repeat(64)] }], {\n oneose: () => {\n sub.close()\n resolve(true)\n },\n eoseTimeout: this.pingTimeout + 1000,\n })\n })\n }\n\n // nodejs requires this magic here to ensure connections are closed when internet goes off and stuff\n // in browsers it's done automatically. see https://github.com/nbd-wtf/nostr-tools/issues/491\n private async pingpong() {\n // if the websocket is connected\n if (this.ws?.readyState === 1) {\n // wait for either a ping-pong reply or a timeout\n const result = await Promise.any([\n // browsers don't have ping so use a dummy req\n this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(),\n new Promise(res => setTimeout(() => res(false), this.pingTimeout)),\n ])\n if (result) {\n // schedule another pingpong\n setTimeout(() => this.pingpong(), this.pingFrequency)\n } else {\n // pingpong closing socket\n this.closeAllSubscriptions('pingpong timed out')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n }\n }\n\n private async runQueue() {\n this.queueRunning = true\n while (true) {\n if (false === this.handleNext()) {\n break\n }\n await yieldThread()\n }\n this.queueRunning = false\n }\n\n private handleNext(): undefined | false {\n const json = this.incomingMessageQueue.dequeue()\n if (!json) {\n return false\n }\n\n const subid = getSubscriptionId(json)\n if (subid) {\n const so = this.openSubs.get(subid as string)\n if (!so) {\n // this is an EVENT message, but for a subscription we don't have, so just stop here\n return\n }\n\n // this will be called only when this message is a EVENT message for a subscription we have\n // we do this before parsing the JSON to not have to do that for duplicate events\n // since JSON parsing is slow\n const id = getHex64(json, 'id')\n const alreadyHave = so.alreadyHaveEvent?.(id)\n\n // notify any interested client that the relay has this event\n // (do this after alreadyHaveEvent() because the client may rely on this to answer that)\n so.receivedEvent?.(this, id)\n\n if (alreadyHave) {\n // if we had already seen this event we can just stop here\n return\n }\n }\n\n try {\n let data = JSON.parse(json)\n // we won't do any checks against the data since all failures (i.e. invalid messages from relays)\n // will naturally be caught by the encompassing try..catch block\n\n switch (data[0]) {\n case 'EVENT': {\n const so = this.openSubs.get(data[1] as string) as Subscription\n const event = data[2] as NostrEvent\n if (this.verifyEvent(event) && matchFilters(so.filters, event)) {\n so.onevent(event)\n }\n return\n }\n case 'COUNT': {\n const id: string = data[1]\n const payload = data[2] as { count: number }\n const cr = this.openCountRequests.get(id) as CountResolver\n if (cr) {\n cr.resolve(payload.count)\n this.openCountRequests.delete(id)\n }\n return\n }\n case 'EOSE': {\n const so = this.openSubs.get(data[1] as string)\n if (!so) return\n so.receivedEose()\n return\n }\n case 'OK': {\n const id: string = data[1]\n const ok: boolean = data[2]\n const reason: string = data[3]\n const ep = this.openEventPublishes.get(id) as EventPublishResolver\n if (ep) {\n clearTimeout(ep.timeout)\n if (ok) ep.resolve(reason)\n else ep.reject(new Error(reason))\n this.openEventPublishes.delete(id)\n }\n return\n }\n case 'CLOSED': {\n const id: string = data[1]\n const so = this.openSubs.get(id)\n if (!so) return\n so.closed = true\n so.close(data[2] as string)\n return\n }\n case 'NOTICE':\n this.onnotice(data[1] as string)\n return\n case 'AUTH': {\n this.challenge = data[1] as string\n return\n }\n }\n } catch (err) {\n return\n }\n }\n\n public async send(message: string) {\n if (!this.connectionPromise) throw new SendingOnClosedConnection(message, this.url)\n\n this.connectionPromise.then(() => {\n this.ws?.send(message)\n })\n }\n\n public async auth(signAuthEvent: (evt: EventTemplate) => Promise): Promise {\n const challenge = this.challenge\n if (!challenge) throw new Error(\"can't perform auth, no challenge was received\")\n if (this.authPromise) return this.authPromise\n\n this.authPromise = new Promise(async (resolve, reject) => {\n try {\n let evt = await signAuthEvent(makeAuthEvent(this.url, challenge))\n let timeout = setTimeout(() => {\n let ep = this.openEventPublishes.get(evt.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('auth timed out'))\n this.openEventPublishes.delete(evt.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(evt.id, { resolve, reject, timeout })\n this.send('[\"AUTH\",' + JSON.stringify(evt) + ']')\n } catch (err) {\n console.warn('subscribe auth function failed:', err)\n }\n })\n return this.authPromise\n }\n\n public async publish(event: Event): Promise {\n const ret = new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n const ep = this.openEventPublishes.get(event.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('publish timed out'))\n this.openEventPublishes.delete(event.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(event.id, { resolve, reject, timeout })\n })\n this.send('[\"EVENT\",' + JSON.stringify(event) + ']')\n return ret\n }\n\n public async count(filters: Filter[], params: { id?: string | null }): Promise {\n this.serial++\n const id = params?.id || 'count:' + this.serial\n const ret = new Promise((resolve, reject) => {\n this.openCountRequests.set(id, { resolve, reject })\n })\n this.send('[\"COUNT\",\"' + id + '\",' + JSON.stringify(filters).substring(1))\n return ret\n }\n\n public subscribe(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n const subscription = this.prepareSubscription(filters, params)\n subscription.fire()\n return subscription\n }\n\n public prepareSubscription(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n this.serial++\n const id = params.id || (params.label ? params.label + ':' : 'sub:') + this.serial\n const subscription = new Subscription(this, id, filters, params)\n this.openSubs.set(id, subscription)\n return subscription\n }\n\n public close() {\n this.closeAllSubscriptions('relay connection closed by us')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n\n // this is the function assigned to this.ws.onmessage\n // it's exposed for testing and debugging purposes\n public _onmessage(ev: MessageEvent) {\n this.incomingMessageQueue.enqueue(ev.data as string)\n if (!this.queueRunning) {\n this.runQueue()\n }\n }\n}\n\nexport class Subscription {\n public readonly relay: AbstractRelay\n public readonly id: string\n\n public closed: boolean = false\n public eosed: boolean = false\n public filters: Filter[]\n public alreadyHaveEvent: ((id: string) => boolean) | undefined\n public receivedEvent: ((relay: AbstractRelay, id: string) => void) | undefined\n\n public onevent: (evt: Event) => void\n public oneose: (() => void) | undefined\n public onclose: ((reason: string) => void) | undefined\n\n public eoseTimeout: number\n private eoseTimeoutHandle: ReturnType | undefined\n\n constructor(relay: AbstractRelay, id: string, filters: Filter[], params: SubscriptionParams) {\n this.relay = relay\n this.filters = filters\n this.id = id\n this.alreadyHaveEvent = params.alreadyHaveEvent\n this.receivedEvent = params.receivedEvent\n this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout\n\n this.oneose = params.oneose\n this.onclose = params.onclose\n this.onevent =\n params.onevent ||\n (event => {\n console.warn(\n `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,\n event,\n )\n })\n }\n\n public fire() {\n this.relay.send('[\"REQ\",\"' + this.id + '\",' + JSON.stringify(this.filters).substring(1))\n\n // only now we start counting the eoseTimeout\n this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout)\n }\n\n public receivedEose() {\n if (this.eosed) return\n clearTimeout(this.eoseTimeoutHandle)\n this.eosed = true\n this.oneose?.()\n }\n\n public close(reason: string = 'closed by caller') {\n if (!this.closed && this.relay.connected) {\n // if the connection was closed by the user calling .close() we will send a CLOSE message\n // otherwise this._open will be already set to false so we will skip this\n try {\n this.relay.send('[\"CLOSE\",' + JSON.stringify(this.id) + ']')\n } catch (err) {\n if (err instanceof SendingOnClosedConnection) {\n /* doesn't matter, it's ok */\n } else {\n throw err\n }\n }\n this.closed = true\n }\n this.relay.openSubs.delete(this.id)\n this.onclose?.(reason)\n }\n}\n\nexport type SubscriptionParams = {\n onevent?: (evt: Event) => void\n oneose?: () => void\n onclose?: (reason: string) => void\n alreadyHaveEvent?: (id: string) => boolean\n receivedEvent?: (relay: AbstractRelay, id: string) => void\n eoseTimeout?: number\n}\n\nexport type CountResolver = {\n resolve: (count: number) => void\n reject: (err: Error) => void\n}\n\nexport type EventPublishResolver = {\n resolve: (reason: string) => void\n reject: (err: Error) => void\n timeout: ReturnType\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { Event } from './core.ts'\nimport { isAddressableKind, isReplaceableKind } from './kinds.ts'\n\nexport type Filter = {\n ids?: string[]\n kinds?: number[]\n authors?: string[]\n since?: number\n until?: number\n limit?: number\n search?: string\n [key: `#${string}`]: string[] | undefined\n}\n\nexport function matchFilter(filter: Filter, event: Event): boolean {\n if (filter.ids && filter.ids.indexOf(event.id) === -1) {\n return false\n }\n if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) {\n return false\n }\n if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) {\n return false\n }\n\n for (let f in filter) {\n if (f[0] === '#') {\n let tagName = f.slice(1)\n let values = filter[`#${tagName}`]\n if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values!.indexOf(v) !== -1)) return false\n }\n }\n\n if (filter.since && event.created_at < filter.since) return false\n if (filter.until && event.created_at > filter.until) return false\n\n return true\n}\n\nexport function matchFilters(filters: Filter[], event: Event): boolean {\n for (let i = 0; i < filters.length; i++) {\n if (matchFilter(filters[i], event)) {\n return true\n }\n }\n return false\n}\n\nexport function mergeFilters(...filters: Filter[]): Filter {\n let result: Filter = {}\n for (let i = 0; i < filters.length; i++) {\n let filter = filters[i]\n Object.entries(filter).forEach(([property, values]) => {\n if (property === 'kinds' || property === 'ids' || property === 'authors' || property[0] === '#') {\n // @ts-ignore\n result[property] = result[property] || []\n // @ts-ignore\n for (let v = 0; v < values.length; v++) {\n // @ts-ignore\n let value = values[v]\n // @ts-ignore\n if (!result[property].includes(value)) result[property].push(value)\n }\n }\n })\n\n if (filter.limit && (!result.limit || filter.limit > result.limit)) result.limit = filter.limit\n if (filter.until && (!result.until || filter.until > result.until)) result.until = filter.until\n if (filter.since && (!result.since || filter.since < result.since)) result.since = filter.since\n }\n\n return result\n}\n\n/**\n * Calculate the intrinsic limit of a filter.\n * This function returns a positive integer, or `Infinity` if there is no intrinsic limit.\n */\nexport function getFilterLimit(filter: Filter): number {\n if (filter.ids && !filter.ids.length) return 0\n if (filter.kinds && !filter.kinds.length) return 0\n if (filter.authors && !filter.authors.length) return 0\n\n for (const [key, value] of Object.entries(filter)) {\n if (key[0] === '#' && Array.isArray(value) && !value.length) return 0\n }\n\n return Math.min(\n // The `limit` property creates an artificial limit.\n Math.max(0, filter.limit ?? Infinity),\n\n // There can only be one event per `id`.\n filter.ids?.length ?? Infinity,\n\n // Replaceable events are limited by the number of authors and kinds.\n filter.authors?.length && filter.kinds?.every(kind => isReplaceableKind(kind))\n ? filter.authors.length * filter.kinds.length\n : Infinity,\n\n // Parameterized replaceable events are limited by the number of authors, kinds, and \"d\" tags.\n filter.authors?.length && filter.kinds?.every(kind => isAddressableKind(kind)) && filter['#d']?.length\n ? filter.authors.length * filter.kinds.length * filter['#d'].length\n : Infinity,\n )\n}\n", "export function getHex64(json: string, field: string): string {\n let len = field.length + 3\n let idx = json.indexOf(`\"${field}\":`) + len\n let s = json.slice(idx).indexOf(`\"`) + idx + 1\n return json.slice(s, s + 64)\n}\n\nexport function getInt(json: string, field: string): number {\n let len = field.length\n let idx = json.indexOf(`\"${field}\":`) + len + 3\n let sliced = json.slice(idx)\n let end = Math.min(sliced.indexOf(','), sliced.indexOf('}'))\n return parseInt(sliced.slice(0, end), 10)\n}\n\nexport function getSubscriptionId(json: string): string | null {\n let idx = json.slice(0, 22).indexOf(`\"EVENT\"`)\n if (idx === -1) return null\n\n let pstart = json.slice(idx + 7 + 1).indexOf(`\"`)\n if (pstart === -1) return null\n let start = idx + 7 + 1 + pstart\n\n let pend = json.slice(start + 1, 80).indexOf(`\"`)\n if (pend === -1) return null\n let end = start + 1 + pend\n\n return json.slice(start + 1, end)\n}\n\nexport function matchEventId(json: string, id: string): boolean {\n return id === getHex64(json, 'id')\n}\n\nexport function matchEventPubkey(json: string, pubkey: string): boolean {\n return pubkey === getHex64(json, 'pubkey')\n}\n\nexport function matchEventKind(json: string, kind: number): boolean {\n return kind === getInt(json, 'kind')\n}\n", "import { EventTemplate } from './core.ts'\nimport { ClientAuth } from './kinds.ts'\n\n/**\n * creates an EventTemplate for an AUTH event to be signed.\n */\nexport function makeAuthEvent(relayURL: string, challenge: string): EventTemplate {\n return {\n kind: ClientAuth,\n created_at: Math.floor(Date.now() / 1000),\n tags: [\n ['relay', relayURL],\n ['challenge', challenge],\n ],\n content: '',\n }\n}\n", "import { verifiedSymbol, type Event, type Nostr, VerifiedEvent } from './core.ts'\n\nexport async function yieldThread() {\n return new Promise(resolve => {\n const ch = new MessageChannel()\n const handler = () => {\n // @ts-ignore (typescript thinks this property should be called `removeListener`, but in fact it's `removeEventListener`)\n ch.port1.removeEventListener('message', handler)\n resolve()\n }\n // @ts-ignore (typescript thinks this property should be called `addListener`, but in fact it's `addEventListener`)\n ch.port1.addEventListener('message', handler)\n ch.port2.postMessage(0)\n ch.port1.start()\n })\n}\n\nexport const alwaysTrue: Nostr['verifyEvent'] = (t: Event): t is VerifiedEvent => {\n t[verifiedSymbol] = true\n return true\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKA,mBAAuC;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;AAIjD,SAAS,aAAa,KAAqB;AAChD,MAAI;AACF,QAAI,IAAI,QAAQ,KAAK,MAAM;AAAI,YAAM,WAAW;AAChD,QAAI,IAAI,IAAI,IAAI,GAAG;AACnB,MAAE,WAAW,EAAE,SAAS,QAAQ,QAAQ,GAAG;AAC3C,QAAI,EAAE,SAAS,SAAS,GAAG;AAAG,QAAE,WAAW,EAAE,SAAS,MAAM,GAAG,EAAE;AACjE,QAAK,EAAE,SAAS,QAAQ,EAAE,aAAa,SAAW,EAAE,SAAS,SAAS,EAAE,aAAa;AAAS,QAAE,OAAO;AACvG,MAAE,aAAa,KAAK;AACpB,MAAE,OAAO;AACT,WAAO,EAAE,SAAS;AAAA,EACpB,SAAS,GAAP;AACA,UAAM,IAAI,MAAM,gBAAgB,KAAK;AAAA,EACvC;AACF;AAgDO,IAAM,YAAN,MAAmB;AAAA,EACjB;AAAA,EACA,OAA4B;AAAA,EAC5B,OAA4B;AAAA,EAEnC,YAAY,SAAY;AACtB,SAAK,QAAQ;AAAA,EACf;AACF;AAEO,IAAM,QAAN,MAAe;AAAA,EACb;AAAA,EACA;AAAA,EAEP,c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OAAO,eAAe,MAAM;AAE/C,SAAK,SAAS,OAAO;AACrB,SAAK,UAAU,OAAO;AACtB,SAAK,UACH,OAAO,YACN,WAAS;AACR,cAAQ;AAAA,QACN,oDAAoD,KAAK,gBAAgB,KAAK,MAAM;AAAA,QACpF;AAAA,MACF;AAAA,IACF;AAAA,EACJ;AAAA,EAEO,OAAO;AACZ,SAAK,MAAM,KAAK,aAAa,KAAK,KAAK,OAAO,KAAK,UAAU,KAAK,OAAO,EAAE,UAAU,CAAC,CAAC;AAGvF,SAAK,oBAAoB,WAAW,KAAK,aAAa,KAAK,IAAI,GAAG,KAAK,WAAW;AAAA,EACpF;AAAA,EAEO,eAAe;AACpB,QAAI,KAAK;AAAO;AAChB,iBAAa,KAAK,iBAAiB;AACnC,SAAK,QAAQ;AACb,SAAK,SAAS;AAAA,EAChB;AAAA,EAEO,MAAM,SAAiB,oBAAoB;AAChD,QAAI,CAAC,KAAK,UAAU,KAAK,MAAM,WAAW;AAGxC,UAAI;AACF,aAAK,MAAM,KAAK,cAAc,KAAK,UAAU,KAAK,EAAE,IAAI,GAAG;AAAA,MAC7D,SAAS,KAAP;AACA,YAAI,eAAe,2BAA2B;AAAA,QAE9C,OAAO;AACL,gBAAM;AAAA,QACR;AAAA,MACF;AACA,WAAK,SAAS;AAAA,IAChB;AACA,SAAK,MAAM,SAAS,OAAO,KAAK,EAAE;AAClC,SAAK,UAAU,MAAM;AAAA,EACvB;AACF;", + "names": ["target"] +} diff --git a/node_modules/nostr-tools/lib/cjs/fakejson.js b/node_modules/nostr-tools/lib/cjs/fakejson.js new file mode 100644 index 0000000..4673d05 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/fakejson.js @@ -0,0 +1,66 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// fakejson.ts +var fakejson_exports = {}; +__export(fakejson_exports, { + getHex64: () => getHex64, + getInt: () => getInt, + getSubscriptionId: () => getSubscriptionId, + matchEventId: () => matchEventId, + matchEventKind: () => matchEventKind, + matchEventPubkey: () => matchEventPubkey +}); +module.exports = __toCommonJS(fakejson_exports); +function getHex64(json, field) { + let len = field.length + 3; + let idx = json.indexOf(`"${field}":`) + len; + let s = json.slice(idx).indexOf(`"`) + idx + 1; + return json.slice(s, s + 64); +} +function getInt(json, field) { + let len = field.length; + let idx = json.indexOf(`"${field}":`) + len + 3; + let sliced = json.slice(idx); + let end = Math.min(sliced.indexOf(","), sliced.indexOf("}")); + return parseInt(sliced.slice(0, end), 10); +} +function getSubscriptionId(json) { + let idx = json.slice(0, 22).indexOf(`"EVENT"`); + if (idx === -1) + return null; + let pstart = json.slice(idx + 7 + 1).indexOf(`"`); + if (pstart === -1) + return null; + let start = idx + 7 + 1 + pstart; + let pend = json.slice(start + 1, 80).indexOf(`"`); + if (pend === -1) + return null; + let end = start + 1 + pend; + return json.slice(start + 1, end); +} +function matchEventId(json, id) { + return id === getHex64(json, "id"); +} +function matchEventPubkey(json, pubkey) { + return pubkey === getHex64(json, "pubkey"); +} +function matchEventKind(json, kind) { + return kind === getInt(json, "kind"); +} diff --git a/node_modules/nostr-tools/lib/cjs/fakejson.js.map b/node_modules/nostr-tools/lib/cjs/fakejson.js.map new file mode 100644 index 0000000..a3afb42 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/fakejson.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../fakejson.ts"], + "sourcesContent": ["export function getHex64(json: string, field: string): string {\n let len = field.length + 3\n let idx = json.indexOf(`\"${field}\":`) + len\n let s = json.slice(idx).indexOf(`\"`) + idx + 1\n return json.slice(s, s + 64)\n}\n\nexport function getInt(json: string, field: string): number {\n let len = field.length\n let idx = json.indexOf(`\"${field}\":`) + len + 3\n let sliced = json.slice(idx)\n let end = Math.min(sliced.indexOf(','), sliced.indexOf('}'))\n return parseInt(sliced.slice(0, end), 10)\n}\n\nexport function getSubscriptionId(json: string): string | null {\n let idx = json.slice(0, 22).indexOf(`\"EVENT\"`)\n if (idx === -1) return null\n\n let pstart = json.slice(idx + 7 + 1).indexOf(`\"`)\n if (pstart === -1) return null\n let start = idx + 7 + 1 + pstart\n\n let pend = json.slice(start + 1, 80).indexOf(`\"`)\n if (pend === -1) return null\n let end = start + 1 + pend\n\n return json.slice(start + 1, end)\n}\n\nexport function matchEventId(json: string, id: string): boolean {\n return id === getHex64(json, 'id')\n}\n\nexport function matchEventPubkey(json: string, pubkey: string): boolean {\n return pubkey === getHex64(json, 'pubkey')\n}\n\nexport function matchEventKind(json: string, kind: number): boolean {\n return kind === getInt(json, 'kind')\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAO,SAAS,SAAS,MAAc,OAAuB;AAC5D,MAAI,MAAM,MAAM,SAAS;AACzB,MAAI,MAAM,KAAK,QAAQ,IAAI,SAAS,IAAI;AACxC,MAAI,IAAI,KAAK,MAAM,GAAG,EAAE,QAAQ,GAAG,IAAI,MAAM;AAC7C,SAAO,KAAK,MAAM,GAAG,IAAI,EAAE;AAC7B;AAEO,SAAS,OAAO,MAAc,OAAuB;AAC1D,MAAI,MAAM,MAAM;AAChB,MAAI,MAAM,KAAK,QAAQ,IAAI,SAAS,IAAI,MAAM;AAC9C,MAAI,SAAS,KAAK,MAAM,GAAG;AAC3B,MAAI,MAAM,KAAK,IAAI,OAAO,QAAQ,GAAG,GAAG,OAAO,QAAQ,GAAG,CAAC;AAC3D,SAAO,SAAS,OAAO,MAAM,GAAG,GAAG,GAAG,EAAE;AAC1C;AAEO,SAAS,kBAAkB,MAA6B;AAC7D,MAAI,MAAM,KAAK,MAAM,GAAG,EAAE,EAAE,QAAQ,SAAS;AAC7C,MAAI,QAAQ;AAAI,WAAO;AAEvB,MAAI,SAAS,KAAK,MAAM,MAAM,IAAI,CAAC,EAAE,QAAQ,GAAG;AAChD,MAAI,WAAW;AAAI,WAAO;AAC1B,MAAI,QAAQ,MAAM,IAAI,IAAI;AAE1B,MAAI,OAAO,KAAK,MAAM,QAAQ,GAAG,EAAE,EAAE,QAAQ,GAAG;AAChD,MAAI,SAAS;AAAI,WAAO;AACxB,MAAI,MAAM,QAAQ,IAAI;AAEtB,SAAO,KAAK,MAAM,QAAQ,GAAG,GAAG;AAClC;AAEO,SAAS,aAAa,MAAc,IAAqB;AAC9D,SAAO,OAAO,SAAS,MAAM,IAAI;AACnC;AAEO,SAAS,iBAAiB,MAAc,QAAyB;AACtE,SAAO,WAAW,SAAS,MAAM,QAAQ;AAC3C;AAEO,SAAS,eAAe,MAAc,MAAuB;AAClE,SAAO,SAAS,OAAO,MAAM,MAAM;AACrC;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/cjs/filter.js b/node_modules/nostr-tools/lib/cjs/filter.js new file mode 100644 index 0000000..19eb9c7 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/filter.js @@ -0,0 +1,111 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// filter.ts +var filter_exports = {}; +__export(filter_exports, { + getFilterLimit: () => getFilterLimit, + matchFilter: () => matchFilter, + matchFilters: () => matchFilters, + mergeFilters: () => mergeFilters +}); +module.exports = __toCommonJS(filter_exports); + +// kinds.ts +function isReplaceableKind(kind) { + return [0, 3].includes(kind) || 1e4 <= kind && kind < 2e4; +} +function isAddressableKind(kind) { + return 3e4 <= kind && kind < 4e4; +} + +// filter.ts +function matchFilter(filter, event) { + if (filter.ids && filter.ids.indexOf(event.id) === -1) { + return false; + } + if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) { + return false; + } + if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) { + return false; + } + for (let f in filter) { + if (f[0] === "#") { + let tagName = f.slice(1); + let values = filter[`#${tagName}`]; + if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values.indexOf(v) !== -1)) + return false; + } + } + if (filter.since && event.created_at < filter.since) + return false; + if (filter.until && event.created_at > filter.until) + return false; + return true; +} +function matchFilters(filters, event) { + for (let i = 0; i < filters.length; i++) { + if (matchFilter(filters[i], event)) { + return true; + } + } + return false; +} +function mergeFilters(...filters) { + let result = {}; + for (let i = 0; i < filters.length; i++) { + let filter = filters[i]; + Object.entries(filter).forEach(([property, values]) => { + if (property === "kinds" || property === "ids" || property === "authors" || property[0] === "#") { + result[property] = result[property] || []; + for (let v = 0; v < values.length; v++) { + let value = values[v]; + if (!result[property].includes(value)) + result[property].push(value); + } + } + }); + if (filter.limit && (!result.limit || filter.limit > result.limit)) + result.limit = filter.limit; + if (filter.until && (!result.until || filter.until > result.until)) + result.until = filter.until; + if (filter.since && (!result.since || filter.since < result.since)) + result.since = filter.since; + } + return result; +} +function getFilterLimit(filter) { + if (filter.ids && !filter.ids.length) + return 0; + if (filter.kinds && !filter.kinds.length) + return 0; + if (filter.authors && !filter.authors.length) + return 0; + for (const [key, value] of Object.entries(filter)) { + if (key[0] === "#" && Array.isArray(value) && !value.length) + return 0; + } + return Math.min( + Math.max(0, filter.limit ?? Infinity), + filter.ids?.length ?? Infinity, + filter.authors?.length && filter.kinds?.every((kind) => isReplaceableKind(kind)) ? filter.authors.length * filter.kinds.length : Infinity, + filter.authors?.length && filter.kinds?.every((kind) => isAddressableKind(kind)) && filter["#d"]?.length ? filter.authors.length * filter.kinds.length * filter["#d"].length : Infinity + ); +} diff --git a/node_modules/nostr-tools/lib/cjs/filter.js.map b/node_modules/nostr-tools/lib/cjs/filter.js.map new file mode 100644 index 0000000..7b6cacb --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/filter.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../filter.ts", "../../kinds.ts"], + "sourcesContent": ["import { Event } from './core.ts'\nimport { isAddressableKind, isReplaceableKind } from './kinds.ts'\n\nexport type Filter = {\n ids?: string[]\n kinds?: number[]\n authors?: string[]\n since?: number\n until?: number\n limit?: number\n search?: string\n [key: `#${string}`]: string[] | undefined\n}\n\nexport function matchFilter(filter: Filter, event: Event): boolean {\n if (filter.ids && filter.ids.indexOf(event.id) === -1) {\n return false\n }\n if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) {\n return false\n }\n if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) {\n return false\n }\n\n for (let f in filter) {\n if (f[0] === '#') {\n let tagName = f.slice(1)\n let values = filter[`#${tagName}`]\n if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values!.indexOf(v) !== -1)) return false\n }\n }\n\n if (filter.since && event.created_at < filter.since) return false\n if (filter.until && event.created_at > filter.until) return false\n\n return true\n}\n\nexport function matchFilters(filters: Filter[], event: Event): boolean {\n for (let i = 0; i < filters.length; i++) {\n if (matchFilter(filters[i], event)) {\n return true\n }\n }\n return false\n}\n\nexport function mergeFilters(...filters: Filter[]): Filter {\n let result: Filter = {}\n for (let i = 0; i < filters.length; i++) {\n let filter = filters[i]\n Object.entries(filter).forEach(([property, values]) => {\n if (property === 'kinds' || property === 'ids' || property === 'authors' || property[0] === '#') {\n // @ts-ignore\n result[property] = result[property] || []\n // @ts-ignore\n for (let v = 0; v < values.length; v++) {\n // @ts-ignore\n let value = values[v]\n // @ts-ignore\n if (!result[property].includes(value)) result[property].push(value)\n }\n }\n })\n\n if (filter.limit && (!result.limit || filter.limit > result.limit)) result.limit = filter.limit\n if (filter.until && (!result.until || filter.until > result.until)) result.until = filter.until\n if (filter.since && (!result.since || filter.since < result.since)) result.since = filter.since\n }\n\n return result\n}\n\n/**\n * Calculate the intrinsic limit of a filter.\n * This function returns a positive integer, or `Infinity` if there is no intrinsic limit.\n */\nexport function getFilterLimit(filter: Filter): number {\n if (filter.ids && !filter.ids.length) return 0\n if (filter.kinds && !filter.kinds.length) return 0\n if (filter.authors && !filter.authors.length) return 0\n\n for (const [key, value] of Object.entries(filter)) {\n if (key[0] === '#' && Array.isArray(value) && !value.length) return 0\n }\n\n return Math.min(\n // The `limit` property creates an artificial limit.\n Math.max(0, filter.limit ?? Infinity),\n\n // There can only be one event per `id`.\n filter.ids?.length ?? Infinity,\n\n // Replaceable events are limited by the number of authors and kinds.\n filter.authors?.length && filter.kinds?.every(kind => isReplaceableKind(kind))\n ? filter.authors.length * filter.kinds.length\n : Infinity,\n\n // Parameterized replaceable events are limited by the number of authors, kinds, and \"d\" tags.\n filter.authors?.length && filter.kinds?.every(kind => isAddressableKind(kind)) && filter['#d']?.length\n ? filter.authors.length * filter.kinds.length * filter['#d'].length\n : Infinity,\n )\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACQO,SAAS,kBAAkB,MAAuB;AACvD,SAAO,CAAC,GAAG,CAAC,EAAE,SAAS,IAAI,KAAM,OAAS,QAAQ,OAAO;AAC3D;AAQO,SAAS,kBAAkB,MAAuB;AACvD,SAAO,OAAS,QAAQ,OAAO;AACjC;;;ADNO,SAAS,YAAY,QAAgB,OAAuB;AACjE,MAAI,OAAO,OAAO,OAAO,IAAI,QAAQ,MAAM,EAAE,MAAM,IAAI;AACrD,WAAO;AAAA,EACT;AACA,MAAI,OAAO,SAAS,OAAO,MAAM,QAAQ,MAAM,IAAI,MAAM,IAAI;AAC3D,WAAO;AAAA,EACT;AACA,MAAI,OAAO,WAAW,OAAO,QAAQ,QAAQ,MAAM,MAAM,MAAM,IAAI;AACjE,WAAO;AAAA,EACT;AAEA,WAAS,KAAK,QAAQ;AACpB,QAAI,EAAE,OAAO,KAAK;AAChB,UAAI,UAAU,EAAE,MAAM,CAAC;AACvB,UAAI,SAAS,OAAO,IAAI;AACxB,UAAI,UAAU,CAAC,MAAM,KAAK,KAAK,CAAC,CAAC,GAAG,CAAC,MAAM,MAAM,E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AC,OAAO,IAAI;AAAQ,WAAO;AAC7C,MAAI,OAAO,SAAS,CAAC,OAAO,MAAM;AAAQ,WAAO;AACjD,MAAI,OAAO,WAAW,CAAC,OAAO,QAAQ;AAAQ,WAAO;AAErD,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,MAAM,GAAG;AACjD,QAAI,IAAI,OAAO,OAAO,MAAM,QAAQ,KAAK,KAAK,CAAC,MAAM;AAAQ,aAAO;AAAA,EACtE;AAEA,SAAO,KAAK;AAAA,IAEV,KAAK,IAAI,GAAG,OAAO,SAAS,QAAQ;AAAA,IAGpC,OAAO,KAAK,UAAU;AAAA,IAGtB,OAAO,SAAS,UAAU,OAAO,OAAO,MAAM,UAAQ,kBAAkB,IAAI,CAAC,IACzE,OAAO,QAAQ,SAAS,OAAO,MAAM,SACrC;AAAA,IAGJ,OAAO,SAAS,UAAU,OAAO,OAAO,MAAM,UAAQ,kBAAkB,IAAI,CAAC,KAAK,OAAO,OAAO,SAC5F,OAAO,QAAQ,SAAS,OAAO,MAAM,SAAS,OAAO,MAAM,SAC3D;AAAA,EACN;AACF;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/cjs/index.js b/node_modules/nostr-tools/lib/cjs/index.js new file mode 100644 index 0000000..7612961 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/index.js @@ -0,0 +1,2780 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// index.ts +var nostr_tools_exports = {}; +__export(nostr_tools_exports, { + Relay: () => Relay, + SimplePool: () => SimplePool, + finalizeEvent: () => finalizeEvent, + fj: () => fakejson_exports, + generateSecretKey: () => generateSecretKey, + getEventHash: () => getEventHash, + getFilterLimit: () => getFilterLimit, + getPublicKey: () => getPublicKey, + kinds: () => kinds_exports, + matchFilter: () => matchFilter, + matchFilters: () => matchFilters, + mergeFilters: () => mergeFilters, + nip04: () => nip04_exports, + nip05: () => nip05_exports, + nip10: () => nip10_exports, + nip11: () => nip11_exports, + nip13: () => nip13_exports, + nip17: () => nip17_exports, + nip18: () => nip18_exports, + nip19: () => nip19_exports, + nip21: () => nip21_exports, + nip25: () => nip25_exports, + nip27: () => nip27_exports, + nip28: () => nip28_exports, + nip30: () => nip30_exports, + nip39: () => nip39_exports, + nip42: () => nip42_exports, + nip44: () => nip44_exports, + nip47: () => nip47_exports, + nip54: () => nip54_exports, + nip57: () => nip57_exports, + nip59: () => nip59_exports, + nip98: () => nip98_exports, + parseReferences: () => parseReferences, + serializeEvent: () => serializeEvent, + sortEvents: () => sortEvents, + utils: () => utils_exports, + validateEvent: () => validateEvent, + verifiedSymbol: () => verifiedSymbol, + verifyEvent: () => verifyEvent +}); +module.exports = __toCommonJS(nostr_tools_exports); + +// pure.ts +var import_secp256k1 = require("@noble/curves/secp256k1"); +var import_utils2 = require("@noble/hashes/utils"); + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} +function sortEvents(events) { + return events.sort((a, b) => { + if (a.created_at !== b.created_at) { + return b.created_at - a.created_at; + } + return a.id.localeCompare(b.id); + }); +} + +// pure.ts +var import_sha256 = require("@noble/hashes/sha256"); + +// utils.ts +var utils_exports = {}; +__export(utils_exports, { + Queue: () => Queue, + QueueNode: () => QueueNode, + binarySearch: () => binarySearch, + bytesToHex: () => import_utils.bytesToHex, + hexToBytes: () => import_utils.hexToBytes, + insertEventIntoAscendingList: () => insertEventIntoAscendingList, + insertEventIntoDescendingList: () => insertEventIntoDescendingList, + normalizeURL: () => normalizeURL, + utf8Decoder: () => utf8Decoder, + utf8Encoder: () => utf8Encoder +}); +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); +function normalizeURL(url) { + try { + if (url.indexOf("://") === -1) + url = "wss://" + url; + let p = new URL(url); + p.pathname = p.pathname.replace(/\/+/g, "/"); + if (p.pathname.endsWith("/")) + p.pathname = p.pathname.slice(0, -1); + if (p.port === "80" && p.protocol === "ws:" || p.port === "443" && p.protocol === "wss:") + p.port = ""; + p.searchParams.sort(); + p.hash = ""; + return p.toString(); + } catch (e) { + throw new Error(`Invalid URL: ${url}`); + } +} +function insertEventIntoDescendingList(sortedArray, event) { + const [idx, found] = binarySearch(sortedArray, (b) => { + if (event.id === b.id) + return 0; + if (event.created_at === b.created_at) + return -1; + return b.created_at - event.created_at; + }); + if (!found) { + sortedArray.splice(idx, 0, event); + } + return sortedArray; +} +function insertEventIntoAscendingList(sortedArray, event) { + const [idx, found] = binarySearch(sortedArray, (b) => { + if (event.id === b.id) + return 0; + if (event.created_at === b.created_at) + return -1; + return event.created_at - b.created_at; + }); + if (!found) { + sortedArray.splice(idx, 0, event); + } + return sortedArray; +} +function binarySearch(arr, compare) { + let start = 0; + let end = arr.length - 1; + while (start <= end) { + const mid = Math.floor((start + end) / 2); + const cmp = compare(arr[mid]); + if (cmp === 0) { + return [mid, true]; + } + if (cmp < 0) { + end = mid - 1; + } else { + start = mid + 1; + } + } + return [start, false]; +} +var QueueNode = class { + value; + next = null; + prev = null; + constructor(message) { + this.value = message; + } +}; +var Queue = class { + first; + last; + constructor() { + this.first = null; + this.last = null; + } + enqueue(value) { + const newNode = new QueueNode(value); + if (!this.last) { + this.first = newNode; + this.last = newNode; + } else if (this.last === this.first) { + this.last = newNode; + this.last.prev = this.first; + this.first.next = newNode; + } else { + newNode.prev = this.last; + this.last.next = newNode; + this.last = newNode; + } + return true; + } + dequeue() { + if (!this.first) + return null; + if (this.first === this.last) { + const target2 = this.first; + this.first = null; + this.last = null; + return target2.value; + } + const target = this.first; + this.first = target.next; + if (this.first) { + this.first.prev = null; + } + return target.value; + } +}; + +// pure.ts +var JS = class { + generateSecretKey() { + return import_secp256k1.schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = import_secp256k1.schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = (0, import_sha256.sha256)(utf8Encoder.encode(serializeEvent(event))); + return (0, import_utils2.bytesToHex)(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// kinds.ts +var kinds_exports = {}; +__export(kinds_exports, { + Application: () => Application, + BadgeAward: () => BadgeAward, + BadgeDefinition: () => BadgeDefinition, + BlockedRelaysList: () => BlockedRelaysList, + BookmarkList: () => BookmarkList, + Bookmarksets: () => Bookmarksets, + Calendar: () => Calendar, + CalendarEventRSVP: () => CalendarEventRSVP, + ChannelCreation: () => ChannelCreation, + ChannelHideMessage: () => ChannelHideMessage, + ChannelMessage: () => ChannelMessage, + ChannelMetadata: () => ChannelMetadata, + ChannelMuteUser: () => ChannelMuteUser, + ClassifiedListing: () => ClassifiedListing, + ClientAuth: () => ClientAuth, + CommunitiesList: () => CommunitiesList, + CommunityDefinition: () => CommunityDefinition, + CommunityPostApproval: () => CommunityPostApproval, + Contacts: () => Contacts, + CreateOrUpdateProduct: () => CreateOrUpdateProduct, + CreateOrUpdateStall: () => CreateOrUpdateStall, + Curationsets: () => Curationsets, + Date: () => Date2, + DirectMessageRelaysList: () => DirectMessageRelaysList, + DraftClassifiedListing: () => DraftClassifiedListing, + DraftLong: () => DraftLong, + Emojisets: () => Emojisets, + EncryptedDirectMessage: () => EncryptedDirectMessage, + EventDeletion: () => EventDeletion, + FileMetadata: () => FileMetadata, + FileServerPreference: () => FileServerPreference, + Followsets: () => Followsets, + GenericRepost: () => GenericRepost, + Genericlists: () => Genericlists, + GiftWrap: () => GiftWrap, + HTTPAuth: () => HTTPAuth, + Handlerinformation: () => Handlerinformation, + Handlerrecommendation: () => Handlerrecommendation, + Highlights: () => Highlights, + InterestsList: () => InterestsList, + Interestsets: () => Interestsets, + JobFeedback: () => JobFeedback, + JobRequest: () => JobRequest, + JobResult: () => JobResult, + Label: () => Label, + LightningPubRPC: () => LightningPubRPC, + LiveChatMessage: () => LiveChatMessage, + LiveEvent: () => LiveEvent, + LongFormArticle: () => LongFormArticle, + Metadata: () => Metadata, + Mutelist: () => Mutelist, + NWCWalletInfo: () => NWCWalletInfo, + NWCWalletRequest: () => NWCWalletRequest, + NWCWalletResponse: () => NWCWalletResponse, + NostrConnect: () => NostrConnect, + OpenTimestamps: () => OpenTimestamps, + Pinlist: () => Pinlist, + PrivateDirectMessage: () => PrivateDirectMessage, + ProblemTracker: () => ProblemTracker, + ProfileBadges: () => ProfileBadges, + PublicChatsList: () => PublicChatsList, + Reaction: () => Reaction, + RecommendRelay: () => RecommendRelay, + RelayList: () => RelayList, + Relaysets: () => Relaysets, + Report: () => Report, + Reporting: () => Reporting, + Repost: () => Repost, + Seal: () => Seal, + SearchRelaysList: () => SearchRelaysList, + ShortTextNote: () => ShortTextNote, + Time: () => Time, + UserEmojiList: () => UserEmojiList, + UserStatuses: () => UserStatuses, + Zap: () => Zap, + ZapGoal: () => ZapGoal, + ZapRequest: () => ZapRequest, + classifyKind: () => classifyKind, + isAddressableKind: () => isAddressableKind, + isEphemeralKind: () => isEphemeralKind, + isKind: () => isKind, + isRegularKind: () => isRegularKind, + isReplaceableKind: () => isReplaceableKind +}); +function isRegularKind(kind) { + return 1e3 <= kind && kind < 1e4 || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind); +} +function isReplaceableKind(kind) { + return [0, 3].includes(kind) || 1e4 <= kind && kind < 2e4; +} +function isEphemeralKind(kind) { + return 2e4 <= kind && kind < 3e4; +} +function isAddressableKind(kind) { + return 3e4 <= kind && kind < 4e4; +} +function classifyKind(kind) { + if (isRegularKind(kind)) + return "regular"; + if (isReplaceableKind(kind)) + return "replaceable"; + if (isEphemeralKind(kind)) + return "ephemeral"; + if (isAddressableKind(kind)) + return "parameterized"; + return "unknown"; +} +function isKind(event, kind) { + const kindAsArray = kind instanceof Array ? kind : [kind]; + return validateEvent(event) && kindAsArray.includes(event.kind) || false; +} +var Metadata = 0; +var ShortTextNote = 1; +var RecommendRelay = 2; +var Contacts = 3; +var EncryptedDirectMessage = 4; +var EventDeletion = 5; +var Repost = 6; +var Reaction = 7; +var BadgeAward = 8; +var Seal = 13; +var PrivateDirectMessage = 14; +var GenericRepost = 16; +var ChannelCreation = 40; +var ChannelMetadata = 41; +var ChannelMessage = 42; +var ChannelHideMessage = 43; +var ChannelMuteUser = 44; +var OpenTimestamps = 1040; +var GiftWrap = 1059; +var FileMetadata = 1063; +var LiveChatMessage = 1311; +var ProblemTracker = 1971; +var Report = 1984; +var Reporting = 1984; +var Label = 1985; +var CommunityPostApproval = 4550; +var JobRequest = 5999; +var JobResult = 6999; +var JobFeedback = 7e3; +var ZapGoal = 9041; +var ZapRequest = 9734; +var Zap = 9735; +var Highlights = 9802; +var Mutelist = 1e4; +var Pinlist = 10001; +var RelayList = 10002; +var BookmarkList = 10003; +var CommunitiesList = 10004; +var PublicChatsList = 10005; +var BlockedRelaysList = 10006; +var SearchRelaysList = 10007; +var InterestsList = 10015; +var UserEmojiList = 10030; +var DirectMessageRelaysList = 10050; +var FileServerPreference = 10096; +var NWCWalletInfo = 13194; +var LightningPubRPC = 21e3; +var ClientAuth = 22242; +var NWCWalletRequest = 23194; +var NWCWalletResponse = 23195; +var NostrConnect = 24133; +var HTTPAuth = 27235; +var Followsets = 3e4; +var Genericlists = 30001; +var Relaysets = 30002; +var Bookmarksets = 30003; +var Curationsets = 30004; +var ProfileBadges = 30008; +var BadgeDefinition = 30009; +var Interestsets = 30015; +var CreateOrUpdateStall = 30017; +var CreateOrUpdateProduct = 30018; +var LongFormArticle = 30023; +var DraftLong = 30024; +var Emojisets = 30030; +var Application = 30078; +var LiveEvent = 30311; +var UserStatuses = 30315; +var ClassifiedListing = 30402; +var DraftClassifiedListing = 30403; +var Date2 = 31922; +var Time = 31923; +var Calendar = 31924; +var CalendarEventRSVP = 31925; +var Handlerrecommendation = 31989; +var Handlerinformation = 31990; +var CommunityDefinition = 34550; + +// filter.ts +function matchFilter(filter, event) { + if (filter.ids && filter.ids.indexOf(event.id) === -1) { + return false; + } + if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) { + return false; + } + if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) { + return false; + } + for (let f in filter) { + if (f[0] === "#") { + let tagName = f.slice(1); + let values = filter[`#${tagName}`]; + if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values.indexOf(v) !== -1)) + return false; + } + } + if (filter.since && event.created_at < filter.since) + return false; + if (filter.until && event.created_at > filter.until) + return false; + return true; +} +function matchFilters(filters, event) { + for (let i2 = 0; i2 < filters.length; i2++) { + if (matchFilter(filters[i2], event)) { + return true; + } + } + return false; +} +function mergeFilters(...filters) { + let result = {}; + for (let i2 = 0; i2 < filters.length; i2++) { + let filter = filters[i2]; + Object.entries(filter).forEach(([property, values]) => { + if (property === "kinds" || property === "ids" || property === "authors" || property[0] === "#") { + result[property] = result[property] || []; + for (let v = 0; v < values.length; v++) { + let value = values[v]; + if (!result[property].includes(value)) + result[property].push(value); + } + } + }); + if (filter.limit && (!result.limit || filter.limit > result.limit)) + result.limit = filter.limit; + if (filter.until && (!result.until || filter.until > result.until)) + result.until = filter.until; + if (filter.since && (!result.since || filter.since < result.since)) + result.since = filter.since; + } + return result; +} +function getFilterLimit(filter) { + if (filter.ids && !filter.ids.length) + return 0; + if (filter.kinds && !filter.kinds.length) + return 0; + if (filter.authors && !filter.authors.length) + return 0; + for (const [key, value] of Object.entries(filter)) { + if (key[0] === "#" && Array.isArray(value) && !value.length) + return 0; + } + return Math.min( + Math.max(0, filter.limit ?? Infinity), + filter.ids?.length ?? Infinity, + filter.authors?.length && filter.kinds?.every((kind) => isReplaceableKind(kind)) ? filter.authors.length * filter.kinds.length : Infinity, + filter.authors?.length && filter.kinds?.every((kind) => isAddressableKind(kind)) && filter["#d"]?.length ? filter.authors.length * filter.kinds.length * filter["#d"].length : Infinity + ); +} + +// fakejson.ts +var fakejson_exports = {}; +__export(fakejson_exports, { + getHex64: () => getHex64, + getInt: () => getInt, + getSubscriptionId: () => getSubscriptionId, + matchEventId: () => matchEventId, + matchEventKind: () => matchEventKind, + matchEventPubkey: () => matchEventPubkey +}); +function getHex64(json, field) { + let len = field.length + 3; + let idx = json.indexOf(`"${field}":`) + len; + let s = json.slice(idx).indexOf(`"`) + idx + 1; + return json.slice(s, s + 64); +} +function getInt(json, field) { + let len = field.length; + let idx = json.indexOf(`"${field}":`) + len + 3; + let sliced = json.slice(idx); + let end = Math.min(sliced.indexOf(","), sliced.indexOf("}")); + return parseInt(sliced.slice(0, end), 10); +} +function getSubscriptionId(json) { + let idx = json.slice(0, 22).indexOf(`"EVENT"`); + if (idx === -1) + return null; + let pstart = json.slice(idx + 7 + 1).indexOf(`"`); + if (pstart === -1) + return null; + let start = idx + 7 + 1 + pstart; + let pend = json.slice(start + 1, 80).indexOf(`"`); + if (pend === -1) + return null; + let end = start + 1 + pend; + return json.slice(start + 1, end); +} +function matchEventId(json, id) { + return id === getHex64(json, "id"); +} +function matchEventPubkey(json, pubkey) { + return pubkey === getHex64(json, "pubkey"); +} +function matchEventKind(json, kind) { + return kind === getInt(json, "kind"); +} + +// nip42.ts +var nip42_exports = {}; +__export(nip42_exports, { + makeAuthEvent: () => makeAuthEvent +}); +function makeAuthEvent(relayURL, challenge) { + return { + kind: ClientAuth, + created_at: Math.floor(Date.now() / 1e3), + tags: [ + ["relay", relayURL], + ["challenge", challenge] + ], + content: "" + }; +} + +// helpers.ts +async function yieldThread() { + return new Promise((resolve) => { + const ch = new MessageChannel(); + const handler = () => { + ch.port1.removeEventListener("message", handler); + resolve(); + }; + ch.port1.addEventListener("message", handler); + ch.port2.postMessage(0); + ch.port1.start(); + }); +} +var alwaysTrue = (t) => { + t[verifiedSymbol] = true; + return true; +}; + +// abstract-relay.ts +var SendingOnClosedConnection = class extends Error { + constructor(message, relay) { + super(`Tried to send message '${message} on a closed connection to ${relay}.`); + this.name = "SendingOnClosedConnection"; + } +}; +var AbstractRelay = class { + url; + _connected = false; + onclose = null; + onnotice = (msg) => console.debug(`NOTICE from ${this.url}: ${msg}`); + baseEoseTimeout = 4400; + connectionTimeout = 4400; + publishTimeout = 4400; + pingFrequency = 2e4; + pingTimeout = 2e4; + openSubs = /* @__PURE__ */ new Map(); + enablePing; + connectionTimeoutHandle; + connectionPromise; + openCountRequests = /* @__PURE__ */ new Map(); + openEventPublishes = /* @__PURE__ */ new Map(); + ws; + incomingMessageQueue = new Queue(); + queueRunning = false; + challenge; + authPromise; + serial = 0; + verifyEvent; + _WebSocket; + constructor(url, opts) { + this.url = normalizeURL(url); + this.verifyEvent = opts.verifyEvent; + this._WebSocket = opts.websocketImplementation || WebSocket; + this.enablePing = opts.enablePing; + } + static async connect(url, opts) { + const relay = new AbstractRelay(url, opts); + await relay.connect(); + return relay; + } + closeAllSubscriptions(reason) { + for (let [_, sub] of this.openSubs) { + sub.close(reason); + } + this.openSubs.clear(); + for (let [_, ep] of this.openEventPublishes) { + ep.reject(new Error(reason)); + } + this.openEventPublishes.clear(); + for (let [_, cr] of this.openCountRequests) { + cr.reject(new Error(reason)); + } + this.openCountRequests.clear(); + } + get connected() { + return this._connected; + } + async connect() { + if (this.connectionPromise) + return this.connectionPromise; + this.challenge = void 0; + this.authPromise = void 0; + this.connectionPromise = new Promise((resolve, reject) => { + this.connectionTimeoutHandle = setTimeout(() => { + reject("connection timed out"); + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection timed out"); + }, this.connectionTimeout); + try { + this.ws = new this._WebSocket(this.url); + } catch (err) { + clearTimeout(this.connectionTimeoutHandle); + reject(err); + return; + } + this.ws.onopen = () => { + clearTimeout(this.connectionTimeoutHandle); + this._connected = true; + if (this.enablePing) { + this.pingpong(); + } + resolve(); + }; + this.ws.onerror = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket error"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection errored"); + } + }; + this.ws.onclose = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket closed"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection closed"); + } + }; + this.ws.onmessage = this._onmessage.bind(this); + }); + return this.connectionPromise; + } + async waitForPingPong() { + return new Promise((res, err) => { + ; + this.ws && this.ws.on && this.ws.on("pong", () => res(true)) || err("ws can't listen for pong"); + this.ws && this.ws.ping && this.ws.ping(); + }); + } + async waitForDummyReq() { + return new Promise((resolve, _) => { + const sub = this.subscribe([{ ids: ["a".repeat(64)] }], { + oneose: () => { + sub.close(); + resolve(true); + }, + eoseTimeout: this.pingTimeout + 1e3 + }); + }); + } + async pingpong() { + if (this.ws?.readyState === 1) { + const result = await Promise.any([ + this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(), + new Promise((res) => setTimeout(() => res(false), this.pingTimeout)) + ]); + if (result) { + setTimeout(() => this.pingpong(), this.pingFrequency); + } else { + this.closeAllSubscriptions("pingpong timed out"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + } + } + async runQueue() { + this.queueRunning = true; + while (true) { + if (false === this.handleNext()) { + break; + } + await yieldThread(); + } + this.queueRunning = false; + } + handleNext() { + const json = this.incomingMessageQueue.dequeue(); + if (!json) { + return false; + } + const subid = getSubscriptionId(json); + if (subid) { + const so = this.openSubs.get(subid); + if (!so) { + return; + } + const id = getHex64(json, "id"); + const alreadyHave = so.alreadyHaveEvent?.(id); + so.receivedEvent?.(this, id); + if (alreadyHave) { + return; + } + } + try { + let data = JSON.parse(json); + switch (data[0]) { + case "EVENT": { + const so = this.openSubs.get(data[1]); + const event = data[2]; + if (this.verifyEvent(event) && matchFilters(so.filters, event)) { + so.onevent(event); + } + return; + } + case "COUNT": { + const id = data[1]; + const payload = data[2]; + const cr = this.openCountRequests.get(id); + if (cr) { + cr.resolve(payload.count); + this.openCountRequests.delete(id); + } + return; + } + case "EOSE": { + const so = this.openSubs.get(data[1]); + if (!so) + return; + so.receivedEose(); + return; + } + case "OK": { + const id = data[1]; + const ok = data[2]; + const reason = data[3]; + const ep = this.openEventPublishes.get(id); + if (ep) { + clearTimeout(ep.timeout); + if (ok) + ep.resolve(reason); + else + ep.reject(new Error(reason)); + this.openEventPublishes.delete(id); + } + return; + } + case "CLOSED": { + const id = data[1]; + const so = this.openSubs.get(id); + if (!so) + return; + so.closed = true; + so.close(data[2]); + return; + } + case "NOTICE": + this.onnotice(data[1]); + return; + case "AUTH": { + this.challenge = data[1]; + return; + } + } + } catch (err) { + return; + } + } + async send(message) { + if (!this.connectionPromise) + throw new SendingOnClosedConnection(message, this.url); + this.connectionPromise.then(() => { + this.ws?.send(message); + }); + } + async auth(signAuthEvent) { + const challenge = this.challenge; + if (!challenge) + throw new Error("can't perform auth, no challenge was received"); + if (this.authPromise) + return this.authPromise; + this.authPromise = new Promise(async (resolve, reject) => { + try { + let evt = await signAuthEvent(makeAuthEvent(this.url, challenge)); + let timeout = setTimeout(() => { + let ep = this.openEventPublishes.get(evt.id); + if (ep) { + ep.reject(new Error("auth timed out")); + this.openEventPublishes.delete(evt.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(evt.id, { resolve, reject, timeout }); + this.send('["AUTH",' + JSON.stringify(evt) + "]"); + } catch (err) { + console.warn("subscribe auth function failed:", err); + } + }); + return this.authPromise; + } + async publish(event) { + const ret = new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + const ep = this.openEventPublishes.get(event.id); + if (ep) { + ep.reject(new Error("publish timed out")); + this.openEventPublishes.delete(event.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(event.id, { resolve, reject, timeout }); + }); + this.send('["EVENT",' + JSON.stringify(event) + "]"); + return ret; + } + async count(filters, params) { + this.serial++; + const id = params?.id || "count:" + this.serial; + const ret = new Promise((resolve, reject) => { + this.openCountRequests.set(id, { resolve, reject }); + }); + this.send('["COUNT","' + id + '",' + JSON.stringify(filters).substring(1)); + return ret; + } + subscribe(filters, params) { + const subscription = this.prepareSubscription(filters, params); + subscription.fire(); + return subscription; + } + prepareSubscription(filters, params) { + this.serial++; + const id = params.id || (params.label ? params.label + ":" : "sub:") + this.serial; + const subscription = new Subscription(this, id, filters, params); + this.openSubs.set(id, subscription); + return subscription; + } + close() { + this.closeAllSubscriptions("relay connection closed by us"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + _onmessage(ev) { + this.incomingMessageQueue.enqueue(ev.data); + if (!this.queueRunning) { + this.runQueue(); + } + } +}; +var Subscription = class { + relay; + id; + closed = false; + eosed = false; + filters; + alreadyHaveEvent; + receivedEvent; + onevent; + oneose; + onclose; + eoseTimeout; + eoseTimeoutHandle; + constructor(relay, id, filters, params) { + this.relay = relay; + this.filters = filters; + this.id = id; + this.alreadyHaveEvent = params.alreadyHaveEvent; + this.receivedEvent = params.receivedEvent; + this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout; + this.oneose = params.oneose; + this.onclose = params.onclose; + this.onevent = params.onevent || ((event) => { + console.warn( + `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`, + event + ); + }); + } + fire() { + this.relay.send('["REQ","' + this.id + '",' + JSON.stringify(this.filters).substring(1)); + this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout); + } + receivedEose() { + if (this.eosed) + return; + clearTimeout(this.eoseTimeoutHandle); + this.eosed = true; + this.oneose?.(); + } + close(reason = "closed by caller") { + if (!this.closed && this.relay.connected) { + try { + this.relay.send('["CLOSE",' + JSON.stringify(this.id) + "]"); + } catch (err) { + if (err instanceof SendingOnClosedConnection) { + } else { + throw err; + } + } + this.closed = true; + } + this.relay.openSubs.delete(this.id); + this.onclose?.(reason); + } +}; + +// relay.ts +var _WebSocket; +try { + _WebSocket = WebSocket; +} catch { +} +var Relay = class extends AbstractRelay { + constructor(url) { + super(url, { verifyEvent, websocketImplementation: _WebSocket }); + } + static async connect(url) { + const relay = new Relay(url); + await relay.connect(); + return relay; + } +}; + +// abstract-pool.ts +var AbstractSimplePool = class { + relays = /* @__PURE__ */ new Map(); + seenOn = /* @__PURE__ */ new Map(); + trackRelays = false; + verifyEvent; + enablePing; + trustedRelayURLs = /* @__PURE__ */ new Set(); + _WebSocket; + constructor(opts) { + this.verifyEvent = opts.verifyEvent; + this._WebSocket = opts.websocketImplementation; + this.enablePing = opts.enablePing; + } + async ensureRelay(url, params) { + url = normalizeURL(url); + let relay = this.relays.get(url); + if (!relay) { + relay = new AbstractRelay(url, { + verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent, + websocketImplementation: this._WebSocket, + enablePing: this.enablePing + }); + relay.onclose = () => { + this.relays.delete(url); + }; + if (params?.connectionTimeout) + relay.connectionTimeout = params.connectionTimeout; + this.relays.set(url, relay); + } + await relay.connect(); + return relay; + } + close(relays) { + relays.map(normalizeURL).forEach((url) => { + this.relays.get(url)?.close(); + this.relays.delete(url); + }); + } + subscribe(relays, filter, params) { + params.onauth = params.onauth || params.doauth; + const request = []; + for (let i2 = 0; i2 < relays.length; i2++) { + const url = normalizeURL(relays[i2]); + if (!request.find((r) => r.url === url)) { + request.push({ url, filter }); + } + } + return this.subscribeMap(request, params); + } + subscribeMany(relays, filters, params) { + params.onauth = params.onauth || params.doauth; + const request = []; + const uniqUrls = []; + for (let i2 = 0; i2 < relays.length; i2++) { + const url = normalizeURL(relays[i2]); + if (uniqUrls.indexOf(url) === -1) { + for (let f = 0; f < filters.length; f++) { + request.push({ url, filter: filters[f] }); + } + } + } + return this.subscribeMap(request, params); + } + subscribeMap(requests, params) { + params.onauth = params.onauth || params.doauth; + if (this.trackRelays) { + params.receivedEvent = (relay, id) => { + let set = this.seenOn.get(id); + if (!set) { + set = /* @__PURE__ */ new Set(); + this.seenOn.set(id, set); + } + set.add(relay); + }; + } + const _knownIds = /* @__PURE__ */ new Set(); + const subs = []; + const eosesReceived = []; + let handleEose = (i2) => { + if (eosesReceived[i2]) + return; + eosesReceived[i2] = true; + if (eosesReceived.filter((a) => a).length === requests.length) { + params.oneose?.(); + handleEose = () => { + }; + } + }; + const closesReceived = []; + let handleClose = (i2, reason) => { + if (closesReceived[i2]) + return; + handleEose(i2); + closesReceived[i2] = reason; + if (closesReceived.filter((a) => a).length === requests.length) { + params.onclose?.(closesReceived); + handleClose = () => { + }; + } + }; + const localAlreadyHaveEventHandler = (id) => { + if (params.alreadyHaveEvent?.(id)) { + return true; + } + const have = _knownIds.has(id); + _knownIds.add(id); + return have; + }; + const allOpened = Promise.all( + requests.map(async ({ url, filter }, i2) => { + let relay; + try { + relay = await this.ensureRelay(url, { + connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1e3) : void 0 + }); + } catch (err) { + handleClose(i2, err?.message || String(err)); + return; + } + let subscription = relay.subscribe([filter], { + ...params, + oneose: () => handleEose(i2), + onclose: (reason) => { + if (reason.startsWith("auth-required: ") && params.onauth) { + relay.auth(params.onauth).then(() => { + relay.subscribe([filter], { + ...params, + oneose: () => handleEose(i2), + onclose: (reason2) => { + handleClose(i2, reason2); + }, + alreadyHaveEvent: localAlreadyHaveEventHandler, + eoseTimeout: params.maxWait + }); + }).catch((err) => { + handleClose(i2, `auth was required and attempted, but failed with: ${err}`); + }); + } else { + handleClose(i2, reason); + } + }, + alreadyHaveEvent: localAlreadyHaveEventHandler, + eoseTimeout: params.maxWait + }); + subs.push(subscription); + }) + ); + return { + async close(reason) { + await allOpened; + subs.forEach((sub) => { + sub.close(reason); + }); + } + }; + } + subscribeEose(relays, filter, params) { + params.onauth = params.onauth || params.doauth; + const subcloser = this.subscribe(relays, filter, { + ...params, + oneose() { + subcloser.close("closed automatically on eose"); + } + }); + return subcloser; + } + subscribeManyEose(relays, filters, params) { + params.onauth = params.onauth || params.doauth; + const subcloser = this.subscribeMany(relays, filters, { + ...params, + oneose() { + subcloser.close("closed automatically on eose"); + } + }); + return subcloser; + } + async querySync(relays, filter, params) { + return new Promise(async (resolve) => { + const events = []; + this.subscribeEose(relays, filter, { + ...params, + onevent(event) { + events.push(event); + }, + onclose(_) { + resolve(events); + } + }); + }); + } + async get(relays, filter, params) { + filter.limit = 1; + const events = await this.querySync(relays, filter, params); + events.sort((a, b) => b.created_at - a.created_at); + return events[0] || null; + } + publish(relays, event, options) { + return relays.map(normalizeURL).map(async (url, i2, arr) => { + if (arr.indexOf(url) !== i2) { + return Promise.reject("duplicate url"); + } + let r = await this.ensureRelay(url); + return r.publish(event).catch(async (err) => { + if (err instanceof Error && err.message.startsWith("auth-required: ") && options?.onauth) { + await r.auth(options.onauth); + return r.publish(event); + } + throw err; + }).then((reason) => { + if (this.trackRelays) { + let set = this.seenOn.get(event.id); + if (!set) { + set = /* @__PURE__ */ new Set(); + this.seenOn.set(event.id, set); + } + set.add(r); + } + return reason; + }); + }); + } + listConnectionStatus() { + const map = /* @__PURE__ */ new Map(); + this.relays.forEach((relay, url) => map.set(url, relay.connected)); + return map; + } + destroy() { + this.relays.forEach((conn) => conn.close()); + this.relays = /* @__PURE__ */ new Map(); + } +}; + +// pool.ts +var _WebSocket2; +try { + _WebSocket2 = WebSocket; +} catch { +} +var SimplePool = class extends AbstractSimplePool { + constructor(options) { + super({ verifyEvent, websocketImplementation: _WebSocket2, ...options }); + } +}; + +// nip19.ts +var nip19_exports = {}; +__export(nip19_exports, { + BECH32_REGEX: () => BECH32_REGEX, + Bech32MaxSize: () => Bech32MaxSize, + NostrTypeGuard: () => NostrTypeGuard, + decode: () => decode, + decodeNostrURI: () => decodeNostrURI, + encodeBytes: () => encodeBytes, + naddrEncode: () => naddrEncode, + neventEncode: () => neventEncode, + noteEncode: () => noteEncode, + nprofileEncode: () => nprofileEncode, + npubEncode: () => npubEncode, + nsecEncode: () => nsecEncode +}); +var import_utils6 = require("@noble/hashes/utils"); +var import_base = require("@scure/base"); +var NostrTypeGuard = { + isNProfile: (value) => /^nprofile1[a-z\d]+$/.test(value || ""), + isNEvent: (value) => /^nevent1[a-z\d]+$/.test(value || ""), + isNAddr: (value) => /^naddr1[a-z\d]+$/.test(value || ""), + isNSec: (value) => /^nsec1[a-z\d]{58}$/.test(value || ""), + isNPub: (value) => /^npub1[a-z\d]{58}$/.test(value || ""), + isNote: (value) => /^note1[a-z\d]+$/.test(value || ""), + isNcryptsec: (value) => /^ncryptsec1[a-z\d]+$/.test(value || "") +}; +var Bech32MaxSize = 5e3; +var BECH32_REGEX = /[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/; +function integerToUint8Array(number) { + const uint8Array = new Uint8Array(4); + uint8Array[0] = number >> 24 & 255; + uint8Array[1] = number >> 16 & 255; + uint8Array[2] = number >> 8 & 255; + uint8Array[3] = number & 255; + return uint8Array; +} +function decodeNostrURI(nip19code) { + try { + if (nip19code.startsWith("nostr:")) + nip19code = nip19code.substring(6); + return decode(nip19code); + } catch (_err) { + return { type: "invalid", data: null }; + } +} +function decode(code) { + let { prefix, words } = import_base.bech32.decode(code, Bech32MaxSize); + let data = new Uint8Array(import_base.bech32.fromWords(words)); + switch (prefix) { + case "nprofile": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nprofile"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + return { + type: "nprofile", + data: { + pubkey: (0, import_utils6.bytesToHex)(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nevent": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nevent"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + if (tlv[2] && tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (tlv[3] && tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "nevent", + data: { + id: (0, import_utils6.bytesToHex)(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [], + author: tlv[2]?.[0] ? (0, import_utils6.bytesToHex)(tlv[2][0]) : void 0, + kind: tlv[3]?.[0] ? parseInt((0, import_utils6.bytesToHex)(tlv[3][0]), 16) : void 0 + } + }; + } + case "naddr": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for naddr"); + if (!tlv[2]?.[0]) + throw new Error("missing TLV 2 for naddr"); + if (tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (!tlv[3]?.[0]) + throw new Error("missing TLV 3 for naddr"); + if (tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "naddr", + data: { + identifier: utf8Decoder.decode(tlv[0][0]), + pubkey: (0, import_utils6.bytesToHex)(tlv[2][0]), + kind: parseInt((0, import_utils6.bytesToHex)(tlv[3][0]), 16), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nsec": + return { type: prefix, data }; + case "npub": + case "note": + return { type: prefix, data: (0, import_utils6.bytesToHex)(data) }; + default: + throw new Error(`unknown prefix ${prefix}`); + } +} +function parseTLV(data) { + let result = {}; + let rest = data; + while (rest.length > 0) { + let t = rest[0]; + let l = rest[1]; + let v = rest.slice(2, 2 + l); + rest = rest.slice(2 + l); + if (v.length < l) + throw new Error(`not enough data to read on TLV ${t}`); + result[t] = result[t] || []; + result[t].push(v); + } + return result; +} +function nsecEncode(key) { + return encodeBytes("nsec", key); +} +function npubEncode(hex) { + return encodeBytes("npub", (0, import_utils6.hexToBytes)(hex)); +} +function noteEncode(hex) { + return encodeBytes("note", (0, import_utils6.hexToBytes)(hex)); +} +function encodeBech32(prefix, data) { + let words = import_base.bech32.toWords(data); + return import_base.bech32.encode(prefix, words, Bech32MaxSize); +} +function encodeBytes(prefix, bytes) { + return encodeBech32(prefix, bytes); +} +function nprofileEncode(profile) { + let data = encodeTLV({ + 0: [(0, import_utils6.hexToBytes)(profile.pubkey)], + 1: (profile.relays || []).map((url) => utf8Encoder.encode(url)) + }); + return encodeBech32("nprofile", data); +} +function neventEncode(event) { + let kindArray; + if (event.kind !== void 0) { + kindArray = integerToUint8Array(event.kind); + } + let data = encodeTLV({ + 0: [(0, import_utils6.hexToBytes)(event.id)], + 1: (event.relays || []).map((url) => utf8Encoder.encode(url)), + 2: event.author ? [(0, import_utils6.hexToBytes)(event.author)] : [], + 3: kindArray ? [new Uint8Array(kindArray)] : [] + }); + return encodeBech32("nevent", data); +} +function naddrEncode(addr) { + let kind = new ArrayBuffer(4); + new DataView(kind).setUint32(0, addr.kind, false); + let data = encodeTLV({ + 0: [utf8Encoder.encode(addr.identifier)], + 1: (addr.relays || []).map((url) => utf8Encoder.encode(url)), + 2: [(0, import_utils6.hexToBytes)(addr.pubkey)], + 3: [new Uint8Array(kind)] + }); + return encodeBech32("naddr", data); +} +function encodeTLV(tlv) { + let entries = []; + Object.entries(tlv).reverse().forEach(([t, vs]) => { + vs.forEach((v) => { + let entry = new Uint8Array(v.length + 2); + entry.set([parseInt(t)], 0); + entry.set([v.length], 1); + entry.set(v, 2); + entries.push(entry); + }); + }); + return (0, import_utils6.concatBytes)(...entries); +} + +// references.ts +var mentionRegex = /\bnostr:((note|npub|naddr|nevent|nprofile)1\w+)\b|#\[(\d+)\]/g; +function parseReferences(evt) { + let references = []; + for (let ref of evt.content.matchAll(mentionRegex)) { + if (ref[2]) { + try { + let { type, data } = decode(ref[1]); + switch (type) { + case "npub": { + references.push({ + text: ref[0], + profile: { pubkey: data, relays: [] } + }); + break; + } + case "nprofile": { + references.push({ + text: ref[0], + profile: data + }); + break; + } + case "note": { + references.push({ + text: ref[0], + event: { id: data, relays: [] } + }); + break; + } + case "nevent": { + references.push({ + text: ref[0], + event: data + }); + break; + } + case "naddr": { + references.push({ + text: ref[0], + address: data + }); + break; + } + } + } catch (err) { + } + } else if (ref[3]) { + let idx = parseInt(ref[3], 10); + let tag = evt.tags[idx]; + if (!tag) + continue; + switch (tag[0]) { + case "p": { + references.push({ + text: ref[0], + profile: { pubkey: tag[1], relays: tag[2] ? [tag[2]] : [] } + }); + break; + } + case "e": { + references.push({ + text: ref[0], + event: { id: tag[1], relays: tag[2] ? [tag[2]] : [] } + }); + break; + } + case "a": { + try { + let [kind, pubkey, identifier] = tag[1].split(":"); + references.push({ + text: ref[0], + address: { + identifier, + pubkey, + kind: parseInt(kind, 10), + relays: tag[2] ? [tag[2]] : [] + } + }); + } catch (err) { + } + break; + } + } + } + } + return references; +} + +// nip04.ts +var nip04_exports = {}; +__export(nip04_exports, { + decrypt: () => decrypt, + encrypt: () => encrypt +}); +var import_utils8 = require("@noble/hashes/utils"); +var import_secp256k12 = require("@noble/curves/secp256k1"); +var import_aes = require("@noble/ciphers/aes"); +var import_base2 = require("@scure/base"); +function encrypt(secretKey, pubkey, text) { + const privkey = secretKey instanceof Uint8Array ? (0, import_utils8.bytesToHex)(secretKey) : secretKey; + const key = import_secp256k12.secp256k1.getSharedSecret(privkey, "02" + pubkey); + const normalizedKey = getNormalizedX(key); + let iv = Uint8Array.from((0, import_utils8.randomBytes)(16)); + let plaintext = utf8Encoder.encode(text); + let ciphertext = (0, import_aes.cbc)(normalizedKey, iv).encrypt(plaintext); + let ctb64 = import_base2.base64.encode(new Uint8Array(ciphertext)); + let ivb64 = import_base2.base64.encode(new Uint8Array(iv.buffer)); + return `${ctb64}?iv=${ivb64}`; +} +function decrypt(secretKey, pubkey, data) { + const privkey = secretKey instanceof Uint8Array ? (0, import_utils8.bytesToHex)(secretKey) : secretKey; + let [ctb64, ivb64] = data.split("?iv="); + let key = import_secp256k12.secp256k1.getSharedSecret(privkey, "02" + pubkey); + let normalizedKey = getNormalizedX(key); + let iv = import_base2.base64.decode(ivb64); + let ciphertext = import_base2.base64.decode(ctb64); + let plaintext = (0, import_aes.cbc)(normalizedKey, iv).decrypt(ciphertext); + return utf8Decoder.decode(plaintext); +} +function getNormalizedX(key) { + return key.slice(1, 33); +} + +// nip05.ts +var nip05_exports = {}; +__export(nip05_exports, { + NIP05_REGEX: () => NIP05_REGEX, + isNip05: () => isNip05, + isValid: () => isValid, + queryProfile: () => queryProfile, + searchDomain: () => searchDomain, + useFetchImplementation: () => useFetchImplementation +}); +var NIP05_REGEX = /^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/; +var isNip05 = (value) => NIP05_REGEX.test(value || ""); +var _fetch; +try { + _fetch = fetch; +} catch (_) { + null; +} +function useFetchImplementation(fetchImplementation) { + _fetch = fetchImplementation; +} +async function searchDomain(domain, query = "") { + try { + const url = `https://${domain}/.well-known/nostr.json?name=${query}`; + const res = await _fetch(url, { redirect: "manual" }); + if (res.status !== 200) { + throw Error("Wrong response code"); + } + const json = await res.json(); + return json.names; + } catch (_) { + return {}; + } +} +async function queryProfile(fullname) { + const match = fullname.match(NIP05_REGEX); + if (!match) + return null; + const [, name = "_", domain] = match; + try { + const url = `https://${domain}/.well-known/nostr.json?name=${name}`; + const res = await _fetch(url, { redirect: "manual" }); + if (res.status !== 200) { + throw Error("Wrong response code"); + } + const json = await res.json(); + const pubkey = json.names[name]; + return pubkey ? { pubkey, relays: json.relays?.[pubkey] } : null; + } catch (_e) { + return null; + } +} +async function isValid(pubkey, nip05) { + const res = await queryProfile(nip05); + return res ? res.pubkey === pubkey : false; +} + +// nip10.ts +var nip10_exports = {}; +__export(nip10_exports, { + parse: () => parse +}); +function parse(event) { + const result = { + reply: void 0, + root: void 0, + mentions: [], + profiles: [], + quotes: [] + }; + let maybeParent; + let maybeRoot; + for (let i2 = event.tags.length - 1; i2 >= 0; i2--) { + const tag = event.tags[i2]; + if (tag[0] === "e" && tag[1]) { + const [_, eTagEventId, eTagRelayUrl, eTagMarker, eTagAuthor] = tag; + const eventPointer = { + id: eTagEventId, + relays: eTagRelayUrl ? [eTagRelayUrl] : [], + author: eTagAuthor + }; + if (eTagMarker === "root") { + result.root = eventPointer; + continue; + } + if (eTagMarker === "reply") { + result.reply = eventPointer; + continue; + } + if (eTagMarker === "mention") { + result.mentions.push(eventPointer); + continue; + } + if (!maybeParent) { + maybeParent = eventPointer; + } else { + maybeRoot = eventPointer; + } + result.mentions.push(eventPointer); + continue; + } + if (tag[0] === "q" && tag[1]) { + const [_, eTagEventId, eTagRelayUrl] = tag; + result.quotes.push({ + id: eTagEventId, + relays: eTagRelayUrl ? [eTagRelayUrl] : [] + }); + } + if (tag[0] === "p" && tag[1]) { + result.profiles.push({ + pubkey: tag[1], + relays: tag[2] ? [tag[2]] : [] + }); + continue; + } + } + if (!result.root) { + result.root = maybeRoot || maybeParent || result.reply; + } + if (!result.reply) { + result.reply = maybeParent || result.root; + } + ; + [result.reply, result.root].forEach((ref) => { + if (!ref) + return; + let idx = result.mentions.indexOf(ref); + if (idx !== -1) { + result.mentions.splice(idx, 1); + } + if (ref.author) { + let author = result.profiles.find((p) => p.pubkey === ref.author); + if (author && author.relays) { + if (!ref.relays) { + ref.relays = []; + } + author.relays.forEach((url) => { + if (ref.relays?.indexOf(url) === -1) + ref.relays.push(url); + }); + author.relays = ref.relays; + } + } + }); + result.mentions.forEach((ref) => { + if (ref.author) { + let author = result.profiles.find((p) => p.pubkey === ref.author); + if (author && author.relays) { + if (!ref.relays) { + ref.relays = []; + } + author.relays.forEach((url) => { + if (ref.relays.indexOf(url) === -1) + ref.relays.push(url); + }); + author.relays = ref.relays; + } + } + }); + return result; +} + +// nip11.ts +var nip11_exports = {}; +__export(nip11_exports, { + fetchRelayInformation: () => fetchRelayInformation, + useFetchImplementation: () => useFetchImplementation2 +}); +var _fetch2; +try { + _fetch2 = fetch; +} catch { +} +function useFetchImplementation2(fetchImplementation) { + _fetch2 = fetchImplementation; +} +async function fetchRelayInformation(url) { + return await (await fetch(url.replace("ws://", "http://").replace("wss://", "https://"), { + headers: { Accept: "application/nostr+json" } + })).json(); +} + +// nip13.ts +var nip13_exports = {}; +__export(nip13_exports, { + fastEventHash: () => fastEventHash, + getPow: () => getPow, + minePow: () => minePow +}); +var import_utils10 = require("@noble/hashes/utils"); +var import_sha2562 = require("@noble/hashes/sha256"); +function getPow(hex) { + let count = 0; + for (let i2 = 0; i2 < 64; i2 += 8) { + const nibble = parseInt(hex.substring(i2, i2 + 8), 16); + if (nibble === 0) { + count += 32; + } else { + count += Math.clz32(nibble); + break; + } + } + return count; +} +function minePow(unsigned, difficulty) { + let count = 0; + const event = unsigned; + const tag = ["nonce", count.toString(), difficulty.toString()]; + event.tags.push(tag); + while (true) { + const now2 = Math.floor(new Date().getTime() / 1e3); + if (now2 !== event.created_at) { + count = 0; + event.created_at = now2; + } + tag[1] = (++count).toString(); + event.id = fastEventHash(event); + if (getPow(event.id) >= difficulty) { + break; + } + } + return event; +} +function fastEventHash(evt) { + return (0, import_utils10.bytesToHex)( + (0, import_sha2562.sha256)(utf8Encoder.encode(JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]))) + ); +} + +// nip17.ts +var nip17_exports = {}; +__export(nip17_exports, { + unwrapEvent: () => unwrapEvent2, + unwrapManyEvents: () => unwrapManyEvents2, + wrapEvent: () => wrapEvent2, + wrapManyEvents: () => wrapManyEvents2 +}); + +// nip59.ts +var nip59_exports = {}; +__export(nip59_exports, { + createRumor: () => createRumor, + createSeal: () => createSeal, + createWrap: () => createWrap, + unwrapEvent: () => unwrapEvent, + unwrapManyEvents: () => unwrapManyEvents, + wrapEvent: () => wrapEvent, + wrapManyEvents: () => wrapManyEvents +}); + +// nip44.ts +var nip44_exports = {}; +__export(nip44_exports, { + decrypt: () => decrypt2, + encrypt: () => encrypt2, + getConversationKey: () => getConversationKey, + v2: () => v2 +}); +var import_chacha = require("@noble/ciphers/chacha"); +var import_utils12 = require("@noble/ciphers/utils"); +var import_secp256k13 = require("@noble/curves/secp256k1"); +var import_hkdf = require("@noble/hashes/hkdf"); +var import_hmac = require("@noble/hashes/hmac"); +var import_sha2563 = require("@noble/hashes/sha256"); +var import_utils13 = require("@noble/hashes/utils"); +var import_base3 = require("@scure/base"); +var minPlaintextSize = 1; +var maxPlaintextSize = 65535; +function getConversationKey(privkeyA, pubkeyB) { + const sharedX = import_secp256k13.secp256k1.getSharedSecret(privkeyA, "02" + pubkeyB).subarray(1, 33); + return (0, import_hkdf.extract)(import_sha2563.sha256, sharedX, "nip44-v2"); +} +function getMessageKeys(conversationKey, nonce) { + const keys = (0, import_hkdf.expand)(import_sha2563.sha256, conversationKey, nonce, 76); + return { + chacha_key: keys.subarray(0, 32), + chacha_nonce: keys.subarray(32, 44), + hmac_key: keys.subarray(44, 76) + }; +} +function calcPaddedLen(len) { + if (!Number.isSafeInteger(len) || len < 1) + throw new Error("expected positive integer"); + if (len <= 32) + return 32; + const nextPower = 1 << Math.floor(Math.log2(len - 1)) + 1; + const chunk = nextPower <= 256 ? 32 : nextPower / 8; + return chunk * (Math.floor((len - 1) / chunk) + 1); +} +function writeU16BE(num) { + if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize) + throw new Error("invalid plaintext size: must be between 1 and 65535 bytes"); + const arr = new Uint8Array(2); + new DataView(arr.buffer).setUint16(0, num, false); + return arr; +} +function pad(plaintext) { + const unpadded = utf8Encoder.encode(plaintext); + const unpaddedLen = unpadded.length; + const prefix = writeU16BE(unpaddedLen); + const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen); + return (0, import_utils13.concatBytes)(prefix, unpadded, suffix); +} +function unpad(padded) { + const unpaddedLen = new DataView(padded.buffer).getUint16(0); + const unpadded = padded.subarray(2, 2 + unpaddedLen); + if (unpaddedLen < minPlaintextSize || unpaddedLen > maxPlaintextSize || unpadded.length !== unpaddedLen || padded.length !== 2 + calcPaddedLen(unpaddedLen)) + throw new Error("invalid padding"); + return utf8Decoder.decode(unpadded); +} +function hmacAad(key, message, aad) { + if (aad.length !== 32) + throw new Error("AAD associated data must be 32 bytes"); + const combined = (0, import_utils13.concatBytes)(aad, message); + return (0, import_hmac.hmac)(import_sha2563.sha256, key, combined); +} +function decodePayload(payload) { + if (typeof payload !== "string") + throw new Error("payload must be a valid string"); + const plen = payload.length; + if (plen < 132 || plen > 87472) + throw new Error("invalid payload length: " + plen); + if (payload[0] === "#") + throw new Error("unknown encryption version"); + let data; + try { + data = import_base3.base64.decode(payload); + } catch (error) { + throw new Error("invalid base64: " + error.message); + } + const dlen = data.length; + if (dlen < 99 || dlen > 65603) + throw new Error("invalid data length: " + dlen); + const vers = data[0]; + if (vers !== 2) + throw new Error("unknown encryption version " + vers); + return { + nonce: data.subarray(1, 33), + ciphertext: data.subarray(33, -32), + mac: data.subarray(-32) + }; +} +function encrypt2(plaintext, conversationKey, nonce = (0, import_utils13.randomBytes)(32)) { + const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); + const padded = pad(plaintext); + const ciphertext = (0, import_chacha.chacha20)(chacha_key, chacha_nonce, padded); + const mac = hmacAad(hmac_key, ciphertext, nonce); + return import_base3.base64.encode((0, import_utils13.concatBytes)(new Uint8Array([2]), nonce, ciphertext, mac)); +} +function decrypt2(payload, conversationKey) { + const { nonce, ciphertext, mac } = decodePayload(payload); + const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); + const calculatedMac = hmacAad(hmac_key, ciphertext, nonce); + if (!(0, import_utils12.equalBytes)(calculatedMac, mac)) + throw new Error("invalid MAC"); + const padded = (0, import_chacha.chacha20)(chacha_key, chacha_nonce, ciphertext); + return unpad(padded); +} +var v2 = { + utils: { + getConversationKey, + calcPaddedLen + }, + encrypt: encrypt2, + decrypt: decrypt2 +}; + +// nip59.ts +var TWO_DAYS = 2 * 24 * 60 * 60; +var now = () => Math.round(Date.now() / 1e3); +var randomNow = () => Math.round(now() - Math.random() * TWO_DAYS); +var nip44ConversationKey = (privateKey, publicKey) => getConversationKey(privateKey, publicKey); +var nip44Encrypt = (data, privateKey, publicKey) => encrypt2(JSON.stringify(data), nip44ConversationKey(privateKey, publicKey)); +var nip44Decrypt = (data, privateKey) => JSON.parse(decrypt2(data.content, nip44ConversationKey(privateKey, data.pubkey))); +function createRumor(event, privateKey) { + const rumor = { + created_at: now(), + content: "", + tags: [], + ...event, + pubkey: getPublicKey(privateKey) + }; + rumor.id = getEventHash(rumor); + return rumor; +} +function createSeal(rumor, privateKey, recipientPublicKey) { + return finalizeEvent( + { + kind: Seal, + content: nip44Encrypt(rumor, privateKey, recipientPublicKey), + created_at: randomNow(), + tags: [] + }, + privateKey + ); +} +function createWrap(seal, recipientPublicKey) { + const randomKey = generateSecretKey(); + return finalizeEvent( + { + kind: GiftWrap, + content: nip44Encrypt(seal, randomKey, recipientPublicKey), + created_at: randomNow(), + tags: [["p", recipientPublicKey]] + }, + randomKey + ); +} +function wrapEvent(event, senderPrivateKey, recipientPublicKey) { + const rumor = createRumor(event, senderPrivateKey); + const seal = createSeal(rumor, senderPrivateKey, recipientPublicKey); + return createWrap(seal, recipientPublicKey); +} +function wrapManyEvents(event, senderPrivateKey, recipientsPublicKeys) { + if (!recipientsPublicKeys || recipientsPublicKeys.length === 0) { + throw new Error("At least one recipient is required."); + } + const senderPublicKey = getPublicKey(senderPrivateKey); + const wrappeds = [wrapEvent(event, senderPrivateKey, senderPublicKey)]; + recipientsPublicKeys.forEach((recipientPublicKey) => { + wrappeds.push(wrapEvent(event, senderPrivateKey, recipientPublicKey)); + }); + return wrappeds; +} +function unwrapEvent(wrap, recipientPrivateKey) { + const unwrappedSeal = nip44Decrypt(wrap, recipientPrivateKey); + return nip44Decrypt(unwrappedSeal, recipientPrivateKey); +} +function unwrapManyEvents(wrappedEvents, recipientPrivateKey) { + let unwrappedEvents = []; + wrappedEvents.forEach((e) => { + unwrappedEvents.push(unwrapEvent(e, recipientPrivateKey)); + }); + unwrappedEvents.sort((a, b) => a.created_at - b.created_at); + return unwrappedEvents; +} + +// nip17.ts +function createEvent(recipients, message, conversationTitle, replyTo) { + const baseEvent = { + created_at: Math.ceil(Date.now() / 1e3), + kind: PrivateDirectMessage, + tags: [], + content: message + }; + const recipientsArray = Array.isArray(recipients) ? recipients : [recipients]; + recipientsArray.forEach(({ publicKey, relayUrl }) => { + baseEvent.tags.push(relayUrl ? ["p", publicKey, relayUrl] : ["p", publicKey]); + }); + if (replyTo) { + baseEvent.tags.push(["e", replyTo.eventId, replyTo.relayUrl || "", "reply"]); + } + if (conversationTitle) { + baseEvent.tags.push(["subject", conversationTitle]); + } + return baseEvent; +} +function wrapEvent2(senderPrivateKey, recipient, message, conversationTitle, replyTo) { + const event = createEvent(recipient, message, conversationTitle, replyTo); + return wrapEvent(event, senderPrivateKey, recipient.publicKey); +} +function wrapManyEvents2(senderPrivateKey, recipients, message, conversationTitle, replyTo) { + if (!recipients || recipients.length === 0) { + throw new Error("At least one recipient is required."); + } + const senderPublicKey = getPublicKey(senderPrivateKey); + return [{ publicKey: senderPublicKey }, ...recipients].map( + (recipient) => wrapEvent2(senderPrivateKey, recipient, message, conversationTitle, replyTo) + ); +} +var unwrapEvent2 = unwrapEvent; +var unwrapManyEvents2 = unwrapManyEvents; + +// nip18.ts +var nip18_exports = {}; +__export(nip18_exports, { + finishRepostEvent: () => finishRepostEvent, + getRepostedEvent: () => getRepostedEvent, + getRepostedEventPointer: () => getRepostedEventPointer +}); +function finishRepostEvent(t, reposted, relayUrl, privateKey) { + let kind; + const tags = [...t.tags ?? [], ["e", reposted.id, relayUrl], ["p", reposted.pubkey]]; + if (reposted.kind === ShortTextNote) { + kind = Repost; + } else { + kind = GenericRepost; + tags.push(["k", String(reposted.kind)]); + } + return finalizeEvent( + { + kind, + tags, + content: t.content === "" || reposted.tags?.find((tag) => tag[0] === "-") ? "" : JSON.stringify(reposted), + created_at: t.created_at + }, + privateKey + ); +} +function getRepostedEventPointer(event) { + if (![Repost, GenericRepost].includes(event.kind)) { + return void 0; + } + let lastETag; + let lastPTag; + for (let i2 = event.tags.length - 1; i2 >= 0 && (lastETag === void 0 || lastPTag === void 0); i2--) { + const tag = event.tags[i2]; + if (tag.length >= 2) { + if (tag[0] === "e" && lastETag === void 0) { + lastETag = tag; + } else if (tag[0] === "p" && lastPTag === void 0) { + lastPTag = tag; + } + } + } + if (lastETag === void 0) { + return void 0; + } + return { + id: lastETag[1], + relays: [lastETag[2], lastPTag?.[2]].filter((x) => typeof x === "string"), + author: lastPTag?.[1] + }; +} +function getRepostedEvent(event, { skipVerification } = {}) { + const pointer = getRepostedEventPointer(event); + if (pointer === void 0 || event.content === "") { + return void 0; + } + let repostedEvent; + try { + repostedEvent = JSON.parse(event.content); + } catch (error) { + return void 0; + } + if (repostedEvent.id !== pointer.id) { + return void 0; + } + if (!skipVerification && !verifyEvent(repostedEvent)) { + return void 0; + } + return repostedEvent; +} + +// nip21.ts +var nip21_exports = {}; +__export(nip21_exports, { + NOSTR_URI_REGEX: () => NOSTR_URI_REGEX, + parse: () => parse2, + test: () => test +}); +var NOSTR_URI_REGEX = new RegExp(`nostr:(${BECH32_REGEX.source})`); +function test(value) { + return typeof value === "string" && new RegExp(`^${NOSTR_URI_REGEX.source}$`).test(value); +} +function parse2(uri) { + const match = uri.match(new RegExp(`^${NOSTR_URI_REGEX.source}$`)); + if (!match) + throw new Error(`Invalid Nostr URI: ${uri}`); + return { + uri: match[0], + value: match[1], + decoded: decode(match[1]) + }; +} + +// nip25.ts +var nip25_exports = {}; +__export(nip25_exports, { + finishReactionEvent: () => finishReactionEvent, + getReactedEventPointer: () => getReactedEventPointer +}); +function finishReactionEvent(t, reacted, privateKey) { + const inheritedTags = reacted.tags.filter((tag) => tag.length >= 2 && (tag[0] === "e" || tag[0] === "p")); + return finalizeEvent( + { + ...t, + kind: Reaction, + tags: [...t.tags ?? [], ...inheritedTags, ["e", reacted.id], ["p", reacted.pubkey]], + content: t.content ?? "+" + }, + privateKey + ); +} +function getReactedEventPointer(event) { + if (event.kind !== Reaction) { + return void 0; + } + let lastETag; + let lastPTag; + for (let i2 = event.tags.length - 1; i2 >= 0 && (lastETag === void 0 || lastPTag === void 0); i2--) { + const tag = event.tags[i2]; + if (tag.length >= 2) { + if (tag[0] === "e" && lastETag === void 0) { + lastETag = tag; + } else if (tag[0] === "p" && lastPTag === void 0) { + lastPTag = tag; + } + } + } + if (lastETag === void 0 || lastPTag === void 0) { + return void 0; + } + return { + id: lastETag[1], + relays: [lastETag[2], lastPTag[2]].filter((x) => x !== void 0), + author: lastPTag[1] + }; +} + +// nip27.ts +var nip27_exports = {}; +__export(nip27_exports, { + parse: () => parse3 +}); +var noCharacter = /\W/m; +var noURLCharacter = /\W |\W$|$|,| /m; +function* parse3(content) { + const max = content.length; + let prevIndex = 0; + let index = 0; + while (index < max) { + let u = content.indexOf(":", index); + if (u === -1) { + break; + } + if (content.substring(u - 5, u) === "nostr") { + const m = content.substring(u + 60).match(noCharacter); + const end = m ? u + 60 + m.index : max; + try { + let pointer; + let { data, type } = decode(content.substring(u + 1, end)); + switch (type) { + case "npub": + pointer = { pubkey: data }; + break; + case "nsec": + case "note": + index = end + 1; + continue; + default: + pointer = data; + } + if (prevIndex !== u - 5) { + yield { type: "text", text: content.substring(prevIndex, u - 5) }; + } + yield { type: "reference", pointer }; + index = end; + prevIndex = index; + continue; + } catch (_err) { + index = u + 1; + continue; + } + } else if (content.substring(u - 5, u) === "https" || content.substring(u - 4, u) === "http") { + const m = content.substring(u + 4).match(noURLCharacter); + const end = m ? u + 4 + m.index : max; + const prefixLen = content[u - 1] === "s" ? 5 : 4; + try { + let url = new URL(content.substring(u - prefixLen, end)); + if (url.hostname.indexOf(".") === -1) { + throw new Error("invalid url"); + } + if (prevIndex !== u - prefixLen) { + yield { type: "text", text: content.substring(prevIndex, u - prefixLen) }; + } + if (url.pathname.endsWith(".png") || url.pathname.endsWith(".jpg") || url.pathname.endsWith(".jpeg") || url.pathname.endsWith(".gif") || url.pathname.endsWith(".webp")) { + yield { type: "image", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } + if (url.pathname.endsWith(".mp4") || url.pathname.endsWith(".avi") || url.pathname.endsWith(".webm") || url.pathname.endsWith(".mkv")) { + yield { type: "video", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } + if (url.pathname.endsWith(".mp3") || url.pathname.endsWith(".aac") || url.pathname.endsWith(".ogg") || url.pathname.endsWith(".opus")) { + yield { type: "audio", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } + yield { type: "url", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } catch (_err) { + index = end + 1; + continue; + } + } else if (content.substring(u - 3, u) === "wss" || content.substring(u - 2, u) === "ws") { + const m = content.substring(u + 4).match(noURLCharacter); + const end = m ? u + 4 + m.index : max; + const prefixLen = content[u - 1] === "s" ? 3 : 2; + try { + let url = new URL(content.substring(u - prefixLen, end)); + if (url.hostname.indexOf(".") === -1) { + throw new Error("invalid ws url"); + } + if (prevIndex !== u - prefixLen) { + yield { type: "text", text: content.substring(prevIndex, u - prefixLen) }; + } + yield { type: "relay", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } catch (_err) { + index = end + 1; + continue; + } + } else { + index = u + 1; + continue; + } + } + if (prevIndex !== max) { + yield { type: "text", text: content.substring(prevIndex) }; + } +} + +// nip28.ts +var nip28_exports = {}; +__export(nip28_exports, { + channelCreateEvent: () => channelCreateEvent, + channelHideMessageEvent: () => channelHideMessageEvent, + channelMessageEvent: () => channelMessageEvent, + channelMetadataEvent: () => channelMetadataEvent, + channelMuteUserEvent: () => channelMuteUserEvent +}); +var channelCreateEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finalizeEvent( + { + kind: ChannelCreation, + tags: [...t.tags ?? []], + content, + created_at: t.created_at + }, + privateKey + ); +}; +var channelMetadataEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finalizeEvent( + { + kind: ChannelMetadata, + tags: [["e", t.channel_create_event_id], ...t.tags ?? []], + content, + created_at: t.created_at + }, + privateKey + ); +}; +var channelMessageEvent = (t, privateKey) => { + const tags = [["e", t.channel_create_event_id, t.relay_url, "root"]]; + if (t.reply_to_channel_message_event_id) { + tags.push(["e", t.reply_to_channel_message_event_id, t.relay_url, "reply"]); + } + return finalizeEvent( + { + kind: ChannelMessage, + tags: [...tags, ...t.tags ?? []], + content: t.content, + created_at: t.created_at + }, + privateKey + ); +}; +var channelHideMessageEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finalizeEvent( + { + kind: ChannelHideMessage, + tags: [["e", t.channel_message_event_id], ...t.tags ?? []], + content, + created_at: t.created_at + }, + privateKey + ); +}; +var channelMuteUserEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finalizeEvent( + { + kind: ChannelMuteUser, + tags: [["p", t.pubkey_to_mute], ...t.tags ?? []], + content, + created_at: t.created_at + }, + privateKey + ); +}; + +// nip30.ts +var nip30_exports = {}; +__export(nip30_exports, { + EMOJI_SHORTCODE_REGEX: () => EMOJI_SHORTCODE_REGEX, + matchAll: () => matchAll, + regex: () => regex, + replaceAll: () => replaceAll +}); +var EMOJI_SHORTCODE_REGEX = /:(\w+):/; +var regex = () => new RegExp(`\\B${EMOJI_SHORTCODE_REGEX.source}\\B`, "g"); +function* matchAll(content) { + const matches = content.matchAll(regex()); + for (const match of matches) { + try { + const [shortcode, name] = match; + yield { + shortcode, + name, + start: match.index, + end: match.index + shortcode.length + }; + } catch (_e) { + } + } +} +function replaceAll(content, replacer) { + return content.replaceAll(regex(), (shortcode, name) => { + return replacer({ + shortcode, + name + }); + }); +} + +// nip39.ts +var nip39_exports = {}; +__export(nip39_exports, { + useFetchImplementation: () => useFetchImplementation3, + validateGithub: () => validateGithub +}); +var _fetch3; +try { + _fetch3 = fetch; +} catch { +} +function useFetchImplementation3(fetchImplementation) { + _fetch3 = fetchImplementation; +} +async function validateGithub(pubkey, username, proof) { + try { + let res = await (await _fetch3(`https://gist.github.com/${username}/${proof}/raw`)).text(); + return res === `Verifying that I control the following Nostr public key: ${pubkey}`; + } catch (_) { + return false; + } +} + +// nip47.ts +var nip47_exports = {}; +__export(nip47_exports, { + makeNwcRequestEvent: () => makeNwcRequestEvent, + parseConnectionString: () => parseConnectionString +}); +function parseConnectionString(connectionString) { + const { host, pathname, searchParams } = new URL(connectionString); + const pubkey = pathname || host; + const relay = searchParams.get("relay"); + const secret = searchParams.get("secret"); + if (!pubkey || !relay || !secret) { + throw new Error("invalid connection string"); + } + return { pubkey, relay, secret }; +} +async function makeNwcRequestEvent(pubkey, secretKey, invoice) { + const content = { + method: "pay_invoice", + params: { + invoice + } + }; + const encryptedContent = encrypt(secretKey, pubkey, JSON.stringify(content)); + const eventTemplate = { + kind: NWCWalletRequest, + created_at: Math.round(Date.now() / 1e3), + content: encryptedContent, + tags: [["p", pubkey]] + }; + return finalizeEvent(eventTemplate, secretKey); +} + +// nip54.ts +var nip54_exports = {}; +__export(nip54_exports, { + normalizeIdentifier: () => normalizeIdentifier +}); +function normalizeIdentifier(name) { + name = name.trim().toLowerCase(); + name = name.normalize("NFKC"); + return Array.from(name).map((char) => { + if (/\p{Letter}/u.test(char) || /\p{Number}/u.test(char)) { + return char; + } + return "-"; + }).join(""); +} + +// nip57.ts +var nip57_exports = {}; +__export(nip57_exports, { + getSatoshisAmountFromBolt11: () => getSatoshisAmountFromBolt11, + getZapEndpoint: () => getZapEndpoint, + makeZapReceipt: () => makeZapReceipt, + makeZapRequest: () => makeZapRequest, + useFetchImplementation: () => useFetchImplementation4, + validateZapRequest: () => validateZapRequest +}); +var import_base4 = require("@scure/base"); +var _fetch4; +try { + _fetch4 = fetch; +} catch { +} +function useFetchImplementation4(fetchImplementation) { + _fetch4 = fetchImplementation; +} +async function getZapEndpoint(metadata) { + try { + let lnurl = ""; + let { lud06, lud16 } = JSON.parse(metadata.content); + if (lud06) { + let { words } = import_base4.bech32.decode(lud06, 1e3); + let data = import_base4.bech32.fromWords(words); + lnurl = utf8Decoder.decode(data); + } else if (lud16) { + let [name, domain] = lud16.split("@"); + lnurl = new URL(`/.well-known/lnurlp/${name}`, `https://${domain}`).toString(); + } else { + return null; + } + let res = await _fetch4(lnurl); + let body = await res.json(); + if (body.allowsNostr && body.nostrPubkey) { + return body.callback; + } + } catch (err) { + } + return null; +} +function makeZapRequest(params) { + let zr = { + kind: 9734, + created_at: Math.round(Date.now() / 1e3), + content: params.comment || "", + tags: [ + ["p", "pubkey" in params ? params.pubkey : params.event.pubkey], + ["amount", params.amount.toString()], + ["relays", ...params.relays] + ] + }; + if ("event" in params) { + zr.tags.push(["e", params.event.id]); + if (isReplaceableKind(params.event.kind)) { + const a = ["a", `${params.event.kind}:${params.event.pubkey}:`]; + zr.tags.push(a); + } else if (isAddressableKind(params.event.kind)) { + let d = params.event.tags.find(([t, v]) => t === "d" && v); + if (!d) + throw new Error("d tag not found or is empty"); + const a = ["a", `${params.event.kind}:${params.event.pubkey}:${d[1]}`]; + zr.tags.push(a); + } + zr.tags.push(["k", params.event.kind.toString()]); + } + return zr; +} +function validateZapRequest(zapRequestString) { + let zapRequest; + try { + zapRequest = JSON.parse(zapRequestString); + } catch (err) { + return "Invalid zap request JSON."; + } + if (!validateEvent(zapRequest)) + return "Zap request is not a valid Nostr event."; + if (!verifyEvent(zapRequest)) + return "Invalid signature on zap request."; + let p = zapRequest.tags.find(([t, v]) => t === "p" && v); + if (!p) + return "Zap request doesn't have a 'p' tag."; + if (!p[1].match(/^[a-f0-9]{64}$/)) + return "Zap request 'p' tag is not valid hex."; + let e = zapRequest.tags.find(([t, v]) => t === "e" && v); + if (e && !e[1].match(/^[a-f0-9]{64}$/)) + return "Zap request 'e' tag is not valid hex."; + let relays = zapRequest.tags.find(([t, v]) => t === "relays" && v); + if (!relays) + return "Zap request doesn't have a 'relays' tag."; + return null; +} +function makeZapReceipt({ + zapRequest, + preimage, + bolt11, + paidAt +}) { + let zr = JSON.parse(zapRequest); + let tagsFromZapRequest = zr.tags.filter(([t]) => t === "e" || t === "p" || t === "a"); + let zap = { + kind: 9735, + created_at: Math.round(paidAt.getTime() / 1e3), + content: "", + tags: [...tagsFromZapRequest, ["P", zr.pubkey], ["bolt11", bolt11], ["description", zapRequest]] + }; + if (preimage) { + zap.tags.push(["preimage", preimage]); + } + return zap; +} +function getSatoshisAmountFromBolt11(bolt11) { + if (bolt11.length < 50) { + return 0; + } + bolt11 = bolt11.substring(0, 50); + const idx = bolt11.lastIndexOf("1"); + if (idx === -1) { + return 0; + } + const hrp = bolt11.substring(0, idx); + if (!hrp.startsWith("lnbc")) { + return 0; + } + const amount = hrp.substring(4); + if (amount.length < 1) { + return 0; + } + const char = amount[amount.length - 1]; + const digit = char.charCodeAt(0) - "0".charCodeAt(0); + const isDigit = digit >= 0 && digit <= 9; + let cutPoint = amount.length - 1; + if (isDigit) { + cutPoint++; + } + if (cutPoint < 1) { + return 0; + } + const num = parseInt(amount.substring(0, cutPoint)); + switch (char) { + case "m": + return num * 1e5; + case "u": + return num * 100; + case "n": + return num / 10; + case "p": + return num / 1e4; + default: + return num * 1e8; + } +} + +// nip98.ts +var nip98_exports = {}; +__export(nip98_exports, { + getToken: () => getToken, + hashPayload: () => hashPayload, + unpackEventFromToken: () => unpackEventFromToken, + validateEvent: () => validateEvent2, + validateEventKind: () => validateEventKind, + validateEventMethodTag: () => validateEventMethodTag, + validateEventPayloadTag: () => validateEventPayloadTag, + validateEventTimestamp: () => validateEventTimestamp, + validateEventUrlTag: () => validateEventUrlTag, + validateToken: () => validateToken +}); +var import_sha2564 = require("@noble/hashes/sha256"); +var import_utils16 = require("@noble/hashes/utils"); +var import_base5 = require("@scure/base"); +var _authorizationScheme = "Nostr "; +async function getToken(loginUrl, httpMethod, sign, includeAuthorizationScheme = false, payload) { + const event = { + kind: HTTPAuth, + tags: [ + ["u", loginUrl], + ["method", httpMethod] + ], + created_at: Math.round(new Date().getTime() / 1e3), + content: "" + }; + if (payload) { + event.tags.push(["payload", hashPayload(payload)]); + } + const signedEvent = await sign(event); + const authorizationScheme = includeAuthorizationScheme ? _authorizationScheme : ""; + return authorizationScheme + import_base5.base64.encode(utf8Encoder.encode(JSON.stringify(signedEvent))); +} +async function validateToken(token, url, method) { + const event = await unpackEventFromToken(token).catch((error) => { + throw error; + }); + const valid = await validateEvent2(event, url, method).catch((error) => { + throw error; + }); + return valid; +} +async function unpackEventFromToken(token) { + if (!token) { + throw new Error("Missing token"); + } + token = token.replace(_authorizationScheme, ""); + const eventB64 = utf8Decoder.decode(import_base5.base64.decode(token)); + if (!eventB64 || eventB64.length === 0 || !eventB64.startsWith("{")) { + throw new Error("Invalid token"); + } + const event = JSON.parse(eventB64); + return event; +} +function validateEventTimestamp(event) { + if (!event.created_at) { + return false; + } + return Math.round(new Date().getTime() / 1e3) - event.created_at < 60; +} +function validateEventKind(event) { + return event.kind === HTTPAuth; +} +function validateEventUrlTag(event, url) { + const urlTag = event.tags.find((t) => t[0] === "u"); + if (!urlTag) { + return false; + } + return urlTag.length > 0 && urlTag[1] === url; +} +function validateEventMethodTag(event, method) { + const methodTag = event.tags.find((t) => t[0] === "method"); + if (!methodTag) { + return false; + } + return methodTag.length > 0 && methodTag[1].toLowerCase() === method.toLowerCase(); +} +function hashPayload(payload) { + const hash = (0, import_sha2564.sha256)(utf8Encoder.encode(JSON.stringify(payload))); + return (0, import_utils16.bytesToHex)(hash); +} +function validateEventPayloadTag(event, payload) { + const payloadTag = event.tags.find((t) => t[0] === "payload"); + if (!payloadTag) { + return false; + } + const payloadHash = hashPayload(payload); + return payloadTag.length > 0 && payloadTag[1] === payloadHash; +} +async function validateEvent2(event, url, method, body) { + if (!verifyEvent(event)) { + throw new Error("Invalid nostr event, signature invalid"); + } + if (!validateEventKind(event)) { + throw new Error("Invalid nostr event, kind invalid"); + } + if (!validateEventTimestamp(event)) { + throw new Error("Invalid nostr event, created_at timestamp invalid"); + } + if (!validateEventUrlTag(event, url)) { + throw new Error("Invalid nostr event, url tag invalid"); + } + if (!validateEventMethodTag(event, method)) { + throw new Error("Invalid nostr event, method tag invalid"); + } + if (Boolean(body) && typeof body === "object" && Object.keys(body).length > 0) { + if (!validateEventPayloadTag(event, body)) { + throw new Error("Invalid nostr event, payload tag does not match request body hash"); + } + } + return true; +} diff --git a/node_modules/nostr-tools/lib/cjs/index.js.map b/node_modules/nostr-tools/lib/cjs/index.js.map new file mode 100644 index 0000000..a704d7c --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/index.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../index.ts", "../../pure.ts", "../../core.ts", "../../utils.ts", "../../kinds.ts", "../../filter.ts", "../../fakejson.ts", "../../nip42.ts", "../../helpers.ts", "../../abstract-relay.ts", "../../relay.ts", "../../abstract-pool.ts", "../../pool.ts", "../../nip19.ts", "../../references.ts", "../../nip04.ts", "../../nip05.ts", "../../nip10.ts", "../../nip11.ts", "../../nip13.ts", "../../nip17.ts", "../../nip59.ts", "../../nip44.ts", "../../nip18.ts", "../../nip21.ts", "../../nip25.ts", "../../nip27.ts", "../../nip28.ts", "../../nip30.ts", "../../nip39.ts", "../../nip47.ts", "../../nip54.ts", "../../nip57.ts", "../../nip98.ts"], + "sourcesContent": ["export * from './pure.ts'\nexport { Relay } from './relay.ts'\nexport * from './filter.ts'\nexport { SimplePool } from './pool.ts'\nexport * from './references.ts'\n\nexport * as nip04 from './nip04.ts'\nexport * as nip05 from './nip05.ts'\nexport * as nip10 from './nip10.ts'\nexport * as nip11 from './nip11.ts'\nexport * as nip13 from './nip13.ts'\nexport * as nip17 from './nip17.ts'\nexport * as nip18 from './nip18.ts'\nexport * as nip19 from './nip19.ts'\nexport * as nip21 from './nip21.ts'\nexport * as nip25 from './nip25.ts'\nexport * as nip27 from './nip27.ts'\nexport * as nip28 from './nip28.ts'\nexport * as nip30 from './nip30.ts'\nexport * as nip39 from './nip39.ts'\nexport * as nip42 from './nip42.ts'\nexport * as nip44 from './nip44.ts'\nexport * as nip47 from './nip47.ts'\nexport * as nip54 from './nip54.ts'\nexport * as nip57 from './nip57.ts'\nexport * as nip59 from './nip59.ts'\nexport * as nip98 from './nip98.ts'\n\nexport * as kinds from './kinds.ts'\nexport * as fj from './fakejson.ts'\nexport * as utils from './utils.ts'\n", "import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { Event } from './core.ts'\nimport { isAddressableKind, isReplaceableKind } from './kinds.ts'\n\nexport type Filter = {\n ids?: string[]\n kinds?: number[]\n authors?: string[]\n since?: number\n until?: number\n limit?: number\n search?: string\n [key: `#${string}`]: string[] | undefined\n}\n\nexport function matchFilter(filter: Filter, event: Event): boolean {\n if (filter.ids && filter.ids.indexOf(event.id) === -1) {\n return false\n }\n if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) {\n return false\n }\n if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) {\n return false\n }\n\n for (let f in filter) {\n if (f[0] === '#') {\n let tagName = f.slice(1)\n let values = filter[`#${tagName}`]\n if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values!.indexOf(v) !== -1)) return false\n }\n }\n\n if (filter.since && event.created_at < filter.since) return false\n if (filter.until && event.created_at > filter.until) return false\n\n return true\n}\n\nexport function matchFilters(filters: Filter[], event: Event): boolean {\n for (let i = 0; i < filters.length; i++) {\n if (matchFilter(filters[i], event)) {\n return true\n }\n }\n return false\n}\n\nexport function mergeFilters(...filters: Filter[]): Filter {\n let result: Filter = {}\n for (let i = 0; i < filters.length; i++) {\n let filter = filters[i]\n Object.entries(filter).forEach(([property, values]) => {\n if (property === 'kinds' || property === 'ids' || property === 'authors' || property[0] === '#') {\n // @ts-ignore\n result[property] = result[property] || []\n // @ts-ignore\n for (let v = 0; v < values.length; v++) {\n // @ts-ignore\n let value = values[v]\n // @ts-ignore\n if (!result[property].includes(value)) result[property].push(value)\n }\n }\n })\n\n if (filter.limit && (!result.limit || filter.limit > result.limit)) result.limit = filter.limit\n if (filter.until && (!result.until || filter.until > result.until)) result.until = filter.until\n if (filter.since && (!result.since || filter.since < result.since)) result.since = filter.since\n }\n\n return result\n}\n\n/**\n * Calculate the intrinsic limit of a filter.\n * This function returns a positive integer, or `Infinity` if there is no intrinsic limit.\n */\nexport function getFilterLimit(filter: Filter): number {\n if (filter.ids && !filter.ids.length) return 0\n if (filter.kinds && !filter.kinds.length) return 0\n if (filter.authors && !filter.authors.length) return 0\n\n for (const [key, value] of Object.entries(filter)) {\n if (key[0] === '#' && Array.isArray(value) && !value.length) return 0\n }\n\n return Math.min(\n // The `limit` property creates an artificial limit.\n Math.max(0, filter.limit ?? Infinity),\n\n // There can only be one event per `id`.\n filter.ids?.length ?? Infinity,\n\n // Replaceable events are limited by the number of authors and kinds.\n filter.authors?.length && filter.kinds?.every(kind => isReplaceableKind(kind))\n ? filter.authors.length * filter.kinds.length\n : Infinity,\n\n // Parameterized replaceable events are limited by the number of authors, kinds, and \"d\" tags.\n filter.authors?.length && filter.kinds?.every(kind => isAddressableKind(kind)) && filter['#d']?.length\n ? filter.authors.length * filter.kinds.length * filter['#d'].length\n : Infinity,\n )\n}\n", "export function getHex64(json: string, field: string): string {\n let len = field.length + 3\n let idx = json.indexOf(`\"${field}\":`) + len\n let s = json.slice(idx).indexOf(`\"`) + idx + 1\n return json.slice(s, s + 64)\n}\n\nexport function getInt(json: string, field: string): number {\n let len = field.length\n let idx = json.indexOf(`\"${field}\":`) + len + 3\n let sliced = json.slice(idx)\n let end = Math.min(sliced.indexOf(','), sliced.indexOf('}'))\n return parseInt(sliced.slice(0, end), 10)\n}\n\nexport function getSubscriptionId(json: string): string | null {\n let idx = json.slice(0, 22).indexOf(`\"EVENT\"`)\n if (idx === -1) return null\n\n let pstart = json.slice(idx + 7 + 1).indexOf(`\"`)\n if (pstart === -1) return null\n let start = idx + 7 + 1 + pstart\n\n let pend = json.slice(start + 1, 80).indexOf(`\"`)\n if (pend === -1) return null\n let end = start + 1 + pend\n\n return json.slice(start + 1, end)\n}\n\nexport function matchEventId(json: string, id: string): boolean {\n return id === getHex64(json, 'id')\n}\n\nexport function matchEventPubkey(json: string, pubkey: string): boolean {\n return pubkey === getHex64(json, 'pubkey')\n}\n\nexport function matchEventKind(json: string, kind: number): boolean {\n return kind === getInt(json, 'kind')\n}\n", "import { EventTemplate } from './core.ts'\nimport { ClientAuth } from './kinds.ts'\n\n/**\n * creates an EventTemplate for an AUTH event to be signed.\n */\nexport function makeAuthEvent(relayURL: string, challenge: string): EventTemplate {\n return {\n kind: ClientAuth,\n created_at: Math.floor(Date.now() / 1000),\n tags: [\n ['relay', relayURL],\n ['challenge', challenge],\n ],\n content: '',\n }\n}\n", "import { verifiedSymbol, type Event, type Nostr, VerifiedEvent } from './core.ts'\n\nexport async function yieldThread() {\n return new Promise(resolve => {\n const ch = new MessageChannel()\n const handler = () => {\n // @ts-ignore (typescript thinks this property should be called `removeListener`, but in fact it's `removeEventListener`)\n ch.port1.removeEventListener('message', handler)\n resolve()\n }\n // @ts-ignore (typescript thinks this property should be called `addListener`, but in fact it's `addEventListener`)\n ch.port1.addEventListener('message', handler)\n ch.port2.postMessage(0)\n ch.port1.start()\n })\n}\n\nexport const alwaysTrue: Nostr['verifyEvent'] = (t: Event): t is VerifiedEvent => {\n t[verifiedSymbol] = true\n return true\n}\n", "/* global WebSocket */\n\nimport type { Event, EventTemplate, VerifiedEvent, Nostr, NostrEvent } from './core.ts'\nimport { matchFilters, type Filter } from './filter.ts'\nimport { getHex64, getSubscriptionId } from './fakejson.ts'\nimport { Queue, normalizeURL } from './utils.ts'\nimport { makeAuthEvent } from './nip42.ts'\nimport { yieldThread } from './helpers.ts'\n\ntype RelayWebSocket = WebSocket & {\n ping?(): void\n on?(event: 'pong', listener: () => void): any\n}\n\nexport type AbstractRelayConstructorOptions = {\n verifyEvent: Nostr['verifyEvent']\n websocketImplementation?: typeof WebSocket\n enablePing?: boolean\n}\n\nexport class SendingOnClosedConnection extends Error {\n constructor(message: string, relay: string) {\n super(`Tried to send message '${message} on a closed connection to ${relay}.`)\n this.name = 'SendingOnClosedConnection'\n }\n}\n\nexport class AbstractRelay {\n public readonly url: string\n private _connected: boolean = false\n\n public onclose: (() => void) | null = null\n public onnotice: (msg: string) => void = msg => console.debug(`NOTICE from ${this.url}: ${msg}`)\n\n public baseEoseTimeout: number = 4400\n public connectionTimeout: number = 4400\n public publishTimeout: number = 4400\n public pingFrequency: number = 20000\n public pingTimeout: number = 20000\n public openSubs: Map = new Map()\n public enablePing: boolean | undefined\n private connectionTimeoutHandle: ReturnType | undefined\n\n private connectionPromise: Promise | undefined\n private openCountRequests = new Map()\n private openEventPublishes = new Map()\n private ws: RelayWebSocket | undefined\n private incomingMessageQueue = new Queue()\n private queueRunning = false\n private challenge: string | undefined\n private authPromise: Promise | undefined\n private serial: number = 0\n private verifyEvent: Nostr['verifyEvent']\n\n private _WebSocket: typeof WebSocket\n\n constructor(url: string, opts: AbstractRelayConstructorOptions) {\n this.url = normalizeURL(url)\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation || WebSocket\n this.enablePing = opts.enablePing\n }\n\n static async connect(url: string, opts: AbstractRelayConstructorOptions): Promise {\n const relay = new AbstractRelay(url, opts)\n await relay.connect()\n return relay\n }\n\n private closeAllSubscriptions(reason: string) {\n for (let [_, sub] of this.openSubs) {\n sub.close(reason)\n }\n this.openSubs.clear()\n\n for (let [_, ep] of this.openEventPublishes) {\n ep.reject(new Error(reason))\n }\n this.openEventPublishes.clear()\n\n for (let [_, cr] of this.openCountRequests) {\n cr.reject(new Error(reason))\n }\n this.openCountRequests.clear()\n }\n\n public get connected(): boolean {\n return this._connected\n }\n\n public async connect(): Promise {\n if (this.connectionPromise) return this.connectionPromise\n\n this.challenge = undefined\n this.authPromise = undefined\n this.connectionPromise = new Promise((resolve, reject) => {\n this.connectionTimeoutHandle = setTimeout(() => {\n reject('connection timed out')\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection timed out')\n }, this.connectionTimeout)\n\n try {\n this.ws = new this._WebSocket(this.url)\n } catch (err) {\n clearTimeout(this.connectionTimeoutHandle)\n reject(err)\n return\n }\n\n this.ws.onopen = () => {\n clearTimeout(this.connectionTimeoutHandle)\n this._connected = true\n if (this.enablePing) {\n this.pingpong()\n }\n resolve()\n }\n\n this.ws.onerror = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket error')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection errored')\n }\n }\n\n this.ws.onclose = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket closed')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection closed')\n }\n }\n\n this.ws.onmessage = this._onmessage.bind(this)\n })\n\n return this.connectionPromise\n }\n\n private async waitForPingPong() {\n return new Promise((res, err) => {\n // listen for pong\n ;(this.ws && this.ws.on && this.ws.on('pong', () => res(true))) || err(\"ws can't listen for pong\")\n // send a ping\n this.ws && this.ws.ping && this.ws.ping()\n })\n }\n\n private async waitForDummyReq() {\n return new Promise((resolve, _) => {\n // make a dummy request with expected empty eose reply\n // [\"REQ\", \"_\", {\"ids\":[\"aaaa...aaaa\"]}]\n const sub = this.subscribe([{ ids: ['a'.repeat(64)] }], {\n oneose: () => {\n sub.close()\n resolve(true)\n },\n eoseTimeout: this.pingTimeout + 1000,\n })\n })\n }\n\n // nodejs requires this magic here to ensure connections are closed when internet goes off and stuff\n // in browsers it's done automatically. see https://github.com/nbd-wtf/nostr-tools/issues/491\n private async pingpong() {\n // if the websocket is connected\n if (this.ws?.readyState === 1) {\n // wait for either a ping-pong reply or a timeout\n const result = await Promise.any([\n // browsers don't have ping so use a dummy req\n this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(),\n new Promise(res => setTimeout(() => res(false), this.pingTimeout)),\n ])\n if (result) {\n // schedule another pingpong\n setTimeout(() => this.pingpong(), this.pingFrequency)\n } else {\n // pingpong closing socket\n this.closeAllSubscriptions('pingpong timed out')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n }\n }\n\n private async runQueue() {\n this.queueRunning = true\n while (true) {\n if (false === this.handleNext()) {\n break\n }\n await yieldThread()\n }\n this.queueRunning = false\n }\n\n private handleNext(): undefined | false {\n const json = this.incomingMessageQueue.dequeue()\n if (!json) {\n return false\n }\n\n const subid = getSubscriptionId(json)\n if (subid) {\n const so = this.openSubs.get(subid as string)\n if (!so) {\n // this is an EVENT message, but for a subscription we don't have, so just stop here\n return\n }\n\n // this will be called only when this message is a EVENT message for a subscription we have\n // we do this before parsing the JSON to not have to do that for duplicate events\n // since JSON parsing is slow\n const id = getHex64(json, 'id')\n const alreadyHave = so.alreadyHaveEvent?.(id)\n\n // notify any interested client that the relay has this event\n // (do this after alreadyHaveEvent() because the client may rely on this to answer that)\n so.receivedEvent?.(this, id)\n\n if (alreadyHave) {\n // if we had already seen this event we can just stop here\n return\n }\n }\n\n try {\n let data = JSON.parse(json)\n // we won't do any checks against the data since all failures (i.e. invalid messages from relays)\n // will naturally be caught by the encompassing try..catch block\n\n switch (data[0]) {\n case 'EVENT': {\n const so = this.openSubs.get(data[1] as string) as Subscription\n const event = data[2] as NostrEvent\n if (this.verifyEvent(event) && matchFilters(so.filters, event)) {\n so.onevent(event)\n }\n return\n }\n case 'COUNT': {\n const id: string = data[1]\n const payload = data[2] as { count: number }\n const cr = this.openCountRequests.get(id) as CountResolver\n if (cr) {\n cr.resolve(payload.count)\n this.openCountRequests.delete(id)\n }\n return\n }\n case 'EOSE': {\n const so = this.openSubs.get(data[1] as string)\n if (!so) return\n so.receivedEose()\n return\n }\n case 'OK': {\n const id: string = data[1]\n const ok: boolean = data[2]\n const reason: string = data[3]\n const ep = this.openEventPublishes.get(id) as EventPublishResolver\n if (ep) {\n clearTimeout(ep.timeout)\n if (ok) ep.resolve(reason)\n else ep.reject(new Error(reason))\n this.openEventPublishes.delete(id)\n }\n return\n }\n case 'CLOSED': {\n const id: string = data[1]\n const so = this.openSubs.get(id)\n if (!so) return\n so.closed = true\n so.close(data[2] as string)\n return\n }\n case 'NOTICE':\n this.onnotice(data[1] as string)\n return\n case 'AUTH': {\n this.challenge = data[1] as string\n return\n }\n }\n } catch (err) {\n return\n }\n }\n\n public async send(message: string) {\n if (!this.connectionPromise) throw new SendingOnClosedConnection(message, this.url)\n\n this.connectionPromise.then(() => {\n this.ws?.send(message)\n })\n }\n\n public async auth(signAuthEvent: (evt: EventTemplate) => Promise): Promise {\n const challenge = this.challenge\n if (!challenge) throw new Error(\"can't perform auth, no challenge was received\")\n if (this.authPromise) return this.authPromise\n\n this.authPromise = new Promise(async (resolve, reject) => {\n try {\n let evt = await signAuthEvent(makeAuthEvent(this.url, challenge))\n let timeout = setTimeout(() => {\n let ep = this.openEventPublishes.get(evt.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('auth timed out'))\n this.openEventPublishes.delete(evt.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(evt.id, { resolve, reject, timeout })\n this.send('[\"AUTH\",' + JSON.stringify(evt) + ']')\n } catch (err) {\n console.warn('subscribe auth function failed:', err)\n }\n })\n return this.authPromise\n }\n\n public async publish(event: Event): Promise {\n const ret = new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n const ep = this.openEventPublishes.get(event.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('publish timed out'))\n this.openEventPublishes.delete(event.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(event.id, { resolve, reject, timeout })\n })\n this.send('[\"EVENT\",' + JSON.stringify(event) + ']')\n return ret\n }\n\n public async count(filters: Filter[], params: { id?: string | null }): Promise {\n this.serial++\n const id = params?.id || 'count:' + this.serial\n const ret = new Promise((resolve, reject) => {\n this.openCountRequests.set(id, { resolve, reject })\n })\n this.send('[\"COUNT\",\"' + id + '\",' + JSON.stringify(filters).substring(1))\n return ret\n }\n\n public subscribe(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n const subscription = this.prepareSubscription(filters, params)\n subscription.fire()\n return subscription\n }\n\n public prepareSubscription(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n this.serial++\n const id = params.id || (params.label ? params.label + ':' : 'sub:') + this.serial\n const subscription = new Subscription(this, id, filters, params)\n this.openSubs.set(id, subscription)\n return subscription\n }\n\n public close() {\n this.closeAllSubscriptions('relay connection closed by us')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n\n // this is the function assigned to this.ws.onmessage\n // it's exposed for testing and debugging purposes\n public _onmessage(ev: MessageEvent) {\n this.incomingMessageQueue.enqueue(ev.data as string)\n if (!this.queueRunning) {\n this.runQueue()\n }\n }\n}\n\nexport class Subscription {\n public readonly relay: AbstractRelay\n public readonly id: string\n\n public closed: boolean = false\n public eosed: boolean = false\n public filters: Filter[]\n public alreadyHaveEvent: ((id: string) => boolean) | undefined\n public receivedEvent: ((relay: AbstractRelay, id: string) => void) | undefined\n\n public onevent: (evt: Event) => void\n public oneose: (() => void) | undefined\n public onclose: ((reason: string) => void) | undefined\n\n public eoseTimeout: number\n private eoseTimeoutHandle: ReturnType | undefined\n\n constructor(relay: AbstractRelay, id: string, filters: Filter[], params: SubscriptionParams) {\n this.relay = relay\n this.filters = filters\n this.id = id\n this.alreadyHaveEvent = params.alreadyHaveEvent\n this.receivedEvent = params.receivedEvent\n this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout\n\n this.oneose = params.oneose\n this.onclose = params.onclose\n this.onevent =\n params.onevent ||\n (event => {\n console.warn(\n `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,\n event,\n )\n })\n }\n\n public fire() {\n this.relay.send('[\"REQ\",\"' + this.id + '\",' + JSON.stringify(this.filters).substring(1))\n\n // only now we start counting the eoseTimeout\n this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout)\n }\n\n public receivedEose() {\n if (this.eosed) return\n clearTimeout(this.eoseTimeoutHandle)\n this.eosed = true\n this.oneose?.()\n }\n\n public close(reason: string = 'closed by caller') {\n if (!this.closed && this.relay.connected) {\n // if the connection was closed by the user calling .close() we will send a CLOSE message\n // otherwise this._open will be already set to false so we will skip this\n try {\n this.relay.send('[\"CLOSE\",' + JSON.stringify(this.id) + ']')\n } catch (err) {\n if (err instanceof SendingOnClosedConnection) {\n /* doesn't matter, it's ok */\n } else {\n throw err\n }\n }\n this.closed = true\n }\n this.relay.openSubs.delete(this.id)\n this.onclose?.(reason)\n }\n}\n\nexport type SubscriptionParams = {\n onevent?: (evt: Event) => void\n oneose?: () => void\n onclose?: (reason: string) => void\n alreadyHaveEvent?: (id: string) => boolean\n receivedEvent?: (relay: AbstractRelay, id: string) => void\n eoseTimeout?: number\n}\n\nexport type CountResolver = {\n resolve: (count: number) => void\n reject: (err: Error) => void\n}\n\nexport type EventPublishResolver = {\n resolve: (reason: string) => void\n reject: (err: Error) => void\n timeout: ReturnType\n}\n", "/* global WebSocket */\n\nimport { verifyEvent } from './pure.ts'\nimport { AbstractRelay } from './abstract-relay.ts'\n\nvar _WebSocket: typeof WebSocket\n\ntry {\n _WebSocket = WebSocket\n} catch {}\n\nexport function useWebSocketImplementation(websocketImplementation: any) {\n _WebSocket = websocketImplementation\n}\n\nexport class Relay extends AbstractRelay {\n constructor(url: string) {\n super(url, { verifyEvent, websocketImplementation: _WebSocket })\n }\n\n static async connect(url: string): Promise {\n const relay = new Relay(url)\n await relay.connect()\n return relay\n }\n}\n\nexport type RelayRecord = Record\n\nexport * from './abstract-relay.ts'\n", "/* global WebSocket */\n\nimport {\n AbstractRelay as AbstractRelay,\n SubscriptionParams,\n Subscription,\n type AbstractRelayConstructorOptions,\n} from './abstract-relay.ts'\nimport { normalizeURL } from './utils.ts'\n\nimport type { Event, EventTemplate, Nostr, VerifiedEvent } from './core.ts'\nimport { type Filter } from './filter.ts'\nimport { alwaysTrue } from './helpers.ts'\n\nexport type SubCloser = { close: (reason?: string) => void }\n\nexport type AbstractPoolConstructorOptions = AbstractRelayConstructorOptions & {}\n\nexport type SubscribeManyParams = Omit & {\n maxWait?: number\n onclose?: (reasons: string[]) => void\n onauth?: (event: EventTemplate) => Promise\n // Deprecated: use onauth instead\n doauth?: (event: EventTemplate) => Promise\n id?: string\n label?: string\n}\n\nexport class AbstractSimplePool {\n protected relays: Map = new Map()\n public seenOn: Map> = new Map()\n public trackRelays: boolean = false\n\n public verifyEvent: Nostr['verifyEvent']\n public enablePing: boolean | undefined\n public trustedRelayURLs: Set = new Set()\n\n private _WebSocket?: typeof WebSocket\n\n constructor(opts: AbstractPoolConstructorOptions) {\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation\n this.enablePing = opts.enablePing\n }\n\n async ensureRelay(url: string, params?: { connectionTimeout?: number }): Promise {\n url = normalizeURL(url)\n\n let relay = this.relays.get(url)\n if (!relay) {\n relay = new AbstractRelay(url, {\n verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent,\n websocketImplementation: this._WebSocket,\n enablePing: this.enablePing,\n })\n relay.onclose = () => {\n this.relays.delete(url)\n }\n if (params?.connectionTimeout) relay.connectionTimeout = params.connectionTimeout\n this.relays.set(url, relay)\n }\n await relay.connect()\n\n return relay\n }\n\n close(relays: string[]) {\n relays.map(normalizeURL).forEach(url => {\n this.relays.get(url)?.close()\n this.relays.delete(url)\n })\n }\n\n subscribe(relays: string[], filter: Filter, params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const request: { url: string; filter: Filter }[] = []\n for (let i = 0; i < relays.length; i++) {\n const url = normalizeURL(relays[i])\n if (!request.find(r => r.url === url)) {\n request.push({ url, filter })\n }\n }\n\n return this.subscribeMap(request, params)\n }\n\n subscribeMany(relays: string[], filters: Filter[], params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const request: { url: string; filter: Filter }[] = []\n const uniqUrls: string[] = []\n for (let i = 0; i < relays.length; i++) {\n const url = normalizeURL(relays[i])\n if (uniqUrls.indexOf(url) === -1) {\n for (let f = 0; f < filters.length; f++) {\n request.push({ url, filter: filters[f] })\n }\n }\n }\n\n return this.subscribeMap(request, params)\n }\n\n subscribeMap(requests: { url: string; filter: Filter }[], params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n if (this.trackRelays) {\n params.receivedEvent = (relay: AbstractRelay, id: string) => {\n let set = this.seenOn.get(id)\n if (!set) {\n set = new Set()\n this.seenOn.set(id, set)\n }\n set.add(relay)\n }\n }\n\n const _knownIds = new Set()\n const subs: Subscription[] = []\n\n // batch all EOSEs into a single\n const eosesReceived: boolean[] = []\n let handleEose = (i: number) => {\n if (eosesReceived[i]) return // do not act twice for the same relay\n eosesReceived[i] = true\n if (eosesReceived.filter(a => a).length === requests.length) {\n params.oneose?.()\n handleEose = () => {}\n }\n }\n // batch all closes into a single\n const closesReceived: string[] = []\n let handleClose = (i: number, reason: string) => {\n if (closesReceived[i]) return // do not act twice for the same relay\n handleEose(i)\n closesReceived[i] = reason\n if (closesReceived.filter(a => a).length === requests.length) {\n params.onclose?.(closesReceived)\n handleClose = () => {}\n }\n }\n\n const localAlreadyHaveEventHandler = (id: string) => {\n if (params.alreadyHaveEvent?.(id)) {\n return true\n }\n const have = _knownIds.has(id)\n _knownIds.add(id)\n return have\n }\n\n // open a subscription in all given relays\n const allOpened = Promise.all(\n requests.map(async ({ url, filter }, i) => {\n let relay: AbstractRelay\n try {\n relay = await this.ensureRelay(url, {\n connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1000) : undefined,\n })\n } catch (err) {\n handleClose(i, (err as any)?.message || String(err))\n return\n }\n\n let subscription = relay.subscribe([filter], {\n ...params,\n oneose: () => handleEose(i),\n onclose: reason => {\n if (reason.startsWith('auth-required: ') && params.onauth) {\n relay\n .auth(params.onauth)\n .then(() => {\n relay.subscribe([filter], {\n ...params,\n oneose: () => handleEose(i),\n onclose: reason => {\n handleClose(i, reason) // the second time we won't try to auth anymore\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait,\n })\n })\n .catch(err => {\n handleClose(i, `auth was required and attempted, but failed with: ${err}`)\n })\n } else {\n handleClose(i, reason)\n }\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait,\n })\n\n subs.push(subscription)\n }),\n )\n\n return {\n async close(reason?: string) {\n await allOpened\n subs.forEach(sub => {\n sub.close(reason)\n })\n },\n }\n }\n\n subscribeEose(\n relays: string[],\n filter: Filter,\n params: Pick,\n ): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const subcloser = this.subscribe(relays, filter, {\n ...params,\n oneose() {\n subcloser.close('closed automatically on eose')\n },\n })\n return subcloser\n }\n\n subscribeManyEose(\n relays: string[],\n filters: Filter[],\n params: Pick,\n ): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const subcloser = this.subscribeMany(relays, filters, {\n ...params,\n oneose() {\n subcloser.close('closed automatically on eose')\n },\n })\n return subcloser\n }\n\n async querySync(\n relays: string[],\n filter: Filter,\n params?: Pick,\n ): Promise {\n return new Promise(async resolve => {\n const events: Event[] = []\n this.subscribeEose(relays, filter, {\n ...params,\n onevent(event: Event) {\n events.push(event)\n },\n onclose(_: string[]) {\n resolve(events)\n },\n })\n })\n }\n\n async get(\n relays: string[],\n filter: Filter,\n params?: Pick,\n ): Promise {\n filter.limit = 1\n const events = await this.querySync(relays, filter, params)\n events.sort((a, b) => b.created_at - a.created_at)\n return events[0] || null\n }\n\n publish(\n relays: string[],\n event: Event,\n options?: { onauth?: (evt: EventTemplate) => Promise },\n ): Promise[] {\n return relays.map(normalizeURL).map(async (url, i, arr) => {\n if (arr.indexOf(url) !== i) {\n // duplicate\n return Promise.reject('duplicate url')\n }\n\n let r = await this.ensureRelay(url)\n return r\n .publish(event)\n .catch(async err => {\n if (err instanceof Error && err.message.startsWith('auth-required: ') && options?.onauth) {\n await r.auth(options.onauth)\n return r.publish(event) // retry\n }\n throw err\n })\n .then(reason => {\n if (this.trackRelays) {\n let set = this.seenOn.get(event.id)\n if (!set) {\n set = new Set()\n this.seenOn.set(event.id, set)\n }\n set.add(r)\n }\n return reason\n })\n })\n }\n\n listConnectionStatus(): Map {\n const map = new Map()\n this.relays.forEach((relay, url) => map.set(url, relay.connected))\n\n return map\n }\n\n destroy(): void {\n this.relays.forEach(conn => conn.close())\n this.relays = new Map()\n }\n}\n", "/* global WebSocket */\n\nimport { verifyEvent } from './pure.ts'\nimport { AbstractSimplePool } from './abstract-pool.ts'\n\nvar _WebSocket: typeof WebSocket\n\ntry {\n _WebSocket = WebSocket\n} catch {}\n\nexport function useWebSocketImplementation(websocketImplementation: any) {\n _WebSocket = websocketImplementation\n}\n\nexport class SimplePool extends AbstractSimplePool {\n constructor(options?: { enablePing?: boolean }) {\n super({ verifyEvent, websocketImplementation: _WebSocket, ...options })\n }\n}\n\nexport * from './abstract-pool.ts'\n", "import { bytesToHex, concatBytes, hexToBytes } from '@noble/hashes/utils'\nimport { bech32 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport type NProfile = `nprofile1${string}`\nexport type NEvent = `nevent1${string}`\nexport type NAddr = `naddr1${string}`\nexport type NSec = `nsec1${string}`\nexport type NPub = `npub1${string}`\nexport type Note = `note1${string}`\nexport type Ncryptsec = `ncryptsec1${string}`\n\nexport const NostrTypeGuard = {\n isNProfile: (value?: string | null): value is NProfile => /^nprofile1[a-z\\d]+$/.test(value || ''),\n isNEvent: (value?: string | null): value is NEvent => /^nevent1[a-z\\d]+$/.test(value || ''),\n isNAddr: (value?: string | null): value is NAddr => /^naddr1[a-z\\d]+$/.test(value || ''),\n isNSec: (value?: string | null): value is NSec => /^nsec1[a-z\\d]{58}$/.test(value || ''),\n isNPub: (value?: string | null): value is NPub => /^npub1[a-z\\d]{58}$/.test(value || ''),\n isNote: (value?: string | null): value is Note => /^note1[a-z\\d]+$/.test(value || ''),\n isNcryptsec: (value?: string | null): value is Ncryptsec => /^ncryptsec1[a-z\\d]+$/.test(value || ''),\n}\n\nexport const Bech32MaxSize = 5000\n\n/**\n * Bech32 regex.\n * @see https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32\n */\nexport const BECH32_REGEX = /[\\x21-\\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/\n\nfunction integerToUint8Array(number: number) {\n // Create a Uint8Array with enough space to hold a 32-bit integer (4 bytes).\n const uint8Array = new Uint8Array(4)\n\n // Use bitwise operations to extract the bytes.\n uint8Array[0] = (number >> 24) & 0xff // Most significant byte (MSB)\n uint8Array[1] = (number >> 16) & 0xff\n uint8Array[2] = (number >> 8) & 0xff\n uint8Array[3] = number & 0xff // Least significant byte (LSB)\n\n return uint8Array\n}\n\nexport type ProfilePointer = {\n pubkey: string // hex\n relays?: string[]\n}\n\nexport type EventPointer = {\n id: string // hex\n relays?: string[]\n author?: string\n kind?: number\n}\n\nexport type AddressPointer = {\n identifier: string\n pubkey: string\n kind: number\n relays?: string[]\n}\n\nexport function decodeNostrURI(nip19code: string): ReturnType | { type: 'invalid'; data: null } {\n try {\n if (nip19code.startsWith('nostr:')) nip19code = nip19code.substring(6)\n return decode(nip19code)\n } catch (_err) {\n return { type: 'invalid', data: null }\n }\n}\n\nexport type DecodedNevent = {\n type: 'nevent'\n data: EventPointer\n}\n\nexport type DecodedNprofile = {\n type: 'nprofile'\n data: ProfilePointer\n}\n\nexport type DecodedNaddr = {\n type: 'naddr'\n data: AddressPointer\n}\n\nexport type DecodedNsec = {\n type: 'nsec'\n data: Uint8Array\n}\n\nexport type DecodedNpub = {\n type: 'npub'\n data: string\n}\n\nexport type DecodedNote = {\n type: 'note'\n data: string\n}\n\nexport type DecodedResult = DecodedNevent | DecodedNprofile | DecodedNaddr | DecodedNpub | DecodedNsec | DecodedNote\n\nexport function decode(nip19: NEvent): DecodedNevent\nexport function decode(nip19: NProfile): DecodedNprofile\nexport function decode(nip19: NAddr): DecodedNaddr\nexport function decode(nip19: NSec): DecodedNsec\nexport function decode(nip19: NPub): DecodedNpub\nexport function decode(nip19: Note): DecodedNote\nexport function decode(code: string): DecodedResult\nexport function decode(code: string): DecodedResult {\n let { prefix, words } = bech32.decode(code, Bech32MaxSize)\n let data = new Uint8Array(bech32.fromWords(words))\n\n switch (prefix) {\n case 'nprofile': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nprofile')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n\n return {\n type: 'nprofile',\n data: {\n pubkey: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n case 'nevent': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nevent')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n if (tlv[2] && tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (tlv[3] && tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'nevent',\n data: {\n id: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n author: tlv[2]?.[0] ? bytesToHex(tlv[2][0]) : undefined,\n kind: tlv[3]?.[0] ? parseInt(bytesToHex(tlv[3][0]), 16) : undefined,\n },\n }\n }\n\n case 'naddr': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for naddr')\n if (!tlv[2]?.[0]) throw new Error('missing TLV 2 for naddr')\n if (tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (!tlv[3]?.[0]) throw new Error('missing TLV 3 for naddr')\n if (tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'naddr',\n data: {\n identifier: utf8Decoder.decode(tlv[0][0]),\n pubkey: bytesToHex(tlv[2][0]),\n kind: parseInt(bytesToHex(tlv[3][0]), 16),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n\n case 'nsec':\n return { type: prefix, data }\n\n case 'npub':\n case 'note':\n return { type: prefix, data: bytesToHex(data) }\n\n default:\n throw new Error(`unknown prefix ${prefix}`)\n }\n}\n\ntype TLV = { [t: number]: Uint8Array[] }\n\nfunction parseTLV(data: Uint8Array): TLV {\n let result: TLV = {}\n let rest = data\n while (rest.length > 0) {\n let t = rest[0]\n let l = rest[1]\n let v = rest.slice(2, 2 + l)\n rest = rest.slice(2 + l)\n if (v.length < l) throw new Error(`not enough data to read on TLV ${t}`)\n result[t] = result[t] || []\n result[t].push(v)\n }\n return result\n}\n\nexport function nsecEncode(key: Uint8Array): NSec {\n return encodeBytes('nsec', key)\n}\n\nexport function npubEncode(hex: string): NPub {\n return encodeBytes('npub', hexToBytes(hex))\n}\n\nexport function noteEncode(hex: string): Note {\n return encodeBytes('note', hexToBytes(hex))\n}\n\nfunction encodeBech32(prefix: Prefix, data: Uint8Array): `${Prefix}1${string}` {\n let words = bech32.toWords(data)\n return bech32.encode(prefix, words, Bech32MaxSize) as `${Prefix}1${string}`\n}\n\nexport function encodeBytes(prefix: Prefix, bytes: Uint8Array): `${Prefix}1${string}` {\n return encodeBech32(prefix, bytes)\n}\n\nexport function nprofileEncode(profile: ProfilePointer): NProfile {\n let data = encodeTLV({\n 0: [hexToBytes(profile.pubkey)],\n 1: (profile.relays || []).map(url => utf8Encoder.encode(url)),\n })\n return encodeBech32('nprofile', data)\n}\n\nexport function neventEncode(event: EventPointer): NEvent {\n let kindArray\n if (event.kind !== undefined) {\n kindArray = integerToUint8Array(event.kind)\n }\n\n let data = encodeTLV({\n 0: [hexToBytes(event.id)],\n 1: (event.relays || []).map(url => utf8Encoder.encode(url)),\n 2: event.author ? [hexToBytes(event.author)] : [],\n 3: kindArray ? [new Uint8Array(kindArray)] : [],\n })\n\n return encodeBech32('nevent', data)\n}\n\nexport function naddrEncode(addr: AddressPointer): NAddr {\n let kind = new ArrayBuffer(4)\n new DataView(kind).setUint32(0, addr.kind, false)\n\n let data = encodeTLV({\n 0: [utf8Encoder.encode(addr.identifier)],\n 1: (addr.relays || []).map(url => utf8Encoder.encode(url)),\n 2: [hexToBytes(addr.pubkey)],\n 3: [new Uint8Array(kind)],\n })\n return encodeBech32('naddr', data)\n}\n\nfunction encodeTLV(tlv: TLV): Uint8Array {\n let entries: Uint8Array[] = []\n\n Object.entries(tlv)\n .reverse()\n .forEach(([t, vs]) => {\n vs.forEach(v => {\n let entry = new Uint8Array(v.length + 2)\n entry.set([parseInt(t)], 0)\n entry.set([v.length], 1)\n entry.set(v, 2)\n entries.push(entry)\n })\n })\n\n return concatBytes(...entries)\n}\n", "import { decode, type AddressPointer, type ProfilePointer, type EventPointer } from './nip19.ts'\n\nimport type { Event } from './core.ts'\n\ntype Reference = {\n text: string\n profile?: ProfilePointer\n event?: EventPointer\n address?: AddressPointer\n}\n\nconst mentionRegex = /\\bnostr:((note|npub|naddr|nevent|nprofile)1\\w+)\\b|#\\[(\\d+)\\]/g\n\nexport function parseReferences(evt: Event): Reference[] {\n let references: Reference[] = []\n for (let ref of evt.content.matchAll(mentionRegex)) {\n if (ref[2]) {\n // it's a NIP-27 mention\n try {\n let { type, data } = decode(ref[1])\n switch (type) {\n case 'npub': {\n references.push({\n text: ref[0],\n profile: { pubkey: data as string, relays: [] },\n })\n break\n }\n case 'nprofile': {\n references.push({\n text: ref[0],\n profile: data as ProfilePointer,\n })\n break\n }\n case 'note': {\n references.push({\n text: ref[0],\n event: { id: data as string, relays: [] },\n })\n break\n }\n case 'nevent': {\n references.push({\n text: ref[0],\n event: data as EventPointer,\n })\n break\n }\n case 'naddr': {\n references.push({\n text: ref[0],\n address: data as AddressPointer,\n })\n break\n }\n }\n } catch (err) {\n /***/\n }\n } else if (ref[3]) {\n // it's a NIP-10 mention\n let idx = parseInt(ref[3], 10)\n let tag = evt.tags[idx]\n if (!tag) continue\n\n switch (tag[0]) {\n case 'p': {\n references.push({\n text: ref[0],\n profile: { pubkey: tag[1], relays: tag[2] ? [tag[2]] : [] },\n })\n break\n }\n case 'e': {\n references.push({\n text: ref[0],\n event: { id: tag[1], relays: tag[2] ? [tag[2]] : [] },\n })\n break\n }\n case 'a': {\n try {\n let [kind, pubkey, identifier] = tag[1].split(':')\n references.push({\n text: ref[0],\n address: {\n identifier,\n pubkey,\n kind: parseInt(kind, 10),\n relays: tag[2] ? [tag[2]] : [],\n },\n })\n } catch (err) {\n /***/\n }\n break\n }\n }\n }\n }\n\n return references\n}\n", "import { bytesToHex, randomBytes } from '@noble/hashes/utils'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { cbc } from '@noble/ciphers/aes'\nimport { base64 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport function encrypt(secretKey: string | Uint8Array, pubkey: string, text: string): string {\n const privkey: string = secretKey instanceof Uint8Array ? bytesToHex(secretKey) : secretKey\n const key = secp256k1.getSharedSecret(privkey, '02' + pubkey)\n const normalizedKey = getNormalizedX(key)\n\n let iv = Uint8Array.from(randomBytes(16))\n let plaintext = utf8Encoder.encode(text)\n\n let ciphertext = cbc(normalizedKey, iv).encrypt(plaintext)\n\n let ctb64 = base64.encode(new Uint8Array(ciphertext))\n let ivb64 = base64.encode(new Uint8Array(iv.buffer))\n\n return `${ctb64}?iv=${ivb64}`\n}\n\nexport function decrypt(secretKey: string | Uint8Array, pubkey: string, data: string): string {\n const privkey: string = secretKey instanceof Uint8Array ? bytesToHex(secretKey) : secretKey\n let [ctb64, ivb64] = data.split('?iv=')\n let key = secp256k1.getSharedSecret(privkey, '02' + pubkey)\n let normalizedKey = getNormalizedX(key)\n\n let iv = base64.decode(ivb64)\n let ciphertext = base64.decode(ctb64)\n\n let plaintext = cbc(normalizedKey, iv).decrypt(ciphertext)\n\n return utf8Decoder.decode(plaintext)\n}\n\nfunction getNormalizedX(key: Uint8Array): Uint8Array {\n return key.slice(1, 33)\n}\n", "import { ProfilePointer } from './nip19.ts'\n\nexport type Nip05 = `${string}@${string}`\n\n/**\n * NIP-05 regex. The localpart is optional, and should be assumed to be `_` otherwise.\n *\n * - 0: full match\n * - 1: name (optional)\n * - 2: domain\n */\nexport const NIP05_REGEX = /^(?:([\\w.+-]+)@)?([\\w_-]+(\\.[\\w_-]+)+)$/\nexport const isNip05 = (value?: string | null): value is Nip05 => NIP05_REGEX.test(value || '')\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _fetch: any\n\ntry {\n _fetch = fetch\n} catch (_) {\n null\n}\n\nexport function useFetchImplementation(fetchImplementation: unknown) {\n _fetch = fetchImplementation\n}\n\nexport async function searchDomain(domain: string, query = ''): Promise<{ [name: string]: string }> {\n try {\n const url = `https://${domain}/.well-known/nostr.json?name=${query}`\n const res = await _fetch(url, { redirect: 'manual' })\n if (res.status !== 200) {\n throw Error('Wrong response code')\n }\n const json = await res.json()\n return json.names\n } catch (_) {\n return {}\n }\n}\n\nexport async function queryProfile(fullname: string): Promise {\n const match = fullname.match(NIP05_REGEX)\n if (!match) return null\n\n const [, name = '_', domain] = match\n\n try {\n const url = `https://${domain}/.well-known/nostr.json?name=${name}`\n const res = await _fetch(url, { redirect: 'manual' })\n if (res.status !== 200) {\n throw Error('Wrong response code')\n }\n const json = await res.json()\n\n const pubkey = json.names[name]\n return pubkey ? { pubkey, relays: json.relays?.[pubkey] } : null\n } catch (_e) {\n return null\n }\n}\n\nexport async function isValid(pubkey: string, nip05: Nip05): Promise {\n const res = await queryProfile(nip05)\n return res ? res.pubkey === pubkey : false\n}\n", "import type { Event } from './core.ts'\nimport type { EventPointer, ProfilePointer } from './nip19.ts'\n\nexport function parse(event: Pick): {\n /**\n * Pointer to the root of the thread.\n */\n root: EventPointer | undefined\n\n /**\n * Pointer to a \"parent\" event that parsed event replies to (responded to).\n */\n reply: EventPointer | undefined\n\n /**\n * Pointers to events that may or may not be in the reply chain.\n */\n mentions: EventPointer[]\n\n /**\n * Pointers to events that were directly quoted.\n */\n quotes: EventPointer[]\n\n /**\n * List of pubkeys that are involved in the thread in no particular order.\n */\n profiles: ProfilePointer[]\n} {\n const result: ReturnType = {\n reply: undefined,\n root: undefined,\n mentions: [],\n profiles: [],\n quotes: [],\n }\n\n let maybeParent: EventPointer | undefined\n let maybeRoot: EventPointer | undefined\n\n for (let i = event.tags.length - 1; i >= 0; i--) {\n const tag = event.tags[i]\n\n if (tag[0] === 'e' && tag[1]) {\n const [_, eTagEventId, eTagRelayUrl, eTagMarker, eTagAuthor] = tag as [\n string,\n string,\n undefined | string,\n undefined | string,\n undefined | string,\n ]\n\n const eventPointer: EventPointer = {\n id: eTagEventId,\n relays: eTagRelayUrl ? [eTagRelayUrl] : [],\n author: eTagAuthor,\n }\n\n if (eTagMarker === 'root') {\n result.root = eventPointer\n continue\n }\n\n if (eTagMarker === 'reply') {\n result.reply = eventPointer\n continue\n }\n\n if (eTagMarker === 'mention') {\n result.mentions.push(eventPointer)\n continue\n }\n\n if (!maybeParent) {\n maybeParent = eventPointer\n } else {\n maybeRoot = eventPointer\n }\n\n result.mentions.push(eventPointer)\n continue\n }\n\n if (tag[0] === 'q' && tag[1]) {\n const [_, eTagEventId, eTagRelayUrl] = tag as [string, string, undefined | string]\n result.quotes.push({\n id: eTagEventId,\n relays: eTagRelayUrl ? [eTagRelayUrl] : [],\n })\n }\n\n if (tag[0] === 'p' && tag[1]) {\n result.profiles.push({\n pubkey: tag[1],\n relays: tag[2] ? [tag[2]] : [],\n })\n continue\n }\n }\n\n // get legacy (positional) markers, set reply to root and vice-versa if one of them is missing\n if (!result.root) {\n result.root = maybeRoot || maybeParent || result.reply\n }\n if (!result.reply) {\n result.reply = maybeParent || result.root\n }\n\n // remove root and reply from mentions, inherit relay hints from authors if any\n ;[result.reply, result.root].forEach(ref => {\n if (!ref) return\n\n let idx = result.mentions.indexOf(ref)\n if (idx !== -1) {\n result.mentions.splice(idx, 1)\n }\n if (ref.author) {\n let author = result.profiles.find(p => p.pubkey === ref.author)\n if (author && author.relays) {\n if (!ref.relays) {\n ref.relays = []\n }\n author.relays.forEach(url => {\n if (ref.relays!?.indexOf(url) === -1) ref.relays!.push(url)\n })\n author.relays = ref.relays\n }\n }\n })\n\n result.mentions.forEach(ref => {\n if (ref!.author) {\n let author = result.profiles.find(p => p.pubkey === ref.author)\n if (author && author.relays) {\n if (!ref.relays) {\n ref.relays = []\n }\n author.relays.forEach(url => {\n if (ref.relays!.indexOf(url) === -1) ref.relays!.push(url)\n })\n author.relays = ref.relays\n }\n }\n })\n\n return result\n}\n", "var _fetch: any\n\ntry {\n _fetch = fetch\n} catch {}\n\nexport function useFetchImplementation(fetchImplementation: any): void {\n _fetch = fetchImplementation\n}\n\nexport async function fetchRelayInformation(url: string): Promise {\n return (await (\n await fetch(url.replace('ws://', 'http://').replace('wss://', 'https://'), {\n headers: { Accept: 'application/nostr+json' },\n })\n ).json()) as RelayInformation\n}\n\n/**\n * ## Relay Information Document\n\n * Relays may provide server metadata to clients to inform\n * them of capabilities, administrative contacts, and\n * various server attributes. This is made available as a\n * JSON document over HTTP, on the same URI as the relay's\n * websocket.\n\n * Any field may be omitted, and clients MUST ignore any\n * additional fields they do not understand. Relays MUST\n * accept CORS requests by sending\n * `Access-Control-Allow-Origin`,\n * `Access-Control-Allow-Headers`, and\n * `Access-Control-Allow-Methods` headers.\n * @param name string identifying relay\n * @param description string with detailed information\n * @param pubkey administrative contact pubkey\n * @param contact: administrative alternate contact\n * @param supported_nips a list of NIP numbers supported by\n * the relay\n * @param software identifying relay software URL\n * @param version string version identifier\n */\nexport interface BasicRelayInformation {\n // string identifying relay\n name: string\n description: string\n pubkey: string\n contact: string\n supported_nips: number[]\n software: string\n version: string\n // limitation?: Limitations\n}\n\n/**\n * * ## Extra Fields\n\n * * ### Server Limitations\n\n * These are limitations imposed by the relay on clients.\n * Your client should expect that requests which exceed\n * these practical_ limitations are rejected or fail immediately.\n * @param max_message_length this is the maximum number of\n * bytes for incoming JSON that the relay will attempt to\n * decode and act upon. When you send large subscriptions,\n * you will be limited by this value. It also effectively\n * limits the maximum size of any event. Value is calculated\n * from `[` to `]` and is after UTF-8 serialization (so some\n * unicode characters will cost 2-3 bytes). It is equal to\n * the maximum size of the WebSocket message frame.\n * @param max_subscriptions total number of subscriptions\n * that may be active on a single websocket connection to\n * this relay. It's possible that authenticated clients with\n * a (paid) relationship to the relay may have higher limits.\n * @param max_filters maximum number of filter values in\n * each subscription. Must be one or higher.\n * @param max_limit the relay server will clamp each\n * filter's `limit` value to this number.\n * This means the client won't be able to get more than this\n * number of events from a single subscription filter. This\n * clamping is typically done silently by the relay, but\n * with this number, you can know that there are additional\n * results if you narrowed your filter's time range or other\n * parameters.\n * @param max_subid_length maximum length of subscription id as a\n * string.\n * @param min_prefix for `authors` and `ids` filters which\n * are to match against a hex prefix, you must provide at\n * least this many hex digits in the prefix.\n * @param max_event_tags in any event, this is the maximum\n * number of elements in the `tags` list.\n * @param max_content_length maximum number of characters in\n * the `content` field of any event. This is a count of\n * unicode characters. After serializing into JSON it may be\n * larger (in bytes), and is still subject to the\n * max_message_length`, if defined.\n * @param min_pow_difficulty new events will require at\n * least this difficulty of PoW, based on [NIP-13](13.md),\n * or they will be rejected by this server.\n * @param auth_required this relay requires [NIP-42](42.md)\n * authentication to happen before a new connection may\n * perform any other action. Even if set to False,\n * authentication may be required for specific actions.\n * @param restricted_writes: this relay requires some kind\n * of condition to be fulfilled in order to accept events\n * (not necessarily, but including\n * @param payment_required this relay requires payment\n * before a new connection may perform any action.\n * @param created_at_lower_limit: 'created_at' lower limit\n * @param created_at_upper_limit: 'created_at' upper limit\n */\nexport interface Limitations {\n max_message_length: number\n max_subscriptions: number\n max_filters: number\n max_limit: number\n max_subid_length: number\n min_prefix: number\n max_event_tags: number\n max_content_length: number\n min_pow_difficulty: number\n auth_required: boolean\n payment_required: boolean\n created_at_lower_limit: number\n created_at_upper_limit: number\n restricted_writes: boolean\n}\n\nexport interface RetentionDetails {\n kinds: (number | number[])[]\n time?: number | null\n count?: number | null\n}\ntype AnyRetentionDetails = RetentionDetails\n/**\n * ### Event Retention\n\n * There may be a cost associated with storing data forever,\n * so relays may wish to state retention times. The values\n * stated here are defaults for unauthenticated users and\n * visitors. Paid users would likely have other policies.\n\n * Retention times are given in seconds, with `null`\n * indicating infinity. If zero is provided, this means the\n * event will not be stored at all, and preferably an error\n * will be provided when those are received.\n * ```json\n{\n...\n \"retention\": [\n { \"kinds\": [0, 1, [5, 7], [40, 49]], \"time\": 3600 },\n { \"kinds\": [[40000, 49999]], \"time\": 100 },\n { \"kinds\": [[30000, 39999]], \"count\": 1000 },\n { \"time\": 3600, \"count\": 10000 }\n ]\n...\n}\n```\n * @param retention is a list of specifications: each will\n * apply to either all kinds, or a subset of kinds. Ranges\n * may be specified for the kind field as a tuple of\n * inclusive start and end values. Events of indicated kind\n * (or all) are then limited to a `count` and/or time\n * period.\n\n * It is possible to effectively blacklist Nostr-based\n * protocols that rely on a specific `kind` number, by\n * giving a retention time of zero for those `kind` values.\n * While that is unfortunate, it does allow clients to\n * discover servers that will support their protocol quickly\n * via a single HTTP fetch.\n\n * There is no need to specify retention times for\n * _ephemeral events_ as defined in [NIP-16](16.md) since\n * they are not retained.\n */\nexport interface Retention {\n retention: AnyRetentionDetails[]\n}\n\n/**\n * Some relays may be governed by the arbitrary laws of a\n * nation state. This may limit what content can be stored\n * in cleartext on those relays. All clients are encouraged\n * to use encryption to work around this limitation.\n\n * It is not possible to describe the limitations of each\n * country's laws and policies which themselves are\n * typically vague and constantly shifting.\n\n * Therefore, this field allows the relay operator to\n * indicate which countries' laws might end up being\n * enforced on them, and then indirectly on their users'\n * content.\n\n * Users should be able to avoid relays in countries they\n * don't like, and/or select relays in more favourable\n * zones. Exposing this flexibility is up to the client\n * software.\n\n * @param relay_countries a list of two-level ISO country\n * codes (ISO 3166-1 alpha-2) whose laws and policies may\n * affect this relay. `EU` may be used for European Union\n * countries.\n\n * Remember that a relay may be hosted in a country which is\n * not the country of the legal entities who own the relay,\n * so it's very likely a number of countries are involved.\n */\nexport interface ContentLimitations {\n relay_countries: string[]\n}\n\n/**\n * ### Community Preferences\n\n * For public text notes at least, a relay may try to foster\n * a local community. This would encourage users to follow\n * the global feed on that relay, in addition to their usual\n * individual follows. To support this goal, relays MAY\n * specify some of the following values.\n\n * @param language_tags is an ordered list of [IETF\n * language\n * tags](https://en.wikipedia.org/wiki/IETF_language_tag\n * indicating the major languages spoken on the relay.\n * @param tags is a list of limitations on the topics to be\n * discussed. For example `sfw-only` indicates that only\n * \"Safe For Work\" content is encouraged on this relay. This\n * relies on assumptions of what the \"work\" \"community\"\n * feels \"safe\" talking about. In time, a common set of tags\n * may emerge that allow users to find relays that suit\n * their needs, and client software will be able to parse\n * these tags easily. The `bitcoin-only` tag indicates that\n * any _altcoin_, _\"crypto\"_ or _blockchain_ comments will\n * be ridiculed without mercy.\n * @param posting_policy is a link to a human-readable page\n * which specifies the community policies for the relay. In\n * cases where `sfw-only` is True, it's important to link to\n * a page which gets into the specifics of your posting\n * policy.\n\n * The `description` field should be used to describe your\n * community goals and values, in brief. The\n * `posting_policy` is for additional detail and legal\n * terms. Use the `tags` field to signify limitations on\n * content, or topics to be discussed, which could be\n * machine processed by appropriate client software.\n */\nexport interface CommunityPreferences {\n language_tags: string[]\n tags: string[]\n posting_policy: string\n}\n\nexport interface Amount {\n amount: number\n unit: 'msat'\n}\nexport interface PublicationAmount extends Amount {\n kinds: number[]\n}\nexport interface Subscription extends Amount {\n period: number\n}\nexport interface Fees {\n admission: Amount[]\n subscription: Subscription[]\n publication: PublicationAmount[]\n}\n/**\n * Relays that require payments may want to expose their fee\n * schedules.\n */\nexport interface PayToRelay {\n payments_url: string\n fees: Fees\n}\n\n/**\n * A URL pointing to an image to be used as an icon for the\n * relay. Recommended to be squared in shape.\n */\nexport interface Icon {\n icon: string\n}\n\nexport type RelayInformation = BasicRelayInformation &\n Partial & {\n limitation?: Partial\n } & Partial &\n Partial &\n Partial &\n Partial\n", "import { bytesToHex } from '@noble/hashes/utils'\nimport { type UnsignedEvent, type Event } from './pure.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\n/** Get POW difficulty from a Nostr hex ID. */\nexport function getPow(hex: string): number {\n let count = 0\n\n for (let i = 0; i < 64; i += 8) {\n const nibble = parseInt(hex.substring(i, i + 8), 16)\n if (nibble === 0) {\n count += 32\n } else {\n count += Math.clz32(nibble)\n break\n }\n }\n\n return count\n}\n\n/**\n * Mine an event with the desired POW. This function mutates the event.\n * Note that this operation is synchronous and should be run in a worker context to avoid blocking the main thread.\n */\nexport function minePow(unsigned: UnsignedEvent, difficulty: number): Omit {\n let count = 0\n\n const event = unsigned as Omit\n const tag = ['nonce', count.toString(), difficulty.toString()]\n\n event.tags.push(tag)\n\n while (true) {\n const now = Math.floor(new Date().getTime() / 1000)\n\n if (now !== event.created_at) {\n count = 0\n event.created_at = now\n }\n\n tag[1] = (++count).toString()\n\n event.id = fastEventHash(event)\n\n if (getPow(event.id) >= difficulty) {\n break\n }\n }\n\n return event\n}\n\nexport function fastEventHash(evt: UnsignedEvent): string {\n return bytesToHex(\n sha256(utf8Encoder.encode(JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]))),\n )\n}\n", "import { PrivateDirectMessage } from './kinds.ts'\nimport { EventTemplate, NostrEvent, getPublicKey } from './pure.ts'\nimport * as nip59 from './nip59.ts'\n\ntype Recipient = {\n publicKey: string\n relayUrl?: string\n}\n\ntype ReplyTo = {\n eventId: string\n relayUrl?: string\n}\n\nfunction createEvent(\n recipients: Recipient | Recipient[],\n message: string,\n conversationTitle?: string,\n replyTo?: ReplyTo,\n): EventTemplate {\n const baseEvent: EventTemplate = {\n created_at: Math.ceil(Date.now() / 1000),\n kind: PrivateDirectMessage,\n tags: [],\n content: message,\n }\n\n const recipientsArray = Array.isArray(recipients) ? recipients : [recipients]\n\n recipientsArray.forEach(({ publicKey, relayUrl }) => {\n baseEvent.tags.push(relayUrl ? ['p', publicKey, relayUrl] : ['p', publicKey])\n })\n\n if (replyTo) {\n baseEvent.tags.push(['e', replyTo.eventId, replyTo.relayUrl || '', 'reply'])\n }\n\n if (conversationTitle) {\n baseEvent.tags.push(['subject', conversationTitle])\n }\n\n return baseEvent\n}\n\nexport function wrapEvent(\n senderPrivateKey: Uint8Array,\n recipient: Recipient,\n message: string,\n conversationTitle?: string,\n replyTo?: ReplyTo,\n): NostrEvent {\n const event = createEvent(recipient, message, conversationTitle, replyTo)\n return nip59.wrapEvent(event, senderPrivateKey, recipient.publicKey)\n}\n\nexport function wrapManyEvents(\n senderPrivateKey: Uint8Array,\n recipients: Recipient[],\n message: string,\n conversationTitle?: string,\n replyTo?: ReplyTo,\n): NostrEvent[] {\n if (!recipients || recipients.length === 0) {\n throw new Error('At least one recipient is required.')\n }\n\n const senderPublicKey = getPublicKey(senderPrivateKey)\n\n // wrap the event for the sender and then for each recipient\n return [{ publicKey: senderPublicKey }, ...recipients].map(recipient =>\n wrapEvent(senderPrivateKey, recipient, message, conversationTitle, replyTo),\n )\n}\n\nexport const unwrapEvent = nip59.unwrapEvent\n\nexport const unwrapManyEvents = nip59.unwrapManyEvents\n", "import { EventTemplate, UnsignedEvent, NostrEvent } from './core.ts'\nimport { getConversationKey, decrypt, encrypt } from './nip44.ts'\nimport { getEventHash, generateSecretKey, finalizeEvent, getPublicKey } from './pure.ts'\nimport { Seal, GiftWrap } from './kinds.ts'\n\ntype Rumor = UnsignedEvent & { id: string }\n\nconst TWO_DAYS = 2 * 24 * 60 * 60\n\nconst now = () => Math.round(Date.now() / 1000)\nconst randomNow = () => Math.round(now() - Math.random() * TWO_DAYS)\n\nconst nip44ConversationKey = (privateKey: Uint8Array, publicKey: string) => getConversationKey(privateKey, publicKey)\n\nconst nip44Encrypt = (data: EventTemplate, privateKey: Uint8Array, publicKey: string) =>\n encrypt(JSON.stringify(data), nip44ConversationKey(privateKey, publicKey))\n\nconst nip44Decrypt = (data: NostrEvent, privateKey: Uint8Array) =>\n JSON.parse(decrypt(data.content, nip44ConversationKey(privateKey, data.pubkey)))\n\nexport function createRumor(event: Partial, privateKey: Uint8Array): Rumor {\n const rumor = {\n created_at: now(),\n content: '',\n tags: [],\n ...event,\n pubkey: getPublicKey(privateKey),\n } as any\n\n rumor.id = getEventHash(rumor)\n\n return rumor as Rumor\n}\n\nexport function createSeal(rumor: Rumor, privateKey: Uint8Array, recipientPublicKey: string): NostrEvent {\n return finalizeEvent(\n {\n kind: Seal,\n content: nip44Encrypt(rumor, privateKey, recipientPublicKey),\n created_at: randomNow(),\n tags: [],\n },\n privateKey,\n )\n}\n\nexport function createWrap(seal: NostrEvent, recipientPublicKey: string): NostrEvent {\n const randomKey = generateSecretKey()\n\n return finalizeEvent(\n {\n kind: GiftWrap,\n content: nip44Encrypt(seal, randomKey, recipientPublicKey),\n created_at: randomNow(),\n tags: [['p', recipientPublicKey]],\n },\n randomKey,\n ) as NostrEvent\n}\n\nexport function wrapEvent(\n event: Partial,\n senderPrivateKey: Uint8Array,\n recipientPublicKey: string,\n): NostrEvent {\n const rumor = createRumor(event, senderPrivateKey)\n\n const seal = createSeal(rumor, senderPrivateKey, recipientPublicKey)\n return createWrap(seal, recipientPublicKey)\n}\n\nexport function wrapManyEvents(\n event: Partial,\n senderPrivateKey: Uint8Array,\n recipientsPublicKeys: string[],\n): NostrEvent[] {\n if (!recipientsPublicKeys || recipientsPublicKeys.length === 0) {\n throw new Error('At least one recipient is required.')\n }\n\n const senderPublicKey = getPublicKey(senderPrivateKey)\n\n const wrappeds = [wrapEvent(event, senderPrivateKey, senderPublicKey)]\n\n recipientsPublicKeys.forEach(recipientPublicKey => {\n wrappeds.push(wrapEvent(event, senderPrivateKey, recipientPublicKey))\n })\n\n return wrappeds\n}\n\nexport function unwrapEvent(wrap: NostrEvent, recipientPrivateKey: Uint8Array): Rumor {\n const unwrappedSeal = nip44Decrypt(wrap, recipientPrivateKey)\n return nip44Decrypt(unwrappedSeal, recipientPrivateKey)\n}\n\nexport function unwrapManyEvents(wrappedEvents: NostrEvent[], recipientPrivateKey: Uint8Array): Rumor[] {\n let unwrappedEvents: Rumor[] = []\n\n wrappedEvents.forEach(e => {\n unwrappedEvents.push(unwrapEvent(e, recipientPrivateKey))\n })\n\n unwrappedEvents.sort((a, b) => a.created_at - b.created_at)\n\n return unwrappedEvents\n}\n", "import { chacha20 } from '@noble/ciphers/chacha'\nimport { equalBytes } from '@noble/ciphers/utils'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { extract as hkdf_extract, expand as hkdf_expand } from '@noble/hashes/hkdf'\nimport { hmac } from '@noble/hashes/hmac'\nimport { sha256 } from '@noble/hashes/sha256'\nimport { concatBytes, randomBytes } from '@noble/hashes/utils'\nimport { base64 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nconst minPlaintextSize = 0x0001 // 1b msg => padded to 32b\nconst maxPlaintextSize = 0xffff // 65535 (64kb-1) => padded to 64kb\n\nexport function getConversationKey(privkeyA: Uint8Array, pubkeyB: string): Uint8Array {\n const sharedX = secp256k1.getSharedSecret(privkeyA, '02' + pubkeyB).subarray(1, 33)\n return hkdf_extract(sha256, sharedX, 'nip44-v2')\n}\n\nfunction getMessageKeys(\n conversationKey: Uint8Array,\n nonce: Uint8Array,\n): { chacha_key: Uint8Array; chacha_nonce: Uint8Array; hmac_key: Uint8Array } {\n const keys = hkdf_expand(sha256, conversationKey, nonce, 76)\n return {\n chacha_key: keys.subarray(0, 32),\n chacha_nonce: keys.subarray(32, 44),\n hmac_key: keys.subarray(44, 76),\n }\n}\n\nfunction calcPaddedLen(len: number): number {\n if (!Number.isSafeInteger(len) || len < 1) throw new Error('expected positive integer')\n if (len <= 32) return 32\n const nextPower = 1 << (Math.floor(Math.log2(len - 1)) + 1)\n const chunk = nextPower <= 256 ? 32 : nextPower / 8\n return chunk * (Math.floor((len - 1) / chunk) + 1)\n}\n\nfunction writeU16BE(num: number): Uint8Array {\n if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize)\n throw new Error('invalid plaintext size: must be between 1 and 65535 bytes')\n const arr = new Uint8Array(2)\n new DataView(arr.buffer).setUint16(0, num, false)\n return arr\n}\n\nfunction pad(plaintext: string): Uint8Array {\n const unpadded = utf8Encoder.encode(plaintext)\n const unpaddedLen = unpadded.length\n const prefix = writeU16BE(unpaddedLen)\n const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen)\n return concatBytes(prefix, unpadded, suffix)\n}\n\nfunction unpad(padded: Uint8Array): string {\n const unpaddedLen = new DataView(padded.buffer).getUint16(0)\n const unpadded = padded.subarray(2, 2 + unpaddedLen)\n if (\n unpaddedLen < minPlaintextSize ||\n unpaddedLen > maxPlaintextSize ||\n unpadded.length !== unpaddedLen ||\n padded.length !== 2 + calcPaddedLen(unpaddedLen)\n )\n throw new Error('invalid padding')\n return utf8Decoder.decode(unpadded)\n}\n\nfunction hmacAad(key: Uint8Array, message: Uint8Array, aad: Uint8Array): Uint8Array {\n if (aad.length !== 32) throw new Error('AAD associated data must be 32 bytes')\n const combined = concatBytes(aad, message)\n return hmac(sha256, key, combined)\n}\n\n// metadata: always 65b (version: 1b, nonce: 32b, max: 32b)\n// plaintext: 1b to 0xffff\n// padded plaintext: 32b to 0xffff\n// ciphertext: 32b+2 to 0xffff+2\n// raw payload: 99 (65+32+2) to 65603 (65+0xffff+2)\n// compressed payload (base64): 132b to 87472b\nfunction decodePayload(payload: string): { nonce: Uint8Array; ciphertext: Uint8Array; mac: Uint8Array } {\n if (typeof payload !== 'string') throw new Error('payload must be a valid string')\n const plen = payload.length\n if (plen < 132 || plen > 87472) throw new Error('invalid payload length: ' + plen)\n if (payload[0] === '#') throw new Error('unknown encryption version')\n let data: Uint8Array\n try {\n data = base64.decode(payload)\n } catch (error) {\n throw new Error('invalid base64: ' + (error as any).message)\n }\n const dlen = data.length\n if (dlen < 99 || dlen > 65603) throw new Error('invalid data length: ' + dlen)\n const vers = data[0]\n if (vers !== 2) throw new Error('unknown encryption version ' + vers)\n return {\n nonce: data.subarray(1, 33),\n ciphertext: data.subarray(33, -32),\n mac: data.subarray(-32),\n }\n}\n\nexport function encrypt(plaintext: string, conversationKey: Uint8Array, nonce: Uint8Array = randomBytes(32)): string {\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n const padded = pad(plaintext)\n const ciphertext = chacha20(chacha_key, chacha_nonce, padded)\n const mac = hmacAad(hmac_key, ciphertext, nonce)\n return base64.encode(concatBytes(new Uint8Array([2]), nonce, ciphertext, mac))\n}\n\nexport function decrypt(payload: string, conversationKey: Uint8Array): string {\n const { nonce, ciphertext, mac } = decodePayload(payload)\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n const calculatedMac = hmacAad(hmac_key, ciphertext, nonce)\n if (!equalBytes(calculatedMac, mac)) throw new Error('invalid MAC')\n const padded = chacha20(chacha_key, chacha_nonce, ciphertext)\n return unpad(padded)\n}\n\nexport const v2 = {\n utils: {\n getConversationKey,\n calcPaddedLen,\n },\n encrypt,\n decrypt,\n}\n", "import { GenericRepost, Repost, ShortTextNote } from './kinds.ts'\nimport { EventPointer } from './nip19.ts'\nimport { Event, finalizeEvent, verifyEvent } from './pure.ts'\n\nexport type RepostEventTemplate = {\n /**\n * Pass only non-nip18 tags if you have to.\n * Nip18 tags ('e' and 'p' tags pointing to the reposted event) will be added automatically.\n */\n tags?: string[][]\n\n /**\n * Pass an empty string to NOT include the stringified JSON of the reposted event.\n * Any other content will be ignored and replaced with the stringified JSON of the reposted event.\n * @default Stringified JSON of the reposted event\n */\n content?: ''\n\n created_at: number\n}\n\nexport function finishRepostEvent(\n t: RepostEventTemplate,\n reposted: Event,\n relayUrl: string,\n privateKey: Uint8Array,\n): Event {\n let kind: Repost | GenericRepost\n const tags = [...(t.tags ?? []), ['e', reposted.id, relayUrl], ['p', reposted.pubkey]]\n if (reposted.kind === ShortTextNote) {\n kind = Repost\n } else {\n kind = GenericRepost\n tags.push(['k', String(reposted.kind)])\n }\n\n return finalizeEvent(\n {\n kind,\n tags,\n content: t.content === '' || reposted.tags?.find(tag => tag[0] === '-') ? '' : JSON.stringify(reposted),\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\nexport function getRepostedEventPointer(event: Event): undefined | EventPointer {\n if (![Repost, GenericRepost].includes(event.kind)) {\n return undefined\n }\n\n let lastETag: undefined | string[]\n let lastPTag: undefined | string[]\n\n for (let i = event.tags.length - 1; i >= 0 && (lastETag === undefined || lastPTag === undefined); i--) {\n const tag = event.tags[i]\n if (tag.length >= 2) {\n if (tag[0] === 'e' && lastETag === undefined) {\n lastETag = tag\n } else if (tag[0] === 'p' && lastPTag === undefined) {\n lastPTag = tag\n }\n }\n }\n\n if (lastETag === undefined) {\n return undefined\n }\n\n return {\n id: lastETag[1],\n relays: [lastETag[2], lastPTag?.[2]].filter((x): x is string => typeof x === 'string'),\n author: lastPTag?.[1],\n }\n}\n\nexport type GetRepostedEventOptions = {\n skipVerification?: boolean\n}\n\nexport function getRepostedEvent(event: Event, { skipVerification }: GetRepostedEventOptions = {}): undefined | Event {\n const pointer = getRepostedEventPointer(event)\n\n if (pointer === undefined || event.content === '') {\n return undefined\n }\n\n let repostedEvent: undefined | Event\n\n try {\n repostedEvent = JSON.parse(event.content) as Event\n } catch (error) {\n return undefined\n }\n\n if (repostedEvent.id !== pointer.id) {\n return undefined\n }\n\n if (!skipVerification && !verifyEvent(repostedEvent)) {\n return undefined\n }\n\n return repostedEvent\n}\n", "import { AddressPointer, BECH32_REGEX, decode, EventPointer, ProfilePointer } from './nip19.ts'\n\n/** Nostr URI regex, eg `nostr:npub1...` */\nexport const NOSTR_URI_REGEX: RegExp = new RegExp(`nostr:(${BECH32_REGEX.source})`)\n\n/** Test whether the value is a Nostr URI. */\nexport function test(value: unknown): value is `nostr:${string}` {\n return typeof value === 'string' && new RegExp(`^${NOSTR_URI_REGEX.source}$`).test(value)\n}\n\n/** Parsed Nostr URI data. */\nexport interface NostrURI {\n /** Full URI including the `nostr:` protocol. */\n uri: `nostr:${string}`\n /** The bech32-encoded data (eg `npub1...`). */\n value: string\n /** Decoded bech32 string, according to NIP-19. */\n decoded:\n | {\n type: 'nevent'\n data: EventPointer\n }\n | {\n type: 'nprofile'\n data: ProfilePointer\n }\n | {\n type: 'naddr'\n data: AddressPointer\n }\n | {\n type: 'npub'\n data: string\n }\n | {\n type: 'nsec'\n data: Uint8Array\n }\n | {\n type: 'note'\n data: string\n }\n}\n\n/** Parse and decode a Nostr URI. */\nexport function parse(uri: string): NostrURI {\n const match = uri.match(new RegExp(`^${NOSTR_URI_REGEX.source}$`))\n if (!match) throw new Error(`Invalid Nostr URI: ${uri}`)\n return {\n uri: match[0] as `nostr:${string}`,\n value: match[1],\n decoded: decode(match[1]),\n }\n}\n", "import { Event, finalizeEvent } from './pure.ts'\nimport { Reaction } from './kinds.ts'\n\nimport type { EventPointer } from './nip19.ts'\n\nexport type ReactionEventTemplate = {\n /**\n * Pass only non-nip25 tags if you have to. Nip25 tags ('e' and 'p' tags from reacted event) will be added automatically.\n */\n tags?: string[][]\n\n /**\n * @default '+'\n */\n content?: string\n\n created_at: number\n}\n\nexport function finishReactionEvent(t: ReactionEventTemplate, reacted: Event, privateKey: Uint8Array): Event {\n const inheritedTags = reacted.tags.filter(tag => tag.length >= 2 && (tag[0] === 'e' || tag[0] === 'p'))\n\n return finalizeEvent(\n {\n ...t,\n kind: Reaction,\n tags: [...(t.tags ?? []), ...inheritedTags, ['e', reacted.id], ['p', reacted.pubkey]],\n content: t.content ?? '+',\n },\n privateKey,\n )\n}\n\nexport function getReactedEventPointer(event: Event): undefined | EventPointer {\n if (event.kind !== Reaction) {\n return undefined\n }\n\n let lastETag: undefined | string[]\n let lastPTag: undefined | string[]\n\n for (let i = event.tags.length - 1; i >= 0 && (lastETag === undefined || lastPTag === undefined); i--) {\n const tag = event.tags[i]\n if (tag.length >= 2) {\n if (tag[0] === 'e' && lastETag === undefined) {\n lastETag = tag\n } else if (tag[0] === 'p' && lastPTag === undefined) {\n lastPTag = tag\n }\n }\n }\n\n if (lastETag === undefined || lastPTag === undefined) {\n return undefined\n }\n\n return {\n id: lastETag[1],\n relays: [lastETag[2], lastPTag[2]].filter(x => x !== undefined),\n author: lastPTag[1],\n }\n}\n", "import { AddressPointer, EventPointer, ProfilePointer, decode } from './nip19.ts'\n\nexport type Block =\n | {\n type: 'text'\n text: string\n }\n | {\n type: 'reference'\n pointer: ProfilePointer | AddressPointer | EventPointer\n }\n | {\n type: 'url'\n url: string\n }\n | {\n type: 'relay'\n url: string\n }\n | {\n type: 'image'\n url: string\n }\n | {\n type: 'video'\n url: string\n }\n | {\n type: 'audio'\n url: string\n }\n\nconst noCharacter = /\\W/m\nconst noURLCharacter = /\\W |\\W$|$|,| /m\n\nexport function* parse(content: string): Iterable {\n const max = content.length\n let prevIndex = 0\n let index = 0\n while (index < max) {\n let u = content.indexOf(':', index)\n if (u === -1) {\n // reached end\n break\n }\n\n if (content.substring(u - 5, u) === 'nostr') {\n const m = content.substring(u + 60).match(noCharacter)\n const end = m ? u + 60 + m.index! : max\n try {\n let pointer: ProfilePointer | AddressPointer | EventPointer\n let { data, type } = decode(content.substring(u + 1, end))\n\n switch (type) {\n case 'npub':\n pointer = { pubkey: data } as ProfilePointer\n break\n case 'nsec':\n case 'note':\n // ignore this, treat it as not a valid uri\n index = end + 1\n continue\n default:\n pointer = data as any\n }\n\n if (prevIndex !== u - 5) {\n yield { type: 'text', text: content.substring(prevIndex, u - 5) }\n }\n yield { type: 'reference', pointer }\n index = end\n prevIndex = index\n continue\n } catch (_err) {\n // ignore this, not a valid nostr uri\n index = u + 1\n continue\n }\n } else if (content.substring(u - 5, u) === 'https' || content.substring(u - 4, u) === 'http') {\n const m = content.substring(u + 4).match(noURLCharacter)\n const end = m ? u + 4 + m.index! : max\n const prefixLen = content[u - 1] === 's' ? 5 : 4\n try {\n let url = new URL(content.substring(u - prefixLen, end))\n if (url.hostname.indexOf('.') === -1) {\n throw new Error('invalid url')\n }\n\n if (prevIndex !== u - prefixLen) {\n yield { type: 'text', text: content.substring(prevIndex, u - prefixLen) }\n }\n\n if (\n url.pathname.endsWith('.png') ||\n url.pathname.endsWith('.jpg') ||\n url.pathname.endsWith('.jpeg') ||\n url.pathname.endsWith('.gif') ||\n url.pathname.endsWith('.webp')\n ) {\n yield { type: 'image', url: url.toString() }\n index = end\n prevIndex = index\n continue\n }\n if (\n url.pathname.endsWith('.mp4') ||\n url.pathname.endsWith('.avi') ||\n url.pathname.endsWith('.webm') ||\n url.pathname.endsWith('.mkv')\n ) {\n yield { type: 'video', url: url.toString() }\n index = end\n prevIndex = index\n continue\n }\n if (\n url.pathname.endsWith('.mp3') ||\n url.pathname.endsWith('.aac') ||\n url.pathname.endsWith('.ogg') ||\n url.pathname.endsWith('.opus')\n ) {\n yield { type: 'audio', url: url.toString() }\n index = end\n prevIndex = index\n continue\n }\n\n yield { type: 'url', url: url.toString() }\n index = end\n prevIndex = index\n continue\n } catch (_err) {\n // ignore this, not a valid url\n index = end + 1\n continue\n }\n } else if (content.substring(u - 3, u) === 'wss' || content.substring(u - 2, u) === 'ws') {\n const m = content.substring(u + 4).match(noURLCharacter)\n const end = m ? u + 4 + m.index! : max\n const prefixLen = content[u - 1] === 's' ? 3 : 2\n try {\n let url = new URL(content.substring(u - prefixLen, end))\n if (url.hostname.indexOf('.') === -1) {\n throw new Error('invalid ws url')\n }\n\n if (prevIndex !== u - prefixLen) {\n yield { type: 'text', text: content.substring(prevIndex, u - prefixLen) }\n }\n yield { type: 'relay', url: url.toString() }\n index = end\n prevIndex = index\n continue\n } catch (_err) {\n // ignore this, not a valid url\n index = end + 1\n continue\n }\n } else {\n // ignore this, it is nothing\n index = u + 1\n continue\n }\n }\n\n if (prevIndex !== max) {\n yield { type: 'text', text: content.substring(prevIndex) }\n }\n}\n", "import { Event, finalizeEvent } from './pure.ts'\nimport {\n ChannelCreation,\n ChannelHideMessage,\n ChannelMessage,\n ChannelMetadata as KindChannelMetadata,\n ChannelMuteUser,\n} from './kinds.ts'\n\nexport interface ChannelMetadata {\n name: string\n about: string\n picture: string\n}\n\nexport interface ChannelCreateEventTemplate {\n /* JSON string containing ChannelMetadata as defined for Kind 40 and 41 in nip-28. */\n content: string | ChannelMetadata\n created_at: number\n tags?: string[][]\n}\n\nexport interface ChannelMetadataEventTemplate {\n channel_create_event_id: string\n /* JSON string containing ChannelMetadata as defined for Kind 40 and 41 in nip-28. */\n content: string | ChannelMetadata\n created_at: number\n tags?: string[][]\n}\n\nexport interface ChannelMessageEventTemplate {\n channel_create_event_id: string\n reply_to_channel_message_event_id?: string\n relay_url: string\n content: string\n created_at: number\n tags?: string[][]\n}\n\nexport interface ChannelHideMessageEventTemplate {\n channel_message_event_id: string\n content: string | { reason: string }\n created_at: number\n tags?: string[][]\n}\n\nexport interface ChannelMuteUserEventTemplate {\n content: string | { reason: string }\n created_at: number\n pubkey_to_mute: string\n tags?: string[][]\n}\n\nexport const channelCreateEvent = (t: ChannelCreateEventTemplate, privateKey: Uint8Array): Event | undefined => {\n let content: string\n if (typeof t.content === 'object') {\n content = JSON.stringify(t.content)\n } else if (typeof t.content === 'string') {\n content = t.content\n } else {\n return undefined\n }\n\n return finalizeEvent(\n {\n kind: ChannelCreation,\n tags: [...(t.tags ?? [])],\n content: content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\nexport const channelMetadataEvent = (t: ChannelMetadataEventTemplate, privateKey: Uint8Array): Event | undefined => {\n let content: string\n if (typeof t.content === 'object') {\n content = JSON.stringify(t.content)\n } else if (typeof t.content === 'string') {\n content = t.content\n } else {\n return undefined\n }\n\n return finalizeEvent(\n {\n kind: KindChannelMetadata,\n tags: [['e', t.channel_create_event_id], ...(t.tags ?? [])],\n content: content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\nexport const channelMessageEvent = (t: ChannelMessageEventTemplate, privateKey: Uint8Array): Event => {\n const tags = [['e', t.channel_create_event_id, t.relay_url, 'root']]\n\n if (t.reply_to_channel_message_event_id) {\n tags.push(['e', t.reply_to_channel_message_event_id, t.relay_url, 'reply'])\n }\n\n return finalizeEvent(\n {\n kind: ChannelMessage,\n tags: [...tags, ...(t.tags ?? [])],\n content: t.content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\n/* \"e\" tag should be the kind 42 event to hide */\nexport const channelHideMessageEvent = (\n t: ChannelHideMessageEventTemplate,\n privateKey: Uint8Array,\n): Event | undefined => {\n let content: string\n if (typeof t.content === 'object') {\n content = JSON.stringify(t.content)\n } else if (typeof t.content === 'string') {\n content = t.content\n } else {\n return undefined\n }\n\n return finalizeEvent(\n {\n kind: ChannelHideMessage,\n tags: [['e', t.channel_message_event_id], ...(t.tags ?? [])],\n content: content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\nexport const channelMuteUserEvent = (t: ChannelMuteUserEventTemplate, privateKey: Uint8Array): Event | undefined => {\n let content: string\n if (typeof t.content === 'object') {\n content = JSON.stringify(t.content)\n } else if (typeof t.content === 'string') {\n content = t.content\n } else {\n return undefined\n }\n\n return finalizeEvent(\n {\n kind: ChannelMuteUser,\n tags: [['p', t.pubkey_to_mute], ...(t.tags ?? [])],\n content: content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n", "/** Regex for a single emoji shortcode. */\nexport const EMOJI_SHORTCODE_REGEX = /:(\\w+):/\n\n/** Regex to find emoji shortcodes in content. */\nexport const regex = (): RegExp => new RegExp(`\\\\B${EMOJI_SHORTCODE_REGEX.source}\\\\B`, 'g')\n\n/** Represents a Nostr custom emoji. */\nexport interface CustomEmoji {\n /** The matched emoji name with colons. */\n shortcode: `:${string}:`\n /** The matched emoji name without colons. */\n name: string\n}\n\n/** Match result for a custom emoji in text content. */\nexport interface CustomEmojiMatch extends CustomEmoji {\n /** Index where the emoji begins in the text content. */\n start: number\n /** Index where the emoji ends in the text content. */\n end: number\n}\n\n/** Find all custom emoji shortcodes. */\nexport function* matchAll(content: string): Iterable {\n const matches = content.matchAll(regex())\n\n for (const match of matches) {\n try {\n const [shortcode, name] = match\n\n yield {\n shortcode: shortcode as `:${string}:`,\n name,\n start: match.index!,\n end: match.index! + shortcode.length,\n }\n } catch (_e) {\n // do nothing\n }\n }\n}\n\n/** Replace all emoji shortcodes in the content. */\nexport function replaceAll(content: string, replacer: (match: CustomEmoji) => string): string {\n return content.replaceAll(regex(), (shortcode, name) => {\n return replacer({\n shortcode: shortcode as `:${string}:`,\n name,\n })\n })\n}\n", "var _fetch: any\n\ntry {\n _fetch = fetch\n} catch {}\n\nexport function useFetchImplementation(fetchImplementation: any) {\n _fetch = fetchImplementation\n}\n\nexport async function validateGithub(pubkey: string, username: string, proof: string): Promise {\n try {\n let res = await (await _fetch(`https://gist.github.com/${username}/${proof}/raw`)).text()\n return res === `Verifying that I control the following Nostr public key: ${pubkey}`\n } catch (_) {\n return false\n }\n}\n", "import { type VerifiedEvent, finalizeEvent } from './pure.ts'\nimport { NWCWalletRequest } from './kinds.ts'\nimport { encrypt } from './nip04.ts'\n\ninterface NWCConnection {\n pubkey: string\n relay: string\n secret: string\n}\n\nexport function parseConnectionString(connectionString: string): NWCConnection {\n const { host, pathname, searchParams } = new URL(connectionString)\n const pubkey = pathname || host\n const relay = searchParams.get('relay')\n const secret = searchParams.get('secret')\n\n if (!pubkey || !relay || !secret) {\n throw new Error('invalid connection string')\n }\n\n return { pubkey, relay, secret }\n}\n\nexport async function makeNwcRequestEvent(\n pubkey: string,\n secretKey: Uint8Array,\n invoice: string,\n): Promise {\n const content = {\n method: 'pay_invoice',\n params: {\n invoice,\n },\n }\n const encryptedContent = encrypt(secretKey, pubkey, JSON.stringify(content))\n const eventTemplate = {\n kind: NWCWalletRequest,\n created_at: Math.round(Date.now() / 1000),\n content: encryptedContent,\n tags: [['p', pubkey]],\n }\n\n return finalizeEvent(eventTemplate, secretKey)\n}\n", "export function normalizeIdentifier(name: string): string {\n // Trim and lowercase\n name = name.trim().toLowerCase()\n\n // Normalize Unicode to NFKC form\n name = name.normalize('NFKC')\n\n // Convert to array of characters and map each one\n return Array.from(name)\n .map(char => {\n // Check if character is letter or number using Unicode ranges\n if (/\\p{Letter}/u.test(char) || /\\p{Number}/u.test(char)) {\n return char\n }\n\n return '-'\n })\n .join('')\n}\n", "import { bech32 } from '@scure/base'\n\nimport { NostrEvent, validateEvent, verifyEvent, type Event, type EventTemplate } from './pure.ts'\nimport { utf8Decoder } from './utils.ts'\nimport { isReplaceableKind, isAddressableKind } from './kinds.ts'\n\nvar _fetch: any\n\ntry {\n _fetch = fetch\n} catch {}\n\nexport function useFetchImplementation(fetchImplementation: any) {\n _fetch = fetchImplementation\n}\n\nexport async function getZapEndpoint(metadata: Event): Promise {\n try {\n let lnurl: string = ''\n let { lud06, lud16 } = JSON.parse(metadata.content)\n if (lud06) {\n let { words } = bech32.decode(lud06, 1000)\n let data = bech32.fromWords(words)\n lnurl = utf8Decoder.decode(data)\n } else if (lud16) {\n let [name, domain] = lud16.split('@')\n lnurl = new URL(`/.well-known/lnurlp/${name}`, `https://${domain}`).toString()\n } else {\n return null\n }\n\n let res = await _fetch(lnurl)\n let body = await res.json()\n\n if (body.allowsNostr && body.nostrPubkey) {\n return body.callback\n }\n } catch (err) {\n /*-*/\n }\n\n return null\n}\n\ntype ProfileZap = {\n pubkey: string\n amount: number\n comment?: string\n relays: string[]\n}\n\ntype EventZap = {\n event: NostrEvent\n amount: number\n comment?: string\n relays: string[]\n}\n\nexport function makeZapRequest(params: ProfileZap | EventZap): EventTemplate {\n let zr: EventTemplate = {\n kind: 9734,\n created_at: Math.round(Date.now() / 1000),\n content: params.comment || '',\n tags: [\n ['p', 'pubkey' in params ? params.pubkey : params.event.pubkey],\n ['amount', params.amount.toString()],\n ['relays', ...params.relays],\n ],\n }\n\n if ('event' in params) {\n zr.tags.push(['e', params.event.id])\n if (isReplaceableKind(params.event.kind)) {\n const a = ['a', `${params.event.kind}:${params.event.pubkey}:`]\n zr.tags.push(a)\n } else if (isAddressableKind(params.event.kind)) {\n let d = params.event.tags.find(([t, v]) => t === 'd' && v)\n if (!d) throw new Error('d tag not found or is empty')\n const a = ['a', `${params.event.kind}:${params.event.pubkey}:${d[1]}`]\n zr.tags.push(a)\n }\n zr.tags.push(['k', params.event.kind.toString()])\n }\n\n return zr\n}\n\nexport function validateZapRequest(zapRequestString: string): string | null {\n let zapRequest: Event\n\n try {\n zapRequest = JSON.parse(zapRequestString)\n } catch (err) {\n return 'Invalid zap request JSON.'\n }\n\n if (!validateEvent(zapRequest)) return 'Zap request is not a valid Nostr event.'\n\n if (!verifyEvent(zapRequest)) return 'Invalid signature on zap request.'\n\n let p = zapRequest.tags.find(([t, v]) => t === 'p' && v)\n if (!p) return \"Zap request doesn't have a 'p' tag.\"\n if (!p[1].match(/^[a-f0-9]{64}$/)) return \"Zap request 'p' tag is not valid hex.\"\n\n let e = zapRequest.tags.find(([t, v]) => t === 'e' && v)\n if (e && !e[1].match(/^[a-f0-9]{64}$/)) return \"Zap request 'e' tag is not valid hex.\"\n\n let relays = zapRequest.tags.find(([t, v]) => t === 'relays' && v)\n if (!relays) return \"Zap request doesn't have a 'relays' tag.\"\n\n return null\n}\n\nexport function makeZapReceipt({\n zapRequest,\n preimage,\n bolt11,\n paidAt,\n}: {\n zapRequest: string\n preimage?: string\n bolt11: string\n paidAt: Date\n}): EventTemplate {\n let zr: Event = JSON.parse(zapRequest)\n let tagsFromZapRequest = zr.tags.filter(([t]) => t === 'e' || t === 'p' || t === 'a')\n\n let zap: EventTemplate = {\n kind: 9735,\n created_at: Math.round(paidAt.getTime() / 1000),\n content: '',\n tags: [...tagsFromZapRequest, ['P', zr.pubkey], ['bolt11', bolt11], ['description', zapRequest]],\n }\n\n if (preimage) {\n zap.tags.push(['preimage', preimage])\n }\n\n return zap\n}\n\nexport function getSatoshisAmountFromBolt11(bolt11: string): number {\n if (bolt11.length < 50) {\n return 0\n }\n bolt11 = bolt11.substring(0, 50)\n const idx = bolt11.lastIndexOf('1')\n if (idx === -1) {\n return 0\n }\n const hrp = bolt11.substring(0, idx)\n if (!hrp.startsWith('lnbc')) {\n return 0\n }\n const amount = hrp.substring(4) // equivalent to strings.CutPrefix\n\n if (amount.length < 1) {\n return 0\n }\n\n // if last character is a digit, then the amount can just be interpreted as BTC\n const char = amount[amount.length - 1]\n const digit = char.charCodeAt(0) - '0'.charCodeAt(0)\n const isDigit = digit >= 0 && digit <= 9\n\n let cutPoint = amount.length - 1\n if (isDigit) {\n cutPoint++\n }\n\n if (cutPoint < 1) {\n return 0\n }\n\n const num = parseInt(amount.substring(0, cutPoint))\n\n switch (char) {\n case 'm':\n return num * 100000\n case 'u':\n return num * 100\n case 'n':\n return num / 10\n case 'p':\n return num / 10000\n default:\n return num * 100000000\n }\n}\n", "import { sha256 } from '@noble/hashes/sha256'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { base64 } from '@scure/base'\n\nimport { HTTPAuth } from './kinds.ts'\nimport { Event, EventTemplate, verifyEvent } from './pure.ts'\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nconst _authorizationScheme = 'Nostr '\n\n/**\n * Generate token for NIP-98 flow.\n *\n * @example\n * const sign = window.nostr.signEvent\n * await nip98.getToken('https://example.com/login', 'post', (e) => sign(e), true)\n */\nexport async function getToken(\n loginUrl: string,\n httpMethod: string,\n sign: (e: EventTemplate) => Promise | Event,\n includeAuthorizationScheme: boolean = false,\n payload?: Record,\n): Promise {\n const event: EventTemplate = {\n kind: HTTPAuth,\n tags: [\n ['u', loginUrl],\n ['method', httpMethod],\n ],\n created_at: Math.round(new Date().getTime() / 1000),\n content: '',\n }\n\n if (payload) {\n event.tags.push(['payload', hashPayload(payload)])\n }\n\n const signedEvent = await sign(event)\n const authorizationScheme = includeAuthorizationScheme ? _authorizationScheme : ''\n\n return authorizationScheme + base64.encode(utf8Encoder.encode(JSON.stringify(signedEvent)))\n}\n\n/**\n * Validate token for NIP-98 flow.\n *\n * @example\n * await nip98.validateToken('Nostr base64token', 'https://example.com/login', 'post')\n */\nexport async function validateToken(token: string, url: string, method: string): Promise {\n const event = await unpackEventFromToken(token).catch(error => {\n throw error\n })\n\n const valid = await validateEvent(event, url, method).catch(error => {\n throw error\n })\n\n return valid\n}\n\n/**\n * Unpacks an event from a token.\n *\n * @param token - The token to unpack.\n * @returns A promise that resolves to the unpacked event.\n * @throws {Error} If the token is missing, invalid, or cannot be parsed.\n */\nexport async function unpackEventFromToken(token: string): Promise {\n if (!token) {\n throw new Error('Missing token')\n }\n\n token = token.replace(_authorizationScheme, '')\n\n const eventB64 = utf8Decoder.decode(base64.decode(token))\n if (!eventB64 || eventB64.length === 0 || !eventB64.startsWith('{')) {\n throw new Error('Invalid token')\n }\n\n const event = JSON.parse(eventB64) as Event\n\n return event\n}\n\n/**\n * Validates the timestamp of an event.\n * @param event - The event object to validate.\n * @returns A boolean indicating whether the event timestamp is within the last 60 seconds.\n */\nexport function validateEventTimestamp(event: Event): boolean {\n if (!event.created_at) {\n return false\n }\n\n return Math.round(new Date().getTime() / 1000) - event.created_at < 60\n}\n\n/**\n * Validates the kind of an event.\n * @param event The event to validate.\n * @returns A boolean indicating whether the event kind is valid.\n */\nexport function validateEventKind(event: Event): boolean {\n return event.kind === HTTPAuth\n}\n\n/**\n * Validates if the given URL matches the URL tag of the event.\n * @param event - The event object.\n * @param url - The URL to validate.\n * @returns A boolean indicating whether the URL is valid or not.\n */\nexport function validateEventUrlTag(event: Event, url: string): boolean {\n const urlTag = event.tags.find(t => t[0] === 'u')\n\n if (!urlTag) {\n return false\n }\n\n return urlTag.length > 0 && urlTag[1] === url\n}\n\n/**\n * Validates if the given event has a method tag that matches the specified method.\n * @param event - The event to validate.\n * @param method - The method to match against the method tag.\n * @returns A boolean indicating whether the event has a matching method tag.\n */\nexport function validateEventMethodTag(event: Event, method: string): boolean {\n const methodTag = event.tags.find(t => t[0] === 'method')\n\n if (!methodTag) {\n return false\n }\n\n return methodTag.length > 0 && methodTag[1].toLowerCase() === method.toLowerCase()\n}\n\n/**\n * Calculates the hash of a payload.\n * @param payload - The payload to be hashed.\n * @returns The hash value as a string.\n */\nexport function hashPayload(payload: any): string {\n const hash = sha256(utf8Encoder.encode(JSON.stringify(payload)))\n return bytesToHex(hash)\n}\n\n/**\n * Validates the event payload tag against the provided payload.\n * @param event The event object.\n * @param payload The payload to validate.\n * @returns A boolean indicating whether the payload tag is valid.\n */\nexport function validateEventPayloadTag(event: Event, payload: any): boolean {\n const payloadTag = event.tags.find(t => t[0] === 'payload')\n\n if (!payloadTag) {\n return false\n }\n\n const payloadHash = hashPayload(payload)\n return payloadTag.length > 0 && payloadTag[1] === payloadHash\n}\n\n/**\n * Validates a Nostr event for the NIP-98 flow.\n *\n * @param event - The Nostr event to validate.\n * @param url - The URL associated with the event.\n * @param method - The HTTP method associated with the event.\n * @param body - The request body associated with the event (optional).\n * @returns A promise that resolves to a boolean indicating whether the event is valid.\n * @throws An error if the event is invalid.\n */\nexport async function validateEvent(event: Event, url: string, method: string, body?: any): Promise {\n if (!verifyEvent(event)) {\n throw new Error('Invalid nostr event, signature invalid')\n }\n\n if (!validateEventKind(event)) {\n throw new Error('Invalid nostr event, kind invalid')\n }\n\n if (!validateEventTimestamp(event)) {\n throw new Error('Invalid nostr event, created_at timestamp invalid')\n }\n\n if (!validateEventUrlTag(event, url)) {\n throw new Error('Invalid nostr event, url tag invalid')\n }\n\n if (!validateEventMethodTag(event, method)) {\n throw new Error('Invalid nostr event, method tag invalid')\n }\n\n if (Boolean(body) && typeof body === 'object' && Object.keys(body).length > 0) {\n if (!validateEventPayloadTag(event, body)) {\n throw new Error('Invalid nostr event, payload tag does not match request body hash')\n }\n }\n\n return true\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,uBAAwB;AACxB,IAAAA,gBAA2B;;;ACOpB,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,CAAC,QAAiD,eAAe;AAE3E,SAAS,cAAiB,OAAsC;AACrE,MAAI,CAAC,SAAS,KAAK;AAAG,WAAO;AAC7B,MAAI,OAAO,MAAM,SAAS;AAAU,WAAO;AAC3C,MAAI,OAAO,MAAM,YAAY;AAAU,WAAO;AAC9C,MAAI,OAAO,MAAM,eAAe;AAAU,WAAO;AACjD,MAAI,OAAO,MAAM,WAAW;AAAU,WAAO;AAC7C,MAAI,CAAC,MAAM,OAAO,MAAM,gBAAgB;AAAG,WAAO;AAElD,MAAI,CAAC,MAAM,QAAQ,MAAM,IAAI;AAAG,WAAO;AACvC,WAASC,KAAI,GAAGA,KAAI,MAAM,KAAK,QAAQA,MAAK;AAC1C,QAAI,MAAM,MAAM,KAA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CAAC,YAAY;AACf,WAAO;AAAA,EACT;AAEA,QAAM,cAAc,YAAY,OAAO;AACvC,SAAO,WAAW,SAAS,KAAK,WAAW,OAAO;AACpD;AAYA,eAAsBA,eAAc,OAAc,KAAa,QAAgB,MAA8B;AAC3G,MAAI,CAAC,YAAY,KAAK,GAAG;AACvB,UAAM,IAAI,MAAM,wCAAwC;AAAA,EAC1D;AAEA,MAAI,CAAC,kBAAkB,KAAK,GAAG;AAC7B,UAAM,IAAI,MAAM,mCAAmC;AAAA,EACrD;AAEA,MAAI,CAAC,uBAAuB,KAAK,GAAG;AAClC,UAAM,IAAI,MAAM,mDAAmD;AAAA,EACrE;AAEA,MAAI,CAAC,oBAAoB,OAAO,GAAG,GAAG;AACpC,UAAM,IAAI,MAAM,sCAAsC;AAAA,EACxD;AAEA,MAAI,CAAC,uBAAuB,OAAO,MAAM,GAAG;AAC1C,UAAM,IAAI,MAAM,yCAAyC;AAAA,EAC3D;AAEA,MAAI,QAAQ,IAAI,KAAK,OAAO,SAAS,YAAY,OAAO,KAAK,IAAI,EAAE,SAAS,GAAG;AAC7E,QAAI,CAAC,wBAAwB,OAAO,IAAI,GAAG;AACzC,YAAM,IAAI,MAAM,mEAAmE;AAAA,IACrF;AAAA,EACF;AAEA,SAAO;AACT;", + "names": ["import_utils", "i", "target", "Date", "Date", "i", "i", "reason", "_WebSocket", "_WebSocket", "import_utils", "import_utils", "import_secp256k1", "import_base", "i", "useFetchImplementation", "_fetch", "import_utils", "import_sha256", "i", "now", "unwrapEvent", "unwrapManyEvents", "wrapEvent", "wrapManyEvents", "decrypt", "encrypt", "import_utils", "import_secp256k1", "import_sha256", "import_base", "hkdf_extract", "hkdf_expand", "encrypt", "decrypt", "encrypt", "decrypt", "wrapEvent", "wrapManyEvents", "unwrapEvent", "unwrapManyEvents", "i", "parse", "parse", "i", "parse", "parse", "useFetchImplementation", "_fetch", "useFetchImplementation", "import_base", "_fetch", "useFetchImplementation", "validateEvent", "import_sha256", "import_utils", "import_base", "validateEvent"] +} diff --git a/node_modules/nostr-tools/lib/cjs/kinds.js b/node_modules/nostr-tools/lib/cjs/kinds.js new file mode 100644 index 0000000..dc57571 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/kinds.js @@ -0,0 +1,243 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// kinds.ts +var kinds_exports = {}; +__export(kinds_exports, { + Application: () => Application, + BadgeAward: () => BadgeAward, + BadgeDefinition: () => BadgeDefinition, + BlockedRelaysList: () => BlockedRelaysList, + BookmarkList: () => BookmarkList, + Bookmarksets: () => Bookmarksets, + Calendar: () => Calendar, + CalendarEventRSVP: () => CalendarEventRSVP, + ChannelCreation: () => ChannelCreation, + ChannelHideMessage: () => ChannelHideMessage, + ChannelMessage: () => ChannelMessage, + ChannelMetadata: () => ChannelMetadata, + ChannelMuteUser: () => ChannelMuteUser, + ClassifiedListing: () => ClassifiedListing, + ClientAuth: () => ClientAuth, + CommunitiesList: () => CommunitiesList, + CommunityDefinition: () => CommunityDefinition, + CommunityPostApproval: () => CommunityPostApproval, + Contacts: () => Contacts, + CreateOrUpdateProduct: () => CreateOrUpdateProduct, + CreateOrUpdateStall: () => CreateOrUpdateStall, + Curationsets: () => Curationsets, + Date: () => Date, + DirectMessageRelaysList: () => DirectMessageRelaysList, + DraftClassifiedListing: () => DraftClassifiedListing, + DraftLong: () => DraftLong, + Emojisets: () => Emojisets, + EncryptedDirectMessage: () => EncryptedDirectMessage, + EventDeletion: () => EventDeletion, + FileMetadata: () => FileMetadata, + FileServerPreference: () => FileServerPreference, + Followsets: () => Followsets, + GenericRepost: () => GenericRepost, + Genericlists: () => Genericlists, + GiftWrap: () => GiftWrap, + HTTPAuth: () => HTTPAuth, + Handlerinformation: () => Handlerinformation, + Handlerrecommendation: () => Handlerrecommendation, + Highlights: () => Highlights, + InterestsList: () => InterestsList, + Interestsets: () => Interestsets, + JobFeedback: () => JobFeedback, + JobRequest: () => JobRequest, + JobResult: () => JobResult, + Label: () => Label, + LightningPubRPC: () => LightningPubRPC, + LiveChatMessage: () => LiveChatMessage, + LiveEvent: () => LiveEvent, + LongFormArticle: () => LongFormArticle, + Metadata: () => Metadata, + Mutelist: () => Mutelist, + NWCWalletInfo: () => NWCWalletInfo, + NWCWalletRequest: () => NWCWalletRequest, + NWCWalletResponse: () => NWCWalletResponse, + NostrConnect: () => NostrConnect, + OpenTimestamps: () => OpenTimestamps, + Pinlist: () => Pinlist, + PrivateDirectMessage: () => PrivateDirectMessage, + ProblemTracker: () => ProblemTracker, + ProfileBadges: () => ProfileBadges, + PublicChatsList: () => PublicChatsList, + Reaction: () => Reaction, + RecommendRelay: () => RecommendRelay, + RelayList: () => RelayList, + Relaysets: () => Relaysets, + Report: () => Report, + Reporting: () => Reporting, + Repost: () => Repost, + Seal: () => Seal, + SearchRelaysList: () => SearchRelaysList, + ShortTextNote: () => ShortTextNote, + Time: () => Time, + UserEmojiList: () => UserEmojiList, + UserStatuses: () => UserStatuses, + Zap: () => Zap, + ZapGoal: () => ZapGoal, + ZapRequest: () => ZapRequest, + classifyKind: () => classifyKind, + isAddressableKind: () => isAddressableKind, + isEphemeralKind: () => isEphemeralKind, + isKind: () => isKind, + isRegularKind: () => isRegularKind, + isReplaceableKind: () => isReplaceableKind +}); +module.exports = __toCommonJS(kinds_exports); + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i = 0; i < event.tags.length; i++) { + let tag = event.tags[i]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// kinds.ts +function isRegularKind(kind) { + return 1e3 <= kind && kind < 1e4 || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind); +} +function isReplaceableKind(kind) { + return [0, 3].includes(kind) || 1e4 <= kind && kind < 2e4; +} +function isEphemeralKind(kind) { + return 2e4 <= kind && kind < 3e4; +} +function isAddressableKind(kind) { + return 3e4 <= kind && kind < 4e4; +} +function classifyKind(kind) { + if (isRegularKind(kind)) + return "regular"; + if (isReplaceableKind(kind)) + return "replaceable"; + if (isEphemeralKind(kind)) + return "ephemeral"; + if (isAddressableKind(kind)) + return "parameterized"; + return "unknown"; +} +function isKind(event, kind) { + const kindAsArray = kind instanceof Array ? kind : [kind]; + return validateEvent(event) && kindAsArray.includes(event.kind) || false; +} +var Metadata = 0; +var ShortTextNote = 1; +var RecommendRelay = 2; +var Contacts = 3; +var EncryptedDirectMessage = 4; +var EventDeletion = 5; +var Repost = 6; +var Reaction = 7; +var BadgeAward = 8; +var Seal = 13; +var PrivateDirectMessage = 14; +var GenericRepost = 16; +var ChannelCreation = 40; +var ChannelMetadata = 41; +var ChannelMessage = 42; +var ChannelHideMessage = 43; +var ChannelMuteUser = 44; +var OpenTimestamps = 1040; +var GiftWrap = 1059; +var FileMetadata = 1063; +var LiveChatMessage = 1311; +var ProblemTracker = 1971; +var Report = 1984; +var Reporting = 1984; +var Label = 1985; +var CommunityPostApproval = 4550; +var JobRequest = 5999; +var JobResult = 6999; +var JobFeedback = 7e3; +var ZapGoal = 9041; +var ZapRequest = 9734; +var Zap = 9735; +var Highlights = 9802; +var Mutelist = 1e4; +var Pinlist = 10001; +var RelayList = 10002; +var BookmarkList = 10003; +var CommunitiesList = 10004; +var PublicChatsList = 10005; +var BlockedRelaysList = 10006; +var SearchRelaysList = 10007; +var InterestsList = 10015; +var UserEmojiList = 10030; +var DirectMessageRelaysList = 10050; +var FileServerPreference = 10096; +var NWCWalletInfo = 13194; +var LightningPubRPC = 21e3; +var ClientAuth = 22242; +var NWCWalletRequest = 23194; +var NWCWalletResponse = 23195; +var NostrConnect = 24133; +var HTTPAuth = 27235; +var Followsets = 3e4; +var Genericlists = 30001; +var Relaysets = 30002; +var Bookmarksets = 30003; +var Curationsets = 30004; +var ProfileBadges = 30008; +var BadgeDefinition = 30009; +var Interestsets = 30015; +var CreateOrUpdateStall = 30017; +var CreateOrUpdateProduct = 30018; +var LongFormArticle = 30023; +var DraftLong = 30024; +var Emojisets = 30030; +var Application = 30078; +var LiveEvent = 30311; +var UserStatuses = 30315; +var ClassifiedListing = 30402; +var DraftClassifiedListing = 30403; +var Date = 31922; +var Time = 31923; +var Calendar = 31924; +var CalendarEventRSVP = 31925; +var Handlerrecommendation = 31989; +var Handlerinformation = 31990; +var CommunityDefinition = 34550; diff --git a/node_modules/nostr-tools/lib/cjs/kinds.js.map b/node_modules/nostr-tools/lib/cjs/kinds.js.map new file mode 100644 index 0000000..c33dd86 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/kinds.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../kinds.ts", "../../core.ts"], + "sourcesContent": ["import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACQO,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,CAAC,QAAiD,eAAe;AAE3E,SAAS,cAAiB,OAAsC;AACrE,MAAI,CAAC,SAAS,KAAK;AAAG,WAAO;AAC7B,MAAI,OAAO,MAAM,SAAS;AAAU,WAAO;AAC3C,MAAI,OAAO,MAAM,YAAY;AAAU,WAAO;AAC9C,MAAI,OAAO,MAAM,eAAe;AAAU,WAAO;AACjD,MAAI,OAAO,MAAM,WAAW;AAAU,WAAO;AAC7C,MAAI,CAAC,MAAM,OAAO,MAAM,gBAAgB;AAAG,WAAO;AAElD,MAAI,CAAC,MAAM,QAAQ,MAAM,IAA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Eb,IAAM,OAAO;AAEb,IAAM,WAAW;AAEjB,IAAM,oBAAoB;AAE1B,IAAM,wBAAwB;AAE9B,IAAM,qBAAqB;AAE3B,IAAM,sBAAsB;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip04.js b/node_modules/nostr-tools/lib/cjs/nip04.js new file mode 100644 index 0000000..432bb49 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip04.js @@ -0,0 +1,61 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip04.ts +var nip04_exports = {}; +__export(nip04_exports, { + decrypt: () => decrypt, + encrypt: () => encrypt +}); +module.exports = __toCommonJS(nip04_exports); +var import_utils2 = require("@noble/hashes/utils"); +var import_secp256k1 = require("@noble/curves/secp256k1"); +var import_aes = require("@noble/ciphers/aes"); +var import_base = require("@scure/base"); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// nip04.ts +function encrypt(secretKey, pubkey, text) { + const privkey = secretKey instanceof Uint8Array ? (0, import_utils2.bytesToHex)(secretKey) : secretKey; + const key = import_secp256k1.secp256k1.getSharedSecret(privkey, "02" + pubkey); + const normalizedKey = getNormalizedX(key); + let iv = Uint8Array.from((0, import_utils2.randomBytes)(16)); + let plaintext = utf8Encoder.encode(text); + let ciphertext = (0, import_aes.cbc)(normalizedKey, iv).encrypt(plaintext); + let ctb64 = import_base.base64.encode(new Uint8Array(ciphertext)); + let ivb64 = import_base.base64.encode(new Uint8Array(iv.buffer)); + return `${ctb64}?iv=${ivb64}`; +} +function decrypt(secretKey, pubkey, data) { + const privkey = secretKey instanceof Uint8Array ? (0, import_utils2.bytesToHex)(secretKey) : secretKey; + let [ctb64, ivb64] = data.split("?iv="); + let key = import_secp256k1.secp256k1.getSharedSecret(privkey, "02" + pubkey); + let normalizedKey = getNormalizedX(key); + let iv = import_base.base64.decode(ivb64); + let ciphertext = import_base.base64.decode(ctb64); + let plaintext = (0, import_aes.cbc)(normalizedKey, iv).decrypt(ciphertext); + return utf8Decoder.decode(plaintext); +} +function getNormalizedX(key) { + return key.slice(1, 33); +} diff --git a/node_modules/nostr-tools/lib/cjs/nip04.js.map b/node_modules/nostr-tools/lib/cjs/nip04.js.map new file mode 100644 index 0000000..cc37bd9 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip04.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip04.ts", "../../utils.ts"], + "sourcesContent": ["import { bytesToHex, randomBytes } from '@noble/hashes/utils'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { cbc } from '@noble/ciphers/aes'\nimport { base64 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport function encrypt(secretKey: string | Uint8Array, pubkey: string, text: string): string {\n const privkey: string = secretKey instanceof Uint8Array ? bytesToHex(secretKey) : secretKey\n const key = secp256k1.getSharedSecret(privkey, '02' + pubkey)\n const normalizedKey = getNormalizedX(key)\n\n let iv = Uint8Array.from(randomBytes(16))\n let plaintext = utf8Encoder.encode(text)\n\n let ciphertext = cbc(normalizedKey, iv).encrypt(plaintext)\n\n let ctb64 = base64.encode(new Uint8Array(ciphertext))\n let ivb64 = base64.encode(new Uint8Array(iv.buffer))\n\n return `${ctb64}?iv=${ivb64}`\n}\n\nexport function decrypt(secretKey: string | Uint8Array, pubkey: string, data: string): string {\n const privkey: string = secretKey instanceof Uint8Array ? bytesToHex(secretKey) : secretKey\n let [ctb64, ivb64] = data.split('?iv=')\n let key = secp256k1.getSharedSecret(privkey, '02' + pubkey)\n let normalizedKey = getNormalizedX(key)\n\n let iv = base64.decode(ivb64)\n let ciphertext = base64.decode(ctb64)\n\n let plaintext = cbc(normalizedKey, iv).decrypt(ciphertext)\n\n return utf8Decoder.decode(plaintext)\n}\n\nfunction getNormalizedX(key: Uint8Array): Uint8Array {\n return key.slice(1, 33)\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,gBAAwC;AACxC,uBAA0B;AAC1B,iBAAoB;AACpB,kBAAuB;;;ACEvB,mBAAuC;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;;;ADIjD,SAAS,QAAQ,WAAgC,QAAgB,MAAsB;AAC5F,QAAM,UAAkB,qBAAqB,iBAAa,0BAAW,SAAS,IAAI;AAClF,QAAM,MAAM,2BAAU,gBAAgB,SAAS,OAAO,MAAM;AAC5D,QAAM,gBAAgB,eAAe,GAAG;AAExC,MAAI,KAAK,WAAW,SAAK,2BAAY,EAAE,CAAC;AACxC,MAAI,YAAY,YAAY,OAAO,IAAI;AAEvC,MAAI,iBAAa,gBAAI,eAAe,EAAE,EAAE,QAAQ,SAAS;AAEzD,MAAI,QAAQ,mBAAO,OAAO,IAAI,WAAW,UAAU,CAAC;AACpD,MAAI,QAAQ,mBAAO,OAAO,IAAI,WAAW,GAAG,MAAM,CAAC;AAEnD,SAAO,GAAG,YAAY;AACxB;AAEO,SAAS,QAAQ,WAAgC,QAAgB,MAAsB;AAC5F,QAAM,UAAkB,qBAAqB,iBAAa,0BAAW,SAAS,IAAI;AAClF,MAAI,CAAC,OAAO,KAAK,IAAI,KAAK,MAAM,MAAM;AACtC,MAAI,MAAM,2BAAU,gBAAgB,SAAS,OAAO,MAAM;AAC1D,MAAI,gBAAgB,eAAe,GAAG;AAEtC,MAAI,KAAK,mBAAO,OAAO,KAAK;AAC5B,MAAI,aAAa,mBAAO,OAAO,KAAK;AAEpC,MAAI,gBAAY,gBAAI,eAAe,EAAE,EAAE,QAAQ,UAAU;AAEzD,SAAO,YAAY,OAAO,SAAS;AACrC;AAEA,SAAS,eAAe,KAA6B;AACnD,SAAO,IAAI,MAAM,GAAG,EAAE;AACxB;", + "names": ["import_utils"] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip05.js b/node_modules/nostr-tools/lib/cjs/nip05.js new file mode 100644 index 0000000..dd909df --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip05.js @@ -0,0 +1,76 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip05.ts +var nip05_exports = {}; +__export(nip05_exports, { + NIP05_REGEX: () => NIP05_REGEX, + isNip05: () => isNip05, + isValid: () => isValid, + queryProfile: () => queryProfile, + searchDomain: () => searchDomain, + useFetchImplementation: () => useFetchImplementation +}); +module.exports = __toCommonJS(nip05_exports); +var NIP05_REGEX = /^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/; +var isNip05 = (value) => NIP05_REGEX.test(value || ""); +var _fetch; +try { + _fetch = fetch; +} catch (_) { + null; +} +function useFetchImplementation(fetchImplementation) { + _fetch = fetchImplementation; +} +async function searchDomain(domain, query = "") { + try { + const url = `https://${domain}/.well-known/nostr.json?name=${query}`; + const res = await _fetch(url, { redirect: "manual" }); + if (res.status !== 200) { + throw Error("Wrong response code"); + } + const json = await res.json(); + return json.names; + } catch (_) { + return {}; + } +} +async function queryProfile(fullname) { + const match = fullname.match(NIP05_REGEX); + if (!match) + return null; + const [, name = "_", domain] = match; + try { + const url = `https://${domain}/.well-known/nostr.json?name=${name}`; + const res = await _fetch(url, { redirect: "manual" }); + if (res.status !== 200) { + throw Error("Wrong response code"); + } + const json = await res.json(); + const pubkey = json.names[name]; + return pubkey ? { pubkey, relays: json.relays?.[pubkey] } : null; + } catch (_e) { + return null; + } +} +async function isValid(pubkey, nip05) { + const res = await queryProfile(nip05); + return res ? res.pubkey === pubkey : false; +} diff --git a/node_modules/nostr-tools/lib/cjs/nip05.js.map b/node_modules/nostr-tools/lib/cjs/nip05.js.map new file mode 100644 index 0000000..1ee2393 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip05.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip05.ts"], + "sourcesContent": ["import { ProfilePointer } from './nip19.ts'\n\nexport type Nip05 = `${string}@${string}`\n\n/**\n * NIP-05 regex. The localpart is optional, and should be assumed to be `_` otherwise.\n *\n * - 0: full match\n * - 1: name (optional)\n * - 2: domain\n */\nexport const NIP05_REGEX = /^(?:([\\w.+-]+)@)?([\\w_-]+(\\.[\\w_-]+)+)$/\nexport const isNip05 = (value?: string | null): value is Nip05 => NIP05_REGEX.test(value || '')\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _fetch: any\n\ntry {\n _fetch = fetch\n} catch (_) {\n null\n}\n\nexport function useFetchImplementation(fetchImplementation: unknown) {\n _fetch = fetchImplementation\n}\n\nexport async function searchDomain(domain: string, query = ''): Promise<{ [name: string]: string }> {\n try {\n const url = `https://${domain}/.well-known/nostr.json?name=${query}`\n const res = await _fetch(url, { redirect: 'manual' })\n if (res.status !== 200) {\n throw Error('Wrong response code')\n }\n const json = await res.json()\n return json.names\n } catch (_) {\n return {}\n }\n}\n\nexport async function queryProfile(fullname: string): Promise {\n const match = fullname.match(NIP05_REGEX)\n if (!match) return null\n\n const [, name = '_', domain] = match\n\n try {\n const url = `https://${domain}/.well-known/nostr.json?name=${name}`\n const res = await _fetch(url, { redirect: 'manual' })\n if (res.status !== 200) {\n throw Error('Wrong response code')\n }\n const json = await res.json()\n\n const pubkey = json.names[name]\n return pubkey ? { pubkey, relays: json.relays?.[pubkey] } : null\n } catch (_e) {\n return null\n }\n}\n\nexport async function isValid(pubkey: string, nip05: Nip05): Promise {\n const res = await queryProfile(nip05)\n return res ? res.pubkey === pubkey : false\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWO,IAAM,cAAc;AACpB,IAAM,UAAU,CAAC,UAA0C,YAAY,KAAK,SAAS,EAAE;AAG9F,IAAI;AAEJ,IAAI;AACF,WAAS;AACX,SAAS,GAAP;AACA;AACF;AAEO,SAAS,uBAAuB,qBAA8B;AACnE,WAAS;AACX;AAEA,eAAsB,aAAa,QAAgB,QAAQ,IAAyC;AAClG,MAAI;AACF,UAAM,MAAM,WAAW,sCAAsC;AAC7D,UAAM,MAAM,MAAM,OAAO,KAAK,EAAE,UAAU,SAAS,CAAC;AACpD,QAAI,IAAI,WAAW,KAAK;AACtB,YAAM,MAAM,qBAAqB;AAAA,IACnC;AACA,UAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,WAAO,KAAK;AAAA,EACd,SAAS,GAAP;AACA,WAAO,CAAC;AAAA,EACV;AACF;AAEA,eAAsB,aAAa,UAAkD;AACnF,QAAM,QAAQ,SAAS,MAAM,WAAW;AACxC,MAAI,CAAC;AAAO,WAAO;AAEnB,QAAM,CAAC,EAAE,OAAO,KAAK,MAAM,IAAI;AAE/B,MAAI;AACF,UAAM,MAAM,WAAW,sCAAsC;AAC7D,UAAM,MAAM,MAAM,OAAO,KAAK,EAAE,UAAU,SAAS,CAAC;AACpD,QAAI,IAAI,WAAW,KAAK;AACtB,YAAM,MAAM,qBAAqB;AAAA,IACnC;AACA,UAAM,OAAO,MAAM,IAAI,KAAK;AAE5B,UAAM,SAAS,KAAK,MAAM;AAC1B,WAAO,SAAS,EAAE,QAAQ,QAAQ,KAAK,SAAS,QAAQ,IAAI;AAAA,EAC9D,SAAS,IAAP;AACA,WAAO;AAAA,EACT;AACF;AAEA,eAAsB,QAAQ,QAAgB,OAAgC;AAC5E,QAAM,MAAM,MAAM,aAAa,KAAK;AACpC,SAAO,MAAM,IAAI,WAAW,SAAS;AACvC;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip06.js b/node_modules/nostr-tools/lib/cjs/nip06.js new file mode 100644 index 0000000..917d582 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip06.js @@ -0,0 +1,82 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip06.ts +var nip06_exports = {}; +__export(nip06_exports, { + accountFromExtendedKey: () => accountFromExtendedKey, + accountFromSeedWords: () => accountFromSeedWords, + extendedKeysFromSeedWords: () => extendedKeysFromSeedWords, + generateSeedWords: () => generateSeedWords, + privateKeyFromSeedWords: () => privateKeyFromSeedWords, + validateWords: () => validateWords +}); +module.exports = __toCommonJS(nip06_exports); +var import_utils = require("@noble/hashes/utils"); +var import_english = require("@scure/bip39/wordlists/english"); +var import_bip39 = require("@scure/bip39"); +var import_bip32 = require("@scure/bip32"); +var DERIVATION_PATH = `m/44'/1237'`; +function privateKeyFromSeedWords(mnemonic, passphrase, accountIndex = 0) { + let root = import_bip32.HDKey.fromMasterSeed((0, import_bip39.mnemonicToSeedSync)(mnemonic, passphrase)); + let privateKey = root.derive(`${DERIVATION_PATH}/${accountIndex}'/0/0`).privateKey; + if (!privateKey) + throw new Error("could not derive private key"); + return privateKey; +} +function accountFromSeedWords(mnemonic, passphrase, accountIndex = 0) { + const root = import_bip32.HDKey.fromMasterSeed((0, import_bip39.mnemonicToSeedSync)(mnemonic, passphrase)); + const seed = root.derive(`${DERIVATION_PATH}/${accountIndex}'/0/0`); + const publicKey = (0, import_utils.bytesToHex)(seed.publicKey.slice(1)); + const privateKey = seed.privateKey; + if (!privateKey || !publicKey) { + throw new Error("could not derive key pair"); + } + return { privateKey, publicKey }; +} +function extendedKeysFromSeedWords(mnemonic, passphrase, extendedAccountIndex = 0) { + let root = import_bip32.HDKey.fromMasterSeed((0, import_bip39.mnemonicToSeedSync)(mnemonic, passphrase)); + let seed = root.derive(`${DERIVATION_PATH}/${extendedAccountIndex}'`); + let privateExtendedKey = seed.privateExtendedKey; + let publicExtendedKey = seed.publicExtendedKey; + if (!privateExtendedKey && !publicExtendedKey) + throw new Error("could not derive extended key pair"); + return { privateExtendedKey, publicExtendedKey }; +} +function accountFromExtendedKey(base58key, accountIndex = 0) { + let extendedKey = import_bip32.HDKey.fromExtendedKey(base58key); + let version = base58key.slice(0, 4); + let child = extendedKey.deriveChild(0).deriveChild(accountIndex); + let publicKey = (0, import_utils.bytesToHex)(child.publicKey.slice(1)); + if (!publicKey) + throw new Error("could not derive public key"); + if (version === "xprv") { + let privateKey = child.privateKey; + if (!privateKey) + throw new Error("could not derive private key"); + return { privateKey, publicKey }; + } + return { publicKey }; +} +function generateSeedWords() { + return (0, import_bip39.generateMnemonic)(import_english.wordlist); +} +function validateWords(words) { + return (0, import_bip39.validateMnemonic)(words, import_english.wordlist); +} diff --git a/node_modules/nostr-tools/lib/cjs/nip06.js.map b/node_modules/nostr-tools/lib/cjs/nip06.js.map new file mode 100644 index 0000000..f81a30b --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip06.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip06.ts"], + "sourcesContent": ["import { bytesToHex } from '@noble/hashes/utils'\nimport { wordlist } from '@scure/bip39/wordlists/english'\nimport { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39'\nimport { HDKey } from '@scure/bip32'\n\nconst DERIVATION_PATH = `m/44'/1237'`\n\nexport function privateKeyFromSeedWords(mnemonic: string, passphrase?: string, accountIndex = 0): Uint8Array {\n let root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase))\n let privateKey = root.derive(`${DERIVATION_PATH}/${accountIndex}'/0/0`).privateKey\n if (!privateKey) throw new Error('could not derive private key')\n return privateKey\n}\n\nexport function accountFromSeedWords(\n mnemonic: string,\n passphrase?: string,\n accountIndex = 0,\n): {\n privateKey: Uint8Array\n publicKey: string\n} {\n const root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase))\n const seed = root.derive(`${DERIVATION_PATH}/${accountIndex}'/0/0`)\n const publicKey = bytesToHex(seed.publicKey!.slice(1))\n const privateKey = seed.privateKey\n if (!privateKey || !publicKey) {\n throw new Error('could not derive key pair')\n }\n return { privateKey, publicKey }\n}\n\nexport function extendedKeysFromSeedWords(\n mnemonic: string,\n passphrase?: string,\n extendedAccountIndex = 0,\n): {\n privateExtendedKey: string\n publicExtendedKey: string\n} {\n let root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase))\n let seed = root.derive(`${DERIVATION_PATH}/${extendedAccountIndex}'`)\n let privateExtendedKey = seed.privateExtendedKey\n let publicExtendedKey = seed.publicExtendedKey\n if (!privateExtendedKey && !publicExtendedKey) throw new Error('could not derive extended key pair')\n return { privateExtendedKey, publicExtendedKey }\n}\n\nexport function accountFromExtendedKey(\n base58key: string,\n accountIndex = 0,\n): {\n privateKey?: Uint8Array\n publicKey: string\n} {\n let extendedKey = HDKey.fromExtendedKey(base58key)\n let version = base58key.slice(0, 4)\n let child = extendedKey.deriveChild(0).deriveChild(accountIndex)\n let publicKey = bytesToHex(child.publicKey!.slice(1))\n if (!publicKey) throw new Error('could not derive public key')\n if (version === 'xprv') {\n let privateKey = child.privateKey!\n if (!privateKey) throw new Error('could not derive private key')\n return { privateKey, publicKey }\n }\n return { publicKey }\n}\n\nexport function generateSeedWords(): string {\n return generateMnemonic(wordlist)\n}\n\nexport function validateWords(words: string): boolean {\n return validateMnemonic(words, wordlist)\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAA2B;AAC3B,qBAAyB;AACzB,mBAAuE;AACvE,mBAAsB;AAEtB,IAAM,kBAAkB;AAEjB,SAAS,wBAAwB,UAAkB,YAAqB,eAAe,GAAe;AAC3G,MAAI,OAAO,mBAAM,mBAAe,iCAAmB,UAAU,UAAU,CAAC;AACxE,MAAI,aAAa,KAAK,OAAO,GAAG,mBAAmB,mBAAmB,EAAE;AACxE,MAAI,CA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EO,SAAS,cAAc,OAAwB;AACpD,aAAO,+BAAiB,OAAO,uBAAQ;AACzC;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip07.js b/node_modules/nostr-tools/lib/cjs/nip07.js new file mode 100644 index 0000000..76295ae --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip07.js @@ -0,0 +1,18 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip07.ts +var nip07_exports = {}; +module.exports = __toCommonJS(nip07_exports); diff --git a/node_modules/nostr-tools/lib/cjs/nip07.js.map b/node_modules/nostr-tools/lib/cjs/nip07.js.map new file mode 100644 index 0000000..79f620f --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip07.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip07.ts"], + "sourcesContent": ["import { EventTemplate, VerifiedEvent } from './core.ts'\n\nexport interface WindowNostr {\n getPublicKey(): Promise\n signEvent(event: EventTemplate): Promise\n nip04?: {\n encrypt(pubkey: string, plaintext: string): Promise\n decrypt(pubkey: string, ciphertext: string): Promise\n }\n nip44?: {\n encrypt(pubkey: string, plaintext: string): Promise\n decrypt(pubkey: string, ciphertext: string): Promise\n }\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;AAAA;AAAA;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip10.js b/node_modules/nostr-tools/lib/cjs/nip10.js new file mode 100644 index 0000000..4e8f5a1 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip10.js @@ -0,0 +1,124 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip10.ts +var nip10_exports = {}; +__export(nip10_exports, { + parse: () => parse +}); +module.exports = __toCommonJS(nip10_exports); +function parse(event) { + const result = { + reply: void 0, + root: void 0, + mentions: [], + profiles: [], + quotes: [] + }; + let maybeParent; + let maybeRoot; + for (let i = event.tags.length - 1; i >= 0; i--) { + const tag = event.tags[i]; + if (tag[0] === "e" && tag[1]) { + const [_, eTagEventId, eTagRelayUrl, eTagMarker, eTagAuthor] = tag; + const eventPointer = { + id: eTagEventId, + relays: eTagRelayUrl ? [eTagRelayUrl] : [], + author: eTagAuthor + }; + if (eTagMarker === "root") { + result.root = eventPointer; + continue; + } + if (eTagMarker === "reply") { + result.reply = eventPointer; + continue; + } + if (eTagMarker === "mention") { + result.mentions.push(eventPointer); + continue; + } + if (!maybeParent) { + maybeParent = eventPointer; + } else { + maybeRoot = eventPointer; + } + result.mentions.push(eventPointer); + continue; + } + if (tag[0] === "q" && tag[1]) { + const [_, eTagEventId, eTagRelayUrl] = tag; + result.quotes.push({ + id: eTagEventId, + relays: eTagRelayUrl ? [eTagRelayUrl] : [] + }); + } + if (tag[0] === "p" && tag[1]) { + result.profiles.push({ + pubkey: tag[1], + relays: tag[2] ? [tag[2]] : [] + }); + continue; + } + } + if (!result.root) { + result.root = maybeRoot || maybeParent || result.reply; + } + if (!result.reply) { + result.reply = maybeParent || result.root; + } + ; + [result.reply, result.root].forEach((ref) => { + if (!ref) + return; + let idx = result.mentions.indexOf(ref); + if (idx !== -1) { + result.mentions.splice(idx, 1); + } + if (ref.author) { + let author = result.profiles.find((p) => p.pubkey === ref.author); + if (author && author.relays) { + if (!ref.relays) { + ref.relays = []; + } + author.relays.forEach((url) => { + if (ref.relays?.indexOf(url) === -1) + ref.relays.push(url); + }); + author.relays = ref.relays; + } + } + }); + result.mentions.forEach((ref) => { + if (ref.author) { + let author = result.profiles.find((p) => p.pubkey === ref.author); + if (author && author.relays) { + if (!ref.relays) { + ref.relays = []; + } + author.relays.forEach((url) => { + if (ref.relays.indexOf(url) === -1) + ref.relays.push(url); + }); + author.relays = ref.relays; + } + } + }); + return result; +} diff --git a/node_modules/nostr-tools/lib/cjs/nip10.js.map b/node_modules/nostr-tools/lib/cjs/nip10.js.map new file mode 100644 index 0000000..f8014ba --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip10.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip10.ts"], + "sourcesContent": ["import type { Event } from './core.ts'\nimport type { EventPointer, ProfilePointer } from './nip19.ts'\n\nexport function parse(event: Pick): {\n /**\n * Pointer to the root of the thread.\n */\n root: EventPointer | undefined\n\n /**\n * Pointer to a \"parent\" event that parsed event replies to (responded to).\n */\n reply: EventPointer | undefined\n\n /**\n * Pointers to events that may or may not be in the reply chain.\n */\n mentions: EventPointer[]\n\n /**\n * Pointers to events that were directly quoted.\n */\n quotes: EventPointer[]\n\n /**\n * List of pubkeys that are involved in the thread in no particular order.\n */\n profiles: ProfilePointer[]\n} {\n const result: ReturnType = {\n reply: undefined,\n root: undefined,\n mentions: [],\n profiles: [],\n quotes: [],\n }\n\n let maybeParent: EventPointer | undefined\n let maybeRoot: EventPointer | undefined\n\n for (let i = event.tags.length - 1; i >= 0; i--) {\n const tag = event.tags[i]\n\n if (tag[0] === 'e' && tag[1]) {\n const [_, eTagEventId, eTagRelayUrl, eTagMarker, eTagAuthor] = tag as [\n string,\n string,\n undefined | string,\n undefined | string,\n undefined | string,\n ]\n\n const eventPointer: EventPointer = {\n id: eTagEventId,\n relays: eTagRelayUrl ? [eTagRelayUrl] : [],\n author: eTagAuthor,\n }\n\n if (eTagMarker === 'root') {\n result.root = eventPointer\n continue\n }\n\n if (eTagMarker === 'reply') {\n result.reply = eventPointer\n continue\n }\n\n if (eTagMarker === 'mention') {\n result.mentions.push(eventPointer)\n continue\n }\n\n if (!maybeParent) {\n maybeParent = eventPointer\n } else {\n maybeRoot = eventPointer\n }\n\n result.mentions.push(eventPointer)\n continue\n }\n\n if (tag[0] === 'q' && tag[1]) {\n const [_, eTagEventId, eTagRelayUrl] = tag as [string, string, undefined | string]\n result.quotes.push({\n id: eTagEventId,\n relays: eTagRelayUrl ? [eTagRelayUrl] : [],\n })\n }\n\n if (tag[0] === 'p' && tag[1]) {\n result.profiles.push({\n pubkey: tag[1],\n relays: tag[2] ? [tag[2]] : [],\n })\n continue\n }\n }\n\n // get legacy (positional) markers, set reply to root and vice-versa if one of them is missing\n if (!result.root) {\n result.root = maybeRoot || maybeParent || result.reply\n }\n if (!result.reply) {\n result.reply = maybeParent || result.root\n }\n\n // remove root and reply from mentions, inherit relay hints from authors if any\n ;[result.reply, result.root].forEach(ref => {\n if (!ref) return\n\n let idx = result.mentions.indexOf(ref)\n if (idx !== -1) {\n result.mentions.splice(idx, 1)\n }\n if (ref.author) {\n let author = result.profiles.find(p => p.pubkey === ref.author)\n if (author && author.relays) {\n if (!ref.relays) {\n ref.relays = []\n }\n author.relays.forEach(url => {\n if (ref.relays!?.indexOf(url) === -1) ref.relays!.push(url)\n })\n author.relays = ref.relays\n }\n }\n })\n\n result.mentions.forEach(ref => {\n if (ref!.author) {\n let author = result.profiles.find(p => p.pubkey === ref.author)\n if (author && author.relays) {\n if (!ref.relays) {\n ref.relays = []\n }\n author.relays.forEach(url => {\n if (ref.relays!.indexOf(url) === -1) ref.relays!.push(url)\n })\n author.relays = ref.relays\n }\n }\n })\n\n return result\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGO,SAAS,MAAM,OAyBpB;AACA,QAAM,SAAmC;AAAA,IACvC,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU,CAAC;AAAA,IACX,UAAU,CAAC;AAAA,IACX,QAAQ,CAAC;AAAA,EACX;AAEA,MAAI;AACJ,MAAI;AAEJ,WAAS,IAAI,MAAM,KAAK,SAAS,GAAG,KAAK,GAAG,KAAK;AAC/C,UAAM,MAAM,MAAM,KAAK;AAEvB,QAAI,IAAI,OAAO,OAAO,IAAI,IAAI;AAC5B,YAAM,CAAC,GAAG,aAAa,cAAc,YAAY,UAAU,IAAI;AAQ/D,YAAM,eAA6B;AAAA,QACjC,IAAI;AAAA,QACJ,QAAQ,eAAe,CAAC,YAAY,IAAI,CAAC;AAAA,QACzC,QAAQ;AAAA,MACV;AAEA,UAAI,eAAe,QAAQ;AACzB,eAAO,OAAO;AACd;AAAA,MACF;AAEA,UAAI,eAAe,SAAS;AAC1B,eAAO,QAAQ;AACf;AAAA,MACF;AAEA,UAAI,eAAe,WAAW;AAC5B,eAAO,SAAS,KAAK,YAAY;AACjC;AAAA,MACF;AAEA,UAAI,CAAC,aAAa;AAChB,sBAAc;AAAA,MAChB,OAAO;AACL,oBAAY;AAAA,MACd;AAEA,aAAO,SAAS,KAAK,YAAY;AACjC;AAAA,IACF;AAEA,QAAI,IAAI,OAAO,OAAO,IAAI,IAAI;AAC5B,YAAM,CAAC,GAAG,aAAa,YAAY,IAAI;AACvC,aAAO,OAAO,KAAK;AAAA,QACjB,IAAI;AAAA,QACJ,QAAQ,eAAe,CAAC,YAAY,IAAI,CAAC;AAAA,MAC3C,CAAC;AAAA,IACH;AAEA,QAAI,IAAI,OAAO,OAAO,IAAI,IAAI;AAC5B,a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D,eAAO,SAAS,IAAI;AAAA,MACtB;AAAA,IACF;AAAA,EACF,CAAC;AAED,SAAO;AACT;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip11.js b/node_modules/nostr-tools/lib/cjs/nip11.js new file mode 100644 index 0000000..d6032ec --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip11.js @@ -0,0 +1,39 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip11.ts +var nip11_exports = {}; +__export(nip11_exports, { + fetchRelayInformation: () => fetchRelayInformation, + useFetchImplementation: () => useFetchImplementation +}); +module.exports = __toCommonJS(nip11_exports); +var _fetch; +try { + _fetch = fetch; +} catch { +} +function useFetchImplementation(fetchImplementation) { + _fetch = fetchImplementation; +} +async function fetchRelayInformation(url) { + return await (await fetch(url.replace("ws://", "http://").replace("wss://", "https://"), { + headers: { Accept: "application/nostr+json" } + })).json(); +} diff --git a/node_modules/nostr-tools/lib/cjs/nip11.js.map b/node_modules/nostr-tools/lib/cjs/nip11.js.map new file mode 100644 index 0000000..e665b0f --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip11.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip11.ts"], + "sourcesContent": ["var _fetch: any\n\ntry {\n _fetch = fetch\n} catch {}\n\nexport function useFetchImplementation(fetchImplementation: any): void {\n _fetch = fetchImplementation\n}\n\nexport async function fetchRelayInformation(url: string): Promise {\n return (await (\n await fetch(url.replace('ws://', 'http://').replace('wss://', 'https://'), {\n headers: { Accept: 'application/nostr+json' },\n })\n ).json()) as RelayInformation\n}\n\n/**\n * ## Relay Information Document\n\n * Relays may provide server metadata to clients to inform\n * them of capabilities, administrative contacts, and\n * various server attributes. This is made available as a\n * JSON document over HTTP, on the same URI as the relay's\n * websocket.\n\n * Any field may be omitted, and clients MUST ignore any\n * additional fields they do not understand. Relays MUST\n * accept CORS requests by sending\n * `Access-Control-Allow-Origin`,\n * `Access-Control-Allow-Headers`, and\n * `Access-Control-Allow-Methods` headers.\n * @param name string identifying relay\n * @param description string with detailed information\n * @param pubkey administrative contact pubkey\n * @param contact: administrative alternate contact\n * @param supported_nips a list of NIP numbers supported by\n * the relay\n * @param software identifying relay software URL\n * @param version string version identifier\n */\nexport interface BasicRelayInformation {\n // string identifying relay\n name: string\n description: string\n pubkey: string\n contact: string\n supported_nips: number[]\n software: string\n version: string\n // limitation?: Limitations\n}\n\n/**\n * * ## Extra Fields\n\n * * ### Server Limitations\n\n * These are limitations imposed by the relay on clients.\n * Your client should expect that requests which exceed\n * these practical_ limitations are rejected or fail immediately.\n * @param max_message_length this is the maximum number of\n * bytes for incoming JSON that the relay will attempt to\n * decode and act upon. When you send large subscriptions,\n * you will be limited by this value. It also effectively\n * limits the maximum size of any event. Value is calculated\n * from `[` to `]` and is after UTF-8 serialization (so some\n * unicode characters will cost 2-3 bytes). It is equal to\n * the maximum size of the WebSocket message frame.\n * @param max_subscriptions total number of subscriptions\n * that may be active on a single websocket connection to\n * this relay. It's possible that authenticated clients with\n * a (paid) relationship to the relay may have higher limits.\n * @param max_filters maximum number of filter values in\n * each subscription. Must be one or higher.\n * @param max_limit the relay server will clamp each\n * filter's `limit` value to this number.\n * This means the client won't be able to get more than this\n * number of events from a single subscription filter. This\n * clamping is typically done silently by the relay, but\n * with this number, you can know that there are additional\n * results if you narrowed your filter's time range or other\n * parameters.\n * @param max_subid_length maximum length of subscription id as a\n * string.\n * @param min_prefix for `authors` and `ids` filters which\n * are to match against a hex prefix, you must provide at\n * least this many hex digits in the prefix.\n * @param max_event_tags in any event, this is the maximum\n * number of elements in the `tags` list.\n * @param max_content_length maximum number of characters in\n * the `content` field of any event. This is a count of\n * unicode characters. After serializing into JSON it may be\n * larger (in bytes), and is still subject to the\n * max_message_length`, if defined.\n * @param min_pow_difficulty new events will require at\n * least this difficulty of PoW, based on [NIP-13](13.md),\n * or they will be rejected by this server.\n * @param auth_required this relay requires [NIP-42](42.md)\n * authentication to happen before a new connection may\n * perform any other action. Even if set to False,\n * authentication may be required for specific actions.\n * @param restricted_writes: this relay requires some kind\n * of condition to be fulfilled in order to accept events\n * (not necessarily, but including\n * @param payment_required this relay requires payment\n * before a new connection may perform any action.\n * @param created_at_lower_limit: 'created_at' lower limit\n * @param created_at_upper_limit: 'created_at' upper limit\n */\nexport interface Limitations {\n max_message_length: number\n max_subscriptions: number\n max_filters: number\n max_limit: number\n max_subid_length: number\n min_prefix: number\n max_event_tags: number\n max_content_length: number\n min_pow_difficulty: number\n auth_required: boolean\n payment_required: boolean\n created_at_lower_limit: number\n created_at_upper_limit: number\n restricted_writes: boolean\n}\n\nexport interface RetentionDetails {\n kinds: (number | number[])[]\n time?: number | null\n count?: number | null\n}\ntype AnyRetentionDetails = RetentionDetails\n/**\n * ### Event Retention\n\n * There may be a cost associated with storing data forever,\n * so relays may wish to state retention times. The values\n * stated here are defaults for unauthenticated users and\n * visitors. Paid users would likely have other policies.\n\n * Retention times are given in seconds, with `null`\n * indicating infinity. If zero is provided, this means the\n * event will not be stored at all, and preferably an error\n * will be provided when those are received.\n * ```json\n{\n...\n \"retention\": [\n { \"kinds\": [0, 1, [5, 7], [40, 49]], \"time\": 3600 },\n { \"kinds\": [[40000, 49999]], \"time\": 100 },\n { \"kinds\": [[30000, 39999]], \"count\": 1000 },\n { \"time\": 3600, \"count\": 10000 }\n ]\n...\n}\n```\n * @param retention is a list of specifications: each will\n * apply to either all kinds, or a subset of kinds. Ranges\n * may be specified for the kind field as a tuple of\n * inclusive start and end values. Events of indicated kind\n * (or all) are then limited to a `count` and/or time\n * period.\n\n * It is possible to effectively blacklist Nostr-based\n * protocols that rely on a specific `kind` number, by\n * giving a retention time of zero for those `kind` values.\n * While that is unfortunate, it does allow clients to\n * discover servers that will support their protocol quickly\n * via a single HTTP fetch.\n\n * There is no need to specify retention times for\n * _ephemeral events_ as defined in [NIP-16](16.md) since\n * they are not retained.\n */\nexport interface Retention {\n retention: AnyRetentionDetails[]\n}\n\n/**\n * Some relays may be governed by the arbitrary laws of a\n * nation state. This may limit what content can be stored\n * in cleartext on those relays. All clients are encouraged\n * to use encryption to work around this limitation.\n\n * It is not possible to describe the limitations of each\n * country's laws and policies which themselves are\n * typically vague and constantly shifting.\n\n * Therefore, this field allows the relay operator to\n * indicate which countries' laws might end up being\n * enforced on them, and then indirectly on their users'\n * content.\n\n * Users should be able to avoid relays in countries they\n * don't like, and/or select relays in more favourable\n * zones. Exposing this flexibility is up to the client\n * software.\n\n * @param relay_countries a list of two-level ISO country\n * codes (ISO 3166-1 alpha-2) whose laws and policies may\n * affect this relay. `EU` may be used for European Union\n * countries.\n\n * Remember that a relay may be hosted in a country which is\n * not the country of the legal entities who own the relay,\n * so it's very likely a number of countries are involved.\n */\nexport interface ContentLimitations {\n relay_countries: string[]\n}\n\n/**\n * ### Community Preferences\n\n * For public text notes at least, a relay may try to foster\n * a local community. This would encourage users to follow\n * the global feed on that relay, in addition to their usual\n * individual follows. To support this goal, relays MAY\n * specify some of the following values.\n\n * @param language_tags is an ordered list of [IETF\n * language\n * tags](https://en.wikipedia.org/wiki/IETF_language_tag\n * indicating the major languages spoken on the relay.\n * @param tags is a list of limitations on the topics to be\n * discussed. For example `sfw-only` indicates that only\n * \"Safe For Work\" content is encouraged on this relay. This\n * relies on assumptions of what the \"work\" \"community\"\n * feels \"safe\" talking about. In time, a common set of tags\n * may emerge that allow users to find relays that suit\n * their needs, and client software will be able to parse\n * these tags easily. The `bitcoin-only` tag indicates that\n * any _altcoin_, _\"crypto\"_ or _blockchain_ comments will\n * be ridiculed without mercy.\n * @param posting_policy is a link to a human-readable page\n * which specifies the community policies for the relay. In\n * cases where `sfw-only` is True, it's important to link to\n * a page which gets into the specifics of your posting\n * policy.\n\n * The `description` field should be used to describe your\n * community goals and values, in brief. The\n * `posting_policy` is for additional detail and legal\n * terms. Use the `tags` field to signify limitations on\n * content, or topics to be discussed, which could be\n * machine processed by appropriate client software.\n */\nexport interface CommunityPreferences {\n language_tags: string[]\n tags: string[]\n posting_policy: string\n}\n\nexport interface Amount {\n amount: number\n unit: 'msat'\n}\nexport interface PublicationAmount extends Amount {\n kinds: number[]\n}\nexport interface Subscription extends Amount {\n period: number\n}\nexport interface Fees {\n admission: Amount[]\n subscription: Subscription[]\n publication: PublicationAmount[]\n}\n/**\n * Relays that require payments may want to expose their fee\n * schedules.\n */\nexport interface PayToRelay {\n payments_url: string\n fees: Fees\n}\n\n/**\n * A URL pointing to an image to be used as an icon for the\n * relay. Recommended to be squared in shape.\n */\nexport interface Icon {\n icon: string\n}\n\nexport type RelayInformation = BasicRelayInformation &\n Partial & {\n limitation?: Partial\n } & Partial &\n Partial &\n Partial &\n Partial\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAI;AAEJ,IAAI;AACF,WAAS;AACX,QAAE;AAAO;AAEF,SAAS,uBAAuB,qBAAgC;AACrE,WAAS;AACX;AAEA,eAAsB,sBAAsB,KAAwC;AAClF,SAAQ,OACN,MAAM,MAAM,IAAI,QAAQ,SAAS,SAAS,EAAE,QAAQ,UAAU,UAAU,GAAG;AAAA,IACzE,SAAS,EAAE,QAAQ,yBAAyB;AAAA,EAC9C,CAAC,GACD,KAAK;AACT;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip13.js b/node_modules/nostr-tools/lib/cjs/nip13.js new file mode 100644 index 0000000..28e6b7e --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip13.js @@ -0,0 +1,73 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip13.ts +var nip13_exports = {}; +__export(nip13_exports, { + fastEventHash: () => fastEventHash, + getPow: () => getPow, + minePow: () => minePow +}); +module.exports = __toCommonJS(nip13_exports); +var import_utils2 = require("@noble/hashes/utils"); +var import_sha256 = require("@noble/hashes/sha256"); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// nip13.ts +function getPow(hex) { + let count = 0; + for (let i = 0; i < 64; i += 8) { + const nibble = parseInt(hex.substring(i, i + 8), 16); + if (nibble === 0) { + count += 32; + } else { + count += Math.clz32(nibble); + break; + } + } + return count; +} +function minePow(unsigned, difficulty) { + let count = 0; + const event = unsigned; + const tag = ["nonce", count.toString(), difficulty.toString()]; + event.tags.push(tag); + while (true) { + const now = Math.floor(new Date().getTime() / 1e3); + if (now !== event.created_at) { + count = 0; + event.created_at = now; + } + tag[1] = (++count).toString(); + event.id = fastEventHash(event); + if (getPow(event.id) >= difficulty) { + break; + } + } + return event; +} +function fastEventHash(evt) { + return (0, import_utils2.bytesToHex)( + (0, import_sha256.sha256)(utf8Encoder.encode(JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]))) + ); +} diff --git a/node_modules/nostr-tools/lib/cjs/nip13.js.map b/node_modules/nostr-tools/lib/cjs/nip13.js.map new file mode 100644 index 0000000..cbec2dc --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip13.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip13.ts", "../../utils.ts"], + "sourcesContent": ["import { bytesToHex } from '@noble/hashes/utils'\nimport { type UnsignedEvent, type Event } from './pure.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\n/** Get POW difficulty from a Nostr hex ID. */\nexport function getPow(hex: string): number {\n let count = 0\n\n for (let i = 0; i < 64; i += 8) {\n const nibble = parseInt(hex.substring(i, i + 8), 16)\n if (nibble === 0) {\n count += 32\n } else {\n count += Math.clz32(nibble)\n break\n }\n }\n\n return count\n}\n\n/**\n * Mine an event with the desired POW. This function mutates the event.\n * Note that this operation is synchronous and should be run in a worker context to avoid blocking the main thread.\n */\nexport function minePow(unsigned: UnsignedEvent, difficulty: number): Omit {\n let count = 0\n\n const event = unsigned as Omit\n const tag = ['nonce', count.toString(), difficulty.toString()]\n\n event.tags.push(tag)\n\n while (true) {\n const now = Math.floor(new Date().getTime() / 1000)\n\n if (now !== event.created_at) {\n count = 0\n event.created_at = now\n }\n\n tag[1] = (++count).toString()\n\n event.id = fastEventHash(event)\n\n if (getPow(event.id) >= difficulty) {\n break\n }\n }\n\n return event\n}\n\nexport function fastEventHash(evt: UnsignedEvent): string {\n return bytesToHex(\n sha256(utf8Encoder.encode(JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]))),\n )\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,gBAA2B;AAE3B,oBAAuB;;;ACGvB,mBAAuC;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;;;ADIjD,SAAS,OAAO,KAAqB;AAC1C,MAAI,QAAQ;AAEZ,WAAS,IAAI,GAAG,IAAI,IAAI,KAAK,GAAG;AAC9B,UAAM,SAAS,SAAS,IAAI,UAAU,GAAG,IAAI,CAAC,GAAG,EAAE;AACnD,QAAI,WAAW,GAAG;AAChB,eAAS;AAAA,IACX,OAAO;AACL,eAAS,KAAK,MAAM,MAAM;AAC1B;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAMO,SAAS,QAAQ,UAAyB,YAAwC;AACvF,MAAI,QAAQ;AAEZ,QAAM,QAAQ;AACd,QAAM,MAAM,CAAC,SAAS,MAAM,SAAS,GAAG,WAAW,SAAS,CAAC;AAE7D,QAAM,KAAK,KAAK,GAAG;AAEnB,SAAO,MAAM;AACX,UAAM,MAAM,KAAK,MAAM,IAAI,KAAK,EAAE,QAAQ,IAAI,GAAI;AAElD,QAAI,QAAQ,MAAM,YAAY;AAC5B,cAAQ;AACR,YAAM,aAAa;AAAA,IACrB;AAEA,QAAI,MAAM,EAAE,OAAO,SAAS;AAE5B,UAAM,KAAK,cAAc,KAAK;AAE9B,QAAI,OAAO,MAAM,EAAE,KAAK,YAAY;AAClC;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAEO,SAAS,cAAc,KAA4B;AACxD,aAAO;AAAA,QACL,sBAAO,YAAY,OAAO,KAAK,UAAU,CAAC,GAAG,IAAI,QAAQ,IAAI,YAAY,IAAI,MAAM,IAAI,MAAM,IAAI,OAAO,CAAC,CAAC,CAAC;AAAA,EAC7G;AACF;", + "names": ["import_utils"] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip17.js b/node_modules/nostr-tools/lib/cjs/nip17.js new file mode 100644 index 0000000..7bd3566 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip17.js @@ -0,0 +1,321 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip17.ts +var nip17_exports = {}; +__export(nip17_exports, { + unwrapEvent: () => unwrapEvent2, + unwrapManyEvents: () => unwrapManyEvents2, + wrapEvent: () => wrapEvent2, + wrapManyEvents: () => wrapManyEvents +}); +module.exports = __toCommonJS(nip17_exports); + +// pure.ts +var import_secp256k1 = require("@noble/curves/secp256k1"); +var import_utils2 = require("@noble/hashes/utils"); + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +var import_sha256 = require("@noble/hashes/sha256"); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// pure.ts +var JS = class { + generateSecretKey() { + return import_secp256k1.schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = import_secp256k1.schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = (0, import_sha256.sha256)(utf8Encoder.encode(serializeEvent(event))); + return (0, import_utils2.bytesToHex)(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// kinds.ts +var Seal = 13; +var PrivateDirectMessage = 14; +var GiftWrap = 1059; + +// nip44.ts +var import_chacha = require("@noble/ciphers/chacha"); +var import_utils4 = require("@noble/ciphers/utils"); +var import_secp256k12 = require("@noble/curves/secp256k1"); +var import_hkdf = require("@noble/hashes/hkdf"); +var import_hmac = require("@noble/hashes/hmac"); +var import_sha2562 = require("@noble/hashes/sha256"); +var import_utils5 = require("@noble/hashes/utils"); +var import_base = require("@scure/base"); +var minPlaintextSize = 1; +var maxPlaintextSize = 65535; +function getConversationKey(privkeyA, pubkeyB) { + const sharedX = import_secp256k12.secp256k1.getSharedSecret(privkeyA, "02" + pubkeyB).subarray(1, 33); + return (0, import_hkdf.extract)(import_sha2562.sha256, sharedX, "nip44-v2"); +} +function getMessageKeys(conversationKey, nonce) { + const keys = (0, import_hkdf.expand)(import_sha2562.sha256, conversationKey, nonce, 76); + return { + chacha_key: keys.subarray(0, 32), + chacha_nonce: keys.subarray(32, 44), + hmac_key: keys.subarray(44, 76) + }; +} +function calcPaddedLen(len) { + if (!Number.isSafeInteger(len) || len < 1) + throw new Error("expected positive integer"); + if (len <= 32) + return 32; + const nextPower = 1 << Math.floor(Math.log2(len - 1)) + 1; + const chunk = nextPower <= 256 ? 32 : nextPower / 8; + return chunk * (Math.floor((len - 1) / chunk) + 1); +} +function writeU16BE(num) { + if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize) + throw new Error("invalid plaintext size: must be between 1 and 65535 bytes"); + const arr = new Uint8Array(2); + new DataView(arr.buffer).setUint16(0, num, false); + return arr; +} +function pad(plaintext) { + const unpadded = utf8Encoder.encode(plaintext); + const unpaddedLen = unpadded.length; + const prefix = writeU16BE(unpaddedLen); + const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen); + return (0, import_utils5.concatBytes)(prefix, unpadded, suffix); +} +function unpad(padded) { + const unpaddedLen = new DataView(padded.buffer).getUint16(0); + const unpadded = padded.subarray(2, 2 + unpaddedLen); + if (unpaddedLen < minPlaintextSize || unpaddedLen > maxPlaintextSize || unpadded.length !== unpaddedLen || padded.length !== 2 + calcPaddedLen(unpaddedLen)) + throw new Error("invalid padding"); + return utf8Decoder.decode(unpadded); +} +function hmacAad(key, message, aad) { + if (aad.length !== 32) + throw new Error("AAD associated data must be 32 bytes"); + const combined = (0, import_utils5.concatBytes)(aad, message); + return (0, import_hmac.hmac)(import_sha2562.sha256, key, combined); +} +function decodePayload(payload) { + if (typeof payload !== "string") + throw new Error("payload must be a valid string"); + const plen = payload.length; + if (plen < 132 || plen > 87472) + throw new Error("invalid payload length: " + plen); + if (payload[0] === "#") + throw new Error("unknown encryption version"); + let data; + try { + data = import_base.base64.decode(payload); + } catch (error) { + throw new Error("invalid base64: " + error.message); + } + const dlen = data.length; + if (dlen < 99 || dlen > 65603) + throw new Error("invalid data length: " + dlen); + const vers = data[0]; + if (vers !== 2) + throw new Error("unknown encryption version " + vers); + return { + nonce: data.subarray(1, 33), + ciphertext: data.subarray(33, -32), + mac: data.subarray(-32) + }; +} +function encrypt(plaintext, conversationKey, nonce = (0, import_utils5.randomBytes)(32)) { + const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); + const padded = pad(plaintext); + const ciphertext = (0, import_chacha.chacha20)(chacha_key, chacha_nonce, padded); + const mac = hmacAad(hmac_key, ciphertext, nonce); + return import_base.base64.encode((0, import_utils5.concatBytes)(new Uint8Array([2]), nonce, ciphertext, mac)); +} +function decrypt(payload, conversationKey) { + const { nonce, ciphertext, mac } = decodePayload(payload); + const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); + const calculatedMac = hmacAad(hmac_key, ciphertext, nonce); + if (!(0, import_utils4.equalBytes)(calculatedMac, mac)) + throw new Error("invalid MAC"); + const padded = (0, import_chacha.chacha20)(chacha_key, chacha_nonce, ciphertext); + return unpad(padded); +} + +// nip59.ts +var TWO_DAYS = 2 * 24 * 60 * 60; +var now = () => Math.round(Date.now() / 1e3); +var randomNow = () => Math.round(now() - Math.random() * TWO_DAYS); +var nip44ConversationKey = (privateKey, publicKey) => getConversationKey(privateKey, publicKey); +var nip44Encrypt = (data, privateKey, publicKey) => encrypt(JSON.stringify(data), nip44ConversationKey(privateKey, publicKey)); +var nip44Decrypt = (data, privateKey) => JSON.parse(decrypt(data.content, nip44ConversationKey(privateKey, data.pubkey))); +function createRumor(event, privateKey) { + const rumor = { + created_at: now(), + content: "", + tags: [], + ...event, + pubkey: getPublicKey(privateKey) + }; + rumor.id = getEventHash(rumor); + return rumor; +} +function createSeal(rumor, privateKey, recipientPublicKey) { + return finalizeEvent( + { + kind: Seal, + content: nip44Encrypt(rumor, privateKey, recipientPublicKey), + created_at: randomNow(), + tags: [] + }, + privateKey + ); +} +function createWrap(seal, recipientPublicKey) { + const randomKey = generateSecretKey(); + return finalizeEvent( + { + kind: GiftWrap, + content: nip44Encrypt(seal, randomKey, recipientPublicKey), + created_at: randomNow(), + tags: [["p", recipientPublicKey]] + }, + randomKey + ); +} +function wrapEvent(event, senderPrivateKey, recipientPublicKey) { + const rumor = createRumor(event, senderPrivateKey); + const seal = createSeal(rumor, senderPrivateKey, recipientPublicKey); + return createWrap(seal, recipientPublicKey); +} +function unwrapEvent(wrap, recipientPrivateKey) { + const unwrappedSeal = nip44Decrypt(wrap, recipientPrivateKey); + return nip44Decrypt(unwrappedSeal, recipientPrivateKey); +} +function unwrapManyEvents(wrappedEvents, recipientPrivateKey) { + let unwrappedEvents = []; + wrappedEvents.forEach((e) => { + unwrappedEvents.push(unwrapEvent(e, recipientPrivateKey)); + }); + unwrappedEvents.sort((a, b) => a.created_at - b.created_at); + return unwrappedEvents; +} + +// nip17.ts +function createEvent(recipients, message, conversationTitle, replyTo) { + const baseEvent = { + created_at: Math.ceil(Date.now() / 1e3), + kind: PrivateDirectMessage, + tags: [], + content: message + }; + const recipientsArray = Array.isArray(recipients) ? recipients : [recipients]; + recipientsArray.forEach(({ publicKey, relayUrl }) => { + baseEvent.tags.push(relayUrl ? ["p", publicKey, relayUrl] : ["p", publicKey]); + }); + if (replyTo) { + baseEvent.tags.push(["e", replyTo.eventId, replyTo.relayUrl || "", "reply"]); + } + if (conversationTitle) { + baseEvent.tags.push(["subject", conversationTitle]); + } + return baseEvent; +} +function wrapEvent2(senderPrivateKey, recipient, message, conversationTitle, replyTo) { + const event = createEvent(recipient, message, conversationTitle, replyTo); + return wrapEvent(event, senderPrivateKey, recipient.publicKey); +} +function wrapManyEvents(senderPrivateKey, recipients, message, conversationTitle, replyTo) { + if (!recipients || recipients.length === 0) { + throw new Error("At least one recipient is required."); + } + const senderPublicKey = getPublicKey(senderPrivateKey); + return [{ publicKey: senderPublicKey }, ...recipients].map( + (recipient) => wrapEvent2(senderPrivateKey, recipient, message, conversationTitle, replyTo) + ); +} +var unwrapEvent2 = unwrapEvent; +var unwrapManyEvents2 = unwrapManyEvents; diff --git a/node_modules/nostr-tools/lib/cjs/nip17.js.map b/node_modules/nostr-tools/lib/cjs/nip17.js.map new file mode 100644 index 0000000..0bd8e2e --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip17.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip17.ts", "../../pure.ts", "../../core.ts", "../../utils.ts", "../../kinds.ts", "../../nip44.ts", "../../nip59.ts"], + "sourcesContent": ["import { PrivateDirectMessage } from './kinds.ts'\nimport { EventTemplate, NostrEvent, getPublicKey } from './pure.ts'\nimport * as nip59 from './nip59.ts'\n\ntype Recipient = {\n publicKey: string\n relayUrl?: string\n}\n\ntype ReplyTo = {\n eventId: string\n relayUrl?: string\n}\n\nfunction createEvent(\n recipients: Recipient | Recipient[],\n message: string,\n conversationTitle?: string,\n replyTo?: ReplyTo,\n): EventTemplate {\n const baseEvent: EventTemplate = {\n created_at: Math.ceil(Date.now() / 1000),\n kind: PrivateDirectMessage,\n tags: [],\n content: message,\n }\n\n const recipientsArray = Array.isArray(recipients) ? recipients : [recipients]\n\n recipientsArray.forEach(({ publicKey, relayUrl }) => {\n baseEvent.tags.push(relayUrl ? ['p', publicKey, relayUrl] : ['p', publicKey])\n })\n\n if (replyTo) {\n baseEvent.tags.push(['e', replyTo.eventId, replyTo.relayUrl || '', 'reply'])\n }\n\n if (conversationTitle) {\n baseEvent.tags.push(['subject', conversationTitle])\n }\n\n return baseEvent\n}\n\nexport function wrapEvent(\n senderPrivateKey: Uint8Array,\n recipient: Recipient,\n message: string,\n conversationTitle?: string,\n replyTo?: ReplyTo,\n): NostrEvent {\n const event = createEvent(recipient, message, conversationTitle, replyTo)\n return nip59.wrapEvent(event, senderPrivateKey, recipient.publicKey)\n}\n\nexport function wrapManyEvents(\n senderPrivateKey: Uint8Array,\n recipients: Recipient[],\n message: string,\n conversationTitle?: string,\n replyTo?: ReplyTo,\n): NostrEvent[] {\n if (!recipients || recipients.length === 0) {\n throw new Error('At least one recipient is required.')\n }\n\n const senderPublicKey = getPublicKey(senderPrivateKey)\n\n // wrap the event for the sender and then for each recipient\n return [{ publicKey: senderPublicKey }, ...recipients].map(recipient =>\n wrapEvent(senderPrivateKey, recipient, message, conversationTitle, replyTo),\n )\n}\n\nexport const unwrapEvent = nip59.unwrapEvent\n\nexport const unwrapManyEvents = nip59.unwrapManyEvents\n", "import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { chacha20 } from '@noble/ciphers/chacha'\nimport { equalBytes } from '@noble/ciphers/utils'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { extract as hkdf_extract, expand as hkdf_expand } from '@noble/hashes/hkdf'\nimport { hmac } from '@noble/hashes/hmac'\nimport { sha256 } from '@noble/hashes/sha256'\nimport { concatBytes, randomBytes } from '@noble/hashes/utils'\nimport { base64 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nconst minPlaintextSize = 0x0001 // 1b msg => padded to 32b\nconst maxPlaintextSize = 0xffff // 65535 (64kb-1) => padded to 64kb\n\nexport function getConversationKey(privkeyA: Uint8Array, pubkeyB: string): Uint8Array {\n const sharedX = secp256k1.getSharedSecret(privkeyA, '02' + pubkeyB).subarray(1, 33)\n return hkdf_extract(sha256, sharedX, 'nip44-v2')\n}\n\nfunction getMessageKeys(\n conversationKey: Uint8Array,\n nonce: Uint8Array,\n): { chacha_key: Uint8Array; chacha_nonce: Uint8Array; hmac_key: Uint8Array } {\n const keys = hkdf_expand(sha256, conversationKey, nonce, 76)\n return {\n chacha_key: keys.subarray(0, 32),\n chacha_nonce: keys.subarray(32, 44),\n hmac_key: keys.subarray(44, 76),\n }\n}\n\nfunction calcPaddedLen(len: number): number {\n if (!Number.isSafeInteger(len) || len < 1) throw new Error('expected positive integer')\n if (len <= 32) return 32\n const nextPower = 1 << (Math.floor(Math.log2(len - 1)) + 1)\n const chunk = nextPower <= 256 ? 32 : nextPower / 8\n return chunk * (Math.floor((len - 1) / chunk) + 1)\n}\n\nfunction writeU16BE(num: number): Uint8Array {\n if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize)\n throw new Error('invalid plaintext size: must be between 1 and 65535 bytes')\n const arr = new Uint8Array(2)\n new DataView(arr.buffer).setUint16(0, num, false)\n return arr\n}\n\nfunction pad(plaintext: string): Uint8Array {\n const unpadded = utf8Encoder.encode(plaintext)\n const unpaddedLen = unpadded.length\n const prefix = writeU16BE(unpaddedLen)\n const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen)\n return concatBytes(prefix, unpadded, suffix)\n}\n\nfunction unpad(padded: Uint8Array): string {\n const unpaddedLen = new DataView(padded.buffer).getUint16(0)\n const unpadded = padded.subarray(2, 2 + unpaddedLen)\n if (\n unpaddedLen < minPlaintextSize ||\n unpaddedLen > maxPlaintextSize ||\n unpadded.length !== unpaddedLen ||\n padded.length !== 2 + calcPaddedLen(unpaddedLen)\n )\n throw new Error('invalid padding')\n return utf8Decoder.decode(unpadded)\n}\n\nfunction hmacAad(key: Uint8Array, message: Uint8Array, aad: Uint8Array): Uint8Array {\n if (aad.length !== 32) throw new Error('AAD associated data must be 32 bytes')\n const combined = concatBytes(aad, message)\n return hmac(sha256, key, combined)\n}\n\n// metadata: always 65b (version: 1b, nonce: 32b, max: 32b)\n// plaintext: 1b to 0xffff\n// padded plaintext: 32b to 0xffff\n// ciphertext: 32b+2 to 0xffff+2\n// raw payload: 99 (65+32+2) to 65603 (65+0xffff+2)\n// compressed payload (base64): 132b to 87472b\nfunction decodePayload(payload: string): { nonce: Uint8Array; ciphertext: Uint8Array; mac: Uint8Array } {\n if (typeof payload !== 'string') throw new Error('payload must be a valid string')\n const plen = payload.length\n if (plen < 132 || plen > 87472) throw new Error('invalid payload length: ' + plen)\n if (payload[0] === '#') throw new Error('unknown encryption version')\n let data: Uint8Array\n try {\n data = base64.decode(payload)\n } catch (error) {\n throw new Error('invalid base64: ' + (error as any).message)\n }\n const dlen = data.length\n if (dlen < 99 || dlen > 65603) throw new Error('invalid data length: ' + dlen)\n const vers = data[0]\n if (vers !== 2) throw new Error('unknown encryption version ' + vers)\n return {\n nonce: data.subarray(1, 33),\n ciphertext: data.subarray(33, -32),\n mac: data.subarray(-32),\n }\n}\n\nexport function encrypt(plaintext: string, conversationKey: Uint8Array, nonce: Uint8Array = randomBytes(32)): string {\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n const padded = pad(plaintext)\n const ciphertext = chacha20(chacha_key, chacha_nonce, padded)\n const mac = hmacAad(hmac_key, ciphertext, nonce)\n return base64.encode(concatBytes(new Uint8Array([2]), nonce, ciphertext, mac))\n}\n\nexport function decrypt(payload: string, conversationKey: Uint8Array): string {\n const { nonce, ciphertext, mac } = decodePayload(payload)\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n const calculatedMac = hmacAad(hmac_key, ciphertext, nonce)\n if (!equalBytes(calculatedMac, mac)) throw new Error('invalid MAC')\n const padded = chacha20(chacha_key, chacha_nonce, ciphertext)\n return unpad(padded)\n}\n\nexport const v2 = {\n utils: {\n getConversationKey,\n calcPaddedLen,\n },\n encrypt,\n decrypt,\n}\n", "import { EventTemplate, UnsignedEvent, NostrEvent } from './core.ts'\nimport { getConversationKey, decrypt, encrypt } from './nip44.ts'\nimport { getEventHash, generateSecretKey, finalizeEvent, getPublicKey } from './pure.ts'\nimport { Seal, GiftWrap } from './kinds.ts'\n\ntype Rumor = UnsignedEvent & { id: string }\n\nconst TWO_DAYS = 2 * 24 * 60 * 60\n\nconst now = () => Math.round(Date.now() / 1000)\nconst randomNow = () => Math.round(now() - Math.random() * TWO_DAYS)\n\nconst nip44ConversationKey = (privateKey: Uint8Array, publicKey: string) => getConversationKey(privateKey, publicKey)\n\nconst nip44Encrypt = (data: EventTemplate, privateKey: Uint8Array, publicKey: string) =>\n encrypt(JSON.stringify(data), nip44ConversationKey(privateKey, publicKey))\n\nconst nip44Decrypt = (data: NostrEvent, privateKey: Uint8Array) =>\n JSON.parse(decrypt(data.content, nip44ConversationKey(privateKey, data.pubkey)))\n\nexport function createRumor(event: Partial, privateKey: Uint8Array): Rumor {\n const rumor = {\n created_at: now(),\n content: '',\n tags: [],\n ...event,\n pubkey: getPublicKey(privateKey),\n } as any\n\n rumor.id = getEventHash(rumor)\n\n return rumor as Rumor\n}\n\nexport function createSeal(rumor: Rumor, privateKey: Uint8Array, recipientPublicKey: string): NostrEvent {\n return finalizeEvent(\n {\n kind: Seal,\n content: nip44Encrypt(rumor, privateKey, recipientPublicKey),\n created_at: randomNow(),\n tags: [],\n },\n privateKey,\n )\n}\n\nexport function createWrap(seal: NostrEvent, recipientPublicKey: string): NostrEvent {\n const randomKey = generateSecretKey()\n\n return finalizeEvent(\n {\n kind: GiftWrap,\n content: nip44Encrypt(seal, randomKey, recipientPublicKey),\n created_at: randomNow(),\n tags: [['p', recipientPublicKey]],\n },\n randomKey,\n ) as NostrEvent\n}\n\nexport function wrapEvent(\n event: Partial,\n senderPrivateKey: Uint8Array,\n recipientPublicKey: string,\n): NostrEvent {\n const rumor = createRumor(event, senderPrivateKey)\n\n const seal = createSeal(rumor, senderPrivateKey, recipientPublicKey)\n return createWrap(seal, recipientPublicKey)\n}\n\nexport function wrapManyEvents(\n event: Partial,\n senderPrivateKey: Uint8Array,\n recipientsPublicKeys: string[],\n): NostrEvent[] {\n if (!recipientsPublicKeys || recipientsPublicKeys.length === 0) {\n throw new Error('At least one recipient is required.')\n }\n\n const senderPublicKey = getPublicKey(senderPrivateKey)\n\n const wrappeds = [wrapEvent(event, senderPrivateKey, senderPublicKey)]\n\n recipientsPublicKeys.forEach(recipientPublicKey => {\n wrappeds.push(wrapEvent(event, senderPrivateKey, recipientPublicKey))\n })\n\n return wrappeds\n}\n\nexport function unwrapEvent(wrap: NostrEvent, recipientPrivateKey: Uint8Array): Rumor {\n const unwrappedSeal = nip44Decrypt(wrap, recipientPrivateKey)\n return nip44Decrypt(unwrappedSeal, recipientPrivateKey)\n}\n\nexport function unwrapManyEvents(wrappedEvents: NostrEvent[], recipientPrivateKey: Uint8Array): Rumor[] {\n let unwrappedEvents: Rumor[] = []\n\n wrappedEvents.forEach(e => {\n unwrappedEvents.push(unwrapEvent(e, recipientPrivateKey))\n })\n\n unwrappedEv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A,QAAM,kBAAkB,MAAM,QAAQ,UAAU,IAAI,aAAa,CAAC,UAAU;AAE5E,kBAAgB,QAAQ,CAAC,EAAE,WAAW,SAAS,MAAM;AACnD,cAAU,KAAK,KAAK,WAAW,CAAC,KAAK,WAAW,QAAQ,IAAI,CAAC,KAAK,SAAS,CAAC;AAAA,EAC9E,CAAC;AAED,MAAI,SAAS;AACX,cAAU,KAAK,KAAK,CAAC,KAAK,QAAQ,SAAS,QAAQ,YAAY,IAAI,OAAO,CAAC;AAAA,EAC7E;AAEA,MAAI,mBAAmB;AACrB,cAAU,KAAK,KAAK,CAAC,WAAW,iBAAiB,CAAC;AAAA,EACpD;AAEA,SAAO;AACT;AAEO,SAASC,WACd,kBACA,WACA,SACA,mBACA,SACY;AACZ,QAAM,QAAQ,YAAY,WAAW,SAAS,mBAAmB,OAAO;AACxE,SAAa,UAAU,OAAO,kBAAkB,UAAU,SAAS;AACrE;AAEO,SAAS,eACd,kBACA,YACA,SACA,mBACA,SACc;AACd,MAAI,CAAC,cAAc,WAAW,WAAW,GAAG;AAC1C,UAAM,IAAI,MAAM,qCAAqC;AAAA,EACvD;AAEA,QAAM,kBAAkB,aAAa,gBAAgB;AAGrD,SAAO,CAAC,EAAE,WAAW,gBAAgB,GAAG,GAAG,UAAU,EAAE;AAAA,IAAI,eACzDA,WAAU,kBAAkB,WAAW,SAAS,mBAAmB,OAAO;AAAA,EAC5E;AACF;AAEO,IAAMC,eAAoB;AAE1B,IAAMC,oBAAyB;", + "names": ["unwrapEvent", "unwrapManyEvents", "wrapEvent", "import_utils", "i", "import_utils", "import_secp256k1", "import_sha256", "hkdf_extract", "hkdf_expand", "wrapEvent", "unwrapEvent", "unwrapManyEvents"] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip18.js b/node_modules/nostr-tools/lib/cjs/nip18.js new file mode 100644 index 0000000..63c74d9 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip18.js @@ -0,0 +1,188 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip18.ts +var nip18_exports = {}; +__export(nip18_exports, { + finishRepostEvent: () => finishRepostEvent, + getRepostedEvent: () => getRepostedEvent, + getRepostedEventPointer: () => getRepostedEventPointer +}); +module.exports = __toCommonJS(nip18_exports); + +// pure.ts +var import_secp256k1 = require("@noble/curves/secp256k1"); +var import_utils2 = require("@noble/hashes/utils"); + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +var import_sha256 = require("@noble/hashes/sha256"); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// pure.ts +var JS = class { + generateSecretKey() { + return import_secp256k1.schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = import_secp256k1.schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = (0, import_sha256.sha256)(utf8Encoder.encode(serializeEvent(event))); + return (0, import_utils2.bytesToHex)(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// kinds.ts +var ShortTextNote = 1; +var Repost = 6; +var GenericRepost = 16; + +// nip18.ts +function finishRepostEvent(t, reposted, relayUrl, privateKey) { + let kind; + const tags = [...t.tags ?? [], ["e", reposted.id, relayUrl], ["p", reposted.pubkey]]; + if (reposted.kind === ShortTextNote) { + kind = Repost; + } else { + kind = GenericRepost; + tags.push(["k", String(reposted.kind)]); + } + return finalizeEvent( + { + kind, + tags, + content: t.content === "" || reposted.tags?.find((tag) => tag[0] === "-") ? "" : JSON.stringify(reposted), + created_at: t.created_at + }, + privateKey + ); +} +function getRepostedEventPointer(event) { + if (![Repost, GenericRepost].includes(event.kind)) { + return void 0; + } + let lastETag; + let lastPTag; + for (let i2 = event.tags.length - 1; i2 >= 0 && (lastETag === void 0 || lastPTag === void 0); i2--) { + const tag = event.tags[i2]; + if (tag.length >= 2) { + if (tag[0] === "e" && lastETag === void 0) { + lastETag = tag; + } else if (tag[0] === "p" && lastPTag === void 0) { + lastPTag = tag; + } + } + } + if (lastETag === void 0) { + return void 0; + } + return { + id: lastETag[1], + relays: [lastETag[2], lastPTag?.[2]].filter((x) => typeof x === "string"), + author: lastPTag?.[1] + }; +} +function getRepostedEvent(event, { skipVerification } = {}) { + const pointer = getRepostedEventPointer(event); + if (pointer === void 0 || event.content === "") { + return void 0; + } + let repostedEvent; + try { + repostedEvent = JSON.parse(event.content); + } catch (error) { + return void 0; + } + if (repostedEvent.id !== pointer.id) { + return void 0; + } + if (!skipVerification && !verifyEvent(repostedEvent)) { + return void 0; + } + return repostedEvent; +} diff --git a/node_modules/nostr-tools/lib/cjs/nip18.js.map b/node_modules/nostr-tools/lib/cjs/nip18.js.map new file mode 100644 index 0000000..aaa9557 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip18.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip18.ts", "../../pure.ts", "../../core.ts", "../../utils.ts", "../../kinds.ts"], + "sourcesContent": ["import { GenericRepost, Repost, ShortTextNote } from './kinds.ts'\nimport { EventPointer } from './nip19.ts'\nimport { Event, finalizeEvent, verifyEvent } from './pure.ts'\n\nexport type RepostEventTemplate = {\n /**\n * Pass only non-nip18 tags if you have to.\n * Nip18 tags ('e' and 'p' tags pointing to the reposted event) will be added automatically.\n */\n tags?: string[][]\n\n /**\n * Pass an empty string to NOT include the stringified JSON of the reposted event.\n * Any other content will be ignored and replaced with the stringified JSON of the reposted event.\n * @default Stringified JSON of the reposted event\n */\n content?: ''\n\n created_at: number\n}\n\nexport function finishRepostEvent(\n t: RepostEventTemplate,\n reposted: Event,\n relayUrl: string,\n privateKey: Uint8Array,\n): Event {\n let kind: Repost | GenericRepost\n const tags = [...(t.tags ?? []), ['e', reposted.id, relayUrl], ['p', reposted.pubkey]]\n if (reposted.kind === ShortTextNote) {\n kind = Repost\n } else {\n kind = GenericRepost\n tags.push(['k', String(reposted.kind)])\n }\n\n return finalizeEvent(\n {\n kind,\n tags,\n content: t.content === '' || reposted.tags?.find(tag => tag[0] === '-') ? '' : JSON.stringify(reposted),\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\nexport function getRepostedEventPointer(event: Event): undefined | EventPointer {\n if (![Repost, GenericRepost].includes(event.kind)) {\n return undefined\n }\n\n let lastETag: undefined | string[]\n let lastPTag: undefined | string[]\n\n for (let i = event.tags.length - 1; i >= 0 && (lastETag === undefined || lastPTag === undefined); i--) {\n const tag = event.tags[i]\n if (tag.length >= 2) {\n if (tag[0] === 'e' && lastETag === undefined) {\n lastETag = tag\n } else if (tag[0] === 'p' && lastPTag === undefined) {\n lastPTag = tag\n }\n }\n }\n\n if (lastETag === undefined) {\n return undefined\n }\n\n return {\n id: lastETag[1],\n relays: [lastETag[2], lastPTag?.[2]].filter((x): x is string => typeof x === 'string'),\n author: lastPTag?.[1],\n }\n}\n\nexport type GetRepostedEventOptions = {\n skipVerification?: boolean\n}\n\nexport function getRepostedEvent(event: Event, { skipVerification }: GetRepostedEventOptions = {}): undefined | Event {\n const pointer = getRepostedEventPointer(event)\n\n if (pointer === undefined || event.content === '') {\n return undefined\n }\n\n let repostedEvent: undefined | Event\n\n try {\n repostedEvent = JSON.parse(event.content) as Event\n } catch (error) {\n return undefined\n }\n\n if (repostedEvent.id !== pointer.id) {\n return undefined\n }\n\n if (!skipVerification && !verifyEvent(repostedEvent)) {\n return undefined\n }\n\n return repostedEvent\n}\n", "import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,uBAAwB;AACxB,IAAAA,gBAA2B;;;ACOpB,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,CAAC,QAAiD,eAAe;AAE3E,SAAS,cAAiB,OAAsC;AACrE,MAAI,CAAC,SAAS,KAAK;AAAG,WAAO;AAC7B,MAAI,OAAO,MAAM,SAAS;AAAU,WAAO;AAC3C,MAAI,OAAO,MAAM,YAAY;AAAU,WAAO;AAC9C,MAAI,OAAO,MAAM,eAAe;AAAU,WAAO;AACjD,MAAI,OAAO,MAAM,WAAW;AAAU,WAAO;AAC7C,MAAI,CAAC,MAAM,OAAO,MAAM,gBAAgB;AAAG,WAAO;AAElD,MAAI,CAAC,MAAM,QAAQ,MAAM,IAAI;AAAG,WAAO;AACvC,WAASC,KAAI,GAAGA,KAAI,MAAM,KAAK,QAAQA,MAAK;AAC1C,QAAI,MAAM,MAAM,KAAKA;AACrB,QAAI,CAAC,MAAM,QAAQ,GAAG;AAAG,aAAO;AAChC,aAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,UAAI,OAAO,IAAI,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a,QAAW;AAC1B,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,IAAI,SAAS;AAAA,IACb,QAAQ,CAAC,SAAS,IAAI,WAAW,EAAE,EAAE,OAAO,CAAC,MAAmB,OAAO,MAAM,QAAQ;AAAA,IACrF,QAAQ,WAAW;AAAA,EACrB;AACF;AAMO,SAAS,iBAAiB,OAAc,EAAE,iBAAiB,IAA6B,CAAC,GAAsB;AACpH,QAAM,UAAU,wBAAwB,KAAK;AAE7C,MAAI,YAAY,UAAa,MAAM,YAAY,IAAI;AACjD,WAAO;AAAA,EACT;AAEA,MAAI;AAEJ,MAAI;AACF,oBAAgB,KAAK,MAAM,MAAM,OAAO;AAAA,EAC1C,SAAS,OAAP;AACA,WAAO;AAAA,EACT;AAEA,MAAI,cAAc,OAAO,QAAQ,IAAI;AACnC,WAAO;AAAA,EACT;AAEA,MAAI,CAAC,oBAAoB,CAAC,YAAY,aAAa,GAAG;AACpD,WAAO;AAAA,EACT;AAEA,SAAO;AACT;", + "names": ["import_utils", "i", "i"] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip19.js b/node_modules/nostr-tools/lib/cjs/nip19.js new file mode 100644 index 0000000..6411c3e --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip19.js @@ -0,0 +1,217 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip19.ts +var nip19_exports = {}; +__export(nip19_exports, { + BECH32_REGEX: () => BECH32_REGEX, + Bech32MaxSize: () => Bech32MaxSize, + NostrTypeGuard: () => NostrTypeGuard, + decode: () => decode, + decodeNostrURI: () => decodeNostrURI, + encodeBytes: () => encodeBytes, + naddrEncode: () => naddrEncode, + neventEncode: () => neventEncode, + noteEncode: () => noteEncode, + nprofileEncode: () => nprofileEncode, + npubEncode: () => npubEncode, + nsecEncode: () => nsecEncode +}); +module.exports = __toCommonJS(nip19_exports); +var import_utils2 = require("@noble/hashes/utils"); +var import_base = require("@scure/base"); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// nip19.ts +var NostrTypeGuard = { + isNProfile: (value) => /^nprofile1[a-z\d]+$/.test(value || ""), + isNEvent: (value) => /^nevent1[a-z\d]+$/.test(value || ""), + isNAddr: (value) => /^naddr1[a-z\d]+$/.test(value || ""), + isNSec: (value) => /^nsec1[a-z\d]{58}$/.test(value || ""), + isNPub: (value) => /^npub1[a-z\d]{58}$/.test(value || ""), + isNote: (value) => /^note1[a-z\d]+$/.test(value || ""), + isNcryptsec: (value) => /^ncryptsec1[a-z\d]+$/.test(value || "") +}; +var Bech32MaxSize = 5e3; +var BECH32_REGEX = /[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/; +function integerToUint8Array(number) { + const uint8Array = new Uint8Array(4); + uint8Array[0] = number >> 24 & 255; + uint8Array[1] = number >> 16 & 255; + uint8Array[2] = number >> 8 & 255; + uint8Array[3] = number & 255; + return uint8Array; +} +function decodeNostrURI(nip19code) { + try { + if (nip19code.startsWith("nostr:")) + nip19code = nip19code.substring(6); + return decode(nip19code); + } catch (_err) { + return { type: "invalid", data: null }; + } +} +function decode(code) { + let { prefix, words } = import_base.bech32.decode(code, Bech32MaxSize); + let data = new Uint8Array(import_base.bech32.fromWords(words)); + switch (prefix) { + case "nprofile": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nprofile"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + return { + type: "nprofile", + data: { + pubkey: (0, import_utils2.bytesToHex)(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nevent": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nevent"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + if (tlv[2] && tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (tlv[3] && tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "nevent", + data: { + id: (0, import_utils2.bytesToHex)(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [], + author: tlv[2]?.[0] ? (0, import_utils2.bytesToHex)(tlv[2][0]) : void 0, + kind: tlv[3]?.[0] ? parseInt((0, import_utils2.bytesToHex)(tlv[3][0]), 16) : void 0 + } + }; + } + case "naddr": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for naddr"); + if (!tlv[2]?.[0]) + throw new Error("missing TLV 2 for naddr"); + if (tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (!tlv[3]?.[0]) + throw new Error("missing TLV 3 for naddr"); + if (tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "naddr", + data: { + identifier: utf8Decoder.decode(tlv[0][0]), + pubkey: (0, import_utils2.bytesToHex)(tlv[2][0]), + kind: parseInt((0, import_utils2.bytesToHex)(tlv[3][0]), 16), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nsec": + return { type: prefix, data }; + case "npub": + case "note": + return { type: prefix, data: (0, import_utils2.bytesToHex)(data) }; + default: + throw new Error(`unknown prefix ${prefix}`); + } +} +function parseTLV(data) { + let result = {}; + let rest = data; + while (rest.length > 0) { + let t = rest[0]; + let l = rest[1]; + let v = rest.slice(2, 2 + l); + rest = rest.slice(2 + l); + if (v.length < l) + throw new Error(`not enough data to read on TLV ${t}`); + result[t] = result[t] || []; + result[t].push(v); + } + return result; +} +function nsecEncode(key) { + return encodeBytes("nsec", key); +} +function npubEncode(hex) { + return encodeBytes("npub", (0, import_utils2.hexToBytes)(hex)); +} +function noteEncode(hex) { + return encodeBytes("note", (0, import_utils2.hexToBytes)(hex)); +} +function encodeBech32(prefix, data) { + let words = import_base.bech32.toWords(data); + return import_base.bech32.encode(prefix, words, Bech32MaxSize); +} +function encodeBytes(prefix, bytes) { + return encodeBech32(prefix, bytes); +} +function nprofileEncode(profile) { + let data = encodeTLV({ + 0: [(0, import_utils2.hexToBytes)(profile.pubkey)], + 1: (profile.relays || []).map((url) => utf8Encoder.encode(url)) + }); + return encodeBech32("nprofile", data); +} +function neventEncode(event) { + let kindArray; + if (event.kind !== void 0) { + kindArray = integerToUint8Array(event.kind); + } + let data = encodeTLV({ + 0: [(0, import_utils2.hexToBytes)(event.id)], + 1: (event.relays || []).map((url) => utf8Encoder.encode(url)), + 2: event.author ? [(0, import_utils2.hexToBytes)(event.author)] : [], + 3: kindArray ? [new Uint8Array(kindArray)] : [] + }); + return encodeBech32("nevent", data); +} +function naddrEncode(addr) { + let kind = new ArrayBuffer(4); + new DataView(kind).setUint32(0, addr.kind, false); + let data = encodeTLV({ + 0: [utf8Encoder.encode(addr.identifier)], + 1: (addr.relays || []).map((url) => utf8Encoder.encode(url)), + 2: [(0, import_utils2.hexToBytes)(addr.pubkey)], + 3: [new Uint8Array(kind)] + }); + return encodeBech32("naddr", data); +} +function encodeTLV(tlv) { + let entries = []; + Object.entries(tlv).reverse().forEach(([t, vs]) => { + vs.forEach((v) => { + let entry = new Uint8Array(v.length + 2); + entry.set([parseInt(t)], 0); + entry.set([v.length], 1); + entry.set(v, 2); + entries.push(entry); + }); + }); + return (0, import_utils2.concatBytes)(...entries); +} diff --git a/node_modules/nostr-tools/lib/cjs/nip19.js.map b/node_modules/nostr-tools/lib/cjs/nip19.js.map new file mode 100644 index 0000000..2470854 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip19.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip19.ts", "../../utils.ts"], + "sourcesContent": ["import { bytesToHex, concatBytes, hexToBytes } from '@noble/hashes/utils'\nimport { bech32 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport type NProfile = `nprofile1${string}`\nexport type NEvent = `nevent1${string}`\nexport type NAddr = `naddr1${string}`\nexport type NSec = `nsec1${string}`\nexport type NPub = `npub1${string}`\nexport type Note = `note1${string}`\nexport type Ncryptsec = `ncryptsec1${string}`\n\nexport const NostrTypeGuard = {\n isNProfile: (value?: string | null): value is NProfile => /^nprofile1[a-z\\d]+$/.test(value || ''),\n isNEvent: (value?: string | null): value is NEvent => /^nevent1[a-z\\d]+$/.test(value || ''),\n isNAddr: (value?: string | null): value is NAddr => /^naddr1[a-z\\d]+$/.test(value || ''),\n isNSec: (value?: string | null): value is NSec => /^nsec1[a-z\\d]{58}$/.test(value || ''),\n isNPub: (value?: string | null): value is NPub => /^npub1[a-z\\d]{58}$/.test(value || ''),\n isNote: (value?: string | null): value is Note => /^note1[a-z\\d]+$/.test(value || ''),\n isNcryptsec: (value?: string | null): value is Ncryptsec => /^ncryptsec1[a-z\\d]+$/.test(value || ''),\n}\n\nexport const Bech32MaxSize = 5000\n\n/**\n * Bech32 regex.\n * @see https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32\n */\nexport const BECH32_REGEX = /[\\x21-\\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/\n\nfunction integerToUint8Array(number: number) {\n // Create a Uint8Array with enough space to hold a 32-bit integer (4 bytes).\n const uint8Array = new Uint8Array(4)\n\n // Use bitwise operations to extract the bytes.\n uint8Array[0] = (number >> 24) & 0xff // Most significant byte (MSB)\n uint8Array[1] = (number >> 16) & 0xff\n uint8Array[2] = (number >> 8) & 0xff\n uint8Array[3] = number & 0xff // Least significant byte (LSB)\n\n return uint8Array\n}\n\nexport type ProfilePointer = {\n pubkey: string // hex\n relays?: string[]\n}\n\nexport type EventPointer = {\n id: string // hex\n relays?: string[]\n author?: string\n kind?: number\n}\n\nexport type AddressPointer = {\n identifier: string\n pubkey: string\n kind: number\n relays?: string[]\n}\n\nexport function decodeNostrURI(nip19code: string): ReturnType | { type: 'invalid'; data: null } {\n try {\n if (nip19code.startsWith('nostr:')) nip19code = nip19code.substring(6)\n return decode(nip19code)\n } catch (_err) {\n return { type: 'invalid', data: null }\n }\n}\n\nexport type DecodedNevent = {\n type: 'nevent'\n data: EventPointer\n}\n\nexport type DecodedNprofile = {\n type: 'nprofile'\n data: ProfilePointer\n}\n\nexport type DecodedNaddr = {\n type: 'naddr'\n data: AddressPointer\n}\n\nexport type DecodedNsec = {\n type: 'nsec'\n data: Uint8Array\n}\n\nexport type DecodedNpub = {\n type: 'npub'\n data: string\n}\n\nexport type DecodedNote = {\n type: 'note'\n data: string\n}\n\nexport type DecodedResult = DecodedNevent | DecodedNprofile | DecodedNaddr | DecodedNpub | DecodedNsec | DecodedNote\n\nexport function decode(nip19: NEvent): DecodedNevent\nexport function decode(nip19: NProfile): DecodedNprofile\nexport function decode(nip19: NAddr): DecodedNaddr\nexport function decode(nip19: NSec): DecodedNsec\nexport function decode(nip19: NPub): DecodedNpub\nexport function decode(nip19: Note): DecodedNote\nexport function decode(code: string): DecodedResult\nexport function decode(code: string): DecodedResult {\n let { prefix, words } = bech32.decode(code, Bech32MaxSize)\n let data = new Uint8Array(bech32.fromWords(words))\n\n switch (prefix) {\n case 'nprofile': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nprofile')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n\n return {\n type: 'nprofile',\n data: {\n pubkey: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n case 'nevent': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nevent')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n if (tlv[2] && tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (tlv[3] && tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'nevent',\n data: {\n id: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n author: tlv[2]?.[0] ? bytesToHex(tlv[2][0]) : undefined,\n kind: tlv[3]?.[0] ? parseInt(bytesToHex(tlv[3][0]), 16) : undefined,\n },\n }\n }\n\n case 'naddr': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for naddr')\n if (!tlv[2]?.[0]) throw new Error('missing TLV 2 for naddr')\n if (tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (!tlv[3]?.[0]) throw new Error('missing TLV 3 for naddr')\n if (tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'naddr',\n data: {\n identifier: utf8Decoder.decode(tlv[0][0]),\n pubkey: bytesToHex(tlv[2][0]),\n kind: parseInt(bytesToHex(tlv[3][0]), 16),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n\n case 'nsec':\n return { type: prefix, data }\n\n case 'npub':\n case 'note':\n return { type: prefix, data: bytesToHex(data) }\n\n default:\n throw new Error(`unknown prefix ${prefix}`)\n }\n}\n\ntype TLV = { [t: number]: Uint8Array[] }\n\nfunction parseTLV(data: Uint8Array): TLV {\n let result: TLV = {}\n let rest = data\n while (rest.length > 0) {\n let t = rest[0]\n let l = rest[1]\n let v = rest.slice(2, 2 + l)\n rest = rest.slice(2 + l)\n if (v.length < l) throw new Error(`not enough data to read on TLV ${t}`)\n result[t] = result[t] || []\n result[t].push(v)\n }\n return result\n}\n\nexport function nsecEncode(key: Uint8Array): NSec {\n return encodeBytes('nsec', key)\n}\n\nexport function npubEncode(hex: string): NPub {\n return encodeBytes('npub', hexToBytes(hex))\n}\n\nexport function noteEncode(hex: string): Note {\n return encodeBytes('note', hexToBytes(hex))\n}\n\nfunction encodeBech32(prefix: Prefix, data: Uint8Array): `${Prefix}1${string}` {\n let words = bech32.toWords(data)\n return bech32.encode(prefix, words, Bech32MaxSize) as `${Prefix}1${string}`\n}\n\nexport function encodeBytes(prefix: Prefix, bytes: Uint8Array): `${Prefix}1${string}` {\n return encodeBech32(prefix, bytes)\n}\n\nexport function nprofileEncode(profile: ProfilePointer): NProfile {\n let data = encodeTLV({\n 0: [hexToBytes(profile.pubkey)],\n 1: (profile.relays || []).map(url => utf8Encoder.encode(url)),\n })\n return encodeBech32('nprofile', data)\n}\n\nexport function neventEncode(event: EventPointer): NEvent {\n let kindArray\n if (event.kind !== undefined) {\n kindArray = integerToUint8Array(event.kind)\n }\n\n let data = encodeTLV({\n 0: [hexToBytes(event.id)],\n 1: (event.relays || []).map(url => utf8Encoder.encode(url)),\n 2: event.author ? [hexToBytes(event.author)] : [],\n 3: kindArray ? [new Uint8Array(kindArray)] : [],\n })\n\n return encodeBech32('nevent', data)\n}\n\nexport function naddrEncode(addr: AddressPointer): NAddr {\n let kind = new ArrayBuffer(4)\n new DataView(kind).setUint32(0, addr.kind, false)\n\n let data = encodeTLV({\n 0: [utf8Encoder.encode(addr.identifier)],\n 1: (addr.relays || []).map(url => utf8Encoder.encode(url)),\n 2: [hexToBytes(addr.pubkey)],\n 3: [new Uint8Array(kind)],\n })\n return encodeBech32('naddr', data)\n}\n\nfunction encodeTLV(tlv: TLV): Uint8Array {\n let entries: Uint8Array[] = []\n\n Object.entries(tlv)\n .reverse()\n .forEach(([t, vs]) => {\n vs.forEach(v => {\n let entry = new Uint8Array(v.length + 2)\n entry.set([parseInt(t)], 0)\n entry.set([v.length], 1)\n entry.set(v, 2)\n entries.push(entry)\n })\n })\n\n return concatBytes(...entries)\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,gBAAoD;AACpD,kBAAuB;;;ACIvB,mBAAuC;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;;;ADUjD,IAAM,iBAAiB;AAAA,EAC5B,YAAY,CAAC,UAA6C,sBAAsB,KAAK,SAAS,EAAE;AAAA,EAChG,UAAU,CAAC,UAA2C,oBAAoB,KAAK,SAAS,EAAE;AAAA,EAC1F,SAAS,CAAC,UAA0C,mBAAmB,KAAK,SAAS,EAAE;AAAA,EACvF,QAAQ,CAAC,UAAyC,qBAAqB,KAAK,SAAS,EAAE;AAAA,EACvF,QAAQ,CAAC,UAAyC,qBAAqB,KAAK,SAAS,EAAE;AAAA,EACvF,QAAQ,CAAC,UAAyC,kBAAkB,KAAK,SAAS,EAAE;AAAA,EACpF,aAAa,CAAC,UAA8C,uBAAuB,KAAK,SAAS,EAAE;AACrG;AAEO,IAAM,gBAAgB;AAMtB,IAAM,eAAe;AAE5B,SAAS,oBAAoB,QA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aAAO,2BAAY,GAAG,OAAO;AAC/B;", + "names": ["import_utils"] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip21.js b/node_modules/nostr-tools/lib/cjs/nip21.js new file mode 100644 index 0000000..70c88c1 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip21.js @@ -0,0 +1,140 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip21.ts +var nip21_exports = {}; +__export(nip21_exports, { + NOSTR_URI_REGEX: () => NOSTR_URI_REGEX, + parse: () => parse, + test: () => test +}); +module.exports = __toCommonJS(nip21_exports); + +// nip19.ts +var import_utils2 = require("@noble/hashes/utils"); +var import_base = require("@scure/base"); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// nip19.ts +var Bech32MaxSize = 5e3; +var BECH32_REGEX = /[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/; +function decode(code) { + let { prefix, words } = import_base.bech32.decode(code, Bech32MaxSize); + let data = new Uint8Array(import_base.bech32.fromWords(words)); + switch (prefix) { + case "nprofile": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nprofile"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + return { + type: "nprofile", + data: { + pubkey: (0, import_utils2.bytesToHex)(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nevent": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nevent"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + if (tlv[2] && tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (tlv[3] && tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "nevent", + data: { + id: (0, import_utils2.bytesToHex)(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [], + author: tlv[2]?.[0] ? (0, import_utils2.bytesToHex)(tlv[2][0]) : void 0, + kind: tlv[3]?.[0] ? parseInt((0, import_utils2.bytesToHex)(tlv[3][0]), 16) : void 0 + } + }; + } + case "naddr": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for naddr"); + if (!tlv[2]?.[0]) + throw new Error("missing TLV 2 for naddr"); + if (tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (!tlv[3]?.[0]) + throw new Error("missing TLV 3 for naddr"); + if (tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "naddr", + data: { + identifier: utf8Decoder.decode(tlv[0][0]), + pubkey: (0, import_utils2.bytesToHex)(tlv[2][0]), + kind: parseInt((0, import_utils2.bytesToHex)(tlv[3][0]), 16), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nsec": + return { type: prefix, data }; + case "npub": + case "note": + return { type: prefix, data: (0, import_utils2.bytesToHex)(data) }; + default: + throw new Error(`unknown prefix ${prefix}`); + } +} +function parseTLV(data) { + let result = {}; + let rest = data; + while (rest.length > 0) { + let t = rest[0]; + let l = rest[1]; + let v = rest.slice(2, 2 + l); + rest = rest.slice(2 + l); + if (v.length < l) + throw new Error(`not enough data to read on TLV ${t}`); + result[t] = result[t] || []; + result[t].push(v); + } + return result; +} + +// nip21.ts +var NOSTR_URI_REGEX = new RegExp(`nostr:(${BECH32_REGEX.source})`); +function test(value) { + return typeof value === "string" && new RegExp(`^${NOSTR_URI_REGEX.source}$`).test(value); +} +function parse(uri) { + const match = uri.match(new RegExp(`^${NOSTR_URI_REGEX.source}$`)); + if (!match) + throw new Error(`Invalid Nostr URI: ${uri}`); + return { + uri: match[0], + value: match[1], + decoded: decode(match[1]) + }; +} diff --git a/node_modules/nostr-tools/lib/cjs/nip21.js.map b/node_modules/nostr-tools/lib/cjs/nip21.js.map new file mode 100644 index 0000000..8432ec3 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip21.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip21.ts", "../../nip19.ts", "../../utils.ts"], + "sourcesContent": ["import { AddressPointer, BECH32_REGEX, decode, EventPointer, ProfilePointer } from './nip19.ts'\n\n/** Nostr URI regex, eg `nostr:npub1...` */\nexport const NOSTR_URI_REGEX: RegExp = new RegExp(`nostr:(${BECH32_REGEX.source})`)\n\n/** Test whether the value is a Nostr URI. */\nexport function test(value: unknown): value is `nostr:${string}` {\n return typeof value === 'string' && new RegExp(`^${NOSTR_URI_REGEX.source}$`).test(value)\n}\n\n/** Parsed Nostr URI data. */\nexport interface NostrURI {\n /** Full URI including the `nostr:` protocol. */\n uri: `nostr:${string}`\n /** The bech32-encoded data (eg `npub1...`). */\n value: string\n /** Decoded bech32 string, according to NIP-19. */\n decoded:\n | {\n type: 'nevent'\n data: EventPointer\n }\n | {\n type: 'nprofile'\n data: ProfilePointer\n }\n | {\n type: 'naddr'\n data: AddressPointer\n }\n | {\n type: 'npub'\n data: string\n }\n | {\n type: 'nsec'\n data: Uint8Array\n }\n | {\n type: 'note'\n data: string\n }\n}\n\n/** Parse and decode a Nostr URI. */\nexport function parse(uri: string): NostrURI {\n const match = uri.match(new RegExp(`^${NOSTR_URI_REGEX.source}$`))\n if (!match) throw new Error(`Invalid Nostr URI: ${uri}`)\n return {\n uri: match[0] as `nostr:${string}`,\n value: match[1],\n decoded: decode(match[1]),\n }\n}\n", "import { bytesToHex, concatBytes, hexToBytes } from '@noble/hashes/utils'\nimport { bech32 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport type NProfile = `nprofile1${string}`\nexport type NEvent = `nevent1${string}`\nexport type NAddr = `naddr1${string}`\nexport type NSec = `nsec1${string}`\nexport type NPub = `npub1${string}`\nexport type Note = `note1${string}`\nexport type Ncryptsec = `ncryptsec1${string}`\n\nexport const NostrTypeGuard = {\n isNProfile: (value?: string | null): value is NProfile => /^nprofile1[a-z\\d]+$/.test(value || ''),\n isNEvent: (value?: string | null): value is NEvent => /^nevent1[a-z\\d]+$/.test(value || ''),\n isNAddr: (value?: string | null): value is NAddr => /^naddr1[a-z\\d]+$/.test(value || ''),\n isNSec: (value?: string | null): value is NSec => /^nsec1[a-z\\d]{58}$/.test(value || ''),\n isNPub: (value?: string | null): value is NPub => /^npub1[a-z\\d]{58}$/.test(value || ''),\n isNote: (value?: string | null): value is Note => /^note1[a-z\\d]+$/.test(value || ''),\n isNcryptsec: (value?: string | null): value is Ncryptsec => /^ncryptsec1[a-z\\d]+$/.test(value || ''),\n}\n\nexport const Bech32MaxSize = 5000\n\n/**\n * Bech32 regex.\n * @see https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32\n */\nexport const BECH32_REGEX = /[\\x21-\\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/\n\nfunction integerToUint8Array(number: number) {\n // Create a Uint8Array with enough space to hold a 32-bit integer (4 bytes).\n const uint8Array = new Uint8Array(4)\n\n // Use bitwise operations to extract the bytes.\n uint8Array[0] = (number >> 24) & 0xff // Most significant byte (MSB)\n uint8Array[1] = (number >> 16) & 0xff\n uint8Array[2] = (number >> 8) & 0xff\n uint8Array[3] = number & 0xff // Least significant byte (LSB)\n\n return uint8Array\n}\n\nexport type ProfilePointer = {\n pubkey: string // hex\n relays?: string[]\n}\n\nexport type EventPointer = {\n id: string // hex\n relays?: string[]\n author?: string\n kind?: number\n}\n\nexport type AddressPointer = {\n identifier: string\n pubkey: string\n kind: number\n relays?: string[]\n}\n\nexport function decodeNostrURI(nip19code: string): ReturnType | { type: 'invalid'; data: null } {\n try {\n if (nip19code.startsWith('nostr:')) nip19code = nip19code.substring(6)\n return decode(nip19code)\n } catch (_err) {\n return { type: 'invalid', data: null }\n }\n}\n\nexport type DecodedNevent = {\n type: 'nevent'\n data: EventPointer\n}\n\nexport type DecodedNprofile = {\n type: 'nprofile'\n data: ProfilePointer\n}\n\nexport type DecodedNaddr = {\n type: 'naddr'\n data: AddressPointer\n}\n\nexport type DecodedNsec = {\n type: 'nsec'\n data: Uint8Array\n}\n\nexport type DecodedNpub = {\n type: 'npub'\n data: string\n}\n\nexport type DecodedNote = {\n type: 'note'\n data: string\n}\n\nexport type DecodedResult = DecodedNevent | DecodedNprofile | DecodedNaddr | DecodedNpub | DecodedNsec | DecodedNote\n\nexport function decode(nip19: NEvent): DecodedNevent\nexport function decode(nip19: NProfile): DecodedNprofile\nexport function decode(nip19: NAddr): DecodedNaddr\nexport function decode(nip19: NSec): DecodedNsec\nexport function decode(nip19: NPub): DecodedNpub\nexport function decode(nip19: Note): DecodedNote\nexport function decode(code: string): DecodedResult\nexport function decode(code: string): DecodedResult {\n let { prefix, words } = bech32.decode(code, Bech32MaxSize)\n let data = new Uint8Array(bech32.fromWords(words))\n\n switch (prefix) {\n case 'nprofile': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nprofile')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n\n return {\n type: 'nprofile',\n data: {\n pubkey: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n case 'nevent': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nevent')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n if (tlv[2] && tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (tlv[3] && tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'nevent',\n data: {\n id: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n author: tlv[2]?.[0] ? bytesToHex(tlv[2][0]) : undefined,\n kind: tlv[3]?.[0] ? parseInt(bytesToHex(tlv[3][0]), 16) : undefined,\n },\n }\n }\n\n case 'naddr': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for naddr')\n if (!tlv[2]?.[0]) throw new Error('missing TLV 2 for naddr')\n if (tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (!tlv[3]?.[0]) throw new Error('missing TLV 3 for naddr')\n if (tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'naddr',\n data: {\n identifier: utf8Decoder.decode(tlv[0][0]),\n pubkey: bytesToHex(tlv[2][0]),\n kind: parseInt(bytesToHex(tlv[3][0]), 16),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n\n case 'nsec':\n return { type: prefix, data }\n\n case 'npub':\n case 'note':\n return { type: prefix, data: bytesToHex(data) }\n\n default:\n throw new Error(`unknown prefix ${prefix}`)\n }\n}\n\ntype TLV = { [t: number]: Uint8Array[] }\n\nfunction parseTLV(data: Uint8Array): TLV {\n let result: TLV = {}\n let rest = data\n while (rest.length > 0) {\n let t = rest[0]\n let l = rest[1]\n let v = rest.slice(2, 2 + l)\n rest = rest.slice(2 + l)\n if (v.length < l) throw new Error(`not enough data to read on TLV ${t}`)\n result[t] = result[t] || []\n result[t].push(v)\n }\n return result\n}\n\nexport function nsecEncode(key: Uint8Array): NSec {\n return encodeBytes('nsec', key)\n}\n\nexport function npubEncode(hex: string): NPub {\n return encodeBytes('npub', hexToBytes(hex))\n}\n\nexport function noteEncode(hex: string): Note {\n return encodeBytes('note', hexToBytes(hex))\n}\n\nfunction encodeBech32(prefix: Prefix, data: Uint8Array): `${Prefix}1${string}` {\n let words = bech32.toWords(data)\n return bech32.encode(prefix, words, Bech32MaxSize) as `${Prefix}1${string}`\n}\n\nexport function encodeBytes(prefix: Prefix, bytes: Uint8Array): `${Prefix}1${string}` {\n return encodeBech32(prefix, bytes)\n}\n\nexport function nprofileEncode(profile: ProfilePointer): NProfile {\n let data = encodeTLV({\n 0: [hexToBytes(profile.pubkey)],\n 1: (profile.relays || []).map(url => utf8Encoder.encode(url)),\n })\n return encodeBech32('nprofile', data)\n}\n\nexport function neventEncode(event: EventPointer): NEvent {\n let kindArray\n if (event.kind !== undefined) {\n kindArray = integerToUint8Array(event.kind)\n }\n\n let data = encodeTLV({\n 0: [hexToBytes(event.id)],\n 1: (event.relays || []).map(url => utf8Encoder.encode(url)),\n 2: event.author ? [hexToBytes(event.author)] : [],\n 3: kindArray ? [new Uint8Array(kindArray)] : [],\n })\n\n return encodeBech32('nevent', data)\n}\n\nexport function naddrEncode(addr: AddressPointer): NAddr {\n let kind = new ArrayBuffer(4)\n new DataView(kind).setUint32(0, addr.kind, false)\n\n let data = encodeTLV({\n 0: [utf8Encoder.encode(addr.identifier)],\n 1: (addr.relays || []).map(url => utf8Encoder.encode(url)),\n 2: [hexToBytes(addr.pubkey)],\n 3: [new Uint8Array(kind)],\n })\n return encodeBech32('naddr', data)\n}\n\nfunction encodeTLV(tlv: TLV): Uint8Array {\n let entries: Uint8Array[] = []\n\n Object.entries(tlv)\n .reverse()\n .forEach(([t, vs]) => {\n vs.forEach(v => {\n let entry = new Uint8Array(v.length + 2)\n entry.set([parseInt(t)], 0)\n entry.set([v.length], 1)\n entry.set(v, 2)\n entries.push(entry)\n })\n })\n\n return concatBytes(...entries)\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,gBAAoD;AACpD,kBAAuB;;;ACIvB,mBAAuC;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;;;ADoBjD,IAAM,gBAAgB;AAMtB,IAAM,eAAe;AAkFrB,SAAS,OAAO,MAA6B;AAClD,MAAI,EAAE,QAAQ,MAAM,IAAI,mBAAO,OAAO,MAAM,aAAa;AACzD,MAAI,OAAO,IAAI,WAAW,mBAAO,UAAU,KAAK,CAAC;AAEjD,UAAQ,QAAQ;AAAA,IACd,KAAK,YAAY;AACf,UAAI,MAAM,SAAS,IAAI;AACvB,UAAI,CAAC,IAAI,KAAK;AAAI,cAAM,IAAI,MAAM,4BAA4B;AAC9D,UAAI,IAAI,GAAG,GAAG,WAAW;AAAI,cAAM,IAAI,MAAM,0BAA0B;AAEvE,aAAO;AAAA,QACL,MAAM;AAAA,QACN,MAAM;AAAA,UACJ,YAAQ,0BAAW,IAAI,GAAG,EAAE;AAAA,UAC5B,QAAQ,IAAI,KAAK,IAAI,GAAG,IAAI,OAAK,YAAY,OAAO,CAAC,CAAC,IAAI,CAAC;AAAA,QAC7D;AAAA,MACF;AAAA,IACF;AAAA,IACA,KAAK,UAAU;AACb,UAAI,MAAM,SAAS,IAAI;AACvB,UAAI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ostr-tools/lib/cjs/nip25.js new file mode 100644 index 0000000..a76e660 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip25.js @@ -0,0 +1,159 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip25.ts +var nip25_exports = {}; +__export(nip25_exports, { + finishReactionEvent: () => finishReactionEvent, + getReactedEventPointer: () => getReactedEventPointer +}); +module.exports = __toCommonJS(nip25_exports); + +// pure.ts +var import_secp256k1 = require("@noble/curves/secp256k1"); +var import_utils2 = require("@noble/hashes/utils"); + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +var import_sha256 = require("@noble/hashes/sha256"); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// pure.ts +var JS = class { + generateSecretKey() { + return import_secp256k1.schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = import_secp256k1.schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = (0, import_sha256.sha256)(utf8Encoder.encode(serializeEvent(event))); + return (0, import_utils2.bytesToHex)(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// kinds.ts +var Reaction = 7; + +// nip25.ts +function finishReactionEvent(t, reacted, privateKey) { + const inheritedTags = reacted.tags.filter((tag) => tag.length >= 2 && (tag[0] === "e" || tag[0] === "p")); + return finalizeEvent( + { + ...t, + kind: Reaction, + tags: [...t.tags ?? [], ...inheritedTags, ["e", reacted.id], ["p", reacted.pubkey]], + content: t.content ?? "+" + }, + privateKey + ); +} +function getReactedEventPointer(event) { + if (event.kind !== Reaction) { + return void 0; + } + let lastETag; + let lastPTag; + for (let i2 = event.tags.length - 1; i2 >= 0 && (lastETag === void 0 || lastPTag === void 0); i2--) { + const tag = event.tags[i2]; + if (tag.length >= 2) { + if (tag[0] === "e" && lastETag === void 0) { + lastETag = tag; + } else if (tag[0] === "p" && lastPTag === void 0) { + lastPTag = tag; + } + } + } + if (lastETag === void 0 || lastPTag === void 0) { + return void 0; + } + return { + id: lastETag[1], + relays: [lastETag[2], lastPTag[2]].filter((x) => x !== void 0), + author: lastPTag[1] + }; +} diff --git a/node_modules/nostr-tools/lib/cjs/nip25.js.map b/node_modules/nostr-tools/lib/cjs/nip25.js.map new file mode 100644 index 0000000..2aea8f5 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip25.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip25.ts", "../../pure.ts", "../../core.ts", "../../utils.ts", "../../kinds.ts"], + "sourcesContent": ["import { Event, finalizeEvent } from './pure.ts'\nimport { Reaction } from './kinds.ts'\n\nimport type { EventPointer } from './nip19.ts'\n\nexport type ReactionEventTemplate = {\n /**\n * Pass only non-nip25 tags if you have to. Nip25 tags ('e' and 'p' tags from reacted event) will be added automatically.\n */\n tags?: string[][]\n\n /**\n * @default '+'\n */\n content?: string\n\n created_at: number\n}\n\nexport function finishReactionEvent(t: ReactionEventTemplate, reacted: Event, privateKey: Uint8Array): Event {\n const inheritedTags = reacted.tags.filter(tag => tag.length >= 2 && (tag[0] === 'e' || tag[0] === 'p'))\n\n return finalizeEvent(\n {\n ...t,\n kind: Reaction,\n tags: [...(t.tags ?? []), ...inheritedTags, ['e', reacted.id], ['p', reacted.pubkey]],\n content: t.content ?? '+',\n },\n privateKey,\n )\n}\n\nexport function getReactedEventPointer(event: Event): undefined | EventPointer {\n if (event.kind !== Reaction) {\n return undefined\n }\n\n let lastETag: undefined | string[]\n let lastPTag: undefined | string[]\n\n for (let i = event.tags.length - 1; i >= 0 && (lastETag === undefined || lastPTag === undefined); i--) {\n const tag = event.tags[i]\n if (tag.length >= 2) {\n if (tag[0] === 'e' && lastETag === undefined) {\n lastETag = tag\n } else if (tag[0] === 'p' && lastPTag === undefined) {\n lastPTag = tag\n }\n }\n }\n\n if (lastETag === undefined || lastPTag === undefined) {\n return undefined\n }\n\n return {\n id: lastETag[1],\n relays: [lastETag[2], lastPTag[2]].filter(x => x !== undefined),\n author: lastPTag[1],\n }\n}\n", "import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,uBAAwB;AACxB,IAAAA,gBAA2B;;;ACOpB,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,CAAC,QAAiD,eAAe;AAE3E,SAAS,cAAiB,OAAsC;AACrE,MAAI,CAAC,SAAS,KAAK;AAAG,WAAO;AAC7B,MAAI,OAAO,MAAM,SAAS;AAAU,WAAO;AAC3C,MAAI,OAAO,MAAM,YAAY;AAAU,WAAO;AAC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KA;AACvB,QAAI,IAAI,UAAU,GAAG;AACnB,UAAI,IAAI,OAAO,OAAO,aAAa,QAAW;AAC5C,mBAAW;AAAA,MACb,WAAW,IAAI,OAAO,OAAO,aAAa,QAAW;AACnD,mBAAW;AAAA,MACb;AAAA,IACF;AAAA,EACF;AAEA,MAAI,aAAa,UAAa,aAAa,QAAW;AACpD,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,IAAI,SAAS;AAAA,IACb,QAAQ,CAAC,SAAS,IAAI,SAAS,EAAE,EAAE,OAAO,OAAK,MAAM,MAAS;AAAA,IAC9D,QAAQ,SAAS;AAAA,EACnB;AACF;", + "names": ["import_utils", "i", "i"] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip27.js b/node_modules/nostr-tools/lib/cjs/nip27.js new file mode 100644 index 0000000..436aeec --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip27.js @@ -0,0 +1,229 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip27.ts +var nip27_exports = {}; +__export(nip27_exports, { + parse: () => parse +}); +module.exports = __toCommonJS(nip27_exports); + +// nip19.ts +var import_utils2 = require("@noble/hashes/utils"); +var import_base = require("@scure/base"); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// nip19.ts +var Bech32MaxSize = 5e3; +function decode(code) { + let { prefix, words } = import_base.bech32.decode(code, Bech32MaxSize); + let data = new Uint8Array(import_base.bech32.fromWords(words)); + switch (prefix) { + case "nprofile": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nprofile"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + return { + type: "nprofile", + data: { + pubkey: (0, import_utils2.bytesToHex)(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nevent": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nevent"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + if (tlv[2] && tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (tlv[3] && tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "nevent", + data: { + id: (0, import_utils2.bytesToHex)(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [], + author: tlv[2]?.[0] ? (0, import_utils2.bytesToHex)(tlv[2][0]) : void 0, + kind: tlv[3]?.[0] ? parseInt((0, import_utils2.bytesToHex)(tlv[3][0]), 16) : void 0 + } + }; + } + case "naddr": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for naddr"); + if (!tlv[2]?.[0]) + throw new Error("missing TLV 2 for naddr"); + if (tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (!tlv[3]?.[0]) + throw new Error("missing TLV 3 for naddr"); + if (tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "naddr", + data: { + identifier: utf8Decoder.decode(tlv[0][0]), + pubkey: (0, import_utils2.bytesToHex)(tlv[2][0]), + kind: parseInt((0, import_utils2.bytesToHex)(tlv[3][0]), 16), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nsec": + return { type: prefix, data }; + case "npub": + case "note": + return { type: prefix, data: (0, import_utils2.bytesToHex)(data) }; + default: + throw new Error(`unknown prefix ${prefix}`); + } +} +function parseTLV(data) { + let result = {}; + let rest = data; + while (rest.length > 0) { + let t = rest[0]; + let l = rest[1]; + let v = rest.slice(2, 2 + l); + rest = rest.slice(2 + l); + if (v.length < l) + throw new Error(`not enough data to read on TLV ${t}`); + result[t] = result[t] || []; + result[t].push(v); + } + return result; +} + +// nip27.ts +var noCharacter = /\W/m; +var noURLCharacter = /\W |\W$|$|,| /m; +function* parse(content) { + const max = content.length; + let prevIndex = 0; + let index = 0; + while (index < max) { + let u = content.indexOf(":", index); + if (u === -1) { + break; + } + if (content.substring(u - 5, u) === "nostr") { + const m = content.substring(u + 60).match(noCharacter); + const end = m ? u + 60 + m.index : max; + try { + let pointer; + let { data, type } = decode(content.substring(u + 1, end)); + switch (type) { + case "npub": + pointer = { pubkey: data }; + break; + case "nsec": + case "note": + index = end + 1; + continue; + default: + pointer = data; + } + if (prevIndex !== u - 5) { + yield { type: "text", text: content.substring(prevIndex, u - 5) }; + } + yield { type: "reference", pointer }; + index = end; + prevIndex = index; + continue; + } catch (_err) { + index = u + 1; + continue; + } + } else if (content.substring(u - 5, u) === "https" || content.substring(u - 4, u) === "http") { + const m = content.substring(u + 4).match(noURLCharacter); + const end = m ? u + 4 + m.index : max; + const prefixLen = content[u - 1] === "s" ? 5 : 4; + try { + let url = new URL(content.substring(u - prefixLen, end)); + if (url.hostname.indexOf(".") === -1) { + throw new Error("invalid url"); + } + if (prevIndex !== u - prefixLen) { + yield { type: "text", text: content.substring(prevIndex, u - prefixLen) }; + } + if (url.pathname.endsWith(".png") || url.pathname.endsWith(".jpg") || url.pathname.endsWith(".jpeg") || url.pathname.endsWith(".gif") || url.pathname.endsWith(".webp")) { + yield { type: "image", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } + if (url.pathname.endsWith(".mp4") || url.pathname.endsWith(".avi") || url.pathname.endsWith(".webm") || url.pathname.endsWith(".mkv")) { + yield { type: "video", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } + if (url.pathname.endsWith(".mp3") || url.pathname.endsWith(".aac") || url.pathname.endsWith(".ogg") || url.pathname.endsWith(".opus")) { + yield { type: "audio", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } + yield { type: "url", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } catch (_err) { + index = end + 1; + continue; + } + } else if (content.substring(u - 3, u) === "wss" || content.substring(u - 2, u) === "ws") { + const m = content.substring(u + 4).match(noURLCharacter); + const end = m ? u + 4 + m.index : max; + const prefixLen = content[u - 1] === "s" ? 3 : 2; + try { + let url = new URL(content.substring(u - prefixLen, end)); + if (url.hostname.indexOf(".") === -1) { + throw new Error("invalid ws url"); + } + if (prevIndex !== u - prefixLen) { + yield { type: "text", text: content.substring(prevIndex, u - prefixLen) }; + } + yield { type: "relay", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } catch (_err) { + index = end + 1; + continue; + } + } else { + index = u + 1; + continue; + } + } + if (prevIndex !== max) { + yield { type: "text", text: content.substring(prevIndex) }; + } +} diff --git a/node_modules/nostr-tools/lib/cjs/nip27.js.map b/node_modules/nostr-tools/lib/cjs/nip27.js.map new file mode 100644 index 0000000..55cb146 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip27.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip27.ts", "../../nip19.ts", "../../utils.ts"], + "sourcesContent": ["import { AddressPointer, EventPointer, ProfilePointer, decode } from './nip19.ts'\n\nexport type Block =\n | {\n type: 'text'\n text: string\n }\n | {\n type: 'reference'\n pointer: ProfilePointer | AddressPointer | EventPointer\n }\n | {\n type: 'url'\n url: string\n }\n | {\n type: 'relay'\n url: string\n }\n | {\n type: 'image'\n url: string\n }\n | {\n type: 'video'\n url: string\n }\n | {\n type: 'audio'\n url: string\n }\n\nconst noCharacter = /\\W/m\nconst noURLCharacter = /\\W |\\W$|$|,| /m\n\nexport function* parse(content: string): Iterable {\n const max = content.length\n let prevIndex = 0\n let index = 0\n while (index < max) {\n let u = content.indexOf(':', index)\n if (u === -1) {\n // reached end\n break\n }\n\n if (content.substring(u - 5, u) === 'nostr') {\n const m = content.substring(u + 60).match(noCharacter)\n const end = m ? u + 60 + m.index! : max\n try {\n let pointer: ProfilePointer | AddressPointer | EventPointer\n let { data, type } = decode(content.substring(u + 1, end))\n\n switch (type) {\n case 'npub':\n pointer = { pubkey: data } as ProfilePointer\n break\n case 'nsec':\n case 'note':\n // ignore this, treat it as not a valid uri\n index = end + 1\n continue\n default:\n pointer = data as any\n }\n\n if (prevIndex !== u - 5) {\n yield { type: 'text', text: content.substring(prevIndex, u - 5) }\n }\n yield { type: 'reference', pointer }\n index = end\n prevIndex = index\n continue\n } catch (_err) {\n // ignore this, not a valid nostr uri\n index = u + 1\n continue\n }\n } else if (content.substring(u - 5, u) === 'https' || content.substring(u - 4, u) === 'http') {\n const m = content.substring(u + 4).match(noURLCharacter)\n const end = m ? u + 4 + m.index! : max\n const prefixLen = content[u - 1] === 's' ? 5 : 4\n try {\n let url = new URL(content.substring(u - prefixLen, end))\n if (url.hostname.indexOf('.') === -1) {\n throw new Error('invalid url')\n }\n\n if (prevIndex !== u - prefixLen) {\n yield { type: 'text', text: content.substring(prevIndex, u - prefixLen) }\n }\n\n if (\n url.pathname.endsWith('.png') ||\n url.pathname.endsWith('.jpg') ||\n url.pathname.endsWith('.jpeg') ||\n url.pathname.endsWith('.gif') ||\n url.pathname.endsWith('.webp')\n ) {\n yield { type: 'image', url: url.toString() }\n index = end\n prevIndex = index\n continue\n }\n if (\n url.pathname.endsWith('.mp4') ||\n url.pathname.endsWith('.avi') ||\n url.pathname.endsWith('.webm') ||\n url.pathname.endsWith('.mkv')\n ) {\n yield { type: 'video', url: url.toString() }\n index = end\n prevIndex = index\n continue\n }\n if (\n url.pathname.endsWith('.mp3') ||\n url.pathname.endsWith('.aac') ||\n url.pathname.endsWith('.ogg') ||\n url.pathname.endsWith('.opus')\n ) {\n yield { type: 'audio', url: url.toString() }\n index = end\n prevIndex = index\n continue\n }\n\n yield { type: 'url', url: url.toString() }\n index = end\n prevIndex = index\n continue\n } catch (_err) {\n // ignore this, not a valid url\n index = end + 1\n continue\n }\n } else if (content.substring(u - 3, u) === 'wss' || content.substring(u - 2, u) === 'ws') {\n const m = content.substring(u + 4).match(noURLCharacter)\n const end = m ? u + 4 + m.index! : max\n const prefixLen = content[u - 1] === 's' ? 3 : 2\n try {\n let url = new URL(content.substring(u - prefixLen, end))\n if (url.hostname.indexOf('.') === -1) {\n throw new Error('invalid ws url')\n }\n\n if (prevIndex !== u - prefixLen) {\n yield { type: 'text', text: content.substring(prevIndex, u - prefixLen) }\n }\n yield { type: 'relay', url: url.toString() }\n index = end\n prevIndex = index\n continue\n } catch (_err) {\n // ignore this, not a valid url\n index = end + 1\n continue\n }\n } else {\n // ignore this, it is nothing\n index = u + 1\n continue\n }\n }\n\n if (prevIndex !== max) {\n yield { type: 'text', text: content.substring(prevIndex) }\n }\n}\n", "import { bytesToHex, concatBytes, hexToBytes } from '@noble/hashes/utils'\nimport { bech32 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport type NProfile = `nprofile1${string}`\nexport type NEvent = `nevent1${string}`\nexport type NAddr = `naddr1${string}`\nexport type NSec = `nsec1${string}`\nexport type NPub = `npub1${string}`\nexport type Note = `note1${string}`\nexport type Ncryptsec = `ncryptsec1${string}`\n\nexport const NostrTypeGuard = {\n isNProfile: (value?: string | null): value is NProfile => /^nprofile1[a-z\\d]+$/.test(value || ''),\n isNEvent: (value?: string | null): value is NEvent => /^nevent1[a-z\\d]+$/.test(value || ''),\n isNAddr: (value?: string | null): value is NAddr => /^naddr1[a-z\\d]+$/.test(value || ''),\n isNSec: (value?: string | null): value is NSec => /^nsec1[a-z\\d]{58}$/.test(value || ''),\n isNPub: (value?: string | null): value is NPub => /^npub1[a-z\\d]{58}$/.test(value || ''),\n isNote: (value?: string | null): value is Note => /^note1[a-z\\d]+$/.test(value || ''),\n isNcryptsec: (value?: string | null): value is Ncryptsec => /^ncryptsec1[a-z\\d]+$/.test(value || ''),\n}\n\nexport const Bech32MaxSize = 5000\n\n/**\n * Bech32 regex.\n * @see https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32\n */\nexport const BECH32_REGEX = /[\\x21-\\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/\n\nfunction integerToUint8Array(number: number) {\n // Create a Uint8Array with enough space to hold a 32-bit integer (4 bytes).\n const uint8Array = new Uint8Array(4)\n\n // Use bitwise operations to extract the bytes.\n uint8Array[0] = (number >> 24) & 0xff // Most significant byte (MSB)\n uint8Array[1] = (number >> 16) & 0xff\n uint8Array[2] = (number >> 8) & 0xff\n uint8Array[3] = number & 0xff // Least significant byte (LSB)\n\n return uint8Array\n}\n\nexport type ProfilePointer = {\n pubkey: string // hex\n relays?: string[]\n}\n\nexport type EventPointer = {\n id: string // hex\n relays?: string[]\n author?: string\n kind?: number\n}\n\nexport type AddressPointer = {\n identifier: string\n pubkey: string\n kind: number\n relays?: string[]\n}\n\nexport function decodeNostrURI(nip19code: string): ReturnType | { type: 'invalid'; data: null } {\n try {\n if (nip19code.startsWith('nostr:')) nip19code = nip19code.substring(6)\n return decode(nip19code)\n } catch (_err) {\n return { type: 'invalid', data: null }\n }\n}\n\nexport type DecodedNevent = {\n type: 'nevent'\n data: EventPointer\n}\n\nexport type DecodedNprofile = {\n type: 'nprofile'\n data: ProfilePointer\n}\n\nexport type DecodedNaddr = {\n type: 'naddr'\n data: AddressPointer\n}\n\nexport type DecodedNsec = {\n type: 'nsec'\n data: Uint8Array\n}\n\nexport type DecodedNpub = {\n type: 'npub'\n data: string\n}\n\nexport type DecodedNote = {\n type: 'note'\n data: string\n}\n\nexport type DecodedResult = DecodedNevent | DecodedNprofile | DecodedNaddr | DecodedNpub | DecodedNsec | DecodedNote\n\nexport function decode(nip19: NEvent): DecodedNevent\nexport function decode(nip19: NProfile): DecodedNprofile\nexport function decode(nip19: NAddr): DecodedNaddr\nexport function decode(nip19: NSec): DecodedNsec\nexport function decode(nip19: NPub): DecodedNpub\nexport function decode(nip19: Note): DecodedNote\nexport function decode(code: string): DecodedResult\nexport function decode(code: string): DecodedResult {\n let { prefix, words } = bech32.decode(code, Bech32MaxSize)\n let data = new Uint8Array(bech32.fromWords(words))\n\n switch (prefix) {\n case 'nprofile': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nprofile')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n\n return {\n type: 'nprofile',\n data: {\n pubkey: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n case 'nevent': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nevent')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n if (tlv[2] && tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (tlv[3] && tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'nevent',\n data: {\n id: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n author: tlv[2]?.[0] ? bytesToHex(tlv[2][0]) : undefined,\n kind: tlv[3]?.[0] ? parseInt(bytesToHex(tlv[3][0]), 16) : undefined,\n },\n }\n }\n\n case 'naddr': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for naddr')\n if (!tlv[2]?.[0]) throw new Error('missing TLV 2 for naddr')\n if (tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (!tlv[3]?.[0]) throw new Error('missing TLV 3 for naddr')\n if (tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'naddr',\n data: {\n identifier: utf8Decoder.decode(tlv[0][0]),\n pubkey: bytesToHex(tlv[2][0]),\n kind: parseInt(bytesToHex(tlv[3][0]), 16),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n\n case 'nsec':\n return { type: prefix, data }\n\n case 'npub':\n case 'note':\n return { type: prefix, data: bytesToHex(data) }\n\n default:\n throw new Error(`unknown prefix ${prefix}`)\n }\n}\n\ntype TLV = { [t: number]: Uint8Array[] }\n\nfunction parseTLV(data: Uint8Array): TLV {\n let result: TLV = {}\n let rest = data\n while (rest.length > 0) {\n let t = rest[0]\n let l = rest[1]\n let v = rest.slice(2, 2 + l)\n rest = rest.slice(2 + l)\n if (v.length < l) throw new Error(`not enough data to read on TLV ${t}`)\n result[t] = result[t] || []\n result[t].push(v)\n }\n return result\n}\n\nexport function nsecEncode(key: Uint8Array): NSec {\n return encodeBytes('nsec', key)\n}\n\nexport function npubEncode(hex: string): NPub {\n return encodeBytes('npub', hexToBytes(hex))\n}\n\nexport function noteEncode(hex: string): Note {\n return encodeBytes('note', hexToBytes(hex))\n}\n\nfunction encodeBech32(prefix: Prefix, data: Uint8Array): `${Prefix}1${string}` {\n let words = bech32.toWords(data)\n return bech32.encode(prefix, words, Bech32MaxSize) as `${Prefix}1${string}`\n}\n\nexport function encodeBytes(prefix: Prefix, bytes: Uint8Array): `${Prefix}1${string}` {\n return encodeBech32(prefix, bytes)\n}\n\nexport function nprofileEncode(profile: ProfilePointer): NProfile {\n let data = encodeTLV({\n 0: [hexToBytes(profile.pubkey)],\n 1: (profile.relays || []).map(url => utf8Encoder.encode(url)),\n })\n return encodeBech32('nprofile', data)\n}\n\nexport function neventEncode(event: EventPointer): NEvent {\n let kindArray\n if (event.kind !== undefined) {\n kindArray = integerToUint8Array(event.kind)\n }\n\n let data = encodeTLV({\n 0: [hexToBytes(event.id)],\n 1: (event.relays || []).map(url => utf8Encoder.encode(url)),\n 2: event.author ? [hexToBytes(event.author)] : [],\n 3: kindArray ? [new Uint8Array(kindArray)] : [],\n })\n\n return encodeBech32('nevent', data)\n}\n\nexport function naddrEncode(addr: AddressPointer): NAddr {\n let kind = new ArrayBuffer(4)\n new DataView(kind).setUint32(0, addr.kind, false)\n\n let data = encodeTLV({\n 0: [utf8Encoder.encode(addr.identifier)],\n 1: (addr.relays || []).map(url => utf8Encoder.encode(url)),\n 2: [hexToBytes(addr.pubkey)],\n 3: [new Uint8Array(kind)],\n })\n return encodeBech32('naddr', data)\n}\n\nfunction encodeTLV(tlv: TLV): Uint8Array {\n let entries: Uint8Array[] = []\n\n Object.entries(tlv)\n .reverse()\n .forEach(([t, vs]) => {\n vs.forEach(v => {\n let entry = new Uint8Array(v.length + 2)\n entry.set([parseInt(t)], 0)\n entry.set([v.length], 1)\n entry.set(v, 2)\n entries.push(entry)\n })\n })\n\n return concatBytes(...entries)\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,gBAAoD;AACpD,kBAAuB;;;ACIvB,mBAAuC;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;;;ADoBjD,IAAM,gBAAgB;AAwFtB,SAAS,OAAO,MAA6B;AAClD,MAAI,EAAE,QAAQ,MAAM,IAAI,mBAAO,OAAO,MAAM,aAAa;AACzD,MAAI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,UAAU,IAAI,GAAG,CAAC,MAAM,MAAM;AACxF,YAAM,IAAI,QAAQ,UAAU,IAAI,CAAC,EAAE,MAAM,cAAc;AACvD,YAAM,MAAM,IAAI,IAAI,IAAI,EAAE,QAAS;AACnC,YAAM,YAAY,QAAQ,IAAI,OAAO,MAAM,IAAI;AAC/C,UAAI;AACF,YAAI,MAAM,IAAI,IAAI,QAAQ,UAAU,IAAI,WAAW,GAAG,CAAC;AACvD,YAAI,IAAI,SAAS,QAAQ,GAAG,MAAM,IAAI;AACpC,gBAAM,IAAI,MAAM,gBAAgB;AAAA,QAClC;AAEA,YAAI,cAAc,IAAI,WAAW;AAC/B,gBAAM,EAAE,MAAM,QAAQ,MAAM,QAAQ,UAAU,WAAW,IAAI,SAAS,EAAE;AAAA,QAC1E;AACA,cAAM,EAAE,MAAM,SAAS,KAAK,IAAI,SAAS,EAAE;AAC3C,gBAAQ;AACR,oBAAY;AACZ;AAAA,MACF,SAAS,MAAP;AAEA,gBAAQ,MAAM;AACd;AAAA,MACF;AAAA,IACF,OAAO;AAEL,cAAQ,IAAI;AACZ;AAAA,IACF;AAAA,EACF;AAEA,MAAI,cAAc,KAAK;AACrB,UAAM,EAAE,MAAM,QAAQ,MAAM,QAAQ,UAAU,SAAS,EAAE;AAAA,EAC3D;AACF;", + "names": ["import_utils"] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip28.js b/node_modules/nostr-tools/lib/cjs/nip28.js new file mode 100644 index 0000000..1f44590 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip28.js @@ -0,0 +1,220 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip28.ts +var nip28_exports = {}; +__export(nip28_exports, { + channelCreateEvent: () => channelCreateEvent, + channelHideMessageEvent: () => channelHideMessageEvent, + channelMessageEvent: () => channelMessageEvent, + channelMetadataEvent: () => channelMetadataEvent, + channelMuteUserEvent: () => channelMuteUserEvent +}); +module.exports = __toCommonJS(nip28_exports); + +// pure.ts +var import_secp256k1 = require("@noble/curves/secp256k1"); +var import_utils2 = require("@noble/hashes/utils"); + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +var import_sha256 = require("@noble/hashes/sha256"); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// pure.ts +var JS = class { + generateSecretKey() { + return import_secp256k1.schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = import_secp256k1.schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = (0, import_sha256.sha256)(utf8Encoder.encode(serializeEvent(event))); + return (0, import_utils2.bytesToHex)(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// kinds.ts +var ChannelCreation = 40; +var ChannelMetadata = 41; +var ChannelMessage = 42; +var ChannelHideMessage = 43; +var ChannelMuteUser = 44; + +// nip28.ts +var channelCreateEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finalizeEvent( + { + kind: ChannelCreation, + tags: [...t.tags ?? []], + content, + created_at: t.created_at + }, + privateKey + ); +}; +var channelMetadataEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finalizeEvent( + { + kind: ChannelMetadata, + tags: [["e", t.channel_create_event_id], ...t.tags ?? []], + content, + created_at: t.created_at + }, + privateKey + ); +}; +var channelMessageEvent = (t, privateKey) => { + const tags = [["e", t.channel_create_event_id, t.relay_url, "root"]]; + if (t.reply_to_channel_message_event_id) { + tags.push(["e", t.reply_to_channel_message_event_id, t.relay_url, "reply"]); + } + return finalizeEvent( + { + kind: ChannelMessage, + tags: [...tags, ...t.tags ?? []], + content: t.content, + created_at: t.created_at + }, + privateKey + ); +}; +var channelHideMessageEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finalizeEvent( + { + kind: ChannelHideMessage, + tags: [["e", t.channel_message_event_id], ...t.tags ?? []], + content, + created_at: t.created_at + }, + privateKey + ); +}; +var channelMuteUserEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finalizeEvent( + { + kind: ChannelMuteUser, + tags: [["p", t.pubkey_to_mute], ...t.tags ?? []], + content, + created_at: t.created_at + }, + privateKey + ); +}; diff --git a/node_modules/nostr-tools/lib/cjs/nip28.js.map b/node_modules/nostr-tools/lib/cjs/nip28.js.map new file mode 100644 index 0000000..b38cf57 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip28.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip28.ts", "../../pure.ts", "../../core.ts", "../../utils.ts", "../../kinds.ts"], + "sourcesContent": ["import { Event, finalizeEvent } from './pure.ts'\nimport {\n ChannelCreation,\n ChannelHideMessage,\n ChannelMessage,\n ChannelMetadata as KindChannelMetadata,\n ChannelMuteUser,\n} from './kinds.ts'\n\nexport interface ChannelMetadata {\n name: string\n about: string\n picture: string\n}\n\nexport interface ChannelCreateEventTemplate {\n /* JSON string containing ChannelMetadata as defined for Kind 40 and 41 in nip-28. */\n content: string | ChannelMetadata\n created_at: number\n tags?: string[][]\n}\n\nexport interface ChannelMetadataEventTemplate {\n channel_create_event_id: string\n /* JSON string containing ChannelMetadata as defined for Kind 40 and 41 in nip-28. */\n content: string | ChannelMetadata\n created_at: number\n tags?: string[][]\n}\n\nexport interface ChannelMessageEventTemplate {\n channel_create_event_id: string\n reply_to_channel_message_event_id?: string\n relay_url: string\n content: string\n created_at: number\n tags?: string[][]\n}\n\nexport interface ChannelHideMessageEventTemplate {\n channel_message_event_id: string\n content: string | { reason: string }\n created_at: number\n tags?: string[][]\n}\n\nexport interface ChannelMuteUserEventTemplate {\n content: string | { reason: string }\n created_at: number\n pubkey_to_mute: string\n tags?: string[][]\n}\n\nexport const channelCreateEvent = (t: ChannelCreateEventTemplate, privateKey: Uint8Array): Event | undefined => {\n let content: string\n if (typeof t.content === 'object') {\n content = JSON.stringify(t.content)\n } else if (typeof t.content === 'string') {\n content = t.content\n } else {\n return undefined\n }\n\n return finalizeEvent(\n {\n kind: ChannelCreation,\n tags: [...(t.tags ?? [])],\n content: content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\nexport const channelMetadataEvent = (t: ChannelMetadataEventTemplate, privateKey: Uint8Array): Event | undefined => {\n let content: string\n if (typeof t.content === 'object') {\n content = JSON.stringify(t.content)\n } else if (typeof t.content === 'string') {\n content = t.content\n } else {\n return undefined\n }\n\n return finalizeEvent(\n {\n kind: KindChannelMetadata,\n tags: [['e', t.channel_create_event_id], ...(t.tags ?? [])],\n content: content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\nexport const channelMessageEvent = (t: ChannelMessageEventTemplate, privateKey: Uint8Array): Event => {\n const tags = [['e', t.channel_create_event_id, t.relay_url, 'root']]\n\n if (t.reply_to_channel_message_event_id) {\n tags.push(['e', t.reply_to_channel_message_event_id, t.relay_url, 'reply'])\n }\n\n return finalizeEvent(\n {\n kind: ChannelMessage,\n tags: [...tags, ...(t.tags ?? [])],\n content: t.content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\n/* \"e\" tag should be the kind 42 event to hide */\nexport const channelHideMessageEvent = (\n t: ChannelHideMessageEventTemplate,\n privateKey: Uint8Array,\n): Event | undefined => {\n let content: string\n if (typeof t.content === 'object') {\n content = JSON.stringify(t.content)\n } else if (typeof t.content === 'string') {\n content = t.content\n } else {\n return undefined\n }\n\n return finalizeEvent(\n {\n kind: ChannelHideMessage,\n tags: [['e', t.channel_message_event_id], ...(t.tags ?? [])],\n content: content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\nexport const channelMuteUserEvent = (t: ChannelMuteUserEventTemplate, privateKey: Uint8Array): Event | undefined => {\n let content: string\n if (typeof t.content === 'object') {\n content = JSON.stringify(t.content)\n } else if (typeof t.content === 'string') {\n content = t.content\n } else {\n return undefined\n }\n\n return finalizeEvent(\n {\n kind: ChannelMuteUser,\n tags: [['p', t.pubkey_to_mute], ...(t.tags ?? [])],\n content: content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n", "import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,uBAAwB;AACxB,IAAAA,gBAA2B;;;ACOpB,I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,GAAG,GAAI,EAAE,QAAQ,CAAC,CAAE;AAAA,MAC3D;AAAA,MACA,YAAY,EAAE;AAAA,IAChB;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,uBAAuB,CAAC,GAAiC,eAA8C;AAClH,MAAI;AACJ,MAAI,OAAO,EAAE,YAAY,UAAU;AACjC,cAAU,KAAK,UAAU,EAAE,OAAO;AAAA,EACpC,WAAW,OAAO,EAAE,YAAY,UAAU;AACxC,cAAU,EAAE;AAAA,EACd,OAAO;AACL,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL;AAAA,MACE,MAAM;AAAA,MACN,MAAM,CAAC,CAAC,KAAK,EAAE,cAAc,GAAG,GAAI,EAAE,QAAQ,CAAC,CAAE;AAAA,MACjD;AAAA,MACA,YAAY,EAAE;AAAA,IAChB;AAAA,IACA;AAAA,EACF;AACF;", + "names": ["import_utils", "i"] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip29.js b/node_modules/nostr-tools/lib/cjs/nip29.js new file mode 100644 index 0000000..0dcb2ac --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip29.js @@ -0,0 +1,495 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip29.ts +var nip29_exports = {}; +__export(nip29_exports, { + GroupAdminPermission: () => GroupAdminPermission, + encodeGroupReference: () => encodeGroupReference, + fetchGroupAdminsEvent: () => fetchGroupAdminsEvent, + fetchGroupMembersEvent: () => fetchGroupMembersEvent, + fetchGroupMetadataEvent: () => fetchGroupMetadataEvent, + fetchRelayInformationByGroupReference: () => fetchRelayInformationByGroupReference, + generateGroupAdminsEventTemplate: () => generateGroupAdminsEventTemplate, + generateGroupMembersEventTemplate: () => generateGroupMembersEventTemplate, + generateGroupMetadataEventTemplate: () => generateGroupMetadataEventTemplate, + getNormalizedRelayURLByGroupReference: () => getNormalizedRelayURLByGroupReference, + loadGroup: () => loadGroup, + loadGroupFromCode: () => loadGroupFromCode, + parseGroupAdminsEvent: () => parseGroupAdminsEvent, + parseGroupCode: () => parseGroupCode, + parseGroupMembersEvent: () => parseGroupMembersEvent, + parseGroupMetadataEvent: () => parseGroupMetadataEvent, + subscribeRelayGroupsMetadataEvents: () => subscribeRelayGroupsMetadataEvents, + validateGroupAdminsEvent: () => validateGroupAdminsEvent, + validateGroupMembersEvent: () => validateGroupMembersEvent, + validateGroupMetadataEvent: () => validateGroupMetadataEvent +}); +module.exports = __toCommonJS(nip29_exports); + +// nip11.ts +var _fetch; +try { + _fetch = fetch; +} catch { +} +async function fetchRelayInformation(url) { + return await (await fetch(url.replace("ws://", "http://").replace("wss://", "https://"), { + headers: { Accept: "application/nostr+json" } + })).json(); +} + +// nip19.ts +var import_utils2 = require("@noble/hashes/utils"); +var import_base = require("@scure/base"); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); +function normalizeURL(url) { + try { + if (url.indexOf("://") === -1) + url = "wss://" + url; + let p = new URL(url); + p.pathname = p.pathname.replace(/\/+/g, "/"); + if (p.pathname.endsWith("/")) + p.pathname = p.pathname.slice(0, -1); + if (p.port === "80" && p.protocol === "ws:" || p.port === "443" && p.protocol === "wss:") + p.port = ""; + p.searchParams.sort(); + p.hash = ""; + return p.toString(); + } catch (e) { + throw new Error(`Invalid URL: ${url}`); + } +} + +// nip19.ts +var NostrTypeGuard = { + isNProfile: (value) => /^nprofile1[a-z\d]+$/.test(value || ""), + isNEvent: (value) => /^nevent1[a-z\d]+$/.test(value || ""), + isNAddr: (value) => /^naddr1[a-z\d]+$/.test(value || ""), + isNSec: (value) => /^nsec1[a-z\d]{58}$/.test(value || ""), + isNPub: (value) => /^npub1[a-z\d]{58}$/.test(value || ""), + isNote: (value) => /^note1[a-z\d]+$/.test(value || ""), + isNcryptsec: (value) => /^ncryptsec1[a-z\d]+$/.test(value || "") +}; +var Bech32MaxSize = 5e3; +function decode(code) { + let { prefix, words } = import_base.bech32.decode(code, Bech32MaxSize); + let data = new Uint8Array(import_base.bech32.fromWords(words)); + switch (prefix) { + case "nprofile": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nprofile"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + return { + type: "nprofile", + data: { + pubkey: (0, import_utils2.bytesToHex)(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nevent": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nevent"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + if (tlv[2] && tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (tlv[3] && tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "nevent", + data: { + id: (0, import_utils2.bytesToHex)(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [], + author: tlv[2]?.[0] ? (0, import_utils2.bytesToHex)(tlv[2][0]) : void 0, + kind: tlv[3]?.[0] ? parseInt((0, import_utils2.bytesToHex)(tlv[3][0]), 16) : void 0 + } + }; + } + case "naddr": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for naddr"); + if (!tlv[2]?.[0]) + throw new Error("missing TLV 2 for naddr"); + if (tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (!tlv[3]?.[0]) + throw new Error("missing TLV 3 for naddr"); + if (tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "naddr", + data: { + identifier: utf8Decoder.decode(tlv[0][0]), + pubkey: (0, import_utils2.bytesToHex)(tlv[2][0]), + kind: parseInt((0, import_utils2.bytesToHex)(tlv[3][0]), 16), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nsec": + return { type: prefix, data }; + case "npub": + case "note": + return { type: prefix, data: (0, import_utils2.bytesToHex)(data) }; + default: + throw new Error(`unknown prefix ${prefix}`); + } +} +function parseTLV(data) { + let result = {}; + let rest = data; + while (rest.length > 0) { + let t = rest[0]; + let l = rest[1]; + let v = rest.slice(2, 2 + l); + rest = rest.slice(2 + l); + if (v.length < l) + throw new Error(`not enough data to read on TLV ${t}`); + result[t] = result[t] || []; + result[t].push(v); + } + return result; +} + +// nip29.ts +var GroupAdminPermission = /* @__PURE__ */ ((GroupAdminPermission2) => { + GroupAdminPermission2["AddUser"] = "add-user"; + GroupAdminPermission2["EditMetadata"] = "edit-metadata"; + GroupAdminPermission2["DeleteEvent"] = "delete-event"; + GroupAdminPermission2["RemoveUser"] = "remove-user"; + GroupAdminPermission2["AddPermission"] = "add-permission"; + GroupAdminPermission2["RemovePermission"] = "remove-permission"; + GroupAdminPermission2["EditGroupStatus"] = "edit-group-status"; + GroupAdminPermission2["PutUser"] = "put-user"; + GroupAdminPermission2["CreateGroup"] = "create-group"; + GroupAdminPermission2["DeleteGroup"] = "delete-group"; + GroupAdminPermission2["CreateInvite"] = "create-invite"; + return GroupAdminPermission2; +})(GroupAdminPermission || {}); +function generateGroupMetadataEventTemplate(group) { + const tags = [["d", group.metadata.id]]; + group.metadata.name && tags.push(["name", group.metadata.name]); + group.metadata.picture && tags.push(["picture", group.metadata.picture]); + group.metadata.about && tags.push(["about", group.metadata.about]); + group.metadata.isPublic && tags.push(["public"]); + group.metadata.isOpen && tags.push(["open"]); + return { + content: "", + created_at: Math.floor(Date.now() / 1e3), + kind: 39e3, + tags + }; +} +function validateGroupMetadataEvent(event) { + if (event.kind !== 39e3) + return false; + if (!event.pubkey) + return false; + const requiredTags = ["d"]; + for (const tag of requiredTags) { + if (!event.tags.find(([t]) => t == tag)) + return false; + } + return true; +} +function generateGroupAdminsEventTemplate(group, admins) { + const tags = [["d", group.metadata.id]]; + for (const admin of admins) { + tags.push(["p", admin.pubkey, admin.label || "", ...admin.permissions]); + } + return { + content: "", + created_at: Math.floor(Date.now() / 1e3), + kind: 39001, + tags + }; +} +function validateGroupAdminsEvent(event) { + if (event.kind !== 39001) + return false; + const requiredTags = ["d"]; + for (const tag of requiredTags) { + if (!event.tags.find(([t]) => t == tag)) + return false; + } + for (const [tag, _value, _label, ...permissions] of event.tags) { + if (tag !== "p") + continue; + for (let i = 0; i < permissions.length; i += 1) { + if (typeof permissions[i] !== "string") + return false; + if (!Object.values(GroupAdminPermission).includes(permissions[i])) + return false; + } + } + return true; +} +function generateGroupMembersEventTemplate(group, members) { + const tags = [["d", group.metadata.id]]; + for (const member of members) { + tags.push(["p", member.pubkey, member.label || ""]); + } + return { + content: "", + created_at: Math.floor(Date.now() / 1e3), + kind: 39002, + tags + }; +} +function validateGroupMembersEvent(event) { + if (event.kind !== 39002) + return false; + const requiredTags = ["d"]; + for (const tag of requiredTags) { + if (!event.tags.find(([t]) => t == tag)) + return false; + } + return true; +} +function getNormalizedRelayURLByGroupReference(groupReference) { + return normalizeURL(groupReference.host); +} +async function fetchRelayInformationByGroupReference(groupReference) { + const normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference); + return fetchRelayInformation(normalizedRelayURL); +} +async function fetchGroupMetadataEvent({ + pool, + groupReference, + relayInformation, + normalizedRelayURL +}) { + if (!normalizedRelayURL) { + normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference); + } + if (!relayInformation) { + relayInformation = await fetchRelayInformation(normalizedRelayURL); + } + const groupMetadataEvent = await pool.get([normalizedRelayURL], { + kinds: [39e3], + authors: [relayInformation.pubkey], + "#d": [groupReference.id] + }); + if (!groupMetadataEvent) + throw new Error(`group '${groupReference.id}' not found on ${normalizedRelayURL}`); + return groupMetadataEvent; +} +function parseGroupMetadataEvent(event) { + if (!validateGroupMetadataEvent(event)) + throw new Error("invalid group metadata event"); + const metadata = { + id: "", + pubkey: event.pubkey + }; + for (const [tag, value] of event.tags) { + switch (tag) { + case "d": + metadata.id = value; + break; + case "name": + metadata.name = value; + break; + case "picture": + metadata.picture = value; + break; + case "about": + metadata.about = value; + break; + case "public": + metadata.isPublic = true; + break; + case "open": + metadata.isOpen = true; + break; + } + } + return metadata; +} +async function fetchGroupAdminsEvent({ + pool, + groupReference, + relayInformation, + normalizedRelayURL +}) { + if (!normalizedRelayURL) { + normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference); + } + if (!relayInformation) { + relayInformation = await fetchRelayInformation(normalizedRelayURL); + } + const groupAdminsEvent = await pool.get([normalizedRelayURL], { + kinds: [39001], + authors: [relayInformation.pubkey], + "#d": [groupReference.id] + }); + if (!groupAdminsEvent) + throw new Error(`admins for group '${groupReference.id}' not found on ${normalizedRelayURL}`); + return groupAdminsEvent; +} +function parseGroupAdminsEvent(event) { + if (!validateGroupAdminsEvent(event)) + throw new Error("invalid group admins event"); + const admins = []; + for (const [tag, value, label, ...permissions] of event.tags) { + if (tag !== "p") + continue; + admins.push({ + pubkey: value, + label, + permissions + }); + } + return admins; +} +async function fetchGroupMembersEvent({ + pool, + groupReference, + relayInformation, + normalizedRelayURL +}) { + if (!normalizedRelayURL) { + normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference); + } + if (!relayInformation) { + relayInformation = await fetchRelayInformation(normalizedRelayURL); + } + const groupMembersEvent = await pool.get([normalizedRelayURL], { + kinds: [39002], + authors: [relayInformation.pubkey], + "#d": [groupReference.id] + }); + if (!groupMembersEvent) + throw new Error(`members for group '${groupReference.id}' not found on ${normalizedRelayURL}`); + return groupMembersEvent; +} +function parseGroupMembersEvent(event) { + if (!validateGroupMembersEvent(event)) + throw new Error("invalid group members event"); + const members = []; + for (const [tag, value, label] of event.tags) { + if (tag !== "p") + continue; + members.push({ + pubkey: value, + label + }); + } + return members; +} +async function loadGroup({ + pool, + groupReference, + normalizedRelayURL, + relayInformation +}) { + if (!normalizedRelayURL) { + normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference); + } + if (!relayInformation) { + relayInformation = await fetchRelayInformation(normalizedRelayURL); + } + const metadataEvent = await fetchGroupMetadataEvent({ pool, groupReference, normalizedRelayURL, relayInformation }); + const metadata = parseGroupMetadataEvent(metadataEvent); + const adminsEvent = await fetchGroupAdminsEvent({ pool, groupReference, normalizedRelayURL, relayInformation }); + const admins = parseGroupAdminsEvent(adminsEvent); + const membersEvent = await fetchGroupMembersEvent({ pool, groupReference, normalizedRelayURL, relayInformation }); + const members = parseGroupMembersEvent(membersEvent); + const group = { + relay: normalizedRelayURL, + metadata, + admins, + members, + reference: groupReference + }; + return group; +} +async function loadGroupFromCode(pool, code) { + const groupReference = parseGroupCode(code); + if (!groupReference) + throw new Error("invalid group code"); + return loadGroup({ pool, groupReference }); +} +function parseGroupCode(code) { + if (NostrTypeGuard.isNAddr(code)) { + try { + let { data } = decode(code); + let { relays, identifier } = data; + if (!relays || relays.length === 0) + return null; + let host = relays[0]; + if (host.startsWith("wss://")) { + host = host.slice(6); + } + return { host, id: identifier }; + } catch (err) { + return null; + } + } else if (code.split("'").length === 2) { + let spl = code.split("'"); + return { host: spl[0], id: spl[1] }; + } + return null; +} +function encodeGroupReference(gr) { + const { host, id } = gr; + const normalizedHost = host.replace(/^(https?:\/\/|wss?:\/\/)/, ""); + return `${normalizedHost}'${id}`; +} +function subscribeRelayGroupsMetadataEvents({ + pool, + relayURL, + onError, + onEvent, + onConnect +}) { + let sub; + const normalizedRelayURL = normalizeURL(relayURL); + fetchRelayInformation(normalizedRelayURL).then(async (info) => { + const abstractedRelay = await pool.ensureRelay(normalizedRelayURL); + onConnect?.(); + sub = abstractedRelay.prepareSubscription( + [ + { + kinds: [39e3], + limit: 50, + authors: [info.pubkey] + } + ], + { + onevent(event) { + onEvent(event); + } + } + ); + }).catch((err) => { + sub.close(); + onError(err); + }); + return () => sub.close(); +} diff --git a/node_modules/nostr-tools/lib/cjs/nip29.js.map b/node_modules/nostr-tools/lib/cjs/nip29.js.map new file mode 100644 index 0000000..cf6c777 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip29.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip29.ts", "../../nip11.ts", "../../nip19.ts", "../../utils.ts"], + "sourcesContent": ["import { AbstractSimplePool } from './abstract-pool.ts'\nimport { Subscription } from './abstract-relay.ts'\nimport type { Event, EventTemplate } from './core.ts'\nimport { fetchRelayInformation, RelayInformation } from './nip11.ts'\nimport { decode, NostrTypeGuard } from './nip19.ts'\nimport { normalizeURL } from './utils.ts'\n\n/**\n * Represents a NIP29 group.\n */\nexport type Group = {\n relay: string\n metadata: GroupMetadata\n admins?: GroupAdmin[]\n members?: GroupMember[]\n reference: GroupReference\n}\n\n/**\n * Represents the metadata for a NIP29 group.\n */\nexport type GroupMetadata = {\n id: string\n pubkey: string\n name?: string\n picture?: string\n about?: string\n isPublic?: boolean\n isOpen?: boolean\n}\n\n/**\n * Represents a NIP29 group reference.\n */\nexport type GroupReference = {\n id: string\n host: string\n}\n\n/**\n * Represents a NIP29 group member.\n */\nexport type GroupMember = {\n pubkey: string\n label?: string\n}\n\n/**\n * Represents a NIP29 group admin.\n */\nexport type GroupAdmin = {\n pubkey: string\n label?: string\n permissions: GroupAdminPermission[]\n}\n\n/**\n * Represents the permissions that a NIP29 group admin can have.\n */\nexport enum GroupAdminPermission {\n /** @deprecated use PutUser instead */\n AddUser = 'add-user',\n EditMetadata = 'edit-metadata',\n DeleteEvent = 'delete-event',\n RemoveUser = 'remove-user',\n /** @deprecated removed from NIP */\n AddPermission = 'add-permission',\n /** @deprecated removed from NIP */\n RemovePermission = 'remove-permission',\n /** @deprecated removed from NIP */\n EditGroupStatus = 'edit-group-status',\n PutUser = 'put-user',\n CreateGroup = 'create-group',\n DeleteGroup = 'delete-group',\n CreateInvite = 'create-invite',\n}\n\n/**\n * Generates a group metadata event template.\n *\n * @param group - The group object.\n * @returns An event template with the generated group metadata that can be signed later.\n */\nexport function generateGroupMetadataEventTemplate(group: Group): EventTemplate {\n const tags: string[][] = [['d', group.metadata.id]]\n group.metadata.name && tags.push(['name', group.metadata.name])\n group.metadata.picture && tags.push(['picture', group.metadata.picture])\n group.metadata.about && tags.push(['about', group.metadata.about])\n group.metadata.isPublic && tags.push(['public'])\n group.metadata.isOpen && tags.push(['open'])\n\n return {\n content: '',\n created_at: Math.floor(Date.now() / 1000),\n kind: 39000,\n tags,\n }\n}\n\n/**\n * Validates a group metadata event.\n *\n * @param event - The event to validate.\n * @returns A boolean indicating whether the event is valid.\n */\nexport function validateGroupMetadataEvent(event: Event): boolean {\n if (event.kind !== 39000) return false\n\n if (!event.pubkey) return false\n\n const requiredTags = ['d'] as const\n for (const tag of requiredTags) {\n if (!event.tags.find(([t]) => t == tag)) return false\n }\n\n return true\n}\n\n/**\n * Generates an event template for group admins.\n *\n * @param group - The group object.\n * @param admins - An array of group admins.\n * @returns The generated event template with the group admins that can be signed later.\n */\nexport function generateGroupAdminsEventTemplate(group: Group, admins: GroupAdmin[]): EventTemplate {\n const tags: string[][] = [['d', group.metadata.id]]\n for (const admin of admins) {\n tags.push(['p', admin.pubkey, admin.label || '', ...admin.permissions])\n }\n\n return {\n content: '',\n created_at: Math.floor(Date.now() / 1000),\n kind: 39001,\n tags,\n }\n}\n\n/**\n * Validates a group admins event.\n *\n * @param event - The event to validate.\n * @returns True if the event is valid, false otherwise.\n */\nexport function validateGroupAdminsEvent(event: Event): boolean {\n if (event.kind !== 39001) return false\n\n const requiredTags = ['d'] as const\n for (const tag of requiredTags) {\n if (!event.tags.find(([t]) => t == tag)) return false\n }\n\n // validate permissions\n for (const [tag, _value, _label, ...permissions] of event.tags) {\n if (tag !== 'p') continue\n\n for (let i = 0; i < permissions.length; i += 1) {\n if (typeof permissions[i] !== 'string') return false\n\n // validate permission name from the GroupAdminPermission enum\n if (!Object.values(GroupAdminPermission).includes(permissions[i] as GroupAdminPermission)) return false\n }\n }\n\n return true\n}\n\n/**\n * Generates an event template for a group with its members.\n *\n * @param group - The group object.\n * @param members - An array of group members.\n * @returns The generated event template with the group members that can be signed later.\n */\nexport function generateGroupMembersEventTemplate(group: Group, members: GroupMember[]): EventTemplate {\n const tags: string[][] = [['d', group.metadata.id]]\n for (const member of members) {\n tags.push(['p', member.pubkey, member.label || ''])\n }\n\n return {\n content: '',\n created_at: Math.floor(Date.now() / 1000),\n kind: 39002,\n tags,\n }\n}\n\n/**\n * Validates a group members event.\n *\n * @param event - The event to validate.\n * @returns Returns `true` if the event is a valid group members event, `false` otherwise.\n */\nexport function validateGroupMembersEvent(event: Event): boolean {\n if (event.kind !== 39002) return false\n\n const requiredTags = ['d'] as const\n for (const tag of requiredTags) {\n if (!event.tags.find(([t]) => t == tag)) return false\n }\n\n return true\n}\n\n/**\n * Returns the normalized relay URL based on the provided group reference.\n *\n * @param groupReference - The group reference object containing the host.\n * @returns The normalized relay URL.\n */\nexport function getNormalizedRelayURLByGroupReference(groupReference: GroupReference): string {\n return normalizeURL(groupReference.host)\n}\n\n/**\n * Fetches relay information by group reference.\n *\n * @param groupReference The group reference.\n * @returns A promise that resolves to the relay information.\n */\nexport async function fetchRelayInformationByGroupReference(groupReference: GroupReference): Promise {\n const normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference)\n\n return fetchRelayInformation(normalizedRelayURL)\n}\n\n/**\n * Fetches the group metadata event from the specified pool.\n * If the normalizedRelayURL is not provided, it will be obtained using the groupReference.\n * If the relayInformation is not provided, it will be fetched using the normalizedRelayURL.\n *\n * @param {Object} options - The options object.\n * @param {AbstractSimplePool} options.pool - The pool to fetch the group metadata event from.\n * @param {GroupReference} options.groupReference - The reference to the group.\n * @param {string} [options.normalizedRelayURL] - The normalized URL of the relay.\n * @param {RelayInformation} [options.relayInformation] - The relay information object.\n * @returns {Promise} The group metadata event that can be parsed later to get the group metadata object.\n * @throws {Error} If the group is not found on the specified relay.\n */\nexport async function fetchGroupMetadataEvent({\n pool,\n groupReference,\n relayInformation,\n normalizedRelayURL,\n}: {\n pool: AbstractSimplePool\n groupReference: GroupReference\n normalizedRelayURL?: string\n relayInformation?: RelayInformation\n}): Promise {\n if (!normalizedRelayURL) {\n normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference)\n }\n\n if (!relayInformation) {\n relayInformation = await fetchRelayInformation(normalizedRelayURL)\n }\n\n const groupMetadataEvent = await pool.get([normalizedRelayURL], {\n kinds: [39000],\n authors: [relayInformation.pubkey],\n '#d': [groupReference.id],\n })\n\n if (!groupMetadataEvent) throw new Error(`group '${groupReference.id}' not found on ${normalizedRelayURL}`)\n\n return groupMetadataEvent\n}\n\n/**\n * Parses a group metadata event and returns the corresponding GroupMetadata object.\n *\n * @param event - The event to parse.\n * @returns The parsed GroupMetadata object.\n * @throws An error if the group metadata event is invalid.\n */\nexport function parseGroupMetadataEvent(event: Event): GroupMetadata {\n if (!validateGroupMetadataEvent(event)) throw new Error('invalid group metadata event')\n\n const metadata: GroupMetadata = {\n id: '',\n pubkey: event.pubkey,\n }\n\n for (const [tag, value] of event.tags) {\n switch (tag) {\n case 'd':\n metadata.id = value\n break\n case 'name':\n metadata.name = value\n break\n case 'picture':\n metadata.picture = value\n break\n case 'about':\n metadata.about = value\n break\n case 'public':\n metadata.isPublic = true\n break\n case 'open':\n metadata.isOpen = true\n break\n }\n }\n\n return metadata\n}\n\n/**\n * Fetches the group admins event from the specified pool.\n * If the normalizedRelayURL is not provided, it will be obtained from the groupReference.\n * If the relayInformation is not provided, it will be fetched using the normalizedRelayURL.\n *\n * @param {Object} options - The options object.\n * @param {AbstractSimplePool} options.pool - The pool to fetch the group admins event from.\n * @param {GroupReference} options.groupReference - The reference to the group.\n * @param {string} [options.normalizedRelayURL] - The normalized relay URL.\n * @param {RelayInformation} [options.relayInformation] - The relay information.\n * @returns {Promise} The group admins event that can be parsed later to get the group admins object.\n * @throws {Error} If the group admins event is not found on the specified relay.\n */\nexport async function fetchGroupAdminsEvent({\n pool,\n groupReference,\n relayInformation,\n normalizedRelayURL,\n}: {\n pool: AbstractSimplePool\n groupReference: GroupReference\n normalizedRelayURL?: string\n relayInformation?: RelayInformation\n}): Promise {\n if (!normalizedRelayURL) {\n normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference)\n }\n\n if (!relayInformation) {\n relayInformation = await fetchRelayInformation(normalizedRelayURL)\n }\n\n const groupAdminsEvent = await pool.get([normalizedRelayURL], {\n kinds: [39001],\n authors: [relayInformation.pubkey],\n '#d': [groupReference.id],\n })\n\n if (!groupAdminsEvent) throw new Error(`admins for group '${groupReference.id}' not found on ${normalizedRelayURL}`)\n\n return groupAdminsEvent\n}\n\n/**\n * Parses a group admins event and returns an array of GroupAdmin objects.\n *\n * @param event - The event to parse.\n * @returns An array of GroupAdmin objects.\n * @throws Throws an error if the group admins event is invalid.\n */\nexport function parseGroupAdminsEvent(event: Event): GroupAdmin[] {\n if (!validateGroupAdminsEvent(event)) throw new Error('invalid group admins event')\n\n const admins: GroupAdmin[] = []\n\n for (const [tag, value, label, ...permissions] of event.tags) {\n if (tag !== 'p') continue\n\n admins.push({\n pubkey: value,\n label,\n permissions: permissions as GroupAdminPermission[],\n })\n }\n\n return admins\n}\n\n/**\n * Fetches the group members event from the specified relay.\n * If the normalizedRelayURL is not provided, it will be obtained using the groupReference.\n * If the relayInformation is not provided, it will be fetched using the normalizedRelayURL.\n *\n * @param {Object} options - The options object.\n * @param {AbstractSimplePool} options.pool - The pool object.\n * @param {GroupReference} options.groupReference - The group reference object.\n * @param {string} [options.normalizedRelayURL] - The normalized relay URL.\n * @param {RelayInformation} [options.relayInformation] - The relay information object.\n * @returns {Promise} The group members event that can be parsed later to get the group members object.\n * @throws {Error} If the group members event is not found.\n */\nexport async function fetchGroupMembersEvent({\n pool,\n groupReference,\n relayInformation,\n normalizedRelayURL,\n}: {\n pool: AbstractSimplePool\n groupReference: GroupReference\n normalizedRelayURL?: string\n relayInformation?: RelayInformation\n}): Promise {\n if (!normalizedRelayURL) {\n normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference)\n }\n\n if (!relayInformation) {\n relayInformation = await fetchRelayInformation(normalizedRelayURL)\n }\n\n const groupMembersEvent = await pool.get([normalizedRelayURL], {\n kinds: [39002],\n authors: [relayInformation.pubkey],\n '#d': [groupReference.id],\n })\n\n if (!groupMembersEvent) throw new Error(`members for group '${groupReference.id}' not found on ${normalizedRelayURL}`)\n\n return groupMembersEvent\n}\n\n/**\n * Parses a group members event and returns an array of GroupMember objects.\n * @param event - The event to parse.\n * @returns An array of GroupMember objects.\n * @throws Throws an error if the group members event is invalid.\n */\nexport function parseGroupMembersEvent(event: Event): GroupMember[] {\n if (!validateGroupMembersEvent(event)) throw new Error('invalid group members event')\n\n const members: GroupMember[] = []\n\n for (const [tag, value, label] of event.tags) {\n if (tag !== 'p') continue\n\n members.push({\n pubkey: value,\n label,\n })\n }\n\n return members\n}\n\n/**\n * Fetches and parses the group metadata event, group admins event, and group members event from the specified pool.\n * If the normalized relay URL is not provided, it will be obtained using the group reference.\n * If the relay information is not provided, it will be fetched using the normalized relay URL.\n *\n * @param {Object} options - The options for loading the group.\n * @param {AbstractSimplePool} options.pool - The pool to load the group from.\n * @param {GroupReference} options.groupReference - The reference of the group to load.\n * @param {string} [options.normalizedRelayURL] - The normalized URL of the relay to use.\n * @param {RelayInformation} [options.relayInformation] - The relay information to use.\n * @returns {Promise} A promise that resolves to the loaded group.\n */\nexport async function loadGroup({\n pool,\n groupReference,\n normalizedRelayURL,\n relayInformation,\n}: {\n pool: AbstractSimplePool\n groupReference: GroupReference\n normalizedRelayURL?: string\n relayInformation?: RelayInformation\n}): Promise {\n if (!normalizedRelayURL) {\n normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference)\n }\n\n if (!relayInformation) {\n relayInformation = await fetchRelayInformation(normalizedRelayURL)\n }\n\n const metadataEvent = await fetchGroupMetadataEvent({ pool, groupReference, normalizedRelayURL, relayInformation })\n const metadata = parseGroupMetadataEvent(metadataEvent)\n\n const adminsEvent = await fetchGroupAdminsEvent({ pool, groupReference, normalizedRelayURL, relayInformation })\n const admins = parseGroupAdminsEvent(adminsEvent)\n\n const membersEvent = await fetchGroupMembersEvent({ pool, groupReference, normalizedRelayURL, relayInformation })\n const members = parseGroupMembersEvent(membersEvent)\n\n const group: Group = {\n relay: normalizedRelayURL,\n metadata,\n admins,\n members,\n reference: groupReference,\n }\n\n return group\n}\n\n/**\n * Loads a group from the specified pool using the provided group code.\n *\n * @param {AbstractSimplePool} pool - The pool to load the group from.\n * @param {string} code - The code representing the group.\n * @returns {Promise} - A promise that resolves to the loaded group.\n * @throws {Error} - If the group code is invalid.\n */\nexport async function loadGroupFromCode(pool: AbstractSimplePool, code: string): Promise {\n const groupReference = parseGroupCode(code)\n\n if (!groupReference) throw new Error('invalid group code')\n\n return loadGroup({ pool, groupReference })\n}\n\n/**\n * Parses a group code and returns a GroupReference object.\n *\n * @param code The group code to parse.\n * @returns A GroupReference object if the code is valid, otherwise null.\n */\nexport function parseGroupCode(code: string): null | GroupReference {\n if (NostrTypeGuard.isNAddr(code)) {\n try {\n let { data } = decode(code)\n\n let { relays, identifier } = data\n if (!relays || relays.length === 0) return null\n\n let host = relays![0]\n if (host.startsWith('wss://')) {\n host = host.slice(6)\n }\n return { host, id: identifier }\n } catch (err) {\n return null\n }\n } else if (code.split(\"'\").length === 2) {\n let spl = code.split(\"'\")\n return { host: spl[0], id: spl[1] }\n }\n\n return null\n}\n\n/**\n * Encodes a group reference into a string.\n *\n * @param gr - The group reference to encode.\n * @returns The encoded group reference as a string.\n */\nexport function encodeGroupReference(gr: GroupReference): string {\n const { host, id } = gr\n const normalizedHost = host.replace(/^(https?:\\/\\/|wss?:\\/\\/)/, '')\n\n return `${normalizedHost}'${id}`\n}\n\n/**\n * Subscribes to relay groups metadata events and calls the provided event handler function\n * when an event is received.\n *\n * @param {Object} options - The options for subscribing to relay groups metadata events.\n * @param {AbstractSimplePool} options.pool - The pool to subscribe to.\n * @param {string} options.relayURL - The URL of the relay.\n * @param {Function} options.onError - The error handler function.\n * @param {Function} options.onEvent - The event handler function.\n * @param {Function} [options.onConnect] - The connect handler function.\n * @returns {Function} - A function to close the subscription\n */\nexport function subscribeRelayGroupsMetadataEvents({\n pool,\n relayURL,\n onError,\n onEvent,\n onConnect,\n}: {\n pool: AbstractSimplePool\n relayURL: string\n onError: (err: Error) => void\n onEvent: (event: Event) => void\n onConnect?: () => void\n}): () => void {\n let sub: Subscription\n\n const normalizedRelayURL = normalizeURL(relayURL)\n\n fetchRelayInformation(normalizedRelayURL)\n .then(async info => {\n const abstractedRelay = await pool.ensureRelay(normalizedRelayURL)\n\n onConnect?.()\n\n sub = abstractedRelay.prepareSubscription(\n [\n {\n kinds: [39000],\n limit: 50,\n authors: [info.pubkey],\n },\n ],\n {\n onevent(event: Event) {\n onEvent(event)\n },\n },\n )\n })\n .catch(err => {\n sub.close()\n\n onError(err)\n })\n\n return () => sub.close()\n}\n", "var _fetch: any\n\ntry {\n _fetch = fetch\n} catch {}\n\nexport function useFetchImplementation(fetchImplementation: any): void {\n _fetch = fetchImplementation\n}\n\nexport async function fetchRelayInformation(url: string): Promise {\n return (await (\n await fetch(url.replace('ws://', 'http://').replace('wss://', 'https://'), {\n headers: { Accept: 'application/nostr+json' },\n })\n ).json()) as RelayInformation\n}\n\n/**\n * ## Relay Information Document\n\n * Relays may provide server metadata to clients to inform\n * them of capabilities, administrative contacts, and\n * various server attributes. This is made available as a\n * JSON document over HTTP, on the same URI as the relay's\n * websocket.\n\n * Any field may be omitted, and clients MUST ignore any\n * additional fields they do not understand. Relays MUST\n * accept CORS requests by sending\n * `Access-Control-Allow-Origin`,\n * `Access-Control-Allow-Headers`, and\n * `Access-Control-Allow-Methods` headers.\n * @param name string identifying relay\n * @param description string with detailed information\n * @param pubkey administrative contact pubkey\n * @param contact: administrative alternate contact\n * @param supported_nips a list of NIP numbers supported by\n * the relay\n * @param software identifying relay software URL\n * @param version string version identifier\n */\nexport interface BasicRelayInformation {\n // string identifying relay\n name: string\n description: string\n pubkey: string\n contact: string\n supported_nips: number[]\n software: string\n version: string\n // limitation?: Limitations\n}\n\n/**\n * * ## Extra Fields\n\n * * ### Server Limitations\n\n * These are limitations imposed by the relay on clients.\n * Your client should expect that requests which exceed\n * these practical_ limitations are rejected or fail immediately.\n * @param max_message_length this is the maximum number of\n * bytes for incoming JSON that the relay will attempt to\n * decode and act upon. When you send large subscriptions,\n * you will be limited by this value. It also effectively\n * limits the maximum size of any event. Value is calculated\n * from `[` to `]` and is after UTF-8 serialization (so some\n * unicode characters will cost 2-3 bytes). It is equal to\n * the maximum size of the WebSocket message frame.\n * @param max_subscriptions total number of subscriptions\n * that may be active on a single websocket connection to\n * this relay. It's possible that authenticated clients with\n * a (paid) relationship to the relay may have higher limits.\n * @param max_filters maximum number of filter values in\n * each subscription. Must be one or higher.\n * @param max_limit the relay server will clamp each\n * filter's `limit` value to this number.\n * This means the client won't be able to get more than this\n * number of events from a single subscription filter. This\n * clamping is typically done silently by the relay, but\n * with this number, you can know that there are additional\n * results if you narrowed your filter's time range or other\n * parameters.\n * @param max_subid_length maximum length of subscription id as a\n * string.\n * @param min_prefix for `authors` and `ids` filters which\n * are to match against a hex prefix, you must provide at\n * least this many hex digits in the prefix.\n * @param max_event_tags in any event, this is the maximum\n * number of elements in the `tags` list.\n * @param max_content_length maximum number of characters in\n * the `content` field of any event. This is a count of\n * unicode characters. After serializing into JSON it may be\n * larger (in bytes), and is still subject to the\n * max_message_length`, if defined.\n * @param min_pow_difficulty new events will require at\n * least this difficulty of PoW, based on [NIP-13](13.md),\n * or they will be rejected by this server.\n * @param auth_required this relay requires [NIP-42](42.md)\n * authentication to happen before a new connection may\n * perform any other action. Even if set to False,\n * authentication may be required for specific actions.\n * @param restricted_writes: this relay requires some kind\n * of condition to be fulfilled in order to accept events\n * (not necessarily, but including\n * @param payment_required this relay requires payment\n * before a new connection may perform any action.\n * @param created_at_lower_limit: 'created_at' lower limit\n * @param created_at_upper_limit: 'created_at' upper limit\n */\nexport interface Limitations {\n max_message_length: number\n max_subscriptions: number\n max_filters: number\n max_limit: number\n max_subid_length: number\n min_prefix: number\n max_event_tags: number\n max_content_length: number\n min_pow_difficulty: number\n auth_required: boolean\n payment_required: boolean\n created_at_lower_limit: number\n created_at_upper_limit: number\n restricted_writes: boolean\n}\n\nexport interface RetentionDetails {\n kinds: (number | number[])[]\n time?: number | null\n count?: number | null\n}\ntype AnyRetentionDetails = RetentionDetails\n/**\n * ### Event Retention\n\n * There may be a cost associated with storing data forever,\n * so relays may wish to state retention times. The values\n * stated here are defaults for unauthenticated users and\n * visitors. Paid users would likely have other policies.\n\n * Retention times are given in seconds, with `null`\n * indicating infinity. If zero is provided, this means the\n * event will not be stored at all, and preferably an error\n * will be provided when those are received.\n * ```json\n{\n...\n \"retention\": [\n { \"kinds\": [0, 1, [5, 7], [40, 49]], \"time\": 3600 },\n { \"kinds\": [[40000, 49999]], \"time\": 100 },\n { \"kinds\": [[30000, 39999]], \"count\": 1000 },\n { \"time\": 3600, \"count\": 10000 }\n ]\n...\n}\n```\n * @param retention is a list of specifications: each will\n * apply to either all kinds, or a subset of kinds. Ranges\n * may be specified for the kind field as a tuple of\n * inclusive start and end values. Events of indicated kind\n * (or all) are then limited to a `count` and/or time\n * period.\n\n * It is possible to effectively blacklist Nostr-based\n * protocols that rely on a specific `kind` number, by\n * giving a retention time of zero for those `kind` values.\n * While that is unfortunate, it does allow clients to\n * discover servers that will support their protocol quickly\n * via a single HTTP fetch.\n\n * There is no need to specify retention times for\n * _ephemeral events_ as defined in [NIP-16](16.md) since\n * they are not retained.\n */\nexport interface Retention {\n retention: AnyRetentionDetails[]\n}\n\n/**\n * Some relays may be governed by the arbitrary laws of a\n * nation state. This may limit what content can be stored\n * in cleartext on those relays. All clients are encouraged\n * to use encryption to work around this limitation.\n\n * It is not possible to describe the limitations of each\n * country's laws and policies which themselves are\n * typically vague and constantly shifting.\n\n * Therefore, this field allows the relay operator to\n * indicate which countries' laws might end up being\n * enforced on them, and then indirectly on their users'\n * content.\n\n * Users should be able to avoid relays in countries they\n * don't like, and/or select relays in more favourable\n * zones. Exposing this flexibility is up to the client\n * software.\n\n * @param relay_countries a list of two-level ISO country\n * codes (ISO 3166-1 alpha-2) whose laws and policies may\n * affect this relay. `EU` may be used for European Union\n * countries.\n\n * Remember that a relay may be hosted in a country which is\n * not the country of the legal entities who own the relay,\n * so it's very likely a number of countries are involved.\n */\nexport interface ContentLimitations {\n relay_countries: string[]\n}\n\n/**\n * ### Community Preferences\n\n * For public text notes at least, a relay may try to foster\n * a local community. This would encourage users to follow\n * the global feed on that relay, in addition to their usual\n * individual follows. To support this goal, relays MAY\n * specify some of the following values.\n\n * @param language_tags is an ordered list of [IETF\n * language\n * tags](https://en.wikipedia.org/wiki/IETF_language_tag\n * indicating the major languages spoken on the relay.\n * @param tags is a list of limitations on the topics to be\n * discussed. For example `sfw-only` indicates that only\n * \"Safe For Work\" content is encouraged on this relay. This\n * relies on assumptions of what the \"work\" \"community\"\n * feels \"safe\" talking about. In time, a common set of tags\n * may emerge that allow users to find relays that suit\n * their needs, and client software will be able to parse\n * these tags easily. The `bitcoin-only` tag indicates that\n * any _altcoin_, _\"crypto\"_ or _blockchain_ comments will\n * be ridiculed without mercy.\n * @param posting_policy is a link to a human-readable page\n * which specifies the community policies for the relay. In\n * cases where `sfw-only` is True, it's important to link to\n * a page which gets into the specifics of your posting\n * policy.\n\n * The `description` field should be used to describe your\n * community goals and values, in brief. The\n * `posting_policy` is for additional detail and legal\n * terms. Use the `tags` field to signify limitations on\n * content, or topics to be discussed, which could be\n * machine processed by appropriate client software.\n */\nexport interface CommunityPreferences {\n language_tags: string[]\n tags: string[]\n posting_policy: string\n}\n\nexport interface Amount {\n amount: number\n unit: 'msat'\n}\nexport interface PublicationAmount extends Amount {\n kinds: number[]\n}\nexport interface Subscription extends Amount {\n period: number\n}\nexport interface Fees {\n admission: Amount[]\n subscription: Subscription[]\n publication: PublicationAmount[]\n}\n/**\n * Relays that require payments may want to expose their fee\n * schedules.\n */\nexport interface PayToRelay {\n payments_url: string\n fees: Fees\n}\n\n/**\n * A URL pointing to an image to be used as an icon for the\n * relay. Recommended to be squared in shape.\n */\nexport interface Icon {\n icon: string\n}\n\nexport type RelayInformation = BasicRelayInformation &\n Partial & {\n limitation?: Partial\n } & Partial &\n Partial &\n Partial &\n Partial\n", "import { bytesToHex, concatBytes, hexToBytes } from '@noble/hashes/utils'\nimport { bech32 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport type NProfile = `nprofile1${string}`\nexport type NEvent = `nevent1${string}`\nexport type NAddr = `naddr1${string}`\nexport type NSec = `nsec1${string}`\nexport type NPub = `npub1${string}`\nexport type Note = `note1${string}`\nexport type Ncryptsec = `ncryptsec1${string}`\n\nexport const NostrTypeGuard = {\n isNProfile: (value?: string | null): value is NProfile => /^nprofile1[a-z\\d]+$/.test(value || ''),\n isNEvent: (value?: string | null): value is NEvent => /^nevent1[a-z\\d]+$/.test(value || ''),\n isNAddr: (value?: string | null): value is NAddr => /^naddr1[a-z\\d]+$/.test(value || ''),\n isNSec: (value?: string | null): value is NSec => /^nsec1[a-z\\d]{58}$/.test(value || ''),\n isNPub: (value?: string | null): value is NPub => /^npub1[a-z\\d]{58}$/.test(value || ''),\n isNote: (value?: string | null): value is Note => /^note1[a-z\\d]+$/.test(value || ''),\n isNcryptsec: (value?: string | null): value is Ncryptsec => /^ncryptsec1[a-z\\d]+$/.test(value || ''),\n}\n\nexport const Bech32MaxSize = 5000\n\n/**\n * Bech32 regex.\n * @see https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32\n */\nexport const BECH32_REGEX = /[\\x21-\\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/\n\nfunction integerToUint8Array(number: number) {\n // Create a Uint8Array with enough space to hold a 32-bit integer (4 bytes).\n const uint8Array = new Uint8Array(4)\n\n // Use bitwise operations to extract the bytes.\n uint8Array[0] = (number >> 24) & 0xff // Most significant byte (MSB)\n uint8Array[1] = (number >> 16) & 0xff\n uint8Array[2] = (number >> 8) & 0xff\n uint8Array[3] = number & 0xff // Least significant byte (LSB)\n\n return uint8Array\n}\n\nexport type ProfilePointer = {\n pubkey: string // hex\n relays?: string[]\n}\n\nexport type EventPointer = {\n id: string // hex\n relays?: string[]\n author?: string\n kind?: number\n}\n\nexport type AddressPointer = {\n identifier: string\n pubkey: string\n kind: number\n relays?: string[]\n}\n\nexport function decodeNostrURI(nip19code: string): ReturnType | { type: 'invalid'; data: null } {\n try {\n if (nip19code.startsWith('nostr:')) nip19code = nip19code.substring(6)\n return decode(nip19code)\n } catch (_err) {\n return { type: 'invalid', data: null }\n }\n}\n\nexport type DecodedNevent = {\n type: 'nevent'\n data: EventPointer\n}\n\nexport type DecodedNprofile = {\n type: 'nprofile'\n data: ProfilePointer\n}\n\nexport type DecodedNaddr = {\n type: 'naddr'\n data: AddressPointer\n}\n\nexport type DecodedNsec = {\n type: 'nsec'\n data: Uint8Array\n}\n\nexport type DecodedNpub = {\n type: 'npub'\n data: string\n}\n\nexport type DecodedNote = {\n type: 'note'\n data: string\n}\n\nexport type DecodedResult = DecodedNevent | DecodedNprofile | DecodedNaddr | DecodedNpub | DecodedNsec | DecodedNote\n\nexport function decode(nip19: NEvent): DecodedNevent\nexport function decode(nip19: NProfile): DecodedNprofile\nexport function decode(nip19: NAddr): DecodedNaddr\nexport function decode(nip19: NSec): DecodedNsec\nexport function decode(nip19: NPub): DecodedNpub\nexport function decode(nip19: Note): DecodedNote\nexport function decode(code: string): DecodedResult\nexport function decode(code: string): DecodedResult {\n let { prefix, words } = bech32.decode(code, Bech32MaxSize)\n let data = new Uint8Array(bech32.fromWords(words))\n\n switch (prefix) {\n case 'nprofile': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nprofile')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n\n return {\n type: 'nprofile',\n data: {\n pubkey: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n case 'nevent': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nevent')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n if (tlv[2] && tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (tlv[3] && tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'nevent',\n data: {\n id: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n author: tlv[2]?.[0] ? bytesToHex(tlv[2][0]) : undefined,\n kind: tlv[3]?.[0] ? parseInt(bytesToHex(tlv[3][0]), 16) : undefined,\n },\n }\n }\n\n case 'naddr': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for naddr')\n if (!tlv[2]?.[0]) throw new Error('missing TLV 2 for naddr')\n if (tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (!tlv[3]?.[0]) throw new Error('missing TLV 3 for naddr')\n if (tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'naddr',\n data: {\n identifier: utf8Decoder.decode(tlv[0][0]),\n pubkey: bytesToHex(tlv[2][0]),\n kind: parseInt(bytesToHex(tlv[3][0]), 16),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n\n case 'nsec':\n return { type: prefix, data }\n\n case 'npub':\n case 'note':\n return { type: prefix, data: bytesToHex(data) }\n\n default:\n throw new Error(`unknown prefix ${prefix}`)\n }\n}\n\ntype TLV = { [t: number]: Uint8Array[] }\n\nfunction parseTLV(data: Uint8Array): TLV {\n let result: TLV = {}\n let rest = data\n while (rest.length > 0) {\n let t = rest[0]\n let l = rest[1]\n let v = rest.slice(2, 2 + l)\n rest = rest.slice(2 + l)\n if (v.length < l) throw new Error(`not enough data to read on TLV ${t}`)\n result[t] = result[t] || []\n result[t].push(v)\n }\n return result\n}\n\nexport function nsecEncode(key: Uint8Array): NSec {\n return encodeBytes('nsec', key)\n}\n\nexport function npubEncode(hex: string): NPub {\n return encodeBytes('npub', hexToBytes(hex))\n}\n\nexport function noteEncode(hex: string): Note {\n return encodeBytes('note', hexToBytes(hex))\n}\n\nfunction encodeBech32(prefix: Prefix, data: Uint8Array): `${Prefix}1${string}` {\n let words = bech32.toWords(data)\n return bech32.encode(prefix, words, Bech32MaxSize) as `${Prefix}1${string}`\n}\n\nexport function encodeBytes(prefix: Prefix, bytes: Uint8Array): `${Prefix}1${string}` {\n return encodeBech32(prefix, bytes)\n}\n\nexport function nprofileEncode(profile: ProfilePointer): NProfile {\n let data = encodeTLV({\n 0: [hexToBytes(profile.pubkey)],\n 1: (profile.relays || []).map(url => utf8Encoder.encode(url)),\n })\n return encodeBech32('nprofile', data)\n}\n\nexport function neventEncode(event: EventPointer): NEvent {\n let kindArray\n if (event.kind !== undefined) {\n kindArray = integerToUint8Array(event.kind)\n }\n\n let data = encodeTLV({\n 0: [hexToBytes(event.id)],\n 1: (event.relays || []).map(url => utf8Encoder.encode(url)),\n 2: event.author ? [hexToBytes(event.author)] : [],\n 3: kindArray ? [new Uint8Array(kindArray)] : [],\n })\n\n return encodeBech32('nevent', data)\n}\n\nexport function naddrEncode(addr: AddressPointer): NAddr {\n let kind = new ArrayBuffer(4)\n new DataView(kind).setUint32(0, addr.kind, false)\n\n let data = encodeTLV({\n 0: [utf8Encoder.encode(addr.identifier)],\n 1: (addr.relays || []).map(url => utf8Encoder.encode(url)),\n 2: [hexToBytes(addr.pubkey)],\n 3: [new Uint8Array(kind)],\n })\n return encodeBech32('naddr', data)\n}\n\nfunction encodeTLV(tlv: TLV): Uint8Array {\n let entries: Uint8Array[] = []\n\n Object.entries(tlv)\n .reverse()\n .forEach(([t, vs]) => {\n vs.forEach(v => {\n let entry = new Uint8Array(v.length + 2)\n entry.set([parseInt(t)], 0)\n entry.set([v.length], 1)\n entry.set(v, 2)\n entries.push(entry)\n })\n })\n\n return concatBytes(...entries)\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAI;AAEJ,IAAI;AACF,WAAS;AACX,QAAE;AAAO;AAMT,eAAsB,sBAAsB,KAAwC;AAClF,SAAQ,OACN,MAAM,MAAM,IAAI,QAAQ,SAAS,SAAS,EAAE,QAAQ,UAAU,UAAU,GAAG;AAAA,IACzE,SAAS,EAAE,QAAQ,yBAAyB;AAAA,EAC9C,CAAC,GACD,KAAK;AACT;;;AChBA,IAAAA,gBAAoD;AACpD,kBAAuB;;;ACIvB,mBAAuC;AAHhC,IAAM,cAA2B,IAAI,YA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Q,GAAG;AAAA,EACb,CAAC;AAEH,SAAO,MAAM,IAAI,MAAM;AACzB;", + "names": ["import_utils", "GroupAdminPermission"] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip30.js b/node_modules/nostr-tools/lib/cjs/nip30.js new file mode 100644 index 0000000..9e14ced --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip30.js @@ -0,0 +1,53 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip30.ts +var nip30_exports = {}; +__export(nip30_exports, { + EMOJI_SHORTCODE_REGEX: () => EMOJI_SHORTCODE_REGEX, + matchAll: () => matchAll, + regex: () => regex, + replaceAll: () => replaceAll +}); +module.exports = __toCommonJS(nip30_exports); +var EMOJI_SHORTCODE_REGEX = /:(\w+):/; +var regex = () => new RegExp(`\\B${EMOJI_SHORTCODE_REGEX.source}\\B`, "g"); +function* matchAll(content) { + const matches = content.matchAll(regex()); + for (const match of matches) { + try { + const [shortcode, name] = match; + yield { + shortcode, + name, + start: match.index, + end: match.index + shortcode.length + }; + } catch (_e) { + } + } +} +function replaceAll(content, replacer) { + return content.replaceAll(regex(), (shortcode, name) => { + return replacer({ + shortcode, + name + }); + }); +} diff --git a/node_modules/nostr-tools/lib/cjs/nip30.js.map b/node_modules/nostr-tools/lib/cjs/nip30.js.map new file mode 100644 index 0000000..e1587de --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip30.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip30.ts"], + "sourcesContent": ["/** Regex for a single emoji shortcode. */\nexport const EMOJI_SHORTCODE_REGEX = /:(\\w+):/\n\n/** Regex to find emoji shortcodes in content. */\nexport const regex = (): RegExp => new RegExp(`\\\\B${EMOJI_SHORTCODE_REGEX.source}\\\\B`, 'g')\n\n/** Represents a Nostr custom emoji. */\nexport interface CustomEmoji {\n /** The matched emoji name with colons. */\n shortcode: `:${string}:`\n /** The matched emoji name without colons. */\n name: string\n}\n\n/** Match result for a custom emoji in text content. */\nexport interface CustomEmojiMatch extends CustomEmoji {\n /** Index where the emoji begins in the text content. */\n start: number\n /** Index where the emoji ends in the text content. */\n end: number\n}\n\n/** Find all custom emoji shortcodes. */\nexport function* matchAll(content: string): Iterable {\n const matches = content.matchAll(regex())\n\n for (const match of matches) {\n try {\n const [shortcode, name] = match\n\n yield {\n shortcode: shortcode as `:${string}:`,\n name,\n start: match.index!,\n end: match.index! + shortcode.length,\n }\n } catch (_e) {\n // do nothing\n }\n }\n}\n\n/** Replace all emoji shortcodes in the content. */\nexport function replaceAll(content: string, replacer: (match: CustomEmoji) => string): string {\n return content.replaceAll(regex(), (shortcode, name) => {\n return replacer({\n shortcode: shortcode as `:${string}:`,\n name,\n })\n })\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACO,IAAM,wBAAwB;AAG9B,IAAM,QAAQ,MAAc,IAAI,OAAO,MAAM,sBAAsB,aAAa,GAAG;AAmBnF,UAAU,SAAS,SAA6C;AACrE,QAAM,UAAU,QAAQ,SAAS,MAAM,CAAC;AAExC,aAAW,SAAS,SAAS;AAC3B,QAAI;AACF,YAAM,CAAC,WAAW,IAAI,IAAI;AAE1B,YAAM;AAAA,QACJ;AAAA,QACA;AAAA,QACA,OAAO,MAAM;AAAA,QACb,KAAK,MAAM,QAAS,UAAU;AAAA,MAChC;AAAA,IACF,SAAS,IAAP;AAAA,IAEF;AAAA,EACF;AACF;AAGO,SAAS,WAAW,SAAiB,UAAkD;AAC5F,SAAO,QAAQ,WAAW,MAAM,GAAG,CAAC,WAAW,SAAS;AACtD,WAAO,SAAS;AAAA,MACd;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AACH;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip39.js b/node_modules/nostr-tools/lib/cjs/nip39.js new file mode 100644 index 0000000..2ca0582 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip39.js @@ -0,0 +1,42 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip39.ts +var nip39_exports = {}; +__export(nip39_exports, { + useFetchImplementation: () => useFetchImplementation, + validateGithub: () => validateGithub +}); +module.exports = __toCommonJS(nip39_exports); +var _fetch; +try { + _fetch = fetch; +} catch { +} +function useFetchImplementation(fetchImplementation) { + _fetch = fetchImplementation; +} +async function validateGithub(pubkey, username, proof) { + try { + let res = await (await _fetch(`https://gist.github.com/${username}/${proof}/raw`)).text(); + return res === `Verifying that I control the following Nostr public key: ${pubkey}`; + } catch (_) { + return false; + } +} diff --git a/node_modules/nostr-tools/lib/cjs/nip39.js.map b/node_modules/nostr-tools/lib/cjs/nip39.js.map new file mode 100644 index 0000000..48da83d --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip39.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip39.ts"], + "sourcesContent": ["var _fetch: any\n\ntry {\n _fetch = fetch\n} catch {}\n\nexport function useFetchImplementation(fetchImplementation: any) {\n _fetch = fetchImplementation\n}\n\nexport async function validateGithub(pubkey: string, username: string, proof: string): Promise {\n try {\n let res = await (await _fetch(`https://gist.github.com/${username}/${proof}/raw`)).text()\n return res === `Verifying that I control the following Nostr public key: ${pubkey}`\n } catch (_) {\n return false\n }\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAI;AAEJ,IAAI;AACF,WAAS;AACX,QAAE;AAAO;AAEF,SAAS,uBAAuB,qBAA0B;AAC/D,WAAS;AACX;AAEA,eAAsB,eAAe,QAAgB,UAAkB,OAAiC;AACtG,MAAI;AACF,QAAI,MAAM,OAAO,MAAM,OAAO,2BAA2B,YAAY,WAAW,GAAG,KAAK;AACxF,WAAO,QAAQ,4DAA4D;AAAA,EAC7E,SAAS,GAAP;AACA,WAAO;AAAA,EACT;AACF;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip40.js b/node_modules/nostr-tools/lib/cjs/nip40.js new file mode 100644 index 0000000..1b76d36 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip40.js @@ -0,0 +1,63 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip40.ts +var nip40_exports = {}; +__export(nip40_exports, { + getExpiration: () => getExpiration, + isEventExpired: () => isEventExpired, + onExpire: () => onExpire, + waitForExpire: () => waitForExpire +}); +module.exports = __toCommonJS(nip40_exports); +function getExpiration(event) { + const tag = event.tags.find(([name]) => name === "expiration"); + if (tag) { + return new Date(parseInt(tag[1]) * 1e3); + } +} +function isEventExpired(event) { + const expiration = getExpiration(event); + if (expiration) { + return Date.now() > expiration.getTime(); + } else { + return false; + } +} +async function waitForExpire(event) { + const expiration = getExpiration(event); + if (expiration) { + const diff = expiration.getTime() - Date.now(); + if (diff > 0) { + await sleep(diff); + return event; + } else { + return event; + } + } else { + throw new Error("Event has no expiration"); + } +} +function onExpire(event, callback) { + waitForExpire(event).then(callback).catch(() => { + }); +} +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/node_modules/nostr-tools/lib/cjs/nip40.js.map b/node_modules/nostr-tools/lib/cjs/nip40.js.map new file mode 100644 index 0000000..29e23c1 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip40.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip40.ts"], + "sourcesContent": ["import { Event } from './core.ts'\n\n/** Get the expiration of the event as a `Date` object, if any. */\nfunction getExpiration(event: Event): Date | undefined {\n const tag = event.tags.find(([name]) => name === 'expiration')\n if (tag) {\n return new Date(parseInt(tag[1]) * 1000)\n }\n}\n\n/** Check if the event has expired. */\nfunction isEventExpired(event: Event): boolean {\n const expiration = getExpiration(event)\n if (expiration) {\n return Date.now() > expiration.getTime()\n } else {\n return false\n }\n}\n\n/** Returns a promise that resolves when the event expires. */\nasync function waitForExpire(event: Event): Promise {\n const expiration = getExpiration(event)\n if (expiration) {\n const diff = expiration.getTime() - Date.now()\n if (diff > 0) {\n await sleep(diff)\n return event\n } else {\n return event\n }\n } else {\n throw new Error('Event has no expiration')\n }\n}\n\n/** Calls the callback when the event expires. */\nfunction onExpire(event: Event, callback: (event: Event) => void): void {\n waitForExpire(event)\n .then(callback)\n .catch(() => {})\n}\n\n/** Resolves when the given number of milliseconds have elapsed. */\nfunction sleep(ms: number): Promise {\n return new Promise(resolve => setTimeout(resolve, ms))\n}\n\nexport { getExpiration, isEventExpired, waitForExpire, onExpire }\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,SAAS,cAAc,OAAgC;AACrD,QAAM,MAAM,MAAM,KAAK,KAAK,CAAC,CAAC,IAAI,MAAM,SAAS,YAAY;AAC7D,MAAI,KAAK;AACP,WAAO,IAAI,KAAK,SAAS,IAAI,EAAE,IAAI,GAAI;AAAA,EACzC;AACF;AAGA,SAAS,eAAe,OAAuB;AAC7C,QAAM,aAAa,cAAc,KAAK;AACtC,MAAI,YAAY;AACd,WAAO,KAAK,IAAI,IAAI,WAAW,QAAQ;AAAA,EACzC,OAAO;AACL,WAAO;AAAA,EACT;AACF;AAGA,eAAe,cAAc,OAA8B;AACzD,QAAM,aAAa,cAAc,KAAK;AACtC,MAAI,YAAY;AACd,UAAM,OAAO,WAAW,QAAQ,IAAI,KAAK,IAAI;AAC7C,QAAI,OAAO,GAAG;AACZ,YAAM,MAAM,IAAI;AAChB,aAAO;AAAA,IACT,OAAO;AACL,aAAO;AAAA,IACT;AAAA,EACF,OAAO;AACL,UAAM,IAAI,MAAM,yBAAyB;AAAA,EAC3C;AACF;AAGA,SAAS,SAAS,OAAc,UAAwC;AACtE,gBAAc,KAAK,EAChB,KAAK,QAAQ,EACb,MAAM,MAAM;AAAA,EAAC,CAAC;AACnB;AAGA,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,aAAW,WAAW,SAAS,EAAE,CAAC;AACvD;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip42.js b/node_modules/nostr-tools/lib/cjs/nip42.js new file mode 100644 index 0000000..469093a --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip42.js @@ -0,0 +1,41 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip42.ts +var nip42_exports = {}; +__export(nip42_exports, { + makeAuthEvent: () => makeAuthEvent +}); +module.exports = __toCommonJS(nip42_exports); + +// kinds.ts +var ClientAuth = 22242; + +// nip42.ts +function makeAuthEvent(relayURL, challenge) { + return { + kind: ClientAuth, + created_at: Math.floor(Date.now() / 1e3), + tags: [ + ["relay", relayURL], + ["challenge", challenge] + ], + content: "" + }; +} diff --git a/node_modules/nostr-tools/lib/cjs/nip42.js.map b/node_modules/nostr-tools/lib/cjs/nip42.js.map new file mode 100644 index 0000000..5bb442e --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip42.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip42.ts", "../../kinds.ts"], + "sourcesContent": ["import { EventTemplate } from './core.ts'\nimport { ClientAuth } from './kinds.ts'\n\n/**\n * creates an EventTemplate for an AUTH event to be signed.\n */\nexport function makeAuthEvent(relayURL: string, challenge: string): EventTemplate {\n return {\n kind: ClientAuth,\n created_at: Math.floor(Date.now() / 1000),\n tags: [\n ['relay', relayURL],\n ['challenge', challenge],\n ],\n content: '',\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACqIO,IAAM,aAAa;;;AD/HnB,SAAS,cAAc,UAAkB,WAAkC;AAChF,SAAO;AAAA,IACL,MAAM;AAAA,IACN,YAAY,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAAA,IACxC,MAAM;AAAA,MACJ,CAAC,SAAS,QAAQ;AAAA,MAClB,CAAC,aAAa,SAAS;AAAA,IACzB;AAAA,IACA,SAAS;AAAA,EACX;AACF;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip44.js b/node_modules/nostr-tools/lib/cjs/nip44.js new file mode 100644 index 0000000..649b30d --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip44.js @@ -0,0 +1,143 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip44.ts +var nip44_exports = {}; +__export(nip44_exports, { + decrypt: () => decrypt, + encrypt: () => encrypt, + getConversationKey: () => getConversationKey, + v2: () => v2 +}); +module.exports = __toCommonJS(nip44_exports); +var import_chacha = require("@noble/ciphers/chacha"); +var import_utils2 = require("@noble/ciphers/utils"); +var import_secp256k1 = require("@noble/curves/secp256k1"); +var import_hkdf = require("@noble/hashes/hkdf"); +var import_hmac = require("@noble/hashes/hmac"); +var import_sha256 = require("@noble/hashes/sha256"); +var import_utils3 = require("@noble/hashes/utils"); +var import_base = require("@scure/base"); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// nip44.ts +var minPlaintextSize = 1; +var maxPlaintextSize = 65535; +function getConversationKey(privkeyA, pubkeyB) { + const sharedX = import_secp256k1.secp256k1.getSharedSecret(privkeyA, "02" + pubkeyB).subarray(1, 33); + return (0, import_hkdf.extract)(import_sha256.sha256, sharedX, "nip44-v2"); +} +function getMessageKeys(conversationKey, nonce) { + const keys = (0, import_hkdf.expand)(import_sha256.sha256, conversationKey, nonce, 76); + return { + chacha_key: keys.subarray(0, 32), + chacha_nonce: keys.subarray(32, 44), + hmac_key: keys.subarray(44, 76) + }; +} +function calcPaddedLen(len) { + if (!Number.isSafeInteger(len) || len < 1) + throw new Error("expected positive integer"); + if (len <= 32) + return 32; + const nextPower = 1 << Math.floor(Math.log2(len - 1)) + 1; + const chunk = nextPower <= 256 ? 32 : nextPower / 8; + return chunk * (Math.floor((len - 1) / chunk) + 1); +} +function writeU16BE(num) { + if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize) + throw new Error("invalid plaintext size: must be between 1 and 65535 bytes"); + const arr = new Uint8Array(2); + new DataView(arr.buffer).setUint16(0, num, false); + return arr; +} +function pad(plaintext) { + const unpadded = utf8Encoder.encode(plaintext); + const unpaddedLen = unpadded.length; + const prefix = writeU16BE(unpaddedLen); + const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen); + return (0, import_utils3.concatBytes)(prefix, unpadded, suffix); +} +function unpad(padded) { + const unpaddedLen = new DataView(padded.buffer).getUint16(0); + const unpadded = padded.subarray(2, 2 + unpaddedLen); + if (unpaddedLen < minPlaintextSize || unpaddedLen > maxPlaintextSize || unpadded.length !== unpaddedLen || padded.length !== 2 + calcPaddedLen(unpaddedLen)) + throw new Error("invalid padding"); + return utf8Decoder.decode(unpadded); +} +function hmacAad(key, message, aad) { + if (aad.length !== 32) + throw new Error("AAD associated data must be 32 bytes"); + const combined = (0, import_utils3.concatBytes)(aad, message); + return (0, import_hmac.hmac)(import_sha256.sha256, key, combined); +} +function decodePayload(payload) { + if (typeof payload !== "string") + throw new Error("payload must be a valid string"); + const plen = payload.length; + if (plen < 132 || plen > 87472) + throw new Error("invalid payload length: " + plen); + if (payload[0] === "#") + throw new Error("unknown encryption version"); + let data; + try { + data = import_base.base64.decode(payload); + } catch (error) { + throw new Error("invalid base64: " + error.message); + } + const dlen = data.length; + if (dlen < 99 || dlen > 65603) + throw new Error("invalid data length: " + dlen); + const vers = data[0]; + if (vers !== 2) + throw new Error("unknown encryption version " + vers); + return { + nonce: data.subarray(1, 33), + ciphertext: data.subarray(33, -32), + mac: data.subarray(-32) + }; +} +function encrypt(plaintext, conversationKey, nonce = (0, import_utils3.randomBytes)(32)) { + const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); + const padded = pad(plaintext); + const ciphertext = (0, import_chacha.chacha20)(chacha_key, chacha_nonce, padded); + const mac = hmacAad(hmac_key, ciphertext, nonce); + return import_base.base64.encode((0, import_utils3.concatBytes)(new Uint8Array([2]), nonce, ciphertext, mac)); +} +function decrypt(payload, conversationKey) { + const { nonce, ciphertext, mac } = decodePayload(payload); + const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); + const calculatedMac = hmacAad(hmac_key, ciphertext, nonce); + if (!(0, import_utils2.equalBytes)(calculatedMac, mac)) + throw new Error("invalid MAC"); + const padded = (0, import_chacha.chacha20)(chacha_key, chacha_nonce, ciphertext); + return unpad(padded); +} +var v2 = { + utils: { + getConversationKey, + calcPaddedLen + }, + encrypt, + decrypt +}; diff --git a/node_modules/nostr-tools/lib/cjs/nip44.js.map b/node_modules/nostr-tools/lib/cjs/nip44.js.map new file mode 100644 index 0000000..5690c75 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip44.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip44.ts", "../../utils.ts"], + "sourcesContent": ["import { chacha20 } from '@noble/ciphers/chacha'\nimport { equalBytes } from '@noble/ciphers/utils'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { extract as hkdf_extract, expand as hkdf_expand } from '@noble/hashes/hkdf'\nimport { hmac } from '@noble/hashes/hmac'\nimport { sha256 } from '@noble/hashes/sha256'\nimport { concatBytes, randomBytes } from '@noble/hashes/utils'\nimport { base64 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nconst minPlaintextSize = 0x0001 // 1b msg => padded to 32b\nconst maxPlaintextSize = 0xffff // 65535 (64kb-1) => padded to 64kb\n\nexport function getConversationKey(privkeyA: Uint8Array, pubkeyB: string): Uint8Array {\n const sharedX = secp256k1.getSharedSecret(privkeyA, '02' + pubkeyB).subarray(1, 33)\n return hkdf_extract(sha256, sharedX, 'nip44-v2')\n}\n\nfunction getMessageKeys(\n conversationKey: Uint8Array,\n nonce: Uint8Array,\n): { chacha_key: Uint8Array; chacha_nonce: Uint8Array; hmac_key: Uint8Array } {\n const keys = hkdf_expand(sha256, conversationKey, nonce, 76)\n return {\n chacha_key: keys.subarray(0, 32),\n chacha_nonce: keys.subarray(32, 44),\n hmac_key: keys.subarray(44, 76),\n }\n}\n\nfunction calcPaddedLen(len: number): number {\n if (!Number.isSafeInteger(len) || len < 1) throw new Error('expected positive integer')\n if (len <= 32) return 32\n const nextPower = 1 << (Math.floor(Math.log2(len - 1)) + 1)\n const chunk = nextPower <= 256 ? 32 : nextPower / 8\n return chunk * (Math.floor((len - 1) / chunk) + 1)\n}\n\nfunction writeU16BE(num: number): Uint8Array {\n if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize)\n throw new Error('invalid plaintext size: must be between 1 and 65535 bytes')\n const arr = new Uint8Array(2)\n new DataView(arr.buffer).setUint16(0, num, false)\n return arr\n}\n\nfunction pad(plaintext: string): Uint8Array {\n const unpadded = utf8Encoder.encode(plaintext)\n const unpaddedLen = unpadded.length\n const prefix = writeU16BE(unpaddedLen)\n const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen)\n return concatBytes(prefix, unpadded, suffix)\n}\n\nfunction unpad(padded: Uint8Array): string {\n const unpaddedLen = new DataView(padded.buffer).getUint16(0)\n const unpadded = padded.subarray(2, 2 + unpaddedLen)\n if (\n unpaddedLen < minPlaintextSize ||\n unpaddedLen > maxPlaintextSize ||\n unpadded.length !== unpaddedLen ||\n padded.length !== 2 + calcPaddedLen(unpaddedLen)\n )\n throw new Error('invalid padding')\n return utf8Decoder.decode(unpadded)\n}\n\nfunction hmacAad(key: Uint8Array, message: Uint8Array, aad: Uint8Array): Uint8Array {\n if (aad.length !== 32) throw new Error('AAD associated data must be 32 bytes')\n const combined = concatBytes(aad, message)\n return hmac(sha256, key, combined)\n}\n\n// metadata: always 65b (version: 1b, nonce: 32b, max: 32b)\n// plaintext: 1b to 0xffff\n// padded plaintext: 32b to 0xffff\n// ciphertext: 32b+2 to 0xffff+2\n// raw payload: 99 (65+32+2) to 65603 (65+0xffff+2)\n// compressed payload (base64): 132b to 87472b\nfunction decodePayload(payload: string): { nonce: Uint8Array; ciphertext: Uint8Array; mac: Uint8Array } {\n if (typeof payload !== 'string') throw new Error('payload must be a valid string')\n const plen = payload.length\n if (plen < 132 || plen > 87472) throw new Error('invalid payload length: ' + plen)\n if (payload[0] === '#') throw new Error('unknown encryption version')\n let data: Uint8Array\n try {\n data = base64.decode(payload)\n } catch (error) {\n throw new Error('invalid base64: ' + (error as any).message)\n }\n const dlen = data.length\n if (dlen < 99 || dlen > 65603) throw new Error('invalid data length: ' + dlen)\n const vers = data[0]\n if (vers !== 2) throw new Error('unknown encryption version ' + vers)\n return {\n nonce: data.subarray(1, 33),\n ciphertext: data.subarray(33, -32),\n mac: data.subarray(-32),\n }\n}\n\nexport function encrypt(plaintext: string, conversationKey: Uint8Array, nonce: Uint8Array = randomBytes(32)): string {\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n const padded = pad(plaintext)\n const ciphertext = chacha20(chacha_key, chacha_nonce, padded)\n const mac = hmacAad(hmac_key, ciphertext, nonce)\n return base64.encode(concatBytes(new Uint8Array([2]), nonce, ciphertext, mac))\n}\n\nexport function decrypt(payload: string, conversationKey: Uint8Array): string {\n const { nonce, ciphertext, mac } = decodePayload(payload)\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n const calculatedMac = hmacAad(hmac_key, ciphertext, nonce)\n if (!equalBytes(calculatedMac, mac)) throw new Error('invalid MAC')\n const padded = chacha20(chacha_key, chacha_nonce, ciphertext)\n return unpad(padded)\n}\n\nexport const v2 = {\n utils: {\n getConversationKey,\n calcPaddedLen,\n },\n encrypt,\n decrypt,\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAyB;AACzB,IAAAA,gBAA2B;AAC3B,uBAA0B;AAC1B,kBAA+D;AAC/D,kBAAqB;AACrB,oBAAuB;AACvB,IAAAA,gBAAyC;AACzC,kBAAuB;;;ACFvB,mBAAuC;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;;;ADQxD,IAAM,mBAAmB;AACzB,IAAM,mBAAmB;AAElB,SAAS,mBAAmB,UAAsB,SAA6B;AACpF,QAAM,UAAU,2BAAU,gBAAgB,UAAU,OAAO,OAAO,EAAE,SAAS,GAAG,EAAE;AAClF,aAAO,YAAAC,SAAa,sBAAQ,SAAS,UAAU;AACjD;AAEA,SAAS,eACP,iBACA,OAC4E;AAC5E,QAAM,WAAO,YAAAC,QAAY,sBAAQ,iBAAiB,OAAO,EAAE;AAC3D,SAAO;AAAA,IACL,YAAY,KAAK,SAAS,GAAG,EAAE;AAAA,IAC/B,cAAc,KAAK,SAAS,IAAI,EAAE;AAAA,IAClC,UAAU,KAAK,SAAS,IAAI,EAAE;AAAA,EAChC;AACF;AAEA,SAAS,cAAc,KAAqB;AAC1C,MAAI,CAAC,OAAO,cAAc,GAAG,KAAK,MAAM;AAAG,UAAM,IAAI,MAAM,2BAA2B;AACtF,MAAI,OAAO;AAAI,WAAO;AACtB,QAAM,YAAY,KAAM,KAAK,MAAM,KAAK,KAAK,MA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O;AAAA,IACL;AAAA,IACA;AAAA,EACF;AAAA,EACA;AAAA,EACA;AACF;", + "names": ["import_utils", "hkdf_extract", "hkdf_expand"] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip46.js b/node_modules/nostr-tools/lib/cjs/nip46.js new file mode 100644 index 0000000..c5c8d6d --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip46.js @@ -0,0 +1,1239 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip46.ts +var nip46_exports = {}; +__export(nip46_exports, { + BUNKER_REGEX: () => BUNKER_REGEX, + BunkerSigner: () => BunkerSigner, + createAccount: () => createAccount, + fetchBunkerProviders: () => fetchBunkerProviders, + parseBunkerInput: () => parseBunkerInput, + queryBunkerProfile: () => queryBunkerProfile, + toBunkerURL: () => toBunkerURL, + useFetchImplementation: () => useFetchImplementation +}); +module.exports = __toCommonJS(nip46_exports); + +// pure.ts +var import_secp256k1 = require("@noble/curves/secp256k1"); +var import_utils2 = require("@noble/hashes/utils"); + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +var import_sha256 = require("@noble/hashes/sha256"); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); +function normalizeURL(url) { + try { + if (url.indexOf("://") === -1) + url = "wss://" + url; + let p = new URL(url); + p.pathname = p.pathname.replace(/\/+/g, "/"); + if (p.pathname.endsWith("/")) + p.pathname = p.pathname.slice(0, -1); + if (p.port === "80" && p.protocol === "ws:" || p.port === "443" && p.protocol === "wss:") + p.port = ""; + p.searchParams.sort(); + p.hash = ""; + return p.toString(); + } catch (e) { + throw new Error(`Invalid URL: ${url}`); + } +} +var QueueNode = class { + value; + next = null; + prev = null; + constructor(message) { + this.value = message; + } +}; +var Queue = class { + first; + last; + constructor() { + this.first = null; + this.last = null; + } + enqueue(value) { + const newNode = new QueueNode(value); + if (!this.last) { + this.first = newNode; + this.last = newNode; + } else if (this.last === this.first) { + this.last = newNode; + this.last.prev = this.first; + this.first.next = newNode; + } else { + newNode.prev = this.last; + this.last.next = newNode; + this.last = newNode; + } + return true; + } + dequeue() { + if (!this.first) + return null; + if (this.first === this.last) { + const target2 = this.first; + this.first = null; + this.last = null; + return target2.value; + } + const target = this.first; + this.first = target.next; + if (this.first) { + this.first.prev = null; + } + return target.value; + } +}; + +// pure.ts +var JS = class { + generateSecretKey() { + return import_secp256k1.schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = import_secp256k1.schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = (0, import_sha256.sha256)(utf8Encoder.encode(serializeEvent(event))); + return (0, import_utils2.bytesToHex)(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// nip44.ts +var import_chacha = require("@noble/ciphers/chacha"); +var import_utils4 = require("@noble/ciphers/utils"); +var import_secp256k12 = require("@noble/curves/secp256k1"); +var import_hkdf = require("@noble/hashes/hkdf"); +var import_hmac = require("@noble/hashes/hmac"); +var import_sha2562 = require("@noble/hashes/sha256"); +var import_utils5 = require("@noble/hashes/utils"); +var import_base = require("@scure/base"); +var minPlaintextSize = 1; +var maxPlaintextSize = 65535; +function getConversationKey(privkeyA, pubkeyB) { + const sharedX = import_secp256k12.secp256k1.getSharedSecret(privkeyA, "02" + pubkeyB).subarray(1, 33); + return (0, import_hkdf.extract)(import_sha2562.sha256, sharedX, "nip44-v2"); +} +function getMessageKeys(conversationKey, nonce) { + const keys = (0, import_hkdf.expand)(import_sha2562.sha256, conversationKey, nonce, 76); + return { + chacha_key: keys.subarray(0, 32), + chacha_nonce: keys.subarray(32, 44), + hmac_key: keys.subarray(44, 76) + }; +} +function calcPaddedLen(len) { + if (!Number.isSafeInteger(len) || len < 1) + throw new Error("expected positive integer"); + if (len <= 32) + return 32; + const nextPower = 1 << Math.floor(Math.log2(len - 1)) + 1; + const chunk = nextPower <= 256 ? 32 : nextPower / 8; + return chunk * (Math.floor((len - 1) / chunk) + 1); +} +function writeU16BE(num) { + if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize) + throw new Error("invalid plaintext size: must be between 1 and 65535 bytes"); + const arr = new Uint8Array(2); + new DataView(arr.buffer).setUint16(0, num, false); + return arr; +} +function pad(plaintext) { + const unpadded = utf8Encoder.encode(plaintext); + const unpaddedLen = unpadded.length; + const prefix = writeU16BE(unpaddedLen); + const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen); + return (0, import_utils5.concatBytes)(prefix, unpadded, suffix); +} +function unpad(padded) { + const unpaddedLen = new DataView(padded.buffer).getUint16(0); + const unpadded = padded.subarray(2, 2 + unpaddedLen); + if (unpaddedLen < minPlaintextSize || unpaddedLen > maxPlaintextSize || unpadded.length !== unpaddedLen || padded.length !== 2 + calcPaddedLen(unpaddedLen)) + throw new Error("invalid padding"); + return utf8Decoder.decode(unpadded); +} +function hmacAad(key, message, aad) { + if (aad.length !== 32) + throw new Error("AAD associated data must be 32 bytes"); + const combined = (0, import_utils5.concatBytes)(aad, message); + return (0, import_hmac.hmac)(import_sha2562.sha256, key, combined); +} +function decodePayload(payload) { + if (typeof payload !== "string") + throw new Error("payload must be a valid string"); + const plen = payload.length; + if (plen < 132 || plen > 87472) + throw new Error("invalid payload length: " + plen); + if (payload[0] === "#") + throw new Error("unknown encryption version"); + let data; + try { + data = import_base.base64.decode(payload); + } catch (error) { + throw new Error("invalid base64: " + error.message); + } + const dlen = data.length; + if (dlen < 99 || dlen > 65603) + throw new Error("invalid data length: " + dlen); + const vers = data[0]; + if (vers !== 2) + throw new Error("unknown encryption version " + vers); + return { + nonce: data.subarray(1, 33), + ciphertext: data.subarray(33, -32), + mac: data.subarray(-32) + }; +} +function encrypt(plaintext, conversationKey, nonce = (0, import_utils5.randomBytes)(32)) { + const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); + const padded = pad(plaintext); + const ciphertext = (0, import_chacha.chacha20)(chacha_key, chacha_nonce, padded); + const mac = hmacAad(hmac_key, ciphertext, nonce); + return import_base.base64.encode((0, import_utils5.concatBytes)(new Uint8Array([2]), nonce, ciphertext, mac)); +} +function decrypt(payload, conversationKey) { + const { nonce, ciphertext, mac } = decodePayload(payload); + const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); + const calculatedMac = hmacAad(hmac_key, ciphertext, nonce); + if (!(0, import_utils4.equalBytes)(calculatedMac, mac)) + throw new Error("invalid MAC"); + const padded = (0, import_chacha.chacha20)(chacha_key, chacha_nonce, ciphertext); + return unpad(padded); +} + +// nip05.ts +var NIP05_REGEX = /^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/; +var _fetch; +try { + _fetch = fetch; +} catch (_) { + null; +} + +// kinds.ts +var ClientAuth = 22242; +var NostrConnect = 24133; +var Handlerinformation = 31990; + +// filter.ts +function matchFilter(filter, event) { + if (filter.ids && filter.ids.indexOf(event.id) === -1) { + return false; + } + if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) { + return false; + } + if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) { + return false; + } + for (let f in filter) { + if (f[0] === "#") { + let tagName = f.slice(1); + let values = filter[`#${tagName}`]; + if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values.indexOf(v) !== -1)) + return false; + } + } + if (filter.since && event.created_at < filter.since) + return false; + if (filter.until && event.created_at > filter.until) + return false; + return true; +} +function matchFilters(filters, event) { + for (let i2 = 0; i2 < filters.length; i2++) { + if (matchFilter(filters[i2], event)) { + return true; + } + } + return false; +} + +// fakejson.ts +function getHex64(json, field) { + let len = field.length + 3; + let idx = json.indexOf(`"${field}":`) + len; + let s = json.slice(idx).indexOf(`"`) + idx + 1; + return json.slice(s, s + 64); +} +function getSubscriptionId(json) { + let idx = json.slice(0, 22).indexOf(`"EVENT"`); + if (idx === -1) + return null; + let pstart = json.slice(idx + 7 + 1).indexOf(`"`); + if (pstart === -1) + return null; + let start = idx + 7 + 1 + pstart; + let pend = json.slice(start + 1, 80).indexOf(`"`); + if (pend === -1) + return null; + let end = start + 1 + pend; + return json.slice(start + 1, end); +} + +// nip42.ts +function makeAuthEvent(relayURL, challenge) { + return { + kind: ClientAuth, + created_at: Math.floor(Date.now() / 1e3), + tags: [ + ["relay", relayURL], + ["challenge", challenge] + ], + content: "" + }; +} + +// helpers.ts +async function yieldThread() { + return new Promise((resolve) => { + const ch = new MessageChannel(); + const handler = () => { + ch.port1.removeEventListener("message", handler); + resolve(); + }; + ch.port1.addEventListener("message", handler); + ch.port2.postMessage(0); + ch.port1.start(); + }); +} +var alwaysTrue = (t) => { + t[verifiedSymbol] = true; + return true; +}; + +// abstract-relay.ts +var SendingOnClosedConnection = class extends Error { + constructor(message, relay) { + super(`Tried to send message '${message} on a closed connection to ${relay}.`); + this.name = "SendingOnClosedConnection"; + } +}; +var AbstractRelay = class { + url; + _connected = false; + onclose = null; + onnotice = (msg) => console.debug(`NOTICE from ${this.url}: ${msg}`); + baseEoseTimeout = 4400; + connectionTimeout = 4400; + publishTimeout = 4400; + pingFrequency = 2e4; + pingTimeout = 2e4; + openSubs = /* @__PURE__ */ new Map(); + enablePing; + connectionTimeoutHandle; + connectionPromise; + openCountRequests = /* @__PURE__ */ new Map(); + openEventPublishes = /* @__PURE__ */ new Map(); + ws; + incomingMessageQueue = new Queue(); + queueRunning = false; + challenge; + authPromise; + serial = 0; + verifyEvent; + _WebSocket; + constructor(url, opts) { + this.url = normalizeURL(url); + this.verifyEvent = opts.verifyEvent; + this._WebSocket = opts.websocketImplementation || WebSocket; + this.enablePing = opts.enablePing; + } + static async connect(url, opts) { + const relay = new AbstractRelay(url, opts); + await relay.connect(); + return relay; + } + closeAllSubscriptions(reason) { + for (let [_, sub] of this.openSubs) { + sub.close(reason); + } + this.openSubs.clear(); + for (let [_, ep] of this.openEventPublishes) { + ep.reject(new Error(reason)); + } + this.openEventPublishes.clear(); + for (let [_, cr] of this.openCountRequests) { + cr.reject(new Error(reason)); + } + this.openCountRequests.clear(); + } + get connected() { + return this._connected; + } + async connect() { + if (this.connectionPromise) + return this.connectionPromise; + this.challenge = void 0; + this.authPromise = void 0; + this.connectionPromise = new Promise((resolve, reject) => { + this.connectionTimeoutHandle = setTimeout(() => { + reject("connection timed out"); + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection timed out"); + }, this.connectionTimeout); + try { + this.ws = new this._WebSocket(this.url); + } catch (err) { + clearTimeout(this.connectionTimeoutHandle); + reject(err); + return; + } + this.ws.onopen = () => { + clearTimeout(this.connectionTimeoutHandle); + this._connected = true; + if (this.enablePing) { + this.pingpong(); + } + resolve(); + }; + this.ws.onerror = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket error"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection errored"); + } + }; + this.ws.onclose = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket closed"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection closed"); + } + }; + this.ws.onmessage = this._onmessage.bind(this); + }); + return this.connectionPromise; + } + async waitForPingPong() { + return new Promise((res, err) => { + ; + this.ws && this.ws.on && this.ws.on("pong", () => res(true)) || err("ws can't listen for pong"); + this.ws && this.ws.ping && this.ws.ping(); + }); + } + async waitForDummyReq() { + return new Promise((resolve, _) => { + const sub = this.subscribe([{ ids: ["a".repeat(64)] }], { + oneose: () => { + sub.close(); + resolve(true); + }, + eoseTimeout: this.pingTimeout + 1e3 + }); + }); + } + async pingpong() { + if (this.ws?.readyState === 1) { + const result = await Promise.any([ + this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(), + new Promise((res) => setTimeout(() => res(false), this.pingTimeout)) + ]); + if (result) { + setTimeout(() => this.pingpong(), this.pingFrequency); + } else { + this.closeAllSubscriptions("pingpong timed out"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + } + } + async runQueue() { + this.queueRunning = true; + while (true) { + if (false === this.handleNext()) { + break; + } + await yieldThread(); + } + this.queueRunning = false; + } + handleNext() { + const json = this.incomingMessageQueue.dequeue(); + if (!json) { + return false; + } + const subid = getSubscriptionId(json); + if (subid) { + const so = this.openSubs.get(subid); + if (!so) { + return; + } + const id = getHex64(json, "id"); + const alreadyHave = so.alreadyHaveEvent?.(id); + so.receivedEvent?.(this, id); + if (alreadyHave) { + return; + } + } + try { + let data = JSON.parse(json); + switch (data[0]) { + case "EVENT": { + const so = this.openSubs.get(data[1]); + const event = data[2]; + if (this.verifyEvent(event) && matchFilters(so.filters, event)) { + so.onevent(event); + } + return; + } + case "COUNT": { + const id = data[1]; + const payload = data[2]; + const cr = this.openCountRequests.get(id); + if (cr) { + cr.resolve(payload.count); + this.openCountRequests.delete(id); + } + return; + } + case "EOSE": { + const so = this.openSubs.get(data[1]); + if (!so) + return; + so.receivedEose(); + return; + } + case "OK": { + const id = data[1]; + const ok = data[2]; + const reason = data[3]; + const ep = this.openEventPublishes.get(id); + if (ep) { + clearTimeout(ep.timeout); + if (ok) + ep.resolve(reason); + else + ep.reject(new Error(reason)); + this.openEventPublishes.delete(id); + } + return; + } + case "CLOSED": { + const id = data[1]; + const so = this.openSubs.get(id); + if (!so) + return; + so.closed = true; + so.close(data[2]); + return; + } + case "NOTICE": + this.onnotice(data[1]); + return; + case "AUTH": { + this.challenge = data[1]; + return; + } + } + } catch (err) { + return; + } + } + async send(message) { + if (!this.connectionPromise) + throw new SendingOnClosedConnection(message, this.url); + this.connectionPromise.then(() => { + this.ws?.send(message); + }); + } + async auth(signAuthEvent) { + const challenge = this.challenge; + if (!challenge) + throw new Error("can't perform auth, no challenge was received"); + if (this.authPromise) + return this.authPromise; + this.authPromise = new Promise(async (resolve, reject) => { + try { + let evt = await signAuthEvent(makeAuthEvent(this.url, challenge)); + let timeout = setTimeout(() => { + let ep = this.openEventPublishes.get(evt.id); + if (ep) { + ep.reject(new Error("auth timed out")); + this.openEventPublishes.delete(evt.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(evt.id, { resolve, reject, timeout }); + this.send('["AUTH",' + JSON.stringify(evt) + "]"); + } catch (err) { + console.warn("subscribe auth function failed:", err); + } + }); + return this.authPromise; + } + async publish(event) { + const ret = new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + const ep = this.openEventPublishes.get(event.id); + if (ep) { + ep.reject(new Error("publish timed out")); + this.openEventPublishes.delete(event.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(event.id, { resolve, reject, timeout }); + }); + this.send('["EVENT",' + JSON.stringify(event) + "]"); + return ret; + } + async count(filters, params) { + this.serial++; + const id = params?.id || "count:" + this.serial; + const ret = new Promise((resolve, reject) => { + this.openCountRequests.set(id, { resolve, reject }); + }); + this.send('["COUNT","' + id + '",' + JSON.stringify(filters).substring(1)); + return ret; + } + subscribe(filters, params) { + const subscription = this.prepareSubscription(filters, params); + subscription.fire(); + return subscription; + } + prepareSubscription(filters, params) { + this.serial++; + const id = params.id || (params.label ? params.label + ":" : "sub:") + this.serial; + const subscription = new Subscription(this, id, filters, params); + this.openSubs.set(id, subscription); + return subscription; + } + close() { + this.closeAllSubscriptions("relay connection closed by us"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + _onmessage(ev) { + this.incomingMessageQueue.enqueue(ev.data); + if (!this.queueRunning) { + this.runQueue(); + } + } +}; +var Subscription = class { + relay; + id; + closed = false; + eosed = false; + filters; + alreadyHaveEvent; + receivedEvent; + onevent; + oneose; + onclose; + eoseTimeout; + eoseTimeoutHandle; + constructor(relay, id, filters, params) { + this.relay = relay; + this.filters = filters; + this.id = id; + this.alreadyHaveEvent = params.alreadyHaveEvent; + this.receivedEvent = params.receivedEvent; + this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout; + this.oneose = params.oneose; + this.onclose = params.onclose; + this.onevent = params.onevent || ((event) => { + console.warn( + `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`, + event + ); + }); + } + fire() { + this.relay.send('["REQ","' + this.id + '",' + JSON.stringify(this.filters).substring(1)); + this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout); + } + receivedEose() { + if (this.eosed) + return; + clearTimeout(this.eoseTimeoutHandle); + this.eosed = true; + this.oneose?.(); + } + close(reason = "closed by caller") { + if (!this.closed && this.relay.connected) { + try { + this.relay.send('["CLOSE",' + JSON.stringify(this.id) + "]"); + } catch (err) { + if (err instanceof SendingOnClosedConnection) { + } else { + throw err; + } + } + this.closed = true; + } + this.relay.openSubs.delete(this.id); + this.onclose?.(reason); + } +}; + +// abstract-pool.ts +var AbstractSimplePool = class { + relays = /* @__PURE__ */ new Map(); + seenOn = /* @__PURE__ */ new Map(); + trackRelays = false; + verifyEvent; + enablePing; + trustedRelayURLs = /* @__PURE__ */ new Set(); + _WebSocket; + constructor(opts) { + this.verifyEvent = opts.verifyEvent; + this._WebSocket = opts.websocketImplementation; + this.enablePing = opts.enablePing; + } + async ensureRelay(url, params) { + url = normalizeURL(url); + let relay = this.relays.get(url); + if (!relay) { + relay = new AbstractRelay(url, { + verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent, + websocketImplementation: this._WebSocket, + enablePing: this.enablePing + }); + relay.onclose = () => { + this.relays.delete(url); + }; + if (params?.connectionTimeout) + relay.connectionTimeout = params.connectionTimeout; + this.relays.set(url, relay); + } + await relay.connect(); + return relay; + } + close(relays) { + relays.map(normalizeURL).forEach((url) => { + this.relays.get(url)?.close(); + this.relays.delete(url); + }); + } + subscribe(relays, filter, params) { + params.onauth = params.onauth || params.doauth; + const request = []; + for (let i2 = 0; i2 < relays.length; i2++) { + const url = normalizeURL(relays[i2]); + if (!request.find((r) => r.url === url)) { + request.push({ url, filter }); + } + } + return this.subscribeMap(request, params); + } + subscribeMany(relays, filters, params) { + params.onauth = params.onauth || params.doauth; + const request = []; + const uniqUrls = []; + for (let i2 = 0; i2 < relays.length; i2++) { + const url = normalizeURL(relays[i2]); + if (uniqUrls.indexOf(url) === -1) { + for (let f = 0; f < filters.length; f++) { + request.push({ url, filter: filters[f] }); + } + } + } + return this.subscribeMap(request, params); + } + subscribeMap(requests, params) { + params.onauth = params.onauth || params.doauth; + if (this.trackRelays) { + params.receivedEvent = (relay, id) => { + let set = this.seenOn.get(id); + if (!set) { + set = /* @__PURE__ */ new Set(); + this.seenOn.set(id, set); + } + set.add(relay); + }; + } + const _knownIds = /* @__PURE__ */ new Set(); + const subs = []; + const eosesReceived = []; + let handleEose = (i2) => { + if (eosesReceived[i2]) + return; + eosesReceived[i2] = true; + if (eosesReceived.filter((a) => a).length === requests.length) { + params.oneose?.(); + handleEose = () => { + }; + } + }; + const closesReceived = []; + let handleClose = (i2, reason) => { + if (closesReceived[i2]) + return; + handleEose(i2); + closesReceived[i2] = reason; + if (closesReceived.filter((a) => a).length === requests.length) { + params.onclose?.(closesReceived); + handleClose = () => { + }; + } + }; + const localAlreadyHaveEventHandler = (id) => { + if (params.alreadyHaveEvent?.(id)) { + return true; + } + const have = _knownIds.has(id); + _knownIds.add(id); + return have; + }; + const allOpened = Promise.all( + requests.map(async ({ url, filter }, i2) => { + let relay; + try { + relay = await this.ensureRelay(url, { + connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1e3) : void 0 + }); + } catch (err) { + handleClose(i2, err?.message || String(err)); + return; + } + let subscription = relay.subscribe([filter], { + ...params, + oneose: () => handleEose(i2), + onclose: (reason) => { + if (reason.startsWith("auth-required: ") && params.onauth) { + relay.auth(params.onauth).then(() => { + relay.subscribe([filter], { + ...params, + oneose: () => handleEose(i2), + onclose: (reason2) => { + handleClose(i2, reason2); + }, + alreadyHaveEvent: localAlreadyHaveEventHandler, + eoseTimeout: params.maxWait + }); + }).catch((err) => { + handleClose(i2, `auth was required and attempted, but failed with: ${err}`); + }); + } else { + handleClose(i2, reason); + } + }, + alreadyHaveEvent: localAlreadyHaveEventHandler, + eoseTimeout: params.maxWait + }); + subs.push(subscription); + }) + ); + return { + async close(reason) { + await allOpened; + subs.forEach((sub) => { + sub.close(reason); + }); + } + }; + } + subscribeEose(relays, filter, params) { + params.onauth = params.onauth || params.doauth; + const subcloser = this.subscribe(relays, filter, { + ...params, + oneose() { + subcloser.close("closed automatically on eose"); + } + }); + return subcloser; + } + subscribeManyEose(relays, filters, params) { + params.onauth = params.onauth || params.doauth; + const subcloser = this.subscribeMany(relays, filters, { + ...params, + oneose() { + subcloser.close("closed automatically on eose"); + } + }); + return subcloser; + } + async querySync(relays, filter, params) { + return new Promise(async (resolve) => { + const events = []; + this.subscribeEose(relays, filter, { + ...params, + onevent(event) { + events.push(event); + }, + onclose(_) { + resolve(events); + } + }); + }); + } + async get(relays, filter, params) { + filter.limit = 1; + const events = await this.querySync(relays, filter, params); + events.sort((a, b) => b.created_at - a.created_at); + return events[0] || null; + } + publish(relays, event, options) { + return relays.map(normalizeURL).map(async (url, i2, arr) => { + if (arr.indexOf(url) !== i2) { + return Promise.reject("duplicate url"); + } + let r = await this.ensureRelay(url); + return r.publish(event).catch(async (err) => { + if (err instanceof Error && err.message.startsWith("auth-required: ") && options?.onauth) { + await r.auth(options.onauth); + return r.publish(event); + } + throw err; + }).then((reason) => { + if (this.trackRelays) { + let set = this.seenOn.get(event.id); + if (!set) { + set = /* @__PURE__ */ new Set(); + this.seenOn.set(event.id, set); + } + set.add(r); + } + return reason; + }); + }); + } + listConnectionStatus() { + const map = /* @__PURE__ */ new Map(); + this.relays.forEach((relay, url) => map.set(url, relay.connected)); + return map; + } + destroy() { + this.relays.forEach((conn) => conn.close()); + this.relays = /* @__PURE__ */ new Map(); + } +}; + +// pool.ts +var _WebSocket; +try { + _WebSocket = WebSocket; +} catch { +} +var SimplePool = class extends AbstractSimplePool { + constructor(options) { + super({ verifyEvent, websocketImplementation: _WebSocket, ...options }); + } +}; + +// nip46.ts +var _fetch2; +try { + _fetch2 = fetch; +} catch { +} +function useFetchImplementation(fetchImplementation) { + _fetch2 = fetchImplementation; +} +var BUNKER_REGEX = /^bunker:\/\/([0-9a-f]{64})\??([?\/\w:.=&%-]*)$/; +var EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; +function toBunkerURL(bunkerPointer) { + let bunkerURL = new URL(`bunker://${bunkerPointer.pubkey}`); + bunkerPointer.relays.forEach((relay) => { + bunkerURL.searchParams.append("relay", relay); + }); + if (bunkerPointer.secret) { + bunkerURL.searchParams.set("secret", bunkerPointer.secret); + } + return bunkerURL.toString(); +} +async function parseBunkerInput(input) { + let match = input.match(BUNKER_REGEX); + if (match) { + try { + const pubkey = match[1]; + const qs = new URLSearchParams(match[2]); + return { + pubkey, + relays: qs.getAll("relay"), + secret: qs.get("secret") + }; + } catch (_err) { + } + } + return queryBunkerProfile(input); +} +async function queryBunkerProfile(nip05) { + const match = nip05.match(NIP05_REGEX); + if (!match) + return null; + const [_, name = "_", domain] = match; + try { + const url = `https://${domain}/.well-known/nostr.json?name=${name}`; + const res = await (await _fetch2(url, { redirect: "error" })).json(); + let pubkey = res.names[name]; + let relays = res.nip46[pubkey] || []; + return { pubkey, relays, secret: null }; + } catch (_err) { + return null; + } +} +var BunkerSigner = class { + params; + pool; + subCloser; + isOpen; + serial; + idPrefix; + listeners; + waitingForAuth; + secretKey; + conversationKey; + bp; + cachedPubKey; + constructor(clientSecretKey, bp, params = {}) { + if (bp.relays.length === 0) { + throw new Error("no relays are specified for this bunker"); + } + this.params = params; + this.pool = params.pool || new SimplePool(); + this.secretKey = clientSecretKey; + this.conversationKey = getConversationKey(clientSecretKey, bp.pubkey); + this.bp = bp; + this.isOpen = false; + this.idPrefix = Math.random().toString(36).substring(7); + this.serial = 0; + this.listeners = {}; + this.waitingForAuth = {}; + this.setupSubscription(params); + } + setupSubscription(params) { + const listeners = this.listeners; + const waitingForAuth = this.waitingForAuth; + const convKey = this.conversationKey; + this.subCloser = this.pool.subscribe( + this.bp.relays, + { kinds: [NostrConnect], authors: [this.bp.pubkey], "#p": [getPublicKey(this.secretKey)] }, + { + onevent: async (event) => { + const o = JSON.parse(decrypt(event.content, convKey)); + const { id, result, error } = o; + if (result === "auth_url" && waitingForAuth[id]) { + delete waitingForAuth[id]; + if (params.onauth) { + params.onauth(error); + } else { + console.warn( + `nostr-tools/nip46: remote signer ${this.bp.pubkey} tried to send an "auth_url"='${error}' but there was no onauth() callback configured.` + ); + } + return; + } + let handler = listeners[id]; + if (handler) { + if (error) + handler.reject(error); + else if (result) + handler.resolve(result); + delete listeners[id]; + } + }, + onclose: () => { + this.subCloser = void 0; + } + } + ); + this.isOpen = true; + } + async close() { + this.isOpen = false; + this.subCloser.close(); + } + async sendRequest(method, params) { + return new Promise(async (resolve, reject) => { + try { + if (!this.isOpen) + throw new Error("this signer is not open anymore, create a new one"); + if (!this.subCloser) + this.setupSubscription(this.params); + this.serial++; + const id = `${this.idPrefix}-${this.serial}`; + const encryptedContent = encrypt(JSON.stringify({ id, method, params }), this.conversationKey); + const verifiedEvent = finalizeEvent( + { + kind: NostrConnect, + tags: [["p", this.bp.pubkey]], + content: encryptedContent, + created_at: Math.floor(Date.now() / 1e3) + }, + this.secretKey + ); + this.listeners[id] = { resolve, reject }; + this.waitingForAuth[id] = true; + await Promise.any(this.pool.publish(this.bp.relays, verifiedEvent)); + } catch (err) { + reject(err); + } + }); + } + async ping() { + let resp = await this.sendRequest("ping", []); + if (resp !== "pong") + throw new Error(`result is not pong: ${resp}`); + } + async connect() { + await this.sendRequest("connect", [this.bp.pubkey, this.bp.secret || ""]); + } + async getPublicKey() { + if (!this.cachedPubKey) { + this.cachedPubKey = await this.sendRequest("get_public_key", []); + } + return this.cachedPubKey; + } + async signEvent(event) { + let resp = await this.sendRequest("sign_event", [JSON.stringify(event)]); + let signed = JSON.parse(resp); + if (verifyEvent(signed)) { + return signed; + } else { + throw new Error(`event returned from bunker is improperly signed: ${JSON.stringify(signed)}`); + } + } + async nip04Encrypt(thirdPartyPubkey, plaintext) { + return await this.sendRequest("nip04_encrypt", [thirdPartyPubkey, plaintext]); + } + async nip04Decrypt(thirdPartyPubkey, ciphertext) { + return await this.sendRequest("nip04_decrypt", [thirdPartyPubkey, ciphertext]); + } + async nip44Encrypt(thirdPartyPubkey, plaintext) { + return await this.sendRequest("nip44_encrypt", [thirdPartyPubkey, plaintext]); + } + async nip44Decrypt(thirdPartyPubkey, ciphertext) { + return await this.sendRequest("nip44_decrypt", [thirdPartyPubkey, ciphertext]); + } +}; +async function createAccount(bunker, params, username, domain, email, localSecretKey = generateSecretKey()) { + if (email && !EMAIL_REGEX.test(email)) + throw new Error("Invalid email"); + let rpc = new BunkerSigner(localSecretKey, bunker.bunkerPointer, params); + let pubkey = await rpc.sendRequest("create_account", [username, domain, email || ""]); + rpc.bp.pubkey = pubkey; + await rpc.connect(); + return rpc; +} +async function fetchBunkerProviders(pool, relays) { + const events = await pool.querySync(relays, { + kinds: [Handlerinformation], + "#k": [NostrConnect.toString()] + }); + events.sort((a, b) => b.created_at - a.created_at); + const validatedBunkers = await Promise.all( + events.map(async (event, i2) => { + try { + const content = JSON.parse(event.content); + try { + if (events.findIndex((ev) => JSON.parse(ev.content).nip05 === content.nip05) !== i2) + return void 0; + } catch (err) { + } + const bp = await queryBunkerProfile(content.nip05); + if (bp && bp.pubkey === event.pubkey && bp.relays.length) { + return { + bunkerPointer: bp, + nip05: content.nip05, + domain: content.nip05.split("@")[1], + name: content.name || content.display_name, + picture: content.picture, + about: content.about, + website: content.website, + local: false + }; + } + } catch (err) { + return void 0; + } + }) + ); + return validatedBunkers.filter((b) => b !== void 0); +} diff --git a/node_modules/nostr-tools/lib/cjs/nip46.js.map b/node_modules/nostr-tools/lib/cjs/nip46.js.map new file mode 100644 index 0000000..a3ec207 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip46.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip46.ts", "../../pure.ts", "../../core.ts", "../../utils.ts", "../../nip44.ts", "../../nip05.ts", "../../kinds.ts", "../../filter.ts", "../../fakejson.ts", "../../nip42.ts", "../../helpers.ts", "../../abstract-relay.ts", "../../abstract-pool.ts", "../../pool.ts"], + "sourcesContent": ["import { EventTemplate, NostrEvent, VerifiedEvent } from './core.ts'\nimport { generateSecretKey, finalizeEvent, getPublicKey, verifyEvent } from './pure.ts'\nimport { AbstractSimplePool, SubCloser } from './abstract-pool.ts'\nimport { getConversationKey, decrypt, encrypt } from './nip44.ts'\nimport { NIP05_REGEX } from './nip05.ts'\nimport { SimplePool } from './pool.ts'\nimport { Handlerinformation, NostrConnect } from './kinds.ts'\nimport { Signer } from './signer.ts'\n\nvar _fetch: any\n\ntry {\n _fetch = fetch\n} catch {}\n\nexport function useFetchImplementation(fetchImplementation: any) {\n _fetch = fetchImplementation\n}\n\nexport const BUNKER_REGEX = /^bunker:\\/\\/([0-9a-f]{64})\\??([?\\/\\w:.=&%-]*)$/\nconst EMAIL_REGEX = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\nexport type BunkerPointer = {\n relays: string[]\n pubkey: string\n secret: null | string\n}\n\nexport function toBunkerURL(bunkerPointer: BunkerPointer): string {\n let bunkerURL = new URL(`bunker://${bunkerPointer.pubkey}`)\n bunkerPointer.relays.forEach(relay => {\n bunkerURL.searchParams.append('relay', relay)\n })\n if (bunkerPointer.secret) {\n bunkerURL.searchParams.set('secret', bunkerPointer.secret)\n }\n return bunkerURL.toString()\n}\n\n/** This takes either a bunker:// URL or a name@domain.com NIP-05 identifier\n and returns a BunkerPointer -- or null in case of error */\nexport async function parseBunkerInput(input: string): Promise {\n let match = input.match(BUNKER_REGEX)\n if (match) {\n try {\n const pubkey = match[1]\n const qs = new URLSearchParams(match[2])\n return {\n pubkey,\n relays: qs.getAll('relay'),\n secret: qs.get('secret'),\n }\n } catch (_err) {\n /* just move to the next case */\n }\n }\n\n return queryBunkerProfile(input)\n}\n\nexport async function queryBunkerProfile(nip05: string): Promise {\n const match = nip05.match(NIP05_REGEX)\n if (!match) return null\n\n const [_, name = '_', domain] = match\n\n try {\n const url = `https://${domain}/.well-known/nostr.json?name=${name}`\n const res = await (await _fetch(url, { redirect: 'error' })).json()\n\n let pubkey = res.names[name]\n let relays = res.nip46[pubkey] || []\n\n return { pubkey, relays, secret: null }\n } catch (_err) {\n return null\n }\n}\n\nexport type BunkerSignerParams = {\n pool?: AbstractSimplePool\n onauth?: (url: string) => void\n}\n\nexport class BunkerSigner implements Signer {\n private params: BunkerSignerParams\n private pool: AbstractSimplePool\n private subCloser: SubCloser | undefined\n private isOpen: boolean\n private serial: number\n private idPrefix: string\n private listeners: {\n [id: string]: {\n resolve: (_: string) => void\n reject: (_: string) => void\n }\n }\n private waitingForAuth: { [id: string]: boolean }\n private secretKey: Uint8Array\n private conversationKey: Uint8Array\n public bp: BunkerPointer\n\n private cachedPubKey: string | undefined\n\n /**\n * Creates a new instance of the Nip46 class.\n * @param relays - An array of relay addresses.\n * @param remotePubkey - An optional remote public key. This is the key you want to sign as.\n * @param secretKey - An optional key pair.\n */\n public constructor(clientSecretKey: Uint8Array, bp: BunkerPointer, params: BunkerSignerParams = {}) {\n if (bp.relays.length === 0) {\n throw new Error('no relays are specified for this bunker')\n }\n\n this.params = params\n this.pool = params.pool || new SimplePool()\n this.secretKey = clientSecretKey\n this.conversationKey = getConversationKey(clientSecretKey, bp.pubkey)\n this.bp = bp\n this.isOpen = false\n this.idPrefix = Math.random().toString(36).substring(7)\n this.serial = 0\n this.listeners = {}\n this.waitingForAuth = {}\n\n this.setupSubscription(params)\n }\n\n private setupSubscription(params: BunkerSignerParams) {\n const listeners = this.listeners\n const waitingForAuth = this.waitingForAuth\n const convKey = this.conversationKey\n\n this.subCloser = this.pool.subscribe(\n this.bp.relays,\n { kinds: [NostrConnect], authors: [this.bp.pubkey], '#p': [getPublicKey(this.secretKey)] },\n {\n onevent: async (event: NostrEvent) => {\n const o = JSON.parse(decrypt(event.content, convKey))\n const { id, result, error } = o\n\n if (result === 'auth_url' && waitingForAuth[id]) {\n delete waitingForAuth[id]\n\n if (params.onauth) {\n params.onauth(error)\n } else {\n console.warn(\n `nostr-tools/nip46: remote signer ${this.bp.pubkey} tried to send an \"auth_url\"='${error}' but there was no onauth() callback configured.`,\n )\n }\n return\n }\n\n let handler = listeners[id]\n if (handler) {\n if (error) handler.reject(error)\n else if (result) handler.resolve(result)\n delete listeners[id]\n }\n },\n onclose: () => {\n this.subCloser = undefined\n },\n },\n )\n this.isOpen = true\n }\n\n // closes the subscription -- this object can't be used anymore after this\n async close() {\n this.isOpen = false\n this.subCloser!.close()\n }\n\n async sendRequest(method: string, params: string[]): Promise {\n return new Promise(async (resolve, reject) => {\n try {\n if (!this.isOpen) throw new Error('this signer is not open anymore, create a new one')\n if (!this.subCloser) this.setupSubscription(this.params)\n\n this.serial++\n const id = `${this.idPrefix}-${this.serial}`\n\n const encryptedContent = encrypt(JSON.stringify({ id, method, params }), this.conversationKey)\n\n // the request event\n const verifiedEvent: VerifiedEvent = finalizeEvent(\n {\n kind: NostrConnect,\n tags: [['p', this.bp.pubkey]],\n content: encryptedContent,\n created_at: Math.floor(Date.now() / 1000),\n },\n this.secretKey,\n )\n\n // setup callback listener\n this.listeners[id] = { resolve, reject }\n this.waitingForAuth[id] = true\n\n // publish the event\n await Promise.any(this.pool.publish(this.bp.relays, verifiedEvent))\n } catch (err) {\n reject(err)\n }\n })\n }\n\n /**\n * Calls the \"connect\" method on the bunker.\n * The promise will be rejected if the response is not \"pong\".\n */\n async ping(): Promise {\n let resp = await this.sendRequest('ping', [])\n if (resp !== 'pong') throw new Error(`result is not pong: ${resp}`)\n }\n\n /**\n * Calls the \"connect\" method on the bunker.\n */\n async connect(): Promise {\n await this.sendRequest('connect', [this.bp.pubkey, this.bp.secret || ''])\n }\n\n /**\n * Calls the \"get_public_key\" method on the bunker.\n * (before we would return the public key hardcoded in the bunker parameters, but\n * that is not correct as that may be the bunker pubkey and the actual signer\n * pubkey may be different.)\n */\n async getPublicKey(): Promise {\n if (!this.cachedPubKey) {\n this.cachedPubKey = await this.sendRequest('get_public_key', [])\n }\n return this.cachedPubKey\n }\n\n /**\n * Signs an event using the remote private key.\n * @param event - The event to sign.\n * @returns A Promise that resolves to the signed event.\n */\n async signEvent(event: EventTemplate): Promise {\n let resp = await this.sendRequest('sign_event', [JSON.stringify(event)])\n let signed: NostrEvent = JSON.parse(resp)\n if (verifyEvent(signed)) {\n return signed\n } else {\n throw new Error(`event returned from bunker is improperly signed: ${JSON.stringify(signed)}`)\n }\n }\n\n async nip04Encrypt(thirdPartyPubkey: string, plaintext: string): Promise {\n return await this.sendRequest('nip04_encrypt', [thirdPartyPubkey, plaintext])\n }\n\n async nip04Decrypt(thirdPartyPubkey: string, ciphertext: string): Promise {\n return await this.sendRequest('nip04_decrypt', [thirdPartyPubkey, ciphertext])\n }\n\n async nip44Encrypt(thirdPartyPubkey: string, plaintext: string): Promise {\n return await this.sendRequest('nip44_encrypt', [thirdPartyPubkey, plaintext])\n }\n\n async nip44Decrypt(thirdPartyPubkey: string, ciphertext: string): Promise {\n return await this.sendRequest('nip44_decrypt', [thirdPartyPubkey, ciphertext])\n }\n}\n\n/**\n * Creates an account with the specified username, domain, and optional email.\n * @param bunkerPubkey - The public key of the bunker to use for the create_account call.\n * @param username - The username for the account.\n * @param domain - The domain for the account.\n * @param email - The optional email for the account.\n * @param localSecretKey - Optionally pass a local secret key that will be used to communicate with the bunker,\n this will default to generating a random key.\n * @throws Error if the email is present but invalid.\n * @returns A Promise that resolves to the auth_url that the client should follow to create an account.\n */\nexport async function createAccount(\n bunker: BunkerProfile,\n params: BunkerSignerParams,\n username: string,\n domain: string,\n email?: string,\n localSecretKey: Uint8Array = generateSecretKey(),\n): Promise {\n if (email && !EMAIL_REGEX.test(email)) throw new Error('Invalid email')\n\n let rpc = new BunkerSigner(localSecretKey, bunker.bunkerPointer, params)\n\n let pubkey = await rpc.sendRequest('create_account', [username, domain, email || ''])\n\n // once we get the newly created pubkey back, we hijack this signer instance\n // and turn it into the main instance for this newly created pubkey\n rpc.bp.pubkey = pubkey\n await rpc.connect()\n\n return rpc\n}\n\n/**\n * Fetches info on available providers that announce themselves using NIP-89 events.\n * @returns A promise that resolves to an array of available bunker objects.\n */\nexport async function fetchBunkerProviders(pool: AbstractSimplePool, relays: string[]): Promise {\n const events = await pool.querySync(relays, {\n kinds: [Handlerinformation],\n '#k': [NostrConnect.toString()],\n })\n\n events.sort((a, b) => b.created_at - a.created_at)\n\n // validate bunkers by checking their NIP-05 and pubkey\n // map to a more useful object\n const validatedBunkers = await Promise.all(\n events.map(async (event, i) => {\n try {\n const content = JSON.parse(event.content)\n\n // skip duplicates\n try {\n if (events.findIndex(ev => JSON.parse(ev.content).nip05 === content.nip05) !== i) return undefined\n } catch (err) {\n /***/\n }\n\n const bp = await queryBunkerProfile(content.nip05)\n if (bp && bp.pubkey === event.pubkey && bp.relays.length) {\n return {\n bunkerPointer: bp,\n nip05: content.nip05,\n domain: content.nip05.split('@')[1],\n name: content.name || content.display_name,\n picture: content.picture,\n about: content.about,\n website: content.website,\n local: false,\n }\n }\n } catch (err) {\n return undefined\n }\n }),\n )\n\n return validatedBunkers.filter(b => b !== undefined) as BunkerProfile[]\n}\n\nexport type BunkerProfile = {\n bunkerPointer: BunkerPointer\n domain: string\n nip05: string\n name: string\n picture: string\n about: string\n website: string\n local: boolean\n}\n", "import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { chacha20 } from '@noble/ciphers/chacha'\nimport { equalBytes } from '@noble/ciphers/utils'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { extract as hkdf_extract, expand as hkdf_expand } from '@noble/hashes/hkdf'\nimport { hmac } from '@noble/hashes/hmac'\nimport { sha256 } from '@noble/hashes/sha256'\nimport { concatBytes, randomBytes } from '@noble/hashes/utils'\nimport { base64 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nconst minPlaintextSize = 0x0001 // 1b msg => padded to 32b\nconst maxPlaintextSize = 0xffff // 65535 (64kb-1) => padded to 64kb\n\nexport function getConversationKey(privkeyA: Uint8Array, pubkeyB: string): Uint8Array {\n const sharedX = secp256k1.getSharedSecret(privkeyA, '02' + pubkeyB).subarray(1, 33)\n return hkdf_extract(sha256, sharedX, 'nip44-v2')\n}\n\nfunction getMessageKeys(\n conversationKey: Uint8Array,\n nonce: Uint8Array,\n): { chacha_key: Uint8Array; chacha_nonce: Uint8Array; hmac_key: Uint8Array } {\n const keys = hkdf_expand(sha256, conversationKey, nonce, 76)\n return {\n chacha_key: keys.subarray(0, 32),\n chacha_nonce: keys.subarray(32, 44),\n hmac_key: keys.subarray(44, 76),\n }\n}\n\nfunction calcPaddedLen(len: number): number {\n if (!Number.isSafeInteger(len) || len < 1) throw new Error('expected positive integer')\n if (len <= 32) return 32\n const nextPower = 1 << (Math.floor(Math.log2(len - 1)) + 1)\n const chunk = nextPower <= 256 ? 32 : nextPower / 8\n return chunk * (Math.floor((len - 1) / chunk) + 1)\n}\n\nfunction writeU16BE(num: number): Uint8Array {\n if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize)\n throw new Error('invalid plaintext size: must be between 1 and 65535 bytes')\n const arr = new Uint8Array(2)\n new DataView(arr.buffer).setUint16(0, num, false)\n return arr\n}\n\nfunction pad(plaintext: string): Uint8Array {\n const unpadded = utf8Encoder.encode(plaintext)\n const unpaddedLen = unpadded.length\n const prefix = writeU16BE(unpaddedLen)\n const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen)\n return concatBytes(prefix, unpadded, suffix)\n}\n\nfunction unpad(padded: Uint8Array): string {\n const unpaddedLen = new DataView(padded.buffer).getUint16(0)\n const unpadded = padded.subarray(2, 2 + unpaddedLen)\n if (\n unpaddedLen < minPlaintextSize ||\n unpaddedLen > maxPlaintextSize ||\n unpadded.length !== unpaddedLen ||\n padded.length !== 2 + calcPaddedLen(unpaddedLen)\n )\n throw new Error('invalid padding')\n return utf8Decoder.decode(unpadded)\n}\n\nfunction hmacAad(key: Uint8Array, message: Uint8Array, aad: Uint8Array): Uint8Array {\n if (aad.length !== 32) throw new Error('AAD associated data must be 32 bytes')\n const combined = concatBytes(aad, message)\n return hmac(sha256, key, combined)\n}\n\n// metadata: always 65b (version: 1b, nonce: 32b, max: 32b)\n// plaintext: 1b to 0xffff\n// padded plaintext: 32b to 0xffff\n// ciphertext: 32b+2 to 0xffff+2\n// raw payload: 99 (65+32+2) to 65603 (65+0xffff+2)\n// compressed payload (base64): 132b to 87472b\nfunction decodePayload(payload: string): { nonce: Uint8Array; ciphertext: Uint8Array; mac: Uint8Array } {\n if (typeof payload !== 'string') throw new Error('payload must be a valid string')\n const plen = payload.length\n if (plen < 132 || plen > 87472) throw new Error('invalid payload length: ' + plen)\n if (payload[0] === '#') throw new Error('unknown encryption version')\n let data: Uint8Array\n try {\n data = base64.decode(payload)\n } catch (error) {\n throw new Error('invalid base64: ' + (error as any).message)\n }\n const dlen = data.length\n if (dlen < 99 || dlen > 65603) throw new Error('invalid data length: ' + dlen)\n const vers = data[0]\n if (vers !== 2) throw new Error('unknown encryption version ' + vers)\n return {\n nonce: data.subarray(1, 33),\n ciphertext: data.subarray(33, -32),\n mac: data.subarray(-32),\n }\n}\n\nexport function encrypt(plaintext: string, conversationKey: Uint8Array, nonce: Uint8Array = randomBytes(32)): string {\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n const padded = pad(plaintext)\n const ciphertext = chacha20(chacha_key, chacha_nonce, padded)\n const mac = hmacAad(hmac_key, ciphertext, nonce)\n return base64.encode(concatBytes(new Uint8Array([2]), nonce, ciphertext, mac))\n}\n\nexport function decrypt(payload: string, conversationKey: Uint8Array): string {\n const { nonce, ciphertext, mac } = decodePayload(payload)\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n const calculatedMac = hmacAad(hmac_key, ciphertext, nonce)\n if (!equalBytes(calculatedMac, mac)) throw new Error('invalid MAC')\n const padded = chacha20(chacha_key, chacha_nonce, ciphertext)\n return unpad(padded)\n}\n\nexport const v2 = {\n utils: {\n getConversationKey,\n calcPaddedLen,\n },\n encrypt,\n decrypt,\n}\n", "import { ProfilePointer } from './nip19.ts'\n\nexport type Nip05 = `${string}@${string}`\n\n/**\n * NIP-05 regex. The localpart is optional, and should be assumed to be `_` otherwise.\n *\n * - 0: full match\n * - 1: name (optional)\n * - 2: domain\n */\nexport const NIP05_REGEX = /^(?:([\\w.+-]+)@)?([\\w_-]+(\\.[\\w_-]+)+)$/\nexport const isNip05 = (value?: string | null): value is Nip05 => NIP05_REGEX.test(value || '')\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _fetch: any\n\ntry {\n _fetch = fetch\n} catch (_) {\n null\n}\n\nexport function useFetchImplementation(fetchImplementation: unknown) {\n _fetch = fetchImplementation\n}\n\nexport async function searchDomain(domain: string, query = ''): Promise<{ [name: string]: string }> {\n try {\n const url = `https://${domain}/.well-known/nostr.json?name=${query}`\n const res = await _fetch(url, { redirect: 'manual' })\n if (res.status !== 200) {\n throw Error('Wrong response code')\n }\n const json = await res.json()\n return json.names\n } catch (_) {\n return {}\n }\n}\n\nexport async function queryProfile(fullname: string): Promise {\n const match = fullname.match(NIP05_REGEX)\n if (!match) return null\n\n const [, name = '_', domain] = match\n\n try {\n const url = `https://${domain}/.well-known/nostr.json?name=${name}`\n const res = await _fetch(url, { redirect: 'manual' })\n if (res.status !== 200) {\n throw Error('Wrong response code')\n }\n const json = await res.json()\n\n const pubkey = json.names[name]\n return pubkey ? { pubkey, relays: json.relays?.[pubkey] } : null\n } catch (_e) {\n return null\n }\n}\n\nexport async function isValid(pubkey: string, nip05: Nip05): Promise {\n const res = await queryProfile(nip05)\n return res ? res.pubkey === pubkey : false\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { Event } from './core.ts'\nimport { isAddressableKind, isReplaceableKind } from './kinds.ts'\n\nexport type Filter = {\n ids?: string[]\n kinds?: number[]\n authors?: string[]\n since?: number\n until?: number\n limit?: number\n search?: string\n [key: `#${string}`]: string[] | undefined\n}\n\nexport function matchFilter(filter: Filter, event: Event): boolean {\n if (filter.ids && filter.ids.indexOf(event.id) === -1) {\n return false\n }\n if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) {\n return false\n }\n if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) {\n return false\n }\n\n for (let f in filter) {\n if (f[0] === '#') {\n let tagName = f.slice(1)\n let values = filter[`#${tagName}`]\n if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values!.indexOf(v) !== -1)) return false\n }\n }\n\n if (filter.since && event.created_at < filter.since) return false\n if (filter.until && event.created_at > filter.until) return false\n\n return true\n}\n\nexport function matchFilters(filters: Filter[], event: Event): boolean {\n for (let i = 0; i < filters.length; i++) {\n if (matchFilter(filters[i], event)) {\n return true\n }\n }\n return false\n}\n\nexport function mergeFilters(...filters: Filter[]): Filter {\n let result: Filter = {}\n for (let i = 0; i < filters.length; i++) {\n let filter = filters[i]\n Object.entries(filter).forEach(([property, values]) => {\n if (property === 'kinds' || property === 'ids' || property === 'authors' || property[0] === '#') {\n // @ts-ignore\n result[property] = result[property] || []\n // @ts-ignore\n for (let v = 0; v < values.length; v++) {\n // @ts-ignore\n let value = values[v]\n // @ts-ignore\n if (!result[property].includes(value)) result[property].push(value)\n }\n }\n })\n\n if (filter.limit && (!result.limit || filter.limit > result.limit)) result.limit = filter.limit\n if (filter.until && (!result.until || filter.until > result.until)) result.until = filter.until\n if (filter.since && (!result.since || filter.since < result.since)) result.since = filter.since\n }\n\n return result\n}\n\n/**\n * Calculate the intrinsic limit of a filter.\n * This function returns a positive integer, or `Infinity` if there is no intrinsic limit.\n */\nexport function getFilterLimit(filter: Filter): number {\n if (filter.ids && !filter.ids.length) return 0\n if (filter.kinds && !filter.kinds.length) return 0\n if (filter.authors && !filter.authors.length) return 0\n\n for (const [key, value] of Object.entries(filter)) {\n if (key[0] === '#' && Array.isArray(value) && !value.length) return 0\n }\n\n return Math.min(\n // The `limit` property creates an artificial limit.\n Math.max(0, filter.limit ?? Infinity),\n\n // There can only be one event per `id`.\n filter.ids?.length ?? Infinity,\n\n // Replaceable events are limited by the number of authors and kinds.\n filter.authors?.length && filter.kinds?.every(kind => isReplaceableKind(kind))\n ? filter.authors.length * filter.kinds.length\n : Infinity,\n\n // Parameterized replaceable events are limited by the number of authors, kinds, and \"d\" tags.\n filter.authors?.length && filter.kinds?.every(kind => isAddressableKind(kind)) && filter['#d']?.length\n ? filter.authors.length * filter.kinds.length * filter['#d'].length\n : Infinity,\n )\n}\n", "export function getHex64(json: string, field: string): string {\n let len = field.length + 3\n let idx = json.indexOf(`\"${field}\":`) + len\n let s = json.slice(idx).indexOf(`\"`) + idx + 1\n return json.slice(s, s + 64)\n}\n\nexport function getInt(json: string, field: string): number {\n let len = field.length\n let idx = json.indexOf(`\"${field}\":`) + len + 3\n let sliced = json.slice(idx)\n let end = Math.min(sliced.indexOf(','), sliced.indexOf('}'))\n return parseInt(sliced.slice(0, end), 10)\n}\n\nexport function getSubscriptionId(json: string): string | null {\n let idx = json.slice(0, 22).indexOf(`\"EVENT\"`)\n if (idx === -1) return null\n\n let pstart = json.slice(idx + 7 + 1).indexOf(`\"`)\n if (pstart === -1) return null\n let start = idx + 7 + 1 + pstart\n\n let pend = json.slice(start + 1, 80).indexOf(`\"`)\n if (pend === -1) return null\n let end = start + 1 + pend\n\n return json.slice(start + 1, end)\n}\n\nexport function matchEventId(json: string, id: string): boolean {\n return id === getHex64(json, 'id')\n}\n\nexport function matchEventPubkey(json: string, pubkey: string): boolean {\n return pubkey === getHex64(json, 'pubkey')\n}\n\nexport function matchEventKind(json: string, kind: number): boolean {\n return kind === getInt(json, 'kind')\n}\n", "import { EventTemplate } from './core.ts'\nimport { ClientAuth } from './kinds.ts'\n\n/**\n * creates an EventTemplate for an AUTH event to be signed.\n */\nexport function makeAuthEvent(relayURL: string, challenge: string): EventTemplate {\n return {\n kind: ClientAuth,\n created_at: Math.floor(Date.now() / 1000),\n tags: [\n ['relay', relayURL],\n ['challenge', challenge],\n ],\n content: '',\n }\n}\n", "import { verifiedSymbol, type Event, type Nostr, VerifiedEvent } from './core.ts'\n\nexport async function yieldThread() {\n return new Promise(resolve => {\n const ch = new MessageChannel()\n const handler = () => {\n // @ts-ignore (typescript thinks this property should be called `removeListener`, but in fact it's `removeEventListener`)\n ch.port1.removeEventListener('message', handler)\n resolve()\n }\n // @ts-ignore (typescript thinks this property should be called `addListener`, but in fact it's `addEventListener`)\n ch.port1.addEventListener('message', handler)\n ch.port2.postMessage(0)\n ch.port1.start()\n })\n}\n\nexport const alwaysTrue: Nostr['verifyEvent'] = (t: Event): t is VerifiedEvent => {\n t[verifiedSymbol] = true\n return true\n}\n", "/* global WebSocket */\n\nimport type { Event, EventTemplate, VerifiedEvent, Nostr, NostrEvent } from './core.ts'\nimport { matchFilters, type Filter } from './filter.ts'\nimport { getHex64, getSubscriptionId } from './fakejson.ts'\nimport { Queue, normalizeURL } from './utils.ts'\nimport { makeAuthEvent } from './nip42.ts'\nimport { yieldThread } from './helpers.ts'\n\ntype RelayWebSocket = WebSocket & {\n ping?(): void\n on?(event: 'pong', listener: () => void): any\n}\n\nexport type AbstractRelayConstructorOptions = {\n verifyEvent: Nostr['verifyEvent']\n websocketImplementation?: typeof WebSocket\n enablePing?: boolean\n}\n\nexport class SendingOnClosedConnection extends Error {\n constructor(message: string, relay: string) {\n super(`Tried to send message '${message} on a closed connection to ${relay}.`)\n this.name = 'SendingOnClosedConnection'\n }\n}\n\nexport class AbstractRelay {\n public readonly url: string\n private _connected: boolean = false\n\n public onclose: (() => void) | null = null\n public onnotice: (msg: string) => void = msg => console.debug(`NOTICE from ${this.url}: ${msg}`)\n\n public baseEoseTimeout: number = 4400\n public connectionTimeout: number = 4400\n public publishTimeout: number = 4400\n public pingFrequency: number = 20000\n public pingTimeout: number = 20000\n public openSubs: Map = new Map()\n public enablePing: boolean | undefined\n private connectionTimeoutHandle: ReturnType | undefined\n\n private connectionPromise: Promise | undefined\n private openCountRequests = new Map()\n private openEventPublishes = new Map()\n private ws: RelayWebSocket | undefined\n private incomingMessageQueue = new Queue()\n private queueRunning = false\n private challenge: string | undefined\n private authPromise: Promise | undefined\n private serial: number = 0\n private verifyEvent: Nostr['verifyEvent']\n\n private _WebSocket: typeof WebSocket\n\n constructor(url: string, opts: AbstractRelayConstructorOptions) {\n this.url = normalizeURL(url)\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation || WebSocket\n this.enablePing = opts.enablePing\n }\n\n static async connect(url: string, opts: AbstractRelayConstructorOptions): Promise {\n const relay = new AbstractRelay(url, opts)\n await relay.connect()\n return relay\n }\n\n private closeAllSubscriptions(reason: string) {\n for (let [_, sub] of this.openSubs) {\n sub.close(reason)\n }\n this.openSubs.clear()\n\n for (let [_, ep] of this.openEventPublishes) {\n ep.reject(new Error(reason))\n }\n this.openEventPublishes.clear()\n\n for (let [_, cr] of this.openCountRequests) {\n cr.reject(new Error(reason))\n }\n this.openCountRequests.clear()\n }\n\n public get connected(): boolean {\n return this._connected\n }\n\n public async connect(): Promise {\n if (this.connectionPromise) return this.connectionPromise\n\n this.challenge = undefined\n this.authPromise = undefined\n this.connectionPromise = new Promise((resolve, reject) => {\n this.connectionTimeoutHandle = setTimeout(() => {\n reject('connection timed out')\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection timed out')\n }, this.connectionTimeout)\n\n try {\n this.ws = new this._WebSocket(this.url)\n } catch (err) {\n clearTimeout(this.connectionTimeoutHandle)\n reject(err)\n return\n }\n\n this.ws.onopen = () => {\n clearTimeout(this.connectionTimeoutHandle)\n this._connected = true\n if (this.enablePing) {\n this.pingpong()\n }\n resolve()\n }\n\n this.ws.onerror = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket error')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection errored')\n }\n }\n\n this.ws.onclose = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket closed')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection closed')\n }\n }\n\n this.ws.onmessage = this._onmessage.bind(this)\n })\n\n return this.connectionPromise\n }\n\n private async waitForPingPong() {\n return new Promise((res, err) => {\n // listen for pong\n ;(this.ws && this.ws.on && this.ws.on('pong', () => res(true))) || err(\"ws can't listen for pong\")\n // send a ping\n this.ws && this.ws.ping && this.ws.ping()\n })\n }\n\n private async waitForDummyReq() {\n return new Promise((resolve, _) => {\n // make a dummy request with expected empty eose reply\n // [\"REQ\", \"_\", {\"ids\":[\"aaaa...aaaa\"]}]\n const sub = this.subscribe([{ ids: ['a'.repeat(64)] }], {\n oneose: () => {\n sub.close()\n resolve(true)\n },\n eoseTimeout: this.pingTimeout + 1000,\n })\n })\n }\n\n // nodejs requires this magic here to ensure connections are closed when internet goes off and stuff\n // in browsers it's done automatically. see https://github.com/nbd-wtf/nostr-tools/issues/491\n private async pingpong() {\n // if the websocket is connected\n if (this.ws?.readyState === 1) {\n // wait for either a ping-pong reply or a timeout\n const result = await Promise.any([\n // browsers don't have ping so use a dummy req\n this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(),\n new Promise(res => setTimeout(() => res(false), this.pingTimeout)),\n ])\n if (result) {\n // schedule another pingpong\n setTimeout(() => this.pingpong(), this.pingFrequency)\n } else {\n // pingpong closing socket\n this.closeAllSubscriptions('pingpong timed out')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n }\n }\n\n private async runQueue() {\n this.queueRunning = true\n while (true) {\n if (false === this.handleNext()) {\n break\n }\n await yieldThread()\n }\n this.queueRunning = false\n }\n\n private handleNext(): undefined | false {\n const json = this.incomingMessageQueue.dequeue()\n if (!json) {\n return false\n }\n\n const subid = getSubscriptionId(json)\n if (subid) {\n const so = this.openSubs.get(subid as string)\n if (!so) {\n // this is an EVENT message, but for a subscription we don't have, so just stop here\n return\n }\n\n // this will be called only when this message is a EVENT message for a subscription we have\n // we do this before parsing the JSON to not have to do that for duplicate events\n // since JSON parsing is slow\n const id = getHex64(json, 'id')\n const alreadyHave = so.alreadyHaveEvent?.(id)\n\n // notify any interested client that the relay has this event\n // (do this after alreadyHaveEvent() because the client may rely on this to answer that)\n so.receivedEvent?.(this, id)\n\n if (alreadyHave) {\n // if we had already seen this event we can just stop here\n return\n }\n }\n\n try {\n let data = JSON.parse(json)\n // we won't do any checks against the data since all failures (i.e. invalid messages from relays)\n // will naturally be caught by the encompassing try..catch block\n\n switch (data[0]) {\n case 'EVENT': {\n const so = this.openSubs.get(data[1] as string) as Subscription\n const event = data[2] as NostrEvent\n if (this.verifyEvent(event) && matchFilters(so.filters, event)) {\n so.onevent(event)\n }\n return\n }\n case 'COUNT': {\n const id: string = data[1]\n const payload = data[2] as { count: number }\n const cr = this.openCountRequests.get(id) as CountResolver\n if (cr) {\n cr.resolve(payload.count)\n this.openCountRequests.delete(id)\n }\n return\n }\n case 'EOSE': {\n const so = this.openSubs.get(data[1] as string)\n if (!so) return\n so.receivedEose()\n return\n }\n case 'OK': {\n const id: string = data[1]\n const ok: boolean = data[2]\n const reason: string = data[3]\n const ep = this.openEventPublishes.get(id) as EventPublishResolver\n if (ep) {\n clearTimeout(ep.timeout)\n if (ok) ep.resolve(reason)\n else ep.reject(new Error(reason))\n this.openEventPublishes.delete(id)\n }\n return\n }\n case 'CLOSED': {\n const id: string = data[1]\n const so = this.openSubs.get(id)\n if (!so) return\n so.closed = true\n so.close(data[2] as string)\n return\n }\n case 'NOTICE':\n this.onnotice(data[1] as string)\n return\n case 'AUTH': {\n this.challenge = data[1] as string\n return\n }\n }\n } catch (err) {\n return\n }\n }\n\n public async send(message: string) {\n if (!this.connectionPromise) throw new SendingOnClosedConnection(message, this.url)\n\n this.connectionPromise.then(() => {\n this.ws?.send(message)\n })\n }\n\n public async auth(signAuthEvent: (evt: EventTemplate) => Promise): Promise {\n const challenge = this.challenge\n if (!challenge) throw new Error(\"can't perform auth, no challenge was received\")\n if (this.authPromise) return this.authPromise\n\n this.authPromise = new Promise(async (resolve, reject) => {\n try {\n let evt = await signAuthEvent(makeAuthEvent(this.url, challenge))\n let timeout = setTimeout(() => {\n let ep = this.openEventPublishes.get(evt.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('auth timed out'))\n this.openEventPublishes.delete(evt.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(evt.id, { resolve, reject, timeout })\n this.send('[\"AUTH\",' + JSON.stringify(evt) + ']')\n } catch (err) {\n console.warn('subscribe auth function failed:', err)\n }\n })\n return this.authPromise\n }\n\n public async publish(event: Event): Promise {\n const ret = new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n const ep = this.openEventPublishes.get(event.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('publish timed out'))\n this.openEventPublishes.delete(event.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(event.id, { resolve, reject, timeout })\n })\n this.send('[\"EVENT\",' + JSON.stringify(event) + ']')\n return ret\n }\n\n public async count(filters: Filter[], params: { id?: string | null }): Promise {\n this.serial++\n const id = params?.id || 'count:' + this.serial\n const ret = new Promise((resolve, reject) => {\n this.openCountRequests.set(id, { resolve, reject })\n })\n this.send('[\"COUNT\",\"' + id + '\",' + JSON.stringify(filters).substring(1))\n return ret\n }\n\n public subscribe(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n const subscription = this.prepareSubscription(filters, params)\n subscription.fire()\n return subscription\n }\n\n public prepareSubscription(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n this.serial++\n const id = params.id || (params.label ? params.label + ':' : 'sub:') + this.serial\n const subscription = new Subscription(this, id, filters, params)\n this.openSubs.set(id, subscription)\n return subscription\n }\n\n public close() {\n this.closeAllSubscriptions('relay connection closed by us')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n\n // this is the function assigned to this.ws.onmessage\n // it's exposed for testing and debugging purposes\n public _onmessage(ev: MessageEvent) {\n this.incomingMessageQueue.enqueue(ev.data as string)\n if (!this.queueRunning) {\n this.runQueue()\n }\n }\n}\n\nexport class Subscription {\n public readonly relay: AbstractRelay\n public readonly id: string\n\n public closed: boolean = false\n public eosed: boolean = false\n public filters: Filter[]\n public alreadyHaveEvent: ((id: string) => boolean) | undefined\n public receivedEvent: ((relay: AbstractRelay, id: string) => void) | undefined\n\n public onevent: (evt: Event) => void\n public oneose: (() => void) | undefined\n public onclose: ((reason: string) => void) | undefined\n\n public eoseTimeout: number\n private eoseTimeoutHandle: ReturnType | undefined\n\n constructor(relay: AbstractRelay, id: string, filters: Filter[], params: SubscriptionParams) {\n this.relay = relay\n this.filters = filters\n this.id = id\n this.alreadyHaveEvent = params.alreadyHaveEvent\n this.receivedEvent = params.receivedEvent\n this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout\n\n this.oneose = params.oneose\n this.onclose = params.onclose\n this.onevent =\n params.onevent ||\n (event => {\n console.warn(\n `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,\n event,\n )\n })\n }\n\n public fire() {\n this.relay.send('[\"REQ\",\"' + this.id + '\",' + JSON.stringify(this.filters).substring(1))\n\n // only now we start counting the eoseTimeout\n this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout)\n }\n\n public receivedEose() {\n if (this.eosed) return\n clearTimeout(this.eoseTimeoutHandle)\n this.eosed = true\n this.oneose?.()\n }\n\n public close(reason: string = 'closed by caller') {\n if (!this.closed && this.relay.connected) {\n // if the connection was closed by the user calling .close() we will send a CLOSE message\n // otherwise this._open will be already set to false so we will skip this\n try {\n this.relay.send('[\"CLOSE\",' + JSON.stringify(this.id) + ']')\n } catch (err) {\n if (err instanceof SendingOnClosedConnection) {\n /* doesn't matter, it's ok */\n } else {\n throw err\n }\n }\n this.closed = true\n }\n this.relay.openSubs.delete(this.id)\n this.onclose?.(reason)\n }\n}\n\nexport type SubscriptionParams = {\n onevent?: (evt: Event) => void\n oneose?: () => void\n onclose?: (reason: string) => void\n alreadyHaveEvent?: (id: string) => boolean\n receivedEvent?: (relay: AbstractRelay, id: string) => void\n eoseTimeout?: number\n}\n\nexport type CountResolver = {\n resolve: (count: number) => void\n reject: (err: Error) => void\n}\n\nexport type EventPublishResolver = {\n resolve: (reason: string) => void\n reject: (err: Error) => void\n timeout: ReturnType\n}\n", "/* global WebSocket */\n\nimport {\n AbstractRelay as AbstractRelay,\n SubscriptionParams,\n Subscription,\n type AbstractRelayConstructorOptions,\n} from './abstract-relay.ts'\nimport { normalizeURL } from './utils.ts'\n\nimport type { Event, EventTemplate, Nostr, VerifiedEvent } from './core.ts'\nimport { type Filter } from './filter.ts'\nimport { alwaysTrue } from './helpers.ts'\n\nexport type SubCloser = { close: (reason?: string) => void }\n\nexport type AbstractPoolConstructorOptions = AbstractRelayConstructorOptions & {}\n\nexport type SubscribeManyParams = Omit & {\n maxWait?: number\n onclose?: (reasons: string[]) => void\n onauth?: (event: EventTemplate) => Promise\n // Deprecated: use onauth instead\n doauth?: (event: EventTemplate) => Promise\n id?: string\n label?: string\n}\n\nexport class AbstractSimplePool {\n protected relays: Map = new Map()\n public seenOn: Map> = new Map()\n public trackRelays: boolean = false\n\n public verifyEvent: Nostr['verifyEvent']\n public enablePing: boolean | undefined\n public trustedRelayURLs: Set = new Set()\n\n private _WebSocket?: typeof WebSocket\n\n constructor(opts: AbstractPoolConstructorOptions) {\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation\n this.enablePing = opts.enablePing\n }\n\n async ensureRelay(url: string, params?: { connectionTimeout?: number }): Promise {\n url = normalizeURL(url)\n\n let relay = this.relays.get(url)\n if (!relay) {\n relay = new AbstractRelay(url, {\n verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent,\n websocketImplementation: this._WebSocket,\n enablePing: this.enablePing,\n })\n relay.onclose = () => {\n this.relays.delete(url)\n }\n if (params?.connectionTimeout) relay.connectionTimeout = params.connectionTimeout\n this.relays.set(url, relay)\n }\n await relay.connect()\n\n return relay\n }\n\n close(relays: string[]) {\n relays.map(normalizeURL).forEach(url => {\n this.relays.get(url)?.close()\n this.relays.delete(url)\n })\n }\n\n subscribe(relays: string[], filter: Filter, params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const request: { url: string; filter: Filter }[] = []\n for (let i = 0; i < relays.length; i++) {\n const url = normalizeURL(relays[i])\n if (!request.find(r => r.url === url)) {\n request.push({ url, filter })\n }\n }\n\n return this.subscribeMap(request, params)\n }\n\n subscribeMany(relays: string[], filters: Filter[], params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const request: { url: string; filter: Filter }[] = []\n const uniqUrls: string[] = []\n for (let i = 0; i < relays.length; i++) {\n const url = normalizeURL(relays[i])\n if (uniqUrls.indexOf(url) === -1) {\n for (let f = 0; f < filters.length; f++) {\n request.push({ url, filter: filters[f] })\n }\n }\n }\n\n return this.subscribeMap(request, params)\n }\n\n subscribeMap(requests: { url: string; filter: Filter }[], params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n if (this.trackRelays) {\n params.receivedEvent = (relay: AbstractRelay, id: string) => {\n let set = this.seenOn.get(id)\n if (!set) {\n set = new Set()\n this.seenOn.set(id, set)\n }\n set.add(relay)\n }\n }\n\n const _knownIds = new Set()\n const subs: Subscription[] = []\n\n // batch all EOSEs into a single\n const eosesReceived: boolean[] = []\n let handleEose = (i: number) => {\n if (eosesReceived[i]) return // do not act twice for the same relay\n eosesReceived[i] = true\n if (eosesReceived.filter(a => a).length === requests.length) {\n params.oneose?.()\n handleEose = () => {}\n }\n }\n // batch all closes into a single\n const closesReceived: string[] = []\n let handleClose = (i: number, reason: string) => {\n if (closesReceived[i]) return // do not act twice for the same relay\n handleEose(i)\n closesReceived[i] = reason\n if (closesReceived.filter(a => a).length === requests.length) {\n params.onclose?.(closesReceived)\n handleClose = () => {}\n }\n }\n\n const localAlreadyHaveEventHandler = (id: string) => {\n if (params.alreadyHaveEvent?.(id)) {\n return true\n }\n const have = _knownIds.has(id)\n _knownIds.add(id)\n return have\n }\n\n // open a subscription in all given relays\n const allOpened = Promise.all(\n requests.map(async ({ url, filter }, i) => {\n let relay: AbstractRelay\n try {\n relay = await this.ensureRelay(url, {\n connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1000) : undefined,\n })\n } catch (err) {\n handleClose(i, (err as any)?.message || String(err))\n return\n }\n\n let subscription = relay.subscribe([filter], {\n ...params,\n oneose: () => handleEose(i),\n onclose: reason => {\n if (reason.startsWith('auth-required: ') && params.onauth) {\n relay\n .auth(params.onauth)\n .then(() => {\n relay.subscribe([filter], {\n ...params,\n oneose: () => handleEose(i),\n onclose: reason => {\n handleClose(i, reason) // the second time we won't try to auth anymore\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait,\n })\n })\n .catch(err => {\n handleClose(i, `auth was required and attempted, but failed with: ${err}`)\n })\n } else {\n handleClose(i, reason)\n }\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait,\n })\n\n subs.push(subscription)\n }),\n )\n\n return {\n async close(reason?: string) {\n await allOpened\n subs.forEach(sub => {\n sub.close(reason)\n })\n },\n }\n }\n\n subscribeEose(\n relays: string[],\n filter: Filter,\n params: Pick,\n ): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const subcloser = this.subscribe(relays, filter, {\n ...params,\n oneose() {\n subcloser.close('closed automatically on eose')\n },\n })\n return subcloser\n }\n\n subscribeManyEose(\n relays: string[],\n filters: Filter[],\n params: Pick,\n ): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const subcloser = this.subscribeMany(relays, filters, {\n ...params,\n oneose() {\n subcloser.close('closed automatically on eose')\n },\n })\n return subcloser\n }\n\n async querySync(\n relays: string[],\n filter: Filter,\n params?: Pick,\n ): Promise {\n return new Promise(async resolve => {\n const events: Event[] = []\n this.subscribeEose(relays, filter, {\n ...params,\n onevent(event: Event) {\n events.push(event)\n },\n onclose(_: string[]) {\n resolve(events)\n },\n })\n })\n }\n\n async get(\n relays: string[],\n filter: Filter,\n params?: Pick,\n ): Promise {\n filter.limit = 1\n const events = await this.querySync(relays, filter, params)\n events.sort((a, b) => b.created_at - a.created_at)\n return events[0] || null\n }\n\n publish(\n relays: string[],\n event: Event,\n options?: { onauth?: (evt: EventTemplate) => Promise },\n ): Promise[] {\n return relays.map(normalizeURL).map(async (url, i, arr) => {\n if (arr.indexOf(url) !== i) {\n // duplicate\n return Promise.reject('duplicate url')\n }\n\n let r = await this.ensureRelay(url)\n return r\n .publish(event)\n .catch(async err => {\n if (err instanceof Error && err.message.startsWith('auth-required: ') && options?.onauth) {\n await r.auth(options.onauth)\n return r.publish(event) // retry\n }\n throw err\n })\n .then(reason => {\n if (this.trackRelays) {\n let set = this.seenOn.get(event.id)\n if (!set) {\n set = new Set()\n this.seenOn.set(event.id, set)\n }\n set.add(r)\n }\n return reason\n })\n })\n }\n\n listConnectionStatus(): Map {\n const map = new Map()\n this.relays.forEach((relay, url) => map.set(url, relay.connected))\n\n return map\n }\n\n destroy(): void {\n this.relays.forEach(conn => conn.close())\n this.relays = new Map()\n }\n}\n", "/* global WebSocket */\n\nimport { verifyEvent } from './pure.ts'\nimport { AbstractSimplePool } from './abstract-pool.ts'\n\nvar _WebSocket: typeof WebSocket\n\ntry {\n _WebSocket = WebSocket\n} catch {}\n\nexport function useWebSocketImplementation(websocketImplementation: any) {\n _WebSocket = websocketImplementation\n}\n\nexport class SimplePool extends AbstractSimplePool {\n constructor(options?: { enablePing?: boolean }) {\n super({ verifyEvent, websocketImplementation: _WebSocket, ...options })\n }\n}\n\nexport * from './abstract-pool.ts'\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,uBAAwB;AACxB,IAAAA,gBAA2B;;;ACOpB,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,CAAC,QAAiD,eAAe;AAE3E,SAAS,cAAiB,OAAsC;AACrE,MAAI,CAAC,SAAS,KAAK;AAAG,WAAO;AAC7B,MAAI,OAAO,MAAM,SAAS;AAAU,WAAO;AAC3C,MAAI,OAAO,MAAM,YAAY;AAAU,WAAO;AAC9C,MAAI,OAAO,MAAM,eAAe;AAAU,WAAO;AACjD,MAAI,OAAO,MAAM,WAAW;AAAU,WAAO;AAC7C,MAAI,CAAC,MAAM,OAAO,MAAM,gBAAgB;AAAG,WAAO;AAElD,MAAI,CAAC,MAAM,QAAQ,MAAM,IAAI;AAAG,WAAO;AACvC,W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I,OAAO,UAAU,QAAM,KAAK,MAAM,GAAG,OAAO,EAAE,UAAU,QAAQ,KAAK,MAAMA;AAAG,mBAAO;AAAA,QAC3F,SAAS,KAAP;AAAA,QAEF;AAEA,cAAM,KAAK,MAAM,mBAAmB,QAAQ,KAAK;AACjD,YAAI,MAAM,GAAG,WAAW,MAAM,UAAU,GAAG,OAAO,QAAQ;AACxD,iBAAO;AAAA,YACL,eAAe;AAAA,YACf,OAAO,QAAQ;AAAA,YACf,QAAQ,QAAQ,MAAM,MAAM,GAAG,EAAE;AAAA,YACjC,MAAM,QAAQ,QAAQ,QAAQ;AAAA,YAC9B,SAAS,QAAQ;AAAA,YACjB,OAAO,QAAQ;AAAA,YACf,SAAS,QAAQ;AAAA,YACjB,OAAO;AAAA,UACT;AAAA,QACF;AAAA,MACF,SAAS,KAAP;AACA,eAAO;AAAA,MACT;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAO,iBAAiB,OAAO,OAAK,MAAM,MAAS;AACrD;", + "names": ["import_utils", "i", "target", "import_utils", "import_secp256k1", "import_sha256", "hkdf_extract", "hkdf_expand", "i", "i", "reason", "_fetch", "i"] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip47.js b/node_modules/nostr-tools/lib/cjs/nip47.js new file mode 100644 index 0000000..85b49c3 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip47.js @@ -0,0 +1,168 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip47.ts +var nip47_exports = {}; +__export(nip47_exports, { + makeNwcRequestEvent: () => makeNwcRequestEvent, + parseConnectionString: () => parseConnectionString +}); +module.exports = __toCommonJS(nip47_exports); + +// pure.ts +var import_secp256k1 = require("@noble/curves/secp256k1"); +var import_utils2 = require("@noble/hashes/utils"); + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +var import_sha256 = require("@noble/hashes/sha256"); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// pure.ts +var JS = class { + generateSecretKey() { + return import_secp256k1.schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = import_secp256k1.schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = (0, import_sha256.sha256)(utf8Encoder.encode(serializeEvent(event))); + return (0, import_utils2.bytesToHex)(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// kinds.ts +var NWCWalletRequest = 23194; + +// nip04.ts +var import_utils4 = require("@noble/hashes/utils"); +var import_secp256k12 = require("@noble/curves/secp256k1"); +var import_aes = require("@noble/ciphers/aes"); +var import_base = require("@scure/base"); +function encrypt(secretKey, pubkey, text) { + const privkey = secretKey instanceof Uint8Array ? (0, import_utils4.bytesToHex)(secretKey) : secretKey; + const key = import_secp256k12.secp256k1.getSharedSecret(privkey, "02" + pubkey); + const normalizedKey = getNormalizedX(key); + let iv = Uint8Array.from((0, import_utils4.randomBytes)(16)); + let plaintext = utf8Encoder.encode(text); + let ciphertext = (0, import_aes.cbc)(normalizedKey, iv).encrypt(plaintext); + let ctb64 = import_base.base64.encode(new Uint8Array(ciphertext)); + let ivb64 = import_base.base64.encode(new Uint8Array(iv.buffer)); + return `${ctb64}?iv=${ivb64}`; +} +function getNormalizedX(key) { + return key.slice(1, 33); +} + +// nip47.ts +function parseConnectionString(connectionString) { + const { host, pathname, searchParams } = new URL(connectionString); + const pubkey = pathname || host; + const relay = searchParams.get("relay"); + const secret = searchParams.get("secret"); + if (!pubkey || !relay || !secret) { + throw new Error("invalid connection string"); + } + return { pubkey, relay, secret }; +} +async function makeNwcRequestEvent(pubkey, secretKey, invoice) { + const content = { + method: "pay_invoice", + params: { + invoice + } + }; + const encryptedContent = encrypt(secretKey, pubkey, JSON.stringify(content)); + const eventTemplate = { + kind: NWCWalletRequest, + created_at: Math.round(Date.now() / 1e3), + content: encryptedContent, + tags: [["p", pubkey]] + }; + return finalizeEvent(eventTemplate, secretKey); +} diff --git a/node_modules/nostr-tools/lib/cjs/nip47.js.map b/node_modules/nostr-tools/lib/cjs/nip47.js.map new file mode 100644 index 0000000..53f7e6b --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip47.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip47.ts", "../../pure.ts", "../../core.ts", "../../utils.ts", "../../kinds.ts", "../../nip04.ts"], + "sourcesContent": ["import { type VerifiedEvent, finalizeEvent } from './pure.ts'\nimport { NWCWalletRequest } from './kinds.ts'\nimport { encrypt } from './nip04.ts'\n\ninterface NWCConnection {\n pubkey: string\n relay: string\n secret: string\n}\n\nexport function parseConnectionString(connectionString: string): NWCConnection {\n const { host, pathname, searchParams } = new URL(connectionString)\n const pubkey = pathname || host\n const relay = searchParams.get('relay')\n const secret = searchParams.get('secret')\n\n if (!pubkey || !relay || !secret) {\n throw new Error('invalid connection string')\n }\n\n return { pubkey, relay, secret }\n}\n\nexport async function makeNwcRequestEvent(\n pubkey: string,\n secretKey: Uint8Array,\n invoice: string,\n): Promise {\n const content = {\n method: 'pay_invoice',\n params: {\n invoice,\n },\n }\n const encryptedContent = encrypt(secretKey, pubkey, JSON.stringify(content))\n const eventTemplate = {\n kind: NWCWalletRequest,\n created_at: Math.round(Date.now() / 1000),\n content: encryptedContent,\n tags: [['p', pubkey]],\n }\n\n return finalizeEvent(eventTemplate, secretKey)\n}\n", "import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { bytesToHex, randomBytes } from '@noble/hashes/utils'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { cbc } from '@noble/ciphers/aes'\nimport { base64 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport function encrypt(secretKey: string | Uint8Array, pubkey: string, text: string): string {\n const privkey: string = secretKey instanceof Uint8Array ? bytesToHex(secretKey) : secretKey\n const key = secp256k1.getSharedSecret(privkey, '02' + pubkey)\n const normalizedKey = getNormalizedX(key)\n\n let iv = Uint8Array.from(randomBytes(16))\n let plaintext = utf8Encoder.encode(text)\n\n let ciphertext = cbc(normalizedKey, iv).encrypt(plaintext)\n\n let ctb64 = base64.encode(new Uint8Array(ciphertext))\n let ivb64 = base64.encode(new Uint8Array(iv.buffer))\n\n return `${ctb64}?iv=${ivb64}`\n}\n\nexport function decrypt(secretKey: string | Uint8Array, pubkey: string, data: string): string {\n const privkey: string = secretKey instanceof Uint8Array ? bytesToHex(secretKey) : secretKey\n let [ctb64, ivb64] = data.split('?iv=')\n let key = secp256k1.getSharedSecret(privkey, '02' + pubkey)\n let normalizedKey = getNormalizedX(key)\n\n let iv = base64.decode(ivb64)\n let ciphertext = base64.decode(ctb64)\n\n let plaintext = c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} diff --git a/node_modules/nostr-tools/lib/cjs/nip49.js b/node_modules/nostr-tools/lib/cjs/nip49.js new file mode 100644 index 0000000..d44ae63 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip49.js @@ -0,0 +1,77 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip49.ts +var nip49_exports = {}; +__export(nip49_exports, { + decrypt: () => decrypt, + encrypt: () => encrypt +}); +module.exports = __toCommonJS(nip49_exports); +var import_scrypt = require("@noble/hashes/scrypt"); +var import_chacha = require("@noble/ciphers/chacha"); +var import_utils2 = require("@noble/hashes/utils"); + +// nip19.ts +var import_utils = require("@noble/hashes/utils"); +var import_base = require("@scure/base"); +var Bech32MaxSize = 5e3; +function encodeBech32(prefix, data) { + let words = import_base.bech32.toWords(data); + return import_base.bech32.encode(prefix, words, Bech32MaxSize); +} +function encodeBytes(prefix, bytes) { + return encodeBech32(prefix, bytes); +} + +// nip49.ts +var import_base2 = require("@scure/base"); +function encrypt(sec, password, logn = 16, ksb = 2) { + let salt = (0, import_utils2.randomBytes)(16); + let n = 2 ** logn; + let key = (0, import_scrypt.scrypt)(password.normalize("NFKC"), salt, { N: n, r: 8, p: 1, dkLen: 32 }); + let nonce = (0, import_utils2.randomBytes)(24); + let aad = Uint8Array.from([ksb]); + let xc2p1 = (0, import_chacha.xchacha20poly1305)(key, nonce, aad); + let ciphertext = xc2p1.encrypt(sec); + let b = (0, import_utils2.concatBytes)(Uint8Array.from([2]), Uint8Array.from([logn]), salt, nonce, aad, ciphertext); + return encodeBytes("ncryptsec", b); +} +function decrypt(ncryptsec, password) { + let { prefix, words } = import_base2.bech32.decode(ncryptsec, Bech32MaxSize); + if (prefix !== "ncryptsec") { + throw new Error(`invalid prefix ${prefix}, expected 'ncryptsec'`); + } + let b = new Uint8Array(import_base2.bech32.fromWords(words)); + let version = b[0]; + if (version !== 2) { + throw new Error(`invalid version ${version}, expected 0x02`); + } + let logn = b[1]; + let n = 2 ** logn; + let salt = b.slice(2, 2 + 16); + let nonce = b.slice(2 + 16, 2 + 16 + 24); + let ksb = b[2 + 16 + 24]; + let aad = Uint8Array.from([ksb]); + let ciphertext = b.slice(2 + 16 + 24 + 1); + let key = (0, import_scrypt.scrypt)(password.normalize("NFKC"), salt, { N: n, r: 8, p: 1, dkLen: 32 }); + let xc2p1 = (0, import_chacha.xchacha20poly1305)(key, nonce, aad); + let sec = xc2p1.decrypt(ciphertext); + return sec; +} diff --git a/node_modules/nostr-tools/lib/cjs/nip49.js.map b/node_modules/nostr-tools/lib/cjs/nip49.js.map new file mode 100644 index 0000000..0c2ad00 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip49.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip49.ts", "../../nip19.ts"], + "sourcesContent": ["import { scrypt } from '@noble/hashes/scrypt'\nimport { xchacha20poly1305 } from '@noble/ciphers/chacha'\nimport { concatBytes, randomBytes } from '@noble/hashes/utils'\nimport { Bech32MaxSize, Ncryptsec, encodeBytes } from './nip19.ts'\nimport { bech32 } from '@scure/base'\n\nexport function encrypt(\n sec: Uint8Array,\n password: string,\n logn: number = 16,\n ksb: 0x00 | 0x01 | 0x02 = 0x02,\n): Ncryptsec {\n let salt = randomBytes(16)\n let n = 2 ** logn\n let key = scrypt(password.normalize('NFKC'), salt, { N: n, r: 8, p: 1, dkLen: 32 })\n let nonce = randomBytes(24)\n let aad = Uint8Array.from([ksb])\n let xc2p1 = xchacha20poly1305(key, nonce, aad)\n let ciphertext = xc2p1.encrypt(sec)\n let b = concatBytes(Uint8Array.from([0x02]), Uint8Array.from([logn]), salt, nonce, aad, ciphertext)\n return encodeBytes('ncryptsec', b)\n}\n\nexport function decrypt(ncryptsec: string, password: string): Uint8Array {\n let { prefix, words } = bech32.decode(ncryptsec, Bech32MaxSize)\n if (prefix !== 'ncryptsec') {\n throw new Error(`invalid prefix ${prefix}, expected 'ncryptsec'`)\n }\n let b = new Uint8Array(bech32.fromWords(words))\n\n let version = b[0]\n if (version !== 0x02) {\n throw new Error(`invalid version ${version}, expected 0x02`)\n }\n\n let logn = b[1]\n let n = 2 ** logn\n\n let salt = b.slice(2, 2 + 16)\n let nonce = b.slice(2 + 16, 2 + 16 + 24)\n let ksb = b[2 + 16 + 24]\n let aad = Uint8Array.from([ksb])\n let ciphertext = b.slice(2 + 16 + 24 + 1)\n\n let key = scrypt(password.normalize('NFKC'), salt, { N: n, r: 8, p: 1, dkLen: 32 })\n let xc2p1 = xchacha20poly1305(key, nonce, aad)\n let sec = xc2p1.decrypt(ciphertext)\n\n return sec\n}\n", "import { bytesToHex, concatBytes, hexToBytes } from '@noble/hashes/utils'\nimport { bech32 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport type NProfile = `nprofile1${string}`\nexport type NEvent = `nevent1${string}`\nexport type NAddr = `naddr1${string}`\nexport type NSec = `nsec1${string}`\nexport type NPub = `npub1${string}`\nexport type Note = `note1${string}`\nexport type Ncryptsec = `ncryptsec1${string}`\n\nexport const NostrTypeGuard = {\n isNProfile: (value?: string | null): value is NProfile => /^nprofile1[a-z\\d]+$/.test(value || ''),\n isNEvent: (value?: string | null): value is NEvent => /^nevent1[a-z\\d]+$/.test(value || ''),\n isNAddr: (value?: string | null): value is NAddr => /^naddr1[a-z\\d]+$/.test(value || ''),\n isNSec: (value?: string | null): value is NSec => /^nsec1[a-z\\d]{58}$/.test(value || ''),\n isNPub: (value?: string | null): value is NPub => /^npub1[a-z\\d]{58}$/.test(value || ''),\n isNote: (value?: string | null): value is Note => /^note1[a-z\\d]+$/.test(value || ''),\n isNcryptsec: (value?: string | null): value is Ncryptsec => /^ncryptsec1[a-z\\d]+$/.test(value || ''),\n}\n\nexport const Bech32MaxSize = 5000\n\n/**\n * Bech32 regex.\n * @see https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32\n */\nexport const BECH32_REGEX = /[\\x21-\\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/\n\nfunction integerToUint8Array(number: number) {\n // Create a Uint8Array with enough space to hold a 32-bit integer (4 bytes).\n const uint8Array = new Uint8Array(4)\n\n // Use bitwise operations to extract the bytes.\n uint8Array[0] = (number >> 24) & 0xff // Most significant byte (MSB)\n uint8Array[1] = (number >> 16) & 0xff\n uint8Array[2] = (number >> 8) & 0xff\n uint8Array[3] = number & 0xff // Least significant byte (LSB)\n\n return uint8Array\n}\n\nexport type ProfilePointer = {\n pubkey: string // hex\n relays?: string[]\n}\n\nexport type EventPointer = {\n id: string // hex\n relays?: string[]\n author?: string\n kind?: number\n}\n\nexport type AddressPointer = {\n identifier: string\n pubkey: string\n kind: number\n relays?: string[]\n}\n\nexport function decodeNostrURI(nip19code: string): ReturnType | { type: 'invalid'; data: null } {\n try {\n if (nip19code.startsWith('nostr:')) nip19code = nip19code.substring(6)\n return decode(nip19code)\n } catch (_err) {\n return { type: 'invalid', data: null }\n }\n}\n\nexport type DecodedNevent = {\n type: 'nevent'\n data: EventPointer\n}\n\nexport type DecodedNprofile = {\n type: 'nprofile'\n data: ProfilePointer\n}\n\nexport type DecodedNaddr = {\n type: 'naddr'\n data: AddressPointer\n}\n\nexport type DecodedNsec = {\n type: 'nsec'\n data: Uint8Array\n}\n\nexport type DecodedNpub = {\n type: 'npub'\n data: string\n}\n\nexport type DecodedNote = {\n type: 'note'\n data: string\n}\n\nexport type DecodedResult = DecodedNevent | DecodedNprofile | DecodedNaddr | DecodedNpub | DecodedNsec | DecodedNote\n\nexport function decode(nip19: NEvent): DecodedNevent\nexport function decode(nip19: NProfile): DecodedNprofile\nexport function decode(nip19: NAddr): DecodedNaddr\nexport function decode(nip19: NSec): DecodedNsec\nexport function decode(nip19: NPub): DecodedNpub\nexport function decode(nip19: Note): DecodedNote\nexport function decode(code: string): DecodedResult\nexport function decode(code: string): DecodedResult {\n let { prefix, words } = bech32.decode(code, Bech32MaxSize)\n let data = new Uint8Array(bech32.fromWords(words))\n\n switch (prefix) {\n case 'nprofile': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nprofile')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n\n return {\n type: 'nprofile',\n data: {\n pubkey: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n case 'nevent': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nevent')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n if (tlv[2] && tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (tlv[3] && tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'nevent',\n data: {\n id: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n author: tlv[2]?.[0] ? bytesToHex(tlv[2][0]) : undefined,\n kind: tlv[3]?.[0] ? parseInt(bytesToHex(tlv[3][0]), 16) : undefined,\n },\n }\n }\n\n case 'naddr': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for naddr')\n if (!tlv[2]?.[0]) throw new Error('missing TLV 2 for naddr')\n if (tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (!tlv[3]?.[0]) throw new Error('missing TLV 3 for naddr')\n if (tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'naddr',\n data: {\n identifier: utf8Decoder.decode(tlv[0][0]),\n pubkey: bytesToHex(tlv[2][0]),\n kind: parseInt(bytesToHex(tlv[3][0]), 16),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n\n case 'nsec':\n return { type: prefix, data }\n\n case 'npub':\n case 'note':\n return { type: prefix, data: bytesToHex(data) }\n\n default:\n throw new Error(`unknown prefix ${prefix}`)\n }\n}\n\ntype TLV = { [t: number]: Uint8Array[] }\n\nfunction parseTLV(data: Uint8Array): TLV {\n let result: TLV = {}\n let rest = data\n while (rest.length > 0) {\n let t = rest[0]\n let l = rest[1]\n let v = rest.slice(2, 2 + l)\n rest = rest.slice(2 + l)\n if (v.length < l) throw new Error(`not enough data to read on TLV ${t}`)\n result[t] = result[t] || []\n result[t].push(v)\n }\n return result\n}\n\nexport function nsecEncode(key: Uint8Array): NSec {\n return encodeBytes('nsec', key)\n}\n\nexport function npubEncode(hex: string): NPub {\n return encodeBytes('npub', hexToBytes(hex))\n}\n\nexport function noteEncode(hex: string): Note {\n return encodeBytes('note', hexToBytes(hex))\n}\n\nfunction encodeBech32(prefix: Prefix, data: Uint8Array): `${Prefix}1${string}` {\n let words = bech32.toWords(data)\n return bech32.encode(prefix, words, Bech32MaxSize) as `${Prefix}1${string}`\n}\n\nexport function encodeBytes(prefix: Prefix, bytes: Uint8Array): `${Prefix}1${string}` {\n return encodeBech32(prefix, bytes)\n}\n\nexport function nprofileEncode(profile: ProfilePointer): NProfile {\n let data = encodeTLV({\n 0: [hexToBytes(profile.pubkey)],\n 1: (profile.relays || []).map(url => utf8Encoder.encode(url)),\n })\n return encodeBech32('nprofile', data)\n}\n\nexport function neventEncode(event: EventPointer): NEvent {\n let kindArray\n if (event.kind !== undefined) {\n kindArray = integerToUint8Array(event.kind)\n }\n\n let data = encodeTLV({\n 0: [hexToBytes(event.id)],\n 1: (event.relays || []).map(url => utf8Encoder.encode(url)),\n 2: event.author ? [hexToBytes(event.author)] : [],\n 3: kindArray ? [new Uint8Array(kindArray)] : [],\n })\n\n return encodeBech32('nevent', data)\n}\n\nexport function naddrEncode(addr: AddressPointer): NAddr {\n let kind = new ArrayBuffer(4)\n new DataView(kind).setUint32(0, addr.kind, false)\n\n let data = encodeTLV({\n 0: [utf8Encoder.encode(addr.identifier)],\n 1: (addr.relays || []).map(url => utf8Encoder.encode(url)),\n 2: [hexToBytes(addr.pubkey)],\n 3: [new Uint8Array(kind)],\n })\n return encodeBech32('naddr', data)\n}\n\nfunction encodeTLV(tlv: TLV): Uint8Array {\n let entries: Uint8Array[] = []\n\n Object.entries(tlv)\n .reverse()\n .forEach(([t, vs]) => {\n vs.forEach(v => {\n let entry = new Uint8Array(v.length + 2)\n entry.set([parseInt(t)], 0)\n entry.set([v.length], 1)\n entry.set(v, 2)\n entries.push(entry)\n })\n })\n\n return concatBytes(...entries)\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAuB;AACvB,oBAAkC;AAClC,IAAAA,gBAAyC;;;ACFzC,mBAAoD;AACpD,kBAAuB;AAsBhB,IAAM,gBAAgB;AAwL7B,SAAS,aAAoC,QAAgB,MAAyC;AACpG,MAAI,QAAQ,mBAAO,QAAQ,IAAI;AAC/B,SAAO,mBAAO,OAAO,QAAQ,OAAO,aAAa;AACnD;AAEO,SAAS,YAAmC,QAAgB,OAA0C;AAC3G,SAAO,aAAa,QAAQ,KAAK;AACnC;;;ADlNA,IAAAC,eAAuB;AAEhB,SAAS,QACd,KACA,UACA,OAAe,IACf,MAA0B,GACf;AACX,MAAI,WAAO,2BAAY,EAAE;AACzB,MAAI,IAAI,KAAK;AACb,MAAI,UAAM,sBAAO,SAAS,UAAU,MAAM,GAAG,MAAM,EAAE,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,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tools/lib/cjs/nip54.js b/node_modules/nostr-tools/lib/cjs/nip54.js new file mode 100644 index 0000000..9d1be85 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip54.js @@ -0,0 +1,35 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip54.ts +var nip54_exports = {}; +__export(nip54_exports, { + normalizeIdentifier: () => normalizeIdentifier +}); +module.exports = __toCommonJS(nip54_exports); +function normalizeIdentifier(name) { + name = name.trim().toLowerCase(); + name = name.normalize("NFKC"); + return Array.from(name).map((char) => { + if (/\p{Letter}/u.test(char) || /\p{Number}/u.test(char)) { + return char; + } + return "-"; + }).join(""); +} diff --git a/node_modules/nostr-tools/lib/cjs/nip54.js.map b/node_modules/nostr-tools/lib/cjs/nip54.js.map new file mode 100644 index 0000000..fc0ce84 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip54.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip54.ts"], + "sourcesContent": ["export function normalizeIdentifier(name: string): string {\n // Trim and lowercase\n name = name.trim().toLowerCase()\n\n // Normalize Unicode to NFKC form\n name = name.normalize('NFKC')\n\n // Convert to array of characters and map each one\n return Array.from(name)\n .map(char => {\n // Check if character is letter or number using Unicode ranges\n if (/\\p{Letter}/u.test(char) || /\\p{Number}/u.test(char)) {\n return char\n }\n\n return '-'\n })\n .join('')\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAO,SAAS,oBAAoB,MAAsB;AAExD,SAAO,KAAK,KAAK,EAAE,YAAY;AAG/B,SAAO,KAAK,UAAU,MAAM;AAG5B,SAAO,MAAM,KAAK,IAAI,EACnB,IAAI,UAAQ;AAEX,QAAI,cAAc,KAAK,IAAI,KAAK,cAAc,KAAK,IAAI,GAAG;AACxD,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT,CAAC,EACA,KAAK,EAAE;AACZ;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip55.js b/node_modules/nostr-tools/lib/cjs/nip55.js new file mode 100644 index 0000000..0f64638 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip55.js @@ -0,0 +1,103 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip55.ts +var nip55_exports = {}; +__export(nip55_exports, { + decryptNip04Uri: () => decryptNip04Uri, + decryptNip44Uri: () => decryptNip44Uri, + decryptZapEventUri: () => decryptZapEventUri, + encryptNip04Uri: () => encryptNip04Uri, + encryptNip44Uri: () => encryptNip44Uri, + getPublicKeyUri: () => getPublicKeyUri, + signEventUri: () => signEventUri +}); +module.exports = __toCommonJS(nip55_exports); +function encodeParams(params) { + return new URLSearchParams(params).toString(); +} +function filterUndefined(obj) { + return Object.fromEntries(Object.entries(obj).filter(([, value]) => value !== void 0)); +} +function buildUri({ + base, + type, + callbackUrl, + returnType = "signature", + compressionType = "none", + ...params +}) { + const baseParams = { + type, + compressionType, + returnType, + callbackUrl, + id: params.id, + current_user: params.currentUser, + permissions: params.permissions && params.permissions.length > 0 ? encodeURIComponent(JSON.stringify(params.permissions)) : void 0, + pubKey: params.pubKey, + plainText: params.plainText, + encryptedText: params.encryptedText, + appName: params.appName + }; + const filteredParams = filterUndefined(baseParams); + return `${base}?${encodeParams(filteredParams)}`; +} +function buildDefaultUri(type, params) { + return buildUri({ + base: "nostrsigner:", + type, + ...params + }); +} +function getPublicKeyUri({ permissions = [], ...params }) { + return buildDefaultUri("get_public_key", { permissions, ...params }); +} +function signEventUri({ eventJson, ...params }) { + return buildUri({ + base: `nostrsigner:${encodeURIComponent(JSON.stringify(eventJson))}`, + type: "sign_event", + ...params + }); +} +function encryptUri(type, params) { + return buildDefaultUri(type, { ...params, plainText: params.content }); +} +function decryptUri(type, params) { + return buildDefaultUri(type, { ...params, encryptedText: params.content }); +} +function encryptNip04Uri(params) { + return encryptUri("nip04_encrypt", params); +} +function decryptNip04Uri(params) { + return decryptUri("nip04_decrypt", params); +} +function encryptNip44Uri(params) { + return encryptUri("nip44_encrypt", params); +} +function decryptNip44Uri(params) { + return decryptUri("nip44_decrypt", params); +} +function decryptZapEventUri({ eventJson, ...params }) { + return buildUri({ + base: `nostrsigner:${encodeURIComponent(JSON.stringify(eventJson))}`, + type: "decrypt_zap_event", + ...params + }); +} diff --git a/node_modules/nostr-tools/lib/cjs/nip55.js.map b/node_modules/nostr-tools/lib/cjs/nip55.js.map new file mode 100644 index 0000000..f9a0080 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip55.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip55.ts"], + "sourcesContent": ["type BaseParams = {\n callbackUrl?: string\n returnType?: 'signature' | 'event'\n compressionType?: 'none' | 'gzip'\n}\n\ntype PermissionsParams = BaseParams & {\n permissions?: { type: string; kind?: number }[]\n}\n\ntype EventUriParams = BaseParams & {\n eventJson: Record\n id?: string\n currentUser?: string\n}\n\ntype EncryptDecryptParams = BaseParams & {\n pubKey: string\n content: string\n id?: string\n currentUser?: string\n}\n\ntype UriParams = BaseParams & {\n base: string\n type: string\n id?: string\n currentUser?: string\n permissions?: { type: string; kind?: number }[]\n pubKey?: string\n plainText?: string\n encryptedText?: string\n appName?: string\n}\n\nfunction encodeParams(params: Record): string {\n return new URLSearchParams(params as Record).toString()\n}\n\nfunction filterUndefined>(obj: T): T {\n return Object.fromEntries(Object.entries(obj).filter(([, value]) => value !== undefined)) as T\n}\n\nfunction buildUri({\n base,\n type,\n callbackUrl,\n returnType = 'signature',\n compressionType = 'none',\n ...params\n}: UriParams): string {\n const baseParams = {\n type,\n compressionType,\n returnType,\n callbackUrl,\n id: params.id,\n current_user: params.currentUser,\n permissions:\n params.permissions && params.permissions.length > 0\n ? encodeURIComponent(JSON.stringify(params.permissions))\n : undefined,\n pubKey: params.pubKey,\n plainText: params.plainText,\n encryptedText: params.encryptedText,\n appName: params.appName,\n }\n\n const filteredParams = filterUndefined(baseParams)\n return `${base}?${encodeParams(filteredParams)}`\n}\n\nfunction buildDefaultUri(type: string, params: Partial): string {\n return buildUri({\n base: 'nostrsigner:',\n type,\n ...params,\n })\n}\n\nexport function getPublicKeyUri({ permissions = [], ...params }: PermissionsParams): string {\n return buildDefaultUri('get_public_key', { permissions, ...params })\n}\n\nexport function signEventUri({ eventJson, ...params }: EventUriParams): string {\n return buildUri({\n base: `nostrsigner:${encodeURIComponent(JSON.stringify(eventJson))}`,\n type: 'sign_event',\n ...params,\n })\n}\n\nfunction encryptUri(type: 'nip44_encrypt' | 'nip04_encrypt', params: EncryptDecryptParams): string {\n return buildDefaultUri(type, { ...params, plainText: params.content })\n}\n\nfunction decryptUri(type: 'nip44_decrypt' | 'nip04_decrypt', params: EncryptDecryptParams): string {\n return buildDefaultUri(type, { ...params, encryptedText: params.content })\n}\n\nexport function encryptNip04Uri(params: EncryptDecryptParams): string {\n return encryptUri('nip04_encrypt', params)\n}\n\nexport function decryptNip04Uri(params: EncryptDecryptParams): string {\n return decryptUri('nip04_decrypt', params)\n}\n\nexport function encryptNip44Uri(params: EncryptDecryptParams): string {\n return encryptUri('nip44_encrypt', params)\n}\n\nexport function decryptNip44Uri(params: EncryptDecryptParams): string {\n return decryptUri('nip44_decrypt', params)\n}\n\nexport function decryptZapEventUri({ eventJson, ...params }: EventUriParams): string {\n return buildUri({\n base: `nostrsigner:${encodeURIComponent(JSON.stringify(eventJson))}`,\n type: 'decrypt_zap_event',\n ...params,\n })\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmCA,SAAS,aAAa,QAAyC;AAC7D,SAAO,IAAI,gBAAgB,MAAgC,EAAE,SAAS;AACxE;AAEA,SAAS,gBAAmD,KAAW;AACrE,SAAO,OAAO,YAAY,OAAO,QAAQ,GAAG,EAAE,OAAO,CAAC,CAAC,EAAE,KAAK,MAAM,UAAU,MAAS,CAAC;AAC1F;AAEA,SAAS,SAAS;AAAA,EAChB;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAa;AAAA,EACb,kBAAkB;AAAA,KACf;AACL,GAAsB;AACpB,QAAM,aAAa;AAAA,IACjB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,IAAI,OAAO;AAAA,IACX,cAAc,OAAO;AAAA,IACrB,aACE,OAAO,eAAe,OAAO,YAAY,SAAS,IAC9C,mBAAmB,KAAK,UAAU,OAAO,WAAW,CAAC,IACrD;AAAA,IACN,QAAQ,OAAO;AAAA,IACf,WAAW,OAAO;AAAA,IAClB,eAAe,OAAO;AAAA,IACtB,SAAS,OAAO;AAAA,EAClB;AAEA,QAAM,iBAAiB,gBAAgB,UAAU;AACjD,SAAO,GAAG,QAAQ,aAAa,cAAc;AAC/C;AAEA,SAAS,gBAAgB,MAAc,QAAoC;AACzE,SAAO,SAAS;AAAA,IACd,MAAM;AAAA,IACN;AAAA,IACA,GAAG;AAAA,EACL,CAAC;AACH;AAEO,SAAS,gBAAgB,EAAE,cAAc,CAAC,MAAM,OAAO,GAA8B;AAC1F,SAAO,gBAAgB,kBAAkB,EAAE,aAAa,GAAG,OAAO,CAAC;AACrE;AAEO,SAAS,aAAa,EAAE,cAAc,OAAO,GAA2B;AAC7E,SAAO,SAAS;AAAA,IACd,MAAM,eAAe,mBAAmB,KAAK,UAAU,SAAS,CAAC;AAAA,IACjE,MAAM;AAAA,IACN,GAAG;AAAA,EACL,CAAC;AACH;AAEA,SAAS,WAAW,MAAyC,QAAsC;AACjG,SAAO,gBAAgB,MAAM,EAAE,GAAG,QAAQ,WAAW,OAAO,QAAQ,CAAC;AACvE;AAEA,SAAS,WAAW,MAAyC,QAAsC;AACjG,SAAO,gBAAgB,MAAM,EAAE,GAAG,QAAQ,eAAe,OAAO,QAAQ,CAAC;AAC3E;AAEO,SAAS,gBAAgB,QAAsC;AACpE,SAAO,WAAW,iBAAiB,MAAM;AAC3C;AAEO,SAAS,gBAAgB,QAAsC;AACpE,SAAO,WAAW,iBAAiB,MAAM;AAC3C;AAEO,SAAS,gBAAgB,QAAsC;AACpE,SAAO,WAAW,iBAAiB,MAAM;AAC3C;AAEO,SAAS,gBAAgB,QAAsC;AACpE,SAAO,WAAW,iBAAiB,MAAM;AAC3C;AAEO,SAAS,mBAAmB,EAAE,cAAc,OAAO,GAA2B;AACnF,SAAO,SAAS;AAAA,IACd,MAAM,eAAe,mBAAmB,KAAK,UAAU,SAAS,CAAC;AAAA,IACjE,MAAM;AAAA,IACN,GAAG;AAAA,EACL,CAAC;AACH;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip57.js b/node_modules/nostr-tools/lib/cjs/nip57.js new file mode 100644 index 0000000..7f3b514 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip57.js @@ -0,0 +1,274 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip57.ts +var nip57_exports = {}; +__export(nip57_exports, { + getSatoshisAmountFromBolt11: () => getSatoshisAmountFromBolt11, + getZapEndpoint: () => getZapEndpoint, + makeZapReceipt: () => makeZapReceipt, + makeZapRequest: () => makeZapRequest, + useFetchImplementation: () => useFetchImplementation, + validateZapRequest: () => validateZapRequest +}); +module.exports = __toCommonJS(nip57_exports); +var import_base = require("@scure/base"); + +// pure.ts +var import_secp256k1 = require("@noble/curves/secp256k1"); +var import_utils2 = require("@noble/hashes/utils"); + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +var import_sha256 = require("@noble/hashes/sha256"); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// pure.ts +var JS = class { + generateSecretKey() { + return import_secp256k1.schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = import_secp256k1.schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = (0, import_sha256.sha256)(utf8Encoder.encode(serializeEvent(event))); + return (0, import_utils2.bytesToHex)(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// kinds.ts +function isReplaceableKind(kind) { + return [0, 3].includes(kind) || 1e4 <= kind && kind < 2e4; +} +function isAddressableKind(kind) { + return 3e4 <= kind && kind < 4e4; +} + +// nip57.ts +var _fetch; +try { + _fetch = fetch; +} catch { +} +function useFetchImplementation(fetchImplementation) { + _fetch = fetchImplementation; +} +async function getZapEndpoint(metadata) { + try { + let lnurl = ""; + let { lud06, lud16 } = JSON.parse(metadata.content); + if (lud06) { + let { words } = import_base.bech32.decode(lud06, 1e3); + let data = import_base.bech32.fromWords(words); + lnurl = utf8Decoder.decode(data); + } else if (lud16) { + let [name, domain] = lud16.split("@"); + lnurl = new URL(`/.well-known/lnurlp/${name}`, `https://${domain}`).toString(); + } else { + return null; + } + let res = await _fetch(lnurl); + let body = await res.json(); + if (body.allowsNostr && body.nostrPubkey) { + return body.callback; + } + } catch (err) { + } + return null; +} +function makeZapRequest(params) { + let zr = { + kind: 9734, + created_at: Math.round(Date.now() / 1e3), + content: params.comment || "", + tags: [ + ["p", "pubkey" in params ? params.pubkey : params.event.pubkey], + ["amount", params.amount.toString()], + ["relays", ...params.relays] + ] + }; + if ("event" in params) { + zr.tags.push(["e", params.event.id]); + if (isReplaceableKind(params.event.kind)) { + const a = ["a", `${params.event.kind}:${params.event.pubkey}:`]; + zr.tags.push(a); + } else if (isAddressableKind(params.event.kind)) { + let d = params.event.tags.find(([t, v]) => t === "d" && v); + if (!d) + throw new Error("d tag not found or is empty"); + const a = ["a", `${params.event.kind}:${params.event.pubkey}:${d[1]}`]; + zr.tags.push(a); + } + zr.tags.push(["k", params.event.kind.toString()]); + } + return zr; +} +function validateZapRequest(zapRequestString) { + let zapRequest; + try { + zapRequest = JSON.parse(zapRequestString); + } catch (err) { + return "Invalid zap request JSON."; + } + if (!validateEvent(zapRequest)) + return "Zap request is not a valid Nostr event."; + if (!verifyEvent(zapRequest)) + return "Invalid signature on zap request."; + let p = zapRequest.tags.find(([t, v]) => t === "p" && v); + if (!p) + return "Zap request doesn't have a 'p' tag."; + if (!p[1].match(/^[a-f0-9]{64}$/)) + return "Zap request 'p' tag is not valid hex."; + let e = zapRequest.tags.find(([t, v]) => t === "e" && v); + if (e && !e[1].match(/^[a-f0-9]{64}$/)) + return "Zap request 'e' tag is not valid hex."; + let relays = zapRequest.tags.find(([t, v]) => t === "relays" && v); + if (!relays) + return "Zap request doesn't have a 'relays' tag."; + return null; +} +function makeZapReceipt({ + zapRequest, + preimage, + bolt11, + paidAt +}) { + let zr = JSON.parse(zapRequest); + let tagsFromZapRequest = zr.tags.filter(([t]) => t === "e" || t === "p" || t === "a"); + let zap = { + kind: 9735, + created_at: Math.round(paidAt.getTime() / 1e3), + content: "", + tags: [...tagsFromZapRequest, ["P", zr.pubkey], ["bolt11", bolt11], ["description", zapRequest]] + }; + if (preimage) { + zap.tags.push(["preimage", preimage]); + } + return zap; +} +function getSatoshisAmountFromBolt11(bolt11) { + if (bolt11.length < 50) { + return 0; + } + bolt11 = bolt11.substring(0, 50); + const idx = bolt11.lastIndexOf("1"); + if (idx === -1) { + return 0; + } + const hrp = bolt11.substring(0, idx); + if (!hrp.startsWith("lnbc")) { + return 0; + } + const amount = hrp.substring(4); + if (amount.length < 1) { + return 0; + } + const char = amount[amount.length - 1]; + const digit = char.charCodeAt(0) - "0".charCodeAt(0); + const isDigit = digit >= 0 && digit <= 9; + let cutPoint = amount.length - 1; + if (isDigit) { + cutPoint++; + } + if (cutPoint < 1) { + return 0; + } + const num = parseInt(amount.substring(0, cutPoint)); + switch (char) { + case "m": + return num * 1e5; + case "u": + return num * 100; + case "n": + return num / 10; + case "p": + return num / 1e4; + default: + return num * 1e8; + } +} diff --git a/node_modules/nostr-tools/lib/cjs/nip57.js.map b/node_modules/nostr-tools/lib/cjs/nip57.js.map new file mode 100644 index 0000000..bf733d7 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip57.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip57.ts", "../../pure.ts", "../../core.ts", "../../utils.ts", "../../kinds.ts"], + "sourcesContent": ["import { bech32 } from '@scure/base'\n\nimport { NostrEvent, validateEvent, verifyEvent, type Event, type EventTemplate } from './pure.ts'\nimport { utf8Decoder } from './utils.ts'\nimport { isReplaceableKind, isAddressableKind } from './kinds.ts'\n\nvar _fetch: any\n\ntry {\n _fetch = fetch\n} catch {}\n\nexport function useFetchImplementation(fetchImplementation: any) {\n _fetch = fetchImplementation\n}\n\nexport async function getZapEndpoint(metadata: Event): Promise {\n try {\n let lnurl: string = ''\n let { lud06, lud16 } = JSON.parse(metadata.content)\n if (lud06) {\n let { words } = bech32.decode(lud06, 1000)\n let data = bech32.fromWords(words)\n lnurl = utf8Decoder.decode(data)\n } else if (lud16) {\n let [name, domain] = lud16.split('@')\n lnurl = new URL(`/.well-known/lnurlp/${name}`, `https://${domain}`).toString()\n } else {\n return null\n }\n\n let res = await _fetch(lnurl)\n let body = await res.json()\n\n if (body.allowsNostr && body.nostrPubkey) {\n return body.callback\n }\n } catch (err) {\n /*-*/\n }\n\n return null\n}\n\ntype ProfileZap = {\n pubkey: string\n amount: number\n comment?: string\n relays: string[]\n}\n\ntype EventZap = {\n event: NostrEvent\n amount: number\n comment?: string\n relays: string[]\n}\n\nexport function makeZapRequest(params: ProfileZap | EventZap): EventTemplate {\n let zr: EventTemplate = {\n kind: 9734,\n created_at: Math.round(Date.now() / 1000),\n content: params.comment || '',\n tags: [\n ['p', 'pubkey' in params ? params.pubkey : params.event.pubkey],\n ['amount', params.amount.toString()],\n ['relays', ...params.relays],\n ],\n }\n\n if ('event' in params) {\n zr.tags.push(['e', params.event.id])\n if (isReplaceableKind(params.event.kind)) {\n const a = ['a', `${params.event.kind}:${params.event.pubkey}:`]\n zr.tags.push(a)\n } else if (isAddressableKind(params.event.kind)) {\n let d = params.event.tags.find(([t, v]) => t === 'd' && v)\n if (!d) throw new Error('d tag not found or is empty')\n const a = ['a', `${params.event.kind}:${params.event.pubkey}:${d[1]}`]\n zr.tags.push(a)\n }\n zr.tags.push(['k', params.event.kind.toString()])\n }\n\n return zr\n}\n\nexport function validateZapRequest(zapRequestString: string): string | null {\n let zapRequest: Event\n\n try {\n zapRequest = JSON.parse(zapRequestString)\n } catch (err) {\n return 'Invalid zap request JSON.'\n }\n\n if (!validateEvent(zapRequest)) return 'Zap request is not a valid Nostr event.'\n\n if (!verifyEvent(zapRequest)) return 'Invalid signature on zap request.'\n\n let p = zapRequest.tags.find(([t, v]) => t === 'p' && v)\n if (!p) return \"Zap request doesn't have a 'p' tag.\"\n if (!p[1].match(/^[a-f0-9]{64}$/)) return \"Zap request 'p' tag is not valid hex.\"\n\n let e = zapRequest.tags.find(([t, v]) => t === 'e' && v)\n if (e && !e[1].match(/^[a-f0-9]{64}$/)) return \"Zap request 'e' tag is not valid hex.\"\n\n let relays = zapRequest.tags.find(([t, v]) => t === 'relays' && v)\n if (!relays) return \"Zap request doesn't have a 'relays' tag.\"\n\n return null\n}\n\nexport function makeZapReceipt({\n zapRequest,\n preimage,\n bolt11,\n paidAt,\n}: {\n zapRequest: string\n preimage?: string\n bolt11: string\n paidAt: Date\n}): EventTemplate {\n let zr: Event = JSON.parse(zapRequest)\n let tagsFromZapRequest = zr.tags.filter(([t]) => t === 'e' || t === 'p' || t === 'a')\n\n let zap: EventTemplate = {\n kind: 9735,\n created_at: Math.round(paidAt.getTime() / 1000),\n content: '',\n tags: [...tagsFromZapRequest, ['P', zr.pubkey], ['bolt11', bolt11], ['description', zapRequest]],\n }\n\n if (preimage) {\n zap.tags.push(['preimage', preimage])\n }\n\n return zap\n}\n\nexport function getSatoshisAmountFromBolt11(bolt11: string): number {\n if (bolt11.length < 50) {\n return 0\n }\n bolt11 = bolt11.substring(0, 50)\n const idx = bolt11.lastIndexOf('1')\n if (idx === -1) {\n return 0\n }\n const hrp = bolt11.substring(0, idx)\n if (!hrp.startsWith('lnbc')) {\n return 0\n }\n const amount = hrp.substring(4) // equivalent to strings.CutPrefix\n\n if (amount.length < 1) {\n return 0\n }\n\n // if last character is a digit, then the amount can just be interpreted as BTC\n const char = amount[amount.length - 1]\n const digit = char.charCodeAt(0) - '0'.charCodeAt(0)\n const isDigit = digit >= 0 && digit <= 9\n\n let cutPoint = amount.length - 1\n if (isDigit) {\n cutPoint++\n }\n\n if (cutPoint < 1) {\n return 0\n }\n\n const num = parseInt(amount.substring(0, cutPoint))\n\n switch (char) {\n case 'm':\n return num * 100000\n case 'u':\n return num * 100\n case 'n':\n return num / 10\n case 'p':\n return num / 10000\n default:\n return num * 100000000\n }\n}\n", "import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAAuB;;;ACAvB,uBAAwB;AACxB,IAAAA,gBAA2B;;;ACOpB,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,CAAC,QAAiD,eAAe;AAE3E,SAAS,cAAiB,OAAsC;AACrE,MAAI,CAAC,SAAS,KAAK;AAAG,WAAO;AAC7B,MAAI,OAAO,MAAM,SAAS;AAAU,WAAO;AAC3C,MAAI,OAAO,MAAM,YAAY;AAAU,WAAO;AAC9C,MAAI,OAAO,MAAM,eAAe;AAAU,WAAO;AACjD,MAAI,OAAO,MAAM,WAAW;AAAU,WAAO;AAC7C,MAAI,CAAC,MAAM,OAAO,MAAM,gBAAgB;AA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GAAG,EAAE;AAC/B,QAAM,MAAM,OAAO,YAAY,GAAG;AAClC,MAAI,QAAQ,IAAI;AACd,WAAO;AAAA,EACT;AACA,QAAM,MAAM,OAAO,UAAU,GAAG,GAAG;AACnC,MAAI,CAAC,IAAI,WAAW,MAAM,GAAG;AAC3B,WAAO;AAAA,EACT;AACA,QAAM,SAAS,IAAI,UAAU,CAAC;AAE9B,MAAI,OAAO,SAAS,GAAG;AACrB,WAAO;AAAA,EACT;AAGA,QAAM,OAAO,OAAO,OAAO,SAAS;AACpC,QAAM,QAAQ,KAAK,WAAW,CAAC,IAAI,IAAI,WAAW,CAAC;AACnD,QAAM,UAAU,SAAS,KAAK,SAAS;AAEvC,MAAI,WAAW,OAAO,SAAS;AAC/B,MAAI,SAAS;AACX;AAAA,EACF;AAEA,MAAI,WAAW,GAAG;AAChB,WAAO;AAAA,EACT;AAEA,QAAM,MAAM,SAAS,OAAO,UAAU,GAAG,QAAQ,CAAC;AAElD,UAAQ,MAAM;AAAA,IACZ,KAAK;AACH,aAAO,MAAM;AAAA,IACf,KAAK;AACH,aAAO,MAAM;AAAA,IACf,KAAK;AACH,aAAO,MAAM;AAAA,IACf,KAAK;AACH,aAAO,MAAM;AAAA,IACf;AACE,aAAO,MAAM;AAAA,EACjB;AACF;", + "names": ["import_utils", "i"] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip58.js b/node_modules/nostr-tools/lib/cjs/nip58.js new file mode 100644 index 0000000..d128ea8 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip58.js @@ -0,0 +1,117 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip58.ts +var nip58_exports = {}; +__export(nip58_exports, { + generateBadgeAwardEventTemplate: () => generateBadgeAwardEventTemplate, + generateBadgeDefinitionEventTemplate: () => generateBadgeDefinitionEventTemplate, + generateProfileBadgesEventTemplate: () => generateProfileBadgesEventTemplate, + validateBadgeAwardEvent: () => validateBadgeAwardEvent, + validateBadgeDefinitionEvent: () => validateBadgeDefinitionEvent, + validateProfileBadgesEvent: () => validateProfileBadgesEvent +}); +module.exports = __toCommonJS(nip58_exports); + +// kinds.ts +var BadgeAward = 8; +var ProfileBadges = 30008; +var BadgeDefinition = 30009; + +// nip58.ts +function generateBadgeDefinitionEventTemplate({ + d, + description, + image, + name, + thumbs +}) { + const tags = [["d", d]]; + name && tags.push(["name", name]); + description && tags.push(["description", description]); + image && tags.push(["image", ...image]); + if (thumbs) { + for (const thumb of thumbs) { + tags.push(["thumb", ...thumb]); + } + } + const eventTemplate = { + content: "", + created_at: Math.floor(Date.now() / 1e3), + kind: BadgeDefinition, + tags + }; + return eventTemplate; +} +function validateBadgeDefinitionEvent(event) { + if (event.kind !== BadgeDefinition) + return false; + const requiredTags = ["d"]; + for (const tag of requiredTags) { + if (!event.tags.find(([t]) => t == tag)) + return false; + } + return true; +} +function generateBadgeAwardEventTemplate({ a, p }) { + const tags = [["a", a]]; + for (const _p of p) { + tags.push(["p", ..._p]); + } + const eventTemplate = { + content: "", + created_at: Math.floor(Date.now() / 1e3), + kind: BadgeAward, + tags + }; + return eventTemplate; +} +function validateBadgeAwardEvent(event) { + if (event.kind !== BadgeAward) + return false; + const requiredTags = ["a", "p"]; + for (const tag of requiredTags) { + if (!event.tags.find(([t]) => t == tag)) + return false; + } + return true; +} +function generateProfileBadgesEventTemplate({ badges }) { + const tags = [["d", "profile_badges"]]; + for (const badge of badges) { + tags.push(["a", badge.a], ["e", ...badge.e]); + } + const eventTemplate = { + content: "", + created_at: Math.floor(Date.now() / 1e3), + kind: ProfileBadges, + tags + }; + return eventTemplate; +} +function validateProfileBadgesEvent(event) { + if (event.kind !== ProfileBadges) + return false; + const requiredTags = ["d"]; + for (const tag of requiredTags) { + if (!event.tags.find(([t]) => t == tag)) + return false; + } + return true; +} diff --git a/node_modules/nostr-tools/lib/cjs/nip58.js.map b/node_modules/nostr-tools/lib/cjs/nip58.js.map new file mode 100644 index 0000000..4f1ed7d --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip58.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip58.ts", "../../kinds.ts"], + "sourcesContent": ["import { Event, EventTemplate } from './core.ts'\nimport {\n BadgeAward as BadgeAwardKind,\n BadgeDefinition as BadgeDefinitionKind,\n ProfileBadges as ProfileBadgesKind,\n} from './kinds.ts'\n\n/**\n * Represents the structure for defining a badge within the Nostr network.\n * This structure is used to create templates for badge definition events,\n * facilitating the recognition and awarding of badges to users for various achievements.\n */\nexport type BadgeDefinition = {\n /**\n * A unique identifier for the badge. This is used to distinguish badges\n * from one another and should be unique across all badge definitions.\n * Typically, this could be a short, descriptive string.\n */\n d: string\n\n /**\n * An optional short name for the badge. This provides a human-readable\n * title for the badge, making it easier to recognize and refer to.\n */\n name?: string\n\n /**\n * An optional description for the badge. This field can be used to\n * provide more detailed information about the badge, such as the criteria\n * for its awarding or its significance.\n */\n description?: string\n\n /**\n * An optional image URL and dimensions for the badge. The first element\n * of the tuple is the URL pointing to a high-resolution image representing\n * the badge, and the second element specifies the image's dimensions in\n * the format \"widthxheight\". The recommended dimensions are 1024x1024 pixels.\n */\n image?: [string, string]\n\n /**\n * An optional list of thumbnail images for the badge. Each element in the\n * array is a tuple, where the first element is the URL pointing to a thumbnail\n * version of the badge image, and the second element specifies the thumbnail's\n * dimensions in the format \"widthxheight\". Multiple thumbnails can be provided\n * to support different display sizes.\n */\n thumbs?: Array<[string, string]>\n}\n\n/**\n * Represents the structure for awarding a badge to one or more recipients\n * within the Nostr network. This structure is used to create templates for\n * badge award events, which are immutable and signify the recognition of\n * individuals' achievements or contributions.\n */\nexport type BadgeAward = {\n /**\n * A reference to the Badge Definition event. This is typically composed\n * of the event ID of the badge definition. It establishes a clear linkage\n * between the badge being awarded and its original definition, ensuring\n * that recipients are awarded the correct badge.\n */\n a: string\n\n /**\n * An array of p tags, each containing a pubkey and its associated relays.\n */\n p: string[][]\n}\n\n/**\n * Represents the collection of badges a user chooses to display on their profile.\n * This structure is crucial for applications that allow users to showcase achievements\n * or recognitions in the form of badges, following the specifications of NIP-58.\n */\nexport type ProfileBadges = {\n /**\n * A unique identifier for the profile badges collection. According to NIP-58,\n * this should be set to \"profile_badges\" to differentiate it from other event types.\n */\n d: 'profile_badges'\n\n /**\n * A list of badges that the user has elected to display on their profile. Each item\n * in the array represents a specific badge, including references to both its definition\n * and the award event.\n */\n badges: Array<{\n /**\n * The event address of the badge definition. This is a reference to the specific badge\n * being displayed, linking back to the badge's original definition event. It allows\n * clients to fetch and display the badge's details, such as its name, description,\n * and image.\n */\n a: string\n\n /**\n * The event id of the badge award with corresponding relays. This references the event\n * in which the badge was awarded to the user. It is crucial for verifying the\n * authenticity of the badge display, ensuring that the user was indeed awarded the\n * badge they are choosing to display.\n */\n e: string[]\n }>\n}\n\n/**\n * Generates an EventTemplate based on the provided BadgeDefinition.\n *\n * @param {BadgeDefinition} badgeDefinition - The BadgeDefinition object.\n * @returns {EventTemplate} - The generated EventTemplate object.\n */\nexport function generateBadgeDefinitionEventTemplate({\n d,\n description,\n image,\n name,\n thumbs,\n}: BadgeDefinition): EventTemplate {\n // Mandatory tags\n const tags: string[][] = [['d', d]]\n\n // Append optional tags\n name && tags.push(['name', name])\n description && tags.push(['description', description])\n image && tags.push(['image', ...image])\n if (thumbs) {\n for (const thumb of thumbs) {\n tags.push(['thumb', ...thumb])\n }\n }\n\n // Construct the EventTemplate object\n const eventTemplate: EventTemplate = {\n content: '',\n created_at: Math.floor(Date.now() / 1000),\n kind: BadgeDefinitionKind,\n tags,\n }\n\n return eventTemplate\n}\n\n/**\n * Validates a badge definition event.\n *\n * @param event - The event to validate.\n * @returns A boolean indicating whether the event is a valid badge definition event.\n */\nexport function validateBadgeDefinitionEvent(event: Event): boolean {\n if (event.kind !== BadgeDefinitionKind) return false\n\n const requiredTags = ['d'] as const\n for (const tag of requiredTags) {\n if (!event.tags.find(([t]) => t == tag)) return false\n }\n\n return true\n}\n\n/**\n * Generates an EventTemplate based on the provided BadgeAward.\n *\n * @param {BadgeAward} badgeAward - The BadgeAward object.\n * @returns {EventTemplate} - The generated EventTemplate object.\n */\nexport function generateBadgeAwardEventTemplate({ a, p }: BadgeAward): EventTemplate {\n // Mandatory tags\n const tags: string[][] = [['a', a]]\n for (const _p of p) {\n tags.push(['p', ..._p])\n }\n\n // Construct the EventTemplate object\n const eventTemplate: EventTemplate = {\n content: '',\n created_at: Math.floor(Date.now() / 1000),\n kind: BadgeAwardKind,\n tags,\n }\n\n return eventTemplate\n}\n\n/**\n * Validates a badge award event.\n *\n * @param event - The event to validate.\n * @returns A boolean indicating whether the event is a valid badge award event.\n */\nexport function validateBadgeAwardEvent(event: Event): boolean {\n if (event.kind !== BadgeAwardKind) return false\n\n const requiredTags = ['a', 'p'] as const\n for (const tag of requiredTags) {\n if (!event.tags.find(([t]) => t == tag)) return false\n }\n\n return true\n}\n\n/**\n * Generates an EventTemplate based on the provided ProfileBadges.\n *\n * @param {ProfileBadges} profileBadges - The ProfileBadges object.\n * @returns {EventTemplate} - The generated EventTemplate object.\n */\nexport function generateProfileBadgesEventTemplate({ badges }: ProfileBadges): EventTemplate {\n // Mandatory tags\n const tags: string[][] = [['d', 'profile_badges']]\n\n // Append optional tags\n for (const badge of badges) {\n tags.push(['a', badge.a], ['e', ...badge.e])\n }\n\n // Construct the EventTemplate object\n const eventTemplate: EventTemplate = {\n content: '',\n created_at: Math.floor(Date.now() / 1000),\n kind: ProfileBadgesKind,\n tags,\n }\n\n return eventTemplate\n}\n\n/**\n * Validates a profile badges event.\n *\n * @param event - The event to validate.\n * @returns A boolean indicating whether the event is a valid profile badges event.\n */\nexport function validateProfileBadgesEvent(event: Event): boolean {\n if (event.kind !== ProfileBadgesKind) return false\n\n const requiredTags = ['d'] as const\n for (const tag of requiredTags) {\n if (!event.tags.find(([t]) => t == tag)) return false\n }\n\n return true\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACuDO,IAAM,aAAa;AAkGnB,IAAM,gBAAgB;AAEtB,IAAM,kBAAkB;;;ADzCxB,SAAS,qCAAqC;AAAA,EACnD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,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AAK,GAAG;AAAG,aAAO;AAAA,EAClD;AAEA,SAAO;AACT;AAQO,SAAS,mCAAmC,EAAE,OAAO,GAAiC;AAE3F,QAAM,OAAmB,CAAC,CAAC,KAAK,gBAAgB,CAAC;AAGjD,aAAW,SAAS,QAAQ;AAC1B,SAAK,KAAK,CAAC,KAAK,MAAM,CAAC,GAAG,CAAC,KAAK,GAAG,MAAM,CAAC,CAAC;AAAA,EAC7C;AAGA,QAAM,gBAA+B;AAAA,IACnC,SAAS;AAAA,IACT,YAAY,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAAA,IACxC,MAAM;AAAA,IACN;AAAA,EACF;AAEA,SAAO;AACT;AAQO,SAAS,2BAA2B,OAAuB;AAChE,MAAI,MAAM,SAAS;AAAmB,WAAO;AAE7C,QAAM,eAAe,CAAC,GAAG;AACzB,aAAW,OAAO,cAAc;AAC9B,QAAI,CAAC,MAAM,KAAK,KAAK,CAAC,CAAC,CAAC,MAAM,KAAK,GAAG;AAAG,aAAO;AAAA,EAClD;AAEA,SAAO;AACT;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip59.js b/node_modules/nostr-tools/lib/cjs/nip59.js new file mode 100644 index 0000000..e95d31b --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip59.js @@ -0,0 +1,298 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip59.ts +var nip59_exports = {}; +__export(nip59_exports, { + createRumor: () => createRumor, + createSeal: () => createSeal, + createWrap: () => createWrap, + unwrapEvent: () => unwrapEvent, + unwrapManyEvents: () => unwrapManyEvents, + wrapEvent: () => wrapEvent, + wrapManyEvents: () => wrapManyEvents +}); +module.exports = __toCommonJS(nip59_exports); + +// nip44.ts +var import_chacha = require("@noble/ciphers/chacha"); +var import_utils2 = require("@noble/ciphers/utils"); +var import_secp256k1 = require("@noble/curves/secp256k1"); +var import_hkdf = require("@noble/hashes/hkdf"); +var import_hmac = require("@noble/hashes/hmac"); +var import_sha256 = require("@noble/hashes/sha256"); +var import_utils3 = require("@noble/hashes/utils"); +var import_base = require("@scure/base"); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// nip44.ts +var minPlaintextSize = 1; +var maxPlaintextSize = 65535; +function getConversationKey(privkeyA, pubkeyB) { + const sharedX = import_secp256k1.secp256k1.getSharedSecret(privkeyA, "02" + pubkeyB).subarray(1, 33); + return (0, import_hkdf.extract)(import_sha256.sha256, sharedX, "nip44-v2"); +} +function getMessageKeys(conversationKey, nonce) { + const keys = (0, import_hkdf.expand)(import_sha256.sha256, conversationKey, nonce, 76); + return { + chacha_key: keys.subarray(0, 32), + chacha_nonce: keys.subarray(32, 44), + hmac_key: keys.subarray(44, 76) + }; +} +function calcPaddedLen(len) { + if (!Number.isSafeInteger(len) || len < 1) + throw new Error("expected positive integer"); + if (len <= 32) + return 32; + const nextPower = 1 << Math.floor(Math.log2(len - 1)) + 1; + const chunk = nextPower <= 256 ? 32 : nextPower / 8; + return chunk * (Math.floor((len - 1) / chunk) + 1); +} +function writeU16BE(num) { + if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize) + throw new Error("invalid plaintext size: must be between 1 and 65535 bytes"); + const arr = new Uint8Array(2); + new DataView(arr.buffer).setUint16(0, num, false); + return arr; +} +function pad(plaintext) { + const unpadded = utf8Encoder.encode(plaintext); + const unpaddedLen = unpadded.length; + const prefix = writeU16BE(unpaddedLen); + const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen); + return (0, import_utils3.concatBytes)(prefix, unpadded, suffix); +} +function unpad(padded) { + const unpaddedLen = new DataView(padded.buffer).getUint16(0); + const unpadded = padded.subarray(2, 2 + unpaddedLen); + if (unpaddedLen < minPlaintextSize || unpaddedLen > maxPlaintextSize || unpadded.length !== unpaddedLen || padded.length !== 2 + calcPaddedLen(unpaddedLen)) + throw new Error("invalid padding"); + return utf8Decoder.decode(unpadded); +} +function hmacAad(key, message, aad) { + if (aad.length !== 32) + throw new Error("AAD associated data must be 32 bytes"); + const combined = (0, import_utils3.concatBytes)(aad, message); + return (0, import_hmac.hmac)(import_sha256.sha256, key, combined); +} +function decodePayload(payload) { + if (typeof payload !== "string") + throw new Error("payload must be a valid string"); + const plen = payload.length; + if (plen < 132 || plen > 87472) + throw new Error("invalid payload length: " + plen); + if (payload[0] === "#") + throw new Error("unknown encryption version"); + let data; + try { + data = import_base.base64.decode(payload); + } catch (error) { + throw new Error("invalid base64: " + error.message); + } + const dlen = data.length; + if (dlen < 99 || dlen > 65603) + throw new Error("invalid data length: " + dlen); + const vers = data[0]; + if (vers !== 2) + throw new Error("unknown encryption version " + vers); + return { + nonce: data.subarray(1, 33), + ciphertext: data.subarray(33, -32), + mac: data.subarray(-32) + }; +} +function encrypt(plaintext, conversationKey, nonce = (0, import_utils3.randomBytes)(32)) { + const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); + const padded = pad(plaintext); + const ciphertext = (0, import_chacha.chacha20)(chacha_key, chacha_nonce, padded); + const mac = hmacAad(hmac_key, ciphertext, nonce); + return import_base.base64.encode((0, import_utils3.concatBytes)(new Uint8Array([2]), nonce, ciphertext, mac)); +} +function decrypt(payload, conversationKey) { + const { nonce, ciphertext, mac } = decodePayload(payload); + const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); + const calculatedMac = hmacAad(hmac_key, ciphertext, nonce); + if (!(0, import_utils2.equalBytes)(calculatedMac, mac)) + throw new Error("invalid MAC"); + const padded = (0, import_chacha.chacha20)(chacha_key, chacha_nonce, ciphertext); + return unpad(padded); +} + +// pure.ts +var import_secp256k12 = require("@noble/curves/secp256k1"); +var import_utils5 = require("@noble/hashes/utils"); + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +var import_sha2562 = require("@noble/hashes/sha256"); +var JS = class { + generateSecretKey() { + return import_secp256k12.schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return (0, import_utils5.bytesToHex)(import_secp256k12.schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = (0, import_utils5.bytesToHex)(import_secp256k12.schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = (0, import_utils5.bytesToHex)(import_secp256k12.schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = import_secp256k12.schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = (0, import_sha2562.sha256)(utf8Encoder.encode(serializeEvent(event))); + return (0, import_utils5.bytesToHex)(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// kinds.ts +var Seal = 13; +var GiftWrap = 1059; + +// nip59.ts +var TWO_DAYS = 2 * 24 * 60 * 60; +var now = () => Math.round(Date.now() / 1e3); +var randomNow = () => Math.round(now() - Math.random() * TWO_DAYS); +var nip44ConversationKey = (privateKey, publicKey) => getConversationKey(privateKey, publicKey); +var nip44Encrypt = (data, privateKey, publicKey) => encrypt(JSON.stringify(data), nip44ConversationKey(privateKey, publicKey)); +var nip44Decrypt = (data, privateKey) => JSON.parse(decrypt(data.content, nip44ConversationKey(privateKey, data.pubkey))); +function createRumor(event, privateKey) { + const rumor = { + created_at: now(), + content: "", + tags: [], + ...event, + pubkey: getPublicKey(privateKey) + }; + rumor.id = getEventHash(rumor); + return rumor; +} +function createSeal(rumor, privateKey, recipientPublicKey) { + return finalizeEvent( + { + kind: Seal, + content: nip44Encrypt(rumor, privateKey, recipientPublicKey), + created_at: randomNow(), + tags: [] + }, + privateKey + ); +} +function createWrap(seal, recipientPublicKey) { + const randomKey = generateSecretKey(); + return finalizeEvent( + { + kind: GiftWrap, + content: nip44Encrypt(seal, randomKey, recipientPublicKey), + created_at: randomNow(), + tags: [["p", recipientPublicKey]] + }, + randomKey + ); +} +function wrapEvent(event, senderPrivateKey, recipientPublicKey) { + const rumor = createRumor(event, senderPrivateKey); + const seal = createSeal(rumor, senderPrivateKey, recipientPublicKey); + return createWrap(seal, recipientPublicKey); +} +function wrapManyEvents(event, senderPrivateKey, recipientsPublicKeys) { + if (!recipientsPublicKeys || recipientsPublicKeys.length === 0) { + throw new Error("At least one recipient is required."); + } + const senderPublicKey = getPublicKey(senderPrivateKey); + const wrappeds = [wrapEvent(event, senderPrivateKey, senderPublicKey)]; + recipientsPublicKeys.forEach((recipientPublicKey) => { + wrappeds.push(wrapEvent(event, senderPrivateKey, recipientPublicKey)); + }); + return wrappeds; +} +function unwrapEvent(wrap, recipientPrivateKey) { + const unwrappedSeal = nip44Decrypt(wrap, recipientPrivateKey); + return nip44Decrypt(unwrappedSeal, recipientPrivateKey); +} +function unwrapManyEvents(wrappedEvents, recipientPrivateKey) { + let unwrappedEvents = []; + wrappedEvents.forEach((e) => { + unwrappedEvents.push(unwrapEvent(e, recipientPrivateKey)); + }); + unwrappedEvents.sort((a, b) => a.created_at - b.created_at); + return unwrappedEvents; +} diff --git a/node_modules/nostr-tools/lib/cjs/nip59.js.map b/node_modules/nostr-tools/lib/cjs/nip59.js.map new file mode 100644 index 0000000..6f147e5 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip59.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip59.ts", "../../nip44.ts", "../../utils.ts", "../../pure.ts", "../../core.ts", "../../kinds.ts"], + "sourcesContent": ["import { EventTemplate, UnsignedEvent, NostrEvent } from './core.ts'\nimport { getConversationKey, decrypt, encrypt } from './nip44.ts'\nimport { getEventHash, generateSecretKey, finalizeEvent, getPublicKey } from './pure.ts'\nimport { Seal, GiftWrap } from './kinds.ts'\n\ntype Rumor = UnsignedEvent & { id: string }\n\nconst TWO_DAYS = 2 * 24 * 60 * 60\n\nconst now = () => Math.round(Date.now() / 1000)\nconst randomNow = () => Math.round(now() - Math.random() * TWO_DAYS)\n\nconst nip44ConversationKey = (privateKey: Uint8Array, publicKey: string) => getConversationKey(privateKey, publicKey)\n\nconst nip44Encrypt = (data: EventTemplate, privateKey: Uint8Array, publicKey: string) =>\n encrypt(JSON.stringify(data), nip44ConversationKey(privateKey, publicKey))\n\nconst nip44Decrypt = (data: NostrEvent, privateKey: Uint8Array) =>\n JSON.parse(decrypt(data.content, nip44ConversationKey(privateKey, data.pubkey)))\n\nexport function createRumor(event: Partial, privateKey: Uint8Array): Rumor {\n const rumor = {\n created_at: now(),\n content: '',\n tags: [],\n ...event,\n pubkey: getPublicKey(privateKey),\n } as any\n\n rumor.id = getEventHash(rumor)\n\n return rumor as Rumor\n}\n\nexport function createSeal(rumor: Rumor, privateKey: Uint8Array, recipientPublicKey: string): NostrEvent {\n return finalizeEvent(\n {\n kind: Seal,\n content: nip44Encrypt(rumor, privateKey, recipientPublicKey),\n created_at: randomNow(),\n tags: [],\n },\n privateKey,\n )\n}\n\nexport function createWrap(seal: NostrEvent, recipientPublicKey: string): NostrEvent {\n const randomKey = generateSecretKey()\n\n return finalizeEvent(\n {\n kind: GiftWrap,\n content: nip44Encrypt(seal, randomKey, recipientPublicKey),\n created_at: randomNow(),\n tags: [['p', recipientPublicKey]],\n },\n randomKey,\n ) as NostrEvent\n}\n\nexport function wrapEvent(\n event: Partial,\n senderPrivateKey: Uint8Array,\n recipientPublicKey: string,\n): NostrEvent {\n const rumor = createRumor(event, senderPrivateKey)\n\n const seal = createSeal(rumor, senderPrivateKey, recipientPublicKey)\n return createWrap(seal, recipientPublicKey)\n}\n\nexport function wrapManyEvents(\n event: Partial,\n senderPrivateKey: Uint8Array,\n recipientsPublicKeys: string[],\n): NostrEvent[] {\n if (!recipientsPublicKeys || recipientsPublicKeys.length === 0) {\n throw new Error('At least one recipient is required.')\n }\n\n const senderPublicKey = getPublicKey(senderPrivateKey)\n\n const wrappeds = [wrapEvent(event, senderPrivateKey, senderPublicKey)]\n\n recipientsPublicKeys.forEach(recipientPublicKey => {\n wrappeds.push(wrapEvent(event, senderPrivateKey, recipientPublicKey))\n })\n\n return wrappeds\n}\n\nexport function unwrapEvent(wrap: NostrEvent, recipientPrivateKey: Uint8Array): Rumor {\n const unwrappedSeal = nip44Decrypt(wrap, recipientPrivateKey)\n return nip44Decrypt(unwrappedSeal, recipientPrivateKey)\n}\n\nexport function unwrapManyEvents(wrappedEvents: NostrEvent[], recipientPrivateKey: Uint8Array): Rumor[] {\n let unwrappedEvents: Rumor[] = []\n\n wrappedEvents.forEach(e => {\n unwrappedEvents.push(unwrapEvent(e, recipientPrivateKey))\n })\n\n unwrappedEvents.sort((a, b) => a.created_at - b.created_at)\n\n return unwrappedEvents\n}\n", "import { chacha20 } from '@noble/ciphers/chacha'\nimport { equalBytes } from '@noble/ciphers/utils'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { extract as hkdf_extract, expand as hkdf_expand } from '@noble/hashes/hkdf'\nimport { hmac } from '@noble/hashes/hmac'\nimport { sha256 } from '@noble/hashes/sha256'\nimport { concatBytes, randomBytes } from '@noble/hashes/utils'\nimport { base64 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nconst minPlaintextSize = 0x0001 // 1b msg => padded to 32b\nconst maxPlaintextSize = 0xffff // 65535 (64kb-1) => padded to 64kb\n\nexport function getConversationKey(privkeyA: Uint8Array, pubkeyB: string): Uint8Array {\n const sharedX = secp256k1.getSharedSecret(privkeyA, '02' + pubkeyB).subarray(1, 33)\n return hkdf_extract(sha256, sharedX, 'nip44-v2')\n}\n\nfunction getMessageKeys(\n conversationKey: Uint8Array,\n nonce: Uint8Array,\n): { chacha_key: Uint8Array; chacha_nonce: Uint8Array; hmac_key: Uint8Array } {\n const keys = hkdf_expand(sha256, conversationKey, nonce, 76)\n return {\n chacha_key: keys.subarray(0, 32),\n chacha_nonce: keys.subarray(32, 44),\n hmac_key: keys.subarray(44, 76),\n }\n}\n\nfunction calcPaddedLen(len: number): number {\n if (!Number.isSafeInteger(len) || len < 1) throw new Error('expected positive integer')\n if (len <= 32) return 32\n const nextPower = 1 << (Math.floor(Math.log2(len - 1)) + 1)\n const chunk = nextPower <= 256 ? 32 : nextPower / 8\n return chunk * (Math.floor((len - 1) / chunk) + 1)\n}\n\nfunction writeU16BE(num: number): Uint8Array {\n if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize)\n throw new Error('invalid plaintext size: must be between 1 and 65535 bytes')\n const arr = new Uint8Array(2)\n new DataView(arr.buffer).setUint16(0, num, false)\n return arr\n}\n\nfunction pad(plaintext: string): Uint8Array {\n const unpadded = utf8Encoder.encode(plaintext)\n const unpaddedLen = unpadded.length\n const prefix = writeU16BE(unpaddedLen)\n const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen)\n return concatBytes(prefix, unpadded, suffix)\n}\n\nfunction unpad(padded: Uint8Array): string {\n const unpaddedLen = new DataView(padded.buffer).getUint16(0)\n const unpadded = padded.subarray(2, 2 + unpaddedLen)\n if (\n unpaddedLen < minPlaintextSize ||\n unpaddedLen > maxPlaintextSize ||\n unpadded.length !== unpaddedLen ||\n padded.length !== 2 + calcPaddedLen(unpaddedLen)\n )\n throw new Error('invalid padding')\n return utf8Decoder.decode(unpadded)\n}\n\nfunction hmacAad(key: Uint8Array, message: Uint8Array, aad: Uint8Array): Uint8Array {\n if (aad.length !== 32) throw new Error('AAD associated data must be 32 bytes')\n const combined = concatBytes(aad, message)\n return hmac(sha256, key, combined)\n}\n\n// metadata: always 65b (version: 1b, nonce: 32b, max: 32b)\n// plaintext: 1b to 0xffff\n// padded plaintext: 32b to 0xffff\n// ciphertext: 32b+2 to 0xffff+2\n// raw payload: 99 (65+32+2) to 65603 (65+0xffff+2)\n// compressed payload (base64): 132b to 87472b\nfunction decodePayload(payload: string): { nonce: Uint8Array; ciphertext: Uint8Array; mac: Uint8Array } {\n if (typeof payload !== 'string') throw new Error('payload must be a valid string')\n const plen = payload.length\n if (plen < 132 || plen > 87472) throw new Error('invalid payload length: ' + plen)\n if (payload[0] === '#') throw new Error('unknown encryption version')\n let data: Uint8Array\n try {\n data = base64.decode(payload)\n } catch (error) {\n throw new Error('invalid base64: ' + (error as any).message)\n }\n const dlen = data.length\n if (dlen < 99 || dlen > 65603) throw new Error('invalid data length: ' + dlen)\n const vers = data[0]\n if (vers !== 2) throw new Error('unknown encryption version ' + vers)\n return {\n nonce: data.subarray(1, 33),\n ciphertext: data.subarray(33, -32),\n mac: data.subarray(-32),\n }\n}\n\nexport function encrypt(plaintext: string, conversationKey: Uint8Array, nonce: Uint8Array = randomBytes(32)): string {\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n const padded = pad(plaintext)\n const ciphertext = chacha20(chacha_key, chacha_nonce, padded)\n const mac = hmacAad(hmac_key, ciphertext, nonce)\n return base64.encode(concatBytes(new Uint8Array([2]), nonce, ciphertext, mac))\n}\n\nexport function decrypt(payload: string, conversationKey: Uint8Array): string {\n const { nonce, ciphertext, mac } = decodePayload(payload)\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n const calculatedMac = hmacAad(hmac_key, ciphertext, nonce)\n if (!equalBytes(calculatedMac, mac)) throw new Error('invalid MAC')\n const padded = chacha20(chacha_key, chacha_nonce, ciphertext)\n return unpad(padded)\n}\n\nexport const v2 = {\n utils: {\n getConversationKey,\n calcPaddedLen,\n },\n encrypt,\n decrypt,\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAAyB;AACzB,IAAAA,gBAA2B;AAC3B,uBAA0B;AAC1B,kBAA+D;AAC/D,kBAAqB;AACrB,oBAAuB;AACvB,IAAAA,gBAAyC;AACzC,kBAAuB;;;ACFvB,mBAAuC;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;;;ADQxD,IAAM,mBAAmB;AACzB,IAAM,mBAAmB;AAElB,SAAS,mBAAmB,UAAsB,SAA6B;AACpF,QAAM,UAAU,2BAAU,gBAAgB,UAAU,OAAO,OAAO,EAAE,SAAS,GAAG,EAAE;AAClF,aAAO,YAAAC,SAAa,sBAAQ,SAAS,UAAU;AACjD;AAEA,SAAS,eACP,iBACA,OAC4E;AAC5E,QAAM,WAAO,YAAAC,QAAY,sBAAQ,iBAAiB,OAAO,EAAE;AAC3D,SAAO;AAAA,IACL,YAAY,KAAK,SAAS,GAAG,EAAE;AAAA,IAC/B,cAAc,KAAK,SAAS,IAAI,EAAE;AAAA,IAClC,UAAU,KAAK,SAAS,IAAI,EAAE;AAAA,EAChC;AACF;AAEA,SAAS,cAAc,KAAqB;AAC1C,MAAI,CAAC,OAAO,cAAc,GAAG,KAAK,MAAM;AAAG,UAAM,IAAI,MAAM,2BAA2B;AACtF,MAAI,OAAO;AAAI,WAAO;AACtB,QAAM,YAAY,KAAM,KAAK,MAAM,KAAK,KAAK,MAAM,CAAC,CAAC,IAAI;AACzD,QAAM,QAAQ,aAAa,MAAM,KAAK,YAAY;AAClD,SAAO,SAAS,KAAK,OAA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AiB,eAA6B,qBAA0C;AACtG,MAAI,kBAA2B,CAAC;AAEhC,gBAAc,QAAQ,OAAK;AACzB,oBAAgB,KAAK,YAAY,GAAG,mBAAmB,CAAC;AAAA,EAC1D,CAAC;AAED,kBAAgB,KAAK,CAAC,GAAG,MAAM,EAAE,aAAa,EAAE,UAAU;AAE1D,SAAO;AACT;", + "names": ["import_utils", "hkdf_extract", "hkdf_expand", "import_secp256k1", "import_utils", "i", "import_sha256"] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip75.js b/node_modules/nostr-tools/lib/cjs/nip75.js new file mode 100644 index 0000000..38014b9 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip75.js @@ -0,0 +1,70 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip75.ts +var nip75_exports = {}; +__export(nip75_exports, { + generateGoalEventTemplate: () => generateGoalEventTemplate, + validateZapGoalEvent: () => validateZapGoalEvent +}); +module.exports = __toCommonJS(nip75_exports); + +// kinds.ts +var ZapGoal = 9041; + +// nip75.ts +function generateGoalEventTemplate({ + amount, + content, + relays, + a, + closedAt, + image, + r, + summary, + zapTags +}) { + const tags = [ + ["amount", amount], + ["relays", ...relays] + ]; + closedAt && tags.push(["closed_at", closedAt.toString()]); + image && tags.push(["image", image]); + summary && tags.push(["summary", summary]); + r && tags.push(["r", r]); + a && tags.push(["a", a]); + zapTags && tags.push(...zapTags); + const eventTemplate = { + created_at: Math.floor(Date.now() / 1e3), + kind: ZapGoal, + content, + tags + }; + return eventTemplate; +} +function validateZapGoalEvent(event) { + if (event.kind !== ZapGoal) + return false; + const requiredTags = ["amount", "relays"]; + for (const tag of requiredTags) { + if (!event.tags.find(([t]) => t == tag)) + return false; + } + return true; +} diff --git a/node_modules/nostr-tools/lib/cjs/nip75.js.map b/node_modules/nostr-tools/lib/cjs/nip75.js.map new file mode 100644 index 0000000..634a112 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip75.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip75.ts", "../../kinds.ts"], + "sourcesContent": ["import { Event, EventTemplate } from './core.ts'\nimport { ZapGoal } from './kinds.ts'\n\n/**\n * Represents a fundraising goal in the Nostr network as defined by NIP-75.\n * This type is used to structure the information needed to create a goal event (`kind:9041`).\n */\nexport type Goal = {\n /**\n * A human-readable description of the fundraising goal.\n * This content should provide clear information about the purpose of the fundraising.\n */\n content: string\n\n /**\n * The target amount for the fundraising goal in milisats.\n * This defines the financial target that the fundraiser aims to reach.\n */\n amount: string\n\n /**\n * A list of relays where the zaps towards this goal will be sent to and tallied from.\n * Each relay is represented by its WebSocket URL.\n */\n relays: string[]\n\n /**\n * An optional timestamp (in seconds, UNIX epoch) indicating when the fundraising goal is considered closed.\n * Zaps published after this timestamp should not count towards the goal progress.\n * If not provided, the goal remains open indefinitely or until manually closed.\n */\n closedAt?: number\n\n /**\n * An optional URL to an image related to the goal.\n * This can be used to visually represent the goal on client interfaces.\n */\n image?: string\n\n /**\n * An optional brief description or summary of the goal.\n * This can provide a quick overview of the goal, separate from the detailed `content`.\n */\n summary?: string\n\n /**\n * An optional URL related to the goal, providing additional information or actions through an 'r' tag.\n * This is a single URL, as per NIP-75 specifications for linking additional resources.\n */\n r?: string\n\n /**\n * An optional parameterized replaceable event linked to the goal, specified through an 'a' tag.\n * This is a single event id, aligning with NIP-75's allowance for linking to specific events.\n */\n a?: string\n\n /**\n * Optional tags specifying multiple beneficiary pubkeys or additional criteria for zapping,\n * allowing contributions to be directed towards multiple recipients or according to specific conditions.\n */\n zapTags?: string[][]\n}\n\n/**\n * Generates an EventTemplate for a fundraising goal based on the provided ZapGoal object.\n * This function is tailored to fit the structure of EventTemplate as defined in the library.\n * @param zapGoal The ZapGoal object containing the details of the fundraising goal.\n * @returns An EventTemplate object structured for creating a Nostr event.\n */\nexport function generateGoalEventTemplate({\n amount,\n content,\n relays,\n a,\n closedAt,\n image,\n r,\n summary,\n zapTags,\n}: Goal): EventTemplate {\n const tags: string[][] = [\n ['amount', amount],\n ['relays', ...relays],\n ]\n\n // Append optional tags based on the presence of optional properties in zapGoal\n closedAt && tags.push(['closed_at', closedAt.toString()])\n image && tags.push(['image', image])\n summary && tags.push(['summary', summary])\n r && tags.push(['r', r])\n a && tags.push(['a', a])\n zapTags && tags.push(...zapTags)\n\n // Construct the EventTemplate object\n const eventTemplate: EventTemplate = {\n created_at: Math.floor(Date.now() / 1000),\n kind: ZapGoal,\n content,\n tags,\n }\n\n return eventTemplate\n}\n\nexport function validateZapGoalEvent(event: Event): boolean {\n if (event.kind !== ZapGoal) return false\n\n const requiredTags = ['amount', 'relays'] as const\n for (const tag of requiredTags) {\n if (!event.tags.find(([t]) => t == tag)) return false\n }\n\n return true\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACiGO,IAAM,UAAU;;;AD3BhB,SAAS,0BAA0B;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAwB;AACtB,QAAM,OAAmB;AAAA,IACvB,CAAC,UAAU,MAAM;AAAA,IACjB,CAAC,UAAU,GAAG,MAAM;AAAA,EACtB;AAGA,cAAY,KAAK,KAAK,CAAC,aAAa,SAAS,SAAS,CAAC,CAAC;AACxD,WAAS,KAAK,KAAK,CAAC,SAAS,KAAK,CAAC;AACnC,aAAW,KAAK,KAAK,CAAC,WAAW,OAAO,CAAC;AACzC,OAAK,KAAK,KAAK,CAAC,KAAK,CAAC,CAAC;AACvB,OAAK,KAAK,KAAK,CAAC,KAAK,CAAC,CAAC;AACvB,aAAW,KAAK,KAAK,GAAG,OAAO;AAG/B,QAAM,gBAA+B;AAAA,IACnC,YAAY,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAAA,IACxC,MAAM;AAAA,IACN;AAAA,IACA;AAAA,EACF;AAEA,SAAO;AACT;AAEO,SAAS,qBAAqB,OAAuB;AAC1D,MAAI,MAAM,SAAS;AAAS,WAAO;AAEnC,QAAM,eAAe,CAAC,UAAU,QAAQ;AACxC,aAAW,OAAO,cAAc;AAC9B,QAAI,CAAC,MAAM,KAAK,KAAK,CAAC,CAAC,CAAC,MAAM,KAAK,GAAG;AAAG,aAAO;AAAA,EAClD;AAEA,SAAO;AACT;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip94.js b/node_modules/nostr-tools/lib/cjs/nip94.js new file mode 100644 index 0000000..242e559 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip94.js @@ -0,0 +1,142 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip94.ts +var nip94_exports = {}; +__export(nip94_exports, { + generateEventTemplate: () => generateEventTemplate, + parseEvent: () => parseEvent, + validateEvent: () => validateEvent +}); +module.exports = __toCommonJS(nip94_exports); + +// kinds.ts +var FileMetadata = 1063; + +// nip94.ts +function generateEventTemplate(fileMetadata) { + const eventTemplate = { + content: fileMetadata.content, + created_at: Math.floor(Date.now() / 1e3), + kind: FileMetadata, + tags: [ + ["url", fileMetadata.url], + ["m", fileMetadata.m], + ["x", fileMetadata.x], + ["ox", fileMetadata.ox] + ] + }; + if (fileMetadata.size) + eventTemplate.tags.push(["size", fileMetadata.size]); + if (fileMetadata.dim) + eventTemplate.tags.push(["dim", fileMetadata.dim]); + if (fileMetadata.i) + eventTemplate.tags.push(["i", fileMetadata.i]); + if (fileMetadata.blurhash) + eventTemplate.tags.push(["blurhash", fileMetadata.blurhash]); + if (fileMetadata.thumb) + eventTemplate.tags.push(["thumb", fileMetadata.thumb]); + if (fileMetadata.image) + eventTemplate.tags.push(["image", fileMetadata.image]); + if (fileMetadata.summary) + eventTemplate.tags.push(["summary", fileMetadata.summary]); + if (fileMetadata.alt) + eventTemplate.tags.push(["alt", fileMetadata.alt]); + if (fileMetadata.fallback) + fileMetadata.fallback.forEach((url) => eventTemplate.tags.push(["fallback", url])); + return eventTemplate; +} +function validateEvent(event) { + if (event.kind !== FileMetadata) + return false; + if (!event.content) + return false; + const requiredTags = ["url", "m", "x", "ox"]; + for (const tag of requiredTags) { + if (!event.tags.find(([t]) => t == tag)) + return false; + } + const sizeTag = event.tags.find(([t]) => t == "size"); + if (sizeTag && isNaN(Number(sizeTag[1]))) + return false; + const dimTag = event.tags.find(([t]) => t == "dim"); + if (dimTag && !dimTag[1].match(/^\d+x\d+$/)) + return false; + return true; +} +function parseEvent(event) { + if (!validateEvent(event)) { + throw new Error("Invalid event"); + } + const fileMetadata = { + content: event.content, + url: "", + m: "", + x: "", + ox: "" + }; + for (const [tag, value] of event.tags) { + switch (tag) { + case "url": + fileMetadata.url = value; + break; + case "m": + fileMetadata.m = value; + break; + case "x": + fileMetadata.x = value; + break; + case "ox": + fileMetadata.ox = value; + break; + case "size": + fileMetadata.size = value; + break; + case "dim": + fileMetadata.dim = value; + break; + case "magnet": + fileMetadata.magnet = value; + break; + case "i": + fileMetadata.i = value; + break; + case "blurhash": + fileMetadata.blurhash = value; + break; + case "thumb": + fileMetadata.thumb = value; + break; + case "image": + fileMetadata.image = value; + break; + case "summary": + fileMetadata.summary = value; + break; + case "alt": + fileMetadata.alt = value; + break; + case "fallback": + fileMetadata.fallback ??= []; + fileMetadata.fallback.push(value); + break; + } + } + return fileMetadata; +} diff --git a/node_modules/nostr-tools/lib/cjs/nip94.js.map b/node_modules/nostr-tools/lib/cjs/nip94.js.map new file mode 100644 index 0000000..dc4a605 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip94.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip94.ts", "../../kinds.ts"], + "sourcesContent": ["import { Event, EventTemplate } from './core.ts'\nimport { FileMetadata as FileMetadataKind } from './kinds.ts'\n\n/**\n * Type definition for File Metadata as specified in NIP-94.\n * This type is used to represent the metadata associated with a file sharing event (kind: 1063).\n */\nexport type FileMetadataObject = {\n /**\n * A description or caption for the file content.\n */\n content: string\n\n /**\n * The URL to download the file.\n */\n url: string\n\n /**\n * The MIME type of the file, in lowercase.\n */\n m: string\n\n /**\n * The SHA-256 hex-encoded string of the file.\n */\n x: string\n\n /**\n * The SHA-256 hex-encoded string of the original file, before any transformations done by the upload server.\n */\n ox: string\n\n /**\n * Optional: The size of the file in bytes.\n */\n size?: string\n\n /**\n * Optional: The dimensions of the file in pixels, in the format \"x\".\n */\n dim?: string\n\n /**\n * Optional: The URI to the magnet file.\n */\n magnet?: string\n\n /**\n * Optional: The torrent infohash.\n */\n i?: string\n\n /**\n * Optional: The blurhash string to show while the file is being loaded by the client.\n */\n blurhash?: string\n\n /**\n * Optional: The URL of the thumbnail image with the same aspect ratio as the original file.\n */\n thumb?: string\n\n /**\n * Optional: The URL of a preview image with the same dimensions as the original file.\n */\n image?: string\n\n /**\n * Optional: A text excerpt or summary of the file's content.\n */\n summary?: string\n\n /**\n * Optional: A description for accessibility, providing context or a brief description of the file.\n */\n alt?: string\n\n /**\n * Optional: fallback URLs in case url fails.\n */\n fallback?: string[]\n}\n\n/**\n * Generates an event template based on a file metadata object.\n *\n * @param fileMetadata - The file metadata object.\n * @returns The event template.\n */\nexport function generateEventTemplate(fileMetadata: FileMetadataObject): EventTemplate {\n const eventTemplate: EventTemplate = {\n content: fileMetadata.content,\n created_at: Math.floor(Date.now() / 1000),\n kind: FileMetadataKind,\n tags: [\n ['url', fileMetadata.url],\n ['m', fileMetadata.m],\n ['x', fileMetadata.x],\n ['ox', fileMetadata.ox],\n ],\n }\n\n if (fileMetadata.size) eventTemplate.tags.push(['size', fileMetadata.size])\n if (fileMetadata.dim) eventTemplate.tags.push(['dim', fileMetadata.dim])\n if (fileMetadata.i) eventTemplate.tags.push(['i', fileMetadata.i])\n if (fileMetadata.blurhash) eventTemplate.tags.push(['blurhash', fileMetadata.blurhash])\n if (fileMetadata.thumb) eventTemplate.tags.push(['thumb', fileMetadata.thumb])\n if (fileMetadata.image) eventTemplate.tags.push(['image', fileMetadata.image])\n if (fileMetadata.summary) eventTemplate.tags.push(['summary', fileMetadata.summary])\n if (fileMetadata.alt) eventTemplate.tags.push(['alt', fileMetadata.alt])\n if (fileMetadata.fallback) fileMetadata.fallback.forEach(url => eventTemplate.tags.push(['fallback', url]))\n\n return eventTemplate\n}\n\n/**\n * Validates an event to ensure it is a valid file metadata event.\n * @param event - The event to validate.\n * @returns True if the event is valid, false otherwise.\n */\nexport function validateEvent(event: Event): boolean {\n if (event.kind !== FileMetadataKind) return false\n\n if (!event.content) return false\n\n const requiredTags = ['url', 'm', 'x', 'ox'] as const\n for (const tag of requiredTags) {\n if (!event.tags.find(([t]) => t == tag)) return false\n }\n\n // validate optional size tag\n const sizeTag = event.tags.find(([t]) => t == 'size')\n if (sizeTag && isNaN(Number(sizeTag[1]))) return false\n\n // validate optional dim tag\n const dimTag = event.tags.find(([t]) => t == 'dim')\n if (dimTag && !dimTag[1].match(/^\\d+x\\d+$/)) return false\n\n return true\n}\n\n/**\n * Parses an event and returns a file metadata object.\n * @param event - The event to parse.\n * @returns The file metadata object.\n * @throws Error if the event is invalid.\n */\nexport function parseEvent(event: Event): FileMetadataObject {\n if (!validateEvent(event)) {\n throw new Error('Invalid event')\n }\n\n const fileMetadata: FileMetadataObject = {\n content: event.content,\n url: '',\n m: '',\n x: '',\n ox: '',\n }\n\n for (const [tag, value] of event.tags) {\n switch (tag) {\n case 'url':\n fileMetadata.url = value\n break\n case 'm':\n fileMetadata.m = value\n break\n case 'x':\n fileMetadata.x = value\n break\n case 'ox':\n fileMetadata.ox = value\n break\n case 'size':\n fileMetadata.size = value\n break\n case 'dim':\n fileMetadata.dim = value\n break\n case 'magnet':\n fileMetadata.magnet = value\n break\n case 'i':\n fileMetadata.i = value\n break\n case 'blurhash':\n fileMetadata.blurhash = value\n break\n case 'thumb':\n fileMetadata.thumb = value\n break\n case 'image':\n fileMetadata.image = value\n break\n case 'summary':\n fileMetadata.summary = value\n break\n case 'alt':\n fileMetadata.alt = value\n break\n case 'fallback':\n fileMetadata.fallback ??= []\n fileMetadata.fallback.push(value)\n break\n }\n }\n\n return fileMetadata\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC6EO,IAAM,eAAe;;;ADarB,SAAS,sBAAsB,cAAiD;AACrF,QAAM,gBAA+B;AAAA,IACnC,SAAS,aAAa;AAAA,IACtB,YAAY,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAAA,IACxC,MAAM;AAAA,IACN,MAAM;AAAA,M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MAAM,OAAO,QAAQ,EAAE,CAAC;AAAG,WAAO;AAGjD,QAAM,SAAS,MAAM,KAAK,KAAK,CAAC,CAAC,CAAC,MAAM,KAAK,KAAK;AAClD,MAAI,UAAU,CAAC,OAAO,GAAG,MAAM,WAAW;AAAG,WAAO;AAEpD,SAAO;AACT;AAQO,SAAS,WAAW,OAAkC;AAC3D,MAAI,CAAC,cAAc,KAAK,GAAG;AACzB,UAAM,IAAI,MAAM,eAAe;AAAA,EACjC;AAEA,QAAM,eAAmC;AAAA,IACvC,SAAS,MAAM;AAAA,IACf,KAAK;AAAA,IACL,GAAG;AAAA,IACH,GAAG;AAAA,IACH,IAAI;AAAA,EACN;AAEA,aAAW,CAAC,KAAK,KAAK,KAAK,MAAM,MAAM;AACrC,YAAQ,KAAK;AAAA,MACX,KAAK;AACH,qBAAa,MAAM;AACnB;AAAA,MACF,KAAK;AACH,qBAAa,IAAI;AACjB;AAAA,MACF,KAAK;AACH,qBAAa,IAAI;AACjB;AAAA,MACF,KAAK;AACH,qBAAa,KAAK;AAClB;AAAA,MACF,KAAK;AACH,qBAAa,OAAO;AACpB;AAAA,MACF,KAAK;AACH,qBAAa,MAAM;AACnB;AAAA,MACF,KAAK;AACH,qBAAa,SAAS;AACtB;AAAA,MACF,KAAK;AACH,qBAAa,IAAI;AACjB;AAAA,MACF,KAAK;AACH,qBAAa,WAAW;AACxB;AAAA,MACF,KAAK;AACH,qBAAa,QAAQ;AACrB;AAAA,MACF,KAAK;AACH,qBAAa,QAAQ;AACrB;AAAA,MACF,KAAK;AACH,qBAAa,UAAU;AACvB;AAAA,MACF,KAAK;AACH,qBAAa,MAAM;AACnB;AAAA,MACF,KAAK;AACH,qBAAa,aAAa,CAAC;AAC3B,qBAAa,SAAS,KAAK,KAAK;AAChC;AAAA,IACJ;AAAA,EACF;AAEA,SAAO;AACT;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip98.js b/node_modules/nostr-tools/lib/cjs/nip98.js new file mode 100644 index 0000000..dbd5d10 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip98.js @@ -0,0 +1,230 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip98.ts +var nip98_exports = {}; +__export(nip98_exports, { + getToken: () => getToken, + hashPayload: () => hashPayload, + unpackEventFromToken: () => unpackEventFromToken, + validateEvent: () => validateEvent2, + validateEventKind: () => validateEventKind, + validateEventMethodTag: () => validateEventMethodTag, + validateEventPayloadTag: () => validateEventPayloadTag, + validateEventTimestamp: () => validateEventTimestamp, + validateEventUrlTag: () => validateEventUrlTag, + validateToken: () => validateToken +}); +module.exports = __toCommonJS(nip98_exports); +var import_sha2562 = require("@noble/hashes/sha256"); +var import_utils4 = require("@noble/hashes/utils"); +var import_base = require("@scure/base"); + +// pure.ts +var import_secp256k1 = require("@noble/curves/secp256k1"); +var import_utils2 = require("@noble/hashes/utils"); + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +var import_sha256 = require("@noble/hashes/sha256"); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// pure.ts +var JS = class { + generateSecretKey() { + return import_secp256k1.schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = import_secp256k1.schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = (0, import_sha256.sha256)(utf8Encoder.encode(serializeEvent(event))); + return (0, import_utils2.bytesToHex)(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// kinds.ts +var HTTPAuth = 27235; + +// nip98.ts +var _authorizationScheme = "Nostr "; +async function getToken(loginUrl, httpMethod, sign, includeAuthorizationScheme = false, payload) { + const event = { + kind: HTTPAuth, + tags: [ + ["u", loginUrl], + ["method", httpMethod] + ], + created_at: Math.round(new Date().getTime() / 1e3), + content: "" + }; + if (payload) { + event.tags.push(["payload", hashPayload(payload)]); + } + const signedEvent = await sign(event); + const authorizationScheme = includeAuthorizationScheme ? _authorizationScheme : ""; + return authorizationScheme + import_base.base64.encode(utf8Encoder.encode(JSON.stringify(signedEvent))); +} +async function validateToken(token, url, method) { + const event = await unpackEventFromToken(token).catch((error) => { + throw error; + }); + const valid = await validateEvent2(event, url, method).catch((error) => { + throw error; + }); + return valid; +} +async function unpackEventFromToken(token) { + if (!token) { + throw new Error("Missing token"); + } + token = token.replace(_authorizationScheme, ""); + const eventB64 = utf8Decoder.decode(import_base.base64.decode(token)); + if (!eventB64 || eventB64.length === 0 || !eventB64.startsWith("{")) { + throw new Error("Invalid token"); + } + const event = JSON.parse(eventB64); + return event; +} +function validateEventTimestamp(event) { + if (!event.created_at) { + return false; + } + return Math.round(new Date().getTime() / 1e3) - event.created_at < 60; +} +function validateEventKind(event) { + return event.kind === HTTPAuth; +} +function validateEventUrlTag(event, url) { + const urlTag = event.tags.find((t) => t[0] === "u"); + if (!urlTag) { + return false; + } + return urlTag.length > 0 && urlTag[1] === url; +} +function validateEventMethodTag(event, method) { + const methodTag = event.tags.find((t) => t[0] === "method"); + if (!methodTag) { + return false; + } + return methodTag.length > 0 && methodTag[1].toLowerCase() === method.toLowerCase(); +} +function hashPayload(payload) { + const hash = (0, import_sha2562.sha256)(utf8Encoder.encode(JSON.stringify(payload))); + return (0, import_utils4.bytesToHex)(hash); +} +function validateEventPayloadTag(event, payload) { + const payloadTag = event.tags.find((t) => t[0] === "payload"); + if (!payloadTag) { + return false; + } + const payloadHash = hashPayload(payload); + return payloadTag.length > 0 && payloadTag[1] === payloadHash; +} +async function validateEvent2(event, url, method, body) { + if (!verifyEvent(event)) { + throw new Error("Invalid nostr event, signature invalid"); + } + if (!validateEventKind(event)) { + throw new Error("Invalid nostr event, kind invalid"); + } + if (!validateEventTimestamp(event)) { + throw new Error("Invalid nostr event, created_at timestamp invalid"); + } + if (!validateEventUrlTag(event, url)) { + throw new Error("Invalid nostr event, url tag invalid"); + } + if (!validateEventMethodTag(event, method)) { + throw new Error("Invalid nostr event, method tag invalid"); + } + if (Boolean(body) && typeof body === "object" && Object.keys(body).length > 0) { + if (!validateEventPayloadTag(event, body)) { + throw new Error("Invalid nostr event, payload tag does not match request body hash"); + } + } + return true; +} diff --git a/node_modules/nostr-tools/lib/cjs/nip98.js.map b/node_modules/nostr-tools/lib/cjs/nip98.js.map new file mode 100644 index 0000000..a742c64 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip98.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip98.ts", "../../pure.ts", "../../core.ts", "../../utils.ts", "../../kinds.ts"], + "sourcesContent": ["import { sha256 } from '@noble/hashes/sha256'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { base64 } from '@scure/base'\n\nimport { HTTPAuth } from './kinds.ts'\nimport { Event, EventTemplate, verifyEvent } from './pure.ts'\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nconst _authorizationScheme = 'Nostr '\n\n/**\n * Generate token for NIP-98 flow.\n *\n * @example\n * const sign = window.nostr.signEvent\n * await nip98.getToken('https://example.com/login', 'post', (e) => sign(e), true)\n */\nexport async function getToken(\n loginUrl: string,\n httpMethod: string,\n sign: (e: EventTemplate) => Promise | Event,\n includeAuthorizationScheme: boolean = false,\n payload?: Record,\n): Promise {\n const event: EventTemplate = {\n kind: HTTPAuth,\n tags: [\n ['u', loginUrl],\n ['method', httpMethod],\n ],\n created_at: Math.round(new Date().getTime() / 1000),\n content: '',\n }\n\n if (payload) {\n event.tags.push(['payload', hashPayload(payload)])\n }\n\n const signedEvent = await sign(event)\n const authorizationScheme = includeAuthorizationScheme ? _authorizationScheme : ''\n\n return authorizationScheme + base64.encode(utf8Encoder.encode(JSON.stringify(signedEvent)))\n}\n\n/**\n * Validate token for NIP-98 flow.\n *\n * @example\n * await nip98.validateToken('Nostr base64token', 'https://example.com/login', 'post')\n */\nexport async function validateToken(token: string, url: string, method: string): Promise {\n const event = await unpackEventFromToken(token).catch(error => {\n throw error\n })\n\n const valid = await validateEvent(event, url, method).catch(error => {\n throw error\n })\n\n return valid\n}\n\n/**\n * Unpacks an event from a token.\n *\n * @param token - The token to unpack.\n * @returns A promise that resolves to the unpacked event.\n * @throws {Error} If the token is missing, invalid, or cannot be parsed.\n */\nexport async function unpackEventFromToken(token: string): Promise {\n if (!token) {\n throw new Error('Missing token')\n }\n\n token = token.replace(_authorizationScheme, '')\n\n const eventB64 = utf8Decoder.decode(base64.decode(token))\n if (!eventB64 || eventB64.length === 0 || !eventB64.startsWith('{')) {\n throw new Error('Invalid token')\n }\n\n const event = JSON.parse(eventB64) as Event\n\n return event\n}\n\n/**\n * Validates the timestamp of an event.\n * @param event - The event object to validate.\n * @returns A boolean indicating whether the event timestamp is within the last 60 seconds.\n */\nexport function validateEventTimestamp(event: Event): boolean {\n if (!event.created_at) {\n return false\n }\n\n return Math.round(new Date().getTime() / 1000) - event.created_at < 60\n}\n\n/**\n * Validates the kind of an event.\n * @param event The event to validate.\n * @returns A boolean indicating whether the event kind is valid.\n */\nexport function validateEventKind(event: Event): boolean {\n return event.kind === HTTPAuth\n}\n\n/**\n * Validates if the given URL matches the URL tag of the event.\n * @param event - The event object.\n * @param url - The URL to validate.\n * @returns A boolean indicating whether the URL is valid or not.\n */\nexport function validateEventUrlTag(event: Event, url: string): boolean {\n const urlTag = event.tags.find(t => t[0] === 'u')\n\n if (!urlTag) {\n return false\n }\n\n return urlTag.length > 0 && urlTag[1] === url\n}\n\n/**\n * Validates if the given event has a method tag that matches the specified method.\n * @param event - The event to validate.\n * @param method - The method to match against the method tag.\n * @returns A boolean indicating whether the event has a matching method tag.\n */\nexport function validateEventMethodTag(event: Event, method: string): boolean {\n const methodTag = event.tags.find(t => t[0] === 'method')\n\n if (!methodTag) {\n return false\n }\n\n return methodTag.length > 0 && methodTag[1].toLowerCase() === method.toLowerCase()\n}\n\n/**\n * Calculates the hash of a payload.\n * @param payload - The payload to be hashed.\n * @returns The hash value as a string.\n */\nexport function hashPayload(payload: any): string {\n const hash = sha256(utf8Encoder.encode(JSON.stringify(payload)))\n return bytesToHex(hash)\n}\n\n/**\n * Validates the event payload tag against the provided payload.\n * @param event The event object.\n * @param payload The payload to validate.\n * @returns A boolean indicating whether the payload tag is valid.\n */\nexport function validateEventPayloadTag(event: Event, payload: any): boolean {\n const payloadTag = event.tags.find(t => t[0] === 'payload')\n\n if (!payloadTag) {\n return false\n }\n\n const payloadHash = hashPayload(payload)\n return payloadTag.length > 0 && payloadTag[1] === payloadHash\n}\n\n/**\n * Validates a Nostr event for the NIP-98 flow.\n *\n * @param event - The Nostr event to validate.\n * @param url - The URL associated with the event.\n * @param method - The HTTP method associated with the event.\n * @param body - The request body associated with the event (optional).\n * @returns A promise that resolves to a boolean indicating whether the event is valid.\n * @throws An error if the event is invalid.\n */\nexport async function validateEvent(event: Event, url: string, method: string, body?: any): Promise {\n if (!verifyEvent(event)) {\n throw new Error('Invalid nostr event, signature invalid')\n }\n\n if (!validateEventKind(event)) {\n throw new Error('Invalid nostr event, kind invalid')\n }\n\n if (!validateEventTimestamp(event)) {\n throw new Error('Invalid nostr event, created_at timestamp invalid')\n }\n\n if (!validateEventUrlTag(event, url)) {\n throw new Error('Invalid nostr event, url tag invalid')\n }\n\n if (!validateEventMethodTag(event, method)) {\n throw new Error('Invalid nostr event, method tag invalid')\n }\n\n if (Boolean(body) && typeof body === 'object' && Object.keys(body).length > 0) {\n if (!validateEventPayloadTag(event, body)) {\n throw new Error('Invalid nostr event, payload tag does not match request body hash')\n }\n }\n\n return true\n}\n", "import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAC,iBAAuB;AACvB,IAAAC,gBAA2B;AAC3B,kBAAuB;;;ACFvB,uBAAwB;AACxB,IAAAC,gBAA2B;;;ACOpB,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,CAAC,QAAiD,eAAe;AAE3E,SAAS,cAAiB,OAAsC;AACrE,MAAI,CAAC,SAAS,KAAK;AAAG,WAAO;AAC7B,MAAI,OAAO,MAAM,SAAS;AAAU,WAAO;AAC3C,MAAI,OAAO,MAAM,YAAY;AAAU,WAAO;AAC9C,MAAI,OAAO,MAAM,eAAe;AAAU,WAAO;AACjD,MAAI,OAAO,MAAM,WAAW;AAAU,WAAO;AAC7C,MAAI,CAAC,MAAM,OAAO,MAAM,gBAAgB;AAAG,WAAO;AAElD,MAAI,CAAC,MAAM,QAAQ,MAAM,IAAI;AAAG,WAAO;AACvC,WAASC,KAAI,GAAGA,KAAI,MAAM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,WAAW,SAAS,KAAK,WAAW,OAAO;AACpD;AAYA,eAAsBA,eAAc,OAAc,KAAa,QAAgB,MAA8B;AAC3G,MAAI,CAAC,YAAY,KAAK,GAAG;AACvB,UAAM,IAAI,MAAM,wCAAwC;AAAA,EAC1D;AAEA,MAAI,CAAC,kBAAkB,KAAK,GAAG;AAC7B,UAAM,IAAI,MAAM,mCAAmC;AAAA,EACrD;AAEA,MAAI,CAAC,uBAAuB,KAAK,GAAG;AAClC,UAAM,IAAI,MAAM,mDAAmD;AAAA,EACrE;AAEA,MAAI,CAAC,oBAAoB,OAAO,GAAG,GAAG;AACpC,UAAM,IAAI,MAAM,sCAAsC;AAAA,EACxD;AAEA,MAAI,CAAC,uBAAuB,OAAO,MAAM,GAAG;AAC1C,UAAM,IAAI,MAAM,yCAAyC;AAAA,EAC3D;AAEA,MAAI,QAAQ,IAAI,KAAK,OAAO,SAAS,YAAY,OAAO,KAAK,IAAI,EAAE,SAAS,GAAG;AAC7E,QAAI,CAAC,wBAAwB,OAAO,IAAI,GAAG;AACzC,YAAM,IAAI,MAAM,mEAAmE;AAAA,IACrF;AAAA,EACF;AAEA,SAAO;AACT;", + "names": ["validateEvent", "import_sha256", "import_utils", "import_utils", "i", "validateEvent"] +} diff --git a/node_modules/nostr-tools/lib/cjs/nip99.js b/node_modules/nostr-tools/lib/cjs/nip99.js new file mode 100644 index 0000000..a705e8b --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip99.js @@ -0,0 +1,153 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nip99.ts +var nip99_exports = {}; +__export(nip99_exports, { + generateEventTemplate: () => generateEventTemplate, + parseEvent: () => parseEvent, + validateEvent: () => validateEvent +}); +module.exports = __toCommonJS(nip99_exports); + +// kinds.ts +var ClassifiedListing = 30402; +var DraftClassifiedListing = 30403; + +// nip99.ts +function validateEvent(event) { + if (![ClassifiedListing, DraftClassifiedListing].includes(event.kind)) + return false; + const requiredTags = ["d", "title", "summary", "location", "published_at", "price"]; + const requiredTagCount = requiredTags.length; + const tagCounts = {}; + if (event.tags.length < requiredTagCount) + return false; + for (const tag of event.tags) { + if (tag.length < 2) + return false; + const [tagName, ...tagValues] = tag; + if (tagName == "published_at") { + const timestamp = parseInt(tagValues[0]); + if (isNaN(timestamp)) + return false; + } else if (tagName == "price") { + if (tagValues.length < 2) + return false; + const price = parseInt(tagValues[0]); + if (isNaN(price) || tagValues[1].length != 3) + return false; + } else if ((tagName == "e" || tagName == "a") && tag.length != 3) { + return false; + } + if (requiredTags.includes(tagName)) { + tagCounts[tagName] = (tagCounts[tagName] || 0) + 1; + } + } + return Object.values(tagCounts).every((count) => count == 1) && Object.keys(tagCounts).length == requiredTagCount; +} +function parseEvent(event) { + if (!validateEvent(event)) { + throw new Error("Invalid event"); + } + const listing = { + isDraft: event.kind === DraftClassifiedListing, + title: "", + summary: "", + content: event.content, + publishedAt: "", + location: "", + price: { + amount: "", + currency: "" + }, + images: [], + hashtags: [], + additionalTags: {} + }; + for (let i = 0; i < event.tags.length; i++) { + const tag = event.tags[i]; + const [tagName, ...tagValues] = tag; + if (tagName == "title") { + listing.title = tagValues[0]; + } else if (tagName == "summary") { + listing.summary = tagValues[0]; + } else if (tagName == "published_at") { + listing.publishedAt = tagValues[0]; + } else if (tagName == "location") { + listing.location = tagValues[0]; + } else if (tagName == "price") { + listing.price.amount = tagValues[0]; + listing.price.currency = tagValues[1]; + if (tagValues.length == 3) { + listing.price.frequency = tagValues[2]; + } + } else if (tagName == "image") { + listing.images.push({ + url: tagValues[0], + dimensions: tagValues?.[1] ?? void 0 + }); + } else if (tagName == "t") { + listing.hashtags.push(tagValues[0]); + } else if (tagName == "e" || tagName == "a") { + listing.additionalTags[tagName] = [...tagValues]; + } + } + return listing; +} +function generateEventTemplate(listing) { + const priceTag = ["price", listing.price.amount, listing.price.currency]; + if (listing.price.frequency) + priceTag.push(listing.price.frequency); + const tags = [ + ["d", listing.title.trim().toLowerCase().replace(/ /g, "-")], + ["title", listing.title], + ["published_at", listing.publishedAt], + ["summary", listing.summary], + ["location", listing.location], + priceTag + ]; + for (let i = 0; i < listing.images.length; i++) { + const image = listing.images[i]; + const imageTag = ["image", image.url]; + if (image.dimensions) + imageTag.push(image.dimensions); + tags.push(imageTag); + } + for (let i = 0; i < listing.hashtags.length; i++) { + const t = listing.hashtags[i]; + tags.push(["t", t]); + } + for (const [key, value] of Object.entries(listing.additionalTags)) { + if (Array.isArray(value)) { + for (let i = 0; i < value.length; i++) { + const val = value[i]; + tags.push([key, val]); + } + } else { + tags.push([key, value]); + } + } + return { + kind: listing.isDraft ? DraftClassifiedListing : ClassifiedListing, + content: listing.content, + tags, + created_at: Math.floor(Date.now() / 1e3) + }; +} diff --git a/node_modules/nostr-tools/lib/cjs/nip99.js.map b/node_modules/nostr-tools/lib/cjs/nip99.js.map new file mode 100644 index 0000000..ee78868 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nip99.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip99.ts", "../../kinds.ts"], + "sourcesContent": ["import { Event, EventTemplate } from './core.ts'\nimport { ClassifiedListing, DraftClassifiedListing } from './kinds.ts'\n\n/**\n * Represents the details of a price.\n * @example { amount: '100', currency: 'USD', frequency: 'month' }\n * @example { amount: '100', currency: 'EUR' }\n */\nexport type PriceDetails = {\n /**\n * The amount of the price.\n */\n amount: string\n /**\n * The currency of the price in 3-letter ISO 4217 format.\n * @example 'USD'\n */\n currency: string\n /**\n * The optional frequency of payment.\n * Can be one of: 'hour', 'day', 'week', 'month', 'year', or a custom string.\n */\n frequency?: string\n}\n\n/**\n * Represents a classified listing object.\n */\nexport type ClassifiedListingObject = {\n /**\n * Whether the listing is a draft or not.\n */\n isDraft: boolean\n /**\n * A title of the listing.\n */\n title: string\n /**\n * A short summary or tagline.\n */\n summary: string\n /**\n * A description in Markdown format.\n */\n content: string\n /**\n * Timestamp in unix seconds of when the listing was published.\n */\n publishedAt: string\n /**\n * Location of the listing.\n * @example 'NYC'\n */\n location: string\n /**\n * Price details.\n */\n price: PriceDetails\n /**\n * Images of the listing with optional dimensions.\n */\n images: Array<{\n url: string\n dimensions?: string\n }>\n /**\n * Tags/Hashtags (i.e. categories, keywords, etc.)\n */\n hashtags: string[]\n /**\n * Other standard tags.\n * @example \"g\", a geohash for more precise location\n */\n additionalTags: Record\n}\n\n/**\n * Validates an event to ensure it is a valid classified listing event.\n * @param event - The event to validate.\n * @returns True if the event is valid, false otherwise.\n */\nexport function validateEvent(event: Event): boolean {\n if (![ClassifiedListing, DraftClassifiedListing].includes(event.kind)) return false\n\n const requiredTags = ['d', 'title', 'summary', 'location', 'published_at', 'price']\n const requiredTagCount = requiredTags.length\n const tagCounts: Record = {}\n\n if (event.tags.length < requiredTagCount) return false\n\n for (const tag of event.tags) {\n if (tag.length < 2) return false\n\n const [tagName, ...tagValues] = tag\n\n if (tagName == 'published_at') {\n const timestamp = parseInt(tagValues[0])\n if (isNaN(timestamp)) return false\n } else if (tagName == 'price') {\n if (tagValues.length < 2) return false\n\n const price = parseInt(tagValues[0])\n if (isNaN(price) || tagValues[1].length != 3) return false\n } else if ((tagName == 'e' || tagName == 'a') && tag.length != 3) {\n return false\n }\n\n if (requiredTags.includes(tagName)) {\n tagCounts[tagName] = (tagCounts[tagName] || 0) + 1\n }\n }\n\n return Object.values(tagCounts).every(count => count == 1) && Object.keys(tagCounts).length == requiredTagCount\n}\n\n/**\n * Parses an event and returns a classified listing object.\n * @param event - The event to parse.\n * @returns The classified listing object.\n * @throws Error if the event is invalid.\n */\nexport function parseEvent(event: Event): ClassifiedListingObject {\n if (!validateEvent(event)) {\n throw new Error('Invalid event')\n }\n\n const listing: ClassifiedListingObject = {\n isDraft: event.kind === DraftClassifiedListing,\n title: '',\n summary: '',\n content: event.content,\n publishedAt: '',\n location: '',\n price: {\n amount: '',\n currency: '',\n },\n images: [],\n hashtags: [],\n additionalTags: {},\n }\n\n for (let i = 0; i < event.tags.length; i++) {\n const tag = event.tags[i]\n const [tagName, ...tagValues] = tag\n\n if (tagName == 'title') {\n listing.title = tagValues[0]\n } else if (tagName == 'summary') {\n listing.summary = tagValues[0]\n } else if (tagName == 'published_at') {\n listing.publishedAt = tagValues[0]\n } else if (tagName == 'location') {\n listing.location = tagValues[0]\n } else if (tagName == 'price') {\n listing.price.amount = tagValues[0]\n listing.price.currency = tagValues[1]\n\n if (tagValues.length == 3) {\n listing.price.frequency = tagValues[2]\n }\n } else if (tagName == 'image') {\n listing.images.push({\n url: tagValues[0],\n dimensions: tagValues?.[1] ?? undefined,\n })\n } else if (tagName == 't') {\n listing.hashtags.push(tagValues[0])\n } else if (tagName == 'e' || tagName == 'a') {\n listing.additionalTags[tagName] = [...tagValues]\n }\n }\n\n return listing\n}\n\n/**\n * Generates an event template based on a classified listing object.\n *\n * @param listing - The classified listing object.\n * @returns The event template.\n */\nexport function generateEventTemplate(listing: ClassifiedListingObject): EventTemplate {\n const priceTag = ['price', listing.price.amount, listing.price.currency]\n if (listing.price.frequency) priceTag.push(listing.price.frequency)\n\n const tags: string[][] = [\n ['d', listing.title.trim().toLowerCase().replace(/ /g, '-')],\n ['title', listing.title],\n ['published_at', listing.publishedAt],\n ['summary', listing.summary],\n ['location', listing.location],\n priceTag,\n ]\n\n for (let i = 0; i < listing.images.length; i++) {\n const image = listing.images[i]\n const imageTag = ['image', image.url]\n if (image.dimensions) imageTag.push(image.dimensions)\n\n tags.push(imageTag)\n }\n\n for (let i = 0; i < listing.hashtags.length; i++) {\n const t = listing.hashtags[i]\n\n tags.push(['t', t])\n }\n\n for (const [key, value] of Object.entries(listing.additionalTags)) {\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n const val = value[i]\n\n tags.push([key, val])\n }\n } else {\n tags.push([key, value])\n }\n }\n\n return {\n kind: listing.isDraft ? DraftClassifiedListing : ClassifiedListing,\n content: listing.content,\n tags,\n created_at: Math.floor(Date.now() / 1000),\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC+KO,IAAM,oBAAoB;AAE1B,IAAM,yBAAyB;;;ADhG/B,SAAS,cAAc,OAAuB;AACnD,MAAI,CAAC,CAAC,mBAAmB,sBAAsB,EA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AA,IAC3B,CAAC,YAAY,QAAQ,QAAQ;AAAA,IAC7B;AAAA,EACF;AAEA,WAAS,IAAI,GAAG,IAAI,QAAQ,OAAO,QAAQ,KAAK;AAC9C,UAAM,QAAQ,QAAQ,OAAO;AAC7B,UAAM,WAAW,CAAC,SAAS,MAAM,GAAG;AACpC,QAAI,MAAM;AAAY,eAAS,KAAK,MAAM,UAAU;AAEpD,SAAK,KAAK,QAAQ;AAAA,EACpB;AAEA,WAAS,IAAI,GAAG,IAAI,QAAQ,SAAS,QAAQ,KAAK;AAChD,UAAM,IAAI,QAAQ,SAAS;AAE3B,SAAK,KAAK,CAAC,KAAK,CAAC,CAAC;AAAA,EACpB;AAEA,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,QAAQ,cAAc,GAAG;AACjE,QAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,eAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,cAAM,MAAM,MAAM;AAElB,aAAK,KAAK,CAAC,KAAK,GAAG,CAAC;AAAA,MACtB;AAAA,IACF,OAAO;AACL,WAAK,KAAK,CAAC,KAAK,KAAK,CAAC;AAAA,IACxB;AAAA,EACF;AAEA,SAAO;AAAA,IACL,MAAM,QAAQ,UAAU,yBAAyB;AAAA,IACjD,SAAS,QAAQ;AAAA,IACjB;AAAA,IACA,YAAY,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAAA,EAC1C;AACF;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/cjs/nipb7.js b/node_modules/nostr-tools/lib/cjs/nipb7.js new file mode 100644 index 0000000..b813949 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nipb7.js @@ -0,0 +1,184 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// nipb7.ts +var nipb7_exports = {}; +__export(nipb7_exports, { + BlossomClient: () => BlossomClient +}); +module.exports = __toCommonJS(nipb7_exports); +var import_sha256 = require("@noble/hashes/sha256"); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// nipb7.ts +var BlossomClient = class { + mediaserver; + signer; + constructor(mediaserver, signer) { + if (!mediaserver.startsWith("http")) { + mediaserver = "https://" + mediaserver; + } + this.mediaserver = mediaserver.replace(/\/$/, "") + "/"; + this.signer = signer; + } + async httpCall(method, url, contentType, addAuthorization, body, result) { + const headers = {}; + if (contentType) { + headers["Content-Type"] = contentType; + } + if (addAuthorization) { + const auth = await addAuthorization(); + if (auth) { + headers["Authorization"] = auth; + } + } + const response = await fetch(this.mediaserver + url, { + method, + headers, + body + }); + if (response.status >= 300) { + const reason = response.headers.get("X-Reason") || response.statusText; + throw new Error(`${url} returned an error (${response.status}): ${reason}`); + } + if (result !== null && response.headers.get("content-type")?.includes("application/json")) { + return await response.json(); + } + return response; + } + async authorizationHeader(modify) { + const now = Math.floor(Date.now() / 1e3); + const event = { + created_at: now, + kind: 24242, + content: "blossom stuff", + tags: [["expiration", String(now + 60)]] + }; + if (modify) { + modify(event); + } + try { + const signedEvent = await this.signer.signEvent(event); + const eventJson = JSON.stringify(signedEvent); + return "Nostr " + btoa(eventJson); + } catch (error) { + return ""; + } + } + isValid32ByteHex(hash) { + return /^[a-f0-9]{64}$/i.test(hash); + } + async check(hash) { + if (!this.isValid32ByteHex(hash)) { + throw new Error(`${hash} is not a valid 32-byte hex string`); + } + try { + await this.httpCall("HEAD", hash); + } catch (error) { + throw new Error(`failed to check for ${hash}: ${error}`); + } + } + async uploadBlob(file, contentType) { + const hash = (0, import_utils.bytesToHex)((0, import_sha256.sha256)(new Uint8Array(await file.arrayBuffer()))); + const actualContentType = contentType || file.type || "application/octet-stream"; + const bd = await this.httpCall( + "PUT", + "upload", + actualContentType, + () => this.authorizationHeader((evt) => { + evt.tags.push(["t", "upload"]); + evt.tags.push(["x", hash]); + }), + file, + {} + ); + return bd; + } + async uploadFile(file) { + return this.uploadBlob(file, file.type); + } + async download(hash) { + if (!this.isValid32ByteHex(hash)) { + throw new Error(`${hash} is not a valid 32-byte hex string`); + } + const authHeader = await this.authorizationHeader((evt) => { + evt.tags.push(["t", "get"]); + evt.tags.push(["x", hash]); + }); + const response = await fetch(this.mediaserver + hash, { + method: "GET", + headers: { + Authorization: authHeader + } + }); + if (response.status >= 300) { + throw new Error(`${hash} is not present in ${this.mediaserver}: ${response.status}`); + } + return await response.arrayBuffer(); + } + async downloadAsBlob(hash) { + const arrayBuffer = await this.download(hash); + return new Blob([arrayBuffer]); + } + async list() { + const pubkey = await this.signer.getPublicKey(); + if (!this.isValid32ByteHex(pubkey)) { + throw new Error(`pubkey ${pubkey} is not valid`); + } + try { + const bds = await this.httpCall( + "GET", + `list/${pubkey}`, + void 0, + () => this.authorizationHeader((evt) => { + evt.tags.push(["t", "list"]); + }), + void 0, + [] + ); + return bds; + } catch (error) { + throw new Error(`failed to list blobs: ${error}`); + } + } + async delete(hash) { + if (!this.isValid32ByteHex(hash)) { + throw new Error(`${hash} is not a valid 32-byte hex string`); + } + try { + await this.httpCall( + "DELETE", + hash, + void 0, + () => this.authorizationHeader((evt) => { + evt.tags.push(["t", "delete"]); + evt.tags.push(["x", hash]); + }), + void 0, + null + ); + } catch (error) { + throw new Error(`failed to delete ${hash}: ${error}`); + } + } +}; diff --git a/node_modules/nostr-tools/lib/cjs/nipb7.js.map b/node_modules/nostr-tools/lib/cjs/nipb7.js.map new file mode 100644 index 0000000..58aeb3d --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/nipb7.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nipb7.ts", "../../utils.ts"], + "sourcesContent": ["import { sha256 } from '@noble/hashes/sha256'\nimport { EventTemplate } from './core.ts'\nimport { Signer } from './signer.ts'\nimport { bytesToHex } from './utils.ts'\n\nexport type BlobDescriptor = {\n url: string\n sha256: string\n size: number\n type: string\n uploaded: number\n}\n\nexport class BlossomClient {\n private mediaserver: string\n private signer: Signer\n\n constructor(mediaserver: string, signer: Signer) {\n if (!mediaserver.startsWith('http')) {\n mediaserver = 'https://' + mediaserver\n }\n this.mediaserver = mediaserver.replace(/\\/$/, '') + '/'\n this.signer = signer\n }\n\n private async httpCall(\n method: string,\n url: string,\n contentType?: string,\n addAuthorization?: () => Promise,\n body?: File | Blob,\n result?: any,\n ): Promise {\n const headers: { [_: string]: string } = {}\n\n if (contentType) {\n headers['Content-Type'] = contentType\n }\n\n if (addAuthorization) {\n const auth = await addAuthorization()\n if (auth) {\n headers['Authorization'] = auth\n }\n }\n\n const response = await fetch(this.mediaserver + url, {\n method,\n headers,\n body,\n })\n\n if (response.status >= 300) {\n const reason = response.headers.get('X-Reason') || response.statusText\n throw new Error(`${url} returned an error (${response.status}): ${reason}`)\n }\n\n if (result !== null && response.headers.get('content-type')?.includes('application/json')) {\n return await response.json()\n }\n\n return response\n }\n\n private async authorizationHeader(modify?: (event: EventTemplate) => void): Promise {\n const now = Math.floor(Date.now() / 1000)\n const event: EventTemplate = {\n created_at: now,\n kind: 24242,\n content: 'blossom stuff',\n tags: [['expiration', String(now + 60)]],\n }\n\n if (modify) {\n modify(event)\n }\n\n try {\n const signedEvent = await this.signer.signEvent(event)\n const eventJson = JSON.stringify(signedEvent)\n return 'Nostr ' + btoa(eventJson)\n } catch (error) {\n return ''\n }\n }\n\n private isValid32ByteHex(hash: string): boolean {\n return /^[a-f0-9]{64}$/i.test(hash)\n }\n\n async check(hash: string): Promise {\n if (!this.isValid32ByteHex(hash)) {\n throw new Error(`${hash} is not a valid 32-byte hex string`)\n }\n\n try {\n await this.httpCall('HEAD', hash)\n } catch (error) {\n throw new Error(`failed to check for ${hash}: ${error}`)\n }\n }\n\n async uploadBlob(file: File | Blob, contentType?: string): Promise {\n const hash = bytesToHex(sha256(new Uint8Array(await file.arrayBuffer())))\n const actualContentType = contentType || file.type || 'application/octet-stream'\n\n const bd = await this.httpCall(\n 'PUT',\n 'upload',\n actualContentType,\n () =>\n this.authorizationHeader(evt => {\n evt.tags.push(['t', 'upload'])\n evt.tags.push(['x', hash])\n }),\n file,\n {},\n )\n\n return bd\n }\n\n async uploadFile(file: File): Promise {\n return this.uploadBlob(file, file.type)\n }\n\n async download(hash: string): Promise {\n if (!this.isValid32ByteHex(hash)) {\n throw new Error(`${hash} is not a valid 32-byte hex string`)\n }\n\n const authHeader = await this.authorizationHeader(evt => {\n evt.tags.push(['t', 'get'])\n evt.tags.push(['x', hash])\n })\n\n const response = await fetch(this.mediaserver + hash, {\n method: 'GET',\n headers: {\n Authorization: authHeader,\n },\n })\n\n if (response.status >= 300) {\n throw new Error(`${hash} is not present in ${this.mediaserver}: ${response.status}`)\n }\n\n return await response.arrayBuffer()\n }\n\n async downloadAsBlob(hash: string): Promise {\n const arrayBuffer = await this.download(hash)\n return new Blob([arrayBuffer])\n }\n\n async list(): Promise {\n const pubkey = await this.signer.getPublicKey()\n\n if (!this.isValid32ByteHex(pubkey)) {\n throw new Error(`pubkey ${pubkey} is not valid`)\n }\n\n try {\n const bds = await this.httpCall(\n 'GET',\n `list/${pubkey}`,\n undefined,\n () =>\n this.authorizationHeader(evt => {\n evt.tags.push(['t', 'list'])\n }),\n undefined,\n [],\n )\n return bds\n } catch (error) {\n throw new Error(`failed to list blobs: ${error}`)\n }\n }\n\n async delete(hash: string): Promise {\n if (!this.isValid32ByteHex(hash)) {\n throw new Error(`${hash} is not a valid 32-byte hex string`)\n }\n\n try {\n await this.httpCall(\n 'DELETE',\n hash,\n undefined,\n () =>\n this.authorizationHeader(evt => {\n evt.tags.push(['t', 'delete'])\n evt.tags.push(['x', hash])\n }),\n undefined,\n null,\n )\n } catch (error) {\n throw new Error(`failed to delete ${hash}: ${error}`)\n }\n }\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAuB;;;ACKvB,mBAAuC;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;;;ADUjD,IAAM,gBAAN,MAAoB;AAAA,EACjB;AAAA,EACA;AAAA,EAER,YAAY,aAAqB,QAAgB;AAC/C,QAAI,CAAC,YAAY,WAAW,MAAM,GAAG;AACnC,oBAAc,aAAa;AAAA,IAC7B;AACA,SAAK,cAAc,YAAY,QAAQ,OAAO,EAAE,IAAI;AACpD,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,MAAc,SACZ,QACA,KACA,aACA,kBACA,MACA,QACc;AACd,UAAM,UAAmC,CAAC;AAE1C,QAAI,aAAa;AACf,cAAQ,kBAAkB;AAAA,IAC5B;AAEA,QAAI,kBAAkB;AACpB,YAAM,OAAO,MAAM,iBAAiB;AACpC,UAAI,MAAM;AACR,gBAAQ,mBAAmB;AAAA,MAC7B;AAAA,IACF;AAEA,UAAM,WAAW,MAAM,MAA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O,aAAa;AAE9C,QAAI,CAAC,KAAK,iBAAiB,MAAM,GAAG;AAClC,YAAM,IAAI,MAAM,UAAU,qBAAqB;AAAA,IACjD;AAEA,QAAI;AACF,YAAM,MAAM,MAAM,KAAK;AAAA,QACrB;AAAA,QACA,QAAQ;AAAA,QACR;AAAA,QACA,MACE,KAAK,oBAAoB,SAAO;AAC9B,cAAI,KAAK,KAAK,CAAC,KAAK,MAAM,CAAC;AAAA,QAC7B,CAAC;AAAA,QACH;AAAA,QACA,CAAC;AAAA,MACH;AACA,aAAO;AAAA,IACT,SAAS,OAAP;AACA,YAAM,IAAI,MAAM,yBAAyB,OAAO;AAAA,IAClD;AAAA,EACF;AAAA,EAEA,MAAM,OAAO,MAA6B;AACxC,QAAI,CAAC,KAAK,iBAAiB,IAAI,GAAG;AAChC,YAAM,IAAI,MAAM,GAAG,wCAAwC;AAAA,IAC7D;AAEA,QAAI;AACF,YAAM,KAAK;AAAA,QACT;AAAA,QACA;AAAA,QACA;AAAA,QACA,MACE,KAAK,oBAAoB,SAAO;AAC9B,cAAI,KAAK,KAAK,CAAC,KAAK,QAAQ,CAAC;AAC7B,cAAI,KAAK,KAAK,CAAC,KAAK,IAAI,CAAC;AAAA,QAC3B,CAAC;AAAA,QACH;AAAA,QACA;AAAA,MACF;AAAA,IACF,SAAS,OAAP;AACA,YAAM,IAAI,MAAM,oBAAoB,SAAS,OAAO;AAAA,IACtD;AAAA,EACF;AACF;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/cjs/package.json b/node_modules/nostr-tools/lib/cjs/package.json new file mode 100644 index 0000000..0292b99 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/package.json @@ -0,0 +1 @@ +{"type":"commonjs"} \ No newline at end of file diff --git a/node_modules/nostr-tools/lib/cjs/pool.js b/node_modules/nostr-tools/lib/cjs/pool.js new file mode 100644 index 0000000..1cb1b6f --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/pool.js @@ -0,0 +1,893 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pool.ts +var pool_exports = {}; +__export(pool_exports, { + AbstractSimplePool: () => AbstractSimplePool, + SimplePool: () => SimplePool, + useWebSocketImplementation: () => useWebSocketImplementation +}); +module.exports = __toCommonJS(pool_exports); + +// pure.ts +var import_secp256k1 = require("@noble/curves/secp256k1"); +var import_utils2 = require("@noble/hashes/utils"); + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +var import_sha256 = require("@noble/hashes/sha256"); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); +function normalizeURL(url) { + try { + if (url.indexOf("://") === -1) + url = "wss://" + url; + let p = new URL(url); + p.pathname = p.pathname.replace(/\/+/g, "/"); + if (p.pathname.endsWith("/")) + p.pathname = p.pathname.slice(0, -1); + if (p.port === "80" && p.protocol === "ws:" || p.port === "443" && p.protocol === "wss:") + p.port = ""; + p.searchParams.sort(); + p.hash = ""; + return p.toString(); + } catch (e) { + throw new Error(`Invalid URL: ${url}`); + } +} +var QueueNode = class { + value; + next = null; + prev = null; + constructor(message) { + this.value = message; + } +}; +var Queue = class { + first; + last; + constructor() { + this.first = null; + this.last = null; + } + enqueue(value) { + const newNode = new QueueNode(value); + if (!this.last) { + this.first = newNode; + this.last = newNode; + } else if (this.last === this.first) { + this.last = newNode; + this.last.prev = this.first; + this.first.next = newNode; + } else { + newNode.prev = this.last; + this.last.next = newNode; + this.last = newNode; + } + return true; + } + dequeue() { + if (!this.first) + return null; + if (this.first === this.last) { + const target2 = this.first; + this.first = null; + this.last = null; + return target2.value; + } + const target = this.first; + this.first = target.next; + if (this.first) { + this.first.prev = null; + } + return target.value; + } +}; + +// pure.ts +var JS = class { + generateSecretKey() { + return import_secp256k1.schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = import_secp256k1.schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = (0, import_sha256.sha256)(utf8Encoder.encode(serializeEvent(event))); + return (0, import_utils2.bytesToHex)(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// kinds.ts +var ClientAuth = 22242; + +// filter.ts +function matchFilter(filter, event) { + if (filter.ids && filter.ids.indexOf(event.id) === -1) { + return false; + } + if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) { + return false; + } + if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) { + return false; + } + for (let f in filter) { + if (f[0] === "#") { + let tagName = f.slice(1); + let values = filter[`#${tagName}`]; + if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values.indexOf(v) !== -1)) + return false; + } + } + if (filter.since && event.created_at < filter.since) + return false; + if (filter.until && event.created_at > filter.until) + return false; + return true; +} +function matchFilters(filters, event) { + for (let i2 = 0; i2 < filters.length; i2++) { + if (matchFilter(filters[i2], event)) { + return true; + } + } + return false; +} + +// fakejson.ts +function getHex64(json, field) { + let len = field.length + 3; + let idx = json.indexOf(`"${field}":`) + len; + let s = json.slice(idx).indexOf(`"`) + idx + 1; + return json.slice(s, s + 64); +} +function getSubscriptionId(json) { + let idx = json.slice(0, 22).indexOf(`"EVENT"`); + if (idx === -1) + return null; + let pstart = json.slice(idx + 7 + 1).indexOf(`"`); + if (pstart === -1) + return null; + let start = idx + 7 + 1 + pstart; + let pend = json.slice(start + 1, 80).indexOf(`"`); + if (pend === -1) + return null; + let end = start + 1 + pend; + return json.slice(start + 1, end); +} + +// nip42.ts +function makeAuthEvent(relayURL, challenge) { + return { + kind: ClientAuth, + created_at: Math.floor(Date.now() / 1e3), + tags: [ + ["relay", relayURL], + ["challenge", challenge] + ], + content: "" + }; +} + +// helpers.ts +async function yieldThread() { + return new Promise((resolve) => { + const ch = new MessageChannel(); + const handler = () => { + ch.port1.removeEventListener("message", handler); + resolve(); + }; + ch.port1.addEventListener("message", handler); + ch.port2.postMessage(0); + ch.port1.start(); + }); +} +var alwaysTrue = (t) => { + t[verifiedSymbol] = true; + return true; +}; + +// abstract-relay.ts +var SendingOnClosedConnection = class extends Error { + constructor(message, relay) { + super(`Tried to send message '${message} on a closed connection to ${relay}.`); + this.name = "SendingOnClosedConnection"; + } +}; +var AbstractRelay = class { + url; + _connected = false; + onclose = null; + onnotice = (msg) => console.debug(`NOTICE from ${this.url}: ${msg}`); + baseEoseTimeout = 4400; + connectionTimeout = 4400; + publishTimeout = 4400; + pingFrequency = 2e4; + pingTimeout = 2e4; + openSubs = /* @__PURE__ */ new Map(); + enablePing; + connectionTimeoutHandle; + connectionPromise; + openCountRequests = /* @__PURE__ */ new Map(); + openEventPublishes = /* @__PURE__ */ new Map(); + ws; + incomingMessageQueue = new Queue(); + queueRunning = false; + challenge; + authPromise; + serial = 0; + verifyEvent; + _WebSocket; + constructor(url, opts) { + this.url = normalizeURL(url); + this.verifyEvent = opts.verifyEvent; + this._WebSocket = opts.websocketImplementation || WebSocket; + this.enablePing = opts.enablePing; + } + static async connect(url, opts) { + const relay = new AbstractRelay(url, opts); + await relay.connect(); + return relay; + } + closeAllSubscriptions(reason) { + for (let [_, sub] of this.openSubs) { + sub.close(reason); + } + this.openSubs.clear(); + for (let [_, ep] of this.openEventPublishes) { + ep.reject(new Error(reason)); + } + this.openEventPublishes.clear(); + for (let [_, cr] of this.openCountRequests) { + cr.reject(new Error(reason)); + } + this.openCountRequests.clear(); + } + get connected() { + return this._connected; + } + async connect() { + if (this.connectionPromise) + return this.connectionPromise; + this.challenge = void 0; + this.authPromise = void 0; + this.connectionPromise = new Promise((resolve, reject) => { + this.connectionTimeoutHandle = setTimeout(() => { + reject("connection timed out"); + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection timed out"); + }, this.connectionTimeout); + try { + this.ws = new this._WebSocket(this.url); + } catch (err) { + clearTimeout(this.connectionTimeoutHandle); + reject(err); + return; + } + this.ws.onopen = () => { + clearTimeout(this.connectionTimeoutHandle); + this._connected = true; + if (this.enablePing) { + this.pingpong(); + } + resolve(); + }; + this.ws.onerror = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket error"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection errored"); + } + }; + this.ws.onclose = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket closed"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection closed"); + } + }; + this.ws.onmessage = this._onmessage.bind(this); + }); + return this.connectionPromise; + } + async waitForPingPong() { + return new Promise((res, err) => { + ; + this.ws && this.ws.on && this.ws.on("pong", () => res(true)) || err("ws can't listen for pong"); + this.ws && this.ws.ping && this.ws.ping(); + }); + } + async waitForDummyReq() { + return new Promise((resolve, _) => { + const sub = this.subscribe([{ ids: ["a".repeat(64)] }], { + oneose: () => { + sub.close(); + resolve(true); + }, + eoseTimeout: this.pingTimeout + 1e3 + }); + }); + } + async pingpong() { + if (this.ws?.readyState === 1) { + const result = await Promise.any([ + this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(), + new Promise((res) => setTimeout(() => res(false), this.pingTimeout)) + ]); + if (result) { + setTimeout(() => this.pingpong(), this.pingFrequency); + } else { + this.closeAllSubscriptions("pingpong timed out"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + } + } + async runQueue() { + this.queueRunning = true; + while (true) { + if (false === this.handleNext()) { + break; + } + await yieldThread(); + } + this.queueRunning = false; + } + handleNext() { + const json = this.incomingMessageQueue.dequeue(); + if (!json) { + return false; + } + const subid = getSubscriptionId(json); + if (subid) { + const so = this.openSubs.get(subid); + if (!so) { + return; + } + const id = getHex64(json, "id"); + const alreadyHave = so.alreadyHaveEvent?.(id); + so.receivedEvent?.(this, id); + if (alreadyHave) { + return; + } + } + try { + let data = JSON.parse(json); + switch (data[0]) { + case "EVENT": { + const so = this.openSubs.get(data[1]); + const event = data[2]; + if (this.verifyEvent(event) && matchFilters(so.filters, event)) { + so.onevent(event); + } + return; + } + case "COUNT": { + const id = data[1]; + const payload = data[2]; + const cr = this.openCountRequests.get(id); + if (cr) { + cr.resolve(payload.count); + this.openCountRequests.delete(id); + } + return; + } + case "EOSE": { + const so = this.openSubs.get(data[1]); + if (!so) + return; + so.receivedEose(); + return; + } + case "OK": { + const id = data[1]; + const ok = data[2]; + const reason = data[3]; + const ep = this.openEventPublishes.get(id); + if (ep) { + clearTimeout(ep.timeout); + if (ok) + ep.resolve(reason); + else + ep.reject(new Error(reason)); + this.openEventPublishes.delete(id); + } + return; + } + case "CLOSED": { + const id = data[1]; + const so = this.openSubs.get(id); + if (!so) + return; + so.closed = true; + so.close(data[2]); + return; + } + case "NOTICE": + this.onnotice(data[1]); + return; + case "AUTH": { + this.challenge = data[1]; + return; + } + } + } catch (err) { + return; + } + } + async send(message) { + if (!this.connectionPromise) + throw new SendingOnClosedConnection(message, this.url); + this.connectionPromise.then(() => { + this.ws?.send(message); + }); + } + async auth(signAuthEvent) { + const challenge = this.challenge; + if (!challenge) + throw new Error("can't perform auth, no challenge was received"); + if (this.authPromise) + return this.authPromise; + this.authPromise = new Promise(async (resolve, reject) => { + try { + let evt = await signAuthEvent(makeAuthEvent(this.url, challenge)); + let timeout = setTimeout(() => { + let ep = this.openEventPublishes.get(evt.id); + if (ep) { + ep.reject(new Error("auth timed out")); + this.openEventPublishes.delete(evt.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(evt.id, { resolve, reject, timeout }); + this.send('["AUTH",' + JSON.stringify(evt) + "]"); + } catch (err) { + console.warn("subscribe auth function failed:", err); + } + }); + return this.authPromise; + } + async publish(event) { + const ret = new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + const ep = this.openEventPublishes.get(event.id); + if (ep) { + ep.reject(new Error("publish timed out")); + this.openEventPublishes.delete(event.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(event.id, { resolve, reject, timeout }); + }); + this.send('["EVENT",' + JSON.stringify(event) + "]"); + return ret; + } + async count(filters, params) { + this.serial++; + const id = params?.id || "count:" + this.serial; + const ret = new Promise((resolve, reject) => { + this.openCountRequests.set(id, { resolve, reject }); + }); + this.send('["COUNT","' + id + '",' + JSON.stringify(filters).substring(1)); + return ret; + } + subscribe(filters, params) { + const subscription = this.prepareSubscription(filters, params); + subscription.fire(); + return subscription; + } + prepareSubscription(filters, params) { + this.serial++; + const id = params.id || (params.label ? params.label + ":" : "sub:") + this.serial; + const subscription = new Subscription(this, id, filters, params); + this.openSubs.set(id, subscription); + return subscription; + } + close() { + this.closeAllSubscriptions("relay connection closed by us"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + _onmessage(ev) { + this.incomingMessageQueue.enqueue(ev.data); + if (!this.queueRunning) { + this.runQueue(); + } + } +}; +var Subscription = class { + relay; + id; + closed = false; + eosed = false; + filters; + alreadyHaveEvent; + receivedEvent; + onevent; + oneose; + onclose; + eoseTimeout; + eoseTimeoutHandle; + constructor(relay, id, filters, params) { + this.relay = relay; + this.filters = filters; + this.id = id; + this.alreadyHaveEvent = params.alreadyHaveEvent; + this.receivedEvent = params.receivedEvent; + this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout; + this.oneose = params.oneose; + this.onclose = params.onclose; + this.onevent = params.onevent || ((event) => { + console.warn( + `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`, + event + ); + }); + } + fire() { + this.relay.send('["REQ","' + this.id + '",' + JSON.stringify(this.filters).substring(1)); + this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout); + } + receivedEose() { + if (this.eosed) + return; + clearTimeout(this.eoseTimeoutHandle); + this.eosed = true; + this.oneose?.(); + } + close(reason = "closed by caller") { + if (!this.closed && this.relay.connected) { + try { + this.relay.send('["CLOSE",' + JSON.stringify(this.id) + "]"); + } catch (err) { + if (err instanceof SendingOnClosedConnection) { + } else { + throw err; + } + } + this.closed = true; + } + this.relay.openSubs.delete(this.id); + this.onclose?.(reason); + } +}; + +// abstract-pool.ts +var AbstractSimplePool = class { + relays = /* @__PURE__ */ new Map(); + seenOn = /* @__PURE__ */ new Map(); + trackRelays = false; + verifyEvent; + enablePing; + trustedRelayURLs = /* @__PURE__ */ new Set(); + _WebSocket; + constructor(opts) { + this.verifyEvent = opts.verifyEvent; + this._WebSocket = opts.websocketImplementation; + this.enablePing = opts.enablePing; + } + async ensureRelay(url, params) { + url = normalizeURL(url); + let relay = this.relays.get(url); + if (!relay) { + relay = new AbstractRelay(url, { + verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent, + websocketImplementation: this._WebSocket, + enablePing: this.enablePing + }); + relay.onclose = () => { + this.relays.delete(url); + }; + if (params?.connectionTimeout) + relay.connectionTimeout = params.connectionTimeout; + this.relays.set(url, relay); + } + await relay.connect(); + return relay; + } + close(relays) { + relays.map(normalizeURL).forEach((url) => { + this.relays.get(url)?.close(); + this.relays.delete(url); + }); + } + subscribe(relays, filter, params) { + params.onauth = params.onauth || params.doauth; + const request = []; + for (let i2 = 0; i2 < relays.length; i2++) { + const url = normalizeURL(relays[i2]); + if (!request.find((r) => r.url === url)) { + request.push({ url, filter }); + } + } + return this.subscribeMap(request, params); + } + subscribeMany(relays, filters, params) { + params.onauth = params.onauth || params.doauth; + const request = []; + const uniqUrls = []; + for (let i2 = 0; i2 < relays.length; i2++) { + const url = normalizeURL(relays[i2]); + if (uniqUrls.indexOf(url) === -1) { + for (let f = 0; f < filters.length; f++) { + request.push({ url, filter: filters[f] }); + } + } + } + return this.subscribeMap(request, params); + } + subscribeMap(requests, params) { + params.onauth = params.onauth || params.doauth; + if (this.trackRelays) { + params.receivedEvent = (relay, id) => { + let set = this.seenOn.get(id); + if (!set) { + set = /* @__PURE__ */ new Set(); + this.seenOn.set(id, set); + } + set.add(relay); + }; + } + const _knownIds = /* @__PURE__ */ new Set(); + const subs = []; + const eosesReceived = []; + let handleEose = (i2) => { + if (eosesReceived[i2]) + return; + eosesReceived[i2] = true; + if (eosesReceived.filter((a) => a).length === requests.length) { + params.oneose?.(); + handleEose = () => { + }; + } + }; + const closesReceived = []; + let handleClose = (i2, reason) => { + if (closesReceived[i2]) + return; + handleEose(i2); + closesReceived[i2] = reason; + if (closesReceived.filter((a) => a).length === requests.length) { + params.onclose?.(closesReceived); + handleClose = () => { + }; + } + }; + const localAlreadyHaveEventHandler = (id) => { + if (params.alreadyHaveEvent?.(id)) { + return true; + } + const have = _knownIds.has(id); + _knownIds.add(id); + return have; + }; + const allOpened = Promise.all( + requests.map(async ({ url, filter }, i2) => { + let relay; + try { + relay = await this.ensureRelay(url, { + connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1e3) : void 0 + }); + } catch (err) { + handleClose(i2, err?.message || String(err)); + return; + } + let subscription = relay.subscribe([filter], { + ...params, + oneose: () => handleEose(i2), + onclose: (reason) => { + if (reason.startsWith("auth-required: ") && params.onauth) { + relay.auth(params.onauth).then(() => { + relay.subscribe([filter], { + ...params, + oneose: () => handleEose(i2), + onclose: (reason2) => { + handleClose(i2, reason2); + }, + alreadyHaveEvent: localAlreadyHaveEventHandler, + eoseTimeout: params.maxWait + }); + }).catch((err) => { + handleClose(i2, `auth was required and attempted, but failed with: ${err}`); + }); + } else { + handleClose(i2, reason); + } + }, + alreadyHaveEvent: localAlreadyHaveEventHandler, + eoseTimeout: params.maxWait + }); + subs.push(subscription); + }) + ); + return { + async close(reason) { + await allOpened; + subs.forEach((sub) => { + sub.close(reason); + }); + } + }; + } + subscribeEose(relays, filter, params) { + params.onauth = params.onauth || params.doauth; + const subcloser = this.subscribe(relays, filter, { + ...params, + oneose() { + subcloser.close("closed automatically on eose"); + } + }); + return subcloser; + } + subscribeManyEose(relays, filters, params) { + params.onauth = params.onauth || params.doauth; + const subcloser = this.subscribeMany(relays, filters, { + ...params, + oneose() { + subcloser.close("closed automatically on eose"); + } + }); + return subcloser; + } + async querySync(relays, filter, params) { + return new Promise(async (resolve) => { + const events = []; + this.subscribeEose(relays, filter, { + ...params, + onevent(event) { + events.push(event); + }, + onclose(_) { + resolve(events); + } + }); + }); + } + async get(relays, filter, params) { + filter.limit = 1; + const events = await this.querySync(relays, filter, params); + events.sort((a, b) => b.created_at - a.created_at); + return events[0] || null; + } + publish(relays, event, options) { + return relays.map(normalizeURL).map(async (url, i2, arr) => { + if (arr.indexOf(url) !== i2) { + return Promise.reject("duplicate url"); + } + let r = await this.ensureRelay(url); + return r.publish(event).catch(async (err) => { + if (err instanceof Error && err.message.startsWith("auth-required: ") && options?.onauth) { + await r.auth(options.onauth); + return r.publish(event); + } + throw err; + }).then((reason) => { + if (this.trackRelays) { + let set = this.seenOn.get(event.id); + if (!set) { + set = /* @__PURE__ */ new Set(); + this.seenOn.set(event.id, set); + } + set.add(r); + } + return reason; + }); + }); + } + listConnectionStatus() { + const map = /* @__PURE__ */ new Map(); + this.relays.forEach((relay, url) => map.set(url, relay.connected)); + return map; + } + destroy() { + this.relays.forEach((conn) => conn.close()); + this.relays = /* @__PURE__ */ new Map(); + } +}; + +// pool.ts +var _WebSocket; +try { + _WebSocket = WebSocket; +} catch { +} +function useWebSocketImplementation(websocketImplementation) { + _WebSocket = websocketImplementation; +} +var SimplePool = class extends AbstractSimplePool { + constructor(options) { + super({ verifyEvent, websocketImplementation: _WebSocket, ...options }); + } +}; diff --git a/node_modules/nostr-tools/lib/cjs/pool.js.map b/node_modules/nostr-tools/lib/cjs/pool.js.map new file mode 100644 index 0000000..2a48125 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/pool.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../pool.ts", "../../pure.ts", "../../core.ts", "../../utils.ts", "../../kinds.ts", "../../filter.ts", "../../fakejson.ts", "../../nip42.ts", "../../helpers.ts", "../../abstract-relay.ts", "../../abstract-pool.ts"], + "sourcesContent": ["/* global WebSocket */\n\nimport { verifyEvent } from './pure.ts'\nimport { AbstractSimplePool } from './abstract-pool.ts'\n\nvar _WebSocket: typeof WebSocket\n\ntry {\n _WebSocket = WebSocket\n} catch {}\n\nexport function useWebSocketImplementation(websocketImplementation: any) {\n _WebSocket = websocketImplementation\n}\n\nexport class SimplePool extends AbstractSimplePool {\n constructor(options?: { enablePing?: boolean }) {\n super({ verifyEvent, websocketImplementation: _WebSocket, ...options })\n }\n}\n\nexport * from './abstract-pool.ts'\n", "import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { Event } from './core.ts'\nimport { isAddressableKind, isReplaceableKind } from './kinds.ts'\n\nexport type Filter = {\n ids?: string[]\n kinds?: number[]\n authors?: string[]\n since?: number\n until?: number\n limit?: number\n search?: string\n [key: `#${string}`]: string[] | undefined\n}\n\nexport function matchFilter(filter: Filter, event: Event): boolean {\n if (filter.ids && filter.ids.indexOf(event.id) === -1) {\n return false\n }\n if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) {\n return false\n }\n if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) {\n return false\n }\n\n for (let f in filter) {\n if (f[0] === '#') {\n let tagName = f.slice(1)\n let values = filter[`#${tagName}`]\n if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values!.indexOf(v) !== -1)) return false\n }\n }\n\n if (filter.since && event.created_at < filter.since) return false\n if (filter.until && event.created_at > filter.until) return false\n\n return true\n}\n\nexport function matchFilters(filters: Filter[], event: Event): boolean {\n for (let i = 0; i < filters.length; i++) {\n if (matchFilter(filters[i], event)) {\n return true\n }\n }\n return false\n}\n\nexport function mergeFilters(...filters: Filter[]): Filter {\n let result: Filter = {}\n for (let i = 0; i < filters.length; i++) {\n let filter = filters[i]\n Object.entries(filter).forEach(([property, values]) => {\n if (property === 'kinds' || property === 'ids' || property === 'authors' || property[0] === '#') {\n // @ts-ignore\n result[property] = result[property] || []\n // @ts-ignore\n for (let v = 0; v < values.length; v++) {\n // @ts-ignore\n let value = values[v]\n // @ts-ignore\n if (!result[property].includes(value)) result[property].push(value)\n }\n }\n })\n\n if (filter.limit && (!result.limit || filter.limit > result.limit)) result.limit = filter.limit\n if (filter.until && (!result.until || filter.until > result.until)) result.until = filter.until\n if (filter.since && (!result.since || filter.since < result.since)) result.since = filter.since\n }\n\n return result\n}\n\n/**\n * Calculate the intrinsic limit of a filter.\n * This function returns a positive integer, or `Infinity` if there is no intrinsic limit.\n */\nexport function getFilterLimit(filter: Filter): number {\n if (filter.ids && !filter.ids.length) return 0\n if (filter.kinds && !filter.kinds.length) return 0\n if (filter.authors && !filter.authors.length) return 0\n\n for (const [key, value] of Object.entries(filter)) {\n if (key[0] === '#' && Array.isArray(value) && !value.length) return 0\n }\n\n return Math.min(\n // The `limit` property creates an artificial limit.\n Math.max(0, filter.limit ?? Infinity),\n\n // There can only be one event per `id`.\n filter.ids?.length ?? Infinity,\n\n // Replaceable events are limited by the number of authors and kinds.\n filter.authors?.length && filter.kinds?.every(kind => isReplaceableKind(kind))\n ? filter.authors.length * filter.kinds.length\n : Infinity,\n\n // Parameterized replaceable events are limited by the number of authors, kinds, and \"d\" tags.\n filter.authors?.length && filter.kinds?.every(kind => isAddressableKind(kind)) && filter['#d']?.length\n ? filter.authors.length * filter.kinds.length * filter['#d'].length\n : Infinity,\n )\n}\n", "export function getHex64(json: string, field: string): string {\n let len = field.length + 3\n let idx = json.indexOf(`\"${field}\":`) + len\n let s = json.slice(idx).indexOf(`\"`) + idx + 1\n return json.slice(s, s + 64)\n}\n\nexport function getInt(json: string, field: string): number {\n let len = field.length\n let idx = json.indexOf(`\"${field}\":`) + len + 3\n let sliced = json.slice(idx)\n let end = Math.min(sliced.indexOf(','), sliced.indexOf('}'))\n return parseInt(sliced.slice(0, end), 10)\n}\n\nexport function getSubscriptionId(json: string): string | null {\n let idx = json.slice(0, 22).indexOf(`\"EVENT\"`)\n if (idx === -1) return null\n\n let pstart = json.slice(idx + 7 + 1).indexOf(`\"`)\n if (pstart === -1) return null\n let start = idx + 7 + 1 + pstart\n\n let pend = json.slice(start + 1, 80).indexOf(`\"`)\n if (pend === -1) return null\n let end = start + 1 + pend\n\n return json.slice(start + 1, end)\n}\n\nexport function matchEventId(json: string, id: string): boolean {\n return id === getHex64(json, 'id')\n}\n\nexport function matchEventPubkey(json: string, pubkey: string): boolean {\n return pubkey === getHex64(json, 'pubkey')\n}\n\nexport function matchEventKind(json: string, kind: number): boolean {\n return kind === getInt(json, 'kind')\n}\n", "import { EventTemplate } from './core.ts'\nimport { ClientAuth } from './kinds.ts'\n\n/**\n * creates an EventTemplate for an AUTH event to be signed.\n */\nexport function makeAuthEvent(relayURL: string, challenge: string): EventTemplate {\n return {\n kind: ClientAuth,\n created_at: Math.floor(Date.now() / 1000),\n tags: [\n ['relay', relayURL],\n ['challenge', challenge],\n ],\n content: '',\n }\n}\n", "import { verifiedSymbol, type Event, type Nostr, VerifiedEvent } from './core.ts'\n\nexport async function yieldThread() {\n return new Promise(resolve => {\n const ch = new MessageChannel()\n const handler = () => {\n // @ts-ignore (typescript thinks this property should be called `removeListener`, but in fact it's `removeEventListener`)\n ch.port1.removeEventListener('message', handler)\n resolve()\n }\n // @ts-ignore (typescript thinks this property should be called `addListener`, but in fact it's `addEventListener`)\n ch.port1.addEventListener('message', handler)\n ch.port2.postMessage(0)\n ch.port1.start()\n })\n}\n\nexport const alwaysTrue: Nostr['verifyEvent'] = (t: Event): t is VerifiedEvent => {\n t[verifiedSymbol] = true\n return true\n}\n", "/* global WebSocket */\n\nimport type { Event, EventTemplate, VerifiedEvent, Nostr, NostrEvent } from './core.ts'\nimport { matchFilters, type Filter } from './filter.ts'\nimport { getHex64, getSubscriptionId } from './fakejson.ts'\nimport { Queue, normalizeURL } from './utils.ts'\nimport { makeAuthEvent } from './nip42.ts'\nimport { yieldThread } from './helpers.ts'\n\ntype RelayWebSocket = WebSocket & {\n ping?(): void\n on?(event: 'pong', listener: () => void): any\n}\n\nexport type AbstractRelayConstructorOptions = {\n verifyEvent: Nostr['verifyEvent']\n websocketImplementation?: typeof WebSocket\n enablePing?: boolean\n}\n\nexport class SendingOnClosedConnection extends Error {\n constructor(message: string, relay: string) {\n super(`Tried to send message '${message} on a closed connection to ${relay}.`)\n this.name = 'SendingOnClosedConnection'\n }\n}\n\nexport class AbstractRelay {\n public readonly url: string\n private _connected: boolean = false\n\n public onclose: (() => void) | null = null\n public onnotice: (msg: string) => void = msg => console.debug(`NOTICE from ${this.url}: ${msg}`)\n\n public baseEoseTimeout: number = 4400\n public connectionTimeout: number = 4400\n public publishTimeout: number = 4400\n public pingFrequency: number = 20000\n public pingTimeout: number = 20000\n public openSubs: Map = new Map()\n public enablePing: boolean | undefined\n private connectionTimeoutHandle: ReturnType | undefined\n\n private connectionPromise: Promise | undefined\n private openCountRequests = new Map()\n private openEventPublishes = new Map()\n private ws: RelayWebSocket | undefined\n private incomingMessageQueue = new Queue()\n private queueRunning = false\n private challenge: string | undefined\n private authPromise: Promise | undefined\n private serial: number = 0\n private verifyEvent: Nostr['verifyEvent']\n\n private _WebSocket: typeof WebSocket\n\n constructor(url: string, opts: AbstractRelayConstructorOptions) {\n this.url = normalizeURL(url)\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation || WebSocket\n this.enablePing = opts.enablePing\n }\n\n static async connect(url: string, opts: AbstractRelayConstructorOptions): Promise {\n const relay = new AbstractRelay(url, opts)\n await relay.connect()\n return relay\n }\n\n private closeAllSubscriptions(reason: string) {\n for (let [_, sub] of this.openSubs) {\n sub.close(reason)\n }\n this.openSubs.clear()\n\n for (let [_, ep] of this.openEventPublishes) {\n ep.reject(new Error(reason))\n }\n this.openEventPublishes.clear()\n\n for (let [_, cr] of this.openCountRequests) {\n cr.reject(new Error(reason))\n }\n this.openCountRequests.clear()\n }\n\n public get connected(): boolean {\n return this._connected\n }\n\n public async connect(): Promise {\n if (this.connectionPromise) return this.connectionPromise\n\n this.challenge = undefined\n this.authPromise = undefined\n this.connectionPromise = new Promise((resolve, reject) => {\n this.connectionTimeoutHandle = setTimeout(() => {\n reject('connection timed out')\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection timed out')\n }, this.connectionTimeout)\n\n try {\n this.ws = new this._WebSocket(this.url)\n } catch (err) {\n clearTimeout(this.connectionTimeoutHandle)\n reject(err)\n return\n }\n\n this.ws.onopen = () => {\n clearTimeout(this.connectionTimeoutHandle)\n this._connected = true\n if (this.enablePing) {\n this.pingpong()\n }\n resolve()\n }\n\n this.ws.onerror = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket error')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection errored')\n }\n }\n\n this.ws.onclose = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket closed')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection closed')\n }\n }\n\n this.ws.onmessage = this._onmessage.bind(this)\n })\n\n return this.connectionPromise\n }\n\n private async waitForPingPong() {\n return new Promise((res, err) => {\n // listen for pong\n ;(this.ws && this.ws.on && this.ws.on('pong', () => res(true))) || err(\"ws can't listen for pong\")\n // send a ping\n this.ws && this.ws.ping && this.ws.ping()\n })\n }\n\n private async waitForDummyReq() {\n return new Promise((resolve, _) => {\n // make a dummy request with expected empty eose reply\n // [\"REQ\", \"_\", {\"ids\":[\"aaaa...aaaa\"]}]\n const sub = this.subscribe([{ ids: ['a'.repeat(64)] }], {\n oneose: () => {\n sub.close()\n resolve(true)\n },\n eoseTimeout: this.pingTimeout + 1000,\n })\n })\n }\n\n // nodejs requires this magic here to ensure connections are closed when internet goes off and stuff\n // in browsers it's done automatically. see https://github.com/nbd-wtf/nostr-tools/issues/491\n private async pingpong() {\n // if the websocket is connected\n if (this.ws?.readyState === 1) {\n // wait for either a ping-pong reply or a timeout\n const result = await Promise.any([\n // browsers don't have ping so use a dummy req\n this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(),\n new Promise(res => setTimeout(() => res(false), this.pingTimeout)),\n ])\n if (result) {\n // schedule another pingpong\n setTimeout(() => this.pingpong(), this.pingFrequency)\n } else {\n // pingpong closing socket\n this.closeAllSubscriptions('pingpong timed out')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n }\n }\n\n private async runQueue() {\n this.queueRunning = true\n while (true) {\n if (false === this.handleNext()) {\n break\n }\n await yieldThread()\n }\n this.queueRunning = false\n }\n\n private handleNext(): undefined | false {\n const json = this.incomingMessageQueue.dequeue()\n if (!json) {\n return false\n }\n\n const subid = getSubscriptionId(json)\n if (subid) {\n const so = this.openSubs.get(subid as string)\n if (!so) {\n // this is an EVENT message, but for a subscription we don't have, so just stop here\n return\n }\n\n // this will be called only when this message is a EVENT message for a subscription we have\n // we do this before parsing the JSON to not have to do that for duplicate events\n // since JSON parsing is slow\n const id = getHex64(json, 'id')\n const alreadyHave = so.alreadyHaveEvent?.(id)\n\n // notify any interested client that the relay has this event\n // (do this after alreadyHaveEvent() because the client may rely on this to answer that)\n so.receivedEvent?.(this, id)\n\n if (alreadyHave) {\n // if we had already seen this event we can just stop here\n return\n }\n }\n\n try {\n let data = JSON.parse(json)\n // we won't do any checks against the data since all failures (i.e. invalid messages from relays)\n // will naturally be caught by the encompassing try..catch block\n\n switch (data[0]) {\n case 'EVENT': {\n const so = this.openSubs.get(data[1] as string) as Subscription\n const event = data[2] as NostrEvent\n if (this.verifyEvent(event) && matchFilters(so.filters, event)) {\n so.onevent(event)\n }\n return\n }\n case 'COUNT': {\n const id: string = data[1]\n const payload = data[2] as { count: number }\n const cr = this.openCountRequests.get(id) as CountResolver\n if (cr) {\n cr.resolve(payload.count)\n this.openCountRequests.delete(id)\n }\n return\n }\n case 'EOSE': {\n const so = this.openSubs.get(data[1] as string)\n if (!so) return\n so.receivedEose()\n return\n }\n case 'OK': {\n const id: string = data[1]\n const ok: boolean = data[2]\n const reason: string = data[3]\n const ep = this.openEventPublishes.get(id) as EventPublishResolver\n if (ep) {\n clearTimeout(ep.timeout)\n if (ok) ep.resolve(reason)\n else ep.reject(new Error(reason))\n this.openEventPublishes.delete(id)\n }\n return\n }\n case 'CLOSED': {\n const id: string = data[1]\n const so = this.openSubs.get(id)\n if (!so) return\n so.closed = true\n so.close(data[2] as string)\n return\n }\n case 'NOTICE':\n this.onnotice(data[1] as string)\n return\n case 'AUTH': {\n this.challenge = data[1] as string\n return\n }\n }\n } catch (err) {\n return\n }\n }\n\n public async send(message: string) {\n if (!this.connectionPromise) throw new SendingOnClosedConnection(message, this.url)\n\n this.connectionPromise.then(() => {\n this.ws?.send(message)\n })\n }\n\n public async auth(signAuthEvent: (evt: EventTemplate) => Promise): Promise {\n const challenge = this.challenge\n if (!challenge) throw new Error(\"can't perform auth, no challenge was received\")\n if (this.authPromise) return this.authPromise\n\n this.authPromise = new Promise(async (resolve, reject) => {\n try {\n let evt = await signAuthEvent(makeAuthEvent(this.url, challenge))\n let timeout = setTimeout(() => {\n let ep = this.openEventPublishes.get(evt.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('auth timed out'))\n this.openEventPublishes.delete(evt.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(evt.id, { resolve, reject, timeout })\n this.send('[\"AUTH\",' + JSON.stringify(evt) + ']')\n } catch (err) {\n console.warn('subscribe auth function failed:', err)\n }\n })\n return this.authPromise\n }\n\n public async publish(event: Event): Promise {\n const ret = new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n const ep = this.openEventPublishes.get(event.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('publish timed out'))\n this.openEventPublishes.delete(event.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(event.id, { resolve, reject, timeout })\n })\n this.send('[\"EVENT\",' + JSON.stringify(event) + ']')\n return ret\n }\n\n public async count(filters: Filter[], params: { id?: string | null }): Promise {\n this.serial++\n const id = params?.id || 'count:' + this.serial\n const ret = new Promise((resolve, reject) => {\n this.openCountRequests.set(id, { resolve, reject })\n })\n this.send('[\"COUNT\",\"' + id + '\",' + JSON.stringify(filters).substring(1))\n return ret\n }\n\n public subscribe(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n const subscription = this.prepareSubscription(filters, params)\n subscription.fire()\n return subscription\n }\n\n public prepareSubscription(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n this.serial++\n const id = params.id || (params.label ? params.label + ':' : 'sub:') + this.serial\n const subscription = new Subscription(this, id, filters, params)\n this.openSubs.set(id, subscription)\n return subscription\n }\n\n public close() {\n this.closeAllSubscriptions('relay connection closed by us')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n\n // this is the function assigned to this.ws.onmessage\n // it's exposed for testing and debugging purposes\n public _onmessage(ev: MessageEvent) {\n this.incomingMessageQueue.enqueue(ev.data as string)\n if (!this.queueRunning) {\n this.runQueue()\n }\n }\n}\n\nexport class Subscription {\n public readonly relay: AbstractRelay\n public readonly id: string\n\n public closed: boolean = false\n public eosed: boolean = false\n public filters: Filter[]\n public alreadyHaveEvent: ((id: string) => boolean) | undefined\n public receivedEvent: ((relay: AbstractRelay, id: string) => void) | undefined\n\n public onevent: (evt: Event) => void\n public oneose: (() => void) | undefined\n public onclose: ((reason: string) => void) | undefined\n\n public eoseTimeout: number\n private eoseTimeoutHandle: ReturnType | undefined\n\n constructor(relay: AbstractRelay, id: string, filters: Filter[], params: SubscriptionParams) {\n this.relay = relay\n this.filters = filters\n this.id = id\n this.alreadyHaveEvent = params.alreadyHaveEvent\n this.receivedEvent = params.receivedEvent\n this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout\n\n this.oneose = params.oneose\n this.onclose = params.onclose\n this.onevent =\n params.onevent ||\n (event => {\n console.warn(\n `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,\n event,\n )\n })\n }\n\n public fire() {\n this.relay.send('[\"REQ\",\"' + this.id + '\",' + JSON.stringify(this.filters).substring(1))\n\n // only now we start counting the eoseTimeout\n this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout)\n }\n\n public receivedEose() {\n if (this.eosed) return\n clearTimeout(this.eoseTimeoutHandle)\n this.eosed = true\n this.oneose?.()\n }\n\n public close(reason: string = 'closed by caller') {\n if (!this.closed && this.relay.connected) {\n // if the connection was closed by the user calling .close() we will send a CLOSE message\n // otherwise this._open will be already set to false so we will skip this\n try {\n this.relay.send('[\"CLOSE\",' + JSON.stringify(this.id) + ']')\n } catch (err) {\n if (err instanceof SendingOnClosedConnection) {\n /* doesn't matter, it's ok */\n } else {\n throw err\n }\n }\n this.closed = true\n }\n this.relay.openSubs.delete(this.id)\n this.onclose?.(reason)\n }\n}\n\nexport type SubscriptionParams = {\n onevent?: (evt: Event) => void\n oneose?: () => void\n onclose?: (reason: string) => void\n alreadyHaveEvent?: (id: string) => boolean\n receivedEvent?: (relay: AbstractRelay, id: string) => void\n eoseTimeout?: number\n}\n\nexport type CountResolver = {\n resolve: (count: number) => void\n reject: (err: Error) => void\n}\n\nexport type EventPublishResolver = {\n resolve: (reason: string) => void\n reject: (err: Error) => void\n timeout: ReturnType\n}\n", "/* global WebSocket */\n\nimport {\n AbstractRelay as AbstractRelay,\n SubscriptionParams,\n Subscription,\n type AbstractRelayConstructorOptions,\n} from './abstract-relay.ts'\nimport { normalizeURL } from './utils.ts'\n\nimport type { Event, EventTemplate, Nostr, VerifiedEvent } from './core.ts'\nimport { type Filter } from './filter.ts'\nimport { alwaysTrue } from './helpers.ts'\n\nexport type SubCloser = { close: (reason?: string) => void }\n\nexport type AbstractPoolConstructorOptions = AbstractRelayConstructorOptions & {}\n\nexport type SubscribeManyParams = Omit & {\n maxWait?: number\n onclose?: (reasons: string[]) => void\n onauth?: (event: EventTemplate) => Promise\n // Deprecated: use onauth instead\n doauth?: (event: EventTemplate) => Promise\n id?: string\n label?: string\n}\n\nexport class AbstractSimplePool {\n protected relays: Map = new Map()\n public seenOn: Map> = new Map()\n public trackRelays: boolean = false\n\n public verifyEvent: Nostr['verifyEvent']\n public enablePing: boolean | undefined\n public trustedRelayURLs: Set = new Set()\n\n private _WebSocket?: typeof WebSocket\n\n constructor(opts: AbstractPoolConstructorOptions) {\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation\n this.enablePing = opts.enablePing\n }\n\n async ensureRelay(url: string, params?: { connectionTimeout?: number }): Promise {\n url = normalizeURL(url)\n\n let relay = this.relays.get(url)\n if (!relay) {\n relay = new AbstractRelay(url, {\n verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent,\n websocketImplementation: this._WebSocket,\n enablePing: this.enablePing,\n })\n relay.onclose = () => {\n this.relays.delete(url)\n }\n if (params?.connectionTimeout) relay.connectionTimeout = params.connectionTimeout\n this.relays.set(url, relay)\n }\n await relay.connect()\n\n return relay\n }\n\n close(relays: string[]) {\n relays.map(normalizeURL).forEach(url => {\n this.relays.get(url)?.close()\n this.relays.delete(url)\n })\n }\n\n subscribe(relays: string[], filter: Filter, params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const request: { url: string; filter: Filter }[] = []\n for (let i = 0; i < relays.length; i++) {\n const url = normalizeURL(relays[i])\n if (!request.find(r => r.url === url)) {\n request.push({ url, filter })\n }\n }\n\n return this.subscribeMap(request, params)\n }\n\n subscribeMany(relays: string[], filters: Filter[], params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const request: { url: string; filter: Filter }[] = []\n const uniqUrls: string[] = []\n for (let i = 0; i < relays.length; i++) {\n const url = normalizeURL(relays[i])\n if (uniqUrls.indexOf(url) === -1) {\n for (let f = 0; f < filters.length; f++) {\n request.push({ url, filter: filters[f] })\n }\n }\n }\n\n return this.subscribeMap(request, params)\n }\n\n subscribeMap(requests: { url: string; filter: Filter }[], params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n if (this.trackRelays) {\n params.receivedEvent = (relay: AbstractRelay, id: string) => {\n let set = this.seenOn.get(id)\n if (!set) {\n set = new Set()\n this.seenOn.set(id, set)\n }\n set.add(relay)\n }\n }\n\n const _knownIds = new Set()\n const subs: Subscription[] = []\n\n // batch all EOSEs into a single\n const eosesReceived: boolean[] = []\n let handleEose = (i: number) => {\n if (eosesReceived[i]) return // do not act twice for the same relay\n eosesReceived[i] = true\n if (eosesReceived.filter(a => a).length === requests.length) {\n params.oneose?.()\n handleEose = () => {}\n }\n }\n // batch all closes into a single\n const closesReceived: string[] = []\n let handleClose = (i: number, reason: string) => {\n if (closesReceived[i]) return // do not act twice for the same relay\n handleEose(i)\n closesReceived[i] = reason\n if (closesReceived.filter(a => a).length === requests.length) {\n params.onclose?.(closesReceived)\n handleClose = () => {}\n }\n }\n\n const localAlreadyHaveEventHandler = (id: string) => {\n if (params.alreadyHaveEvent?.(id)) {\n return true\n }\n const have = _knownIds.has(id)\n _knownIds.add(id)\n return have\n }\n\n // open a subscription in all given relays\n const allOpened = Promise.all(\n requests.map(async ({ url, filter }, i) => {\n let relay: AbstractRelay\n try {\n relay = await this.ensureRelay(url, {\n connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1000) : undefined,\n })\n } catch (err) {\n handleClose(i, (err as any)?.message || String(err))\n return\n }\n\n let subscription = relay.subscribe([filter], {\n ...params,\n oneose: () => handleEose(i),\n onclose: reason => {\n if (reason.startsWith('auth-required: ') && params.onauth) {\n relay\n .auth(params.onauth)\n .then(() => {\n relay.subscribe([filter], {\n ...params,\n oneose: () => handleEose(i),\n onclose: reason => {\n handleClose(i, reason) // the second time we won't try to auth anymore\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait,\n })\n })\n .catch(err => {\n handleClose(i, `auth was required and attempted, but failed with: ${err}`)\n })\n } else {\n handleClose(i, reason)\n }\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait,\n })\n\n subs.push(subscription)\n }),\n )\n\n return {\n async close(reason?: string) {\n await allOpened\n subs.forEach(sub => {\n sub.close(reason)\n })\n },\n }\n }\n\n subscribeEose(\n relays: string[],\n filter: Filter,\n params: Pick,\n ): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const subcloser = this.subscribe(relays, filter, {\n ...params,\n oneose() {\n subcloser.close('closed automatically on eose')\n },\n })\n return subcloser\n }\n\n subscribeManyEose(\n relays: string[],\n filters: Filter[],\n params: Pick,\n ): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const subcloser = this.subscribeMany(relays, filters, {\n ...params,\n oneose() {\n subcloser.close('closed automatically on eose')\n },\n })\n return subcloser\n }\n\n async querySync(\n relays: string[],\n filter: Filter,\n params?: Pick,\n ): Promise {\n return new Promise(async resolve => {\n const events: Event[] = []\n this.subscribeEose(relays, filter, {\n ...params,\n onevent(event: Event) {\n events.push(event)\n },\n onclose(_: string[]) {\n resolve(events)\n },\n })\n })\n }\n\n async get(\n relays: string[],\n filter: Filter,\n params?: Pick,\n ): Promise {\n filter.limit = 1\n const events = await this.querySync(relays, filter, params)\n events.sort((a, b) => b.created_at - a.created_at)\n return events[0] || null\n }\n\n publish(\n relays: string[],\n event: Event,\n options?: { onauth?: (evt: EventTemplate) => Promise },\n ): Promise[] {\n return relays.map(normalizeURL).map(async (url, i, arr) => {\n if (arr.indexOf(url) !== i) {\n // duplicate\n return Promise.reject('duplicate url')\n }\n\n let r = await this.ensureRelay(url)\n return r\n .publish(event)\n .catch(async err => {\n if (err instanceof Error && err.message.startsWith('auth-required: ') && options?.onauth) {\n await r.auth(options.onauth)\n return r.publish(event) // retry\n }\n throw err\n })\n .then(reason => {\n if (this.trackRelays) {\n let set = this.seenOn.get(event.id)\n if (!set) {\n set = new Set()\n this.seenOn.set(event.id, set)\n }\n set.add(r)\n }\n return reason\n })\n })\n }\n\n listConnectionStatus(): Map {\n const map = new Map()\n this.relays.forEach((relay, url) => map.set(url, relay.connected))\n\n return map\n }\n\n destroy(): void {\n this.relays.forEach(conn => conn.close())\n this.relays = new Map()\n }\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,uBAAwB;AACxB,IAAAA,gBAA2B;;;ACOpB,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,CAAC,QAAiD,eAAe;AAE3E,SAAS,cAAiB,OAAsC;AACrE,MAAI,CAAC,SAAS,KAAK;AAAG,WAAO;AAC7B,MAAI,OAAO,MAAM,SAAS;AAAU,WAAO;AAC3C,MAAI,OAAO,MAAM,YAAY;AAAU,WAAO;AAC9C,MAAI,OAAO,MAAM,eAAe;AAAU,WAAO;AACjD,MAAI,OAAO,MAAM,WAAW;AAAU,WAAO;AAC7C,MAAI,CAAC,MAAM,OAAO,MAAM,gBAAgB;AAAG,WAAO;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Y,GAAG;AAClC,aAAO,EACJ,QAAQ,KAAK,EACb,MAAM,OAAM,QAAO;AAClB,YAAI,eAAe,SAAS,IAAI,QAAQ,WAAW,iBAAiB,KAAK,SAAS,QAAQ;AACxF,gBAAM,EAAE,KAAK,QAAQ,MAAM;AAC3B,iBAAO,EAAE,QAAQ,KAAK;AAAA,QACxB;AACA,cAAM;AAAA,MACR,CAAC,EACA,KAAK,YAAU;AACd,YAAI,KAAK,aAAa;AACpB,cAAI,MAAM,KAAK,OAAO,IAAI,MAAM,EAAE;AAClC,cAAI,CAAC,KAAK;AACR,kBAAM,oBAAI,IAAI;AACd,iBAAK,OAAO,IAAI,MAAM,IAAI,GAAG;AAAA,UAC/B;AACA,cAAI,IAAI,CAAC;AAAA,QACX;AACA,eAAO;AAAA,MACT,CAAC;AAAA,IACL,CAAC;AAAA,EACH;AAAA,EAEA,uBAA6C;AAC3C,UAAM,MAAM,oBAAI,IAAqB;AACrC,SAAK,OAAO,QAAQ,CAAC,OAAO,QAAQ,IAAI,IAAI,KAAK,MAAM,SAAS,CAAC;AAEjE,WAAO;AAAA,EACT;AAAA,EAEA,UAAgB;AACd,SAAK,OAAO,QAAQ,UAAQ,KAAK,MAAM,CAAC;AACxC,SAAK,SAAS,oBAAI,IAAI;AAAA,EACxB;AACF;;;AVvTA,IAAI;AAEJ,IAAI;AACF,eAAa;AACf,QAAE;AAAO;AAEF,SAAS,2BAA2B,yBAA8B;AACvE,eAAa;AACf;AAEO,IAAM,aAAN,cAAyB,mBAAmB;AAAA,EACjD,YAAY,SAAoC;AAC9C,UAAM,EAAE,aAAa,yBAAyB,YAAY,GAAG,QAAQ,CAAC;AAAA,EACxE;AACF;", + "names": ["import_utils", "i", "target", "i", "i", "reason"] +} diff --git a/node_modules/nostr-tools/lib/cjs/pure.js b/node_modules/nostr-tools/lib/cjs/pure.js new file mode 100644 index 0000000..d3a367b --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/pure.js @@ -0,0 +1,130 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pure.ts +var pure_exports = {}; +__export(pure_exports, { + finalizeEvent: () => finalizeEvent, + generateSecretKey: () => generateSecretKey, + getEventHash: () => getEventHash, + getPublicKey: () => getPublicKey, + serializeEvent: () => serializeEvent, + sortEvents: () => sortEvents, + validateEvent: () => validateEvent, + verifiedSymbol: () => verifiedSymbol, + verifyEvent: () => verifyEvent +}); +module.exports = __toCommonJS(pure_exports); +var import_secp256k1 = require("@noble/curves/secp256k1"); +var import_utils2 = require("@noble/hashes/utils"); + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} +function sortEvents(events) { + return events.sort((a, b) => { + if (a.created_at !== b.created_at) { + return b.created_at - a.created_at; + } + return a.id.localeCompare(b.id); + }); +} + +// pure.ts +var import_sha256 = require("@noble/hashes/sha256"); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// pure.ts +var JS = class { + generateSecretKey() { + return import_secp256k1.schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = import_secp256k1.schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = (0, import_sha256.sha256)(utf8Encoder.encode(serializeEvent(event))); + return (0, import_utils2.bytesToHex)(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; diff --git a/node_modules/nostr-tools/lib/cjs/pure.js.map b/node_modules/nostr-tools/lib/cjs/pure.js.map new file mode 100644 index 0000000..3674c9e --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/pure.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../pure.ts", "../../core.ts", "../../utils.ts"], + "sourcesContent": ["import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n"], + "mappings": ";;;;;;;;;;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lib/cjs/references.js new file mode 100644 index 0000000..9001bfc --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/references.js @@ -0,0 +1,210 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// references.ts +var references_exports = {}; +__export(references_exports, { + parseReferences: () => parseReferences +}); +module.exports = __toCommonJS(references_exports); + +// nip19.ts +var import_utils2 = require("@noble/hashes/utils"); +var import_base = require("@scure/base"); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// nip19.ts +var Bech32MaxSize = 5e3; +function decode(code) { + let { prefix, words } = import_base.bech32.decode(code, Bech32MaxSize); + let data = new Uint8Array(import_base.bech32.fromWords(words)); + switch (prefix) { + case "nprofile": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nprofile"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + return { + type: "nprofile", + data: { + pubkey: (0, import_utils2.bytesToHex)(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nevent": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nevent"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + if (tlv[2] && tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (tlv[3] && tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "nevent", + data: { + id: (0, import_utils2.bytesToHex)(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [], + author: tlv[2]?.[0] ? (0, import_utils2.bytesToHex)(tlv[2][0]) : void 0, + kind: tlv[3]?.[0] ? parseInt((0, import_utils2.bytesToHex)(tlv[3][0]), 16) : void 0 + } + }; + } + case "naddr": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for naddr"); + if (!tlv[2]?.[0]) + throw new Error("missing TLV 2 for naddr"); + if (tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (!tlv[3]?.[0]) + throw new Error("missing TLV 3 for naddr"); + if (tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "naddr", + data: { + identifier: utf8Decoder.decode(tlv[0][0]), + pubkey: (0, import_utils2.bytesToHex)(tlv[2][0]), + kind: parseInt((0, import_utils2.bytesToHex)(tlv[3][0]), 16), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nsec": + return { type: prefix, data }; + case "npub": + case "note": + return { type: prefix, data: (0, import_utils2.bytesToHex)(data) }; + default: + throw new Error(`unknown prefix ${prefix}`); + } +} +function parseTLV(data) { + let result = {}; + let rest = data; + while (rest.length > 0) { + let t = rest[0]; + let l = rest[1]; + let v = rest.slice(2, 2 + l); + rest = rest.slice(2 + l); + if (v.length < l) + throw new Error(`not enough data to read on TLV ${t}`); + result[t] = result[t] || []; + result[t].push(v); + } + return result; +} + +// references.ts +var mentionRegex = /\bnostr:((note|npub|naddr|nevent|nprofile)1\w+)\b|#\[(\d+)\]/g; +function parseReferences(evt) { + let references = []; + for (let ref of evt.content.matchAll(mentionRegex)) { + if (ref[2]) { + try { + let { type, data } = decode(ref[1]); + switch (type) { + case "npub": { + references.push({ + text: ref[0], + profile: { pubkey: data, relays: [] } + }); + break; + } + case "nprofile": { + references.push({ + text: ref[0], + profile: data + }); + break; + } + case "note": { + references.push({ + text: ref[0], + event: { id: data, relays: [] } + }); + break; + } + case "nevent": { + references.push({ + text: ref[0], + event: data + }); + break; + } + case "naddr": { + references.push({ + text: ref[0], + address: data + }); + break; + } + } + } catch (err) { + } + } else if (ref[3]) { + let idx = parseInt(ref[3], 10); + let tag = evt.tags[idx]; + if (!tag) + continue; + switch (tag[0]) { + case "p": { + references.push({ + text: ref[0], + profile: { pubkey: tag[1], relays: tag[2] ? [tag[2]] : [] } + }); + break; + } + case "e": { + references.push({ + text: ref[0], + event: { id: tag[1], relays: tag[2] ? [tag[2]] : [] } + }); + break; + } + case "a": { + try { + let [kind, pubkey, identifier] = tag[1].split(":"); + references.push({ + text: ref[0], + address: { + identifier, + pubkey, + kind: parseInt(kind, 10), + relays: tag[2] ? [tag[2]] : [] + } + }); + } catch (err) { + } + break; + } + } + } + } + return references; +} diff --git a/node_modules/nostr-tools/lib/cjs/references.js.map b/node_modules/nostr-tools/lib/cjs/references.js.map new file mode 100644 index 0000000..978ad07 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/references.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../references.ts", "../../nip19.ts", "../../utils.ts"], + "sourcesContent": ["import { decode, type AddressPointer, type ProfilePointer, type EventPointer } from './nip19.ts'\n\nimport type { Event } from './core.ts'\n\ntype Reference = {\n text: string\n profile?: ProfilePointer\n event?: EventPointer\n address?: AddressPointer\n}\n\nconst mentionRegex = /\\bnostr:((note|npub|naddr|nevent|nprofile)1\\w+)\\b|#\\[(\\d+)\\]/g\n\nexport function parseReferences(evt: Event): Reference[] {\n let references: Reference[] = []\n for (let ref of evt.content.matchAll(mentionRegex)) {\n if (ref[2]) {\n // it's a NIP-27 mention\n try {\n let { type, data } = decode(ref[1])\n switch (type) {\n case 'npub': {\n references.push({\n text: ref[0],\n profile: { pubkey: data as string, relays: [] },\n })\n break\n }\n case 'nprofile': {\n references.push({\n text: ref[0],\n profile: data as ProfilePointer,\n })\n break\n }\n case 'note': {\n references.push({\n text: ref[0],\n event: { id: data as string, relays: [] },\n })\n break\n }\n case 'nevent': {\n references.push({\n text: ref[0],\n event: data as EventPointer,\n })\n break\n }\n case 'naddr': {\n references.push({\n text: ref[0],\n address: data as AddressPointer,\n })\n break\n }\n }\n } catch (err) {\n /***/\n }\n } else if (ref[3]) {\n // it's a NIP-10 mention\n let idx = parseInt(ref[3], 10)\n let tag = evt.tags[idx]\n if (!tag) continue\n\n switch (tag[0]) {\n case 'p': {\n references.push({\n text: ref[0],\n profile: { pubkey: tag[1], relays: tag[2] ? [tag[2]] : [] },\n })\n break\n }\n case 'e': {\n references.push({\n text: ref[0],\n event: { id: tag[1], relays: tag[2] ? [tag[2]] : [] },\n })\n break\n }\n case 'a': {\n try {\n let [kind, pubkey, identifier] = tag[1].split(':')\n references.push({\n text: ref[0],\n address: {\n identifier,\n pubkey,\n kind: parseInt(kind, 10),\n relays: tag[2] ? [tag[2]] : [],\n },\n })\n } catch (err) {\n /***/\n }\n break\n }\n }\n }\n }\n\n return references\n}\n", "import { bytesToHex, concatBytes, hexToBytes } from '@noble/hashes/utils'\nimport { bech32 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport type NProfile = `nprofile1${string}`\nexport type NEvent = `nevent1${string}`\nexport type NAddr = `naddr1${string}`\nexport type NSec = `nsec1${string}`\nexport type NPub = `npub1${string}`\nexport type Note = `note1${string}`\nexport type Ncryptsec = `ncryptsec1${string}`\n\nexport const NostrTypeGuard = {\n isNProfile: (value?: string | null): value is NProfile => /^nprofile1[a-z\\d]+$/.test(value || ''),\n isNEvent: (value?: string | null): value is NEvent => /^nevent1[a-z\\d]+$/.test(value || ''),\n isNAddr: (value?: string | null): value is NAddr => /^naddr1[a-z\\d]+$/.test(value || ''),\n isNSec: (value?: string | null): value is NSec => /^nsec1[a-z\\d]{58}$/.test(value || ''),\n isNPub: (value?: string | null): value is NPub => /^npub1[a-z\\d]{58}$/.test(value || ''),\n isNote: (value?: string | null): value is Note => /^note1[a-z\\d]+$/.test(value || ''),\n isNcryptsec: (value?: string | null): value is Ncryptsec => /^ncryptsec1[a-z\\d]+$/.test(value || ''),\n}\n\nexport const Bech32MaxSize = 5000\n\n/**\n * Bech32 regex.\n * @see https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32\n */\nexport const BECH32_REGEX = /[\\x21-\\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/\n\nfunction integerToUint8Array(number: number) {\n // Create a Uint8Array with enough space to hold a 32-bit integer (4 bytes).\n const uint8Array = new Uint8Array(4)\n\n // Use bitwise operations to extract the bytes.\n uint8Array[0] = (number >> 24) & 0xff // Most significant byte (MSB)\n uint8Array[1] = (number >> 16) & 0xff\n uint8Array[2] = (number >> 8) & 0xff\n uint8Array[3] = number & 0xff // Least significant byte (LSB)\n\n return uint8Array\n}\n\nexport type ProfilePointer = {\n pubkey: string // hex\n relays?: string[]\n}\n\nexport type EventPointer = {\n id: string // hex\n relays?: string[]\n author?: string\n kind?: number\n}\n\nexport type AddressPointer = {\n identifier: string\n pubkey: string\n kind: number\n relays?: string[]\n}\n\nexport function decodeNostrURI(nip19code: string): ReturnType | { type: 'invalid'; data: null } {\n try {\n if (nip19code.startsWith('nostr:')) nip19code = nip19code.substring(6)\n return decode(nip19code)\n } catch (_err) {\n return { type: 'invalid', data: null }\n }\n}\n\nexport type DecodedNevent = {\n type: 'nevent'\n data: EventPointer\n}\n\nexport type DecodedNprofile = {\n type: 'nprofile'\n data: ProfilePointer\n}\n\nexport type DecodedNaddr = {\n type: 'naddr'\n data: AddressPointer\n}\n\nexport type DecodedNsec = {\n type: 'nsec'\n data: Uint8Array\n}\n\nexport type DecodedNpub = {\n type: 'npub'\n data: string\n}\n\nexport type DecodedNote = {\n type: 'note'\n data: string\n}\n\nexport type DecodedResult = DecodedNevent | DecodedNprofile | DecodedNaddr | DecodedNpub | DecodedNsec | DecodedNote\n\nexport function decode(nip19: NEvent): DecodedNevent\nexport function decode(nip19: NProfile): DecodedNprofile\nexport function decode(nip19: NAddr): DecodedNaddr\nexport function decode(nip19: NSec): DecodedNsec\nexport function decode(nip19: NPub): DecodedNpub\nexport function decode(nip19: Note): DecodedNote\nexport function decode(code: string): DecodedResult\nexport function decode(code: string): DecodedResult {\n let { prefix, words } = bech32.decode(code, Bech32MaxSize)\n let data = new Uint8Array(bech32.fromWords(words))\n\n switch (prefix) {\n case 'nprofile': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nprofile')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n\n return {\n type: 'nprofile',\n data: {\n pubkey: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n case 'nevent': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nevent')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n if (tlv[2] && tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (tlv[3] && tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'nevent',\n data: {\n id: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n author: tlv[2]?.[0] ? bytesToHex(tlv[2][0]) : undefined,\n kind: tlv[3]?.[0] ? parseInt(bytesToHex(tlv[3][0]), 16) : undefined,\n },\n }\n }\n\n case 'naddr': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for naddr')\n if (!tlv[2]?.[0]) throw new Error('missing TLV 2 for naddr')\n if (tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (!tlv[3]?.[0]) throw new Error('missing TLV 3 for naddr')\n if (tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'naddr',\n data: {\n identifier: utf8Decoder.decode(tlv[0][0]),\n pubkey: bytesToHex(tlv[2][0]),\n kind: parseInt(bytesToHex(tlv[3][0]), 16),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n\n case 'nsec':\n return { type: prefix, data }\n\n case 'npub':\n case 'note':\n return { type: prefix, data: bytesToHex(data) }\n\n default:\n throw new Error(`unknown prefix ${prefix}`)\n }\n}\n\ntype TLV = { [t: number]: Uint8Array[] }\n\nfunction parseTLV(data: Uint8Array): TLV {\n let result: TLV = {}\n let rest = data\n while (rest.length > 0) {\n let t = rest[0]\n let l = rest[1]\n let v = rest.slice(2, 2 + l)\n rest = rest.slice(2 + l)\n if (v.length < l) throw new Error(`not enough data to read on TLV ${t}`)\n result[t] = result[t] || []\n result[t].push(v)\n }\n return result\n}\n\nexport function nsecEncode(key: Uint8Array): NSec {\n return encodeBytes('nsec', key)\n}\n\nexport function npubEncode(hex: string): NPub {\n return encodeBytes('npub', hexToBytes(hex))\n}\n\nexport function noteEncode(hex: string): Note {\n return encodeBytes('note', hexToBytes(hex))\n}\n\nfunction encodeBech32(prefix: Prefix, data: Uint8Array): `${Prefix}1${string}` {\n let words = bech32.toWords(data)\n return bech32.encode(prefix, words, Bech32MaxSize) as `${Prefix}1${string}`\n}\n\nexport function encodeBytes(prefix: Prefix, bytes: Uint8Array): `${Prefix}1${string}` {\n return encodeBech32(prefix, bytes)\n}\n\nexport function nprofileEncode(profile: ProfilePointer): NProfile {\n let data = encodeTLV({\n 0: [hexToBytes(profile.pubkey)],\n 1: (profile.relays || []).map(url => utf8Encoder.encode(url)),\n })\n return encodeBech32('nprofile', data)\n}\n\nexport function neventEncode(event: EventPointer): NEvent {\n let kindArray\n if (event.kind !== undefined) {\n kindArray = integerToUint8Array(event.kind)\n }\n\n let data = encodeTLV({\n 0: [hexToBytes(event.id)],\n 1: (event.relays || []).map(url => utf8Encoder.encode(url)),\n 2: event.author ? [hexToBytes(event.author)] : [],\n 3: kindArray ? [new Uint8Array(kindArray)] : [],\n })\n\n return encodeBech32('nevent', data)\n}\n\nexport function naddrEncode(addr: AddressPointer): NAddr {\n let kind = new ArrayBuffer(4)\n new DataView(kind).setUint32(0, addr.kind, false)\n\n let data = encodeTLV({\n 0: [utf8Encoder.encode(addr.identifier)],\n 1: (addr.relays || []).map(url => utf8Encoder.encode(url)),\n 2: [hexToBytes(addr.pubkey)],\n 3: [new Uint8Array(kind)],\n })\n return encodeBech32('naddr', data)\n}\n\nfunction encodeTLV(tlv: TLV): Uint8Array {\n let entries: Uint8Array[] = []\n\n Object.entries(tlv)\n .reverse()\n .forEach(([t, vs]) => {\n vs.forEach(v => {\n let entry = new Uint8Array(v.length + 2)\n entry.set([parseInt(t)], 0)\n entry.set([v.length], 1)\n entry.set(v, 2)\n entries.push(entry)\n })\n })\n\n return concatBytes(...entries)\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,gBAAoD;AACpD,kBAAuB;;;ACIvB,mBAAuC;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;;;ADoBjD,IAAM,gBAAgB;AAwFtB,SAAS,OAAO,MAA6B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K;AAAA,YACd,MAAM,IAAI;AAAA,YACV,SAAS,EAAE,QAAQ,IAAI,IAAI,QAAQ,IAAI,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,EAAE;AAAA,UAC5D,CAAC;AACD;AAAA,QACF;AAAA,QACA,KAAK,KAAK;AACR,qBAAW,KAAK;AAAA,YACd,MAAM,IAAI;AAAA,YACV,OAAO,EAAE,IAAI,IAAI,IAAI,QAAQ,IAAI,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,EAAE;AAAA,UACtD,CAAC;AACD;AAAA,QACF;AAAA,QACA,KAAK,KAAK;AACR,cAAI;AACF,gBAAI,CAAC,MAAM,QAAQ,UAAU,IAAI,IAAI,GAAG,MAAM,GAAG;AACjD,uBAAW,KAAK;AAAA,cACd,MAAM,IAAI;AAAA,cACV,SAAS;AAAA,gBACP;AAAA,gBACA;AAAA,gBACA,MAAM,SAAS,MAAM,EAAE;AAAA,gBACvB,QAAQ,IAAI,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC;AAAA,cAC/B;AAAA,YACF,CAAC;AAAA,UACH,SAAS,KAAP;AAAA,UAEF;AACA;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;", + "names": ["import_utils"] +} diff --git a/node_modules/nostr-tools/lib/cjs/relay.js b/node_modules/nostr-tools/lib/cjs/relay.js new file mode 100644 index 0000000..38c994e --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/relay.js @@ -0,0 +1,663 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// relay.ts +var relay_exports = {}; +__export(relay_exports, { + AbstractRelay: () => AbstractRelay, + Relay: () => Relay, + SendingOnClosedConnection: () => SendingOnClosedConnection, + Subscription: () => Subscription, + useWebSocketImplementation: () => useWebSocketImplementation +}); +module.exports = __toCommonJS(relay_exports); + +// pure.ts +var import_secp256k1 = require("@noble/curves/secp256k1"); +var import_utils2 = require("@noble/hashes/utils"); + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +var import_sha256 = require("@noble/hashes/sha256"); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); +function normalizeURL(url) { + try { + if (url.indexOf("://") === -1) + url = "wss://" + url; + let p = new URL(url); + p.pathname = p.pathname.replace(/\/+/g, "/"); + if (p.pathname.endsWith("/")) + p.pathname = p.pathname.slice(0, -1); + if (p.port === "80" && p.protocol === "ws:" || p.port === "443" && p.protocol === "wss:") + p.port = ""; + p.searchParams.sort(); + p.hash = ""; + return p.toString(); + } catch (e) { + throw new Error(`Invalid URL: ${url}`); + } +} +var QueueNode = class { + value; + next = null; + prev = null; + constructor(message) { + this.value = message; + } +}; +var Queue = class { + first; + last; + constructor() { + this.first = null; + this.last = null; + } + enqueue(value) { + const newNode = new QueueNode(value); + if (!this.last) { + this.first = newNode; + this.last = newNode; + } else if (this.last === this.first) { + this.last = newNode; + this.last.prev = this.first; + this.first.next = newNode; + } else { + newNode.prev = this.last; + this.last.next = newNode; + this.last = newNode; + } + return true; + } + dequeue() { + if (!this.first) + return null; + if (this.first === this.last) { + const target2 = this.first; + this.first = null; + this.last = null; + return target2.value; + } + const target = this.first; + this.first = target.next; + if (this.first) { + this.first.prev = null; + } + return target.value; + } +}; + +// pure.ts +var JS = class { + generateSecretKey() { + return import_secp256k1.schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = import_secp256k1.schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = (0, import_sha256.sha256)(utf8Encoder.encode(serializeEvent(event))); + return (0, import_utils2.bytesToHex)(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// kinds.ts +var ClientAuth = 22242; + +// filter.ts +function matchFilter(filter, event) { + if (filter.ids && filter.ids.indexOf(event.id) === -1) { + return false; + } + if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) { + return false; + } + if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) { + return false; + } + for (let f in filter) { + if (f[0] === "#") { + let tagName = f.slice(1); + let values = filter[`#${tagName}`]; + if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values.indexOf(v) !== -1)) + return false; + } + } + if (filter.since && event.created_at < filter.since) + return false; + if (filter.until && event.created_at > filter.until) + return false; + return true; +} +function matchFilters(filters, event) { + for (let i2 = 0; i2 < filters.length; i2++) { + if (matchFilter(filters[i2], event)) { + return true; + } + } + return false; +} + +// fakejson.ts +function getHex64(json, field) { + let len = field.length + 3; + let idx = json.indexOf(`"${field}":`) + len; + let s = json.slice(idx).indexOf(`"`) + idx + 1; + return json.slice(s, s + 64); +} +function getSubscriptionId(json) { + let idx = json.slice(0, 22).indexOf(`"EVENT"`); + if (idx === -1) + return null; + let pstart = json.slice(idx + 7 + 1).indexOf(`"`); + if (pstart === -1) + return null; + let start = idx + 7 + 1 + pstart; + let pend = json.slice(start + 1, 80).indexOf(`"`); + if (pend === -1) + return null; + let end = start + 1 + pend; + return json.slice(start + 1, end); +} + +// nip42.ts +function makeAuthEvent(relayURL, challenge) { + return { + kind: ClientAuth, + created_at: Math.floor(Date.now() / 1e3), + tags: [ + ["relay", relayURL], + ["challenge", challenge] + ], + content: "" + }; +} + +// helpers.ts +async function yieldThread() { + return new Promise((resolve) => { + const ch = new MessageChannel(); + const handler = () => { + ch.port1.removeEventListener("message", handler); + resolve(); + }; + ch.port1.addEventListener("message", handler); + ch.port2.postMessage(0); + ch.port1.start(); + }); +} + +// abstract-relay.ts +var SendingOnClosedConnection = class extends Error { + constructor(message, relay) { + super(`Tried to send message '${message} on a closed connection to ${relay}.`); + this.name = "SendingOnClosedConnection"; + } +}; +var AbstractRelay = class { + url; + _connected = false; + onclose = null; + onnotice = (msg) => console.debug(`NOTICE from ${this.url}: ${msg}`); + baseEoseTimeout = 4400; + connectionTimeout = 4400; + publishTimeout = 4400; + pingFrequency = 2e4; + pingTimeout = 2e4; + openSubs = /* @__PURE__ */ new Map(); + enablePing; + connectionTimeoutHandle; + connectionPromise; + openCountRequests = /* @__PURE__ */ new Map(); + openEventPublishes = /* @__PURE__ */ new Map(); + ws; + incomingMessageQueue = new Queue(); + queueRunning = false; + challenge; + authPromise; + serial = 0; + verifyEvent; + _WebSocket; + constructor(url, opts) { + this.url = normalizeURL(url); + this.verifyEvent = opts.verifyEvent; + this._WebSocket = opts.websocketImplementation || WebSocket; + this.enablePing = opts.enablePing; + } + static async connect(url, opts) { + const relay = new AbstractRelay(url, opts); + await relay.connect(); + return relay; + } + closeAllSubscriptions(reason) { + for (let [_, sub] of this.openSubs) { + sub.close(reason); + } + this.openSubs.clear(); + for (let [_, ep] of this.openEventPublishes) { + ep.reject(new Error(reason)); + } + this.openEventPublishes.clear(); + for (let [_, cr] of this.openCountRequests) { + cr.reject(new Error(reason)); + } + this.openCountRequests.clear(); + } + get connected() { + return this._connected; + } + async connect() { + if (this.connectionPromise) + return this.connectionPromise; + this.challenge = void 0; + this.authPromise = void 0; + this.connectionPromise = new Promise((resolve, reject) => { + this.connectionTimeoutHandle = setTimeout(() => { + reject("connection timed out"); + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection timed out"); + }, this.connectionTimeout); + try { + this.ws = new this._WebSocket(this.url); + } catch (err) { + clearTimeout(this.connectionTimeoutHandle); + reject(err); + return; + } + this.ws.onopen = () => { + clearTimeout(this.connectionTimeoutHandle); + this._connected = true; + if (this.enablePing) { + this.pingpong(); + } + resolve(); + }; + this.ws.onerror = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket error"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection errored"); + } + }; + this.ws.onclose = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket closed"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection closed"); + } + }; + this.ws.onmessage = this._onmessage.bind(this); + }); + return this.connectionPromise; + } + async waitForPingPong() { + return new Promise((res, err) => { + ; + this.ws && this.ws.on && this.ws.on("pong", () => res(true)) || err("ws can't listen for pong"); + this.ws && this.ws.ping && this.ws.ping(); + }); + } + async waitForDummyReq() { + return new Promise((resolve, _) => { + const sub = this.subscribe([{ ids: ["a".repeat(64)] }], { + oneose: () => { + sub.close(); + resolve(true); + }, + eoseTimeout: this.pingTimeout + 1e3 + }); + }); + } + async pingpong() { + if (this.ws?.readyState === 1) { + const result = await Promise.any([ + this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(), + new Promise((res) => setTimeout(() => res(false), this.pingTimeout)) + ]); + if (result) { + setTimeout(() => this.pingpong(), this.pingFrequency); + } else { + this.closeAllSubscriptions("pingpong timed out"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + } + } + async runQueue() { + this.queueRunning = true; + while (true) { + if (false === this.handleNext()) { + break; + } + await yieldThread(); + } + this.queueRunning = false; + } + handleNext() { + const json = this.incomingMessageQueue.dequeue(); + if (!json) { + return false; + } + const subid = getSubscriptionId(json); + if (subid) { + const so = this.openSubs.get(subid); + if (!so) { + return; + } + const id = getHex64(json, "id"); + const alreadyHave = so.alreadyHaveEvent?.(id); + so.receivedEvent?.(this, id); + if (alreadyHave) { + return; + } + } + try { + let data = JSON.parse(json); + switch (data[0]) { + case "EVENT": { + const so = this.openSubs.get(data[1]); + const event = data[2]; + if (this.verifyEvent(event) && matchFilters(so.filters, event)) { + so.onevent(event); + } + return; + } + case "COUNT": { + const id = data[1]; + const payload = data[2]; + const cr = this.openCountRequests.get(id); + if (cr) { + cr.resolve(payload.count); + this.openCountRequests.delete(id); + } + return; + } + case "EOSE": { + const so = this.openSubs.get(data[1]); + if (!so) + return; + so.receivedEose(); + return; + } + case "OK": { + const id = data[1]; + const ok = data[2]; + const reason = data[3]; + const ep = this.openEventPublishes.get(id); + if (ep) { + clearTimeout(ep.timeout); + if (ok) + ep.resolve(reason); + else + ep.reject(new Error(reason)); + this.openEventPublishes.delete(id); + } + return; + } + case "CLOSED": { + const id = data[1]; + const so = this.openSubs.get(id); + if (!so) + return; + so.closed = true; + so.close(data[2]); + return; + } + case "NOTICE": + this.onnotice(data[1]); + return; + case "AUTH": { + this.challenge = data[1]; + return; + } + } + } catch (err) { + return; + } + } + async send(message) { + if (!this.connectionPromise) + throw new SendingOnClosedConnection(message, this.url); + this.connectionPromise.then(() => { + this.ws?.send(message); + }); + } + async auth(signAuthEvent) { + const challenge = this.challenge; + if (!challenge) + throw new Error("can't perform auth, no challenge was received"); + if (this.authPromise) + return this.authPromise; + this.authPromise = new Promise(async (resolve, reject) => { + try { + let evt = await signAuthEvent(makeAuthEvent(this.url, challenge)); + let timeout = setTimeout(() => { + let ep = this.openEventPublishes.get(evt.id); + if (ep) { + ep.reject(new Error("auth timed out")); + this.openEventPublishes.delete(evt.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(evt.id, { resolve, reject, timeout }); + this.send('["AUTH",' + JSON.stringify(evt) + "]"); + } catch (err) { + console.warn("subscribe auth function failed:", err); + } + }); + return this.authPromise; + } + async publish(event) { + const ret = new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + const ep = this.openEventPublishes.get(event.id); + if (ep) { + ep.reject(new Error("publish timed out")); + this.openEventPublishes.delete(event.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(event.id, { resolve, reject, timeout }); + }); + this.send('["EVENT",' + JSON.stringify(event) + "]"); + return ret; + } + async count(filters, params) { + this.serial++; + const id = params?.id || "count:" + this.serial; + const ret = new Promise((resolve, reject) => { + this.openCountRequests.set(id, { resolve, reject }); + }); + this.send('["COUNT","' + id + '",' + JSON.stringify(filters).substring(1)); + return ret; + } + subscribe(filters, params) { + const subscription = this.prepareSubscription(filters, params); + subscription.fire(); + return subscription; + } + prepareSubscription(filters, params) { + this.serial++; + const id = params.id || (params.label ? params.label + ":" : "sub:") + this.serial; + const subscription = new Subscription(this, id, filters, params); + this.openSubs.set(id, subscription); + return subscription; + } + close() { + this.closeAllSubscriptions("relay connection closed by us"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + _onmessage(ev) { + this.incomingMessageQueue.enqueue(ev.data); + if (!this.queueRunning) { + this.runQueue(); + } + } +}; +var Subscription = class { + relay; + id; + closed = false; + eosed = false; + filters; + alreadyHaveEvent; + receivedEvent; + onevent; + oneose; + onclose; + eoseTimeout; + eoseTimeoutHandle; + constructor(relay, id, filters, params) { + this.relay = relay; + this.filters = filters; + this.id = id; + this.alreadyHaveEvent = params.alreadyHaveEvent; + this.receivedEvent = params.receivedEvent; + this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout; + this.oneose = params.oneose; + this.onclose = params.onclose; + this.onevent = params.onevent || ((event) => { + console.warn( + `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`, + event + ); + }); + } + fire() { + this.relay.send('["REQ","' + this.id + '",' + JSON.stringify(this.filters).substring(1)); + this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout); + } + receivedEose() { + if (this.eosed) + return; + clearTimeout(this.eoseTimeoutHandle); + this.eosed = true; + this.oneose?.(); + } + close(reason = "closed by caller") { + if (!this.closed && this.relay.connected) { + try { + this.relay.send('["CLOSE",' + JSON.stringify(this.id) + "]"); + } catch (err) { + if (err instanceof SendingOnClosedConnection) { + } else { + throw err; + } + } + this.closed = true; + } + this.relay.openSubs.delete(this.id); + this.onclose?.(reason); + } +}; + +// relay.ts +var _WebSocket; +try { + _WebSocket = WebSocket; +} catch { +} +function useWebSocketImplementation(websocketImplementation) { + _WebSocket = websocketImplementation; +} +var Relay = class extends AbstractRelay { + constructor(url) { + super(url, { verifyEvent, websocketImplementation: _WebSocket }); + } + static async connect(url) { + const relay = new Relay(url); + await relay.connect(); + return relay; + } +}; diff --git a/node_modules/nostr-tools/lib/cjs/relay.js.map b/node_modules/nostr-tools/lib/cjs/relay.js.map new file mode 100644 index 0000000..a1137e7 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/relay.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../relay.ts", "../../pure.ts", "../../core.ts", "../../utils.ts", "../../kinds.ts", "../../filter.ts", "../../fakejson.ts", "../../nip42.ts", "../../helpers.ts", "../../abstract-relay.ts"], + "sourcesContent": ["/* global WebSocket */\n\nimport { verifyEvent } from './pure.ts'\nimport { AbstractRelay } from './abstract-relay.ts'\n\nvar _WebSocket: typeof WebSocket\n\ntry {\n _WebSocket = WebSocket\n} catch {}\n\nexport function useWebSocketImplementation(websocketImplementation: any) {\n _WebSocket = websocketImplementation\n}\n\nexport class Relay extends AbstractRelay {\n constructor(url: string) {\n super(url, { verifyEvent, websocketImplementation: _WebSocket })\n }\n\n static async connect(url: string): Promise {\n const relay = new Relay(url)\n await relay.connect()\n return relay\n }\n}\n\nexport type RelayRecord = Record\n\nexport * from './abstract-relay.ts'\n", "import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { Event } from './core.ts'\nimport { isAddressableKind, isReplaceableKind } from './kinds.ts'\n\nexport type Filter = {\n ids?: string[]\n kinds?: number[]\n authors?: string[]\n since?: number\n until?: number\n limit?: number\n search?: string\n [key: `#${string}`]: string[] | undefined\n}\n\nexport function matchFilter(filter: Filter, event: Event): boolean {\n if (filter.ids && filter.ids.indexOf(event.id) === -1) {\n return false\n }\n if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) {\n return false\n }\n if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) {\n return false\n }\n\n for (let f in filter) {\n if (f[0] === '#') {\n let tagName = f.slice(1)\n let values = filter[`#${tagName}`]\n if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values!.indexOf(v) !== -1)) return false\n }\n }\n\n if (filter.since && event.created_at < filter.since) return false\n if (filter.until && event.created_at > filter.until) return false\n\n return true\n}\n\nexport function matchFilters(filters: Filter[], event: Event): boolean {\n for (let i = 0; i < filters.length; i++) {\n if (matchFilter(filters[i], event)) {\n return true\n }\n }\n return false\n}\n\nexport function mergeFilters(...filters: Filter[]): Filter {\n let result: Filter = {}\n for (let i = 0; i < filters.length; i++) {\n let filter = filters[i]\n Object.entries(filter).forEach(([property, values]) => {\n if (property === 'kinds' || property === 'ids' || property === 'authors' || property[0] === '#') {\n // @ts-ignore\n result[property] = result[property] || []\n // @ts-ignore\n for (let v = 0; v < values.length; v++) {\n // @ts-ignore\n let value = values[v]\n // @ts-ignore\n if (!result[property].includes(value)) result[property].push(value)\n }\n }\n })\n\n if (filter.limit && (!result.limit || filter.limit > result.limit)) result.limit = filter.limit\n if (filter.until && (!result.until || filter.until > result.until)) result.until = filter.until\n if (filter.since && (!result.since || filter.since < result.since)) result.since = filter.since\n }\n\n return result\n}\n\n/**\n * Calculate the intrinsic limit of a filter.\n * This function returns a positive integer, or `Infinity` if there is no intrinsic limit.\n */\nexport function getFilterLimit(filter: Filter): number {\n if (filter.ids && !filter.ids.length) return 0\n if (filter.kinds && !filter.kinds.length) return 0\n if (filter.authors && !filter.authors.length) return 0\n\n for (const [key, value] of Object.entries(filter)) {\n if (key[0] === '#' && Array.isArray(value) && !value.length) return 0\n }\n\n return Math.min(\n // The `limit` property creates an artificial limit.\n Math.max(0, filter.limit ?? Infinity),\n\n // There can only be one event per `id`.\n filter.ids?.length ?? Infinity,\n\n // Replaceable events are limited by the number of authors and kinds.\n filter.authors?.length && filter.kinds?.every(kind => isReplaceableKind(kind))\n ? filter.authors.length * filter.kinds.length\n : Infinity,\n\n // Parameterized replaceable events are limited by the number of authors, kinds, and \"d\" tags.\n filter.authors?.length && filter.kinds?.every(kind => isAddressableKind(kind)) && filter['#d']?.length\n ? filter.authors.length * filter.kinds.length * filter['#d'].length\n : Infinity,\n )\n}\n", "export function getHex64(json: string, field: string): string {\n let len = field.length + 3\n let idx = json.indexOf(`\"${field}\":`) + len\n let s = json.slice(idx).indexOf(`\"`) + idx + 1\n return json.slice(s, s + 64)\n}\n\nexport function getInt(json: string, field: string): number {\n let len = field.length\n let idx = json.indexOf(`\"${field}\":`) + len + 3\n let sliced = json.slice(idx)\n let end = Math.min(sliced.indexOf(','), sliced.indexOf('}'))\n return parseInt(sliced.slice(0, end), 10)\n}\n\nexport function getSubscriptionId(json: string): string | null {\n let idx = json.slice(0, 22).indexOf(`\"EVENT\"`)\n if (idx === -1) return null\n\n let pstart = json.slice(idx + 7 + 1).indexOf(`\"`)\n if (pstart === -1) return null\n let start = idx + 7 + 1 + pstart\n\n let pend = json.slice(start + 1, 80).indexOf(`\"`)\n if (pend === -1) return null\n let end = start + 1 + pend\n\n return json.slice(start + 1, end)\n}\n\nexport function matchEventId(json: string, id: string): boolean {\n return id === getHex64(json, 'id')\n}\n\nexport function matchEventPubkey(json: string, pubkey: string): boolean {\n return pubkey === getHex64(json, 'pubkey')\n}\n\nexport function matchEventKind(json: string, kind: number): boolean {\n return kind === getInt(json, 'kind')\n}\n", "import { EventTemplate } from './core.ts'\nimport { ClientAuth } from './kinds.ts'\n\n/**\n * creates an EventTemplate for an AUTH event to be signed.\n */\nexport function makeAuthEvent(relayURL: string, challenge: string): EventTemplate {\n return {\n kind: ClientAuth,\n created_at: Math.floor(Date.now() / 1000),\n tags: [\n ['relay', relayURL],\n ['challenge', challenge],\n ],\n content: '',\n }\n}\n", "import { verifiedSymbol, type Event, type Nostr, VerifiedEvent } from './core.ts'\n\nexport async function yieldThread() {\n return new Promise(resolve => {\n const ch = new MessageChannel()\n const handler = () => {\n // @ts-ignore (typescript thinks this property should be called `removeListener`, but in fact it's `removeEventListener`)\n ch.port1.removeEventListener('message', handler)\n resolve()\n }\n // @ts-ignore (typescript thinks this property should be called `addListener`, but in fact it's `addEventListener`)\n ch.port1.addEventListener('message', handler)\n ch.port2.postMessage(0)\n ch.port1.start()\n })\n}\n\nexport const alwaysTrue: Nostr['verifyEvent'] = (t: Event): t is VerifiedEvent => {\n t[verifiedSymbol] = true\n return true\n}\n", "/* global WebSocket */\n\nimport type { Event, EventTemplate, VerifiedEvent, Nostr, NostrEvent } from './core.ts'\nimport { matchFilters, type Filter } from './filter.ts'\nimport { getHex64, getSubscriptionId } from './fakejson.ts'\nimport { Queue, normalizeURL } from './utils.ts'\nimport { makeAuthEvent } from './nip42.ts'\nimport { yieldThread } from './helpers.ts'\n\ntype RelayWebSocket = WebSocket & {\n ping?(): void\n on?(event: 'pong', listener: () => void): any\n}\n\nexport type AbstractRelayConstructorOptions = {\n verifyEvent: Nostr['verifyEvent']\n websocketImplementation?: typeof WebSocket\n enablePing?: boolean\n}\n\nexport class SendingOnClosedConnection extends Error {\n constructor(message: string, relay: string) {\n super(`Tried to send message '${message} on a closed connection to ${relay}.`)\n this.name = 'SendingOnClosedConnection'\n }\n}\n\nexport class AbstractRelay {\n public readonly url: string\n private _connected: boolean = false\n\n public onclose: (() => void) | null = null\n public onnotice: (msg: string) => void = msg => console.debug(`NOTICE from ${this.url}: ${msg}`)\n\n public baseEoseTimeout: number = 4400\n public connectionTimeout: number = 4400\n public publishTimeout: number = 4400\n public pingFrequency: number = 20000\n public pingTimeout: number = 20000\n public openSubs: Map = new Map()\n public enablePing: boolean | undefined\n private connectionTimeoutHandle: ReturnType | undefined\n\n private connectionPromise: Promise | undefined\n private openCountRequests = new Map()\n private openEventPublishes = new Map()\n private ws: RelayWebSocket | undefined\n private incomingMessageQueue = new Queue()\n private queueRunning = false\n private challenge: string | undefined\n private authPromise: Promise | undefined\n private serial: number = 0\n private verifyEvent: Nostr['verifyEvent']\n\n private _WebSocket: typeof WebSocket\n\n constructor(url: string, opts: AbstractRelayConstructorOptions) {\n this.url = normalizeURL(url)\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation || WebSocket\n this.enablePing = opts.enablePing\n }\n\n static async connect(url: string, opts: AbstractRelayConstructorOptions): Promise {\n const relay = new AbstractRelay(url, opts)\n await relay.connect()\n return relay\n }\n\n private closeAllSubscriptions(reason: string) {\n for (let [_, sub] of this.openSubs) {\n sub.close(reason)\n }\n this.openSubs.clear()\n\n for (let [_, ep] of this.openEventPublishes) {\n ep.reject(new Error(reason))\n }\n this.openEventPublishes.clear()\n\n for (let [_, cr] of this.openCountRequests) {\n cr.reject(new Error(reason))\n }\n this.openCountRequests.clear()\n }\n\n public get connected(): boolean {\n return this._connected\n }\n\n public async connect(): Promise {\n if (this.connectionPromise) return this.connectionPromise\n\n this.challenge = undefined\n this.authPromise = undefined\n this.connectionPromise = new Promise((resolve, reject) => {\n this.connectionTimeoutHandle = setTimeout(() => {\n reject('connection timed out')\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection timed out')\n }, this.connectionTimeout)\n\n try {\n this.ws = new this._WebSocket(this.url)\n } catch (err) {\n clearTimeout(this.connectionTimeoutHandle)\n reject(err)\n return\n }\n\n this.ws.onopen = () => {\n clearTimeout(this.connectionTimeoutHandle)\n this._connected = true\n if (this.enablePing) {\n this.pingpong()\n }\n resolve()\n }\n\n this.ws.onerror = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket error')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection errored')\n }\n }\n\n this.ws.onclose = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket closed')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection closed')\n }\n }\n\n this.ws.onmessage = this._onmessage.bind(this)\n })\n\n return this.connectionPromise\n }\n\n private async waitForPingPong() {\n return new Promise((res, err) => {\n // listen for pong\n ;(this.ws && this.ws.on && this.ws.on('pong', () => res(true))) || err(\"ws can't listen for pong\")\n // send a ping\n this.ws && this.ws.ping && this.ws.ping()\n })\n }\n\n private async waitForDummyReq() {\n return new Promise((resolve, _) => {\n // make a dummy request with expected empty eose reply\n // [\"REQ\", \"_\", {\"ids\":[\"aaaa...aaaa\"]}]\n const sub = this.subscribe([{ ids: ['a'.repeat(64)] }], {\n oneose: () => {\n sub.close()\n resolve(true)\n },\n eoseTimeout: this.pingTimeout + 1000,\n })\n })\n }\n\n // nodejs requires this magic here to ensure connections are closed when internet goes off and stuff\n // in browsers it's done automatically. see https://github.com/nbd-wtf/nostr-tools/issues/491\n private async pingpong() {\n // if the websocket is connected\n if (this.ws?.readyState === 1) {\n // wait for either a ping-pong reply or a timeout\n const result = await Promise.any([\n // browsers don't have ping so use a dummy req\n this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(),\n new Promise(res => setTimeout(() => res(false), this.pingTimeout)),\n ])\n if (result) {\n // schedule another pingpong\n setTimeout(() => this.pingpong(), this.pingFrequency)\n } else {\n // pingpong closing socket\n this.closeAllSubscriptions('pingpong timed out')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n }\n }\n\n private async runQueue() {\n this.queueRunning = true\n while (true) {\n if (false === this.handleNext()) {\n break\n }\n await yieldThread()\n }\n this.queueRunning = false\n }\n\n private handleNext(): undefined | false {\n const json = this.incomingMessageQueue.dequeue()\n if (!json) {\n return false\n }\n\n const subid = getSubscriptionId(json)\n if (subid) {\n const so = this.openSubs.get(subid as string)\n if (!so) {\n // this is an EVENT message, but for a subscription we don't have, so just stop here\n return\n }\n\n // this will be called only when this message is a EVENT message for a subscription we have\n // we do this before parsing the JSON to not have to do that for duplicate events\n // since JSON parsing is slow\n const id = getHex64(json, 'id')\n const alreadyHave = so.alreadyHaveEvent?.(id)\n\n // notify any interested client that the relay has this event\n // (do this after alreadyHaveEvent() because the client may rely on this to answer that)\n so.receivedEvent?.(this, id)\n\n if (alreadyHave) {\n // if we had already seen this event we can just stop here\n return\n }\n }\n\n try {\n let data = JSON.parse(json)\n // we won't do any checks against the data since all failures (i.e. invalid messages from relays)\n // will naturally be caught by the encompassing try..catch block\n\n switch (data[0]) {\n case 'EVENT': {\n const so = this.openSubs.get(data[1] as string) as Subscription\n const event = data[2] as NostrEvent\n if (this.verifyEvent(event) && matchFilters(so.filters, event)) {\n so.onevent(event)\n }\n return\n }\n case 'COUNT': {\n const id: string = data[1]\n const payload = data[2] as { count: number }\n const cr = this.openCountRequests.get(id) as CountResolver\n if (cr) {\n cr.resolve(payload.count)\n this.openCountRequests.delete(id)\n }\n return\n }\n case 'EOSE': {\n const so = this.openSubs.get(data[1] as string)\n if (!so) return\n so.receivedEose()\n return\n }\n case 'OK': {\n const id: string = data[1]\n const ok: boolean = data[2]\n const reason: string = data[3]\n const ep = this.openEventPublishes.get(id) as EventPublishResolver\n if (ep) {\n clearTimeout(ep.timeout)\n if (ok) ep.resolve(reason)\n else ep.reject(new Error(reason))\n this.openEventPublishes.delete(id)\n }\n return\n }\n case 'CLOSED': {\n const id: string = data[1]\n const so = this.openSubs.get(id)\n if (!so) return\n so.closed = true\n so.close(data[2] as string)\n return\n }\n case 'NOTICE':\n this.onnotice(data[1] as string)\n return\n case 'AUTH': {\n this.challenge = data[1] as string\n return\n }\n }\n } catch (err) {\n return\n }\n }\n\n public async send(message: string) {\n if (!this.connectionPromise) throw new SendingOnClosedConnection(message, this.url)\n\n this.connectionPromise.then(() => {\n this.ws?.send(message)\n })\n }\n\n public async auth(signAuthEvent: (evt: EventTemplate) => Promise): Promise {\n const challenge = this.challenge\n if (!challenge) throw new Error(\"can't perform auth, no challenge was received\")\n if (this.authPromise) return this.authPromise\n\n this.authPromise = new Promise(async (resolve, reject) => {\n try {\n let evt = await signAuthEvent(makeAuthEvent(this.url, challenge))\n let timeout = setTimeout(() => {\n let ep = this.openEventPublishes.get(evt.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('auth timed out'))\n this.openEventPublishes.delete(evt.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(evt.id, { resolve, reject, timeout })\n this.send('[\"AUTH\",' + JSON.stringify(evt) + ']')\n } catch (err) {\n console.warn('subscribe auth function failed:', err)\n }\n })\n return this.authPromise\n }\n\n public async publish(event: Event): Promise {\n const ret = new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n const ep = this.openEventPublishes.get(event.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('publish timed out'))\n this.openEventPublishes.delete(event.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(event.id, { resolve, reject, timeout })\n })\n this.send('[\"EVENT\",' + JSON.stringify(event) + ']')\n return ret\n }\n\n public async count(filters: Filter[], params: { id?: string | null }): Promise {\n this.serial++\n const id = params?.id || 'count:' + this.serial\n const ret = new Promise((resolve, reject) => {\n this.openCountRequests.set(id, { resolve, reject })\n })\n this.send('[\"COUNT\",\"' + id + '\",' + JSON.stringify(filters).substring(1))\n return ret\n }\n\n public subscribe(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n const subscription = this.prepareSubscription(filters, params)\n subscription.fire()\n return subscription\n }\n\n public prepareSubscription(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n this.serial++\n const id = params.id || (params.label ? params.label + ':' : 'sub:') + this.serial\n const subscription = new Subscription(this, id, filters, params)\n this.openSubs.set(id, subscription)\n return subscription\n }\n\n public close() {\n this.closeAllSubscriptions('relay connection closed by us')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n\n // this is the function assigned to this.ws.onmessage\n // it's exposed for testing and debugging purposes\n public _onmessage(ev: MessageEvent) {\n this.incomingMessageQueue.enqueue(ev.data as string)\n if (!this.queueRunning) {\n this.runQueue()\n }\n }\n}\n\nexport class Subscription {\n public readonly relay: AbstractRelay\n public readonly id: string\n\n public closed: boolean = false\n public eosed: boolean = false\n public filters: Filter[]\n public alreadyHaveEvent: ((id: string) => boolean) | undefined\n public receivedEvent: ((relay: AbstractRelay, id: string) => void) | undefined\n\n public onevent: (evt: Event) => void\n public oneose: (() => void) | undefined\n public onclose: ((reason: string) => void) | undefined\n\n public eoseTimeout: number\n private eoseTimeoutHandle: ReturnType | undefined\n\n constructor(relay: AbstractRelay, id: string, filters: Filter[], params: SubscriptionParams) {\n this.relay = relay\n this.filters = filters\n this.id = id\n this.alreadyHaveEvent = params.alreadyHaveEvent\n this.receivedEvent = params.receivedEvent\n this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout\n\n this.oneose = params.oneose\n this.onclose = params.onclose\n this.onevent =\n params.onevent ||\n (event => {\n console.warn(\n `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,\n event,\n )\n })\n }\n\n public fire() {\n this.relay.send('[\"REQ\",\"' + this.id + '\",' + JSON.stringify(this.filters).substring(1))\n\n // only now we start counting the eoseTimeout\n this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout)\n }\n\n public receivedEose() {\n if (this.eosed) return\n clearTimeout(this.eoseTimeoutHandle)\n this.eosed = true\n this.oneose?.()\n }\n\n public close(reason: string = 'closed by caller') {\n if (!this.closed && this.relay.connected) {\n // if the connection was closed by the user calling .close() we will send a CLOSE message\n // otherwise this._open will be already set to false so we will skip this\n try {\n this.relay.send('[\"CLOSE\",' + JSON.stringify(this.id) + ']')\n } catch (err) {\n if (err instanceof SendingOnClosedConnection) {\n /* doesn't matter, it's ok */\n } else {\n throw err\n }\n }\n this.closed = true\n }\n this.relay.openSubs.delete(this.id)\n this.onclose?.(reason)\n }\n}\n\nexport type SubscriptionParams = {\n onevent?: (evt: Event) => void\n oneose?: () => void\n onclose?: (reason: string) => void\n alreadyHaveEvent?: (id: string) => boolean\n receivedEvent?: (relay: AbstractRelay, id: string) => void\n eoseTimeout?: number\n}\n\nexport type CountResolver = {\n resolve: (count: number) => void\n reject: (err: Error) => void\n}\n\nexport type EventPublishResolver = {\n resolve: (reason: string) => void\n reject: (err: Error) => void\n timeout: ReturnType\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,uBAAwB;AACxB,IAAAA,gBAA2B;;;ACOpB,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,CAAC,QAAiD,eAAe;AAE3E,SAAS,cAAiB,OAAsC;AACrE,MAAI,CAAC,SAAS,KAAK;AAAG,WAAO;AAC7B,MAAI,OAAO,MAAM,SAAS;AAAU,WAAO;AAC3C,MAAI,OAAO,MAAM,YAAY;AAAU,WAAO;AAC9C,MAAI,OAAO,MAAM,eAAe;AAAU,WAAO;AACjD,MAAI,OAAO,MAAM,WAAW;AAAU,WAAO;AAC7C,MAAI,CAAC,MAAM,OAAO,MAAM,gBAAgB;AAAG,WAAO;AAElD,MAAI,CAAC,MAAM,QAAQ,MAAM,IAAI;AAAG,WAAO;AACvC,WAASC,KAAI,GAAGA,KAAI,MAAM,KAAK,QAAQA,MAAK;AAC1C,QAAI,MAAM,MAAM,KAAKA;AACrB,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K,MAAM,KAAK,aAAa,KAAK,KAAK,OAAO,KAAK,UAAU,KAAK,OAAO,EAAE,UAAU,CAAC,CAAC;AAGvF,SAAK,oBAAoB,WAAW,KAAK,aAAa,KAAK,IAAI,GAAG,KAAK,WAAW;AAAA,EACpF;AAAA,EAEO,eAAe;AACpB,QAAI,KAAK;AAAO;AAChB,iBAAa,KAAK,iBAAiB;AACnC,SAAK,QAAQ;AACb,SAAK,SAAS;AAAA,EAChB;AAAA,EAEO,MAAM,SAAiB,oBAAoB;AAChD,QAAI,CAAC,KAAK,UAAU,KAAK,MAAM,WAAW;AAGxC,UAAI;AACF,aAAK,MAAM,KAAK,cAAc,KAAK,UAAU,KAAK,EAAE,IAAI,GAAG;AAAA,MAC7D,SAAS,KAAP;AACA,YAAI,eAAe,2BAA2B;AAAA,QAE9C,OAAO;AACL,gBAAM;AAAA,QACR;AAAA,MACF;AACA,WAAK,SAAS;AAAA,IAChB;AACA,SAAK,MAAM,SAAS,OAAO,KAAK,EAAE;AAClC,SAAK,UAAU,MAAM;AAAA,EACvB;AACF;;;AT1cA,IAAI;AAEJ,IAAI;AACF,eAAa;AACf,QAAE;AAAO;AAEF,SAAS,2BAA2B,yBAA8B;AACvE,eAAa;AACf;AAEO,IAAM,QAAN,cAAoB,cAAc;AAAA,EACvC,YAAY,KAAa;AACvB,UAAM,KAAK,EAAE,aAAa,yBAAyB,WAAW,CAAC;AAAA,EACjE;AAAA,EAEA,aAAa,QAAQ,KAA6B;AAChD,UAAM,QAAQ,IAAI,MAAM,GAAG;AAC3B,UAAM,MAAM,QAAQ;AACpB,WAAO;AAAA,EACT;AACF;", + "names": ["import_utils", "i", "target", "i"] +} diff --git a/node_modules/nostr-tools/lib/cjs/signer.js b/node_modules/nostr-tools/lib/cjs/signer.js new file mode 100644 index 0000000..75d043b --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/signer.js @@ -0,0 +1,130 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// signer.ts +var signer_exports = {}; +__export(signer_exports, { + PlainKeySigner: () => PlainKeySigner +}); +module.exports = __toCommonJS(signer_exports); + +// pure.ts +var import_secp256k1 = require("@noble/curves/secp256k1"); +var import_utils2 = require("@noble/hashes/utils"); + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +var import_sha256 = require("@noble/hashes/sha256"); + +// utils.ts +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// pure.ts +var JS = class { + generateSecretKey() { + return import_secp256k1.schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = import_secp256k1.schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = (0, import_sha256.sha256)(utf8Encoder.encode(serializeEvent(event))); + return (0, import_utils2.bytesToHex)(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// signer.ts +var PlainKeySigner = class { + secretKey; + constructor(secretKey) { + this.secretKey = secretKey; + } + async getPublicKey() { + return getPublicKey(this.secretKey); + } + async signEvent(event) { + return finalizeEvent(event, this.secretKey); + } +}; diff --git a/node_modules/nostr-tools/lib/cjs/signer.js.map b/node_modules/nostr-tools/lib/cjs/signer.js.map new file mode 100644 index 0000000..1c58390 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/signer.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../signer.ts", "../../pure.ts", "../../core.ts", "../../utils.ts"], + "sourcesContent": ["import { EventTemplate, VerifiedEvent } from './core.ts'\nimport { finalizeEvent, getPublicKey } from './pure.ts'\n\nexport interface Signer {\n getPublicKey(): Promise\n signEvent(event: EventTemplate): Promise\n}\n\nexport class PlainKeySigner implements Signer {\n private secretKey: Uint8Array\n\n constructor(secretKey: Uint8Array) {\n this.secretKey = secretKey\n }\n\n async getPublicKey(): Promise {\n return getPublicKey(this.secretKey)\n }\n\n async signEvent(event: EventTemplate): Promise {\n return finalizeEvent(event, this.secretKey)\n }\n}\n", "import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,uBAAwB;AACxB,IAAAA,gBAA2B;;;ACOpB,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,CAAC,QAAiD,eAAe;AAE3E,SAAS,cAAiB,OAAsC;AACrE,MAAI,CAAC,SAAS,KAAK;AAAG,WAAO;AAC7B,MAAI,OAAO,MAAM,SAAS;AAAU,WAAO;AAC3C,MAAI,OAAO,MAAM,YAAY;AAAU,WAAO;AAC9C,MAAI,OAAO,MAAM,eAAe;AAAU,WAAO;AACjD,MAAI,OAAO,MAAM,WAAW;AAAU,WAAO;AAC7C,MAAI,CAAC,MAAM,OAAO,MAAM,gBAAgB;AAAG,WAAO;AAElD,MAAI,CAAC,MAAM,QAAQ,MAAM,IAAI;AAAG,WAAO;AACvC,WAASC,KAAI,GAAGA,KAAI,MAAM,KAAK,QAAQA,MAAK;AAC1C,QAAI,MAAM,MAAM,KAAKA;AACrB,QAAI,CAAC,MAAM,QAAQ,GAAG;AAAG,aAAO;AAChC,aAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,UAAI,OAAO,IAAI,OAAO;AAAU,eAAO;AAAA,IACzC;AAAA,EACF;AAEA,SAAO;AACT;;;AD/CA,oBAAuB;;;AEEvB,mBAAuC;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;;;AFIxD,IAAM,KAAN,MAA0B;AAAA,EACxB,oBAAgC;AAC9B,WAAO,yBAAQ,MAAM,iBAAiB;AAAA,EACxC;AAAA,EACA,aAAa,WAA+B;AAC1C,eAAO,0BAAW,yBAAQ,aAAa,SAAS,CAAC;AA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A,EACpC;AAAA,EAEA,MAAM,UAAU,OAA8C;AAC5D,WAAO,cAAc,OAAO,KAAK,SAAS;AAAA,EAC5C;AACF;", + "names": ["import_utils", "i"] +} diff --git a/node_modules/nostr-tools/lib/cjs/utils.js b/node_modules/nostr-tools/lib/cjs/utils.js new file mode 100644 index 0000000..a7bf202 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/utils.js @@ -0,0 +1,145 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// utils.ts +var utils_exports = {}; +__export(utils_exports, { + Queue: () => Queue, + QueueNode: () => QueueNode, + binarySearch: () => binarySearch, + bytesToHex: () => import_utils.bytesToHex, + hexToBytes: () => import_utils.hexToBytes, + insertEventIntoAscendingList: () => insertEventIntoAscendingList, + insertEventIntoDescendingList: () => insertEventIntoDescendingList, + normalizeURL: () => normalizeURL, + utf8Decoder: () => utf8Decoder, + utf8Encoder: () => utf8Encoder +}); +module.exports = __toCommonJS(utils_exports); +var import_utils = require("@noble/hashes/utils"); +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); +function normalizeURL(url) { + try { + if (url.indexOf("://") === -1) + url = "wss://" + url; + let p = new URL(url); + p.pathname = p.pathname.replace(/\/+/g, "/"); + if (p.pathname.endsWith("/")) + p.pathname = p.pathname.slice(0, -1); + if (p.port === "80" && p.protocol === "ws:" || p.port === "443" && p.protocol === "wss:") + p.port = ""; + p.searchParams.sort(); + p.hash = ""; + return p.toString(); + } catch (e) { + throw new Error(`Invalid URL: ${url}`); + } +} +function insertEventIntoDescendingList(sortedArray, event) { + const [idx, found] = binarySearch(sortedArray, (b) => { + if (event.id === b.id) + return 0; + if (event.created_at === b.created_at) + return -1; + return b.created_at - event.created_at; + }); + if (!found) { + sortedArray.splice(idx, 0, event); + } + return sortedArray; +} +function insertEventIntoAscendingList(sortedArray, event) { + const [idx, found] = binarySearch(sortedArray, (b) => { + if (event.id === b.id) + return 0; + if (event.created_at === b.created_at) + return -1; + return event.created_at - b.created_at; + }); + if (!found) { + sortedArray.splice(idx, 0, event); + } + return sortedArray; +} +function binarySearch(arr, compare) { + let start = 0; + let end = arr.length - 1; + while (start <= end) { + const mid = Math.floor((start + end) / 2); + const cmp = compare(arr[mid]); + if (cmp === 0) { + return [mid, true]; + } + if (cmp < 0) { + end = mid - 1; + } else { + start = mid + 1; + } + } + return [start, false]; +} +var QueueNode = class { + value; + next = null; + prev = null; + constructor(message) { + this.value = message; + } +}; +var Queue = class { + first; + last; + constructor() { + this.first = null; + this.last = null; + } + enqueue(value) { + const newNode = new QueueNode(value); + if (!this.last) { + this.first = newNode; + this.last = newNode; + } else if (this.last === this.first) { + this.last = newNode; + this.last.prev = this.first; + this.first.next = newNode; + } else { + newNode.prev = this.last; + this.last.next = newNode; + this.last = newNode; + } + return true; + } + dequeue() { + if (!this.first) + return null; + if (this.first === this.last) { + const target2 = this.first; + this.first = null; + this.last = null; + return target2.value; + } + const target = this.first; + this.first = target.next; + if (this.first) { + this.first.prev = null; + } + return target.value; + } +}; diff --git a/node_modules/nostr-tools/lib/cjs/utils.js.map b/node_modules/nostr-tools/lib/cjs/utils.js.map new file mode 100644 index 0000000..6b93206 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/utils.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../utils.ts"], + "sourcesContent": ["import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,mBAAuC;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;AAIjD,SAAS,aAAa,KAAqB;AAChD,MAAI;AACF,QAAI,IAAI,QAAQ,KAAK,MAAM;AAAI,YAAM,WAAW;AAChD,QAAI,IAAI,IAAI,IAAI,GAAG;AACnB,MAAE,WAAW,EAAE,SAAS,QAAQ,QAAQ,GAAG;AAC3C,QAAI,EAAE,SAAS,SAAS,GAAG;AAAG,QAAE,WAAW,EAAE,SAAS,MAAM,GAAG,EAAE;AACjE,QAAK,EAAE,SAAS,QAAQ,EAAE,aAAa,SAAW,EAAE,SAAS,SAAS,EAAE,aAAa;AAAS,QAAE,OAAO;AACvG,MAAE,aAAa,KAAK;AACpB,MAAE,OAAO;AACT,WAAO,EAAE,SAAS;AAAA,EACpB,SAAS,GAAP;AACA,UAAM,IAAI,MAAM,gBAAgB,KAAK;AAAA,EACvC;AACF;AAEO,SAAS,8BAA8B,aAAsB,OAAuB;AACzF,QAAM,CAAC,KAAK,KAAK,IAAI,aAAa,aAAa,OAAK;AAClD,QAAI,MAAM,OAAO,EAAE;AAAI,aAAO;AAC9B,QAAI,MAAM,eAAe,EAAE;AAAY,aAAO;AAC9C,W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K,SAAS,KAAK,OAAO;AAEnC,WAAK,OAAO;AACZ,WAAK,KAAK,OAAO,KAAK;AACtB,WAAK,MAAM,OAAO;AAAA,IACpB,OAAO;AAEL,cAAQ,OAAO,KAAK;AACpB,WAAK,KAAK,OAAO;AACjB,WAAK,OAAO;AAAA,IACd;AACA,WAAO;AAAA,EACT;AAAA,EAEA,UAAoB;AAClB,QAAI,CAAC,KAAK;AAAO,aAAO;AAExB,QAAI,KAAK,UAAU,KAAK,MAAM;AAC5B,YAAMA,UAAS,KAAK;AACpB,WAAK,QAAQ;AACb,WAAK,OAAO;AACZ,aAAOA,QAAO;AAAA,IAChB;AAEA,UAAM,SAAS,KAAK;AACpB,SAAK,QAAQ,OAAO;AACpB,QAAI,KAAK,OAAO;AACd,WAAK,MAAM,OAAO;AAAA,IACpB;AAEA,WAAO,OAAO;AAAA,EAChB;AACF;", + "names": ["target"] +} diff --git a/node_modules/nostr-tools/lib/cjs/wasm.js b/node_modules/nostr-tools/lib/cjs/wasm.js new file mode 100644 index 0000000..a8ded70 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/wasm.js @@ -0,0 +1,103 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// wasm.ts +var wasm_exports = {}; +__export(wasm_exports, { + finalizeEvent: () => finalizeEvent, + generateSecretKey: () => generateSecretKey, + getPublicKey: () => getPublicKey, + setNostrWasm: () => setNostrWasm, + sortEvents: () => sortEvents, + validateEvent: () => validateEvent, + verifiedSymbol: () => verifiedSymbol, + verifyEvent: () => verifyEvent +}); +module.exports = __toCommonJS(wasm_exports); +var import_utils = require("@noble/hashes/utils"); + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} +function sortEvents(events) { + return events.sort((a, b) => { + if (a.created_at !== b.created_at) { + return b.created_at - a.created_at; + } + return a.id.localeCompare(b.id); + }); +} + +// wasm.ts +var nw; +function setNostrWasm(x) { + nw = x; +} +var Wasm = class { + generateSecretKey() { + return nw.generateSecretKey(); + } + getPublicKey(secretKey) { + return (0, import_utils.bytesToHex)(nw.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + nw.finalizeEvent(t, secretKey); + return t; + } + verifyEvent(event) { + try { + nw.verifyEvent(event); + event[verifiedSymbol] = true; + return true; + } catch (err) { + return false; + } + } +}; +var i = new Wasm(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; diff --git a/node_modules/nostr-tools/lib/cjs/wasm.js.map b/node_modules/nostr-tools/lib/cjs/wasm.js.map new file mode 100644 index 0000000..7b5d904 --- /dev/null +++ b/node_modules/nostr-tools/lib/cjs/wasm.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../wasm.ts", "../../core.ts"], + "sourcesContent": ["import { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr as NostrWasm } from 'nostr-wasm'\nimport { EventTemplate, Event, Nostr, VerifiedEvent, verifiedSymbol } from './core.ts'\n\nlet nw: NostrWasm\n\nexport function setNostrWasm(x: NostrWasm) {\n nw = x\n}\n\nclass Wasm implements Nostr {\n generateSecretKey(): Uint8Array {\n return nw.generateSecretKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(nw.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n nw.finalizeEvent(t as any, secretKey)\n return t as VerifiedEvent\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n try {\n nw.verifyEvent(event)\n event[verifiedSymbol] = true\n return true\n } catch (err) {\n return false\n }\n }\n}\n\nconst i: Wasm = new Wasm()\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAA2B;;;ACQpB,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,CAAC,QAAiD,eAAe;AAE3E,SAAS,cAAiB,OAAsC;AACrE,MAAI,CAAC,SAAS,KAAK;AAAG,WAAO;AAC7B,MAAI,OAAO,MAAM,SAAS;AAAU,WAAO;AAC3C,MAAI,OAAO,MAAM,YAAY;AAAU,WAAO;AAC9C,MAAI,OAAO,MAAM,eAAe;AAAU,WAAO;AACjD,MAAI,OAAO,MAAM,WAAW;AAAU,WAAO;AAC7C,MAAI,CAAC,MAAM,OAAO,MAAM,gBAAgB;AAAG,WAAO;AAElD,MAAI,CAAC,MAAM,QAAQ,MAAM,IAAI;AAAG,WAAO;AACvC,WAASA,KAAI,GAAGA,KAAI,MAAM,KAAK,QAAQA,MAAK;AAC1C,QAAI,MAAM,MAAM,KAAKA;AACrB,QAAI,CAAC,MAAM,QAAQ,GAAG;AAAG,aAAO;AAChC,aAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,UAAI,OAAO,IAAI,OAAO;AAAU,eAAO;AAAA,IACzC;AAAA,EACF;AAEA,SAAO;AACT;AAOO,SAAS,WAAW,QAA0B;AACnD,SAAO,OAAO,KAAK,CAAC,GAAe,MAA0B;AAC3D,QAAI,EAAE,eAAe,EAAE,YAAY;AACjC,aAAO,EAAE,aAAa,EAAE;AAAA,IAC1B;AACA,WAAO,EAAE,GAAG,cAAc,EAAE,EAAE;AAAA,EAChC,CAAC;AACH;;;AD5DA,IAAI;AAEG,SAAS,aAAa,GAAc;AACzC,OAAK;AACP;AAEA,IAAM,OAAN,MAA4B;AAAA,EAC1B,oBAAgC;AAC9B,WAAO,GAAG,kBAAkB;AAAA,EAC9B;AAAA,EACA,aAAa,WAA+B;AAC1C,eAAO,yBAAW,GAAG,aAAa,SAAS,CAAC;AAAA,EAC9C;AAAA,EACA,cAAc,GAAkB,WAAsC;AACpE,OAAG,cAAc,GAAU,SAAS;AACpC,WAAO;AAAA,EACT;AAAA,EACA,YAAY,OAAsC;AAChD,QAAI;AACF,SAAG,YAAY,KAAK;AACpB,YAAM,kBAAkB;AACxB,aAAO;AAAA,IACT,SAAS,KAAP;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAEA,IAAM,IAAU,IAAI,KAAK;AAClB,IAAM,oBAAoB,EAAE;AAC5B,IAAM,eAAe,EAAE;AACvB,IAAM,gBAAgB,EAAE;AACxB,IAAM,cAAc,EAAE;", + "names": ["i"] +} diff --git a/node_modules/nostr-tools/lib/esm/abstract-pool.js b/node_modules/nostr-tools/lib/esm/abstract-pool.js new file mode 100644 index 0000000..480f1f9 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/abstract-pool.js @@ -0,0 +1,770 @@ +// core.ts +var verifiedSymbol = Symbol("verified"); + +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); +function normalizeURL(url) { + try { + if (url.indexOf("://") === -1) + url = "wss://" + url; + let p = new URL(url); + p.pathname = p.pathname.replace(/\/+/g, "/"); + if (p.pathname.endsWith("/")) + p.pathname = p.pathname.slice(0, -1); + if (p.port === "80" && p.protocol === "ws:" || p.port === "443" && p.protocol === "wss:") + p.port = ""; + p.searchParams.sort(); + p.hash = ""; + return p.toString(); + } catch (e) { + throw new Error(`Invalid URL: ${url}`); + } +} +var QueueNode = class { + value; + next = null; + prev = null; + constructor(message) { + this.value = message; + } +}; +var Queue = class { + first; + last; + constructor() { + this.first = null; + this.last = null; + } + enqueue(value) { + const newNode = new QueueNode(value); + if (!this.last) { + this.first = newNode; + this.last = newNode; + } else if (this.last === this.first) { + this.last = newNode; + this.last.prev = this.first; + this.first.next = newNode; + } else { + newNode.prev = this.last; + this.last.next = newNode; + this.last = newNode; + } + return true; + } + dequeue() { + if (!this.first) + return null; + if (this.first === this.last) { + const target2 = this.first; + this.first = null; + this.last = null; + return target2.value; + } + const target = this.first; + this.first = target.next; + if (this.first) { + this.first.prev = null; + } + return target.value; + } +}; + +// kinds.ts +var ClientAuth = 22242; + +// filter.ts +function matchFilter(filter, event) { + if (filter.ids && filter.ids.indexOf(event.id) === -1) { + return false; + } + if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) { + return false; + } + if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) { + return false; + } + for (let f in filter) { + if (f[0] === "#") { + let tagName = f.slice(1); + let values = filter[`#${tagName}`]; + if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values.indexOf(v) !== -1)) + return false; + } + } + if (filter.since && event.created_at < filter.since) + return false; + if (filter.until && event.created_at > filter.until) + return false; + return true; +} +function matchFilters(filters, event) { + for (let i = 0; i < filters.length; i++) { + if (matchFilter(filters[i], event)) { + return true; + } + } + return false; +} + +// fakejson.ts +function getHex64(json, field) { + let len = field.length + 3; + let idx = json.indexOf(`"${field}":`) + len; + let s = json.slice(idx).indexOf(`"`) + idx + 1; + return json.slice(s, s + 64); +} +function getSubscriptionId(json) { + let idx = json.slice(0, 22).indexOf(`"EVENT"`); + if (idx === -1) + return null; + let pstart = json.slice(idx + 7 + 1).indexOf(`"`); + if (pstart === -1) + return null; + let start = idx + 7 + 1 + pstart; + let pend = json.slice(start + 1, 80).indexOf(`"`); + if (pend === -1) + return null; + let end = start + 1 + pend; + return json.slice(start + 1, end); +} + +// nip42.ts +function makeAuthEvent(relayURL, challenge) { + return { + kind: ClientAuth, + created_at: Math.floor(Date.now() / 1e3), + tags: [ + ["relay", relayURL], + ["challenge", challenge] + ], + content: "" + }; +} + +// helpers.ts +async function yieldThread() { + return new Promise((resolve) => { + const ch = new MessageChannel(); + const handler = () => { + ch.port1.removeEventListener("message", handler); + resolve(); + }; + ch.port1.addEventListener("message", handler); + ch.port2.postMessage(0); + ch.port1.start(); + }); +} +var alwaysTrue = (t) => { + t[verifiedSymbol] = true; + return true; +}; + +// abstract-relay.ts +var SendingOnClosedConnection = class extends Error { + constructor(message, relay) { + super(`Tried to send message '${message} on a closed connection to ${relay}.`); + this.name = "SendingOnClosedConnection"; + } +}; +var AbstractRelay = class { + url; + _connected = false; + onclose = null; + onnotice = (msg) => console.debug(`NOTICE from ${this.url}: ${msg}`); + baseEoseTimeout = 4400; + connectionTimeout = 4400; + publishTimeout = 4400; + pingFrequency = 2e4; + pingTimeout = 2e4; + openSubs = /* @__PURE__ */ new Map(); + enablePing; + connectionTimeoutHandle; + connectionPromise; + openCountRequests = /* @__PURE__ */ new Map(); + openEventPublishes = /* @__PURE__ */ new Map(); + ws; + incomingMessageQueue = new Queue(); + queueRunning = false; + challenge; + authPromise; + serial = 0; + verifyEvent; + _WebSocket; + constructor(url, opts) { + this.url = normalizeURL(url); + this.verifyEvent = opts.verifyEvent; + this._WebSocket = opts.websocketImplementation || WebSocket; + this.enablePing = opts.enablePing; + } + static async connect(url, opts) { + const relay = new AbstractRelay(url, opts); + await relay.connect(); + return relay; + } + closeAllSubscriptions(reason) { + for (let [_, sub] of this.openSubs) { + sub.close(reason); + } + this.openSubs.clear(); + for (let [_, ep] of this.openEventPublishes) { + ep.reject(new Error(reason)); + } + this.openEventPublishes.clear(); + for (let [_, cr] of this.openCountRequests) { + cr.reject(new Error(reason)); + } + this.openCountRequests.clear(); + } + get connected() { + return this._connected; + } + async connect() { + if (this.connectionPromise) + return this.connectionPromise; + this.challenge = void 0; + this.authPromise = void 0; + this.connectionPromise = new Promise((resolve, reject) => { + this.connectionTimeoutHandle = setTimeout(() => { + reject("connection timed out"); + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection timed out"); + }, this.connectionTimeout); + try { + this.ws = new this._WebSocket(this.url); + } catch (err) { + clearTimeout(this.connectionTimeoutHandle); + reject(err); + return; + } + this.ws.onopen = () => { + clearTimeout(this.connectionTimeoutHandle); + this._connected = true; + if (this.enablePing) { + this.pingpong(); + } + resolve(); + }; + this.ws.onerror = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket error"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection errored"); + } + }; + this.ws.onclose = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket closed"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection closed"); + } + }; + this.ws.onmessage = this._onmessage.bind(this); + }); + return this.connectionPromise; + } + async waitForPingPong() { + return new Promise((res, err) => { + ; + this.ws && this.ws.on && this.ws.on("pong", () => res(true)) || err("ws can't listen for pong"); + this.ws && this.ws.ping && this.ws.ping(); + }); + } + async waitForDummyReq() { + return new Promise((resolve, _) => { + const sub = this.subscribe([{ ids: ["a".repeat(64)] }], { + oneose: () => { + sub.close(); + resolve(true); + }, + eoseTimeout: this.pingTimeout + 1e3 + }); + }); + } + async pingpong() { + if (this.ws?.readyState === 1) { + const result = await Promise.any([ + this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(), + new Promise((res) => setTimeout(() => res(false), this.pingTimeout)) + ]); + if (result) { + setTimeout(() => this.pingpong(), this.pingFrequency); + } else { + this.closeAllSubscriptions("pingpong timed out"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + } + } + async runQueue() { + this.queueRunning = true; + while (true) { + if (false === this.handleNext()) { + break; + } + await yieldThread(); + } + this.queueRunning = false; + } + handleNext() { + const json = this.incomingMessageQueue.dequeue(); + if (!json) { + return false; + } + const subid = getSubscriptionId(json); + if (subid) { + const so = this.openSubs.get(subid); + if (!so) { + return; + } + const id = getHex64(json, "id"); + const alreadyHave = so.alreadyHaveEvent?.(id); + so.receivedEvent?.(this, id); + if (alreadyHave) { + return; + } + } + try { + let data = JSON.parse(json); + switch (data[0]) { + case "EVENT": { + const so = this.openSubs.get(data[1]); + const event = data[2]; + if (this.verifyEvent(event) && matchFilters(so.filters, event)) { + so.onevent(event); + } + return; + } + case "COUNT": { + const id = data[1]; + const payload = data[2]; + const cr = this.openCountRequests.get(id); + if (cr) { + cr.resolve(payload.count); + this.openCountRequests.delete(id); + } + return; + } + case "EOSE": { + const so = this.openSubs.get(data[1]); + if (!so) + return; + so.receivedEose(); + return; + } + case "OK": { + const id = data[1]; + const ok = data[2]; + const reason = data[3]; + const ep = this.openEventPublishes.get(id); + if (ep) { + clearTimeout(ep.timeout); + if (ok) + ep.resolve(reason); + else + ep.reject(new Error(reason)); + this.openEventPublishes.delete(id); + } + return; + } + case "CLOSED": { + const id = data[1]; + const so = this.openSubs.get(id); + if (!so) + return; + so.closed = true; + so.close(data[2]); + return; + } + case "NOTICE": + this.onnotice(data[1]); + return; + case "AUTH": { + this.challenge = data[1]; + return; + } + } + } catch (err) { + return; + } + } + async send(message) { + if (!this.connectionPromise) + throw new SendingOnClosedConnection(message, this.url); + this.connectionPromise.then(() => { + this.ws?.send(message); + }); + } + async auth(signAuthEvent) { + const challenge = this.challenge; + if (!challenge) + throw new Error("can't perform auth, no challenge was received"); + if (this.authPromise) + return this.authPromise; + this.authPromise = new Promise(async (resolve, reject) => { + try { + let evt = await signAuthEvent(makeAuthEvent(this.url, challenge)); + let timeout = setTimeout(() => { + let ep = this.openEventPublishes.get(evt.id); + if (ep) { + ep.reject(new Error("auth timed out")); + this.openEventPublishes.delete(evt.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(evt.id, { resolve, reject, timeout }); + this.send('["AUTH",' + JSON.stringify(evt) + "]"); + } catch (err) { + console.warn("subscribe auth function failed:", err); + } + }); + return this.authPromise; + } + async publish(event) { + const ret = new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + const ep = this.openEventPublishes.get(event.id); + if (ep) { + ep.reject(new Error("publish timed out")); + this.openEventPublishes.delete(event.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(event.id, { resolve, reject, timeout }); + }); + this.send('["EVENT",' + JSON.stringify(event) + "]"); + return ret; + } + async count(filters, params) { + this.serial++; + const id = params?.id || "count:" + this.serial; + const ret = new Promise((resolve, reject) => { + this.openCountRequests.set(id, { resolve, reject }); + }); + this.send('["COUNT","' + id + '",' + JSON.stringify(filters).substring(1)); + return ret; + } + subscribe(filters, params) { + const subscription = this.prepareSubscription(filters, params); + subscription.fire(); + return subscription; + } + prepareSubscription(filters, params) { + this.serial++; + const id = params.id || (params.label ? params.label + ":" : "sub:") + this.serial; + const subscription = new Subscription(this, id, filters, params); + this.openSubs.set(id, subscription); + return subscription; + } + close() { + this.closeAllSubscriptions("relay connection closed by us"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + _onmessage(ev) { + this.incomingMessageQueue.enqueue(ev.data); + if (!this.queueRunning) { + this.runQueue(); + } + } +}; +var Subscription = class { + relay; + id; + closed = false; + eosed = false; + filters; + alreadyHaveEvent; + receivedEvent; + onevent; + oneose; + onclose; + eoseTimeout; + eoseTimeoutHandle; + constructor(relay, id, filters, params) { + this.relay = relay; + this.filters = filters; + this.id = id; + this.alreadyHaveEvent = params.alreadyHaveEvent; + this.receivedEvent = params.receivedEvent; + this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout; + this.oneose = params.oneose; + this.onclose = params.onclose; + this.onevent = params.onevent || ((event) => { + console.warn( + `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`, + event + ); + }); + } + fire() { + this.relay.send('["REQ","' + this.id + '",' + JSON.stringify(this.filters).substring(1)); + this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout); + } + receivedEose() { + if (this.eosed) + return; + clearTimeout(this.eoseTimeoutHandle); + this.eosed = true; + this.oneose?.(); + } + close(reason = "closed by caller") { + if (!this.closed && this.relay.connected) { + try { + this.relay.send('["CLOSE",' + JSON.stringify(this.id) + "]"); + } catch (err) { + if (err instanceof SendingOnClosedConnection) { + } else { + throw err; + } + } + this.closed = true; + } + this.relay.openSubs.delete(this.id); + this.onclose?.(reason); + } +}; + +// abstract-pool.ts +var AbstractSimplePool = class { + relays = /* @__PURE__ */ new Map(); + seenOn = /* @__PURE__ */ new Map(); + trackRelays = false; + verifyEvent; + enablePing; + trustedRelayURLs = /* @__PURE__ */ new Set(); + _WebSocket; + constructor(opts) { + this.verifyEvent = opts.verifyEvent; + this._WebSocket = opts.websocketImplementation; + this.enablePing = opts.enablePing; + } + async ensureRelay(url, params) { + url = normalizeURL(url); + let relay = this.relays.get(url); + if (!relay) { + relay = new AbstractRelay(url, { + verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent, + websocketImplementation: this._WebSocket, + enablePing: this.enablePing + }); + relay.onclose = () => { + this.relays.delete(url); + }; + if (params?.connectionTimeout) + relay.connectionTimeout = params.connectionTimeout; + this.relays.set(url, relay); + } + await relay.connect(); + return relay; + } + close(relays) { + relays.map(normalizeURL).forEach((url) => { + this.relays.get(url)?.close(); + this.relays.delete(url); + }); + } + subscribe(relays, filter, params) { + params.onauth = params.onauth || params.doauth; + const request = []; + for (let i = 0; i < relays.length; i++) { + const url = normalizeURL(relays[i]); + if (!request.find((r) => r.url === url)) { + request.push({ url, filter }); + } + } + return this.subscribeMap(request, params); + } + subscribeMany(relays, filters, params) { + params.onauth = params.onauth || params.doauth; + const request = []; + const uniqUrls = []; + for (let i = 0; i < relays.length; i++) { + const url = normalizeURL(relays[i]); + if (uniqUrls.indexOf(url) === -1) { + for (let f = 0; f < filters.length; f++) { + request.push({ url, filter: filters[f] }); + } + } + } + return this.subscribeMap(request, params); + } + subscribeMap(requests, params) { + params.onauth = params.onauth || params.doauth; + if (this.trackRelays) { + params.receivedEvent = (relay, id) => { + let set = this.seenOn.get(id); + if (!set) { + set = /* @__PURE__ */ new Set(); + this.seenOn.set(id, set); + } + set.add(relay); + }; + } + const _knownIds = /* @__PURE__ */ new Set(); + const subs = []; + const eosesReceived = []; + let handleEose = (i) => { + if (eosesReceived[i]) + return; + eosesReceived[i] = true; + if (eosesReceived.filter((a) => a).length === requests.length) { + params.oneose?.(); + handleEose = () => { + }; + } + }; + const closesReceived = []; + let handleClose = (i, reason) => { + if (closesReceived[i]) + return; + handleEose(i); + closesReceived[i] = reason; + if (closesReceived.filter((a) => a).length === requests.length) { + params.onclose?.(closesReceived); + handleClose = () => { + }; + } + }; + const localAlreadyHaveEventHandler = (id) => { + if (params.alreadyHaveEvent?.(id)) { + return true; + } + const have = _knownIds.has(id); + _knownIds.add(id); + return have; + }; + const allOpened = Promise.all( + requests.map(async ({ url, filter }, i) => { + let relay; + try { + relay = await this.ensureRelay(url, { + connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1e3) : void 0 + }); + } catch (err) { + handleClose(i, err?.message || String(err)); + return; + } + let subscription = relay.subscribe([filter], { + ...params, + oneose: () => handleEose(i), + onclose: (reason) => { + if (reason.startsWith("auth-required: ") && params.onauth) { + relay.auth(params.onauth).then(() => { + relay.subscribe([filter], { + ...params, + oneose: () => handleEose(i), + onclose: (reason2) => { + handleClose(i, reason2); + }, + alreadyHaveEvent: localAlreadyHaveEventHandler, + eoseTimeout: params.maxWait + }); + }).catch((err) => { + handleClose(i, `auth was required and attempted, but failed with: ${err}`); + }); + } else { + handleClose(i, reason); + } + }, + alreadyHaveEvent: localAlreadyHaveEventHandler, + eoseTimeout: params.maxWait + }); + subs.push(subscription); + }) + ); + return { + async close(reason) { + await allOpened; + subs.forEach((sub) => { + sub.close(reason); + }); + } + }; + } + subscribeEose(relays, filter, params) { + params.onauth = params.onauth || params.doauth; + const subcloser = this.subscribe(relays, filter, { + ...params, + oneose() { + subcloser.close("closed automatically on eose"); + } + }); + return subcloser; + } + subscribeManyEose(relays, filters, params) { + params.onauth = params.onauth || params.doauth; + const subcloser = this.subscribeMany(relays, filters, { + ...params, + oneose() { + subcloser.close("closed automatically on eose"); + } + }); + return subcloser; + } + async querySync(relays, filter, params) { + return new Promise(async (resolve) => { + const events = []; + this.subscribeEose(relays, filter, { + ...params, + onevent(event) { + events.push(event); + }, + onclose(_) { + resolve(events); + } + }); + }); + } + async get(relays, filter, params) { + filter.limit = 1; + const events = await this.querySync(relays, filter, params); + events.sort((a, b) => b.created_at - a.created_at); + return events[0] || null; + } + publish(relays, event, options) { + return relays.map(normalizeURL).map(async (url, i, arr) => { + if (arr.indexOf(url) !== i) { + return Promise.reject("duplicate url"); + } + let r = await this.ensureRelay(url); + return r.publish(event).catch(async (err) => { + if (err instanceof Error && err.message.startsWith("auth-required: ") && options?.onauth) { + await r.auth(options.onauth); + return r.publish(event); + } + throw err; + }).then((reason) => { + if (this.trackRelays) { + let set = this.seenOn.get(event.id); + if (!set) { + set = /* @__PURE__ */ new Set(); + this.seenOn.set(event.id, set); + } + set.add(r); + } + return reason; + }); + }); + } + listConnectionStatus() { + const map = /* @__PURE__ */ new Map(); + this.relays.forEach((relay, url) => map.set(url, relay.connected)); + return map; + } + destroy() { + this.relays.forEach((conn) => conn.close()); + this.relays = /* @__PURE__ */ new Map(); + } +}; +export { + AbstractSimplePool +}; diff --git a/node_modules/nostr-tools/lib/esm/abstract-pool.js.map b/node_modules/nostr-tools/lib/esm/abstract-pool.js.map new file mode 100644 index 0000000..3d33fbc --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/abstract-pool.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../core.ts", "../../utils.ts", "../../kinds.ts", "../../filter.ts", "../../fakejson.ts", "../../nip42.ts", "../../helpers.ts", "../../abstract-relay.ts", "../../abstract-pool.ts"], + "sourcesContent": ["export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { Event } from './core.ts'\nimport { isAddressableKind, isReplaceableKind } from './kinds.ts'\n\nexport type Filter = {\n ids?: string[]\n kinds?: number[]\n authors?: string[]\n since?: number\n until?: number\n limit?: number\n search?: string\n [key: `#${string}`]: string[] | undefined\n}\n\nexport function matchFilter(filter: Filter, event: Event): boolean {\n if (filter.ids && filter.ids.indexOf(event.id) === -1) {\n return false\n }\n if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) {\n return false\n }\n if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) {\n return false\n }\n\n for (let f in filter) {\n if (f[0] === '#') {\n let tagName = f.slice(1)\n let values = filter[`#${tagName}`]\n if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values!.indexOf(v) !== -1)) return false\n }\n }\n\n if (filter.since && event.created_at < filter.since) return false\n if (filter.until && event.created_at > filter.until) return false\n\n return true\n}\n\nexport function matchFilters(filters: Filter[], event: Event): boolean {\n for (let i = 0; i < filters.length; i++) {\n if (matchFilter(filters[i], event)) {\n return true\n }\n }\n return false\n}\n\nexport function mergeFilters(...filters: Filter[]): Filter {\n let result: Filter = {}\n for (let i = 0; i < filters.length; i++) {\n let filter = filters[i]\n Object.entries(filter).forEach(([property, values]) => {\n if (property === 'kinds' || property === 'ids' || property === 'authors' || property[0] === '#') {\n // @ts-ignore\n result[property] = result[property] || []\n // @ts-ignore\n for (let v = 0; v < values.length; v++) {\n // @ts-ignore\n let value = values[v]\n // @ts-ignore\n if (!result[property].includes(value)) result[property].push(value)\n }\n }\n })\n\n if (filter.limit && (!result.limit || filter.limit > result.limit)) result.limit = filter.limit\n if (filter.until && (!result.until || filter.until > result.until)) result.until = filter.until\n if (filter.since && (!result.since || filter.since < result.since)) result.since = filter.since\n }\n\n return result\n}\n\n/**\n * Calculate the intrinsic limit of a filter.\n * This function returns a positive integer, or `Infinity` if there is no intrinsic limit.\n */\nexport function getFilterLimit(filter: Filter): number {\n if (filter.ids && !filter.ids.length) return 0\n if (filter.kinds && !filter.kinds.length) return 0\n if (filter.authors && !filter.authors.length) return 0\n\n for (const [key, value] of Object.entries(filter)) {\n if (key[0] === '#' && Array.isArray(value) && !value.length) return 0\n }\n\n return Math.min(\n // The `limit` property creates an artificial limit.\n Math.max(0, filter.limit ?? Infinity),\n\n // There can only be one event per `id`.\n filter.ids?.length ?? Infinity,\n\n // Replaceable events are limited by the number of authors and kinds.\n filter.authors?.length && filter.kinds?.every(kind => isReplaceableKind(kind))\n ? filter.authors.length * filter.kinds.length\n : Infinity,\n\n // Parameterized replaceable events are limited by the number of authors, kinds, and \"d\" tags.\n filter.authors?.length && filter.kinds?.every(kind => isAddressableKind(kind)) && filter['#d']?.length\n ? filter.authors.length * filter.kinds.length * filter['#d'].length\n : Infinity,\n )\n}\n", "export function getHex64(json: string, field: string): string {\n let len = field.length + 3\n let idx = json.indexOf(`\"${field}\":`) + len\n let s = json.slice(idx).indexOf(`\"`) + idx + 1\n return json.slice(s, s + 64)\n}\n\nexport function getInt(json: string, field: string): number {\n let len = field.length\n let idx = json.indexOf(`\"${field}\":`) + len + 3\n let sliced = json.slice(idx)\n let end = Math.min(sliced.indexOf(','), sliced.indexOf('}'))\n return parseInt(sliced.slice(0, end), 10)\n}\n\nexport function getSubscriptionId(json: string): string | null {\n let idx = json.slice(0, 22).indexOf(`\"EVENT\"`)\n if (idx === -1) return null\n\n let pstart = json.slice(idx + 7 + 1).indexOf(`\"`)\n if (pstart === -1) return null\n let start = idx + 7 + 1 + pstart\n\n let pend = json.slice(start + 1, 80).indexOf(`\"`)\n if (pend === -1) return null\n let end = start + 1 + pend\n\n return json.slice(start + 1, end)\n}\n\nexport function matchEventId(json: string, id: string): boolean {\n return id === getHex64(json, 'id')\n}\n\nexport function matchEventPubkey(json: string, pubkey: string): boolean {\n return pubkey === getHex64(json, 'pubkey')\n}\n\nexport function matchEventKind(json: string, kind: number): boolean {\n return kind === getInt(json, 'kind')\n}\n", "import { EventTemplate } from './core.ts'\nimport { ClientAuth } from './kinds.ts'\n\n/**\n * creates an EventTemplate for an AUTH event to be signed.\n */\nexport function makeAuthEvent(relayURL: string, challenge: string): EventTemplate {\n return {\n kind: ClientAuth,\n created_at: Math.floor(Date.now() / 1000),\n tags: [\n ['relay', relayURL],\n ['challenge', challenge],\n ],\n content: '',\n }\n}\n", "import { verifiedSymbol, type Event, type Nostr, VerifiedEvent } from './core.ts'\n\nexport async function yieldThread() {\n return new Promise(resolve => {\n const ch = new MessageChannel()\n const handler = () => {\n // @ts-ignore (typescript thinks this property should be called `removeListener`, but in fact it's `removeEventListener`)\n ch.port1.removeEventListener('message', handler)\n resolve()\n }\n // @ts-ignore (typescript thinks this property should be called `addListener`, but in fact it's `addEventListener`)\n ch.port1.addEventListener('message', handler)\n ch.port2.postMessage(0)\n ch.port1.start()\n })\n}\n\nexport const alwaysTrue: Nostr['verifyEvent'] = (t: Event): t is VerifiedEvent => {\n t[verifiedSymbol] = true\n return true\n}\n", "/* global WebSocket */\n\nimport type { Event, EventTemplate, VerifiedEvent, Nostr, NostrEvent } from './core.ts'\nimport { matchFilters, type Filter } from './filter.ts'\nimport { getHex64, getSubscriptionId } from './fakejson.ts'\nimport { Queue, normalizeURL } from './utils.ts'\nimport { makeAuthEvent } from './nip42.ts'\nimport { yieldThread } from './helpers.ts'\n\ntype RelayWebSocket = WebSocket & {\n ping?(): void\n on?(event: 'pong', listener: () => void): any\n}\n\nexport type AbstractRelayConstructorOptions = {\n verifyEvent: Nostr['verifyEvent']\n websocketImplementation?: typeof WebSocket\n enablePing?: boolean\n}\n\nexport class SendingOnClosedConnection extends Error {\n constructor(message: string, relay: string) {\n super(`Tried to send message '${message} on a closed connection to ${relay}.`)\n this.name = 'SendingOnClosedConnection'\n }\n}\n\nexport class AbstractRelay {\n public readonly url: string\n private _connected: boolean = false\n\n public onclose: (() => void) | null = null\n public onnotice: (msg: string) => void = msg => console.debug(`NOTICE from ${this.url}: ${msg}`)\n\n public baseEoseTimeout: number = 4400\n public connectionTimeout: number = 4400\n public publishTimeout: number = 4400\n public pingFrequency: number = 20000\n public pingTimeout: number = 20000\n public openSubs: Map = new Map()\n public enablePing: boolean | undefined\n private connectionTimeoutHandle: ReturnType | undefined\n\n private connectionPromise: Promise | undefined\n private openCountRequests = new Map()\n private openEventPublishes = new Map()\n private ws: RelayWebSocket | undefined\n private incomingMessageQueue = new Queue()\n private queueRunning = false\n private challenge: string | undefined\n private authPromise: Promise | undefined\n private serial: number = 0\n private verifyEvent: Nostr['verifyEvent']\n\n private _WebSocket: typeof WebSocket\n\n constructor(url: string, opts: AbstractRelayConstructorOptions) {\n this.url = normalizeURL(url)\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation || WebSocket\n this.enablePing = opts.enablePing\n }\n\n static async connect(url: string, opts: AbstractRelayConstructorOptions): Promise {\n const relay = new AbstractRelay(url, opts)\n await relay.connect()\n return relay\n }\n\n private closeAllSubscriptions(reason: string) {\n for (let [_, sub] of this.openSubs) {\n sub.close(reason)\n }\n this.openSubs.clear()\n\n for (let [_, ep] of this.openEventPublishes) {\n ep.reject(new Error(reason))\n }\n this.openEventPublishes.clear()\n\n for (let [_, cr] of this.openCountRequests) {\n cr.reject(new Error(reason))\n }\n this.openCountRequests.clear()\n }\n\n public get connected(): boolean {\n return this._connected\n }\n\n public async connect(): Promise {\n if (this.connectionPromise) return this.connectionPromise\n\n this.challenge = undefined\n this.authPromise = undefined\n this.connectionPromise = new Promise((resolve, reject) => {\n this.connectionTimeoutHandle = setTimeout(() => {\n reject('connection timed out')\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection timed out')\n }, this.connectionTimeout)\n\n try {\n this.ws = new this._WebSocket(this.url)\n } catch (err) {\n clearTimeout(this.connectionTimeoutHandle)\n reject(err)\n return\n }\n\n this.ws.onopen = () => {\n clearTimeout(this.connectionTimeoutHandle)\n this._connected = true\n if (this.enablePing) {\n this.pingpong()\n }\n resolve()\n }\n\n this.ws.onerror = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket error')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection errored')\n }\n }\n\n this.ws.onclose = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket closed')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection closed')\n }\n }\n\n this.ws.onmessage = this._onmessage.bind(this)\n })\n\n return this.connectionPromise\n }\n\n private async waitForPingPong() {\n return new Promise((res, err) => {\n // listen for pong\n ;(this.ws && this.ws.on && this.ws.on('pong', () => res(true))) || err(\"ws can't listen for pong\")\n // send a ping\n this.ws && this.ws.ping && this.ws.ping()\n })\n }\n\n private async waitForDummyReq() {\n return new Promise((resolve, _) => {\n // make a dummy request with expected empty eose reply\n // [\"REQ\", \"_\", {\"ids\":[\"aaaa...aaaa\"]}]\n const sub = this.subscribe([{ ids: ['a'.repeat(64)] }], {\n oneose: () => {\n sub.close()\n resolve(true)\n },\n eoseTimeout: this.pingTimeout + 1000,\n })\n })\n }\n\n // nodejs requires this magic here to ensure connections are closed when internet goes off and stuff\n // in browsers it's done automatically. see https://github.com/nbd-wtf/nostr-tools/issues/491\n private async pingpong() {\n // if the websocket is connected\n if (this.ws?.readyState === 1) {\n // wait for either a ping-pong reply or a timeout\n const result = await Promise.any([\n // browsers don't have ping so use a dummy req\n this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(),\n new Promise(res => setTimeout(() => res(false), this.pingTimeout)),\n ])\n if (result) {\n // schedule another pingpong\n setTimeout(() => this.pingpong(), this.pingFrequency)\n } else {\n // pingpong closing socket\n this.closeAllSubscriptions('pingpong timed out')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n }\n }\n\n private async runQueue() {\n this.queueRunning = true\n while (true) {\n if (false === this.handleNext()) {\n break\n }\n await yieldThread()\n }\n this.queueRunning = false\n }\n\n private handleNext(): undefined | false {\n const json = this.incomingMessageQueue.dequeue()\n if (!json) {\n return false\n }\n\n const subid = getSubscriptionId(json)\n if (subid) {\n const so = this.openSubs.get(subid as string)\n if (!so) {\n // this is an EVENT message, but for a subscription we don't have, so just stop here\n return\n }\n\n // this will be called only when this message is a EVENT message for a subscription we have\n // we do this before parsing the JSON to not have to do that for duplicate events\n // since JSON parsing is slow\n const id = getHex64(json, 'id')\n const alreadyHave = so.alreadyHaveEvent?.(id)\n\n // notify any interested client that the relay has this event\n // (do this after alreadyHaveEvent() because the client may rely on this to answer that)\n so.receivedEvent?.(this, id)\n\n if (alreadyHave) {\n // if we had already seen this event we can just stop here\n return\n }\n }\n\n try {\n let data = JSON.parse(json)\n // we won't do any checks against the data since all failures (i.e. invalid messages from relays)\n // will naturally be caught by the encompassing try..catch block\n\n switch (data[0]) {\n case 'EVENT': {\n const so = this.openSubs.get(data[1] as string) as Subscription\n const event = data[2] as NostrEvent\n if (this.verifyEvent(event) && matchFilters(so.filters, event)) {\n so.onevent(event)\n }\n return\n }\n case 'COUNT': {\n const id: string = data[1]\n const payload = data[2] as { count: number }\n const cr = this.openCountRequests.get(id) as CountResolver\n if (cr) {\n cr.resolve(payload.count)\n this.openCountRequests.delete(id)\n }\n return\n }\n case 'EOSE': {\n const so = this.openSubs.get(data[1] as string)\n if (!so) return\n so.receivedEose()\n return\n }\n case 'OK': {\n const id: string = data[1]\n const ok: boolean = data[2]\n const reason: string = data[3]\n const ep = this.openEventPublishes.get(id) as EventPublishResolver\n if (ep) {\n clearTimeout(ep.timeout)\n if (ok) ep.resolve(reason)\n else ep.reject(new Error(reason))\n this.openEventPublishes.delete(id)\n }\n return\n }\n case 'CLOSED': {\n const id: string = data[1]\n const so = this.openSubs.get(id)\n if (!so) return\n so.closed = true\n so.close(data[2] as string)\n return\n }\n case 'NOTICE':\n this.onnotice(data[1] as string)\n return\n case 'AUTH': {\n this.challenge = data[1] as string\n return\n }\n }\n } catch (err) {\n return\n }\n }\n\n public async send(message: string) {\n if (!this.connectionPromise) throw new SendingOnClosedConnection(message, this.url)\n\n this.connectionPromise.then(() => {\n this.ws?.send(message)\n })\n }\n\n public async auth(signAuthEvent: (evt: EventTemplate) => Promise): Promise {\n const challenge = this.challenge\n if (!challenge) throw new Error(\"can't perform auth, no challenge was received\")\n if (this.authPromise) return this.authPromise\n\n this.authPromise = new Promise(async (resolve, reject) => {\n try {\n let evt = await signAuthEvent(makeAuthEvent(this.url, challenge))\n let timeout = setTimeout(() => {\n let ep = this.openEventPublishes.get(evt.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('auth timed out'))\n this.openEventPublishes.delete(evt.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(evt.id, { resolve, reject, timeout })\n this.send('[\"AUTH\",' + JSON.stringify(evt) + ']')\n } catch (err) {\n console.warn('subscribe auth function failed:', err)\n }\n })\n return this.authPromise\n }\n\n public async publish(event: Event): Promise {\n const ret = new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n const ep = this.openEventPublishes.get(event.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('publish timed out'))\n this.openEventPublishes.delete(event.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(event.id, { resolve, reject, timeout })\n })\n this.send('[\"EVENT\",' + JSON.stringify(event) + ']')\n return ret\n }\n\n public async count(filters: Filter[], params: { id?: string | null }): Promise {\n this.serial++\n const id = params?.id || 'count:' + this.serial\n const ret = new Promise((resolve, reject) => {\n this.openCountRequests.set(id, { resolve, reject })\n })\n this.send('[\"COUNT\",\"' + id + '\",' + JSON.stringify(filters).substring(1))\n return ret\n }\n\n public subscribe(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n const subscription = this.prepareSubscription(filters, params)\n subscription.fire()\n return subscription\n }\n\n public prepareSubscription(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n this.serial++\n const id = params.id || (params.label ? params.label + ':' : 'sub:') + this.serial\n const subscription = new Subscription(this, id, filters, params)\n this.openSubs.set(id, subscription)\n return subscription\n }\n\n public close() {\n this.closeAllSubscriptions('relay connection closed by us')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n\n // this is the function assigned to this.ws.onmessage\n // it's exposed for testing and debugging purposes\n public _onmessage(ev: MessageEvent) {\n this.incomingMessageQueue.enqueue(ev.data as string)\n if (!this.queueRunning) {\n this.runQueue()\n }\n }\n}\n\nexport class Subscription {\n public readonly relay: AbstractRelay\n public readonly id: string\n\n public closed: boolean = false\n public eosed: boolean = false\n public filters: Filter[]\n public alreadyHaveEvent: ((id: string) => boolean) | undefined\n public receivedEvent: ((relay: AbstractRelay, id: string) => void) | undefined\n\n public onevent: (evt: Event) => void\n public oneose: (() => void) | undefined\n public onclose: ((reason: string) => void) | undefined\n\n public eoseTimeout: number\n private eoseTimeoutHandle: ReturnType | undefined\n\n constructor(relay: AbstractRelay, id: string, filters: Filter[], params: SubscriptionParams) {\n this.relay = relay\n this.filters = filters\n this.id = id\n this.alreadyHaveEvent = params.alreadyHaveEvent\n this.receivedEvent = params.receivedEvent\n this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout\n\n this.oneose = params.oneose\n this.onclose = params.onclose\n this.onevent =\n params.onevent ||\n (event => {\n console.warn(\n `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,\n event,\n )\n })\n }\n\n public fire() {\n this.relay.send('[\"REQ\",\"' + this.id + '\",' + JSON.stringify(this.filters).substring(1))\n\n // only now we start counting the eoseTimeout\n this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout)\n }\n\n public receivedEose() {\n if (this.eosed) return\n clearTimeout(this.eoseTimeoutHandle)\n this.eosed = true\n this.oneose?.()\n }\n\n public close(reason: string = 'closed by caller') {\n if (!this.closed && this.relay.connected) {\n // if the connection was closed by the user calling .close() we will send a CLOSE message\n // otherwise this._open will be already set to false so we will skip this\n try {\n this.relay.send('[\"CLOSE\",' + JSON.stringify(this.id) + ']')\n } catch (err) {\n if (err instanceof SendingOnClosedConnection) {\n /* doesn't matter, it's ok */\n } else {\n throw err\n }\n }\n this.closed = true\n }\n this.relay.openSubs.delete(this.id)\n this.onclose?.(reason)\n }\n}\n\nexport type SubscriptionParams = {\n onevent?: (evt: Event) => void\n oneose?: () => void\n onclose?: (reason: string) => void\n alreadyHaveEvent?: (id: string) => boolean\n receivedEvent?: (relay: AbstractRelay, id: string) => void\n eoseTimeout?: number\n}\n\nexport type CountResolver = {\n resolve: (count: number) => void\n reject: (err: Error) => void\n}\n\nexport type EventPublishResolver = {\n resolve: (reason: string) => void\n reject: (err: Error) => void\n timeout: ReturnType\n}\n", "/* global WebSocket */\n\nimport {\n AbstractRelay as AbstractRelay,\n SubscriptionParams,\n Subscription,\n type AbstractRelayConstructorOptions,\n} from './abstract-relay.ts'\nimport { normalizeURL } from './utils.ts'\n\nimport type { Event, EventTemplate, Nostr, VerifiedEvent } from './core.ts'\nimport { type Filter } from './filter.ts'\nimport { alwaysTrue } from './helpers.ts'\n\nexport type SubCloser = { close: (reason?: string) => void }\n\nexport type AbstractPoolConstructorOptions = AbstractRelayConstructorOptions & {}\n\nexport type SubscribeManyParams = Omit & {\n maxWait?: number\n onclose?: (reasons: string[]) => void\n onauth?: (event: EventTemplate) => Promise\n // Deprecated: use onauth instead\n doauth?: (event: EventTemplate) => Promise\n id?: string\n label?: string\n}\n\nexport class AbstractSimplePool {\n protected relays: Map = new Map()\n public seenOn: Map> = new Map()\n public trackRelays: boolean = false\n\n public verifyEvent: Nostr['verifyEvent']\n public enablePing: boolean | undefined\n public trustedRelayURLs: Set = new Set()\n\n private _WebSocket?: typeof WebSocket\n\n constructor(opts: AbstractPoolConstructorOptions) {\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation\n this.enablePing = opts.enablePing\n }\n\n async ensureRelay(url: string, params?: { connectionTimeout?: number }): Promise {\n url = normalizeURL(url)\n\n let relay = this.relays.get(url)\n if (!relay) {\n relay = new AbstractRelay(url, {\n verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent,\n websocketImplementation: this._WebSocket,\n enablePing: this.enablePing,\n })\n relay.onclose = () => {\n this.relays.delete(url)\n }\n if (params?.connectionTimeout) relay.connectionTimeout = params.connectionTimeout\n this.relays.set(url, relay)\n }\n await relay.connect()\n\n return relay\n }\n\n close(relays: string[]) {\n relays.map(normalizeURL).forEach(url => {\n this.relays.get(url)?.close()\n this.relays.delete(url)\n })\n }\n\n subscribe(relays: string[], filter: Filter, params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const request: { url: string; filter: Filter }[] = []\n for (let i = 0; i < relays.length; i++) {\n const url = normalizeURL(relays[i])\n if (!request.find(r => r.url === url)) {\n request.push({ url, filter })\n }\n }\n\n return this.subscribeMap(request, params)\n }\n\n subscribeMany(relays: string[], filters: Filter[], params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const request: { url: string; filter: Filter }[] = []\n const uniqUrls: string[] = []\n for (let i = 0; i < relays.length; i++) {\n const url = normalizeURL(relays[i])\n if (uniqUrls.indexOf(url) === -1) {\n for (let f = 0; f < filters.length; f++) {\n request.push({ url, filter: filters[f] })\n }\n }\n }\n\n return this.subscribeMap(request, params)\n }\n\n subscribeMap(requests: { url: string; filter: Filter }[], params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n if (this.trackRelays) {\n params.receivedEvent = (relay: AbstractRelay, id: string) => {\n let set = this.seenOn.get(id)\n if (!set) {\n set = new Set()\n this.seenOn.set(id, set)\n }\n set.add(relay)\n }\n }\n\n const _knownIds = new Set()\n const subs: Subscription[] = []\n\n // batch all EOSEs into a single\n const eosesReceived: boolean[] = []\n let handleEose = (i: number) => {\n if (eosesReceived[i]) return // do not act twice for the same relay\n eosesReceived[i] = true\n if (eosesReceived.filter(a => a).length === requests.length) {\n params.oneose?.()\n handleEose = () => {}\n }\n }\n // batch all closes into a single\n const closesReceived: string[] = []\n let handleClose = (i: number, reason: string) => {\n if (closesReceived[i]) return // do not act twice for the same relay\n handleEose(i)\n closesReceived[i] = reason\n if (closesReceived.filter(a => a).length === requests.length) {\n params.onclose?.(closesReceived)\n handleClose = () => {}\n }\n }\n\n const localAlreadyHaveEventHandler = (id: string) => {\n if (params.alreadyHaveEvent?.(id)) {\n return true\n }\n const have = _knownIds.has(id)\n _knownIds.add(id)\n return have\n }\n\n // open a subscription in all given relays\n const allOpened = Promise.all(\n requests.map(async ({ url, filter }, i) => {\n let relay: AbstractRelay\n try {\n relay = await this.ensureRelay(url, {\n connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1000) : undefined,\n })\n } catch (err) {\n handleClose(i, (err as any)?.message || String(err))\n return\n }\n\n let subscription = relay.subscribe([filter], {\n ...params,\n oneose: () => handleEose(i),\n onclose: reason => {\n if (reason.startsWith('auth-required: ') && params.onauth) {\n relay\n .auth(params.onauth)\n .then(() => {\n relay.subscribe([filter], {\n ...params,\n oneose: () => handleEose(i),\n onclose: reason => {\n handleClose(i, reason) // the second time we won't try to auth anymore\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait,\n })\n })\n .catch(err => {\n handleClose(i, `auth was required and attempted, but failed with: ${err}`)\n })\n } else {\n handleClose(i, reason)\n }\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait,\n })\n\n subs.push(subscription)\n }),\n )\n\n return {\n async close(reason?: string) {\n await allOpened\n subs.forEach(sub => {\n sub.close(reason)\n })\n },\n }\n }\n\n subscribeEose(\n relays: string[],\n filter: Filter,\n params: Pick,\n ): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const subcloser = this.subscribe(relays, filter, {\n ...params,\n oneose() {\n subcloser.close('closed automatically on eose')\n },\n })\n return subcloser\n }\n\n subscribeManyEose(\n relays: string[],\n filters: Filter[],\n params: Pick,\n ): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const subcloser = this.subscribeMany(relays, filters, {\n ...params,\n oneose() {\n subcloser.close('closed automatically on eose')\n },\n })\n return subcloser\n }\n\n async querySync(\n relays: string[],\n filter: Filter,\n params?: Pick,\n ): Promise {\n return new Promise(async resolve => {\n const events: Event[] = []\n this.subscribeEose(relays, filter, {\n ...params,\n onevent(event: Event) {\n events.push(event)\n },\n onclose(_: string[]) {\n resolve(events)\n },\n })\n })\n }\n\n async get(\n relays: string[],\n filter: Filter,\n params?: Pick,\n ): Promise {\n filter.limit = 1\n const events = await this.querySync(relays, filter, params)\n events.sort((a, b) => b.created_at - a.created_at)\n return events[0] || null\n }\n\n publish(\n relays: string[],\n event: Event,\n options?: { onauth?: (evt: EventTemplate) => Promise },\n ): Promise[] {\n return relays.map(normalizeURL).map(async (url, i, arr) => {\n if (arr.indexOf(url) !== i) {\n // duplicate\n return Promise.reject('duplicate url')\n }\n\n let r = await this.ensureRelay(url)\n return r\n .publish(event)\n .catch(async err => {\n if (err instanceof Error && err.message.startsWith('auth-required: ') && options?.onauth) {\n await r.auth(options.onauth)\n return r.publish(event) // retry\n }\n throw err\n })\n .then(reason => {\n if (this.trackRelays) {\n let set = this.seenOn.get(event.id)\n if (!set) {\n set = new Set()\n this.seenOn.set(event.id, set)\n }\n set.add(r)\n }\n return reason\n })\n })\n }\n\n listConnectionStatus(): Map {\n const map = new Map()\n this.relays.forEach((relay, url) => map.set(url, relay.connected))\n\n return map\n }\n\n destroy(): void {\n this.relays.forEach(conn => conn.close())\n this.relays = new Map()\n }\n}\n"], + "mappings": ";AAQO,IAAM,iBAAiB,OAAO,UAAU;;;ACH/C,SAAS,YAAY,kBAAkB;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;AAIjD,SAAS,aAAa,KAAqB;AAChD,MAAI;AACF,QAAI,IAAI,QAAQ,KAAK,MAAM;AAAI,YAAM,WAAW;AAChD,QAAI,IAAI,IAAI,IAAI,GAAG;AACnB,MAAE,WAAW,EAAE,SAAS,QAAQ,QAAQ,GAAG;AAC3C,QAAI,EAAE,SAAS,SAAS,GAAG;AAAG,QAAE,WAAW,EAAE,SAAS,MAAM,GAAG,EAAE;AACjE,QAAK,EAAE,SAAS,QAAQ,EAAE,aAAa,SAAW,EAAE,SAAS,SAAS,EAAE,aAAa;AAAS,QAAE,OAAO;AACvG,MAAE,aAAa,KAAK;AACpB,MAAE,OAAO;AACT,WAAO,EAAE,SAAS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Q,QAAQ,MAAM;AAC1D,WAAO,KAAK,CAAC,GAAG,MAAM,EAAE,aAAa,EAAE,UAAU;AACjD,WAAO,OAAO,MAAM;AAAA,EACtB;AAAA,EAEA,QACE,QACA,OACA,SACmB;AACnB,WAAO,OAAO,IAAI,YAAY,EAAE,IAAI,OAAO,KAAK,GAAG,QAAQ;AACzD,UAAI,IAAI,QAAQ,GAAG,MAAM,GAAG;AAE1B,eAAO,QAAQ,OAAO,eAAe;AAAA,MACvC;AAEA,UAAI,IAAI,MAAM,KAAK,YAAY,GAAG;AAClC,aAAO,EACJ,QAAQ,KAAK,EACb,MAAM,OAAM,QAAO;AAClB,YAAI,eAAe,SAAS,IAAI,QAAQ,WAAW,iBAAiB,KAAK,SAAS,QAAQ;AACxF,gBAAM,EAAE,KAAK,QAAQ,MAAM;AAC3B,iBAAO,EAAE,QAAQ,KAAK;AAAA,QACxB;AACA,cAAM;AAAA,MACR,CAAC,EACA,KAAK,YAAU;AACd,YAAI,KAAK,aAAa;AACpB,cAAI,MAAM,KAAK,OAAO,IAAI,MAAM,EAAE;AAClC,cAAI,CAAC,KAAK;AACR,kBAAM,oBAAI,IAAI;AACd,iBAAK,OAAO,IAAI,MAAM,IAAI,GAAG;AAAA,UAC/B;AACA,cAAI,IAAI,CAAC;AAAA,QACX;AACA,eAAO;AAAA,MACT,CAAC;AAAA,IACL,CAAC;AAAA,EACH;AAAA,EAEA,uBAA6C;AAC3C,UAAM,MAAM,oBAAI,IAAqB;AACrC,SAAK,OAAO,QAAQ,CAAC,OAAO,QAAQ,IAAI,IAAI,KAAK,MAAM,SAAS,CAAC;AAEjE,WAAO;AAAA,EACT;AAAA,EAEA,UAAgB;AACd,SAAK,OAAO,QAAQ,UAAQ,KAAK,MAAM,CAAC;AACxC,SAAK,SAAS,oBAAI,IAAI;AAAA,EACxB;AACF;", + "names": ["target", "reason"] +} diff --git a/node_modules/nostr-tools/lib/esm/abstract-relay.js b/node_modules/nostr-tools/lib/esm/abstract-relay.js new file mode 100644 index 0000000..0d1ecc3 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/abstract-relay.js @@ -0,0 +1,532 @@ +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); +function normalizeURL(url) { + try { + if (url.indexOf("://") === -1) + url = "wss://" + url; + let p = new URL(url); + p.pathname = p.pathname.replace(/\/+/g, "/"); + if (p.pathname.endsWith("/")) + p.pathname = p.pathname.slice(0, -1); + if (p.port === "80" && p.protocol === "ws:" || p.port === "443" && p.protocol === "wss:") + p.port = ""; + p.searchParams.sort(); + p.hash = ""; + return p.toString(); + } catch (e) { + throw new Error(`Invalid URL: ${url}`); + } +} +var QueueNode = class { + value; + next = null; + prev = null; + constructor(message) { + this.value = message; + } +}; +var Queue = class { + first; + last; + constructor() { + this.first = null; + this.last = null; + } + enqueue(value) { + const newNode = new QueueNode(value); + if (!this.last) { + this.first = newNode; + this.last = newNode; + } else if (this.last === this.first) { + this.last = newNode; + this.last.prev = this.first; + this.first.next = newNode; + } else { + newNode.prev = this.last; + this.last.next = newNode; + this.last = newNode; + } + return true; + } + dequeue() { + if (!this.first) + return null; + if (this.first === this.last) { + const target2 = this.first; + this.first = null; + this.last = null; + return target2.value; + } + const target = this.first; + this.first = target.next; + if (this.first) { + this.first.prev = null; + } + return target.value; + } +}; + +// kinds.ts +var ClientAuth = 22242; + +// filter.ts +function matchFilter(filter, event) { + if (filter.ids && filter.ids.indexOf(event.id) === -1) { + return false; + } + if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) { + return false; + } + if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) { + return false; + } + for (let f in filter) { + if (f[0] === "#") { + let tagName = f.slice(1); + let values = filter[`#${tagName}`]; + if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values.indexOf(v) !== -1)) + return false; + } + } + if (filter.since && event.created_at < filter.since) + return false; + if (filter.until && event.created_at > filter.until) + return false; + return true; +} +function matchFilters(filters, event) { + for (let i = 0; i < filters.length; i++) { + if (matchFilter(filters[i], event)) { + return true; + } + } + return false; +} + +// fakejson.ts +function getHex64(json, field) { + let len = field.length + 3; + let idx = json.indexOf(`"${field}":`) + len; + let s = json.slice(idx).indexOf(`"`) + idx + 1; + return json.slice(s, s + 64); +} +function getSubscriptionId(json) { + let idx = json.slice(0, 22).indexOf(`"EVENT"`); + if (idx === -1) + return null; + let pstart = json.slice(idx + 7 + 1).indexOf(`"`); + if (pstart === -1) + return null; + let start = idx + 7 + 1 + pstart; + let pend = json.slice(start + 1, 80).indexOf(`"`); + if (pend === -1) + return null; + let end = start + 1 + pend; + return json.slice(start + 1, end); +} + +// nip42.ts +function makeAuthEvent(relayURL, challenge) { + return { + kind: ClientAuth, + created_at: Math.floor(Date.now() / 1e3), + tags: [ + ["relay", relayURL], + ["challenge", challenge] + ], + content: "" + }; +} + +// helpers.ts +async function yieldThread() { + return new Promise((resolve) => { + const ch = new MessageChannel(); + const handler = () => { + ch.port1.removeEventListener("message", handler); + resolve(); + }; + ch.port1.addEventListener("message", handler); + ch.port2.postMessage(0); + ch.port1.start(); + }); +} + +// abstract-relay.ts +var SendingOnClosedConnection = class extends Error { + constructor(message, relay) { + super(`Tried to send message '${message} on a closed connection to ${relay}.`); + this.name = "SendingOnClosedConnection"; + } +}; +var AbstractRelay = class { + url; + _connected = false; + onclose = null; + onnotice = (msg) => console.debug(`NOTICE from ${this.url}: ${msg}`); + baseEoseTimeout = 4400; + connectionTimeout = 4400; + publishTimeout = 4400; + pingFrequency = 2e4; + pingTimeout = 2e4; + openSubs = /* @__PURE__ */ new Map(); + enablePing; + connectionTimeoutHandle; + connectionPromise; + openCountRequests = /* @__PURE__ */ new Map(); + openEventPublishes = /* @__PURE__ */ new Map(); + ws; + incomingMessageQueue = new Queue(); + queueRunning = false; + challenge; + authPromise; + serial = 0; + verifyEvent; + _WebSocket; + constructor(url, opts) { + this.url = normalizeURL(url); + this.verifyEvent = opts.verifyEvent; + this._WebSocket = opts.websocketImplementation || WebSocket; + this.enablePing = opts.enablePing; + } + static async connect(url, opts) { + const relay = new AbstractRelay(url, opts); + await relay.connect(); + return relay; + } + closeAllSubscriptions(reason) { + for (let [_, sub] of this.openSubs) { + sub.close(reason); + } + this.openSubs.clear(); + for (let [_, ep] of this.openEventPublishes) { + ep.reject(new Error(reason)); + } + this.openEventPublishes.clear(); + for (let [_, cr] of this.openCountRequests) { + cr.reject(new Error(reason)); + } + this.openCountRequests.clear(); + } + get connected() { + return this._connected; + } + async connect() { + if (this.connectionPromise) + return this.connectionPromise; + this.challenge = void 0; + this.authPromise = void 0; + this.connectionPromise = new Promise((resolve, reject) => { + this.connectionTimeoutHandle = setTimeout(() => { + reject("connection timed out"); + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection timed out"); + }, this.connectionTimeout); + try { + this.ws = new this._WebSocket(this.url); + } catch (err) { + clearTimeout(this.connectionTimeoutHandle); + reject(err); + return; + } + this.ws.onopen = () => { + clearTimeout(this.connectionTimeoutHandle); + this._connected = true; + if (this.enablePing) { + this.pingpong(); + } + resolve(); + }; + this.ws.onerror = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket error"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection errored"); + } + }; + this.ws.onclose = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket closed"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection closed"); + } + }; + this.ws.onmessage = this._onmessage.bind(this); + }); + return this.connectionPromise; + } + async waitForPingPong() { + return new Promise((res, err) => { + ; + this.ws && this.ws.on && this.ws.on("pong", () => res(true)) || err("ws can't listen for pong"); + this.ws && this.ws.ping && this.ws.ping(); + }); + } + async waitForDummyReq() { + return new Promise((resolve, _) => { + const sub = this.subscribe([{ ids: ["a".repeat(64)] }], { + oneose: () => { + sub.close(); + resolve(true); + }, + eoseTimeout: this.pingTimeout + 1e3 + }); + }); + } + async pingpong() { + if (this.ws?.readyState === 1) { + const result = await Promise.any([ + this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(), + new Promise((res) => setTimeout(() => res(false), this.pingTimeout)) + ]); + if (result) { + setTimeout(() => this.pingpong(), this.pingFrequency); + } else { + this.closeAllSubscriptions("pingpong timed out"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + } + } + async runQueue() { + this.queueRunning = true; + while (true) { + if (false === this.handleNext()) { + break; + } + await yieldThread(); + } + this.queueRunning = false; + } + handleNext() { + const json = this.incomingMessageQueue.dequeue(); + if (!json) { + return false; + } + const subid = getSubscriptionId(json); + if (subid) { + const so = this.openSubs.get(subid); + if (!so) { + return; + } + const id = getHex64(json, "id"); + const alreadyHave = so.alreadyHaveEvent?.(id); + so.receivedEvent?.(this, id); + if (alreadyHave) { + return; + } + } + try { + let data = JSON.parse(json); + switch (data[0]) { + case "EVENT": { + const so = this.openSubs.get(data[1]); + const event = data[2]; + if (this.verifyEvent(event) && matchFilters(so.filters, event)) { + so.onevent(event); + } + return; + } + case "COUNT": { + const id = data[1]; + const payload = data[2]; + const cr = this.openCountRequests.get(id); + if (cr) { + cr.resolve(payload.count); + this.openCountRequests.delete(id); + } + return; + } + case "EOSE": { + const so = this.openSubs.get(data[1]); + if (!so) + return; + so.receivedEose(); + return; + } + case "OK": { + const id = data[1]; + const ok = data[2]; + const reason = data[3]; + const ep = this.openEventPublishes.get(id); + if (ep) { + clearTimeout(ep.timeout); + if (ok) + ep.resolve(reason); + else + ep.reject(new Error(reason)); + this.openEventPublishes.delete(id); + } + return; + } + case "CLOSED": { + const id = data[1]; + const so = this.openSubs.get(id); + if (!so) + return; + so.closed = true; + so.close(data[2]); + return; + } + case "NOTICE": + this.onnotice(data[1]); + return; + case "AUTH": { + this.challenge = data[1]; + return; + } + } + } catch (err) { + return; + } + } + async send(message) { + if (!this.connectionPromise) + throw new SendingOnClosedConnection(message, this.url); + this.connectionPromise.then(() => { + this.ws?.send(message); + }); + } + async auth(signAuthEvent) { + const challenge = this.challenge; + if (!challenge) + throw new Error("can't perform auth, no challenge was received"); + if (this.authPromise) + return this.authPromise; + this.authPromise = new Promise(async (resolve, reject) => { + try { + let evt = await signAuthEvent(makeAuthEvent(this.url, challenge)); + let timeout = setTimeout(() => { + let ep = this.openEventPublishes.get(evt.id); + if (ep) { + ep.reject(new Error("auth timed out")); + this.openEventPublishes.delete(evt.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(evt.id, { resolve, reject, timeout }); + this.send('["AUTH",' + JSON.stringify(evt) + "]"); + } catch (err) { + console.warn("subscribe auth function failed:", err); + } + }); + return this.authPromise; + } + async publish(event) { + const ret = new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + const ep = this.openEventPublishes.get(event.id); + if (ep) { + ep.reject(new Error("publish timed out")); + this.openEventPublishes.delete(event.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(event.id, { resolve, reject, timeout }); + }); + this.send('["EVENT",' + JSON.stringify(event) + "]"); + return ret; + } + async count(filters, params) { + this.serial++; + const id = params?.id || "count:" + this.serial; + const ret = new Promise((resolve, reject) => { + this.openCountRequests.set(id, { resolve, reject }); + }); + this.send('["COUNT","' + id + '",' + JSON.stringify(filters).substring(1)); + return ret; + } + subscribe(filters, params) { + const subscription = this.prepareSubscription(filters, params); + subscription.fire(); + return subscription; + } + prepareSubscription(filters, params) { + this.serial++; + const id = params.id || (params.label ? params.label + ":" : "sub:") + this.serial; + const subscription = new Subscription(this, id, filters, params); + this.openSubs.set(id, subscription); + return subscription; + } + close() { + this.closeAllSubscriptions("relay connection closed by us"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + _onmessage(ev) { + this.incomingMessageQueue.enqueue(ev.data); + if (!this.queueRunning) { + this.runQueue(); + } + } +}; +var Subscription = class { + relay; + id; + closed = false; + eosed = false; + filters; + alreadyHaveEvent; + receivedEvent; + onevent; + oneose; + onclose; + eoseTimeout; + eoseTimeoutHandle; + constructor(relay, id, filters, params) { + this.relay = relay; + this.filters = filters; + this.id = id; + this.alreadyHaveEvent = params.alreadyHaveEvent; + this.receivedEvent = params.receivedEvent; + this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout; + this.oneose = params.oneose; + this.onclose = params.onclose; + this.onevent = params.onevent || ((event) => { + console.warn( + `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`, + event + ); + }); + } + fire() { + this.relay.send('["REQ","' + this.id + '",' + JSON.stringify(this.filters).substring(1)); + this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout); + } + receivedEose() { + if (this.eosed) + return; + clearTimeout(this.eoseTimeoutHandle); + this.eosed = true; + this.oneose?.(); + } + close(reason = "closed by caller") { + if (!this.closed && this.relay.connected) { + try { + this.relay.send('["CLOSE",' + JSON.stringify(this.id) + "]"); + } catch (err) { + if (err instanceof SendingOnClosedConnection) { + } else { + throw err; + } + } + this.closed = true; + } + this.relay.openSubs.delete(this.id); + this.onclose?.(reason); + } +}; +export { + AbstractRelay, + SendingOnClosedConnection, + Subscription +}; diff --git a/node_modules/nostr-tools/lib/esm/abstract-relay.js.map b/node_modules/nostr-tools/lib/esm/abstract-relay.js.map new file mode 100644 index 0000000..cf7ba52 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/abstract-relay.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../utils.ts", "../../kinds.ts", "../../filter.ts", "../../fakejson.ts", "../../nip42.ts", "../../helpers.ts", "../../abstract-relay.ts"], + "sourcesContent": ["import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { Event } from './core.ts'\nimport { isAddressableKind, isReplaceableKind } from './kinds.ts'\n\nexport type Filter = {\n ids?: string[]\n kinds?: number[]\n authors?: string[]\n since?: number\n until?: number\n limit?: number\n search?: string\n [key: `#${string}`]: string[] | undefined\n}\n\nexport function matchFilter(filter: Filter, event: Event): boolean {\n if (filter.ids && filter.ids.indexOf(event.id) === -1) {\n return false\n }\n if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) {\n return false\n }\n if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) {\n return false\n }\n\n for (let f in filter) {\n if (f[0] === '#') {\n let tagName = f.slice(1)\n let values = filter[`#${tagName}`]\n if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values!.indexOf(v) !== -1)) return false\n }\n }\n\n if (filter.since && event.created_at < filter.since) return false\n if (filter.until && event.created_at > filter.until) return false\n\n return true\n}\n\nexport function matchFilters(filters: Filter[], event: Event): boolean {\n for (let i = 0; i < filters.length; i++) {\n if (matchFilter(filters[i], event)) {\n return true\n }\n }\n return false\n}\n\nexport function mergeFilters(...filters: Filter[]): Filter {\n let result: Filter = {}\n for (let i = 0; i < filters.length; i++) {\n let filter = filters[i]\n Object.entries(filter).forEach(([property, values]) => {\n if (property === 'kinds' || property === 'ids' || property === 'authors' || property[0] === '#') {\n // @ts-ignore\n result[property] = result[property] || []\n // @ts-ignore\n for (let v = 0; v < values.length; v++) {\n // @ts-ignore\n let value = values[v]\n // @ts-ignore\n if (!result[property].includes(value)) result[property].push(value)\n }\n }\n })\n\n if (filter.limit && (!result.limit || filter.limit > result.limit)) result.limit = filter.limit\n if (filter.until && (!result.until || filter.until > result.until)) result.until = filter.until\n if (filter.since && (!result.since || filter.since < result.since)) result.since = filter.since\n }\n\n return result\n}\n\n/**\n * Calculate the intrinsic limit of a filter.\n * This function returns a positive integer, or `Infinity` if there is no intrinsic limit.\n */\nexport function getFilterLimit(filter: Filter): number {\n if (filter.ids && !filter.ids.length) return 0\n if (filter.kinds && !filter.kinds.length) return 0\n if (filter.authors && !filter.authors.length) return 0\n\n for (const [key, value] of Object.entries(filter)) {\n if (key[0] === '#' && Array.isArray(value) && !value.length) return 0\n }\n\n return Math.min(\n // The `limit` property creates an artificial limit.\n Math.max(0, filter.limit ?? Infinity),\n\n // There can only be one event per `id`.\n filter.ids?.length ?? Infinity,\n\n // Replaceable events are limited by the number of authors and kinds.\n filter.authors?.length && filter.kinds?.every(kind => isReplaceableKind(kind))\n ? filter.authors.length * filter.kinds.length\n : Infinity,\n\n // Parameterized replaceable events are limited by the number of authors, kinds, and \"d\" tags.\n filter.authors?.length && filter.kinds?.every(kind => isAddressableKind(kind)) && filter['#d']?.length\n ? filter.authors.length * filter.kinds.length * filter['#d'].length\n : Infinity,\n )\n}\n", "export function getHex64(json: string, field: string): string {\n let len = field.length + 3\n let idx = json.indexOf(`\"${field}\":`) + len\n let s = json.slice(idx).indexOf(`\"`) + idx + 1\n return json.slice(s, s + 64)\n}\n\nexport function getInt(json: string, field: string): number {\n let len = field.length\n let idx = json.indexOf(`\"${field}\":`) + len + 3\n let sliced = json.slice(idx)\n let end = Math.min(sliced.indexOf(','), sliced.indexOf('}'))\n return parseInt(sliced.slice(0, end), 10)\n}\n\nexport function getSubscriptionId(json: string): string | null {\n let idx = json.slice(0, 22).indexOf(`\"EVENT\"`)\n if (idx === -1) return null\n\n let pstart = json.slice(idx + 7 + 1).indexOf(`\"`)\n if (pstart === -1) return null\n let start = idx + 7 + 1 + pstart\n\n let pend = json.slice(start + 1, 80).indexOf(`\"`)\n if (pend === -1) return null\n let end = start + 1 + pend\n\n return json.slice(start + 1, end)\n}\n\nexport function matchEventId(json: string, id: string): boolean {\n return id === getHex64(json, 'id')\n}\n\nexport function matchEventPubkey(json: string, pubkey: string): boolean {\n return pubkey === getHex64(json, 'pubkey')\n}\n\nexport function matchEventKind(json: string, kind: number): boolean {\n return kind === getInt(json, 'kind')\n}\n", "import { EventTemplate } from './core.ts'\nimport { ClientAuth } from './kinds.ts'\n\n/**\n * creates an EventTemplate for an AUTH event to be signed.\n */\nexport function makeAuthEvent(relayURL: string, challenge: string): EventTemplate {\n return {\n kind: ClientAuth,\n created_at: Math.floor(Date.now() / 1000),\n tags: [\n ['relay', relayURL],\n ['challenge', challenge],\n ],\n content: '',\n }\n}\n", "import { verifiedSymbol, type Event, type Nostr, VerifiedEvent } from './core.ts'\n\nexport async function yieldThread() {\n return new Promise(resolve => {\n const ch = new MessageChannel()\n const handler = () => {\n // @ts-ignore (typescript thinks this property should be called `removeListener`, but in fact it's `removeEventListener`)\n ch.port1.removeEventListener('message', handler)\n resolve()\n }\n // @ts-ignore (typescript thinks this property should be called `addListener`, but in fact it's `addEventListener`)\n ch.port1.addEventListener('message', handler)\n ch.port2.postMessage(0)\n ch.port1.start()\n })\n}\n\nexport const alwaysTrue: Nostr['verifyEvent'] = (t: Event): t is VerifiedEvent => {\n t[verifiedSymbol] = true\n return true\n}\n", "/* global WebSocket */\n\nimport type { Event, EventTemplate, VerifiedEvent, Nostr, NostrEvent } from './core.ts'\nimport { matchFilters, type Filter } from './filter.ts'\nimport { getHex64, getSubscriptionId } from './fakejson.ts'\nimport { Queue, normalizeURL } from './utils.ts'\nimport { makeAuthEvent } from './nip42.ts'\nimport { yieldThread } from './helpers.ts'\n\ntype RelayWebSocket = WebSocket & {\n ping?(): void\n on?(event: 'pong', listener: () => void): any\n}\n\nexport type AbstractRelayConstructorOptions = {\n verifyEvent: Nostr['verifyEvent']\n websocketImplementation?: typeof WebSocket\n enablePing?: boolean\n}\n\nexport class SendingOnClosedConnection extends Error {\n constructor(message: string, relay: string) {\n super(`Tried to send message '${message} on a closed connection to ${relay}.`)\n this.name = 'SendingOnClosedConnection'\n }\n}\n\nexport class AbstractRelay {\n public readonly url: string\n private _connected: boolean = false\n\n public onclose: (() => void) | null = null\n public onnotice: (msg: string) => void = msg => console.debug(`NOTICE from ${this.url}: ${msg}`)\n\n public baseEoseTimeout: number = 4400\n public connectionTimeout: number = 4400\n public publishTimeout: number = 4400\n public pingFrequency: number = 20000\n public pingTimeout: number = 20000\n public openSubs: Map = new Map()\n public enablePing: boolean | undefined\n private connectionTimeoutHandle: ReturnType | undefined\n\n private connectionPromise: Promise | undefined\n private openCountRequests = new Map()\n private openEventPublishes = new Map()\n private ws: RelayWebSocket | undefined\n private incomingMessageQueue = new Queue()\n private queueRunning = false\n private challenge: string | undefined\n private authPromise: Promise | undefined\n private serial: number = 0\n private verifyEvent: Nostr['verifyEvent']\n\n private _WebSocket: typeof WebSocket\n\n constructor(url: string, opts: AbstractRelayConstructorOptions) {\n this.url = normalizeURL(url)\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation || WebSocket\n this.enablePing = opts.enablePing\n }\n\n static async connect(url: string, opts: AbstractRelayConstructorOptions): Promise {\n const relay = new AbstractRelay(url, opts)\n await relay.connect()\n return relay\n }\n\n private closeAllSubscriptions(reason: string) {\n for (let [_, sub] of this.openSubs) {\n sub.close(reason)\n }\n this.openSubs.clear()\n\n for (let [_, ep] of this.openEventPublishes) {\n ep.reject(new Error(reason))\n }\n this.openEventPublishes.clear()\n\n for (let [_, cr] of this.openCountRequests) {\n cr.reject(new Error(reason))\n }\n this.openCountRequests.clear()\n }\n\n public get connected(): boolean {\n return this._connected\n }\n\n public async connect(): Promise {\n if (this.connectionPromise) return this.connectionPromise\n\n this.challenge = undefined\n this.authPromise = undefined\n this.connectionPromise = new Promise((resolve, reject) => {\n this.connectionTimeoutHandle = setTimeout(() => {\n reject('connection timed out')\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection timed out')\n }, this.connectionTimeout)\n\n try {\n this.ws = new this._WebSocket(this.url)\n } catch (err) {\n clearTimeout(this.connectionTimeoutHandle)\n reject(err)\n return\n }\n\n this.ws.onopen = () => {\n clearTimeout(this.connectionTimeoutHandle)\n this._connected = true\n if (this.enablePing) {\n this.pingpong()\n }\n resolve()\n }\n\n this.ws.onerror = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket error')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection errored')\n }\n }\n\n this.ws.onclose = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket closed')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection closed')\n }\n }\n\n this.ws.onmessage = this._onmessage.bind(this)\n })\n\n return this.connectionPromise\n }\n\n private async waitForPingPong() {\n return new Promise((res, err) => {\n // listen for pong\n ;(this.ws && this.ws.on && this.ws.on('pong', () => res(true))) || err(\"ws can't listen for pong\")\n // send a ping\n this.ws && this.ws.ping && this.ws.ping()\n })\n }\n\n private async waitForDummyReq() {\n return new Promise((resolve, _) => {\n // make a dummy request with expected empty eose reply\n // [\"REQ\", \"_\", {\"ids\":[\"aaaa...aaaa\"]}]\n const sub = this.subscribe([{ ids: ['a'.repeat(64)] }], {\n oneose: () => {\n sub.close()\n resolve(true)\n },\n eoseTimeout: this.pingTimeout + 1000,\n })\n })\n }\n\n // nodejs requires this magic here to ensure connections are closed when internet goes off and stuff\n // in browsers it's done automatically. see https://github.com/nbd-wtf/nostr-tools/issues/491\n private async pingpong() {\n // if the websocket is connected\n if (this.ws?.readyState === 1) {\n // wait for either a ping-pong reply or a timeout\n const result = await Promise.any([\n // browsers don't have ping so use a dummy req\n this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(),\n new Promise(res => setTimeout(() => res(false), this.pingTimeout)),\n ])\n if (result) {\n // schedule another pingpong\n setTimeout(() => this.pingpong(), this.pingFrequency)\n } else {\n // pingpong closing socket\n this.closeAllSubscriptions('pingpong timed out')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n }\n }\n\n private async runQueue() {\n this.queueRunning = true\n while (true) {\n if (false === this.handleNext()) {\n break\n }\n await yieldThread()\n }\n this.queueRunning = false\n }\n\n private handleNext(): undefined | false {\n const json = this.incomingMessageQueue.dequeue()\n if (!json) {\n return false\n }\n\n const subid = getSubscriptionId(json)\n if (subid) {\n const so = this.openSubs.get(subid as string)\n if (!so) {\n // this is an EVENT message, but for a subscription we don't have, so just stop here\n return\n }\n\n // this will be called only when this message is a EVENT message for a subscription we have\n // we do this before parsing the JSON to not have to do that for duplicate events\n // since JSON parsing is slow\n const id = getHex64(json, 'id')\n const alreadyHave = so.alreadyHaveEvent?.(id)\n\n // notify any interested client that the relay has this event\n // (do this after alreadyHaveEvent() because the client may rely on this to answer that)\n so.receivedEvent?.(this, id)\n\n if (alreadyHave) {\n // if we had already seen this event we can just stop here\n return\n }\n }\n\n try {\n let data = JSON.parse(json)\n // we won't do any checks against the data since all failures (i.e. invalid messages from relays)\n // will naturally be caught by the encompassing try..catch block\n\n switch (data[0]) {\n case 'EVENT': {\n const so = this.openSubs.get(data[1] as string) as Subscription\n const event = data[2] as NostrEvent\n if (this.verifyEvent(event) && matchFilters(so.filters, event)) {\n so.onevent(event)\n }\n return\n }\n case 'COUNT': {\n const id: string = data[1]\n const payload = data[2] as { count: number }\n const cr = this.openCountRequests.get(id) as CountResolver\n if (cr) {\n cr.resolve(payload.count)\n this.openCountRequests.delete(id)\n }\n return\n }\n case 'EOSE': {\n const so = this.openSubs.get(data[1] as string)\n if (!so) return\n so.receivedEose()\n return\n }\n case 'OK': {\n const id: string = data[1]\n const ok: boolean = data[2]\n const reason: string = data[3]\n const ep = this.openEventPublishes.get(id) as EventPublishResolver\n if (ep) {\n clearTimeout(ep.timeout)\n if (ok) ep.resolve(reason)\n else ep.reject(new Error(reason))\n this.openEventPublishes.delete(id)\n }\n return\n }\n case 'CLOSED': {\n const id: string = data[1]\n const so = this.openSubs.get(id)\n if (!so) return\n so.closed = true\n so.close(data[2] as string)\n return\n }\n case 'NOTICE':\n this.onnotice(data[1] as string)\n return\n case 'AUTH': {\n this.challenge = data[1] as string\n return\n }\n }\n } catch (err) {\n return\n }\n }\n\n public async send(message: string) {\n if (!this.connectionPromise) throw new SendingOnClosedConnection(message, this.url)\n\n this.connectionPromise.then(() => {\n this.ws?.send(message)\n })\n }\n\n public async auth(signAuthEvent: (evt: EventTemplate) => Promise): Promise {\n const challenge = this.challenge\n if (!challenge) throw new Error(\"can't perform auth, no challenge was received\")\n if (this.authPromise) return this.authPromise\n\n this.authPromise = new Promise(async (resolve, reject) => {\n try {\n let evt = await signAuthEvent(makeAuthEvent(this.url, challenge))\n let timeout = setTimeout(() => {\n let ep = this.openEventPublishes.get(evt.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('auth timed out'))\n this.openEventPublishes.delete(evt.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(evt.id, { resolve, reject, timeout })\n this.send('[\"AUTH\",' + JSON.stringify(evt) + ']')\n } catch (err) {\n console.warn('subscribe auth function failed:', err)\n }\n })\n return this.authPromise\n }\n\n public async publish(event: Event): Promise {\n const ret = new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n const ep = this.openEventPublishes.get(event.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('publish timed out'))\n this.openEventPublishes.delete(event.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(event.id, { resolve, reject, timeout })\n })\n this.send('[\"EVENT\",' + JSON.stringify(event) + ']')\n return ret\n }\n\n public async count(filters: Filter[], params: { id?: string | null }): Promise {\n this.serial++\n const id = params?.id || 'count:' + this.serial\n const ret = new Promise((resolve, reject) => {\n this.openCountRequests.set(id, { resolve, reject })\n })\n this.send('[\"COUNT\",\"' + id + '\",' + JSON.stringify(filters).substring(1))\n return ret\n }\n\n public subscribe(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n const subscription = this.prepareSubscription(filters, params)\n subscription.fire()\n return subscription\n }\n\n public prepareSubscription(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n this.serial++\n const id = params.id || (params.label ? params.label + ':' : 'sub:') + this.serial\n const subscription = new Subscription(this, id, filters, params)\n this.openSubs.set(id, subscription)\n return subscription\n }\n\n public close() {\n this.closeAllSubscriptions('relay connection closed by us')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n\n // this is the function assigned to this.ws.onmessage\n // it's exposed for testing and debugging purposes\n public _onmessage(ev: MessageEvent) {\n this.incomingMessageQueue.enqueue(ev.data as string)\n if (!this.queueRunning) {\n this.runQueue()\n }\n }\n}\n\nexport class Subscription {\n public readonly relay: AbstractRelay\n public readonly id: string\n\n public closed: boolean = false\n public eosed: boolean = false\n public filters: Filter[]\n public alreadyHaveEvent: ((id: string) => boolean) | undefined\n public receivedEvent: ((relay: AbstractRelay, id: string) => void) | undefined\n\n public onevent: (evt: Event) => void\n public oneose: (() => void) | undefined\n public onclose: ((reason: string) => void) | undefined\n\n public eoseTimeout: number\n private eoseTimeoutHandle: ReturnType | undefined\n\n constructor(relay: AbstractRelay, id: string, filters: Filter[], params: SubscriptionParams) {\n this.relay = relay\n this.filters = filters\n this.id = id\n this.alreadyHaveEvent = params.alreadyHaveEvent\n this.receivedEvent = params.receivedEvent\n this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout\n\n this.oneose = params.oneose\n this.onclose = params.onclose\n this.onevent =\n params.onevent ||\n (event => {\n console.warn(\n `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,\n event,\n )\n })\n }\n\n public fire() {\n this.relay.send('[\"REQ\",\"' + this.id + '\",' + JSON.stringify(this.filters).substring(1))\n\n // only now we start counting the eoseTimeout\n this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout)\n }\n\n public receivedEose() {\n if (this.eosed) return\n clearTimeout(this.eoseTimeoutHandle)\n this.eosed = true\n this.oneose?.()\n }\n\n public close(reason: string = 'closed by caller') {\n if (!this.closed && this.relay.connected) {\n // if the connection was closed by the user calling .close() we will send a CLOSE message\n // otherwise this._open will be already set to false so we will skip this\n try {\n this.relay.send('[\"CLOSE\",' + JSON.stringify(this.id) + ']')\n } catch (err) {\n if (err instanceof SendingOnClosedConnection) {\n /* doesn't matter, it's ok */\n } else {\n throw err\n }\n }\n this.closed = true\n }\n this.relay.openSubs.delete(this.id)\n this.onclose?.(reason)\n }\n}\n\nexport type SubscriptionParams = {\n onevent?: (evt: Event) => void\n oneose?: () => void\n onclose?: (reason: string) => void\n alreadyHaveEvent?: (id: string) => boolean\n receivedEvent?: (relay: AbstractRelay, id: string) => void\n eoseTimeout?: number\n}\n\nexport type CountResolver = {\n resolve: (count: number) => void\n reject: (err: Error) => void\n}\n\nexport type EventPublishResolver = {\n resolve: (reason: string) => void\n reject: (err: Error) => void\n timeout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EO,eAAe;AACpB,QAAI,KAAK;AAAO;AAChB,iBAAa,KAAK,iBAAiB;AACnC,SAAK,QAAQ;AACb,SAAK,SAAS;AAAA,EAChB;AAAA,EAEO,MAAM,SAAiB,oBAAoB;AAChD,QAAI,CAAC,KAAK,UAAU,KAAK,MAAM,WAAW;AAGxC,UAAI;AACF,aAAK,MAAM,KAAK,cAAc,KAAK,UAAU,KAAK,EAAE,IAAI,GAAG;AAAA,MAC7D,SAAS,KAAP;AACA,YAAI,eAAe,2BAA2B;AAAA,QAE9C,OAAO;AACL,gBAAM;AAAA,QACR;AAAA,MACF;AACA,WAAK,SAAS;AAAA,IAChB;AACA,SAAK,MAAM,SAAS,OAAO,KAAK,EAAE;AAClC,SAAK,UAAU,MAAM;AAAA,EACvB;AACF;", + "names": ["target"] +} diff --git a/node_modules/nostr-tools/lib/esm/fakejson.js b/node_modules/nostr-tools/lib/esm/fakejson.js new file mode 100644 index 0000000..6599af7 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/fakejson.js @@ -0,0 +1,45 @@ +// fakejson.ts +function getHex64(json, field) { + let len = field.length + 3; + let idx = json.indexOf(`"${field}":`) + len; + let s = json.slice(idx).indexOf(`"`) + idx + 1; + return json.slice(s, s + 64); +} +function getInt(json, field) { + let len = field.length; + let idx = json.indexOf(`"${field}":`) + len + 3; + let sliced = json.slice(idx); + let end = Math.min(sliced.indexOf(","), sliced.indexOf("}")); + return parseInt(sliced.slice(0, end), 10); +} +function getSubscriptionId(json) { + let idx = json.slice(0, 22).indexOf(`"EVENT"`); + if (idx === -1) + return null; + let pstart = json.slice(idx + 7 + 1).indexOf(`"`); + if (pstart === -1) + return null; + let start = idx + 7 + 1 + pstart; + let pend = json.slice(start + 1, 80).indexOf(`"`); + if (pend === -1) + return null; + let end = start + 1 + pend; + return json.slice(start + 1, end); +} +function matchEventId(json, id) { + return id === getHex64(json, "id"); +} +function matchEventPubkey(json, pubkey) { + return pubkey === getHex64(json, "pubkey"); +} +function matchEventKind(json, kind) { + return kind === getInt(json, "kind"); +} +export { + getHex64, + getInt, + getSubscriptionId, + matchEventId, + matchEventKind, + matchEventPubkey +}; diff --git a/node_modules/nostr-tools/lib/esm/fakejson.js.map b/node_modules/nostr-tools/lib/esm/fakejson.js.map new file mode 100644 index 0000000..e44e70a --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/fakejson.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../fakejson.ts"], + "sourcesContent": ["export function getHex64(json: string, field: string): string {\n let len = field.length + 3\n let idx = json.indexOf(`\"${field}\":`) + len\n let s = json.slice(idx).indexOf(`\"`) + idx + 1\n return json.slice(s, s + 64)\n}\n\nexport function getInt(json: string, field: string): number {\n let len = field.length\n let idx = json.indexOf(`\"${field}\":`) + len + 3\n let sliced = json.slice(idx)\n let end = Math.min(sliced.indexOf(','), sliced.indexOf('}'))\n return parseInt(sliced.slice(0, end), 10)\n}\n\nexport function getSubscriptionId(json: string): string | null {\n let idx = json.slice(0, 22).indexOf(`\"EVENT\"`)\n if (idx === -1) return null\n\n let pstart = json.slice(idx + 7 + 1).indexOf(`\"`)\n if (pstart === -1) return null\n let start = idx + 7 + 1 + pstart\n\n let pend = json.slice(start + 1, 80).indexOf(`\"`)\n if (pend === -1) return null\n let end = start + 1 + pend\n\n return json.slice(start + 1, end)\n}\n\nexport function matchEventId(json: string, id: string): boolean {\n return id === getHex64(json, 'id')\n}\n\nexport function matchEventPubkey(json: string, pubkey: string): boolean {\n return pubkey === getHex64(json, 'pubkey')\n}\n\nexport function matchEventKind(json: string, kind: number): boolean {\n return kind === getInt(json, 'kind')\n}\n"], + "mappings": ";AAAO,SAAS,SAAS,MAAc,OAAuB;AAC5D,MAAI,MAAM,MAAM,SAAS;AACzB,MAAI,MAAM,KAAK,QAAQ,IAAI,SAAS,IAAI;AACxC,MAAI,IAAI,KAAK,MAAM,GAAG,EAAE,QAAQ,GAAG,IAAI,MAAM;AAC7C,SAAO,KAAK,MAAM,GAAG,IAAI,EAAE;AAC7B;AAEO,SAAS,OAAO,MAAc,OAAuB;AAC1D,MAAI,MAAM,MAAM;AAChB,MAAI,MAAM,KAAK,QAAQ,IAAI,SAAS,IAAI,MAAM;AAC9C,MAAI,SAAS,KAAK,MAAM,GAAG;AAC3B,MAAI,MAAM,KAAK,IAAI,OAAO,QAAQ,GAAG,GAAG,OAAO,QAAQ,GAAG,CAAC;AAC3D,SAAO,SAAS,OAAO,MAAM,GAAG,GAAG,GAAG,EAAE;AAC1C;AAEO,SAAS,kBAAkB,MAA6B;AAC7D,MAAI,MAAM,KAAK,MAAM,GAAG,EAAE,EAAE,QAAQ,SAAS;AAC7C,MAAI,QAAQ;AAAI,WAAO;AAEvB,MAAI,SAAS,KAAK,MAAM,MAAM,IAAI,CAAC,EAAE,QAAQ,GAAG;AAChD,MAAI,WAAW;AAAI,WAAO;AAC1B,MAAI,QAAQ,MAAM,IAAI,IAAI;AAE1B,MAAI,OAAO,KAAK,MAAM,QAAQ,GAAG,EAAE,EAAE,QAAQ,GAAG;AAChD,MAAI,SAAS;AAAI,WAAO;AACxB,MAAI,MAAM,QAAQ,IAAI;AAEtB,SAAO,KAAK,MAAM,QAAQ,GAAG,GAAG;AAClC;AAEO,SAAS,aAAa,MAAc,IAAqB;AAC9D,SAAO,OAAO,SAAS,MAAM,IAAI;AACnC;AAEO,SAAS,iBAAiB,MAAc,QAAyB;AACtE,SAAO,WAAW,SAAS,MAAM,QAAQ;AAC3C;AAEO,SAAS,eAAe,MAAc,MAAuB;AAClE,SAAO,SAAS,OAAO,MAAM,MAAM;AACrC;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/esm/filter.js b/node_modules/nostr-tools/lib/esm/filter.js new file mode 100644 index 0000000..a73113e --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/filter.js @@ -0,0 +1,88 @@ +// kinds.ts +function isReplaceableKind(kind) { + return [0, 3].includes(kind) || 1e4 <= kind && kind < 2e4; +} +function isAddressableKind(kind) { + return 3e4 <= kind && kind < 4e4; +} + +// filter.ts +function matchFilter(filter, event) { + if (filter.ids && filter.ids.indexOf(event.id) === -1) { + return false; + } + if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) { + return false; + } + if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) { + return false; + } + for (let f in filter) { + if (f[0] === "#") { + let tagName = f.slice(1); + let values = filter[`#${tagName}`]; + if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values.indexOf(v) !== -1)) + return false; + } + } + if (filter.since && event.created_at < filter.since) + return false; + if (filter.until && event.created_at > filter.until) + return false; + return true; +} +function matchFilters(filters, event) { + for (let i = 0; i < filters.length; i++) { + if (matchFilter(filters[i], event)) { + return true; + } + } + return false; +} +function mergeFilters(...filters) { + let result = {}; + for (let i = 0; i < filters.length; i++) { + let filter = filters[i]; + Object.entries(filter).forEach(([property, values]) => { + if (property === "kinds" || property === "ids" || property === "authors" || property[0] === "#") { + result[property] = result[property] || []; + for (let v = 0; v < values.length; v++) { + let value = values[v]; + if (!result[property].includes(value)) + result[property].push(value); + } + } + }); + if (filter.limit && (!result.limit || filter.limit > result.limit)) + result.limit = filter.limit; + if (filter.until && (!result.until || filter.until > result.until)) + result.until = filter.until; + if (filter.since && (!result.since || filter.since < result.since)) + result.since = filter.since; + } + return result; +} +function getFilterLimit(filter) { + if (filter.ids && !filter.ids.length) + return 0; + if (filter.kinds && !filter.kinds.length) + return 0; + if (filter.authors && !filter.authors.length) + return 0; + for (const [key, value] of Object.entries(filter)) { + if (key[0] === "#" && Array.isArray(value) && !value.length) + return 0; + } + return Math.min( + Math.max(0, filter.limit ?? Infinity), + filter.ids?.length ?? Infinity, + filter.authors?.length && filter.kinds?.every((kind) => isReplaceableKind(kind)) ? filter.authors.length * filter.kinds.length : Infinity, + filter.authors?.length && filter.kinds?.every((kind) => isAddressableKind(kind)) && filter["#d"]?.length ? filter.authors.length * filter.kinds.length * filter["#d"].length : Infinity + ); +} +export { + getFilterLimit, + matchFilter, + matchFilters, + mergeFilters +}; diff --git a/node_modules/nostr-tools/lib/esm/filter.js.map b/node_modules/nostr-tools/lib/esm/filter.js.map new file mode 100644 index 0000000..0fd9a7b --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/filter.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../kinds.ts", "../../filter.ts"], + "sourcesContent": ["import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { Event } from './core.ts'\nimport { isAddressableKind, isReplaceableKind } from './kinds.ts'\n\nexport type Filter = {\n ids?: string[]\n kinds?: number[]\n authors?: string[]\n since?: number\n until?: number\n limit?: number\n search?: string\n [key: `#${string}`]: string[] | undefined\n}\n\nexport function matchFilter(filter: Filter, event: Event): boolean {\n if (filter.ids && filter.ids.indexOf(event.id) === -1) {\n return false\n }\n if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) {\n return false\n }\n if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) {\n return false\n }\n\n for (let f in filter) {\n if (f[0] === '#') {\n let tagName = f.slice(1)\n let values = filter[`#${tagName}`]\n if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values!.indexOf(v) !== -1)) return false\n }\n }\n\n if (filter.since && event.created_at < filter.since) return false\n if (filter.until && event.created_at > filter.until) return false\n\n return true\n}\n\nexport function matchFilters(filters: Filter[], event: Event): boolean {\n for (let i = 0; i < filters.length; i++) {\n if (matchFilter(filters[i], event)) {\n return true\n }\n }\n return false\n}\n\nexport function mergeFilters(...filters: Filter[]): Filter {\n let result: Filter = {}\n for (let i = 0; i < filters.length; i++) {\n let filter = filters[i]\n Object.entries(filter).forEach(([property, values]) => {\n if (property === 'kinds' || property === 'ids' || property === 'authors' || property[0] === '#') {\n // @ts-ignore\n result[property] = result[property] || []\n // @ts-ignore\n for (let v = 0; v < values.length; v++) {\n // @ts-ignore\n let value = values[v]\n // @ts-ignore\n if (!result[property].includes(value)) result[property].push(value)\n }\n }\n })\n\n if (filter.limit && (!result.limit || filter.limit > result.limit)) result.limit = filter.limit\n if (filter.until && (!result.until || filter.until > result.until)) result.until = filter.until\n if (filter.since && (!result.since || filter.since < result.since)) result.since = filter.since\n }\n\n return result\n}\n\n/**\n * Calculate the intrinsic limit of a filter.\n * This function returns a positive integer, or `Infinity` if there is no intrinsic limit.\n */\nexport function getFilterLimit(filter: Filter): number {\n if (filter.ids && !filter.ids.length) return 0\n if (filter.kinds && !filter.kinds.length) return 0\n if (filter.authors && !filter.authors.length) return 0\n\n for (const [key, value] of Object.entries(filter)) {\n if (key[0] === '#' && Array.isArray(value) && !value.length) return 0\n }\n\n return Math.min(\n // The `limit` property creates an artificial limit.\n Math.max(0, filter.limit ?? Infinity),\n\n // There can only be one event per `id`.\n filter.ids?.length ?? Infinity,\n\n // Replaceable events are limited by the number of authors and kinds.\n filter.authors?.length && filter.kinds?.every(kind => isReplaceableKind(kind))\n ? filter.authors.length * filter.kinds.length\n : Infinity,\n\n // Parameterized replaceable events are limited by the number of authors, kinds, and \"d\" tags.\n filter.authors?.length && filter.kinds?.every(kind => isAddressableKind(kind)) && filter['#d']?.length\n ? filter.authors.length * filter.kinds.length * filter['#d'].length\n : Infinity,\n )\n}\n"], + "mappings": ";AAQO,SAAS,kBAAkB,MAAuB;AACvD,SAAO,CAAC,GAAG,CAAC,EAAE,SAAS,IAAI,KAAM,OAAS,QAAQ,OAAO;AAC3D;AAQO,SAAS,kBAAkB,MAAuB;AACvD,SAAO,OAAS,QAAQ,OAAO;AACjC;;;ACNO,SAAS,YAAY,QAAgB,OAAuB;AACjE,MAAI,OAAO,OAAO,OAAO,IAAI,QAAQ,MAAM,EAAE,MAAM,IAAI;AACrD,WAAO;AAAA,EACT;AACA,MAAI,OAAO,SAAS,OAAO,MAAM,QAAQ,MAAM,IAAI,MAAM,IAAI;AAC3D,WAAO;AAAA,EACT;AACA,MAAI,OAAO,WAAW,OAAO,QAAQ,QAAQ,MAAM,MAAM,MAAM,IAAI;AACjE,WAAO;AAAA,EACT;AAEA,WAAS,KAAK,QAAQ;AACpB,QAAI,EAAE,OAAO,KAAK;AAChB,UAAI,UAAU,EAAE,MAAM,CAAC;AACvB,UAAI,SAAS,OAAO,IAAI;AACxB,UAAI,UAAU,CAAC,MAAM,KAAK,KAAK,CAAC,CAAC,GAAG,CAAC,MAAM,MAAM,EAAE,MAAM,CAAC,KAAK,OAAQ,QAAQ,CAAC,MAAM,EAAE;AAAG,eAAO;AAAA,IACpG;AAAA,EACF;AAEA,MAAI,OAAO,SAAS,MAAM,aAAa,OAAO;AAAO,WAAO;AAC5D,MAAI,OAAO,SAAS,MAAM,aAAa,OAAO;AAAO,WAAO;AAE5D,SAAO;AACT;AAEO,SAAS,aAAa,SAAmB,OAAuB;AACrE,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,QAAI,YAAY,QAAQ,IAAI,KAAK,GAAG;AAClC,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAEO,SAAS,g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,OAAO,SAAS,UAAU,OAAO,OAAO,MAAM,UAAQ,kBAAkB,IAAI,CAAC,IACzE,OAAO,QAAQ,SAAS,OAAO,MAAM,SACrC;AAAA,IAGJ,OAAO,SAAS,UAAU,OAAO,OAAO,MAAM,UAAQ,kBAAkB,IAAI,CAAC,KAAK,OAAO,OAAO,SAC5F,OAAO,QAAQ,SAAS,OAAO,MAAM,SAAS,OAAO,MAAM,SAC3D;AAAA,EACN;AACF;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/esm/index.js b/node_modules/nostr-tools/lib/esm/index.js new file mode 100644 index 0000000..0632ab6 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/index.js @@ -0,0 +1,2763 @@ +var __defProp = Object.defineProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; + +// pure.ts +import { schnorr } from "@noble/curves/secp256k1"; +import { bytesToHex as bytesToHex2 } from "@noble/hashes/utils"; + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} +function sortEvents(events) { + return events.sort((a, b) => { + if (a.created_at !== b.created_at) { + return b.created_at - a.created_at; + } + return a.id.localeCompare(b.id); + }); +} + +// pure.ts +import { sha256 } from "@noble/hashes/sha256"; + +// utils.ts +var utils_exports = {}; +__export(utils_exports, { + Queue: () => Queue, + QueueNode: () => QueueNode, + binarySearch: () => binarySearch, + bytesToHex: () => bytesToHex, + hexToBytes: () => hexToBytes, + insertEventIntoAscendingList: () => insertEventIntoAscendingList, + insertEventIntoDescendingList: () => insertEventIntoDescendingList, + normalizeURL: () => normalizeURL, + utf8Decoder: () => utf8Decoder, + utf8Encoder: () => utf8Encoder +}); +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); +function normalizeURL(url) { + try { + if (url.indexOf("://") === -1) + url = "wss://" + url; + let p = new URL(url); + p.pathname = p.pathname.replace(/\/+/g, "/"); + if (p.pathname.endsWith("/")) + p.pathname = p.pathname.slice(0, -1); + if (p.port === "80" && p.protocol === "ws:" || p.port === "443" && p.protocol === "wss:") + p.port = ""; + p.searchParams.sort(); + p.hash = ""; + return p.toString(); + } catch (e) { + throw new Error(`Invalid URL: ${url}`); + } +} +function insertEventIntoDescendingList(sortedArray, event) { + const [idx, found] = binarySearch(sortedArray, (b) => { + if (event.id === b.id) + return 0; + if (event.created_at === b.created_at) + return -1; + return b.created_at - event.created_at; + }); + if (!found) { + sortedArray.splice(idx, 0, event); + } + return sortedArray; +} +function insertEventIntoAscendingList(sortedArray, event) { + const [idx, found] = binarySearch(sortedArray, (b) => { + if (event.id === b.id) + return 0; + if (event.created_at === b.created_at) + return -1; + return event.created_at - b.created_at; + }); + if (!found) { + sortedArray.splice(idx, 0, event); + } + return sortedArray; +} +function binarySearch(arr, compare) { + let start = 0; + let end = arr.length - 1; + while (start <= end) { + const mid = Math.floor((start + end) / 2); + const cmp = compare(arr[mid]); + if (cmp === 0) { + return [mid, true]; + } + if (cmp < 0) { + end = mid - 1; + } else { + start = mid + 1; + } + } + return [start, false]; +} +var QueueNode = class { + value; + next = null; + prev = null; + constructor(message) { + this.value = message; + } +}; +var Queue = class { + first; + last; + constructor() { + this.first = null; + this.last = null; + } + enqueue(value) { + const newNode = new QueueNode(value); + if (!this.last) { + this.first = newNode; + this.last = newNode; + } else if (this.last === this.first) { + this.last = newNode; + this.last.prev = this.first; + this.first.next = newNode; + } else { + newNode.prev = this.last; + this.last.next = newNode; + this.last = newNode; + } + return true; + } + dequeue() { + if (!this.first) + return null; + if (this.first === this.last) { + const target2 = this.first; + this.first = null; + this.last = null; + return target2.value; + } + const target = this.first; + this.first = target.next; + if (this.first) { + this.first.prev = null; + } + return target.value; + } +}; + +// pure.ts +var JS = class { + generateSecretKey() { + return schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return bytesToHex2(schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = bytesToHex2(schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = bytesToHex2(schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = sha256(utf8Encoder.encode(serializeEvent(event))); + return bytesToHex2(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// kinds.ts +var kinds_exports = {}; +__export(kinds_exports, { + Application: () => Application, + BadgeAward: () => BadgeAward, + BadgeDefinition: () => BadgeDefinition, + BlockedRelaysList: () => BlockedRelaysList, + BookmarkList: () => BookmarkList, + Bookmarksets: () => Bookmarksets, + Calendar: () => Calendar, + CalendarEventRSVP: () => CalendarEventRSVP, + ChannelCreation: () => ChannelCreation, + ChannelHideMessage: () => ChannelHideMessage, + ChannelMessage: () => ChannelMessage, + ChannelMetadata: () => ChannelMetadata, + ChannelMuteUser: () => ChannelMuteUser, + ClassifiedListing: () => ClassifiedListing, + ClientAuth: () => ClientAuth, + CommunitiesList: () => CommunitiesList, + CommunityDefinition: () => CommunityDefinition, + CommunityPostApproval: () => CommunityPostApproval, + Contacts: () => Contacts, + CreateOrUpdateProduct: () => CreateOrUpdateProduct, + CreateOrUpdateStall: () => CreateOrUpdateStall, + Curationsets: () => Curationsets, + Date: () => Date2, + DirectMessageRelaysList: () => DirectMessageRelaysList, + DraftClassifiedListing: () => DraftClassifiedListing, + DraftLong: () => DraftLong, + Emojisets: () => Emojisets, + EncryptedDirectMessage: () => EncryptedDirectMessage, + EventDeletion: () => EventDeletion, + FileMetadata: () => FileMetadata, + FileServerPreference: () => FileServerPreference, + Followsets: () => Followsets, + GenericRepost: () => GenericRepost, + Genericlists: () => Genericlists, + GiftWrap: () => GiftWrap, + HTTPAuth: () => HTTPAuth, + Handlerinformation: () => Handlerinformation, + Handlerrecommendation: () => Handlerrecommendation, + Highlights: () => Highlights, + InterestsList: () => InterestsList, + Interestsets: () => Interestsets, + JobFeedback: () => JobFeedback, + JobRequest: () => JobRequest, + JobResult: () => JobResult, + Label: () => Label, + LightningPubRPC: () => LightningPubRPC, + LiveChatMessage: () => LiveChatMessage, + LiveEvent: () => LiveEvent, + LongFormArticle: () => LongFormArticle, + Metadata: () => Metadata, + Mutelist: () => Mutelist, + NWCWalletInfo: () => NWCWalletInfo, + NWCWalletRequest: () => NWCWalletRequest, + NWCWalletResponse: () => NWCWalletResponse, + NostrConnect: () => NostrConnect, + OpenTimestamps: () => OpenTimestamps, + Pinlist: () => Pinlist, + PrivateDirectMessage: () => PrivateDirectMessage, + ProblemTracker: () => ProblemTracker, + ProfileBadges: () => ProfileBadges, + PublicChatsList: () => PublicChatsList, + Reaction: () => Reaction, + RecommendRelay: () => RecommendRelay, + RelayList: () => RelayList, + Relaysets: () => Relaysets, + Report: () => Report, + Reporting: () => Reporting, + Repost: () => Repost, + Seal: () => Seal, + SearchRelaysList: () => SearchRelaysList, + ShortTextNote: () => ShortTextNote, + Time: () => Time, + UserEmojiList: () => UserEmojiList, + UserStatuses: () => UserStatuses, + Zap: () => Zap, + ZapGoal: () => ZapGoal, + ZapRequest: () => ZapRequest, + classifyKind: () => classifyKind, + isAddressableKind: () => isAddressableKind, + isEphemeralKind: () => isEphemeralKind, + isKind: () => isKind, + isRegularKind: () => isRegularKind, + isReplaceableKind: () => isReplaceableKind +}); +function isRegularKind(kind) { + return 1e3 <= kind && kind < 1e4 || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind); +} +function isReplaceableKind(kind) { + return [0, 3].includes(kind) || 1e4 <= kind && kind < 2e4; +} +function isEphemeralKind(kind) { + return 2e4 <= kind && kind < 3e4; +} +function isAddressableKind(kind) { + return 3e4 <= kind && kind < 4e4; +} +function classifyKind(kind) { + if (isRegularKind(kind)) + return "regular"; + if (isReplaceableKind(kind)) + return "replaceable"; + if (isEphemeralKind(kind)) + return "ephemeral"; + if (isAddressableKind(kind)) + return "parameterized"; + return "unknown"; +} +function isKind(event, kind) { + const kindAsArray = kind instanceof Array ? kind : [kind]; + return validateEvent(event) && kindAsArray.includes(event.kind) || false; +} +var Metadata = 0; +var ShortTextNote = 1; +var RecommendRelay = 2; +var Contacts = 3; +var EncryptedDirectMessage = 4; +var EventDeletion = 5; +var Repost = 6; +var Reaction = 7; +var BadgeAward = 8; +var Seal = 13; +var PrivateDirectMessage = 14; +var GenericRepost = 16; +var ChannelCreation = 40; +var ChannelMetadata = 41; +var ChannelMessage = 42; +var ChannelHideMessage = 43; +var ChannelMuteUser = 44; +var OpenTimestamps = 1040; +var GiftWrap = 1059; +var FileMetadata = 1063; +var LiveChatMessage = 1311; +var ProblemTracker = 1971; +var Report = 1984; +var Reporting = 1984; +var Label = 1985; +var CommunityPostApproval = 4550; +var JobRequest = 5999; +var JobResult = 6999; +var JobFeedback = 7e3; +var ZapGoal = 9041; +var ZapRequest = 9734; +var Zap = 9735; +var Highlights = 9802; +var Mutelist = 1e4; +var Pinlist = 10001; +var RelayList = 10002; +var BookmarkList = 10003; +var CommunitiesList = 10004; +var PublicChatsList = 10005; +var BlockedRelaysList = 10006; +var SearchRelaysList = 10007; +var InterestsList = 10015; +var UserEmojiList = 10030; +var DirectMessageRelaysList = 10050; +var FileServerPreference = 10096; +var NWCWalletInfo = 13194; +var LightningPubRPC = 21e3; +var ClientAuth = 22242; +var NWCWalletRequest = 23194; +var NWCWalletResponse = 23195; +var NostrConnect = 24133; +var HTTPAuth = 27235; +var Followsets = 3e4; +var Genericlists = 30001; +var Relaysets = 30002; +var Bookmarksets = 30003; +var Curationsets = 30004; +var ProfileBadges = 30008; +var BadgeDefinition = 30009; +var Interestsets = 30015; +var CreateOrUpdateStall = 30017; +var CreateOrUpdateProduct = 30018; +var LongFormArticle = 30023; +var DraftLong = 30024; +var Emojisets = 30030; +var Application = 30078; +var LiveEvent = 30311; +var UserStatuses = 30315; +var ClassifiedListing = 30402; +var DraftClassifiedListing = 30403; +var Date2 = 31922; +var Time = 31923; +var Calendar = 31924; +var CalendarEventRSVP = 31925; +var Handlerrecommendation = 31989; +var Handlerinformation = 31990; +var CommunityDefinition = 34550; + +// filter.ts +function matchFilter(filter, event) { + if (filter.ids && filter.ids.indexOf(event.id) === -1) { + return false; + } + if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) { + return false; + } + if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) { + return false; + } + for (let f in filter) { + if (f[0] === "#") { + let tagName = f.slice(1); + let values = filter[`#${tagName}`]; + if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values.indexOf(v) !== -1)) + return false; + } + } + if (filter.since && event.created_at < filter.since) + return false; + if (filter.until && event.created_at > filter.until) + return false; + return true; +} +function matchFilters(filters, event) { + for (let i2 = 0; i2 < filters.length; i2++) { + if (matchFilter(filters[i2], event)) { + return true; + } + } + return false; +} +function mergeFilters(...filters) { + let result = {}; + for (let i2 = 0; i2 < filters.length; i2++) { + let filter = filters[i2]; + Object.entries(filter).forEach(([property, values]) => { + if (property === "kinds" || property === "ids" || property === "authors" || property[0] === "#") { + result[property] = result[property] || []; + for (let v = 0; v < values.length; v++) { + let value = values[v]; + if (!result[property].includes(value)) + result[property].push(value); + } + } + }); + if (filter.limit && (!result.limit || filter.limit > result.limit)) + result.limit = filter.limit; + if (filter.until && (!result.until || filter.until > result.until)) + result.until = filter.until; + if (filter.since && (!result.since || filter.since < result.since)) + result.since = filter.since; + } + return result; +} +function getFilterLimit(filter) { + if (filter.ids && !filter.ids.length) + return 0; + if (filter.kinds && !filter.kinds.length) + return 0; + if (filter.authors && !filter.authors.length) + return 0; + for (const [key, value] of Object.entries(filter)) { + if (key[0] === "#" && Array.isArray(value) && !value.length) + return 0; + } + return Math.min( + Math.max(0, filter.limit ?? Infinity), + filter.ids?.length ?? Infinity, + filter.authors?.length && filter.kinds?.every((kind) => isReplaceableKind(kind)) ? filter.authors.length * filter.kinds.length : Infinity, + filter.authors?.length && filter.kinds?.every((kind) => isAddressableKind(kind)) && filter["#d"]?.length ? filter.authors.length * filter.kinds.length * filter["#d"].length : Infinity + ); +} + +// fakejson.ts +var fakejson_exports = {}; +__export(fakejson_exports, { + getHex64: () => getHex64, + getInt: () => getInt, + getSubscriptionId: () => getSubscriptionId, + matchEventId: () => matchEventId, + matchEventKind: () => matchEventKind, + matchEventPubkey: () => matchEventPubkey +}); +function getHex64(json, field) { + let len = field.length + 3; + let idx = json.indexOf(`"${field}":`) + len; + let s = json.slice(idx).indexOf(`"`) + idx + 1; + return json.slice(s, s + 64); +} +function getInt(json, field) { + let len = field.length; + let idx = json.indexOf(`"${field}":`) + len + 3; + let sliced = json.slice(idx); + let end = Math.min(sliced.indexOf(","), sliced.indexOf("}")); + return parseInt(sliced.slice(0, end), 10); +} +function getSubscriptionId(json) { + let idx = json.slice(0, 22).indexOf(`"EVENT"`); + if (idx === -1) + return null; + let pstart = json.slice(idx + 7 + 1).indexOf(`"`); + if (pstart === -1) + return null; + let start = idx + 7 + 1 + pstart; + let pend = json.slice(start + 1, 80).indexOf(`"`); + if (pend === -1) + return null; + let end = start + 1 + pend; + return json.slice(start + 1, end); +} +function matchEventId(json, id) { + return id === getHex64(json, "id"); +} +function matchEventPubkey(json, pubkey) { + return pubkey === getHex64(json, "pubkey"); +} +function matchEventKind(json, kind) { + return kind === getInt(json, "kind"); +} + +// nip42.ts +var nip42_exports = {}; +__export(nip42_exports, { + makeAuthEvent: () => makeAuthEvent +}); +function makeAuthEvent(relayURL, challenge) { + return { + kind: ClientAuth, + created_at: Math.floor(Date.now() / 1e3), + tags: [ + ["relay", relayURL], + ["challenge", challenge] + ], + content: "" + }; +} + +// helpers.ts +async function yieldThread() { + return new Promise((resolve) => { + const ch = new MessageChannel(); + const handler = () => { + ch.port1.removeEventListener("message", handler); + resolve(); + }; + ch.port1.addEventListener("message", handler); + ch.port2.postMessage(0); + ch.port1.start(); + }); +} +var alwaysTrue = (t) => { + t[verifiedSymbol] = true; + return true; +}; + +// abstract-relay.ts +var SendingOnClosedConnection = class extends Error { + constructor(message, relay) { + super(`Tried to send message '${message} on a closed connection to ${relay}.`); + this.name = "SendingOnClosedConnection"; + } +}; +var AbstractRelay = class { + url; + _connected = false; + onclose = null; + onnotice = (msg) => console.debug(`NOTICE from ${this.url}: ${msg}`); + baseEoseTimeout = 4400; + connectionTimeout = 4400; + publishTimeout = 4400; + pingFrequency = 2e4; + pingTimeout = 2e4; + openSubs = /* @__PURE__ */ new Map(); + enablePing; + connectionTimeoutHandle; + connectionPromise; + openCountRequests = /* @__PURE__ */ new Map(); + openEventPublishes = /* @__PURE__ */ new Map(); + ws; + incomingMessageQueue = new Queue(); + queueRunning = false; + challenge; + authPromise; + serial = 0; + verifyEvent; + _WebSocket; + constructor(url, opts) { + this.url = normalizeURL(url); + this.verifyEvent = opts.verifyEvent; + this._WebSocket = opts.websocketImplementation || WebSocket; + this.enablePing = opts.enablePing; + } + static async connect(url, opts) { + const relay = new AbstractRelay(url, opts); + await relay.connect(); + return relay; + } + closeAllSubscriptions(reason) { + for (let [_, sub] of this.openSubs) { + sub.close(reason); + } + this.openSubs.clear(); + for (let [_, ep] of this.openEventPublishes) { + ep.reject(new Error(reason)); + } + this.openEventPublishes.clear(); + for (let [_, cr] of this.openCountRequests) { + cr.reject(new Error(reason)); + } + this.openCountRequests.clear(); + } + get connected() { + return this._connected; + } + async connect() { + if (this.connectionPromise) + return this.connectionPromise; + this.challenge = void 0; + this.authPromise = void 0; + this.connectionPromise = new Promise((resolve, reject) => { + this.connectionTimeoutHandle = setTimeout(() => { + reject("connection timed out"); + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection timed out"); + }, this.connectionTimeout); + try { + this.ws = new this._WebSocket(this.url); + } catch (err) { + clearTimeout(this.connectionTimeoutHandle); + reject(err); + return; + } + this.ws.onopen = () => { + clearTimeout(this.connectionTimeoutHandle); + this._connected = true; + if (this.enablePing) { + this.pingpong(); + } + resolve(); + }; + this.ws.onerror = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket error"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection errored"); + } + }; + this.ws.onclose = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket closed"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection closed"); + } + }; + this.ws.onmessage = this._onmessage.bind(this); + }); + return this.connectionPromise; + } + async waitForPingPong() { + return new Promise((res, err) => { + ; + this.ws && this.ws.on && this.ws.on("pong", () => res(true)) || err("ws can't listen for pong"); + this.ws && this.ws.ping && this.ws.ping(); + }); + } + async waitForDummyReq() { + return new Promise((resolve, _) => { + const sub = this.subscribe([{ ids: ["a".repeat(64)] }], { + oneose: () => { + sub.close(); + resolve(true); + }, + eoseTimeout: this.pingTimeout + 1e3 + }); + }); + } + async pingpong() { + if (this.ws?.readyState === 1) { + const result = await Promise.any([ + this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(), + new Promise((res) => setTimeout(() => res(false), this.pingTimeout)) + ]); + if (result) { + setTimeout(() => this.pingpong(), this.pingFrequency); + } else { + this.closeAllSubscriptions("pingpong timed out"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + } + } + async runQueue() { + this.queueRunning = true; + while (true) { + if (false === this.handleNext()) { + break; + } + await yieldThread(); + } + this.queueRunning = false; + } + handleNext() { + const json = this.incomingMessageQueue.dequeue(); + if (!json) { + return false; + } + const subid = getSubscriptionId(json); + if (subid) { + const so = this.openSubs.get(subid); + if (!so) { + return; + } + const id = getHex64(json, "id"); + const alreadyHave = so.alreadyHaveEvent?.(id); + so.receivedEvent?.(this, id); + if (alreadyHave) { + return; + } + } + try { + let data = JSON.parse(json); + switch (data[0]) { + case "EVENT": { + const so = this.openSubs.get(data[1]); + const event = data[2]; + if (this.verifyEvent(event) && matchFilters(so.filters, event)) { + so.onevent(event); + } + return; + } + case "COUNT": { + const id = data[1]; + const payload = data[2]; + const cr = this.openCountRequests.get(id); + if (cr) { + cr.resolve(payload.count); + this.openCountRequests.delete(id); + } + return; + } + case "EOSE": { + const so = this.openSubs.get(data[1]); + if (!so) + return; + so.receivedEose(); + return; + } + case "OK": { + const id = data[1]; + const ok = data[2]; + const reason = data[3]; + const ep = this.openEventPublishes.get(id); + if (ep) { + clearTimeout(ep.timeout); + if (ok) + ep.resolve(reason); + else + ep.reject(new Error(reason)); + this.openEventPublishes.delete(id); + } + return; + } + case "CLOSED": { + const id = data[1]; + const so = this.openSubs.get(id); + if (!so) + return; + so.closed = true; + so.close(data[2]); + return; + } + case "NOTICE": + this.onnotice(data[1]); + return; + case "AUTH": { + this.challenge = data[1]; + return; + } + } + } catch (err) { + return; + } + } + async send(message) { + if (!this.connectionPromise) + throw new SendingOnClosedConnection(message, this.url); + this.connectionPromise.then(() => { + this.ws?.send(message); + }); + } + async auth(signAuthEvent) { + const challenge = this.challenge; + if (!challenge) + throw new Error("can't perform auth, no challenge was received"); + if (this.authPromise) + return this.authPromise; + this.authPromise = new Promise(async (resolve, reject) => { + try { + let evt = await signAuthEvent(makeAuthEvent(this.url, challenge)); + let timeout = setTimeout(() => { + let ep = this.openEventPublishes.get(evt.id); + if (ep) { + ep.reject(new Error("auth timed out")); + this.openEventPublishes.delete(evt.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(evt.id, { resolve, reject, timeout }); + this.send('["AUTH",' + JSON.stringify(evt) + "]"); + } catch (err) { + console.warn("subscribe auth function failed:", err); + } + }); + return this.authPromise; + } + async publish(event) { + const ret = new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + const ep = this.openEventPublishes.get(event.id); + if (ep) { + ep.reject(new Error("publish timed out")); + this.openEventPublishes.delete(event.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(event.id, { resolve, reject, timeout }); + }); + this.send('["EVENT",' + JSON.stringify(event) + "]"); + return ret; + } + async count(filters, params) { + this.serial++; + const id = params?.id || "count:" + this.serial; + const ret = new Promise((resolve, reject) => { + this.openCountRequests.set(id, { resolve, reject }); + }); + this.send('["COUNT","' + id + '",' + JSON.stringify(filters).substring(1)); + return ret; + } + subscribe(filters, params) { + const subscription = this.prepareSubscription(filters, params); + subscription.fire(); + return subscription; + } + prepareSubscription(filters, params) { + this.serial++; + const id = params.id || (params.label ? params.label + ":" : "sub:") + this.serial; + const subscription = new Subscription(this, id, filters, params); + this.openSubs.set(id, subscription); + return subscription; + } + close() { + this.closeAllSubscriptions("relay connection closed by us"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + _onmessage(ev) { + this.incomingMessageQueue.enqueue(ev.data); + if (!this.queueRunning) { + this.runQueue(); + } + } +}; +var Subscription = class { + relay; + id; + closed = false; + eosed = false; + filters; + alreadyHaveEvent; + receivedEvent; + onevent; + oneose; + onclose; + eoseTimeout; + eoseTimeoutHandle; + constructor(relay, id, filters, params) { + this.relay = relay; + this.filters = filters; + this.id = id; + this.alreadyHaveEvent = params.alreadyHaveEvent; + this.receivedEvent = params.receivedEvent; + this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout; + this.oneose = params.oneose; + this.onclose = params.onclose; + this.onevent = params.onevent || ((event) => { + console.warn( + `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`, + event + ); + }); + } + fire() { + this.relay.send('["REQ","' + this.id + '",' + JSON.stringify(this.filters).substring(1)); + this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout); + } + receivedEose() { + if (this.eosed) + return; + clearTimeout(this.eoseTimeoutHandle); + this.eosed = true; + this.oneose?.(); + } + close(reason = "closed by caller") { + if (!this.closed && this.relay.connected) { + try { + this.relay.send('["CLOSE",' + JSON.stringify(this.id) + "]"); + } catch (err) { + if (err instanceof SendingOnClosedConnection) { + } else { + throw err; + } + } + this.closed = true; + } + this.relay.openSubs.delete(this.id); + this.onclose?.(reason); + } +}; + +// relay.ts +var _WebSocket; +try { + _WebSocket = WebSocket; +} catch { +} +var Relay = class extends AbstractRelay { + constructor(url) { + super(url, { verifyEvent, websocketImplementation: _WebSocket }); + } + static async connect(url) { + const relay = new Relay(url); + await relay.connect(); + return relay; + } +}; + +// abstract-pool.ts +var AbstractSimplePool = class { + relays = /* @__PURE__ */ new Map(); + seenOn = /* @__PURE__ */ new Map(); + trackRelays = false; + verifyEvent; + enablePing; + trustedRelayURLs = /* @__PURE__ */ new Set(); + _WebSocket; + constructor(opts) { + this.verifyEvent = opts.verifyEvent; + this._WebSocket = opts.websocketImplementation; + this.enablePing = opts.enablePing; + } + async ensureRelay(url, params) { + url = normalizeURL(url); + let relay = this.relays.get(url); + if (!relay) { + relay = new AbstractRelay(url, { + verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent, + websocketImplementation: this._WebSocket, + enablePing: this.enablePing + }); + relay.onclose = () => { + this.relays.delete(url); + }; + if (params?.connectionTimeout) + relay.connectionTimeout = params.connectionTimeout; + this.relays.set(url, relay); + } + await relay.connect(); + return relay; + } + close(relays) { + relays.map(normalizeURL).forEach((url) => { + this.relays.get(url)?.close(); + this.relays.delete(url); + }); + } + subscribe(relays, filter, params) { + params.onauth = params.onauth || params.doauth; + const request = []; + for (let i2 = 0; i2 < relays.length; i2++) { + const url = normalizeURL(relays[i2]); + if (!request.find((r) => r.url === url)) { + request.push({ url, filter }); + } + } + return this.subscribeMap(request, params); + } + subscribeMany(relays, filters, params) { + params.onauth = params.onauth || params.doauth; + const request = []; + const uniqUrls = []; + for (let i2 = 0; i2 < relays.length; i2++) { + const url = normalizeURL(relays[i2]); + if (uniqUrls.indexOf(url) === -1) { + for (let f = 0; f < filters.length; f++) { + request.push({ url, filter: filters[f] }); + } + } + } + return this.subscribeMap(request, params); + } + subscribeMap(requests, params) { + params.onauth = params.onauth || params.doauth; + if (this.trackRelays) { + params.receivedEvent = (relay, id) => { + let set = this.seenOn.get(id); + if (!set) { + set = /* @__PURE__ */ new Set(); + this.seenOn.set(id, set); + } + set.add(relay); + }; + } + const _knownIds = /* @__PURE__ */ new Set(); + const subs = []; + const eosesReceived = []; + let handleEose = (i2) => { + if (eosesReceived[i2]) + return; + eosesReceived[i2] = true; + if (eosesReceived.filter((a) => a).length === requests.length) { + params.oneose?.(); + handleEose = () => { + }; + } + }; + const closesReceived = []; + let handleClose = (i2, reason) => { + if (closesReceived[i2]) + return; + handleEose(i2); + closesReceived[i2] = reason; + if (closesReceived.filter((a) => a).length === requests.length) { + params.onclose?.(closesReceived); + handleClose = () => { + }; + } + }; + const localAlreadyHaveEventHandler = (id) => { + if (params.alreadyHaveEvent?.(id)) { + return true; + } + const have = _knownIds.has(id); + _knownIds.add(id); + return have; + }; + const allOpened = Promise.all( + requests.map(async ({ url, filter }, i2) => { + let relay; + try { + relay = await this.ensureRelay(url, { + connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1e3) : void 0 + }); + } catch (err) { + handleClose(i2, err?.message || String(err)); + return; + } + let subscription = relay.subscribe([filter], { + ...params, + oneose: () => handleEose(i2), + onclose: (reason) => { + if (reason.startsWith("auth-required: ") && params.onauth) { + relay.auth(params.onauth).then(() => { + relay.subscribe([filter], { + ...params, + oneose: () => handleEose(i2), + onclose: (reason2) => { + handleClose(i2, reason2); + }, + alreadyHaveEvent: localAlreadyHaveEventHandler, + eoseTimeout: params.maxWait + }); + }).catch((err) => { + handleClose(i2, `auth was required and attempted, but failed with: ${err}`); + }); + } else { + handleClose(i2, reason); + } + }, + alreadyHaveEvent: localAlreadyHaveEventHandler, + eoseTimeout: params.maxWait + }); + subs.push(subscription); + }) + ); + return { + async close(reason) { + await allOpened; + subs.forEach((sub) => { + sub.close(reason); + }); + } + }; + } + subscribeEose(relays, filter, params) { + params.onauth = params.onauth || params.doauth; + const subcloser = this.subscribe(relays, filter, { + ...params, + oneose() { + subcloser.close("closed automatically on eose"); + } + }); + return subcloser; + } + subscribeManyEose(relays, filters, params) { + params.onauth = params.onauth || params.doauth; + const subcloser = this.subscribeMany(relays, filters, { + ...params, + oneose() { + subcloser.close("closed automatically on eose"); + } + }); + return subcloser; + } + async querySync(relays, filter, params) { + return new Promise(async (resolve) => { + const events = []; + this.subscribeEose(relays, filter, { + ...params, + onevent(event) { + events.push(event); + }, + onclose(_) { + resolve(events); + } + }); + }); + } + async get(relays, filter, params) { + filter.limit = 1; + const events = await this.querySync(relays, filter, params); + events.sort((a, b) => b.created_at - a.created_at); + return events[0] || null; + } + publish(relays, event, options) { + return relays.map(normalizeURL).map(async (url, i2, arr) => { + if (arr.indexOf(url) !== i2) { + return Promise.reject("duplicate url"); + } + let r = await this.ensureRelay(url); + return r.publish(event).catch(async (err) => { + if (err instanceof Error && err.message.startsWith("auth-required: ") && options?.onauth) { + await r.auth(options.onauth); + return r.publish(event); + } + throw err; + }).then((reason) => { + if (this.trackRelays) { + let set = this.seenOn.get(event.id); + if (!set) { + set = /* @__PURE__ */ new Set(); + this.seenOn.set(event.id, set); + } + set.add(r); + } + return reason; + }); + }); + } + listConnectionStatus() { + const map = /* @__PURE__ */ new Map(); + this.relays.forEach((relay, url) => map.set(url, relay.connected)); + return map; + } + destroy() { + this.relays.forEach((conn) => conn.close()); + this.relays = /* @__PURE__ */ new Map(); + } +}; + +// pool.ts +var _WebSocket2; +try { + _WebSocket2 = WebSocket; +} catch { +} +var SimplePool = class extends AbstractSimplePool { + constructor(options) { + super({ verifyEvent, websocketImplementation: _WebSocket2, ...options }); + } +}; + +// nip19.ts +var nip19_exports = {}; +__export(nip19_exports, { + BECH32_REGEX: () => BECH32_REGEX, + Bech32MaxSize: () => Bech32MaxSize, + NostrTypeGuard: () => NostrTypeGuard, + decode: () => decode, + decodeNostrURI: () => decodeNostrURI, + encodeBytes: () => encodeBytes, + naddrEncode: () => naddrEncode, + neventEncode: () => neventEncode, + noteEncode: () => noteEncode, + nprofileEncode: () => nprofileEncode, + npubEncode: () => npubEncode, + nsecEncode: () => nsecEncode +}); +import { bytesToHex as bytesToHex3, concatBytes, hexToBytes as hexToBytes2 } from "@noble/hashes/utils"; +import { bech32 } from "@scure/base"; +var NostrTypeGuard = { + isNProfile: (value) => /^nprofile1[a-z\d]+$/.test(value || ""), + isNEvent: (value) => /^nevent1[a-z\d]+$/.test(value || ""), + isNAddr: (value) => /^naddr1[a-z\d]+$/.test(value || ""), + isNSec: (value) => /^nsec1[a-z\d]{58}$/.test(value || ""), + isNPub: (value) => /^npub1[a-z\d]{58}$/.test(value || ""), + isNote: (value) => /^note1[a-z\d]+$/.test(value || ""), + isNcryptsec: (value) => /^ncryptsec1[a-z\d]+$/.test(value || "") +}; +var Bech32MaxSize = 5e3; +var BECH32_REGEX = /[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/; +function integerToUint8Array(number) { + const uint8Array = new Uint8Array(4); + uint8Array[0] = number >> 24 & 255; + uint8Array[1] = number >> 16 & 255; + uint8Array[2] = number >> 8 & 255; + uint8Array[3] = number & 255; + return uint8Array; +} +function decodeNostrURI(nip19code) { + try { + if (nip19code.startsWith("nostr:")) + nip19code = nip19code.substring(6); + return decode(nip19code); + } catch (_err) { + return { type: "invalid", data: null }; + } +} +function decode(code) { + let { prefix, words } = bech32.decode(code, Bech32MaxSize); + let data = new Uint8Array(bech32.fromWords(words)); + switch (prefix) { + case "nprofile": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nprofile"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + return { + type: "nprofile", + data: { + pubkey: bytesToHex3(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nevent": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nevent"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + if (tlv[2] && tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (tlv[3] && tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "nevent", + data: { + id: bytesToHex3(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [], + author: tlv[2]?.[0] ? bytesToHex3(tlv[2][0]) : void 0, + kind: tlv[3]?.[0] ? parseInt(bytesToHex3(tlv[3][0]), 16) : void 0 + } + }; + } + case "naddr": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for naddr"); + if (!tlv[2]?.[0]) + throw new Error("missing TLV 2 for naddr"); + if (tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (!tlv[3]?.[0]) + throw new Error("missing TLV 3 for naddr"); + if (tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "naddr", + data: { + identifier: utf8Decoder.decode(tlv[0][0]), + pubkey: bytesToHex3(tlv[2][0]), + kind: parseInt(bytesToHex3(tlv[3][0]), 16), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nsec": + return { type: prefix, data }; + case "npub": + case "note": + return { type: prefix, data: bytesToHex3(data) }; + default: + throw new Error(`unknown prefix ${prefix}`); + } +} +function parseTLV(data) { + let result = {}; + let rest = data; + while (rest.length > 0) { + let t = rest[0]; + let l = rest[1]; + let v = rest.slice(2, 2 + l); + rest = rest.slice(2 + l); + if (v.length < l) + throw new Error(`not enough data to read on TLV ${t}`); + result[t] = result[t] || []; + result[t].push(v); + } + return result; +} +function nsecEncode(key) { + return encodeBytes("nsec", key); +} +function npubEncode(hex) { + return encodeBytes("npub", hexToBytes2(hex)); +} +function noteEncode(hex) { + return encodeBytes("note", hexToBytes2(hex)); +} +function encodeBech32(prefix, data) { + let words = bech32.toWords(data); + return bech32.encode(prefix, words, Bech32MaxSize); +} +function encodeBytes(prefix, bytes) { + return encodeBech32(prefix, bytes); +} +function nprofileEncode(profile) { + let data = encodeTLV({ + 0: [hexToBytes2(profile.pubkey)], + 1: (profile.relays || []).map((url) => utf8Encoder.encode(url)) + }); + return encodeBech32("nprofile", data); +} +function neventEncode(event) { + let kindArray; + if (event.kind !== void 0) { + kindArray = integerToUint8Array(event.kind); + } + let data = encodeTLV({ + 0: [hexToBytes2(event.id)], + 1: (event.relays || []).map((url) => utf8Encoder.encode(url)), + 2: event.author ? [hexToBytes2(event.author)] : [], + 3: kindArray ? [new Uint8Array(kindArray)] : [] + }); + return encodeBech32("nevent", data); +} +function naddrEncode(addr) { + let kind = new ArrayBuffer(4); + new DataView(kind).setUint32(0, addr.kind, false); + let data = encodeTLV({ + 0: [utf8Encoder.encode(addr.identifier)], + 1: (addr.relays || []).map((url) => utf8Encoder.encode(url)), + 2: [hexToBytes2(addr.pubkey)], + 3: [new Uint8Array(kind)] + }); + return encodeBech32("naddr", data); +} +function encodeTLV(tlv) { + let entries = []; + Object.entries(tlv).reverse().forEach(([t, vs]) => { + vs.forEach((v) => { + let entry = new Uint8Array(v.length + 2); + entry.set([parseInt(t)], 0); + entry.set([v.length], 1); + entry.set(v, 2); + entries.push(entry); + }); + }); + return concatBytes(...entries); +} + +// references.ts +var mentionRegex = /\bnostr:((note|npub|naddr|nevent|nprofile)1\w+)\b|#\[(\d+)\]/g; +function parseReferences(evt) { + let references = []; + for (let ref of evt.content.matchAll(mentionRegex)) { + if (ref[2]) { + try { + let { type, data } = decode(ref[1]); + switch (type) { + case "npub": { + references.push({ + text: ref[0], + profile: { pubkey: data, relays: [] } + }); + break; + } + case "nprofile": { + references.push({ + text: ref[0], + profile: data + }); + break; + } + case "note": { + references.push({ + text: ref[0], + event: { id: data, relays: [] } + }); + break; + } + case "nevent": { + references.push({ + text: ref[0], + event: data + }); + break; + } + case "naddr": { + references.push({ + text: ref[0], + address: data + }); + break; + } + } + } catch (err) { + } + } else if (ref[3]) { + let idx = parseInt(ref[3], 10); + let tag = evt.tags[idx]; + if (!tag) + continue; + switch (tag[0]) { + case "p": { + references.push({ + text: ref[0], + profile: { pubkey: tag[1], relays: tag[2] ? [tag[2]] : [] } + }); + break; + } + case "e": { + references.push({ + text: ref[0], + event: { id: tag[1], relays: tag[2] ? [tag[2]] : [] } + }); + break; + } + case "a": { + try { + let [kind, pubkey, identifier] = tag[1].split(":"); + references.push({ + text: ref[0], + address: { + identifier, + pubkey, + kind: parseInt(kind, 10), + relays: tag[2] ? [tag[2]] : [] + } + }); + } catch (err) { + } + break; + } + } + } + } + return references; +} + +// nip04.ts +var nip04_exports = {}; +__export(nip04_exports, { + decrypt: () => decrypt, + encrypt: () => encrypt +}); +import { bytesToHex as bytesToHex4, randomBytes } from "@noble/hashes/utils"; +import { secp256k1 } from "@noble/curves/secp256k1"; +import { cbc } from "@noble/ciphers/aes"; +import { base64 } from "@scure/base"; +function encrypt(secretKey, pubkey, text) { + const privkey = secretKey instanceof Uint8Array ? bytesToHex4(secretKey) : secretKey; + const key = secp256k1.getSharedSecret(privkey, "02" + pubkey); + const normalizedKey = getNormalizedX(key); + let iv = Uint8Array.from(randomBytes(16)); + let plaintext = utf8Encoder.encode(text); + let ciphertext = cbc(normalizedKey, iv).encrypt(plaintext); + let ctb64 = base64.encode(new Uint8Array(ciphertext)); + let ivb64 = base64.encode(new Uint8Array(iv.buffer)); + return `${ctb64}?iv=${ivb64}`; +} +function decrypt(secretKey, pubkey, data) { + const privkey = secretKey instanceof Uint8Array ? bytesToHex4(secretKey) : secretKey; + let [ctb64, ivb64] = data.split("?iv="); + let key = secp256k1.getSharedSecret(privkey, "02" + pubkey); + let normalizedKey = getNormalizedX(key); + let iv = base64.decode(ivb64); + let ciphertext = base64.decode(ctb64); + let plaintext = cbc(normalizedKey, iv).decrypt(ciphertext); + return utf8Decoder.decode(plaintext); +} +function getNormalizedX(key) { + return key.slice(1, 33); +} + +// nip05.ts +var nip05_exports = {}; +__export(nip05_exports, { + NIP05_REGEX: () => NIP05_REGEX, + isNip05: () => isNip05, + isValid: () => isValid, + queryProfile: () => queryProfile, + searchDomain: () => searchDomain, + useFetchImplementation: () => useFetchImplementation +}); +var NIP05_REGEX = /^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/; +var isNip05 = (value) => NIP05_REGEX.test(value || ""); +var _fetch; +try { + _fetch = fetch; +} catch (_) { + null; +} +function useFetchImplementation(fetchImplementation) { + _fetch = fetchImplementation; +} +async function searchDomain(domain, query = "") { + try { + const url = `https://${domain}/.well-known/nostr.json?name=${query}`; + const res = await _fetch(url, { redirect: "manual" }); + if (res.status !== 200) { + throw Error("Wrong response code"); + } + const json = await res.json(); + return json.names; + } catch (_) { + return {}; + } +} +async function queryProfile(fullname) { + const match = fullname.match(NIP05_REGEX); + if (!match) + return null; + const [, name = "_", domain] = match; + try { + const url = `https://${domain}/.well-known/nostr.json?name=${name}`; + const res = await _fetch(url, { redirect: "manual" }); + if (res.status !== 200) { + throw Error("Wrong response code"); + } + const json = await res.json(); + const pubkey = json.names[name]; + return pubkey ? { pubkey, relays: json.relays?.[pubkey] } : null; + } catch (_e) { + return null; + } +} +async function isValid(pubkey, nip05) { + const res = await queryProfile(nip05); + return res ? res.pubkey === pubkey : false; +} + +// nip10.ts +var nip10_exports = {}; +__export(nip10_exports, { + parse: () => parse +}); +function parse(event) { + const result = { + reply: void 0, + root: void 0, + mentions: [], + profiles: [], + quotes: [] + }; + let maybeParent; + let maybeRoot; + for (let i2 = event.tags.length - 1; i2 >= 0; i2--) { + const tag = event.tags[i2]; + if (tag[0] === "e" && tag[1]) { + const [_, eTagEventId, eTagRelayUrl, eTagMarker, eTagAuthor] = tag; + const eventPointer = { + id: eTagEventId, + relays: eTagRelayUrl ? [eTagRelayUrl] : [], + author: eTagAuthor + }; + if (eTagMarker === "root") { + result.root = eventPointer; + continue; + } + if (eTagMarker === "reply") { + result.reply = eventPointer; + continue; + } + if (eTagMarker === "mention") { + result.mentions.push(eventPointer); + continue; + } + if (!maybeParent) { + maybeParent = eventPointer; + } else { + maybeRoot = eventPointer; + } + result.mentions.push(eventPointer); + continue; + } + if (tag[0] === "q" && tag[1]) { + const [_, eTagEventId, eTagRelayUrl] = tag; + result.quotes.push({ + id: eTagEventId, + relays: eTagRelayUrl ? [eTagRelayUrl] : [] + }); + } + if (tag[0] === "p" && tag[1]) { + result.profiles.push({ + pubkey: tag[1], + relays: tag[2] ? [tag[2]] : [] + }); + continue; + } + } + if (!result.root) { + result.root = maybeRoot || maybeParent || result.reply; + } + if (!result.reply) { + result.reply = maybeParent || result.root; + } + ; + [result.reply, result.root].forEach((ref) => { + if (!ref) + return; + let idx = result.mentions.indexOf(ref); + if (idx !== -1) { + result.mentions.splice(idx, 1); + } + if (ref.author) { + let author = result.profiles.find((p) => p.pubkey === ref.author); + if (author && author.relays) { + if (!ref.relays) { + ref.relays = []; + } + author.relays.forEach((url) => { + if (ref.relays?.indexOf(url) === -1) + ref.relays.push(url); + }); + author.relays = ref.relays; + } + } + }); + result.mentions.forEach((ref) => { + if (ref.author) { + let author = result.profiles.find((p) => p.pubkey === ref.author); + if (author && author.relays) { + if (!ref.relays) { + ref.relays = []; + } + author.relays.forEach((url) => { + if (ref.relays.indexOf(url) === -1) + ref.relays.push(url); + }); + author.relays = ref.relays; + } + } + }); + return result; +} + +// nip11.ts +var nip11_exports = {}; +__export(nip11_exports, { + fetchRelayInformation: () => fetchRelayInformation, + useFetchImplementation: () => useFetchImplementation2 +}); +var _fetch2; +try { + _fetch2 = fetch; +} catch { +} +function useFetchImplementation2(fetchImplementation) { + _fetch2 = fetchImplementation; +} +async function fetchRelayInformation(url) { + return await (await fetch(url.replace("ws://", "http://").replace("wss://", "https://"), { + headers: { Accept: "application/nostr+json" } + })).json(); +} + +// nip13.ts +var nip13_exports = {}; +__export(nip13_exports, { + fastEventHash: () => fastEventHash, + getPow: () => getPow, + minePow: () => minePow +}); +import { bytesToHex as bytesToHex5 } from "@noble/hashes/utils"; +import { sha256 as sha2562 } from "@noble/hashes/sha256"; +function getPow(hex) { + let count = 0; + for (let i2 = 0; i2 < 64; i2 += 8) { + const nibble = parseInt(hex.substring(i2, i2 + 8), 16); + if (nibble === 0) { + count += 32; + } else { + count += Math.clz32(nibble); + break; + } + } + return count; +} +function minePow(unsigned, difficulty) { + let count = 0; + const event = unsigned; + const tag = ["nonce", count.toString(), difficulty.toString()]; + event.tags.push(tag); + while (true) { + const now2 = Math.floor(new Date().getTime() / 1e3); + if (now2 !== event.created_at) { + count = 0; + event.created_at = now2; + } + tag[1] = (++count).toString(); + event.id = fastEventHash(event); + if (getPow(event.id) >= difficulty) { + break; + } + } + return event; +} +function fastEventHash(evt) { + return bytesToHex5( + sha2562(utf8Encoder.encode(JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]))) + ); +} + +// nip17.ts +var nip17_exports = {}; +__export(nip17_exports, { + unwrapEvent: () => unwrapEvent2, + unwrapManyEvents: () => unwrapManyEvents2, + wrapEvent: () => wrapEvent2, + wrapManyEvents: () => wrapManyEvents2 +}); + +// nip59.ts +var nip59_exports = {}; +__export(nip59_exports, { + createRumor: () => createRumor, + createSeal: () => createSeal, + createWrap: () => createWrap, + unwrapEvent: () => unwrapEvent, + unwrapManyEvents: () => unwrapManyEvents, + wrapEvent: () => wrapEvent, + wrapManyEvents: () => wrapManyEvents +}); + +// nip44.ts +var nip44_exports = {}; +__export(nip44_exports, { + decrypt: () => decrypt2, + encrypt: () => encrypt2, + getConversationKey: () => getConversationKey, + v2: () => v2 +}); +import { chacha20 } from "@noble/ciphers/chacha"; +import { equalBytes } from "@noble/ciphers/utils"; +import { secp256k1 as secp256k12 } from "@noble/curves/secp256k1"; +import { extract as hkdf_extract, expand as hkdf_expand } from "@noble/hashes/hkdf"; +import { hmac } from "@noble/hashes/hmac"; +import { sha256 as sha2563 } from "@noble/hashes/sha256"; +import { concatBytes as concatBytes2, randomBytes as randomBytes2 } from "@noble/hashes/utils"; +import { base64 as base642 } from "@scure/base"; +var minPlaintextSize = 1; +var maxPlaintextSize = 65535; +function getConversationKey(privkeyA, pubkeyB) { + const sharedX = secp256k12.getSharedSecret(privkeyA, "02" + pubkeyB).subarray(1, 33); + return hkdf_extract(sha2563, sharedX, "nip44-v2"); +} +function getMessageKeys(conversationKey, nonce) { + const keys = hkdf_expand(sha2563, conversationKey, nonce, 76); + return { + chacha_key: keys.subarray(0, 32), + chacha_nonce: keys.subarray(32, 44), + hmac_key: keys.subarray(44, 76) + }; +} +function calcPaddedLen(len) { + if (!Number.isSafeInteger(len) || len < 1) + throw new Error("expected positive integer"); + if (len <= 32) + return 32; + const nextPower = 1 << Math.floor(Math.log2(len - 1)) + 1; + const chunk = nextPower <= 256 ? 32 : nextPower / 8; + return chunk * (Math.floor((len - 1) / chunk) + 1); +} +function writeU16BE(num) { + if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize) + throw new Error("invalid plaintext size: must be between 1 and 65535 bytes"); + const arr = new Uint8Array(2); + new DataView(arr.buffer).setUint16(0, num, false); + return arr; +} +function pad(plaintext) { + const unpadded = utf8Encoder.encode(plaintext); + const unpaddedLen = unpadded.length; + const prefix = writeU16BE(unpaddedLen); + const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen); + return concatBytes2(prefix, unpadded, suffix); +} +function unpad(padded) { + const unpaddedLen = new DataView(padded.buffer).getUint16(0); + const unpadded = padded.subarray(2, 2 + unpaddedLen); + if (unpaddedLen < minPlaintextSize || unpaddedLen > maxPlaintextSize || unpadded.length !== unpaddedLen || padded.length !== 2 + calcPaddedLen(unpaddedLen)) + throw new Error("invalid padding"); + return utf8Decoder.decode(unpadded); +} +function hmacAad(key, message, aad) { + if (aad.length !== 32) + throw new Error("AAD associated data must be 32 bytes"); + const combined = concatBytes2(aad, message); + return hmac(sha2563, key, combined); +} +function decodePayload(payload) { + if (typeof payload !== "string") + throw new Error("payload must be a valid string"); + const plen = payload.length; + if (plen < 132 || plen > 87472) + throw new Error("invalid payload length: " + plen); + if (payload[0] === "#") + throw new Error("unknown encryption version"); + let data; + try { + data = base642.decode(payload); + } catch (error) { + throw new Error("invalid base64: " + error.message); + } + const dlen = data.length; + if (dlen < 99 || dlen > 65603) + throw new Error("invalid data length: " + dlen); + const vers = data[0]; + if (vers !== 2) + throw new Error("unknown encryption version " + vers); + return { + nonce: data.subarray(1, 33), + ciphertext: data.subarray(33, -32), + mac: data.subarray(-32) + }; +} +function encrypt2(plaintext, conversationKey, nonce = randomBytes2(32)) { + const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); + const padded = pad(plaintext); + const ciphertext = chacha20(chacha_key, chacha_nonce, padded); + const mac = hmacAad(hmac_key, ciphertext, nonce); + return base642.encode(concatBytes2(new Uint8Array([2]), nonce, ciphertext, mac)); +} +function decrypt2(payload, conversationKey) { + const { nonce, ciphertext, mac } = decodePayload(payload); + const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); + const calculatedMac = hmacAad(hmac_key, ciphertext, nonce); + if (!equalBytes(calculatedMac, mac)) + throw new Error("invalid MAC"); + const padded = chacha20(chacha_key, chacha_nonce, ciphertext); + return unpad(padded); +} +var v2 = { + utils: { + getConversationKey, + calcPaddedLen + }, + encrypt: encrypt2, + decrypt: decrypt2 +}; + +// nip59.ts +var TWO_DAYS = 2 * 24 * 60 * 60; +var now = () => Math.round(Date.now() / 1e3); +var randomNow = () => Math.round(now() - Math.random() * TWO_DAYS); +var nip44ConversationKey = (privateKey, publicKey) => getConversationKey(privateKey, publicKey); +var nip44Encrypt = (data, privateKey, publicKey) => encrypt2(JSON.stringify(data), nip44ConversationKey(privateKey, publicKey)); +var nip44Decrypt = (data, privateKey) => JSON.parse(decrypt2(data.content, nip44ConversationKey(privateKey, data.pubkey))); +function createRumor(event, privateKey) { + const rumor = { + created_at: now(), + content: "", + tags: [], + ...event, + pubkey: getPublicKey(privateKey) + }; + rumor.id = getEventHash(rumor); + return rumor; +} +function createSeal(rumor, privateKey, recipientPublicKey) { + return finalizeEvent( + { + kind: Seal, + content: nip44Encrypt(rumor, privateKey, recipientPublicKey), + created_at: randomNow(), + tags: [] + }, + privateKey + ); +} +function createWrap(seal, recipientPublicKey) { + const randomKey = generateSecretKey(); + return finalizeEvent( + { + kind: GiftWrap, + content: nip44Encrypt(seal, randomKey, recipientPublicKey), + created_at: randomNow(), + tags: [["p", recipientPublicKey]] + }, + randomKey + ); +} +function wrapEvent(event, senderPrivateKey, recipientPublicKey) { + const rumor = createRumor(event, senderPrivateKey); + const seal = createSeal(rumor, senderPrivateKey, recipientPublicKey); + return createWrap(seal, recipientPublicKey); +} +function wrapManyEvents(event, senderPrivateKey, recipientsPublicKeys) { + if (!recipientsPublicKeys || recipientsPublicKeys.length === 0) { + throw new Error("At least one recipient is required."); + } + const senderPublicKey = getPublicKey(senderPrivateKey); + const wrappeds = [wrapEvent(event, senderPrivateKey, senderPublicKey)]; + recipientsPublicKeys.forEach((recipientPublicKey) => { + wrappeds.push(wrapEvent(event, senderPrivateKey, recipientPublicKey)); + }); + return wrappeds; +} +function unwrapEvent(wrap, recipientPrivateKey) { + const unwrappedSeal = nip44Decrypt(wrap, recipientPrivateKey); + return nip44Decrypt(unwrappedSeal, recipientPrivateKey); +} +function unwrapManyEvents(wrappedEvents, recipientPrivateKey) { + let unwrappedEvents = []; + wrappedEvents.forEach((e) => { + unwrappedEvents.push(unwrapEvent(e, recipientPrivateKey)); + }); + unwrappedEvents.sort((a, b) => a.created_at - b.created_at); + return unwrappedEvents; +} + +// nip17.ts +function createEvent(recipients, message, conversationTitle, replyTo) { + const baseEvent = { + created_at: Math.ceil(Date.now() / 1e3), + kind: PrivateDirectMessage, + tags: [], + content: message + }; + const recipientsArray = Array.isArray(recipients) ? recipients : [recipients]; + recipientsArray.forEach(({ publicKey, relayUrl }) => { + baseEvent.tags.push(relayUrl ? ["p", publicKey, relayUrl] : ["p", publicKey]); + }); + if (replyTo) { + baseEvent.tags.push(["e", replyTo.eventId, replyTo.relayUrl || "", "reply"]); + } + if (conversationTitle) { + baseEvent.tags.push(["subject", conversationTitle]); + } + return baseEvent; +} +function wrapEvent2(senderPrivateKey, recipient, message, conversationTitle, replyTo) { + const event = createEvent(recipient, message, conversationTitle, replyTo); + return wrapEvent(event, senderPrivateKey, recipient.publicKey); +} +function wrapManyEvents2(senderPrivateKey, recipients, message, conversationTitle, replyTo) { + if (!recipients || recipients.length === 0) { + throw new Error("At least one recipient is required."); + } + const senderPublicKey = getPublicKey(senderPrivateKey); + return [{ publicKey: senderPublicKey }, ...recipients].map( + (recipient) => wrapEvent2(senderPrivateKey, recipient, message, conversationTitle, replyTo) + ); +} +var unwrapEvent2 = unwrapEvent; +var unwrapManyEvents2 = unwrapManyEvents; + +// nip18.ts +var nip18_exports = {}; +__export(nip18_exports, { + finishRepostEvent: () => finishRepostEvent, + getRepostedEvent: () => getRepostedEvent, + getRepostedEventPointer: () => getRepostedEventPointer +}); +function finishRepostEvent(t, reposted, relayUrl, privateKey) { + let kind; + const tags = [...t.tags ?? [], ["e", reposted.id, relayUrl], ["p", reposted.pubkey]]; + if (reposted.kind === ShortTextNote) { + kind = Repost; + } else { + kind = GenericRepost; + tags.push(["k", String(reposted.kind)]); + } + return finalizeEvent( + { + kind, + tags, + content: t.content === "" || reposted.tags?.find((tag) => tag[0] === "-") ? "" : JSON.stringify(reposted), + created_at: t.created_at + }, + privateKey + ); +} +function getRepostedEventPointer(event) { + if (![Repost, GenericRepost].includes(event.kind)) { + return void 0; + } + let lastETag; + let lastPTag; + for (let i2 = event.tags.length - 1; i2 >= 0 && (lastETag === void 0 || lastPTag === void 0); i2--) { + const tag = event.tags[i2]; + if (tag.length >= 2) { + if (tag[0] === "e" && lastETag === void 0) { + lastETag = tag; + } else if (tag[0] === "p" && lastPTag === void 0) { + lastPTag = tag; + } + } + } + if (lastETag === void 0) { + return void 0; + } + return { + id: lastETag[1], + relays: [lastETag[2], lastPTag?.[2]].filter((x) => typeof x === "string"), + author: lastPTag?.[1] + }; +} +function getRepostedEvent(event, { skipVerification } = {}) { + const pointer = getRepostedEventPointer(event); + if (pointer === void 0 || event.content === "") { + return void 0; + } + let repostedEvent; + try { + repostedEvent = JSON.parse(event.content); + } catch (error) { + return void 0; + } + if (repostedEvent.id !== pointer.id) { + return void 0; + } + if (!skipVerification && !verifyEvent(repostedEvent)) { + return void 0; + } + return repostedEvent; +} + +// nip21.ts +var nip21_exports = {}; +__export(nip21_exports, { + NOSTR_URI_REGEX: () => NOSTR_URI_REGEX, + parse: () => parse2, + test: () => test +}); +var NOSTR_URI_REGEX = new RegExp(`nostr:(${BECH32_REGEX.source})`); +function test(value) { + return typeof value === "string" && new RegExp(`^${NOSTR_URI_REGEX.source}$`).test(value); +} +function parse2(uri) { + const match = uri.match(new RegExp(`^${NOSTR_URI_REGEX.source}$`)); + if (!match) + throw new Error(`Invalid Nostr URI: ${uri}`); + return { + uri: match[0], + value: match[1], + decoded: decode(match[1]) + }; +} + +// nip25.ts +var nip25_exports = {}; +__export(nip25_exports, { + finishReactionEvent: () => finishReactionEvent, + getReactedEventPointer: () => getReactedEventPointer +}); +function finishReactionEvent(t, reacted, privateKey) { + const inheritedTags = reacted.tags.filter((tag) => tag.length >= 2 && (tag[0] === "e" || tag[0] === "p")); + return finalizeEvent( + { + ...t, + kind: Reaction, + tags: [...t.tags ?? [], ...inheritedTags, ["e", reacted.id], ["p", reacted.pubkey]], + content: t.content ?? "+" + }, + privateKey + ); +} +function getReactedEventPointer(event) { + if (event.kind !== Reaction) { + return void 0; + } + let lastETag; + let lastPTag; + for (let i2 = event.tags.length - 1; i2 >= 0 && (lastETag === void 0 || lastPTag === void 0); i2--) { + const tag = event.tags[i2]; + if (tag.length >= 2) { + if (tag[0] === "e" && lastETag === void 0) { + lastETag = tag; + } else if (tag[0] === "p" && lastPTag === void 0) { + lastPTag = tag; + } + } + } + if (lastETag === void 0 || lastPTag === void 0) { + return void 0; + } + return { + id: lastETag[1], + relays: [lastETag[2], lastPTag[2]].filter((x) => x !== void 0), + author: lastPTag[1] + }; +} + +// nip27.ts +var nip27_exports = {}; +__export(nip27_exports, { + parse: () => parse3 +}); +var noCharacter = /\W/m; +var noURLCharacter = /\W |\W$|$|,| /m; +function* parse3(content) { + const max = content.length; + let prevIndex = 0; + let index = 0; + while (index < max) { + let u = content.indexOf(":", index); + if (u === -1) { + break; + } + if (content.substring(u - 5, u) === "nostr") { + const m = content.substring(u + 60).match(noCharacter); + const end = m ? u + 60 + m.index : max; + try { + let pointer; + let { data, type } = decode(content.substring(u + 1, end)); + switch (type) { + case "npub": + pointer = { pubkey: data }; + break; + case "nsec": + case "note": + index = end + 1; + continue; + default: + pointer = data; + } + if (prevIndex !== u - 5) { + yield { type: "text", text: content.substring(prevIndex, u - 5) }; + } + yield { type: "reference", pointer }; + index = end; + prevIndex = index; + continue; + } catch (_err) { + index = u + 1; + continue; + } + } else if (content.substring(u - 5, u) === "https" || content.substring(u - 4, u) === "http") { + const m = content.substring(u + 4).match(noURLCharacter); + const end = m ? u + 4 + m.index : max; + const prefixLen = content[u - 1] === "s" ? 5 : 4; + try { + let url = new URL(content.substring(u - prefixLen, end)); + if (url.hostname.indexOf(".") === -1) { + throw new Error("invalid url"); + } + if (prevIndex !== u - prefixLen) { + yield { type: "text", text: content.substring(prevIndex, u - prefixLen) }; + } + if (url.pathname.endsWith(".png") || url.pathname.endsWith(".jpg") || url.pathname.endsWith(".jpeg") || url.pathname.endsWith(".gif") || url.pathname.endsWith(".webp")) { + yield { type: "image", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } + if (url.pathname.endsWith(".mp4") || url.pathname.endsWith(".avi") || url.pathname.endsWith(".webm") || url.pathname.endsWith(".mkv")) { + yield { type: "video", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } + if (url.pathname.endsWith(".mp3") || url.pathname.endsWith(".aac") || url.pathname.endsWith(".ogg") || url.pathname.endsWith(".opus")) { + yield { type: "audio", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } + yield { type: "url", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } catch (_err) { + index = end + 1; + continue; + } + } else if (content.substring(u - 3, u) === "wss" || content.substring(u - 2, u) === "ws") { + const m = content.substring(u + 4).match(noURLCharacter); + const end = m ? u + 4 + m.index : max; + const prefixLen = content[u - 1] === "s" ? 3 : 2; + try { + let url = new URL(content.substring(u - prefixLen, end)); + if (url.hostname.indexOf(".") === -1) { + throw new Error("invalid ws url"); + } + if (prevIndex !== u - prefixLen) { + yield { type: "text", text: content.substring(prevIndex, u - prefixLen) }; + } + yield { type: "relay", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } catch (_err) { + index = end + 1; + continue; + } + } else { + index = u + 1; + continue; + } + } + if (prevIndex !== max) { + yield { type: "text", text: content.substring(prevIndex) }; + } +} + +// nip28.ts +var nip28_exports = {}; +__export(nip28_exports, { + channelCreateEvent: () => channelCreateEvent, + channelHideMessageEvent: () => channelHideMessageEvent, + channelMessageEvent: () => channelMessageEvent, + channelMetadataEvent: () => channelMetadataEvent, + channelMuteUserEvent: () => channelMuteUserEvent +}); +var channelCreateEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finalizeEvent( + { + kind: ChannelCreation, + tags: [...t.tags ?? []], + content, + created_at: t.created_at + }, + privateKey + ); +}; +var channelMetadataEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finalizeEvent( + { + kind: ChannelMetadata, + tags: [["e", t.channel_create_event_id], ...t.tags ?? []], + content, + created_at: t.created_at + }, + privateKey + ); +}; +var channelMessageEvent = (t, privateKey) => { + const tags = [["e", t.channel_create_event_id, t.relay_url, "root"]]; + if (t.reply_to_channel_message_event_id) { + tags.push(["e", t.reply_to_channel_message_event_id, t.relay_url, "reply"]); + } + return finalizeEvent( + { + kind: ChannelMessage, + tags: [...tags, ...t.tags ?? []], + content: t.content, + created_at: t.created_at + }, + privateKey + ); +}; +var channelHideMessageEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finalizeEvent( + { + kind: ChannelHideMessage, + tags: [["e", t.channel_message_event_id], ...t.tags ?? []], + content, + created_at: t.created_at + }, + privateKey + ); +}; +var channelMuteUserEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finalizeEvent( + { + kind: ChannelMuteUser, + tags: [["p", t.pubkey_to_mute], ...t.tags ?? []], + content, + created_at: t.created_at + }, + privateKey + ); +}; + +// nip30.ts +var nip30_exports = {}; +__export(nip30_exports, { + EMOJI_SHORTCODE_REGEX: () => EMOJI_SHORTCODE_REGEX, + matchAll: () => matchAll, + regex: () => regex, + replaceAll: () => replaceAll +}); +var EMOJI_SHORTCODE_REGEX = /:(\w+):/; +var regex = () => new RegExp(`\\B${EMOJI_SHORTCODE_REGEX.source}\\B`, "g"); +function* matchAll(content) { + const matches = content.matchAll(regex()); + for (const match of matches) { + try { + const [shortcode, name] = match; + yield { + shortcode, + name, + start: match.index, + end: match.index + shortcode.length + }; + } catch (_e) { + } + } +} +function replaceAll(content, replacer) { + return content.replaceAll(regex(), (shortcode, name) => { + return replacer({ + shortcode, + name + }); + }); +} + +// nip39.ts +var nip39_exports = {}; +__export(nip39_exports, { + useFetchImplementation: () => useFetchImplementation3, + validateGithub: () => validateGithub +}); +var _fetch3; +try { + _fetch3 = fetch; +} catch { +} +function useFetchImplementation3(fetchImplementation) { + _fetch3 = fetchImplementation; +} +async function validateGithub(pubkey, username, proof) { + try { + let res = await (await _fetch3(`https://gist.github.com/${username}/${proof}/raw`)).text(); + return res === `Verifying that I control the following Nostr public key: ${pubkey}`; + } catch (_) { + return false; + } +} + +// nip47.ts +var nip47_exports = {}; +__export(nip47_exports, { + makeNwcRequestEvent: () => makeNwcRequestEvent, + parseConnectionString: () => parseConnectionString +}); +function parseConnectionString(connectionString) { + const { host, pathname, searchParams } = new URL(connectionString); + const pubkey = pathname || host; + const relay = searchParams.get("relay"); + const secret = searchParams.get("secret"); + if (!pubkey || !relay || !secret) { + throw new Error("invalid connection string"); + } + return { pubkey, relay, secret }; +} +async function makeNwcRequestEvent(pubkey, secretKey, invoice) { + const content = { + method: "pay_invoice", + params: { + invoice + } + }; + const encryptedContent = encrypt(secretKey, pubkey, JSON.stringify(content)); + const eventTemplate = { + kind: NWCWalletRequest, + created_at: Math.round(Date.now() / 1e3), + content: encryptedContent, + tags: [["p", pubkey]] + }; + return finalizeEvent(eventTemplate, secretKey); +} + +// nip54.ts +var nip54_exports = {}; +__export(nip54_exports, { + normalizeIdentifier: () => normalizeIdentifier +}); +function normalizeIdentifier(name) { + name = name.trim().toLowerCase(); + name = name.normalize("NFKC"); + return Array.from(name).map((char) => { + if (/\p{Letter}/u.test(char) || /\p{Number}/u.test(char)) { + return char; + } + return "-"; + }).join(""); +} + +// nip57.ts +var nip57_exports = {}; +__export(nip57_exports, { + getSatoshisAmountFromBolt11: () => getSatoshisAmountFromBolt11, + getZapEndpoint: () => getZapEndpoint, + makeZapReceipt: () => makeZapReceipt, + makeZapRequest: () => makeZapRequest, + useFetchImplementation: () => useFetchImplementation4, + validateZapRequest: () => validateZapRequest +}); +import { bech32 as bech322 } from "@scure/base"; +var _fetch4; +try { + _fetch4 = fetch; +} catch { +} +function useFetchImplementation4(fetchImplementation) { + _fetch4 = fetchImplementation; +} +async function getZapEndpoint(metadata) { + try { + let lnurl = ""; + let { lud06, lud16 } = JSON.parse(metadata.content); + if (lud06) { + let { words } = bech322.decode(lud06, 1e3); + let data = bech322.fromWords(words); + lnurl = utf8Decoder.decode(data); + } else if (lud16) { + let [name, domain] = lud16.split("@"); + lnurl = new URL(`/.well-known/lnurlp/${name}`, `https://${domain}`).toString(); + } else { + return null; + } + let res = await _fetch4(lnurl); + let body = await res.json(); + if (body.allowsNostr && body.nostrPubkey) { + return body.callback; + } + } catch (err) { + } + return null; +} +function makeZapRequest(params) { + let zr = { + kind: 9734, + created_at: Math.round(Date.now() / 1e3), + content: params.comment || "", + tags: [ + ["p", "pubkey" in params ? params.pubkey : params.event.pubkey], + ["amount", params.amount.toString()], + ["relays", ...params.relays] + ] + }; + if ("event" in params) { + zr.tags.push(["e", params.event.id]); + if (isReplaceableKind(params.event.kind)) { + const a = ["a", `${params.event.kind}:${params.event.pubkey}:`]; + zr.tags.push(a); + } else if (isAddressableKind(params.event.kind)) { + let d = params.event.tags.find(([t, v]) => t === "d" && v); + if (!d) + throw new Error("d tag not found or is empty"); + const a = ["a", `${params.event.kind}:${params.event.pubkey}:${d[1]}`]; + zr.tags.push(a); + } + zr.tags.push(["k", params.event.kind.toString()]); + } + return zr; +} +function validateZapRequest(zapRequestString) { + let zapRequest; + try { + zapRequest = JSON.parse(zapRequestString); + } catch (err) { + return "Invalid zap request JSON."; + } + if (!validateEvent(zapRequest)) + return "Zap request is not a valid Nostr event."; + if (!verifyEvent(zapRequest)) + return "Invalid signature on zap request."; + let p = zapRequest.tags.find(([t, v]) => t === "p" && v); + if (!p) + return "Zap request doesn't have a 'p' tag."; + if (!p[1].match(/^[a-f0-9]{64}$/)) + return "Zap request 'p' tag is not valid hex."; + let e = zapRequest.tags.find(([t, v]) => t === "e" && v); + if (e && !e[1].match(/^[a-f0-9]{64}$/)) + return "Zap request 'e' tag is not valid hex."; + let relays = zapRequest.tags.find(([t, v]) => t === "relays" && v); + if (!relays) + return "Zap request doesn't have a 'relays' tag."; + return null; +} +function makeZapReceipt({ + zapRequest, + preimage, + bolt11, + paidAt +}) { + let zr = JSON.parse(zapRequest); + let tagsFromZapRequest = zr.tags.filter(([t]) => t === "e" || t === "p" || t === "a"); + let zap = { + kind: 9735, + created_at: Math.round(paidAt.getTime() / 1e3), + content: "", + tags: [...tagsFromZapRequest, ["P", zr.pubkey], ["bolt11", bolt11], ["description", zapRequest]] + }; + if (preimage) { + zap.tags.push(["preimage", preimage]); + } + return zap; +} +function getSatoshisAmountFromBolt11(bolt11) { + if (bolt11.length < 50) { + return 0; + } + bolt11 = bolt11.substring(0, 50); + const idx = bolt11.lastIndexOf("1"); + if (idx === -1) { + return 0; + } + const hrp = bolt11.substring(0, idx); + if (!hrp.startsWith("lnbc")) { + return 0; + } + const amount = hrp.substring(4); + if (amount.length < 1) { + return 0; + } + const char = amount[amount.length - 1]; + const digit = char.charCodeAt(0) - "0".charCodeAt(0); + const isDigit = digit >= 0 && digit <= 9; + let cutPoint = amount.length - 1; + if (isDigit) { + cutPoint++; + } + if (cutPoint < 1) { + return 0; + } + const num = parseInt(amount.substring(0, cutPoint)); + switch (char) { + case "m": + return num * 1e5; + case "u": + return num * 100; + case "n": + return num / 10; + case "p": + return num / 1e4; + default: + return num * 1e8; + } +} + +// nip98.ts +var nip98_exports = {}; +__export(nip98_exports, { + getToken: () => getToken, + hashPayload: () => hashPayload, + unpackEventFromToken: () => unpackEventFromToken, + validateEvent: () => validateEvent2, + validateEventKind: () => validateEventKind, + validateEventMethodTag: () => validateEventMethodTag, + validateEventPayloadTag: () => validateEventPayloadTag, + validateEventTimestamp: () => validateEventTimestamp, + validateEventUrlTag: () => validateEventUrlTag, + validateToken: () => validateToken +}); +import { sha256 as sha2564 } from "@noble/hashes/sha256"; +import { bytesToHex as bytesToHex6 } from "@noble/hashes/utils"; +import { base64 as base643 } from "@scure/base"; +var _authorizationScheme = "Nostr "; +async function getToken(loginUrl, httpMethod, sign, includeAuthorizationScheme = false, payload) { + const event = { + kind: HTTPAuth, + tags: [ + ["u", loginUrl], + ["method", httpMethod] + ], + created_at: Math.round(new Date().getTime() / 1e3), + content: "" + }; + if (payload) { + event.tags.push(["payload", hashPayload(payload)]); + } + const signedEvent = await sign(event); + const authorizationScheme = includeAuthorizationScheme ? _authorizationScheme : ""; + return authorizationScheme + base643.encode(utf8Encoder.encode(JSON.stringify(signedEvent))); +} +async function validateToken(token, url, method) { + const event = await unpackEventFromToken(token).catch((error) => { + throw error; + }); + const valid = await validateEvent2(event, url, method).catch((error) => { + throw error; + }); + return valid; +} +async function unpackEventFromToken(token) { + if (!token) { + throw new Error("Missing token"); + } + token = token.replace(_authorizationScheme, ""); + const eventB64 = utf8Decoder.decode(base643.decode(token)); + if (!eventB64 || eventB64.length === 0 || !eventB64.startsWith("{")) { + throw new Error("Invalid token"); + } + const event = JSON.parse(eventB64); + return event; +} +function validateEventTimestamp(event) { + if (!event.created_at) { + return false; + } + return Math.round(new Date().getTime() / 1e3) - event.created_at < 60; +} +function validateEventKind(event) { + return event.kind === HTTPAuth; +} +function validateEventUrlTag(event, url) { + const urlTag = event.tags.find((t) => t[0] === "u"); + if (!urlTag) { + return false; + } + return urlTag.length > 0 && urlTag[1] === url; +} +function validateEventMethodTag(event, method) { + const methodTag = event.tags.find((t) => t[0] === "method"); + if (!methodTag) { + return false; + } + return methodTag.length > 0 && methodTag[1].toLowerCase() === method.toLowerCase(); +} +function hashPayload(payload) { + const hash = sha2564(utf8Encoder.encode(JSON.stringify(payload))); + return bytesToHex6(hash); +} +function validateEventPayloadTag(event, payload) { + const payloadTag = event.tags.find((t) => t[0] === "payload"); + if (!payloadTag) { + return false; + } + const payloadHash = hashPayload(payload); + return payloadTag.length > 0 && payloadTag[1] === payloadHash; +} +async function validateEvent2(event, url, method, body) { + if (!verifyEvent(event)) { + throw new Error("Invalid nostr event, signature invalid"); + } + if (!validateEventKind(event)) { + throw new Error("Invalid nostr event, kind invalid"); + } + if (!validateEventTimestamp(event)) { + throw new Error("Invalid nostr event, created_at timestamp invalid"); + } + if (!validateEventUrlTag(event, url)) { + throw new Error("Invalid nostr event, url tag invalid"); + } + if (!validateEventMethodTag(event, method)) { + throw new Error("Invalid nostr event, method tag invalid"); + } + if (Boolean(body) && typeof body === "object" && Object.keys(body).length > 0) { + if (!validateEventPayloadTag(event, body)) { + throw new Error("Invalid nostr event, payload tag does not match request body hash"); + } + } + return true; +} +export { + Relay, + SimplePool, + finalizeEvent, + fakejson_exports as fj, + generateSecretKey, + getEventHash, + getFilterLimit, + getPublicKey, + kinds_exports as kinds, + matchFilter, + matchFilters, + mergeFilters, + nip04_exports as nip04, + nip05_exports as nip05, + nip10_exports as nip10, + nip11_exports as nip11, + nip13_exports as nip13, + nip17_exports as nip17, + nip18_exports as nip18, + nip19_exports as nip19, + nip21_exports as nip21, + nip25_exports as nip25, + nip27_exports as nip27, + nip28_exports as nip28, + nip30_exports as nip30, + nip39_exports as nip39, + nip42_exports as nip42, + nip44_exports as nip44, + nip47_exports as nip47, + nip54_exports as nip54, + nip57_exports as nip57, + nip59_exports as nip59, + nip98_exports as nip98, + parseReferences, + serializeEvent, + sortEvents, + utils_exports as utils, + validateEvent, + verifiedSymbol, + verifyEvent +}; diff --git a/node_modules/nostr-tools/lib/esm/index.js.map b/node_modules/nostr-tools/lib/esm/index.js.map new file mode 100644 index 0000000..3bcb968 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/index.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../pure.ts", "../../core.ts", "../../utils.ts", "../../kinds.ts", "../../filter.ts", "../../fakejson.ts", "../../nip42.ts", "../../helpers.ts", "../../abstract-relay.ts", "../../relay.ts", "../../abstract-pool.ts", "../../pool.ts", "../../nip19.ts", "../../references.ts", "../../nip04.ts", "../../nip05.ts", "../../nip10.ts", "../../nip11.ts", "../../nip13.ts", "../../nip17.ts", "../../nip59.ts", "../../nip44.ts", "../../nip18.ts", "../../nip21.ts", "../../nip25.ts", "../../nip27.ts", "../../nip28.ts", "../../nip30.ts", "../../nip39.ts", "../../nip47.ts", "../../nip54.ts", "../../nip57.ts", "../../nip98.ts"], + "sourcesContent": ["import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { Event } from './core.ts'\nimport { isAddressableKind, isReplaceableKind } from './kinds.ts'\n\nexport type Filter = {\n ids?: string[]\n kinds?: number[]\n authors?: string[]\n since?: number\n until?: number\n limit?: number\n search?: string\n [key: `#${string}`]: string[] | undefined\n}\n\nexport function matchFilter(filter: Filter, event: Event): boolean {\n if (filter.ids && filter.ids.indexOf(event.id) === -1) {\n return false\n }\n if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) {\n return false\n }\n if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) {\n return false\n }\n\n for (let f in filter) {\n if (f[0] === '#') {\n let tagName = f.slice(1)\n let values = filter[`#${tagName}`]\n if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values!.indexOf(v) !== -1)) return false\n }\n }\n\n if (filter.since && event.created_at < filter.since) return false\n if (filter.until && event.created_at > filter.until) return false\n\n return true\n}\n\nexport function matchFilters(filters: Filter[], event: Event): boolean {\n for (let i = 0; i < filters.length; i++) {\n if (matchFilter(filters[i], event)) {\n return true\n }\n }\n return false\n}\n\nexport function mergeFilters(...filters: Filter[]): Filter {\n let result: Filter = {}\n for (let i = 0; i < filters.length; i++) {\n let filter = filters[i]\n Object.entries(filter).forEach(([property, values]) => {\n if (property === 'kinds' || property === 'ids' || property === 'authors' || property[0] === '#') {\n // @ts-ignore\n result[property] = result[property] || []\n // @ts-ignore\n for (let v = 0; v < values.length; v++) {\n // @ts-ignore\n let value = values[v]\n // @ts-ignore\n if (!result[property].includes(value)) result[property].push(value)\n }\n }\n })\n\n if (filter.limit && (!result.limit || filter.limit > result.limit)) result.limit = filter.limit\n if (filter.until && (!result.until || filter.until > result.until)) result.until = filter.until\n if (filter.since && (!result.since || filter.since < result.since)) result.since = filter.since\n }\n\n return result\n}\n\n/**\n * Calculate the intrinsic limit of a filter.\n * This function returns a positive integer, or `Infinity` if there is no intrinsic limit.\n */\nexport function getFilterLimit(filter: Filter): number {\n if (filter.ids && !filter.ids.length) return 0\n if (filter.kinds && !filter.kinds.length) return 0\n if (filter.authors && !filter.authors.length) return 0\n\n for (const [key, value] of Object.entries(filter)) {\n if (key[0] === '#' && Array.isArray(value) && !value.length) return 0\n }\n\n return Math.min(\n // The `limit` property creates an artificial limit.\n Math.max(0, filter.limit ?? Infinity),\n\n // There can only be one event per `id`.\n filter.ids?.length ?? Infinity,\n\n // Replaceable events are limited by the number of authors and kinds.\n filter.authors?.length && filter.kinds?.every(kind => isReplaceableKind(kind))\n ? filter.authors.length * filter.kinds.length\n : Infinity,\n\n // Parameterized replaceable events are limited by the number of authors, kinds, and \"d\" tags.\n filter.authors?.length && filter.kinds?.every(kind => isAddressableKind(kind)) && filter['#d']?.length\n ? filter.authors.length * filter.kinds.length * filter['#d'].length\n : Infinity,\n )\n}\n", "export function getHex64(json: string, field: string): string {\n let len = field.length + 3\n let idx = json.indexOf(`\"${field}\":`) + len\n let s = json.slice(idx).indexOf(`\"`) + idx + 1\n return json.slice(s, s + 64)\n}\n\nexport function getInt(json: string, field: string): number {\n let len = field.length\n let idx = json.indexOf(`\"${field}\":`) + len + 3\n let sliced = json.slice(idx)\n let end = Math.min(sliced.indexOf(','), sliced.indexOf('}'))\n return parseInt(sliced.slice(0, end), 10)\n}\n\nexport function getSubscriptionId(json: string): string | null {\n let idx = json.slice(0, 22).indexOf(`\"EVENT\"`)\n if (idx === -1) return null\n\n let pstart = json.slice(idx + 7 + 1).indexOf(`\"`)\n if (pstart === -1) return null\n let start = idx + 7 + 1 + pstart\n\n let pend = json.slice(start + 1, 80).indexOf(`\"`)\n if (pend === -1) return null\n let end = start + 1 + pend\n\n return json.slice(start + 1, end)\n}\n\nexport function matchEventId(json: string, id: string): boolean {\n return id === getHex64(json, 'id')\n}\n\nexport function matchEventPubkey(json: string, pubkey: string): boolean {\n return pubkey === getHex64(json, 'pubkey')\n}\n\nexport function matchEventKind(json: string, kind: number): boolean {\n return kind === getInt(json, 'kind')\n}\n", "import { EventTemplate } from './core.ts'\nimport { ClientAuth } from './kinds.ts'\n\n/**\n * creates an EventTemplate for an AUTH event to be signed.\n */\nexport function makeAuthEvent(relayURL: string, challenge: string): EventTemplate {\n return {\n kind: ClientAuth,\n created_at: Math.floor(Date.now() / 1000),\n tags: [\n ['relay', relayURL],\n ['challenge', challenge],\n ],\n content: '',\n }\n}\n", "import { verifiedSymbol, type Event, type Nostr, VerifiedEvent } from './core.ts'\n\nexport async function yieldThread() {\n return new Promise(resolve => {\n const ch = new MessageChannel()\n const handler = () => {\n // @ts-ignore (typescript thinks this property should be called `removeListener`, but in fact it's `removeEventListener`)\n ch.port1.removeEventListener('message', handler)\n resolve()\n }\n // @ts-ignore (typescript thinks this property should be called `addListener`, but in fact it's `addEventListener`)\n ch.port1.addEventListener('message', handler)\n ch.port2.postMessage(0)\n ch.port1.start()\n })\n}\n\nexport const alwaysTrue: Nostr['verifyEvent'] = (t: Event): t is VerifiedEvent => {\n t[verifiedSymbol] = true\n return true\n}\n", "/* global WebSocket */\n\nimport type { Event, EventTemplate, VerifiedEvent, Nostr, NostrEvent } from './core.ts'\nimport { matchFilters, type Filter } from './filter.ts'\nimport { getHex64, getSubscriptionId } from './fakejson.ts'\nimport { Queue, normalizeURL } from './utils.ts'\nimport { makeAuthEvent } from './nip42.ts'\nimport { yieldThread } from './helpers.ts'\n\ntype RelayWebSocket = WebSocket & {\n ping?(): void\n on?(event: 'pong', listener: () => void): any\n}\n\nexport type AbstractRelayConstructorOptions = {\n verifyEvent: Nostr['verifyEvent']\n websocketImplementation?: typeof WebSocket\n enablePing?: boolean\n}\n\nexport class SendingOnClosedConnection extends Error {\n constructor(message: string, relay: string) {\n super(`Tried to send message '${message} on a closed connection to ${relay}.`)\n this.name = 'SendingOnClosedConnection'\n }\n}\n\nexport class AbstractRelay {\n public readonly url: string\n private _connected: boolean = false\n\n public onclose: (() => void) | null = null\n public onnotice: (msg: string) => void = msg => console.debug(`NOTICE from ${this.url}: ${msg}`)\n\n public baseEoseTimeout: number = 4400\n public connectionTimeout: number = 4400\n public publishTimeout: number = 4400\n public pingFrequency: number = 20000\n public pingTimeout: number = 20000\n public openSubs: Map = new Map()\n public enablePing: boolean | undefined\n private connectionTimeoutHandle: ReturnType | undefined\n\n private connectionPromise: Promise | undefined\n private openCountRequests = new Map()\n private openEventPublishes = new Map()\n private ws: RelayWebSocket | undefined\n private incomingMessageQueue = new Queue()\n private queueRunning = false\n private challenge: string | undefined\n private authPromise: Promise | undefined\n private serial: number = 0\n private verifyEvent: Nostr['verifyEvent']\n\n private _WebSocket: typeof WebSocket\n\n constructor(url: string, opts: AbstractRelayConstructorOptions) {\n this.url = normalizeURL(url)\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation || WebSocket\n this.enablePing = opts.enablePing\n }\n\n static async connect(url: string, opts: AbstractRelayConstructorOptions): Promise {\n const relay = new AbstractRelay(url, opts)\n await relay.connect()\n return relay\n }\n\n private closeAllSubscriptions(reason: string) {\n for (let [_, sub] of this.openSubs) {\n sub.close(reason)\n }\n this.openSubs.clear()\n\n for (let [_, ep] of this.openEventPublishes) {\n ep.reject(new Error(reason))\n }\n this.openEventPublishes.clear()\n\n for (let [_, cr] of this.openCountRequests) {\n cr.reject(new Error(reason))\n }\n this.openCountRequests.clear()\n }\n\n public get connected(): boolean {\n return this._connected\n }\n\n public async connect(): Promise {\n if (this.connectionPromise) return this.connectionPromise\n\n this.challenge = undefined\n this.authPromise = undefined\n this.connectionPromise = new Promise((resolve, reject) => {\n this.connectionTimeoutHandle = setTimeout(() => {\n reject('connection timed out')\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection timed out')\n }, this.connectionTimeout)\n\n try {\n this.ws = new this._WebSocket(this.url)\n } catch (err) {\n clearTimeout(this.connectionTimeoutHandle)\n reject(err)\n return\n }\n\n this.ws.onopen = () => {\n clearTimeout(this.connectionTimeoutHandle)\n this._connected = true\n if (this.enablePing) {\n this.pingpong()\n }\n resolve()\n }\n\n this.ws.onerror = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket error')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection errored')\n }\n }\n\n this.ws.onclose = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket closed')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection closed')\n }\n }\n\n this.ws.onmessage = this._onmessage.bind(this)\n })\n\n return this.connectionPromise\n }\n\n private async waitForPingPong() {\n return new Promise((res, err) => {\n // listen for pong\n ;(this.ws && this.ws.on && this.ws.on('pong', () => res(true))) || err(\"ws can't listen for pong\")\n // send a ping\n this.ws && this.ws.ping && this.ws.ping()\n })\n }\n\n private async waitForDummyReq() {\n return new Promise((resolve, _) => {\n // make a dummy request with expected empty eose reply\n // [\"REQ\", \"_\", {\"ids\":[\"aaaa...aaaa\"]}]\n const sub = this.subscribe([{ ids: ['a'.repeat(64)] }], {\n oneose: () => {\n sub.close()\n resolve(true)\n },\n eoseTimeout: this.pingTimeout + 1000,\n })\n })\n }\n\n // nodejs requires this magic here to ensure connections are closed when internet goes off and stuff\n // in browsers it's done automatically. see https://github.com/nbd-wtf/nostr-tools/issues/491\n private async pingpong() {\n // if the websocket is connected\n if (this.ws?.readyState === 1) {\n // wait for either a ping-pong reply or a timeout\n const result = await Promise.any([\n // browsers don't have ping so use a dummy req\n this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(),\n new Promise(res => setTimeout(() => res(false), this.pingTimeout)),\n ])\n if (result) {\n // schedule another pingpong\n setTimeout(() => this.pingpong(), this.pingFrequency)\n } else {\n // pingpong closing socket\n this.closeAllSubscriptions('pingpong timed out')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n }\n }\n\n private async runQueue() {\n this.queueRunning = true\n while (true) {\n if (false === this.handleNext()) {\n break\n }\n await yieldThread()\n }\n this.queueRunning = false\n }\n\n private handleNext(): undefined | false {\n const json = this.incomingMessageQueue.dequeue()\n if (!json) {\n return false\n }\n\n const subid = getSubscriptionId(json)\n if (subid) {\n const so = this.openSubs.get(subid as string)\n if (!so) {\n // this is an EVENT message, but for a subscription we don't have, so just stop here\n return\n }\n\n // this will be called only when this message is a EVENT message for a subscription we have\n // we do this before parsing the JSON to not have to do that for duplicate events\n // since JSON parsing is slow\n const id = getHex64(json, 'id')\n const alreadyHave = so.alreadyHaveEvent?.(id)\n\n // notify any interested client that the relay has this event\n // (do this after alreadyHaveEvent() because the client may rely on this to answer that)\n so.receivedEvent?.(this, id)\n\n if (alreadyHave) {\n // if we had already seen this event we can just stop here\n return\n }\n }\n\n try {\n let data = JSON.parse(json)\n // we won't do any checks against the data since all failures (i.e. invalid messages from relays)\n // will naturally be caught by the encompassing try..catch block\n\n switch (data[0]) {\n case 'EVENT': {\n const so = this.openSubs.get(data[1] as string) as Subscription\n const event = data[2] as NostrEvent\n if (this.verifyEvent(event) && matchFilters(so.filters, event)) {\n so.onevent(event)\n }\n return\n }\n case 'COUNT': {\n const id: string = data[1]\n const payload = data[2] as { count: number }\n const cr = this.openCountRequests.get(id) as CountResolver\n if (cr) {\n cr.resolve(payload.count)\n this.openCountRequests.delete(id)\n }\n return\n }\n case 'EOSE': {\n const so = this.openSubs.get(data[1] as string)\n if (!so) return\n so.receivedEose()\n return\n }\n case 'OK': {\n const id: string = data[1]\n const ok: boolean = data[2]\n const reason: string = data[3]\n const ep = this.openEventPublishes.get(id) as EventPublishResolver\n if (ep) {\n clearTimeout(ep.timeout)\n if (ok) ep.resolve(reason)\n else ep.reject(new Error(reason))\n this.openEventPublishes.delete(id)\n }\n return\n }\n case 'CLOSED': {\n const id: string = data[1]\n const so = this.openSubs.get(id)\n if (!so) return\n so.closed = true\n so.close(data[2] as string)\n return\n }\n case 'NOTICE':\n this.onnotice(data[1] as string)\n return\n case 'AUTH': {\n this.challenge = data[1] as string\n return\n }\n }\n } catch (err) {\n return\n }\n }\n\n public async send(message: string) {\n if (!this.connectionPromise) throw new SendingOnClosedConnection(message, this.url)\n\n this.connectionPromise.then(() => {\n this.ws?.send(message)\n })\n }\n\n public async auth(signAuthEvent: (evt: EventTemplate) => Promise): Promise {\n const challenge = this.challenge\n if (!challenge) throw new Error(\"can't perform auth, no challenge was received\")\n if (this.authPromise) return this.authPromise\n\n this.authPromise = new Promise(async (resolve, reject) => {\n try {\n let evt = await signAuthEvent(makeAuthEvent(this.url, challenge))\n let timeout = setTimeout(() => {\n let ep = this.openEventPublishes.get(evt.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('auth timed out'))\n this.openEventPublishes.delete(evt.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(evt.id, { resolve, reject, timeout })\n this.send('[\"AUTH\",' + JSON.stringify(evt) + ']')\n } catch (err) {\n console.warn('subscribe auth function failed:', err)\n }\n })\n return this.authPromise\n }\n\n public async publish(event: Event): Promise {\n const ret = new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n const ep = this.openEventPublishes.get(event.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('publish timed out'))\n this.openEventPublishes.delete(event.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(event.id, { resolve, reject, timeout })\n })\n this.send('[\"EVENT\",' + JSON.stringify(event) + ']')\n return ret\n }\n\n public async count(filters: Filter[], params: { id?: string | null }): Promise {\n this.serial++\n const id = params?.id || 'count:' + this.serial\n const ret = new Promise((resolve, reject) => {\n this.openCountRequests.set(id, { resolve, reject })\n })\n this.send('[\"COUNT\",\"' + id + '\",' + JSON.stringify(filters).substring(1))\n return ret\n }\n\n public subscribe(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n const subscription = this.prepareSubscription(filters, params)\n subscription.fire()\n return subscription\n }\n\n public prepareSubscription(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n this.serial++\n const id = params.id || (params.label ? params.label + ':' : 'sub:') + this.serial\n const subscription = new Subscription(this, id, filters, params)\n this.openSubs.set(id, subscription)\n return subscription\n }\n\n public close() {\n this.closeAllSubscriptions('relay connection closed by us')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n\n // this is the function assigned to this.ws.onmessage\n // it's exposed for testing and debugging purposes\n public _onmessage(ev: MessageEvent) {\n this.incomingMessageQueue.enqueue(ev.data as string)\n if (!this.queueRunning) {\n this.runQueue()\n }\n }\n}\n\nexport class Subscription {\n public readonly relay: AbstractRelay\n public readonly id: string\n\n public closed: boolean = false\n public eosed: boolean = false\n public filters: Filter[]\n public alreadyHaveEvent: ((id: string) => boolean) | undefined\n public receivedEvent: ((relay: AbstractRelay, id: string) => void) | undefined\n\n public onevent: (evt: Event) => void\n public oneose: (() => void) | undefined\n public onclose: ((reason: string) => void) | undefined\n\n public eoseTimeout: number\n private eoseTimeoutHandle: ReturnType | undefined\n\n constructor(relay: AbstractRelay, id: string, filters: Filter[], params: SubscriptionParams) {\n this.relay = relay\n this.filters = filters\n this.id = id\n this.alreadyHaveEvent = params.alreadyHaveEvent\n this.receivedEvent = params.receivedEvent\n this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout\n\n this.oneose = params.oneose\n this.onclose = params.onclose\n this.onevent =\n params.onevent ||\n (event => {\n console.warn(\n `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,\n event,\n )\n })\n }\n\n public fire() {\n this.relay.send('[\"REQ\",\"' + this.id + '\",' + JSON.stringify(this.filters).substring(1))\n\n // only now we start counting the eoseTimeout\n this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout)\n }\n\n public receivedEose() {\n if (this.eosed) return\n clearTimeout(this.eoseTimeoutHandle)\n this.eosed = true\n this.oneose?.()\n }\n\n public close(reason: string = 'closed by caller') {\n if (!this.closed && this.relay.connected) {\n // if the connection was closed by the user calling .close() we will send a CLOSE message\n // otherwise this._open will be already set to false so we will skip this\n try {\n this.relay.send('[\"CLOSE\",' + JSON.stringify(this.id) + ']')\n } catch (err) {\n if (err instanceof SendingOnClosedConnection) {\n /* doesn't matter, it's ok */\n } else {\n throw err\n }\n }\n this.closed = true\n }\n this.relay.openSubs.delete(this.id)\n this.onclose?.(reason)\n }\n}\n\nexport type SubscriptionParams = {\n onevent?: (evt: Event) => void\n oneose?: () => void\n onclose?: (reason: string) => void\n alreadyHaveEvent?: (id: string) => boolean\n receivedEvent?: (relay: AbstractRelay, id: string) => void\n eoseTimeout?: number\n}\n\nexport type CountResolver = {\n resolve: (count: number) => void\n reject: (err: Error) => void\n}\n\nexport type EventPublishResolver = {\n resolve: (reason: string) => void\n reject: (err: Error) => void\n timeout: ReturnType\n}\n", "/* global WebSocket */\n\nimport { verifyEvent } from './pure.ts'\nimport { AbstractRelay } from './abstract-relay.ts'\n\nvar _WebSocket: typeof WebSocket\n\ntry {\n _WebSocket = WebSocket\n} catch {}\n\nexport function useWebSocketImplementation(websocketImplementation: any) {\n _WebSocket = websocketImplementation\n}\n\nexport class Relay extends AbstractRelay {\n constructor(url: string) {\n super(url, { verifyEvent, websocketImplementation: _WebSocket })\n }\n\n static async connect(url: string): Promise {\n const relay = new Relay(url)\n await relay.connect()\n return relay\n }\n}\n\nexport type RelayRecord = Record\n\nexport * from './abstract-relay.ts'\n", "/* global WebSocket */\n\nimport {\n AbstractRelay as AbstractRelay,\n SubscriptionParams,\n Subscription,\n type AbstractRelayConstructorOptions,\n} from './abstract-relay.ts'\nimport { normalizeURL } from './utils.ts'\n\nimport type { Event, EventTemplate, Nostr, VerifiedEvent } from './core.ts'\nimport { type Filter } from './filter.ts'\nimport { alwaysTrue } from './helpers.ts'\n\nexport type SubCloser = { close: (reason?: string) => void }\n\nexport type AbstractPoolConstructorOptions = AbstractRelayConstructorOptions & {}\n\nexport type SubscribeManyParams = Omit & {\n maxWait?: number\n onclose?: (reasons: string[]) => void\n onauth?: (event: EventTemplate) => Promise\n // Deprecated: use onauth instead\n doauth?: (event: EventTemplate) => Promise\n id?: string\n label?: string\n}\n\nexport class AbstractSimplePool {\n protected relays: Map = new Map()\n public seenOn: Map> = new Map()\n public trackRelays: boolean = false\n\n public verifyEvent: Nostr['verifyEvent']\n public enablePing: boolean | undefined\n public trustedRelayURLs: Set = new Set()\n\n private _WebSocket?: typeof WebSocket\n\n constructor(opts: AbstractPoolConstructorOptions) {\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation\n this.enablePing = opts.enablePing\n }\n\n async ensureRelay(url: string, params?: { connectionTimeout?: number }): Promise {\n url = normalizeURL(url)\n\n let relay = this.relays.get(url)\n if (!relay) {\n relay = new AbstractRelay(url, {\n verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent,\n websocketImplementation: this._WebSocket,\n enablePing: this.enablePing,\n })\n relay.onclose = () => {\n this.relays.delete(url)\n }\n if (params?.connectionTimeout) relay.connectionTimeout = params.connectionTimeout\n this.relays.set(url, relay)\n }\n await relay.connect()\n\n return relay\n }\n\n close(relays: string[]) {\n relays.map(normalizeURL).forEach(url => {\n this.relays.get(url)?.close()\n this.relays.delete(url)\n })\n }\n\n subscribe(relays: string[], filter: Filter, params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const request: { url: string; filter: Filter }[] = []\n for (let i = 0; i < relays.length; i++) {\n const url = normalizeURL(relays[i])\n if (!request.find(r => r.url === url)) {\n request.push({ url, filter })\n }\n }\n\n return this.subscribeMap(request, params)\n }\n\n subscribeMany(relays: string[], filters: Filter[], params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const request: { url: string; filter: Filter }[] = []\n const uniqUrls: string[] = []\n for (let i = 0; i < relays.length; i++) {\n const url = normalizeURL(relays[i])\n if (uniqUrls.indexOf(url) === -1) {\n for (let f = 0; f < filters.length; f++) {\n request.push({ url, filter: filters[f] })\n }\n }\n }\n\n return this.subscribeMap(request, params)\n }\n\n subscribeMap(requests: { url: string; filter: Filter }[], params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n if (this.trackRelays) {\n params.receivedEvent = (relay: AbstractRelay, id: string) => {\n let set = this.seenOn.get(id)\n if (!set) {\n set = new Set()\n this.seenOn.set(id, set)\n }\n set.add(relay)\n }\n }\n\n const _knownIds = new Set()\n const subs: Subscription[] = []\n\n // batch all EOSEs into a single\n const eosesReceived: boolean[] = []\n let handleEose = (i: number) => {\n if (eosesReceived[i]) return // do not act twice for the same relay\n eosesReceived[i] = true\n if (eosesReceived.filter(a => a).length === requests.length) {\n params.oneose?.()\n handleEose = () => {}\n }\n }\n // batch all closes into a single\n const closesReceived: string[] = []\n let handleClose = (i: number, reason: string) => {\n if (closesReceived[i]) return // do not act twice for the same relay\n handleEose(i)\n closesReceived[i] = reason\n if (closesReceived.filter(a => a).length === requests.length) {\n params.onclose?.(closesReceived)\n handleClose = () => {}\n }\n }\n\n const localAlreadyHaveEventHandler = (id: string) => {\n if (params.alreadyHaveEvent?.(id)) {\n return true\n }\n const have = _knownIds.has(id)\n _knownIds.add(id)\n return have\n }\n\n // open a subscription in all given relays\n const allOpened = Promise.all(\n requests.map(async ({ url, filter }, i) => {\n let relay: AbstractRelay\n try {\n relay = await this.ensureRelay(url, {\n connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1000) : undefined,\n })\n } catch (err) {\n handleClose(i, (err as any)?.message || String(err))\n return\n }\n\n let subscription = relay.subscribe([filter], {\n ...params,\n oneose: () => handleEose(i),\n onclose: reason => {\n if (reason.startsWith('auth-required: ') && params.onauth) {\n relay\n .auth(params.onauth)\n .then(() => {\n relay.subscribe([filter], {\n ...params,\n oneose: () => handleEose(i),\n onclose: reason => {\n handleClose(i, reason) // the second time we won't try to auth anymore\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait,\n })\n })\n .catch(err => {\n handleClose(i, `auth was required and attempted, but failed with: ${err}`)\n })\n } else {\n handleClose(i, reason)\n }\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait,\n })\n\n subs.push(subscription)\n }),\n )\n\n return {\n async close(reason?: string) {\n await allOpened\n subs.forEach(sub => {\n sub.close(reason)\n })\n },\n }\n }\n\n subscribeEose(\n relays: string[],\n filter: Filter,\n params: Pick,\n ): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const subcloser = this.subscribe(relays, filter, {\n ...params,\n oneose() {\n subcloser.close('closed automatically on eose')\n },\n })\n return subcloser\n }\n\n subscribeManyEose(\n relays: string[],\n filters: Filter[],\n params: Pick,\n ): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const subcloser = this.subscribeMany(relays, filters, {\n ...params,\n oneose() {\n subcloser.close('closed automatically on eose')\n },\n })\n return subcloser\n }\n\n async querySync(\n relays: string[],\n filter: Filter,\n params?: Pick,\n ): Promise {\n return new Promise(async resolve => {\n const events: Event[] = []\n this.subscribeEose(relays, filter, {\n ...params,\n onevent(event: Event) {\n events.push(event)\n },\n onclose(_: string[]) {\n resolve(events)\n },\n })\n })\n }\n\n async get(\n relays: string[],\n filter: Filter,\n params?: Pick,\n ): Promise {\n filter.limit = 1\n const events = await this.querySync(relays, filter, params)\n events.sort((a, b) => b.created_at - a.created_at)\n return events[0] || null\n }\n\n publish(\n relays: string[],\n event: Event,\n options?: { onauth?: (evt: EventTemplate) => Promise },\n ): Promise[] {\n return relays.map(normalizeURL).map(async (url, i, arr) => {\n if (arr.indexOf(url) !== i) {\n // duplicate\n return Promise.reject('duplicate url')\n }\n\n let r = await this.ensureRelay(url)\n return r\n .publish(event)\n .catch(async err => {\n if (err instanceof Error && err.message.startsWith('auth-required: ') && options?.onauth) {\n await r.auth(options.onauth)\n return r.publish(event) // retry\n }\n throw err\n })\n .then(reason => {\n if (this.trackRelays) {\n let set = this.seenOn.get(event.id)\n if (!set) {\n set = new Set()\n this.seenOn.set(event.id, set)\n }\n set.add(r)\n }\n return reason\n })\n })\n }\n\n listConnectionStatus(): Map {\n const map = new Map()\n this.relays.forEach((relay, url) => map.set(url, relay.connected))\n\n return map\n }\n\n destroy(): void {\n this.relays.forEach(conn => conn.close())\n this.relays = new Map()\n }\n}\n", "/* global WebSocket */\n\nimport { verifyEvent } from './pure.ts'\nimport { AbstractSimplePool } from './abstract-pool.ts'\n\nvar _WebSocket: typeof WebSocket\n\ntry {\n _WebSocket = WebSocket\n} catch {}\n\nexport function useWebSocketImplementation(websocketImplementation: any) {\n _WebSocket = websocketImplementation\n}\n\nexport class SimplePool extends AbstractSimplePool {\n constructor(options?: { enablePing?: boolean }) {\n super({ verifyEvent, websocketImplementation: _WebSocket, ...options })\n }\n}\n\nexport * from './abstract-pool.ts'\n", "import { bytesToHex, concatBytes, hexToBytes } from '@noble/hashes/utils'\nimport { bech32 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport type NProfile = `nprofile1${string}`\nexport type NEvent = `nevent1${string}`\nexport type NAddr = `naddr1${string}`\nexport type NSec = `nsec1${string}`\nexport type NPub = `npub1${string}`\nexport type Note = `note1${string}`\nexport type Ncryptsec = `ncryptsec1${string}`\n\nexport const NostrTypeGuard = {\n isNProfile: (value?: string | null): value is NProfile => /^nprofile1[a-z\\d]+$/.test(value || ''),\n isNEvent: (value?: string | null): value is NEvent => /^nevent1[a-z\\d]+$/.test(value || ''),\n isNAddr: (value?: string | null): value is NAddr => /^naddr1[a-z\\d]+$/.test(value || ''),\n isNSec: (value?: string | null): value is NSec => /^nsec1[a-z\\d]{58}$/.test(value || ''),\n isNPub: (value?: string | null): value is NPub => /^npub1[a-z\\d]{58}$/.test(value || ''),\n isNote: (value?: string | null): value is Note => /^note1[a-z\\d]+$/.test(value || ''),\n isNcryptsec: (value?: string | null): value is Ncryptsec => /^ncryptsec1[a-z\\d]+$/.test(value || ''),\n}\n\nexport const Bech32MaxSize = 5000\n\n/**\n * Bech32 regex.\n * @see https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32\n */\nexport const BECH32_REGEX = /[\\x21-\\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/\n\nfunction integerToUint8Array(number: number) {\n // Create a Uint8Array with enough space to hold a 32-bit integer (4 bytes).\n const uint8Array = new Uint8Array(4)\n\n // Use bitwise operations to extract the bytes.\n uint8Array[0] = (number >> 24) & 0xff // Most significant byte (MSB)\n uint8Array[1] = (number >> 16) & 0xff\n uint8Array[2] = (number >> 8) & 0xff\n uint8Array[3] = number & 0xff // Least significant byte (LSB)\n\n return uint8Array\n}\n\nexport type ProfilePointer = {\n pubkey: string // hex\n relays?: string[]\n}\n\nexport type EventPointer = {\n id: string // hex\n relays?: string[]\n author?: string\n kind?: number\n}\n\nexport type AddressPointer = {\n identifier: string\n pubkey: string\n kind: number\n relays?: string[]\n}\n\nexport function decodeNostrURI(nip19code: string): ReturnType | { type: 'invalid'; data: null } {\n try {\n if (nip19code.startsWith('nostr:')) nip19code = nip19code.substring(6)\n return decode(nip19code)\n } catch (_err) {\n return { type: 'invalid', data: null }\n }\n}\n\nexport type DecodedNevent = {\n type: 'nevent'\n data: EventPointer\n}\n\nexport type DecodedNprofile = {\n type: 'nprofile'\n data: ProfilePointer\n}\n\nexport type DecodedNaddr = {\n type: 'naddr'\n data: AddressPointer\n}\n\nexport type DecodedNsec = {\n type: 'nsec'\n data: Uint8Array\n}\n\nexport type DecodedNpub = {\n type: 'npub'\n data: string\n}\n\nexport type DecodedNote = {\n type: 'note'\n data: string\n}\n\nexport type DecodedResult = DecodedNevent | DecodedNprofile | DecodedNaddr | DecodedNpub | DecodedNsec | DecodedNote\n\nexport function decode(nip19: NEvent): DecodedNevent\nexport function decode(nip19: NProfile): DecodedNprofile\nexport function decode(nip19: NAddr): DecodedNaddr\nexport function decode(nip19: NSec): DecodedNsec\nexport function decode(nip19: NPub): DecodedNpub\nexport function decode(nip19: Note): DecodedNote\nexport function decode(code: string): DecodedResult\nexport function decode(code: string): DecodedResult {\n let { prefix, words } = bech32.decode(code, Bech32MaxSize)\n let data = new Uint8Array(bech32.fromWords(words))\n\n switch (prefix) {\n case 'nprofile': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nprofile')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n\n return {\n type: 'nprofile',\n data: {\n pubkey: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n case 'nevent': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nevent')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n if (tlv[2] && tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (tlv[3] && tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'nevent',\n data: {\n id: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n author: tlv[2]?.[0] ? bytesToHex(tlv[2][0]) : undefined,\n kind: tlv[3]?.[0] ? parseInt(bytesToHex(tlv[3][0]), 16) : undefined,\n },\n }\n }\n\n case 'naddr': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for naddr')\n if (!tlv[2]?.[0]) throw new Error('missing TLV 2 for naddr')\n if (tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (!tlv[3]?.[0]) throw new Error('missing TLV 3 for naddr')\n if (tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'naddr',\n data: {\n identifier: utf8Decoder.decode(tlv[0][0]),\n pubkey: bytesToHex(tlv[2][0]),\n kind: parseInt(bytesToHex(tlv[3][0]), 16),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n\n case 'nsec':\n return { type: prefix, data }\n\n case 'npub':\n case 'note':\n return { type: prefix, data: bytesToHex(data) }\n\n default:\n throw new Error(`unknown prefix ${prefix}`)\n }\n}\n\ntype TLV = { [t: number]: Uint8Array[] }\n\nfunction parseTLV(data: Uint8Array): TLV {\n let result: TLV = {}\n let rest = data\n while (rest.length > 0) {\n let t = rest[0]\n let l = rest[1]\n let v = rest.slice(2, 2 + l)\n rest = rest.slice(2 + l)\n if (v.length < l) throw new Error(`not enough data to read on TLV ${t}`)\n result[t] = result[t] || []\n result[t].push(v)\n }\n return result\n}\n\nexport function nsecEncode(key: Uint8Array): NSec {\n return encodeBytes('nsec', key)\n}\n\nexport function npubEncode(hex: string): NPub {\n return encodeBytes('npub', hexToBytes(hex))\n}\n\nexport function noteEncode(hex: string): Note {\n return encodeBytes('note', hexToBytes(hex))\n}\n\nfunction encodeBech32(prefix: Prefix, data: Uint8Array): `${Prefix}1${string}` {\n let words = bech32.toWords(data)\n return bech32.encode(prefix, words, Bech32MaxSize) as `${Prefix}1${string}`\n}\n\nexport function encodeBytes(prefix: Prefix, bytes: Uint8Array): `${Prefix}1${string}` {\n return encodeBech32(prefix, bytes)\n}\n\nexport function nprofileEncode(profile: ProfilePointer): NProfile {\n let data = encodeTLV({\n 0: [hexToBytes(profile.pubkey)],\n 1: (profile.relays || []).map(url => utf8Encoder.encode(url)),\n })\n return encodeBech32('nprofile', data)\n}\n\nexport function neventEncode(event: EventPointer): NEvent {\n let kindArray\n if (event.kind !== undefined) {\n kindArray = integerToUint8Array(event.kind)\n }\n\n let data = encodeTLV({\n 0: [hexToBytes(event.id)],\n 1: (event.relays || []).map(url => utf8Encoder.encode(url)),\n 2: event.author ? [hexToBytes(event.author)] : [],\n 3: kindArray ? [new Uint8Array(kindArray)] : [],\n })\n\n return encodeBech32('nevent', data)\n}\n\nexport function naddrEncode(addr: AddressPointer): NAddr {\n let kind = new ArrayBuffer(4)\n new DataView(kind).setUint32(0, addr.kind, false)\n\n let data = encodeTLV({\n 0: [utf8Encoder.encode(addr.identifier)],\n 1: (addr.relays || []).map(url => utf8Encoder.encode(url)),\n 2: [hexToBytes(addr.pubkey)],\n 3: [new Uint8Array(kind)],\n })\n return encodeBech32('naddr', data)\n}\n\nfunction encodeTLV(tlv: TLV): Uint8Array {\n let entries: Uint8Array[] = []\n\n Object.entries(tlv)\n .reverse()\n .forEach(([t, vs]) => {\n vs.forEach(v => {\n let entry = new Uint8Array(v.length + 2)\n entry.set([parseInt(t)], 0)\n entry.set([v.length], 1)\n entry.set(v, 2)\n entries.push(entry)\n })\n })\n\n return concatBytes(...entries)\n}\n", "import { decode, type AddressPointer, type ProfilePointer, type EventPointer } from './nip19.ts'\n\nimport type { Event } from './core.ts'\n\ntype Reference = {\n text: string\n profile?: ProfilePointer\n event?: EventPointer\n address?: AddressPointer\n}\n\nconst mentionRegex = /\\bnostr:((note|npub|naddr|nevent|nprofile)1\\w+)\\b|#\\[(\\d+)\\]/g\n\nexport function parseReferences(evt: Event): Reference[] {\n let references: Reference[] = []\n for (let ref of evt.content.matchAll(mentionRegex)) {\n if (ref[2]) {\n // it's a NIP-27 mention\n try {\n let { type, data } = decode(ref[1])\n switch (type) {\n case 'npub': {\n references.push({\n text: ref[0],\n profile: { pubkey: data as string, relays: [] },\n })\n break\n }\n case 'nprofile': {\n references.push({\n text: ref[0],\n profile: data as ProfilePointer,\n })\n break\n }\n case 'note': {\n references.push({\n text: ref[0],\n event: { id: data as string, relays: [] },\n })\n break\n }\n case 'nevent': {\n references.push({\n text: ref[0],\n event: data as EventPointer,\n })\n break\n }\n case 'naddr': {\n references.push({\n text: ref[0],\n address: data as AddressPointer,\n })\n break\n }\n }\n } catch (err) {\n /***/\n }\n } else if (ref[3]) {\n // it's a NIP-10 mention\n let idx = parseInt(ref[3], 10)\n let tag = evt.tags[idx]\n if (!tag) continue\n\n switch (tag[0]) {\n case 'p': {\n references.push({\n text: ref[0],\n profile: { pubkey: tag[1], relays: tag[2] ? [tag[2]] : [] },\n })\n break\n }\n case 'e': {\n references.push({\n text: ref[0],\n event: { id: tag[1], relays: tag[2] ? [tag[2]] : [] },\n })\n break\n }\n case 'a': {\n try {\n let [kind, pubkey, identifier] = tag[1].split(':')\n references.push({\n text: ref[0],\n address: {\n identifier,\n pubkey,\n kind: parseInt(kind, 10),\n relays: tag[2] ? [tag[2]] : [],\n },\n })\n } catch (err) {\n /***/\n }\n break\n }\n }\n }\n }\n\n return references\n}\n", "import { bytesToHex, randomBytes } from '@noble/hashes/utils'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { cbc } from '@noble/ciphers/aes'\nimport { base64 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport function encrypt(secretKey: string | Uint8Array, pubkey: string, text: string): string {\n const privkey: string = secretKey instanceof Uint8Array ? bytesToHex(secretKey) : secretKey\n const key = secp256k1.getSharedSecret(privkey, '02' + pubkey)\n const normalizedKey = getNormalizedX(key)\n\n let iv = Uint8Array.from(randomBytes(16))\n let plaintext = utf8Encoder.encode(text)\n\n let ciphertext = cbc(normalizedKey, iv).encrypt(plaintext)\n\n let ctb64 = base64.encode(new Uint8Array(ciphertext))\n let ivb64 = base64.encode(new Uint8Array(iv.buffer))\n\n return `${ctb64}?iv=${ivb64}`\n}\n\nexport function decrypt(secretKey: string | Uint8Array, pubkey: string, data: string): string {\n const privkey: string = secretKey instanceof Uint8Array ? bytesToHex(secretKey) : secretKey\n let [ctb64, ivb64] = data.split('?iv=')\n let key = secp256k1.getSharedSecret(privkey, '02' + pubkey)\n let normalizedKey = getNormalizedX(key)\n\n let iv = base64.decode(ivb64)\n let ciphertext = base64.decode(ctb64)\n\n let plaintext = cbc(normalizedKey, iv).decrypt(ciphertext)\n\n return utf8Decoder.decode(plaintext)\n}\n\nfunction getNormalizedX(key: Uint8Array): Uint8Array {\n return key.slice(1, 33)\n}\n", "import { ProfilePointer } from './nip19.ts'\n\nexport type Nip05 = `${string}@${string}`\n\n/**\n * NIP-05 regex. The localpart is optional, and should be assumed to be `_` otherwise.\n *\n * - 0: full match\n * - 1: name (optional)\n * - 2: domain\n */\nexport const NIP05_REGEX = /^(?:([\\w.+-]+)@)?([\\w_-]+(\\.[\\w_-]+)+)$/\nexport const isNip05 = (value?: string | null): value is Nip05 => NIP05_REGEX.test(value || '')\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _fetch: any\n\ntry {\n _fetch = fetch\n} catch (_) {\n null\n}\n\nexport function useFetchImplementation(fetchImplementation: unknown) {\n _fetch = fetchImplementation\n}\n\nexport async function searchDomain(domain: string, query = ''): Promise<{ [name: string]: string }> {\n try {\n const url = `https://${domain}/.well-known/nostr.json?name=${query}`\n const res = await _fetch(url, { redirect: 'manual' })\n if (res.status !== 200) {\n throw Error('Wrong response code')\n }\n const json = await res.json()\n return json.names\n } catch (_) {\n return {}\n }\n}\n\nexport async function queryProfile(fullname: string): Promise {\n const match = fullname.match(NIP05_REGEX)\n if (!match) return null\n\n const [, name = '_', domain] = match\n\n try {\n const url = `https://${domain}/.well-known/nostr.json?name=${name}`\n const res = await _fetch(url, { redirect: 'manual' })\n if (res.status !== 200) {\n throw Error('Wrong response code')\n }\n const json = await res.json()\n\n const pubkey = json.names[name]\n return pubkey ? { pubkey, relays: json.relays?.[pubkey] } : null\n } catch (_e) {\n return null\n }\n}\n\nexport async function isValid(pubkey: string, nip05: Nip05): Promise {\n const res = await queryProfile(nip05)\n return res ? res.pubkey === pubkey : false\n}\n", "import type { Event } from './core.ts'\nimport type { EventPointer, ProfilePointer } from './nip19.ts'\n\nexport function parse(event: Pick): {\n /**\n * Pointer to the root of the thread.\n */\n root: EventPointer | undefined\n\n /**\n * Pointer to a \"parent\" event that parsed event replies to (responded to).\n */\n reply: EventPointer | undefined\n\n /**\n * Pointers to events that may or may not be in the reply chain.\n */\n mentions: EventPointer[]\n\n /**\n * Pointers to events that were directly quoted.\n */\n quotes: EventPointer[]\n\n /**\n * List of pubkeys that are involved in the thread in no particular order.\n */\n profiles: ProfilePointer[]\n} {\n const result: ReturnType = {\n reply: undefined,\n root: undefined,\n mentions: [],\n profiles: [],\n quotes: [],\n }\n\n let maybeParent: EventPointer | undefined\n let maybeRoot: EventPointer | undefined\n\n for (let i = event.tags.length - 1; i >= 0; i--) {\n const tag = event.tags[i]\n\n if (tag[0] === 'e' && tag[1]) {\n const [_, eTagEventId, eTagRelayUrl, eTagMarker, eTagAuthor] = tag as [\n string,\n string,\n undefined | string,\n undefined | string,\n undefined | string,\n ]\n\n const eventPointer: EventPointer = {\n id: eTagEventId,\n relays: eTagRelayUrl ? [eTagRelayUrl] : [],\n author: eTagAuthor,\n }\n\n if (eTagMarker === 'root') {\n result.root = eventPointer\n continue\n }\n\n if (eTagMarker === 'reply') {\n result.reply = eventPointer\n continue\n }\n\n if (eTagMarker === 'mention') {\n result.mentions.push(eventPointer)\n continue\n }\n\n if (!maybeParent) {\n maybeParent = eventPointer\n } else {\n maybeRoot = eventPointer\n }\n\n result.mentions.push(eventPointer)\n continue\n }\n\n if (tag[0] === 'q' && tag[1]) {\n const [_, eTagEventId, eTagRelayUrl] = tag as [string, string, undefined | string]\n result.quotes.push({\n id: eTagEventId,\n relays: eTagRelayUrl ? [eTagRelayUrl] : [],\n })\n }\n\n if (tag[0] === 'p' && tag[1]) {\n result.profiles.push({\n pubkey: tag[1],\n relays: tag[2] ? [tag[2]] : [],\n })\n continue\n }\n }\n\n // get legacy (positional) markers, set reply to root and vice-versa if one of them is missing\n if (!result.root) {\n result.root = maybeRoot || maybeParent || result.reply\n }\n if (!result.reply) {\n result.reply = maybeParent || result.root\n }\n\n // remove root and reply from mentions, inherit relay hints from authors if any\n ;[result.reply, result.root].forEach(ref => {\n if (!ref) return\n\n let idx = result.mentions.indexOf(ref)\n if (idx !== -1) {\n result.mentions.splice(idx, 1)\n }\n if (ref.author) {\n let author = result.profiles.find(p => p.pubkey === ref.author)\n if (author && author.relays) {\n if (!ref.relays) {\n ref.relays = []\n }\n author.relays.forEach(url => {\n if (ref.relays!?.indexOf(url) === -1) ref.relays!.push(url)\n })\n author.relays = ref.relays\n }\n }\n })\n\n result.mentions.forEach(ref => {\n if (ref!.author) {\n let author = result.profiles.find(p => p.pubkey === ref.author)\n if (author && author.relays) {\n if (!ref.relays) {\n ref.relays = []\n }\n author.relays.forEach(url => {\n if (ref.relays!.indexOf(url) === -1) ref.relays!.push(url)\n })\n author.relays = ref.relays\n }\n }\n })\n\n return result\n}\n", "var _fetch: any\n\ntry {\n _fetch = fetch\n} catch {}\n\nexport function useFetchImplementation(fetchImplementation: any): void {\n _fetch = fetchImplementation\n}\n\nexport async function fetchRelayInformation(url: string): Promise {\n return (await (\n await fetch(url.replace('ws://', 'http://').replace('wss://', 'https://'), {\n headers: { Accept: 'application/nostr+json' },\n })\n ).json()) as RelayInformation\n}\n\n/**\n * ## Relay Information Document\n\n * Relays may provide server metadata to clients to inform\n * them of capabilities, administrative contacts, and\n * various server attributes. This is made available as a\n * JSON document over HTTP, on the same URI as the relay's\n * websocket.\n\n * Any field may be omitted, and clients MUST ignore any\n * additional fields they do not understand. Relays MUST\n * accept CORS requests by sending\n * `Access-Control-Allow-Origin`,\n * `Access-Control-Allow-Headers`, and\n * `Access-Control-Allow-Methods` headers.\n * @param name string identifying relay\n * @param description string with detailed information\n * @param pubkey administrative contact pubkey\n * @param contact: administrative alternate contact\n * @param supported_nips a list of NIP numbers supported by\n * the relay\n * @param software identifying relay software URL\n * @param version string version identifier\n */\nexport interface BasicRelayInformation {\n // string identifying relay\n name: string\n description: string\n pubkey: string\n contact: string\n supported_nips: number[]\n software: string\n version: string\n // limitation?: Limitations\n}\n\n/**\n * * ## Extra Fields\n\n * * ### Server Limitations\n\n * These are limitations imposed by the relay on clients.\n * Your client should expect that requests which exceed\n * these practical_ limitations are rejected or fail immediately.\n * @param max_message_length this is the maximum number of\n * bytes for incoming JSON that the relay will attempt to\n * decode and act upon. When you send large subscriptions,\n * you will be limited by this value. It also effectively\n * limits the maximum size of any event. Value is calculated\n * from `[` to `]` and is after UTF-8 serialization (so some\n * unicode characters will cost 2-3 bytes). It is equal to\n * the maximum size of the WebSocket message frame.\n * @param max_subscriptions total number of subscriptions\n * that may be active on a single websocket connection to\n * this relay. It's possible that authenticated clients with\n * a (paid) relationship to the relay may have higher limits.\n * @param max_filters maximum number of filter values in\n * each subscription. Must be one or higher.\n * @param max_limit the relay server will clamp each\n * filter's `limit` value to this number.\n * This means the client won't be able to get more than this\n * number of events from a single subscription filter. This\n * clamping is typically done silently by the relay, but\n * with this number, you can know that there are additional\n * results if you narrowed your filter's time range or other\n * parameters.\n * @param max_subid_length maximum length of subscription id as a\n * string.\n * @param min_prefix for `authors` and `ids` filters which\n * are to match against a hex prefix, you must provide at\n * least this many hex digits in the prefix.\n * @param max_event_tags in any event, this is the maximum\n * number of elements in the `tags` list.\n * @param max_content_length maximum number of characters in\n * the `content` field of any event. This is a count of\n * unicode characters. After serializing into JSON it may be\n * larger (in bytes), and is still subject to the\n * max_message_length`, if defined.\n * @param min_pow_difficulty new events will require at\n * least this difficulty of PoW, based on [NIP-13](13.md),\n * or they will be rejected by this server.\n * @param auth_required this relay requires [NIP-42](42.md)\n * authentication to happen before a new connection may\n * perform any other action. Even if set to False,\n * authentication may be required for specific actions.\n * @param restricted_writes: this relay requires some kind\n * of condition to be fulfilled in order to accept events\n * (not necessarily, but including\n * @param payment_required this relay requires payment\n * before a new connection may perform any action.\n * @param created_at_lower_limit: 'created_at' lower limit\n * @param created_at_upper_limit: 'created_at' upper limit\n */\nexport interface Limitations {\n max_message_length: number\n max_subscriptions: number\n max_filters: number\n max_limit: number\n max_subid_length: number\n min_prefix: number\n max_event_tags: number\n max_content_length: number\n min_pow_difficulty: number\n auth_required: boolean\n payment_required: boolean\n created_at_lower_limit: number\n created_at_upper_limit: number\n restricted_writes: boolean\n}\n\nexport interface RetentionDetails {\n kinds: (number | number[])[]\n time?: number | null\n count?: number | null\n}\ntype AnyRetentionDetails = RetentionDetails\n/**\n * ### Event Retention\n\n * There may be a cost associated with storing data forever,\n * so relays may wish to state retention times. The values\n * stated here are defaults for unauthenticated users and\n * visitors. Paid users would likely have other policies.\n\n * Retention times are given in seconds, with `null`\n * indicating infinity. If zero is provided, this means the\n * event will not be stored at all, and preferably an error\n * will be provided when those are received.\n * ```json\n{\n...\n \"retention\": [\n { \"kinds\": [0, 1, [5, 7], [40, 49]], \"time\": 3600 },\n { \"kinds\": [[40000, 49999]], \"time\": 100 },\n { \"kinds\": [[30000, 39999]], \"count\": 1000 },\n { \"time\": 3600, \"count\": 10000 }\n ]\n...\n}\n```\n * @param retention is a list of specifications: each will\n * apply to either all kinds, or a subset of kinds. Ranges\n * may be specified for the kind field as a tuple of\n * inclusive start and end values. Events of indicated kind\n * (or all) are then limited to a `count` and/or time\n * period.\n\n * It is possible to effectively blacklist Nostr-based\n * protocols that rely on a specific `kind` number, by\n * giving a retention time of zero for those `kind` values.\n * While that is unfortunate, it does allow clients to\n * discover servers that will support their protocol quickly\n * via a single HTTP fetch.\n\n * There is no need to specify retention times for\n * _ephemeral events_ as defined in [NIP-16](16.md) since\n * they are not retained.\n */\nexport interface Retention {\n retention: AnyRetentionDetails[]\n}\n\n/**\n * Some relays may be governed by the arbitrary laws of a\n * nation state. This may limit what content can be stored\n * in cleartext on those relays. All clients are encouraged\n * to use encryption to work around this limitation.\n\n * It is not possible to describe the limitations of each\n * country's laws and policies which themselves are\n * typically vague and constantly shifting.\n\n * Therefore, this field allows the relay operator to\n * indicate which countries' laws might end up being\n * enforced on them, and then indirectly on their users'\n * content.\n\n * Users should be able to avoid relays in countries they\n * don't like, and/or select relays in more favourable\n * zones. Exposing this flexibility is up to the client\n * software.\n\n * @param relay_countries a list of two-level ISO country\n * codes (ISO 3166-1 alpha-2) whose laws and policies may\n * affect this relay. `EU` may be used for European Union\n * countries.\n\n * Remember that a relay may be hosted in a country which is\n * not the country of the legal entities who own the relay,\n * so it's very likely a number of countries are involved.\n */\nexport interface ContentLimitations {\n relay_countries: string[]\n}\n\n/**\n * ### Community Preferences\n\n * For public text notes at least, a relay may try to foster\n * a local community. This would encourage users to follow\n * the global feed on that relay, in addition to their usual\n * individual follows. To support this goal, relays MAY\n * specify some of the following values.\n\n * @param language_tags is an ordered list of [IETF\n * language\n * tags](https://en.wikipedia.org/wiki/IETF_language_tag\n * indicating the major languages spoken on the relay.\n * @param tags is a list of limitations on the topics to be\n * discussed. For example `sfw-only` indicates that only\n * \"Safe For Work\" content is encouraged on this relay. This\n * relies on assumptions of what the \"work\" \"community\"\n * feels \"safe\" talking about. In time, a common set of tags\n * may emerge that allow users to find relays that suit\n * their needs, and client software will be able to parse\n * these tags easily. The `bitcoin-only` tag indicates that\n * any _altcoin_, _\"crypto\"_ or _blockchain_ comments will\n * be ridiculed without mercy.\n * @param posting_policy is a link to a human-readable page\n * which specifies the community policies for the relay. In\n * cases where `sfw-only` is True, it's important to link to\n * a page which gets into the specifics of your posting\n * policy.\n\n * The `description` field should be used to describe your\n * community goals and values, in brief. The\n * `posting_policy` is for additional detail and legal\n * terms. Use the `tags` field to signify limitations on\n * content, or topics to be discussed, which could be\n * machine processed by appropriate client software.\n */\nexport interface CommunityPreferences {\n language_tags: string[]\n tags: string[]\n posting_policy: string\n}\n\nexport interface Amount {\n amount: number\n unit: 'msat'\n}\nexport interface PublicationAmount extends Amount {\n kinds: number[]\n}\nexport interface Subscription extends Amount {\n period: number\n}\nexport interface Fees {\n admission: Amount[]\n subscription: Subscription[]\n publication: PublicationAmount[]\n}\n/**\n * Relays that require payments may want to expose their fee\n * schedules.\n */\nexport interface PayToRelay {\n payments_url: string\n fees: Fees\n}\n\n/**\n * A URL pointing to an image to be used as an icon for the\n * relay. Recommended to be squared in shape.\n */\nexport interface Icon {\n icon: string\n}\n\nexport type RelayInformation = BasicRelayInformation &\n Partial & {\n limitation?: Partial\n } & Partial &\n Partial &\n Partial &\n Partial\n", "import { bytesToHex } from '@noble/hashes/utils'\nimport { type UnsignedEvent, type Event } from './pure.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\n/** Get POW difficulty from a Nostr hex ID. */\nexport function getPow(hex: string): number {\n let count = 0\n\n for (let i = 0; i < 64; i += 8) {\n const nibble = parseInt(hex.substring(i, i + 8), 16)\n if (nibble === 0) {\n count += 32\n } else {\n count += Math.clz32(nibble)\n break\n }\n }\n\n return count\n}\n\n/**\n * Mine an event with the desired POW. This function mutates the event.\n * Note that this operation is synchronous and should be run in a worker context to avoid blocking the main thread.\n */\nexport function minePow(unsigned: UnsignedEvent, difficulty: number): Omit {\n let count = 0\n\n const event = unsigned as Omit\n const tag = ['nonce', count.toString(), difficulty.toString()]\n\n event.tags.push(tag)\n\n while (true) {\n const now = Math.floor(new Date().getTime() / 1000)\n\n if (now !== event.created_at) {\n count = 0\n event.created_at = now\n }\n\n tag[1] = (++count).toString()\n\n event.id = fastEventHash(event)\n\n if (getPow(event.id) >= difficulty) {\n break\n }\n }\n\n return event\n}\n\nexport function fastEventHash(evt: UnsignedEvent): string {\n return bytesToHex(\n sha256(utf8Encoder.encode(JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]))),\n )\n}\n", "import { PrivateDirectMessage } from './kinds.ts'\nimport { EventTemplate, NostrEvent, getPublicKey } from './pure.ts'\nimport * as nip59 from './nip59.ts'\n\ntype Recipient = {\n publicKey: string\n relayUrl?: string\n}\n\ntype ReplyTo = {\n eventId: string\n relayUrl?: string\n}\n\nfunction createEvent(\n recipients: Recipient | Recipient[],\n message: string,\n conversationTitle?: string,\n replyTo?: ReplyTo,\n): EventTemplate {\n const baseEvent: EventTemplate = {\n created_at: Math.ceil(Date.now() / 1000),\n kind: PrivateDirectMessage,\n tags: [],\n content: message,\n }\n\n const recipientsArray = Array.isArray(recipients) ? recipients : [recipients]\n\n recipientsArray.forEach(({ publicKey, relayUrl }) => {\n baseEvent.tags.push(relayUrl ? ['p', publicKey, relayUrl] : ['p', publicKey])\n })\n\n if (replyTo) {\n baseEvent.tags.push(['e', replyTo.eventId, replyTo.relayUrl || '', 'reply'])\n }\n\n if (conversationTitle) {\n baseEvent.tags.push(['subject', conversationTitle])\n }\n\n return baseEvent\n}\n\nexport function wrapEvent(\n senderPrivateKey: Uint8Array,\n recipient: Recipient,\n message: string,\n conversationTitle?: string,\n replyTo?: ReplyTo,\n): NostrEvent {\n const event = createEvent(recipient, message, conversationTitle, replyTo)\n return nip59.wrapEvent(event, senderPrivateKey, recipient.publicKey)\n}\n\nexport function wrapManyEvents(\n senderPrivateKey: Uint8Array,\n recipients: Recipient[],\n message: string,\n conversationTitle?: string,\n replyTo?: ReplyTo,\n): NostrEvent[] {\n if (!recipients || recipients.length === 0) {\n throw new Error('At least one recipient is required.')\n }\n\n const senderPublicKey = getPublicKey(senderPrivateKey)\n\n // wrap the event for the sender and then for each recipient\n return [{ publicKey: senderPublicKey }, ...recipients].map(recipient =>\n wrapEvent(senderPrivateKey, recipient, message, conversationTitle, replyTo),\n )\n}\n\nexport const unwrapEvent = nip59.unwrapEvent\n\nexport const unwrapManyEvents = nip59.unwrapManyEvents\n", "import { EventTemplate, UnsignedEvent, NostrEvent } from './core.ts'\nimport { getConversationKey, decrypt, encrypt } from './nip44.ts'\nimport { getEventHash, generateSecretKey, finalizeEvent, getPublicKey } from './pure.ts'\nimport { Seal, GiftWrap } from './kinds.ts'\n\ntype Rumor = UnsignedEvent & { id: string }\n\nconst TWO_DAYS = 2 * 24 * 60 * 60\n\nconst now = () => Math.round(Date.now() / 1000)\nconst randomNow = () => Math.round(now() - Math.random() * TWO_DAYS)\n\nconst nip44ConversationKey = (privateKey: Uint8Array, publicKey: string) => getConversationKey(privateKey, publicKey)\n\nconst nip44Encrypt = (data: EventTemplate, privateKey: Uint8Array, publicKey: string) =>\n encrypt(JSON.stringify(data), nip44ConversationKey(privateKey, publicKey))\n\nconst nip44Decrypt = (data: NostrEvent, privateKey: Uint8Array) =>\n JSON.parse(decrypt(data.content, nip44ConversationKey(privateKey, data.pubkey)))\n\nexport function createRumor(event: Partial, privateKey: Uint8Array): Rumor {\n const rumor = {\n created_at: now(),\n content: '',\n tags: [],\n ...event,\n pubkey: getPublicKey(privateKey),\n } as any\n\n rumor.id = getEventHash(rumor)\n\n return rumor as Rumor\n}\n\nexport function createSeal(rumor: Rumor, privateKey: Uint8Array, recipientPublicKey: string): NostrEvent {\n return finalizeEvent(\n {\n kind: Seal,\n content: nip44Encrypt(rumor, privateKey, recipientPublicKey),\n created_at: randomNow(),\n tags: [],\n },\n privateKey,\n )\n}\n\nexport function createWrap(seal: NostrEvent, recipientPublicKey: string): NostrEvent {\n const randomKey = generateSecretKey()\n\n return finalizeEvent(\n {\n kind: GiftWrap,\n content: nip44Encrypt(seal, randomKey, recipientPublicKey),\n created_at: randomNow(),\n tags: [['p', recipientPublicKey]],\n },\n randomKey,\n ) as NostrEvent\n}\n\nexport function wrapEvent(\n event: Partial,\n senderPrivateKey: Uint8Array,\n recipientPublicKey: string,\n): NostrEvent {\n const rumor = createRumor(event, senderPrivateKey)\n\n const seal = createSeal(rumor, senderPrivateKey, recipientPublicKey)\n return createWrap(seal, recipientPublicKey)\n}\n\nexport function wrapManyEvents(\n event: Partial,\n senderPrivateKey: Uint8Array,\n recipientsPublicKeys: string[],\n): NostrEvent[] {\n if (!recipientsPublicKeys || recipientsPublicKeys.length === 0) {\n throw new Error('At least one recipient is required.')\n }\n\n const senderPublicKey = getPublicKey(senderPrivateKey)\n\n const wrappeds = [wrapEvent(event, senderPrivateKey, senderPublicKey)]\n\n recipientsPublicKeys.forEach(recipientPublicKey => {\n wrappeds.push(wrapEvent(event, senderPrivateKey, recipientPublicKey))\n })\n\n return wrappeds\n}\n\nexport function unwrapEvent(wrap: NostrEvent, recipientPrivateKey: Uint8Array): Rumor {\n const unwrappedSeal = nip44Decrypt(wrap, recipientPrivateKey)\n return nip44Decrypt(unwrappedSeal, recipientPrivateKey)\n}\n\nexport function unwrapManyEvents(wrappedEvents: NostrEvent[], recipientPrivateKey: Uint8Array): Rumor[] {\n let unwrappedEvents: Rumor[] = []\n\n wrappedEvents.forEach(e => {\n unwrappedEvents.push(unwrapEvent(e, recipientPrivateKey))\n })\n\n unwrappedEvents.sort((a, b) => a.created_at - b.created_at)\n\n return unwrappedEvents\n}\n", "import { chacha20 } from '@noble/ciphers/chacha'\nimport { equalBytes } from '@noble/ciphers/utils'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { extract as hkdf_extract, expand as hkdf_expand } from '@noble/hashes/hkdf'\nimport { hmac } from '@noble/hashes/hmac'\nimport { sha256 } from '@noble/hashes/sha256'\nimport { concatBytes, randomBytes } from '@noble/hashes/utils'\nimport { base64 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nconst minPlaintextSize = 0x0001 // 1b msg => padded to 32b\nconst maxPlaintextSize = 0xffff // 65535 (64kb-1) => padded to 64kb\n\nexport function getConversationKey(privkeyA: Uint8Array, pubkeyB: string): Uint8Array {\n const sharedX = secp256k1.getSharedSecret(privkeyA, '02' + pubkeyB).subarray(1, 33)\n return hkdf_extract(sha256, sharedX, 'nip44-v2')\n}\n\nfunction getMessageKeys(\n conversationKey: Uint8Array,\n nonce: Uint8Array,\n): { chacha_key: Uint8Array; chacha_nonce: Uint8Array; hmac_key: Uint8Array } {\n const keys = hkdf_expand(sha256, conversationKey, nonce, 76)\n return {\n chacha_key: keys.subarray(0, 32),\n chacha_nonce: keys.subarray(32, 44),\n hmac_key: keys.subarray(44, 76),\n }\n}\n\nfunction calcPaddedLen(len: number): number {\n if (!Number.isSafeInteger(len) || len < 1) throw new Error('expected positive integer')\n if (len <= 32) return 32\n const nextPower = 1 << (Math.floor(Math.log2(len - 1)) + 1)\n const chunk = nextPower <= 256 ? 32 : nextPower / 8\n return chunk * (Math.floor((len - 1) / chunk) + 1)\n}\n\nfunction writeU16BE(num: number): Uint8Array {\n if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize)\n throw new Error('invalid plaintext size: must be between 1 and 65535 bytes')\n const arr = new Uint8Array(2)\n new DataView(arr.buffer).setUint16(0, num, false)\n return arr\n}\n\nfunction pad(plaintext: string): Uint8Array {\n const unpadded = utf8Encoder.encode(plaintext)\n const unpaddedLen = unpadded.length\n const prefix = writeU16BE(unpaddedLen)\n const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen)\n return concatBytes(prefix, unpadded, suffix)\n}\n\nfunction unpad(padded: Uint8Array): string {\n const unpaddedLen = new DataView(padded.buffer).getUint16(0)\n const unpadded = padded.subarray(2, 2 + unpaddedLen)\n if (\n unpaddedLen < minPlaintextSize ||\n unpaddedLen > maxPlaintextSize ||\n unpadded.length !== unpaddedLen ||\n padded.length !== 2 + calcPaddedLen(unpaddedLen)\n )\n throw new Error('invalid padding')\n return utf8Decoder.decode(unpadded)\n}\n\nfunction hmacAad(key: Uint8Array, message: Uint8Array, aad: Uint8Array): Uint8Array {\n if (aad.length !== 32) throw new Error('AAD associated data must be 32 bytes')\n const combined = concatBytes(aad, message)\n return hmac(sha256, key, combined)\n}\n\n// metadata: always 65b (version: 1b, nonce: 32b, max: 32b)\n// plaintext: 1b to 0xffff\n// padded plaintext: 32b to 0xffff\n// ciphertext: 32b+2 to 0xffff+2\n// raw payload: 99 (65+32+2) to 65603 (65+0xffff+2)\n// compressed payload (base64): 132b to 87472b\nfunction decodePayload(payload: string): { nonce: Uint8Array; ciphertext: Uint8Array; mac: Uint8Array } {\n if (typeof payload !== 'string') throw new Error('payload must be a valid string')\n const plen = payload.length\n if (plen < 132 || plen > 87472) throw new Error('invalid payload length: ' + plen)\n if (payload[0] === '#') throw new Error('unknown encryption version')\n let data: Uint8Array\n try {\n data = base64.decode(payload)\n } catch (error) {\n throw new Error('invalid base64: ' + (error as any).message)\n }\n const dlen = data.length\n if (dlen < 99 || dlen > 65603) throw new Error('invalid data length: ' + dlen)\n const vers = data[0]\n if (vers !== 2) throw new Error('unknown encryption version ' + vers)\n return {\n nonce: data.subarray(1, 33),\n ciphertext: data.subarray(33, -32),\n mac: data.subarray(-32),\n }\n}\n\nexport function encrypt(plaintext: string, conversationKey: Uint8Array, nonce: Uint8Array = randomBytes(32)): string {\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n const padded = pad(plaintext)\n const ciphertext = chacha20(chacha_key, chacha_nonce, padded)\n const mac = hmacAad(hmac_key, ciphertext, nonce)\n return base64.encode(concatBytes(new Uint8Array([2]), nonce, ciphertext, mac))\n}\n\nexport function decrypt(payload: string, conversationKey: Uint8Array): string {\n const { nonce, ciphertext, mac } = decodePayload(payload)\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n const calculatedMac = hmacAad(hmac_key, ciphertext, nonce)\n if (!equalBytes(calculatedMac, mac)) throw new Error('invalid MAC')\n const padded = chacha20(chacha_key, chacha_nonce, ciphertext)\n return unpad(padded)\n}\n\nexport const v2 = {\n utils: {\n getConversationKey,\n calcPaddedLen,\n },\n encrypt,\n decrypt,\n}\n", "import { GenericRepost, Repost, ShortTextNote } from './kinds.ts'\nimport { EventPointer } from './nip19.ts'\nimport { Event, finalizeEvent, verifyEvent } from './pure.ts'\n\nexport type RepostEventTemplate = {\n /**\n * Pass only non-nip18 tags if you have to.\n * Nip18 tags ('e' and 'p' tags pointing to the reposted event) will be added automatically.\n */\n tags?: string[][]\n\n /**\n * Pass an empty string to NOT include the stringified JSON of the reposted event.\n * Any other content will be ignored and replaced with the stringified JSON of the reposted event.\n * @default Stringified JSON of the reposted event\n */\n content?: ''\n\n created_at: number\n}\n\nexport function finishRepostEvent(\n t: RepostEventTemplate,\n reposted: Event,\n relayUrl: string,\n privateKey: Uint8Array,\n): Event {\n let kind: Repost | GenericRepost\n const tags = [...(t.tags ?? []), ['e', reposted.id, relayUrl], ['p', reposted.pubkey]]\n if (reposted.kind === ShortTextNote) {\n kind = Repost\n } else {\n kind = GenericRepost\n tags.push(['k', String(reposted.kind)])\n }\n\n return finalizeEvent(\n {\n kind,\n tags,\n content: t.content === '' || reposted.tags?.find(tag => tag[0] === '-') ? '' : JSON.stringify(reposted),\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\nexport function getRepostedEventPointer(event: Event): undefined | EventPointer {\n if (![Repost, GenericRepost].includes(event.kind)) {\n return undefined\n }\n\n let lastETag: undefined | string[]\n let lastPTag: undefined | string[]\n\n for (let i = event.tags.length - 1; i >= 0 && (lastETag === undefined || lastPTag === undefined); i--) {\n const tag = event.tags[i]\n if (tag.length >= 2) {\n if (tag[0] === 'e' && lastETag === undefined) {\n lastETag = tag\n } else if (tag[0] === 'p' && lastPTag === undefined) {\n lastPTag = tag\n }\n }\n }\n\n if (lastETag === undefined) {\n return undefined\n }\n\n return {\n id: lastETag[1],\n relays: [lastETag[2], lastPTag?.[2]].filter((x): x is string => typeof x === 'string'),\n author: lastPTag?.[1],\n }\n}\n\nexport type GetRepostedEventOptions = {\n skipVerification?: boolean\n}\n\nexport function getRepostedEvent(event: Event, { skipVerification }: GetRepostedEventOptions = {}): undefined | Event {\n const pointer = getRepostedEventPointer(event)\n\n if (pointer === undefined || event.content === '') {\n return undefined\n }\n\n let repostedEvent: undefined | Event\n\n try {\n repostedEvent = JSON.parse(event.content) as Event\n } catch (error) {\n return undefined\n }\n\n if (repostedEvent.id !== pointer.id) {\n return undefined\n }\n\n if (!skipVerification && !verifyEvent(repostedEvent)) {\n return undefined\n }\n\n return repostedEvent\n}\n", "import { AddressPointer, BECH32_REGEX, decode, EventPointer, ProfilePointer } from './nip19.ts'\n\n/** Nostr URI regex, eg `nostr:npub1...` */\nexport const NOSTR_URI_REGEX: RegExp = new RegExp(`nostr:(${BECH32_REGEX.source})`)\n\n/** Test whether the value is a Nostr URI. */\nexport function test(value: unknown): value is `nostr:${string}` {\n return typeof value === 'string' && new RegExp(`^${NOSTR_URI_REGEX.source}$`).test(value)\n}\n\n/** Parsed Nostr URI data. */\nexport interface NostrURI {\n /** Full URI including the `nostr:` protocol. */\n uri: `nostr:${string}`\n /** The bech32-encoded data (eg `npub1...`). */\n value: string\n /** Decoded bech32 string, according to NIP-19. */\n decoded:\n | {\n type: 'nevent'\n data: EventPointer\n }\n | {\n type: 'nprofile'\n data: ProfilePointer\n }\n | {\n type: 'naddr'\n data: AddressPointer\n }\n | {\n type: 'npub'\n data: string\n }\n | {\n type: 'nsec'\n data: Uint8Array\n }\n | {\n type: 'note'\n data: string\n }\n}\n\n/** Parse and decode a Nostr URI. */\nexport function parse(uri: string): NostrURI {\n const match = uri.match(new RegExp(`^${NOSTR_URI_REGEX.source}$`))\n if (!match) throw new Error(`Invalid Nostr URI: ${uri}`)\n return {\n uri: match[0] as `nostr:${string}`,\n value: match[1],\n decoded: decode(match[1]),\n }\n}\n", "import { Event, finalizeEvent } from './pure.ts'\nimport { Reaction } from './kinds.ts'\n\nimport type { EventPointer } from './nip19.ts'\n\nexport type ReactionEventTemplate = {\n /**\n * Pass only non-nip25 tags if you have to. Nip25 tags ('e' and 'p' tags from reacted event) will be added automatically.\n */\n tags?: string[][]\n\n /**\n * @default '+'\n */\n content?: string\n\n created_at: number\n}\n\nexport function finishReactionEvent(t: ReactionEventTemplate, reacted: Event, privateKey: Uint8Array): Event {\n const inheritedTags = reacted.tags.filter(tag => tag.length >= 2 && (tag[0] === 'e' || tag[0] === 'p'))\n\n return finalizeEvent(\n {\n ...t,\n kind: Reaction,\n tags: [...(t.tags ?? []), ...inheritedTags, ['e', reacted.id], ['p', reacted.pubkey]],\n content: t.content ?? '+',\n },\n privateKey,\n )\n}\n\nexport function getReactedEventPointer(event: Event): undefined | EventPointer {\n if (event.kind !== Reaction) {\n return undefined\n }\n\n let lastETag: undefined | string[]\n let lastPTag: undefined | string[]\n\n for (let i = event.tags.length - 1; i >= 0 && (lastETag === undefined || lastPTag === undefined); i--) {\n const tag = event.tags[i]\n if (tag.length >= 2) {\n if (tag[0] === 'e' && lastETag === undefined) {\n lastETag = tag\n } else if (tag[0] === 'p' && lastPTag === undefined) {\n lastPTag = tag\n }\n }\n }\n\n if (lastETag === undefined || lastPTag === undefined) {\n return undefined\n }\n\n return {\n id: lastETag[1],\n relays: [lastETag[2], lastPTag[2]].filter(x => x !== undefined),\n author: lastPTag[1],\n }\n}\n", "import { AddressPointer, EventPointer, ProfilePointer, decode } from './nip19.ts'\n\nexport type Block =\n | {\n type: 'text'\n text: string\n }\n | {\n type: 'reference'\n pointer: ProfilePointer | AddressPointer | EventPointer\n }\n | {\n type: 'url'\n url: string\n }\n | {\n type: 'relay'\n url: string\n }\n | {\n type: 'image'\n url: string\n }\n | {\n type: 'video'\n url: string\n }\n | {\n type: 'audio'\n url: string\n }\n\nconst noCharacter = /\\W/m\nconst noURLCharacter = /\\W |\\W$|$|,| /m\n\nexport function* parse(content: string): Iterable {\n const max = content.length\n let prevIndex = 0\n let index = 0\n while (index < max) {\n let u = content.indexOf(':', index)\n if (u === -1) {\n // reached end\n break\n }\n\n if (content.substring(u - 5, u) === 'nostr') {\n const m = content.substring(u + 60).match(noCharacter)\n const end = m ? u + 60 + m.index! : max\n try {\n let pointer: ProfilePointer | AddressPointer | EventPointer\n let { data, type } = decode(content.substring(u + 1, end))\n\n switch (type) {\n case 'npub':\n pointer = { pubkey: data } as ProfilePointer\n break\n case 'nsec':\n case 'note':\n // ignore this, treat it as not a valid uri\n index = end + 1\n continue\n default:\n pointer = data as any\n }\n\n if (prevIndex !== u - 5) {\n yield { type: 'text', text: content.substring(prevIndex, u - 5) }\n }\n yield { type: 'reference', pointer }\n index = end\n prevIndex = index\n continue\n } catch (_err) {\n // ignore this, not a valid nostr uri\n index = u + 1\n continue\n }\n } else if (content.substring(u - 5, u) === 'https' || content.substring(u - 4, u) === 'http') {\n const m = content.substring(u + 4).match(noURLCharacter)\n const end = m ? u + 4 + m.index! : max\n const prefixLen = content[u - 1] === 's' ? 5 : 4\n try {\n let url = new URL(content.substring(u - prefixLen, end))\n if (url.hostname.indexOf('.') === -1) {\n throw new Error('invalid url')\n }\n\n if (prevIndex !== u - prefixLen) {\n yield { type: 'text', text: content.substring(prevIndex, u - prefixLen) }\n }\n\n if (\n url.pathname.endsWith('.png') ||\n url.pathname.endsWith('.jpg') ||\n url.pathname.endsWith('.jpeg') ||\n url.pathname.endsWith('.gif') ||\n url.pathname.endsWith('.webp')\n ) {\n yield { type: 'image', url: url.toString() }\n index = end\n prevIndex = index\n continue\n }\n if (\n url.pathname.endsWith('.mp4') ||\n url.pathname.endsWith('.avi') ||\n url.pathname.endsWith('.webm') ||\n url.pathname.endsWith('.mkv')\n ) {\n yield { type: 'video', url: url.toString() }\n index = end\n prevIndex = index\n continue\n }\n if (\n url.pathname.endsWith('.mp3') ||\n url.pathname.endsWith('.aac') ||\n url.pathname.endsWith('.ogg') ||\n url.pathname.endsWith('.opus')\n ) {\n yield { type: 'audio', url: url.toString() }\n index = end\n prevIndex = index\n continue\n }\n\n yield { type: 'url', url: url.toString() }\n index = end\n prevIndex = index\n continue\n } catch (_err) {\n // ignore this, not a valid url\n index = end + 1\n continue\n }\n } else if (content.substring(u - 3, u) === 'wss' || content.substring(u - 2, u) === 'ws') {\n const m = content.substring(u + 4).match(noURLCharacter)\n const end = m ? u + 4 + m.index! : max\n const prefixLen = content[u - 1] === 's' ? 3 : 2\n try {\n let url = new URL(content.substring(u - prefixLen, end))\n if (url.hostname.indexOf('.') === -1) {\n throw new Error('invalid ws url')\n }\n\n if (prevIndex !== u - prefixLen) {\n yield { type: 'text', text: content.substring(prevIndex, u - prefixLen) }\n }\n yield { type: 'relay', url: url.toString() }\n index = end\n prevIndex = index\n continue\n } catch (_err) {\n // ignore this, not a valid url\n index = end + 1\n continue\n }\n } else {\n // ignore this, it is nothing\n index = u + 1\n continue\n }\n }\n\n if (prevIndex !== max) {\n yield { type: 'text', text: content.substring(prevIndex) }\n }\n}\n", "import { Event, finalizeEvent } from './pure.ts'\nimport {\n ChannelCreation,\n ChannelHideMessage,\n ChannelMessage,\n ChannelMetadata as KindChannelMetadata,\n ChannelMuteUser,\n} from './kinds.ts'\n\nexport interface ChannelMetadata {\n name: string\n about: string\n picture: string\n}\n\nexport interface ChannelCreateEventTemplate {\n /* JSON string containing ChannelMetadata as defined for Kind 40 and 41 in nip-28. */\n content: string | ChannelMetadata\n created_at: number\n tags?: string[][]\n}\n\nexport interface ChannelMetadataEventTemplate {\n channel_create_event_id: string\n /* JSON string containing ChannelMetadata as defined for Kind 40 and 41 in nip-28. */\n content: string | ChannelMetadata\n created_at: number\n tags?: string[][]\n}\n\nexport interface ChannelMessageEventTemplate {\n channel_create_event_id: string\n reply_to_channel_message_event_id?: string\n relay_url: string\n content: string\n created_at: number\n tags?: string[][]\n}\n\nexport interface ChannelHideMessageEventTemplate {\n channel_message_event_id: string\n content: string | { reason: string }\n created_at: number\n tags?: string[][]\n}\n\nexport interface ChannelMuteUserEventTemplate {\n content: string | { reason: string }\n created_at: number\n pubkey_to_mute: string\n tags?: string[][]\n}\n\nexport const channelCreateEvent = (t: ChannelCreateEventTemplate, privateKey: Uint8Array): Event | undefined => {\n let content: string\n if (typeof t.content === 'object') {\n content = JSON.stringify(t.content)\n } else if (typeof t.content === 'string') {\n content = t.content\n } else {\n return undefined\n }\n\n return finalizeEvent(\n {\n kind: ChannelCreation,\n tags: [...(t.tags ?? [])],\n content: content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\nexport const channelMetadataEvent = (t: ChannelMetadataEventTemplate, privateKey: Uint8Array): Event | undefined => {\n let content: string\n if (typeof t.content === 'object') {\n content = JSON.stringify(t.content)\n } else if (typeof t.content === 'string') {\n content = t.content\n } else {\n return undefined\n }\n\n return finalizeEvent(\n {\n kind: KindChannelMetadata,\n tags: [['e', t.channel_create_event_id], ...(t.tags ?? [])],\n content: content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\nexport const channelMessageEvent = (t: ChannelMessageEventTemplate, privateKey: Uint8Array): Event => {\n const tags = [['e', t.channel_create_event_id, t.relay_url, 'root']]\n\n if (t.reply_to_channel_message_event_id) {\n tags.push(['e', t.reply_to_channel_message_event_id, t.relay_url, 'reply'])\n }\n\n return finalizeEvent(\n {\n kind: ChannelMessage,\n tags: [...tags, ...(t.tags ?? [])],\n content: t.content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\n/* \"e\" tag should be the kind 42 event to hide */\nexport const channelHideMessageEvent = (\n t: ChannelHideMessageEventTemplate,\n privateKey: Uint8Array,\n): Event | undefined => {\n let content: string\n if (typeof t.content === 'object') {\n content = JSON.stringify(t.content)\n } else if (typeof t.content === 'string') {\n content = t.content\n } else {\n return undefined\n }\n\n return finalizeEvent(\n {\n kind: ChannelHideMessage,\n tags: [['e', t.channel_message_event_id], ...(t.tags ?? [])],\n content: content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\nexport const channelMuteUserEvent = (t: ChannelMuteUserEventTemplate, privateKey: Uint8Array): Event | undefined => {\n let content: string\n if (typeof t.content === 'object') {\n content = JSON.stringify(t.content)\n } else if (typeof t.content === 'string') {\n content = t.content\n } else {\n return undefined\n }\n\n return finalizeEvent(\n {\n kind: ChannelMuteUser,\n tags: [['p', t.pubkey_to_mute], ...(t.tags ?? [])],\n content: content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n", "/** Regex for a single emoji shortcode. */\nexport const EMOJI_SHORTCODE_REGEX = /:(\\w+):/\n\n/** Regex to find emoji shortcodes in content. */\nexport const regex = (): RegExp => new RegExp(`\\\\B${EMOJI_SHORTCODE_REGEX.source}\\\\B`, 'g')\n\n/** Represents a Nostr custom emoji. */\nexport interface CustomEmoji {\n /** The matched emoji name with colons. */\n shortcode: `:${string}:`\n /** The matched emoji name without colons. */\n name: string\n}\n\n/** Match result for a custom emoji in text content. */\nexport interface CustomEmojiMatch extends CustomEmoji {\n /** Index where the emoji begins in the text content. */\n start: number\n /** Index where the emoji ends in the text content. */\n end: number\n}\n\n/** Find all custom emoji shortcodes. */\nexport function* matchAll(content: string): Iterable {\n const matches = content.matchAll(regex())\n\n for (const match of matches) {\n try {\n const [shortcode, name] = match\n\n yield {\n shortcode: shortcode as `:${string}:`,\n name,\n start: match.index!,\n end: match.index! + shortcode.length,\n }\n } catch (_e) {\n // do nothing\n }\n }\n}\n\n/** Replace all emoji shortcodes in the content. */\nexport function replaceAll(content: string, replacer: (match: CustomEmoji) => string): string {\n return content.replaceAll(regex(), (shortcode, name) => {\n return replacer({\n shortcode: shortcode as `:${string}:`,\n name,\n })\n })\n}\n", "var _fetch: any\n\ntry {\n _fetch = fetch\n} catch {}\n\nexport function useFetchImplementation(fetchImplementation: any) {\n _fetch = fetchImplementation\n}\n\nexport async function validateGithub(pubkey: string, username: string, proof: string): Promise {\n try {\n let res = await (await _fetch(`https://gist.github.com/${username}/${proof}/raw`)).text()\n return res === `Verifying that I control the following Nostr public key: ${pubkey}`\n } catch (_) {\n return false\n }\n}\n", "import { type VerifiedEvent, finalizeEvent } from './pure.ts'\nimport { NWCWalletRequest } from './kinds.ts'\nimport { encrypt } from './nip04.ts'\n\ninterface NWCConnection {\n pubkey: string\n relay: string\n secret: string\n}\n\nexport function parseConnectionString(connectionString: string): NWCConnection {\n const { host, pathname, searchParams } = new URL(connectionString)\n const pubkey = pathname || host\n const relay = searchParams.get('relay')\n const secret = searchParams.get('secret')\n\n if (!pubkey || !relay || !secret) {\n throw new Error('invalid connection string')\n }\n\n return { pubkey, relay, secret }\n}\n\nexport async function makeNwcRequestEvent(\n pubkey: string,\n secretKey: Uint8Array,\n invoice: string,\n): Promise {\n const content = {\n method: 'pay_invoice',\n params: {\n invoice,\n },\n }\n const encryptedContent = encrypt(secretKey, pubkey, JSON.stringify(content))\n const eventTemplate = {\n kind: NWCWalletRequest,\n created_at: Math.round(Date.now() / 1000),\n content: encryptedContent,\n tags: [['p', pubkey]],\n }\n\n return finalizeEvent(eventTemplate, secretKey)\n}\n", "export function normalizeIdentifier(name: string): string {\n // Trim and lowercase\n name = name.trim().toLowerCase()\n\n // Normalize Unicode to NFKC form\n name = name.normalize('NFKC')\n\n // Convert to array of characters and map each one\n return Array.from(name)\n .map(char => {\n // Check if character is letter or number using Unicode ranges\n if (/\\p{Letter}/u.test(char) || /\\p{Number}/u.test(char)) {\n return char\n }\n\n return '-'\n })\n .join('')\n}\n", "import { bech32 } from '@scure/base'\n\nimport { NostrEvent, validateEvent, verifyEvent, type Event, type EventTemplate } from './pure.ts'\nimport { utf8Decoder } from './utils.ts'\nimport { isReplaceableKind, isAddressableKind } from './kinds.ts'\n\nvar _fetch: any\n\ntry {\n _fetch = fetch\n} catch {}\n\nexport function useFetchImplementation(fetchImplementation: any) {\n _fetch = fetchImplementation\n}\n\nexport async function getZapEndpoint(metadata: Event): Promise {\n try {\n let lnurl: string = ''\n let { lud06, lud16 } = JSON.parse(metadata.content)\n if (lud06) {\n let { words } = bech32.decode(lud06, 1000)\n let data = bech32.fromWords(words)\n lnurl = utf8Decoder.decode(data)\n } else if (lud16) {\n let [name, domain] = lud16.split('@')\n lnurl = new URL(`/.well-known/lnurlp/${name}`, `https://${domain}`).toString()\n } else {\n return null\n }\n\n let res = await _fetch(lnurl)\n let body = await res.json()\n\n if (body.allowsNostr && body.nostrPubkey) {\n return body.callback\n }\n } catch (err) {\n /*-*/\n }\n\n return null\n}\n\ntype ProfileZap = {\n pubkey: string\n amount: number\n comment?: string\n relays: string[]\n}\n\ntype EventZap = {\n event: NostrEvent\n amount: number\n comment?: string\n relays: string[]\n}\n\nexport function makeZapRequest(params: ProfileZap | EventZap): EventTemplate {\n let zr: EventTemplate = {\n kind: 9734,\n created_at: Math.round(Date.now() / 1000),\n content: params.comment || '',\n tags: [\n ['p', 'pubkey' in params ? params.pubkey : params.event.pubkey],\n ['amount', params.amount.toString()],\n ['relays', ...params.relays],\n ],\n }\n\n if ('event' in params) {\n zr.tags.push(['e', params.event.id])\n if (isReplaceableKind(params.event.kind)) {\n const a = ['a', `${params.event.kind}:${params.event.pubkey}:`]\n zr.tags.push(a)\n } else if (isAddressableKind(params.event.kind)) {\n let d = params.event.tags.find(([t, v]) => t === 'd' && v)\n if (!d) throw new Error('d tag not found or is empty')\n const a = ['a', `${params.event.kind}:${params.event.pubkey}:${d[1]}`]\n zr.tags.push(a)\n }\n zr.tags.push(['k', params.event.kind.toString()])\n }\n\n return zr\n}\n\nexport function validateZapRequest(zapRequestString: string): string | null {\n let zapRequest: Event\n\n try {\n zapRequest = JSON.parse(zapRequestString)\n } catch (err) {\n return 'Invalid zap request JSON.'\n }\n\n if (!validateEvent(zapRequest)) return 'Zap request is not a valid Nostr event.'\n\n if (!verifyEvent(zapRequest)) return 'Invalid signature on zap request.'\n\n let p = zapRequest.tags.find(([t, v]) => t === 'p' && v)\n if (!p) return \"Zap request doesn't have a 'p' tag.\"\n if (!p[1].match(/^[a-f0-9]{64}$/)) return \"Zap request 'p' tag is not valid hex.\"\n\n let e = zapRequest.tags.find(([t, v]) => t === 'e' && v)\n if (e && !e[1].match(/^[a-f0-9]{64}$/)) return \"Zap request 'e' tag is not valid hex.\"\n\n let relays = zapRequest.tags.find(([t, v]) => t === 'relays' && v)\n if (!relays) return \"Zap request doesn't have a 'relays' tag.\"\n\n return null\n}\n\nexport function makeZapReceipt({\n zapRequest,\n preimage,\n bolt11,\n paidAt,\n}: {\n zapRequest: string\n preimage?: string\n bolt11: string\n paidAt: Date\n}): EventTemplate {\n let zr: Event = JSON.parse(zapRequest)\n let tagsFromZapRequest = zr.tags.filter(([t]) => t === 'e' || t === 'p' || t === 'a')\n\n let zap: EventTemplate = {\n kind: 9735,\n created_at: Math.round(paidAt.getTime() / 1000),\n content: '',\n tags: [...tagsFromZapRequest, ['P', zr.pubkey], ['bolt11', bolt11], ['description', zapRequest]],\n }\n\n if (preimage) {\n zap.tags.push(['preimage', preimage])\n }\n\n return zap\n}\n\nexport function getSatoshisAmountFromBolt11(bolt11: string): number {\n if (bolt11.length < 50) {\n return 0\n }\n bolt11 = bolt11.substring(0, 50)\n const idx = bolt11.lastIndexOf('1')\n if (idx === -1) {\n return 0\n }\n const hrp = bolt11.substring(0, idx)\n if (!hrp.startsWith('lnbc')) {\n return 0\n }\n const amount = hrp.substring(4) // equivalent to strings.CutPrefix\n\n if (amount.length < 1) {\n return 0\n }\n\n // if last character is a digit, then the amount can just be interpreted as BTC\n const char = amount[amount.length - 1]\n const digit = char.charCodeAt(0) - '0'.charCodeAt(0)\n const isDigit = digit >= 0 && digit <= 9\n\n let cutPoint = amount.length - 1\n if (isDigit) {\n cutPoint++\n }\n\n if (cutPoint < 1) {\n return 0\n }\n\n const num = parseInt(amount.substring(0, cutPoint))\n\n switch (char) {\n case 'm':\n return num * 100000\n case 'u':\n return num * 100\n case 'n':\n return num / 10\n case 'p':\n return num / 10000\n default:\n return num * 100000000\n }\n}\n", "import { sha256 } from '@noble/hashes/sha256'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { base64 } from '@scure/base'\n\nimport { HTTPAuth } from './kinds.ts'\nimport { Event, EventTemplate, verifyEvent } from './pure.ts'\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nconst _authorizationScheme = 'Nostr '\n\n/**\n * Generate token for NIP-98 flow.\n *\n * @example\n * const sign = window.nostr.signEvent\n * await nip98.getToken('https://example.com/login', 'post', (e) => sign(e), true)\n */\nexport async function getToken(\n loginUrl: string,\n httpMethod: string,\n sign: (e: EventTemplate) => Promise | Event,\n includeAuthorizationScheme: boolean = false,\n payload?: Record,\n): Promise {\n const event: EventTemplate = {\n kind: HTTPAuth,\n tags: [\n ['u', loginUrl],\n ['method', httpMethod],\n ],\n created_at: Math.round(new Date().getTime() / 1000),\n content: '',\n }\n\n if (payload) {\n event.tags.push(['payload', hashPayload(payload)])\n }\n\n const signedEvent = await sign(event)\n const authorizationScheme = includeAuthorizationScheme ? _authorizationScheme : ''\n\n return authorizationScheme + base64.encode(utf8Encoder.encode(JSON.stringify(signedEvent)))\n}\n\n/**\n * Validate token for NIP-98 flow.\n *\n * @example\n * await nip98.validateToken('Nostr base64token', 'https://example.com/login', 'post')\n */\nexport async function validateToken(token: string, url: string, method: string): Promise {\n const event = await unpackEventFromToken(token).catch(error => {\n throw error\n })\n\n const valid = await validateEvent(event, url, method).catch(error => {\n throw error\n })\n\n return valid\n}\n\n/**\n * Unpacks an event from a token.\n *\n * @param token - The token to unpack.\n * @returns A promise that resolves to the unpacked event.\n * @throws {Error} If the token is missing, invalid, or cannot be parsed.\n */\nexport async function unpackEventFromToken(token: string): Promise {\n if (!token) {\n throw new Error('Missing token')\n }\n\n token = token.replace(_authorizationScheme, '')\n\n const eventB64 = utf8Decoder.decode(base64.decode(token))\n if (!eventB64 || eventB64.length === 0 || !eventB64.startsWith('{')) {\n throw new Error('Invalid token')\n }\n\n const event = JSON.parse(eventB64) as Event\n\n return event\n}\n\n/**\n * Validates the timestamp of an event.\n * @param event - The event object to validate.\n * @returns A boolean indicating whether the event timestamp is within the last 60 seconds.\n */\nexport function validateEventTimestamp(event: Event): boolean {\n if (!event.created_at) {\n return false\n }\n\n return Math.round(new Date().getTime() / 1000) - event.created_at < 60\n}\n\n/**\n * Validates the kind of an event.\n * @param event The event to validate.\n * @returns A boolean indicating whether the event kind is valid.\n */\nexport function validateEventKind(event: Event): boolean {\n return event.kind === HTTPAuth\n}\n\n/**\n * Validates if the given URL matches the URL tag of the event.\n * @param event - The event object.\n * @param url - The URL to validate.\n * @returns A boolean indicating whether the URL is valid or not.\n */\nexport function validateEventUrlTag(event: Event, url: string): boolean {\n const urlTag = event.tags.find(t => t[0] === 'u')\n\n if (!urlTag) {\n return false\n }\n\n return urlTag.length > 0 && urlTag[1] === url\n}\n\n/**\n * Validates if the given event has a method tag that matches the specified method.\n * @param event - The event to validate.\n * @param method - The method to match against the method tag.\n * @returns A boolean indicating whether the event has a matching method tag.\n */\nexport function validateEventMethodTag(event: Event, method: string): boolean {\n const methodTag = event.tags.find(t => t[0] === 'method')\n\n if (!methodTag) {\n return false\n }\n\n return methodTag.length > 0 && methodTag[1].toLowerCase() === method.toLowerCase()\n}\n\n/**\n * Calculates the hash of a payload.\n * @param payload - The payload to be hashed.\n * @returns The hash value as a string.\n */\nexport function hashPayload(payload: any): string {\n const hash = sha256(utf8Encoder.encode(JSON.stringify(payload)))\n return bytesToHex(hash)\n}\n\n/**\n * Validates the event payload tag against the provided payload.\n * @param event The event object.\n * @param payload The payload to validate.\n * @returns A boolean indicating whether the payload tag is valid.\n */\nexport function validateEventPayloadTag(event: Event, payload: any): boolean {\n const payloadTag = event.tags.find(t => t[0] === 'payload')\n\n if (!payloadTag) {\n return false\n }\n\n const payloadHash = hashPayload(payload)\n return payloadTag.length > 0 && payloadTag[1] === payloadHash\n}\n\n/**\n * Validates a Nostr event for the NIP-98 flow.\n *\n * @param event - The Nostr event to validate.\n * @param url - The URL associated with the event.\n * @param method - The HTTP method associated with the event.\n * @param body - The request body associated with the event (optional).\n * @returns A promise that resolves to a boolean indicating whether the event is valid.\n * @throws An error if the event is invalid.\n */\nexport async function validateEvent(event: Event, url: string, method: string, body?: any): Promise {\n if (!verifyEvent(event)) {\n throw new Error('Invalid nostr event, signature invalid')\n }\n\n if (!validateEventKind(event)) {\n throw new Error('Invalid nostr event, kind invalid')\n }\n\n if (!validateEventTimestamp(event)) {\n throw new Error('Invalid nostr event, created_at timestamp invalid')\n }\n\n if (!validateEventUrlTag(event, url)) {\n throw new Error('Invalid nostr event, url tag invalid')\n }\n\n if (!validateEventMethodTag(event, method)) {\n throw new Error('Invalid nostr event, method tag invalid')\n }\n\n if (Boolean(body) && typeof body === 'object' && Object.keys(body).length > 0) {\n if (!validateEventPayloadTag(event, body)) {\n throw new Error('Invalid nostr event, payload tag does not match request body hash')\n }\n }\n\n return true\n}\n"], + "mappings": ";;;;;;;AAAA,SAAS,eAAe;AACxB,SAAS,cAAAA,mBAAkB;;;ACOpB,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,CAAC,QAAiD,eAAe;AAE3E,SAAS,cAAiB,OAAsC;AACrE,MAAI,CAAC,SAAS,KAAK;AAAG,WAAO;AAC7B,MAAI,OAAO,MAAM,SAAS;AAAU,WAAO;AAC3C,MAAI,OAAO,MAAM,YAAY;AAAU,WAAO;AAC9C,MAAI,OAAO,MAAM,eAAe;AAAU,WAAO;AACjD,MAAI,OAAO,MAAM,WAAW;AAAU,WAAO;AAC7C,MAAI,CAAC,MAAM,OAAO,MAAM,gBAAgB;AAAG,WAAO;AAElD,MAAI,CAAC,MAAM,QAAQ,MAAM,IAAI;AAAG,WAAO;AACvC,WAASC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AAU,OAAO,CAAC,CAAC;AAC/D,SAAOC,YAAW,IAAI;AACxB;AAQO,SAAS,wBAAwB,OAAc,SAAuB;AAC3E,QAAM,aAAa,MAAM,KAAK,KAAK,OAAK,EAAE,OAAO,SAAS;AAE1D,MAAI,CAAC,YAAY;AACf,WAAO;AAAA,EACT;AAEA,QAAM,cAAc,YAAY,OAAO;AACvC,SAAO,WAAW,SAAS,KAAK,WAAW,OAAO;AACpD;AAYA,eAAsBF,eAAc,OAAc,KAAa,QAAgB,MAA8B;AAC3G,MAAI,CAAC,YAAY,KAAK,GAAG;AACvB,UAAM,IAAI,MAAM,wCAAwC;AAAA,EAC1D;AAEA,MAAI,CAAC,kBAAkB,KAAK,GAAG;AAC7B,UAAM,IAAI,MAAM,mCAAmC;AAAA,EACrD;AAEA,MAAI,CAAC,uBAAuB,KAAK,GAAG;AAClC,UAAM,IAAI,MAAM,mDAAmD;AAAA,EACrE;AAEA,MAAI,CAAC,oBAAoB,OAAO,GAAG,GAAG;AACpC,UAAM,IAAI,MAAM,sCAAsC;AAAA,EACxD;AAEA,MAAI,CAAC,uBAAuB,OAAO,MAAM,GAAG;AAC1C,UAAM,IAAI,MAAM,yCAAyC;AAAA,EAC3D;AAEA,MAAI,QAAQ,IAAI,KAAK,OAAO,SAAS,YAAY,OAAO,KAAK,IAAI,EAAE,SAAS,GAAG;AAC7E,QAAI,CAAC,wBAAwB,OAAO,IAAI,GAAG;AACzC,YAAM,IAAI,MAAM,mEAAmE;AAAA,IACrF;AAAA,EACF;AAEA,SAAO;AACT;", + "names": ["bytesToHex", "i", "target", "bytesToHex", "Date", "Date", "i", "i", "reason", "_WebSocket", "_WebSocket", "bytesToHex", "hexToBytes", "bytesToHex", "hexToBytes", "bytesToHex", "bytesToHex", "i", "useFetchImplementation", "_fetch", "bytesToHex", "sha256", "i", "now", "bytesToHex", "sha256", "unwrapEvent", "unwrapManyEvents", "wrapEvent", "wrapManyEvents", "decrypt", "encrypt", "secp256k1", "sha256", "concatBytes", "randomBytes", "base64", "secp256k1", "sha256", "concatBytes", "base64", "encrypt", "randomBytes", "decrypt", "encrypt", "decrypt", "wrapEvent", "wrapManyEvents", "unwrapEvent", "unwrapManyEvents", "i", "parse", "parse", "i", "parse", "parse", "useFetchImplementation", "_fetch", "useFetchImplementation", "bech32", "_fetch", "useFetchImplementation", "bech32", "validateEvent", "sha256", "bytesToHex", "base64", "base64", "validateEvent", "sha256", "bytesToHex"] +} diff --git a/node_modules/nostr-tools/lib/esm/kinds.js b/node_modules/nostr-tools/lib/esm/kinds.js new file mode 100644 index 0000000..291000d --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/kinds.js @@ -0,0 +1,220 @@ +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i = 0; i < event.tags.length; i++) { + let tag = event.tags[i]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// kinds.ts +function isRegularKind(kind) { + return 1e3 <= kind && kind < 1e4 || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind); +} +function isReplaceableKind(kind) { + return [0, 3].includes(kind) || 1e4 <= kind && kind < 2e4; +} +function isEphemeralKind(kind) { + return 2e4 <= kind && kind < 3e4; +} +function isAddressableKind(kind) { + return 3e4 <= kind && kind < 4e4; +} +function classifyKind(kind) { + if (isRegularKind(kind)) + return "regular"; + if (isReplaceableKind(kind)) + return "replaceable"; + if (isEphemeralKind(kind)) + return "ephemeral"; + if (isAddressableKind(kind)) + return "parameterized"; + return "unknown"; +} +function isKind(event, kind) { + const kindAsArray = kind instanceof Array ? kind : [kind]; + return validateEvent(event) && kindAsArray.includes(event.kind) || false; +} +var Metadata = 0; +var ShortTextNote = 1; +var RecommendRelay = 2; +var Contacts = 3; +var EncryptedDirectMessage = 4; +var EventDeletion = 5; +var Repost = 6; +var Reaction = 7; +var BadgeAward = 8; +var Seal = 13; +var PrivateDirectMessage = 14; +var GenericRepost = 16; +var ChannelCreation = 40; +var ChannelMetadata = 41; +var ChannelMessage = 42; +var ChannelHideMessage = 43; +var ChannelMuteUser = 44; +var OpenTimestamps = 1040; +var GiftWrap = 1059; +var FileMetadata = 1063; +var LiveChatMessage = 1311; +var ProblemTracker = 1971; +var Report = 1984; +var Reporting = 1984; +var Label = 1985; +var CommunityPostApproval = 4550; +var JobRequest = 5999; +var JobResult = 6999; +var JobFeedback = 7e3; +var ZapGoal = 9041; +var ZapRequest = 9734; +var Zap = 9735; +var Highlights = 9802; +var Mutelist = 1e4; +var Pinlist = 10001; +var RelayList = 10002; +var BookmarkList = 10003; +var CommunitiesList = 10004; +var PublicChatsList = 10005; +var BlockedRelaysList = 10006; +var SearchRelaysList = 10007; +var InterestsList = 10015; +var UserEmojiList = 10030; +var DirectMessageRelaysList = 10050; +var FileServerPreference = 10096; +var NWCWalletInfo = 13194; +var LightningPubRPC = 21e3; +var ClientAuth = 22242; +var NWCWalletRequest = 23194; +var NWCWalletResponse = 23195; +var NostrConnect = 24133; +var HTTPAuth = 27235; +var Followsets = 3e4; +var Genericlists = 30001; +var Relaysets = 30002; +var Bookmarksets = 30003; +var Curationsets = 30004; +var ProfileBadges = 30008; +var BadgeDefinition = 30009; +var Interestsets = 30015; +var CreateOrUpdateStall = 30017; +var CreateOrUpdateProduct = 30018; +var LongFormArticle = 30023; +var DraftLong = 30024; +var Emojisets = 30030; +var Application = 30078; +var LiveEvent = 30311; +var UserStatuses = 30315; +var ClassifiedListing = 30402; +var DraftClassifiedListing = 30403; +var Date = 31922; +var Time = 31923; +var Calendar = 31924; +var CalendarEventRSVP = 31925; +var Handlerrecommendation = 31989; +var Handlerinformation = 31990; +var CommunityDefinition = 34550; +export { + Application, + BadgeAward, + BadgeDefinition, + BlockedRelaysList, + BookmarkList, + Bookmarksets, + Calendar, + CalendarEventRSVP, + ChannelCreation, + ChannelHideMessage, + ChannelMessage, + ChannelMetadata, + ChannelMuteUser, + ClassifiedListing, + ClientAuth, + CommunitiesList, + CommunityDefinition, + CommunityPostApproval, + Contacts, + CreateOrUpdateProduct, + CreateOrUpdateStall, + Curationsets, + Date, + DirectMessageRelaysList, + DraftClassifiedListing, + DraftLong, + Emojisets, + EncryptedDirectMessage, + EventDeletion, + FileMetadata, + FileServerPreference, + Followsets, + GenericRepost, + Genericlists, + GiftWrap, + HTTPAuth, + Handlerinformation, + Handlerrecommendation, + Highlights, + InterestsList, + Interestsets, + JobFeedback, + JobRequest, + JobResult, + Label, + LightningPubRPC, + LiveChatMessage, + LiveEvent, + LongFormArticle, + Metadata, + Mutelist, + NWCWalletInfo, + NWCWalletRequest, + NWCWalletResponse, + NostrConnect, + OpenTimestamps, + Pinlist, + PrivateDirectMessage, + ProblemTracker, + ProfileBadges, + PublicChatsList, + Reaction, + RecommendRelay, + RelayList, + Relaysets, + Report, + Reporting, + Repost, + Seal, + SearchRelaysList, + ShortTextNote, + Time, + UserEmojiList, + UserStatuses, + Zap, + ZapGoal, + ZapRequest, + classifyKind, + isAddressableKind, + isEphemeralKind, + isKind, + isRegularKind, + isReplaceableKind +}; diff --git a/node_modules/nostr-tools/lib/esm/kinds.js.map b/node_modules/nostr-tools/lib/esm/kinds.js.map new file mode 100644 index 0000000..021ea6f --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/kinds.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../core.ts", "../../kinds.ts"], + "sourcesContent": ["export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n"], + "mappings": ";AAQO,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,CAAC,QAAiD,eAAe;AAE3E,SAAS,cAAiB,OAAsC;AACrE,MAAI,CAAC,SAAS,KAAK;AAAG,WAAO;AAC7B,MAAI,OAAO,MAAM,SAAS;AAAU,WAAO;AAC3C,MAAI,OAAO,MAAM,YAAY;AAAU,WAAO;AAC9C,MAAI,OAAO,MAAM,eAAe;AAAU,WAAO;AACjD,MAAI,OAAO,MAAM,WAAW;AAAU,WAAO;AAC7C,MAAI,CAAC,MAAM,OAAO,MAAM,gBAAgB;AAAG,WAAO;AAElD,MAAI,CAAC,MAAM,QAAQ,MAAM,IAAI;AAAG,WAAO;AACvC,WAAS,IAAI,GAAG,IAAI,MAAM,KAAK,QAAQ,KAAK;AAC1C,QAAI,MAAM,MAAM,KAAK;AACrB,QAAI,CAAC,MAAM,QAAQ,GAAG;AAAG,aAAO;AAChC,aAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,UAAI,OAAO,IAAI,OAAO;AAAU,eAAO;AAAA,IACzC;AAAA,EACF;AAEA,SAAO;AACT;;;AC/CO,SAAS,cAAc,MAAuB;AACnD,SAAQ,OAAQ,QAAQ,OAAO,OAAU,CAAC,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,IAAI,IAAI,IAAI,IAAI,IAAI,EAAE,EAAE,SAAS,IAAI;AACtG;AAGO,SAAS,kBAAkB,MAAu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M,WAAW;AAEjB,IAAM,UAAU;AAEhB,IAAM,YAAY;AAElB,IAAM,eAAe;AAErB,IAAM,kBAAkB;AAExB,IAAM,kBAAkB;AAExB,IAAM,oBAAoB;AAE1B,IAAM,mBAAmB;AAEzB,IAAM,gBAAgB;AAEtB,IAAM,gBAAgB;AAEtB,IAAM,0BAA0B;AAEhC,IAAM,uBAAuB;AAE7B,IAAM,gBAAgB;AAEtB,IAAM,kBAAkB;AAExB,IAAM,aAAa;AAEnB,IAAM,mBAAmB;AAEzB,IAAM,oBAAoB;AAE1B,IAAM,eAAe;AAErB,IAAM,WAAW;AAEjB,IAAM,aAAa;AAEnB,IAAM,eAAe;AAErB,IAAM,YAAY;AAElB,IAAM,eAAe;AAErB,IAAM,eAAe;AAErB,IAAM,gBAAgB;AAEtB,IAAM,kBAAkB;AAExB,IAAM,eAAe;AAErB,IAAM,sBAAsB;AAE5B,IAAM,wBAAwB;AAE9B,IAAM,kBAAkB;AAExB,IAAM,YAAY;AAElB,IAAM,YAAY;AAElB,IAAM,cAAc;AAEpB,IAAM,YAAY;AAElB,IAAM,eAAe;AAErB,IAAM,oBAAoB;AAE1B,IAAM,yBAAyB;AAE/B,IAAM,OAAO;AAEb,IAAM,OAAO;AAEb,IAAM,WAAW;AAEjB,IAAM,oBAAoB;AAE1B,IAAM,wBAAwB;AAE9B,IAAM,qBAAqB;AAE3B,IAAM,sBAAsB;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/esm/nip04.js b/node_modules/nostr-tools/lib/esm/nip04.js new file mode 100644 index 0000000..0800255 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip04.js @@ -0,0 +1,40 @@ +// nip04.ts +import { bytesToHex as bytesToHex2, randomBytes } from "@noble/hashes/utils"; +import { secp256k1 } from "@noble/curves/secp256k1"; +import { cbc } from "@noble/ciphers/aes"; +import { base64 } from "@scure/base"; + +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// nip04.ts +function encrypt(secretKey, pubkey, text) { + const privkey = secretKey instanceof Uint8Array ? bytesToHex2(secretKey) : secretKey; + const key = secp256k1.getSharedSecret(privkey, "02" + pubkey); + const normalizedKey = getNormalizedX(key); + let iv = Uint8Array.from(randomBytes(16)); + let plaintext = utf8Encoder.encode(text); + let ciphertext = cbc(normalizedKey, iv).encrypt(plaintext); + let ctb64 = base64.encode(new Uint8Array(ciphertext)); + let ivb64 = base64.encode(new Uint8Array(iv.buffer)); + return `${ctb64}?iv=${ivb64}`; +} +function decrypt(secretKey, pubkey, data) { + const privkey = secretKey instanceof Uint8Array ? bytesToHex2(secretKey) : secretKey; + let [ctb64, ivb64] = data.split("?iv="); + let key = secp256k1.getSharedSecret(privkey, "02" + pubkey); + let normalizedKey = getNormalizedX(key); + let iv = base64.decode(ivb64); + let ciphertext = base64.decode(ctb64); + let plaintext = cbc(normalizedKey, iv).decrypt(ciphertext); + return utf8Decoder.decode(plaintext); +} +function getNormalizedX(key) { + return key.slice(1, 33); +} +export { + decrypt, + encrypt +}; diff --git a/node_modules/nostr-tools/lib/esm/nip04.js.map b/node_modules/nostr-tools/lib/esm/nip04.js.map new file mode 100644 index 0000000..e0dc7cc --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip04.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip04.ts", "../../utils.ts"], + "sourcesContent": ["import { bytesToHex, randomBytes } from '@noble/hashes/utils'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { cbc } from '@noble/ciphers/aes'\nimport { base64 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport function encrypt(secretKey: string | Uint8Array, pubkey: string, text: string): string {\n const privkey: string = secretKey instanceof Uint8Array ? bytesToHex(secretKey) : secretKey\n const key = secp256k1.getSharedSecret(privkey, '02' + pubkey)\n const normalizedKey = getNormalizedX(key)\n\n let iv = Uint8Array.from(randomBytes(16))\n let plaintext = utf8Encoder.encode(text)\n\n let ciphertext = cbc(normalizedKey, iv).encrypt(plaintext)\n\n let ctb64 = base64.encode(new Uint8Array(ciphertext))\n let ivb64 = base64.encode(new Uint8Array(iv.buffer))\n\n return `${ctb64}?iv=${ivb64}`\n}\n\nexport function decrypt(secretKey: string | Uint8Array, pubkey: string, data: string): string {\n const privkey: string = secretKey instanceof Uint8Array ? bytesToHex(secretKey) : secretKey\n let [ctb64, ivb64] = data.split('?iv=')\n let key = secp256k1.getSharedSecret(privkey, '02' + pubkey)\n let normalizedKey = getNormalizedX(key)\n\n let iv = base64.decode(ivb64)\n let ciphertext = base64.decode(ctb64)\n\n let plaintext = cbc(normalizedKey, iv).decrypt(ciphertext)\n\n return utf8Decoder.decode(plaintext)\n}\n\nfunction getNormalizedX(key: Uint8Array): Uint8Array {\n return key.slice(1, 33)\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n"], + "mappings": ";AAAA,SAAS,cAAAA,aAAY,mBAAmB;AACxC,SAAS,iBAAiB;AAC1B,SAAS,WAAW;AACpB,SAAS,cAAc;;;ACEvB,SAAS,YAAY,kBAAkB;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;;;ADIjD,SAAS,QAAQ,WAAgC,QAAgB,MAAsB;AAC5F,QAAM,UAAkB,qBAAqB,aAAaC,YAAW,SAAS,IAAI;AAClF,QAAM,MAAM,UAAU,gBAAgB,SAAS,OAAO,MAAM;AAC5D,QAAM,gBAAgB,eAAe,GAAG;AAExC,MAAI,KAAK,WAAW,KAAK,YAAY,EAAE,CAAC;AACxC,MAAI,YAAY,YAAY,OAAO,IAAI;AAEvC,MAAI,aAAa,IAAI,eAAe,EAAE,EAAE,QAAQ,SAAS;AAEzD,MAAI,QAAQ,OAAO,OAAO,IAAI,WAAW,UAAU,CAAC;AACpD,MAAI,QAAQ,OAAO,OAAO,IAAI,WAAW,GAAG,MAAM,CAAC;AAEnD,SAAO,GAAG,YAAY;AACxB;AAEO,SAAS,QAAQ,WAAgC,QAAgB,MAAsB;AAC5F,QAAM,UAAkB,qBAAqB,aAAaA,YAAW,SAAS,IAAI;AAClF,MAAI,CAAC,OAAO,KAAK,IAAI,KAAK,MAAM,MAAM;AACtC,MAAI,MAAM,UAAU,gBAAgB,SAAS,OAAO,MAAM;AAC1D,MAAI,gBAAgB,eAAe,GAAG;AAEtC,MAAI,KAAK,OAAO,OAAO,KAAK;AAC5B,MAAI,aAAa,OAAO,OAAO,KAAK;AAEpC,MAAI,YAAY,IAAI,eAAe,EAAE,EAAE,QAAQ,UAAU;AAEzD,SAAO,YAAY,OAAO,SAAS;AACrC;AAEA,SAAS,eAAe,KAA6B;AACnD,SAAO,IAAI,MAAM,GAAG,EAAE;AACxB;", + "names": ["bytesToHex", "bytesToHex"] +} diff --git a/node_modules/nostr-tools/lib/esm/nip05.js b/node_modules/nostr-tools/lib/esm/nip05.js new file mode 100644 index 0000000..f6ca4ec --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip05.js @@ -0,0 +1,55 @@ +// nip05.ts +var NIP05_REGEX = /^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/; +var isNip05 = (value) => NIP05_REGEX.test(value || ""); +var _fetch; +try { + _fetch = fetch; +} catch (_) { + null; +} +function useFetchImplementation(fetchImplementation) { + _fetch = fetchImplementation; +} +async function searchDomain(domain, query = "") { + try { + const url = `https://${domain}/.well-known/nostr.json?name=${query}`; + const res = await _fetch(url, { redirect: "manual" }); + if (res.status !== 200) { + throw Error("Wrong response code"); + } + const json = await res.json(); + return json.names; + } catch (_) { + return {}; + } +} +async function queryProfile(fullname) { + const match = fullname.match(NIP05_REGEX); + if (!match) + return null; + const [, name = "_", domain] = match; + try { + const url = `https://${domain}/.well-known/nostr.json?name=${name}`; + const res = await _fetch(url, { redirect: "manual" }); + if (res.status !== 200) { + throw Error("Wrong response code"); + } + const json = await res.json(); + const pubkey = json.names[name]; + return pubkey ? { pubkey, relays: json.relays?.[pubkey] } : null; + } catch (_e) { + return null; + } +} +async function isValid(pubkey, nip05) { + const res = await queryProfile(nip05); + return res ? res.pubkey === pubkey : false; +} +export { + NIP05_REGEX, + isNip05, + isValid, + queryProfile, + searchDomain, + useFetchImplementation +}; diff --git a/node_modules/nostr-tools/lib/esm/nip05.js.map b/node_modules/nostr-tools/lib/esm/nip05.js.map new file mode 100644 index 0000000..575f8c6 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip05.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip05.ts"], + "sourcesContent": ["import { ProfilePointer } from './nip19.ts'\n\nexport type Nip05 = `${string}@${string}`\n\n/**\n * NIP-05 regex. The localpart is optional, and should be assumed to be `_` otherwise.\n *\n * - 0: full match\n * - 1: name (optional)\n * - 2: domain\n */\nexport const NIP05_REGEX = /^(?:([\\w.+-]+)@)?([\\w_-]+(\\.[\\w_-]+)+)$/\nexport const isNip05 = (value?: string | null): value is Nip05 => NIP05_REGEX.test(value || '')\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _fetch: any\n\ntry {\n _fetch = fetch\n} catch (_) {\n null\n}\n\nexport function useFetchImplementation(fetchImplementation: unknown) {\n _fetch = fetchImplementation\n}\n\nexport async function searchDomain(domain: string, query = ''): Promise<{ [name: string]: string }> {\n try {\n const url = `https://${domain}/.well-known/nostr.json?name=${query}`\n const res = await _fetch(url, { redirect: 'manual' })\n if (res.status !== 200) {\n throw Error('Wrong response code')\n }\n const json = await res.json()\n return json.names\n } catch (_) {\n return {}\n }\n}\n\nexport async function queryProfile(fullname: string): Promise {\n const match = fullname.match(NIP05_REGEX)\n if (!match) return null\n\n const [, name = '_', domain] = match\n\n try {\n const url = `https://${domain}/.well-known/nostr.json?name=${name}`\n const res = await _fetch(url, { redirect: 'manual' })\n if (res.status !== 200) {\n throw Error('Wrong response code')\n }\n const json = await res.json()\n\n const pubkey = json.names[name]\n return pubkey ? { pubkey, relays: json.relays?.[pubkey] } : null\n } catch (_e) {\n return null\n }\n}\n\nexport async function isValid(pubkey: string, nip05: Nip05): Promise {\n const res = await queryProfile(nip05)\n return res ? res.pubkey === pubkey : false\n}\n"], + "mappings": ";AAWO,IAAM,cAAc;AACpB,IAAM,UAAU,CAAC,UAA0C,YAAY,KAAK,SAAS,EAAE;AAG9F,IAAI;AAEJ,IAAI;AACF,WAAS;AACX,SAAS,GAAP;AACA;AACF;AAEO,SAAS,uBAAuB,qBAA8B;AACnE,WAAS;AACX;AAEA,eAAsB,aAAa,QAAgB,QAAQ,IAAyC;AAClG,MAAI;AACF,UAAM,MAAM,WAAW,sCAAsC;AAC7D,UAAM,MAAM,MAAM,OAAO,KAAK,EAAE,UAAU,SAAS,CAAC;AACpD,QAAI,IAAI,WAAW,KAAK;AACtB,YAAM,MAAM,qBAAqB;AAAA,IACnC;AACA,UAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,WAAO,KAAK;AAAA,EACd,SAAS,GAAP;AACA,WAAO,CAAC;AAAA,EACV;AACF;AAEA,eAAsB,aAAa,UAAkD;AACnF,QAAM,QAAQ,SAAS,MAAM,WAAW;AACxC,MAAI,CAAC;AAAO,WAAO;AAEnB,QAAM,CAAC,EAAE,OAAO,KAAK,MAAM,IAAI;AAE/B,MAAI;AACF,UAAM,MAAM,WAAW,sCAAsC;AAC7D,UAAM,MAAM,MAAM,OAAO,KAAK,EAAE,UAAU,SAAS,CAAC;AACpD,QAAI,IAAI,WAAW,KAAK;AACtB,YAAM,MAAM,qBAAqB;AAAA,IACnC;AACA,UAAM,OAAO,MAAM,IAAI,KAAK;AAE5B,UAAM,SAAS,KAAK,MAAM;AAC1B,WAAO,SAAS,EAAE,QAAQ,QAAQ,KAAK,SAAS,QAAQ,IAAI;AAAA,EAC9D,SAAS,IAAP;AACA,WAAO;AAAA,EACT;AACF;AAEA,eAAsB,QAAQ,QAAgB,OAAgC;AAC5E,QAAM,MAAM,MAAM,aAAa,KAAK;AACpC,SAAO,MAAM,IAAI,WAAW,SAAS;AACvC;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/esm/nip06.js b/node_modules/nostr-tools/lib/esm/nip06.js new file mode 100644 index 0000000..1d76cc5 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip06.js @@ -0,0 +1,61 @@ +// nip06.ts +import { bytesToHex } from "@noble/hashes/utils"; +import { wordlist } from "@scure/bip39/wordlists/english"; +import { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from "@scure/bip39"; +import { HDKey } from "@scure/bip32"; +var DERIVATION_PATH = `m/44'/1237'`; +function privateKeyFromSeedWords(mnemonic, passphrase, accountIndex = 0) { + let root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase)); + let privateKey = root.derive(`${DERIVATION_PATH}/${accountIndex}'/0/0`).privateKey; + if (!privateKey) + throw new Error("could not derive private key"); + return privateKey; +} +function accountFromSeedWords(mnemonic, passphrase, accountIndex = 0) { + const root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase)); + const seed = root.derive(`${DERIVATION_PATH}/${accountIndex}'/0/0`); + const publicKey = bytesToHex(seed.publicKey.slice(1)); + const privateKey = seed.privateKey; + if (!privateKey || !publicKey) { + throw new Error("could not derive key pair"); + } + return { privateKey, publicKey }; +} +function extendedKeysFromSeedWords(mnemonic, passphrase, extendedAccountIndex = 0) { + let root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase)); + let seed = root.derive(`${DERIVATION_PATH}/${extendedAccountIndex}'`); + let privateExtendedKey = seed.privateExtendedKey; + let publicExtendedKey = seed.publicExtendedKey; + if (!privateExtendedKey && !publicExtendedKey) + throw new Error("could not derive extended key pair"); + return { privateExtendedKey, publicExtendedKey }; +} +function accountFromExtendedKey(base58key, accountIndex = 0) { + let extendedKey = HDKey.fromExtendedKey(base58key); + let version = base58key.slice(0, 4); + let child = extendedKey.deriveChild(0).deriveChild(accountIndex); + let publicKey = bytesToHex(child.publicKey.slice(1)); + if (!publicKey) + throw new Error("could not derive public key"); + if (version === "xprv") { + let privateKey = child.privateKey; + if (!privateKey) + throw new Error("could not derive private key"); + return { privateKey, publicKey }; + } + return { publicKey }; +} +function generateSeedWords() { + return generateMnemonic(wordlist); +} +function validateWords(words) { + return validateMnemonic(words, wordlist); +} +export { + accountFromExtendedKey, + accountFromSeedWords, + extendedKeysFromSeedWords, + generateSeedWords, + privateKeyFromSeedWords, + validateWords +}; diff --git a/node_modules/nostr-tools/lib/esm/nip06.js.map b/node_modules/nostr-tools/lib/esm/nip06.js.map new file mode 100644 index 0000000..404544c --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip06.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip06.ts"], + "sourcesContent": ["import { bytesToHex } from '@noble/hashes/utils'\nimport { wordlist } from '@scure/bip39/wordlists/english'\nimport { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39'\nimport { HDKey } from '@scure/bip32'\n\nconst DERIVATION_PATH = `m/44'/1237'`\n\nexport function privateKeyFromSeedWords(mnemonic: string, passphrase?: string, accountIndex = 0): Uint8Array {\n let root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase))\n let privateKey = root.derive(`${DERIVATION_PATH}/${accountIndex}'/0/0`).privateKey\n if (!privateKey) throw new Error('could not derive private key')\n return privateKey\n}\n\nexport function accountFromSeedWords(\n mnemonic: string,\n passphrase?: string,\n accountIndex = 0,\n): {\n privateKey: Uint8Array\n publicKey: string\n} {\n const root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase))\n const seed = root.derive(`${DERIVATION_PATH}/${accountIndex}'/0/0`)\n const publicKey = bytesToHex(seed.publicKey!.slice(1))\n const privateKey = seed.privateKey\n if (!privateKey || !publicKey) {\n throw new Error('could not derive key pair')\n }\n return { privateKey, publicKey }\n}\n\nexport function extendedKeysFromSeedWords(\n mnemonic: string,\n passphrase?: string,\n extendedAccountIndex = 0,\n): {\n privateExtendedKey: string\n publicExtendedKey: string\n} {\n let root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase))\n let seed = root.derive(`${DERIVATION_PATH}/${extendedAccountIndex}'`)\n let privateExtendedKey = seed.privateExtendedKey\n let publicExtendedKey = seed.publicExtendedKey\n if (!privateExtendedKey && !publicExtendedKey) throw new Error('could not derive extended key pair')\n return { privateExtendedKey, publicExtendedKey }\n}\n\nexport function accountFromExtendedKey(\n base58key: string,\n accountIndex = 0,\n): {\n privateKey?: Uint8Array\n publicKey: string\n} {\n let extendedKey = HDKey.fromExtendedKey(base58key)\n let version = base58key.slice(0, 4)\n let child = extendedKey.deriveChild(0).deriveChild(accountIndex)\n let publicKey = bytesToHex(child.publicKey!.slice(1))\n if (!publicKey) throw new Error('could not derive public key')\n if (version === 'xprv') {\n let privateKey = child.privateKey!\n if (!privateKey) throw new Error('could not derive private key')\n return { privateKey, publicKey }\n }\n return { publicKey }\n}\n\nexport function generateSeedWords(): string {\n return generateMnemonic(wordlist)\n}\n\nexport function validateWords(words: string): boolean {\n return validateMnemonic(words, wordlist)\n}\n"], + "mappings": ";AAAA,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB;AACzB,SAAS,kBAAkB,oBAAoB,wBAAwB;AACvE,SAAS,aAAa;AAEtB,IAAM,kBAAkB;AAEjB,SAAS,wBAAwB,UAAkB,YAAqB,eAAe,GAAe;AAC3G,MAAI,OAAO,MAAM,eAAe,mBAAmB,UAAU,UAAU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AAU;AACrB;AAEO,SAAS,oBAA4B;AAC1C,SAAO,iBAAiB,QAAQ;AAClC;AAEO,SAAS,cAAc,OAAwB;AACpD,SAAO,iBAAiB,OAAO,QAAQ;AACzC;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/esm/nip07.js b/node_modules/nostr-tools/lib/esm/nip07.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/nostr-tools/lib/esm/nip07.js.map b/node_modules/nostr-tools/lib/esm/nip07.js.map new file mode 100644 index 0000000..9865211 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip07.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": [], + "sourcesContent": [], + "mappings": "", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/esm/nip10.js b/node_modules/nostr-tools/lib/esm/nip10.js new file mode 100644 index 0000000..db54e18 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip10.js @@ -0,0 +1,103 @@ +// nip10.ts +function parse(event) { + const result = { + reply: void 0, + root: void 0, + mentions: [], + profiles: [], + quotes: [] + }; + let maybeParent; + let maybeRoot; + for (let i = event.tags.length - 1; i >= 0; i--) { + const tag = event.tags[i]; + if (tag[0] === "e" && tag[1]) { + const [_, eTagEventId, eTagRelayUrl, eTagMarker, eTagAuthor] = tag; + const eventPointer = { + id: eTagEventId, + relays: eTagRelayUrl ? [eTagRelayUrl] : [], + author: eTagAuthor + }; + if (eTagMarker === "root") { + result.root = eventPointer; + continue; + } + if (eTagMarker === "reply") { + result.reply = eventPointer; + continue; + } + if (eTagMarker === "mention") { + result.mentions.push(eventPointer); + continue; + } + if (!maybeParent) { + maybeParent = eventPointer; + } else { + maybeRoot = eventPointer; + } + result.mentions.push(eventPointer); + continue; + } + if (tag[0] === "q" && tag[1]) { + const [_, eTagEventId, eTagRelayUrl] = tag; + result.quotes.push({ + id: eTagEventId, + relays: eTagRelayUrl ? [eTagRelayUrl] : [] + }); + } + if (tag[0] === "p" && tag[1]) { + result.profiles.push({ + pubkey: tag[1], + relays: tag[2] ? [tag[2]] : [] + }); + continue; + } + } + if (!result.root) { + result.root = maybeRoot || maybeParent || result.reply; + } + if (!result.reply) { + result.reply = maybeParent || result.root; + } + ; + [result.reply, result.root].forEach((ref) => { + if (!ref) + return; + let idx = result.mentions.indexOf(ref); + if (idx !== -1) { + result.mentions.splice(idx, 1); + } + if (ref.author) { + let author = result.profiles.find((p) => p.pubkey === ref.author); + if (author && author.relays) { + if (!ref.relays) { + ref.relays = []; + } + author.relays.forEach((url) => { + if (ref.relays?.indexOf(url) === -1) + ref.relays.push(url); + }); + author.relays = ref.relays; + } + } + }); + result.mentions.forEach((ref) => { + if (ref.author) { + let author = result.profiles.find((p) => p.pubkey === ref.author); + if (author && author.relays) { + if (!ref.relays) { + ref.relays = []; + } + author.relays.forEach((url) => { + if (ref.relays.indexOf(url) === -1) + ref.relays.push(url); + }); + author.relays = ref.relays; + } + } + }); + return result; +} +export { + parse +}; diff --git a/node_modules/nostr-tools/lib/esm/nip10.js.map b/node_modules/nostr-tools/lib/esm/nip10.js.map new file mode 100644 index 0000000..f2e3afa --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip10.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip10.ts"], + "sourcesContent": ["import type { Event } from './core.ts'\nimport type { EventPointer, ProfilePointer } from './nip19.ts'\n\nexport function parse(event: Pick): {\n /**\n * Pointer to the root of the thread.\n */\n root: EventPointer | undefined\n\n /**\n * Pointer to a \"parent\" event that parsed event replies to (responded to).\n */\n reply: EventPointer | undefined\n\n /**\n * Pointers to events that may or may not be in the reply chain.\n */\n mentions: EventPointer[]\n\n /**\n * Pointers to events that were directly quoted.\n */\n quotes: EventPointer[]\n\n /**\n * List of pubkeys that are involved in the thread in no particular order.\n */\n profiles: ProfilePointer[]\n} {\n const result: ReturnType = {\n reply: undefined,\n root: undefined,\n mentions: [],\n profiles: [],\n quotes: [],\n }\n\n let maybeParent: EventPointer | undefined\n let maybeRoot: EventPointer | undefined\n\n for (let i = event.tags.length - 1; i >= 0; i--) {\n const tag = event.tags[i]\n\n if (tag[0] === 'e' && tag[1]) {\n const [_, eTagEventId, eTagRelayUrl, eTagMarker, eTagAuthor] = tag as [\n string,\n string,\n undefined | string,\n undefined | string,\n undefined | string,\n ]\n\n const eventPointer: EventPointer = {\n id: eTagEventId,\n relays: eTagRelayUrl ? [eTagRelayUrl] : [],\n author: eTagAuthor,\n }\n\n if (eTagMarker === 'root') {\n result.root = eventPointer\n continue\n }\n\n if (eTagMarker === 'reply') {\n result.reply = eventPointer\n continue\n }\n\n if (eTagMarker === 'mention') {\n result.mentions.push(eventPointer)\n continue\n }\n\n if (!maybeParent) {\n maybeParent = eventPointer\n } else {\n maybeRoot = eventPointer\n }\n\n result.mentions.push(eventPointer)\n continue\n }\n\n if (tag[0] === 'q' && tag[1]) {\n const [_, eTagEventId, eTagRelayUrl] = tag as [string, string, undefined | string]\n result.quotes.push({\n id: eTagEventId,\n relays: eTagRelayUrl ? [eTagRelayUrl] : [],\n })\n }\n\n if (tag[0] === 'p' && tag[1]) {\n result.profiles.push({\n pubkey: tag[1],\n relays: tag[2] ? [tag[2]] : [],\n })\n continue\n }\n }\n\n // get legacy (positional) markers, set reply to root and vice-versa if one of them is missing\n if (!result.root) {\n result.root = maybeRoot || maybeParent || result.reply\n }\n if (!result.reply) {\n result.reply = maybeParent || result.root\n }\n\n // remove root and reply from mentions, inherit relay hints from authors if any\n ;[result.reply, result.root].forEach(ref => {\n if (!ref) return\n\n let idx = result.mentions.indexOf(ref)\n if (idx !== -1) {\n result.mentions.splice(idx, 1)\n }\n if (ref.author) {\n let author = result.profiles.find(p => p.pubkey === ref.author)\n if (author && author.relays) {\n if (!ref.relays) {\n ref.relays = []\n }\n author.relays.forEach(url => {\n if (ref.relays!?.indexOf(url) === -1) ref.relays!.push(url)\n })\n author.relays = ref.relays\n }\n }\n })\n\n result.mentions.forEach(ref => {\n if (ref!.author) {\n let author = result.profiles.find(p => p.pubkey === ref.author)\n if (author && author.relays) {\n if (!ref.relays) {\n ref.relays = []\n }\n author.relays.forEach(url => {\n if (ref.relays!.indexOf(url) === -1) ref.relays!.push(url)\n })\n author.relays = ref.relays\n }\n }\n })\n\n return result\n}\n"], + "mappings": ";AAGO,SAAS,MAAM,OAyBpB;AACA,QAAM,SAAmC;AAAA,IACvC,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU,CAAC;AAAA,IACX,UAAU,CAAC;AAAA,IACX,QAAQ,CAAC;AAAA,EACX;AAEA,MAAI;AACJ,MAAI;AAEJ,WAAS,IAAI,MAAM,KAAK,SAAS,GAAG,KAAK,GAAG,KAAK;AAC/C,UAAM,MAAM,MAAM,KAAK;AAEvB,QAAI,IAAI,OAAO,OAAO,IAAI,IAAI;AAC5B,YAAM,CAAC,GAAG,aAAa,cAAc,YAAY,UAAU,IAAI;AAQ/D,YAAM,eAA6B;AAAA,QACjC,IAAI;AAAA,QACJ,QAAQ,eAAe,CAAC,YAAY,IAAI,CAAC;AAAA,QACzC,QAAQ;AAAA,MACV;AAEA,UAAI,eAAe,QAAQ;AACzB,eAAO,OAAO;AACd;AAAA,MACF;AAEA,UAAI,eAAe,SAAS;AAC1B,eAAO,QAAQ;AACf;AAAA,MACF;AAEA,UAAI,eAAe,WAAW;AAC5B,eAAO,SAAS,KAAK,YAAY;AACjC;AAAA,MACF;AAEA,UAAI,CAAC,aAAa;AAChB,sBAAc;AAAA,MAChB,OAAO;AACL,oBAAY;AAAA,MACd;AAEA,aAAO,SAAS,KAAK,YAAY;AACjC;AAAA,IACF;AAEA,QAAI,IAAI,OAAO,OAAO,IAAI,IAAI;AAC5B,YAAM,CAAC,GAAG,aAAa,YAAY,IAAI;AACvC,aAAO,OAAO,KAAK;AAAA,QACjB,IAAI;AAAA,QACJ,QAAQ,eAAe,CAAC,YAAY,IAAI,CAAC;AAAA,MAC3C,CAAC;AAAA,IACH;AAEA,QAAI,IAAI,OAAO,OAAO,IAAI,IAAI;AAC5B,aA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,eAAO,SAAS,IAAI;AAAA,MACtB;AAAA,IACF;AAAA,EACF,CAAC;AAED,SAAO;AACT;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/esm/nip11.js b/node_modules/nostr-tools/lib/esm/nip11.js new file mode 100644 index 0000000..14052fa --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip11.js @@ -0,0 +1,18 @@ +// nip11.ts +var _fetch; +try { + _fetch = fetch; +} catch { +} +function useFetchImplementation(fetchImplementation) { + _fetch = fetchImplementation; +} +async function fetchRelayInformation(url) { + return await (await fetch(url.replace("ws://", "http://").replace("wss://", "https://"), { + headers: { Accept: "application/nostr+json" } + })).json(); +} +export { + fetchRelayInformation, + useFetchImplementation +}; diff --git a/node_modules/nostr-tools/lib/esm/nip11.js.map b/node_modules/nostr-tools/lib/esm/nip11.js.map new file mode 100644 index 0000000..9e31335 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip11.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip11.ts"], + "sourcesContent": ["var _fetch: any\n\ntry {\n _fetch = fetch\n} catch {}\n\nexport function useFetchImplementation(fetchImplementation: any): void {\n _fetch = fetchImplementation\n}\n\nexport async function fetchRelayInformation(url: string): Promise {\n return (await (\n await fetch(url.replace('ws://', 'http://').replace('wss://', 'https://'), {\n headers: { Accept: 'application/nostr+json' },\n })\n ).json()) as RelayInformation\n}\n\n/**\n * ## Relay Information Document\n\n * Relays may provide server metadata to clients to inform\n * them of capabilities, administrative contacts, and\n * various server attributes. This is made available as a\n * JSON document over HTTP, on the same URI as the relay's\n * websocket.\n\n * Any field may be omitted, and clients MUST ignore any\n * additional fields they do not understand. Relays MUST\n * accept CORS requests by sending\n * `Access-Control-Allow-Origin`,\n * `Access-Control-Allow-Headers`, and\n * `Access-Control-Allow-Methods` headers.\n * @param name string identifying relay\n * @param description string with detailed information\n * @param pubkey administrative contact pubkey\n * @param contact: administrative alternate contact\n * @param supported_nips a list of NIP numbers supported by\n * the relay\n * @param software identifying relay software URL\n * @param version string version identifier\n */\nexport interface BasicRelayInformation {\n // string identifying relay\n name: string\n description: string\n pubkey: string\n contact: string\n supported_nips: number[]\n software: string\n version: string\n // limitation?: Limitations\n}\n\n/**\n * * ## Extra Fields\n\n * * ### Server Limitations\n\n * These are limitations imposed by the relay on clients.\n * Your client should expect that requests which exceed\n * these practical_ limitations are rejected or fail immediately.\n * @param max_message_length this is the maximum number of\n * bytes for incoming JSON that the relay will attempt to\n * decode and act upon. When you send large subscriptions,\n * you will be limited by this value. It also effectively\n * limits the maximum size of any event. Value is calculated\n * from `[` to `]` and is after UTF-8 serialization (so some\n * unicode characters will cost 2-3 bytes). It is equal to\n * the maximum size of the WebSocket message frame.\n * @param max_subscriptions total number of subscriptions\n * that may be active on a single websocket connection to\n * this relay. It's possible that authenticated clients with\n * a (paid) relationship to the relay may have higher limits.\n * @param max_filters maximum number of filter values in\n * each subscription. Must be one or higher.\n * @param max_limit the relay server will clamp each\n * filter's `limit` value to this number.\n * This means the client won't be able to get more than this\n * number of events from a single subscription filter. This\n * clamping is typically done silently by the relay, but\n * with this number, you can know that there are additional\n * results if you narrowed your filter's time range or other\n * parameters.\n * @param max_subid_length maximum length of subscription id as a\n * string.\n * @param min_prefix for `authors` and `ids` filters which\n * are to match against a hex prefix, you must provide at\n * least this many hex digits in the prefix.\n * @param max_event_tags in any event, this is the maximum\n * number of elements in the `tags` list.\n * @param max_content_length maximum number of characters in\n * the `content` field of any event. This is a count of\n * unicode characters. After serializing into JSON it may be\n * larger (in bytes), and is still subject to the\n * max_message_length`, if defined.\n * @param min_pow_difficulty new events will require at\n * least this difficulty of PoW, based on [NIP-13](13.md),\n * or they will be rejected by this server.\n * @param auth_required this relay requires [NIP-42](42.md)\n * authentication to happen before a new connection may\n * perform any other action. Even if set to False,\n * authentication may be required for specific actions.\n * @param restricted_writes: this relay requires some kind\n * of condition to be fulfilled in order to accept events\n * (not necessarily, but including\n * @param payment_required this relay requires payment\n * before a new connection may perform any action.\n * @param created_at_lower_limit: 'created_at' lower limit\n * @param created_at_upper_limit: 'created_at' upper limit\n */\nexport interface Limitations {\n max_message_length: number\n max_subscriptions: number\n max_filters: number\n max_limit: number\n max_subid_length: number\n min_prefix: number\n max_event_tags: number\n max_content_length: number\n min_pow_difficulty: number\n auth_required: boolean\n payment_required: boolean\n created_at_lower_limit: number\n created_at_upper_limit: number\n restricted_writes: boolean\n}\n\nexport interface RetentionDetails {\n kinds: (number | number[])[]\n time?: number | null\n count?: number | null\n}\ntype AnyRetentionDetails = RetentionDetails\n/**\n * ### Event Retention\n\n * There may be a cost associated with storing data forever,\n * so relays may wish to state retention times. The values\n * stated here are defaults for unauthenticated users and\n * visitors. Paid users would likely have other policies.\n\n * Retention times are given in seconds, with `null`\n * indicating infinity. If zero is provided, this means the\n * event will not be stored at all, and preferably an error\n * will be provided when those are received.\n * ```json\n{\n...\n \"retention\": [\n { \"kinds\": [0, 1, [5, 7], [40, 49]], \"time\": 3600 },\n { \"kinds\": [[40000, 49999]], \"time\": 100 },\n { \"kinds\": [[30000, 39999]], \"count\": 1000 },\n { \"time\": 3600, \"count\": 10000 }\n ]\n...\n}\n```\n * @param retention is a list of specifications: each will\n * apply to either all kinds, or a subset of kinds. Ranges\n * may be specified for the kind field as a tuple of\n * inclusive start and end values. Events of indicated kind\n * (or all) are then limited to a `count` and/or time\n * period.\n\n * It is possible to effectively blacklist Nostr-based\n * protocols that rely on a specific `kind` number, by\n * giving a retention time of zero for those `kind` values.\n * While that is unfortunate, it does allow clients to\n * discover servers that will support their protocol quickly\n * via a single HTTP fetch.\n\n * There is no need to specify retention times for\n * _ephemeral events_ as defined in [NIP-16](16.md) since\n * they are not retained.\n */\nexport interface Retention {\n retention: AnyRetentionDetails[]\n}\n\n/**\n * Some relays may be governed by the arbitrary laws of a\n * nation state. This may limit what content can be stored\n * in cleartext on those relays. All clients are encouraged\n * to use encryption to work around this limitation.\n\n * It is not possible to describe the limitations of each\n * country's laws and policies which themselves are\n * typically vague and constantly shifting.\n\n * Therefore, this field allows the relay operator to\n * indicate which countries' laws might end up being\n * enforced on them, and then indirectly on their users'\n * content.\n\n * Users should be able to avoid relays in countries they\n * don't like, and/or select relays in more favourable\n * zones. Exposing this flexibility is up to the client\n * software.\n\n * @param relay_countries a list of two-level ISO country\n * codes (ISO 3166-1 alpha-2) whose laws and policies may\n * affect this relay. `EU` may be used for European Union\n * countries.\n\n * Remember that a relay may be hosted in a country which is\n * not the country of the legal entities who own the relay,\n * so it's very likely a number of countries are involved.\n */\nexport interface ContentLimitations {\n relay_countries: string[]\n}\n\n/**\n * ### Community Preferences\n\n * For public text notes at least, a relay may try to foster\n * a local community. This would encourage users to follow\n * the global feed on that relay, in addition to their usual\n * individual follows. To support this goal, relays MAY\n * specify some of the following values.\n\n * @param language_tags is an ordered list of [IETF\n * language\n * tags](https://en.wikipedia.org/wiki/IETF_language_tag\n * indicating the major languages spoken on the relay.\n * @param tags is a list of limitations on the topics to be\n * discussed. For example `sfw-only` indicates that only\n * \"Safe For Work\" content is encouraged on this relay. This\n * relies on assumptions of what the \"work\" \"community\"\n * feels \"safe\" talking about. In time, a common set of tags\n * may emerge that allow users to find relays that suit\n * their needs, and client software will be able to parse\n * these tags easily. The `bitcoin-only` tag indicates that\n * any _altcoin_, _\"crypto\"_ or _blockchain_ comments will\n * be ridiculed without mercy.\n * @param posting_policy is a link to a human-readable page\n * which specifies the community policies for the relay. In\n * cases where `sfw-only` is True, it's important to link to\n * a page which gets into the specifics of your posting\n * policy.\n\n * The `description` field should be used to describe your\n * community goals and values, in brief. The\n * `posting_policy` is for additional detail and legal\n * terms. Use the `tags` field to signify limitations on\n * content, or topics to be discussed, which could be\n * machine processed by appropriate client software.\n */\nexport interface CommunityPreferences {\n language_tags: string[]\n tags: string[]\n posting_policy: string\n}\n\nexport interface Amount {\n amount: number\n unit: 'msat'\n}\nexport interface PublicationAmount extends Amount {\n kinds: number[]\n}\nexport interface Subscription extends Amount {\n period: number\n}\nexport interface Fees {\n admission: Amount[]\n subscription: Subscription[]\n publication: PublicationAmount[]\n}\n/**\n * Relays that require payments may want to expose their fee\n * schedules.\n */\nexport interface PayToRelay {\n payments_url: string\n fees: Fees\n}\n\n/**\n * A URL pointing to an image to be used as an icon for the\n * relay. Recommended to be squared in shape.\n */\nexport interface Icon {\n icon: string\n}\n\nexport type RelayInformation = BasicRelayInformation &\n Partial & {\n limitation?: Partial\n } & Partial &\n Partial &\n Partial &\n Partial\n"], + "mappings": ";AAAA,IAAI;AAEJ,IAAI;AACF,WAAS;AACX,QAAE;AAAO;AAEF,SAAS,uBAAuB,qBAAgC;AACrE,WAAS;AACX;AAEA,eAAsB,sBAAsB,KAAwC;AAClF,SAAQ,OACN,MAAM,MAAM,IAAI,QAAQ,SAAS,SAAS,EAAE,QAAQ,UAAU,UAAU,GAAG;AAAA,IACzE,SAAS,EAAE,QAAQ,yBAAyB;AAAA,EAC9C,CAAC,GACD,KAAK;AACT;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/esm/nip13.js b/node_modules/nostr-tools/lib/esm/nip13.js new file mode 100644 index 0000000..3ea8968 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip13.js @@ -0,0 +1,52 @@ +// nip13.ts +import { bytesToHex as bytesToHex2 } from "@noble/hashes/utils"; +import { sha256 } from "@noble/hashes/sha256"; + +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// nip13.ts +function getPow(hex) { + let count = 0; + for (let i = 0; i < 64; i += 8) { + const nibble = parseInt(hex.substring(i, i + 8), 16); + if (nibble === 0) { + count += 32; + } else { + count += Math.clz32(nibble); + break; + } + } + return count; +} +function minePow(unsigned, difficulty) { + let count = 0; + const event = unsigned; + const tag = ["nonce", count.toString(), difficulty.toString()]; + event.tags.push(tag); + while (true) { + const now = Math.floor(new Date().getTime() / 1e3); + if (now !== event.created_at) { + count = 0; + event.created_at = now; + } + tag[1] = (++count).toString(); + event.id = fastEventHash(event); + if (getPow(event.id) >= difficulty) { + break; + } + } + return event; +} +function fastEventHash(evt) { + return bytesToHex2( + sha256(utf8Encoder.encode(JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]))) + ); +} +export { + fastEventHash, + getPow, + minePow +}; diff --git a/node_modules/nostr-tools/lib/esm/nip13.js.map b/node_modules/nostr-tools/lib/esm/nip13.js.map new file mode 100644 index 0000000..f7f098d --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip13.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip13.ts", "../../utils.ts"], + "sourcesContent": ["import { bytesToHex } from '@noble/hashes/utils'\nimport { type UnsignedEvent, type Event } from './pure.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\n/** Get POW difficulty from a Nostr hex ID. */\nexport function getPow(hex: string): number {\n let count = 0\n\n for (let i = 0; i < 64; i += 8) {\n const nibble = parseInt(hex.substring(i, i + 8), 16)\n if (nibble === 0) {\n count += 32\n } else {\n count += Math.clz32(nibble)\n break\n }\n }\n\n return count\n}\n\n/**\n * Mine an event with the desired POW. This function mutates the event.\n * Note that this operation is synchronous and should be run in a worker context to avoid blocking the main thread.\n */\nexport function minePow(unsigned: UnsignedEvent, difficulty: number): Omit {\n let count = 0\n\n const event = unsigned as Omit\n const tag = ['nonce', count.toString(), difficulty.toString()]\n\n event.tags.push(tag)\n\n while (true) {\n const now = Math.floor(new Date().getTime() / 1000)\n\n if (now !== event.created_at) {\n count = 0\n event.created_at = now\n }\n\n tag[1] = (++count).toString()\n\n event.id = fastEventHash(event)\n\n if (getPow(event.id) >= difficulty) {\n break\n }\n }\n\n return event\n}\n\nexport function fastEventHash(evt: UnsignedEvent): string {\n return bytesToHex(\n sha256(utf8Encoder.encode(JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]))),\n )\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n"], + "mappings": ";AAAA,SAAS,cAAAA,mBAAkB;AAE3B,SAAS,cAAc;;;ACGvB,SAAS,YAAY,kBAAkB;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;;;ADIjD,SAAS,OAAO,KAAqB;AAC1C,MAAI,QAAQ;AAEZ,WAAS,IAAI,GAAG,IAAI,IAAI,KAAK,GAAG;AAC9B,UAAM,SAAS,SAAS,IAAI,UAAU,GAAG,IAAI,CAAC,GAAG,EAAE;AACnD,QAAI,WAAW,GAAG;AAChB,eAAS;AAAA,IACX,OAAO;AACL,eAAS,KAAK,MAAM,MAAM;AAC1B;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAMO,SAAS,QAAQ,UAAyB,YAAwC;AACvF,MAAI,QAAQ;AAEZ,QAAM,QAAQ;AACd,QAAM,MAAM,CAAC,SAAS,MAAM,SAAS,GAAG,WAAW,SAAS,CAAC;AAE7D,QAAM,KAAK,KAAK,GAAG;AAEnB,SAAO,MAAM;AACX,UAAM,MAAM,KAAK,MAAM,IAAI,KAAK,EAAE,QAAQ,IAAI,GAAI;AAElD,QAAI,QAAQ,MAAM,YAAY;AAC5B,cAAQ;AACR,YAAM,aAAa;AAAA,IACrB;AAEA,QAAI,MAAM,EAAE,OAAO,SAAS;AAE5B,UAAM,KAAK,cAAc,KAAK;AAE9B,QAAI,OAAO,MAAM,EAAE,KAAK,YAAY;AAClC;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAEO,SAAS,cAAc,KAA4B;AACxD,SAAOC;AAAA,IACL,OAAO,YAAY,OAAO,KAAK,UAAU,CAAC,GAAG,IAAI,QAAQ,IAAI,YAAY,IAAI,MAAM,IAAI,MAAM,IAAI,OAAO,CAAC,CAAC,CAAC;AAAA,EAC7G;AACF;", + "names": ["bytesToHex", "bytesToHex"] +} diff --git a/node_modules/nostr-tools/lib/esm/nip17.js b/node_modules/nostr-tools/lib/esm/nip17.js new file mode 100644 index 0000000..3f9f64b --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip17.js @@ -0,0 +1,298 @@ +// pure.ts +import { schnorr } from "@noble/curves/secp256k1"; +import { bytesToHex as bytesToHex2 } from "@noble/hashes/utils"; + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +import { sha256 } from "@noble/hashes/sha256"; + +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// pure.ts +var JS = class { + generateSecretKey() { + return schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return bytesToHex2(schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = bytesToHex2(schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = bytesToHex2(schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = sha256(utf8Encoder.encode(serializeEvent(event))); + return bytesToHex2(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// kinds.ts +var Seal = 13; +var PrivateDirectMessage = 14; +var GiftWrap = 1059; + +// nip44.ts +import { chacha20 } from "@noble/ciphers/chacha"; +import { equalBytes } from "@noble/ciphers/utils"; +import { secp256k1 } from "@noble/curves/secp256k1"; +import { extract as hkdf_extract, expand as hkdf_expand } from "@noble/hashes/hkdf"; +import { hmac } from "@noble/hashes/hmac"; +import { sha256 as sha2562 } from "@noble/hashes/sha256"; +import { concatBytes, randomBytes } from "@noble/hashes/utils"; +import { base64 } from "@scure/base"; +var minPlaintextSize = 1; +var maxPlaintextSize = 65535; +function getConversationKey(privkeyA, pubkeyB) { + const sharedX = secp256k1.getSharedSecret(privkeyA, "02" + pubkeyB).subarray(1, 33); + return hkdf_extract(sha2562, sharedX, "nip44-v2"); +} +function getMessageKeys(conversationKey, nonce) { + const keys = hkdf_expand(sha2562, conversationKey, nonce, 76); + return { + chacha_key: keys.subarray(0, 32), + chacha_nonce: keys.subarray(32, 44), + hmac_key: keys.subarray(44, 76) + }; +} +function calcPaddedLen(len) { + if (!Number.isSafeInteger(len) || len < 1) + throw new Error("expected positive integer"); + if (len <= 32) + return 32; + const nextPower = 1 << Math.floor(Math.log2(len - 1)) + 1; + const chunk = nextPower <= 256 ? 32 : nextPower / 8; + return chunk * (Math.floor((len - 1) / chunk) + 1); +} +function writeU16BE(num) { + if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize) + throw new Error("invalid plaintext size: must be between 1 and 65535 bytes"); + const arr = new Uint8Array(2); + new DataView(arr.buffer).setUint16(0, num, false); + return arr; +} +function pad(plaintext) { + const unpadded = utf8Encoder.encode(plaintext); + const unpaddedLen = unpadded.length; + const prefix = writeU16BE(unpaddedLen); + const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen); + return concatBytes(prefix, unpadded, suffix); +} +function unpad(padded) { + const unpaddedLen = new DataView(padded.buffer).getUint16(0); + const unpadded = padded.subarray(2, 2 + unpaddedLen); + if (unpaddedLen < minPlaintextSize || unpaddedLen > maxPlaintextSize || unpadded.length !== unpaddedLen || padded.length !== 2 + calcPaddedLen(unpaddedLen)) + throw new Error("invalid padding"); + return utf8Decoder.decode(unpadded); +} +function hmacAad(key, message, aad) { + if (aad.length !== 32) + throw new Error("AAD associated data must be 32 bytes"); + const combined = concatBytes(aad, message); + return hmac(sha2562, key, combined); +} +function decodePayload(payload) { + if (typeof payload !== "string") + throw new Error("payload must be a valid string"); + const plen = payload.length; + if (plen < 132 || plen > 87472) + throw new Error("invalid payload length: " + plen); + if (payload[0] === "#") + throw new Error("unknown encryption version"); + let data; + try { + data = base64.decode(payload); + } catch (error) { + throw new Error("invalid base64: " + error.message); + } + const dlen = data.length; + if (dlen < 99 || dlen > 65603) + throw new Error("invalid data length: " + dlen); + const vers = data[0]; + if (vers !== 2) + throw new Error("unknown encryption version " + vers); + return { + nonce: data.subarray(1, 33), + ciphertext: data.subarray(33, -32), + mac: data.subarray(-32) + }; +} +function encrypt(plaintext, conversationKey, nonce = randomBytes(32)) { + const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); + const padded = pad(plaintext); + const ciphertext = chacha20(chacha_key, chacha_nonce, padded); + const mac = hmacAad(hmac_key, ciphertext, nonce); + return base64.encode(concatBytes(new Uint8Array([2]), nonce, ciphertext, mac)); +} +function decrypt(payload, conversationKey) { + const { nonce, ciphertext, mac } = decodePayload(payload); + const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); + const calculatedMac = hmacAad(hmac_key, ciphertext, nonce); + if (!equalBytes(calculatedMac, mac)) + throw new Error("invalid MAC"); + const padded = chacha20(chacha_key, chacha_nonce, ciphertext); + return unpad(padded); +} + +// nip59.ts +var TWO_DAYS = 2 * 24 * 60 * 60; +var now = () => Math.round(Date.now() / 1e3); +var randomNow = () => Math.round(now() - Math.random() * TWO_DAYS); +var nip44ConversationKey = (privateKey, publicKey) => getConversationKey(privateKey, publicKey); +var nip44Encrypt = (data, privateKey, publicKey) => encrypt(JSON.stringify(data), nip44ConversationKey(privateKey, publicKey)); +var nip44Decrypt = (data, privateKey) => JSON.parse(decrypt(data.content, nip44ConversationKey(privateKey, data.pubkey))); +function createRumor(event, privateKey) { + const rumor = { + created_at: now(), + content: "", + tags: [], + ...event, + pubkey: getPublicKey(privateKey) + }; + rumor.id = getEventHash(rumor); + return rumor; +} +function createSeal(rumor, privateKey, recipientPublicKey) { + return finalizeEvent( + { + kind: Seal, + content: nip44Encrypt(rumor, privateKey, recipientPublicKey), + created_at: randomNow(), + tags: [] + }, + privateKey + ); +} +function createWrap(seal, recipientPublicKey) { + const randomKey = generateSecretKey(); + return finalizeEvent( + { + kind: GiftWrap, + content: nip44Encrypt(seal, randomKey, recipientPublicKey), + created_at: randomNow(), + tags: [["p", recipientPublicKey]] + }, + randomKey + ); +} +function wrapEvent(event, senderPrivateKey, recipientPublicKey) { + const rumor = createRumor(event, senderPrivateKey); + const seal = createSeal(rumor, senderPrivateKey, recipientPublicKey); + return createWrap(seal, recipientPublicKey); +} +function unwrapEvent(wrap, recipientPrivateKey) { + const unwrappedSeal = nip44Decrypt(wrap, recipientPrivateKey); + return nip44Decrypt(unwrappedSeal, recipientPrivateKey); +} +function unwrapManyEvents(wrappedEvents, recipientPrivateKey) { + let unwrappedEvents = []; + wrappedEvents.forEach((e) => { + unwrappedEvents.push(unwrapEvent(e, recipientPrivateKey)); + }); + unwrappedEvents.sort((a, b) => a.created_at - b.created_at); + return unwrappedEvents; +} + +// nip17.ts +function createEvent(recipients, message, conversationTitle, replyTo) { + const baseEvent = { + created_at: Math.ceil(Date.now() / 1e3), + kind: PrivateDirectMessage, + tags: [], + content: message + }; + const recipientsArray = Array.isArray(recipients) ? recipients : [recipients]; + recipientsArray.forEach(({ publicKey, relayUrl }) => { + baseEvent.tags.push(relayUrl ? ["p", publicKey, relayUrl] : ["p", publicKey]); + }); + if (replyTo) { + baseEvent.tags.push(["e", replyTo.eventId, replyTo.relayUrl || "", "reply"]); + } + if (conversationTitle) { + baseEvent.tags.push(["subject", conversationTitle]); + } + return baseEvent; +} +function wrapEvent2(senderPrivateKey, recipient, message, conversationTitle, replyTo) { + const event = createEvent(recipient, message, conversationTitle, replyTo); + return wrapEvent(event, senderPrivateKey, recipient.publicKey); +} +function wrapManyEvents(senderPrivateKey, recipients, message, conversationTitle, replyTo) { + if (!recipients || recipients.length === 0) { + throw new Error("At least one recipient is required."); + } + const senderPublicKey = getPublicKey(senderPrivateKey); + return [{ publicKey: senderPublicKey }, ...recipients].map( + (recipient) => wrapEvent2(senderPrivateKey, recipient, message, conversationTitle, replyTo) + ); +} +var unwrapEvent2 = unwrapEvent; +var unwrapManyEvents2 = unwrapManyEvents; +export { + unwrapEvent2 as unwrapEvent, + unwrapManyEvents2 as unwrapManyEvents, + wrapEvent2 as wrapEvent, + wrapManyEvents +}; diff --git a/node_modules/nostr-tools/lib/esm/nip17.js.map b/node_modules/nostr-tools/lib/esm/nip17.js.map new file mode 100644 index 0000000..7ba313d --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip17.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../pure.ts", "../../core.ts", "../../utils.ts", "../../kinds.ts", "../../nip44.ts", "../../nip59.ts", "../../nip17.ts"], + "sourcesContent": ["import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { chacha20 } from '@noble/ciphers/chacha'\nimport { equalBytes } from '@noble/ciphers/utils'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { extract as hkdf_extract, expand as hkdf_expand } from '@noble/hashes/hkdf'\nimport { hmac } from '@noble/hashes/hmac'\nimport { sha256 } from '@noble/hashes/sha256'\nimport { concatBytes, randomBytes } from '@noble/hashes/utils'\nimport { base64 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nconst minPlaintextSize = 0x0001 // 1b msg => padded to 32b\nconst maxPlaintextSize = 0xffff // 65535 (64kb-1) => padded to 64kb\n\nexport function getConversationKey(privkeyA: Uint8Array, pubkeyB: string): Uint8Array {\n const sharedX = secp256k1.getSharedSecret(privkeyA, '02' + pubkeyB).subarray(1, 33)\n return hkdf_extract(sha256, sharedX, 'nip44-v2')\n}\n\nfunction getMessageKeys(\n conversationKey: Uint8Array,\n nonce: Uint8Array,\n): { chacha_key: Uint8Array; chacha_nonce: Uint8Array; hmac_key: Uint8Array } {\n const keys = hkdf_expand(sha256, conversationKey, nonce, 76)\n return {\n chacha_key: keys.subarray(0, 32),\n chacha_nonce: keys.subarray(32, 44),\n hmac_key: keys.subarray(44, 76),\n }\n}\n\nfunction calcPaddedLen(len: number): number {\n if (!Number.isSafeInteger(len) || len < 1) throw new Error('expected positive integer')\n if (len <= 32) return 32\n const nextPower = 1 << (Math.floor(Math.log2(len - 1)) + 1)\n const chunk = nextPower <= 256 ? 32 : nextPower / 8\n return chunk * (Math.floor((len - 1) / chunk) + 1)\n}\n\nfunction writeU16BE(num: number): Uint8Array {\n if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize)\n throw new Error('invalid plaintext size: must be between 1 and 65535 bytes')\n const arr = new Uint8Array(2)\n new DataView(arr.buffer).setUint16(0, num, false)\n return arr\n}\n\nfunction pad(plaintext: string): Uint8Array {\n const unpadded = utf8Encoder.encode(plaintext)\n const unpaddedLen = unpadded.length\n const prefix = writeU16BE(unpaddedLen)\n const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen)\n return concatBytes(prefix, unpadded, suffix)\n}\n\nfunction unpad(padded: Uint8Array): string {\n const unpaddedLen = new DataView(padded.buffer).getUint16(0)\n const unpadded = padded.subarray(2, 2 + unpaddedLen)\n if (\n unpaddedLen < minPlaintextSize ||\n unpaddedLen > maxPlaintextSize ||\n unpadded.length !== unpaddedLen ||\n padded.length !== 2 + calcPaddedLen(unpaddedLen)\n )\n throw new Error('invalid padding')\n return utf8Decoder.decode(unpadded)\n}\n\nfunction hmacAad(key: Uint8Array, message: Uint8Array, aad: Uint8Array): Uint8Array {\n if (aad.length !== 32) throw new Error('AAD associated data must be 32 bytes')\n const combined = concatBytes(aad, message)\n return hmac(sha256, key, combined)\n}\n\n// metadata: always 65b (version: 1b, nonce: 32b, max: 32b)\n// plaintext: 1b to 0xffff\n// padded plaintext: 32b to 0xffff\n// ciphertext: 32b+2 to 0xffff+2\n// raw payload: 99 (65+32+2) to 65603 (65+0xffff+2)\n// compressed payload (base64): 132b to 87472b\nfunction decodePayload(payload: string): { nonce: Uint8Array; ciphertext: Uint8Array; mac: Uint8Array } {\n if (typeof payload !== 'string') throw new Error('payload must be a valid string')\n const plen = payload.length\n if (plen < 132 || plen > 87472) throw new Error('invalid payload length: ' + plen)\n if (payload[0] === '#') throw new Error('unknown encryption version')\n let data: Uint8Array\n try {\n data = base64.decode(payload)\n } catch (error) {\n throw new Error('invalid base64: ' + (error as any).message)\n }\n const dlen = data.length\n if (dlen < 99 || dlen > 65603) throw new Error('invalid data length: ' + dlen)\n const vers = data[0]\n if (vers !== 2) throw new Error('unknown encryption version ' + vers)\n return {\n nonce: data.subarray(1, 33),\n ciphertext: data.subarray(33, -32),\n mac: data.subarray(-32),\n }\n}\n\nexport function encrypt(plaintext: string, conversationKey: Uint8Array, nonce: Uint8Array = randomBytes(32)): string {\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n const padded = pad(plaintext)\n const ciphertext = chacha20(chacha_key, chacha_nonce, padded)\n const mac = hmacAad(hmac_key, ciphertext, nonce)\n return base64.encode(concatBytes(new Uint8Array([2]), nonce, ciphertext, mac))\n}\n\nexport function decrypt(payload: string, conversationKey: Uint8Array): string {\n const { nonce, ciphertext, mac } = decodePayload(payload)\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n const calculatedMac = hmacAad(hmac_key, ciphertext, nonce)\n if (!equalBytes(calculatedMac, mac)) throw new Error('invalid MAC')\n const padded = chacha20(chacha_key, chacha_nonce, ciphertext)\n return unpad(padded)\n}\n\nexport const v2 = {\n utils: {\n getConversationKey,\n calcPaddedLen,\n },\n encrypt,\n decrypt,\n}\n", "import { EventTemplate, UnsignedEvent, NostrEvent } from './core.ts'\nimport { getConversationKey, decrypt, encrypt } from './nip44.ts'\nimport { getEventHash, generateSecretKey, finalizeEvent, getPublicKey } from './pure.ts'\nimport { Seal, GiftWrap } from './kinds.ts'\n\ntype Rumor = UnsignedEvent & { id: string }\n\nconst TWO_DAYS = 2 * 24 * 60 * 60\n\nconst now = () => Math.round(Date.now() / 1000)\nconst randomNow = () => Math.round(now() - Math.random() * TWO_DAYS)\n\nconst nip44ConversationKey = (privateKey: Uint8Array, publicKey: string) => getConversationKey(privateKey, publicKey)\n\nconst nip44Encrypt = (data: EventTemplate, privateKey: Uint8Array, publicKey: string) =>\n encrypt(JSON.stringify(data), nip44ConversationKey(privateKey, publicKey))\n\nconst nip44Decrypt = (data: NostrEvent, privateKey: Uint8Array) =>\n JSON.parse(decrypt(data.content, nip44ConversationKey(privateKey, data.pubkey)))\n\nexport function createRumor(event: Partial, privateKey: Uint8Array): Rumor {\n const rumor = {\n created_at: now(),\n content: '',\n tags: [],\n ...event,\n pubkey: getPublicKey(privateKey),\n } as any\n\n rumor.id = getEventHash(rumor)\n\n return rumor as Rumor\n}\n\nexport function createSeal(rumor: Rumor, privateKey: Uint8Array, recipientPublicKey: string): NostrEvent {\n return finalizeEvent(\n {\n kind: Seal,\n content: nip44Encrypt(rumor, privateKey, recipientPublicKey),\n created_at: randomNow(),\n tags: [],\n },\n privateKey,\n )\n}\n\nexport function createWrap(seal: NostrEvent, recipientPublicKey: string): NostrEvent {\n const randomKey = generateSecretKey()\n\n return finalizeEvent(\n {\n kind: GiftWrap,\n content: nip44Encrypt(seal, randomKey, recipientPublicKey),\n created_at: randomNow(),\n tags: [['p', recipientPublicKey]],\n },\n randomKey,\n ) as NostrEvent\n}\n\nexport function wrapEvent(\n event: Partial,\n senderPrivateKey: Uint8Array,\n recipientPublicKey: string,\n): NostrEvent {\n const rumor = createRumor(event, senderPrivateKey)\n\n const seal = createSeal(rumor, senderPrivateKey, recipientPublicKey)\n return createWrap(seal, recipientPublicKey)\n}\n\nexport function wrapManyEvents(\n event: Partial,\n senderPrivateKey: Uint8Array,\n recipientsPublicKeys: string[],\n): NostrEvent[] {\n if (!recipientsPublicKeys || recipientsPublicKeys.length === 0) {\n throw new Error('At least one recipient is required.')\n }\n\n const senderPublicKey = getPublicKey(senderPrivateKey)\n\n const wrappeds = [wrapEvent(event, senderPrivateKey, senderPublicKey)]\n\n recipientsPublicKeys.forEach(recipientPublicKey => {\n wrappeds.push(wrapEvent(event, senderPrivateKey, recipientPublicKey))\n })\n\n return wrappeds\n}\n\nexport function unwrapEvent(wrap: NostrEvent, recipientPrivateKey: Uint8Array): Rumor {\n const unwrappedSeal = nip44Decrypt(wrap, recipientPrivateKey)\n return nip44Decrypt(unwrappedSeal, recipientPrivateKey)\n}\n\nexport function unwrapManyEvents(wrappedEvents: NostrEvent[], recipientPrivateKey: Uint8Array): Rumor[] {\n let unwrappedEvents: Rumor[] = []\n\n wrappedEvents.forEach(e => {\n unwrappedEvents.push(unwrapEvent(e, recipientPrivateKey))\n })\n\n unwrappedEvents.sort((a, b) => a.created_at - b.created_at)\n\n return unwrappedEvents\n}\n", "import { PrivateDirectMessage } from './kinds.ts'\nimport { EventTemplate, NostrEvent, getPublicKey } from './pure.ts'\nimport * as nip59 from './nip59.ts'\n\ntype Recipient = {\n publicKey: string\n relayUrl?: string\n}\n\ntype ReplyTo = {\n eventId: string\n relayUrl?: string\n}\n\nfunction createEvent(\n recipients: Recipient | Recipient[],\n message: string,\n conversationTitle?: string,\n replyTo?: ReplyTo,\n): EventTemplate {\n const baseEvent: EventTemplate = {\n created_at: Math.ceil(Date.now() / 1000),\n kind: PrivateDirectMessage,\n tags: [],\n content: message,\n }\n\n const recipientsArray = Array.isArray(recipients) ? recipients : [recipients]\n\n recipientsArray.forEach(({ publicKey, relayUrl }) => {\n baseEvent.tags.push(relayUrl ? ['p', publicKey, relayUrl] : ['p', publicKey])\n })\n\n if (replyTo) {\n baseEvent.tags.push(['e', replyTo.eventId, replyTo.relayUrl || '', 'reply'])\n }\n\n if (conversationTitle) {\n baseEvent.tags.push(['subject', conversationTitle])\n }\n\n return baseEvent\n}\n\nexport function wrapEvent(\n senderPrivateKey: Uint8Array,\n recipient: Recipient,\n message: string,\n conversationTitle?: string,\n replyTo?: ReplyTo,\n): NostrEvent {\n const event = createEvent(recipient, message, conversationTitle, replyTo)\n return nip59.wrapEvent(event, senderPrivateKey, recipient.publicKey)\n}\n\nexport function wrapManyEvents(\n senderPrivateKey: Uint8Array,\n recipients: Recipient[],\n message: string,\n conversationTitle?: string,\n replyTo?: ReplyTo,\n): NostrEvent[] {\n if (!recipients || recipients.length === 0) {\n throw new Error('At least one recipient is required.')\n }\n\n const senderPublicKey = getPublicKey(senderPrivateKey)\n\n // wrap the event for the sender and then for each recipient\n return [{ publicKey: senderPublicKey }, ...recipients].map(recipient =>\n wrapEvent(senderPrivateKey, recipient, message, conversationTitle, replyTo),\n )\n}\n\nexport const unwrapEvent = nip59.unwrapEvent\n\nexport const unwrapManyEvents = nip59.unwrapManyEvents\n"], + "mappings": ";AAAA,SAAS,eAAe;AACxB,SAAS,cAAAA,mBAAkB;;;ACOpB,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,CAAC,QAAiD,eAAe;AAE3E,SAAS,cAAiB,OAAsC;AACrE,MAAI,CAAC,SAAS,KAAK;AAAG,WAAO;AAC7B,MAAI,OAAO,MAAM,SAAS;AAAU,WAAO;AAC3C,MAAI,OAAO,MAAM,YAAY;AAAU,WAAO;AAC9C,MAAI,OAAO,MAAM,eAAe;AAAU,WAAO;AACjD,MAAI,OAAO,MAAM,WAAW;AAAU,WAAO;AAC7C,MAAI,CAAC,MAAM,OAAO,MAAM,gBAAgB;AAAG,WAAO;AAElD,MAAI,CAAC,MAAM,QAAQ,MAAM,IAAI;AAAG,WAAO;AACvC,WAASC,KAAI,GAAGA,KAAI,MAAM,KAAK,Q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M,IAAI,MAAM,qCAAqC;AAAA,EACvD;AAEA,QAAM,kBAAkB,aAAa,gBAAgB;AAGrD,SAAO,CAAC,EAAE,WAAW,gBAAgB,GAAG,GAAG,UAAU,EAAE;AAAA,IAAI,eACzDA,WAAU,kBAAkB,WAAW,SAAS,mBAAmB,OAAO;AAAA,EAC5E;AACF;AAEO,IAAMC,eAAoB;AAE1B,IAAMC,oBAAyB;", + "names": ["bytesToHex", "i", "bytesToHex", "sha256", "sha256", "wrapEvent", "unwrapEvent", "unwrapManyEvents"] +} diff --git a/node_modules/nostr-tools/lib/esm/nip18.js b/node_modules/nostr-tools/lib/esm/nip18.js new file mode 100644 index 0000000..91f2f0e --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip18.js @@ -0,0 +1,165 @@ +// pure.ts +import { schnorr } from "@noble/curves/secp256k1"; +import { bytesToHex as bytesToHex2 } from "@noble/hashes/utils"; + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +import { sha256 } from "@noble/hashes/sha256"; + +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// pure.ts +var JS = class { + generateSecretKey() { + return schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return bytesToHex2(schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = bytesToHex2(schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = bytesToHex2(schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = sha256(utf8Encoder.encode(serializeEvent(event))); + return bytesToHex2(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// kinds.ts +var ShortTextNote = 1; +var Repost = 6; +var GenericRepost = 16; + +// nip18.ts +function finishRepostEvent(t, reposted, relayUrl, privateKey) { + let kind; + const tags = [...t.tags ?? [], ["e", reposted.id, relayUrl], ["p", reposted.pubkey]]; + if (reposted.kind === ShortTextNote) { + kind = Repost; + } else { + kind = GenericRepost; + tags.push(["k", String(reposted.kind)]); + } + return finalizeEvent( + { + kind, + tags, + content: t.content === "" || reposted.tags?.find((tag) => tag[0] === "-") ? "" : JSON.stringify(reposted), + created_at: t.created_at + }, + privateKey + ); +} +function getRepostedEventPointer(event) { + if (![Repost, GenericRepost].includes(event.kind)) { + return void 0; + } + let lastETag; + let lastPTag; + for (let i2 = event.tags.length - 1; i2 >= 0 && (lastETag === void 0 || lastPTag === void 0); i2--) { + const tag = event.tags[i2]; + if (tag.length >= 2) { + if (tag[0] === "e" && lastETag === void 0) { + lastETag = tag; + } else if (tag[0] === "p" && lastPTag === void 0) { + lastPTag = tag; + } + } + } + if (lastETag === void 0) { + return void 0; + } + return { + id: lastETag[1], + relays: [lastETag[2], lastPTag?.[2]].filter((x) => typeof x === "string"), + author: lastPTag?.[1] + }; +} +function getRepostedEvent(event, { skipVerification } = {}) { + const pointer = getRepostedEventPointer(event); + if (pointer === void 0 || event.content === "") { + return void 0; + } + let repostedEvent; + try { + repostedEvent = JSON.parse(event.content); + } catch (error) { + return void 0; + } + if (repostedEvent.id !== pointer.id) { + return void 0; + } + if (!skipVerification && !verifyEvent(repostedEvent)) { + return void 0; + } + return repostedEvent; +} +export { + finishRepostEvent, + getRepostedEvent, + getRepostedEventPointer +}; diff --git a/node_modules/nostr-tools/lib/esm/nip18.js.map b/node_modules/nostr-tools/lib/esm/nip18.js.map new file mode 100644 index 0000000..c2f0051 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip18.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../pure.ts", "../../core.ts", "../../utils.ts", "../../kinds.ts", "../../nip18.ts"], + "sourcesContent": ["import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { GenericRepost, Repost, ShortTextNote } from './kinds.ts'\nimport { EventPointer } from './nip19.ts'\nimport { Event, finalizeEvent, verifyEvent } from './pure.ts'\n\nexport type RepostEventTemplate = {\n /**\n * Pass only non-nip18 tags if you have to.\n * Nip18 tags ('e' and 'p' tags pointing to the reposted event) will be added automatically.\n */\n tags?: string[][]\n\n /**\n * Pass an empty string to NOT include the stringified JSON of the reposted event.\n * Any other content will be ignored and replaced with the stringified JSON of the reposted event.\n * @default Stringified JSON of the reposted event\n */\n content?: ''\n\n created_at: number\n}\n\nexport function finishRepostEvent(\n t: RepostEventTemplate,\n reposted: Event,\n relayUrl: string,\n privateKey: Uint8Array,\n): Event {\n let kind: Repost | GenericRepost\n const tags = [...(t.tags ?? []), ['e', reposted.id, relayUrl], ['p', reposted.pubkey]]\n if (reposted.kind === ShortTextNote) {\n kind = Repost\n } else {\n kind = GenericRepost\n tags.push(['k', String(reposted.kind)])\n }\n\n return finalizeEvent(\n {\n kind,\n tags,\n content: t.content === '' || reposted.tags?.find(tag => tag[0] === '-') ? '' : JSON.stringify(reposted),\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\nexport function getRepostedEventPointer(event: Event): undefined | EventPointer {\n if (![Repost, GenericRepost].includes(event.kind)) {\n return undefined\n }\n\n let lastETag: undefined | string[]\n let lastPTag: undefined | string[]\n\n for (let i = event.tags.length - 1; i >= 0 && (lastETag === undefined || lastPTag === undefined); i--) {\n const tag = event.tags[i]\n if (tag.length >= 2) {\n if (tag[0] === 'e' && lastETag === undefined) {\n lastETag = tag\n } else if (tag[0] === 'p' && lastPTag === undefined) {\n lastPTag = tag\n }\n }\n }\n\n if (lastETag === undefined) {\n return undefined\n }\n\n return {\n id: lastETag[1],\n relays: [lastETag[2], lastPTag?.[2]].filter((x): x is string => typeof x === 'string'),\n author: lastPTag?.[1],\n }\n}\n\nexport type GetRepostedEventOptions = {\n skipVerification?: boolean\n}\n\nexport function getRepostedEvent(event: Event, { skipVerification }: GetRepostedEventOptions = {}): undefined | Event {\n const pointer = getRepostedEventPointer(event)\n\n if (pointer === undefined || event.content === '') {\n return undefined\n }\n\n let repostedEvent: undefined | Event\n\n try {\n repostedEvent = JSON.parse(event.content) as Event\n } catch (error) {\n return undefined\n }\n\n if (repostedEvent.id !== pointer.id) {\n return undefined\n }\n\n if (!skipVerification && !verifyEvent(repostedEvent)) {\n return undefined\n }\n\n return repostedEvent\n}\n"], + "mappings": ";AAAA,SAAS,eAAe;AACxB,SAAS,cAAAA,mBAAkB;;;ACOpB,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,CAAC,QAAiD,eAAe;AAE3E,SAAS,cAAiB,OAAsC;AACrE,MAAI,CAAC,SAAS,KAAK;AAAG,WAAO;AAC7B,MAAI,OAAO,MAAM,SAAS;AAAU,WAAO;AAC3C,MAAI,OAAO,MAAM,YAAY;AAAU,WAAO;AAC9C,MAAI,OAAO,MAAM,eAAe;AAAU,WAAO;AACjD,MAAI,OAAO,MAAM,WAAW;AAAU,WAAO;AAC7C,MAAI,CAAC,MAAM,OAAO,MAAM,gBAAgB;AAAG,WAAO;AAElD,MAAI,CAAC,MAAM,QAAQ,MAAM,IAAI;AAAG,WAAO;AACvC,WAASC,KAAI,GAAGA,KAAI,MAAM,KAAK,QAAQA,MAAK;AAC1C,QAAI,MAAM,MAAM,KAAKA;AACrB,QAAI,CAAC,MAAM,QAAQ,GAAG;AAAG,aAAO;AAChC,aAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,UAAI,OAAO,IAAI,OAAO;AAAU,eAAO;AAAA,IACzC;AAAA,EACF;AAEA,SAAO;AACT;;;AD/CA,SAAS,cAAc;;;AEEvB,SAAS,YAAY,kBAAkB;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B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AAAA,IACrF,QAAQ,WAAW;AAAA,EACrB;AACF;AAMO,SAAS,iBAAiB,OAAc,EAAE,iBAAiB,IAA6B,CAAC,GAAsB;AACpH,QAAM,UAAU,wBAAwB,KAAK;AAE7C,MAAI,YAAY,UAAa,MAAM,YAAY,IAAI;AACjD,WAAO;AAAA,EACT;AAEA,MAAI;AAEJ,MAAI;AACF,oBAAgB,KAAK,MAAM,MAAM,OAAO;AAAA,EAC1C,SAAS,OAAP;AACA,WAAO;AAAA,EACT;AAEA,MAAI,cAAc,OAAO,QAAQ,IAAI;AACnC,WAAO;AAAA,EACT;AAEA,MAAI,CAAC,oBAAoB,CAAC,YAAY,aAAa,GAAG;AACpD,WAAO;AAAA,EACT;AAEA,SAAO;AACT;", + "names": ["bytesToHex", "i", "bytesToHex", "i"] +} diff --git a/node_modules/nostr-tools/lib/esm/nip19.js b/node_modules/nostr-tools/lib/esm/nip19.js new file mode 100644 index 0000000..384c548 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip19.js @@ -0,0 +1,196 @@ +// nip19.ts +import { bytesToHex as bytesToHex2, concatBytes, hexToBytes as hexToBytes2 } from "@noble/hashes/utils"; +import { bech32 } from "@scure/base"; + +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// nip19.ts +var NostrTypeGuard = { + isNProfile: (value) => /^nprofile1[a-z\d]+$/.test(value || ""), + isNEvent: (value) => /^nevent1[a-z\d]+$/.test(value || ""), + isNAddr: (value) => /^naddr1[a-z\d]+$/.test(value || ""), + isNSec: (value) => /^nsec1[a-z\d]{58}$/.test(value || ""), + isNPub: (value) => /^npub1[a-z\d]{58}$/.test(value || ""), + isNote: (value) => /^note1[a-z\d]+$/.test(value || ""), + isNcryptsec: (value) => /^ncryptsec1[a-z\d]+$/.test(value || "") +}; +var Bech32MaxSize = 5e3; +var BECH32_REGEX = /[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/; +function integerToUint8Array(number) { + const uint8Array = new Uint8Array(4); + uint8Array[0] = number >> 24 & 255; + uint8Array[1] = number >> 16 & 255; + uint8Array[2] = number >> 8 & 255; + uint8Array[3] = number & 255; + return uint8Array; +} +function decodeNostrURI(nip19code) { + try { + if (nip19code.startsWith("nostr:")) + nip19code = nip19code.substring(6); + return decode(nip19code); + } catch (_err) { + return { type: "invalid", data: null }; + } +} +function decode(code) { + let { prefix, words } = bech32.decode(code, Bech32MaxSize); + let data = new Uint8Array(bech32.fromWords(words)); + switch (prefix) { + case "nprofile": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nprofile"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + return { + type: "nprofile", + data: { + pubkey: bytesToHex2(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nevent": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nevent"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + if (tlv[2] && tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (tlv[3] && tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "nevent", + data: { + id: bytesToHex2(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [], + author: tlv[2]?.[0] ? bytesToHex2(tlv[2][0]) : void 0, + kind: tlv[3]?.[0] ? parseInt(bytesToHex2(tlv[3][0]), 16) : void 0 + } + }; + } + case "naddr": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for naddr"); + if (!tlv[2]?.[0]) + throw new Error("missing TLV 2 for naddr"); + if (tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (!tlv[3]?.[0]) + throw new Error("missing TLV 3 for naddr"); + if (tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "naddr", + data: { + identifier: utf8Decoder.decode(tlv[0][0]), + pubkey: bytesToHex2(tlv[2][0]), + kind: parseInt(bytesToHex2(tlv[3][0]), 16), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nsec": + return { type: prefix, data }; + case "npub": + case "note": + return { type: prefix, data: bytesToHex2(data) }; + default: + throw new Error(`unknown prefix ${prefix}`); + } +} +function parseTLV(data) { + let result = {}; + let rest = data; + while (rest.length > 0) { + let t = rest[0]; + let l = rest[1]; + let v = rest.slice(2, 2 + l); + rest = rest.slice(2 + l); + if (v.length < l) + throw new Error(`not enough data to read on TLV ${t}`); + result[t] = result[t] || []; + result[t].push(v); + } + return result; +} +function nsecEncode(key) { + return encodeBytes("nsec", key); +} +function npubEncode(hex) { + return encodeBytes("npub", hexToBytes2(hex)); +} +function noteEncode(hex) { + return encodeBytes("note", hexToBytes2(hex)); +} +function encodeBech32(prefix, data) { + let words = bech32.toWords(data); + return bech32.encode(prefix, words, Bech32MaxSize); +} +function encodeBytes(prefix, bytes) { + return encodeBech32(prefix, bytes); +} +function nprofileEncode(profile) { + let data = encodeTLV({ + 0: [hexToBytes2(profile.pubkey)], + 1: (profile.relays || []).map((url) => utf8Encoder.encode(url)) + }); + return encodeBech32("nprofile", data); +} +function neventEncode(event) { + let kindArray; + if (event.kind !== void 0) { + kindArray = integerToUint8Array(event.kind); + } + let data = encodeTLV({ + 0: [hexToBytes2(event.id)], + 1: (event.relays || []).map((url) => utf8Encoder.encode(url)), + 2: event.author ? [hexToBytes2(event.author)] : [], + 3: kindArray ? [new Uint8Array(kindArray)] : [] + }); + return encodeBech32("nevent", data); +} +function naddrEncode(addr) { + let kind = new ArrayBuffer(4); + new DataView(kind).setUint32(0, addr.kind, false); + let data = encodeTLV({ + 0: [utf8Encoder.encode(addr.identifier)], + 1: (addr.relays || []).map((url) => utf8Encoder.encode(url)), + 2: [hexToBytes2(addr.pubkey)], + 3: [new Uint8Array(kind)] + }); + return encodeBech32("naddr", data); +} +function encodeTLV(tlv) { + let entries = []; + Object.entries(tlv).reverse().forEach(([t, vs]) => { + vs.forEach((v) => { + let entry = new Uint8Array(v.length + 2); + entry.set([parseInt(t)], 0); + entry.set([v.length], 1); + entry.set(v, 2); + entries.push(entry); + }); + }); + return concatBytes(...entries); +} +export { + BECH32_REGEX, + Bech32MaxSize, + NostrTypeGuard, + decode, + decodeNostrURI, + encodeBytes, + naddrEncode, + neventEncode, + noteEncode, + nprofileEncode, + npubEncode, + nsecEncode +}; diff --git a/node_modules/nostr-tools/lib/esm/nip19.js.map b/node_modules/nostr-tools/lib/esm/nip19.js.map new file mode 100644 index 0000000..d3e0a4b --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip19.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip19.ts", "../../utils.ts"], + "sourcesContent": ["import { bytesToHex, concatBytes, hexToBytes } from '@noble/hashes/utils'\nimport { bech32 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport type NProfile = `nprofile1${string}`\nexport type NEvent = `nevent1${string}`\nexport type NAddr = `naddr1${string}`\nexport type NSec = `nsec1${string}`\nexport type NPub = `npub1${string}`\nexport type Note = `note1${string}`\nexport type Ncryptsec = `ncryptsec1${string}`\n\nexport const NostrTypeGuard = {\n isNProfile: (value?: string | null): value is NProfile => /^nprofile1[a-z\\d]+$/.test(value || ''),\n isNEvent: (value?: string | null): value is NEvent => /^nevent1[a-z\\d]+$/.test(value || ''),\n isNAddr: (value?: string | null): value is NAddr => /^naddr1[a-z\\d]+$/.test(value || ''),\n isNSec: (value?: string | null): value is NSec => /^nsec1[a-z\\d]{58}$/.test(value || ''),\n isNPub: (value?: string | null): value is NPub => /^npub1[a-z\\d]{58}$/.test(value || ''),\n isNote: (value?: string | null): value is Note => /^note1[a-z\\d]+$/.test(value || ''),\n isNcryptsec: (value?: string | null): value is Ncryptsec => /^ncryptsec1[a-z\\d]+$/.test(value || ''),\n}\n\nexport const Bech32MaxSize = 5000\n\n/**\n * Bech32 regex.\n * @see https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32\n */\nexport const BECH32_REGEX = /[\\x21-\\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/\n\nfunction integerToUint8Array(number: number) {\n // Create a Uint8Array with enough space to hold a 32-bit integer (4 bytes).\n const uint8Array = new Uint8Array(4)\n\n // Use bitwise operations to extract the bytes.\n uint8Array[0] = (number >> 24) & 0xff // Most significant byte (MSB)\n uint8Array[1] = (number >> 16) & 0xff\n uint8Array[2] = (number >> 8) & 0xff\n uint8Array[3] = number & 0xff // Least significant byte (LSB)\n\n return uint8Array\n}\n\nexport type ProfilePointer = {\n pubkey: string // hex\n relays?: string[]\n}\n\nexport type EventPointer = {\n id: string // hex\n relays?: string[]\n author?: string\n kind?: number\n}\n\nexport type AddressPointer = {\n identifier: string\n pubkey: string\n kind: number\n relays?: string[]\n}\n\nexport function decodeNostrURI(nip19code: string): ReturnType | { type: 'invalid'; data: null } {\n try {\n if (nip19code.startsWith('nostr:')) nip19code = nip19code.substring(6)\n return decode(nip19code)\n } catch (_err) {\n return { type: 'invalid', data: null }\n }\n}\n\nexport type DecodedNevent = {\n type: 'nevent'\n data: EventPointer\n}\n\nexport type DecodedNprofile = {\n type: 'nprofile'\n data: ProfilePointer\n}\n\nexport type DecodedNaddr = {\n type: 'naddr'\n data: AddressPointer\n}\n\nexport type DecodedNsec = {\n type: 'nsec'\n data: Uint8Array\n}\n\nexport type DecodedNpub = {\n type: 'npub'\n data: string\n}\n\nexport type DecodedNote = {\n type: 'note'\n data: string\n}\n\nexport type DecodedResult = DecodedNevent | DecodedNprofile | DecodedNaddr | DecodedNpub | DecodedNsec | DecodedNote\n\nexport function decode(nip19: NEvent): DecodedNevent\nexport function decode(nip19: NProfile): DecodedNprofile\nexport function decode(nip19: NAddr): DecodedNaddr\nexport function decode(nip19: NSec): DecodedNsec\nexport function decode(nip19: NPub): DecodedNpub\nexport function decode(nip19: Note): DecodedNote\nexport function decode(code: string): DecodedResult\nexport function decode(code: string): DecodedResult {\n let { prefix, words } = bech32.decode(code, Bech32MaxSize)\n let data = new Uint8Array(bech32.fromWords(words))\n\n switch (prefix) {\n case 'nprofile': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nprofile')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n\n return {\n type: 'nprofile',\n data: {\n pubkey: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n case 'nevent': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nevent')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n if (tlv[2] && tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (tlv[3] && tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'nevent',\n data: {\n id: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n author: tlv[2]?.[0] ? bytesToHex(tlv[2][0]) : undefined,\n kind: tlv[3]?.[0] ? parseInt(bytesToHex(tlv[3][0]), 16) : undefined,\n },\n }\n }\n\n case 'naddr': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for naddr')\n if (!tlv[2]?.[0]) throw new Error('missing TLV 2 for naddr')\n if (tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (!tlv[3]?.[0]) throw new Error('missing TLV 3 for naddr')\n if (tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'naddr',\n data: {\n identifier: utf8Decoder.decode(tlv[0][0]),\n pubkey: bytesToHex(tlv[2][0]),\n kind: parseInt(bytesToHex(tlv[3][0]), 16),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n\n case 'nsec':\n return { type: prefix, data }\n\n case 'npub':\n case 'note':\n return { type: prefix, data: bytesToHex(data) }\n\n default:\n throw new Error(`unknown prefix ${prefix}`)\n }\n}\n\ntype TLV = { [t: number]: Uint8Array[] }\n\nfunction parseTLV(data: Uint8Array): TLV {\n let result: TLV = {}\n let rest = data\n while (rest.length > 0) {\n let t = rest[0]\n let l = rest[1]\n let v = rest.slice(2, 2 + l)\n rest = rest.slice(2 + l)\n if (v.length < l) throw new Error(`not enough data to read on TLV ${t}`)\n result[t] = result[t] || []\n result[t].push(v)\n }\n return result\n}\n\nexport function nsecEncode(key: Uint8Array): NSec {\n return encodeBytes('nsec', key)\n}\n\nexport function npubEncode(hex: string): NPub {\n return encodeBytes('npub', hexToBytes(hex))\n}\n\nexport function noteEncode(hex: string): Note {\n return encodeBytes('note', hexToBytes(hex))\n}\n\nfunction encodeBech32(prefix: Prefix, data: Uint8Array): `${Prefix}1${string}` {\n let words = bech32.toWords(data)\n return bech32.encode(prefix, words, Bech32MaxSize) as `${Prefix}1${string}`\n}\n\nexport function encodeBytes(prefix: Prefix, bytes: Uint8Array): `${Prefix}1${string}` {\n return encodeBech32(prefix, bytes)\n}\n\nexport function nprofileEncode(profile: ProfilePointer): NProfile {\n let data = encodeTLV({\n 0: [hexToBytes(profile.pubkey)],\n 1: (profile.relays || []).map(url => utf8Encoder.encode(url)),\n })\n return encodeBech32('nprofile', data)\n}\n\nexport function neventEncode(event: EventPointer): NEvent {\n let kindArray\n if (event.kind !== undefined) {\n kindArray = integerToUint8Array(event.kind)\n }\n\n let data = encodeTLV({\n 0: [hexToBytes(event.id)],\n 1: (event.relays || []).map(url => utf8Encoder.encode(url)),\n 2: event.author ? [hexToBytes(event.author)] : [],\n 3: kindArray ? [new Uint8Array(kindArray)] : [],\n })\n\n return encodeBech32('nevent', data)\n}\n\nexport function naddrEncode(addr: AddressPointer): NAddr {\n let kind = new ArrayBuffer(4)\n new DataView(kind).setUint32(0, addr.kind, false)\n\n let data = encodeTLV({\n 0: [utf8Encoder.encode(addr.identifier)],\n 1: (addr.relays || []).map(url => utf8Encoder.encode(url)),\n 2: [hexToBytes(addr.pubkey)],\n 3: [new Uint8Array(kind)],\n })\n return encodeBech32('naddr', data)\n}\n\nfunction encodeTLV(tlv: TLV): Uint8Array {\n let entries: Uint8Array[] = []\n\n Object.entries(tlv)\n .reverse()\n .forEach(([t, vs]) => {\n vs.forEach(v => {\n let entry = new Uint8Array(v.length + 2)\n entry.set([parseInt(t)], 0)\n entry.set([v.length], 1)\n entry.set(v, 2)\n entries.push(entry)\n })\n })\n\n return concatBytes(...entries)\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n"], + "mappings": ";AAAA,SAAS,cAAAA,aAAY,aAAa,cAAAC,mBAAkB;AACpD,SAAS,cAAc;;;ACIvB,SAAS,YAAY,kBAAkB;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;;;ADUjD,IAAM,iBAAiB;AAAA,EAC5B,YAAY,CAAC,UAA6C,sBAAsB,KAAK,SAAS,EAAE;AAAA,EAChG,UAAU,CAAC,UAA2C,oBAAoB,KAAK,SAAS,EAAE;AAAA,EAC1F,SAAS,CAAC,UAA0C,mBAAmB,KAAK,SAAS,EAAE;AAAA,EACvF,QAAQ,CAAC,UA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QAAQ,OAAK;AACd,UAAI,QAAQ,IAAI,WAAW,EAAE,SAAS,CAAC;AACvC,YAAM,IAAI,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC;AAC1B,YAAM,IAAI,CAAC,EAAE,MAAM,GAAG,CAAC;AACvB,YAAM,IAAI,GAAG,CAAC;AACd,cAAQ,KAAK,KAAK;AAAA,IACpB,CAAC;AAAA,EACH,CAAC;AAEH,SAAO,YAAY,GAAG,OAAO;AAC/B;", + "names": ["bytesToHex", "hexToBytes", "bytesToHex", "hexToBytes"] +} diff --git a/node_modules/nostr-tools/lib/esm/nip21.js b/node_modules/nostr-tools/lib/esm/nip21.js new file mode 100644 index 0000000..cfa087e --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip21.js @@ -0,0 +1,117 @@ +// nip19.ts +import { bytesToHex as bytesToHex2, concatBytes, hexToBytes as hexToBytes2 } from "@noble/hashes/utils"; +import { bech32 } from "@scure/base"; + +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// nip19.ts +var Bech32MaxSize = 5e3; +var BECH32_REGEX = /[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/; +function decode(code) { + let { prefix, words } = bech32.decode(code, Bech32MaxSize); + let data = new Uint8Array(bech32.fromWords(words)); + switch (prefix) { + case "nprofile": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nprofile"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + return { + type: "nprofile", + data: { + pubkey: bytesToHex2(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nevent": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nevent"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + if (tlv[2] && tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (tlv[3] && tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "nevent", + data: { + id: bytesToHex2(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [], + author: tlv[2]?.[0] ? bytesToHex2(tlv[2][0]) : void 0, + kind: tlv[3]?.[0] ? parseInt(bytesToHex2(tlv[3][0]), 16) : void 0 + } + }; + } + case "naddr": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for naddr"); + if (!tlv[2]?.[0]) + throw new Error("missing TLV 2 for naddr"); + if (tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (!tlv[3]?.[0]) + throw new Error("missing TLV 3 for naddr"); + if (tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "naddr", + data: { + identifier: utf8Decoder.decode(tlv[0][0]), + pubkey: bytesToHex2(tlv[2][0]), + kind: parseInt(bytesToHex2(tlv[3][0]), 16), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nsec": + return { type: prefix, data }; + case "npub": + case "note": + return { type: prefix, data: bytesToHex2(data) }; + default: + throw new Error(`unknown prefix ${prefix}`); + } +} +function parseTLV(data) { + let result = {}; + let rest = data; + while (rest.length > 0) { + let t = rest[0]; + let l = rest[1]; + let v = rest.slice(2, 2 + l); + rest = rest.slice(2 + l); + if (v.length < l) + throw new Error(`not enough data to read on TLV ${t}`); + result[t] = result[t] || []; + result[t].push(v); + } + return result; +} + +// nip21.ts +var NOSTR_URI_REGEX = new RegExp(`nostr:(${BECH32_REGEX.source})`); +function test(value) { + return typeof value === "string" && new RegExp(`^${NOSTR_URI_REGEX.source}$`).test(value); +} +function parse(uri) { + const match = uri.match(new RegExp(`^${NOSTR_URI_REGEX.source}$`)); + if (!match) + throw new Error(`Invalid Nostr URI: ${uri}`); + return { + uri: match[0], + value: match[1], + decoded: decode(match[1]) + }; +} +export { + NOSTR_URI_REGEX, + parse, + test +}; diff --git a/node_modules/nostr-tools/lib/esm/nip21.js.map b/node_modules/nostr-tools/lib/esm/nip21.js.map new file mode 100644 index 0000000..29b66cb --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip21.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip19.ts", "../../utils.ts", "../../nip21.ts"], + "sourcesContent": ["import { bytesToHex, concatBytes, hexToBytes } from '@noble/hashes/utils'\nimport { bech32 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport type NProfile = `nprofile1${string}`\nexport type NEvent = `nevent1${string}`\nexport type NAddr = `naddr1${string}`\nexport type NSec = `nsec1${string}`\nexport type NPub = `npub1${string}`\nexport type Note = `note1${string}`\nexport type Ncryptsec = `ncryptsec1${string}`\n\nexport const NostrTypeGuard = {\n isNProfile: (value?: string | null): value is NProfile => /^nprofile1[a-z\\d]+$/.test(value || ''),\n isNEvent: (value?: string | null): value is NEvent => /^nevent1[a-z\\d]+$/.test(value || ''),\n isNAddr: (value?: string | null): value is NAddr => /^naddr1[a-z\\d]+$/.test(value || ''),\n isNSec: (value?: string | null): value is NSec => /^nsec1[a-z\\d]{58}$/.test(value || ''),\n isNPub: (value?: string | null): value is NPub => /^npub1[a-z\\d]{58}$/.test(value || ''),\n isNote: (value?: string | null): value is Note => /^note1[a-z\\d]+$/.test(value || ''),\n isNcryptsec: (value?: string | null): value is Ncryptsec => /^ncryptsec1[a-z\\d]+$/.test(value || ''),\n}\n\nexport const Bech32MaxSize = 5000\n\n/**\n * Bech32 regex.\n * @see https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32\n */\nexport const BECH32_REGEX = /[\\x21-\\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/\n\nfunction integerToUint8Array(number: number) {\n // Create a Uint8Array with enough space to hold a 32-bit integer (4 bytes).\n const uint8Array = new Uint8Array(4)\n\n // Use bitwise operations to extract the bytes.\n uint8Array[0] = (number >> 24) & 0xff // Most significant byte (MSB)\n uint8Array[1] = (number >> 16) & 0xff\n uint8Array[2] = (number >> 8) & 0xff\n uint8Array[3] = number & 0xff // Least significant byte (LSB)\n\n return uint8Array\n}\n\nexport type ProfilePointer = {\n pubkey: string // hex\n relays?: string[]\n}\n\nexport type EventPointer = {\n id: string // hex\n relays?: string[]\n author?: string\n kind?: number\n}\n\nexport type AddressPointer = {\n identifier: string\n pubkey: string\n kind: number\n relays?: string[]\n}\n\nexport function decodeNostrURI(nip19code: string): ReturnType | { type: 'invalid'; data: null } {\n try {\n if (nip19code.startsWith('nostr:')) nip19code = nip19code.substring(6)\n return decode(nip19code)\n } catch (_err) {\n return { type: 'invalid', data: null }\n }\n}\n\nexport type DecodedNevent = {\n type: 'nevent'\n data: EventPointer\n}\n\nexport type DecodedNprofile = {\n type: 'nprofile'\n data: ProfilePointer\n}\n\nexport type DecodedNaddr = {\n type: 'naddr'\n data: AddressPointer\n}\n\nexport type DecodedNsec = {\n type: 'nsec'\n data: Uint8Array\n}\n\nexport type DecodedNpub = {\n type: 'npub'\n data: string\n}\n\nexport type DecodedNote = {\n type: 'note'\n data: string\n}\n\nexport type DecodedResult = DecodedNevent | DecodedNprofile | DecodedNaddr | DecodedNpub | DecodedNsec | DecodedNote\n\nexport function decode(nip19: NEvent): DecodedNevent\nexport function decode(nip19: NProfile): DecodedNprofile\nexport function decode(nip19: NAddr): DecodedNaddr\nexport function decode(nip19: NSec): DecodedNsec\nexport function decode(nip19: NPub): DecodedNpub\nexport function decode(nip19: Note): DecodedNote\nexport function decode(code: string): DecodedResult\nexport function decode(code: string): DecodedResult {\n let { prefix, words } = bech32.decode(code, Bech32MaxSize)\n let data = new Uint8Array(bech32.fromWords(words))\n\n switch (prefix) {\n case 'nprofile': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nprofile')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n\n return {\n type: 'nprofile',\n data: {\n pubkey: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n case 'nevent': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nevent')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n if (tlv[2] && tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (tlv[3] && tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'nevent',\n data: {\n id: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n author: tlv[2]?.[0] ? bytesToHex(tlv[2][0]) : undefined,\n kind: tlv[3]?.[0] ? parseInt(bytesToHex(tlv[3][0]), 16) : undefined,\n },\n }\n }\n\n case 'naddr': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for naddr')\n if (!tlv[2]?.[0]) throw new Error('missing TLV 2 for naddr')\n if (tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (!tlv[3]?.[0]) throw new Error('missing TLV 3 for naddr')\n if (tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'naddr',\n data: {\n identifier: utf8Decoder.decode(tlv[0][0]),\n pubkey: bytesToHex(tlv[2][0]),\n kind: parseInt(bytesToHex(tlv[3][0]), 16),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n\n case 'nsec':\n return { type: prefix, data }\n\n case 'npub':\n case 'note':\n return { type: prefix, data: bytesToHex(data) }\n\n default:\n throw new Error(`unknown prefix ${prefix}`)\n }\n}\n\ntype TLV = { [t: number]: Uint8Array[] }\n\nfunction parseTLV(data: Uint8Array): TLV {\n let result: TLV = {}\n let rest = data\n while (rest.length > 0) {\n let t = rest[0]\n let l = rest[1]\n let v = rest.slice(2, 2 + l)\n rest = rest.slice(2 + l)\n if (v.length < l) throw new Error(`not enough data to read on TLV ${t}`)\n result[t] = result[t] || []\n result[t].push(v)\n }\n return result\n}\n\nexport function nsecEncode(key: Uint8Array): NSec {\n return encodeBytes('nsec', key)\n}\n\nexport function npubEncode(hex: string): NPub {\n return encodeBytes('npub', hexToBytes(hex))\n}\n\nexport function noteEncode(hex: string): Note {\n return encodeBytes('note', hexToBytes(hex))\n}\n\nfunction encodeBech32(prefix: Prefix, data: Uint8Array): `${Prefix}1${string}` {\n let words = bech32.toWords(data)\n return bech32.encode(prefix, words, Bech32MaxSize) as `${Prefix}1${string}`\n}\n\nexport function encodeBytes(prefix: Prefix, bytes: Uint8Array): `${Prefix}1${string}` {\n return encodeBech32(prefix, bytes)\n}\n\nexport function nprofileEncode(profile: ProfilePointer): NProfile {\n let data = encodeTLV({\n 0: [hexToBytes(profile.pubkey)],\n 1: (profile.relays || []).map(url => utf8Encoder.encode(url)),\n })\n return encodeBech32('nprofile', data)\n}\n\nexport function neventEncode(event: EventPointer): NEvent {\n let kindArray\n if (event.kind !== undefined) {\n kindArray = integerToUint8Array(event.kind)\n }\n\n let data = encodeTLV({\n 0: [hexToBytes(event.id)],\n 1: (event.relays || []).map(url => utf8Encoder.encode(url)),\n 2: event.author ? [hexToBytes(event.author)] : [],\n 3: kindArray ? [new Uint8Array(kindArray)] : [],\n })\n\n return encodeBech32('nevent', data)\n}\n\nexport function naddrEncode(addr: AddressPointer): NAddr {\n let kind = new ArrayBuffer(4)\n new DataView(kind).setUint32(0, addr.kind, false)\n\n let data = encodeTLV({\n 0: [utf8Encoder.encode(addr.identifier)],\n 1: (addr.relays || []).map(url => utf8Encoder.encode(url)),\n 2: [hexToBytes(addr.pubkey)],\n 3: [new Uint8Array(kind)],\n })\n return encodeBech32('naddr', data)\n}\n\nfunction encodeTLV(tlv: TLV): Uint8Array {\n let entries: Uint8Array[] = []\n\n Object.entries(tlv)\n .reverse()\n .forEach(([t, vs]) => {\n vs.forEach(v => {\n let entry = new Uint8Array(v.length + 2)\n entry.set([parseInt(t)], 0)\n entry.set([v.length], 1)\n entry.set(v, 2)\n entries.push(entry)\n })\n })\n\n return concatBytes(...entries)\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { AddressPointer, BECH32_REGEX, decode, EventPointer, ProfilePointer } from './nip19.ts'\n\n/** Nostr URI regex, eg `nostr:npub1...` */\nexport const NOSTR_URI_REGEX: RegExp = new RegExp(`nostr:(${BECH32_REGEX.source})`)\n\n/** Test whether the value is a Nostr URI. */\nexport function test(value: unknown): value is `nostr:${string}` {\n return typeof value === 'string' && new RegExp(`^${NOSTR_URI_REGEX.source}$`).test(value)\n}\n\n/** Parsed Nostr URI data. */\nexport interface NostrURI {\n /** Full URI including the `nostr:` protocol. */\n uri: `nostr:${string}`\n /** The bech32-encoded data (eg `npub1...`). */\n value: string\n /** Decoded bech32 string, according to NIP-19. */\n decoded:\n | {\n type: 'nevent'\n data: EventPointer\n }\n | {\n type: 'nprofile'\n data: ProfilePointer\n }\n | {\n type: 'naddr'\n data: AddressPointer\n }\n | {\n type: 'npub'\n data: string\n }\n | {\n type: 'nsec'\n data: Uint8Array\n }\n | {\n type: 'note'\n data: string\n }\n}\n\n/** Parse and decode a Nostr URI. */\nexport function parse(uri: string): NostrURI {\n const match = uri.match(new RegExp(`^${NOSTR_URI_REGEX.source}$`))\n if (!match) throw new Error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,YAAM,IAAI,MAAM,kBAAkB,QAAQ;AAAA,EAC9C;AACF;AAIA,SAAS,SAAS,MAAuB;AACvC,MAAI,SAAc,CAAC;AACnB,MAAI,OAAO;AACX,SAAO,KAAK,SAAS,GAAG;AACtB,QAAI,IAAI,KAAK;AACb,QAAI,IAAI,KAAK;AACb,QAAI,IAAI,KAAK,MAAM,GAAG,IAAI,CAAC;AAC3B,WAAO,KAAK,MAAM,IAAI,CAAC;AACvB,QAAI,EAAE,SAAS;AAAG,YAAM,IAAI,MAAM,kCAAkC,GAAG;AACvE,WAAO,KAAK,OAAO,MAAM,CAAC;AAC1B,WAAO,GAAG,KAAK,CAAC;AAAA,EAClB;AACA,SAAO;AACT;;;AE9LO,IAAM,kBAA0B,IAAI,OAAO,UAAU,aAAa,SAAS;AAG3E,SAAS,KAAK,OAA4C;AAC/D,SAAO,OAAO,UAAU,YAAY,IAAI,OAAO,IAAI,gBAAgB,SAAS,EAAE,KAAK,KAAK;AAC1F;AAqCO,SAAS,MAAM,KAAuB;AAC3C,QAAM,QAAQ,IAAI,MAAM,IAAI,OAAO,IAAI,gBAAgB,SAAS,CAAC;AACjE,MAAI,CAAC;AAAO,UAAM,IAAI,MAAM,sBAAsB,KAAK;AACvD,SAAO;AAAA,IACL,KAAK,MAAM;AAAA,IACX,OAAO,MAAM;AAAA,IACb,SAAS,OAAO,MAAM,EAAE;AAAA,EAC1B;AACF;", + "names": ["bytesToHex", "hexToBytes", "bytesToHex"] +} diff --git a/node_modules/nostr-tools/lib/esm/nip25.js b/node_modules/nostr-tools/lib/esm/nip25.js new file mode 100644 index 0000000..f2507ad --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip25.js @@ -0,0 +1,136 @@ +// pure.ts +import { schnorr } from "@noble/curves/secp256k1"; +import { bytesToHex as bytesToHex2 } from "@noble/hashes/utils"; + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +import { sha256 } from "@noble/hashes/sha256"; + +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// pure.ts +var JS = class { + generateSecretKey() { + return schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return bytesToHex2(schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = bytesToHex2(schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = bytesToHex2(schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = sha256(utf8Encoder.encode(serializeEvent(event))); + return bytesToHex2(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// kinds.ts +var Reaction = 7; + +// nip25.ts +function finishReactionEvent(t, reacted, privateKey) { + const inheritedTags = reacted.tags.filter((tag) => tag.length >= 2 && (tag[0] === "e" || tag[0] === "p")); + return finalizeEvent( + { + ...t, + kind: Reaction, + tags: [...t.tags ?? [], ...inheritedTags, ["e", reacted.id], ["p", reacted.pubkey]], + content: t.content ?? "+" + }, + privateKey + ); +} +function getReactedEventPointer(event) { + if (event.kind !== Reaction) { + return void 0; + } + let lastETag; + let lastPTag; + for (let i2 = event.tags.length - 1; i2 >= 0 && (lastETag === void 0 || lastPTag === void 0); i2--) { + const tag = event.tags[i2]; + if (tag.length >= 2) { + if (tag[0] === "e" && lastETag === void 0) { + lastETag = tag; + } else if (tag[0] === "p" && lastPTag === void 0) { + lastPTag = tag; + } + } + } + if (lastETag === void 0 || lastPTag === void 0) { + return void 0; + } + return { + id: lastETag[1], + relays: [lastETag[2], lastPTag[2]].filter((x) => x !== void 0), + author: lastPTag[1] + }; +} +export { + finishReactionEvent, + getReactedEventPointer +}; diff --git a/node_modules/nostr-tools/lib/esm/nip25.js.map b/node_modules/nostr-tools/lib/esm/nip25.js.map new file mode 100644 index 0000000..f66d250 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip25.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../pure.ts", "../../core.ts", "../../utils.ts", "../../kinds.ts", "../../nip25.ts"], + "sourcesContent": ["import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { Event, finalizeEvent } from './pure.ts'\nimport { Reaction } from './kinds.ts'\n\nimport type { EventPointer } from './nip19.ts'\n\nexport type ReactionEventTemplate = {\n /**\n * Pass only non-nip25 tags if you have to. Nip25 tags ('e' and 'p' tags from reacted event) will be added automatically.\n */\n tags?: string[][]\n\n /**\n * @default '+'\n */\n content?: string\n\n created_at: number\n}\n\nexport function finishReactionEvent(t: ReactionEventTemplate, reacted: Event, privateKey: Uint8Array): Event {\n const inheritedTags = reacted.tags.filter(tag => tag.length >= 2 && (tag[0] === 'e' || tag[0] === 'p'))\n\n return finalizeEvent(\n {\n ...t,\n kind: Reaction,\n tags: [...(t.tags ?? []), ...inheritedTags, ['e', reacted.id], ['p', reacted.pubkey]],\n content: t.content ?? '+',\n },\n privateKey,\n )\n}\n\nexport function getReactedEventPointer(event: Event): undefined | EventPointer {\n if (event.kind !== Reaction) {\n return undefined\n }\n\n let lastETag: undefined | string[]\n let lastPTag: undefined | string[]\n\n for (let i = event.tags.length - 1; i >= 0 && (lastETag === undefined || lastPTag === undefined); i--) {\n const tag = event.tags[i]\n if (tag.length >= 2) {\n if (tag[0] === 'e' && lastETag === undefined) {\n lastETag = tag\n } else if (tag[0] === 'p' && lastPTag === undefined) {\n lastPTag = tag\n }\n }\n }\n\n if (lastETag === undefined || lastPTag === undefined) {\n return undefined\n }\n\n return {\n id: lastETag[1],\n relays: [lastETag[2], lastPTag[2]].filter(x => x !== undefined),\n author: lastPTag[1],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AQ,MAAM,CAAC;AAAA,MACpF,SAAS,EAAE,WAAW;AAAA,IACxB;AAAA,IACA;AAAA,EACF;AACF;AAEO,SAAS,uBAAuB,OAAwC;AAC7E,MAAI,MAAM,SAAS,UAAU;AAC3B,WAAO;AAAA,EACT;AAEA,MAAI;AACJ,MAAI;AAEJ,WAASC,KAAI,MAAM,KAAK,SAAS,GAAGA,MAAK,MAAM,aAAa,UAAa,aAAa,SAAYA,MAAK;AACrG,UAAM,MAAM,MAAM,KAAKA;AACvB,QAAI,IAAI,UAAU,GAAG;AACnB,UAAI,IAAI,OAAO,OAAO,aAAa,QAAW;AAC5C,mBAAW;AAAA,MACb,WAAW,IAAI,OAAO,OAAO,aAAa,QAAW;AACnD,mBAAW;AAAA,MACb;AAAA,IACF;AAAA,EACF;AAEA,MAAI,aAAa,UAAa,aAAa,QAAW;AACpD,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,IAAI,SAAS;AAAA,IACb,QAAQ,CAAC,SAAS,IAAI,SAAS,EAAE,EAAE,OAAO,OAAK,MAAM,MAAS;AAAA,IAC9D,QAAQ,SAAS;AAAA,EACnB;AACF;", + "names": ["bytesToHex", "i", "bytesToHex", "i"] +} diff --git a/node_modules/nostr-tools/lib/esm/nip27.js b/node_modules/nostr-tools/lib/esm/nip27.js new file mode 100644 index 0000000..d9a7dd5 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip27.js @@ -0,0 +1,206 @@ +// nip19.ts +import { bytesToHex as bytesToHex2, concatBytes, hexToBytes as hexToBytes2 } from "@noble/hashes/utils"; +import { bech32 } from "@scure/base"; + +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// nip19.ts +var Bech32MaxSize = 5e3; +function decode(code) { + let { prefix, words } = bech32.decode(code, Bech32MaxSize); + let data = new Uint8Array(bech32.fromWords(words)); + switch (prefix) { + case "nprofile": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nprofile"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + return { + type: "nprofile", + data: { + pubkey: bytesToHex2(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nevent": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nevent"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + if (tlv[2] && tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (tlv[3] && tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "nevent", + data: { + id: bytesToHex2(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [], + author: tlv[2]?.[0] ? bytesToHex2(tlv[2][0]) : void 0, + kind: tlv[3]?.[0] ? parseInt(bytesToHex2(tlv[3][0]), 16) : void 0 + } + }; + } + case "naddr": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for naddr"); + if (!tlv[2]?.[0]) + throw new Error("missing TLV 2 for naddr"); + if (tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (!tlv[3]?.[0]) + throw new Error("missing TLV 3 for naddr"); + if (tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "naddr", + data: { + identifier: utf8Decoder.decode(tlv[0][0]), + pubkey: bytesToHex2(tlv[2][0]), + kind: parseInt(bytesToHex2(tlv[3][0]), 16), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nsec": + return { type: prefix, data }; + case "npub": + case "note": + return { type: prefix, data: bytesToHex2(data) }; + default: + throw new Error(`unknown prefix ${prefix}`); + } +} +function parseTLV(data) { + let result = {}; + let rest = data; + while (rest.length > 0) { + let t = rest[0]; + let l = rest[1]; + let v = rest.slice(2, 2 + l); + rest = rest.slice(2 + l); + if (v.length < l) + throw new Error(`not enough data to read on TLV ${t}`); + result[t] = result[t] || []; + result[t].push(v); + } + return result; +} + +// nip27.ts +var noCharacter = /\W/m; +var noURLCharacter = /\W |\W$|$|,| /m; +function* parse(content) { + const max = content.length; + let prevIndex = 0; + let index = 0; + while (index < max) { + let u = content.indexOf(":", index); + if (u === -1) { + break; + } + if (content.substring(u - 5, u) === "nostr") { + const m = content.substring(u + 60).match(noCharacter); + const end = m ? u + 60 + m.index : max; + try { + let pointer; + let { data, type } = decode(content.substring(u + 1, end)); + switch (type) { + case "npub": + pointer = { pubkey: data }; + break; + case "nsec": + case "note": + index = end + 1; + continue; + default: + pointer = data; + } + if (prevIndex !== u - 5) { + yield { type: "text", text: content.substring(prevIndex, u - 5) }; + } + yield { type: "reference", pointer }; + index = end; + prevIndex = index; + continue; + } catch (_err) { + index = u + 1; + continue; + } + } else if (content.substring(u - 5, u) === "https" || content.substring(u - 4, u) === "http") { + const m = content.substring(u + 4).match(noURLCharacter); + const end = m ? u + 4 + m.index : max; + const prefixLen = content[u - 1] === "s" ? 5 : 4; + try { + let url = new URL(content.substring(u - prefixLen, end)); + if (url.hostname.indexOf(".") === -1) { + throw new Error("invalid url"); + } + if (prevIndex !== u - prefixLen) { + yield { type: "text", text: content.substring(prevIndex, u - prefixLen) }; + } + if (url.pathname.endsWith(".png") || url.pathname.endsWith(".jpg") || url.pathname.endsWith(".jpeg") || url.pathname.endsWith(".gif") || url.pathname.endsWith(".webp")) { + yield { type: "image", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } + if (url.pathname.endsWith(".mp4") || url.pathname.endsWith(".avi") || url.pathname.endsWith(".webm") || url.pathname.endsWith(".mkv")) { + yield { type: "video", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } + if (url.pathname.endsWith(".mp3") || url.pathname.endsWith(".aac") || url.pathname.endsWith(".ogg") || url.pathname.endsWith(".opus")) { + yield { type: "audio", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } + yield { type: "url", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } catch (_err) { + index = end + 1; + continue; + } + } else if (content.substring(u - 3, u) === "wss" || content.substring(u - 2, u) === "ws") { + const m = content.substring(u + 4).match(noURLCharacter); + const end = m ? u + 4 + m.index : max; + const prefixLen = content[u - 1] === "s" ? 3 : 2; + try { + let url = new URL(content.substring(u - prefixLen, end)); + if (url.hostname.indexOf(".") === -1) { + throw new Error("invalid ws url"); + } + if (prevIndex !== u - prefixLen) { + yield { type: "text", text: content.substring(prevIndex, u - prefixLen) }; + } + yield { type: "relay", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } catch (_err) { + index = end + 1; + continue; + } + } else { + index = u + 1; + continue; + } + } + if (prevIndex !== max) { + yield { type: "text", text: content.substring(prevIndex) }; + } +} +export { + parse +}; diff --git a/node_modules/nostr-tools/lib/esm/nip27.js.map b/node_modules/nostr-tools/lib/esm/nip27.js.map new file mode 100644 index 0000000..142ed68 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip27.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip19.ts", "../../utils.ts", "../../nip27.ts"], + "sourcesContent": ["import { bytesToHex, concatBytes, hexToBytes } from '@noble/hashes/utils'\nimport { bech32 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport type NProfile = `nprofile1${string}`\nexport type NEvent = `nevent1${string}`\nexport type NAddr = `naddr1${string}`\nexport type NSec = `nsec1${string}`\nexport type NPub = `npub1${string}`\nexport type Note = `note1${string}`\nexport type Ncryptsec = `ncryptsec1${string}`\n\nexport const NostrTypeGuard = {\n isNProfile: (value?: string | null): value is NProfile => /^nprofile1[a-z\\d]+$/.test(value || ''),\n isNEvent: (value?: string | null): value is NEvent => /^nevent1[a-z\\d]+$/.test(value || ''),\n isNAddr: (value?: string | null): value is NAddr => /^naddr1[a-z\\d]+$/.test(value || ''),\n isNSec: (value?: string | null): value is NSec => /^nsec1[a-z\\d]{58}$/.test(value || ''),\n isNPub: (value?: string | null): value is NPub => /^npub1[a-z\\d]{58}$/.test(value || ''),\n isNote: (value?: string | null): value is Note => /^note1[a-z\\d]+$/.test(value || ''),\n isNcryptsec: (value?: string | null): value is Ncryptsec => /^ncryptsec1[a-z\\d]+$/.test(value || ''),\n}\n\nexport const Bech32MaxSize = 5000\n\n/**\n * Bech32 regex.\n * @see https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32\n */\nexport const BECH32_REGEX = /[\\x21-\\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/\n\nfunction integerToUint8Array(number: number) {\n // Create a Uint8Array with enough space to hold a 32-bit integer (4 bytes).\n const uint8Array = new Uint8Array(4)\n\n // Use bitwise operations to extract the bytes.\n uint8Array[0] = (number >> 24) & 0xff // Most significant byte (MSB)\n uint8Array[1] = (number >> 16) & 0xff\n uint8Array[2] = (number >> 8) & 0xff\n uint8Array[3] = number & 0xff // Least significant byte (LSB)\n\n return uint8Array\n}\n\nexport type ProfilePointer = {\n pubkey: string // hex\n relays?: string[]\n}\n\nexport type EventPointer = {\n id: string // hex\n relays?: string[]\n author?: string\n kind?: number\n}\n\nexport type AddressPointer = {\n identifier: string\n pubkey: string\n kind: number\n relays?: string[]\n}\n\nexport function decodeNostrURI(nip19code: string): ReturnType | { type: 'invalid'; data: null } {\n try {\n if (nip19code.startsWith('nostr:')) nip19code = nip19code.substring(6)\n return decode(nip19code)\n } catch (_err) {\n return { type: 'invalid', data: null }\n }\n}\n\nexport type DecodedNevent = {\n type: 'nevent'\n data: EventPointer\n}\n\nexport type DecodedNprofile = {\n type: 'nprofile'\n data: ProfilePointer\n}\n\nexport type DecodedNaddr = {\n type: 'naddr'\n data: AddressPointer\n}\n\nexport type DecodedNsec = {\n type: 'nsec'\n data: Uint8Array\n}\n\nexport type DecodedNpub = {\n type: 'npub'\n data: string\n}\n\nexport type DecodedNote = {\n type: 'note'\n data: string\n}\n\nexport type DecodedResult = DecodedNevent | DecodedNprofile | DecodedNaddr | DecodedNpub | DecodedNsec | DecodedNote\n\nexport function decode(nip19: NEvent): DecodedNevent\nexport function decode(nip19: NProfile): DecodedNprofile\nexport function decode(nip19: NAddr): DecodedNaddr\nexport function decode(nip19: NSec): DecodedNsec\nexport function decode(nip19: NPub): DecodedNpub\nexport function decode(nip19: Note): DecodedNote\nexport function decode(code: string): DecodedResult\nexport function decode(code: string): DecodedResult {\n let { prefix, words } = bech32.decode(code, Bech32MaxSize)\n let data = new Uint8Array(bech32.fromWords(words))\n\n switch (prefix) {\n case 'nprofile': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nprofile')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n\n return {\n type: 'nprofile',\n data: {\n pubkey: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n case 'nevent': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nevent')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n if (tlv[2] && tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (tlv[3] && tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'nevent',\n data: {\n id: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n author: tlv[2]?.[0] ? bytesToHex(tlv[2][0]) : undefined,\n kind: tlv[3]?.[0] ? parseInt(bytesToHex(tlv[3][0]), 16) : undefined,\n },\n }\n }\n\n case 'naddr': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for naddr')\n if (!tlv[2]?.[0]) throw new Error('missing TLV 2 for naddr')\n if (tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (!tlv[3]?.[0]) throw new Error('missing TLV 3 for naddr')\n if (tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'naddr',\n data: {\n identifier: utf8Decoder.decode(tlv[0][0]),\n pubkey: bytesToHex(tlv[2][0]),\n kind: parseInt(bytesToHex(tlv[3][0]), 16),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n\n case 'nsec':\n return { type: prefix, data }\n\n case 'npub':\n case 'note':\n return { type: prefix, data: bytesToHex(data) }\n\n default:\n throw new Error(`unknown prefix ${prefix}`)\n }\n}\n\ntype TLV = { [t: number]: Uint8Array[] }\n\nfunction parseTLV(data: Uint8Array): TLV {\n let result: TLV = {}\n let rest = data\n while (rest.length > 0) {\n let t = rest[0]\n let l = rest[1]\n let v = rest.slice(2, 2 + l)\n rest = rest.slice(2 + l)\n if (v.length < l) throw new Error(`not enough data to read on TLV ${t}`)\n result[t] = result[t] || []\n result[t].push(v)\n }\n return result\n}\n\nexport function nsecEncode(key: Uint8Array): NSec {\n return encodeBytes('nsec', key)\n}\n\nexport function npubEncode(hex: string): NPub {\n return encodeBytes('npub', hexToBytes(hex))\n}\n\nexport function noteEncode(hex: string): Note {\n return encodeBytes('note', hexToBytes(hex))\n}\n\nfunction encodeBech32(prefix: Prefix, data: Uint8Array): `${Prefix}1${string}` {\n let words = bech32.toWords(data)\n return bech32.encode(prefix, words, Bech32MaxSize) as `${Prefix}1${string}`\n}\n\nexport function encodeBytes(prefix: Prefix, bytes: Uint8Array): `${Prefix}1${string}` {\n return encodeBech32(prefix, bytes)\n}\n\nexport function nprofileEncode(profile: ProfilePointer): NProfile {\n let data = encodeTLV({\n 0: [hexToBytes(profile.pubkey)],\n 1: (profile.relays || []).map(url => utf8Encoder.encode(url)),\n })\n return encodeBech32('nprofile', data)\n}\n\nexport function neventEncode(event: EventPointer): NEvent {\n let kindArray\n if (event.kind !== undefined) {\n kindArray = integerToUint8Array(event.kind)\n }\n\n let data = encodeTLV({\n 0: [hexToBytes(event.id)],\n 1: (event.relays || []).map(url => utf8Encoder.encode(url)),\n 2: event.author ? [hexToBytes(event.author)] : [],\n 3: kindArray ? [new Uint8Array(kindArray)] : [],\n })\n\n return encodeBech32('nevent', data)\n}\n\nexport function naddrEncode(addr: AddressPointer): NAddr {\n let kind = new ArrayBuffer(4)\n new DataView(kind).setUint32(0, addr.kind, false)\n\n let data = encodeTLV({\n 0: [utf8Encoder.encode(addr.identifier)],\n 1: (addr.relays || []).map(url => utf8Encoder.encode(url)),\n 2: [hexToBytes(addr.pubkey)],\n 3: [new Uint8Array(kind)],\n })\n return encodeBech32('naddr', data)\n}\n\nfunction encodeTLV(tlv: TLV): Uint8Array {\n let entries: Uint8Array[] = []\n\n Object.entries(tlv)\n .reverse()\n .forEach(([t, vs]) => {\n vs.forEach(v => {\n let entry = new Uint8Array(v.length + 2)\n entry.set([parseInt(t)], 0)\n entry.set([v.length], 1)\n entry.set(v, 2)\n entries.push(entry)\n })\n })\n\n return concatBytes(...entries)\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { AddressPointer, EventPointer, ProfilePointer, decode } from './nip19.ts'\n\nexport type Block =\n | {\n type: 'text'\n text: string\n }\n | {\n type: 'reference'\n pointer: ProfilePointer | AddressPointer | EventPointer\n }\n | {\n type: 'url'\n url: string\n }\n | {\n type: 'relay'\n url: string\n }\n | {\n type: 'image'\n url: string\n }\n | {\n type: 'video'\n url: string\n }\n | {\n type: 'audio'\n url: string\n }\n\nconst noCharacter = /\\W/m\nconst noURLCharacter = /\\W |\\W$|$|,| /m\n\nexport function* parse(content: string): Iterable {\n const max = content.length\n let prevIndex = 0\n let index = 0\n while (index < max) {\n let u = content.indexOf(':', index)\n if (u === -1) {\n // reached end\n break\n }\n\n if (content.substring(u - 5, u) === 'nostr') {\n const m = content.substring(u + 60).match(noCharacter)\n const end = m ? u + 60 + m.index! : max\n try {\n let pointer: ProfilePointer | AddressPointer | EventPointer\n let { data, type } = decode(content.substring(u + 1, end))\n\n switch (type) {\n case 'npub':\n pointer = { pubkey: data } as ProfilePointer\n break\n case 'nsec':\n case 'note':\n // ignore this, treat it as not a valid uri\n index = end + 1\n continue\n default:\n pointer = data as any\n }\n\n if (prevIndex !== u - 5) {\n yield { type: 'text', text: content.substring(prevIndex, u - 5) }\n }\n yield { type: 'reference', pointer }\n index = end\n prevIndex = index\n continue\n } catch (_err) {\n // ignore this, not a valid nostr uri\n index = u + 1\n continue\n }\n } else if (content.substring(u - 5, u) === 'https' || content.substring(u - 4, u) === 'http') {\n const m = content.substring(u + 4).match(noURLCharacter)\n const end = m ? u + 4 + m.index! : max\n const prefixLen = content[u - 1] === 's' ? 5 : 4\n try {\n let url = new URL(content.substring(u - prefixLen, end))\n if (url.hostname.indexOf('.') === -1) {\n throw new Error('invalid url')\n }\n\n if (prevIndex !== u - prefixLen) {\n yield { type: 'text', text: content.substring(prevIndex, u - prefixLen) }\n }\n\n if (\n url.pathname.endsWith('.png') ||\n url.pathname.endsWith('.jpg') ||\n url.pathname.endsWith('.jpeg') ||\n url.pathname.endsWith('.gif') ||\n url.pathname.endsWith('.webp')\n ) {\n yield { type: 'image', url: url.toString() }\n index = end\n prevIndex = index\n continue\n }\n if (\n url.pathname.endsWith('.mp4') ||\n url.pathname.endsWith('.avi') ||\n url.pathname.endsWith('.webm') ||\n url.pathname.endsWith('.mkv')\n ) {\n yield { type: 'video', url: url.toString() }\n index = end\n prevIndex = index\n continue\n }\n if (\n url.pathname.endsWith('.mp3') ||\n url.pathname.endsWith('.aac') ||\n url.pathname.endsWith('.ogg') ||\n url.pathname.endsWith('.opus')\n ) {\n yield { type: 'audio', url: url.toString() }\n index = end\n prevIndex = index\n continue\n }\n\n yield { type: 'url', url: url.toString() }\n index = end\n prevIndex = index\n continue\n } catch (_err) {\n // ignore this, not a valid url\n index = end + 1\n continue\n }\n } else if (content.substring(u - 3, u) === 'wss' || content.substring(u - 2, u) === 'ws') {\n const m = content.substring(u + 4).match(noURLCharacter)\n const end = m ? u + 4 + m.index! : max\n const prefixLen = content[u - 1] === 's' ? 3 : 2\n try {\n let url = new URL(content.substring(u - prefixLen, end))\n if (url.hostname.indexOf('.') === -1) {\n throw new Error('invalid ws url')\n }\n\n if (prevIndex !== u - prefixLen) {\n yield { type: 'text', text: content.substring(prevIndex, u - prefixLen) }\n }\n yield { type: 'relay', url: url.toString() }\n index = end\n prevIndex = index\n continue\n } catch (_err) {\n // ignore this, not a valid url\n index = end + 1\n continue\n }\n } else {\n // ignore this, it is nothing\n index = u + 1\n continue\n }\n }\n\n if (prevIndex !== max) {\n yield { type: 'text', text: content.substring(prevIndex) }\n }\n}\n"], + "mappings": ";AAAA,SAAS,cAAAA,aAAY,aAAa,cAAAC,mBAAkB;AACpD,SAAS,cAAc;;;ACIvB,SAAS,YAAY,kBAAkB;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;;;ADoBjD,IAAM,gBAAgB;AAwFtB,SAAS,OAAO,MAA6B;AAClD,MAAI,EAAE,QAAQ,MAAM,IAAI,OAAO,OAAO,MAAM,aAAa;AACzD,MAAI,OAAO,IAAI,WAAW,OAAO,UAAU,KAAK,CAAC;AAEjD,UAAQ,QAAQ;AAAA,IACd,KAAK,YAAY;AACf,UAAI,MAAM,SAAS,IAAI;AACvB,UAAI,CAAC,IAAI,KAAK;AAAI,cAAM,IAAI,MAAM,4BAA4B;AAC9D,UAAI,IAAI,GAAG,GAAG,WAAW;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AM,IAAI,IAAI,QAAQ,UAAU,IAAI,WAAW,GAAG,CAAC;AACvD,YAAI,IAAI,SAAS,QAAQ,GAAG,MAAM,IAAI;AACpC,gBAAM,IAAI,MAAM,gBAAgB;AAAA,QAClC;AAEA,YAAI,cAAc,IAAI,WAAW;AAC/B,gBAAM,EAAE,MAAM,QAAQ,MAAM,QAAQ,UAAU,WAAW,IAAI,SAAS,EAAE;AAAA,QAC1E;AACA,cAAM,EAAE,MAAM,SAAS,KAAK,IAAI,SAAS,EAAE;AAC3C,gBAAQ;AACR,oBAAY;AACZ;AAAA,MACF,SAAS,MAAP;AAEA,gBAAQ,MAAM;AACd;AAAA,MACF;AAAA,IACF,OAAO;AAEL,cAAQ,IAAI;AACZ;AAAA,IACF;AAAA,EACF;AAEA,MAAI,cAAc,KAAK;AACrB,UAAM,EAAE,MAAM,QAAQ,MAAM,QAAQ,UAAU,SAAS,EAAE;AAAA,EAC3D;AACF;", + "names": ["bytesToHex", "hexToBytes", "bytesToHex"] +} diff --git a/node_modules/nostr-tools/lib/esm/nip28.js b/node_modules/nostr-tools/lib/esm/nip28.js new file mode 100644 index 0000000..d98268d --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip28.js @@ -0,0 +1,197 @@ +// pure.ts +import { schnorr } from "@noble/curves/secp256k1"; +import { bytesToHex as bytesToHex2 } from "@noble/hashes/utils"; + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +import { sha256 } from "@noble/hashes/sha256"; + +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// pure.ts +var JS = class { + generateSecretKey() { + return schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return bytesToHex2(schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = bytesToHex2(schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = bytesToHex2(schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = sha256(utf8Encoder.encode(serializeEvent(event))); + return bytesToHex2(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// kinds.ts +var ChannelCreation = 40; +var ChannelMetadata = 41; +var ChannelMessage = 42; +var ChannelHideMessage = 43; +var ChannelMuteUser = 44; + +// nip28.ts +var channelCreateEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finalizeEvent( + { + kind: ChannelCreation, + tags: [...t.tags ?? []], + content, + created_at: t.created_at + }, + privateKey + ); +}; +var channelMetadataEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finalizeEvent( + { + kind: ChannelMetadata, + tags: [["e", t.channel_create_event_id], ...t.tags ?? []], + content, + created_at: t.created_at + }, + privateKey + ); +}; +var channelMessageEvent = (t, privateKey) => { + const tags = [["e", t.channel_create_event_id, t.relay_url, "root"]]; + if (t.reply_to_channel_message_event_id) { + tags.push(["e", t.reply_to_channel_message_event_id, t.relay_url, "reply"]); + } + return finalizeEvent( + { + kind: ChannelMessage, + tags: [...tags, ...t.tags ?? []], + content: t.content, + created_at: t.created_at + }, + privateKey + ); +}; +var channelHideMessageEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finalizeEvent( + { + kind: ChannelHideMessage, + tags: [["e", t.channel_message_event_id], ...t.tags ?? []], + content, + created_at: t.created_at + }, + privateKey + ); +}; +var channelMuteUserEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finalizeEvent( + { + kind: ChannelMuteUser, + tags: [["p", t.pubkey_to_mute], ...t.tags ?? []], + content, + created_at: t.created_at + }, + privateKey + ); +}; +export { + channelCreateEvent, + channelHideMessageEvent, + channelMessageEvent, + channelMetadataEvent, + channelMuteUserEvent +}; diff --git a/node_modules/nostr-tools/lib/esm/nip28.js.map b/node_modules/nostr-tools/lib/esm/nip28.js.map new file mode 100644 index 0000000..fe3d393 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip28.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../pure.ts", "../../core.ts", "../../utils.ts", "../../kinds.ts", "../../nip28.ts"], + "sourcesContent": ["import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { Event, finalizeEvent } from './pure.ts'\nimport {\n ChannelCreation,\n ChannelHideMessage,\n ChannelMessage,\n ChannelMetadata as KindChannelMetadata,\n ChannelMuteUser,\n} from './kinds.ts'\n\nexport interface ChannelMetadata {\n name: string\n about: string\n picture: string\n}\n\nexport interface ChannelCreateEventTemplate {\n /* JSON string containing ChannelMetadata as defined for Kind 40 and 41 in nip-28. */\n content: string | ChannelMetadata\n created_at: number\n tags?: string[][]\n}\n\nexport interface ChannelMetadataEventTemplate {\n channel_create_event_id: string\n /* JSON string containing ChannelMetadata as defined for Kind 40 and 41 in nip-28. */\n content: string | ChannelMetadata\n created_at: number\n tags?: string[][]\n}\n\nexport interface ChannelMessageEventTemplate {\n channel_create_event_id: string\n reply_to_channel_message_event_id?: string\n relay_url: string\n content: string\n created_at: number\n tags?: string[][]\n}\n\nexport interface ChannelHideMessageEventTemplate {\n channel_message_event_id: string\n content: string | { reason: string }\n created_at: number\n tags?: string[][]\n}\n\nexport interface ChannelMuteUserEventTemplate {\n content: string | { reason: string }\n created_at: number\n pubkey_to_mute: string\n tags?: string[][]\n}\n\nexport const channelCreateEvent = (t: ChannelCreateEventTemplate, privateKey: Uint8Array): Event | undefined => {\n let content: string\n if (typeof t.content === 'object') {\n content = JSON.stringify(t.content)\n } else if (typeof t.content === 'string') {\n content = t.content\n } else {\n return undefined\n }\n\n return finalizeEvent(\n {\n kind: ChannelCreation,\n tags: [...(t.tags ?? [])],\n content: content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\nexport const channelMetadataEvent = (t: ChannelMetadataEventTemplate, privateKey: Uint8Array): Event | undefined => {\n let content: string\n if (typeof t.content === 'object') {\n content = JSON.stringify(t.content)\n } else if (typeof t.content === 'string') {\n content = t.content\n } else {\n return undefined\n }\n\n return finalizeEvent(\n {\n kind: KindChannelMetadata,\n tags: [['e', t.channel_create_event_id], ...(t.tags ?? [])],\n content: content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\nexport const channelMessageEvent = (t: ChannelMessageEventTemplate, privateKey: Uint8Array): Event => {\n const tags = [['e', t.channel_create_event_id, t.relay_url, 'root']]\n\n if (t.reply_to_channel_message_event_id) {\n tags.push(['e', t.reply_to_channel_message_event_id, t.relay_url, 'reply'])\n }\n\n return finalizeEvent(\n {\n kind: ChannelMessage,\n tags: [...tags, ...(t.tags ?? [])],\n content: t.content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\n/* \"e\" tag should be the kind 42 event to hide */\nexport const channelHideMessageEvent = (\n t: ChannelHideMessageEventTemplate,\n privateKey: Uint8Array,\n): Event | undefined => {\n let content: string\n if (typeof t.content === 'object') {\n content = JSON.stringify(t.content)\n } else if (typeof t.content === 'string') {\n content = t.content\n } else {\n return undefined\n }\n\n return finalizeEvent(\n {\n kind: ChannelHideMessage,\n tags: [['e', t.channel_message_event_id], ...(t.tags ?? [])],\n content: content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\nexport const channelMuteUserEvent = (t: ChannelMuteUserEventTemplate, privateKey: Uint8Array): Event | undefined => {\n let content: string\n if (typeof t.content === 'object') {\n content = JSON.stringify(t.content)\n } else if (typeof t.content === 'string') {\n content = t.content\n } else {\n return undefined\n }\n\n return finalizeEvent(\n {\n kind: ChannelMuteUser,\n tags: [['p', t.pubkey_to_mute], ...(t.tags ?? [])],\n content: content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n"], + "mappings": ";AAAA,SAAS,eAAe;AACxB,SAAS,cAAAA,mBAAkB;;;ACOpB,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,CAAC,QAAiD,eAAe;AAE3E,SAAS,cAAiB,OAAsC;AACrE,MAAI,CAAC,SAAS,KAAK;AAAG,WAAO;AAC7B,MAAI,OAAO,MAAM,SAAS;AAAU,WAAO;AAC3C,MAAI,OAAO,MAAM,YAAY;AAAU,WAAO;AAC9C,MAAI,OAAO,MAAM,eAAe;AAAU,WAAO;AACjD,MAAI,OAAO,MAAM,WAAW;AAAU,WAAO;AAC7C,MAAI,CAAC,MAAM,OAAO,MAAM,gBAAgB;AAAG,WAAO;AAElD,MAAI,CAAC,MAAM,QAAQ,MAAM,IAAI;AAAG,WAAO;AACvC,WAASC,KAAI,GAAGA,KAAI,MAAM,KAAK,QAAQA,MAAK;AAC1C,QAAI,MAAM,MAAM,KAAKA;AACrB,QAAI,CAAC,MAAM,QAAQ,GAAG;AAAG,aAAO;AAChC,aAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,UAAI,OAAO,IAAI,OAAO;AAAU,eAAO;AAAA,IACzC;AAAA,EACF;AAEA,SAAO;AACT;;;AD/CA,SAAS,cAAc;;;AEEvB,SAAS,YAAY,kBAAkB;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;;;AFIxD,IAAM,KAAN,MAA0B;AAAA,EACxB,oBAAgC;AAC9B,WAAO,QAAQ,MAAM,iBAAiB;AAAA,EACxC;AAAA,EACA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A,EACF;AACF;AAGO,IAAM,0BAA0B,CACrC,GACA,eACsB;AACtB,MAAI;AACJ,MAAI,OAAO,EAAE,YAAY,UAAU;AACjC,cAAU,KAAK,UAAU,EAAE,OAAO;AAAA,EACpC,WAAW,OAAO,EAAE,YAAY,UAAU;AACxC,cAAU,EAAE;AAAA,EACd,OAAO;AACL,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL;AAAA,MACE,MAAM;AAAA,MACN,MAAM,CAAC,CAAC,KAAK,EAAE,wBAAwB,GAAG,GAAI,EAAE,QAAQ,CAAC,CAAE;AAAA,MAC3D;AAAA,MACA,YAAY,EAAE;AAAA,IAChB;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,uBAAuB,CAAC,GAAiC,eAA8C;AAClH,MAAI;AACJ,MAAI,OAAO,EAAE,YAAY,UAAU;AACjC,cAAU,KAAK,UAAU,EAAE,OAAO;AAAA,EACpC,WAAW,OAAO,EAAE,YAAY,UAAU;AACxC,cAAU,EAAE;AAAA,EACd,OAAO;AACL,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL;AAAA,MACE,MAAM;AAAA,MACN,MAAM,CAAC,CAAC,KAAK,EAAE,cAAc,GAAG,GAAI,EAAE,QAAQ,CAAC,CAAE;AAAA,MACjD;AAAA,MACA,YAAY,EAAE;AAAA,IAChB;AAAA,IACA;AAAA,EACF;AACF;", + "names": ["bytesToHex", "i", "bytesToHex"] +} diff --git a/node_modules/nostr-tools/lib/esm/nip29.js b/node_modules/nostr-tools/lib/esm/nip29.js new file mode 100644 index 0000000..6d27d67 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip29.js @@ -0,0 +1,472 @@ +// nip11.ts +var _fetch; +try { + _fetch = fetch; +} catch { +} +async function fetchRelayInformation(url) { + return await (await fetch(url.replace("ws://", "http://").replace("wss://", "https://"), { + headers: { Accept: "application/nostr+json" } + })).json(); +} + +// nip19.ts +import { bytesToHex as bytesToHex2, concatBytes, hexToBytes as hexToBytes2 } from "@noble/hashes/utils"; +import { bech32 } from "@scure/base"; + +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); +function normalizeURL(url) { + try { + if (url.indexOf("://") === -1) + url = "wss://" + url; + let p = new URL(url); + p.pathname = p.pathname.replace(/\/+/g, "/"); + if (p.pathname.endsWith("/")) + p.pathname = p.pathname.slice(0, -1); + if (p.port === "80" && p.protocol === "ws:" || p.port === "443" && p.protocol === "wss:") + p.port = ""; + p.searchParams.sort(); + p.hash = ""; + return p.toString(); + } catch (e) { + throw new Error(`Invalid URL: ${url}`); + } +} + +// nip19.ts +var NostrTypeGuard = { + isNProfile: (value) => /^nprofile1[a-z\d]+$/.test(value || ""), + isNEvent: (value) => /^nevent1[a-z\d]+$/.test(value || ""), + isNAddr: (value) => /^naddr1[a-z\d]+$/.test(value || ""), + isNSec: (value) => /^nsec1[a-z\d]{58}$/.test(value || ""), + isNPub: (value) => /^npub1[a-z\d]{58}$/.test(value || ""), + isNote: (value) => /^note1[a-z\d]+$/.test(value || ""), + isNcryptsec: (value) => /^ncryptsec1[a-z\d]+$/.test(value || "") +}; +var Bech32MaxSize = 5e3; +function decode(code) { + let { prefix, words } = bech32.decode(code, Bech32MaxSize); + let data = new Uint8Array(bech32.fromWords(words)); + switch (prefix) { + case "nprofile": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nprofile"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + return { + type: "nprofile", + data: { + pubkey: bytesToHex2(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nevent": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nevent"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + if (tlv[2] && tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (tlv[3] && tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "nevent", + data: { + id: bytesToHex2(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [], + author: tlv[2]?.[0] ? bytesToHex2(tlv[2][0]) : void 0, + kind: tlv[3]?.[0] ? parseInt(bytesToHex2(tlv[3][0]), 16) : void 0 + } + }; + } + case "naddr": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for naddr"); + if (!tlv[2]?.[0]) + throw new Error("missing TLV 2 for naddr"); + if (tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (!tlv[3]?.[0]) + throw new Error("missing TLV 3 for naddr"); + if (tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "naddr", + data: { + identifier: utf8Decoder.decode(tlv[0][0]), + pubkey: bytesToHex2(tlv[2][0]), + kind: parseInt(bytesToHex2(tlv[3][0]), 16), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nsec": + return { type: prefix, data }; + case "npub": + case "note": + return { type: prefix, data: bytesToHex2(data) }; + default: + throw new Error(`unknown prefix ${prefix}`); + } +} +function parseTLV(data) { + let result = {}; + let rest = data; + while (rest.length > 0) { + let t = rest[0]; + let l = rest[1]; + let v = rest.slice(2, 2 + l); + rest = rest.slice(2 + l); + if (v.length < l) + throw new Error(`not enough data to read on TLV ${t}`); + result[t] = result[t] || []; + result[t].push(v); + } + return result; +} + +// nip29.ts +var GroupAdminPermission = /* @__PURE__ */ ((GroupAdminPermission2) => { + GroupAdminPermission2["AddUser"] = "add-user"; + GroupAdminPermission2["EditMetadata"] = "edit-metadata"; + GroupAdminPermission2["DeleteEvent"] = "delete-event"; + GroupAdminPermission2["RemoveUser"] = "remove-user"; + GroupAdminPermission2["AddPermission"] = "add-permission"; + GroupAdminPermission2["RemovePermission"] = "remove-permission"; + GroupAdminPermission2["EditGroupStatus"] = "edit-group-status"; + GroupAdminPermission2["PutUser"] = "put-user"; + GroupAdminPermission2["CreateGroup"] = "create-group"; + GroupAdminPermission2["DeleteGroup"] = "delete-group"; + GroupAdminPermission2["CreateInvite"] = "create-invite"; + return GroupAdminPermission2; +})(GroupAdminPermission || {}); +function generateGroupMetadataEventTemplate(group) { + const tags = [["d", group.metadata.id]]; + group.metadata.name && tags.push(["name", group.metadata.name]); + group.metadata.picture && tags.push(["picture", group.metadata.picture]); + group.metadata.about && tags.push(["about", group.metadata.about]); + group.metadata.isPublic && tags.push(["public"]); + group.metadata.isOpen && tags.push(["open"]); + return { + content: "", + created_at: Math.floor(Date.now() / 1e3), + kind: 39e3, + tags + }; +} +function validateGroupMetadataEvent(event) { + if (event.kind !== 39e3) + return false; + if (!event.pubkey) + return false; + const requiredTags = ["d"]; + for (const tag of requiredTags) { + if (!event.tags.find(([t]) => t == tag)) + return false; + } + return true; +} +function generateGroupAdminsEventTemplate(group, admins) { + const tags = [["d", group.metadata.id]]; + for (const admin of admins) { + tags.push(["p", admin.pubkey, admin.label || "", ...admin.permissions]); + } + return { + content: "", + created_at: Math.floor(Date.now() / 1e3), + kind: 39001, + tags + }; +} +function validateGroupAdminsEvent(event) { + if (event.kind !== 39001) + return false; + const requiredTags = ["d"]; + for (const tag of requiredTags) { + if (!event.tags.find(([t]) => t == tag)) + return false; + } + for (const [tag, _value, _label, ...permissions] of event.tags) { + if (tag !== "p") + continue; + for (let i = 0; i < permissions.length; i += 1) { + if (typeof permissions[i] !== "string") + return false; + if (!Object.values(GroupAdminPermission).includes(permissions[i])) + return false; + } + } + return true; +} +function generateGroupMembersEventTemplate(group, members) { + const tags = [["d", group.metadata.id]]; + for (const member of members) { + tags.push(["p", member.pubkey, member.label || ""]); + } + return { + content: "", + created_at: Math.floor(Date.now() / 1e3), + kind: 39002, + tags + }; +} +function validateGroupMembersEvent(event) { + if (event.kind !== 39002) + return false; + const requiredTags = ["d"]; + for (const tag of requiredTags) { + if (!event.tags.find(([t]) => t == tag)) + return false; + } + return true; +} +function getNormalizedRelayURLByGroupReference(groupReference) { + return normalizeURL(groupReference.host); +} +async function fetchRelayInformationByGroupReference(groupReference) { + const normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference); + return fetchRelayInformation(normalizedRelayURL); +} +async function fetchGroupMetadataEvent({ + pool, + groupReference, + relayInformation, + normalizedRelayURL +}) { + if (!normalizedRelayURL) { + normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference); + } + if (!relayInformation) { + relayInformation = await fetchRelayInformation(normalizedRelayURL); + } + const groupMetadataEvent = await pool.get([normalizedRelayURL], { + kinds: [39e3], + authors: [relayInformation.pubkey], + "#d": [groupReference.id] + }); + if (!groupMetadataEvent) + throw new Error(`group '${groupReference.id}' not found on ${normalizedRelayURL}`); + return groupMetadataEvent; +} +function parseGroupMetadataEvent(event) { + if (!validateGroupMetadataEvent(event)) + throw new Error("invalid group metadata event"); + const metadata = { + id: "", + pubkey: event.pubkey + }; + for (const [tag, value] of event.tags) { + switch (tag) { + case "d": + metadata.id = value; + break; + case "name": + metadata.name = value; + break; + case "picture": + metadata.picture = value; + break; + case "about": + metadata.about = value; + break; + case "public": + metadata.isPublic = true; + break; + case "open": + metadata.isOpen = true; + break; + } + } + return metadata; +} +async function fetchGroupAdminsEvent({ + pool, + groupReference, + relayInformation, + normalizedRelayURL +}) { + if (!normalizedRelayURL) { + normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference); + } + if (!relayInformation) { + relayInformation = await fetchRelayInformation(normalizedRelayURL); + } + const groupAdminsEvent = await pool.get([normalizedRelayURL], { + kinds: [39001], + authors: [relayInformation.pubkey], + "#d": [groupReference.id] + }); + if (!groupAdminsEvent) + throw new Error(`admins for group '${groupReference.id}' not found on ${normalizedRelayURL}`); + return groupAdminsEvent; +} +function parseGroupAdminsEvent(event) { + if (!validateGroupAdminsEvent(event)) + throw new Error("invalid group admins event"); + const admins = []; + for (const [tag, value, label, ...permissions] of event.tags) { + if (tag !== "p") + continue; + admins.push({ + pubkey: value, + label, + permissions + }); + } + return admins; +} +async function fetchGroupMembersEvent({ + pool, + groupReference, + relayInformation, + normalizedRelayURL +}) { + if (!normalizedRelayURL) { + normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference); + } + if (!relayInformation) { + relayInformation = await fetchRelayInformation(normalizedRelayURL); + } + const groupMembersEvent = await pool.get([normalizedRelayURL], { + kinds: [39002], + authors: [relayInformation.pubkey], + "#d": [groupReference.id] + }); + if (!groupMembersEvent) + throw new Error(`members for group '${groupReference.id}' not found on ${normalizedRelayURL}`); + return groupMembersEvent; +} +function parseGroupMembersEvent(event) { + if (!validateGroupMembersEvent(event)) + throw new Error("invalid group members event"); + const members = []; + for (const [tag, value, label] of event.tags) { + if (tag !== "p") + continue; + members.push({ + pubkey: value, + label + }); + } + return members; +} +async function loadGroup({ + pool, + groupReference, + normalizedRelayURL, + relayInformation +}) { + if (!normalizedRelayURL) { + normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference); + } + if (!relayInformation) { + relayInformation = await fetchRelayInformation(normalizedRelayURL); + } + const metadataEvent = await fetchGroupMetadataEvent({ pool, groupReference, normalizedRelayURL, relayInformation }); + const metadata = parseGroupMetadataEvent(metadataEvent); + const adminsEvent = await fetchGroupAdminsEvent({ pool, groupReference, normalizedRelayURL, relayInformation }); + const admins = parseGroupAdminsEvent(adminsEvent); + const membersEvent = await fetchGroupMembersEvent({ pool, groupReference, normalizedRelayURL, relayInformation }); + const members = parseGroupMembersEvent(membersEvent); + const group = { + relay: normalizedRelayURL, + metadata, + admins, + members, + reference: groupReference + }; + return group; +} +async function loadGroupFromCode(pool, code) { + const groupReference = parseGroupCode(code); + if (!groupReference) + throw new Error("invalid group code"); + return loadGroup({ pool, groupReference }); +} +function parseGroupCode(code) { + if (NostrTypeGuard.isNAddr(code)) { + try { + let { data } = decode(code); + let { relays, identifier } = data; + if (!relays || relays.length === 0) + return null; + let host = relays[0]; + if (host.startsWith("wss://")) { + host = host.slice(6); + } + return { host, id: identifier }; + } catch (err) { + return null; + } + } else if (code.split("'").length === 2) { + let spl = code.split("'"); + return { host: spl[0], id: spl[1] }; + } + return null; +} +function encodeGroupReference(gr) { + const { host, id } = gr; + const normalizedHost = host.replace(/^(https?:\/\/|wss?:\/\/)/, ""); + return `${normalizedHost}'${id}`; +} +function subscribeRelayGroupsMetadataEvents({ + pool, + relayURL, + onError, + onEvent, + onConnect +}) { + let sub; + const normalizedRelayURL = normalizeURL(relayURL); + fetchRelayInformation(normalizedRelayURL).then(async (info) => { + const abstractedRelay = await pool.ensureRelay(normalizedRelayURL); + onConnect?.(); + sub = abstractedRelay.prepareSubscription( + [ + { + kinds: [39e3], + limit: 50, + authors: [info.pubkey] + } + ], + { + onevent(event) { + onEvent(event); + } + } + ); + }).catch((err) => { + sub.close(); + onError(err); + }); + return () => sub.close(); +} +export { + GroupAdminPermission, + encodeGroupReference, + fetchGroupAdminsEvent, + fetchGroupMembersEvent, + fetchGroupMetadataEvent, + fetchRelayInformationByGroupReference, + generateGroupAdminsEventTemplate, + generateGroupMembersEventTemplate, + generateGroupMetadataEventTemplate, + getNormalizedRelayURLByGroupReference, + loadGroup, + loadGroupFromCode, + parseGroupAdminsEvent, + parseGroupCode, + parseGroupMembersEvent, + parseGroupMetadataEvent, + subscribeRelayGroupsMetadataEvents, + validateGroupAdminsEvent, + validateGroupMembersEvent, + validateGroupMetadataEvent +}; diff --git a/node_modules/nostr-tools/lib/esm/nip29.js.map b/node_modules/nostr-tools/lib/esm/nip29.js.map new file mode 100644 index 0000000..02133c4 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip29.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip11.ts", "../../nip19.ts", "../../utils.ts", "../../nip29.ts"], + "sourcesContent": ["var _fetch: any\n\ntry {\n _fetch = fetch\n} catch {}\n\nexport function useFetchImplementation(fetchImplementation: any): void {\n _fetch = fetchImplementation\n}\n\nexport async function fetchRelayInformation(url: string): Promise {\n return (await (\n await fetch(url.replace('ws://', 'http://').replace('wss://', 'https://'), {\n headers: { Accept: 'application/nostr+json' },\n })\n ).json()) as RelayInformation\n}\n\n/**\n * ## Relay Information Document\n\n * Relays may provide server metadata to clients to inform\n * them of capabilities, administrative contacts, and\n * various server attributes. This is made available as a\n * JSON document over HTTP, on the same URI as the relay's\n * websocket.\n\n * Any field may be omitted, and clients MUST ignore any\n * additional fields they do not understand. Relays MUST\n * accept CORS requests by sending\n * `Access-Control-Allow-Origin`,\n * `Access-Control-Allow-Headers`, and\n * `Access-Control-Allow-Methods` headers.\n * @param name string identifying relay\n * @param description string with detailed information\n * @param pubkey administrative contact pubkey\n * @param contact: administrative alternate contact\n * @param supported_nips a list of NIP numbers supported by\n * the relay\n * @param software identifying relay software URL\n * @param version string version identifier\n */\nexport interface BasicRelayInformation {\n // string identifying relay\n name: string\n description: string\n pubkey: string\n contact: string\n supported_nips: number[]\n software: string\n version: string\n // limitation?: Limitations\n}\n\n/**\n * * ## Extra Fields\n\n * * ### Server Limitations\n\n * These are limitations imposed by the relay on clients.\n * Your client should expect that requests which exceed\n * these practical_ limitations are rejected or fail immediately.\n * @param max_message_length this is the maximum number of\n * bytes for incoming JSON that the relay will attempt to\n * decode and act upon. When you send large subscriptions,\n * you will be limited by this value. It also effectively\n * limits the maximum size of any event. Value is calculated\n * from `[` to `]` and is after UTF-8 serialization (so some\n * unicode characters will cost 2-3 bytes). It is equal to\n * the maximum size of the WebSocket message frame.\n * @param max_subscriptions total number of subscriptions\n * that may be active on a single websocket connection to\n * this relay. It's possible that authenticated clients with\n * a (paid) relationship to the relay may have higher limits.\n * @param max_filters maximum number of filter values in\n * each subscription. Must be one or higher.\n * @param max_limit the relay server will clamp each\n * filter's `limit` value to this number.\n * This means the client won't be able to get more than this\n * number of events from a single subscription filter. This\n * clamping is typically done silently by the relay, but\n * with this number, you can know that there are additional\n * results if you narrowed your filter's time range or other\n * parameters.\n * @param max_subid_length maximum length of subscription id as a\n * string.\n * @param min_prefix for `authors` and `ids` filters which\n * are to match against a hex prefix, you must provide at\n * least this many hex digits in the prefix.\n * @param max_event_tags in any event, this is the maximum\n * number of elements in the `tags` list.\n * @param max_content_length maximum number of characters in\n * the `content` field of any event. This is a count of\n * unicode characters. After serializing into JSON it may be\n * larger (in bytes), and is still subject to the\n * max_message_length`, if defined.\n * @param min_pow_difficulty new events will require at\n * least this difficulty of PoW, based on [NIP-13](13.md),\n * or they will be rejected by this server.\n * @param auth_required this relay requires [NIP-42](42.md)\n * authentication to happen before a new connection may\n * perform any other action. Even if set to False,\n * authentication may be required for specific actions.\n * @param restricted_writes: this relay requires some kind\n * of condition to be fulfilled in order to accept events\n * (not necessarily, but including\n * @param payment_required this relay requires payment\n * before a new connection may perform any action.\n * @param created_at_lower_limit: 'created_at' lower limit\n * @param created_at_upper_limit: 'created_at' upper limit\n */\nexport interface Limitations {\n max_message_length: number\n max_subscriptions: number\n max_filters: number\n max_limit: number\n max_subid_length: number\n min_prefix: number\n max_event_tags: number\n max_content_length: number\n min_pow_difficulty: number\n auth_required: boolean\n payment_required: boolean\n created_at_lower_limit: number\n created_at_upper_limit: number\n restricted_writes: boolean\n}\n\nexport interface RetentionDetails {\n kinds: (number | number[])[]\n time?: number | null\n count?: number | null\n}\ntype AnyRetentionDetails = RetentionDetails\n/**\n * ### Event Retention\n\n * There may be a cost associated with storing data forever,\n * so relays may wish to state retention times. The values\n * stated here are defaults for unauthenticated users and\n * visitors. Paid users would likely have other policies.\n\n * Retention times are given in seconds, with `null`\n * indicating infinity. If zero is provided, this means the\n * event will not be stored at all, and preferably an error\n * will be provided when those are received.\n * ```json\n{\n...\n \"retention\": [\n { \"kinds\": [0, 1, [5, 7], [40, 49]], \"time\": 3600 },\n { \"kinds\": [[40000, 49999]], \"time\": 100 },\n { \"kinds\": [[30000, 39999]], \"count\": 1000 },\n { \"time\": 3600, \"count\": 10000 }\n ]\n...\n}\n```\n * @param retention is a list of specifications: each will\n * apply to either all kinds, or a subset of kinds. Ranges\n * may be specified for the kind field as a tuple of\n * inclusive start and end values. Events of indicated kind\n * (or all) are then limited to a `count` and/or time\n * period.\n\n * It is possible to effectively blacklist Nostr-based\n * protocols that rely on a specific `kind` number, by\n * giving a retention time of zero for those `kind` values.\n * While that is unfortunate, it does allow clients to\n * discover servers that will support their protocol quickly\n * via a single HTTP fetch.\n\n * There is no need to specify retention times for\n * _ephemeral events_ as defined in [NIP-16](16.md) since\n * they are not retained.\n */\nexport interface Retention {\n retention: AnyRetentionDetails[]\n}\n\n/**\n * Some relays may be governed by the arbitrary laws of a\n * nation state. This may limit what content can be stored\n * in cleartext on those relays. All clients are encouraged\n * to use encryption to work around this limitation.\n\n * It is not possible to describe the limitations of each\n * country's laws and policies which themselves are\n * typically vague and constantly shifting.\n\n * Therefore, this field allows the relay operator to\n * indicate which countries' laws might end up being\n * enforced on them, and then indirectly on their users'\n * content.\n\n * Users should be able to avoid relays in countries they\n * don't like, and/or select relays in more favourable\n * zones. Exposing this flexibility is up to the client\n * software.\n\n * @param relay_countries a list of two-level ISO country\n * codes (ISO 3166-1 alpha-2) whose laws and policies may\n * affect this relay. `EU` may be used for European Union\n * countries.\n\n * Remember that a relay may be hosted in a country which is\n * not the country of the legal entities who own the relay,\n * so it's very likely a number of countries are involved.\n */\nexport interface ContentLimitations {\n relay_countries: string[]\n}\n\n/**\n * ### Community Preferences\n\n * For public text notes at least, a relay may try to foster\n * a local community. This would encourage users to follow\n * the global feed on that relay, in addition to their usual\n * individual follows. To support this goal, relays MAY\n * specify some of the following values.\n\n * @param language_tags is an ordered list of [IETF\n * language\n * tags](https://en.wikipedia.org/wiki/IETF_language_tag\n * indicating the major languages spoken on the relay.\n * @param tags is a list of limitations on the topics to be\n * discussed. For example `sfw-only` indicates that only\n * \"Safe For Work\" content is encouraged on this relay. This\n * relies on assumptions of what the \"work\" \"community\"\n * feels \"safe\" talking about. In time, a common set of tags\n * may emerge that allow users to find relays that suit\n * their needs, and client software will be able to parse\n * these tags easily. The `bitcoin-only` tag indicates that\n * any _altcoin_, _\"crypto\"_ or _blockchain_ comments will\n * be ridiculed without mercy.\n * @param posting_policy is a link to a human-readable page\n * which specifies the community policies for the relay. In\n * cases where `sfw-only` is True, it's important to link to\n * a page which gets into the specifics of your posting\n * policy.\n\n * The `description` field should be used to describe your\n * community goals and values, in brief. The\n * `posting_policy` is for additional detail and legal\n * terms. Use the `tags` field to signify limitations on\n * content, or topics to be discussed, which could be\n * machine processed by appropriate client software.\n */\nexport interface CommunityPreferences {\n language_tags: string[]\n tags: string[]\n posting_policy: string\n}\n\nexport interface Amount {\n amount: number\n unit: 'msat'\n}\nexport interface PublicationAmount extends Amount {\n kinds: number[]\n}\nexport interface Subscription extends Amount {\n period: number\n}\nexport interface Fees {\n admission: Amount[]\n subscription: Subscription[]\n publication: PublicationAmount[]\n}\n/**\n * Relays that require payments may want to expose their fee\n * schedules.\n */\nexport interface PayToRelay {\n payments_url: string\n fees: Fees\n}\n\n/**\n * A URL pointing to an image to be used as an icon for the\n * relay. Recommended to be squared in shape.\n */\nexport interface Icon {\n icon: string\n}\n\nexport type RelayInformation = BasicRelayInformation &\n Partial & {\n limitation?: Partial\n } & Partial &\n Partial &\n Partial &\n Partial\n", "import { bytesToHex, concatBytes, hexToBytes } from '@noble/hashes/utils'\nimport { bech32 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport type NProfile = `nprofile1${string}`\nexport type NEvent = `nevent1${string}`\nexport type NAddr = `naddr1${string}`\nexport type NSec = `nsec1${string}`\nexport type NPub = `npub1${string}`\nexport type Note = `note1${string}`\nexport type Ncryptsec = `ncryptsec1${string}`\n\nexport const NostrTypeGuard = {\n isNProfile: (value?: string | null): value is NProfile => /^nprofile1[a-z\\d]+$/.test(value || ''),\n isNEvent: (value?: string | null): value is NEvent => /^nevent1[a-z\\d]+$/.test(value || ''),\n isNAddr: (value?: string | null): value is NAddr => /^naddr1[a-z\\d]+$/.test(value || ''),\n isNSec: (value?: string | null): value is NSec => /^nsec1[a-z\\d]{58}$/.test(value || ''),\n isNPub: (value?: string | null): value is NPub => /^npub1[a-z\\d]{58}$/.test(value || ''),\n isNote: (value?: string | null): value is Note => /^note1[a-z\\d]+$/.test(value || ''),\n isNcryptsec: (value?: string | null): value is Ncryptsec => /^ncryptsec1[a-z\\d]+$/.test(value || ''),\n}\n\nexport const Bech32MaxSize = 5000\n\n/**\n * Bech32 regex.\n * @see https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32\n */\nexport const BECH32_REGEX = /[\\x21-\\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/\n\nfunction integerToUint8Array(number: number) {\n // Create a Uint8Array with enough space to hold a 32-bit integer (4 bytes).\n const uint8Array = new Uint8Array(4)\n\n // Use bitwise operations to extract the bytes.\n uint8Array[0] = (number >> 24) & 0xff // Most significant byte (MSB)\n uint8Array[1] = (number >> 16) & 0xff\n uint8Array[2] = (number >> 8) & 0xff\n uint8Array[3] = number & 0xff // Least significant byte (LSB)\n\n return uint8Array\n}\n\nexport type ProfilePointer = {\n pubkey: string // hex\n relays?: string[]\n}\n\nexport type EventPointer = {\n id: string // hex\n relays?: string[]\n author?: string\n kind?: number\n}\n\nexport type AddressPointer = {\n identifier: string\n pubkey: string\n kind: number\n relays?: string[]\n}\n\nexport function decodeNostrURI(nip19code: string): ReturnType | { type: 'invalid'; data: null } {\n try {\n if (nip19code.startsWith('nostr:')) nip19code = nip19code.substring(6)\n return decode(nip19code)\n } catch (_err) {\n return { type: 'invalid', data: null }\n }\n}\n\nexport type DecodedNevent = {\n type: 'nevent'\n data: EventPointer\n}\n\nexport type DecodedNprofile = {\n type: 'nprofile'\n data: ProfilePointer\n}\n\nexport type DecodedNaddr = {\n type: 'naddr'\n data: AddressPointer\n}\n\nexport type DecodedNsec = {\n type: 'nsec'\n data: Uint8Array\n}\n\nexport type DecodedNpub = {\n type: 'npub'\n data: string\n}\n\nexport type DecodedNote = {\n type: 'note'\n data: string\n}\n\nexport type DecodedResult = DecodedNevent | DecodedNprofile | DecodedNaddr | DecodedNpub | DecodedNsec | DecodedNote\n\nexport function decode(nip19: NEvent): DecodedNevent\nexport function decode(nip19: NProfile): DecodedNprofile\nexport function decode(nip19: NAddr): DecodedNaddr\nexport function decode(nip19: NSec): DecodedNsec\nexport function decode(nip19: NPub): DecodedNpub\nexport function decode(nip19: Note): DecodedNote\nexport function decode(code: string): DecodedResult\nexport function decode(code: string): DecodedResult {\n let { prefix, words } = bech32.decode(code, Bech32MaxSize)\n let data = new Uint8Array(bech32.fromWords(words))\n\n switch (prefix) {\n case 'nprofile': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nprofile')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n\n return {\n type: 'nprofile',\n data: {\n pubkey: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n case 'nevent': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nevent')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n if (tlv[2] && tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (tlv[3] && tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'nevent',\n data: {\n id: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n author: tlv[2]?.[0] ? bytesToHex(tlv[2][0]) : undefined,\n kind: tlv[3]?.[0] ? parseInt(bytesToHex(tlv[3][0]), 16) : undefined,\n },\n }\n }\n\n case 'naddr': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for naddr')\n if (!tlv[2]?.[0]) throw new Error('missing TLV 2 for naddr')\n if (tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (!tlv[3]?.[0]) throw new Error('missing TLV 3 for naddr')\n if (tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'naddr',\n data: {\n identifier: utf8Decoder.decode(tlv[0][0]),\n pubkey: bytesToHex(tlv[2][0]),\n kind: parseInt(bytesToHex(tlv[3][0]), 16),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n\n case 'nsec':\n return { type: prefix, data }\n\n case 'npub':\n case 'note':\n return { type: prefix, data: bytesToHex(data) }\n\n default:\n throw new Error(`unknown prefix ${prefix}`)\n }\n}\n\ntype TLV = { [t: number]: Uint8Array[] }\n\nfunction parseTLV(data: Uint8Array): TLV {\n let result: TLV = {}\n let rest = data\n while (rest.length > 0) {\n let t = rest[0]\n let l = rest[1]\n let v = rest.slice(2, 2 + l)\n rest = rest.slice(2 + l)\n if (v.length < l) throw new Error(`not enough data to read on TLV ${t}`)\n result[t] = result[t] || []\n result[t].push(v)\n }\n return result\n}\n\nexport function nsecEncode(key: Uint8Array): NSec {\n return encodeBytes('nsec', key)\n}\n\nexport function npubEncode(hex: string): NPub {\n return encodeBytes('npub', hexToBytes(hex))\n}\n\nexport function noteEncode(hex: string): Note {\n return encodeBytes('note', hexToBytes(hex))\n}\n\nfunction encodeBech32(prefix: Prefix, data: Uint8Array): `${Prefix}1${string}` {\n let words = bech32.toWords(data)\n return bech32.encode(prefix, words, Bech32MaxSize) as `${Prefix}1${string}`\n}\n\nexport function encodeBytes(prefix: Prefix, bytes: Uint8Array): `${Prefix}1${string}` {\n return encodeBech32(prefix, bytes)\n}\n\nexport function nprofileEncode(profile: ProfilePointer): NProfile {\n let data = encodeTLV({\n 0: [hexToBytes(profile.pubkey)],\n 1: (profile.relays || []).map(url => utf8Encoder.encode(url)),\n })\n return encodeBech32('nprofile', data)\n}\n\nexport function neventEncode(event: EventPointer): NEvent {\n let kindArray\n if (event.kind !== undefined) {\n kindArray = integerToUint8Array(event.kind)\n }\n\n let data = encodeTLV({\n 0: [hexToBytes(event.id)],\n 1: (event.relays || []).map(url => utf8Encoder.encode(url)),\n 2: event.author ? [hexToBytes(event.author)] : [],\n 3: kindArray ? [new Uint8Array(kindArray)] : [],\n })\n\n return encodeBech32('nevent', data)\n}\n\nexport function naddrEncode(addr: AddressPointer): NAddr {\n let kind = new ArrayBuffer(4)\n new DataView(kind).setUint32(0, addr.kind, false)\n\n let data = encodeTLV({\n 0: [utf8Encoder.encode(addr.identifier)],\n 1: (addr.relays || []).map(url => utf8Encoder.encode(url)),\n 2: [hexToBytes(addr.pubkey)],\n 3: [new Uint8Array(kind)],\n })\n return encodeBech32('naddr', data)\n}\n\nfunction encodeTLV(tlv: TLV): Uint8Array {\n let entries: Uint8Array[] = []\n\n Object.entries(tlv)\n .reverse()\n .forEach(([t, vs]) => {\n vs.forEach(v => {\n let entry = new Uint8Array(v.length + 2)\n entry.set([parseInt(t)], 0)\n entry.set([v.length], 1)\n entry.set(v, 2)\n entries.push(entry)\n })\n })\n\n return concatBytes(...entries)\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { AbstractSimplePool } from './abstract-pool.ts'\nimport { Subscription } from './abstract-relay.ts'\nimport type { Event, EventTemplate } from './core.ts'\nimport { fetchRelayInformation, RelayInformation } from './nip11.ts'\nimport { decode, NostrTypeGuard } from './nip19.ts'\nimport { normalizeURL } from './utils.ts'\n\n/**\n * Represents a NIP29 group.\n */\nexport type Group = {\n relay: string\n metadata: GroupMetadata\n admins?: GroupAdmin[]\n members?: GroupMember[]\n reference: GroupReference\n}\n\n/**\n * Represents the metadata for a NIP29 group.\n */\nexport type GroupMetadata = {\n id: string\n pubkey: string\n name?: string\n picture?: string\n about?: string\n isPublic?: boolean\n isOpen?: boolean\n}\n\n/**\n * Represents a NIP29 group reference.\n */\nexport type GroupReference = {\n id: string\n host: string\n}\n\n/**\n * Represents a NIP29 group member.\n */\nexport type GroupMember = {\n pubkey: string\n label?: string\n}\n\n/**\n * Represents a NIP29 group admin.\n */\nexport type GroupAdmin = {\n pubkey: string\n label?: string\n permissions: GroupAdminPermission[]\n}\n\n/**\n * Represents the permissions that a NIP29 group admin can have.\n */\nexport enum GroupAdminPermission {\n /** @deprecated use PutUser instead */\n AddUser = 'add-user',\n EditMetadata = 'edit-metadata',\n DeleteEvent = 'delete-event',\n RemoveUser = 'remove-user',\n /** @deprecated removed from NIP */\n AddPermission = 'add-permission',\n /** @deprecated removed from NIP */\n RemovePermission = 'remove-permission',\n /** @deprecated removed from NIP */\n EditGroupStatus = 'edit-group-status',\n PutUser = 'put-user',\n CreateGroup = 'create-group',\n DeleteGroup = 'delete-group',\n CreateInvite = 'create-invite',\n}\n\n/**\n * Generates a group metadata event template.\n *\n * @param group - The group object.\n * @returns An event template with the generated group metadata that can be signed later.\n */\nexport function generateGroupMetadataEventTemplate(group: Group): EventTemplate {\n const tags: string[][] = [['d', group.metadata.id]]\n group.metadata.name && tags.push(['name', group.metadata.name])\n group.metadata.picture && tags.push(['picture', group.metadata.picture])\n group.metadata.about && tags.push(['about', group.metadata.about])\n group.metadata.isPublic && tags.push(['public'])\n group.metadata.isOpen && tags.push(['open'])\n\n return {\n content: '',\n created_at: Math.floor(Date.now() / 1000),\n kind: 39000,\n tags,\n }\n}\n\n/**\n * Validates a group metadata event.\n *\n * @param event - The event to validate.\n * @returns A boolean indicating whether the event is valid.\n */\nexport function validateGroupMetadataEvent(event: Event): boolean {\n if (event.kind !== 39000) return false\n\n if (!event.pubkey) return false\n\n const requiredTags = ['d'] as const\n for (const tag of requiredTags) {\n if (!event.tags.find(([t]) => t == tag)) return false\n }\n\n return true\n}\n\n/**\n * Generates an event template for group admins.\n *\n * @param group - The group object.\n * @param admins - An array of group admins.\n * @returns The generated event template with the group admins that can be signed later.\n */\nexport function generateGroupAdminsEventTemplate(group: Group, admins: GroupAdmin[]): EventTemplate {\n const tags: string[][] = [['d', group.metadata.id]]\n for (const admin of admins) {\n tags.push(['p', admin.pubkey, admin.label || '', ...admin.permissions])\n }\n\n return {\n content: '',\n created_at: Math.floor(Date.now() / 1000),\n kind: 39001,\n tags,\n }\n}\n\n/**\n * Validates a group admins event.\n *\n * @param event - The event to validate.\n * @returns True if the event is valid, false otherwise.\n */\nexport function validateGroupAdminsEvent(event: Event): boolean {\n if (event.kind !== 39001) return false\n\n const requiredTags = ['d'] as const\n for (const tag of requiredTags) {\n if (!event.tags.find(([t]) => t == tag)) return false\n }\n\n // validate permissions\n for (const [tag, _value, _label, ...permissions] of event.tags) {\n if (tag !== 'p') continue\n\n for (let i = 0; i < permissions.length; i += 1) {\n if (typeof permissions[i] !== 'string') return false\n\n // validate permission name from the GroupAdminPermission enum\n if (!Object.values(GroupAdminPermission).includes(permissions[i] as GroupAdminPermission)) return false\n }\n }\n\n return true\n}\n\n/**\n * Generates an event template for a group with its members.\n *\n * @param group - The group object.\n * @param members - An array of group members.\n * @returns The generated event template with the group members that can be signed later.\n */\nexport function generateGroupMembersEventTemplate(group: Group, members: GroupMember[]): EventTemplate {\n const tags: string[][] = [['d', group.metadata.id]]\n for (const member of members) {\n tags.push(['p', member.pubkey, member.label || ''])\n }\n\n return {\n content: '',\n created_at: Math.floor(Date.now() / 1000),\n kind: 39002,\n tags,\n }\n}\n\n/**\n * Validates a group members event.\n *\n * @param event - The event to validate.\n * @returns Returns `true` if the event is a valid group members event, `false` otherwise.\n */\nexport function validateGroupMembersEvent(event: Event): boolean {\n if (event.kind !== 39002) return false\n\n const requiredTags = ['d'] as const\n for (const tag of requiredTags) {\n if (!event.tags.find(([t]) => t == tag)) return false\n }\n\n return true\n}\n\n/**\n * Returns the normalized relay URL based on the provided group reference.\n *\n * @param groupReference - The group reference object containing the host.\n * @returns The normalized relay URL.\n */\nexport function getNormalizedRelayURLByGroupReference(groupReference: GroupReference): string {\n return normalizeURL(groupReference.host)\n}\n\n/**\n * Fetches relay information by group reference.\n *\n * @param groupReference The group reference.\n * @returns A promise that resolves to the relay information.\n */\nexport async function fetchRelayInformationByGroupReference(groupReference: GroupReference): Promise {\n const normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference)\n\n return fetchRelayInformation(normalizedRelayURL)\n}\n\n/**\n * Fetches the group metadata event from the specified pool.\n * If the normalizedRelayURL is not provided, it will be obtained using the groupReference.\n * If the relayInformation is not provided, it will be fetched using the normalizedRelayURL.\n *\n * @param {Object} options - The options object.\n * @param {AbstractSimplePool} options.pool - The pool to fetch the group metadata event from.\n * @param {GroupReference} options.groupReference - The reference to the group.\n * @param {string} [options.normalizedRelayURL] - The normalized URL of the relay.\n * @param {RelayInformation} [options.relayInformation] - The relay information object.\n * @returns {Promise} The group metadata event that can be parsed later to get the group metadata object.\n * @throws {Error} If the group is not found on the specified relay.\n */\nexport async function fetchGroupMetadataEvent({\n pool,\n groupReference,\n relayInformation,\n normalizedRelayURL,\n}: {\n pool: AbstractSimplePool\n groupReference: GroupReference\n normalizedRelayURL?: string\n relayInformation?: RelayInformation\n}): Promise {\n if (!normalizedRelayURL) {\n normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference)\n }\n\n if (!relayInformation) {\n relayInformation = await fetchRelayInformation(normalizedRelayURL)\n }\n\n const groupMetadataEvent = await pool.get([normalizedRelayURL], {\n kinds: [39000],\n authors: [relayInformation.pubkey],\n '#d': [groupReference.id],\n })\n\n if (!groupMetadataEvent) throw new Error(`group '${groupReference.id}' not found on ${normalizedRelayURL}`)\n\n return groupMetadataEvent\n}\n\n/**\n * Parses a group metadata event and returns the corresponding GroupMetadata object.\n *\n * @param event - The event to parse.\n * @returns The parsed GroupMetadata object.\n * @throws An error if the group metadata event is invalid.\n */\nexport function parseGroupMetadataEvent(event: Event): GroupMetadata {\n if (!validateGroupMetadataEvent(event)) throw new Error('invalid group metadata event')\n\n const metadata: GroupMetadata = {\n id: '',\n pubkey: event.pubkey,\n }\n\n for (const [tag, value] of event.tags) {\n switch (tag) {\n case 'd':\n metadata.id = value\n break\n case 'name':\n metadata.name = value\n break\n case 'picture':\n metadata.picture = value\n break\n case 'about':\n metadata.about = value\n break\n case 'public':\n metadata.isPublic = true\n break\n case 'open':\n metadata.isOpen = true\n break\n }\n }\n\n return metadata\n}\n\n/**\n * Fetches the group admins event from the specified pool.\n * If the normalizedRelayURL is not provided, it will be obtained from the groupReference.\n * If the relayInformation is not provided, it will be fetched using the normalizedRelayURL.\n *\n * @param {Object} options - The options object.\n * @param {AbstractSimplePool} options.pool - The pool to fetch the group admins event from.\n * @param {GroupReference} options.groupReference - The reference to the group.\n * @param {string} [options.normalizedRelayURL] - The normalized relay URL.\n * @param {RelayInformation} [options.relayInformation] - The relay information.\n * @returns {Promise} The group admins event that can be parsed later to get the group admins object.\n * @throws {Error} If the group admins event is not found on the specified relay.\n */\nexport async function fetchGroupAdminsEvent({\n pool,\n groupReference,\n relayInformation,\n normalizedRelayURL,\n}: {\n pool: AbstractSimplePool\n groupReference: GroupReference\n normalizedRelayURL?: string\n relayInformation?: RelayInformation\n}): Promise {\n if (!normalizedRelayURL) {\n normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference)\n }\n\n if (!relayInformation) {\n relayInformation = await fetchRelayInformation(normalizedRelayURL)\n }\n\n const groupAdminsEvent = await pool.get([normalizedRelayURL], {\n kinds: [39001],\n authors: [relayInformation.pubkey],\n '#d': [groupReference.id],\n })\n\n if (!groupAdminsEvent) throw new Error(`admins for group '${groupReference.id}' not found on ${normalizedRelayURL}`)\n\n return groupAdminsEvent\n}\n\n/**\n * Parses a group admins event and returns an array of GroupAdmin objects.\n *\n * @param event - The event to parse.\n * @returns An array of GroupAdmin objects.\n * @throws Throws an error if the group admins event is invalid.\n */\nexport function parseGroupAdminsEvent(event: Event): GroupAdmin[] {\n if (!validateGroupAdminsEvent(event)) throw new Error('invalid group admins event')\n\n const admins: GroupAdmin[] = []\n\n for (const [tag, value, label, ...permissions] of event.tags) {\n if (tag !== 'p') continue\n\n admins.push({\n pubkey: value,\n label,\n permissions: permissions as GroupAdminPermission[],\n })\n }\n\n return admins\n}\n\n/**\n * Fetches the group members event from the specified relay.\n * If the normalizedRelayURL is not provided, it will be obtained using the groupReference.\n * If the relayInformation is not provided, it will be fetched using the normalizedRelayURL.\n *\n * @param {Object} options - The options object.\n * @param {AbstractSimplePool} options.pool - The pool object.\n * @param {GroupReference} options.groupReference - The group reference object.\n * @param {string} [options.normalizedRelayURL] - The normalized relay URL.\n * @param {RelayInformation} [options.relayInformation] - The relay information object.\n * @returns {Promise} The group members event that can be parsed later to get the group members object.\n * @throws {Error} If the group members event is not found.\n */\nexport async function fetchGroupMembersEvent({\n pool,\n groupReference,\n relayInformation,\n normalizedRelayURL,\n}: {\n pool: AbstractSimplePool\n groupReference: GroupReference\n normalizedRelayURL?: string\n relayInformation?: RelayInformation\n}): Promise {\n if (!normalizedRelayURL) {\n normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference)\n }\n\n if (!relayInformation) {\n relayInformation = await fetchRelayInformation(normalizedRelayURL)\n }\n\n const groupMembersEvent = await pool.get([normalizedRelayURL], {\n kinds: [39002],\n authors: [relayInformation.pubkey],\n '#d': [groupReference.id],\n })\n\n if (!groupMembersEvent) throw new Error(`members for group '${groupReference.id}' not found on ${normalizedRelayURL}`)\n\n return groupMembersEvent\n}\n\n/**\n * Parses a group members event and returns an array of GroupMember objects.\n * @param event - The event to parse.\n * @returns An array of GroupMember objects.\n * @throws Throws an error if the group members event is invalid.\n */\nexport function parseGroupMembersEvent(event: Event): GroupMember[] {\n if (!validateGroupMembersEvent(event)) throw new Error('invalid group members event')\n\n const members: GroupMember[] = []\n\n for (const [tag, value, label] of event.tags) {\n if (tag !== 'p') continue\n\n members.push({\n pubkey: value,\n label,\n })\n }\n\n return members\n}\n\n/**\n * Fetches and parses the group metadata event, group admins event, and group members event from the specified pool.\n * If the normalized relay URL is not provided, it will be obtained using the group reference.\n * If the relay information is not provided, it will be fetched using the normalized relay URL.\n *\n * @param {Object} options - The options for loading the group.\n * @param {AbstractSimplePool} options.pool - The pool to load the group from.\n * @param {GroupReference} options.groupReference - The reference of the group to load.\n * @param {string} [options.normalizedRelayURL] - The normalized URL of the relay to use.\n * @param {RelayInformation} [options.relayInformation] - The relay information to use.\n * @returns {Promise} A promise that resolves to the loaded group.\n */\nexport async function loadGroup({\n pool,\n groupReference,\n normalizedRelayURL,\n relayInformation,\n}: {\n pool: AbstractSimplePool\n groupReference: GroupReference\n normalizedRelayURL?: string\n relayInformation?: RelayInformation\n}): Promise {\n if (!normalizedRelayURL) {\n normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference)\n }\n\n if (!relayInformation) {\n relayInformation = await fetchRelayInformation(normalizedRelayURL)\n }\n\n const metadataEvent = await fetchGroupMetadataEvent({ pool, groupReference, normalizedRelayURL, relayInformation })\n const metadata = parseGroupMetadataEvent(metadataEvent)\n\n const adminsEvent = await fetchGroupAdminsEvent({ pool, groupReference, normalizedRelayURL, relayInformation })\n const admins = parseGroupAdminsEvent(adminsEvent)\n\n const membersEvent = await fetchGroupMembersEvent({ pool, groupReference, normalizedRelayURL, relayInformation })\n const members = parseGroupMembersEvent(membersEvent)\n\n const group: Group = {\n relay: normalizedRelayURL,\n metadata,\n admins,\n members,\n reference: groupReference,\n }\n\n return group\n}\n\n/**\n * Loads a group from the specified pool using the provided group code.\n *\n * @param {AbstractSimplePool} pool - The pool to load the group from.\n * @param {string} code - The code representing the group.\n * @returns {Promise} - A promise that resolves to the loaded group.\n * @throws {Error} - If the group code is invalid.\n */\nexport async function loadGroupFromCode(pool: AbstractSimplePool, code: string): Promise {\n const groupReference = parseGroupCode(code)\n\n if (!groupReference) throw new Error('invalid group code')\n\n return loadGroup({ pool, groupReference })\n}\n\n/**\n * Parses a group code and returns a GroupReference object.\n *\n * @param code The group code to parse.\n * @returns A GroupReference object if the code is valid, otherwise null.\n */\nexport function parseGroupCode(code: string): null | GroupReference {\n if (NostrTypeGuard.isNAddr(code)) {\n try {\n let { data } = decode(code)\n\n let { relays, identifier } = data\n if (!relays || relays.length === 0) return null\n\n let host = relays![0]\n if (host.startsWith('wss://')) {\n host = host.slice(6)\n }\n return { host, id: identifier }\n } catch (err) {\n return null\n }\n } else if (code.split(\"'\").length === 2) {\n let spl = code.split(\"'\")\n return { host: spl[0], id: spl[1] }\n }\n\n return null\n}\n\n/**\n * Encodes a group reference into a string.\n *\n * @param gr - The group reference to encode.\n * @returns The encoded group reference as a string.\n */\nexport function encodeGroupReference(gr: GroupReference): string {\n const { host, id } = gr\n const normalizedHost = host.replace(/^(https?:\\/\\/|wss?:\\/\\/)/, '')\n\n return `${normalizedHost}'${id}`\n}\n\n/**\n * Subscribes to relay groups metadata events and calls the provided event handler function\n * when an event is received.\n *\n * @param {Object} options - The options for subscribing to relay groups metadata events.\n * @param {AbstractSimplePool} options.pool - The pool to subscribe to.\n * @param {string} options.relayURL - The URL of the relay.\n * @param {Function} options.onError - The error handler function.\n * @param {Function} options.onEvent - The event handler function.\n * @param {Function} [options.onConnect] - The connect handler function.\n * @returns {Function} - A function to close the subscription\n */\nexport function subscribeRelayGroupsMetadataEvents({\n pool,\n relayURL,\n onError,\n onEvent,\n onConnect,\n}: {\n pool: AbstractSimplePool\n relayURL: string\n onError: (err: Error) => void\n onEvent: (event: Event) => void\n onConnect?: () => void\n}): () => void {\n let sub: Subscription\n\n const normalizedRelayURL = normalizeURL(relayURL)\n\n fetchRelayInformation(normalizedRelayURL)\n .then(async info => {\n const abstractedRelay = await pool.ensureRelay(normalizedRelayURL)\n\n onConnect?.()\n\n sub = abstractedRelay.prepareSubscription(\n [\n {\n kinds: [39000],\n limit: 50,\n authors: [info.pubkey],\n },\n ],\n {\n onevent(event: Event) {\n onEvent(event)\n },\n },\n )\n })\n .catch(err => {\n sub.close()\n\n onError(err)\n })\n\n return () => sub.close()\n}\n"], + "mappings": ";AAAA,IAAI;AAEJ,IAAI;AACF,WAAS;AACX,QAAE;AAAO;AAMT,eAAsB,sBAAsB,KAAwC;AAClF,SAAQ,OACN,MAAM,MAAM,IAAI,QAAQ,SAAS,SAAS,EAAE,QAAQ,UAAU,UAAU,GAAG;AAAA,IACzE,SAAS,EAAE,QAAQ,yBAAyB;AAAA,EAC9C,CAAC,GACD,KAAK;AACT;;;AChBA,SAAS,cAAAA,aAAY,aAAa,cAAAC,mBAAkB;AACpD,SAAS,cAAc;;;ACIvB,SAAS,YAAY,kBAAkB;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;AAIjD,SAAS,aAAa,KAAqB;AAChD,MAAI;AACF,QAAI,IAAI,QAAQ,KAAK,MAAM;AAAI,YAAM,WAAW;AAChD,QAAI,IAAI,IAAI,IAAI,GAAG;AACnB,MAAE,WAAW,EAAE,SAAS,QAAQ,QAAQ,GAAG;AAC3C,QAAI,EAAE,SAAS,SAAS,GAAG;AAAG,QAAE,WAAW,EAAE,SAAS,MAAM,GAAG,EAAE;AACjE,QAAK,EAAE,SAAS,QAAQ,EAAE,aAAa,SAAW,EAAE,SAAS,SAAS,EAAE,aAAa;AAAS,QAAE,OAAO;AACvG,MAAE,aAAa,KAAK;AACpB,MAAE,OAAO;AACT,WAAO,EAAE,SAAS;AAAA,EACpB,SAAS,GAAP;AACA,UAAM,IAAI,MAAM,gBAAgB,KAAK;AAAA,EACvC;AACF;;;ADPO,IAAM,iBAAiB;AAAA,EAC5B,YAAY,CAAC,UAA6C,sBAAsB,KAAK,SAAS,EAAE;AAAA,EAChG,UAAU,CAAC,UAA2C,oBAAoB,KAAK,SAAS,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C9B;AAcO,SAAS,mCAAmC;AAAA,EACjD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAMe;AACb,MAAI;AAEJ,QAAM,qBAAqB,aAAa,QAAQ;AAEhD,wBAAsB,kBAAkB,EACrC,KAAK,OAAM,SAAQ;AAClB,UAAM,kBAAkB,MAAM,KAAK,YAAY,kBAAkB;AAEjE,gBAAY;AAEZ,UAAM,gBAAgB;AAAA,MACpB;AAAA,QACE;AAAA,UACE,OAAO,CAAC,IAAK;AAAA,UACb,OAAO;AAAA,UACP,SAAS,CAAC,KAAK,MAAM;AAAA,QACvB;AAAA,MACF;AAAA,MACA;AAAA,QACE,QAAQ,OAAc;AACpB,kBAAQ,KAAK;AAAA,QACf;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAC,EACA,MAAM,SAAO;AACZ,QAAI,MAAM;AAEV,YAAQ,GAAG;AAAA,EACb,CAAC;AAEH,SAAO,MAAM,IAAI,MAAM;AACzB;", + "names": ["bytesToHex", "hexToBytes", "bytesToHex", "GroupAdminPermission"] +} diff --git a/node_modules/nostr-tools/lib/esm/nip30.js b/node_modules/nostr-tools/lib/esm/nip30.js new file mode 100644 index 0000000..76846ef --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip30.js @@ -0,0 +1,32 @@ +// nip30.ts +var EMOJI_SHORTCODE_REGEX = /:(\w+):/; +var regex = () => new RegExp(`\\B${EMOJI_SHORTCODE_REGEX.source}\\B`, "g"); +function* matchAll(content) { + const matches = content.matchAll(regex()); + for (const match of matches) { + try { + const [shortcode, name] = match; + yield { + shortcode, + name, + start: match.index, + end: match.index + shortcode.length + }; + } catch (_e) { + } + } +} +function replaceAll(content, replacer) { + return content.replaceAll(regex(), (shortcode, name) => { + return replacer({ + shortcode, + name + }); + }); +} +export { + EMOJI_SHORTCODE_REGEX, + matchAll, + regex, + replaceAll +}; diff --git a/node_modules/nostr-tools/lib/esm/nip30.js.map b/node_modules/nostr-tools/lib/esm/nip30.js.map new file mode 100644 index 0000000..b68b9fa --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip30.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip30.ts"], + "sourcesContent": ["/** Regex for a single emoji shortcode. */\nexport const EMOJI_SHORTCODE_REGEX = /:(\\w+):/\n\n/** Regex to find emoji shortcodes in content. */\nexport const regex = (): RegExp => new RegExp(`\\\\B${EMOJI_SHORTCODE_REGEX.source}\\\\B`, 'g')\n\n/** Represents a Nostr custom emoji. */\nexport interface CustomEmoji {\n /** The matched emoji name with colons. */\n shortcode: `:${string}:`\n /** The matched emoji name without colons. */\n name: string\n}\n\n/** Match result for a custom emoji in text content. */\nexport interface CustomEmojiMatch extends CustomEmoji {\n /** Index where the emoji begins in the text content. */\n start: number\n /** Index where the emoji ends in the text content. */\n end: number\n}\n\n/** Find all custom emoji shortcodes. */\nexport function* matchAll(content: string): Iterable {\n const matches = content.matchAll(regex())\n\n for (const match of matches) {\n try {\n const [shortcode, name] = match\n\n yield {\n shortcode: shortcode as `:${string}:`,\n name,\n start: match.index!,\n end: match.index! + shortcode.length,\n }\n } catch (_e) {\n // do nothing\n }\n }\n}\n\n/** Replace all emoji shortcodes in the content. */\nexport function replaceAll(content: string, replacer: (match: CustomEmoji) => string): string {\n return content.replaceAll(regex(), (shortcode, name) => {\n return replacer({\n shortcode: shortcode as `:${string}:`,\n name,\n })\n })\n}\n"], + "mappings": ";AACO,IAAM,wBAAwB;AAG9B,IAAM,QAAQ,MAAc,IAAI,OAAO,MAAM,sBAAsB,aAAa,GAAG;AAmBnF,UAAU,SAAS,SAA6C;AACrE,QAAM,UAAU,QAAQ,SAAS,MAAM,CAAC;AAExC,aAAW,SAAS,SAAS;AAC3B,QAAI;AACF,YAAM,CAAC,WAAW,IAAI,IAAI;AAE1B,YAAM;AAAA,QACJ;AAAA,QACA;AAAA,QACA,OAAO,MAAM;AAAA,QACb,KAAK,MAAM,QAAS,UAAU;AAAA,MAChC;AAAA,IACF,SAAS,IAAP;AAAA,IAEF;AAAA,EACF;AACF;AAGO,SAAS,WAAW,SAAiB,UAAkD;AAC5F,SAAO,QAAQ,WAAW,MAAM,GAAG,CAAC,WAAW,SAAS;AACtD,WAAO,SAAS;AAAA,MACd;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AACH;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/esm/nip39.js b/node_modules/nostr-tools/lib/esm/nip39.js new file mode 100644 index 0000000..80fce10 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip39.js @@ -0,0 +1,21 @@ +// nip39.ts +var _fetch; +try { + _fetch = fetch; +} catch { +} +function useFetchImplementation(fetchImplementation) { + _fetch = fetchImplementation; +} +async function validateGithub(pubkey, username, proof) { + try { + let res = await (await _fetch(`https://gist.github.com/${username}/${proof}/raw`)).text(); + return res === `Verifying that I control the following Nostr public key: ${pubkey}`; + } catch (_) { + return false; + } +} +export { + useFetchImplementation, + validateGithub +}; diff --git a/node_modules/nostr-tools/lib/esm/nip39.js.map b/node_modules/nostr-tools/lib/esm/nip39.js.map new file mode 100644 index 0000000..faca555 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip39.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip39.ts"], + "sourcesContent": ["var _fetch: any\n\ntry {\n _fetch = fetch\n} catch {}\n\nexport function useFetchImplementation(fetchImplementation: any) {\n _fetch = fetchImplementation\n}\n\nexport async function validateGithub(pubkey: string, username: string, proof: string): Promise {\n try {\n let res = await (await _fetch(`https://gist.github.com/${username}/${proof}/raw`)).text()\n return res === `Verifying that I control the following Nostr public key: ${pubkey}`\n } catch (_) {\n return false\n }\n}\n"], + "mappings": ";AAAA,IAAI;AAEJ,IAAI;AACF,WAAS;AACX,QAAE;AAAO;AAEF,SAAS,uBAAuB,qBAA0B;AAC/D,WAAS;AACX;AAEA,eAAsB,eAAe,QAAgB,UAAkB,OAAiC;AACtG,MAAI;AACF,QAAI,MAAM,OAAO,MAAM,OAAO,2BAA2B,YAAY,WAAW,GAAG,KAAK;AACxF,WAAO,QAAQ,4DAA4D;AAAA,EAC7E,SAAS,GAAP;AACA,WAAO;AAAA,EACT;AACF;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/esm/nip40.js b/node_modules/nostr-tools/lib/esm/nip40.js new file mode 100644 index 0000000..e129c59 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip40.js @@ -0,0 +1,42 @@ +// nip40.ts +function getExpiration(event) { + const tag = event.tags.find(([name]) => name === "expiration"); + if (tag) { + return new Date(parseInt(tag[1]) * 1e3); + } +} +function isEventExpired(event) { + const expiration = getExpiration(event); + if (expiration) { + return Date.now() > expiration.getTime(); + } else { + return false; + } +} +async function waitForExpire(event) { + const expiration = getExpiration(event); + if (expiration) { + const diff = expiration.getTime() - Date.now(); + if (diff > 0) { + await sleep(diff); + return event; + } else { + return event; + } + } else { + throw new Error("Event has no expiration"); + } +} +function onExpire(event, callback) { + waitForExpire(event).then(callback).catch(() => { + }); +} +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} +export { + getExpiration, + isEventExpired, + onExpire, + waitForExpire +}; diff --git a/node_modules/nostr-tools/lib/esm/nip40.js.map b/node_modules/nostr-tools/lib/esm/nip40.js.map new file mode 100644 index 0000000..46cae6b --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip40.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip40.ts"], + "sourcesContent": ["import { Event } from './core.ts'\n\n/** Get the expiration of the event as a `Date` object, if any. */\nfunction getExpiration(event: Event): Date | undefined {\n const tag = event.tags.find(([name]) => name === 'expiration')\n if (tag) {\n return new Date(parseInt(tag[1]) * 1000)\n }\n}\n\n/** Check if the event has expired. */\nfunction isEventExpired(event: Event): boolean {\n const expiration = getExpiration(event)\n if (expiration) {\n return Date.now() > expiration.getTime()\n } else {\n return false\n }\n}\n\n/** Returns a promise that resolves when the event expires. */\nasync function waitForExpire(event: Event): Promise {\n const expiration = getExpiration(event)\n if (expiration) {\n const diff = expiration.getTime() - Date.now()\n if (diff > 0) {\n await sleep(diff)\n return event\n } else {\n return event\n }\n } else {\n throw new Error('Event has no expiration')\n }\n}\n\n/** Calls the callback when the event expires. */\nfunction onExpire(event: Event, callback: (event: Event) => void): void {\n waitForExpire(event)\n .then(callback)\n .catch(() => {})\n}\n\n/** Resolves when the given number of milliseconds have elapsed. */\nfunction sleep(ms: number): Promise {\n return new Promise(resolve => setTimeout(resolve, ms))\n}\n\nexport { getExpiration, isEventExpired, waitForExpire, onExpire }\n"], + "mappings": ";AAGA,SAAS,cAAc,OAAgC;AACrD,QAAM,MAAM,MAAM,KAAK,KAAK,CAAC,CAAC,IAAI,MAAM,SAAS,YAAY;AAC7D,MAAI,KAAK;AACP,WAAO,IAAI,KAAK,SAAS,IAAI,EAAE,IAAI,GAAI;AAAA,EACzC;AACF;AAGA,SAAS,eAAe,OAAuB;AAC7C,QAAM,aAAa,cAAc,KAAK;AACtC,MAAI,YAAY;AACd,WAAO,KAAK,IAAI,IAAI,WAAW,QAAQ;AAAA,EACzC,OAAO;AACL,WAAO;AAAA,EACT;AACF;AAGA,eAAe,cAAc,OAA8B;AACzD,QAAM,aAAa,cAAc,KAAK;AACtC,MAAI,YAAY;AACd,UAAM,OAAO,WAAW,QAAQ,IAAI,KAAK,IAAI;AAC7C,QAAI,OAAO,GAAG;AACZ,YAAM,MAAM,IAAI;AAChB,aAAO;AAAA,IACT,OAAO;AACL,aAAO;AAAA,IACT;AAAA,EACF,OAAO;AACL,UAAM,IAAI,MAAM,yBAAyB;AAAA,EAC3C;AACF;AAGA,SAAS,SAAS,OAAc,UAAwC;AACtE,gBAAc,KAAK,EAChB,KAAK,QAAQ,EACb,MAAM,MAAM;AAAA,EAAC,CAAC;AACnB;AAGA,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,aAAW,WAAW,SAAS,EAAE,CAAC;AACvD;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/esm/nip42.js b/node_modules/nostr-tools/lib/esm/nip42.js new file mode 100644 index 0000000..9d6154c --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip42.js @@ -0,0 +1,18 @@ +// kinds.ts +var ClientAuth = 22242; + +// nip42.ts +function makeAuthEvent(relayURL, challenge) { + return { + kind: ClientAuth, + created_at: Math.floor(Date.now() / 1e3), + tags: [ + ["relay", relayURL], + ["challenge", challenge] + ], + content: "" + }; +} +export { + makeAuthEvent +}; diff --git a/node_modules/nostr-tools/lib/esm/nip42.js.map b/node_modules/nostr-tools/lib/esm/nip42.js.map new file mode 100644 index 0000000..7ee7110 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip42.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../kinds.ts", "../../nip42.ts"], + "sourcesContent": ["import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { EventTemplate } from './core.ts'\nimport { ClientAuth } from './kinds.ts'\n\n/**\n * creates an EventTemplate for an AUTH event to be signed.\n */\nexport function makeAuthEvent(relayURL: string, challenge: string): EventTemplate {\n return {\n kind: ClientAuth,\n created_at: Math.floor(Date.now() / 1000),\n tags: [\n ['relay', relayURL],\n ['challenge', challenge],\n ],\n content: '',\n }\n}\n"], + "mappings": ";AAqIO,IAAM,aAAa;;;AC/HnB,SAAS,cAAc,UAAkB,WAAkC;AAChF,SAAO;AAAA,IACL,MAAM;AAAA,IACN,YAAY,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAAA,IACxC,MAAM;AAAA,MACJ,CAAC,SAAS,QAAQ;AAAA,MAClB,CAAC,aAAa,SAAS;AAAA,IACzB;AAAA,IACA,SAAS;AAAA,EACX;AACF;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/esm/nip44.js b/node_modules/nostr-tools/lib/esm/nip44.js new file mode 100644 index 0000000..b437b77 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip44.js @@ -0,0 +1,122 @@ +// nip44.ts +import { chacha20 } from "@noble/ciphers/chacha"; +import { equalBytes } from "@noble/ciphers/utils"; +import { secp256k1 } from "@noble/curves/secp256k1"; +import { extract as hkdf_extract, expand as hkdf_expand } from "@noble/hashes/hkdf"; +import { hmac } from "@noble/hashes/hmac"; +import { sha256 } from "@noble/hashes/sha256"; +import { concatBytes, randomBytes } from "@noble/hashes/utils"; +import { base64 } from "@scure/base"; + +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// nip44.ts +var minPlaintextSize = 1; +var maxPlaintextSize = 65535; +function getConversationKey(privkeyA, pubkeyB) { + const sharedX = secp256k1.getSharedSecret(privkeyA, "02" + pubkeyB).subarray(1, 33); + return hkdf_extract(sha256, sharedX, "nip44-v2"); +} +function getMessageKeys(conversationKey, nonce) { + const keys = hkdf_expand(sha256, conversationKey, nonce, 76); + return { + chacha_key: keys.subarray(0, 32), + chacha_nonce: keys.subarray(32, 44), + hmac_key: keys.subarray(44, 76) + }; +} +function calcPaddedLen(len) { + if (!Number.isSafeInteger(len) || len < 1) + throw new Error("expected positive integer"); + if (len <= 32) + return 32; + const nextPower = 1 << Math.floor(Math.log2(len - 1)) + 1; + const chunk = nextPower <= 256 ? 32 : nextPower / 8; + return chunk * (Math.floor((len - 1) / chunk) + 1); +} +function writeU16BE(num) { + if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize) + throw new Error("invalid plaintext size: must be between 1 and 65535 bytes"); + const arr = new Uint8Array(2); + new DataView(arr.buffer).setUint16(0, num, false); + return arr; +} +function pad(plaintext) { + const unpadded = utf8Encoder.encode(plaintext); + const unpaddedLen = unpadded.length; + const prefix = writeU16BE(unpaddedLen); + const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen); + return concatBytes(prefix, unpadded, suffix); +} +function unpad(padded) { + const unpaddedLen = new DataView(padded.buffer).getUint16(0); + const unpadded = padded.subarray(2, 2 + unpaddedLen); + if (unpaddedLen < minPlaintextSize || unpaddedLen > maxPlaintextSize || unpadded.length !== unpaddedLen || padded.length !== 2 + calcPaddedLen(unpaddedLen)) + throw new Error("invalid padding"); + return utf8Decoder.decode(unpadded); +} +function hmacAad(key, message, aad) { + if (aad.length !== 32) + throw new Error("AAD associated data must be 32 bytes"); + const combined = concatBytes(aad, message); + return hmac(sha256, key, combined); +} +function decodePayload(payload) { + if (typeof payload !== "string") + throw new Error("payload must be a valid string"); + const plen = payload.length; + if (plen < 132 || plen > 87472) + throw new Error("invalid payload length: " + plen); + if (payload[0] === "#") + throw new Error("unknown encryption version"); + let data; + try { + data = base64.decode(payload); + } catch (error) { + throw new Error("invalid base64: " + error.message); + } + const dlen = data.length; + if (dlen < 99 || dlen > 65603) + throw new Error("invalid data length: " + dlen); + const vers = data[0]; + if (vers !== 2) + throw new Error("unknown encryption version " + vers); + return { + nonce: data.subarray(1, 33), + ciphertext: data.subarray(33, -32), + mac: data.subarray(-32) + }; +} +function encrypt(plaintext, conversationKey, nonce = randomBytes(32)) { + const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); + const padded = pad(plaintext); + const ciphertext = chacha20(chacha_key, chacha_nonce, padded); + const mac = hmacAad(hmac_key, ciphertext, nonce); + return base64.encode(concatBytes(new Uint8Array([2]), nonce, ciphertext, mac)); +} +function decrypt(payload, conversationKey) { + const { nonce, ciphertext, mac } = decodePayload(payload); + const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); + const calculatedMac = hmacAad(hmac_key, ciphertext, nonce); + if (!equalBytes(calculatedMac, mac)) + throw new Error("invalid MAC"); + const padded = chacha20(chacha_key, chacha_nonce, ciphertext); + return unpad(padded); +} +var v2 = { + utils: { + getConversationKey, + calcPaddedLen + }, + encrypt, + decrypt +}; +export { + decrypt, + encrypt, + getConversationKey, + v2 +}; diff --git a/node_modules/nostr-tools/lib/esm/nip44.js.map b/node_modules/nostr-tools/lib/esm/nip44.js.map new file mode 100644 index 0000000..f5370dd --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip44.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip44.ts", "../../utils.ts"], + "sourcesContent": ["import { chacha20 } from '@noble/ciphers/chacha'\nimport { equalBytes } from '@noble/ciphers/utils'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { extract as hkdf_extract, expand as hkdf_expand } from '@noble/hashes/hkdf'\nimport { hmac } from '@noble/hashes/hmac'\nimport { sha256 } from '@noble/hashes/sha256'\nimport { concatBytes, randomBytes } from '@noble/hashes/utils'\nimport { base64 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nconst minPlaintextSize = 0x0001 // 1b msg => padded to 32b\nconst maxPlaintextSize = 0xffff // 65535 (64kb-1) => padded to 64kb\n\nexport function getConversationKey(privkeyA: Uint8Array, pubkeyB: string): Uint8Array {\n const sharedX = secp256k1.getSharedSecret(privkeyA, '02' + pubkeyB).subarray(1, 33)\n return hkdf_extract(sha256, sharedX, 'nip44-v2')\n}\n\nfunction getMessageKeys(\n conversationKey: Uint8Array,\n nonce: Uint8Array,\n): { chacha_key: Uint8Array; chacha_nonce: Uint8Array; hmac_key: Uint8Array } {\n const keys = hkdf_expand(sha256, conversationKey, nonce, 76)\n return {\n chacha_key: keys.subarray(0, 32),\n chacha_nonce: keys.subarray(32, 44),\n hmac_key: keys.subarray(44, 76),\n }\n}\n\nfunction calcPaddedLen(len: number): number {\n if (!Number.isSafeInteger(len) || len < 1) throw new Error('expected positive integer')\n if (len <= 32) return 32\n const nextPower = 1 << (Math.floor(Math.log2(len - 1)) + 1)\n const chunk = nextPower <= 256 ? 32 : nextPower / 8\n return chunk * (Math.floor((len - 1) / chunk) + 1)\n}\n\nfunction writeU16BE(num: number): Uint8Array {\n if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize)\n throw new Error('invalid plaintext size: must be between 1 and 65535 bytes')\n const arr = new Uint8Array(2)\n new DataView(arr.buffer).setUint16(0, num, false)\n return arr\n}\n\nfunction pad(plaintext: string): Uint8Array {\n const unpadded = utf8Encoder.encode(plaintext)\n const unpaddedLen = unpadded.length\n const prefix = writeU16BE(unpaddedLen)\n const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen)\n return concatBytes(prefix, unpadded, suffix)\n}\n\nfunction unpad(padded: Uint8Array): string {\n const unpaddedLen = new DataView(padded.buffer).getUint16(0)\n const unpadded = padded.subarray(2, 2 + unpaddedLen)\n if (\n unpaddedLen < minPlaintextSize ||\n unpaddedLen > maxPlaintextSize ||\n unpadded.length !== unpaddedLen ||\n padded.length !== 2 + calcPaddedLen(unpaddedLen)\n )\n throw new Error('invalid padding')\n return utf8Decoder.decode(unpadded)\n}\n\nfunction hmacAad(key: Uint8Array, message: Uint8Array, aad: Uint8Array): Uint8Array {\n if (aad.length !== 32) throw new Error('AAD associated data must be 32 bytes')\n const combined = concatBytes(aad, message)\n return hmac(sha256, key, combined)\n}\n\n// metadata: always 65b (version: 1b, nonce: 32b, max: 32b)\n// plaintext: 1b to 0xffff\n// padded plaintext: 32b to 0xffff\n// ciphertext: 32b+2 to 0xffff+2\n// raw payload: 99 (65+32+2) to 65603 (65+0xffff+2)\n// compressed payload (base64): 132b to 87472b\nfunction decodePayload(payload: string): { nonce: Uint8Array; ciphertext: Uint8Array; mac: Uint8Array } {\n if (typeof payload !== 'string') throw new Error('payload must be a valid string')\n const plen = payload.length\n if (plen < 132 || plen > 87472) throw new Error('invalid payload length: ' + plen)\n if (payload[0] === '#') throw new Error('unknown encryption version')\n let data: Uint8Array\n try {\n data = base64.decode(payload)\n } catch (error) {\n throw new Error('invalid base64: ' + (error as any).message)\n }\n const dlen = data.length\n if (dlen < 99 || dlen > 65603) throw new Error('invalid data length: ' + dlen)\n const vers = data[0]\n if (vers !== 2) throw new Error('unknown encryption version ' + vers)\n return {\n nonce: data.subarray(1, 33),\n ciphertext: data.subarray(33, -32),\n mac: data.subarray(-32),\n }\n}\n\nexport function encrypt(plaintext: string, conversationKey: Uint8Array, nonce: Uint8Array = randomBytes(32)): string {\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n const padded = pad(plaintext)\n const ciphertext = chacha20(chacha_key, chacha_nonce, padded)\n const mac = hmacAad(hmac_key, ciphertext, nonce)\n return base64.encode(concatBytes(new Uint8Array([2]), nonce, ciphertext, mac))\n}\n\nexport function decrypt(payload: string, conversationKey: Uint8Array): string {\n const { nonce, ciphertext, mac } = decodePayload(payload)\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n const calculatedMac = hmacAad(hmac_key, ciphertext, nonce)\n if (!equalBytes(calculatedMac, mac)) throw new Error('invalid MAC')\n const padded = chacha20(chacha_key, chacha_nonce, ciphertext)\n return unpad(padded)\n}\n\nexport const v2 = {\n utils: {\n getConversationKey,\n calcPaddedLen,\n },\n encrypt,\n decrypt,\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n"], + "mappings": ";AAAA,SAAS,gBAAgB;AACzB,SAAS,kBAAkB;AAC3B,SAAS,iBAAiB;AAC1B,SAAS,WAAW,cAAc,UAAU,mBAAmB;AAC/D,SAAS,YAAY;AACrB,SAAS,cAAc;AACvB,SAAS,aAAa,mBAAmB;AACzC,SAAS,cAAc;;;ACFvB,SAAS,YAAY,kBAAkB;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;;;ADQxD,IAAM,mBAAmB;AACzB,IAAM,mBAAmB;AAElB,SAAS,mBAAmB,UAAsB,SAA6B;AACpF,QAAM,UAAU,UAAU,gBAAgB,UAAU,OAAO,OAAO,EAAE,SAAS,GAAG,EAAE;AAClF,SAAO,aAAa,QAAQ,SAAS,UAAU;AACjD;AAEA,SAAS,eACP,iBACA,OAC4E;AAC5E,QAAM,OAAO,YAAY,QAAQ,iBAAiB,OAAO,EAAE;AAC3D,SAAO;AAAA,IACL,YAAY,KAAK,SAAS,GAAG,EAAE;AAAA,IAC/B,cAAc,KAAK,SAAS,IAAI,EAAE;AAAA,IAClC,UAAU,KAAK,SAAS,IAAI,EAAE;AAAA,EAChC;AACF;AAEA,SAAS,cAAc,KAAqB;AAC1C,MAAI,CAAC,OAAO,cAAc,GAAG,KAAK,MAAM;AAAG,UAAM,IAAI,MAAM,2BAA2B;A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AAC5D,SAAO,MAAM,MAAM;AACrB;AAEO,IAAM,KAAK;AAAA,EAChB,OAAO;AAAA,IACL;AAAA,IACA;AAAA,EACF;AAAA,EACA;AAAA,EACA;AACF;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/esm/nip46.js b/node_modules/nostr-tools/lib/esm/nip46.js new file mode 100644 index 0000000..bd57990 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip46.js @@ -0,0 +1,1216 @@ +// pure.ts +import { schnorr } from "@noble/curves/secp256k1"; +import { bytesToHex as bytesToHex2 } from "@noble/hashes/utils"; + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +import { sha256 } from "@noble/hashes/sha256"; + +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); +function normalizeURL(url) { + try { + if (url.indexOf("://") === -1) + url = "wss://" + url; + let p = new URL(url); + p.pathname = p.pathname.replace(/\/+/g, "/"); + if (p.pathname.endsWith("/")) + p.pathname = p.pathname.slice(0, -1); + if (p.port === "80" && p.protocol === "ws:" || p.port === "443" && p.protocol === "wss:") + p.port = ""; + p.searchParams.sort(); + p.hash = ""; + return p.toString(); + } catch (e) { + throw new Error(`Invalid URL: ${url}`); + } +} +var QueueNode = class { + value; + next = null; + prev = null; + constructor(message) { + this.value = message; + } +}; +var Queue = class { + first; + last; + constructor() { + this.first = null; + this.last = null; + } + enqueue(value) { + const newNode = new QueueNode(value); + if (!this.last) { + this.first = newNode; + this.last = newNode; + } else if (this.last === this.first) { + this.last = newNode; + this.last.prev = this.first; + this.first.next = newNode; + } else { + newNode.prev = this.last; + this.last.next = newNode; + this.last = newNode; + } + return true; + } + dequeue() { + if (!this.first) + return null; + if (this.first === this.last) { + const target2 = this.first; + this.first = null; + this.last = null; + return target2.value; + } + const target = this.first; + this.first = target.next; + if (this.first) { + this.first.prev = null; + } + return target.value; + } +}; + +// pure.ts +var JS = class { + generateSecretKey() { + return schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return bytesToHex2(schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = bytesToHex2(schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = bytesToHex2(schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = sha256(utf8Encoder.encode(serializeEvent(event))); + return bytesToHex2(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// nip44.ts +import { chacha20 } from "@noble/ciphers/chacha"; +import { equalBytes } from "@noble/ciphers/utils"; +import { secp256k1 } from "@noble/curves/secp256k1"; +import { extract as hkdf_extract, expand as hkdf_expand } from "@noble/hashes/hkdf"; +import { hmac } from "@noble/hashes/hmac"; +import { sha256 as sha2562 } from "@noble/hashes/sha256"; +import { concatBytes, randomBytes } from "@noble/hashes/utils"; +import { base64 } from "@scure/base"; +var minPlaintextSize = 1; +var maxPlaintextSize = 65535; +function getConversationKey(privkeyA, pubkeyB) { + const sharedX = secp256k1.getSharedSecret(privkeyA, "02" + pubkeyB).subarray(1, 33); + return hkdf_extract(sha2562, sharedX, "nip44-v2"); +} +function getMessageKeys(conversationKey, nonce) { + const keys = hkdf_expand(sha2562, conversationKey, nonce, 76); + return { + chacha_key: keys.subarray(0, 32), + chacha_nonce: keys.subarray(32, 44), + hmac_key: keys.subarray(44, 76) + }; +} +function calcPaddedLen(len) { + if (!Number.isSafeInteger(len) || len < 1) + throw new Error("expected positive integer"); + if (len <= 32) + return 32; + const nextPower = 1 << Math.floor(Math.log2(len - 1)) + 1; + const chunk = nextPower <= 256 ? 32 : nextPower / 8; + return chunk * (Math.floor((len - 1) / chunk) + 1); +} +function writeU16BE(num) { + if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize) + throw new Error("invalid plaintext size: must be between 1 and 65535 bytes"); + const arr = new Uint8Array(2); + new DataView(arr.buffer).setUint16(0, num, false); + return arr; +} +function pad(plaintext) { + const unpadded = utf8Encoder.encode(plaintext); + const unpaddedLen = unpadded.length; + const prefix = writeU16BE(unpaddedLen); + const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen); + return concatBytes(prefix, unpadded, suffix); +} +function unpad(padded) { + const unpaddedLen = new DataView(padded.buffer).getUint16(0); + const unpadded = padded.subarray(2, 2 + unpaddedLen); + if (unpaddedLen < minPlaintextSize || unpaddedLen > maxPlaintextSize || unpadded.length !== unpaddedLen || padded.length !== 2 + calcPaddedLen(unpaddedLen)) + throw new Error("invalid padding"); + return utf8Decoder.decode(unpadded); +} +function hmacAad(key, message, aad) { + if (aad.length !== 32) + throw new Error("AAD associated data must be 32 bytes"); + const combined = concatBytes(aad, message); + return hmac(sha2562, key, combined); +} +function decodePayload(payload) { + if (typeof payload !== "string") + throw new Error("payload must be a valid string"); + const plen = payload.length; + if (plen < 132 || plen > 87472) + throw new Error("invalid payload length: " + plen); + if (payload[0] === "#") + throw new Error("unknown encryption version"); + let data; + try { + data = base64.decode(payload); + } catch (error) { + throw new Error("invalid base64: " + error.message); + } + const dlen = data.length; + if (dlen < 99 || dlen > 65603) + throw new Error("invalid data length: " + dlen); + const vers = data[0]; + if (vers !== 2) + throw new Error("unknown encryption version " + vers); + return { + nonce: data.subarray(1, 33), + ciphertext: data.subarray(33, -32), + mac: data.subarray(-32) + }; +} +function encrypt(plaintext, conversationKey, nonce = randomBytes(32)) { + const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); + const padded = pad(plaintext); + const ciphertext = chacha20(chacha_key, chacha_nonce, padded); + const mac = hmacAad(hmac_key, ciphertext, nonce); + return base64.encode(concatBytes(new Uint8Array([2]), nonce, ciphertext, mac)); +} +function decrypt(payload, conversationKey) { + const { nonce, ciphertext, mac } = decodePayload(payload); + const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); + const calculatedMac = hmacAad(hmac_key, ciphertext, nonce); + if (!equalBytes(calculatedMac, mac)) + throw new Error("invalid MAC"); + const padded = chacha20(chacha_key, chacha_nonce, ciphertext); + return unpad(padded); +} + +// nip05.ts +var NIP05_REGEX = /^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/; +var _fetch; +try { + _fetch = fetch; +} catch (_) { + null; +} + +// kinds.ts +var ClientAuth = 22242; +var NostrConnect = 24133; +var Handlerinformation = 31990; + +// filter.ts +function matchFilter(filter, event) { + if (filter.ids && filter.ids.indexOf(event.id) === -1) { + return false; + } + if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) { + return false; + } + if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) { + return false; + } + for (let f in filter) { + if (f[0] === "#") { + let tagName = f.slice(1); + let values = filter[`#${tagName}`]; + if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values.indexOf(v) !== -1)) + return false; + } + } + if (filter.since && event.created_at < filter.since) + return false; + if (filter.until && event.created_at > filter.until) + return false; + return true; +} +function matchFilters(filters, event) { + for (let i2 = 0; i2 < filters.length; i2++) { + if (matchFilter(filters[i2], event)) { + return true; + } + } + return false; +} + +// fakejson.ts +function getHex64(json, field) { + let len = field.length + 3; + let idx = json.indexOf(`"${field}":`) + len; + let s = json.slice(idx).indexOf(`"`) + idx + 1; + return json.slice(s, s + 64); +} +function getSubscriptionId(json) { + let idx = json.slice(0, 22).indexOf(`"EVENT"`); + if (idx === -1) + return null; + let pstart = json.slice(idx + 7 + 1).indexOf(`"`); + if (pstart === -1) + return null; + let start = idx + 7 + 1 + pstart; + let pend = json.slice(start + 1, 80).indexOf(`"`); + if (pend === -1) + return null; + let end = start + 1 + pend; + return json.slice(start + 1, end); +} + +// nip42.ts +function makeAuthEvent(relayURL, challenge) { + return { + kind: ClientAuth, + created_at: Math.floor(Date.now() / 1e3), + tags: [ + ["relay", relayURL], + ["challenge", challenge] + ], + content: "" + }; +} + +// helpers.ts +async function yieldThread() { + return new Promise((resolve) => { + const ch = new MessageChannel(); + const handler = () => { + ch.port1.removeEventListener("message", handler); + resolve(); + }; + ch.port1.addEventListener("message", handler); + ch.port2.postMessage(0); + ch.port1.start(); + }); +} +var alwaysTrue = (t) => { + t[verifiedSymbol] = true; + return true; +}; + +// abstract-relay.ts +var SendingOnClosedConnection = class extends Error { + constructor(message, relay) { + super(`Tried to send message '${message} on a closed connection to ${relay}.`); + this.name = "SendingOnClosedConnection"; + } +}; +var AbstractRelay = class { + url; + _connected = false; + onclose = null; + onnotice = (msg) => console.debug(`NOTICE from ${this.url}: ${msg}`); + baseEoseTimeout = 4400; + connectionTimeout = 4400; + publishTimeout = 4400; + pingFrequency = 2e4; + pingTimeout = 2e4; + openSubs = /* @__PURE__ */ new Map(); + enablePing; + connectionTimeoutHandle; + connectionPromise; + openCountRequests = /* @__PURE__ */ new Map(); + openEventPublishes = /* @__PURE__ */ new Map(); + ws; + incomingMessageQueue = new Queue(); + queueRunning = false; + challenge; + authPromise; + serial = 0; + verifyEvent; + _WebSocket; + constructor(url, opts) { + this.url = normalizeURL(url); + this.verifyEvent = opts.verifyEvent; + this._WebSocket = opts.websocketImplementation || WebSocket; + this.enablePing = opts.enablePing; + } + static async connect(url, opts) { + const relay = new AbstractRelay(url, opts); + await relay.connect(); + return relay; + } + closeAllSubscriptions(reason) { + for (let [_, sub] of this.openSubs) { + sub.close(reason); + } + this.openSubs.clear(); + for (let [_, ep] of this.openEventPublishes) { + ep.reject(new Error(reason)); + } + this.openEventPublishes.clear(); + for (let [_, cr] of this.openCountRequests) { + cr.reject(new Error(reason)); + } + this.openCountRequests.clear(); + } + get connected() { + return this._connected; + } + async connect() { + if (this.connectionPromise) + return this.connectionPromise; + this.challenge = void 0; + this.authPromise = void 0; + this.connectionPromise = new Promise((resolve, reject) => { + this.connectionTimeoutHandle = setTimeout(() => { + reject("connection timed out"); + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection timed out"); + }, this.connectionTimeout); + try { + this.ws = new this._WebSocket(this.url); + } catch (err) { + clearTimeout(this.connectionTimeoutHandle); + reject(err); + return; + } + this.ws.onopen = () => { + clearTimeout(this.connectionTimeoutHandle); + this._connected = true; + if (this.enablePing) { + this.pingpong(); + } + resolve(); + }; + this.ws.onerror = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket error"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection errored"); + } + }; + this.ws.onclose = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket closed"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection closed"); + } + }; + this.ws.onmessage = this._onmessage.bind(this); + }); + return this.connectionPromise; + } + async waitForPingPong() { + return new Promise((res, err) => { + ; + this.ws && this.ws.on && this.ws.on("pong", () => res(true)) || err("ws can't listen for pong"); + this.ws && this.ws.ping && this.ws.ping(); + }); + } + async waitForDummyReq() { + return new Promise((resolve, _) => { + const sub = this.subscribe([{ ids: ["a".repeat(64)] }], { + oneose: () => { + sub.close(); + resolve(true); + }, + eoseTimeout: this.pingTimeout + 1e3 + }); + }); + } + async pingpong() { + if (this.ws?.readyState === 1) { + const result = await Promise.any([ + this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(), + new Promise((res) => setTimeout(() => res(false), this.pingTimeout)) + ]); + if (result) { + setTimeout(() => this.pingpong(), this.pingFrequency); + } else { + this.closeAllSubscriptions("pingpong timed out"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + } + } + async runQueue() { + this.queueRunning = true; + while (true) { + if (false === this.handleNext()) { + break; + } + await yieldThread(); + } + this.queueRunning = false; + } + handleNext() { + const json = this.incomingMessageQueue.dequeue(); + if (!json) { + return false; + } + const subid = getSubscriptionId(json); + if (subid) { + const so = this.openSubs.get(subid); + if (!so) { + return; + } + const id = getHex64(json, "id"); + const alreadyHave = so.alreadyHaveEvent?.(id); + so.receivedEvent?.(this, id); + if (alreadyHave) { + return; + } + } + try { + let data = JSON.parse(json); + switch (data[0]) { + case "EVENT": { + const so = this.openSubs.get(data[1]); + const event = data[2]; + if (this.verifyEvent(event) && matchFilters(so.filters, event)) { + so.onevent(event); + } + return; + } + case "COUNT": { + const id = data[1]; + const payload = data[2]; + const cr = this.openCountRequests.get(id); + if (cr) { + cr.resolve(payload.count); + this.openCountRequests.delete(id); + } + return; + } + case "EOSE": { + const so = this.openSubs.get(data[1]); + if (!so) + return; + so.receivedEose(); + return; + } + case "OK": { + const id = data[1]; + const ok = data[2]; + const reason = data[3]; + const ep = this.openEventPublishes.get(id); + if (ep) { + clearTimeout(ep.timeout); + if (ok) + ep.resolve(reason); + else + ep.reject(new Error(reason)); + this.openEventPublishes.delete(id); + } + return; + } + case "CLOSED": { + const id = data[1]; + const so = this.openSubs.get(id); + if (!so) + return; + so.closed = true; + so.close(data[2]); + return; + } + case "NOTICE": + this.onnotice(data[1]); + return; + case "AUTH": { + this.challenge = data[1]; + return; + } + } + } catch (err) { + return; + } + } + async send(message) { + if (!this.connectionPromise) + throw new SendingOnClosedConnection(message, this.url); + this.connectionPromise.then(() => { + this.ws?.send(message); + }); + } + async auth(signAuthEvent) { + const challenge = this.challenge; + if (!challenge) + throw new Error("can't perform auth, no challenge was received"); + if (this.authPromise) + return this.authPromise; + this.authPromise = new Promise(async (resolve, reject) => { + try { + let evt = await signAuthEvent(makeAuthEvent(this.url, challenge)); + let timeout = setTimeout(() => { + let ep = this.openEventPublishes.get(evt.id); + if (ep) { + ep.reject(new Error("auth timed out")); + this.openEventPublishes.delete(evt.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(evt.id, { resolve, reject, timeout }); + this.send('["AUTH",' + JSON.stringify(evt) + "]"); + } catch (err) { + console.warn("subscribe auth function failed:", err); + } + }); + return this.authPromise; + } + async publish(event) { + const ret = new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + const ep = this.openEventPublishes.get(event.id); + if (ep) { + ep.reject(new Error("publish timed out")); + this.openEventPublishes.delete(event.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(event.id, { resolve, reject, timeout }); + }); + this.send('["EVENT",' + JSON.stringify(event) + "]"); + return ret; + } + async count(filters, params) { + this.serial++; + const id = params?.id || "count:" + this.serial; + const ret = new Promise((resolve, reject) => { + this.openCountRequests.set(id, { resolve, reject }); + }); + this.send('["COUNT","' + id + '",' + JSON.stringify(filters).substring(1)); + return ret; + } + subscribe(filters, params) { + const subscription = this.prepareSubscription(filters, params); + subscription.fire(); + return subscription; + } + prepareSubscription(filters, params) { + this.serial++; + const id = params.id || (params.label ? params.label + ":" : "sub:") + this.serial; + const subscription = new Subscription(this, id, filters, params); + this.openSubs.set(id, subscription); + return subscription; + } + close() { + this.closeAllSubscriptions("relay connection closed by us"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + _onmessage(ev) { + this.incomingMessageQueue.enqueue(ev.data); + if (!this.queueRunning) { + this.runQueue(); + } + } +}; +var Subscription = class { + relay; + id; + closed = false; + eosed = false; + filters; + alreadyHaveEvent; + receivedEvent; + onevent; + oneose; + onclose; + eoseTimeout; + eoseTimeoutHandle; + constructor(relay, id, filters, params) { + this.relay = relay; + this.filters = filters; + this.id = id; + this.alreadyHaveEvent = params.alreadyHaveEvent; + this.receivedEvent = params.receivedEvent; + this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout; + this.oneose = params.oneose; + this.onclose = params.onclose; + this.onevent = params.onevent || ((event) => { + console.warn( + `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`, + event + ); + }); + } + fire() { + this.relay.send('["REQ","' + this.id + '",' + JSON.stringify(this.filters).substring(1)); + this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout); + } + receivedEose() { + if (this.eosed) + return; + clearTimeout(this.eoseTimeoutHandle); + this.eosed = true; + this.oneose?.(); + } + close(reason = "closed by caller") { + if (!this.closed && this.relay.connected) { + try { + this.relay.send('["CLOSE",' + JSON.stringify(this.id) + "]"); + } catch (err) { + if (err instanceof SendingOnClosedConnection) { + } else { + throw err; + } + } + this.closed = true; + } + this.relay.openSubs.delete(this.id); + this.onclose?.(reason); + } +}; + +// abstract-pool.ts +var AbstractSimplePool = class { + relays = /* @__PURE__ */ new Map(); + seenOn = /* @__PURE__ */ new Map(); + trackRelays = false; + verifyEvent; + enablePing; + trustedRelayURLs = /* @__PURE__ */ new Set(); + _WebSocket; + constructor(opts) { + this.verifyEvent = opts.verifyEvent; + this._WebSocket = opts.websocketImplementation; + this.enablePing = opts.enablePing; + } + async ensureRelay(url, params) { + url = normalizeURL(url); + let relay = this.relays.get(url); + if (!relay) { + relay = new AbstractRelay(url, { + verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent, + websocketImplementation: this._WebSocket, + enablePing: this.enablePing + }); + relay.onclose = () => { + this.relays.delete(url); + }; + if (params?.connectionTimeout) + relay.connectionTimeout = params.connectionTimeout; + this.relays.set(url, relay); + } + await relay.connect(); + return relay; + } + close(relays) { + relays.map(normalizeURL).forEach((url) => { + this.relays.get(url)?.close(); + this.relays.delete(url); + }); + } + subscribe(relays, filter, params) { + params.onauth = params.onauth || params.doauth; + const request = []; + for (let i2 = 0; i2 < relays.length; i2++) { + const url = normalizeURL(relays[i2]); + if (!request.find((r) => r.url === url)) { + request.push({ url, filter }); + } + } + return this.subscribeMap(request, params); + } + subscribeMany(relays, filters, params) { + params.onauth = params.onauth || params.doauth; + const request = []; + const uniqUrls = []; + for (let i2 = 0; i2 < relays.length; i2++) { + const url = normalizeURL(relays[i2]); + if (uniqUrls.indexOf(url) === -1) { + for (let f = 0; f < filters.length; f++) { + request.push({ url, filter: filters[f] }); + } + } + } + return this.subscribeMap(request, params); + } + subscribeMap(requests, params) { + params.onauth = params.onauth || params.doauth; + if (this.trackRelays) { + params.receivedEvent = (relay, id) => { + let set = this.seenOn.get(id); + if (!set) { + set = /* @__PURE__ */ new Set(); + this.seenOn.set(id, set); + } + set.add(relay); + }; + } + const _knownIds = /* @__PURE__ */ new Set(); + const subs = []; + const eosesReceived = []; + let handleEose = (i2) => { + if (eosesReceived[i2]) + return; + eosesReceived[i2] = true; + if (eosesReceived.filter((a) => a).length === requests.length) { + params.oneose?.(); + handleEose = () => { + }; + } + }; + const closesReceived = []; + let handleClose = (i2, reason) => { + if (closesReceived[i2]) + return; + handleEose(i2); + closesReceived[i2] = reason; + if (closesReceived.filter((a) => a).length === requests.length) { + params.onclose?.(closesReceived); + handleClose = () => { + }; + } + }; + const localAlreadyHaveEventHandler = (id) => { + if (params.alreadyHaveEvent?.(id)) { + return true; + } + const have = _knownIds.has(id); + _knownIds.add(id); + return have; + }; + const allOpened = Promise.all( + requests.map(async ({ url, filter }, i2) => { + let relay; + try { + relay = await this.ensureRelay(url, { + connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1e3) : void 0 + }); + } catch (err) { + handleClose(i2, err?.message || String(err)); + return; + } + let subscription = relay.subscribe([filter], { + ...params, + oneose: () => handleEose(i2), + onclose: (reason) => { + if (reason.startsWith("auth-required: ") && params.onauth) { + relay.auth(params.onauth).then(() => { + relay.subscribe([filter], { + ...params, + oneose: () => handleEose(i2), + onclose: (reason2) => { + handleClose(i2, reason2); + }, + alreadyHaveEvent: localAlreadyHaveEventHandler, + eoseTimeout: params.maxWait + }); + }).catch((err) => { + handleClose(i2, `auth was required and attempted, but failed with: ${err}`); + }); + } else { + handleClose(i2, reason); + } + }, + alreadyHaveEvent: localAlreadyHaveEventHandler, + eoseTimeout: params.maxWait + }); + subs.push(subscription); + }) + ); + return { + async close(reason) { + await allOpened; + subs.forEach((sub) => { + sub.close(reason); + }); + } + }; + } + subscribeEose(relays, filter, params) { + params.onauth = params.onauth || params.doauth; + const subcloser = this.subscribe(relays, filter, { + ...params, + oneose() { + subcloser.close("closed automatically on eose"); + } + }); + return subcloser; + } + subscribeManyEose(relays, filters, params) { + params.onauth = params.onauth || params.doauth; + const subcloser = this.subscribeMany(relays, filters, { + ...params, + oneose() { + subcloser.close("closed automatically on eose"); + } + }); + return subcloser; + } + async querySync(relays, filter, params) { + return new Promise(async (resolve) => { + const events = []; + this.subscribeEose(relays, filter, { + ...params, + onevent(event) { + events.push(event); + }, + onclose(_) { + resolve(events); + } + }); + }); + } + async get(relays, filter, params) { + filter.limit = 1; + const events = await this.querySync(relays, filter, params); + events.sort((a, b) => b.created_at - a.created_at); + return events[0] || null; + } + publish(relays, event, options) { + return relays.map(normalizeURL).map(async (url, i2, arr) => { + if (arr.indexOf(url) !== i2) { + return Promise.reject("duplicate url"); + } + let r = await this.ensureRelay(url); + return r.publish(event).catch(async (err) => { + if (err instanceof Error && err.message.startsWith("auth-required: ") && options?.onauth) { + await r.auth(options.onauth); + return r.publish(event); + } + throw err; + }).then((reason) => { + if (this.trackRelays) { + let set = this.seenOn.get(event.id); + if (!set) { + set = /* @__PURE__ */ new Set(); + this.seenOn.set(event.id, set); + } + set.add(r); + } + return reason; + }); + }); + } + listConnectionStatus() { + const map = /* @__PURE__ */ new Map(); + this.relays.forEach((relay, url) => map.set(url, relay.connected)); + return map; + } + destroy() { + this.relays.forEach((conn) => conn.close()); + this.relays = /* @__PURE__ */ new Map(); + } +}; + +// pool.ts +var _WebSocket; +try { + _WebSocket = WebSocket; +} catch { +} +var SimplePool = class extends AbstractSimplePool { + constructor(options) { + super({ verifyEvent, websocketImplementation: _WebSocket, ...options }); + } +}; + +// nip46.ts +var _fetch2; +try { + _fetch2 = fetch; +} catch { +} +function useFetchImplementation(fetchImplementation) { + _fetch2 = fetchImplementation; +} +var BUNKER_REGEX = /^bunker:\/\/([0-9a-f]{64})\??([?\/\w:.=&%-]*)$/; +var EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; +function toBunkerURL(bunkerPointer) { + let bunkerURL = new URL(`bunker://${bunkerPointer.pubkey}`); + bunkerPointer.relays.forEach((relay) => { + bunkerURL.searchParams.append("relay", relay); + }); + if (bunkerPointer.secret) { + bunkerURL.searchParams.set("secret", bunkerPointer.secret); + } + return bunkerURL.toString(); +} +async function parseBunkerInput(input) { + let match = input.match(BUNKER_REGEX); + if (match) { + try { + const pubkey = match[1]; + const qs = new URLSearchParams(match[2]); + return { + pubkey, + relays: qs.getAll("relay"), + secret: qs.get("secret") + }; + } catch (_err) { + } + } + return queryBunkerProfile(input); +} +async function queryBunkerProfile(nip05) { + const match = nip05.match(NIP05_REGEX); + if (!match) + return null; + const [_, name = "_", domain] = match; + try { + const url = `https://${domain}/.well-known/nostr.json?name=${name}`; + const res = await (await _fetch2(url, { redirect: "error" })).json(); + let pubkey = res.names[name]; + let relays = res.nip46[pubkey] || []; + return { pubkey, relays, secret: null }; + } catch (_err) { + return null; + } +} +var BunkerSigner = class { + params; + pool; + subCloser; + isOpen; + serial; + idPrefix; + listeners; + waitingForAuth; + secretKey; + conversationKey; + bp; + cachedPubKey; + constructor(clientSecretKey, bp, params = {}) { + if (bp.relays.length === 0) { + throw new Error("no relays are specified for this bunker"); + } + this.params = params; + this.pool = params.pool || new SimplePool(); + this.secretKey = clientSecretKey; + this.conversationKey = getConversationKey(clientSecretKey, bp.pubkey); + this.bp = bp; + this.isOpen = false; + this.idPrefix = Math.random().toString(36).substring(7); + this.serial = 0; + this.listeners = {}; + this.waitingForAuth = {}; + this.setupSubscription(params); + } + setupSubscription(params) { + const listeners = this.listeners; + const waitingForAuth = this.waitingForAuth; + const convKey = this.conversationKey; + this.subCloser = this.pool.subscribe( + this.bp.relays, + { kinds: [NostrConnect], authors: [this.bp.pubkey], "#p": [getPublicKey(this.secretKey)] }, + { + onevent: async (event) => { + const o = JSON.parse(decrypt(event.content, convKey)); + const { id, result, error } = o; + if (result === "auth_url" && waitingForAuth[id]) { + delete waitingForAuth[id]; + if (params.onauth) { + params.onauth(error); + } else { + console.warn( + `nostr-tools/nip46: remote signer ${this.bp.pubkey} tried to send an "auth_url"='${error}' but there was no onauth() callback configured.` + ); + } + return; + } + let handler = listeners[id]; + if (handler) { + if (error) + handler.reject(error); + else if (result) + handler.resolve(result); + delete listeners[id]; + } + }, + onclose: () => { + this.subCloser = void 0; + } + } + ); + this.isOpen = true; + } + async close() { + this.isOpen = false; + this.subCloser.close(); + } + async sendRequest(method, params) { + return new Promise(async (resolve, reject) => { + try { + if (!this.isOpen) + throw new Error("this signer is not open anymore, create a new one"); + if (!this.subCloser) + this.setupSubscription(this.params); + this.serial++; + const id = `${this.idPrefix}-${this.serial}`; + const encryptedContent = encrypt(JSON.stringify({ id, method, params }), this.conversationKey); + const verifiedEvent = finalizeEvent( + { + kind: NostrConnect, + tags: [["p", this.bp.pubkey]], + content: encryptedContent, + created_at: Math.floor(Date.now() / 1e3) + }, + this.secretKey + ); + this.listeners[id] = { resolve, reject }; + this.waitingForAuth[id] = true; + await Promise.any(this.pool.publish(this.bp.relays, verifiedEvent)); + } catch (err) { + reject(err); + } + }); + } + async ping() { + let resp = await this.sendRequest("ping", []); + if (resp !== "pong") + throw new Error(`result is not pong: ${resp}`); + } + async connect() { + await this.sendRequest("connect", [this.bp.pubkey, this.bp.secret || ""]); + } + async getPublicKey() { + if (!this.cachedPubKey) { + this.cachedPubKey = await this.sendRequest("get_public_key", []); + } + return this.cachedPubKey; + } + async signEvent(event) { + let resp = await this.sendRequest("sign_event", [JSON.stringify(event)]); + let signed = JSON.parse(resp); + if (verifyEvent(signed)) { + return signed; + } else { + throw new Error(`event returned from bunker is improperly signed: ${JSON.stringify(signed)}`); + } + } + async nip04Encrypt(thirdPartyPubkey, plaintext) { + return await this.sendRequest("nip04_encrypt", [thirdPartyPubkey, plaintext]); + } + async nip04Decrypt(thirdPartyPubkey, ciphertext) { + return await this.sendRequest("nip04_decrypt", [thirdPartyPubkey, ciphertext]); + } + async nip44Encrypt(thirdPartyPubkey, plaintext) { + return await this.sendRequest("nip44_encrypt", [thirdPartyPubkey, plaintext]); + } + async nip44Decrypt(thirdPartyPubkey, ciphertext) { + return await this.sendRequest("nip44_decrypt", [thirdPartyPubkey, ciphertext]); + } +}; +async function createAccount(bunker, params, username, domain, email, localSecretKey = generateSecretKey()) { + if (email && !EMAIL_REGEX.test(email)) + throw new Error("Invalid email"); + let rpc = new BunkerSigner(localSecretKey, bunker.bunkerPointer, params); + let pubkey = await rpc.sendRequest("create_account", [username, domain, email || ""]); + rpc.bp.pubkey = pubkey; + await rpc.connect(); + return rpc; +} +async function fetchBunkerProviders(pool, relays) { + const events = await pool.querySync(relays, { + kinds: [Handlerinformation], + "#k": [NostrConnect.toString()] + }); + events.sort((a, b) => b.created_at - a.created_at); + const validatedBunkers = await Promise.all( + events.map(async (event, i2) => { + try { + const content = JSON.parse(event.content); + try { + if (events.findIndex((ev) => JSON.parse(ev.content).nip05 === content.nip05) !== i2) + return void 0; + } catch (err) { + } + const bp = await queryBunkerProfile(content.nip05); + if (bp && bp.pubkey === event.pubkey && bp.relays.length) { + return { + bunkerPointer: bp, + nip05: content.nip05, + domain: content.nip05.split("@")[1], + name: content.name || content.display_name, + picture: content.picture, + about: content.about, + website: content.website, + local: false + }; + } + } catch (err) { + return void 0; + } + }) + ); + return validatedBunkers.filter((b) => b !== void 0); +} +export { + BUNKER_REGEX, + BunkerSigner, + createAccount, + fetchBunkerProviders, + parseBunkerInput, + queryBunkerProfile, + toBunkerURL, + useFetchImplementation +}; diff --git a/node_modules/nostr-tools/lib/esm/nip46.js.map b/node_modules/nostr-tools/lib/esm/nip46.js.map new file mode 100644 index 0000000..e9ed804 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip46.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../pure.ts", "../../core.ts", "../../utils.ts", "../../nip44.ts", "../../nip05.ts", "../../kinds.ts", "../../filter.ts", "../../fakejson.ts", "../../nip42.ts", "../../helpers.ts", "../../abstract-relay.ts", "../../abstract-pool.ts", "../../pool.ts", "../../nip46.ts"], + "sourcesContent": ["import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { chacha20 } from '@noble/ciphers/chacha'\nimport { equalBytes } from '@noble/ciphers/utils'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { extract as hkdf_extract, expand as hkdf_expand } from '@noble/hashes/hkdf'\nimport { hmac } from '@noble/hashes/hmac'\nimport { sha256 } from '@noble/hashes/sha256'\nimport { concatBytes, randomBytes } from '@noble/hashes/utils'\nimport { base64 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nconst minPlaintextSize = 0x0001 // 1b msg => padded to 32b\nconst maxPlaintextSize = 0xffff // 65535 (64kb-1) => padded to 64kb\n\nexport function getConversationKey(privkeyA: Uint8Array, pubkeyB: string): Uint8Array {\n const sharedX = secp256k1.getSharedSecret(privkeyA, '02' + pubkeyB).subarray(1, 33)\n return hkdf_extract(sha256, sharedX, 'nip44-v2')\n}\n\nfunction getMessageKeys(\n conversationKey: Uint8Array,\n nonce: Uint8Array,\n): { chacha_key: Uint8Array; chacha_nonce: Uint8Array; hmac_key: Uint8Array } {\n const keys = hkdf_expand(sha256, conversationKey, nonce, 76)\n return {\n chacha_key: keys.subarray(0, 32),\n chacha_nonce: keys.subarray(32, 44),\n hmac_key: keys.subarray(44, 76),\n }\n}\n\nfunction calcPaddedLen(len: number): number {\n if (!Number.isSafeInteger(len) || len < 1) throw new Error('expected positive integer')\n if (len <= 32) return 32\n const nextPower = 1 << (Math.floor(Math.log2(len - 1)) + 1)\n const chunk = nextPower <= 256 ? 32 : nextPower / 8\n return chunk * (Math.floor((len - 1) / chunk) + 1)\n}\n\nfunction writeU16BE(num: number): Uint8Array {\n if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize)\n throw new Error('invalid plaintext size: must be between 1 and 65535 bytes')\n const arr = new Uint8Array(2)\n new DataView(arr.buffer).setUint16(0, num, false)\n return arr\n}\n\nfunction pad(plaintext: string): Uint8Array {\n const unpadded = utf8Encoder.encode(plaintext)\n const unpaddedLen = unpadded.length\n const prefix = writeU16BE(unpaddedLen)\n const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen)\n return concatBytes(prefix, unpadded, suffix)\n}\n\nfunction unpad(padded: Uint8Array): string {\n const unpaddedLen = new DataView(padded.buffer).getUint16(0)\n const unpadded = padded.subarray(2, 2 + unpaddedLen)\n if (\n unpaddedLen < minPlaintextSize ||\n unpaddedLen > maxPlaintextSize ||\n unpadded.length !== unpaddedLen ||\n padded.length !== 2 + calcPaddedLen(unpaddedLen)\n )\n throw new Error('invalid padding')\n return utf8Decoder.decode(unpadded)\n}\n\nfunction hmacAad(key: Uint8Array, message: Uint8Array, aad: Uint8Array): Uint8Array {\n if (aad.length !== 32) throw new Error('AAD associated data must be 32 bytes')\n const combined = concatBytes(aad, message)\n return hmac(sha256, key, combined)\n}\n\n// metadata: always 65b (version: 1b, nonce: 32b, max: 32b)\n// plaintext: 1b to 0xffff\n// padded plaintext: 32b to 0xffff\n// ciphertext: 32b+2 to 0xffff+2\n// raw payload: 99 (65+32+2) to 65603 (65+0xffff+2)\n// compressed payload (base64): 132b to 87472b\nfunction decodePayload(payload: string): { nonce: Uint8Array; ciphertext: Uint8Array; mac: Uint8Array } {\n if (typeof payload !== 'string') throw new Error('payload must be a valid string')\n const plen = payload.length\n if (plen < 132 || plen > 87472) throw new Error('invalid payload length: ' + plen)\n if (payload[0] === '#') throw new Error('unknown encryption version')\n let data: Uint8Array\n try {\n data = base64.decode(payload)\n } catch (error) {\n throw new Error('invalid base64: ' + (error as any).message)\n }\n const dlen = data.length\n if (dlen < 99 || dlen > 65603) throw new Error('invalid data length: ' + dlen)\n const vers = data[0]\n if (vers !== 2) throw new Error('unknown encryption version ' + vers)\n return {\n nonce: data.subarray(1, 33),\n ciphertext: data.subarray(33, -32),\n mac: data.subarray(-32),\n }\n}\n\nexport function encrypt(plaintext: string, conversationKey: Uint8Array, nonce: Uint8Array = randomBytes(32)): string {\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n const padded = pad(plaintext)\n const ciphertext = chacha20(chacha_key, chacha_nonce, padded)\n const mac = hmacAad(hmac_key, ciphertext, nonce)\n return base64.encode(concatBytes(new Uint8Array([2]), nonce, ciphertext, mac))\n}\n\nexport function decrypt(payload: string, conversationKey: Uint8Array): string {\n const { nonce, ciphertext, mac } = decodePayload(payload)\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n const calculatedMac = hmacAad(hmac_key, ciphertext, nonce)\n if (!equalBytes(calculatedMac, mac)) throw new Error('invalid MAC')\n const padded = chacha20(chacha_key, chacha_nonce, ciphertext)\n return unpad(padded)\n}\n\nexport const v2 = {\n utils: {\n getConversationKey,\n calcPaddedLen,\n },\n encrypt,\n decrypt,\n}\n", "import { ProfilePointer } from './nip19.ts'\n\nexport type Nip05 = `${string}@${string}`\n\n/**\n * NIP-05 regex. The localpart is optional, and should be assumed to be `_` otherwise.\n *\n * - 0: full match\n * - 1: name (optional)\n * - 2: domain\n */\nexport const NIP05_REGEX = /^(?:([\\w.+-]+)@)?([\\w_-]+(\\.[\\w_-]+)+)$/\nexport const isNip05 = (value?: string | null): value is Nip05 => NIP05_REGEX.test(value || '')\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _fetch: any\n\ntry {\n _fetch = fetch\n} catch (_) {\n null\n}\n\nexport function useFetchImplementation(fetchImplementation: unknown) {\n _fetch = fetchImplementation\n}\n\nexport async function searchDomain(domain: string, query = ''): Promise<{ [name: string]: string }> {\n try {\n const url = `https://${domain}/.well-known/nostr.json?name=${query}`\n const res = await _fetch(url, { redirect: 'manual' })\n if (res.status !== 200) {\n throw Error('Wrong response code')\n }\n const json = await res.json()\n return json.names\n } catch (_) {\n return {}\n }\n}\n\nexport async function queryProfile(fullname: string): Promise {\n const match = fullname.match(NIP05_REGEX)\n if (!match) return null\n\n const [, name = '_', domain] = match\n\n try {\n const url = `https://${domain}/.well-known/nostr.json?name=${name}`\n const res = await _fetch(url, { redirect: 'manual' })\n if (res.status !== 200) {\n throw Error('Wrong response code')\n }\n const json = await res.json()\n\n const pubkey = json.names[name]\n return pubkey ? { pubkey, relays: json.relays?.[pubkey] } : null\n } catch (_e) {\n return null\n }\n}\n\nexport async function isValid(pubkey: string, nip05: Nip05): Promise {\n const res = await queryProfile(nip05)\n return res ? res.pubkey === pubkey : false\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { Event } from './core.ts'\nimport { isAddressableKind, isReplaceableKind } from './kinds.ts'\n\nexport type Filter = {\n ids?: string[]\n kinds?: number[]\n authors?: string[]\n since?: number\n until?: number\n limit?: number\n search?: string\n [key: `#${string}`]: string[] | undefined\n}\n\nexport function matchFilter(filter: Filter, event: Event): boolean {\n if (filter.ids && filter.ids.indexOf(event.id) === -1) {\n return false\n }\n if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) {\n return false\n }\n if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) {\n return false\n }\n\n for (let f in filter) {\n if (f[0] === '#') {\n let tagName = f.slice(1)\n let values = filter[`#${tagName}`]\n if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values!.indexOf(v) !== -1)) return false\n }\n }\n\n if (filter.since && event.created_at < filter.since) return false\n if (filter.until && event.created_at > filter.until) return false\n\n return true\n}\n\nexport function matchFilters(filters: Filter[], event: Event): boolean {\n for (let i = 0; i < filters.length; i++) {\n if (matchFilter(filters[i], event)) {\n return true\n }\n }\n return false\n}\n\nexport function mergeFilters(...filters: Filter[]): Filter {\n let result: Filter = {}\n for (let i = 0; i < filters.length; i++) {\n let filter = filters[i]\n Object.entries(filter).forEach(([property, values]) => {\n if (property === 'kinds' || property === 'ids' || property === 'authors' || property[0] === '#') {\n // @ts-ignore\n result[property] = result[property] || []\n // @ts-ignore\n for (let v = 0; v < values.length; v++) {\n // @ts-ignore\n let value = values[v]\n // @ts-ignore\n if (!result[property].includes(value)) result[property].push(value)\n }\n }\n })\n\n if (filter.limit && (!result.limit || filter.limit > result.limit)) result.limit = filter.limit\n if (filter.until && (!result.until || filter.until > result.until)) result.until = filter.until\n if (filter.since && (!result.since || filter.since < result.since)) result.since = filter.since\n }\n\n return result\n}\n\n/**\n * Calculate the intrinsic limit of a filter.\n * This function returns a positive integer, or `Infinity` if there is no intrinsic limit.\n */\nexport function getFilterLimit(filter: Filter): number {\n if (filter.ids && !filter.ids.length) return 0\n if (filter.kinds && !filter.kinds.length) return 0\n if (filter.authors && !filter.authors.length) return 0\n\n for (const [key, value] of Object.entries(filter)) {\n if (key[0] === '#' && Array.isArray(value) && !value.length) return 0\n }\n\n return Math.min(\n // The `limit` property creates an artificial limit.\n Math.max(0, filter.limit ?? Infinity),\n\n // There can only be one event per `id`.\n filter.ids?.length ?? Infinity,\n\n // Replaceable events are limited by the number of authors and kinds.\n filter.authors?.length && filter.kinds?.every(kind => isReplaceableKind(kind))\n ? filter.authors.length * filter.kinds.length\n : Infinity,\n\n // Parameterized replaceable events are limited by the number of authors, kinds, and \"d\" tags.\n filter.authors?.length && filter.kinds?.every(kind => isAddressableKind(kind)) && filter['#d']?.length\n ? filter.authors.length * filter.kinds.length * filter['#d'].length\n : Infinity,\n )\n}\n", "export function getHex64(json: string, field: string): string {\n let len = field.length + 3\n let idx = json.indexOf(`\"${field}\":`) + len\n let s = json.slice(idx).indexOf(`\"`) + idx + 1\n return json.slice(s, s + 64)\n}\n\nexport function getInt(json: string, field: string): number {\n let len = field.length\n let idx = json.indexOf(`\"${field}\":`) + len + 3\n let sliced = json.slice(idx)\n let end = Math.min(sliced.indexOf(','), sliced.indexOf('}'))\n return parseInt(sliced.slice(0, end), 10)\n}\n\nexport function getSubscriptionId(json: string): string | null {\n let idx = json.slice(0, 22).indexOf(`\"EVENT\"`)\n if (idx === -1) return null\n\n let pstart = json.slice(idx + 7 + 1).indexOf(`\"`)\n if (pstart === -1) return null\n let start = idx + 7 + 1 + pstart\n\n let pend = json.slice(start + 1, 80).indexOf(`\"`)\n if (pend === -1) return null\n let end = start + 1 + pend\n\n return json.slice(start + 1, end)\n}\n\nexport function matchEventId(json: string, id: string): boolean {\n return id === getHex64(json, 'id')\n}\n\nexport function matchEventPubkey(json: string, pubkey: string): boolean {\n return pubkey === getHex64(json, 'pubkey')\n}\n\nexport function matchEventKind(json: string, kind: number): boolean {\n return kind === getInt(json, 'kind')\n}\n", "import { EventTemplate } from './core.ts'\nimport { ClientAuth } from './kinds.ts'\n\n/**\n * creates an EventTemplate for an AUTH event to be signed.\n */\nexport function makeAuthEvent(relayURL: string, challenge: string): EventTemplate {\n return {\n kind: ClientAuth,\n created_at: Math.floor(Date.now() / 1000),\n tags: [\n ['relay', relayURL],\n ['challenge', challenge],\n ],\n content: '',\n }\n}\n", "import { verifiedSymbol, type Event, type Nostr, VerifiedEvent } from './core.ts'\n\nexport async function yieldThread() {\n return new Promise(resolve => {\n const ch = new MessageChannel()\n const handler = () => {\n // @ts-ignore (typescript thinks this property should be called `removeListener`, but in fact it's `removeEventListener`)\n ch.port1.removeEventListener('message', handler)\n resolve()\n }\n // @ts-ignore (typescript thinks this property should be called `addListener`, but in fact it's `addEventListener`)\n ch.port1.addEventListener('message', handler)\n ch.port2.postMessage(0)\n ch.port1.start()\n })\n}\n\nexport const alwaysTrue: Nostr['verifyEvent'] = (t: Event): t is VerifiedEvent => {\n t[verifiedSymbol] = true\n return true\n}\n", "/* global WebSocket */\n\nimport type { Event, EventTemplate, VerifiedEvent, Nostr, NostrEvent } from './core.ts'\nimport { matchFilters, type Filter } from './filter.ts'\nimport { getHex64, getSubscriptionId } from './fakejson.ts'\nimport { Queue, normalizeURL } from './utils.ts'\nimport { makeAuthEvent } from './nip42.ts'\nimport { yieldThread } from './helpers.ts'\n\ntype RelayWebSocket = WebSocket & {\n ping?(): void\n on?(event: 'pong', listener: () => void): any\n}\n\nexport type AbstractRelayConstructorOptions = {\n verifyEvent: Nostr['verifyEvent']\n websocketImplementation?: typeof WebSocket\n enablePing?: boolean\n}\n\nexport class SendingOnClosedConnection extends Error {\n constructor(message: string, relay: string) {\n super(`Tried to send message '${message} on a closed connection to ${relay}.`)\n this.name = 'SendingOnClosedConnection'\n }\n}\n\nexport class AbstractRelay {\n public readonly url: string\n private _connected: boolean = false\n\n public onclose: (() => void) | null = null\n public onnotice: (msg: string) => void = msg => console.debug(`NOTICE from ${this.url}: ${msg}`)\n\n public baseEoseTimeout: number = 4400\n public connectionTimeout: number = 4400\n public publishTimeout: number = 4400\n public pingFrequency: number = 20000\n public pingTimeout: number = 20000\n public openSubs: Map = new Map()\n public enablePing: boolean | undefined\n private connectionTimeoutHandle: ReturnType | undefined\n\n private connectionPromise: Promise | undefined\n private openCountRequests = new Map()\n private openEventPublishes = new Map()\n private ws: RelayWebSocket | undefined\n private incomingMessageQueue = new Queue()\n private queueRunning = false\n private challenge: string | undefined\n private authPromise: Promise | undefined\n private serial: number = 0\n private verifyEvent: Nostr['verifyEvent']\n\n private _WebSocket: typeof WebSocket\n\n constructor(url: string, opts: AbstractRelayConstructorOptions) {\n this.url = normalizeURL(url)\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation || WebSocket\n this.enablePing = opts.enablePing\n }\n\n static async connect(url: string, opts: AbstractRelayConstructorOptions): Promise {\n const relay = new AbstractRelay(url, opts)\n await relay.connect()\n return relay\n }\n\n private closeAllSubscriptions(reason: string) {\n for (let [_, sub] of this.openSubs) {\n sub.close(reason)\n }\n this.openSubs.clear()\n\n for (let [_, ep] of this.openEventPublishes) {\n ep.reject(new Error(reason))\n }\n this.openEventPublishes.clear()\n\n for (let [_, cr] of this.openCountRequests) {\n cr.reject(new Error(reason))\n }\n this.openCountRequests.clear()\n }\n\n public get connected(): boolean {\n return this._connected\n }\n\n public async connect(): Promise {\n if (this.connectionPromise) return this.connectionPromise\n\n this.challenge = undefined\n this.authPromise = undefined\n this.connectionPromise = new Promise((resolve, reject) => {\n this.connectionTimeoutHandle = setTimeout(() => {\n reject('connection timed out')\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection timed out')\n }, this.connectionTimeout)\n\n try {\n this.ws = new this._WebSocket(this.url)\n } catch (err) {\n clearTimeout(this.connectionTimeoutHandle)\n reject(err)\n return\n }\n\n this.ws.onopen = () => {\n clearTimeout(this.connectionTimeoutHandle)\n this._connected = true\n if (this.enablePing) {\n this.pingpong()\n }\n resolve()\n }\n\n this.ws.onerror = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket error')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection errored')\n }\n }\n\n this.ws.onclose = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket closed')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection closed')\n }\n }\n\n this.ws.onmessage = this._onmessage.bind(this)\n })\n\n return this.connectionPromise\n }\n\n private async waitForPingPong() {\n return new Promise((res, err) => {\n // listen for pong\n ;(this.ws && this.ws.on && this.ws.on('pong', () => res(true))) || err(\"ws can't listen for pong\")\n // send a ping\n this.ws && this.ws.ping && this.ws.ping()\n })\n }\n\n private async waitForDummyReq() {\n return new Promise((resolve, _) => {\n // make a dummy request with expected empty eose reply\n // [\"REQ\", \"_\", {\"ids\":[\"aaaa...aaaa\"]}]\n const sub = this.subscribe([{ ids: ['a'.repeat(64)] }], {\n oneose: () => {\n sub.close()\n resolve(true)\n },\n eoseTimeout: this.pingTimeout + 1000,\n })\n })\n }\n\n // nodejs requires this magic here to ensure connections are closed when internet goes off and stuff\n // in browsers it's done automatically. see https://github.com/nbd-wtf/nostr-tools/issues/491\n private async pingpong() {\n // if the websocket is connected\n if (this.ws?.readyState === 1) {\n // wait for either a ping-pong reply or a timeout\n const result = await Promise.any([\n // browsers don't have ping so use a dummy req\n this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(),\n new Promise(res => setTimeout(() => res(false), this.pingTimeout)),\n ])\n if (result) {\n // schedule another pingpong\n setTimeout(() => this.pingpong(), this.pingFrequency)\n } else {\n // pingpong closing socket\n this.closeAllSubscriptions('pingpong timed out')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n }\n }\n\n private async runQueue() {\n this.queueRunning = true\n while (true) {\n if (false === this.handleNext()) {\n break\n }\n await yieldThread()\n }\n this.queueRunning = false\n }\n\n private handleNext(): undefined | false {\n const json = this.incomingMessageQueue.dequeue()\n if (!json) {\n return false\n }\n\n const subid = getSubscriptionId(json)\n if (subid) {\n const so = this.openSubs.get(subid as string)\n if (!so) {\n // this is an EVENT message, but for a subscription we don't have, so just stop here\n return\n }\n\n // this will be called only when this message is a EVENT message for a subscription we have\n // we do this before parsing the JSON to not have to do that for duplicate events\n // since JSON parsing is slow\n const id = getHex64(json, 'id')\n const alreadyHave = so.alreadyHaveEvent?.(id)\n\n // notify any interested client that the relay has this event\n // (do this after alreadyHaveEvent() because the client may rely on this to answer that)\n so.receivedEvent?.(this, id)\n\n if (alreadyHave) {\n // if we had already seen this event we can just stop here\n return\n }\n }\n\n try {\n let data = JSON.parse(json)\n // we won't do any checks against the data since all failures (i.e. invalid messages from relays)\n // will naturally be caught by the encompassing try..catch block\n\n switch (data[0]) {\n case 'EVENT': {\n const so = this.openSubs.get(data[1] as string) as Subscription\n const event = data[2] as NostrEvent\n if (this.verifyEvent(event) && matchFilters(so.filters, event)) {\n so.onevent(event)\n }\n return\n }\n case 'COUNT': {\n const id: string = data[1]\n const payload = data[2] as { count: number }\n const cr = this.openCountRequests.get(id) as CountResolver\n if (cr) {\n cr.resolve(payload.count)\n this.openCountRequests.delete(id)\n }\n return\n }\n case 'EOSE': {\n const so = this.openSubs.get(data[1] as string)\n if (!so) return\n so.receivedEose()\n return\n }\n case 'OK': {\n const id: string = data[1]\n const ok: boolean = data[2]\n const reason: string = data[3]\n const ep = this.openEventPublishes.get(id) as EventPublishResolver\n if (ep) {\n clearTimeout(ep.timeout)\n if (ok) ep.resolve(reason)\n else ep.reject(new Error(reason))\n this.openEventPublishes.delete(id)\n }\n return\n }\n case 'CLOSED': {\n const id: string = data[1]\n const so = this.openSubs.get(id)\n if (!so) return\n so.closed = true\n so.close(data[2] as string)\n return\n }\n case 'NOTICE':\n this.onnotice(data[1] as string)\n return\n case 'AUTH': {\n this.challenge = data[1] as string\n return\n }\n }\n } catch (err) {\n return\n }\n }\n\n public async send(message: string) {\n if (!this.connectionPromise) throw new SendingOnClosedConnection(message, this.url)\n\n this.connectionPromise.then(() => {\n this.ws?.send(message)\n })\n }\n\n public async auth(signAuthEvent: (evt: EventTemplate) => Promise): Promise {\n const challenge = this.challenge\n if (!challenge) throw new Error(\"can't perform auth, no challenge was received\")\n if (this.authPromise) return this.authPromise\n\n this.authPromise = new Promise(async (resolve, reject) => {\n try {\n let evt = await signAuthEvent(makeAuthEvent(this.url, challenge))\n let timeout = setTimeout(() => {\n let ep = this.openEventPublishes.get(evt.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('auth timed out'))\n this.openEventPublishes.delete(evt.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(evt.id, { resolve, reject, timeout })\n this.send('[\"AUTH\",' + JSON.stringify(evt) + ']')\n } catch (err) {\n console.warn('subscribe auth function failed:', err)\n }\n })\n return this.authPromise\n }\n\n public async publish(event: Event): Promise {\n const ret = new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n const ep = this.openEventPublishes.get(event.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('publish timed out'))\n this.openEventPublishes.delete(event.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(event.id, { resolve, reject, timeout })\n })\n this.send('[\"EVENT\",' + JSON.stringify(event) + ']')\n return ret\n }\n\n public async count(filters: Filter[], params: { id?: string | null }): Promise {\n this.serial++\n const id = params?.id || 'count:' + this.serial\n const ret = new Promise((resolve, reject) => {\n this.openCountRequests.set(id, { resolve, reject })\n })\n this.send('[\"COUNT\",\"' + id + '\",' + JSON.stringify(filters).substring(1))\n return ret\n }\n\n public subscribe(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n const subscription = this.prepareSubscription(filters, params)\n subscription.fire()\n return subscription\n }\n\n public prepareSubscription(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n this.serial++\n const id = params.id || (params.label ? params.label + ':' : 'sub:') + this.serial\n const subscription = new Subscription(this, id, filters, params)\n this.openSubs.set(id, subscription)\n return subscription\n }\n\n public close() {\n this.closeAllSubscriptions('relay connection closed by us')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n\n // this is the function assigned to this.ws.onmessage\n // it's exposed for testing and debugging purposes\n public _onmessage(ev: MessageEvent) {\n this.incomingMessageQueue.enqueue(ev.data as string)\n if (!this.queueRunning) {\n this.runQueue()\n }\n }\n}\n\nexport class Subscription {\n public readonly relay: AbstractRelay\n public readonly id: string\n\n public closed: boolean = false\n public eosed: boolean = false\n public filters: Filter[]\n public alreadyHaveEvent: ((id: string) => boolean) | undefined\n public receivedEvent: ((relay: AbstractRelay, id: string) => void) | undefined\n\n public onevent: (evt: Event) => void\n public oneose: (() => void) | undefined\n public onclose: ((reason: string) => void) | undefined\n\n public eoseTimeout: number\n private eoseTimeoutHandle: ReturnType | undefined\n\n constructor(relay: AbstractRelay, id: string, filters: Filter[], params: SubscriptionParams) {\n this.relay = relay\n this.filters = filters\n this.id = id\n this.alreadyHaveEvent = params.alreadyHaveEvent\n this.receivedEvent = params.receivedEvent\n this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout\n\n this.oneose = params.oneose\n this.onclose = params.onclose\n this.onevent =\n params.onevent ||\n (event => {\n console.warn(\n `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,\n event,\n )\n })\n }\n\n public fire() {\n this.relay.send('[\"REQ\",\"' + this.id + '\",' + JSON.stringify(this.filters).substring(1))\n\n // only now we start counting the eoseTimeout\n this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout)\n }\n\n public receivedEose() {\n if (this.eosed) return\n clearTimeout(this.eoseTimeoutHandle)\n this.eosed = true\n this.oneose?.()\n }\n\n public close(reason: string = 'closed by caller') {\n if (!this.closed && this.relay.connected) {\n // if the connection was closed by the user calling .close() we will send a CLOSE message\n // otherwise this._open will be already set to false so we will skip this\n try {\n this.relay.send('[\"CLOSE\",' + JSON.stringify(this.id) + ']')\n } catch (err) {\n if (err instanceof SendingOnClosedConnection) {\n /* doesn't matter, it's ok */\n } else {\n throw err\n }\n }\n this.closed = true\n }\n this.relay.openSubs.delete(this.id)\n this.onclose?.(reason)\n }\n}\n\nexport type SubscriptionParams = {\n onevent?: (evt: Event) => void\n oneose?: () => void\n onclose?: (reason: string) => void\n alreadyHaveEvent?: (id: string) => boolean\n receivedEvent?: (relay: AbstractRelay, id: string) => void\n eoseTimeout?: number\n}\n\nexport type CountResolver = {\n resolve: (count: number) => void\n reject: (err: Error) => void\n}\n\nexport type EventPublishResolver = {\n resolve: (reason: string) => void\n reject: (err: Error) => void\n timeout: ReturnType\n}\n", "/* global WebSocket */\n\nimport {\n AbstractRelay as AbstractRelay,\n SubscriptionParams,\n Subscription,\n type AbstractRelayConstructorOptions,\n} from './abstract-relay.ts'\nimport { normalizeURL } from './utils.ts'\n\nimport type { Event, EventTemplate, Nostr, VerifiedEvent } from './core.ts'\nimport { type Filter } from './filter.ts'\nimport { alwaysTrue } from './helpers.ts'\n\nexport type SubCloser = { close: (reason?: string) => void }\n\nexport type AbstractPoolConstructorOptions = AbstractRelayConstructorOptions & {}\n\nexport type SubscribeManyParams = Omit & {\n maxWait?: number\n onclose?: (reasons: string[]) => void\n onauth?: (event: EventTemplate) => Promise\n // Deprecated: use onauth instead\n doauth?: (event: EventTemplate) => Promise\n id?: string\n label?: string\n}\n\nexport class AbstractSimplePool {\n protected relays: Map = new Map()\n public seenOn: Map> = new Map()\n public trackRelays: boolean = false\n\n public verifyEvent: Nostr['verifyEvent']\n public enablePing: boolean | undefined\n public trustedRelayURLs: Set = new Set()\n\n private _WebSocket?: typeof WebSocket\n\n constructor(opts: AbstractPoolConstructorOptions) {\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation\n this.enablePing = opts.enablePing\n }\n\n async ensureRelay(url: string, params?: { connectionTimeout?: number }): Promise {\n url = normalizeURL(url)\n\n let relay = this.relays.get(url)\n if (!relay) {\n relay = new AbstractRelay(url, {\n verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent,\n websocketImplementation: this._WebSocket,\n enablePing: this.enablePing,\n })\n relay.onclose = () => {\n this.relays.delete(url)\n }\n if (params?.connectionTimeout) relay.connectionTimeout = params.connectionTimeout\n this.relays.set(url, relay)\n }\n await relay.connect()\n\n return relay\n }\n\n close(relays: string[]) {\n relays.map(normalizeURL).forEach(url => {\n this.relays.get(url)?.close()\n this.relays.delete(url)\n })\n }\n\n subscribe(relays: string[], filter: Filter, params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const request: { url: string; filter: Filter }[] = []\n for (let i = 0; i < relays.length; i++) {\n const url = normalizeURL(relays[i])\n if (!request.find(r => r.url === url)) {\n request.push({ url, filter })\n }\n }\n\n return this.subscribeMap(request, params)\n }\n\n subscribeMany(relays: string[], filters: Filter[], params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const request: { url: string; filter: Filter }[] = []\n const uniqUrls: string[] = []\n for (let i = 0; i < relays.length; i++) {\n const url = normalizeURL(relays[i])\n if (uniqUrls.indexOf(url) === -1) {\n for (let f = 0; f < filters.length; f++) {\n request.push({ url, filter: filters[f] })\n }\n }\n }\n\n return this.subscribeMap(request, params)\n }\n\n subscribeMap(requests: { url: string; filter: Filter }[], params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n if (this.trackRelays) {\n params.receivedEvent = (relay: AbstractRelay, id: string) => {\n let set = this.seenOn.get(id)\n if (!set) {\n set = new Set()\n this.seenOn.set(id, set)\n }\n set.add(relay)\n }\n }\n\n const _knownIds = new Set()\n const subs: Subscription[] = []\n\n // batch all EOSEs into a single\n const eosesReceived: boolean[] = []\n let handleEose = (i: number) => {\n if (eosesReceived[i]) return // do not act twice for the same relay\n eosesReceived[i] = true\n if (eosesReceived.filter(a => a).length === requests.length) {\n params.oneose?.()\n handleEose = () => {}\n }\n }\n // batch all closes into a single\n const closesReceived: string[] = []\n let handleClose = (i: number, reason: string) => {\n if (closesReceived[i]) return // do not act twice for the same relay\n handleEose(i)\n closesReceived[i] = reason\n if (closesReceived.filter(a => a).length === requests.length) {\n params.onclose?.(closesReceived)\n handleClose = () => {}\n }\n }\n\n const localAlreadyHaveEventHandler = (id: string) => {\n if (params.alreadyHaveEvent?.(id)) {\n return true\n }\n const have = _knownIds.has(id)\n _knownIds.add(id)\n return have\n }\n\n // open a subscription in all given relays\n const allOpened = Promise.all(\n requests.map(async ({ url, filter }, i) => {\n let relay: AbstractRelay\n try {\n relay = await this.ensureRelay(url, {\n connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1000) : undefined,\n })\n } catch (err) {\n handleClose(i, (err as any)?.message || String(err))\n return\n }\n\n let subscription = relay.subscribe([filter], {\n ...params,\n oneose: () => handleEose(i),\n onclose: reason => {\n if (reason.startsWith('auth-required: ') && params.onauth) {\n relay\n .auth(params.onauth)\n .then(() => {\n relay.subscribe([filter], {\n ...params,\n oneose: () => handleEose(i),\n onclose: reason => {\n handleClose(i, reason) // the second time we won't try to auth anymore\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait,\n })\n })\n .catch(err => {\n handleClose(i, `auth was required and attempted, but failed with: ${err}`)\n })\n } else {\n handleClose(i, reason)\n }\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait,\n })\n\n subs.push(subscription)\n }),\n )\n\n return {\n async close(reason?: string) {\n await allOpened\n subs.forEach(sub => {\n sub.close(reason)\n })\n },\n }\n }\n\n subscribeEose(\n relays: string[],\n filter: Filter,\n params: Pick,\n ): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const subcloser = this.subscribe(relays, filter, {\n ...params,\n oneose() {\n subcloser.close('closed automatically on eose')\n },\n })\n return subcloser\n }\n\n subscribeManyEose(\n relays: string[],\n filters: Filter[],\n params: Pick,\n ): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const subcloser = this.subscribeMany(relays, filters, {\n ...params,\n oneose() {\n subcloser.close('closed automatically on eose')\n },\n })\n return subcloser\n }\n\n async querySync(\n relays: string[],\n filter: Filter,\n params?: Pick,\n ): Promise {\n return new Promise(async resolve => {\n const events: Event[] = []\n this.subscribeEose(relays, filter, {\n ...params,\n onevent(event: Event) {\n events.push(event)\n },\n onclose(_: string[]) {\n resolve(events)\n },\n })\n })\n }\n\n async get(\n relays: string[],\n filter: Filter,\n params?: Pick,\n ): Promise {\n filter.limit = 1\n const events = await this.querySync(relays, filter, params)\n events.sort((a, b) => b.created_at - a.created_at)\n return events[0] || null\n }\n\n publish(\n relays: string[],\n event: Event,\n options?: { onauth?: (evt: EventTemplate) => Promise },\n ): Promise[] {\n return relays.map(normalizeURL).map(async (url, i, arr) => {\n if (arr.indexOf(url) !== i) {\n // duplicate\n return Promise.reject('duplicate url')\n }\n\n let r = await this.ensureRelay(url)\n return r\n .publish(event)\n .catch(async err => {\n if (err instanceof Error && err.message.startsWith('auth-required: ') && options?.onauth) {\n await r.auth(options.onauth)\n return r.publish(event) // retry\n }\n throw err\n })\n .then(reason => {\n if (this.trackRelays) {\n let set = this.seenOn.get(event.id)\n if (!set) {\n set = new Set()\n this.seenOn.set(event.id, set)\n }\n set.add(r)\n }\n return reason\n })\n })\n }\n\n listConnectionStatus(): Map {\n const map = new Map()\n this.relays.forEach((relay, url) => map.set(url, relay.connected))\n\n return map\n }\n\n destroy(): void {\n this.relays.forEach(conn => conn.close())\n this.relays = new Map()\n }\n}\n", "/* global WebSocket */\n\nimport { verifyEvent } from './pure.ts'\nimport { AbstractSimplePool } from './abstract-pool.ts'\n\nvar _WebSocket: typeof WebSocket\n\ntry {\n _WebSocket = WebSocket\n} catch {}\n\nexport function useWebSocketImplementation(websocketImplementation: any) {\n _WebSocket = websocketImplementation\n}\n\nexport class SimplePool extends AbstractSimplePool {\n constructor(options?: { enablePing?: boolean }) {\n super({ verifyEvent, websocketImplementation: _WebSocket, ...options })\n }\n}\n\nexport * from './abstract-pool.ts'\n", "import { EventTemplate, NostrEvent, VerifiedEvent } from './core.ts'\nimport { generateSecretKey, finalizeEvent, getPublicKey, verifyEvent } from './pure.ts'\nimport { AbstractSimplePool, SubCloser } from './abstract-pool.ts'\nimport { getConversationKey, decrypt, encrypt } from './nip44.ts'\nimport { NIP05_REGEX } from './nip05.ts'\nimport { SimplePool } from './pool.ts'\nimport { Handlerinformation, NostrConnect } from './kinds.ts'\nimport { Signer } from './signer.ts'\n\nvar _fetch: any\n\ntry {\n _fetch = fetch\n} catch {}\n\nexport function useFetchImplementation(fetchImplementation: any) {\n _fetch = fetchImplementation\n}\n\nexport const BUNKER_REGEX = /^bunker:\\/\\/([0-9a-f]{64})\\??([?\\/\\w:.=&%-]*)$/\nconst EMAIL_REGEX = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\nexport type BunkerPointer = {\n relays: string[]\n pubkey: string\n secret: null | string\n}\n\nexport function toBunkerURL(bunkerPointer: BunkerPointer): string {\n let bunkerURL = new URL(`bunker://${bunkerPointer.pubkey}`)\n bunkerPointer.relays.forEach(relay => {\n bunkerURL.searchParams.append('relay', relay)\n })\n if (bunkerPointer.secret) {\n bunkerURL.searchParams.set('secret', bunkerPointer.secret)\n }\n return bunkerURL.toString()\n}\n\n/** This takes either a bunker:// URL or a name@domain.com NIP-05 identifier\n and returns a BunkerPointer -- or null in case of error */\nexport async function parseBunkerInput(input: string): Promise {\n let match = input.match(BUNKER_REGEX)\n if (match) {\n try {\n const pubkey = match[1]\n const qs = new URLSearchParams(match[2])\n return {\n pubkey,\n relays: qs.getAll('relay'),\n secret: qs.get('secret'),\n }\n } catch (_err) {\n /* just move to the next case */\n }\n }\n\n return queryBunkerProfile(input)\n}\n\nexport async function queryBunkerProfile(nip05: string): Promise {\n const match = nip05.match(NIP05_REGEX)\n if (!match) return null\n\n const [_, name = '_', domain] = match\n\n try {\n const url = `https://${domain}/.well-known/nostr.json?name=${name}`\n const res = await (await _fetch(url, { redirect: 'error' })).json()\n\n let pubkey = res.names[name]\n let relays = res.nip46[pubkey] || []\n\n return { pubkey, relays, secret: null }\n } catch (_err) {\n return null\n }\n}\n\nexport type BunkerSignerParams = {\n pool?: AbstractSimplePool\n onauth?: (url: string) => void\n}\n\nexport class BunkerSigner implements Signer {\n private params: BunkerSignerParams\n private pool: AbstractSimplePool\n private subCloser: SubCloser | undefined\n private isOpen: boolean\n private serial: number\n private idPrefix: string\n private listeners: {\n [id: string]: {\n resolve: (_: string) => void\n reject: (_: string) => void\n }\n }\n private waitingForAuth: { [id: string]: boolean }\n private secretKey: Uint8Array\n private conversationKey: Uint8Array\n public bp: BunkerPointer\n\n private cachedPubKey: string | undefined\n\n /**\n * Creates a new instance of the Nip46 class.\n * @param relays - An array of relay addresses.\n * @param remotePubkey - An optional remote public key. This is the key you want to sign as.\n * @param secretKey - An optional key pair.\n */\n public constructor(clientSecretKey: Uint8Array, bp: BunkerPointer, params: BunkerSignerParams = {}) {\n if (bp.relays.length === 0) {\n throw new Error('no relays are specified for this bunker')\n }\n\n this.params = params\n this.pool = params.pool || new SimplePool()\n this.secretKey = clientSecretKey\n this.conversationKey = getConversationKey(clientSecretKey, bp.pubkey)\n this.bp = bp\n this.isOpen = false\n this.idPrefix = Math.random().toString(36).substring(7)\n this.serial = 0\n this.listeners = {}\n this.waitingForAuth = {}\n\n this.setupSubscription(params)\n }\n\n private setupSubscription(params: BunkerSignerParams) {\n const listeners = this.listeners\n const waitingForAuth = this.waitingForAuth\n const convKey = this.conversationKey\n\n this.subCloser = this.pool.subscribe(\n this.bp.relays,\n { kinds: [NostrConnect], authors: [this.bp.pubkey], '#p': [getPublicKey(this.secretKey)] },\n {\n onevent: async (event: NostrEvent) => {\n const o = JSON.parse(decrypt(event.content, convKey))\n const { id, result, error } = o\n\n if (result === 'auth_url' && waitingForAuth[id]) {\n delete waitingForAuth[id]\n\n if (params.onauth) {\n params.onauth(error)\n } else {\n console.warn(\n `nostr-tools/nip46: remote signer ${this.bp.pubkey} tried to send an \"auth_url\"='${error}' but there was no onauth() callback configured.`,\n )\n }\n return\n }\n\n let handler = listeners[id]\n if (handler) {\n if (error) handler.reject(error)\n else if (result) handler.resolve(result)\n delete listeners[id]\n }\n },\n onclose: () => {\n this.subCloser = undefined\n },\n },\n )\n this.isOpen = true\n }\n\n // closes the subscription -- this object can't be used anymore after this\n async close() {\n this.isOpen = false\n this.subCloser!.close()\n }\n\n async sendRequest(method: string, params: string[]): Promise {\n return new Promise(async (resolve, reject) => {\n try {\n if (!this.isOpen) throw new Error('this signer is not open anymore, create a new one')\n if (!this.subCloser) this.setupSubscription(this.params)\n\n this.serial++\n const id = `${this.idPrefix}-${this.serial}`\n\n const encryptedContent = encrypt(JSON.stringify({ id, method, params }), this.conversationKey)\n\n // the request event\n const verifiedEvent: VerifiedEvent = finalizeEvent(\n {\n kind: NostrConnect,\n tags: [['p', this.bp.pubkey]],\n content: encryptedContent,\n created_at: Math.floor(Date.now() / 1000),\n },\n this.secretKey,\n )\n\n // setup callback listener\n this.listeners[id] = { resolve, reject }\n this.waitingForAuth[id] = true\n\n // publish the event\n await Promise.any(this.pool.publish(this.bp.relays, verifiedEvent))\n } catch (err) {\n reject(err)\n }\n })\n }\n\n /**\n * Calls the \"connect\" method on the bunker.\n * The promise will be rejected if the response is not \"pong\".\n */\n async ping(): Promise {\n let resp = await this.sendRequest('ping', [])\n if (resp !== 'pong') throw new Error(`result is not pong: ${resp}`)\n }\n\n /**\n * Calls the \"connect\" method on the bunker.\n */\n async connect(): Promise {\n await this.sendRequest('connect', [this.bp.pubkey, this.bp.secret || ''])\n }\n\n /**\n * Calls the \"get_public_key\" method on the bunker.\n * (before we would return the public key hardcoded in the bunker parameters, but\n * that is not correct as that may be the bunker pubkey and the actual signer\n * pubkey may be different.)\n */\n async getPublicKey(): Promise {\n if (!this.cachedPubKey) {\n this.cachedPubKey = await this.sendRequest('get_public_key', [])\n }\n return this.cachedPubKey\n }\n\n /**\n * Signs an event using the remote private key.\n * @param event - The event to sign.\n * @returns A Promise that resolves to the signed event.\n */\n async signEvent(event: EventTemplate): Promise {\n let resp = await this.sendRequest('sign_event', [JSON.stringify(event)])\n let signed: NostrEvent = JSON.parse(resp)\n if (verifyEvent(signed)) {\n return signed\n } else {\n throw new Error(`event returned from bunker is improperly signed: ${JSON.stringify(signed)}`)\n }\n }\n\n async nip04Encrypt(thirdPartyPubkey: string, plaintext: string): Promise {\n return await this.sendRequest('nip04_encrypt', [thirdPartyPubkey, plaintext])\n }\n\n async nip04Decrypt(thirdPartyPubkey: string, ciphertext: string): Promise {\n return await this.sendRequest('nip04_decrypt', [thirdPartyPubkey, ciphertext])\n }\n\n async nip44Encrypt(thirdPartyPubkey: string, plaintext: string): Promise {\n return await this.sendRequest('nip44_encrypt', [thirdPartyPubkey, plaintext])\n }\n\n async nip44Decrypt(thirdPartyPubkey: string, ciphertext: string): Promise {\n return await this.sendRequest('nip44_decrypt', [thirdPartyPubkey, ciphertext])\n }\n}\n\n/**\n * Creates an account with the specified username, domain, and optional email.\n * @param bunkerPubkey - The public key of the bunker to use for the create_account call.\n * @param username - The username for the account.\n * @param domain - The domain for the account.\n * @param email - The optional email for the account.\n * @param localSecretKey - Optionally pass a local secret key that will be used to communicate with the bunker,\n this will default to generating a random key.\n * @throws Error if the email is present but invalid.\n * @returns A Promise that resolves to the auth_url that the client should follow to create an account.\n */\nexport async function createAccount(\n bunker: BunkerProfile,\n params: BunkerSignerParams,\n username: string,\n domain: string,\n email?: string,\n localSecretKey: Uint8Array = generateSecretKey(),\n): Promise {\n if (email && !EMAIL_REGEX.test(email)) throw new Error('Invalid email')\n\n let rpc = new BunkerSigner(localSecretKey, bunker.bunkerPointer, params)\n\n let pubkey = await rpc.sendRequest('create_account', [username, domain, email || ''])\n\n // once we get the newly created pubkey back, we hijack this signer instance\n // and turn it into the main instance for this newly created pubkey\n rpc.bp.pubkey = pubkey\n await rpc.connect()\n\n return rpc\n}\n\n/**\n * Fetches info on available providers that announce themselves using NIP-89 events.\n * @returns A promise that resolves to an array of available bunker objects.\n */\nexport async function fetchBunkerProviders(pool: AbstractSimplePool, relays: string[]): Promise {\n const events = await pool.querySync(relays, {\n kinds: [Handlerinformation],\n '#k': [NostrConnect.toString()],\n })\n\n events.sort((a, b) => b.created_at - a.created_at)\n\n // validate bunkers by checking their NIP-05 and pubkey\n // map to a more useful object\n const validatedBunkers = await Promise.all(\n events.map(async (event, i) => {\n try {\n const content = JSON.parse(event.content)\n\n // skip duplicates\n try {\n if (events.findIndex(ev => JSON.parse(ev.content).nip05 === content.nip05) !== i) return undefined\n } catch (err) {\n /***/\n }\n\n const bp = await queryBunkerProfile(content.nip05)\n if (bp && bp.pubkey === event.pubkey && bp.relays.length) {\n return {\n bunkerPointer: bp,\n nip05: content.nip05,\n domain: content.nip05.split('@')[1],\n name: content.name || content.display_name,\n picture: content.picture,\n about: content.about,\n website: content.website,\n local: false,\n }\n }\n } catch (err) {\n return undefined\n }\n }),\n )\n\n return validatedBunkers.filter(b => b !== undefined) as BunkerProfile[]\n}\n\nexport type BunkerProfile = {\n bunkerPointer: BunkerPointer\n domain: string\n nip05: string\n name: string\n picture: string\n about: string\n website: string\n local: boolean\n}\n"], + "mappings": ";AAAA,SAAS,eAAe;AACxB,SAAS,cAAAA,mBAAkB;;;ACOpB,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,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B,SAAO;AACT;AAMA,eAAsB,qBAAqB,MAA0B,QAA4C;AAC/G,QAAM,SAAS,MAAM,KAAK,UAAU,QAAQ;AAAA,IAC1C,OAAO,CAAC,kBAAkB;AAAA,IAC1B,MAAM,CAAC,aAAa,SAAS,CAAC;AAAA,EAChC,CAAC;AAED,SAAO,KAAK,CAAC,GAAG,MAAM,EAAE,aAAa,EAAE,UAAU;AAIjD,QAAM,mBAAmB,MAAM,QAAQ;AAAA,IACrC,OAAO,IAAI,OAAO,OAAOC,OAAM;AAC7B,UAAI;AACF,cAAM,UAAU,KAAK,MAAM,MAAM,OAAO;AAGxC,YAAI;AACF,cAAI,OAAO,UAAU,QAAM,KAAK,MAAM,GAAG,OAAO,EAAE,UAAU,QAAQ,KAAK,MAAMA;AAAG,mBAAO;AAAA,QAC3F,SAAS,KAAP;AAAA,QAEF;AAEA,cAAM,KAAK,MAAM,mBAAmB,QAAQ,KAAK;AACjD,YAAI,MAAM,GAAG,WAAW,MAAM,UAAU,GAAG,OAAO,QAAQ;AACxD,iBAAO;AAAA,YACL,eAAe;AAAA,YACf,OAAO,QAAQ;AAAA,YACf,QAAQ,QAAQ,MAAM,MAAM,GAAG,EAAE;AAAA,YACjC,MAAM,QAAQ,QAAQ,QAAQ;AAAA,YAC9B,SAAS,QAAQ;AAAA,YACjB,OAAO,QAAQ;AAAA,YACf,SAAS,QAAQ;AAAA,YACjB,OAAO;AAAA,UACT;AAAA,QACF;AAAA,MACF,SAAS,KAAP;AACA,eAAO;AAAA,MACT;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAO,iBAAiB,OAAO,OAAK,MAAM,MAAS;AACrD;", + "names": ["bytesToHex", "i", "target", "bytesToHex", "sha256", "sha256", "i", "i", "reason", "_fetch", "i"] +} diff --git a/node_modules/nostr-tools/lib/esm/nip47.js b/node_modules/nostr-tools/lib/esm/nip47.js new file mode 100644 index 0000000..d4035a5 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip47.js @@ -0,0 +1,145 @@ +// pure.ts +import { schnorr } from "@noble/curves/secp256k1"; +import { bytesToHex as bytesToHex2 } from "@noble/hashes/utils"; + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +import { sha256 } from "@noble/hashes/sha256"; + +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// pure.ts +var JS = class { + generateSecretKey() { + return schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return bytesToHex2(schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = bytesToHex2(schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = bytesToHex2(schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = sha256(utf8Encoder.encode(serializeEvent(event))); + return bytesToHex2(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// kinds.ts +var NWCWalletRequest = 23194; + +// nip04.ts +import { bytesToHex as bytesToHex3, randomBytes } from "@noble/hashes/utils"; +import { secp256k1 } from "@noble/curves/secp256k1"; +import { cbc } from "@noble/ciphers/aes"; +import { base64 } from "@scure/base"; +function encrypt(secretKey, pubkey, text) { + const privkey = secretKey instanceof Uint8Array ? bytesToHex3(secretKey) : secretKey; + const key = secp256k1.getSharedSecret(privkey, "02" + pubkey); + const normalizedKey = getNormalizedX(key); + let iv = Uint8Array.from(randomBytes(16)); + let plaintext = utf8Encoder.encode(text); + let ciphertext = cbc(normalizedKey, iv).encrypt(plaintext); + let ctb64 = base64.encode(new Uint8Array(ciphertext)); + let ivb64 = base64.encode(new Uint8Array(iv.buffer)); + return `${ctb64}?iv=${ivb64}`; +} +function getNormalizedX(key) { + return key.slice(1, 33); +} + +// nip47.ts +function parseConnectionString(connectionString) { + const { host, pathname, searchParams } = new URL(connectionString); + const pubkey = pathname || host; + const relay = searchParams.get("relay"); + const secret = searchParams.get("secret"); + if (!pubkey || !relay || !secret) { + throw new Error("invalid connection string"); + } + return { pubkey, relay, secret }; +} +async function makeNwcRequestEvent(pubkey, secretKey, invoice) { + const content = { + method: "pay_invoice", + params: { + invoice + } + }; + const encryptedContent = encrypt(secretKey, pubkey, JSON.stringify(content)); + const eventTemplate = { + kind: NWCWalletRequest, + created_at: Math.round(Date.now() / 1e3), + content: encryptedContent, + tags: [["p", pubkey]] + }; + return finalizeEvent(eventTemplate, secretKey); +} +export { + makeNwcRequestEvent, + parseConnectionString +}; diff --git a/node_modules/nostr-tools/lib/esm/nip47.js.map b/node_modules/nostr-tools/lib/esm/nip47.js.map new file mode 100644 index 0000000..c5519d4 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip47.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../pure.ts", "../../core.ts", "../../utils.ts", "../../kinds.ts", "../../nip04.ts", "../../nip47.ts"], + "sourcesContent": ["import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { bytesToHex, randomBytes } from '@noble/hashes/utils'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { cbc } from '@noble/ciphers/aes'\nimport { base64 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport function encrypt(secretKey: string | Uint8Array, pubkey: string, text: string): string {\n const privkey: string = secretKey instanceof Uint8Array ? bytesToHex(secretKey) : secretKey\n const key = secp256k1.getSharedSecret(privkey, '02' + pubkey)\n const normalizedKey = getNormalizedX(key)\n\n let iv = Uint8Array.from(randomBytes(16))\n let plaintext = utf8Encoder.encode(text)\n\n let ciphertext = cbc(normalizedKey, iv).encrypt(plaintext)\n\n let ctb64 = base64.encode(new Uint8Array(ciphertext))\n let ivb64 = base64.encode(new Uint8Array(iv.buffer))\n\n return `${ctb64}?iv=${ivb64}`\n}\n\nexport function decrypt(secretKey: string | Uint8Array, pubkey: string, data: string): string {\n const privkey: string = secretKey instanceof Uint8Array ? bytesToHex(secretKey) : secretKey\n let [ctb64, ivb64] = data.split('?iv=')\n let key = secp256k1.getSharedSecret(privkey, '02' + pubkey)\n let normalizedKey = getNormalizedX(key)\n\n let iv = base64.decode(ivb64)\n let ciphertext = base64.decode(ctb64)\n\n let plaintext = cbc(normalizedKey, iv).decrypt(ciphertext)\n\n return utf8Decoder.decode(plaintext)\n}\n\nfunction getNormalizedX(key: Uint8Array): Uint8Array {\n return key.slice(1, 33)\n}\n", "import { type VerifiedEvent, finalizeEvent } from './pure.ts'\nimport { NWCWalletRequest } from './kinds.ts'\nimport { encrypt } from './nip04.ts'\n\ninterface NWCConnection {\n pubkey: string\n relay: string\n secret: string\n}\n\nexport function parseConnectionString(connectionString: string): NWCConnection {\n const { host, pathname, searchParams } = new URL(connectionString)\n const pubkey = pathname || host\n const relay = searchParams.get('relay')\n const secret = searchParams.get('secret')\n\n if (!pubkey || !relay || !secret) {\n throw new Error('invalid connection string')\n }\n\n return { pubkey, relay, secret }\n}\n\nexport async function makeNwcRequestEvent(\n pubkey: string,\n secretKey: Uint8Array,\n invoice: string,\n): Promise {\n const content = {\n method: 'pay_invoice',\n params: {\n invoice,\n },\n }\n const encryptedContent = encrypt(secretKey, pubkey, JSON.stringify(content))\n const eventTemplate = {\n kind: NWCWalletRequest,\n created_at: Math.round(Date.now() / 1000),\n content: encryptedContent,\n tags: [['p', pubkey]],\n }\n\n return finalizeEvent(eventTemplate, secretKey)\n}\n"], + "mappings": ";AAAA,SAAS,eAAe;AACxB,SAAS,cAAAA,mBAAkB;;;ACOpB,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,CAAC,QAAiD,eAAe;AAE3E,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AAU,CAAC;AACpD,MAAI,QAAQ,OAAO,OAAO,IAAI,WAAW,GAAG,MAAM,CAAC;AAEnD,SAAO,GAAG,YAAY;AACxB;AAgBA,SAAS,eAAe,KAA6B;AACnD,SAAO,IAAI,MAAM,GAAG,EAAE;AACxB;;;AC7BO,SAAS,sBAAsB,kBAAyC;AAC7E,QAAM,EAAE,MAAM,UAAU,aAAa,IAAI,IAAI,IAAI,gBAAgB;AACjE,QAAM,SAAS,YAAY;AAC3B,QAAM,QAAQ,aAAa,IAAI,OAAO;AACtC,QAAM,SAAS,aAAa,IAAI,QAAQ;AAExC,MAAI,CAAC,UAAU,CAAC,SAAS,CAAC,QAAQ;AAChC,UAAM,IAAI,MAAM,2BAA2B;AAAA,EAC7C;AAEA,SAAO,EAAE,QAAQ,OAAO,OAAO;AACjC;AAEA,eAAsB,oBACpB,QACA,WACA,SACwB;AACxB,QAAM,UAAU;AAAA,IACd,QAAQ;AAAA,IACR,QAAQ;AAAA,MACN;AAAA,IACF;AAAA,EACF;AACA,QAAM,mBAAmB,QAAQ,WAAW,QAAQ,KAAK,UAAU,OAAO,CAAC;AAC3E,QAAM,gBAAgB;AAAA,IACpB,MAAM;AAAA,IACN,YAAY,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAAA,IACxC,SAAS;AAAA,IACT,MAAM,CAAC,CAAC,KAAK,MAAM,CAAC;AAAA,EACtB;AAEA,SAAO,cAAc,eAAe,SAAS;AAC/C;", + "names": ["bytesToHex", "i", "bytesToHex", "bytesToHex", "bytesToHex"] +} diff --git a/node_modules/nostr-tools/lib/esm/nip49.js b/node_modules/nostr-tools/lib/esm/nip49.js new file mode 100644 index 0000000..c35d68d --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip49.js @@ -0,0 +1,56 @@ +// nip49.ts +import { scrypt } from "@noble/hashes/scrypt"; +import { xchacha20poly1305 } from "@noble/ciphers/chacha"; +import { concatBytes as concatBytes2, randomBytes } from "@noble/hashes/utils"; + +// nip19.ts +import { bytesToHex, concatBytes, hexToBytes } from "@noble/hashes/utils"; +import { bech32 } from "@scure/base"; +var Bech32MaxSize = 5e3; +function encodeBech32(prefix, data) { + let words = bech32.toWords(data); + return bech32.encode(prefix, words, Bech32MaxSize); +} +function encodeBytes(prefix, bytes) { + return encodeBech32(prefix, bytes); +} + +// nip49.ts +import { bech32 as bech322 } from "@scure/base"; +function encrypt(sec, password, logn = 16, ksb = 2) { + let salt = randomBytes(16); + let n = 2 ** logn; + let key = scrypt(password.normalize("NFKC"), salt, { N: n, r: 8, p: 1, dkLen: 32 }); + let nonce = randomBytes(24); + let aad = Uint8Array.from([ksb]); + let xc2p1 = xchacha20poly1305(key, nonce, aad); + let ciphertext = xc2p1.encrypt(sec); + let b = concatBytes2(Uint8Array.from([2]), Uint8Array.from([logn]), salt, nonce, aad, ciphertext); + return encodeBytes("ncryptsec", b); +} +function decrypt(ncryptsec, password) { + let { prefix, words } = bech322.decode(ncryptsec, Bech32MaxSize); + if (prefix !== "ncryptsec") { + throw new Error(`invalid prefix ${prefix}, expected 'ncryptsec'`); + } + let b = new Uint8Array(bech322.fromWords(words)); + let version = b[0]; + if (version !== 2) { + throw new Error(`invalid version ${version}, expected 0x02`); + } + let logn = b[1]; + let n = 2 ** logn; + let salt = b.slice(2, 2 + 16); + let nonce = b.slice(2 + 16, 2 + 16 + 24); + let ksb = b[2 + 16 + 24]; + let aad = Uint8Array.from([ksb]); + let ciphertext = b.slice(2 + 16 + 24 + 1); + let key = scrypt(password.normalize("NFKC"), salt, { N: n, r: 8, p: 1, dkLen: 32 }); + let xc2p1 = xchacha20poly1305(key, nonce, aad); + let sec = xc2p1.decrypt(ciphertext); + return sec; +} +export { + decrypt, + encrypt +}; diff --git a/node_modules/nostr-tools/lib/esm/nip49.js.map b/node_modules/nostr-tools/lib/esm/nip49.js.map new file mode 100644 index 0000000..3c9170b --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip49.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip49.ts", "../../nip19.ts"], + "sourcesContent": ["import { scrypt } from '@noble/hashes/scrypt'\nimport { xchacha20poly1305 } from '@noble/ciphers/chacha'\nimport { concatBytes, randomBytes } from '@noble/hashes/utils'\nimport { Bech32MaxSize, Ncryptsec, encodeBytes } from './nip19.ts'\nimport { bech32 } from '@scure/base'\n\nexport function encrypt(\n sec: Uint8Array,\n password: string,\n logn: number = 16,\n ksb: 0x00 | 0x01 | 0x02 = 0x02,\n): Ncryptsec {\n let salt = randomBytes(16)\n let n = 2 ** logn\n let key = scrypt(password.normalize('NFKC'), salt, { N: n, r: 8, p: 1, dkLen: 32 })\n let nonce = randomBytes(24)\n let aad = Uint8Array.from([ksb])\n let xc2p1 = xchacha20poly1305(key, nonce, aad)\n let ciphertext = xc2p1.encrypt(sec)\n let b = concatBytes(Uint8Array.from([0x02]), Uint8Array.from([logn]), salt, nonce, aad, ciphertext)\n return encodeBytes('ncryptsec', b)\n}\n\nexport function decrypt(ncryptsec: string, password: string): Uint8Array {\n let { prefix, words } = bech32.decode(ncryptsec, Bech32MaxSize)\n if (prefix !== 'ncryptsec') {\n throw new Error(`invalid prefix ${prefix}, expected 'ncryptsec'`)\n }\n let b = new Uint8Array(bech32.fromWords(words))\n\n let version = b[0]\n if (version !== 0x02) {\n throw new Error(`invalid version ${version}, expected 0x02`)\n }\n\n let logn = b[1]\n let n = 2 ** logn\n\n let salt = b.slice(2, 2 + 16)\n let nonce = b.slice(2 + 16, 2 + 16 + 24)\n let ksb = b[2 + 16 + 24]\n let aad = Uint8Array.from([ksb])\n let ciphertext = b.slice(2 + 16 + 24 + 1)\n\n let key = scrypt(password.normalize('NFKC'), salt, { N: n, r: 8, p: 1, dkLen: 32 })\n let xc2p1 = xchacha20poly1305(key, nonce, aad)\n let sec = xc2p1.decrypt(ciphertext)\n\n return sec\n}\n", "import { bytesToHex, concatBytes, hexToBytes } from '@noble/hashes/utils'\nimport { bech32 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport type NProfile = `nprofile1${string}`\nexport type NEvent = `nevent1${string}`\nexport type NAddr = `naddr1${string}`\nexport type NSec = `nsec1${string}`\nexport type NPub = `npub1${string}`\nexport type Note = `note1${string}`\nexport type Ncryptsec = `ncryptsec1${string}`\n\nexport const NostrTypeGuard = {\n isNProfile: (value?: string | null): value is NProfile => /^nprofile1[a-z\\d]+$/.test(value || ''),\n isNEvent: (value?: string | null): value is NEvent => /^nevent1[a-z\\d]+$/.test(value || ''),\n isNAddr: (value?: string | null): value is NAddr => /^naddr1[a-z\\d]+$/.test(value || ''),\n isNSec: (value?: string | null): value is NSec => /^nsec1[a-z\\d]{58}$/.test(value || ''),\n isNPub: (value?: string | null): value is NPub => /^npub1[a-z\\d]{58}$/.test(value || ''),\n isNote: (value?: string | null): value is Note => /^note1[a-z\\d]+$/.test(value || ''),\n isNcryptsec: (value?: string | null): value is Ncryptsec => /^ncryptsec1[a-z\\d]+$/.test(value || ''),\n}\n\nexport const Bech32MaxSize = 5000\n\n/**\n * Bech32 regex.\n * @see https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32\n */\nexport const BECH32_REGEX = /[\\x21-\\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/\n\nfunction integerToUint8Array(number: number) {\n // Create a Uint8Array with enough space to hold a 32-bit integer (4 bytes).\n const uint8Array = new Uint8Array(4)\n\n // Use bitwise operations to extract the bytes.\n uint8Array[0] = (number >> 24) & 0xff // Most significant byte (MSB)\n uint8Array[1] = (number >> 16) & 0xff\n uint8Array[2] = (number >> 8) & 0xff\n uint8Array[3] = number & 0xff // Least significant byte (LSB)\n\n return uint8Array\n}\n\nexport type ProfilePointer = {\n pubkey: string // hex\n relays?: string[]\n}\n\nexport type EventPointer = {\n id: string // hex\n relays?: string[]\n author?: string\n kind?: number\n}\n\nexport type AddressPointer = {\n identifier: string\n pubkey: string\n kind: number\n relays?: string[]\n}\n\nexport function decodeNostrURI(nip19code: string): ReturnType | { type: 'invalid'; data: null } {\n try {\n if (nip19code.startsWith('nostr:')) nip19code = nip19code.substring(6)\n return decode(nip19code)\n } catch (_err) {\n return { type: 'invalid', data: null }\n }\n}\n\nexport type DecodedNevent = {\n type: 'nevent'\n data: EventPointer\n}\n\nexport type DecodedNprofile = {\n type: 'nprofile'\n data: ProfilePointer\n}\n\nexport type DecodedNaddr = {\n type: 'naddr'\n data: AddressPointer\n}\n\nexport type DecodedNsec = {\n type: 'nsec'\n data: Uint8Array\n}\n\nexport type DecodedNpub = {\n type: 'npub'\n data: string\n}\n\nexport type DecodedNote = {\n type: 'note'\n data: string\n}\n\nexport type DecodedResult = DecodedNevent | DecodedNprofile | DecodedNaddr | DecodedNpub | DecodedNsec | DecodedNote\n\nexport function decode(nip19: NEvent): DecodedNevent\nexport function decode(nip19: NProfile): DecodedNprofile\nexport function decode(nip19: NAddr): DecodedNaddr\nexport function decode(nip19: NSec): DecodedNsec\nexport function decode(nip19: NPub): DecodedNpub\nexport function decode(nip19: Note): DecodedNote\nexport function decode(code: string): DecodedResult\nexport function decode(code: string): DecodedResult {\n let { prefix, words } = bech32.decode(code, Bech32MaxSize)\n let data = new Uint8Array(bech32.fromWords(words))\n\n switch (prefix) {\n case 'nprofile': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nprofile')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n\n return {\n type: 'nprofile',\n data: {\n pubkey: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n case 'nevent': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nevent')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n if (tlv[2] && tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (tlv[3] && tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'nevent',\n data: {\n id: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n author: tlv[2]?.[0] ? bytesToHex(tlv[2][0]) : undefined,\n kind: tlv[3]?.[0] ? parseInt(bytesToHex(tlv[3][0]), 16) : undefined,\n },\n }\n }\n\n case 'naddr': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for naddr')\n if (!tlv[2]?.[0]) throw new Error('missing TLV 2 for naddr')\n if (tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (!tlv[3]?.[0]) throw new Error('missing TLV 3 for naddr')\n if (tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'naddr',\n data: {\n identifier: utf8Decoder.decode(tlv[0][0]),\n pubkey: bytesToHex(tlv[2][0]),\n kind: parseInt(bytesToHex(tlv[3][0]), 16),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n\n case 'nsec':\n return { type: prefix, data }\n\n case 'npub':\n case 'note':\n return { type: prefix, data: bytesToHex(data) }\n\n default:\n throw new Error(`unknown prefix ${prefix}`)\n }\n}\n\ntype TLV = { [t: number]: Uint8Array[] }\n\nfunction parseTLV(data: Uint8Array): TLV {\n let result: TLV = {}\n let rest = data\n while (rest.length > 0) {\n let t = rest[0]\n let l = rest[1]\n let v = rest.slice(2, 2 + l)\n rest = rest.slice(2 + l)\n if (v.length < l) throw new Error(`not enough data to read on TLV ${t}`)\n result[t] = result[t] || []\n result[t].push(v)\n }\n return result\n}\n\nexport function nsecEncode(key: Uint8Array): NSec {\n return encodeBytes('nsec', key)\n}\n\nexport function npubEncode(hex: string): NPub {\n return encodeBytes('npub', hexToBytes(hex))\n}\n\nexport function noteEncode(hex: string): Note {\n return encodeBytes('note', hexToBytes(hex))\n}\n\nfunction encodeBech32(prefix: Prefix, data: Uint8Array): `${Prefix}1${string}` {\n let words = bech32.toWords(data)\n return bech32.encode(prefix, words, Bech32MaxSize) as `${Prefix}1${string}`\n}\n\nexport function encodeBytes(prefix: Prefix, bytes: Uint8Array): `${Prefix}1${string}` {\n return encodeBech32(prefix, bytes)\n}\n\nexport function nprofileEncode(profile: ProfilePointer): NProfile {\n let data = encodeTLV({\n 0: [hexToBytes(profile.pubkey)],\n 1: (profile.relays || []).map(url => utf8Encoder.encode(url)),\n })\n return encodeBech32('nprofile', data)\n}\n\nexport function neventEncode(event: EventPointer): NEvent {\n let kindArray\n if (event.kind !== undefined) {\n kindArray = integerToUint8Array(event.kind)\n }\n\n let data = encodeTLV({\n 0: [hexToBytes(event.id)],\n 1: (event.relays || []).map(url => utf8Encoder.encode(url)),\n 2: event.author ? [hexToBytes(event.author)] : [],\n 3: kindArray ? [new Uint8Array(kindArray)] : [],\n })\n\n return encodeBech32('nevent', data)\n}\n\nexport function naddrEncode(addr: AddressPointer): NAddr {\n let kind = new ArrayBuffer(4)\n new DataView(kind).setUint32(0, addr.kind, false)\n\n let data = encodeTLV({\n 0: [utf8Encoder.encode(addr.identifier)],\n 1: (addr.relays || []).map(url => utf8Encoder.encode(url)),\n 2: [hexToBytes(addr.pubkey)],\n 3: [new Uint8Array(kind)],\n })\n return encodeBech32('naddr', data)\n}\n\nfunction encodeTLV(tlv: TLV): Uint8Array {\n let entries: Uint8Array[] = []\n\n Object.entries(tlv)\n .reverse()\n .forEach(([t, vs]) => {\n vs.forEach(v => {\n let entry = new Uint8Array(v.length + 2)\n entry.set([parseInt(t)], 0)\n entry.set([v.length], 1)\n entry.set(v, 2)\n entries.push(entry)\n })\n })\n\n return concatBytes(...entries)\n}\n"], + "mappings": ";AAAA,SAAS,cAAc;AACvB,SAAS,yBAAyB;AAClC,SAAS,eAAAA,cAAa,mBAAmB;;;ACFzC,SAAS,YAAY,aAAa,kBAAkB;AACpD,SAAS,cAAc;AAsBhB,IAAM,gBAAgB;AAwL7B,SAAS,aAAoC,QAAgB,MAAyC;AACpG,MA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AE,IAAI,KAAK;AACrB,MAAI,MAAM,WAAW,KAAK,CAAC,GAAG,CAAC;AAC/B,MAAI,aAAa,EAAE,MAAM,IAAI,KAAK,KAAK,CAAC;AAExC,MAAI,MAAM,OAAO,SAAS,UAAU,MAAM,GAAG,MAAM,EAAE,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,OAAO,GAAG,CAAC;AAClF,MAAI,QAAQ,kBAAkB,KAAK,OAAO,GAAG;AAC7C,MAAI,MAAM,MAAM,QAAQ,UAAU;AAElC,SAAO;AACT;", + "names": ["concatBytes", "bech32", "concatBytes"] +} diff --git a/node_modules/nostr-tools/lib/esm/nip54.js b/node_modules/nostr-tools/lib/esm/nip54.js new file mode 100644 index 0000000..01fa0ac --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip54.js @@ -0,0 +1,14 @@ +// nip54.ts +function normalizeIdentifier(name) { + name = name.trim().toLowerCase(); + name = name.normalize("NFKC"); + return Array.from(name).map((char) => { + if (/\p{Letter}/u.test(char) || /\p{Number}/u.test(char)) { + return char; + } + return "-"; + }).join(""); +} +export { + normalizeIdentifier +}; diff --git a/node_modules/nostr-tools/lib/esm/nip54.js.map b/node_modules/nostr-tools/lib/esm/nip54.js.map new file mode 100644 index 0000000..b9d0708 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip54.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip54.ts"], + "sourcesContent": ["export function normalizeIdentifier(name: string): string {\n // Trim and lowercase\n name = name.trim().toLowerCase()\n\n // Normalize Unicode to NFKC form\n name = name.normalize('NFKC')\n\n // Convert to array of characters and map each one\n return Array.from(name)\n .map(char => {\n // Check if character is letter or number using Unicode ranges\n if (/\\p{Letter}/u.test(char) || /\\p{Number}/u.test(char)) {\n return char\n }\n\n return '-'\n })\n .join('')\n}\n"], + "mappings": ";AAAO,SAAS,oBAAoB,MAAsB;AAExD,SAAO,KAAK,KAAK,EAAE,YAAY;AAG/B,SAAO,KAAK,UAAU,MAAM;AAG5B,SAAO,MAAM,KAAK,IAAI,EACnB,IAAI,UAAQ;AAEX,QAAI,cAAc,KAAK,IAAI,KAAK,cAAc,KAAK,IAAI,GAAG;AACxD,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT,CAAC,EACA,KAAK,EAAE;AACZ;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/esm/nip55.js b/node_modules/nostr-tools/lib/esm/nip55.js new file mode 100644 index 0000000..3bde1f4 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip55.js @@ -0,0 +1,82 @@ +// nip55.ts +function encodeParams(params) { + return new URLSearchParams(params).toString(); +} +function filterUndefined(obj) { + return Object.fromEntries(Object.entries(obj).filter(([, value]) => value !== void 0)); +} +function buildUri({ + base, + type, + callbackUrl, + returnType = "signature", + compressionType = "none", + ...params +}) { + const baseParams = { + type, + compressionType, + returnType, + callbackUrl, + id: params.id, + current_user: params.currentUser, + permissions: params.permissions && params.permissions.length > 0 ? encodeURIComponent(JSON.stringify(params.permissions)) : void 0, + pubKey: params.pubKey, + plainText: params.plainText, + encryptedText: params.encryptedText, + appName: params.appName + }; + const filteredParams = filterUndefined(baseParams); + return `${base}?${encodeParams(filteredParams)}`; +} +function buildDefaultUri(type, params) { + return buildUri({ + base: "nostrsigner:", + type, + ...params + }); +} +function getPublicKeyUri({ permissions = [], ...params }) { + return buildDefaultUri("get_public_key", { permissions, ...params }); +} +function signEventUri({ eventJson, ...params }) { + return buildUri({ + base: `nostrsigner:${encodeURIComponent(JSON.stringify(eventJson))}`, + type: "sign_event", + ...params + }); +} +function encryptUri(type, params) { + return buildDefaultUri(type, { ...params, plainText: params.content }); +} +function decryptUri(type, params) { + return buildDefaultUri(type, { ...params, encryptedText: params.content }); +} +function encryptNip04Uri(params) { + return encryptUri("nip04_encrypt", params); +} +function decryptNip04Uri(params) { + return decryptUri("nip04_decrypt", params); +} +function encryptNip44Uri(params) { + return encryptUri("nip44_encrypt", params); +} +function decryptNip44Uri(params) { + return decryptUri("nip44_decrypt", params); +} +function decryptZapEventUri({ eventJson, ...params }) { + return buildUri({ + base: `nostrsigner:${encodeURIComponent(JSON.stringify(eventJson))}`, + type: "decrypt_zap_event", + ...params + }); +} +export { + decryptNip04Uri, + decryptNip44Uri, + decryptZapEventUri, + encryptNip04Uri, + encryptNip44Uri, + getPublicKeyUri, + signEventUri +}; diff --git a/node_modules/nostr-tools/lib/esm/nip55.js.map b/node_modules/nostr-tools/lib/esm/nip55.js.map new file mode 100644 index 0000000..703adfa --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip55.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip55.ts"], + "sourcesContent": ["type BaseParams = {\n callbackUrl?: string\n returnType?: 'signature' | 'event'\n compressionType?: 'none' | 'gzip'\n}\n\ntype PermissionsParams = BaseParams & {\n permissions?: { type: string; kind?: number }[]\n}\n\ntype EventUriParams = BaseParams & {\n eventJson: Record\n id?: string\n currentUser?: string\n}\n\ntype EncryptDecryptParams = BaseParams & {\n pubKey: string\n content: string\n id?: string\n currentUser?: string\n}\n\ntype UriParams = BaseParams & {\n base: string\n type: string\n id?: string\n currentUser?: string\n permissions?: { type: string; kind?: number }[]\n pubKey?: string\n plainText?: string\n encryptedText?: string\n appName?: string\n}\n\nfunction encodeParams(params: Record): string {\n return new URLSearchParams(params as Record).toString()\n}\n\nfunction filterUndefined>(obj: T): T {\n return Object.fromEntries(Object.entries(obj).filter(([, value]) => value !== undefined)) as T\n}\n\nfunction buildUri({\n base,\n type,\n callbackUrl,\n returnType = 'signature',\n compressionType = 'none',\n ...params\n}: UriParams): string {\n const baseParams = {\n type,\n compressionType,\n returnType,\n callbackUrl,\n id: params.id,\n current_user: params.currentUser,\n permissions:\n params.permissions && params.permissions.length > 0\n ? encodeURIComponent(JSON.stringify(params.permissions))\n : undefined,\n pubKey: params.pubKey,\n plainText: params.plainText,\n encryptedText: params.encryptedText,\n appName: params.appName,\n }\n\n const filteredParams = filterUndefined(baseParams)\n return `${base}?${encodeParams(filteredParams)}`\n}\n\nfunction buildDefaultUri(type: string, params: Partial): string {\n return buildUri({\n base: 'nostrsigner:',\n type,\n ...params,\n })\n}\n\nexport function getPublicKeyUri({ permissions = [], ...params }: PermissionsParams): string {\n return buildDefaultUri('get_public_key', { permissions, ...params })\n}\n\nexport function signEventUri({ eventJson, ...params }: EventUriParams): string {\n return buildUri({\n base: `nostrsigner:${encodeURIComponent(JSON.stringify(eventJson))}`,\n type: 'sign_event',\n ...params,\n })\n}\n\nfunction encryptUri(type: 'nip44_encrypt' | 'nip04_encrypt', params: EncryptDecryptParams): string {\n return buildDefaultUri(type, { ...params, plainText: params.content })\n}\n\nfunction decryptUri(type: 'nip44_decrypt' | 'nip04_decrypt', params: EncryptDecryptParams): string {\n return buildDefaultUri(type, { ...params, encryptedText: params.content })\n}\n\nexport function encryptNip04Uri(params: EncryptDecryptParams): string {\n return encryptUri('nip04_encrypt', params)\n}\n\nexport function decryptNip04Uri(params: EncryptDecryptParams): string {\n return decryptUri('nip04_decrypt', params)\n}\n\nexport function encryptNip44Uri(params: EncryptDecryptParams): string {\n return encryptUri('nip44_encrypt', params)\n}\n\nexport function decryptNip44Uri(params: EncryptDecryptParams): string {\n return decryptUri('nip44_decrypt', params)\n}\n\nexport function decryptZapEventUri({ eventJson, ...params }: EventUriParams): string {\n return buildUri({\n base: `nostrsigner:${encodeURIComponent(JSON.stringify(eventJson))}`,\n type: 'decrypt_zap_event',\n ...params,\n })\n}\n"], + "mappings": ";AAmCA,SAAS,aAAa,QAAyC;AAC7D,SAAO,IAAI,gBAAgB,MAAgC,EAAE,SAAS;AACxE;AAEA,SAAS,gBAAmD,KAAW;AACrE,SAAO,OAAO,YAAY,OAAO,QAAQ,GAAG,EAAE,OAAO,CAAC,CAAC,EAAE,KAAK,MAAM,UAAU,MAAS,CAAC;AAC1F;AAEA,SAAS,SAAS;AAAA,EAChB;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAa;AAAA,EAC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SAAO,WAAW,iBAAiB,MAAM;AAC3C;AAEO,SAAS,gBAAgB,QAAsC;AACpE,SAAO,WAAW,iBAAiB,MAAM;AAC3C;AAEO,SAAS,mBAAmB,EAAE,cAAc,OAAO,GAA2B;AACnF,SAAO,SAAS;AAAA,IACd,MAAM,eAAe,mBAAmB,KAAK,UAAU,SAAS,CAAC;AAAA,IACjE,MAAM;AAAA,IACN,GAAG;AAAA,EACL,CAAC;AACH;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/esm/nip57.js b/node_modules/nostr-tools/lib/esm/nip57.js new file mode 100644 index 0000000..1d46859 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip57.js @@ -0,0 +1,253 @@ +// nip57.ts +import { bech32 } from "@scure/base"; + +// pure.ts +import { schnorr } from "@noble/curves/secp256k1"; +import { bytesToHex as bytesToHex2 } from "@noble/hashes/utils"; + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +import { sha256 } from "@noble/hashes/sha256"; + +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// pure.ts +var JS = class { + generateSecretKey() { + return schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return bytesToHex2(schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = bytesToHex2(schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = bytesToHex2(schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = sha256(utf8Encoder.encode(serializeEvent(event))); + return bytesToHex2(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// kinds.ts +function isReplaceableKind(kind) { + return [0, 3].includes(kind) || 1e4 <= kind && kind < 2e4; +} +function isAddressableKind(kind) { + return 3e4 <= kind && kind < 4e4; +} + +// nip57.ts +var _fetch; +try { + _fetch = fetch; +} catch { +} +function useFetchImplementation(fetchImplementation) { + _fetch = fetchImplementation; +} +async function getZapEndpoint(metadata) { + try { + let lnurl = ""; + let { lud06, lud16 } = JSON.parse(metadata.content); + if (lud06) { + let { words } = bech32.decode(lud06, 1e3); + let data = bech32.fromWords(words); + lnurl = utf8Decoder.decode(data); + } else if (lud16) { + let [name, domain] = lud16.split("@"); + lnurl = new URL(`/.well-known/lnurlp/${name}`, `https://${domain}`).toString(); + } else { + return null; + } + let res = await _fetch(lnurl); + let body = await res.json(); + if (body.allowsNostr && body.nostrPubkey) { + return body.callback; + } + } catch (err) { + } + return null; +} +function makeZapRequest(params) { + let zr = { + kind: 9734, + created_at: Math.round(Date.now() / 1e3), + content: params.comment || "", + tags: [ + ["p", "pubkey" in params ? params.pubkey : params.event.pubkey], + ["amount", params.amount.toString()], + ["relays", ...params.relays] + ] + }; + if ("event" in params) { + zr.tags.push(["e", params.event.id]); + if (isReplaceableKind(params.event.kind)) { + const a = ["a", `${params.event.kind}:${params.event.pubkey}:`]; + zr.tags.push(a); + } else if (isAddressableKind(params.event.kind)) { + let d = params.event.tags.find(([t, v]) => t === "d" && v); + if (!d) + throw new Error("d tag not found or is empty"); + const a = ["a", `${params.event.kind}:${params.event.pubkey}:${d[1]}`]; + zr.tags.push(a); + } + zr.tags.push(["k", params.event.kind.toString()]); + } + return zr; +} +function validateZapRequest(zapRequestString) { + let zapRequest; + try { + zapRequest = JSON.parse(zapRequestString); + } catch (err) { + return "Invalid zap request JSON."; + } + if (!validateEvent(zapRequest)) + return "Zap request is not a valid Nostr event."; + if (!verifyEvent(zapRequest)) + return "Invalid signature on zap request."; + let p = zapRequest.tags.find(([t, v]) => t === "p" && v); + if (!p) + return "Zap request doesn't have a 'p' tag."; + if (!p[1].match(/^[a-f0-9]{64}$/)) + return "Zap request 'p' tag is not valid hex."; + let e = zapRequest.tags.find(([t, v]) => t === "e" && v); + if (e && !e[1].match(/^[a-f0-9]{64}$/)) + return "Zap request 'e' tag is not valid hex."; + let relays = zapRequest.tags.find(([t, v]) => t === "relays" && v); + if (!relays) + return "Zap request doesn't have a 'relays' tag."; + return null; +} +function makeZapReceipt({ + zapRequest, + preimage, + bolt11, + paidAt +}) { + let zr = JSON.parse(zapRequest); + let tagsFromZapRequest = zr.tags.filter(([t]) => t === "e" || t === "p" || t === "a"); + let zap = { + kind: 9735, + created_at: Math.round(paidAt.getTime() / 1e3), + content: "", + tags: [...tagsFromZapRequest, ["P", zr.pubkey], ["bolt11", bolt11], ["description", zapRequest]] + }; + if (preimage) { + zap.tags.push(["preimage", preimage]); + } + return zap; +} +function getSatoshisAmountFromBolt11(bolt11) { + if (bolt11.length < 50) { + return 0; + } + bolt11 = bolt11.substring(0, 50); + const idx = bolt11.lastIndexOf("1"); + if (idx === -1) { + return 0; + } + const hrp = bolt11.substring(0, idx); + if (!hrp.startsWith("lnbc")) { + return 0; + } + const amount = hrp.substring(4); + if (amount.length < 1) { + return 0; + } + const char = amount[amount.length - 1]; + const digit = char.charCodeAt(0) - "0".charCodeAt(0); + const isDigit = digit >= 0 && digit <= 9; + let cutPoint = amount.length - 1; + if (isDigit) { + cutPoint++; + } + if (cutPoint < 1) { + return 0; + } + const num = parseInt(amount.substring(0, cutPoint)); + switch (char) { + case "m": + return num * 1e5; + case "u": + return num * 100; + case "n": + return num / 10; + case "p": + return num / 1e4; + default: + return num * 1e8; + } +} +export { + getSatoshisAmountFromBolt11, + getZapEndpoint, + makeZapReceipt, + makeZapRequest, + useFetchImplementation, + validateZapRequest +}; diff --git a/node_modules/nostr-tools/lib/esm/nip57.js.map b/node_modules/nostr-tools/lib/esm/nip57.js.map new file mode 100644 index 0000000..74dc862 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip57.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip57.ts", "../../pure.ts", "../../core.ts", "../../utils.ts", "../../kinds.ts"], + "sourcesContent": ["import { bech32 } from '@scure/base'\n\nimport { NostrEvent, validateEvent, verifyEvent, type Event, type EventTemplate } from './pure.ts'\nimport { utf8Decoder } from './utils.ts'\nimport { isReplaceableKind, isAddressableKind } from './kinds.ts'\n\nvar _fetch: any\n\ntry {\n _fetch = fetch\n} catch {}\n\nexport function useFetchImplementation(fetchImplementation: any) {\n _fetch = fetchImplementation\n}\n\nexport async function getZapEndpoint(metadata: Event): Promise {\n try {\n let lnurl: string = ''\n let { lud06, lud16 } = JSON.parse(metadata.content)\n if (lud06) {\n let { words } = bech32.decode(lud06, 1000)\n let data = bech32.fromWords(words)\n lnurl = utf8Decoder.decode(data)\n } else if (lud16) {\n let [name, domain] = lud16.split('@')\n lnurl = new URL(`/.well-known/lnurlp/${name}`, `https://${domain}`).toString()\n } else {\n return null\n }\n\n let res = await _fetch(lnurl)\n let body = await res.json()\n\n if (body.allowsNostr && body.nostrPubkey) {\n return body.callback\n }\n } catch (err) {\n /*-*/\n }\n\n return null\n}\n\ntype ProfileZap = {\n pubkey: string\n amount: number\n comment?: string\n relays: string[]\n}\n\ntype EventZap = {\n event: NostrEvent\n amount: number\n comment?: string\n relays: string[]\n}\n\nexport function makeZapRequest(params: ProfileZap | EventZap): EventTemplate {\n let zr: EventTemplate = {\n kind: 9734,\n created_at: Math.round(Date.now() / 1000),\n content: params.comment || '',\n tags: [\n ['p', 'pubkey' in params ? params.pubkey : params.event.pubkey],\n ['amount', params.amount.toString()],\n ['relays', ...params.relays],\n ],\n }\n\n if ('event' in params) {\n zr.tags.push(['e', params.event.id])\n if (isReplaceableKind(params.event.kind)) {\n const a = ['a', `${params.event.kind}:${params.event.pubkey}:`]\n zr.tags.push(a)\n } else if (isAddressableKind(params.event.kind)) {\n let d = params.event.tags.find(([t, v]) => t === 'd' && v)\n if (!d) throw new Error('d tag not found or is empty')\n const a = ['a', `${params.event.kind}:${params.event.pubkey}:${d[1]}`]\n zr.tags.push(a)\n }\n zr.tags.push(['k', params.event.kind.toString()])\n }\n\n return zr\n}\n\nexport function validateZapRequest(zapRequestString: string): string | null {\n let zapRequest: Event\n\n try {\n zapRequest = JSON.parse(zapRequestString)\n } catch (err) {\n return 'Invalid zap request JSON.'\n }\n\n if (!validateEvent(zapRequest)) return 'Zap request is not a valid Nostr event.'\n\n if (!verifyEvent(zapRequest)) return 'Invalid signature on zap request.'\n\n let p = zapRequest.tags.find(([t, v]) => t === 'p' && v)\n if (!p) return \"Zap request doesn't have a 'p' tag.\"\n if (!p[1].match(/^[a-f0-9]{64}$/)) return \"Zap request 'p' tag is not valid hex.\"\n\n let e = zapRequest.tags.find(([t, v]) => t === 'e' && v)\n if (e && !e[1].match(/^[a-f0-9]{64}$/)) return \"Zap request 'e' tag is not valid hex.\"\n\n let relays = zapRequest.tags.find(([t, v]) => t === 'relays' && v)\n if (!relays) return \"Zap request doesn't have a 'relays' tag.\"\n\n return null\n}\n\nexport function makeZapReceipt({\n zapRequest,\n preimage,\n bolt11,\n paidAt,\n}: {\n zapRequest: string\n preimage?: string\n bolt11: string\n paidAt: Date\n}): EventTemplate {\n let zr: Event = JSON.parse(zapRequest)\n let tagsFromZapRequest = zr.tags.filter(([t]) => t === 'e' || t === 'p' || t === 'a')\n\n let zap: EventTemplate = {\n kind: 9735,\n created_at: Math.round(paidAt.getTime() / 1000),\n content: '',\n tags: [...tagsFromZapRequest, ['P', zr.pubkey], ['bolt11', bolt11], ['description', zapRequest]],\n }\n\n if (preimage) {\n zap.tags.push(['preimage', preimage])\n }\n\n return zap\n}\n\nexport function getSatoshisAmountFromBolt11(bolt11: string): number {\n if (bolt11.length < 50) {\n return 0\n }\n bolt11 = bolt11.substring(0, 50)\n const idx = bolt11.lastIndexOf('1')\n if (idx === -1) {\n return 0\n }\n const hrp = bolt11.substring(0, idx)\n if (!hrp.startsWith('lnbc')) {\n return 0\n }\n const amount = hrp.substring(4) // equivalent to strings.CutPrefix\n\n if (amount.length < 1) {\n return 0\n }\n\n // if last character is a digit, then the amount can just be interpreted as BTC\n const char = amount[amount.length - 1]\n const digit = char.charCodeAt(0) - '0'.charCodeAt(0)\n const isDigit = digit >= 0 && digit <= 9\n\n let cutPoint = amount.length - 1\n if (isDigit) {\n cutPoint++\n }\n\n if (cutPoint < 1) {\n return 0\n }\n\n const num = parseInt(amount.substring(0, cutPoint))\n\n switch (char) {\n case 'm':\n return num * 100000\n case 'u':\n return num * 100\n case 'n':\n return num / 10\n case 'p':\n return num / 10000\n default:\n return num * 100000000\n }\n}\n", "import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n"], + "mappings": ";AAAA,SAAS,cAAc;;;ACAvB,SAAS,eAAe;AACxB,SAAS,cAAAA,mBAAkB;;;ACOpB,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,CAAC,QAAiD,eAAe;AAE3E,SAAS,cAAiB,OAAsC;AACrE,MAAI,CAAC,SAAS,KAAK;AAAG,WAAO;AAC7B,MAAI,OAAO,MAAM,SAAS;AAAU,WAAO;AAC3C,MAAI,OAAO,MAAM,YAAY;AAAU,WAAO;AAC9C,MAAI,OAAO,MAAM,eAAe;AAAU,WAAO;AACjD,MAAI,OAAO,MAAM,WAAW;AAAU,WAAO;AAC7C,MAAI,CAAC,MAAM,OAAO,MAAM,gBAAgB;AAAG,WAAO;AAElD,MAAI,CAAC,MAAM,QAAQ,MAAM,IAAI;AAAG,WAAO;AACvC,WAASC,KAAI,GAAGA,KAAI,MAAM,KAAK,QAAQA,MAAK;AAC1C,QAAI,MAAM,MAAM,KAAKA;AACrB,QAAI,CAAC,MAAM,QAAQ,GAAG;AAAG,aAAO;AAChC,aAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,UAAI,OAAO,IAAI,OAAO;AAAU,eAAO;AAAA,IACzC;AAAA,EACF;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O,OAAO,SAAS;AACpC,QAAM,QAAQ,KAAK,WAAW,CAAC,IAAI,IAAI,WAAW,CAAC;AACnD,QAAM,UAAU,SAAS,KAAK,SAAS;AAEvC,MAAI,WAAW,OAAO,SAAS;AAC/B,MAAI,SAAS;AACX;AAAA,EACF;AAEA,MAAI,WAAW,GAAG;AAChB,WAAO;AAAA,EACT;AAEA,QAAM,MAAM,SAAS,OAAO,UAAU,GAAG,QAAQ,CAAC;AAElD,UAAQ,MAAM;AAAA,IACZ,KAAK;AACH,aAAO,MAAM;AAAA,IACf,KAAK;AACH,aAAO,MAAM;AAAA,IACf,KAAK;AACH,aAAO,MAAM;AAAA,IACf,KAAK;AACH,aAAO,MAAM;AAAA,IACf;AACE,aAAO,MAAM;AAAA,EACjB;AACF;", + "names": ["bytesToHex", "i", "bytesToHex"] +} diff --git a/node_modules/nostr-tools/lib/esm/nip58.js b/node_modules/nostr-tools/lib/esm/nip58.js new file mode 100644 index 0000000..79b35d1 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip58.js @@ -0,0 +1,94 @@ +// kinds.ts +var BadgeAward = 8; +var ProfileBadges = 30008; +var BadgeDefinition = 30009; + +// nip58.ts +function generateBadgeDefinitionEventTemplate({ + d, + description, + image, + name, + thumbs +}) { + const tags = [["d", d]]; + name && tags.push(["name", name]); + description && tags.push(["description", description]); + image && tags.push(["image", ...image]); + if (thumbs) { + for (const thumb of thumbs) { + tags.push(["thumb", ...thumb]); + } + } + const eventTemplate = { + content: "", + created_at: Math.floor(Date.now() / 1e3), + kind: BadgeDefinition, + tags + }; + return eventTemplate; +} +function validateBadgeDefinitionEvent(event) { + if (event.kind !== BadgeDefinition) + return false; + const requiredTags = ["d"]; + for (const tag of requiredTags) { + if (!event.tags.find(([t]) => t == tag)) + return false; + } + return true; +} +function generateBadgeAwardEventTemplate({ a, p }) { + const tags = [["a", a]]; + for (const _p of p) { + tags.push(["p", ..._p]); + } + const eventTemplate = { + content: "", + created_at: Math.floor(Date.now() / 1e3), + kind: BadgeAward, + tags + }; + return eventTemplate; +} +function validateBadgeAwardEvent(event) { + if (event.kind !== BadgeAward) + return false; + const requiredTags = ["a", "p"]; + for (const tag of requiredTags) { + if (!event.tags.find(([t]) => t == tag)) + return false; + } + return true; +} +function generateProfileBadgesEventTemplate({ badges }) { + const tags = [["d", "profile_badges"]]; + for (const badge of badges) { + tags.push(["a", badge.a], ["e", ...badge.e]); + } + const eventTemplate = { + content: "", + created_at: Math.floor(Date.now() / 1e3), + kind: ProfileBadges, + tags + }; + return eventTemplate; +} +function validateProfileBadgesEvent(event) { + if (event.kind !== ProfileBadges) + return false; + const requiredTags = ["d"]; + for (const tag of requiredTags) { + if (!event.tags.find(([t]) => t == tag)) + return false; + } + return true; +} +export { + generateBadgeAwardEventTemplate, + generateBadgeDefinitionEventTemplate, + generateProfileBadgesEventTemplate, + validateBadgeAwardEvent, + validateBadgeDefinitionEvent, + validateProfileBadgesEvent +}; diff --git a/node_modules/nostr-tools/lib/esm/nip58.js.map b/node_modules/nostr-tools/lib/esm/nip58.js.map new file mode 100644 index 0000000..7ea031c --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip58.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../kinds.ts", "../../nip58.ts"], + "sourcesContent": ["import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { Event, EventTemplate } from './core.ts'\nimport {\n BadgeAward as BadgeAwardKind,\n BadgeDefinition as BadgeDefinitionKind,\n ProfileBadges as ProfileBadgesKind,\n} from './kinds.ts'\n\n/**\n * Represents the structure for defining a badge within the Nostr network.\n * This structure is used to create templates for badge definition events,\n * facilitating the recognition and awarding of badges to users for various achievements.\n */\nexport type BadgeDefinition = {\n /**\n * A unique identifier for the badge. This is used to distinguish badges\n * from one another and should be unique across all badge definitions.\n * Typically, this could be a short, descriptive string.\n */\n d: string\n\n /**\n * An optional short name for the badge. This provides a human-readable\n * title for the badge, making it easier to recognize and refer to.\n */\n name?: string\n\n /**\n * An optional description for the badge. This field can be used to\n * provide more detailed information about the badge, such as the criteria\n * for its awarding or its significance.\n */\n description?: string\n\n /**\n * An optional image URL and dimensions for the badge. The first element\n * of the tuple is the URL pointing to a high-resolution image representing\n * the badge, and the second element specifies the image's dimensions in\n * the format \"widthxheight\". The recommended dimensions are 1024x1024 pixels.\n */\n image?: [string, string]\n\n /**\n * An optional list of thumbnail images for the badge. Each element in the\n * array is a tuple, where the first element is the URL pointing to a thumbnail\n * version of the badge image, and the second element specifies the thumbnail's\n * dimensions in the format \"widthxheight\". Multiple thumbnails can be provided\n * to support different display sizes.\n */\n thumbs?: Array<[string, string]>\n}\n\n/**\n * Represents the structure for awarding a badge to one or more recipients\n * within the Nostr network. This structure is used to create templates for\n * badge award events, which are immutable and signify the recognition of\n * individuals' achievements or contributions.\n */\nexport type BadgeAward = {\n /**\n * A reference to the Badge Definition event. This is typically composed\n * of the event ID of the badge definition. It establishes a clear linkage\n * between the badge being awarded and its original definition, ensuring\n * that recipients are awarded the correct badge.\n */\n a: string\n\n /**\n * An array of p tags, each containing a pubkey and its associated relays.\n */\n p: string[][]\n}\n\n/**\n * Represents the collection of badges a user chooses to display on their profile.\n * This structure is crucial for applications that allow users to showcase achievements\n * or recognitions in the form of badges, following the specifications of NIP-58.\n */\nexport type ProfileBadges = {\n /**\n * A unique identifier for the profile badges collection. According to NIP-58,\n * this should be set to \"profile_badges\" to differentiate it from other event types.\n */\n d: 'profile_badges'\n\n /**\n * A list of badges that the user has elected to display on their profile. Each item\n * in the array represents a specific badge, including references to both its definition\n * and the award event.\n */\n badges: Array<{\n /**\n * The event address of the badge definition. This is a reference to the specific badge\n * being displayed, linking back to the badge's original definition event. It allows\n * clients to fetch and display the badge's details, such as its name, description,\n * and image.\n */\n a: string\n\n /**\n * The event id of the badge award with corresponding relays. This references the event\n * in which the badge was awarded to the user. It is crucial for verifying the\n * authenticity of the badge display, ensuring that the user was indeed awarded the\n * badge they are choosing to display.\n */\n e: string[]\n }>\n}\n\n/**\n * Generates an EventTemplate based on the provided BadgeDefinition.\n *\n * @param {BadgeDefinition} badgeDefinition - The BadgeDefinition object.\n * @returns {EventTemplate} - The generated EventTemplate object.\n */\nexport function generateBadgeDefinitionEventTemplate({\n d,\n description,\n image,\n name,\n thumbs,\n}: BadgeDefinition): EventTemplate {\n // Mandatory tags\n const tags: string[][] = [['d', d]]\n\n // Append optional tags\n name && tags.push(['name', name])\n description && tags.push(['description', description])\n image && tags.push(['image', ...image])\n if (thumbs) {\n for (const thumb of thumbs) {\n tags.push(['thumb', ...thumb])\n }\n }\n\n // Construct the EventTemplate object\n const eventTemplate: EventTemplate = {\n content: '',\n created_at: Math.floor(Date.now() / 1000),\n kind: BadgeDefinitionKind,\n tags,\n }\n\n return eventTemplate\n}\n\n/**\n * Validates a badge definition event.\n *\n * @param event - The event to validate.\n * @returns A boolean indicating whether the event is a valid badge definition event.\n */\nexport function validateBadgeDefinitionEvent(event: Event): boolean {\n if (event.kind !== BadgeDefinitionKind) return false\n\n const requiredTags = ['d'] as const\n for (const tag of requiredTags) {\n if (!event.tags.find(([t]) => t == tag)) return false\n }\n\n return true\n}\n\n/**\n * Generates an EventTemplate based on the provided BadgeAward.\n *\n * @param {BadgeAward} badgeAward - The BadgeAward object.\n * @returns {EventTemplate} - The generated EventTemplate object.\n */\nexport function generateBadgeAwardEventTemplate({ a, p }: BadgeAward): EventTemplate {\n // Mandatory tags\n const tags: string[][] = [['a', a]]\n for (const _p of p) {\n tags.push(['p', ..._p])\n }\n\n // Construct the EventTemplate object\n const eventTemplate: EventTemplate = {\n content: '',\n created_at: Math.floor(Date.now() / 1000),\n kind: BadgeAwardKind,\n tags,\n }\n\n return eventTemplate\n}\n\n/**\n * Validates a badge award event.\n *\n * @param event - The event to validate.\n * @returns A boolean indicating whether the event is a valid badge award event.\n */\nexport function validateBadgeAwardEvent(event: Event): boolean {\n if (event.kind !== BadgeAwardKind) return false\n\n const requiredTags = ['a', 'p'] as const\n for (const tag of requiredTags) {\n if (!event.tags.find(([t]) => t == tag)) return false\n }\n\n return true\n}\n\n/**\n * Generates an EventTemplate based on the provided ProfileBadges.\n *\n * @param {ProfileBadges} profileBadges - The ProfileBadges object.\n * @returns {EventTemplate} - The generated EventTemplate object.\n */\nexport function generateProfileBadgesEventTemplate({ badges }: ProfileBadges): EventTemplate {\n // Mandatory tags\n const tags: string[][] = [['d', 'profile_badges']]\n\n // Append optional tags\n for (const badge of badges) {\n tags.push(['a', badge.a], ['e', ...badge.e])\n }\n\n // Construct the EventTemplate object\n const eventTemplate: EventTemplate = {\n content: '',\n created_at: Math.floor(Date.now() / 1000),\n kind: ProfileBadgesKind,\n tags,\n }\n\n return eventTemplate\n}\n\n/**\n * Validates a profile badges event.\n *\n * @param event - The event to validate.\n * @returns A boolean indicating whether the event is a valid profile badges event.\n */\nexport function validateProfileBadgesEvent(event: Event): boolean {\n if (event.kind !== ProfileBadgesKind) return false\n\n const requiredTags = ['d'] as const\n for (const tag of requiredTags) {\n if (!event.tags.find(([t]) => t == tag)) return false\n }\n\n return true\n}\n"], + "mappings": ";AAuDO,IAAM,aAAa;AAkGnB,IAAM,gBAAgB;AAEtB,IAAM,kBAAkB;;;ACzCxB,SAAS,qCAAqC;AAAA,EACnD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAmC;AAEjC,QAAM,OAAmB,CAAC,CAAC,KAAK,CAAC,CAAC;AAGlC,UAAQ,KAAK,KAAK,CAAC,QAAQ,IAAI,CAAC;AAChC,iBAAe,KAAK,KAAK,CAAC,eAAe,WAAW,CAAC;AACrD,WAAS,KAAK,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC;AACtC,MAAI,QAAQ;AACV,eAAW,SAAS,QAAQ;AAC1B,WAAK,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC;AAAA,IAC/B;AAAA,EACF;AAGA,QAAM,gBAA+B;AAAA,IACnC,SAAS;AAAA,IACT,YAAY,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAAA,IACxC,MAAM;AAAA,IACN;AAAA,EACF;AAEA,SAAO;AACT;AAQO,SAAS,6BAA6B,OAAuB;AAClE,MAAI,MAAM,SAAS;AAAqB,WAAO;AAE/C,QAAM,eAAe,CAAC,GAAG;AACzB,aAAW,OAAO,cAAc;AAC9B,QAAI,CAAC,MAAM,KAAK,KAAK,CAAC,CAAC,CAAC,MAAM,KAAK,GAAG;AAAG,aAAO;AAAA,EAClD;AAEA,SAAO;AACT;AAQO,SAAS,gCAAgC,EAAE,GAAG,EAAE,GAA8B;AAEnF,QAAM,OAAmB,CAAC,CAAC,KAAK,CAAC,CAAC;AAClC,aAAW,MAAM,GAAG;AAClB,SAAK,KAAK,CAAC,KAAK,GAAG,EAAE,CAAC;AAAA,EACxB;AAGA,QAAM,gBAA+B;AAAA,IACnC,SAAS;AAAA,IACT,YAAY,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAAA,IACxC,MAAM;AAAA,IACN;AAAA,EACF;AAEA,SAAO;AACT;AAQO,SAAS,wBAAwB,OAAuB;AAC7D,MAAI,MAAM,SAAS;AAAgB,WAAO;AAE1C,QAAM,eAAe,CAAC,KAAK,GAAG;AAC9B,aAAW,OAAO,cAAc;AAC9B,QAAI,CAAC,MAAM,KAAK,KAAK,CAAC,CAAC,CAAC,MAAM,KAAK,GAAG;AAAG,aAAO;AAAA,EAClD;AAEA,SAAO;AACT;AAQO,SAAS,mCAAmC,EAAE,OAAO,GAAiC;AAE3F,QAAM,OAAmB,CAAC,CAAC,KAAK,gBAAgB,CAAC;AAGjD,aAAW,SAAS,QAAQ;AAC1B,SAAK,KAAK,CAAC,KAAK,MAAM,CAAC,GAAG,CAAC,KAAK,GAAG,MAAM,CAAC,CAAC;AAAA,EAC7C;AAGA,QAAM,gBAA+B;AAAA,IACnC,SAAS;AAAA,IACT,YAAY,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAAA,IACxC,MAAM;AAAA,IACN;AAAA,EACF;AAEA,SAAO;AACT;AAQO,SAAS,2BAA2B,OAAuB;AAChE,MAAI,MAAM,SAAS;AAAmB,WAAO;AAE7C,QAAM,eAAe,CAAC,GAAG;AACzB,aAAW,OAAO,cAAc;AAC9B,QAAI,CAAC,MAAM,KAAK,KAAK,CAAC,CAAC,CAAC,MAAM,KAAK,GAAG;AAAG,aAAO;AAAA,EAClD;AAEA,SAAO;AACT;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/esm/nip59.js b/node_modules/nostr-tools/lib/esm/nip59.js new file mode 100644 index 0000000..b48e9dc --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip59.js @@ -0,0 +1,275 @@ +// nip44.ts +import { chacha20 } from "@noble/ciphers/chacha"; +import { equalBytes } from "@noble/ciphers/utils"; +import { secp256k1 } from "@noble/curves/secp256k1"; +import { extract as hkdf_extract, expand as hkdf_expand } from "@noble/hashes/hkdf"; +import { hmac } from "@noble/hashes/hmac"; +import { sha256 } from "@noble/hashes/sha256"; +import { concatBytes, randomBytes } from "@noble/hashes/utils"; +import { base64 } from "@scure/base"; + +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// nip44.ts +var minPlaintextSize = 1; +var maxPlaintextSize = 65535; +function getConversationKey(privkeyA, pubkeyB) { + const sharedX = secp256k1.getSharedSecret(privkeyA, "02" + pubkeyB).subarray(1, 33); + return hkdf_extract(sha256, sharedX, "nip44-v2"); +} +function getMessageKeys(conversationKey, nonce) { + const keys = hkdf_expand(sha256, conversationKey, nonce, 76); + return { + chacha_key: keys.subarray(0, 32), + chacha_nonce: keys.subarray(32, 44), + hmac_key: keys.subarray(44, 76) + }; +} +function calcPaddedLen(len) { + if (!Number.isSafeInteger(len) || len < 1) + throw new Error("expected positive integer"); + if (len <= 32) + return 32; + const nextPower = 1 << Math.floor(Math.log2(len - 1)) + 1; + const chunk = nextPower <= 256 ? 32 : nextPower / 8; + return chunk * (Math.floor((len - 1) / chunk) + 1); +} +function writeU16BE(num) { + if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize) + throw new Error("invalid plaintext size: must be between 1 and 65535 bytes"); + const arr = new Uint8Array(2); + new DataView(arr.buffer).setUint16(0, num, false); + return arr; +} +function pad(plaintext) { + const unpadded = utf8Encoder.encode(plaintext); + const unpaddedLen = unpadded.length; + const prefix = writeU16BE(unpaddedLen); + const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen); + return concatBytes(prefix, unpadded, suffix); +} +function unpad(padded) { + const unpaddedLen = new DataView(padded.buffer).getUint16(0); + const unpadded = padded.subarray(2, 2 + unpaddedLen); + if (unpaddedLen < minPlaintextSize || unpaddedLen > maxPlaintextSize || unpadded.length !== unpaddedLen || padded.length !== 2 + calcPaddedLen(unpaddedLen)) + throw new Error("invalid padding"); + return utf8Decoder.decode(unpadded); +} +function hmacAad(key, message, aad) { + if (aad.length !== 32) + throw new Error("AAD associated data must be 32 bytes"); + const combined = concatBytes(aad, message); + return hmac(sha256, key, combined); +} +function decodePayload(payload) { + if (typeof payload !== "string") + throw new Error("payload must be a valid string"); + const plen = payload.length; + if (plen < 132 || plen > 87472) + throw new Error("invalid payload length: " + plen); + if (payload[0] === "#") + throw new Error("unknown encryption version"); + let data; + try { + data = base64.decode(payload); + } catch (error) { + throw new Error("invalid base64: " + error.message); + } + const dlen = data.length; + if (dlen < 99 || dlen > 65603) + throw new Error("invalid data length: " + dlen); + const vers = data[0]; + if (vers !== 2) + throw new Error("unknown encryption version " + vers); + return { + nonce: data.subarray(1, 33), + ciphertext: data.subarray(33, -32), + mac: data.subarray(-32) + }; +} +function encrypt(plaintext, conversationKey, nonce = randomBytes(32)) { + const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); + const padded = pad(plaintext); + const ciphertext = chacha20(chacha_key, chacha_nonce, padded); + const mac = hmacAad(hmac_key, ciphertext, nonce); + return base64.encode(concatBytes(new Uint8Array([2]), nonce, ciphertext, mac)); +} +function decrypt(payload, conversationKey) { + const { nonce, ciphertext, mac } = decodePayload(payload); + const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); + const calculatedMac = hmacAad(hmac_key, ciphertext, nonce); + if (!equalBytes(calculatedMac, mac)) + throw new Error("invalid MAC"); + const padded = chacha20(chacha_key, chacha_nonce, ciphertext); + return unpad(padded); +} + +// pure.ts +import { schnorr } from "@noble/curves/secp256k1"; +import { bytesToHex as bytesToHex2 } from "@noble/hashes/utils"; + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +import { sha256 as sha2562 } from "@noble/hashes/sha256"; +var JS = class { + generateSecretKey() { + return schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return bytesToHex2(schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = bytesToHex2(schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = bytesToHex2(schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = sha2562(utf8Encoder.encode(serializeEvent(event))); + return bytesToHex2(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// kinds.ts +var Seal = 13; +var GiftWrap = 1059; + +// nip59.ts +var TWO_DAYS = 2 * 24 * 60 * 60; +var now = () => Math.round(Date.now() / 1e3); +var randomNow = () => Math.round(now() - Math.random() * TWO_DAYS); +var nip44ConversationKey = (privateKey, publicKey) => getConversationKey(privateKey, publicKey); +var nip44Encrypt = (data, privateKey, publicKey) => encrypt(JSON.stringify(data), nip44ConversationKey(privateKey, publicKey)); +var nip44Decrypt = (data, privateKey) => JSON.parse(decrypt(data.content, nip44ConversationKey(privateKey, data.pubkey))); +function createRumor(event, privateKey) { + const rumor = { + created_at: now(), + content: "", + tags: [], + ...event, + pubkey: getPublicKey(privateKey) + }; + rumor.id = getEventHash(rumor); + return rumor; +} +function createSeal(rumor, privateKey, recipientPublicKey) { + return finalizeEvent( + { + kind: Seal, + content: nip44Encrypt(rumor, privateKey, recipientPublicKey), + created_at: randomNow(), + tags: [] + }, + privateKey + ); +} +function createWrap(seal, recipientPublicKey) { + const randomKey = generateSecretKey(); + return finalizeEvent( + { + kind: GiftWrap, + content: nip44Encrypt(seal, randomKey, recipientPublicKey), + created_at: randomNow(), + tags: [["p", recipientPublicKey]] + }, + randomKey + ); +} +function wrapEvent(event, senderPrivateKey, recipientPublicKey) { + const rumor = createRumor(event, senderPrivateKey); + const seal = createSeal(rumor, senderPrivateKey, recipientPublicKey); + return createWrap(seal, recipientPublicKey); +} +function wrapManyEvents(event, senderPrivateKey, recipientsPublicKeys) { + if (!recipientsPublicKeys || recipientsPublicKeys.length === 0) { + throw new Error("At least one recipient is required."); + } + const senderPublicKey = getPublicKey(senderPrivateKey); + const wrappeds = [wrapEvent(event, senderPrivateKey, senderPublicKey)]; + recipientsPublicKeys.forEach((recipientPublicKey) => { + wrappeds.push(wrapEvent(event, senderPrivateKey, recipientPublicKey)); + }); + return wrappeds; +} +function unwrapEvent(wrap, recipientPrivateKey) { + const unwrappedSeal = nip44Decrypt(wrap, recipientPrivateKey); + return nip44Decrypt(unwrappedSeal, recipientPrivateKey); +} +function unwrapManyEvents(wrappedEvents, recipientPrivateKey) { + let unwrappedEvents = []; + wrappedEvents.forEach((e) => { + unwrappedEvents.push(unwrapEvent(e, recipientPrivateKey)); + }); + unwrappedEvents.sort((a, b) => a.created_at - b.created_at); + return unwrappedEvents; +} +export { + createRumor, + createSeal, + createWrap, + unwrapEvent, + unwrapManyEvents, + wrapEvent, + wrapManyEvents +}; diff --git a/node_modules/nostr-tools/lib/esm/nip59.js.map b/node_modules/nostr-tools/lib/esm/nip59.js.map new file mode 100644 index 0000000..0419bd8 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip59.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip44.ts", "../../utils.ts", "../../pure.ts", "../../core.ts", "../../kinds.ts", "../../nip59.ts"], + "sourcesContent": ["import { chacha20 } from '@noble/ciphers/chacha'\nimport { equalBytes } from '@noble/ciphers/utils'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { extract as hkdf_extract, expand as hkdf_expand } from '@noble/hashes/hkdf'\nimport { hmac } from '@noble/hashes/hmac'\nimport { sha256 } from '@noble/hashes/sha256'\nimport { concatBytes, randomBytes } from '@noble/hashes/utils'\nimport { base64 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nconst minPlaintextSize = 0x0001 // 1b msg => padded to 32b\nconst maxPlaintextSize = 0xffff // 65535 (64kb-1) => padded to 64kb\n\nexport function getConversationKey(privkeyA: Uint8Array, pubkeyB: string): Uint8Array {\n const sharedX = secp256k1.getSharedSecret(privkeyA, '02' + pubkeyB).subarray(1, 33)\n return hkdf_extract(sha256, sharedX, 'nip44-v2')\n}\n\nfunction getMessageKeys(\n conversationKey: Uint8Array,\n nonce: Uint8Array,\n): { chacha_key: Uint8Array; chacha_nonce: Uint8Array; hmac_key: Uint8Array } {\n const keys = hkdf_expand(sha256, conversationKey, nonce, 76)\n return {\n chacha_key: keys.subarray(0, 32),\n chacha_nonce: keys.subarray(32, 44),\n hmac_key: keys.subarray(44, 76),\n }\n}\n\nfunction calcPaddedLen(len: number): number {\n if (!Number.isSafeInteger(len) || len < 1) throw new Error('expected positive integer')\n if (len <= 32) return 32\n const nextPower = 1 << (Math.floor(Math.log2(len - 1)) + 1)\n const chunk = nextPower <= 256 ? 32 : nextPower / 8\n return chunk * (Math.floor((len - 1) / chunk) + 1)\n}\n\nfunction writeU16BE(num: number): Uint8Array {\n if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize)\n throw new Error('invalid plaintext size: must be between 1 and 65535 bytes')\n const arr = new Uint8Array(2)\n new DataView(arr.buffer).setUint16(0, num, false)\n return arr\n}\n\nfunction pad(plaintext: string): Uint8Array {\n const unpadded = utf8Encoder.encode(plaintext)\n const unpaddedLen = unpadded.length\n const prefix = writeU16BE(unpaddedLen)\n const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen)\n return concatBytes(prefix, unpadded, suffix)\n}\n\nfunction unpad(padded: Uint8Array): string {\n const unpaddedLen = new DataView(padded.buffer).getUint16(0)\n const unpadded = padded.subarray(2, 2 + unpaddedLen)\n if (\n unpaddedLen < minPlaintextSize ||\n unpaddedLen > maxPlaintextSize ||\n unpadded.length !== unpaddedLen ||\n padded.length !== 2 + calcPaddedLen(unpaddedLen)\n )\n throw new Error('invalid padding')\n return utf8Decoder.decode(unpadded)\n}\n\nfunction hmacAad(key: Uint8Array, message: Uint8Array, aad: Uint8Array): Uint8Array {\n if (aad.length !== 32) throw new Error('AAD associated data must be 32 bytes')\n const combined = concatBytes(aad, message)\n return hmac(sha256, key, combined)\n}\n\n// metadata: always 65b (version: 1b, nonce: 32b, max: 32b)\n// plaintext: 1b to 0xffff\n// padded plaintext: 32b to 0xffff\n// ciphertext: 32b+2 to 0xffff+2\n// raw payload: 99 (65+32+2) to 65603 (65+0xffff+2)\n// compressed payload (base64): 132b to 87472b\nfunction decodePayload(payload: string): { nonce: Uint8Array; ciphertext: Uint8Array; mac: Uint8Array } {\n if (typeof payload !== 'string') throw new Error('payload must be a valid string')\n const plen = payload.length\n if (plen < 132 || plen > 87472) throw new Error('invalid payload length: ' + plen)\n if (payload[0] === '#') throw new Error('unknown encryption version')\n let data: Uint8Array\n try {\n data = base64.decode(payload)\n } catch (error) {\n throw new Error('invalid base64: ' + (error as any).message)\n }\n const dlen = data.length\n if (dlen < 99 || dlen > 65603) throw new Error('invalid data length: ' + dlen)\n const vers = data[0]\n if (vers !== 2) throw new Error('unknown encryption version ' + vers)\n return {\n nonce: data.subarray(1, 33),\n ciphertext: data.subarray(33, -32),\n mac: data.subarray(-32),\n }\n}\n\nexport function encrypt(plaintext: string, conversationKey: Uint8Array, nonce: Uint8Array = randomBytes(32)): string {\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n const padded = pad(plaintext)\n const ciphertext = chacha20(chacha_key, chacha_nonce, padded)\n const mac = hmacAad(hmac_key, ciphertext, nonce)\n return base64.encode(concatBytes(new Uint8Array([2]), nonce, ciphertext, mac))\n}\n\nexport function decrypt(payload: string, conversationKey: Uint8Array): string {\n const { nonce, ciphertext, mac } = decodePayload(payload)\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n const calculatedMac = hmacAad(hmac_key, ciphertext, nonce)\n if (!equalBytes(calculatedMac, mac)) throw new Error('invalid MAC')\n const padded = chacha20(chacha_key, chacha_nonce, ciphertext)\n return unpad(padded)\n}\n\nexport const v2 = {\n utils: {\n getConversationKey,\n calcPaddedLen,\n },\n encrypt,\n decrypt,\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { EventTemplate, UnsignedEvent, NostrEvent } from './core.ts'\nimport { getConversationKey, decrypt, encrypt } from './nip44.ts'\nimport { getEventHash, generateSecretKey, finalizeEvent, getPublicKey } from './pure.ts'\nimport { Seal, GiftWrap } from './kinds.ts'\n\ntype Rumor = UnsignedEvent & { id: string }\n\nconst TWO_DAYS = 2 * 24 * 60 * 60\n\nconst now = () => Math.round(Date.now() / 1000)\nconst randomNow = () => Math.round(now() - Math.random() * TWO_DAYS)\n\nconst nip44ConversationKey = (privateKey: Uint8Array, publicKey: string) => getConversationKey(privateKey, publicKey)\n\nconst nip44Encrypt = (data: EventTemplate, privateKey: Uint8Array, publicKey: string) =>\n encrypt(JSON.stringify(data), nip44ConversationKey(privateKey, publicKey))\n\nconst nip44Decrypt = (data: NostrEvent, privateKey: Uint8Array) =>\n JSON.parse(decrypt(data.content, nip44ConversationKey(privateKey, data.pubkey)))\n\nexport function createRumor(event: Partial, privateKey: Uint8Array): Rumor {\n const rumor = {\n created_at: now(),\n content: '',\n tags: [],\n ...event,\n pubkey: getPublicKey(privateKey),\n } as any\n\n rumor.id = getEventHash(rumor)\n\n return rumor as Rumor\n}\n\nexport function createSeal(rumor: Rumor, privateKey: Uint8Array, recipientPublicKey: string): NostrEvent {\n return finalizeEvent(\n {\n kind: Seal,\n content: nip44Encrypt(rumor, privateKey, recipientPublicKey),\n created_at: randomNow(),\n tags: [],\n },\n privateKey,\n )\n}\n\nexport function createWrap(seal: NostrEvent, recipientPublicKey: string): NostrEvent {\n const randomKey = generateSecretKey()\n\n return finalizeEvent(\n {\n kind: GiftWrap,\n content: nip44Encrypt(seal, randomKey, recipientPublicKey),\n created_at: randomNow(),\n tags: [['p', recipientPublicKey]],\n },\n randomKey,\n ) as NostrEvent\n}\n\nexport function wrapEvent(\n event: Partial,\n senderPrivateKey: Uint8Array,\n recipientPublicKey: string,\n): NostrEvent {\n const rumor = createRumor(event, senderPrivateKey)\n\n const seal = createSeal(rumor, senderPrivateKey, recipientPublicKey)\n return createWrap(seal, recipientPublicKey)\n}\n\nexport function wrapManyEvents(\n event: Partial,\n senderPrivateKey: Uint8Array,\n recipientsPublicKeys: string[],\n): NostrEvent[] {\n if (!recipientsPublicKeys || recipientsPublicKeys.length === 0) {\n throw new Error('At least one recipient is required.')\n }\n\n const senderPublicKey = getPublicKey(senderPrivateKey)\n\n const wrappeds = [wrapEvent(event, senderPrivateKey, senderPublicKey)]\n\n recipientsPublicKeys.forEach(recipientPublicKey => {\n wrappeds.push(wrapEvent(event, senderPrivateKey, recipientPublicKey))\n })\n\n return wrappeds\n}\n\nexport function unwrapEvent(wrap: NostrEvent, recipientPrivateKey: Uint8Array): Rumor {\n const unwrappedSeal = nip44Decrypt(wrap, recipientPrivateKey)\n return nip44Decrypt(unwrappedSeal, recipientPrivateKey)\n}\n\nexport function unwrapManyEvents(wrappedEvents: NostrEvent[], recipientPrivateKey: Uint8Array): Rumor[] {\n let unwrappedEvents: Rumor[] = []\n\n wrappedEvents.forEach(e => {\n unwrappedEvents.push(unwrapEvent(e, recipientPrivateKey))\n })\n\n unwrappedEvents.sort((a, b) => a.created_at - b.created_at)\n\n return unwrappedEvents\n}\n"], + "mappings": ";AAAA,SAAS,gBAAgB;AACzB,SAAS,kBAAkB;AAC3B,SAAS,iBAAiB;AAC1B,SAAS,WAAW,cAAc,UAAU,mBAAmB;AAC/D,SAAS,YAAY;AACrB,SAAS,cAAc;AACvB,SAAS,aAAa,mBAAmB;AACzC,SAAS,cAAc;;;ACFvB,SAAS,YAAY,kBAAkB;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;;;ADQxD,IAAM,mBAAmB;AACzB,IAAM,mBAAmB;AAElB,SAAS,mBAAmB,UAA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F;AACF;AAEO,SAAS,UACd,OACA,kBACA,oBACY;AACZ,QAAM,QAAQ,YAAY,OAAO,gBAAgB;AAEjD,QAAM,OAAO,WAAW,OAAO,kBAAkB,kBAAkB;AACnE,SAAO,WAAW,MAAM,kBAAkB;AAC5C;AAEO,SAAS,eACd,OACA,kBACA,sBACc;AACd,MAAI,CAAC,wBAAwB,qBAAqB,WAAW,GAAG;AAC9D,UAAM,IAAI,MAAM,qCAAqC;AAAA,EACvD;AAEA,QAAM,kBAAkB,aAAa,gBAAgB;AAErD,QAAM,WAAW,CAAC,UAAU,OAAO,kBAAkB,eAAe,CAAC;AAErE,uBAAqB,QAAQ,wBAAsB;AACjD,aAAS,KAAK,UAAU,OAAO,kBAAkB,kBAAkB,CAAC;AAAA,EACtE,CAAC;AAED,SAAO;AACT;AAEO,SAAS,YAAY,MAAkB,qBAAwC;AACpF,QAAM,gBAAgB,aAAa,MAAM,mBAAmB;AAC5D,SAAO,aAAa,eAAe,mBAAmB;AACxD;AAEO,SAAS,iBAAiB,eAA6B,qBAA0C;AACtG,MAAI,kBAA2B,CAAC;AAEhC,gBAAc,QAAQ,OAAK;AACzB,oBAAgB,KAAK,YAAY,GAAG,mBAAmB,CAAC;AAAA,EAC1D,CAAC;AAED,kBAAgB,KAAK,CAAC,GAAG,MAAM,EAAE,aAAa,EAAE,UAAU;AAE1D,SAAO;AACT;", + "names": ["bytesToHex", "i", "sha256", "bytesToHex", "sha256"] +} diff --git a/node_modules/nostr-tools/lib/esm/nip75.js b/node_modules/nostr-tools/lib/esm/nip75.js new file mode 100644 index 0000000..77a2c04 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip75.js @@ -0,0 +1,47 @@ +// kinds.ts +var ZapGoal = 9041; + +// nip75.ts +function generateGoalEventTemplate({ + amount, + content, + relays, + a, + closedAt, + image, + r, + summary, + zapTags +}) { + const tags = [ + ["amount", amount], + ["relays", ...relays] + ]; + closedAt && tags.push(["closed_at", closedAt.toString()]); + image && tags.push(["image", image]); + summary && tags.push(["summary", summary]); + r && tags.push(["r", r]); + a && tags.push(["a", a]); + zapTags && tags.push(...zapTags); + const eventTemplate = { + created_at: Math.floor(Date.now() / 1e3), + kind: ZapGoal, + content, + tags + }; + return eventTemplate; +} +function validateZapGoalEvent(event) { + if (event.kind !== ZapGoal) + return false; + const requiredTags = ["amount", "relays"]; + for (const tag of requiredTags) { + if (!event.tags.find(([t]) => t == tag)) + return false; + } + return true; +} +export { + generateGoalEventTemplate, + validateZapGoalEvent +}; diff --git a/node_modules/nostr-tools/lib/esm/nip75.js.map b/node_modules/nostr-tools/lib/esm/nip75.js.map new file mode 100644 index 0000000..37427a6 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip75.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../kinds.ts", "../../nip75.ts"], + "sourcesContent": ["import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { Event, EventTemplate } from './core.ts'\nimport { ZapGoal } from './kinds.ts'\n\n/**\n * Represents a fundraising goal in the Nostr network as defined by NIP-75.\n * This type is used to structure the information needed to create a goal event (`kind:9041`).\n */\nexport type Goal = {\n /**\n * A human-readable description of the fundraising goal.\n * This content should provide clear information about the purpose of the fundraising.\n */\n content: string\n\n /**\n * The target amount for the fundraising goal in milisats.\n * This defines the financial target that the fundraiser aims to reach.\n */\n amount: string\n\n /**\n * A list of relays where the zaps towards this goal will be sent to and tallied from.\n * Each relay is represented by its WebSocket URL.\n */\n relays: string[]\n\n /**\n * An optional timestamp (in seconds, UNIX epoch) indicating when the fundraising goal is considered closed.\n * Zaps published after this timestamp should not count towards the goal progress.\n * If not provided, the goal remains open indefinitely or until manually closed.\n */\n closedAt?: number\n\n /**\n * An optional URL to an image related to the goal.\n * This can be used to visually represent the goal on client interfaces.\n */\n image?: string\n\n /**\n * An optional brief description or summary of the goal.\n * This can provide a quick overview of the goal, separate from the detailed `content`.\n */\n summary?: string\n\n /**\n * An optional URL related to the goal, providing additional information or actions through an 'r' tag.\n * This is a single URL, as per NIP-75 specifications for linking additional resources.\n */\n r?: string\n\n /**\n * An optional parameterized replaceable event linked to the goal, specified through an 'a' tag.\n * This is a single event id, aligning with NIP-75's allowance for linking to specific events.\n */\n a?: string\n\n /**\n * Optional tags specifying multiple beneficiary pubkeys or additional criteria for zapping,\n * allowing contributions to be directed towards multiple recipients or according to specific conditions.\n */\n zapTags?: string[][]\n}\n\n/**\n * Generates an EventTemplate for a fundraising goal based on the provided ZapGoal object.\n * This function is tailored to fit the structure of EventTemplate as defined in the library.\n * @param zapGoal The ZapGoal object containing the details of the fundraising goal.\n * @returns An EventTemplate object structured for creating a Nostr event.\n */\nexport function generateGoalEventTemplate({\n amount,\n content,\n relays,\n a,\n closedAt,\n image,\n r,\n summary,\n zapTags,\n}: Goal): EventTemplate {\n const tags: string[][] = [\n ['amount', amount],\n ['relays', ...relays],\n ]\n\n // Append optional tags based on the presence of optional properties in zapGoal\n closedAt && tags.push(['closed_at', closedAt.toString()])\n image && tags.push(['image', image])\n summary && tags.push(['summary', summary])\n r && tags.push(['r', r])\n a && tags.push(['a', a])\n zapTags && tags.push(...zapTags)\n\n // Construct the EventTemplate object\n const eventTemplate: EventTemplate = {\n created_at: Math.floor(Date.now() / 1000),\n kind: ZapGoal,\n content,\n tags,\n }\n\n return eventTemplate\n}\n\nexport function validateZapGoalEvent(event: Event): boolean {\n if (event.kind !== ZapGoal) return false\n\n const requiredTags = ['amount', 'relays'] as const\n for (const tag of requiredTags) {\n if (!event.tags.find(([t]) => t == tag)) return false\n }\n\n return true\n}\n"], + "mappings": ";AAiGO,IAAM,UAAU;;;AC3BhB,SAAS,0BAA0B;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAwB;AACtB,QAAM,OAAmB;AAAA,IACvB,CAAC,UAAU,MAAM;AAAA,IACjB,CAAC,UAAU,GAAG,MAAM;AAAA,EACtB;AAGA,cAAY,KAAK,KAAK,CAAC,aAAa,SAAS,SAAS,CAAC,CAAC;AACxD,WAAS,KAAK,KAAK,CAAC,SAAS,KAAK,CAAC;AACnC,aAAW,KAAK,KAAK,CAAC,WAAW,OAAO,CAAC;AACzC,OAAK,KAAK,KAAK,CAAC,KAAK,CAAC,CAAC;AACvB,OAAK,KAAK,KAAK,CAAC,KAAK,CAAC,CAAC;AACvB,aAAW,KAAK,KAAK,GAAG,OAAO;AAG/B,QAAM,gBAA+B;AAAA,IACnC,YAAY,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAAA,IACxC,MAAM;AAAA,IACN;AAAA,IACA;AAAA,EACF;AAEA,SAAO;AACT;AAEO,SAAS,qBAAqB,OAAuB;AAC1D,MAAI,MAAM,SAAS;AAAS,WAAO;AAEnC,QAAM,eAAe,CAAC,UAAU,QAAQ;AACxC,aAAW,OAAO,cAAc;AAC9B,QAAI,CAAC,MAAM,KAAK,KAAK,CAAC,CAAC,CAAC,MAAM,KAAK,GAAG;AAAG,aAAO;AAAA,EAClD;AAEA,SAAO;AACT;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/esm/nip94.js b/node_modules/nostr-tools/lib/esm/nip94.js new file mode 100644 index 0000000..a87123e --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip94.js @@ -0,0 +1,119 @@ +// kinds.ts +var FileMetadata = 1063; + +// nip94.ts +function generateEventTemplate(fileMetadata) { + const eventTemplate = { + content: fileMetadata.content, + created_at: Math.floor(Date.now() / 1e3), + kind: FileMetadata, + tags: [ + ["url", fileMetadata.url], + ["m", fileMetadata.m], + ["x", fileMetadata.x], + ["ox", fileMetadata.ox] + ] + }; + if (fileMetadata.size) + eventTemplate.tags.push(["size", fileMetadata.size]); + if (fileMetadata.dim) + eventTemplate.tags.push(["dim", fileMetadata.dim]); + if (fileMetadata.i) + eventTemplate.tags.push(["i", fileMetadata.i]); + if (fileMetadata.blurhash) + eventTemplate.tags.push(["blurhash", fileMetadata.blurhash]); + if (fileMetadata.thumb) + eventTemplate.tags.push(["thumb", fileMetadata.thumb]); + if (fileMetadata.image) + eventTemplate.tags.push(["image", fileMetadata.image]); + if (fileMetadata.summary) + eventTemplate.tags.push(["summary", fileMetadata.summary]); + if (fileMetadata.alt) + eventTemplate.tags.push(["alt", fileMetadata.alt]); + if (fileMetadata.fallback) + fileMetadata.fallback.forEach((url) => eventTemplate.tags.push(["fallback", url])); + return eventTemplate; +} +function validateEvent(event) { + if (event.kind !== FileMetadata) + return false; + if (!event.content) + return false; + const requiredTags = ["url", "m", "x", "ox"]; + for (const tag of requiredTags) { + if (!event.tags.find(([t]) => t == tag)) + return false; + } + const sizeTag = event.tags.find(([t]) => t == "size"); + if (sizeTag && isNaN(Number(sizeTag[1]))) + return false; + const dimTag = event.tags.find(([t]) => t == "dim"); + if (dimTag && !dimTag[1].match(/^\d+x\d+$/)) + return false; + return true; +} +function parseEvent(event) { + if (!validateEvent(event)) { + throw new Error("Invalid event"); + } + const fileMetadata = { + content: event.content, + url: "", + m: "", + x: "", + ox: "" + }; + for (const [tag, value] of event.tags) { + switch (tag) { + case "url": + fileMetadata.url = value; + break; + case "m": + fileMetadata.m = value; + break; + case "x": + fileMetadata.x = value; + break; + case "ox": + fileMetadata.ox = value; + break; + case "size": + fileMetadata.size = value; + break; + case "dim": + fileMetadata.dim = value; + break; + case "magnet": + fileMetadata.magnet = value; + break; + case "i": + fileMetadata.i = value; + break; + case "blurhash": + fileMetadata.blurhash = value; + break; + case "thumb": + fileMetadata.thumb = value; + break; + case "image": + fileMetadata.image = value; + break; + case "summary": + fileMetadata.summary = value; + break; + case "alt": + fileMetadata.alt = value; + break; + case "fallback": + fileMetadata.fallback ??= []; + fileMetadata.fallback.push(value); + break; + } + } + return fileMetadata; +} +export { + generateEventTemplate, + parseEvent, + validateEvent +}; diff --git a/node_modules/nostr-tools/lib/esm/nip94.js.map b/node_modules/nostr-tools/lib/esm/nip94.js.map new file mode 100644 index 0000000..40a2d4f --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip94.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../kinds.ts", "../../nip94.ts"], + "sourcesContent": ["import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { Event, EventTemplate } from './core.ts'\nimport { FileMetadata as FileMetadataKind } from './kinds.ts'\n\n/**\n * Type definition for File Metadata as specified in NIP-94.\n * This type is used to represent the metadata associated with a file sharing event (kind: 1063).\n */\nexport type FileMetadataObject = {\n /**\n * A description or caption for the file content.\n */\n content: string\n\n /**\n * The URL to download the file.\n */\n url: string\n\n /**\n * The MIME type of the file, in lowercase.\n */\n m: string\n\n /**\n * The SHA-256 hex-encoded string of the file.\n */\n x: string\n\n /**\n * The SHA-256 hex-encoded string of the original file, before any transformations done by the upload server.\n */\n ox: string\n\n /**\n * Optional: The size of the file in bytes.\n */\n size?: string\n\n /**\n * Optional: The dimensions of the file in pixels, in the format \"x\".\n */\n dim?: string\n\n /**\n * Optional: The URI to the magnet file.\n */\n magnet?: string\n\n /**\n * Optional: The torrent infohash.\n */\n i?: string\n\n /**\n * Optional: The blurhash string to show while the file is being loaded by the client.\n */\n blurhash?: string\n\n /**\n * Optional: The URL of the thumbnail image with the same aspect ratio as the original file.\n */\n thumb?: string\n\n /**\n * Optional: The URL of a preview image with the same dimensions as the original file.\n */\n image?: string\n\n /**\n * Optional: A text excerpt or summary of the file's content.\n */\n summary?: string\n\n /**\n * Optional: A description for accessibility, providing context or a brief description of the file.\n */\n alt?: string\n\n /**\n * Optional: fallback URLs in case url fails.\n */\n fallback?: string[]\n}\n\n/**\n * Generates an event template based on a file metadata object.\n *\n * @param fileMetadata - The file metadata object.\n * @returns The event template.\n */\nexport function generateEventTemplate(fileMetadata: FileMetadataObject): EventTemplate {\n const eventTemplate: EventTemplate = {\n content: fileMetadata.content,\n created_at: Math.floor(Date.now() / 1000),\n kind: FileMetadataKind,\n tags: [\n ['url', fileMetadata.url],\n ['m', fileMetadata.m],\n ['x', fileMetadata.x],\n ['ox', fileMetadata.ox],\n ],\n }\n\n if (fileMetadata.size) eventTemplate.tags.push(['size', fileMetadata.size])\n if (fileMetadata.dim) eventTemplate.tags.push(['dim', fileMetadata.dim])\n if (fileMetadata.i) eventTemplate.tags.push(['i', fileMetadata.i])\n if (fileMetadata.blurhash) eventTemplate.tags.push(['blurhash', fileMetadata.blurhash])\n if (fileMetadata.thumb) eventTemplate.tags.push(['thumb', fileMetadata.thumb])\n if (fileMetadata.image) eventTemplate.tags.push(['image', fileMetadata.image])\n if (fileMetadata.summary) eventTemplate.tags.push(['summary', fileMetadata.summary])\n if (fileMetadata.alt) eventTemplate.tags.push(['alt', fileMetadata.alt])\n if (fileMetadata.fallback) fileMetadata.fallback.forEach(url => eventTemplate.tags.push(['fallback', url]))\n\n return eventTemplate\n}\n\n/**\n * Validates an event to ensure it is a valid file metadata event.\n * @param event - The event to validate.\n * @returns True if the event is valid, false otherwise.\n */\nexport function validateEvent(event: Event): boolean {\n if (event.kind !== FileMetadataKind) return false\n\n if (!event.content) return false\n\n const requiredTags = ['url', 'm', 'x', 'ox'] as const\n for (const tag of requiredTags) {\n if (!event.tags.find(([t]) => t == tag)) return false\n }\n\n // validate optional size tag\n const sizeTag = event.tags.find(([t]) => t == 'size')\n if (sizeTag && isNaN(Number(sizeTag[1]))) return false\n\n // validate optional dim tag\n const dimTag = event.tags.find(([t]) => t == 'dim')\n if (dimTag && !dimTag[1].match(/^\\d+x\\d+$/)) return false\n\n return true\n}\n\n/**\n * Parses an event and returns a file metadata object.\n * @param event - The event to parse.\n * @returns The file metadata object.\n * @throws Error if the event is invalid.\n */\nexport function parseEvent(event: Event): FileMetadataObject {\n if (!validateEvent(event)) {\n throw new Error('Invalid event')\n }\n\n const fileMetadata: FileMetadataObject = {\n content: event.content,\n url: '',\n m: '',\n x: '',\n ox: '',\n }\n\n for (const [tag, value] of event.tags) {\n switch (tag) {\n case 'url':\n fileMetadata.url = value\n break\n case 'm':\n fileMetadata.m = value\n break\n case 'x':\n fileMetadata.x = value\n break\n case 'ox':\n fileMetadata.ox = value\n break\n case 'size':\n fileMetadata.size = value\n break\n case 'dim':\n fileMetadata.dim = value\n break\n case 'magnet':\n fileMetadata.magnet = value\n break\n case 'i':\n fileMetadata.i = value\n break\n case 'blurhash':\n fileMetadata.blurhash = value\n break\n case 'thumb':\n fileMetadata.thumb = value\n break\n case 'image':\n fileMetadata.image = value\n break\n case 'summary':\n fileMetadata.summary = value\n break\n case 'alt':\n fileMetadata.alt = value\n break\n case 'fallback':\n fileMetadata.fallback ??= []\n fileMetadata.fallback.push(value)\n break\n }\n }\n\n return fileMetadata\n}\n"], + "mappings": ";AA6EO,IAAM,eAAe;;;ACarB,SAAS,sBAAsB,cAAiD;AACrF,QAAM,gBAA+B;AAAA,IACnC,SAAS,aAAa;AAAA,IACtB,YAAY,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAAA,IACxC,MAAM;AAAA,IACN,MAAM;AAAA,MACJ,CAAC,OAAO,aAAa,GAAG;AAAA,MACxB,CAAC,KAAK,aAAa,CAAC;AAAA,MACpB,CAAC,KAAK,aAAa,CAAC;AAAA,MACpB,CAAC,MAAM,aAAa,EAAE;AAAA,IACxB;AAAA,EACF;AAEA,MAAI,aAAa;AAAM,kBAAc,KAAK,KAAK,CAAC,QAAQ,aAAa,IAAI,CAAC;AAC1E,MAAI,aAAa;AAAK,kBAAc,KAAK,KAAK,CAAC,OAAO,aAAa,GAAG,CAAC;AACvE,MAAI,aAAa;AAAG,kBAAc,KAAK,KAAK,CAAC,KAAK,aAAa,CAAC,CAAC;AACjE,MAAI,aAAa;AAAU,kBAAc,KAAK,KAAK,CAAC,YAAY,aAAa,QAAQ,CAAC;AACtF,MAAI,aAAa;AAAO,kBAAc,KAAK,KAAK,CAAC,SAAS,aAAa,KAAK,CAAC;AAC7E,MAAI,aAAa;AAAO,kBAA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AI;AACjB;AAAA,MACF,KAAK;AACH,qBAAa,IAAI;AACjB;AAAA,MACF,KAAK;AACH,qBAAa,KAAK;AAClB;AAAA,MACF,KAAK;AACH,qBAAa,OAAO;AACpB;AAAA,MACF,KAAK;AACH,qBAAa,MAAM;AACnB;AAAA,MACF,KAAK;AACH,qBAAa,SAAS;AACtB;AAAA,MACF,KAAK;AACH,qBAAa,IAAI;AACjB;AAAA,MACF,KAAK;AACH,qBAAa,WAAW;AACxB;AAAA,MACF,KAAK;AACH,qBAAa,QAAQ;AACrB;AAAA,MACF,KAAK;AACH,qBAAa,QAAQ;AACrB;AAAA,MACF,KAAK;AACH,qBAAa,UAAU;AACvB;AAAA,MACF,KAAK;AACH,qBAAa,MAAM;AACnB;AAAA,MACF,KAAK;AACH,qBAAa,aAAa,CAAC;AAC3B,qBAAa,SAAS,KAAK,KAAK;AAChC;AAAA,IACJ;AAAA,EACF;AAEA,SAAO;AACT;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/esm/nip98.js b/node_modules/nostr-tools/lib/esm/nip98.js new file mode 100644 index 0000000..d24a22e --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip98.js @@ -0,0 +1,209 @@ +// nip98.ts +import { sha256 as sha2562 } from "@noble/hashes/sha256"; +import { bytesToHex as bytesToHex3 } from "@noble/hashes/utils"; +import { base64 } from "@scure/base"; + +// pure.ts +import { schnorr } from "@noble/curves/secp256k1"; +import { bytesToHex as bytesToHex2 } from "@noble/hashes/utils"; + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +import { sha256 } from "@noble/hashes/sha256"; + +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// pure.ts +var JS = class { + generateSecretKey() { + return schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return bytesToHex2(schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = bytesToHex2(schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = bytesToHex2(schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = sha256(utf8Encoder.encode(serializeEvent(event))); + return bytesToHex2(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// kinds.ts +var HTTPAuth = 27235; + +// nip98.ts +var _authorizationScheme = "Nostr "; +async function getToken(loginUrl, httpMethod, sign, includeAuthorizationScheme = false, payload) { + const event = { + kind: HTTPAuth, + tags: [ + ["u", loginUrl], + ["method", httpMethod] + ], + created_at: Math.round(new Date().getTime() / 1e3), + content: "" + }; + if (payload) { + event.tags.push(["payload", hashPayload(payload)]); + } + const signedEvent = await sign(event); + const authorizationScheme = includeAuthorizationScheme ? _authorizationScheme : ""; + return authorizationScheme + base64.encode(utf8Encoder.encode(JSON.stringify(signedEvent))); +} +async function validateToken(token, url, method) { + const event = await unpackEventFromToken(token).catch((error) => { + throw error; + }); + const valid = await validateEvent2(event, url, method).catch((error) => { + throw error; + }); + return valid; +} +async function unpackEventFromToken(token) { + if (!token) { + throw new Error("Missing token"); + } + token = token.replace(_authorizationScheme, ""); + const eventB64 = utf8Decoder.decode(base64.decode(token)); + if (!eventB64 || eventB64.length === 0 || !eventB64.startsWith("{")) { + throw new Error("Invalid token"); + } + const event = JSON.parse(eventB64); + return event; +} +function validateEventTimestamp(event) { + if (!event.created_at) { + return false; + } + return Math.round(new Date().getTime() / 1e3) - event.created_at < 60; +} +function validateEventKind(event) { + return event.kind === HTTPAuth; +} +function validateEventUrlTag(event, url) { + const urlTag = event.tags.find((t) => t[0] === "u"); + if (!urlTag) { + return false; + } + return urlTag.length > 0 && urlTag[1] === url; +} +function validateEventMethodTag(event, method) { + const methodTag = event.tags.find((t) => t[0] === "method"); + if (!methodTag) { + return false; + } + return methodTag.length > 0 && methodTag[1].toLowerCase() === method.toLowerCase(); +} +function hashPayload(payload) { + const hash = sha2562(utf8Encoder.encode(JSON.stringify(payload))); + return bytesToHex3(hash); +} +function validateEventPayloadTag(event, payload) { + const payloadTag = event.tags.find((t) => t[0] === "payload"); + if (!payloadTag) { + return false; + } + const payloadHash = hashPayload(payload); + return payloadTag.length > 0 && payloadTag[1] === payloadHash; +} +async function validateEvent2(event, url, method, body) { + if (!verifyEvent(event)) { + throw new Error("Invalid nostr event, signature invalid"); + } + if (!validateEventKind(event)) { + throw new Error("Invalid nostr event, kind invalid"); + } + if (!validateEventTimestamp(event)) { + throw new Error("Invalid nostr event, created_at timestamp invalid"); + } + if (!validateEventUrlTag(event, url)) { + throw new Error("Invalid nostr event, url tag invalid"); + } + if (!validateEventMethodTag(event, method)) { + throw new Error("Invalid nostr event, method tag invalid"); + } + if (Boolean(body) && typeof body === "object" && Object.keys(body).length > 0) { + if (!validateEventPayloadTag(event, body)) { + throw new Error("Invalid nostr event, payload tag does not match request body hash"); + } + } + return true; +} +export { + getToken, + hashPayload, + unpackEventFromToken, + validateEvent2 as validateEvent, + validateEventKind, + validateEventMethodTag, + validateEventPayloadTag, + validateEventTimestamp, + validateEventUrlTag, + validateToken +}; diff --git a/node_modules/nostr-tools/lib/esm/nip98.js.map b/node_modules/nostr-tools/lib/esm/nip98.js.map new file mode 100644 index 0000000..3c6863c --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip98.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip98.ts", "../../pure.ts", "../../core.ts", "../../utils.ts", "../../kinds.ts"], + "sourcesContent": ["import { sha256 } from '@noble/hashes/sha256'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { base64 } from '@scure/base'\n\nimport { HTTPAuth } from './kinds.ts'\nimport { Event, EventTemplate, verifyEvent } from './pure.ts'\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nconst _authorizationScheme = 'Nostr '\n\n/**\n * Generate token for NIP-98 flow.\n *\n * @example\n * const sign = window.nostr.signEvent\n * await nip98.getToken('https://example.com/login', 'post', (e) => sign(e), true)\n */\nexport async function getToken(\n loginUrl: string,\n httpMethod: string,\n sign: (e: EventTemplate) => Promise | Event,\n includeAuthorizationScheme: boolean = false,\n payload?: Record,\n): Promise {\n const event: EventTemplate = {\n kind: HTTPAuth,\n tags: [\n ['u', loginUrl],\n ['method', httpMethod],\n ],\n created_at: Math.round(new Date().getTime() / 1000),\n content: '',\n }\n\n if (payload) {\n event.tags.push(['payload', hashPayload(payload)])\n }\n\n const signedEvent = await sign(event)\n const authorizationScheme = includeAuthorizationScheme ? _authorizationScheme : ''\n\n return authorizationScheme + base64.encode(utf8Encoder.encode(JSON.stringify(signedEvent)))\n}\n\n/**\n * Validate token for NIP-98 flow.\n *\n * @example\n * await nip98.validateToken('Nostr base64token', 'https://example.com/login', 'post')\n */\nexport async function validateToken(token: string, url: string, method: string): Promise {\n const event = await unpackEventFromToken(token).catch(error => {\n throw error\n })\n\n const valid = await validateEvent(event, url, method).catch(error => {\n throw error\n })\n\n return valid\n}\n\n/**\n * Unpacks an event from a token.\n *\n * @param token - The token to unpack.\n * @returns A promise that resolves to the unpacked event.\n * @throws {Error} If the token is missing, invalid, or cannot be parsed.\n */\nexport async function unpackEventFromToken(token: string): Promise {\n if (!token) {\n throw new Error('Missing token')\n }\n\n token = token.replace(_authorizationScheme, '')\n\n const eventB64 = utf8Decoder.decode(base64.decode(token))\n if (!eventB64 || eventB64.length === 0 || !eventB64.startsWith('{')) {\n throw new Error('Invalid token')\n }\n\n const event = JSON.parse(eventB64) as Event\n\n return event\n}\n\n/**\n * Validates the timestamp of an event.\n * @param event - The event object to validate.\n * @returns A boolean indicating whether the event timestamp is within the last 60 seconds.\n */\nexport function validateEventTimestamp(event: Event): boolean {\n if (!event.created_at) {\n return false\n }\n\n return Math.round(new Date().getTime() / 1000) - event.created_at < 60\n}\n\n/**\n * Validates the kind of an event.\n * @param event The event to validate.\n * @returns A boolean indicating whether the event kind is valid.\n */\nexport function validateEventKind(event: Event): boolean {\n return event.kind === HTTPAuth\n}\n\n/**\n * Validates if the given URL matches the URL tag of the event.\n * @param event - The event object.\n * @param url - The URL to validate.\n * @returns A boolean indicating whether the URL is valid or not.\n */\nexport function validateEventUrlTag(event: Event, url: string): boolean {\n const urlTag = event.tags.find(t => t[0] === 'u')\n\n if (!urlTag) {\n return false\n }\n\n return urlTag.length > 0 && urlTag[1] === url\n}\n\n/**\n * Validates if the given event has a method tag that matches the specified method.\n * @param event - The event to validate.\n * @param method - The method to match against the method tag.\n * @returns A boolean indicating whether the event has a matching method tag.\n */\nexport function validateEventMethodTag(event: Event, method: string): boolean {\n const methodTag = event.tags.find(t => t[0] === 'method')\n\n if (!methodTag) {\n return false\n }\n\n return methodTag.length > 0 && methodTag[1].toLowerCase() === method.toLowerCase()\n}\n\n/**\n * Calculates the hash of a payload.\n * @param payload - The payload to be hashed.\n * @returns The hash value as a string.\n */\nexport function hashPayload(payload: any): string {\n const hash = sha256(utf8Encoder.encode(JSON.stringify(payload)))\n return bytesToHex(hash)\n}\n\n/**\n * Validates the event payload tag against the provided payload.\n * @param event The event object.\n * @param payload The payload to validate.\n * @returns A boolean indicating whether the payload tag is valid.\n */\nexport function validateEventPayloadTag(event: Event, payload: any): boolean {\n const payloadTag = event.tags.find(t => t[0] === 'payload')\n\n if (!payloadTag) {\n return false\n }\n\n const payloadHash = hashPayload(payload)\n return payloadTag.length > 0 && payloadTag[1] === payloadHash\n}\n\n/**\n * Validates a Nostr event for the NIP-98 flow.\n *\n * @param event - The Nostr event to validate.\n * @param url - The URL associated with the event.\n * @param method - The HTTP method associated with the event.\n * @param body - The request body associated with the event (optional).\n * @returns A promise that resolves to a boolean indicating whether the event is valid.\n * @throws An error if the event is invalid.\n */\nexport async function validateEvent(event: Event, url: string, method: string, body?: any): Promise {\n if (!verifyEvent(event)) {\n throw new Error('Invalid nostr event, signature invalid')\n }\n\n if (!validateEventKind(event)) {\n throw new Error('Invalid nostr event, kind invalid')\n }\n\n if (!validateEventTimestamp(event)) {\n throw new Error('Invalid nostr event, created_at timestamp invalid')\n }\n\n if (!validateEventUrlTag(event, url)) {\n throw new Error('Invalid nostr event, url tag invalid')\n }\n\n if (!validateEventMethodTag(event, method)) {\n throw new Error('Invalid nostr event, method tag invalid')\n }\n\n if (Boolean(body) && typeof body === 'object' && Object.keys(body).length > 0) {\n if (!validateEventPayloadTag(event, body)) {\n throw new Error('Invalid nostr event, payload tag does not match request body hash')\n }\n }\n\n return true\n}\n", "import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n"], + "mappings": ";AAAA,SAAS,UAAAA,eAAc;AACvB,SAAS,cAAAC,mBAAkB;AAC3B,SAAS,cAAc;;;ACFvB,SAAS,eAAe;AACxB,SAAS,cAAAC,mBAAkB;;;ACOpB,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,CAAC,QAAiD,eAAe;AAE3E,SAAS,cAAiB,OAAsC;AACrE,MAAI,CAAC,SAAS,KAAK;AAAG,WAAO;AAC7B,MAAI,OAAO,MAAM,SAAS;AAAU,WAAO;AAC3C,MAAI,OAAO,MAAM,YAAY;AAAU,WAAO;AAC9C,MAAI,OAAO,MAAM,eAAe;AAAU,WAAO;AACjD,MAAI,OAAO,MAAM,WAAW;AAAU,WAAO;AAC7C,MAAI,CAAC,MAAM,OAAO,MAAM,gBAAgB;AAAG,WAAO;AAElD,MAAI,CAAC,MAAM,QAAQ,MAAM,IAAI;AAAG,WAAO;AACvC,WAASC,KAAI,GAAGA,KAAI,MAAM,KAAK,QAAQA,MAAK;AAC1C,QAAI,MAAM,MAAM,KAAKA;AACrB,QAAI,CAAC,MAAM,QAAQ,GAAG;AAAG,aAAO;AAChC,aAAS,IA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K,GAAG;AACvB,UAAM,IAAI,MAAM,wCAAwC;AAAA,EAC1D;AAEA,MAAI,CAAC,kBAAkB,KAAK,GAAG;AAC7B,UAAM,IAAI,MAAM,mCAAmC;AAAA,EACrD;AAEA,MAAI,CAAC,uBAAuB,KAAK,GAAG;AAClC,UAAM,IAAI,MAAM,mDAAmD;AAAA,EACrE;AAEA,MAAI,CAAC,oBAAoB,OAAO,GAAG,GAAG;AACpC,UAAM,IAAI,MAAM,sCAAsC;AAAA,EACxD;AAEA,MAAI,CAAC,uBAAuB,OAAO,MAAM,GAAG;AAC1C,UAAM,IAAI,MAAM,yCAAyC;AAAA,EAC3D;AAEA,MAAI,QAAQ,IAAI,KAAK,OAAO,SAAS,YAAY,OAAO,KAAK,IAAI,EAAE,SAAS,GAAG;AAC7E,QAAI,CAAC,wBAAwB,OAAO,IAAI,GAAG;AACzC,YAAM,IAAI,MAAM,mEAAmE;AAAA,IACrF;AAAA,EACF;AAEA,SAAO;AACT;", + "names": ["sha256", "bytesToHex", "bytesToHex", "i", "bytesToHex", "validateEvent", "sha256", "bytesToHex"] +} diff --git a/node_modules/nostr-tools/lib/esm/nip99.js b/node_modules/nostr-tools/lib/esm/nip99.js new file mode 100644 index 0000000..b18d7ce --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip99.js @@ -0,0 +1,130 @@ +// kinds.ts +var ClassifiedListing = 30402; +var DraftClassifiedListing = 30403; + +// nip99.ts +function validateEvent(event) { + if (![ClassifiedListing, DraftClassifiedListing].includes(event.kind)) + return false; + const requiredTags = ["d", "title", "summary", "location", "published_at", "price"]; + const requiredTagCount = requiredTags.length; + const tagCounts = {}; + if (event.tags.length < requiredTagCount) + return false; + for (const tag of event.tags) { + if (tag.length < 2) + return false; + const [tagName, ...tagValues] = tag; + if (tagName == "published_at") { + const timestamp = parseInt(tagValues[0]); + if (isNaN(timestamp)) + return false; + } else if (tagName == "price") { + if (tagValues.length < 2) + return false; + const price = parseInt(tagValues[0]); + if (isNaN(price) || tagValues[1].length != 3) + return false; + } else if ((tagName == "e" || tagName == "a") && tag.length != 3) { + return false; + } + if (requiredTags.includes(tagName)) { + tagCounts[tagName] = (tagCounts[tagName] || 0) + 1; + } + } + return Object.values(tagCounts).every((count) => count == 1) && Object.keys(tagCounts).length == requiredTagCount; +} +function parseEvent(event) { + if (!validateEvent(event)) { + throw new Error("Invalid event"); + } + const listing = { + isDraft: event.kind === DraftClassifiedListing, + title: "", + summary: "", + content: event.content, + publishedAt: "", + location: "", + price: { + amount: "", + currency: "" + }, + images: [], + hashtags: [], + additionalTags: {} + }; + for (let i = 0; i < event.tags.length; i++) { + const tag = event.tags[i]; + const [tagName, ...tagValues] = tag; + if (tagName == "title") { + listing.title = tagValues[0]; + } else if (tagName == "summary") { + listing.summary = tagValues[0]; + } else if (tagName == "published_at") { + listing.publishedAt = tagValues[0]; + } else if (tagName == "location") { + listing.location = tagValues[0]; + } else if (tagName == "price") { + listing.price.amount = tagValues[0]; + listing.price.currency = tagValues[1]; + if (tagValues.length == 3) { + listing.price.frequency = tagValues[2]; + } + } else if (tagName == "image") { + listing.images.push({ + url: tagValues[0], + dimensions: tagValues?.[1] ?? void 0 + }); + } else if (tagName == "t") { + listing.hashtags.push(tagValues[0]); + } else if (tagName == "e" || tagName == "a") { + listing.additionalTags[tagName] = [...tagValues]; + } + } + return listing; +} +function generateEventTemplate(listing) { + const priceTag = ["price", listing.price.amount, listing.price.currency]; + if (listing.price.frequency) + priceTag.push(listing.price.frequency); + const tags = [ + ["d", listing.title.trim().toLowerCase().replace(/ /g, "-")], + ["title", listing.title], + ["published_at", listing.publishedAt], + ["summary", listing.summary], + ["location", listing.location], + priceTag + ]; + for (let i = 0; i < listing.images.length; i++) { + const image = listing.images[i]; + const imageTag = ["image", image.url]; + if (image.dimensions) + imageTag.push(image.dimensions); + tags.push(imageTag); + } + for (let i = 0; i < listing.hashtags.length; i++) { + const t = listing.hashtags[i]; + tags.push(["t", t]); + } + for (const [key, value] of Object.entries(listing.additionalTags)) { + if (Array.isArray(value)) { + for (let i = 0; i < value.length; i++) { + const val = value[i]; + tags.push([key, val]); + } + } else { + tags.push([key, value]); + } + } + return { + kind: listing.isDraft ? DraftClassifiedListing : ClassifiedListing, + content: listing.content, + tags, + created_at: Math.floor(Date.now() / 1e3) + }; +} +export { + generateEventTemplate, + parseEvent, + validateEvent +}; diff --git a/node_modules/nostr-tools/lib/esm/nip99.js.map b/node_modules/nostr-tools/lib/esm/nip99.js.map new file mode 100644 index 0000000..2277cd2 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nip99.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../kinds.ts", "../../nip99.ts"], + "sourcesContent": ["import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { Event, EventTemplate } from './core.ts'\nimport { ClassifiedListing, DraftClassifiedListing } from './kinds.ts'\n\n/**\n * Represents the details of a price.\n * @example { amount: '100', currency: 'USD', frequency: 'month' }\n * @example { amount: '100', currency: 'EUR' }\n */\nexport type PriceDetails = {\n /**\n * The amount of the price.\n */\n amount: string\n /**\n * The currency of the price in 3-letter ISO 4217 format.\n * @example 'USD'\n */\n currency: string\n /**\n * The optional frequency of payment.\n * Can be one of: 'hour', 'day', 'week', 'month', 'year', or a custom string.\n */\n frequency?: string\n}\n\n/**\n * Represents a classified listing object.\n */\nexport type ClassifiedListingObject = {\n /**\n * Whether the listing is a draft or not.\n */\n isDraft: boolean\n /**\n * A title of the listing.\n */\n title: string\n /**\n * A short summary or tagline.\n */\n summary: string\n /**\n * A description in Markdown format.\n */\n content: string\n /**\n * Timestamp in unix seconds of when the listing was published.\n */\n publishedAt: string\n /**\n * Location of the listing.\n * @example 'NYC'\n */\n location: string\n /**\n * Price details.\n */\n price: PriceDetails\n /**\n * Images of the listing with optional dimensions.\n */\n images: Array<{\n url: string\n dimensions?: string\n }>\n /**\n * Tags/Hashtags (i.e. categories, keywords, etc.)\n */\n hashtags: string[]\n /**\n * Other standard tags.\n * @example \"g\", a geohash for more precise location\n */\n additionalTags: Record\n}\n\n/**\n * Validates an event to ensure it is a valid classified listing event.\n * @param event - The event to validate.\n * @returns True if the event is valid, false otherwise.\n */\nexport function validateEvent(event: Event): boolean {\n if (![ClassifiedListing, DraftClassifiedListing].includes(event.kind)) return false\n\n const requiredTags = ['d', 'title', 'summary', 'location', 'published_at', 'price']\n const requiredTagCount = requiredTags.length\n const tagCounts: Record = {}\n\n if (event.tags.length < requiredTagCount) return false\n\n for (const tag of event.tags) {\n if (tag.length < 2) return false\n\n const [tagName, ...tagValues] = tag\n\n if (tagName == 'published_at') {\n const timestamp = parseInt(tagValues[0])\n if (isNaN(timestamp)) return false\n } else if (tagName == 'price') {\n if (tagValues.length < 2) return false\n\n const price = parseInt(tagValues[0])\n if (isNaN(price) || tagValues[1].length != 3) return false\n } else if ((tagName == 'e' || tagName == 'a') && tag.length != 3) {\n return false\n }\n\n if (requiredTags.includes(tagName)) {\n tagCounts[tagName] = (tagCounts[tagName] || 0) + 1\n }\n }\n\n return Object.values(tagCounts).every(count => count == 1) && Object.keys(tagCounts).length == requiredTagCount\n}\n\n/**\n * Parses an event and returns a classified listing object.\n * @param event - The event to parse.\n * @returns The classified listing object.\n * @throws Error if the event is invalid.\n */\nexport function parseEvent(event: Event): ClassifiedListingObject {\n if (!validateEvent(event)) {\n throw new Error('Invalid event')\n }\n\n const listing: ClassifiedListingObject = {\n isDraft: event.kind === DraftClassifiedListing,\n title: '',\n summary: '',\n content: event.content,\n publishedAt: '',\n location: '',\n price: {\n amount: '',\n currency: '',\n },\n images: [],\n hashtags: [],\n additionalTags: {},\n }\n\n for (let i = 0; i < event.tags.length; i++) {\n const tag = event.tags[i]\n const [tagName, ...tagValues] = tag\n\n if (tagName == 'title') {\n listing.title = tagValues[0]\n } else if (tagName == 'summary') {\n listing.summary = tagValues[0]\n } else if (tagName == 'published_at') {\n listing.publishedAt = tagValues[0]\n } else if (tagName == 'location') {\n listing.location = tagValues[0]\n } else if (tagName == 'price') {\n listing.price.amount = tagValues[0]\n listing.price.currency = tagValues[1]\n\n if (tagValues.length == 3) {\n listing.price.frequency = tagValues[2]\n }\n } else if (tagName == 'image') {\n listing.images.push({\n url: tagValues[0],\n dimensions: tagValues?.[1] ?? undefined,\n })\n } else if (tagName == 't') {\n listing.hashtags.push(tagValues[0])\n } else if (tagName == 'e' || tagName == 'a') {\n listing.additionalTags[tagName] = [...tagValues]\n }\n }\n\n return listing\n}\n\n/**\n * Generates an event template based on a classified listing object.\n *\n * @param listing - The classified listing object.\n * @returns The event template.\n */\nexport function generateEventTemplate(listing: ClassifiedListingObject): EventTemplate {\n const priceTag = ['price', listing.price.amount, listing.price.currency]\n if (listing.price.frequency) priceTag.push(listing.price.frequency)\n\n const tags: string[][] = [\n ['d', listing.title.trim().toLowerCase().replace(/ /g, '-')],\n ['title', listing.title],\n ['published_at', listing.publishedAt],\n ['summary', listing.summary],\n ['location', listing.location],\n priceTag,\n ]\n\n for (let i = 0; i < listing.images.length; i++) {\n const image = listing.images[i]\n const imageTag = ['image', image.url]\n if (image.dimensions) imageTag.push(image.dimensions)\n\n tags.push(imageTag)\n }\n\n for (let i = 0; i < listing.hashtags.length; i++) {\n const t = listing.hashtags[i]\n\n tags.push(['t', t])\n }\n\n for (const [key, value] of Object.entries(listing.additionalTags)) {\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n const val = value[i]\n\n tags.push([key, val])\n }\n } else {\n tags.push([key, value])\n }\n }\n\n return {\n kind: listing.isDraft ? DraftClassifiedListing : ClassifiedListing,\n content: listing.content,\n tags,\n created_at: Math.floor(Date.now() / 1000),\n }\n}\n"], + "mappings": ";AA+KO,IAAM,oBAAoB;AAE1B,IAAM,yBAAyB;;;AChG/B,SAAS,cAAc,OAAuB;AACnD,MAAI,CAAC,CAAC,mBAAmB,sBAAsB,EAAE,SAAS,MAAM,IAAI;AAAG,WAAO;AAE9E,QAAM,eAAe,CAAC,KAAK,SAAS,WAAW,YAAY,gBAAgB,OAAO;AAClF,QAAM,mBAAmB,aAAa;AACtC,QAAM,YAAoC,CAAC;AAE3C,MAAI,MAAM,KAAK,SAAS;AAAkB,WAAO;AAEjD,aAAW,OAAO,MAAM,MAAM;AAC5B,QAAI,IAAI,SAAS;AAAG,aAAO;AAE3B,UAAM,CAAC,YAAY,SAAS,IAAI;AAEhC,QAAI,WAAW,gBAAgB;AAC7B,YAAM,YAAY,SAAS,UAAU,EAAE;AACvC,UAAI,MAAM,SAAS;AAAG,eAAO;AAAA,IAC/B,WAAW,WAAW,SAAS;AAC7B,UAAI,UAAU,SAAS;AAAG,eAAO;AAEjC,YAAM,QAAQ,SAAS,UAAU,EAAE;AACnC,UAAI,MAAM,KAAK,KAAK,UAAU,GAAG,UAAU;AAAG,eAAO;AAAA,IACvD,YAAY,WAAW,OAAO,WAAW,QAAQ,IAAI,UAAU,GAAG;AAChE,aAAO;AAAA,IACT;AAEA,QAAI,aAAa,SAAS,OAAO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AAK,KAAK,CAAC,KAAK,KAAK,CAAC;AAAA,IACxB;AAAA,EACF;AAEA,SAAO;AAAA,IACL,MAAM,QAAQ,UAAU,yBAAyB;AAAA,IACjD,SAAS,QAAQ;AAAA,IACjB;AAAA,IACA,YAAY,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAAA,EAC1C;AACF;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/esm/nipb7.js b/node_modules/nostr-tools/lib/esm/nipb7.js new file mode 100644 index 0000000..f89dba1 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nipb7.js @@ -0,0 +1,163 @@ +// nipb7.ts +import { sha256 } from "@noble/hashes/sha256"; + +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// nipb7.ts +var BlossomClient = class { + mediaserver; + signer; + constructor(mediaserver, signer) { + if (!mediaserver.startsWith("http")) { + mediaserver = "https://" + mediaserver; + } + this.mediaserver = mediaserver.replace(/\/$/, "") + "/"; + this.signer = signer; + } + async httpCall(method, url, contentType, addAuthorization, body, result) { + const headers = {}; + if (contentType) { + headers["Content-Type"] = contentType; + } + if (addAuthorization) { + const auth = await addAuthorization(); + if (auth) { + headers["Authorization"] = auth; + } + } + const response = await fetch(this.mediaserver + url, { + method, + headers, + body + }); + if (response.status >= 300) { + const reason = response.headers.get("X-Reason") || response.statusText; + throw new Error(`${url} returned an error (${response.status}): ${reason}`); + } + if (result !== null && response.headers.get("content-type")?.includes("application/json")) { + return await response.json(); + } + return response; + } + async authorizationHeader(modify) { + const now = Math.floor(Date.now() / 1e3); + const event = { + created_at: now, + kind: 24242, + content: "blossom stuff", + tags: [["expiration", String(now + 60)]] + }; + if (modify) { + modify(event); + } + try { + const signedEvent = await this.signer.signEvent(event); + const eventJson = JSON.stringify(signedEvent); + return "Nostr " + btoa(eventJson); + } catch (error) { + return ""; + } + } + isValid32ByteHex(hash) { + return /^[a-f0-9]{64}$/i.test(hash); + } + async check(hash) { + if (!this.isValid32ByteHex(hash)) { + throw new Error(`${hash} is not a valid 32-byte hex string`); + } + try { + await this.httpCall("HEAD", hash); + } catch (error) { + throw new Error(`failed to check for ${hash}: ${error}`); + } + } + async uploadBlob(file, contentType) { + const hash = bytesToHex(sha256(new Uint8Array(await file.arrayBuffer()))); + const actualContentType = contentType || file.type || "application/octet-stream"; + const bd = await this.httpCall( + "PUT", + "upload", + actualContentType, + () => this.authorizationHeader((evt) => { + evt.tags.push(["t", "upload"]); + evt.tags.push(["x", hash]); + }), + file, + {} + ); + return bd; + } + async uploadFile(file) { + return this.uploadBlob(file, file.type); + } + async download(hash) { + if (!this.isValid32ByteHex(hash)) { + throw new Error(`${hash} is not a valid 32-byte hex string`); + } + const authHeader = await this.authorizationHeader((evt) => { + evt.tags.push(["t", "get"]); + evt.tags.push(["x", hash]); + }); + const response = await fetch(this.mediaserver + hash, { + method: "GET", + headers: { + Authorization: authHeader + } + }); + if (response.status >= 300) { + throw new Error(`${hash} is not present in ${this.mediaserver}: ${response.status}`); + } + return await response.arrayBuffer(); + } + async downloadAsBlob(hash) { + const arrayBuffer = await this.download(hash); + return new Blob([arrayBuffer]); + } + async list() { + const pubkey = await this.signer.getPublicKey(); + if (!this.isValid32ByteHex(pubkey)) { + throw new Error(`pubkey ${pubkey} is not valid`); + } + try { + const bds = await this.httpCall( + "GET", + `list/${pubkey}`, + void 0, + () => this.authorizationHeader((evt) => { + evt.tags.push(["t", "list"]); + }), + void 0, + [] + ); + return bds; + } catch (error) { + throw new Error(`failed to list blobs: ${error}`); + } + } + async delete(hash) { + if (!this.isValid32ByteHex(hash)) { + throw new Error(`${hash} is not a valid 32-byte hex string`); + } + try { + await this.httpCall( + "DELETE", + hash, + void 0, + () => this.authorizationHeader((evt) => { + evt.tags.push(["t", "delete"]); + evt.tags.push(["x", hash]); + }), + void 0, + null + ); + } catch (error) { + throw new Error(`failed to delete ${hash}: ${error}`); + } + } +}; +export { + BlossomClient +}; diff --git a/node_modules/nostr-tools/lib/esm/nipb7.js.map b/node_modules/nostr-tools/lib/esm/nipb7.js.map new file mode 100644 index 0000000..ac9ab85 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/nipb7.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nipb7.ts", "../../utils.ts"], + "sourcesContent": ["import { sha256 } from '@noble/hashes/sha256'\nimport { EventTemplate } from './core.ts'\nimport { Signer } from './signer.ts'\nimport { bytesToHex } from './utils.ts'\n\nexport type BlobDescriptor = {\n url: string\n sha256: string\n size: number\n type: string\n uploaded: number\n}\n\nexport class BlossomClient {\n private mediaserver: string\n private signer: Signer\n\n constructor(mediaserver: string, signer: Signer) {\n if (!mediaserver.startsWith('http')) {\n mediaserver = 'https://' + mediaserver\n }\n this.mediaserver = mediaserver.replace(/\\/$/, '') + '/'\n this.signer = signer\n }\n\n private async httpCall(\n method: string,\n url: string,\n contentType?: string,\n addAuthorization?: () => Promise,\n body?: File | Blob,\n result?: any,\n ): Promise {\n const headers: { [_: string]: string } = {}\n\n if (contentType) {\n headers['Content-Type'] = contentType\n }\n\n if (addAuthorization) {\n const auth = await addAuthorization()\n if (auth) {\n headers['Authorization'] = auth\n }\n }\n\n const response = await fetch(this.mediaserver + url, {\n method,\n headers,\n body,\n })\n\n if (response.status >= 300) {\n const reason = response.headers.get('X-Reason') || response.statusText\n throw new Error(`${url} returned an error (${response.status}): ${reason}`)\n }\n\n if (result !== null && response.headers.get('content-type')?.includes('application/json')) {\n return await response.json()\n }\n\n return response\n }\n\n private async authorizationHeader(modify?: (event: EventTemplate) => void): Promise {\n const now = Math.floor(Date.now() / 1000)\n const event: EventTemplate = {\n created_at: now,\n kind: 24242,\n content: 'blossom stuff',\n tags: [['expiration', String(now + 60)]],\n }\n\n if (modify) {\n modify(event)\n }\n\n try {\n const signedEvent = await this.signer.signEvent(event)\n const eventJson = JSON.stringify(signedEvent)\n return 'Nostr ' + btoa(eventJson)\n } catch (error) {\n return ''\n }\n }\n\n private isValid32ByteHex(hash: string): boolean {\n return /^[a-f0-9]{64}$/i.test(hash)\n }\n\n async check(hash: string): Promise {\n if (!this.isValid32ByteHex(hash)) {\n throw new Error(`${hash} is not a valid 32-byte hex string`)\n }\n\n try {\n await this.httpCall('HEAD', hash)\n } catch (error) {\n throw new Error(`failed to check for ${hash}: ${error}`)\n }\n }\n\n async uploadBlob(file: File | Blob, contentType?: string): Promise {\n const hash = bytesToHex(sha256(new Uint8Array(await file.arrayBuffer())))\n const actualContentType = contentType || file.type || 'application/octet-stream'\n\n const bd = await this.httpCall(\n 'PUT',\n 'upload',\n actualContentType,\n () =>\n this.authorizationHeader(evt => {\n evt.tags.push(['t', 'upload'])\n evt.tags.push(['x', hash])\n }),\n file,\n {},\n )\n\n return bd\n }\n\n async uploadFile(file: File): Promise {\n return this.uploadBlob(file, file.type)\n }\n\n async download(hash: string): Promise {\n if (!this.isValid32ByteHex(hash)) {\n throw new Error(`${hash} is not a valid 32-byte hex string`)\n }\n\n const authHeader = await this.authorizationHeader(evt => {\n evt.tags.push(['t', 'get'])\n evt.tags.push(['x', hash])\n })\n\n const response = await fetch(this.mediaserver + hash, {\n method: 'GET',\n headers: {\n Authorization: authHeader,\n },\n })\n\n if (response.status >= 300) {\n throw new Error(`${hash} is not present in ${this.mediaserver}: ${response.status}`)\n }\n\n return await response.arrayBuffer()\n }\n\n async downloadAsBlob(hash: string): Promise {\n const arrayBuffer = await this.download(hash)\n return new Blob([arrayBuffer])\n }\n\n async list(): Promise {\n const pubkey = await this.signer.getPublicKey()\n\n if (!this.isValid32ByteHex(pubkey)) {\n throw new Error(`pubkey ${pubkey} is not valid`)\n }\n\n try {\n const bds = await this.httpCall(\n 'GET',\n `list/${pubkey}`,\n undefined,\n () =>\n this.authorizationHeader(evt => {\n evt.tags.push(['t', 'list'])\n }),\n undefined,\n [],\n )\n return bds\n } catch (error) {\n throw new Error(`failed to list blobs: ${error}`)\n }\n }\n\n async delete(hash: string): Promise {\n if (!this.isValid32ByteHex(hash)) {\n throw new Error(`${hash} is not a valid 32-byte hex string`)\n }\n\n try {\n await this.httpCall(\n 'DELETE',\n hash,\n undefined,\n () =>\n this.authorizationHeader(evt => {\n evt.tags.push(['t', 'delete'])\n evt.tags.push(['x', hash])\n }),\n undefined,\n null,\n )\n } catch (error) {\n throw new Error(`failed to delete ${hash}: ${error}`)\n }\n }\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n"], + "mappings": ";AAAA,SAAS,cAAc;;;ACKvB,SAAS,YAAY,kBAAkB;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;;;ADUjD,IAAM,gBAAN,MAAoB;AAAA,EACjB;AAAA,EACA;AAAA,EAER,YAAY,aAAqB,QAAgB;AAC/C,QAAI,CAAC,YAAY,WAAW,MAAM,GAAG;AACnC,oBAAc,aAAa;AAAA,IAC7B;AACA,SAAK,cAAc,YAAY,QAAQ,OAAO,EAAE,IAAI;AACpD,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,MAAc,SACZ,QACA,KACA,aACA,kBACA,MACA,QACc;AACd,UAAM,UAAmC,CAAC;AAE1C,QAAI,aAAa;AACf,cAAQ,kBAAkB;AAAA,IAC5B;AAEA,QAAI,kBAAkB;AACpB,YAAM,OAAO,MAAM,iBAAiB;AACpC,UAAI,MAAM;AACR,gBAAQ,mBAAmB;AAAA,MAC7B;AAAA,IACF;AAEA,UAAM,W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M,KAAK,OAAO,aAAa;AAE9C,QAAI,CAAC,KAAK,iBAAiB,MAAM,GAAG;AAClC,YAAM,IAAI,MAAM,UAAU,qBAAqB;AAAA,IACjD;AAEA,QAAI;AACF,YAAM,MAAM,MAAM,KAAK;AAAA,QACrB;AAAA,QACA,QAAQ;AAAA,QACR;AAAA,QACA,MACE,KAAK,oBAAoB,SAAO;AAC9B,cAAI,KAAK,KAAK,CAAC,KAAK,MAAM,CAAC;AAAA,QAC7B,CAAC;AAAA,QACH;AAAA,QACA,CAAC;AAAA,MACH;AACA,aAAO;AAAA,IACT,SAAS,OAAP;AACA,YAAM,IAAI,MAAM,yBAAyB,OAAO;AAAA,IAClD;AAAA,EACF;AAAA,EAEA,MAAM,OAAO,MAA6B;AACxC,QAAI,CAAC,KAAK,iBAAiB,IAAI,GAAG;AAChC,YAAM,IAAI,MAAM,GAAG,wCAAwC;AAAA,IAC7D;AAEA,QAAI;AACF,YAAM,KAAK;AAAA,QACT;AAAA,QACA;AAAA,QACA;AAAA,QACA,MACE,KAAK,oBAAoB,SAAO;AAC9B,cAAI,KAAK,KAAK,CAAC,KAAK,QAAQ,CAAC;AAC7B,cAAI,KAAK,KAAK,CAAC,KAAK,IAAI,CAAC;AAAA,QAC3B,CAAC;AAAA,QACH;AAAA,QACA;AAAA,MACF;AAAA,IACF,SAAS,OAAP;AACA,YAAM,IAAI,MAAM,oBAAoB,SAAS,OAAO;AAAA,IACtD;AAAA,EACF;AACF;", + "names": [] +} diff --git a/node_modules/nostr-tools/lib/esm/pool.js b/node_modules/nostr-tools/lib/esm/pool.js new file mode 100644 index 0000000..eb58ec4 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/pool.js @@ -0,0 +1,870 @@ +// pure.ts +import { schnorr } from "@noble/curves/secp256k1"; +import { bytesToHex as bytesToHex2 } from "@noble/hashes/utils"; + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +import { sha256 } from "@noble/hashes/sha256"; + +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); +function normalizeURL(url) { + try { + if (url.indexOf("://") === -1) + url = "wss://" + url; + let p = new URL(url); + p.pathname = p.pathname.replace(/\/+/g, "/"); + if (p.pathname.endsWith("/")) + p.pathname = p.pathname.slice(0, -1); + if (p.port === "80" && p.protocol === "ws:" || p.port === "443" && p.protocol === "wss:") + p.port = ""; + p.searchParams.sort(); + p.hash = ""; + return p.toString(); + } catch (e) { + throw new Error(`Invalid URL: ${url}`); + } +} +var QueueNode = class { + value; + next = null; + prev = null; + constructor(message) { + this.value = message; + } +}; +var Queue = class { + first; + last; + constructor() { + this.first = null; + this.last = null; + } + enqueue(value) { + const newNode = new QueueNode(value); + if (!this.last) { + this.first = newNode; + this.last = newNode; + } else if (this.last === this.first) { + this.last = newNode; + this.last.prev = this.first; + this.first.next = newNode; + } else { + newNode.prev = this.last; + this.last.next = newNode; + this.last = newNode; + } + return true; + } + dequeue() { + if (!this.first) + return null; + if (this.first === this.last) { + const target2 = this.first; + this.first = null; + this.last = null; + return target2.value; + } + const target = this.first; + this.first = target.next; + if (this.first) { + this.first.prev = null; + } + return target.value; + } +}; + +// pure.ts +var JS = class { + generateSecretKey() { + return schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return bytesToHex2(schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = bytesToHex2(schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = bytesToHex2(schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = sha256(utf8Encoder.encode(serializeEvent(event))); + return bytesToHex2(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// kinds.ts +var ClientAuth = 22242; + +// filter.ts +function matchFilter(filter, event) { + if (filter.ids && filter.ids.indexOf(event.id) === -1) { + return false; + } + if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) { + return false; + } + if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) { + return false; + } + for (let f in filter) { + if (f[0] === "#") { + let tagName = f.slice(1); + let values = filter[`#${tagName}`]; + if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values.indexOf(v) !== -1)) + return false; + } + } + if (filter.since && event.created_at < filter.since) + return false; + if (filter.until && event.created_at > filter.until) + return false; + return true; +} +function matchFilters(filters, event) { + for (let i2 = 0; i2 < filters.length; i2++) { + if (matchFilter(filters[i2], event)) { + return true; + } + } + return false; +} + +// fakejson.ts +function getHex64(json, field) { + let len = field.length + 3; + let idx = json.indexOf(`"${field}":`) + len; + let s = json.slice(idx).indexOf(`"`) + idx + 1; + return json.slice(s, s + 64); +} +function getSubscriptionId(json) { + let idx = json.slice(0, 22).indexOf(`"EVENT"`); + if (idx === -1) + return null; + let pstart = json.slice(idx + 7 + 1).indexOf(`"`); + if (pstart === -1) + return null; + let start = idx + 7 + 1 + pstart; + let pend = json.slice(start + 1, 80).indexOf(`"`); + if (pend === -1) + return null; + let end = start + 1 + pend; + return json.slice(start + 1, end); +} + +// nip42.ts +function makeAuthEvent(relayURL, challenge) { + return { + kind: ClientAuth, + created_at: Math.floor(Date.now() / 1e3), + tags: [ + ["relay", relayURL], + ["challenge", challenge] + ], + content: "" + }; +} + +// helpers.ts +async function yieldThread() { + return new Promise((resolve) => { + const ch = new MessageChannel(); + const handler = () => { + ch.port1.removeEventListener("message", handler); + resolve(); + }; + ch.port1.addEventListener("message", handler); + ch.port2.postMessage(0); + ch.port1.start(); + }); +} +var alwaysTrue = (t) => { + t[verifiedSymbol] = true; + return true; +}; + +// abstract-relay.ts +var SendingOnClosedConnection = class extends Error { + constructor(message, relay) { + super(`Tried to send message '${message} on a closed connection to ${relay}.`); + this.name = "SendingOnClosedConnection"; + } +}; +var AbstractRelay = class { + url; + _connected = false; + onclose = null; + onnotice = (msg) => console.debug(`NOTICE from ${this.url}: ${msg}`); + baseEoseTimeout = 4400; + connectionTimeout = 4400; + publishTimeout = 4400; + pingFrequency = 2e4; + pingTimeout = 2e4; + openSubs = /* @__PURE__ */ new Map(); + enablePing; + connectionTimeoutHandle; + connectionPromise; + openCountRequests = /* @__PURE__ */ new Map(); + openEventPublishes = /* @__PURE__ */ new Map(); + ws; + incomingMessageQueue = new Queue(); + queueRunning = false; + challenge; + authPromise; + serial = 0; + verifyEvent; + _WebSocket; + constructor(url, opts) { + this.url = normalizeURL(url); + this.verifyEvent = opts.verifyEvent; + this._WebSocket = opts.websocketImplementation || WebSocket; + this.enablePing = opts.enablePing; + } + static async connect(url, opts) { + const relay = new AbstractRelay(url, opts); + await relay.connect(); + return relay; + } + closeAllSubscriptions(reason) { + for (let [_, sub] of this.openSubs) { + sub.close(reason); + } + this.openSubs.clear(); + for (let [_, ep] of this.openEventPublishes) { + ep.reject(new Error(reason)); + } + this.openEventPublishes.clear(); + for (let [_, cr] of this.openCountRequests) { + cr.reject(new Error(reason)); + } + this.openCountRequests.clear(); + } + get connected() { + return this._connected; + } + async connect() { + if (this.connectionPromise) + return this.connectionPromise; + this.challenge = void 0; + this.authPromise = void 0; + this.connectionPromise = new Promise((resolve, reject) => { + this.connectionTimeoutHandle = setTimeout(() => { + reject("connection timed out"); + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection timed out"); + }, this.connectionTimeout); + try { + this.ws = new this._WebSocket(this.url); + } catch (err) { + clearTimeout(this.connectionTimeoutHandle); + reject(err); + return; + } + this.ws.onopen = () => { + clearTimeout(this.connectionTimeoutHandle); + this._connected = true; + if (this.enablePing) { + this.pingpong(); + } + resolve(); + }; + this.ws.onerror = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket error"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection errored"); + } + }; + this.ws.onclose = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket closed"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection closed"); + } + }; + this.ws.onmessage = this._onmessage.bind(this); + }); + return this.connectionPromise; + } + async waitForPingPong() { + return new Promise((res, err) => { + ; + this.ws && this.ws.on && this.ws.on("pong", () => res(true)) || err("ws can't listen for pong"); + this.ws && this.ws.ping && this.ws.ping(); + }); + } + async waitForDummyReq() { + return new Promise((resolve, _) => { + const sub = this.subscribe([{ ids: ["a".repeat(64)] }], { + oneose: () => { + sub.close(); + resolve(true); + }, + eoseTimeout: this.pingTimeout + 1e3 + }); + }); + } + async pingpong() { + if (this.ws?.readyState === 1) { + const result = await Promise.any([ + this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(), + new Promise((res) => setTimeout(() => res(false), this.pingTimeout)) + ]); + if (result) { + setTimeout(() => this.pingpong(), this.pingFrequency); + } else { + this.closeAllSubscriptions("pingpong timed out"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + } + } + async runQueue() { + this.queueRunning = true; + while (true) { + if (false === this.handleNext()) { + break; + } + await yieldThread(); + } + this.queueRunning = false; + } + handleNext() { + const json = this.incomingMessageQueue.dequeue(); + if (!json) { + return false; + } + const subid = getSubscriptionId(json); + if (subid) { + const so = this.openSubs.get(subid); + if (!so) { + return; + } + const id = getHex64(json, "id"); + const alreadyHave = so.alreadyHaveEvent?.(id); + so.receivedEvent?.(this, id); + if (alreadyHave) { + return; + } + } + try { + let data = JSON.parse(json); + switch (data[0]) { + case "EVENT": { + const so = this.openSubs.get(data[1]); + const event = data[2]; + if (this.verifyEvent(event) && matchFilters(so.filters, event)) { + so.onevent(event); + } + return; + } + case "COUNT": { + const id = data[1]; + const payload = data[2]; + const cr = this.openCountRequests.get(id); + if (cr) { + cr.resolve(payload.count); + this.openCountRequests.delete(id); + } + return; + } + case "EOSE": { + const so = this.openSubs.get(data[1]); + if (!so) + return; + so.receivedEose(); + return; + } + case "OK": { + const id = data[1]; + const ok = data[2]; + const reason = data[3]; + const ep = this.openEventPublishes.get(id); + if (ep) { + clearTimeout(ep.timeout); + if (ok) + ep.resolve(reason); + else + ep.reject(new Error(reason)); + this.openEventPublishes.delete(id); + } + return; + } + case "CLOSED": { + const id = data[1]; + const so = this.openSubs.get(id); + if (!so) + return; + so.closed = true; + so.close(data[2]); + return; + } + case "NOTICE": + this.onnotice(data[1]); + return; + case "AUTH": { + this.challenge = data[1]; + return; + } + } + } catch (err) { + return; + } + } + async send(message) { + if (!this.connectionPromise) + throw new SendingOnClosedConnection(message, this.url); + this.connectionPromise.then(() => { + this.ws?.send(message); + }); + } + async auth(signAuthEvent) { + const challenge = this.challenge; + if (!challenge) + throw new Error("can't perform auth, no challenge was received"); + if (this.authPromise) + return this.authPromise; + this.authPromise = new Promise(async (resolve, reject) => { + try { + let evt = await signAuthEvent(makeAuthEvent(this.url, challenge)); + let timeout = setTimeout(() => { + let ep = this.openEventPublishes.get(evt.id); + if (ep) { + ep.reject(new Error("auth timed out")); + this.openEventPublishes.delete(evt.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(evt.id, { resolve, reject, timeout }); + this.send('["AUTH",' + JSON.stringify(evt) + "]"); + } catch (err) { + console.warn("subscribe auth function failed:", err); + } + }); + return this.authPromise; + } + async publish(event) { + const ret = new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + const ep = this.openEventPublishes.get(event.id); + if (ep) { + ep.reject(new Error("publish timed out")); + this.openEventPublishes.delete(event.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(event.id, { resolve, reject, timeout }); + }); + this.send('["EVENT",' + JSON.stringify(event) + "]"); + return ret; + } + async count(filters, params) { + this.serial++; + const id = params?.id || "count:" + this.serial; + const ret = new Promise((resolve, reject) => { + this.openCountRequests.set(id, { resolve, reject }); + }); + this.send('["COUNT","' + id + '",' + JSON.stringify(filters).substring(1)); + return ret; + } + subscribe(filters, params) { + const subscription = this.prepareSubscription(filters, params); + subscription.fire(); + return subscription; + } + prepareSubscription(filters, params) { + this.serial++; + const id = params.id || (params.label ? params.label + ":" : "sub:") + this.serial; + const subscription = new Subscription(this, id, filters, params); + this.openSubs.set(id, subscription); + return subscription; + } + close() { + this.closeAllSubscriptions("relay connection closed by us"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + _onmessage(ev) { + this.incomingMessageQueue.enqueue(ev.data); + if (!this.queueRunning) { + this.runQueue(); + } + } +}; +var Subscription = class { + relay; + id; + closed = false; + eosed = false; + filters; + alreadyHaveEvent; + receivedEvent; + onevent; + oneose; + onclose; + eoseTimeout; + eoseTimeoutHandle; + constructor(relay, id, filters, params) { + this.relay = relay; + this.filters = filters; + this.id = id; + this.alreadyHaveEvent = params.alreadyHaveEvent; + this.receivedEvent = params.receivedEvent; + this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout; + this.oneose = params.oneose; + this.onclose = params.onclose; + this.onevent = params.onevent || ((event) => { + console.warn( + `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`, + event + ); + }); + } + fire() { + this.relay.send('["REQ","' + this.id + '",' + JSON.stringify(this.filters).substring(1)); + this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout); + } + receivedEose() { + if (this.eosed) + return; + clearTimeout(this.eoseTimeoutHandle); + this.eosed = true; + this.oneose?.(); + } + close(reason = "closed by caller") { + if (!this.closed && this.relay.connected) { + try { + this.relay.send('["CLOSE",' + JSON.stringify(this.id) + "]"); + } catch (err) { + if (err instanceof SendingOnClosedConnection) { + } else { + throw err; + } + } + this.closed = true; + } + this.relay.openSubs.delete(this.id); + this.onclose?.(reason); + } +}; + +// abstract-pool.ts +var AbstractSimplePool = class { + relays = /* @__PURE__ */ new Map(); + seenOn = /* @__PURE__ */ new Map(); + trackRelays = false; + verifyEvent; + enablePing; + trustedRelayURLs = /* @__PURE__ */ new Set(); + _WebSocket; + constructor(opts) { + this.verifyEvent = opts.verifyEvent; + this._WebSocket = opts.websocketImplementation; + this.enablePing = opts.enablePing; + } + async ensureRelay(url, params) { + url = normalizeURL(url); + let relay = this.relays.get(url); + if (!relay) { + relay = new AbstractRelay(url, { + verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent, + websocketImplementation: this._WebSocket, + enablePing: this.enablePing + }); + relay.onclose = () => { + this.relays.delete(url); + }; + if (params?.connectionTimeout) + relay.connectionTimeout = params.connectionTimeout; + this.relays.set(url, relay); + } + await relay.connect(); + return relay; + } + close(relays) { + relays.map(normalizeURL).forEach((url) => { + this.relays.get(url)?.close(); + this.relays.delete(url); + }); + } + subscribe(relays, filter, params) { + params.onauth = params.onauth || params.doauth; + const request = []; + for (let i2 = 0; i2 < relays.length; i2++) { + const url = normalizeURL(relays[i2]); + if (!request.find((r) => r.url === url)) { + request.push({ url, filter }); + } + } + return this.subscribeMap(request, params); + } + subscribeMany(relays, filters, params) { + params.onauth = params.onauth || params.doauth; + const request = []; + const uniqUrls = []; + for (let i2 = 0; i2 < relays.length; i2++) { + const url = normalizeURL(relays[i2]); + if (uniqUrls.indexOf(url) === -1) { + for (let f = 0; f < filters.length; f++) { + request.push({ url, filter: filters[f] }); + } + } + } + return this.subscribeMap(request, params); + } + subscribeMap(requests, params) { + params.onauth = params.onauth || params.doauth; + if (this.trackRelays) { + params.receivedEvent = (relay, id) => { + let set = this.seenOn.get(id); + if (!set) { + set = /* @__PURE__ */ new Set(); + this.seenOn.set(id, set); + } + set.add(relay); + }; + } + const _knownIds = /* @__PURE__ */ new Set(); + const subs = []; + const eosesReceived = []; + let handleEose = (i2) => { + if (eosesReceived[i2]) + return; + eosesReceived[i2] = true; + if (eosesReceived.filter((a) => a).length === requests.length) { + params.oneose?.(); + handleEose = () => { + }; + } + }; + const closesReceived = []; + let handleClose = (i2, reason) => { + if (closesReceived[i2]) + return; + handleEose(i2); + closesReceived[i2] = reason; + if (closesReceived.filter((a) => a).length === requests.length) { + params.onclose?.(closesReceived); + handleClose = () => { + }; + } + }; + const localAlreadyHaveEventHandler = (id) => { + if (params.alreadyHaveEvent?.(id)) { + return true; + } + const have = _knownIds.has(id); + _knownIds.add(id); + return have; + }; + const allOpened = Promise.all( + requests.map(async ({ url, filter }, i2) => { + let relay; + try { + relay = await this.ensureRelay(url, { + connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1e3) : void 0 + }); + } catch (err) { + handleClose(i2, err?.message || String(err)); + return; + } + let subscription = relay.subscribe([filter], { + ...params, + oneose: () => handleEose(i2), + onclose: (reason) => { + if (reason.startsWith("auth-required: ") && params.onauth) { + relay.auth(params.onauth).then(() => { + relay.subscribe([filter], { + ...params, + oneose: () => handleEose(i2), + onclose: (reason2) => { + handleClose(i2, reason2); + }, + alreadyHaveEvent: localAlreadyHaveEventHandler, + eoseTimeout: params.maxWait + }); + }).catch((err) => { + handleClose(i2, `auth was required and attempted, but failed with: ${err}`); + }); + } else { + handleClose(i2, reason); + } + }, + alreadyHaveEvent: localAlreadyHaveEventHandler, + eoseTimeout: params.maxWait + }); + subs.push(subscription); + }) + ); + return { + async close(reason) { + await allOpened; + subs.forEach((sub) => { + sub.close(reason); + }); + } + }; + } + subscribeEose(relays, filter, params) { + params.onauth = params.onauth || params.doauth; + const subcloser = this.subscribe(relays, filter, { + ...params, + oneose() { + subcloser.close("closed automatically on eose"); + } + }); + return subcloser; + } + subscribeManyEose(relays, filters, params) { + params.onauth = params.onauth || params.doauth; + const subcloser = this.subscribeMany(relays, filters, { + ...params, + oneose() { + subcloser.close("closed automatically on eose"); + } + }); + return subcloser; + } + async querySync(relays, filter, params) { + return new Promise(async (resolve) => { + const events = []; + this.subscribeEose(relays, filter, { + ...params, + onevent(event) { + events.push(event); + }, + onclose(_) { + resolve(events); + } + }); + }); + } + async get(relays, filter, params) { + filter.limit = 1; + const events = await this.querySync(relays, filter, params); + events.sort((a, b) => b.created_at - a.created_at); + return events[0] || null; + } + publish(relays, event, options) { + return relays.map(normalizeURL).map(async (url, i2, arr) => { + if (arr.indexOf(url) !== i2) { + return Promise.reject("duplicate url"); + } + let r = await this.ensureRelay(url); + return r.publish(event).catch(async (err) => { + if (err instanceof Error && err.message.startsWith("auth-required: ") && options?.onauth) { + await r.auth(options.onauth); + return r.publish(event); + } + throw err; + }).then((reason) => { + if (this.trackRelays) { + let set = this.seenOn.get(event.id); + if (!set) { + set = /* @__PURE__ */ new Set(); + this.seenOn.set(event.id, set); + } + set.add(r); + } + return reason; + }); + }); + } + listConnectionStatus() { + const map = /* @__PURE__ */ new Map(); + this.relays.forEach((relay, url) => map.set(url, relay.connected)); + return map; + } + destroy() { + this.relays.forEach((conn) => conn.close()); + this.relays = /* @__PURE__ */ new Map(); + } +}; + +// pool.ts +var _WebSocket; +try { + _WebSocket = WebSocket; +} catch { +} +function useWebSocketImplementation(websocketImplementation) { + _WebSocket = websocketImplementation; +} +var SimplePool = class extends AbstractSimplePool { + constructor(options) { + super({ verifyEvent, websocketImplementation: _WebSocket, ...options }); + } +}; +export { + AbstractSimplePool, + SimplePool, + useWebSocketImplementation +}; diff --git a/node_modules/nostr-tools/lib/esm/pool.js.map b/node_modules/nostr-tools/lib/esm/pool.js.map new file mode 100644 index 0000000..8ce7df9 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/pool.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../pure.ts", "../../core.ts", "../../utils.ts", "../../kinds.ts", "../../filter.ts", "../../fakejson.ts", "../../nip42.ts", "../../helpers.ts", "../../abstract-relay.ts", "../../abstract-pool.ts", "../../pool.ts"], + "sourcesContent": ["import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { Event } from './core.ts'\nimport { isAddressableKind, isReplaceableKind } from './kinds.ts'\n\nexport type Filter = {\n ids?: string[]\n kinds?: number[]\n authors?: string[]\n since?: number\n until?: number\n limit?: number\n search?: string\n [key: `#${string}`]: string[] | undefined\n}\n\nexport function matchFilter(filter: Filter, event: Event): boolean {\n if (filter.ids && filter.ids.indexOf(event.id) === -1) {\n return false\n }\n if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) {\n return false\n }\n if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) {\n return false\n }\n\n for (let f in filter) {\n if (f[0] === '#') {\n let tagName = f.slice(1)\n let values = filter[`#${tagName}`]\n if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values!.indexOf(v) !== -1)) return false\n }\n }\n\n if (filter.since && event.created_at < filter.since) return false\n if (filter.until && event.created_at > filter.until) return false\n\n return true\n}\n\nexport function matchFilters(filters: Filter[], event: Event): boolean {\n for (let i = 0; i < filters.length; i++) {\n if (matchFilter(filters[i], event)) {\n return true\n }\n }\n return false\n}\n\nexport function mergeFilters(...filters: Filter[]): Filter {\n let result: Filter = {}\n for (let i = 0; i < filters.length; i++) {\n let filter = filters[i]\n Object.entries(filter).forEach(([property, values]) => {\n if (property === 'kinds' || property === 'ids' || property === 'authors' || property[0] === '#') {\n // @ts-ignore\n result[property] = result[property] || []\n // @ts-ignore\n for (let v = 0; v < values.length; v++) {\n // @ts-ignore\n let value = values[v]\n // @ts-ignore\n if (!result[property].includes(value)) result[property].push(value)\n }\n }\n })\n\n if (filter.limit && (!result.limit || filter.limit > result.limit)) result.limit = filter.limit\n if (filter.until && (!result.until || filter.until > result.until)) result.until = filter.until\n if (filter.since && (!result.since || filter.since < result.since)) result.since = filter.since\n }\n\n return result\n}\n\n/**\n * Calculate the intrinsic limit of a filter.\n * This function returns a positive integer, or `Infinity` if there is no intrinsic limit.\n */\nexport function getFilterLimit(filter: Filter): number {\n if (filter.ids && !filter.ids.length) return 0\n if (filter.kinds && !filter.kinds.length) return 0\n if (filter.authors && !filter.authors.length) return 0\n\n for (const [key, value] of Object.entries(filter)) {\n if (key[0] === '#' && Array.isArray(value) && !value.length) return 0\n }\n\n return Math.min(\n // The `limit` property creates an artificial limit.\n Math.max(0, filter.limit ?? Infinity),\n\n // There can only be one event per `id`.\n filter.ids?.length ?? Infinity,\n\n // Replaceable events are limited by the number of authors and kinds.\n filter.authors?.length && filter.kinds?.every(kind => isReplaceableKind(kind))\n ? filter.authors.length * filter.kinds.length\n : Infinity,\n\n // Parameterized replaceable events are limited by the number of authors, kinds, and \"d\" tags.\n filter.authors?.length && filter.kinds?.every(kind => isAddressableKind(kind)) && filter['#d']?.length\n ? filter.authors.length * filter.kinds.length * filter['#d'].length\n : Infinity,\n )\n}\n", "export function getHex64(json: string, field: string): string {\n let len = field.length + 3\n let idx = json.indexOf(`\"${field}\":`) + len\n let s = json.slice(idx).indexOf(`\"`) + idx + 1\n return json.slice(s, s + 64)\n}\n\nexport function getInt(json: string, field: string): number {\n let len = field.length\n let idx = json.indexOf(`\"${field}\":`) + len + 3\n let sliced = json.slice(idx)\n let end = Math.min(sliced.indexOf(','), sliced.indexOf('}'))\n return parseInt(sliced.slice(0, end), 10)\n}\n\nexport function getSubscriptionId(json: string): string | null {\n let idx = json.slice(0, 22).indexOf(`\"EVENT\"`)\n if (idx === -1) return null\n\n let pstart = json.slice(idx + 7 + 1).indexOf(`\"`)\n if (pstart === -1) return null\n let start = idx + 7 + 1 + pstart\n\n let pend = json.slice(start + 1, 80).indexOf(`\"`)\n if (pend === -1) return null\n let end = start + 1 + pend\n\n return json.slice(start + 1, end)\n}\n\nexport function matchEventId(json: string, id: string): boolean {\n return id === getHex64(json, 'id')\n}\n\nexport function matchEventPubkey(json: string, pubkey: string): boolean {\n return pubkey === getHex64(json, 'pubkey')\n}\n\nexport function matchEventKind(json: string, kind: number): boolean {\n return kind === getInt(json, 'kind')\n}\n", "import { EventTemplate } from './core.ts'\nimport { ClientAuth } from './kinds.ts'\n\n/**\n * creates an EventTemplate for an AUTH event to be signed.\n */\nexport function makeAuthEvent(relayURL: string, challenge: string): EventTemplate {\n return {\n kind: ClientAuth,\n created_at: Math.floor(Date.now() / 1000),\n tags: [\n ['relay', relayURL],\n ['challenge', challenge],\n ],\n content: '',\n }\n}\n", "import { verifiedSymbol, type Event, type Nostr, VerifiedEvent } from './core.ts'\n\nexport async function yieldThread() {\n return new Promise(resolve => {\n const ch = new MessageChannel()\n const handler = () => {\n // @ts-ignore (typescript thinks this property should be called `removeListener`, but in fact it's `removeEventListener`)\n ch.port1.removeEventListener('message', handler)\n resolve()\n }\n // @ts-ignore (typescript thinks this property should be called `addListener`, but in fact it's `addEventListener`)\n ch.port1.addEventListener('message', handler)\n ch.port2.postMessage(0)\n ch.port1.start()\n })\n}\n\nexport const alwaysTrue: Nostr['verifyEvent'] = (t: Event): t is VerifiedEvent => {\n t[verifiedSymbol] = true\n return true\n}\n", "/* global WebSocket */\n\nimport type { Event, EventTemplate, VerifiedEvent, Nostr, NostrEvent } from './core.ts'\nimport { matchFilters, type Filter } from './filter.ts'\nimport { getHex64, getSubscriptionId } from './fakejson.ts'\nimport { Queue, normalizeURL } from './utils.ts'\nimport { makeAuthEvent } from './nip42.ts'\nimport { yieldThread } from './helpers.ts'\n\ntype RelayWebSocket = WebSocket & {\n ping?(): void\n on?(event: 'pong', listener: () => void): any\n}\n\nexport type AbstractRelayConstructorOptions = {\n verifyEvent: Nostr['verifyEvent']\n websocketImplementation?: typeof WebSocket\n enablePing?: boolean\n}\n\nexport class SendingOnClosedConnection extends Error {\n constructor(message: string, relay: string) {\n super(`Tried to send message '${message} on a closed connection to ${relay}.`)\n this.name = 'SendingOnClosedConnection'\n }\n}\n\nexport class AbstractRelay {\n public readonly url: string\n private _connected: boolean = false\n\n public onclose: (() => void) | null = null\n public onnotice: (msg: string) => void = msg => console.debug(`NOTICE from ${this.url}: ${msg}`)\n\n public baseEoseTimeout: number = 4400\n public connectionTimeout: number = 4400\n public publishTimeout: number = 4400\n public pingFrequency: number = 20000\n public pingTimeout: number = 20000\n public openSubs: Map = new Map()\n public enablePing: boolean | undefined\n private connectionTimeoutHandle: ReturnType | undefined\n\n private connectionPromise: Promise | undefined\n private openCountRequests = new Map()\n private openEventPublishes = new Map()\n private ws: RelayWebSocket | undefined\n private incomingMessageQueue = new Queue()\n private queueRunning = false\n private challenge: string | undefined\n private authPromise: Promise | undefined\n private serial: number = 0\n private verifyEvent: Nostr['verifyEvent']\n\n private _WebSocket: typeof WebSocket\n\n constructor(url: string, opts: AbstractRelayConstructorOptions) {\n this.url = normalizeURL(url)\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation || WebSocket\n this.enablePing = opts.enablePing\n }\n\n static async connect(url: string, opts: AbstractRelayConstructorOptions): Promise {\n const relay = new AbstractRelay(url, opts)\n await relay.connect()\n return relay\n }\n\n private closeAllSubscriptions(reason: string) {\n for (let [_, sub] of this.openSubs) {\n sub.close(reason)\n }\n this.openSubs.clear()\n\n for (let [_, ep] of this.openEventPublishes) {\n ep.reject(new Error(reason))\n }\n this.openEventPublishes.clear()\n\n for (let [_, cr] of this.openCountRequests) {\n cr.reject(new Error(reason))\n }\n this.openCountRequests.clear()\n }\n\n public get connected(): boolean {\n return this._connected\n }\n\n public async connect(): Promise {\n if (this.connectionPromise) return this.connectionPromise\n\n this.challenge = undefined\n this.authPromise = undefined\n this.connectionPromise = new Promise((resolve, reject) => {\n this.connectionTimeoutHandle = setTimeout(() => {\n reject('connection timed out')\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection timed out')\n }, this.connectionTimeout)\n\n try {\n this.ws = new this._WebSocket(this.url)\n } catch (err) {\n clearTimeout(this.connectionTimeoutHandle)\n reject(err)\n return\n }\n\n this.ws.onopen = () => {\n clearTimeout(this.connectionTimeoutHandle)\n this._connected = true\n if (this.enablePing) {\n this.pingpong()\n }\n resolve()\n }\n\n this.ws.onerror = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket error')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection errored')\n }\n }\n\n this.ws.onclose = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket closed')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection closed')\n }\n }\n\n this.ws.onmessage = this._onmessage.bind(this)\n })\n\n return this.connectionPromise\n }\n\n private async waitForPingPong() {\n return new Promise((res, err) => {\n // listen for pong\n ;(this.ws && this.ws.on && this.ws.on('pong', () => res(true))) || err(\"ws can't listen for pong\")\n // send a ping\n this.ws && this.ws.ping && this.ws.ping()\n })\n }\n\n private async waitForDummyReq() {\n return new Promise((resolve, _) => {\n // make a dummy request with expected empty eose reply\n // [\"REQ\", \"_\", {\"ids\":[\"aaaa...aaaa\"]}]\n const sub = this.subscribe([{ ids: ['a'.repeat(64)] }], {\n oneose: () => {\n sub.close()\n resolve(true)\n },\n eoseTimeout: this.pingTimeout + 1000,\n })\n })\n }\n\n // nodejs requires this magic here to ensure connections are closed when internet goes off and stuff\n // in browsers it's done automatically. see https://github.com/nbd-wtf/nostr-tools/issues/491\n private async pingpong() {\n // if the websocket is connected\n if (this.ws?.readyState === 1) {\n // wait for either a ping-pong reply or a timeout\n const result = await Promise.any([\n // browsers don't have ping so use a dummy req\n this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(),\n new Promise(res => setTimeout(() => res(false), this.pingTimeout)),\n ])\n if (result) {\n // schedule another pingpong\n setTimeout(() => this.pingpong(), this.pingFrequency)\n } else {\n // pingpong closing socket\n this.closeAllSubscriptions('pingpong timed out')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n }\n }\n\n private async runQueue() {\n this.queueRunning = true\n while (true) {\n if (false === this.handleNext()) {\n break\n }\n await yieldThread()\n }\n this.queueRunning = false\n }\n\n private handleNext(): undefined | false {\n const json = this.incomingMessageQueue.dequeue()\n if (!json) {\n return false\n }\n\n const subid = getSubscriptionId(json)\n if (subid) {\n const so = this.openSubs.get(subid as string)\n if (!so) {\n // this is an EVENT message, but for a subscription we don't have, so just stop here\n return\n }\n\n // this will be called only when this message is a EVENT message for a subscription we have\n // we do this before parsing the JSON to not have to do that for duplicate events\n // since JSON parsing is slow\n const id = getHex64(json, 'id')\n const alreadyHave = so.alreadyHaveEvent?.(id)\n\n // notify any interested client that the relay has this event\n // (do this after alreadyHaveEvent() because the client may rely on this to answer that)\n so.receivedEvent?.(this, id)\n\n if (alreadyHave) {\n // if we had already seen this event we can just stop here\n return\n }\n }\n\n try {\n let data = JSON.parse(json)\n // we won't do any checks against the data since all failures (i.e. invalid messages from relays)\n // will naturally be caught by the encompassing try..catch block\n\n switch (data[0]) {\n case 'EVENT': {\n const so = this.openSubs.get(data[1] as string) as Subscription\n const event = data[2] as NostrEvent\n if (this.verifyEvent(event) && matchFilters(so.filters, event)) {\n so.onevent(event)\n }\n return\n }\n case 'COUNT': {\n const id: string = data[1]\n const payload = data[2] as { count: number }\n const cr = this.openCountRequests.get(id) as CountResolver\n if (cr) {\n cr.resolve(payload.count)\n this.openCountRequests.delete(id)\n }\n return\n }\n case 'EOSE': {\n const so = this.openSubs.get(data[1] as string)\n if (!so) return\n so.receivedEose()\n return\n }\n case 'OK': {\n const id: string = data[1]\n const ok: boolean = data[2]\n const reason: string = data[3]\n const ep = this.openEventPublishes.get(id) as EventPublishResolver\n if (ep) {\n clearTimeout(ep.timeout)\n if (ok) ep.resolve(reason)\n else ep.reject(new Error(reason))\n this.openEventPublishes.delete(id)\n }\n return\n }\n case 'CLOSED': {\n const id: string = data[1]\n const so = this.openSubs.get(id)\n if (!so) return\n so.closed = true\n so.close(data[2] as string)\n return\n }\n case 'NOTICE':\n this.onnotice(data[1] as string)\n return\n case 'AUTH': {\n this.challenge = data[1] as string\n return\n }\n }\n } catch (err) {\n return\n }\n }\n\n public async send(message: string) {\n if (!this.connectionPromise) throw new SendingOnClosedConnection(message, this.url)\n\n this.connectionPromise.then(() => {\n this.ws?.send(message)\n })\n }\n\n public async auth(signAuthEvent: (evt: EventTemplate) => Promise): Promise {\n const challenge = this.challenge\n if (!challenge) throw new Error(\"can't perform auth, no challenge was received\")\n if (this.authPromise) return this.authPromise\n\n this.authPromise = new Promise(async (resolve, reject) => {\n try {\n let evt = await signAuthEvent(makeAuthEvent(this.url, challenge))\n let timeout = setTimeout(() => {\n let ep = this.openEventPublishes.get(evt.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('auth timed out'))\n this.openEventPublishes.delete(evt.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(evt.id, { resolve, reject, timeout })\n this.send('[\"AUTH\",' + JSON.stringify(evt) + ']')\n } catch (err) {\n console.warn('subscribe auth function failed:', err)\n }\n })\n return this.authPromise\n }\n\n public async publish(event: Event): Promise {\n const ret = new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n const ep = this.openEventPublishes.get(event.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('publish timed out'))\n this.openEventPublishes.delete(event.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(event.id, { resolve, reject, timeout })\n })\n this.send('[\"EVENT\",' + JSON.stringify(event) + ']')\n return ret\n }\n\n public async count(filters: Filter[], params: { id?: string | null }): Promise {\n this.serial++\n const id = params?.id || 'count:' + this.serial\n const ret = new Promise((resolve, reject) => {\n this.openCountRequests.set(id, { resolve, reject })\n })\n this.send('[\"COUNT\",\"' + id + '\",' + JSON.stringify(filters).substring(1))\n return ret\n }\n\n public subscribe(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n const subscription = this.prepareSubscription(filters, params)\n subscription.fire()\n return subscription\n }\n\n public prepareSubscription(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n this.serial++\n const id = params.id || (params.label ? params.label + ':' : 'sub:') + this.serial\n const subscription = new Subscription(this, id, filters, params)\n this.openSubs.set(id, subscription)\n return subscription\n }\n\n public close() {\n this.closeAllSubscriptions('relay connection closed by us')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n\n // this is the function assigned to this.ws.onmessage\n // it's exposed for testing and debugging purposes\n public _onmessage(ev: MessageEvent) {\n this.incomingMessageQueue.enqueue(ev.data as string)\n if (!this.queueRunning) {\n this.runQueue()\n }\n }\n}\n\nexport class Subscription {\n public readonly relay: AbstractRelay\n public readonly id: string\n\n public closed: boolean = false\n public eosed: boolean = false\n public filters: Filter[]\n public alreadyHaveEvent: ((id: string) => boolean) | undefined\n public receivedEvent: ((relay: AbstractRelay, id: string) => void) | undefined\n\n public onevent: (evt: Event) => void\n public oneose: (() => void) | undefined\n public onclose: ((reason: string) => void) | undefined\n\n public eoseTimeout: number\n private eoseTimeoutHandle: ReturnType | undefined\n\n constructor(relay: AbstractRelay, id: string, filters: Filter[], params: SubscriptionParams) {\n this.relay = relay\n this.filters = filters\n this.id = id\n this.alreadyHaveEvent = params.alreadyHaveEvent\n this.receivedEvent = params.receivedEvent\n this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout\n\n this.oneose = params.oneose\n this.onclose = params.onclose\n this.onevent =\n params.onevent ||\n (event => {\n console.warn(\n `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,\n event,\n )\n })\n }\n\n public fire() {\n this.relay.send('[\"REQ\",\"' + this.id + '\",' + JSON.stringify(this.filters).substring(1))\n\n // only now we start counting the eoseTimeout\n this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout)\n }\n\n public receivedEose() {\n if (this.eosed) return\n clearTimeout(this.eoseTimeoutHandle)\n this.eosed = true\n this.oneose?.()\n }\n\n public close(reason: string = 'closed by caller') {\n if (!this.closed && this.relay.connected) {\n // if the connection was closed by the user calling .close() we will send a CLOSE message\n // otherwise this._open will be already set to false so we will skip this\n try {\n this.relay.send('[\"CLOSE\",' + JSON.stringify(this.id) + ']')\n } catch (err) {\n if (err instanceof SendingOnClosedConnection) {\n /* doesn't matter, it's ok */\n } else {\n throw err\n }\n }\n this.closed = true\n }\n this.relay.openSubs.delete(this.id)\n this.onclose?.(reason)\n }\n}\n\nexport type SubscriptionParams = {\n onevent?: (evt: Event) => void\n oneose?: () => void\n onclose?: (reason: string) => void\n alreadyHaveEvent?: (id: string) => boolean\n receivedEvent?: (relay: AbstractRelay, id: string) => void\n eoseTimeout?: number\n}\n\nexport type CountResolver = {\n resolve: (count: number) => void\n reject: (err: Error) => void\n}\n\nexport type EventPublishResolver = {\n resolve: (reason: string) => void\n reject: (err: Error) => void\n timeout: ReturnType\n}\n", "/* global WebSocket */\n\nimport {\n AbstractRelay as AbstractRelay,\n SubscriptionParams,\n Subscription,\n type AbstractRelayConstructorOptions,\n} from './abstract-relay.ts'\nimport { normalizeURL } from './utils.ts'\n\nimport type { Event, EventTemplate, Nostr, VerifiedEvent } from './core.ts'\nimport { type Filter } from './filter.ts'\nimport { alwaysTrue } from './helpers.ts'\n\nexport type SubCloser = { close: (reason?: string) => void }\n\nexport type AbstractPoolConstructorOptions = AbstractRelayConstructorOptions & {}\n\nexport type SubscribeManyParams = Omit & {\n maxWait?: number\n onclose?: (reasons: string[]) => void\n onauth?: (event: EventTemplate) => Promise\n // Deprecated: use onauth instead\n doauth?: (event: EventTemplate) => Promise\n id?: string\n label?: string\n}\n\nexport class AbstractSimplePool {\n protected relays: Map = new Map()\n public seenOn: Map> = new Map()\n public trackRelays: boolean = false\n\n public verifyEvent: Nostr['verifyEvent']\n public enablePing: boolean | undefined\n public trustedRelayURLs: Set = new Set()\n\n private _WebSocket?: typeof WebSocket\n\n constructor(opts: AbstractPoolConstructorOptions) {\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation\n this.enablePing = opts.enablePing\n }\n\n async ensureRelay(url: string, params?: { connectionTimeout?: number }): Promise {\n url = normalizeURL(url)\n\n let relay = this.relays.get(url)\n if (!relay) {\n relay = new AbstractRelay(url, {\n verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent,\n websocketImplementation: this._WebSocket,\n enablePing: this.enablePing,\n })\n relay.onclose = () => {\n this.relays.delete(url)\n }\n if (params?.connectionTimeout) relay.connectionTimeout = params.connectionTimeout\n this.relays.set(url, relay)\n }\n await relay.connect()\n\n return relay\n }\n\n close(relays: string[]) {\n relays.map(normalizeURL).forEach(url => {\n this.relays.get(url)?.close()\n this.relays.delete(url)\n })\n }\n\n subscribe(relays: string[], filter: Filter, params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const request: { url: string; filter: Filter }[] = []\n for (let i = 0; i < relays.length; i++) {\n const url = normalizeURL(relays[i])\n if (!request.find(r => r.url === url)) {\n request.push({ url, filter })\n }\n }\n\n return this.subscribeMap(request, params)\n }\n\n subscribeMany(relays: string[], filters: Filter[], params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const request: { url: string; filter: Filter }[] = []\n const uniqUrls: string[] = []\n for (let i = 0; i < relays.length; i++) {\n const url = normalizeURL(relays[i])\n if (uniqUrls.indexOf(url) === -1) {\n for (let f = 0; f < filters.length; f++) {\n request.push({ url, filter: filters[f] })\n }\n }\n }\n\n return this.subscribeMap(request, params)\n }\n\n subscribeMap(requests: { url: string; filter: Filter }[], params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n if (this.trackRelays) {\n params.receivedEvent = (relay: AbstractRelay, id: string) => {\n let set = this.seenOn.get(id)\n if (!set) {\n set = new Set()\n this.seenOn.set(id, set)\n }\n set.add(relay)\n }\n }\n\n const _knownIds = new Set()\n const subs: Subscription[] = []\n\n // batch all EOSEs into a single\n const eosesReceived: boolean[] = []\n let handleEose = (i: number) => {\n if (eosesReceived[i]) return // do not act twice for the same relay\n eosesReceived[i] = true\n if (eosesReceived.filter(a => a).length === requests.length) {\n params.oneose?.()\n handleEose = () => {}\n }\n }\n // batch all closes into a single\n const closesReceived: string[] = []\n let handleClose = (i: number, reason: string) => {\n if (closesReceived[i]) return // do not act twice for the same relay\n handleEose(i)\n closesReceived[i] = reason\n if (closesReceived.filter(a => a).length === requests.length) {\n params.onclose?.(closesReceived)\n handleClose = () => {}\n }\n }\n\n const localAlreadyHaveEventHandler = (id: string) => {\n if (params.alreadyHaveEvent?.(id)) {\n return true\n }\n const have = _knownIds.has(id)\n _knownIds.add(id)\n return have\n }\n\n // open a subscription in all given relays\n const allOpened = Promise.all(\n requests.map(async ({ url, filter }, i) => {\n let relay: AbstractRelay\n try {\n relay = await this.ensureRelay(url, {\n connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1000) : undefined,\n })\n } catch (err) {\n handleClose(i, (err as any)?.message || String(err))\n return\n }\n\n let subscription = relay.subscribe([filter], {\n ...params,\n oneose: () => handleEose(i),\n onclose: reason => {\n if (reason.startsWith('auth-required: ') && params.onauth) {\n relay\n .auth(params.onauth)\n .then(() => {\n relay.subscribe([filter], {\n ...params,\n oneose: () => handleEose(i),\n onclose: reason => {\n handleClose(i, reason) // the second time we won't try to auth anymore\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait,\n })\n })\n .catch(err => {\n handleClose(i, `auth was required and attempted, but failed with: ${err}`)\n })\n } else {\n handleClose(i, reason)\n }\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait,\n })\n\n subs.push(subscription)\n }),\n )\n\n return {\n async close(reason?: string) {\n await allOpened\n subs.forEach(sub => {\n sub.close(reason)\n })\n },\n }\n }\n\n subscribeEose(\n relays: string[],\n filter: Filter,\n params: Pick,\n ): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const subcloser = this.subscribe(relays, filter, {\n ...params,\n oneose() {\n subcloser.close('closed automatically on eose')\n },\n })\n return subcloser\n }\n\n subscribeManyEose(\n relays: string[],\n filters: Filter[],\n params: Pick,\n ): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const subcloser = this.subscribeMany(relays, filters, {\n ...params,\n oneose() {\n subcloser.close('closed automatically on eose')\n },\n })\n return subcloser\n }\n\n async querySync(\n relays: string[],\n filter: Filter,\n params?: Pick,\n ): Promise {\n return new Promise(async resolve => {\n const events: Event[] = []\n this.subscribeEose(relays, filter, {\n ...params,\n onevent(event: Event) {\n events.push(event)\n },\n onclose(_: string[]) {\n resolve(events)\n },\n })\n })\n }\n\n async get(\n relays: string[],\n filter: Filter,\n params?: Pick,\n ): Promise {\n filter.limit = 1\n const events = await this.querySync(relays, filter, params)\n events.sort((a, b) => b.created_at - a.created_at)\n return events[0] || null\n }\n\n publish(\n relays: string[],\n event: Event,\n options?: { onauth?: (evt: EventTemplate) => Promise },\n ): Promise[] {\n return relays.map(normalizeURL).map(async (url, i, arr) => {\n if (arr.indexOf(url) !== i) {\n // duplicate\n return Promise.reject('duplicate url')\n }\n\n let r = await this.ensureRelay(url)\n return r\n .publish(event)\n .catch(async err => {\n if (err instanceof Error && err.message.startsWith('auth-required: ') && options?.onauth) {\n await r.auth(options.onauth)\n return r.publish(event) // retry\n }\n throw err\n })\n .then(reason => {\n if (this.trackRelays) {\n let set = this.seenOn.get(event.id)\n if (!set) {\n set = new Set()\n this.seenOn.set(event.id, set)\n }\n set.add(r)\n }\n return reason\n })\n })\n }\n\n listConnectionStatus(): Map {\n const map = new Map()\n this.relays.forEach((relay, url) => map.set(url, relay.connected))\n\n return map\n }\n\n destroy(): void {\n this.relays.forEach(conn => conn.close())\n this.relays = new Map()\n }\n}\n", "/* global WebSocket */\n\nimport { verifyEvent } from './pure.ts'\nimport { AbstractSimplePool } from './abstract-pool.ts'\n\nvar _WebSocket: typeof WebSocket\n\ntry {\n _WebSocket = WebSocket\n} catch {}\n\nexport function useWebSocketImplementation(websocketImplementation: any) {\n _WebSocket = websocketImplementation\n}\n\nexport class SimplePool extends AbstractSimplePool {\n constructor(options?: { enablePing?: boolean }) {\n super({ verifyEvent, websocketImplementation: _WebSocket, ...options })\n }\n}\n\nexport * from './abstract-pool.ts'\n"], + "mappings": ";AAAA,SA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AAI;AAEJ,IAAI;AACF,eAAa;AACf,QAAE;AAAO;AAEF,SAAS,2BAA2B,yBAA8B;AACvE,eAAa;AACf;AAEO,IAAM,aAAN,cAAyB,mBAAmB;AAAA,EACjD,YAAY,SAAoC;AAC9C,UAAM,EAAE,aAAa,yBAAyB,YAAY,GAAG,QAAQ,CAAC;AAAA,EACxE;AACF;", + "names": ["bytesToHex", "i", "target", "bytesToHex", "i", "i", "reason"] +} diff --git a/node_modules/nostr-tools/lib/esm/pure.js b/node_modules/nostr-tools/lib/esm/pure.js new file mode 100644 index 0000000..9d7dc62 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/pure.js @@ -0,0 +1,109 @@ +// pure.ts +import { schnorr } from "@noble/curves/secp256k1"; +import { bytesToHex as bytesToHex2 } from "@noble/hashes/utils"; + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} +function sortEvents(events) { + return events.sort((a, b) => { + if (a.created_at !== b.created_at) { + return b.created_at - a.created_at; + } + return a.id.localeCompare(b.id); + }); +} + +// pure.ts +import { sha256 } from "@noble/hashes/sha256"; + +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// pure.ts +var JS = class { + generateSecretKey() { + return schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return bytesToHex2(schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = bytesToHex2(schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = bytesToHex2(schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = sha256(utf8Encoder.encode(serializeEvent(event))); + return bytesToHex2(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; +export { + finalizeEvent, + generateSecretKey, + getEventHash, + getPublicKey, + serializeEvent, + sortEvents, + validateEvent, + verifiedSymbol, + verifyEvent +}; diff --git a/node_modules/nostr-tools/lib/esm/pure.js.map b/node_modules/nostr-tools/lib/esm/pure.js.map new file mode 100644 index 0000000..f55e589 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/pure.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../pure.ts", "../../core.ts", "../../utils.ts"], + "sourcesContent": ["import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n"], + "mappings": ";AAAA,SAAS,eAAe;AACxB,SAAS,cAAAA,mBAAkB;;;ACOpB,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,CAAC,QAAiD,eAAe;AAE3E,SAAS,cAAiB,OAAsC;AACrE,MAAI,CAAC,SAAS,KAAK;AAAG,WAAO;AAC7B,MAAI,OAAO,MAAM,SAAS;AAAU,WAAO;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M,kBAAkB;AACxB,WAAO;AAAA,EACT;AAAA,EACA,YAAY,OAAsC;AAChD,QAAI,OAAO,MAAM,oBAAoB;AAAW,aAAO,MAAM;AAE7D,UAAM,OAAO,aAAa,KAAK;AAC/B,QAAI,SAAS,MAAM,IAAI;AACrB,YAAM,kBAAkB;AACxB,aAAO;AAAA,IACT;AAEA,QAAI;AACF,YAAM,QAAQ,QAAQ,OAAO,MAAM,KAAK,MAAM,MAAM,MAAM;AAC1D,YAAM,kBAAkB;AACxB,aAAO;AAAA,IACT,SAAS,KAAP;AACA,YAAM,kBAAkB;AACxB,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAEO,SAAS,eAAe,KAA4B;AACzD,MAAI,CAAC,cAAc,GAAG;AAAG,UAAM,IAAI,MAAM,wDAAwD;AACjG,SAAO,KAAK,UAAU,CAAC,GAAG,IAAI,QAAQ,IAAI,YAAY,IAAI,MAAM,IAAI,MAAM,IAAI,OAAO,CAAC;AACxF;AAEO,SAAS,aAAa,OAA8B;AACzD,MAAI,YAAY,OAAO,YAAY,OAAO,eAAe,KAAK,CAAC,CAAC;AAChE,SAAOA,YAAW,SAAS;AAC7B;AAEA,IAAM,IAAQ,IAAI,GAAG;AAEd,IAAM,oBAAoB,EAAE;AAC5B,IAAM,eAAe,EAAE;AACvB,IAAM,gBAAgB,EAAE;AACxB,IAAM,cAAc,EAAE;", + "names": ["bytesToHex", "i", "bytesToHex"] +} diff --git a/node_modules/nostr-tools/lib/esm/references.js b/node_modules/nostr-tools/lib/esm/references.js new file mode 100644 index 0000000..7b82b27 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/references.js @@ -0,0 +1,187 @@ +// nip19.ts +import { bytesToHex as bytesToHex2, concatBytes, hexToBytes as hexToBytes2 } from "@noble/hashes/utils"; +import { bech32 } from "@scure/base"; + +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// nip19.ts +var Bech32MaxSize = 5e3; +function decode(code) { + let { prefix, words } = bech32.decode(code, Bech32MaxSize); + let data = new Uint8Array(bech32.fromWords(words)); + switch (prefix) { + case "nprofile": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nprofile"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + return { + type: "nprofile", + data: { + pubkey: bytesToHex2(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nevent": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nevent"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + if (tlv[2] && tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (tlv[3] && tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "nevent", + data: { + id: bytesToHex2(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [], + author: tlv[2]?.[0] ? bytesToHex2(tlv[2][0]) : void 0, + kind: tlv[3]?.[0] ? parseInt(bytesToHex2(tlv[3][0]), 16) : void 0 + } + }; + } + case "naddr": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for naddr"); + if (!tlv[2]?.[0]) + throw new Error("missing TLV 2 for naddr"); + if (tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (!tlv[3]?.[0]) + throw new Error("missing TLV 3 for naddr"); + if (tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "naddr", + data: { + identifier: utf8Decoder.decode(tlv[0][0]), + pubkey: bytesToHex2(tlv[2][0]), + kind: parseInt(bytesToHex2(tlv[3][0]), 16), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nsec": + return { type: prefix, data }; + case "npub": + case "note": + return { type: prefix, data: bytesToHex2(data) }; + default: + throw new Error(`unknown prefix ${prefix}`); + } +} +function parseTLV(data) { + let result = {}; + let rest = data; + while (rest.length > 0) { + let t = rest[0]; + let l = rest[1]; + let v = rest.slice(2, 2 + l); + rest = rest.slice(2 + l); + if (v.length < l) + throw new Error(`not enough data to read on TLV ${t}`); + result[t] = result[t] || []; + result[t].push(v); + } + return result; +} + +// references.ts +var mentionRegex = /\bnostr:((note|npub|naddr|nevent|nprofile)1\w+)\b|#\[(\d+)\]/g; +function parseReferences(evt) { + let references = []; + for (let ref of evt.content.matchAll(mentionRegex)) { + if (ref[2]) { + try { + let { type, data } = decode(ref[1]); + switch (type) { + case "npub": { + references.push({ + text: ref[0], + profile: { pubkey: data, relays: [] } + }); + break; + } + case "nprofile": { + references.push({ + text: ref[0], + profile: data + }); + break; + } + case "note": { + references.push({ + text: ref[0], + event: { id: data, relays: [] } + }); + break; + } + case "nevent": { + references.push({ + text: ref[0], + event: data + }); + break; + } + case "naddr": { + references.push({ + text: ref[0], + address: data + }); + break; + } + } + } catch (err) { + } + } else if (ref[3]) { + let idx = parseInt(ref[3], 10); + let tag = evt.tags[idx]; + if (!tag) + continue; + switch (tag[0]) { + case "p": { + references.push({ + text: ref[0], + profile: { pubkey: tag[1], relays: tag[2] ? [tag[2]] : [] } + }); + break; + } + case "e": { + references.push({ + text: ref[0], + event: { id: tag[1], relays: tag[2] ? [tag[2]] : [] } + }); + break; + } + case "a": { + try { + let [kind, pubkey, identifier] = tag[1].split(":"); + references.push({ + text: ref[0], + address: { + identifier, + pubkey, + kind: parseInt(kind, 10), + relays: tag[2] ? [tag[2]] : [] + } + }); + } catch (err) { + } + break; + } + } + } + } + return references; +} +export { + parseReferences +}; diff --git a/node_modules/nostr-tools/lib/esm/references.js.map b/node_modules/nostr-tools/lib/esm/references.js.map new file mode 100644 index 0000000..9fd7a30 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/references.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../nip19.ts", "../../utils.ts", "../../references.ts"], + "sourcesContent": ["import { bytesToHex, concatBytes, hexToBytes } from '@noble/hashes/utils'\nimport { bech32 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport type NProfile = `nprofile1${string}`\nexport type NEvent = `nevent1${string}`\nexport type NAddr = `naddr1${string}`\nexport type NSec = `nsec1${string}`\nexport type NPub = `npub1${string}`\nexport type Note = `note1${string}`\nexport type Ncryptsec = `ncryptsec1${string}`\n\nexport const NostrTypeGuard = {\n isNProfile: (value?: string | null): value is NProfile => /^nprofile1[a-z\\d]+$/.test(value || ''),\n isNEvent: (value?: string | null): value is NEvent => /^nevent1[a-z\\d]+$/.test(value || ''),\n isNAddr: (value?: string | null): value is NAddr => /^naddr1[a-z\\d]+$/.test(value || ''),\n isNSec: (value?: string | null): value is NSec => /^nsec1[a-z\\d]{58}$/.test(value || ''),\n isNPub: (value?: string | null): value is NPub => /^npub1[a-z\\d]{58}$/.test(value || ''),\n isNote: (value?: string | null): value is Note => /^note1[a-z\\d]+$/.test(value || ''),\n isNcryptsec: (value?: string | null): value is Ncryptsec => /^ncryptsec1[a-z\\d]+$/.test(value || ''),\n}\n\nexport const Bech32MaxSize = 5000\n\n/**\n * Bech32 regex.\n * @see https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32\n */\nexport const BECH32_REGEX = /[\\x21-\\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/\n\nfunction integerToUint8Array(number: number) {\n // Create a Uint8Array with enough space to hold a 32-bit integer (4 bytes).\n const uint8Array = new Uint8Array(4)\n\n // Use bitwise operations to extract the bytes.\n uint8Array[0] = (number >> 24) & 0xff // Most significant byte (MSB)\n uint8Array[1] = (number >> 16) & 0xff\n uint8Array[2] = (number >> 8) & 0xff\n uint8Array[3] = number & 0xff // Least significant byte (LSB)\n\n return uint8Array\n}\n\nexport type ProfilePointer = {\n pubkey: string // hex\n relays?: string[]\n}\n\nexport type EventPointer = {\n id: string // hex\n relays?: string[]\n author?: string\n kind?: number\n}\n\nexport type AddressPointer = {\n identifier: string\n pubkey: string\n kind: number\n relays?: string[]\n}\n\nexport function decodeNostrURI(nip19code: string): ReturnType | { type: 'invalid'; data: null } {\n try {\n if (nip19code.startsWith('nostr:')) nip19code = nip19code.substring(6)\n return decode(nip19code)\n } catch (_err) {\n return { type: 'invalid', data: null }\n }\n}\n\nexport type DecodedNevent = {\n type: 'nevent'\n data: EventPointer\n}\n\nexport type DecodedNprofile = {\n type: 'nprofile'\n data: ProfilePointer\n}\n\nexport type DecodedNaddr = {\n type: 'naddr'\n data: AddressPointer\n}\n\nexport type DecodedNsec = {\n type: 'nsec'\n data: Uint8Array\n}\n\nexport type DecodedNpub = {\n type: 'npub'\n data: string\n}\n\nexport type DecodedNote = {\n type: 'note'\n data: string\n}\n\nexport type DecodedResult = DecodedNevent | DecodedNprofile | DecodedNaddr | DecodedNpub | DecodedNsec | DecodedNote\n\nexport function decode(nip19: NEvent): DecodedNevent\nexport function decode(nip19: NProfile): DecodedNprofile\nexport function decode(nip19: NAddr): DecodedNaddr\nexport function decode(nip19: NSec): DecodedNsec\nexport function decode(nip19: NPub): DecodedNpub\nexport function decode(nip19: Note): DecodedNote\nexport function decode(code: string): DecodedResult\nexport function decode(code: string): DecodedResult {\n let { prefix, words } = bech32.decode(code, Bech32MaxSize)\n let data = new Uint8Array(bech32.fromWords(words))\n\n switch (prefix) {\n case 'nprofile': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nprofile')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n\n return {\n type: 'nprofile',\n data: {\n pubkey: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n case 'nevent': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nevent')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n if (tlv[2] && tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (tlv[3] && tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'nevent',\n data: {\n id: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n author: tlv[2]?.[0] ? bytesToHex(tlv[2][0]) : undefined,\n kind: tlv[3]?.[0] ? parseInt(bytesToHex(tlv[3][0]), 16) : undefined,\n },\n }\n }\n\n case 'naddr': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for naddr')\n if (!tlv[2]?.[0]) throw new Error('missing TLV 2 for naddr')\n if (tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (!tlv[3]?.[0]) throw new Error('missing TLV 3 for naddr')\n if (tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'naddr',\n data: {\n identifier: utf8Decoder.decode(tlv[0][0]),\n pubkey: bytesToHex(tlv[2][0]),\n kind: parseInt(bytesToHex(tlv[3][0]), 16),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n\n case 'nsec':\n return { type: prefix, data }\n\n case 'npub':\n case 'note':\n return { type: prefix, data: bytesToHex(data) }\n\n default:\n throw new Error(`unknown prefix ${prefix}`)\n }\n}\n\ntype TLV = { [t: number]: Uint8Array[] }\n\nfunction parseTLV(data: Uint8Array): TLV {\n let result: TLV = {}\n let rest = data\n while (rest.length > 0) {\n let t = rest[0]\n let l = rest[1]\n let v = rest.slice(2, 2 + l)\n rest = rest.slice(2 + l)\n if (v.length < l) throw new Error(`not enough data to read on TLV ${t}`)\n result[t] = result[t] || []\n result[t].push(v)\n }\n return result\n}\n\nexport function nsecEncode(key: Uint8Array): NSec {\n return encodeBytes('nsec', key)\n}\n\nexport function npubEncode(hex: string): NPub {\n return encodeBytes('npub', hexToBytes(hex))\n}\n\nexport function noteEncode(hex: string): Note {\n return encodeBytes('note', hexToBytes(hex))\n}\n\nfunction encodeBech32(prefix: Prefix, data: Uint8Array): `${Prefix}1${string}` {\n let words = bech32.toWords(data)\n return bech32.encode(prefix, words, Bech32MaxSize) as `${Prefix}1${string}`\n}\n\nexport function encodeBytes(prefix: Prefix, bytes: Uint8Array): `${Prefix}1${string}` {\n return encodeBech32(prefix, bytes)\n}\n\nexport function nprofileEncode(profile: ProfilePointer): NProfile {\n let data = encodeTLV({\n 0: [hexToBytes(profile.pubkey)],\n 1: (profile.relays || []).map(url => utf8Encoder.encode(url)),\n })\n return encodeBech32('nprofile', data)\n}\n\nexport function neventEncode(event: EventPointer): NEvent {\n let kindArray\n if (event.kind !== undefined) {\n kindArray = integerToUint8Array(event.kind)\n }\n\n let data = encodeTLV({\n 0: [hexToBytes(event.id)],\n 1: (event.relays || []).map(url => utf8Encoder.encode(url)),\n 2: event.author ? [hexToBytes(event.author)] : [],\n 3: kindArray ? [new Uint8Array(kindArray)] : [],\n })\n\n return encodeBech32('nevent', data)\n}\n\nexport function naddrEncode(addr: AddressPointer): NAddr {\n let kind = new ArrayBuffer(4)\n new DataView(kind).setUint32(0, addr.kind, false)\n\n let data = encodeTLV({\n 0: [utf8Encoder.encode(addr.identifier)],\n 1: (addr.relays || []).map(url => utf8Encoder.encode(url)),\n 2: [hexToBytes(addr.pubkey)],\n 3: [new Uint8Array(kind)],\n })\n return encodeBech32('naddr', data)\n}\n\nfunction encodeTLV(tlv: TLV): Uint8Array {\n let entries: Uint8Array[] = []\n\n Object.entries(tlv)\n .reverse()\n .forEach(([t, vs]) => {\n vs.forEach(v => {\n let entry = new Uint8Array(v.length + 2)\n entry.set([parseInt(t)], 0)\n entry.set([v.length], 1)\n entry.set(v, 2)\n entries.push(entry)\n })\n })\n\n return concatBytes(...entries)\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { decode, type AddressPointer, type ProfilePointer, type EventPointer } from './nip19.ts'\n\nimport type { Event } from './core.ts'\n\ntype Reference = {\n text: string\n profile?: ProfilePointer\n event?: EventPointer\n address?: AddressPointer\n}\n\nconst mentionRegex = /\\bnostr:((note|npub|naddr|nevent|nprofile)1\\w+)\\b|#\\[(\\d+)\\]/g\n\nexport function parseReferences(evt: Event): Reference[] {\n let references: Reference[] = []\n for (let ref of evt.content.matchAll(mentionRegex)) {\n if (ref[2]) {\n // it's a NIP-27 mention\n try {\n let { type, data } = decode(ref[1])\n switch (type) {\n case 'npub': {\n references.push({\n text: ref[0],\n profile: { pubkey: data as string, relays: [] },\n })\n break\n }\n case 'nprofile': {\n references.push({\n text: ref[0],\n profile: data as ProfilePointer,\n })\n break\n }\n case 'note': {\n references.push({\n text: ref[0],\n event: { id: data as string, relays: [] },\n })\n break\n }\n case 'nevent': {\n references.push({\n text: ref[0],\n event: data as EventPointer,\n })\n break\n }\n case 'naddr': {\n references.push({\n text: ref[0],\n address: data as AddressPointer,\n })\n break\n }\n }\n } catch (err) {\n /***/\n }\n } else if (ref[3]) {\n // it's a NIP-10 mention\n let idx = parseInt(ref[3], 10)\n let tag = evt.tags[idx]\n if (!tag) continue\n\n switch (tag[0]) {\n case 'p': {\n references.push({\n text: ref[0],\n profile: { pubkey: tag[1], relays: tag[2] ? [tag[2]] : [] },\n })\n break\n }\n case 'e': {\n references.push({\n text: ref[0],\n event: { id: tag[1], relays: tag[2] ? [tag[2]] : [] },\n })\n break\n }\n case 'a': {\n try {\n let [kind, pubkey, identifier] = tag[1].split(':')\n references.push({\n text: ref[0],\n address: {\n identifier,\n pubkey,\n kind: parseInt(kind, 10),\n relays: tag[2] ? [tag[2]] : [],\n },\n })\n } catch (err) {\n /***/\n }\n break\n }\n }\n }\n }\n\n return references\n}\n"], + "mappings": ";AAAA,SAAS,cAAAA,aAAY,aAAa,cAAAC,mBAAkB;AACpD,SAAS,cAAc;;;ACIvB,SAAS,YAAY,kBAAkB;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;;;ADoBjD,IAAM,gBAAgB;AAwFtB,SAAS,OAAO,MAA6B;AAClD,MAAI,EAAE,QAAQ,MAAM,IAAI,OAAO,OAAO,MAAM,aAAa;AACzD,MAAI,OAAO,IAAI,WAAW,OAAO,UAAU,KAAK,CAAC;AAEjD,UAAQ,QAAQ;AAAA,IACd,KAAK,YAAY;AACf,UAAI,MAAM,SAAS,IAAI;AACvB,UAAI,CAAC,IAAI,KAAK;AAAI,cAAM,IAAI,MAAM,4BAA4B;AAC9D,UAAI,IAAI,GAAG,GAAG,WAAW;AAAI,cAAM,IAAI,MAAM,0BAA0B;AAEvE,aAAO;AAAA,QACL,MAAM;AAAA,QACN,MAAM;AAAA,UACJ,QAAQC,YAAW,IAAI,GAAG,EAAE;AAAA,UAC5B,QAAQ,IAAI,KAAK,IAAI,GAAG,IAAI,OAAK,YAAY,OAAO,CAAC,CAAC,IAAI,CAAC;AAAA,QAC7D;AAAA,MACF;AAAA,IACF;AAAA,IACA,KAAK,UAAU;AACb,UAAI,MAAM,SAAS,IAAI;AACvB,UAAI,CAAC,IAAI,KAAK;AAAI,cAAM,IAAI,MAAM,0BAA0B;AAC5D,UAAI,IAAI,GAAG,GAAG,WAAW;AAAI,cAAM,IAAI,MAAM,0BAA0B;AACvE,UAAI,IAAI,MAAM,IAAI,GAAG,GAAG,WAAW;AAAI,cAAM,IAAI,MAAM,0BAA0B;AACjF,UAAI,IAAI,MAAM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.js b/node_modules/nostr-tools/lib/esm/relay.js new file mode 100644 index 0000000..9bfbbea --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/relay.js @@ -0,0 +1,640 @@ +// pure.ts +import { schnorr } from "@noble/curves/secp256k1"; +import { bytesToHex as bytesToHex2 } from "@noble/hashes/utils"; + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +import { sha256 } from "@noble/hashes/sha256"; + +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); +function normalizeURL(url) { + try { + if (url.indexOf("://") === -1) + url = "wss://" + url; + let p = new URL(url); + p.pathname = p.pathname.replace(/\/+/g, "/"); + if (p.pathname.endsWith("/")) + p.pathname = p.pathname.slice(0, -1); + if (p.port === "80" && p.protocol === "ws:" || p.port === "443" && p.protocol === "wss:") + p.port = ""; + p.searchParams.sort(); + p.hash = ""; + return p.toString(); + } catch (e) { + throw new Error(`Invalid URL: ${url}`); + } +} +var QueueNode = class { + value; + next = null; + prev = null; + constructor(message) { + this.value = message; + } +}; +var Queue = class { + first; + last; + constructor() { + this.first = null; + this.last = null; + } + enqueue(value) { + const newNode = new QueueNode(value); + if (!this.last) { + this.first = newNode; + this.last = newNode; + } else if (this.last === this.first) { + this.last = newNode; + this.last.prev = this.first; + this.first.next = newNode; + } else { + newNode.prev = this.last; + this.last.next = newNode; + this.last = newNode; + } + return true; + } + dequeue() { + if (!this.first) + return null; + if (this.first === this.last) { + const target2 = this.first; + this.first = null; + this.last = null; + return target2.value; + } + const target = this.first; + this.first = target.next; + if (this.first) { + this.first.prev = null; + } + return target.value; + } +}; + +// pure.ts +var JS = class { + generateSecretKey() { + return schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return bytesToHex2(schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = bytesToHex2(schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = bytesToHex2(schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = sha256(utf8Encoder.encode(serializeEvent(event))); + return bytesToHex2(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// kinds.ts +var ClientAuth = 22242; + +// filter.ts +function matchFilter(filter, event) { + if (filter.ids && filter.ids.indexOf(event.id) === -1) { + return false; + } + if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) { + return false; + } + if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) { + return false; + } + for (let f in filter) { + if (f[0] === "#") { + let tagName = f.slice(1); + let values = filter[`#${tagName}`]; + if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values.indexOf(v) !== -1)) + return false; + } + } + if (filter.since && event.created_at < filter.since) + return false; + if (filter.until && event.created_at > filter.until) + return false; + return true; +} +function matchFilters(filters, event) { + for (let i2 = 0; i2 < filters.length; i2++) { + if (matchFilter(filters[i2], event)) { + return true; + } + } + return false; +} + +// fakejson.ts +function getHex64(json, field) { + let len = field.length + 3; + let idx = json.indexOf(`"${field}":`) + len; + let s = json.slice(idx).indexOf(`"`) + idx + 1; + return json.slice(s, s + 64); +} +function getSubscriptionId(json) { + let idx = json.slice(0, 22).indexOf(`"EVENT"`); + if (idx === -1) + return null; + let pstart = json.slice(idx + 7 + 1).indexOf(`"`); + if (pstart === -1) + return null; + let start = idx + 7 + 1 + pstart; + let pend = json.slice(start + 1, 80).indexOf(`"`); + if (pend === -1) + return null; + let end = start + 1 + pend; + return json.slice(start + 1, end); +} + +// nip42.ts +function makeAuthEvent(relayURL, challenge) { + return { + kind: ClientAuth, + created_at: Math.floor(Date.now() / 1e3), + tags: [ + ["relay", relayURL], + ["challenge", challenge] + ], + content: "" + }; +} + +// helpers.ts +async function yieldThread() { + return new Promise((resolve) => { + const ch = new MessageChannel(); + const handler = () => { + ch.port1.removeEventListener("message", handler); + resolve(); + }; + ch.port1.addEventListener("message", handler); + ch.port2.postMessage(0); + ch.port1.start(); + }); +} + +// abstract-relay.ts +var SendingOnClosedConnection = class extends Error { + constructor(message, relay) { + super(`Tried to send message '${message} on a closed connection to ${relay}.`); + this.name = "SendingOnClosedConnection"; + } +}; +var AbstractRelay = class { + url; + _connected = false; + onclose = null; + onnotice = (msg) => console.debug(`NOTICE from ${this.url}: ${msg}`); + baseEoseTimeout = 4400; + connectionTimeout = 4400; + publishTimeout = 4400; + pingFrequency = 2e4; + pingTimeout = 2e4; + openSubs = /* @__PURE__ */ new Map(); + enablePing; + connectionTimeoutHandle; + connectionPromise; + openCountRequests = /* @__PURE__ */ new Map(); + openEventPublishes = /* @__PURE__ */ new Map(); + ws; + incomingMessageQueue = new Queue(); + queueRunning = false; + challenge; + authPromise; + serial = 0; + verifyEvent; + _WebSocket; + constructor(url, opts) { + this.url = normalizeURL(url); + this.verifyEvent = opts.verifyEvent; + this._WebSocket = opts.websocketImplementation || WebSocket; + this.enablePing = opts.enablePing; + } + static async connect(url, opts) { + const relay = new AbstractRelay(url, opts); + await relay.connect(); + return relay; + } + closeAllSubscriptions(reason) { + for (let [_, sub] of this.openSubs) { + sub.close(reason); + } + this.openSubs.clear(); + for (let [_, ep] of this.openEventPublishes) { + ep.reject(new Error(reason)); + } + this.openEventPublishes.clear(); + for (let [_, cr] of this.openCountRequests) { + cr.reject(new Error(reason)); + } + this.openCountRequests.clear(); + } + get connected() { + return this._connected; + } + async connect() { + if (this.connectionPromise) + return this.connectionPromise; + this.challenge = void 0; + this.authPromise = void 0; + this.connectionPromise = new Promise((resolve, reject) => { + this.connectionTimeoutHandle = setTimeout(() => { + reject("connection timed out"); + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection timed out"); + }, this.connectionTimeout); + try { + this.ws = new this._WebSocket(this.url); + } catch (err) { + clearTimeout(this.connectionTimeoutHandle); + reject(err); + return; + } + this.ws.onopen = () => { + clearTimeout(this.connectionTimeoutHandle); + this._connected = true; + if (this.enablePing) { + this.pingpong(); + } + resolve(); + }; + this.ws.onerror = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket error"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection errored"); + } + }; + this.ws.onclose = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket closed"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection closed"); + } + }; + this.ws.onmessage = this._onmessage.bind(this); + }); + return this.connectionPromise; + } + async waitForPingPong() { + return new Promise((res, err) => { + ; + this.ws && this.ws.on && this.ws.on("pong", () => res(true)) || err("ws can't listen for pong"); + this.ws && this.ws.ping && this.ws.ping(); + }); + } + async waitForDummyReq() { + return new Promise((resolve, _) => { + const sub = this.subscribe([{ ids: ["a".repeat(64)] }], { + oneose: () => { + sub.close(); + resolve(true); + }, + eoseTimeout: this.pingTimeout + 1e3 + }); + }); + } + async pingpong() { + if (this.ws?.readyState === 1) { + const result = await Promise.any([ + this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(), + new Promise((res) => setTimeout(() => res(false), this.pingTimeout)) + ]); + if (result) { + setTimeout(() => this.pingpong(), this.pingFrequency); + } else { + this.closeAllSubscriptions("pingpong timed out"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + } + } + async runQueue() { + this.queueRunning = true; + while (true) { + if (false === this.handleNext()) { + break; + } + await yieldThread(); + } + this.queueRunning = false; + } + handleNext() { + const json = this.incomingMessageQueue.dequeue(); + if (!json) { + return false; + } + const subid = getSubscriptionId(json); + if (subid) { + const so = this.openSubs.get(subid); + if (!so) { + return; + } + const id = getHex64(json, "id"); + const alreadyHave = so.alreadyHaveEvent?.(id); + so.receivedEvent?.(this, id); + if (alreadyHave) { + return; + } + } + try { + let data = JSON.parse(json); + switch (data[0]) { + case "EVENT": { + const so = this.openSubs.get(data[1]); + const event = data[2]; + if (this.verifyEvent(event) && matchFilters(so.filters, event)) { + so.onevent(event); + } + return; + } + case "COUNT": { + const id = data[1]; + const payload = data[2]; + const cr = this.openCountRequests.get(id); + if (cr) { + cr.resolve(payload.count); + this.openCountRequests.delete(id); + } + return; + } + case "EOSE": { + const so = this.openSubs.get(data[1]); + if (!so) + return; + so.receivedEose(); + return; + } + case "OK": { + const id = data[1]; + const ok = data[2]; + const reason = data[3]; + const ep = this.openEventPublishes.get(id); + if (ep) { + clearTimeout(ep.timeout); + if (ok) + ep.resolve(reason); + else + ep.reject(new Error(reason)); + this.openEventPublishes.delete(id); + } + return; + } + case "CLOSED": { + const id = data[1]; + const so = this.openSubs.get(id); + if (!so) + return; + so.closed = true; + so.close(data[2]); + return; + } + case "NOTICE": + this.onnotice(data[1]); + return; + case "AUTH": { + this.challenge = data[1]; + return; + } + } + } catch (err) { + return; + } + } + async send(message) { + if (!this.connectionPromise) + throw new SendingOnClosedConnection(message, this.url); + this.connectionPromise.then(() => { + this.ws?.send(message); + }); + } + async auth(signAuthEvent) { + const challenge = this.challenge; + if (!challenge) + throw new Error("can't perform auth, no challenge was received"); + if (this.authPromise) + return this.authPromise; + this.authPromise = new Promise(async (resolve, reject) => { + try { + let evt = await signAuthEvent(makeAuthEvent(this.url, challenge)); + let timeout = setTimeout(() => { + let ep = this.openEventPublishes.get(evt.id); + if (ep) { + ep.reject(new Error("auth timed out")); + this.openEventPublishes.delete(evt.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(evt.id, { resolve, reject, timeout }); + this.send('["AUTH",' + JSON.stringify(evt) + "]"); + } catch (err) { + console.warn("subscribe auth function failed:", err); + } + }); + return this.authPromise; + } + async publish(event) { + const ret = new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + const ep = this.openEventPublishes.get(event.id); + if (ep) { + ep.reject(new Error("publish timed out")); + this.openEventPublishes.delete(event.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(event.id, { resolve, reject, timeout }); + }); + this.send('["EVENT",' + JSON.stringify(event) + "]"); + return ret; + } + async count(filters, params) { + this.serial++; + const id = params?.id || "count:" + this.serial; + const ret = new Promise((resolve, reject) => { + this.openCountRequests.set(id, { resolve, reject }); + }); + this.send('["COUNT","' + id + '",' + JSON.stringify(filters).substring(1)); + return ret; + } + subscribe(filters, params) { + const subscription = this.prepareSubscription(filters, params); + subscription.fire(); + return subscription; + } + prepareSubscription(filters, params) { + this.serial++; + const id = params.id || (params.label ? params.label + ":" : "sub:") + this.serial; + const subscription = new Subscription(this, id, filters, params); + this.openSubs.set(id, subscription); + return subscription; + } + close() { + this.closeAllSubscriptions("relay connection closed by us"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + _onmessage(ev) { + this.incomingMessageQueue.enqueue(ev.data); + if (!this.queueRunning) { + this.runQueue(); + } + } +}; +var Subscription = class { + relay; + id; + closed = false; + eosed = false; + filters; + alreadyHaveEvent; + receivedEvent; + onevent; + oneose; + onclose; + eoseTimeout; + eoseTimeoutHandle; + constructor(relay, id, filters, params) { + this.relay = relay; + this.filters = filters; + this.id = id; + this.alreadyHaveEvent = params.alreadyHaveEvent; + this.receivedEvent = params.receivedEvent; + this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout; + this.oneose = params.oneose; + this.onclose = params.onclose; + this.onevent = params.onevent || ((event) => { + console.warn( + `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`, + event + ); + }); + } + fire() { + this.relay.send('["REQ","' + this.id + '",' + JSON.stringify(this.filters).substring(1)); + this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout); + } + receivedEose() { + if (this.eosed) + return; + clearTimeout(this.eoseTimeoutHandle); + this.eosed = true; + this.oneose?.(); + } + close(reason = "closed by caller") { + if (!this.closed && this.relay.connected) { + try { + this.relay.send('["CLOSE",' + JSON.stringify(this.id) + "]"); + } catch (err) { + if (err instanceof SendingOnClosedConnection) { + } else { + throw err; + } + } + this.closed = true; + } + this.relay.openSubs.delete(this.id); + this.onclose?.(reason); + } +}; + +// relay.ts +var _WebSocket; +try { + _WebSocket = WebSocket; +} catch { +} +function useWebSocketImplementation(websocketImplementation) { + _WebSocket = websocketImplementation; +} +var Relay = class extends AbstractRelay { + constructor(url) { + super(url, { verifyEvent, websocketImplementation: _WebSocket }); + } + static async connect(url) { + const relay = new Relay(url); + await relay.connect(); + return relay; + } +}; +export { + AbstractRelay, + Relay, + SendingOnClosedConnection, + Subscription, + useWebSocketImplementation +}; diff --git a/node_modules/nostr-tools/lib/esm/relay.js.map b/node_modules/nostr-tools/lib/esm/relay.js.map new file mode 100644 index 0000000..85661e9 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/relay.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../pure.ts", "../../core.ts", "../../utils.ts", "../../kinds.ts", "../../filter.ts", "../../fakejson.ts", "../../nip42.ts", "../../helpers.ts", "../../abstract-relay.ts", "../../relay.ts"], + "sourcesContent": ["import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { Event } from './core.ts'\nimport { isAddressableKind, isReplaceableKind } from './kinds.ts'\n\nexport type Filter = {\n ids?: string[]\n kinds?: number[]\n authors?: string[]\n since?: number\n until?: number\n limit?: number\n search?: string\n [key: `#${string}`]: string[] | undefined\n}\n\nexport function matchFilter(filter: Filter, event: Event): boolean {\n if (filter.ids && filter.ids.indexOf(event.id) === -1) {\n return false\n }\n if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) {\n return false\n }\n if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) {\n return false\n }\n\n for (let f in filter) {\n if (f[0] === '#') {\n let tagName = f.slice(1)\n let values = filter[`#${tagName}`]\n if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values!.indexOf(v) !== -1)) return false\n }\n }\n\n if (filter.since && event.created_at < filter.since) return false\n if (filter.until && event.created_at > filter.until) return false\n\n return true\n}\n\nexport function matchFilters(filters: Filter[], event: Event): boolean {\n for (let i = 0; i < filters.length; i++) {\n if (matchFilter(filters[i], event)) {\n return true\n }\n }\n return false\n}\n\nexport function mergeFilters(...filters: Filter[]): Filter {\n let result: Filter = {}\n for (let i = 0; i < filters.length; i++) {\n let filter = filters[i]\n Object.entries(filter).forEach(([property, values]) => {\n if (property === 'kinds' || property === 'ids' || property === 'authors' || property[0] === '#') {\n // @ts-ignore\n result[property] = result[property] || []\n // @ts-ignore\n for (let v = 0; v < values.length; v++) {\n // @ts-ignore\n let value = values[v]\n // @ts-ignore\n if (!result[property].includes(value)) result[property].push(value)\n }\n }\n })\n\n if (filter.limit && (!result.limit || filter.limit > result.limit)) result.limit = filter.limit\n if (filter.until && (!result.until || filter.until > result.until)) result.until = filter.until\n if (filter.since && (!result.since || filter.since < result.since)) result.since = filter.since\n }\n\n return result\n}\n\n/**\n * Calculate the intrinsic limit of a filter.\n * This function returns a positive integer, or `Infinity` if there is no intrinsic limit.\n */\nexport function getFilterLimit(filter: Filter): number {\n if (filter.ids && !filter.ids.length) return 0\n if (filter.kinds && !filter.kinds.length) return 0\n if (filter.authors && !filter.authors.length) return 0\n\n for (const [key, value] of Object.entries(filter)) {\n if (key[0] === '#' && Array.isArray(value) && !value.length) return 0\n }\n\n return Math.min(\n // The `limit` property creates an artificial limit.\n Math.max(0, filter.limit ?? Infinity),\n\n // There can only be one event per `id`.\n filter.ids?.length ?? Infinity,\n\n // Replaceable events are limited by the number of authors and kinds.\n filter.authors?.length && filter.kinds?.every(kind => isReplaceableKind(kind))\n ? filter.authors.length * filter.kinds.length\n : Infinity,\n\n // Parameterized replaceable events are limited by the number of authors, kinds, and \"d\" tags.\n filter.authors?.length && filter.kinds?.every(kind => isAddressableKind(kind)) && filter['#d']?.length\n ? filter.authors.length * filter.kinds.length * filter['#d'].length\n : Infinity,\n )\n}\n", "export function getHex64(json: string, field: string): string {\n let len = field.length + 3\n let idx = json.indexOf(`\"${field}\":`) + len\n let s = json.slice(idx).indexOf(`\"`) + idx + 1\n return json.slice(s, s + 64)\n}\n\nexport function getInt(json: string, field: string): number {\n let len = field.length\n let idx = json.indexOf(`\"${field}\":`) + len + 3\n let sliced = json.slice(idx)\n let end = Math.min(sliced.indexOf(','), sliced.indexOf('}'))\n return parseInt(sliced.slice(0, end), 10)\n}\n\nexport function getSubscriptionId(json: string): string | null {\n let idx = json.slice(0, 22).indexOf(`\"EVENT\"`)\n if (idx === -1) return null\n\n let pstart = json.slice(idx + 7 + 1).indexOf(`\"`)\n if (pstart === -1) return null\n let start = idx + 7 + 1 + pstart\n\n let pend = json.slice(start + 1, 80).indexOf(`\"`)\n if (pend === -1) return null\n let end = start + 1 + pend\n\n return json.slice(start + 1, end)\n}\n\nexport function matchEventId(json: string, id: string): boolean {\n return id === getHex64(json, 'id')\n}\n\nexport function matchEventPubkey(json: string, pubkey: string): boolean {\n return pubkey === getHex64(json, 'pubkey')\n}\n\nexport function matchEventKind(json: string, kind: number): boolean {\n return kind === getInt(json, 'kind')\n}\n", "import { EventTemplate } from './core.ts'\nimport { ClientAuth } from './kinds.ts'\n\n/**\n * creates an EventTemplate for an AUTH event to be signed.\n */\nexport function makeAuthEvent(relayURL: string, challenge: string): EventTemplate {\n return {\n kind: ClientAuth,\n created_at: Math.floor(Date.now() / 1000),\n tags: [\n ['relay', relayURL],\n ['challenge', challenge],\n ],\n content: '',\n }\n}\n", "import { verifiedSymbol, type Event, type Nostr, VerifiedEvent } from './core.ts'\n\nexport async function yieldThread() {\n return new Promise(resolve => {\n const ch = new MessageChannel()\n const handler = () => {\n // @ts-ignore (typescript thinks this property should be called `removeListener`, but in fact it's `removeEventListener`)\n ch.port1.removeEventListener('message', handler)\n resolve()\n }\n // @ts-ignore (typescript thinks this property should be called `addListener`, but in fact it's `addEventListener`)\n ch.port1.addEventListener('message', handler)\n ch.port2.postMessage(0)\n ch.port1.start()\n })\n}\n\nexport const alwaysTrue: Nostr['verifyEvent'] = (t: Event): t is VerifiedEvent => {\n t[verifiedSymbol] = true\n return true\n}\n", "/* global WebSocket */\n\nimport type { Event, EventTemplate, VerifiedEvent, Nostr, NostrEvent } from './core.ts'\nimport { matchFilters, type Filter } from './filter.ts'\nimport { getHex64, getSubscriptionId } from './fakejson.ts'\nimport { Queue, normalizeURL } from './utils.ts'\nimport { makeAuthEvent } from './nip42.ts'\nimport { yieldThread } from './helpers.ts'\n\ntype RelayWebSocket = WebSocket & {\n ping?(): void\n on?(event: 'pong', listener: () => void): any\n}\n\nexport type AbstractRelayConstructorOptions = {\n verifyEvent: Nostr['verifyEvent']\n websocketImplementation?: typeof WebSocket\n enablePing?: boolean\n}\n\nexport class SendingOnClosedConnection extends Error {\n constructor(message: string, relay: string) {\n super(`Tried to send message '${message} on a closed connection to ${relay}.`)\n this.name = 'SendingOnClosedConnection'\n }\n}\n\nexport class AbstractRelay {\n public readonly url: string\n private _connected: boolean = false\n\n public onclose: (() => void) | null = null\n public onnotice: (msg: string) => void = msg => console.debug(`NOTICE from ${this.url}: ${msg}`)\n\n public baseEoseTimeout: number = 4400\n public connectionTimeout: number = 4400\n public publishTimeout: number = 4400\n public pingFrequency: number = 20000\n public pingTimeout: number = 20000\n public openSubs: Map = new Map()\n public enablePing: boolean | undefined\n private connectionTimeoutHandle: ReturnType | undefined\n\n private connectionPromise: Promise | undefined\n private openCountRequests = new Map()\n private openEventPublishes = new Map()\n private ws: RelayWebSocket | undefined\n private incomingMessageQueue = new Queue()\n private queueRunning = false\n private challenge: string | undefined\n private authPromise: Promise | undefined\n private serial: number = 0\n private verifyEvent: Nostr['verifyEvent']\n\n private _WebSocket: typeof WebSocket\n\n constructor(url: string, opts: AbstractRelayConstructorOptions) {\n this.url = normalizeURL(url)\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation || WebSocket\n this.enablePing = opts.enablePing\n }\n\n static async connect(url: string, opts: AbstractRelayConstructorOptions): Promise {\n const relay = new AbstractRelay(url, opts)\n await relay.connect()\n return relay\n }\n\n private closeAllSubscriptions(reason: string) {\n for (let [_, sub] of this.openSubs) {\n sub.close(reason)\n }\n this.openSubs.clear()\n\n for (let [_, ep] of this.openEventPublishes) {\n ep.reject(new Error(reason))\n }\n this.openEventPublishes.clear()\n\n for (let [_, cr] of this.openCountRequests) {\n cr.reject(new Error(reason))\n }\n this.openCountRequests.clear()\n }\n\n public get connected(): boolean {\n return this._connected\n }\n\n public async connect(): Promise {\n if (this.connectionPromise) return this.connectionPromise\n\n this.challenge = undefined\n this.authPromise = undefined\n this.connectionPromise = new Promise((resolve, reject) => {\n this.connectionTimeoutHandle = setTimeout(() => {\n reject('connection timed out')\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection timed out')\n }, this.connectionTimeout)\n\n try {\n this.ws = new this._WebSocket(this.url)\n } catch (err) {\n clearTimeout(this.connectionTimeoutHandle)\n reject(err)\n return\n }\n\n this.ws.onopen = () => {\n clearTimeout(this.connectionTimeoutHandle)\n this._connected = true\n if (this.enablePing) {\n this.pingpong()\n }\n resolve()\n }\n\n this.ws.onerror = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket error')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection errored')\n }\n }\n\n this.ws.onclose = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket closed')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection closed')\n }\n }\n\n this.ws.onmessage = this._onmessage.bind(this)\n })\n\n return this.connectionPromise\n }\n\n private async waitForPingPong() {\n return new Promise((res, err) => {\n // listen for pong\n ;(this.ws && this.ws.on && this.ws.on('pong', () => res(true))) || err(\"ws can't listen for pong\")\n // send a ping\n this.ws && this.ws.ping && this.ws.ping()\n })\n }\n\n private async waitForDummyReq() {\n return new Promise((resolve, _) => {\n // make a dummy request with expected empty eose reply\n // [\"REQ\", \"_\", {\"ids\":[\"aaaa...aaaa\"]}]\n const sub = this.subscribe([{ ids: ['a'.repeat(64)] }], {\n oneose: () => {\n sub.close()\n resolve(true)\n },\n eoseTimeout: this.pingTimeout + 1000,\n })\n })\n }\n\n // nodejs requires this magic here to ensure connections are closed when internet goes off and stuff\n // in browsers it's done automatically. see https://github.com/nbd-wtf/nostr-tools/issues/491\n private async pingpong() {\n // if the websocket is connected\n if (this.ws?.readyState === 1) {\n // wait for either a ping-pong reply or a timeout\n const result = await Promise.any([\n // browsers don't have ping so use a dummy req\n this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(),\n new Promise(res => setTimeout(() => res(false), this.pingTimeout)),\n ])\n if (result) {\n // schedule another pingpong\n setTimeout(() => this.pingpong(), this.pingFrequency)\n } else {\n // pingpong closing socket\n this.closeAllSubscriptions('pingpong timed out')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n }\n }\n\n private async runQueue() {\n this.queueRunning = true\n while (true) {\n if (false === this.handleNext()) {\n break\n }\n await yieldThread()\n }\n this.queueRunning = false\n }\n\n private handleNext(): undefined | false {\n const json = this.incomingMessageQueue.dequeue()\n if (!json) {\n return false\n }\n\n const subid = getSubscriptionId(json)\n if (subid) {\n const so = this.openSubs.get(subid as string)\n if (!so) {\n // this is an EVENT message, but for a subscription we don't have, so just stop here\n return\n }\n\n // this will be called only when this message is a EVENT message for a subscription we have\n // we do this before parsing the JSON to not have to do that for duplicate events\n // since JSON parsing is slow\n const id = getHex64(json, 'id')\n const alreadyHave = so.alreadyHaveEvent?.(id)\n\n // notify any interested client that the relay has this event\n // (do this after alreadyHaveEvent() because the client may rely on this to answer that)\n so.receivedEvent?.(this, id)\n\n if (alreadyHave) {\n // if we had already seen this event we can just stop here\n return\n }\n }\n\n try {\n let data = JSON.parse(json)\n // we won't do any checks against the data since all failures (i.e. invalid messages from relays)\n // will naturally be caught by the encompassing try..catch block\n\n switch (data[0]) {\n case 'EVENT': {\n const so = this.openSubs.get(data[1] as string) as Subscription\n const event = data[2] as NostrEvent\n if (this.verifyEvent(event) && matchFilters(so.filters, event)) {\n so.onevent(event)\n }\n return\n }\n case 'COUNT': {\n const id: string = data[1]\n const payload = data[2] as { count: number }\n const cr = this.openCountRequests.get(id) as CountResolver\n if (cr) {\n cr.resolve(payload.count)\n this.openCountRequests.delete(id)\n }\n return\n }\n case 'EOSE': {\n const so = this.openSubs.get(data[1] as string)\n if (!so) return\n so.receivedEose()\n return\n }\n case 'OK': {\n const id: string = data[1]\n const ok: boolean = data[2]\n const reason: string = data[3]\n const ep = this.openEventPublishes.get(id) as EventPublishResolver\n if (ep) {\n clearTimeout(ep.timeout)\n if (ok) ep.resolve(reason)\n else ep.reject(new Error(reason))\n this.openEventPublishes.delete(id)\n }\n return\n }\n case 'CLOSED': {\n const id: string = data[1]\n const so = this.openSubs.get(id)\n if (!so) return\n so.closed = true\n so.close(data[2] as string)\n return\n }\n case 'NOTICE':\n this.onnotice(data[1] as string)\n return\n case 'AUTH': {\n this.challenge = data[1] as string\n return\n }\n }\n } catch (err) {\n return\n }\n }\n\n public async send(message: string) {\n if (!this.connectionPromise) throw new SendingOnClosedConnection(message, this.url)\n\n this.connectionPromise.then(() => {\n this.ws?.send(message)\n })\n }\n\n public async auth(signAuthEvent: (evt: EventTemplate) => Promise): Promise {\n const challenge = this.challenge\n if (!challenge) throw new Error(\"can't perform auth, no challenge was received\")\n if (this.authPromise) return this.authPromise\n\n this.authPromise = new Promise(async (resolve, reject) => {\n try {\n let evt = await signAuthEvent(makeAuthEvent(this.url, challenge))\n let timeout = setTimeout(() => {\n let ep = this.openEventPublishes.get(evt.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('auth timed out'))\n this.openEventPublishes.delete(evt.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(evt.id, { resolve, reject, timeout })\n this.send('[\"AUTH\",' + JSON.stringify(evt) + ']')\n } catch (err) {\n console.warn('subscribe auth function failed:', err)\n }\n })\n return this.authPromise\n }\n\n public async publish(event: Event): Promise {\n const ret = new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n const ep = this.openEventPublishes.get(event.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('publish timed out'))\n this.openEventPublishes.delete(event.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(event.id, { resolve, reject, timeout })\n })\n this.send('[\"EVENT\",' + JSON.stringify(event) + ']')\n return ret\n }\n\n public async count(filters: Filter[], params: { id?: string | null }): Promise {\n this.serial++\n const id = params?.id || 'count:' + this.serial\n const ret = new Promise((resolve, reject) => {\n this.openCountRequests.set(id, { resolve, reject })\n })\n this.send('[\"COUNT\",\"' + id + '\",' + JSON.stringify(filters).substring(1))\n return ret\n }\n\n public subscribe(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n const subscription = this.prepareSubscription(filters, params)\n subscription.fire()\n return subscription\n }\n\n public prepareSubscription(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n this.serial++\n const id = params.id || (params.label ? params.label + ':' : 'sub:') + this.serial\n const subscription = new Subscription(this, id, filters, params)\n this.openSubs.set(id, subscription)\n return subscription\n }\n\n public close() {\n this.closeAllSubscriptions('relay connection closed by us')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n\n // this is the function assigned to this.ws.onmessage\n // it's exposed for testing and debugging purposes\n public _onmessage(ev: MessageEvent) {\n this.incomingMessageQueue.enqueue(ev.data as string)\n if (!this.queueRunning) {\n this.runQueue()\n }\n }\n}\n\nexport class Subscription {\n public readonly relay: AbstractRelay\n public readonly id: string\n\n public closed: boolean = false\n public eosed: boolean = false\n public filters: Filter[]\n public alreadyHaveEvent: ((id: string) => boolean) | undefined\n public receivedEvent: ((relay: AbstractRelay, id: string) => void) | undefined\n\n public onevent: (evt: Event) => void\n public oneose: (() => void) | undefined\n public onclose: ((reason: string) => void) | undefined\n\n public eoseTimeout: number\n private eoseTimeoutHandle: ReturnType | undefined\n\n constructor(relay: AbstractRelay, id: string, filters: Filter[], params: SubscriptionParams) {\n this.relay = relay\n this.filters = filters\n this.id = id\n this.alreadyHaveEvent = params.alreadyHaveEvent\n this.receivedEvent = params.receivedEvent\n this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout\n\n this.oneose = params.oneose\n this.onclose = params.onclose\n this.onevent =\n params.onevent ||\n (event => {\n console.warn(\n `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,\n event,\n )\n })\n }\n\n public fire() {\n this.relay.send('[\"REQ\",\"' + this.id + '\",' + JSON.stringify(this.filters).substring(1))\n\n // only now we start counting the eoseTimeout\n this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout)\n }\n\n public receivedEose() {\n if (this.eosed) return\n clearTimeout(this.eoseTimeoutHandle)\n this.eosed = true\n this.oneose?.()\n }\n\n public close(reason: string = 'closed by caller') {\n if (!this.closed && this.relay.connected) {\n // if the connection was closed by the user calling .close() we will send a CLOSE message\n // otherwise this._open will be already set to false so we will skip this\n try {\n this.relay.send('[\"CLOSE\",' + JSON.stringify(this.id) + ']')\n } catch (err) {\n if (err instanceof SendingOnClosedConnection) {\n /* doesn't matter, it's ok */\n } else {\n throw err\n }\n }\n this.closed = true\n }\n this.relay.openSubs.delete(this.id)\n this.onclose?.(reason)\n }\n}\n\nexport type SubscriptionParams = {\n onevent?: (evt: Event) => void\n oneose?: () => void\n onclose?: (reason: string) => void\n alreadyHaveEvent?: (id: string) => boolean\n receivedEvent?: (relay: AbstractRelay, id: string) => void\n eoseTimeout?: number\n}\n\nexport type CountResolver = {\n resolve: (count: number) => void\n reject: (err: Error) => void\n}\n\nexport type EventPublishResolver = {\n resolve: (reason: string) => void\n reject: (err: Error) => void\n timeout: ReturnType\n}\n", "/* global WebSocket */\n\nimport { verifyEvent } from './pure.ts'\nimport { AbstractRelay } from './abstract-relay.ts'\n\nvar _WebSocket: typeof WebSocket\n\ntry {\n _WebSocket = WebSocket\n} catch {}\n\nexport function useWebSocketImplementation(websocketImplementation: any) {\n _WebSocket = websocketImplementation\n}\n\nexport class Relay extends AbstractRelay {\n constructor(url: string) {\n super(url, { verifyEvent, websocketImplementation: _WebSocket })\n }\n\n static async connect(url: string): Promise {\n const relay = new Relay(url)\n await relay.connect()\n return relay\n }\n}\n\nexport type RelayRecord = Record\n\nexport * from './abstract-relay.ts'\n"], + "mappings": ";AAAA,SAAS,eAAe;AACxB,SAAS,cAAAA,mBAAkB;;;ACOpB,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,CAAC,QAAiD,eAAe;AAE3E,SAAS,cAAiB,OAAsC;AACrE,MAAI,CAAC,SAAS,KAAK;AAAG,WAAO;AAC7B,MAAI,OAAO,MAAM,SAAS;AAAU,WAAO;AAC3C,MAAI,OAAO,MAAM,YAAY;AAAU,WAAO;AAC9C,MAAI,OAAO,MAAM,eAAe;AAAU,WAAO;AACjD,MAAI,OAAO,MAAM,WAAW;AAAU,WAAO;AAC7C,MAAI,CAAC,MAAM,OAAO,MAAM,gBAAgB;AAAG,WAAO;AAElD,MAAI,CAAC,MAAM,QAAQ,MAAM,IAAI;AAAG,WAAO;AACvC,WAASC,KAAI,GAAGA,KAAI,MAAM,KAAK,QAAQA,MAAK;AAC1C,QAAI,MAAM,MAAM,KAAKA;AACrB,QAAI,CAAC,MAAM,QAAQ,GAAG;AAAG,aAAO;AAChC,aAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,UAAI,OAAO,IAAI,OAAO;AAAU,eAAO;AAAA,IACzC;AAAA,EACF;AAEA,SAAO;AACT;;;AD/CA,SAAS,cAAc;;;AEEvB,SAAS,YAAY,kBAAkB;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,c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S;AAAA,EAChB;AAAA,EAEO,MAAM,SAAiB,oBAAoB;AAChD,QAAI,CAAC,KAAK,UAAU,KAAK,MAAM,WAAW;AAGxC,UAAI;AACF,aAAK,MAAM,KAAK,cAAc,KAAK,UAAU,KAAK,EAAE,IAAI,GAAG;AAAA,MAC7D,SAAS,KAAP;AACA,YAAI,eAAe,2BAA2B;AAAA,QAE9C,OAAO;AACL,gBAAM;AAAA,QACR;AAAA,MACF;AACA,WAAK,SAAS;AAAA,IAChB;AACA,SAAK,MAAM,SAAS,OAAO,KAAK,EAAE;AAClC,SAAK,UAAU,MAAM;AAAA,EACvB;AACF;;;AC1cA,IAAI;AAEJ,IAAI;AACF,eAAa;AACf,QAAE;AAAO;AAEF,SAAS,2BAA2B,yBAA8B;AACvE,eAAa;AACf;AAEO,IAAM,QAAN,cAAoB,cAAc;AAAA,EACvC,YAAY,KAAa;AACvB,UAAM,KAAK,EAAE,aAAa,yBAAyB,WAAW,CAAC;AAAA,EACjE;AAAA,EAEA,aAAa,QAAQ,KAA6B;AAChD,UAAM,QAAQ,IAAI,MAAM,GAAG;AAC3B,UAAM,MAAM,QAAQ;AACpB,WAAO;AAAA,EACT;AACF;", + "names": ["bytesToHex", "i", "target", "bytesToHex", "i"] +} diff --git a/node_modules/nostr-tools/lib/esm/signer.js b/node_modules/nostr-tools/lib/esm/signer.js new file mode 100644 index 0000000..cc39b62 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/signer.js @@ -0,0 +1,107 @@ +// pure.ts +import { schnorr } from "@noble/curves/secp256k1"; +import { bytesToHex as bytesToHex2 } from "@noble/hashes/utils"; + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} + +// pure.ts +import { sha256 } from "@noble/hashes/sha256"; + +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); + +// pure.ts +var JS = class { + generateSecretKey() { + return schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return bytesToHex2(schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = bytesToHex2(schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = bytesToHex2(schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash = getEventHash(event); + if (hash !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = schnorr.verify(event.sig, hash, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } +}; +function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); +} +function getEventHash(event) { + let eventHash = sha256(utf8Encoder.encode(serializeEvent(event))); + return bytesToHex2(eventHash); +} +var i = new JS(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; + +// signer.ts +var PlainKeySigner = class { + secretKey; + constructor(secretKey) { + this.secretKey = secretKey; + } + async getPublicKey() { + return getPublicKey(this.secretKey); + } + async signEvent(event) { + return finalizeEvent(event, this.secretKey); + } +}; +export { + PlainKeySigner +}; diff --git a/node_modules/nostr-tools/lib/esm/signer.js.map b/node_modules/nostr-tools/lib/esm/signer.js.map new file mode 100644 index 0000000..4489be6 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/signer.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../pure.ts", "../../core.ts", "../../utils.ts", "../../signer.ts"], + "sourcesContent": ["import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { EventTemplate, VerifiedEvent } from './core.ts'\nimport { finalizeEvent, getPublicKey } from './pure.ts'\n\nexport interface Signer {\n getPublicKey(): Promise\n signEvent(event: EventTemplate): Promise\n}\n\nexport class PlainKeySigner implements Signer {\n private secretKey: Uint8Array\n\n constructor(secretKey: Uint8Array) {\n this.secretKey = secretKey\n }\n\n async getPublicKey(): Promise {\n return getPublicKey(this.secretKey)\n }\n\n async signEvent(event: EventTemplate): Promise {\n return finalizeEvent(event, this.secretKey)\n }\n}\n"], + "mappings": ";AAAA,SAAS,eAAe;AACxB,SAAS,cAAAA,mBAAkB;;;ACOpB,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,CAAC,QAAiD,eAAe;AAE3E,SAAS,cAAiB,OAAsC;AACrE,MAAI,CAAC,SAAS,KAAK;AAAG,WAAO;AAC7B,MAAI,OAAO,MAAM,SAAS;AAAU,WAAO;AAC3C,MAAI,OAAO,MAAM,YAAY;AAAU,WAAO;AAC9C,MAAI,OAAO,MAAM,eAAe;AAAU,WAAO;AACjD,MAAI,OAAO,MAAM,WAAW;AAAU,WAAO;AAC7C,MAAI,CAAC,MAAM,OAAO,MAAM,gBAAgB;AAAG,WAAO;AAElD,MAAI,CAAC,MAAM,QAAQ,MAAM,IAAI;AAAG,WAAO;AACvC,WAASC,KAAI,GAAGA,KAAI,MAAM,KAAK,QAAQA,MAAK;AAC1C,QAAI,MAAM,MAAM,KAAKA;AACrB,QAAI,CAAC,MAAM,QAAQ,GAAG;AAAG,aAAO;AAChC,aAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,UAAI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,OAAO,eAAe,KAAK,CAAC,CAAC;AAChE,SAAOA,YAAW,SAAS;AAC7B;AAEA,IAAM,IAAQ,IAAI,GAAG;AAEd,IAAM,oBAAoB,EAAE;AAC5B,IAAM,eAAe,EAAE;AACvB,IAAM,gBAAgB,EAAE;AACxB,IAAM,cAAc,EAAE;;;AGjDtB,IAAM,iBAAN,MAAuC;AAAA,EACpC;AAAA,EAER,YAAY,WAAuB;AACjC,SAAK,YAAY;AAAA,EACnB;AAAA,EAEA,MAAM,eAAgC;AACpC,WAAO,aAAa,KAAK,SAAS;AAAA,EACpC;AAAA,EAEA,MAAM,UAAU,OAA8C;AAC5D,WAAO,cAAc,OAAO,KAAK,SAAS;AAAA,EAC5C;AACF;", + "names": ["bytesToHex", "i", "bytesToHex"] +} diff --git a/node_modules/nostr-tools/lib/esm/utils.js b/node_modules/nostr-tools/lib/esm/utils.js new file mode 100644 index 0000000..25a3b0a --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/utils.js @@ -0,0 +1,124 @@ +// utils.ts +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +var utf8Decoder = new TextDecoder("utf-8"); +var utf8Encoder = new TextEncoder(); +function normalizeURL(url) { + try { + if (url.indexOf("://") === -1) + url = "wss://" + url; + let p = new URL(url); + p.pathname = p.pathname.replace(/\/+/g, "/"); + if (p.pathname.endsWith("/")) + p.pathname = p.pathname.slice(0, -1); + if (p.port === "80" && p.protocol === "ws:" || p.port === "443" && p.protocol === "wss:") + p.port = ""; + p.searchParams.sort(); + p.hash = ""; + return p.toString(); + } catch (e) { + throw new Error(`Invalid URL: ${url}`); + } +} +function insertEventIntoDescendingList(sortedArray, event) { + const [idx, found] = binarySearch(sortedArray, (b) => { + if (event.id === b.id) + return 0; + if (event.created_at === b.created_at) + return -1; + return b.created_at - event.created_at; + }); + if (!found) { + sortedArray.splice(idx, 0, event); + } + return sortedArray; +} +function insertEventIntoAscendingList(sortedArray, event) { + const [idx, found] = binarySearch(sortedArray, (b) => { + if (event.id === b.id) + return 0; + if (event.created_at === b.created_at) + return -1; + return event.created_at - b.created_at; + }); + if (!found) { + sortedArray.splice(idx, 0, event); + } + return sortedArray; +} +function binarySearch(arr, compare) { + let start = 0; + let end = arr.length - 1; + while (start <= end) { + const mid = Math.floor((start + end) / 2); + const cmp = compare(arr[mid]); + if (cmp === 0) { + return [mid, true]; + } + if (cmp < 0) { + end = mid - 1; + } else { + start = mid + 1; + } + } + return [start, false]; +} +var QueueNode = class { + value; + next = null; + prev = null; + constructor(message) { + this.value = message; + } +}; +var Queue = class { + first; + last; + constructor() { + this.first = null; + this.last = null; + } + enqueue(value) { + const newNode = new QueueNode(value); + if (!this.last) { + this.first = newNode; + this.last = newNode; + } else if (this.last === this.first) { + this.last = newNode; + this.last.prev = this.first; + this.first.next = newNode; + } else { + newNode.prev = this.last; + this.last.next = newNode; + this.last = newNode; + } + return true; + } + dequeue() { + if (!this.first) + return null; + if (this.first === this.last) { + const target2 = this.first; + this.first = null; + this.last = null; + return target2.value; + } + const target = this.first; + this.first = target.next; + if (this.first) { + this.first.prev = null; + } + return target.value; + } +}; +export { + Queue, + QueueNode, + binarySearch, + bytesToHex, + hexToBytes, + insertEventIntoAscendingList, + insertEventIntoDescendingList, + normalizeURL, + utf8Decoder, + utf8Encoder +}; diff --git a/node_modules/nostr-tools/lib/esm/utils.js.map b/node_modules/nostr-tools/lib/esm/utils.js.map new file mode 100644 index 0000000..c23de92 --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/utils.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../utils.ts"], + "sourcesContent": ["import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n"], + "mappings": ";AAKA,SAAS,YAAY,kBAAkB;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;AAIjD,SAAS,aAAa,KAAqB;AAChD,MAAI;AACF,QAAI,IAAI,QAAQ,KAAK,MAAM;AAAI,YAAM,WAAW;AAChD,QAAI,IAAI,IAAI,IAAI,GAAG;AACnB,MAAE,WAAW,EAAE,SAAS,QAAQ,QAAQ,GAAG;AAC3C,QAAI,EAAE,SAAS,SAAS,GAAG;AAAG,QAAE,WAAW,EAAE,SAAS,MAAM,GAAG,EAAE;AACjE,QAAK,EAAE,SAAS,QAAQ,EAAE,aAAa,SAAW,EAAE,SAAS,SAAS,EAAE,aAAa;AAAS,QAAE,OAAO;AACvG,MAAE,aAAa,KAAK;AACpB,MAAE,OAAO;AACT,WAAO,EAAE,SAAS;AAAA,EACpB,SAAS,GAAP;AACA,UAAM,IAAI,MAAM,gBAAgB,KAAK;AAAA,EACvC;AACF;AAEO,SAAS,8BAA8B,aAAsB,OAAuB;AACzF,QAAM,CAAC,KAAK,KAAK,IAAI,aAAa,aAAa,OAAK;AAClD,QAAI,MAAM,OAAO,EAAE;AAAI,aAAO;AAC9B,QAAI,MAAM,eAAe,EAAE;AAAY,aAAO;AAC9C,WAAO,EAAE,aAAa,MAAM;AAAA,EAC9B,CAAC;AACD,MAAI,CAAC,OAAO;AACV,gBAAY,OAAO,KAAK,GAAG,KAAK;AAAA,EAClC;AACA,SAAO;AACT;AAEO,SAAS,6BAA6B,aAAsB,OAAuB;AACxF,QAAM,CAAC,KAAK,KAAK,IAAI,aAAa,aAAa,OAAK;AAClD,QAAI,MAAM,OAAO,EAAE;AAAI,aAAO;AAC9B,QAAI,MAAM,eAAe,EAAE;AAAY,aAAO;AAC9C,WAAO,MAAM,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,KAAK;AACpB,WAAK,QAAQ;AACb,WAAK,OAAO;AACZ,aAAOA,QAAO;AAAA,IAChB;AAEA,UAAM,SAAS,KAAK;AACpB,SAAK,QAAQ,OAAO;AACpB,QAAI,KAAK,OAAO;AACd,WAAK,MAAM,OAAO;AAAA,IACpB;AAEA,WAAO,OAAO;AAAA,EAChB;AACF;", + "names": ["target"] +} diff --git a/node_modules/nostr-tools/lib/esm/wasm.js b/node_modules/nostr-tools/lib/esm/wasm.js new file mode 100644 index 0000000..9237a6b --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/wasm.js @@ -0,0 +1,82 @@ +// wasm.ts +import { bytesToHex } from "@noble/hashes/utils"; + +// core.ts +var verifiedSymbol = Symbol("verified"); +var isRecord = (obj) => obj instanceof Object; +function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; +} +function sortEvents(events) { + return events.sort((a, b) => { + if (a.created_at !== b.created_at) { + return b.created_at - a.created_at; + } + return a.id.localeCompare(b.id); + }); +} + +// wasm.ts +var nw; +function setNostrWasm(x) { + nw = x; +} +var Wasm = class { + generateSecretKey() { + return nw.generateSecretKey(); + } + getPublicKey(secretKey) { + return bytesToHex(nw.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + nw.finalizeEvent(t, secretKey); + return t; + } + verifyEvent(event) { + try { + nw.verifyEvent(event); + event[verifiedSymbol] = true; + return true; + } catch (err) { + return false; + } + } +}; +var i = new Wasm(); +var generateSecretKey = i.generateSecretKey; +var getPublicKey = i.getPublicKey; +var finalizeEvent = i.finalizeEvent; +var verifyEvent = i.verifyEvent; +export { + finalizeEvent, + generateSecretKey, + getPublicKey, + setNostrWasm, + sortEvents, + validateEvent, + verifiedSymbol, + verifyEvent +}; diff --git a/node_modules/nostr-tools/lib/esm/wasm.js.map b/node_modules/nostr-tools/lib/esm/wasm.js.map new file mode 100644 index 0000000..c97d15c --- /dev/null +++ b/node_modules/nostr-tools/lib/esm/wasm.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../wasm.ts", "../../core.ts"], + "sourcesContent": ["import { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr as NostrWasm } from 'nostr-wasm'\nimport { EventTemplate, Event, Nostr, VerifiedEvent, verifiedSymbol } from './core.ts'\n\nlet nw: NostrWasm\n\nexport function setNostrWasm(x: NostrWasm) {\n nw = x\n}\n\nclass Wasm implements Nostr {\n generateSecretKey(): Uint8Array {\n return nw.generateSecretKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(nw.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n nw.finalizeEvent(t as any, secretKey)\n return t as VerifiedEvent\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n try {\n nw.verifyEvent(event)\n event[verifiedSymbol] = true\n return true\n } catch (err) {\n return false\n }\n }\n}\n\nconst i: Wasm = new Wasm()\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n"], + "mappings": ";AAAA,SAAS,kBAAkB;;;ACQpB,IAAM,iBAAiB,OAAO,UAAU;AAsB/C,IAAM,WAAW,CAAC,QAAiD,eAAe;AAE3E,SAAS,cAAiB,OAAsC;AACrE,MAAI,CAAC,SAAS,KAAK;AAAG,WAAO;AAC7B,MAAI,OAAO,MAAM,SAAS;AAAU,WAAO;AAC3C,MAAI,OAAO,MAAM,YAAY;AAAU,WAAO;AAC9C,MAAI,OAAO,MAAM,eAAe;AAAU,WAAO;AACjD,MAAI,OAAO,MAAM,WAAW;AAAU,WAAO;AAC7C,MAAI,CAAC,MAAM,OAAO,MAAM,gBAAgB;AAAG,WAAO;AAElD,MAAI,CAAC,MAAM,QAAQ,MAAM,IAAI;AAAG,WAAO;AACvC,WAASA,KAAI,GAAGA,KAAI,MAAM,KAAK,QAAQA,MAAK;AAC1C,QAAI,MAAM,MAAM,KAAKA;AACrB,QAAI,CAAC,MAAM,QAAQ,GAAG;AAAG,aAAO;AAChC,aAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,UAAI,OAAO,IAAI,OAAO;AAAU,eAAO;AAAA,IACzC;AAAA,EACF;AAEA,SAAO;AACT;AAOO,SAAS,WAAW,QAA0B;AACnD,SAAO,OAAO,KAAK,CAAC,GAAe,MAA0B;AAC3D,QAAI,EAAE,eAAe,EAAE,YAAY;AACjC,aAAO,EAAE,aAAa,EAAE;AAAA,IAC1B;AACA,WAAO,EAAE,GAAG,cAAc,EAAE,EAAE;AAAA,EAChC,CAAC;AACH;;;AD5DA,IAAI;AAEG,SAAS,aAAa,GAAc;AACzC,OAAK;AACP;AAEA,IAAM,OAAN,MAA4B;AAAA,EAC1B,oBAAgC;AAC9B,WAAO,GAAG,kBAAkB;AAAA,EAC9B;AAAA,EACA,aAAa,WAA+B;AAC1C,WAAO,WAAW,GAAG,aAAa,SAAS,CAAC;AAAA,EAC9C;AAAA,EACA,cAAc,GAAkB,WAAsC;AACpE,OAAG,cAAc,GAAU,SAAS;AACpC,WAAO;AAAA,EACT;AAAA,EACA,YAAY,OAAsC;AAChD,QAAI;AACF,SAAG,YAAY,KAAK;AACpB,YAAM,kBAAkB;AACxB,aAAO;AAAA,IACT,SAAS,KAAP;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAEA,IAAM,IAAU,IAAI,KAAK;AAClB,IAAM,oBAAoB,EAAE;AAC5B,IAAM,eAAe,EAAE;AACvB,IAAM,gBAAgB,EAAE;AACxB,IAAM,cAAc,EAAE;", + "names": ["i"] +} diff --git a/node_modules/nostr-tools/lib/nostr.bundle.js b/node_modules/nostr-tools/lib/nostr.bundle.js new file mode 100644 index 0000000..17634d1 --- /dev/null +++ b/node_modules/nostr-tools/lib/nostr.bundle.js @@ -0,0 +1,6860 @@ +"use strict"; +var NostrTools = (() => { + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2); + + // index.ts + var nostr_tools_exports = {}; + __export(nostr_tools_exports, { + Relay: () => Relay, + SimplePool: () => SimplePool, + finalizeEvent: () => finalizeEvent, + fj: () => fakejson_exports, + generateSecretKey: () => generateSecretKey, + getEventHash: () => getEventHash, + getFilterLimit: () => getFilterLimit, + getPublicKey: () => getPublicKey, + kinds: () => kinds_exports, + matchFilter: () => matchFilter, + matchFilters: () => matchFilters, + mergeFilters: () => mergeFilters, + nip04: () => nip04_exports, + nip05: () => nip05_exports, + nip10: () => nip10_exports, + nip11: () => nip11_exports, + nip13: () => nip13_exports, + nip17: () => nip17_exports, + nip18: () => nip18_exports, + nip19: () => nip19_exports, + nip21: () => nip21_exports, + nip25: () => nip25_exports, + nip27: () => nip27_exports, + nip28: () => nip28_exports, + nip30: () => nip30_exports, + nip39: () => nip39_exports, + nip42: () => nip42_exports, + nip44: () => nip44_exports, + nip47: () => nip47_exports, + nip54: () => nip54_exports, + nip57: () => nip57_exports, + nip59: () => nip59_exports, + nip98: () => nip98_exports, + parseReferences: () => parseReferences, + serializeEvent: () => serializeEvent, + sortEvents: () => sortEvents, + utils: () => utils_exports2, + validateEvent: () => validateEvent, + verifiedSymbol: () => verifiedSymbol, + verifyEvent: () => verifyEvent + }); + + // node_modules/@noble/curves/node_modules/@noble/hashes/esm/_assert.js + function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); + } + function bytes(b, ...lengths) { + if (!(b instanceof Uint8Array)) + throw new Error("Expected Uint8Array"); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); + } + function hash(hash3) { + if (typeof hash3 !== "function" || typeof hash3.create !== "function") + throw new Error("Hash should be wrapped by utils.wrapConstructor"); + number(hash3.outputLen); + number(hash3.blockLen); + } + function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error("Hash instance has been destroyed"); + if (checkFinished && instance.finished) + throw new Error("Hash#digest() has already been called"); + } + function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } + } + + // node_modules/@noble/curves/node_modules/@noble/hashes/esm/crypto.js + var crypto = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0; + + // node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js + var u8a = (a) => a instanceof Uint8Array; + var createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); + var rotr = (word, shift) => word << 32 - shift | word >>> shift; + var isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; + if (!isLE) + throw new Error("Non little-endian hardware is not supported"); + function utf8ToBytes(str) { + if (typeof str !== "string") + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); + } + function toBytes(data) { + if (typeof data === "string") + data = utf8ToBytes(data); + if (!u8a(data)) + throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; + } + function concatBytes(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad2 = 0; + arrays.forEach((a) => { + if (!u8a(a)) + throw new Error("Uint8Array expected"); + r.set(a, pad2); + pad2 += a.length; + }); + return r; + } + var Hash = class { + clone() { + return this._cloneInto(); + } + }; + var toStr = {}.toString; + function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; + } + function randomBytes(bytesLength = 32) { + if (crypto && typeof crypto.getRandomValues === "function") { + return crypto.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error("crypto.getRandomValues must be defined"); + } + + // node_modules/@noble/curves/node_modules/@noble/hashes/esm/_sha2.js + function setBigUint64(view, byteOffset, value, isLE4) { + if (typeof view.setBigUint64 === "function") + return view.setBigUint64(byteOffset, value, isLE4); + const _32n = BigInt(32); + const _u32_max = BigInt(4294967295); + const wh = Number(value >> _32n & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE4 ? 4 : 0; + const l = isLE4 ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE4); + view.setUint32(byteOffset + l, wl, isLE4); + } + var SHA2 = class extends Hash { + constructor(blockLen, outputLen, padOffset, isLE4) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE4; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + exists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + exists(this); + output(out, this); + this.finished = true; + const { buffer, view, blockLen, isLE: isLE4 } = this; + let { pos } = this; + buffer[pos++] = 128; + this.buffer.subarray(pos).fill(0); + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + for (let i2 = pos; i2 < blockLen; i2++) + buffer[i2] = 0; + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE4); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + if (len % 4) + throw new Error("_sha2: outputLen should be aligned to 32bit"); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error("_sha2: outputLen bigger than state"); + for (let i2 = 0; i2 < outLen; i2++) + oview.setUint32(4 * i2, state[i2], isLE4); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } + }; + + // node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha256.js + var Chi = (a, b, c) => a & b ^ ~a & c; + var Maj = (a, b, c) => a & b ^ a & c ^ b & c; + var SHA256_K = /* @__PURE__ */ new Uint32Array([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 + ]); + var IV = /* @__PURE__ */ new Uint32Array([ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 + ]); + var SHA256_W = /* @__PURE__ */ new Uint32Array(64); + var SHA256 = class extends SHA2 { + constructor() { + super(64, 32, 8, false); + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + this.F = IV[5] | 0; + this.G = IV[6] | 0; + this.H = IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + for (let i2 = 0; i2 < 16; i2++, offset += 4) + SHA256_W[i2] = view.getUint32(offset, false); + for (let i2 = 16; i2 < 64; i2++) { + const W15 = SHA256_W[i2 - 15]; + const W2 = SHA256_W[i2 - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; + SHA256_W[i2] = s1 + SHA256_W[i2 - 7] + s0 + SHA256_W[i2 - 16] | 0; + } + let { A, B, C, D, E, F, G, H } = this; + for (let i2 = 0; i2 < 64; i2++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i2] + SHA256_W[i2] | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = sigma0 + Maj(A, B, C) | 0; + H = G; + G = F; + F = E; + E = D + T1 | 0; + D = C; + C = B; + B = A; + A = T1 + T2 | 0; + } + A = A + this.A | 0; + B = B + this.B | 0; + C = C + this.C | 0; + D = D + this.D | 0; + E = E + this.E | 0; + F = F + this.F | 0; + G = G + this.G | 0; + H = H + this.H | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } + }; + var sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); + + // node_modules/@noble/curves/esm/abstract/utils.js + var utils_exports = {}; + __export(utils_exports, { + bitGet: () => bitGet, + bitLen: () => bitLen, + bitMask: () => bitMask, + bitSet: () => bitSet, + bytesToHex: () => bytesToHex, + bytesToNumberBE: () => bytesToNumberBE, + bytesToNumberLE: () => bytesToNumberLE, + concatBytes: () => concatBytes2, + createHmacDrbg: () => createHmacDrbg, + ensureBytes: () => ensureBytes, + equalBytes: () => equalBytes, + hexToBytes: () => hexToBytes, + hexToNumber: () => hexToNumber, + numberToBytesBE: () => numberToBytesBE, + numberToBytesLE: () => numberToBytesLE, + numberToHexUnpadded: () => numberToHexUnpadded, + numberToVarBytesBE: () => numberToVarBytesBE, + utf8ToBytes: () => utf8ToBytes2, + validateObject: () => validateObject + }); + var _0n = BigInt(0); + var _1n = BigInt(1); + var _2n = BigInt(2); + var u8a2 = (a) => a instanceof Uint8Array; + var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i2) => i2.toString(16).padStart(2, "0")); + function bytesToHex(bytes4) { + if (!u8a2(bytes4)) + throw new Error("Uint8Array expected"); + let hex2 = ""; + for (let i2 = 0; i2 < bytes4.length; i2++) { + hex2 += hexes[bytes4[i2]]; + } + return hex2; + } + function numberToHexUnpadded(num) { + const hex2 = num.toString(16); + return hex2.length & 1 ? `0${hex2}` : hex2; + } + function hexToNumber(hex2) { + if (typeof hex2 !== "string") + throw new Error("hex string expected, got " + typeof hex2); + return BigInt(hex2 === "" ? "0" : `0x${hex2}`); + } + function hexToBytes(hex2) { + if (typeof hex2 !== "string") + throw new Error("hex string expected, got " + typeof hex2); + const len = hex2.length; + if (len % 2) + throw new Error("padded hex string expected, got unpadded hex of length " + len); + const array = new Uint8Array(len / 2); + for (let i2 = 0; i2 < array.length; i2++) { + const j = i2 * 2; + const hexByte = hex2.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error("Invalid byte sequence"); + array[i2] = byte; + } + return array; + } + function bytesToNumberBE(bytes4) { + return hexToNumber(bytesToHex(bytes4)); + } + function bytesToNumberLE(bytes4) { + if (!u8a2(bytes4)) + throw new Error("Uint8Array expected"); + return hexToNumber(bytesToHex(Uint8Array.from(bytes4).reverse())); + } + function numberToBytesBE(n, len) { + return hexToBytes(n.toString(16).padStart(len * 2, "0")); + } + function numberToBytesLE(n, len) { + return numberToBytesBE(n, len).reverse(); + } + function numberToVarBytesBE(n) { + return hexToBytes(numberToHexUnpadded(n)); + } + function ensureBytes(title, hex2, expectedLength) { + let res; + if (typeof hex2 === "string") { + try { + res = hexToBytes(hex2); + } catch (e) { + throw new Error(`${title} must be valid hex string, got "${hex2}". Cause: ${e}`); + } + } else if (u8a2(hex2)) { + res = Uint8Array.from(hex2); + } else { + throw new Error(`${title} must be hex string or Uint8Array`); + } + const len = res.length; + if (typeof expectedLength === "number" && len !== expectedLength) + throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); + return res; + } + function concatBytes2(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad2 = 0; + arrays.forEach((a) => { + if (!u8a2(a)) + throw new Error("Uint8Array expected"); + r.set(a, pad2); + pad2 += a.length; + }); + return r; + } + function equalBytes(b1, b2) { + if (b1.length !== b2.length) + return false; + for (let i2 = 0; i2 < b1.length; i2++) + if (b1[i2] !== b2[i2]) + return false; + return true; + } + function utf8ToBytes2(str) { + if (typeof str !== "string") + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); + } + function bitLen(n) { + let len; + for (len = 0; n > _0n; n >>= _1n, len += 1) + ; + return len; + } + function bitGet(n, pos) { + return n >> BigInt(pos) & _1n; + } + var bitSet = (n, pos, value) => { + return n | (value ? _1n : _0n) << BigInt(pos); + }; + var bitMask = (n) => (_2n << BigInt(n - 1)) - _1n; + var u8n = (data) => new Uint8Array(data); + var u8fr = (arr) => Uint8Array.from(arr); + function createHmacDrbg(hashLen, qByteLen, hmacFn) { + if (typeof hashLen !== "number" || hashLen < 2) + throw new Error("hashLen must be a number"); + if (typeof qByteLen !== "number" || qByteLen < 2) + throw new Error("qByteLen must be a number"); + if (typeof hmacFn !== "function") + throw new Error("hmacFn must be a function"); + let v = u8n(hashLen); + let k = u8n(hashLen); + let i2 = 0; + const reset = () => { + v.fill(1); + k.fill(0); + i2 = 0; + }; + const h = (...b) => hmacFn(k, v, ...b); + const reseed = (seed = u8n()) => { + k = h(u8fr([0]), seed); + v = h(); + if (seed.length === 0) + return; + k = h(u8fr([1]), seed); + v = h(); + }; + const gen = () => { + if (i2++ >= 1e3) + throw new Error("drbg: tried 1000 values"); + let len = 0; + const out = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes2(...out); + }; + const genUntil = (seed, pred) => { + reset(); + reseed(seed); + let res = void 0; + while (!(res = pred(gen()))) + reseed(); + reset(); + return res; + }; + return genUntil; + } + var validatorFns = { + bigint: (val) => typeof val === "bigint", + function: (val) => typeof val === "function", + boolean: (val) => typeof val === "boolean", + string: (val) => typeof val === "string", + stringOrUint8Array: (val) => typeof val === "string" || val instanceof Uint8Array, + isSafeInteger: (val) => Number.isSafeInteger(val), + array: (val) => Array.isArray(val), + field: (val, object) => object.Fp.isValid(val), + hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen) + }; + function validateObject(object, validators, optValidators = {}) { + const checkField = (fieldName, type, isOptional) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== "function") + throw new Error(`Invalid validator "${type}", expected function`); + const val = object[fieldName]; + if (isOptional && val === void 0) + return; + if (!checkVal(val, object)) { + throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); + } + }; + for (const [fieldName, type] of Object.entries(validators)) + checkField(fieldName, type, false); + for (const [fieldName, type] of Object.entries(optValidators)) + checkField(fieldName, type, true); + return object; + } + + // node_modules/@noble/curves/esm/abstract/modular.js + var _0n2 = BigInt(0); + var _1n2 = BigInt(1); + var _2n2 = BigInt(2); + var _3n = BigInt(3); + var _4n = BigInt(4); + var _5n = BigInt(5); + var _8n = BigInt(8); + var _9n = BigInt(9); + var _16n = BigInt(16); + function mod(a, b) { + const result = a % b; + return result >= _0n2 ? result : b + result; + } + function pow(num, power, modulo) { + if (modulo <= _0n2 || power < _0n2) + throw new Error("Expected power/modulo > 0"); + if (modulo === _1n2) + return _0n2; + let res = _1n2; + while (power > _0n2) { + if (power & _1n2) + res = res * num % modulo; + num = num * num % modulo; + power >>= _1n2; + } + return res; + } + function pow2(x, power, modulo) { + let res = x; + while (power-- > _0n2) { + res *= res; + res %= modulo; + } + return res; + } + function invert(number4, modulo) { + if (number4 === _0n2 || modulo <= _0n2) { + throw new Error(`invert: expected positive integers, got n=${number4} mod=${modulo}`); + } + let a = mod(number4, modulo); + let b = modulo; + let x = _0n2, y = _1n2, u = _1n2, v = _0n2; + while (a !== _0n2) { + const q = b / a; + const r = b % a; + const m = x - u * q; + const n = y - v * q; + b = a, a = r, x = u, y = v, u = m, v = n; + } + const gcd2 = b; + if (gcd2 !== _1n2) + throw new Error("invert: does not exist"); + return mod(x, modulo); + } + function tonelliShanks(P) { + const legendreC = (P - _1n2) / _2n2; + let Q, S, Z; + for (Q = P - _1n2, S = 0; Q % _2n2 === _0n2; Q /= _2n2, S++) + ; + for (Z = _2n2; Z < P && pow(Z, legendreC, P) !== P - _1n2; Z++) + ; + if (S === 1) { + const p1div4 = (P + _1n2) / _4n; + return function tonelliFast(Fp2, n) { + const root = Fp2.pow(n, p1div4); + if (!Fp2.eql(Fp2.sqr(root), n)) + throw new Error("Cannot find square root"); + return root; + }; + } + const Q1div2 = (Q + _1n2) / _2n2; + return function tonelliSlow(Fp2, n) { + if (Fp2.pow(n, legendreC) === Fp2.neg(Fp2.ONE)) + throw new Error("Cannot find square root"); + let r = S; + let g = Fp2.pow(Fp2.mul(Fp2.ONE, Z), Q); + let x = Fp2.pow(n, Q1div2); + let b = Fp2.pow(n, Q); + while (!Fp2.eql(b, Fp2.ONE)) { + if (Fp2.eql(b, Fp2.ZERO)) + return Fp2.ZERO; + let m = 1; + for (let t2 = Fp2.sqr(b); m < r; m++) { + if (Fp2.eql(t2, Fp2.ONE)) + break; + t2 = Fp2.sqr(t2); + } + const ge2 = Fp2.pow(g, _1n2 << BigInt(r - m - 1)); + g = Fp2.sqr(ge2); + x = Fp2.mul(x, ge2); + b = Fp2.mul(b, g); + r = m; + } + return x; + }; + } + function FpSqrt(P) { + if (P % _4n === _3n) { + const p1div4 = (P + _1n2) / _4n; + return function sqrt3mod4(Fp2, n) { + const root = Fp2.pow(n, p1div4); + if (!Fp2.eql(Fp2.sqr(root), n)) + throw new Error("Cannot find square root"); + return root; + }; + } + if (P % _8n === _5n) { + const c1 = (P - _5n) / _8n; + return function sqrt5mod8(Fp2, n) { + const n2 = Fp2.mul(n, _2n2); + const v = Fp2.pow(n2, c1); + const nv = Fp2.mul(n, v); + const i2 = Fp2.mul(Fp2.mul(nv, _2n2), v); + const root = Fp2.mul(nv, Fp2.sub(i2, Fp2.ONE)); + if (!Fp2.eql(Fp2.sqr(root), n)) + throw new Error("Cannot find square root"); + return root; + }; + } + if (P % _16n === _9n) { + } + return tonelliShanks(P); + } + var FIELD_FIELDS = [ + "create", + "isValid", + "is0", + "neg", + "inv", + "sqrt", + "sqr", + "eql", + "add", + "sub", + "mul", + "pow", + "div", + "addN", + "subN", + "mulN", + "sqrN" + ]; + function validateField(field) { + const initial = { + ORDER: "bigint", + MASK: "bigint", + BYTES: "isSafeInteger", + BITS: "isSafeInteger" + }; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = "function"; + return map; + }, initial); + return validateObject(field, opts); + } + function FpPow(f, num, power) { + if (power < _0n2) + throw new Error("Expected power > 0"); + if (power === _0n2) + return f.ONE; + if (power === _1n2) + return num; + let p = f.ONE; + let d = num; + while (power > _0n2) { + if (power & _1n2) + p = f.mul(p, d); + d = f.sqr(d); + power >>= _1n2; + } + return p; + } + function FpInvertBatch(f, nums) { + const tmp = new Array(nums.length); + const lastMultiplied = nums.reduce((acc, num, i2) => { + if (f.is0(num)) + return acc; + tmp[i2] = acc; + return f.mul(acc, num); + }, f.ONE); + const inverted = f.inv(lastMultiplied); + nums.reduceRight((acc, num, i2) => { + if (f.is0(num)) + return acc; + tmp[i2] = f.mul(acc, tmp[i2]); + return f.mul(acc, num); + }, inverted); + return tmp; + } + function nLength(n, nBitLength) { + const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; + } + function Field(ORDER, bitLen2, isLE4 = false, redef = {}) { + if (ORDER <= _0n2) + throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2); + if (BYTES > 2048) + throw new Error("Field lengths over 2048 bytes are not supported"); + const sqrtP = FpSqrt(ORDER); + const f = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: bitMask(BITS), + ZERO: _0n2, + ONE: _1n2, + create: (num) => mod(num, ORDER), + isValid: (num) => { + if (typeof num !== "bigint") + throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); + return _0n2 <= num && num < ORDER; + }, + is0: (num) => num === _0n2, + isOdd: (num) => (num & _1n2) === _1n2, + neg: (num) => mod(-num, ORDER), + eql: (lhs, rhs) => lhs === rhs, + sqr: (num) => mod(num * num, ORDER), + add: (lhs, rhs) => mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod(lhs * rhs, ORDER), + pow: (num, power) => FpPow(f, num, power), + div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), + sqrN: (num) => num * num, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + inv: (num) => invert(num, ORDER), + sqrt: redef.sqrt || ((n) => sqrtP(f, n)), + invertBatch: (lst) => FpInvertBatch(f, lst), + cmov: (a, b, c) => c ? b : a, + toBytes: (num) => isLE4 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES), + fromBytes: (bytes4) => { + if (bytes4.length !== BYTES) + throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes4.length}`); + return isLE4 ? bytesToNumberLE(bytes4) : bytesToNumberBE(bytes4); + } + }); + return Object.freeze(f); + } + function getFieldBytesLength(fieldOrder) { + if (typeof fieldOrder !== "bigint") + throw new Error("field order must be bigint"); + const bitLength = fieldOrder.toString(2).length; + return Math.ceil(bitLength / 8); + } + function getMinHashLength(fieldOrder) { + const length = getFieldBytesLength(fieldOrder); + return length + Math.ceil(length / 2); + } + function mapHashToField(key, fieldOrder, isLE4 = false) { + const len = key.length; + const fieldLen = getFieldBytesLength(fieldOrder); + const minLen = getMinHashLength(fieldOrder); + if (len < 16 || len < minLen || len > 1024) + throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`); + const num = isLE4 ? bytesToNumberBE(key) : bytesToNumberLE(key); + const reduced = mod(num, fieldOrder - _1n2) + _1n2; + return isLE4 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); + } + + // node_modules/@noble/curves/esm/abstract/curve.js + var _0n3 = BigInt(0); + var _1n3 = BigInt(1); + function wNAF(c, bits) { + const constTimeNegate = (condition, item) => { + const neg = item.negate(); + return condition ? neg : item; + }; + const opts = (W) => { + const windows = Math.ceil(bits / W) + 1; + const windowSize = 2 ** (W - 1); + return { windows, windowSize }; + }; + return { + constTimeNegate, + unsafeLadder(elm, n) { + let p = c.ZERO; + let d = elm; + while (n > _0n3) { + if (n & _1n3) + p = p.add(d); + d = d.double(); + n >>= _1n3; + } + return p; + }, + precomputeWindow(elm, W) { + const { windows, windowSize } = opts(W); + const points = []; + let p = elm; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + for (let i2 = 1; i2 < windowSize; i2++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + }, + wNAF(W, precomputes, n) { + const { windows, windowSize } = opts(W); + let p = c.ZERO; + let f = c.BASE; + const mask = BigInt(2 ** W - 1); + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + let wbits = Number(n & mask); + n >>= shiftBy; + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n3; + } + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + return { p, f }; + }, + wNAFCached(P, precomputesMap, n, transform) { + const W = P._WINDOW_SIZE || 1; + let comp = precomputesMap.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W); + if (W !== 1) { + precomputesMap.set(P, transform(comp)); + } + } + return this.wNAF(W, comp, n); + } + }; + } + function validateBasic(curve) { + validateField(curve.Fp); + validateObject(curve, { + n: "bigint", + h: "bigint", + Gx: "field", + Gy: "field" + }, { + nBitLength: "isSafeInteger", + nByteLength: "isSafeInteger" + }); + return Object.freeze({ + ...nLength(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER } + }); + } + + // node_modules/@noble/curves/esm/abstract/weierstrass.js + function validatePointOpts(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + a: "field", + b: "field" + }, { + allowedPrivateKeyLengths: "array", + wrapPrivateKey: "boolean", + isTorsionFree: "function", + clearCofactor: "function", + allowInfinityPoint: "boolean", + fromBytes: "function", + toBytes: "function" + }); + const { endo, Fp: Fp2, a } = opts; + if (endo) { + if (!Fp2.eql(a, Fp2.ZERO)) { + throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0"); + } + if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") { + throw new Error("Expected endomorphism with beta: bigint and splitScalar: function"); + } + } + return Object.freeze({ ...opts }); + } + var { bytesToNumberBE: b2n, hexToBytes: h2b } = utils_exports; + var DER = { + Err: class DERErr extends Error { + constructor(m = "") { + super(m); + } + }, + _parseInt(data) { + const { Err: E } = DER; + if (data.length < 2 || data[0] !== 2) + throw new E("Invalid signature integer tag"); + const len = data[1]; + const res = data.subarray(2, len + 2); + if (!len || res.length !== len) + throw new E("Invalid signature integer: wrong length"); + if (res[0] & 128) + throw new E("Invalid signature integer: negative"); + if (res[0] === 0 && !(res[1] & 128)) + throw new E("Invalid signature integer: unnecessary leading zero"); + return { d: b2n(res), l: data.subarray(len + 2) }; + }, + toSig(hex2) { + const { Err: E } = DER; + const data = typeof hex2 === "string" ? h2b(hex2) : hex2; + if (!(data instanceof Uint8Array)) + throw new Error("ui8a expected"); + let l = data.length; + if (l < 2 || data[0] != 48) + throw new E("Invalid signature tag"); + if (data[1] !== l - 2) + throw new E("Invalid signature: incorrect length"); + const { d: r, l: sBytes } = DER._parseInt(data.subarray(2)); + const { d: s, l: rBytesLeft } = DER._parseInt(sBytes); + if (rBytesLeft.length) + throw new E("Invalid signature: left bytes after parsing"); + return { r, s }; + }, + hexFromSig(sig) { + const slice = (s2) => Number.parseInt(s2[0], 16) & 8 ? "00" + s2 : s2; + const h = (num) => { + const hex2 = num.toString(16); + return hex2.length & 1 ? `0${hex2}` : hex2; + }; + const s = slice(h(sig.s)); + const r = slice(h(sig.r)); + const shl = s.length / 2; + const rhl = r.length / 2; + const sl = h(shl); + const rl = h(rhl); + return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`; + } + }; + var _0n4 = BigInt(0); + var _1n4 = BigInt(1); + var _2n3 = BigInt(2); + var _3n2 = BigInt(3); + var _4n2 = BigInt(4); + function weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp: Fp2 } = CURVE; + const toBytes4 = CURVE.toBytes || ((_c, point, _isCompressed) => { + const a = point.toAffine(); + return concatBytes2(Uint8Array.from([4]), Fp2.toBytes(a.x), Fp2.toBytes(a.y)); + }); + const fromBytes = CURVE.fromBytes || ((bytes4) => { + const tail = bytes4.subarray(1); + const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); + const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); + return { x, y }; + }); + function weierstrassEquation(x) { + const { a, b } = CURVE; + const x2 = Fp2.sqr(x); + const x3 = Fp2.mul(x2, x); + return Fp2.add(Fp2.add(x3, Fp2.mul(x, a)), b); + } + if (!Fp2.eql(Fp2.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error("bad generator point: equation left != right"); + function isWithinCurveOrder(num) { + return typeof num === "bigint" && _0n4 < num && num < CURVE.n; + } + function assertGE(num) { + if (!isWithinCurveOrder(num)) + throw new Error("Expected valid bigint: 0 < bigint < curve.n"); + } + function normPrivateKeyToScalar(key) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE; + if (lengths && typeof key !== "bigint") { + if (key instanceof Uint8Array) + key = bytesToHex(key); + if (typeof key !== "string" || !lengths.includes(key.length)) + throw new Error("Invalid key"); + key = key.padStart(nByteLength * 2, "0"); + } + let num; + try { + num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength)); + } catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + } + if (wrapPrivateKey) + num = mod(num, n); + assertGE(num); + return num; + } + const pointPrecomputes = /* @__PURE__ */ new Map(); + function assertPrjPoint(other) { + if (!(other instanceof Point2)) + throw new Error("ProjectivePoint expected"); + } + class Point2 { + constructor(px, py, pz) { + this.px = px; + this.py = py; + this.pz = pz; + if (px == null || !Fp2.isValid(px)) + throw new Error("x required"); + if (py == null || !Fp2.isValid(py)) + throw new Error("y required"); + if (pz == null || !Fp2.isValid(pz)) + throw new Error("z required"); + } + static fromAffine(p) { + const { x, y } = p || {}; + if (!p || !Fp2.isValid(x) || !Fp2.isValid(y)) + throw new Error("invalid affine point"); + if (p instanceof Point2) + throw new Error("projective point not allowed"); + const is0 = (i2) => Fp2.eql(i2, Fp2.ZERO); + if (is0(x) && is0(y)) + return Point2.ZERO; + return new Point2(x, y, Fp2.ONE); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + static normalizeZ(points) { + const toInv = Fp2.invertBatch(points.map((p) => p.pz)); + return points.map((p, i2) => p.toAffine(toInv[i2])).map(Point2.fromAffine); + } + static fromHex(hex2) { + const P = Point2.fromAffine(fromBytes(ensureBytes("pointHex", hex2))); + P.assertValidity(); + return P; + } + static fromPrivateKey(privateKey) { + return Point2.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + assertValidity() { + if (this.is0()) { + if (CURVE.allowInfinityPoint && !Fp2.is0(this.py)) + return; + throw new Error("bad point: ZERO"); + } + const { x, y } = this.toAffine(); + if (!Fp2.isValid(x) || !Fp2.isValid(y)) + throw new Error("bad point: x or y not FE"); + const left = Fp2.sqr(y); + const right = weierstrassEquation(x); + if (!Fp2.eql(left, right)) + throw new Error("bad point: equation left != right"); + if (!this.isTorsionFree()) + throw new Error("bad point: not in prime-order subgroup"); + } + hasEvenY() { + const { y } = this.toAffine(); + if (Fp2.isOdd) + return !Fp2.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1)); + const U2 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1)); + return U1 && U2; + } + negate() { + return new Point2(this.px, Fp2.neg(this.py), this.pz); + } + double() { + const { a, b } = CURVE; + const b3 = Fp2.mul(b, _3n2); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; + let t0 = Fp2.mul(X1, X1); + let t1 = Fp2.mul(Y1, Y1); + let t2 = Fp2.mul(Z1, Z1); + let t3 = Fp2.mul(X1, Y1); + t3 = Fp2.add(t3, t3); + Z3 = Fp2.mul(X1, Z1); + Z3 = Fp2.add(Z3, Z3); + X3 = Fp2.mul(a, Z3); + Y3 = Fp2.mul(b3, t2); + Y3 = Fp2.add(X3, Y3); + X3 = Fp2.sub(t1, Y3); + Y3 = Fp2.add(t1, Y3); + Y3 = Fp2.mul(X3, Y3); + X3 = Fp2.mul(t3, X3); + Z3 = Fp2.mul(b3, Z3); + t2 = Fp2.mul(a, t2); + t3 = Fp2.sub(t0, t2); + t3 = Fp2.mul(a, t3); + t3 = Fp2.add(t3, Z3); + Z3 = Fp2.add(t0, t0); + t0 = Fp2.add(Z3, t0); + t0 = Fp2.add(t0, t2); + t0 = Fp2.mul(t0, t3); + Y3 = Fp2.add(Y3, t0); + t2 = Fp2.mul(Y1, Z1); + t2 = Fp2.add(t2, t2); + t0 = Fp2.mul(t2, t3); + X3 = Fp2.sub(X3, t0); + Z3 = Fp2.mul(t2, t1); + Z3 = Fp2.add(Z3, Z3); + Z3 = Fp2.add(Z3, Z3); + return new Point2(X3, Y3, Z3); + } + add(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; + const a = CURVE.a; + const b3 = Fp2.mul(CURVE.b, _3n2); + let t0 = Fp2.mul(X1, X2); + let t1 = Fp2.mul(Y1, Y2); + let t2 = Fp2.mul(Z1, Z2); + let t3 = Fp2.add(X1, Y1); + let t4 = Fp2.add(X2, Y2); + t3 = Fp2.mul(t3, t4); + t4 = Fp2.add(t0, t1); + t3 = Fp2.sub(t3, t4); + t4 = Fp2.add(X1, Z1); + let t5 = Fp2.add(X2, Z2); + t4 = Fp2.mul(t4, t5); + t5 = Fp2.add(t0, t2); + t4 = Fp2.sub(t4, t5); + t5 = Fp2.add(Y1, Z1); + X3 = Fp2.add(Y2, Z2); + t5 = Fp2.mul(t5, X3); + X3 = Fp2.add(t1, t2); + t5 = Fp2.sub(t5, X3); + Z3 = Fp2.mul(a, t4); + X3 = Fp2.mul(b3, t2); + Z3 = Fp2.add(X3, Z3); + X3 = Fp2.sub(t1, Z3); + Z3 = Fp2.add(t1, Z3); + Y3 = Fp2.mul(X3, Z3); + t1 = Fp2.add(t0, t0); + t1 = Fp2.add(t1, t0); + t2 = Fp2.mul(a, t2); + t4 = Fp2.mul(b3, t4); + t1 = Fp2.add(t1, t2); + t2 = Fp2.sub(t0, t2); + t2 = Fp2.mul(a, t2); + t4 = Fp2.add(t4, t2); + t0 = Fp2.mul(t1, t4); + Y3 = Fp2.add(Y3, t0); + t0 = Fp2.mul(t5, t4); + X3 = Fp2.mul(t3, X3); + X3 = Fp2.sub(X3, t0); + t0 = Fp2.mul(t3, t1); + Z3 = Fp2.mul(t5, Z3); + Z3 = Fp2.add(Z3, t0); + return new Point2(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + is0() { + return this.equals(Point2.ZERO); + } + wNAF(n) { + return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => { + const toInv = Fp2.invertBatch(comp.map((p) => p.pz)); + return comp.map((p, i2) => p.toAffine(toInv[i2])).map(Point2.fromAffine); + }); + } + multiplyUnsafe(n) { + const I = Point2.ZERO; + if (n === _0n4) + return I; + assertGE(n); + if (n === _1n4) + return this; + const { endo } = CURVE; + if (!endo) + return wnaf.unsafeLadder(this, n); + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let k1p = I; + let k2p = I; + let d = this; + while (k1 > _0n4 || k2 > _0n4) { + if (k1 & _1n4) + k1p = k1p.add(d); + if (k2 & _1n4) + k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n4; + k2 >>= _1n4; + } + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new Point2(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + multiply(scalar) { + assertGE(scalar); + let n = scalar; + let point, fake; + const { endo } = CURVE; + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point2(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } else { + const { p, f } = this.wNAF(n); + point = p; + fake = f; + } + return Point2.normalizeZ([point, fake])[0]; + } + multiplyAndAddUnsafe(Q, a, b) { + const G = Point2.BASE; + const mul3 = (P, a2) => a2 === _0n4 || a2 === _1n4 || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2); + const sum = mul3(this, a).add(mul3(Q, b)); + return sum.is0() ? void 0 : sum; + } + toAffine(iz) { + const { px: x, py: y, pz: z } = this; + const is0 = this.is0(); + if (iz == null) + iz = is0 ? Fp2.ONE : Fp2.inv(z); + const ax = Fp2.mul(x, iz); + const ay = Fp2.mul(y, iz); + const zz = Fp2.mul(z, iz); + if (is0) + return { x: Fp2.ZERO, y: Fp2.ZERO }; + if (!Fp2.eql(zz, Fp2.ONE)) + throw new Error("invZ was invalid"); + return { x: ax, y: ay }; + } + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n4) + return true; + if (isTorsionFree) + return isTorsionFree(Point2, this); + throw new Error("isTorsionFree() has not been declared for the elliptic curve"); + } + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n4) + return this; + if (clearCofactor) + return clearCofactor(Point2, this); + return this.multiplyUnsafe(CURVE.h); + } + toRawBytes(isCompressed = true) { + this.assertValidity(); + return toBytes4(Point2, this, isCompressed); + } + toHex(isCompressed = true) { + return bytesToHex(this.toRawBytes(isCompressed)); + } + } + Point2.BASE = new Point2(CURVE.Gx, CURVE.Gy, Fp2.ONE); + Point2.ZERO = new Point2(Fp2.ZERO, Fp2.ONE, Fp2.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = wNAF(Point2, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + return { + CURVE, + ProjectivePoint: Point2, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder + }; + } + function validateOpts(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + hash: "hash", + hmac: "function", + randomBytes: "function" + }, { + bits2int: "function", + bits2int_modN: "function", + lowS: "boolean" + }); + return Object.freeze({ lowS: true, ...opts }); + } + function weierstrass(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp: Fp2, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp2.BYTES + 1; + const uncompressedLen = 2 * Fp2.BYTES + 1; + function isValidFieldElement(num) { + return _0n4 < num && num < Fp2.ORDER; + } + function modN2(a) { + return mod(a, CURVE_ORDER); + } + function invN(a) { + return invert(a, CURVE_ORDER); + } + const { ProjectivePoint: Point2, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({ + ...CURVE, + toBytes(_c, point, isCompressed) { + const a = point.toAffine(); + const x = Fp2.toBytes(a.x); + const cat = concatBytes2; + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x); + } else { + return cat(Uint8Array.from([4]), x, Fp2.toBytes(a.y)); + } + }, + fromBytes(bytes4) { + const len = bytes4.length; + const head = bytes4[0]; + const tail = bytes4.subarray(1); + if (len === compressedLen && (head === 2 || head === 3)) { + const x = bytesToNumberBE(tail); + if (!isValidFieldElement(x)) + throw new Error("Point is not on curve"); + const y2 = weierstrassEquation(x); + let y = Fp2.sqrt(y2); + const isYOdd = (y & _1n4) === _1n4; + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y = Fp2.neg(y); + return { x, y }; + } else if (len === uncompressedLen && head === 4) { + const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); + const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); + return { x, y }; + } else { + throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); + } + } + }); + const numToNByteStr = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number4) { + const HALF = CURVE_ORDER >> _1n4; + return number4 > HALF; + } + function normalizeS(s) { + return isBiggerThanHalfOrder(s) ? modN2(-s) : s; + } + const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to)); + class Signature { + constructor(r, s, recovery) { + this.r = r; + this.s = s; + this.recovery = recovery; + this.assertValidity(); + } + static fromCompact(hex2) { + const l = CURVE.nByteLength; + hex2 = ensureBytes("compactSignature", hex2, l * 2); + return new Signature(slcNum(hex2, 0, l), slcNum(hex2, l, 2 * l)); + } + static fromDER(hex2) { + const { r, s } = DER.toSig(ensureBytes("DER", hex2)); + return new Signature(r, s); + } + assertValidity() { + if (!isWithinCurveOrder(this.r)) + throw new Error("r must be 0 < r < CURVE.n"); + if (!isWithinCurveOrder(this.s)) + throw new Error("s must be 0 < s < CURVE.n"); + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(msgHash) { + const { r, s, recovery: rec } = this; + const h = bits2int_modN(ensureBytes("msgHash", msgHash)); + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error("recovery id invalid"); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp2.ORDER) + throw new Error("recovery id 2 or 3 invalid"); + const prefix = (rec & 1) === 0 ? "02" : "03"; + const R = Point2.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); + const u1 = modN2(-h * ir); + const u2 = modN2(s * ir); + const Q = Point2.BASE.multiplyAndAddUnsafe(R, u1, u2); + if (!Q) + throw new Error("point at infinify"); + Q.assertValidity(); + return Q; + } + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN2(-this.s), this.recovery) : this; + } + toDERRawBytes() { + return hexToBytes(this.toDERHex()); + } + toDERHex() { + return DER.hexFromSig({ r: this.r, s: this.s }); + } + toCompactRawBytes() { + return hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + const utils = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } catch (error) { + return false; + } + }, + normPrivateKeyToScalar, + randomPrivateKey: () => { + const length = getMinHashLength(CURVE.n); + return mapHashToField(CURVE.randomBytes(length), CURVE.n); + }, + precompute(windowSize = 8, point = Point2.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; + } + }; + function getPublicKey2(privateKey, isCompressed = true) { + return Point2.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + function isProbPub(item) { + const arr = item instanceof Uint8Array; + const str = typeof item === "string"; + const len = (arr || str) && item.length; + if (arr) + return len === compressedLen || len === uncompressedLen; + if (str) + return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point2) + return true; + return false; + } + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) + throw new Error("first arg must be private key"); + if (!isProbPub(publicB)) + throw new Error("second arg must be public key"); + const b = Point2.fromHex(publicB); + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + const bits2int = CURVE.bits2int || function(bytes4) { + const num = bytesToNumberBE(bytes4); + const delta = bytes4.length * 8 - CURVE.nBitLength; + return delta > 0 ? num >> BigInt(delta) : num; + }; + const bits2int_modN = CURVE.bits2int_modN || function(bytes4) { + return modN2(bits2int(bytes4)); + }; + const ORDER_MASK = bitMask(CURVE.nBitLength); + function int2octets(num) { + if (typeof num !== "bigint") + throw new Error("bigint expected"); + if (!(_0n4 <= num && num < ORDER_MASK)) + throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); + return numberToBytesBE(num, CURVE.nByteLength); + } + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (["recovered", "canonical"].some((k) => k in opts)) + throw new Error("sign() legacy options not supported"); + const { hash: hash3, randomBytes: randomBytes3 } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; + if (lowS == null) + lowS = true; + msgHash = ensureBytes("msgHash", msgHash); + if (prehash) + msgHash = ensureBytes("prehashed msgHash", hash3(msgHash)); + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); + const seedArgs = [int2octets(d), int2octets(h1int)]; + if (ent != null) { + const e = ent === true ? randomBytes3(Fp2.BYTES) : ent; + seedArgs.push(ensureBytes("extraEntropy", e)); + } + const seed = concatBytes2(...seedArgs); + const m = h1int; + function k2sig(kBytes) { + const k = bits2int(kBytes); + if (!isWithinCurveOrder(k)) + return; + const ik = invN(k); + const q = Point2.BASE.multiply(k).toAffine(); + const r = modN2(q.x); + if (r === _0n4) + return; + const s = modN2(ik * modN2(m + r * d)); + if (s === _0n4) + return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4); + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); + recovery ^= 1; + } + return new Signature(r, normS, recovery); + } + return { seed, k2sig }; + } + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + function sign(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); + const C = CURVE; + const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); + } + Point2.BASE._setWindowSize(8); + function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { + const sg = signature; + msgHash = ensureBytes("msgHash", msgHash); + publicKey = ensureBytes("publicKey", publicKey); + if ("strict" in opts) + throw new Error("options.strict was renamed to lowS"); + const { lowS, prehash } = opts; + let _sig = void 0; + let P; + try { + if (typeof sg === "string" || sg instanceof Uint8Array) { + try { + _sig = Signature.fromDER(sg); + } catch (derError) { + if (!(derError instanceof DER.Err)) + throw derError; + _sig = Signature.fromCompact(sg); + } + } else if (typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint") { + const { r: r2, s: s2 } = sg; + _sig = new Signature(r2, s2); + } else { + throw new Error("PARSE"); + } + P = Point2.fromHex(publicKey); + } catch (error) { + if (error.message === "PARSE") + throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; + } + if (lowS && _sig.hasHighS()) + return false; + if (prehash) + msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); + const is = invN(s); + const u1 = modN2(h * is); + const u2 = modN2(r * is); + const R = Point2.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); + if (!R) + return false; + const v = modN2(R.x); + return v === r; + } + return { + CURVE, + getPublicKey: getPublicKey2, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point2, + Signature, + utils + }; + } + + // node_modules/@noble/curves/node_modules/@noble/hashes/esm/hmac.js + var HMAC = class extends Hash { + constructor(hash3, _key) { + super(); + this.finished = false; + this.destroyed = false; + hash(hash3); + const key = toBytes(_key); + this.iHash = hash3.create(); + if (typeof this.iHash.update !== "function") + throw new Error("Expected instance of class which extends utils.Hash"); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad2 = new Uint8Array(blockLen); + pad2.set(key.length > blockLen ? hash3.create().update(key).digest() : key); + for (let i2 = 0; i2 < pad2.length; i2++) + pad2[i2] ^= 54; + this.iHash.update(pad2); + this.oHash = hash3.create(); + for (let i2 = 0; i2 < pad2.length; i2++) + pad2[i2] ^= 54 ^ 92; + this.oHash.update(pad2); + pad2.fill(0); + } + update(buf) { + exists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + exists(this); + bytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } + }; + var hmac = (hash3, key, message) => new HMAC(hash3, key).update(message).digest(); + hmac.create = (hash3, key) => new HMAC(hash3, key); + + // node_modules/@noble/curves/esm/_shortw_utils.js + function getHash(hash3) { + return { + hash: hash3, + hmac: (key, ...msgs) => hmac(hash3, key, concatBytes(...msgs)), + randomBytes + }; + } + function createCurve(curveDef, defHash) { + const create = (hash3) => weierstrass({ ...curveDef, ...getHash(hash3) }); + return Object.freeze({ ...create(defHash), create }); + } + + // node_modules/@noble/curves/esm/secp256k1.js + var secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"); + var secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); + var _1n5 = BigInt(1); + var _2n4 = BigInt(2); + var divNearest = (a, b) => (a + b / _2n4) / b; + function sqrtMod(y) { + const P = secp256k1P; + const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = y * y * y % P; + const b3 = b2 * b2 * y % P; + const b6 = pow2(b3, _3n3, P) * b3 % P; + const b9 = pow2(b6, _3n3, P) * b3 % P; + const b11 = pow2(b9, _2n4, P) * b2 % P; + const b22 = pow2(b11, _11n, P) * b11 % P; + const b44 = pow2(b22, _22n, P) * b22 % P; + const b88 = pow2(b44, _44n, P) * b44 % P; + const b176 = pow2(b88, _88n, P) * b88 % P; + const b220 = pow2(b176, _44n, P) * b44 % P; + const b223 = pow2(b220, _3n3, P) * b3 % P; + const t1 = pow2(b223, _23n, P) * b22 % P; + const t2 = pow2(t1, _6n, P) * b2 % P; + const root = pow2(t2, _2n4, P); + if (!Fp.eql(Fp.sqr(root), y)) + throw new Error("Cannot find square root"); + return root; + } + var Fp = Field(secp256k1P, void 0, void 0, { sqrt: sqrtMod }); + var secp256k1 = createCurve({ + a: BigInt(0), + b: BigInt(7), + Fp, + n: secp256k1N, + Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"), + Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"), + h: BigInt(1), + lowS: true, + endo: { + beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), + splitScalar: (k) => { + const n = secp256k1N; + const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15"); + const b1 = -_1n5 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"); + const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"); + const b2 = a1; + const POW_2_128 = BigInt("0x100000000000000000000000000000000"); + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = mod(k - c1 * a1 - c2 * a2, n); + let k2 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) + k1 = n - k1; + if (k2neg) + k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error("splitScalar: Endomorphism failed, k=" + k); + } + return { k1neg, k1, k2neg, k2 }; + } + } + }, sha256); + var _0n5 = BigInt(0); + var fe = (x) => typeof x === "bigint" && _0n5 < x && x < secp256k1P; + var ge = (x) => typeof x === "bigint" && _0n5 < x && x < secp256k1N; + var TAGGED_HASH_PREFIXES = {}; + function taggedHash(tag, ...messages) { + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === void 0) { + const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + tagP = concatBytes2(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return sha256(concatBytes2(tagP, ...messages)); + } + var pointToBytes = (point) => point.toRawBytes(true).slice(1); + var numTo32b = (n) => numberToBytesBE(n, 32); + var modP = (x) => mod(x, secp256k1P); + var modN = (x) => mod(x, secp256k1N); + var Point = secp256k1.ProjectivePoint; + var GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b); + function schnorrGetExtPubKey(priv) { + let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); + let p = Point.fromPrivateKey(d_); + const scalar = p.hasEvenY() ? d_ : modN(-d_); + return { scalar, bytes: pointToBytes(p) }; + } + function lift_x(x) { + if (!fe(x)) + throw new Error("bad x: need 0 < x < p"); + const xx = modP(x * x); + const c = modP(xx * x + BigInt(7)); + let y = sqrtMod(c); + if (y % _2n4 !== _0n5) + y = modP(-y); + const p = new Point(x, y, _1n5); + p.assertValidity(); + return p; + } + function challenge(...args) { + return modN(bytesToNumberBE(taggedHash("BIP0340/challenge", ...args))); + } + function schnorrGetPublicKey(privateKey) { + return schnorrGetExtPubKey(privateKey).bytes; + } + function schnorrSign(message, privateKey, auxRand = randomBytes(32)) { + const m = ensureBytes("message", message); + const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); + const a = ensureBytes("auxRand", auxRand, 32); + const t = numTo32b(d ^ bytesToNumberBE(taggedHash("BIP0340/aux", a))); + const rand = taggedHash("BIP0340/nonce", t, px, m); + const k_ = modN(bytesToNumberBE(rand)); + if (k_ === _0n5) + throw new Error("sign failed: k is zero"); + const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); + const e = challenge(rx, px, m); + const sig = new Uint8Array(64); + sig.set(rx, 0); + sig.set(numTo32b(modN(k + e * d)), 32); + if (!schnorrVerify(sig, m, px)) + throw new Error("sign: Invalid signature produced"); + return sig; + } + function schnorrVerify(signature, message, publicKey) { + const sig = ensureBytes("signature", signature, 64); + const m = ensureBytes("message", message); + const pub = ensureBytes("publicKey", publicKey, 32); + try { + const P = lift_x(bytesToNumberBE(pub)); + const r = bytesToNumberBE(sig.subarray(0, 32)); + if (!fe(r)) + return false; + const s = bytesToNumberBE(sig.subarray(32, 64)); + if (!ge(s)) + return false; + const e = challenge(numTo32b(r), pointToBytes(P), m); + const R = GmulAdd(P, s, modN(-e)); + if (!R || !R.hasEvenY() || R.toAffine().x !== r) + return false; + return true; + } catch (error) { + return false; + } + } + var schnorr = /* @__PURE__ */ (() => ({ + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + utils: { + randomPrivateKey: secp256k1.utils.randomPrivateKey, + lift_x, + pointToBytes, + numberToBytesBE, + bytesToNumberBE, + taggedHash, + mod + } + }))(); + + // node_modules/@noble/hashes/esm/crypto.js + var crypto2 = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0; + + // node_modules/@noble/hashes/esm/utils.js + var u8a3 = (a) => a instanceof Uint8Array; + var createView2 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); + var rotr2 = (word, shift) => word << 32 - shift | word >>> shift; + var isLE2 = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; + if (!isLE2) + throw new Error("Non little-endian hardware is not supported"); + var hexes2 = Array.from({ length: 256 }, (v, i2) => i2.toString(16).padStart(2, "0")); + function bytesToHex2(bytes4) { + if (!u8a3(bytes4)) + throw new Error("Uint8Array expected"); + let hex2 = ""; + for (let i2 = 0; i2 < bytes4.length; i2++) { + hex2 += hexes2[bytes4[i2]]; + } + return hex2; + } + function hexToBytes2(hex2) { + if (typeof hex2 !== "string") + throw new Error("hex string expected, got " + typeof hex2); + const len = hex2.length; + if (len % 2) + throw new Error("padded hex string expected, got unpadded hex of length " + len); + const array = new Uint8Array(len / 2); + for (let i2 = 0; i2 < array.length; i2++) { + const j = i2 * 2; + const hexByte = hex2.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error("Invalid byte sequence"); + array[i2] = byte; + } + return array; + } + function utf8ToBytes3(str) { + if (typeof str !== "string") + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); + } + function toBytes2(data) { + if (typeof data === "string") + data = utf8ToBytes3(data); + if (!u8a3(data)) + throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; + } + function concatBytes3(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad2 = 0; + arrays.forEach((a) => { + if (!u8a3(a)) + throw new Error("Uint8Array expected"); + r.set(a, pad2); + pad2 += a.length; + }); + return r; + } + var Hash2 = class { + clone() { + return this._cloneInto(); + } + }; + function wrapConstructor2(hashCons) { + const hashC = (msg) => hashCons().update(toBytes2(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; + } + function randomBytes2(bytesLength = 32) { + if (crypto2 && typeof crypto2.getRandomValues === "function") { + return crypto2.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error("crypto.getRandomValues must be defined"); + } + + // core.ts + var verifiedSymbol = Symbol("verified"); + var isRecord = (obj) => obj instanceof Object; + function validateEvent(event) { + if (!isRecord(event)) + return false; + if (typeof event.kind !== "number") + return false; + if (typeof event.content !== "string") + return false; + if (typeof event.created_at !== "number") + return false; + if (typeof event.pubkey !== "string") + return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) + return false; + if (!Array.isArray(event.tags)) + return false; + for (let i2 = 0; i2 < event.tags.length; i2++) { + let tag = event.tags[i2]; + if (!Array.isArray(tag)) + return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] !== "string") + return false; + } + } + return true; + } + function sortEvents(events) { + return events.sort((a, b) => { + if (a.created_at !== b.created_at) { + return b.created_at - a.created_at; + } + return a.id.localeCompare(b.id); + }); + } + + // node_modules/@noble/hashes/esm/_assert.js + function number2(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); + } + function bool(b) { + if (typeof b !== "boolean") + throw new Error(`Expected boolean, not ${b}`); + } + function bytes2(b, ...lengths) { + if (!(b instanceof Uint8Array)) + throw new Error("Expected Uint8Array"); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); + } + function hash2(hash3) { + if (typeof hash3 !== "function" || typeof hash3.create !== "function") + throw new Error("Hash should be wrapped by utils.wrapConstructor"); + number2(hash3.outputLen); + number2(hash3.blockLen); + } + function exists2(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error("Hash instance has been destroyed"); + if (checkFinished && instance.finished) + throw new Error("Hash#digest() has already been called"); + } + function output2(out, instance) { + bytes2(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } + } + var assert = { + number: number2, + bool, + bytes: bytes2, + hash: hash2, + exists: exists2, + output: output2 + }; + var assert_default = assert; + + // node_modules/@noble/hashes/esm/_sha2.js + function setBigUint642(view, byteOffset, value, isLE4) { + if (typeof view.setBigUint64 === "function") + return view.setBigUint64(byteOffset, value, isLE4); + const _32n = BigInt(32); + const _u32_max = BigInt(4294967295); + const wh = Number(value >> _32n & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE4 ? 4 : 0; + const l = isLE4 ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE4); + view.setUint32(byteOffset + l, wl, isLE4); + } + var SHA22 = class extends Hash2 { + constructor(blockLen, outputLen, padOffset, isLE4) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE4; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView2(this.buffer); + } + update(data) { + assert_default.exists(this); + const { view, buffer, blockLen } = this; + data = toBytes2(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + const dataView = createView2(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + assert_default.exists(this); + assert_default.output(out, this); + this.finished = true; + const { buffer, view, blockLen, isLE: isLE4 } = this; + let { pos } = this; + buffer[pos++] = 128; + this.buffer.subarray(pos).fill(0); + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + for (let i2 = pos; i2 < blockLen; i2++) + buffer[i2] = 0; + setBigUint642(view, blockLen - 8, BigInt(this.length * 8), isLE4); + this.process(view, 0); + const oview = createView2(out); + const len = this.outputLen; + if (len % 4) + throw new Error("_sha2: outputLen should be aligned to 32bit"); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error("_sha2: outputLen bigger than state"); + for (let i2 = 0; i2 < outLen; i2++) + oview.setUint32(4 * i2, state[i2], isLE4); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } + }; + + // node_modules/@noble/hashes/esm/sha256.js + var Chi2 = (a, b, c) => a & b ^ ~a & c; + var Maj2 = (a, b, c) => a & b ^ a & c ^ b & c; + var SHA256_K2 = new Uint32Array([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 + ]); + var IV2 = new Uint32Array([ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 + ]); + var SHA256_W2 = new Uint32Array(64); + var SHA2562 = class extends SHA22 { + constructor() { + super(64, 32, 8, false); + this.A = IV2[0] | 0; + this.B = IV2[1] | 0; + this.C = IV2[2] | 0; + this.D = IV2[3] | 0; + this.E = IV2[4] | 0; + this.F = IV2[5] | 0; + this.G = IV2[6] | 0; + this.H = IV2[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + for (let i2 = 0; i2 < 16; i2++, offset += 4) + SHA256_W2[i2] = view.getUint32(offset, false); + for (let i2 = 16; i2 < 64; i2++) { + const W15 = SHA256_W2[i2 - 15]; + const W2 = SHA256_W2[i2 - 2]; + const s0 = rotr2(W15, 7) ^ rotr2(W15, 18) ^ W15 >>> 3; + const s1 = rotr2(W2, 17) ^ rotr2(W2, 19) ^ W2 >>> 10; + SHA256_W2[i2] = s1 + SHA256_W2[i2 - 7] + s0 + SHA256_W2[i2 - 16] | 0; + } + let { A, B, C, D, E, F, G, H } = this; + for (let i2 = 0; i2 < 64; i2++) { + const sigma1 = rotr2(E, 6) ^ rotr2(E, 11) ^ rotr2(E, 25); + const T1 = H + sigma1 + Chi2(E, F, G) + SHA256_K2[i2] + SHA256_W2[i2] | 0; + const sigma0 = rotr2(A, 2) ^ rotr2(A, 13) ^ rotr2(A, 22); + const T2 = sigma0 + Maj2(A, B, C) | 0; + H = G; + G = F; + F = E; + E = D + T1 | 0; + D = C; + C = B; + B = A; + A = T1 + T2 | 0; + } + A = A + this.A | 0; + B = B + this.B | 0; + C = C + this.C | 0; + D = D + this.D | 0; + E = E + this.E | 0; + F = F + this.F | 0; + G = G + this.G | 0; + H = H + this.H | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + SHA256_W2.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } + }; + var SHA224 = class extends SHA2562 { + constructor() { + super(); + this.A = 3238371032 | 0; + this.B = 914150663 | 0; + this.C = 812702999 | 0; + this.D = 4144912697 | 0; + this.E = 4290775857 | 0; + this.F = 1750603025 | 0; + this.G = 1694076839 | 0; + this.H = 3204075428 | 0; + this.outputLen = 28; + } + }; + var sha2562 = wrapConstructor2(() => new SHA2562()); + var sha224 = wrapConstructor2(() => new SHA224()); + + // utils.ts + var utils_exports2 = {}; + __export(utils_exports2, { + Queue: () => Queue, + QueueNode: () => QueueNode, + binarySearch: () => binarySearch, + bytesToHex: () => bytesToHex2, + hexToBytes: () => hexToBytes2, + insertEventIntoAscendingList: () => insertEventIntoAscendingList, + insertEventIntoDescendingList: () => insertEventIntoDescendingList, + normalizeURL: () => normalizeURL, + utf8Decoder: () => utf8Decoder, + utf8Encoder: () => utf8Encoder + }); + var utf8Decoder = new TextDecoder("utf-8"); + var utf8Encoder = new TextEncoder(); + function normalizeURL(url) { + try { + if (url.indexOf("://") === -1) + url = "wss://" + url; + let p = new URL(url); + p.pathname = p.pathname.replace(/\/+/g, "/"); + if (p.pathname.endsWith("/")) + p.pathname = p.pathname.slice(0, -1); + if (p.port === "80" && p.protocol === "ws:" || p.port === "443" && p.protocol === "wss:") + p.port = ""; + p.searchParams.sort(); + p.hash = ""; + return p.toString(); + } catch (e) { + throw new Error(`Invalid URL: ${url}`); + } + } + function insertEventIntoDescendingList(sortedArray, event) { + const [idx, found] = binarySearch(sortedArray, (b) => { + if (event.id === b.id) + return 0; + if (event.created_at === b.created_at) + return -1; + return b.created_at - event.created_at; + }); + if (!found) { + sortedArray.splice(idx, 0, event); + } + return sortedArray; + } + function insertEventIntoAscendingList(sortedArray, event) { + const [idx, found] = binarySearch(sortedArray, (b) => { + if (event.id === b.id) + return 0; + if (event.created_at === b.created_at) + return -1; + return event.created_at - b.created_at; + }); + if (!found) { + sortedArray.splice(idx, 0, event); + } + return sortedArray; + } + function binarySearch(arr, compare) { + let start = 0; + let end = arr.length - 1; + while (start <= end) { + const mid = Math.floor((start + end) / 2); + const cmp = compare(arr[mid]); + if (cmp === 0) { + return [mid, true]; + } + if (cmp < 0) { + end = mid - 1; + } else { + start = mid + 1; + } + } + return [start, false]; + } + var QueueNode = class { + value; + next = null; + prev = null; + constructor(message) { + this.value = message; + } + }; + var Queue = class { + first; + last; + constructor() { + this.first = null; + this.last = null; + } + enqueue(value) { + const newNode = new QueueNode(value); + if (!this.last) { + this.first = newNode; + this.last = newNode; + } else if (this.last === this.first) { + this.last = newNode; + this.last.prev = this.first; + this.first.next = newNode; + } else { + newNode.prev = this.last; + this.last.next = newNode; + this.last = newNode; + } + return true; + } + dequeue() { + if (!this.first) + return null; + if (this.first === this.last) { + const target2 = this.first; + this.first = null; + this.last = null; + return target2.value; + } + const target = this.first; + this.first = target.next; + if (this.first) { + this.first.prev = null; + } + return target.value; + } + }; + + // pure.ts + var JS = class { + generateSecretKey() { + return schnorr.utils.randomPrivateKey(); + } + getPublicKey(secretKey) { + return bytesToHex2(schnorr.getPublicKey(secretKey)); + } + finalizeEvent(t, secretKey) { + const event = t; + event.pubkey = bytesToHex2(schnorr.getPublicKey(secretKey)); + event.id = getEventHash(event); + event.sig = bytesToHex2(schnorr.sign(getEventHash(event), secretKey)); + event[verifiedSymbol] = true; + return event; + } + verifyEvent(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash3 = getEventHash(event); + if (hash3 !== event.id) { + event[verifiedSymbol] = false; + return false; + } + try { + const valid = schnorr.verify(event.sig, hash3, event.pubkey); + event[verifiedSymbol] = valid; + return valid; + } catch (err) { + event[verifiedSymbol] = false; + return false; + } + } + }; + function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); + } + function getEventHash(event) { + let eventHash = sha2562(utf8Encoder.encode(serializeEvent(event))); + return bytesToHex2(eventHash); + } + var i = new JS(); + var generateSecretKey = i.generateSecretKey; + var getPublicKey = i.getPublicKey; + var finalizeEvent = i.finalizeEvent; + var verifyEvent = i.verifyEvent; + + // kinds.ts + var kinds_exports = {}; + __export(kinds_exports, { + Application: () => Application, + BadgeAward: () => BadgeAward, + BadgeDefinition: () => BadgeDefinition, + BlockedRelaysList: () => BlockedRelaysList, + BookmarkList: () => BookmarkList, + Bookmarksets: () => Bookmarksets, + Calendar: () => Calendar, + CalendarEventRSVP: () => CalendarEventRSVP, + ChannelCreation: () => ChannelCreation, + ChannelHideMessage: () => ChannelHideMessage, + ChannelMessage: () => ChannelMessage, + ChannelMetadata: () => ChannelMetadata, + ChannelMuteUser: () => ChannelMuteUser, + ClassifiedListing: () => ClassifiedListing, + ClientAuth: () => ClientAuth, + CommunitiesList: () => CommunitiesList, + CommunityDefinition: () => CommunityDefinition, + CommunityPostApproval: () => CommunityPostApproval, + Contacts: () => Contacts, + CreateOrUpdateProduct: () => CreateOrUpdateProduct, + CreateOrUpdateStall: () => CreateOrUpdateStall, + Curationsets: () => Curationsets, + Date: () => Date2, + DirectMessageRelaysList: () => DirectMessageRelaysList, + DraftClassifiedListing: () => DraftClassifiedListing, + DraftLong: () => DraftLong, + Emojisets: () => Emojisets, + EncryptedDirectMessage: () => EncryptedDirectMessage, + EventDeletion: () => EventDeletion, + FileMetadata: () => FileMetadata, + FileServerPreference: () => FileServerPreference, + Followsets: () => Followsets, + GenericRepost: () => GenericRepost, + Genericlists: () => Genericlists, + GiftWrap: () => GiftWrap, + HTTPAuth: () => HTTPAuth, + Handlerinformation: () => Handlerinformation, + Handlerrecommendation: () => Handlerrecommendation, + Highlights: () => Highlights, + InterestsList: () => InterestsList, + Interestsets: () => Interestsets, + JobFeedback: () => JobFeedback, + JobRequest: () => JobRequest, + JobResult: () => JobResult, + Label: () => Label, + LightningPubRPC: () => LightningPubRPC, + LiveChatMessage: () => LiveChatMessage, + LiveEvent: () => LiveEvent, + LongFormArticle: () => LongFormArticle, + Metadata: () => Metadata, + Mutelist: () => Mutelist, + NWCWalletInfo: () => NWCWalletInfo, + NWCWalletRequest: () => NWCWalletRequest, + NWCWalletResponse: () => NWCWalletResponse, + NostrConnect: () => NostrConnect, + OpenTimestamps: () => OpenTimestamps, + Pinlist: () => Pinlist, + PrivateDirectMessage: () => PrivateDirectMessage, + ProblemTracker: () => ProblemTracker, + ProfileBadges: () => ProfileBadges, + PublicChatsList: () => PublicChatsList, + Reaction: () => Reaction, + RecommendRelay: () => RecommendRelay, + RelayList: () => RelayList, + Relaysets: () => Relaysets, + Report: () => Report, + Reporting: () => Reporting, + Repost: () => Repost, + Seal: () => Seal, + SearchRelaysList: () => SearchRelaysList, + ShortTextNote: () => ShortTextNote, + Time: () => Time, + UserEmojiList: () => UserEmojiList, + UserStatuses: () => UserStatuses, + Zap: () => Zap, + ZapGoal: () => ZapGoal, + ZapRequest: () => ZapRequest, + classifyKind: () => classifyKind, + isAddressableKind: () => isAddressableKind, + isEphemeralKind: () => isEphemeralKind, + isKind: () => isKind, + isRegularKind: () => isRegularKind, + isReplaceableKind: () => isReplaceableKind + }); + function isRegularKind(kind) { + return 1e3 <= kind && kind < 1e4 || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind); + } + function isReplaceableKind(kind) { + return [0, 3].includes(kind) || 1e4 <= kind && kind < 2e4; + } + function isEphemeralKind(kind) { + return 2e4 <= kind && kind < 3e4; + } + function isAddressableKind(kind) { + return 3e4 <= kind && kind < 4e4; + } + function classifyKind(kind) { + if (isRegularKind(kind)) + return "regular"; + if (isReplaceableKind(kind)) + return "replaceable"; + if (isEphemeralKind(kind)) + return "ephemeral"; + if (isAddressableKind(kind)) + return "parameterized"; + return "unknown"; + } + function isKind(event, kind) { + const kindAsArray = kind instanceof Array ? kind : [kind]; + return validateEvent(event) && kindAsArray.includes(event.kind) || false; + } + var Metadata = 0; + var ShortTextNote = 1; + var RecommendRelay = 2; + var Contacts = 3; + var EncryptedDirectMessage = 4; + var EventDeletion = 5; + var Repost = 6; + var Reaction = 7; + var BadgeAward = 8; + var Seal = 13; + var PrivateDirectMessage = 14; + var GenericRepost = 16; + var ChannelCreation = 40; + var ChannelMetadata = 41; + var ChannelMessage = 42; + var ChannelHideMessage = 43; + var ChannelMuteUser = 44; + var OpenTimestamps = 1040; + var GiftWrap = 1059; + var FileMetadata = 1063; + var LiveChatMessage = 1311; + var ProblemTracker = 1971; + var Report = 1984; + var Reporting = 1984; + var Label = 1985; + var CommunityPostApproval = 4550; + var JobRequest = 5999; + var JobResult = 6999; + var JobFeedback = 7e3; + var ZapGoal = 9041; + var ZapRequest = 9734; + var Zap = 9735; + var Highlights = 9802; + var Mutelist = 1e4; + var Pinlist = 10001; + var RelayList = 10002; + var BookmarkList = 10003; + var CommunitiesList = 10004; + var PublicChatsList = 10005; + var BlockedRelaysList = 10006; + var SearchRelaysList = 10007; + var InterestsList = 10015; + var UserEmojiList = 10030; + var DirectMessageRelaysList = 10050; + var FileServerPreference = 10096; + var NWCWalletInfo = 13194; + var LightningPubRPC = 21e3; + var ClientAuth = 22242; + var NWCWalletRequest = 23194; + var NWCWalletResponse = 23195; + var NostrConnect = 24133; + var HTTPAuth = 27235; + var Followsets = 3e4; + var Genericlists = 30001; + var Relaysets = 30002; + var Bookmarksets = 30003; + var Curationsets = 30004; + var ProfileBadges = 30008; + var BadgeDefinition = 30009; + var Interestsets = 30015; + var CreateOrUpdateStall = 30017; + var CreateOrUpdateProduct = 30018; + var LongFormArticle = 30023; + var DraftLong = 30024; + var Emojisets = 30030; + var Application = 30078; + var LiveEvent = 30311; + var UserStatuses = 30315; + var ClassifiedListing = 30402; + var DraftClassifiedListing = 30403; + var Date2 = 31922; + var Time = 31923; + var Calendar = 31924; + var CalendarEventRSVP = 31925; + var Handlerrecommendation = 31989; + var Handlerinformation = 31990; + var CommunityDefinition = 34550; + + // filter.ts + function matchFilter(filter, event) { + if (filter.ids && filter.ids.indexOf(event.id) === -1) { + return false; + } + if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) { + return false; + } + if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) { + return false; + } + for (let f in filter) { + if (f[0] === "#") { + let tagName = f.slice(1); + let values = filter[`#${tagName}`]; + if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values.indexOf(v) !== -1)) + return false; + } + } + if (filter.since && event.created_at < filter.since) + return false; + if (filter.until && event.created_at > filter.until) + return false; + return true; + } + function matchFilters(filters, event) { + for (let i2 = 0; i2 < filters.length; i2++) { + if (matchFilter(filters[i2], event)) { + return true; + } + } + return false; + } + function mergeFilters(...filters) { + let result = {}; + for (let i2 = 0; i2 < filters.length; i2++) { + let filter = filters[i2]; + Object.entries(filter).forEach(([property, values]) => { + if (property === "kinds" || property === "ids" || property === "authors" || property[0] === "#") { + result[property] = result[property] || []; + for (let v = 0; v < values.length; v++) { + let value = values[v]; + if (!result[property].includes(value)) + result[property].push(value); + } + } + }); + if (filter.limit && (!result.limit || filter.limit > result.limit)) + result.limit = filter.limit; + if (filter.until && (!result.until || filter.until > result.until)) + result.until = filter.until; + if (filter.since && (!result.since || filter.since < result.since)) + result.since = filter.since; + } + return result; + } + function getFilterLimit(filter) { + if (filter.ids && !filter.ids.length) + return 0; + if (filter.kinds && !filter.kinds.length) + return 0; + if (filter.authors && !filter.authors.length) + return 0; + for (const [key, value] of Object.entries(filter)) { + if (key[0] === "#" && Array.isArray(value) && !value.length) + return 0; + } + return Math.min( + Math.max(0, filter.limit ?? Infinity), + filter.ids?.length ?? Infinity, + filter.authors?.length && filter.kinds?.every((kind) => isReplaceableKind(kind)) ? filter.authors.length * filter.kinds.length : Infinity, + filter.authors?.length && filter.kinds?.every((kind) => isAddressableKind(kind)) && filter["#d"]?.length ? filter.authors.length * filter.kinds.length * filter["#d"].length : Infinity + ); + } + + // fakejson.ts + var fakejson_exports = {}; + __export(fakejson_exports, { + getHex64: () => getHex64, + getInt: () => getInt, + getSubscriptionId: () => getSubscriptionId, + matchEventId: () => matchEventId, + matchEventKind: () => matchEventKind, + matchEventPubkey: () => matchEventPubkey + }); + function getHex64(json, field) { + let len = field.length + 3; + let idx = json.indexOf(`"${field}":`) + len; + let s = json.slice(idx).indexOf(`"`) + idx + 1; + return json.slice(s, s + 64); + } + function getInt(json, field) { + let len = field.length; + let idx = json.indexOf(`"${field}":`) + len + 3; + let sliced = json.slice(idx); + let end = Math.min(sliced.indexOf(","), sliced.indexOf("}")); + return parseInt(sliced.slice(0, end), 10); + } + function getSubscriptionId(json) { + let idx = json.slice(0, 22).indexOf(`"EVENT"`); + if (idx === -1) + return null; + let pstart = json.slice(idx + 7 + 1).indexOf(`"`); + if (pstart === -1) + return null; + let start = idx + 7 + 1 + pstart; + let pend = json.slice(start + 1, 80).indexOf(`"`); + if (pend === -1) + return null; + let end = start + 1 + pend; + return json.slice(start + 1, end); + } + function matchEventId(json, id) { + return id === getHex64(json, "id"); + } + function matchEventPubkey(json, pubkey) { + return pubkey === getHex64(json, "pubkey"); + } + function matchEventKind(json, kind) { + return kind === getInt(json, "kind"); + } + + // nip42.ts + var nip42_exports = {}; + __export(nip42_exports, { + makeAuthEvent: () => makeAuthEvent + }); + function makeAuthEvent(relayURL, challenge2) { + return { + kind: ClientAuth, + created_at: Math.floor(Date.now() / 1e3), + tags: [ + ["relay", relayURL], + ["challenge", challenge2] + ], + content: "" + }; + } + + // helpers.ts + async function yieldThread() { + return new Promise((resolve) => { + const ch = new MessageChannel(); + const handler = () => { + ch.port1.removeEventListener("message", handler); + resolve(); + }; + ch.port1.addEventListener("message", handler); + ch.port2.postMessage(0); + ch.port1.start(); + }); + } + var alwaysTrue = (t) => { + t[verifiedSymbol] = true; + return true; + }; + + // abstract-relay.ts + var SendingOnClosedConnection = class extends Error { + constructor(message, relay) { + super(`Tried to send message '${message} on a closed connection to ${relay}.`); + this.name = "SendingOnClosedConnection"; + } + }; + var AbstractRelay = class { + url; + _connected = false; + onclose = null; + onnotice = (msg) => console.debug(`NOTICE from ${this.url}: ${msg}`); + baseEoseTimeout = 4400; + connectionTimeout = 4400; + publishTimeout = 4400; + pingFrequency = 2e4; + pingTimeout = 2e4; + openSubs = /* @__PURE__ */ new Map(); + enablePing; + connectionTimeoutHandle; + connectionPromise; + openCountRequests = /* @__PURE__ */ new Map(); + openEventPublishes = /* @__PURE__ */ new Map(); + ws; + incomingMessageQueue = new Queue(); + queueRunning = false; + challenge; + authPromise; + serial = 0; + verifyEvent; + _WebSocket; + constructor(url, opts) { + this.url = normalizeURL(url); + this.verifyEvent = opts.verifyEvent; + this._WebSocket = opts.websocketImplementation || WebSocket; + this.enablePing = opts.enablePing; + } + static async connect(url, opts) { + const relay = new AbstractRelay(url, opts); + await relay.connect(); + return relay; + } + closeAllSubscriptions(reason) { + for (let [_, sub] of this.openSubs) { + sub.close(reason); + } + this.openSubs.clear(); + for (let [_, ep] of this.openEventPublishes) { + ep.reject(new Error(reason)); + } + this.openEventPublishes.clear(); + for (let [_, cr] of this.openCountRequests) { + cr.reject(new Error(reason)); + } + this.openCountRequests.clear(); + } + get connected() { + return this._connected; + } + async connect() { + if (this.connectionPromise) + return this.connectionPromise; + this.challenge = void 0; + this.authPromise = void 0; + this.connectionPromise = new Promise((resolve, reject) => { + this.connectionTimeoutHandle = setTimeout(() => { + reject("connection timed out"); + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection timed out"); + }, this.connectionTimeout); + try { + this.ws = new this._WebSocket(this.url); + } catch (err) { + clearTimeout(this.connectionTimeoutHandle); + reject(err); + return; + } + this.ws.onopen = () => { + clearTimeout(this.connectionTimeoutHandle); + this._connected = true; + if (this.enablePing) { + this.pingpong(); + } + resolve(); + }; + this.ws.onerror = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket error"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection errored"); + } + }; + this.ws.onclose = (ev) => { + clearTimeout(this.connectionTimeoutHandle); + reject(ev.message || "websocket closed"); + if (this._connected) { + this._connected = false; + this.connectionPromise = void 0; + this.onclose?.(); + this.closeAllSubscriptions("relay connection closed"); + } + }; + this.ws.onmessage = this._onmessage.bind(this); + }); + return this.connectionPromise; + } + async waitForPingPong() { + return new Promise((res, err) => { + ; + this.ws && this.ws.on && this.ws.on("pong", () => res(true)) || err("ws can't listen for pong"); + this.ws && this.ws.ping && this.ws.ping(); + }); + } + async waitForDummyReq() { + return new Promise((resolve, _) => { + const sub = this.subscribe([{ ids: ["a".repeat(64)] }], { + oneose: () => { + sub.close(); + resolve(true); + }, + eoseTimeout: this.pingTimeout + 1e3 + }); + }); + } + async pingpong() { + if (this.ws?.readyState === 1) { + const result = await Promise.any([ + this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(), + new Promise((res) => setTimeout(() => res(false), this.pingTimeout)) + ]); + if (result) { + setTimeout(() => this.pingpong(), this.pingFrequency); + } else { + this.closeAllSubscriptions("pingpong timed out"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + } + } + async runQueue() { + this.queueRunning = true; + while (true) { + if (false === this.handleNext()) { + break; + } + await yieldThread(); + } + this.queueRunning = false; + } + handleNext() { + const json = this.incomingMessageQueue.dequeue(); + if (!json) { + return false; + } + const subid = getSubscriptionId(json); + if (subid) { + const so = this.openSubs.get(subid); + if (!so) { + return; + } + const id = getHex64(json, "id"); + const alreadyHave = so.alreadyHaveEvent?.(id); + so.receivedEvent?.(this, id); + if (alreadyHave) { + return; + } + } + try { + let data = JSON.parse(json); + switch (data[0]) { + case "EVENT": { + const so = this.openSubs.get(data[1]); + const event = data[2]; + if (this.verifyEvent(event) && matchFilters(so.filters, event)) { + so.onevent(event); + } + return; + } + case "COUNT": { + const id = data[1]; + const payload = data[2]; + const cr = this.openCountRequests.get(id); + if (cr) { + cr.resolve(payload.count); + this.openCountRequests.delete(id); + } + return; + } + case "EOSE": { + const so = this.openSubs.get(data[1]); + if (!so) + return; + so.receivedEose(); + return; + } + case "OK": { + const id = data[1]; + const ok = data[2]; + const reason = data[3]; + const ep = this.openEventPublishes.get(id); + if (ep) { + clearTimeout(ep.timeout); + if (ok) + ep.resolve(reason); + else + ep.reject(new Error(reason)); + this.openEventPublishes.delete(id); + } + return; + } + case "CLOSED": { + const id = data[1]; + const so = this.openSubs.get(id); + if (!so) + return; + so.closed = true; + so.close(data[2]); + return; + } + case "NOTICE": + this.onnotice(data[1]); + return; + case "AUTH": { + this.challenge = data[1]; + return; + } + } + } catch (err) { + return; + } + } + async send(message) { + if (!this.connectionPromise) + throw new SendingOnClosedConnection(message, this.url); + this.connectionPromise.then(() => { + this.ws?.send(message); + }); + } + async auth(signAuthEvent) { + const challenge2 = this.challenge; + if (!challenge2) + throw new Error("can't perform auth, no challenge was received"); + if (this.authPromise) + return this.authPromise; + this.authPromise = new Promise(async (resolve, reject) => { + try { + let evt = await signAuthEvent(makeAuthEvent(this.url, challenge2)); + let timeout = setTimeout(() => { + let ep = this.openEventPublishes.get(evt.id); + if (ep) { + ep.reject(new Error("auth timed out")); + this.openEventPublishes.delete(evt.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(evt.id, { resolve, reject, timeout }); + this.send('["AUTH",' + JSON.stringify(evt) + "]"); + } catch (err) { + console.warn("subscribe auth function failed:", err); + } + }); + return this.authPromise; + } + async publish(event) { + const ret = new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + const ep = this.openEventPublishes.get(event.id); + if (ep) { + ep.reject(new Error("publish timed out")); + this.openEventPublishes.delete(event.id); + } + }, this.publishTimeout); + this.openEventPublishes.set(event.id, { resolve, reject, timeout }); + }); + this.send('["EVENT",' + JSON.stringify(event) + "]"); + return ret; + } + async count(filters, params) { + this.serial++; + const id = params?.id || "count:" + this.serial; + const ret = new Promise((resolve, reject) => { + this.openCountRequests.set(id, { resolve, reject }); + }); + this.send('["COUNT","' + id + '",' + JSON.stringify(filters).substring(1)); + return ret; + } + subscribe(filters, params) { + const subscription = this.prepareSubscription(filters, params); + subscription.fire(); + return subscription; + } + prepareSubscription(filters, params) { + this.serial++; + const id = params.id || (params.label ? params.label + ":" : "sub:") + this.serial; + const subscription = new Subscription(this, id, filters, params); + this.openSubs.set(id, subscription); + return subscription; + } + close() { + this.closeAllSubscriptions("relay connection closed by us"); + this._connected = false; + this.ws?.close(); + this.onclose?.(); + } + _onmessage(ev) { + this.incomingMessageQueue.enqueue(ev.data); + if (!this.queueRunning) { + this.runQueue(); + } + } + }; + var Subscription = class { + relay; + id; + closed = false; + eosed = false; + filters; + alreadyHaveEvent; + receivedEvent; + onevent; + oneose; + onclose; + eoseTimeout; + eoseTimeoutHandle; + constructor(relay, id, filters, params) { + this.relay = relay; + this.filters = filters; + this.id = id; + this.alreadyHaveEvent = params.alreadyHaveEvent; + this.receivedEvent = params.receivedEvent; + this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout; + this.oneose = params.oneose; + this.onclose = params.onclose; + this.onevent = params.onevent || ((event) => { + console.warn( + `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`, + event + ); + }); + } + fire() { + this.relay.send('["REQ","' + this.id + '",' + JSON.stringify(this.filters).substring(1)); + this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout); + } + receivedEose() { + if (this.eosed) + return; + clearTimeout(this.eoseTimeoutHandle); + this.eosed = true; + this.oneose?.(); + } + close(reason = "closed by caller") { + if (!this.closed && this.relay.connected) { + try { + this.relay.send('["CLOSE",' + JSON.stringify(this.id) + "]"); + } catch (err) { + if (err instanceof SendingOnClosedConnection) { + } else { + throw err; + } + } + this.closed = true; + } + this.relay.openSubs.delete(this.id); + this.onclose?.(reason); + } + }; + + // relay.ts + var _WebSocket; + try { + _WebSocket = WebSocket; + } catch { + } + var Relay = class extends AbstractRelay { + constructor(url) { + super(url, { verifyEvent, websocketImplementation: _WebSocket }); + } + static async connect(url) { + const relay = new Relay(url); + await relay.connect(); + return relay; + } + }; + + // abstract-pool.ts + var AbstractSimplePool = class { + relays = /* @__PURE__ */ new Map(); + seenOn = /* @__PURE__ */ new Map(); + trackRelays = false; + verifyEvent; + enablePing; + trustedRelayURLs = /* @__PURE__ */ new Set(); + _WebSocket; + constructor(opts) { + this.verifyEvent = opts.verifyEvent; + this._WebSocket = opts.websocketImplementation; + this.enablePing = opts.enablePing; + } + async ensureRelay(url, params) { + url = normalizeURL(url); + let relay = this.relays.get(url); + if (!relay) { + relay = new AbstractRelay(url, { + verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent, + websocketImplementation: this._WebSocket, + enablePing: this.enablePing + }); + relay.onclose = () => { + this.relays.delete(url); + }; + if (params?.connectionTimeout) + relay.connectionTimeout = params.connectionTimeout; + this.relays.set(url, relay); + } + await relay.connect(); + return relay; + } + close(relays) { + relays.map(normalizeURL).forEach((url) => { + this.relays.get(url)?.close(); + this.relays.delete(url); + }); + } + subscribe(relays, filter, params) { + params.onauth = params.onauth || params.doauth; + const request = []; + for (let i2 = 0; i2 < relays.length; i2++) { + const url = normalizeURL(relays[i2]); + if (!request.find((r) => r.url === url)) { + request.push({ url, filter }); + } + } + return this.subscribeMap(request, params); + } + subscribeMany(relays, filters, params) { + params.onauth = params.onauth || params.doauth; + const request = []; + const uniqUrls = []; + for (let i2 = 0; i2 < relays.length; i2++) { + const url = normalizeURL(relays[i2]); + if (uniqUrls.indexOf(url) === -1) { + for (let f = 0; f < filters.length; f++) { + request.push({ url, filter: filters[f] }); + } + } + } + return this.subscribeMap(request, params); + } + subscribeMap(requests, params) { + params.onauth = params.onauth || params.doauth; + if (this.trackRelays) { + params.receivedEvent = (relay, id) => { + let set = this.seenOn.get(id); + if (!set) { + set = /* @__PURE__ */ new Set(); + this.seenOn.set(id, set); + } + set.add(relay); + }; + } + const _knownIds = /* @__PURE__ */ new Set(); + const subs = []; + const eosesReceived = []; + let handleEose = (i2) => { + if (eosesReceived[i2]) + return; + eosesReceived[i2] = true; + if (eosesReceived.filter((a) => a).length === requests.length) { + params.oneose?.(); + handleEose = () => { + }; + } + }; + const closesReceived = []; + let handleClose = (i2, reason) => { + if (closesReceived[i2]) + return; + handleEose(i2); + closesReceived[i2] = reason; + if (closesReceived.filter((a) => a).length === requests.length) { + params.onclose?.(closesReceived); + handleClose = () => { + }; + } + }; + const localAlreadyHaveEventHandler = (id) => { + if (params.alreadyHaveEvent?.(id)) { + return true; + } + const have = _knownIds.has(id); + _knownIds.add(id); + return have; + }; + const allOpened = Promise.all( + requests.map(async ({ url, filter }, i2) => { + let relay; + try { + relay = await this.ensureRelay(url, { + connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1e3) : void 0 + }); + } catch (err) { + handleClose(i2, err?.message || String(err)); + return; + } + let subscription = relay.subscribe([filter], { + ...params, + oneose: () => handleEose(i2), + onclose: (reason) => { + if (reason.startsWith("auth-required: ") && params.onauth) { + relay.auth(params.onauth).then(() => { + relay.subscribe([filter], { + ...params, + oneose: () => handleEose(i2), + onclose: (reason2) => { + handleClose(i2, reason2); + }, + alreadyHaveEvent: localAlreadyHaveEventHandler, + eoseTimeout: params.maxWait + }); + }).catch((err) => { + handleClose(i2, `auth was required and attempted, but failed with: ${err}`); + }); + } else { + handleClose(i2, reason); + } + }, + alreadyHaveEvent: localAlreadyHaveEventHandler, + eoseTimeout: params.maxWait + }); + subs.push(subscription); + }) + ); + return { + async close(reason) { + await allOpened; + subs.forEach((sub) => { + sub.close(reason); + }); + } + }; + } + subscribeEose(relays, filter, params) { + params.onauth = params.onauth || params.doauth; + const subcloser = this.subscribe(relays, filter, { + ...params, + oneose() { + subcloser.close("closed automatically on eose"); + } + }); + return subcloser; + } + subscribeManyEose(relays, filters, params) { + params.onauth = params.onauth || params.doauth; + const subcloser = this.subscribeMany(relays, filters, { + ...params, + oneose() { + subcloser.close("closed automatically on eose"); + } + }); + return subcloser; + } + async querySync(relays, filter, params) { + return new Promise(async (resolve) => { + const events = []; + this.subscribeEose(relays, filter, { + ...params, + onevent(event) { + events.push(event); + }, + onclose(_) { + resolve(events); + } + }); + }); + } + async get(relays, filter, params) { + filter.limit = 1; + const events = await this.querySync(relays, filter, params); + events.sort((a, b) => b.created_at - a.created_at); + return events[0] || null; + } + publish(relays, event, options) { + return relays.map(normalizeURL).map(async (url, i2, arr) => { + if (arr.indexOf(url) !== i2) { + return Promise.reject("duplicate url"); + } + let r = await this.ensureRelay(url); + return r.publish(event).catch(async (err) => { + if (err instanceof Error && err.message.startsWith("auth-required: ") && options?.onauth) { + await r.auth(options.onauth); + return r.publish(event); + } + throw err; + }).then((reason) => { + if (this.trackRelays) { + let set = this.seenOn.get(event.id); + if (!set) { + set = /* @__PURE__ */ new Set(); + this.seenOn.set(event.id, set); + } + set.add(r); + } + return reason; + }); + }); + } + listConnectionStatus() { + const map = /* @__PURE__ */ new Map(); + this.relays.forEach((relay, url) => map.set(url, relay.connected)); + return map; + } + destroy() { + this.relays.forEach((conn) => conn.close()); + this.relays = /* @__PURE__ */ new Map(); + } + }; + + // pool.ts + var _WebSocket2; + try { + _WebSocket2 = WebSocket; + } catch { + } + var SimplePool = class extends AbstractSimplePool { + constructor(options) { + super({ verifyEvent, websocketImplementation: _WebSocket2, ...options }); + } + }; + + // nip19.ts + var nip19_exports = {}; + __export(nip19_exports, { + BECH32_REGEX: () => BECH32_REGEX, + Bech32MaxSize: () => Bech32MaxSize, + NostrTypeGuard: () => NostrTypeGuard, + decode: () => decode, + decodeNostrURI: () => decodeNostrURI, + encodeBytes: () => encodeBytes, + naddrEncode: () => naddrEncode, + neventEncode: () => neventEncode, + noteEncode: () => noteEncode, + nprofileEncode: () => nprofileEncode, + npubEncode: () => npubEncode, + nsecEncode: () => nsecEncode + }); + + // node_modules/@scure/base/lib/esm/index.js + function assertNumber(n) { + if (!Number.isSafeInteger(n)) + throw new Error(`Wrong integer: ${n}`); + } + function chain(...args) { + const wrap = (a, b) => (c) => a(b(c)); + const encode = Array.from(args).reverse().reduce((acc, i2) => acc ? wrap(acc, i2.encode) : i2.encode, void 0); + const decode2 = args.reduce((acc, i2) => acc ? wrap(acc, i2.decode) : i2.decode, void 0); + return { encode, decode: decode2 }; + } + function alphabet(alphabet2) { + return { + encode: (digits) => { + if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number") + throw new Error("alphabet.encode input should be an array of numbers"); + return digits.map((i2) => { + assertNumber(i2); + if (i2 < 0 || i2 >= alphabet2.length) + throw new Error(`Digit index outside alphabet: ${i2} (alphabet: ${alphabet2.length})`); + return alphabet2[i2]; + }); + }, + decode: (input) => { + if (!Array.isArray(input) || input.length && typeof input[0] !== "string") + throw new Error("alphabet.decode input should be array of strings"); + return input.map((letter) => { + if (typeof letter !== "string") + throw new Error(`alphabet.decode: not string element=${letter}`); + const index = alphabet2.indexOf(letter); + if (index === -1) + throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet2}`); + return index; + }); + } + }; + } + function join(separator = "") { + if (typeof separator !== "string") + throw new Error("join separator should be string"); + return { + encode: (from) => { + if (!Array.isArray(from) || from.length && typeof from[0] !== "string") + throw new Error("join.encode input should be array of strings"); + for (let i2 of from) + if (typeof i2 !== "string") + throw new Error(`join.encode: non-string input=${i2}`); + return from.join(separator); + }, + decode: (to) => { + if (typeof to !== "string") + throw new Error("join.decode input should be string"); + return to.split(separator); + } + }; + } + function padding(bits, chr = "=") { + assertNumber(bits); + if (typeof chr !== "string") + throw new Error("padding chr should be string"); + return { + encode(data) { + if (!Array.isArray(data) || data.length && typeof data[0] !== "string") + throw new Error("padding.encode input should be array of strings"); + for (let i2 of data) + if (typeof i2 !== "string") + throw new Error(`padding.encode: non-string input=${i2}`); + while (data.length * bits % 8) + data.push(chr); + return data; + }, + decode(input) { + if (!Array.isArray(input) || input.length && typeof input[0] !== "string") + throw new Error("padding.encode input should be array of strings"); + for (let i2 of input) + if (typeof i2 !== "string") + throw new Error(`padding.decode: non-string input=${i2}`); + let end = input.length; + if (end * bits % 8) + throw new Error("Invalid padding: string should have whole number of bytes"); + for (; end > 0 && input[end - 1] === chr; end--) { + if (!((end - 1) * bits % 8)) + throw new Error("Invalid padding: string has too much padding"); + } + return input.slice(0, end); + } + }; + } + function normalize(fn) { + if (typeof fn !== "function") + throw new Error("normalize fn should be function"); + return { encode: (from) => from, decode: (to) => fn(to) }; + } + function convertRadix(data, from, to) { + if (from < 2) + throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`); + if (to < 2) + throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`); + if (!Array.isArray(data)) + throw new Error("convertRadix: data should be array"); + if (!data.length) + return []; + let pos = 0; + const res = []; + const digits = Array.from(data); + digits.forEach((d) => { + assertNumber(d); + if (d < 0 || d >= from) + throw new Error(`Wrong integer: ${d}`); + }); + while (true) { + let carry = 0; + let done = true; + for (let i2 = pos; i2 < digits.length; i2++) { + const digit = digits[i2]; + const digitBase = from * carry + digit; + if (!Number.isSafeInteger(digitBase) || from * carry / from !== carry || digitBase - digit !== from * carry) { + throw new Error("convertRadix: carry overflow"); + } + carry = digitBase % to; + digits[i2] = Math.floor(digitBase / to); + if (!Number.isSafeInteger(digits[i2]) || digits[i2] * to + carry !== digitBase) + throw new Error("convertRadix: carry overflow"); + if (!done) + continue; + else if (!digits[i2]) + pos = i2; + else + done = false; + } + res.push(carry); + if (done) + break; + } + for (let i2 = 0; i2 < data.length - 1 && data[i2] === 0; i2++) + res.push(0); + return res.reverse(); + } + var gcd = (a, b) => !b ? a : gcd(b, a % b); + var radix2carry = (from, to) => from + (to - gcd(from, to)); + function convertRadix2(data, from, to, padding2) { + if (!Array.isArray(data)) + throw new Error("convertRadix2: data should be array"); + if (from <= 0 || from > 32) + throw new Error(`convertRadix2: wrong from=${from}`); + if (to <= 0 || to > 32) + throw new Error(`convertRadix2: wrong to=${to}`); + if (radix2carry(from, to) > 32) { + throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`); + } + let carry = 0; + let pos = 0; + const mask = 2 ** to - 1; + const res = []; + for (const n of data) { + assertNumber(n); + if (n >= 2 ** from) + throw new Error(`convertRadix2: invalid data word=${n} from=${from}`); + carry = carry << from | n; + if (pos + from > 32) + throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`); + pos += from; + for (; pos >= to; pos -= to) + res.push((carry >> pos - to & mask) >>> 0); + carry &= 2 ** pos - 1; + } + carry = carry << to - pos & mask; + if (!padding2 && pos >= from) + throw new Error("Excess padding"); + if (!padding2 && carry) + throw new Error(`Non-zero padding: ${carry}`); + if (padding2 && pos > 0) + res.push(carry >>> 0); + return res; + } + function radix(num) { + assertNumber(num); + return { + encode: (bytes4) => { + if (!(bytes4 instanceof Uint8Array)) + throw new Error("radix.encode input should be Uint8Array"); + return convertRadix(Array.from(bytes4), 2 ** 8, num); + }, + decode: (digits) => { + if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number") + throw new Error("radix.decode input should be array of strings"); + return Uint8Array.from(convertRadix(digits, num, 2 ** 8)); + } + }; + } + function radix2(bits, revPadding = false) { + assertNumber(bits); + if (bits <= 0 || bits > 32) + throw new Error("radix2: bits should be in (0..32]"); + if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32) + throw new Error("radix2: carry overflow"); + return { + encode: (bytes4) => { + if (!(bytes4 instanceof Uint8Array)) + throw new Error("radix2.encode input should be Uint8Array"); + return convertRadix2(Array.from(bytes4), 8, bits, !revPadding); + }, + decode: (digits) => { + if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number") + throw new Error("radix2.decode input should be array of strings"); + return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding)); + } + }; + } + function unsafeWrapper(fn) { + if (typeof fn !== "function") + throw new Error("unsafeWrapper fn should be function"); + return function(...args) { + try { + return fn.apply(null, args); + } catch (e) { + } + }; + } + var base16 = chain(radix2(4), alphabet("0123456789ABCDEF"), join("")); + var base32 = chain(radix2(5), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), padding(5), join("")); + var base32hex = chain(radix2(5), alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), padding(5), join("")); + var base32crockford = chain(radix2(5), alphabet("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), join(""), normalize((s) => s.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1"))); + var base64 = chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), padding(6), join("")); + var base64url = chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), padding(6), join("")); + var genBase58 = (abc) => chain(radix(58), alphabet(abc), join("")); + var base58 = genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"); + var base58flickr = genBase58("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"); + var base58xrp = genBase58("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"); + var XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11]; + var base58xmr = { + encode(data) { + let res = ""; + for (let i2 = 0; i2 < data.length; i2 += 8) { + const block = data.subarray(i2, i2 + 8); + res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], "1"); + } + return res; + }, + decode(str) { + let res = []; + for (let i2 = 0; i2 < str.length; i2 += 11) { + const slice = str.slice(i2, i2 + 11); + const blockLen = XMR_BLOCK_LEN.indexOf(slice.length); + const block = base58.decode(slice); + for (let j = 0; j < block.length - blockLen; j++) { + if (block[j] !== 0) + throw new Error("base58xmr: wrong padding"); + } + res = res.concat(Array.from(block.slice(block.length - blockLen))); + } + return Uint8Array.from(res); + } + }; + var BECH_ALPHABET = chain(alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), join("")); + var POLYMOD_GENERATORS = [996825010, 642813549, 513874426, 1027748829, 705979059]; + function bech32Polymod(pre) { + const b = pre >> 25; + let chk = (pre & 33554431) << 5; + for (let i2 = 0; i2 < POLYMOD_GENERATORS.length; i2++) { + if ((b >> i2 & 1) === 1) + chk ^= POLYMOD_GENERATORS[i2]; + } + return chk; + } + function bechChecksum(prefix, words, encodingConst = 1) { + const len = prefix.length; + let chk = 1; + for (let i2 = 0; i2 < len; i2++) { + const c = prefix.charCodeAt(i2); + if (c < 33 || c > 126) + throw new Error(`Invalid prefix (${prefix})`); + chk = bech32Polymod(chk) ^ c >> 5; + } + chk = bech32Polymod(chk); + for (let i2 = 0; i2 < len; i2++) + chk = bech32Polymod(chk) ^ prefix.charCodeAt(i2) & 31; + for (let v of words) + chk = bech32Polymod(chk) ^ v; + for (let i2 = 0; i2 < 6; i2++) + chk = bech32Polymod(chk); + chk ^= encodingConst; + return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false)); + } + function genBech32(encoding) { + const ENCODING_CONST = encoding === "bech32" ? 1 : 734539939; + const _words = radix2(5); + const fromWords = _words.decode; + const toWords = _words.encode; + const fromWordsUnsafe = unsafeWrapper(fromWords); + function encode(prefix, words, limit2 = 90) { + if (typeof prefix !== "string") + throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`); + if (!Array.isArray(words) || words.length && typeof words[0] !== "number") + throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`); + const actualLength = prefix.length + 7 + words.length; + if (limit2 !== false && actualLength > limit2) + throw new TypeError(`Length ${actualLength} exceeds limit ${limit2}`); + prefix = prefix.toLowerCase(); + return `${prefix}1${BECH_ALPHABET.encode(words)}${bechChecksum(prefix, words, ENCODING_CONST)}`; + } + function decode2(str, limit2 = 90) { + if (typeof str !== "string") + throw new Error(`bech32.decode input should be string, not ${typeof str}`); + if (str.length < 8 || limit2 !== false && str.length > limit2) + throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit2})`); + const lowered = str.toLowerCase(); + if (str !== lowered && str !== str.toUpperCase()) + throw new Error(`String must be lowercase or uppercase`); + str = lowered; + const sepIndex = str.lastIndexOf("1"); + if (sepIndex === 0 || sepIndex === -1) + throw new Error(`Letter "1" must be present between prefix and data only`); + const prefix = str.slice(0, sepIndex); + const _words2 = str.slice(sepIndex + 1); + if (_words2.length < 6) + throw new Error("Data must be at least 6 characters long"); + const words = BECH_ALPHABET.decode(_words2).slice(0, -6); + const sum = bechChecksum(prefix, words, ENCODING_CONST); + if (!_words2.endsWith(sum)) + throw new Error(`Invalid checksum in ${str}: expected "${sum}"`); + return { prefix, words }; + } + const decodeUnsafe = unsafeWrapper(decode2); + function decodeToBytes(str) { + const { prefix, words } = decode2(str, false); + return { prefix, words, bytes: fromWords(words) }; + } + return { encode, decode: decode2, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords }; + } + var bech32 = genBech32("bech32"); + var bech32m = genBech32("bech32m"); + var utf8 = { + encode: (data) => new TextDecoder().decode(data), + decode: (str) => new TextEncoder().encode(str) + }; + var hex = chain(radix2(4), alphabet("0123456789abcdef"), join(""), normalize((s) => { + if (typeof s !== "string" || s.length % 2) + throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`); + return s.toLowerCase(); + })); + var CODERS = { + utf8, + hex, + base16, + base32, + base64, + base64url, + base58, + base58xmr + }; + var coderTypeError = `Invalid encoding type. Available types: ${Object.keys(CODERS).join(", ")}`; + + // nip19.ts + var NostrTypeGuard = { + isNProfile: (value) => /^nprofile1[a-z\d]+$/.test(value || ""), + isNEvent: (value) => /^nevent1[a-z\d]+$/.test(value || ""), + isNAddr: (value) => /^naddr1[a-z\d]+$/.test(value || ""), + isNSec: (value) => /^nsec1[a-z\d]{58}$/.test(value || ""), + isNPub: (value) => /^npub1[a-z\d]{58}$/.test(value || ""), + isNote: (value) => /^note1[a-z\d]+$/.test(value || ""), + isNcryptsec: (value) => /^ncryptsec1[a-z\d]+$/.test(value || "") + }; + var Bech32MaxSize = 5e3; + var BECH32_REGEX = /[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/; + function integerToUint8Array(number4) { + const uint8Array = new Uint8Array(4); + uint8Array[0] = number4 >> 24 & 255; + uint8Array[1] = number4 >> 16 & 255; + uint8Array[2] = number4 >> 8 & 255; + uint8Array[3] = number4 & 255; + return uint8Array; + } + function decodeNostrURI(nip19code) { + try { + if (nip19code.startsWith("nostr:")) + nip19code = nip19code.substring(6); + return decode(nip19code); + } catch (_err) { + return { type: "invalid", data: null }; + } + } + function decode(code) { + let { prefix, words } = bech32.decode(code, Bech32MaxSize); + let data = new Uint8Array(bech32.fromWords(words)); + switch (prefix) { + case "nprofile": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nprofile"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + return { + type: "nprofile", + data: { + pubkey: bytesToHex2(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nevent": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for nevent"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + if (tlv[2] && tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (tlv[3] && tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "nevent", + data: { + id: bytesToHex2(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [], + author: tlv[2]?.[0] ? bytesToHex2(tlv[2][0]) : void 0, + kind: tlv[3]?.[0] ? parseInt(bytesToHex2(tlv[3][0]), 16) : void 0 + } + }; + } + case "naddr": { + let tlv = parseTLV(data); + if (!tlv[0]?.[0]) + throw new Error("missing TLV 0 for naddr"); + if (!tlv[2]?.[0]) + throw new Error("missing TLV 2 for naddr"); + if (tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (!tlv[3]?.[0]) + throw new Error("missing TLV 3 for naddr"); + if (tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "naddr", + data: { + identifier: utf8Decoder.decode(tlv[0][0]), + pubkey: bytesToHex2(tlv[2][0]), + kind: parseInt(bytesToHex2(tlv[3][0]), 16), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] + } + }; + } + case "nsec": + return { type: prefix, data }; + case "npub": + case "note": + return { type: prefix, data: bytesToHex2(data) }; + default: + throw new Error(`unknown prefix ${prefix}`); + } + } + function parseTLV(data) { + let result = {}; + let rest = data; + while (rest.length > 0) { + let t = rest[0]; + let l = rest[1]; + let v = rest.slice(2, 2 + l); + rest = rest.slice(2 + l); + if (v.length < l) + throw new Error(`not enough data to read on TLV ${t}`); + result[t] = result[t] || []; + result[t].push(v); + } + return result; + } + function nsecEncode(key) { + return encodeBytes("nsec", key); + } + function npubEncode(hex2) { + return encodeBytes("npub", hexToBytes2(hex2)); + } + function noteEncode(hex2) { + return encodeBytes("note", hexToBytes2(hex2)); + } + function encodeBech32(prefix, data) { + let words = bech32.toWords(data); + return bech32.encode(prefix, words, Bech32MaxSize); + } + function encodeBytes(prefix, bytes4) { + return encodeBech32(prefix, bytes4); + } + function nprofileEncode(profile) { + let data = encodeTLV({ + 0: [hexToBytes2(profile.pubkey)], + 1: (profile.relays || []).map((url) => utf8Encoder.encode(url)) + }); + return encodeBech32("nprofile", data); + } + function neventEncode(event) { + let kindArray; + if (event.kind !== void 0) { + kindArray = integerToUint8Array(event.kind); + } + let data = encodeTLV({ + 0: [hexToBytes2(event.id)], + 1: (event.relays || []).map((url) => utf8Encoder.encode(url)), + 2: event.author ? [hexToBytes2(event.author)] : [], + 3: kindArray ? [new Uint8Array(kindArray)] : [] + }); + return encodeBech32("nevent", data); + } + function naddrEncode(addr) { + let kind = new ArrayBuffer(4); + new DataView(kind).setUint32(0, addr.kind, false); + let data = encodeTLV({ + 0: [utf8Encoder.encode(addr.identifier)], + 1: (addr.relays || []).map((url) => utf8Encoder.encode(url)), + 2: [hexToBytes2(addr.pubkey)], + 3: [new Uint8Array(kind)] + }); + return encodeBech32("naddr", data); + } + function encodeTLV(tlv) { + let entries = []; + Object.entries(tlv).reverse().forEach(([t, vs]) => { + vs.forEach((v) => { + let entry = new Uint8Array(v.length + 2); + entry.set([parseInt(t)], 0); + entry.set([v.length], 1); + entry.set(v, 2); + entries.push(entry); + }); + }); + return concatBytes3(...entries); + } + + // references.ts + var mentionRegex = /\bnostr:((note|npub|naddr|nevent|nprofile)1\w+)\b|#\[(\d+)\]/g; + function parseReferences(evt) { + let references = []; + for (let ref of evt.content.matchAll(mentionRegex)) { + if (ref[2]) { + try { + let { type, data } = decode(ref[1]); + switch (type) { + case "npub": { + references.push({ + text: ref[0], + profile: { pubkey: data, relays: [] } + }); + break; + } + case "nprofile": { + references.push({ + text: ref[0], + profile: data + }); + break; + } + case "note": { + references.push({ + text: ref[0], + event: { id: data, relays: [] } + }); + break; + } + case "nevent": { + references.push({ + text: ref[0], + event: data + }); + break; + } + case "naddr": { + references.push({ + text: ref[0], + address: data + }); + break; + } + } + } catch (err) { + } + } else if (ref[3]) { + let idx = parseInt(ref[3], 10); + let tag = evt.tags[idx]; + if (!tag) + continue; + switch (tag[0]) { + case "p": { + references.push({ + text: ref[0], + profile: { pubkey: tag[1], relays: tag[2] ? [tag[2]] : [] } + }); + break; + } + case "e": { + references.push({ + text: ref[0], + event: { id: tag[1], relays: tag[2] ? [tag[2]] : [] } + }); + break; + } + case "a": { + try { + let [kind, pubkey, identifier] = tag[1].split(":"); + references.push({ + text: ref[0], + address: { + identifier, + pubkey, + kind: parseInt(kind, 10), + relays: tag[2] ? [tag[2]] : [] + } + }); + } catch (err) { + } + break; + } + } + } + } + return references; + } + + // nip04.ts + var nip04_exports = {}; + __export(nip04_exports, { + decrypt: () => decrypt2, + encrypt: () => encrypt2 + }); + + // node_modules/@noble/ciphers/esm/_assert.js + function number3(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`positive integer expected, not ${n}`); + } + function bool2(b) { + if (typeof b !== "boolean") + throw new Error(`boolean expected, not ${b}`); + } + function isBytes(a) { + return a instanceof Uint8Array || a != null && typeof a === "object" && a.constructor.name === "Uint8Array"; + } + function bytes3(b, ...lengths) { + if (!isBytes(b)) + throw new Error("Uint8Array expected"); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`); + } + function exists3(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error("Hash instance has been destroyed"); + if (checkFinished && instance.finished) + throw new Error("Hash#digest() has already been called"); + } + function output3(out, instance) { + bytes3(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } + } + + // node_modules/@noble/ciphers/esm/utils.js + var u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); + var u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); + var createView3 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); + var isLE3 = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; + if (!isLE3) + throw new Error("Non little-endian hardware is not supported"); + function utf8ToBytes4(str) { + if (typeof str !== "string") + throw new Error(`string expected, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); + } + function toBytes3(data) { + if (typeof data === "string") + data = utf8ToBytes4(data); + else if (isBytes(data)) + data = data.slice(); + else + throw new Error(`Uint8Array expected, got ${typeof data}`); + return data; + } + function checkOpts(defaults, opts) { + if (opts == null || typeof opts !== "object") + throw new Error("options must be defined"); + const merged = Object.assign(defaults, opts); + return merged; + } + function equalBytes2(a, b) { + if (a.length !== b.length) + return false; + let diff = 0; + for (let i2 = 0; i2 < a.length; i2++) + diff |= a[i2] ^ b[i2]; + return diff === 0; + } + var wrapCipher = (params, c) => { + Object.assign(c, params); + return c; + }; + function setBigUint643(view, byteOffset, value, isLE4) { + if (typeof view.setBigUint64 === "function") + return view.setBigUint64(byteOffset, value, isLE4); + const _32n = BigInt(32); + const _u32_max = BigInt(4294967295); + const wh = Number(value >> _32n & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE4 ? 4 : 0; + const l = isLE4 ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE4); + view.setUint32(byteOffset + l, wl, isLE4); + } + + // node_modules/@noble/ciphers/esm/_polyval.js + var BLOCK_SIZE = 16; + var ZEROS16 = /* @__PURE__ */ new Uint8Array(16); + var ZEROS32 = u32(ZEROS16); + var POLY = 225; + var mul2 = (s0, s1, s2, s3) => { + const hiBit = s3 & 1; + return { + s3: s2 << 31 | s3 >>> 1, + s2: s1 << 31 | s2 >>> 1, + s1: s0 << 31 | s1 >>> 1, + s0: s0 >>> 1 ^ POLY << 24 & -(hiBit & 1) + }; + }; + var swapLE = (n) => (n >>> 0 & 255) << 24 | (n >>> 8 & 255) << 16 | (n >>> 16 & 255) << 8 | n >>> 24 & 255 | 0; + function _toGHASHKey(k) { + k.reverse(); + const hiBit = k[15] & 1; + let carry = 0; + for (let i2 = 0; i2 < k.length; i2++) { + const t = k[i2]; + k[i2] = t >>> 1 | carry; + carry = (t & 1) << 7; + } + k[0] ^= -hiBit & 225; + return k; + } + var estimateWindow = (bytes4) => { + if (bytes4 > 64 * 1024) + return 8; + if (bytes4 > 1024) + return 4; + return 2; + }; + var GHASH = class { + constructor(key, expectedLength) { + this.blockLen = BLOCK_SIZE; + this.outputLen = BLOCK_SIZE; + this.s0 = 0; + this.s1 = 0; + this.s2 = 0; + this.s3 = 0; + this.finished = false; + key = toBytes3(key); + bytes3(key, 16); + const kView = createView3(key); + let k0 = kView.getUint32(0, false); + let k1 = kView.getUint32(4, false); + let k2 = kView.getUint32(8, false); + let k3 = kView.getUint32(12, false); + const doubles = []; + for (let i2 = 0; i2 < 128; i2++) { + doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) }); + ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3)); + } + const W = estimateWindow(expectedLength || 1024); + if (![1, 2, 4, 8].includes(W)) + throw new Error(`ghash: wrong window size=${W}, should be 2, 4 or 8`); + this.W = W; + const bits = 128; + const windows = bits / W; + const windowSize = this.windowSize = 2 ** W; + const items = []; + for (let w = 0; w < windows; w++) { + for (let byte = 0; byte < windowSize; byte++) { + let s0 = 0, s1 = 0, s2 = 0, s3 = 0; + for (let j = 0; j < W; j++) { + const bit = byte >>> W - j - 1 & 1; + if (!bit) + continue; + const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j]; + s0 ^= d0, s1 ^= d1, s2 ^= d2, s3 ^= d3; + } + items.push({ s0, s1, s2, s3 }); + } + } + this.t = items; + } + _updateBlock(s0, s1, s2, s3) { + s0 ^= this.s0, s1 ^= this.s1, s2 ^= this.s2, s3 ^= this.s3; + const { W, t, windowSize } = this; + let o0 = 0, o1 = 0, o2 = 0, o3 = 0; + const mask = (1 << W) - 1; + let w = 0; + for (const num of [s0, s1, s2, s3]) { + for (let bytePos = 0; bytePos < 4; bytePos++) { + const byte = num >>> 8 * bytePos & 255; + for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) { + const bit = byte >>> W * bitPos & mask; + const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit]; + o0 ^= e0, o1 ^= e1, o2 ^= e2, o3 ^= e3; + w += 1; + } + } + } + this.s0 = o0; + this.s1 = o1; + this.s2 = o2; + this.s3 = o3; + } + update(data) { + data = toBytes3(data); + exists3(this); + const b32 = u32(data); + const blocks = Math.floor(data.length / BLOCK_SIZE); + const left = data.length % BLOCK_SIZE; + for (let i2 = 0; i2 < blocks; i2++) { + this._updateBlock(b32[i2 * 4 + 0], b32[i2 * 4 + 1], b32[i2 * 4 + 2], b32[i2 * 4 + 3]); + } + if (left) { + ZEROS16.set(data.subarray(blocks * BLOCK_SIZE)); + this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]); + ZEROS32.fill(0); + } + return this; + } + destroy() { + const { t } = this; + for (const elm of t) { + elm.s0 = 0, elm.s1 = 0, elm.s2 = 0, elm.s3 = 0; + } + } + digestInto(out) { + exists3(this); + output3(out, this); + this.finished = true; + const { s0, s1, s2, s3 } = this; + const o32 = u32(out); + o32[0] = s0; + o32[1] = s1; + o32[2] = s2; + o32[3] = s3; + return out; + } + digest() { + const res = new Uint8Array(BLOCK_SIZE); + this.digestInto(res); + this.destroy(); + return res; + } + }; + var Polyval = class extends GHASH { + constructor(key, expectedLength) { + key = toBytes3(key); + const ghKey = _toGHASHKey(key.slice()); + super(ghKey, expectedLength); + ghKey.fill(0); + } + update(data) { + data = toBytes3(data); + exists3(this); + const b32 = u32(data); + const left = data.length % BLOCK_SIZE; + const blocks = Math.floor(data.length / BLOCK_SIZE); + for (let i2 = 0; i2 < blocks; i2++) { + this._updateBlock(swapLE(b32[i2 * 4 + 3]), swapLE(b32[i2 * 4 + 2]), swapLE(b32[i2 * 4 + 1]), swapLE(b32[i2 * 4 + 0])); + } + if (left) { + ZEROS16.set(data.subarray(blocks * BLOCK_SIZE)); + this._updateBlock(swapLE(ZEROS32[3]), swapLE(ZEROS32[2]), swapLE(ZEROS32[1]), swapLE(ZEROS32[0])); + ZEROS32.fill(0); + } + return this; + } + digestInto(out) { + exists3(this); + output3(out, this); + this.finished = true; + const { s0, s1, s2, s3 } = this; + const o32 = u32(out); + o32[0] = s0; + o32[1] = s1; + o32[2] = s2; + o32[3] = s3; + return out.reverse(); + } + }; + function wrapConstructorWithKey(hashCons) { + const hashC = (msg, key) => hashCons(key, msg.length).update(toBytes3(msg)).digest(); + const tmp = hashCons(new Uint8Array(16), 0); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (key, expectedLength) => hashCons(key, expectedLength); + return hashC; + } + var ghash = wrapConstructorWithKey((key, expectedLength) => new GHASH(key, expectedLength)); + var polyval = wrapConstructorWithKey((key, expectedLength) => new Polyval(key, expectedLength)); + + // node_modules/@noble/ciphers/esm/aes.js + var BLOCK_SIZE2 = 16; + var BLOCK_SIZE32 = 4; + var EMPTY_BLOCK = new Uint8Array(BLOCK_SIZE2); + var POLY2 = 283; + function mul22(n) { + return n << 1 ^ POLY2 & -(n >> 7); + } + function mul(a, b) { + let res = 0; + for (; b > 0; b >>= 1) { + res ^= a & -(b & 1); + a = mul22(a); + } + return res; + } + var sbox = /* @__PURE__ */ (() => { + let t = new Uint8Array(256); + for (let i2 = 0, x = 1; i2 < 256; i2++, x ^= mul22(x)) + t[i2] = x; + const box = new Uint8Array(256); + box[0] = 99; + for (let i2 = 0; i2 < 255; i2++) { + let x = t[255 - i2]; + x |= x << 8; + box[t[i2]] = (x ^ x >> 4 ^ x >> 5 ^ x >> 6 ^ x >> 7 ^ 99) & 255; + } + return box; + })(); + var invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j)); + var rotr32_8 = (n) => n << 24 | n >>> 8; + var rotl32_8 = (n) => n << 8 | n >>> 24; + function genTtable(sbox2, fn) { + if (sbox2.length !== 256) + throw new Error("Wrong sbox length"); + const T0 = new Uint32Array(256).map((_, j) => fn(sbox2[j])); + const T1 = T0.map(rotl32_8); + const T2 = T1.map(rotl32_8); + const T3 = T2.map(rotl32_8); + const T01 = new Uint32Array(256 * 256); + const T23 = new Uint32Array(256 * 256); + const sbox22 = new Uint16Array(256 * 256); + for (let i2 = 0; i2 < 256; i2++) { + for (let j = 0; j < 256; j++) { + const idx = i2 * 256 + j; + T01[idx] = T0[i2] ^ T1[j]; + T23[idx] = T2[i2] ^ T3[j]; + sbox22[idx] = sbox2[i2] << 8 | sbox2[j]; + } + } + return { sbox: sbox2, sbox2: sbox22, T0, T1, T2, T3, T01, T23 }; + } + var tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => mul(s, 3) << 24 | s << 16 | s << 8 | mul(s, 2)); + var tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => mul(s, 11) << 24 | mul(s, 13) << 16 | mul(s, 9) << 8 | mul(s, 14)); + var xPowers = /* @__PURE__ */ (() => { + const p = new Uint8Array(16); + for (let i2 = 0, x = 1; i2 < 16; i2++, x = mul22(x)) + p[i2] = x; + return p; + })(); + function expandKeyLE(key) { + bytes3(key); + const len = key.length; + if (![16, 24, 32].includes(len)) + throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`); + const { sbox2 } = tableEncoding; + const k32 = u32(key); + const Nk = k32.length; + const subByte = (n) => applySbox(sbox2, n, n, n, n); + const xk = new Uint32Array(len + 28); + xk.set(k32); + for (let i2 = Nk; i2 < xk.length; i2++) { + let t = xk[i2 - 1]; + if (i2 % Nk === 0) + t = subByte(rotr32_8(t)) ^ xPowers[i2 / Nk - 1]; + else if (Nk > 6 && i2 % Nk === 4) + t = subByte(t); + xk[i2] = xk[i2 - Nk] ^ t; + } + return xk; + } + function expandKeyDecLE(key) { + const encKey = expandKeyLE(key); + const xk = encKey.slice(); + const Nk = encKey.length; + const { sbox2 } = tableEncoding; + const { T0, T1, T2, T3 } = tableDecoding; + for (let i2 = 0; i2 < Nk; i2 += 4) { + for (let j = 0; j < 4; j++) + xk[i2 + j] = encKey[Nk - i2 - 4 + j]; + } + encKey.fill(0); + for (let i2 = 4; i2 < Nk - 4; i2++) { + const x = xk[i2]; + const w = applySbox(sbox2, x, x, x, x); + xk[i2] = T0[w & 255] ^ T1[w >>> 8 & 255] ^ T2[w >>> 16 & 255] ^ T3[w >>> 24]; + } + return xk; + } + function apply0123(T01, T23, s0, s1, s2, s3) { + return T01[s0 << 8 & 65280 | s1 >>> 8 & 255] ^ T23[s2 >>> 8 & 65280 | s3 >>> 24 & 255]; + } + function applySbox(sbox2, s0, s1, s2, s3) { + return sbox2[s0 & 255 | s1 & 65280] | sbox2[s2 >>> 16 & 255 | s3 >>> 16 & 65280] << 16; + } + function encrypt(xk, s0, s1, s2, s3) { + const { sbox2, T01, T23 } = tableEncoding; + let k = 0; + s0 ^= xk[k++], s1 ^= xk[k++], s2 ^= xk[k++], s3 ^= xk[k++]; + const rounds = xk.length / 4 - 2; + for (let i2 = 0; i2 < rounds; i2++) { + const t02 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3); + const t12 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0); + const t22 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1); + const t32 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2); + s0 = t02, s1 = t12, s2 = t22, s3 = t32; + } + const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3); + const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0); + const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1); + const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; + } + function decrypt(xk, s0, s1, s2, s3) { + const { sbox2, T01, T23 } = tableDecoding; + let k = 0; + s0 ^= xk[k++], s1 ^= xk[k++], s2 ^= xk[k++], s3 ^= xk[k++]; + const rounds = xk.length / 4 - 2; + for (let i2 = 0; i2 < rounds; i2++) { + const t02 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1); + const t12 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2); + const t22 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3); + const t32 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0); + s0 = t02, s1 = t12, s2 = t22, s3 = t32; + } + const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1); + const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2); + const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3); + const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; + } + function getDst(len, dst) { + if (!dst) + return new Uint8Array(len); + bytes3(dst); + if (dst.length < len) + throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`); + return dst; + } + function ctrCounter(xk, nonce, src, dst) { + bytes3(nonce, BLOCK_SIZE2); + bytes3(src); + const srcLen = src.length; + dst = getDst(srcLen, dst); + const ctr3 = nonce; + const c32 = u32(ctr3); + let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]); + const src32 = u32(src); + const dst32 = u32(dst); + for (let i2 = 0; i2 + 4 <= src32.length; i2 += 4) { + dst32[i2 + 0] = src32[i2 + 0] ^ s0; + dst32[i2 + 1] = src32[i2 + 1] ^ s1; + dst32[i2 + 2] = src32[i2 + 2] ^ s2; + dst32[i2 + 3] = src32[i2 + 3] ^ s3; + let carry = 1; + for (let i3 = ctr3.length - 1; i3 >= 0; i3--) { + carry = carry + (ctr3[i3] & 255) | 0; + ctr3[i3] = carry & 255; + carry >>>= 8; + } + ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3])); + } + const start = BLOCK_SIZE2 * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + const b32 = new Uint32Array([s0, s1, s2, s3]); + const buf = u8(b32); + for (let i2 = start, pos = 0; i2 < srcLen; i2++, pos++) + dst[i2] = src[i2] ^ buf[pos]; + } + return dst; + } + function ctr32(xk, isLE4, nonce, src, dst) { + bytes3(nonce, BLOCK_SIZE2); + bytes3(src); + dst = getDst(src.length, dst); + const ctr3 = nonce; + const c32 = u32(ctr3); + const view = createView3(ctr3); + const src32 = u32(src); + const dst32 = u32(dst); + const ctrPos = isLE4 ? 0 : 12; + const srcLen = src.length; + let ctrNum = view.getUint32(ctrPos, isLE4); + let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]); + for (let i2 = 0; i2 + 4 <= src32.length; i2 += 4) { + dst32[i2 + 0] = src32[i2 + 0] ^ s0; + dst32[i2 + 1] = src32[i2 + 1] ^ s1; + dst32[i2 + 2] = src32[i2 + 2] ^ s2; + dst32[i2 + 3] = src32[i2 + 3] ^ s3; + ctrNum = ctrNum + 1 >>> 0; + view.setUint32(ctrPos, ctrNum, isLE4); + ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3])); + } + const start = BLOCK_SIZE2 * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + const b32 = new Uint32Array([s0, s1, s2, s3]); + const buf = u8(b32); + for (let i2 = start, pos = 0; i2 < srcLen; i2++, pos++) + dst[i2] = src[i2] ^ buf[pos]; + } + return dst; + } + var ctr = wrapCipher({ blockSize: 16, nonceLength: 16 }, function ctr2(key, nonce) { + bytes3(key); + bytes3(nonce, BLOCK_SIZE2); + function processCtr(buf, dst) { + const xk = expandKeyLE(key); + const n = nonce.slice(); + const out = ctrCounter(xk, n, buf, dst); + xk.fill(0); + n.fill(0); + return out; + } + return { + encrypt: (plaintext, dst) => processCtr(plaintext, dst), + decrypt: (ciphertext, dst) => processCtr(ciphertext, dst) + }; + }); + function validateBlockDecrypt(data) { + bytes3(data); + if (data.length % BLOCK_SIZE2 !== 0) { + throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE2}`); + } + } + function validateBlockEncrypt(plaintext, pcks5, dst) { + let outLen = plaintext.length; + const remaining = outLen % BLOCK_SIZE2; + if (!pcks5 && remaining !== 0) + throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding"); + const b = u32(plaintext); + if (pcks5) { + let left = BLOCK_SIZE2 - remaining; + if (!left) + left = BLOCK_SIZE2; + outLen = outLen + left; + } + const out = getDst(outLen, dst); + const o = u32(out); + return { b, o, out }; + } + function validatePCKS(data, pcks5) { + if (!pcks5) + return data; + const len = data.length; + if (!len) + throw new Error(`aes/pcks5: empty ciphertext not allowed`); + const lastByte = data[len - 1]; + if (lastByte <= 0 || lastByte > 16) + throw new Error(`aes/pcks5: wrong padding byte: ${lastByte}`); + const out = data.subarray(0, -lastByte); + for (let i2 = 0; i2 < lastByte; i2++) + if (data[len - i2 - 1] !== lastByte) + throw new Error(`aes/pcks5: wrong padding`); + return out; + } + function padPCKS(left) { + const tmp = new Uint8Array(16); + const tmp32 = u32(tmp); + tmp.set(left); + const paddingByte = BLOCK_SIZE2 - left.length; + for (let i2 = BLOCK_SIZE2 - paddingByte; i2 < BLOCK_SIZE2; i2++) + tmp[i2] = paddingByte; + return tmp32; + } + var ecb = wrapCipher({ blockSize: 16 }, function ecb2(key, opts = {}) { + bytes3(key); + const pcks5 = !opts.disablePadding; + return { + encrypt: (plaintext, dst) => { + bytes3(plaintext); + const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst); + const xk = expandKeyLE(key); + let i2 = 0; + for (; i2 + 4 <= b.length; ) { + const { s0, s1, s2, s3 } = encrypt(xk, b[i2 + 0], b[i2 + 1], b[i2 + 2], b[i2 + 3]); + o[i2++] = s0, o[i2++] = s1, o[i2++] = s2, o[i2++] = s3; + } + if (pcks5) { + const tmp32 = padPCKS(plaintext.subarray(i2 * 4)); + const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]); + o[i2++] = s0, o[i2++] = s1, o[i2++] = s2, o[i2++] = s3; + } + xk.fill(0); + return _out; + }, + decrypt: (ciphertext, dst) => { + validateBlockDecrypt(ciphertext); + const xk = expandKeyDecLE(key); + const out = getDst(ciphertext.length, dst); + const b = u32(ciphertext); + const o = u32(out); + for (let i2 = 0; i2 + 4 <= b.length; ) { + const { s0, s1, s2, s3 } = decrypt(xk, b[i2 + 0], b[i2 + 1], b[i2 + 2], b[i2 + 3]); + o[i2++] = s0, o[i2++] = s1, o[i2++] = s2, o[i2++] = s3; + } + xk.fill(0); + return validatePCKS(out, pcks5); + } + }; + }); + var cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc2(key, iv, opts = {}) { + bytes3(key); + bytes3(iv, 16); + const pcks5 = !opts.disablePadding; + return { + encrypt: (plaintext, dst) => { + const xk = expandKeyLE(key); + const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst); + const n32 = u32(iv); + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + let i2 = 0; + for (; i2 + 4 <= b.length; ) { + s0 ^= b[i2 + 0], s1 ^= b[i2 + 1], s2 ^= b[i2 + 2], s3 ^= b[i2 + 3]; + ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3)); + o[i2++] = s0, o[i2++] = s1, o[i2++] = s2, o[i2++] = s3; + } + if (pcks5) { + const tmp32 = padPCKS(plaintext.subarray(i2 * 4)); + s0 ^= tmp32[0], s1 ^= tmp32[1], s2 ^= tmp32[2], s3 ^= tmp32[3]; + ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3)); + o[i2++] = s0, o[i2++] = s1, o[i2++] = s2, o[i2++] = s3; + } + xk.fill(0); + return _out; + }, + decrypt: (ciphertext, dst) => { + validateBlockDecrypt(ciphertext); + const xk = expandKeyDecLE(key); + const n32 = u32(iv); + const out = getDst(ciphertext.length, dst); + const b = u32(ciphertext); + const o = u32(out); + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + for (let i2 = 0; i2 + 4 <= b.length; ) { + const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3; + s0 = b[i2 + 0], s1 = b[i2 + 1], s2 = b[i2 + 2], s3 = b[i2 + 3]; + const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3); + o[i2++] = o0 ^ ps0, o[i2++] = o1 ^ ps1, o[i2++] = o2 ^ ps2, o[i2++] = o3 ^ ps3; + } + xk.fill(0); + return validatePCKS(out, pcks5); + } + }; + }); + function computeTag(fn, isLE4, key, data, AAD) { + const h = fn.create(key, data.length + (AAD?.length || 0)); + if (AAD) + h.update(AAD); + h.update(data); + const num = new Uint8Array(16); + const view = createView3(num); + if (AAD) + setBigUint643(view, 0, BigInt(AAD.length * 8), isLE4); + setBigUint643(view, 8, BigInt(data.length * 8), isLE4); + h.update(num); + return h.digest(); + } + var gcm = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function gcm2(key, nonce, AAD) { + bytes3(nonce); + if (nonce.length === 0) + throw new Error("aes/gcm: empty nonce"); + const tagLength = 16; + function _computeTag(authKey, tagMask, data) { + const tag = computeTag(ghash, false, authKey, data, AAD); + for (let i2 = 0; i2 < tagMask.length; i2++) + tag[i2] ^= tagMask[i2]; + return tag; + } + function deriveKeys() { + const xk = expandKeyLE(key); + const authKey = EMPTY_BLOCK.slice(); + const counter = EMPTY_BLOCK.slice(); + ctr32(xk, false, counter, counter, authKey); + if (nonce.length === 12) { + counter.set(nonce); + } else { + const nonceLen = EMPTY_BLOCK.slice(); + const view = createView3(nonceLen); + setBigUint643(view, 8, BigInt(nonce.length * 8), false); + ghash.create(authKey).update(nonce).update(nonceLen).digestInto(counter); + } + const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK); + return { xk, authKey, counter, tagMask }; + } + return { + encrypt: (plaintext) => { + bytes3(plaintext); + const { xk, authKey, counter, tagMask } = deriveKeys(); + const out = new Uint8Array(plaintext.length + tagLength); + ctr32(xk, false, counter, plaintext, out); + const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength)); + out.set(tag, plaintext.length); + xk.fill(0); + return out; + }, + decrypt: (ciphertext) => { + bytes3(ciphertext); + if (ciphertext.length < tagLength) + throw new Error(`aes/gcm: ciphertext less than tagLen (${tagLength})`); + const { xk, authKey, counter, tagMask } = deriveKeys(); + const data = ciphertext.subarray(0, -tagLength); + const passedTag = ciphertext.subarray(-tagLength); + const tag = _computeTag(authKey, tagMask, data); + if (!equalBytes2(tag, passedTag)) + throw new Error("aes/gcm: invalid ghash tag"); + const out = ctr32(xk, false, counter, data); + authKey.fill(0); + tagMask.fill(0); + xk.fill(0); + return out; + } + }; + }); + var limit = (name, min, max) => (value) => { + if (!Number.isSafeInteger(value) || min > value || value > max) + throw new Error(`${name}: invalid value=${value}, must be [${min}..${max}]`); + }; + var siv = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function siv2(key, nonce, AAD) { + const tagLength = 16; + const AAD_LIMIT = limit("AAD", 0, 2 ** 36); + const PLAIN_LIMIT = limit("plaintext", 0, 2 ** 36); + const NONCE_LIMIT = limit("nonce", 12, 12); + const CIPHER_LIMIT = limit("ciphertext", 16, 2 ** 36 + 16); + bytes3(nonce); + NONCE_LIMIT(nonce.length); + if (AAD) { + bytes3(AAD); + AAD_LIMIT(AAD.length); + } + function deriveKeys() { + const len = key.length; + if (len !== 16 && len !== 24 && len !== 32) + throw new Error(`key length must be 16, 24 or 32 bytes, got: ${len} bytes`); + const xk = expandKeyLE(key); + const encKey = new Uint8Array(len); + const authKey = new Uint8Array(16); + const n32 = u32(nonce); + let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2]; + let counter = 0; + for (const derivedKey of [authKey, encKey].map(u32)) { + const d32 = u32(derivedKey); + for (let i2 = 0; i2 < d32.length; i2 += 2) { + const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3); + d32[i2 + 0] = o0; + d32[i2 + 1] = o1; + s0 = ++counter; + } + } + xk.fill(0); + return { authKey, encKey: expandKeyLE(encKey) }; + } + function _computeTag(encKey, authKey, data) { + const tag = computeTag(polyval, true, authKey, data, AAD); + for (let i2 = 0; i2 < 12; i2++) + tag[i2] ^= nonce[i2]; + tag[15] &= 127; + const t32 = u32(tag); + let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3]; + ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3)); + t32[0] = s0, t32[1] = s1, t32[2] = s2, t32[3] = s3; + return tag; + } + function processSiv(encKey, tag, input) { + let block = tag.slice(); + block[15] |= 128; + return ctr32(encKey, true, block, input); + } + return { + encrypt: (plaintext) => { + bytes3(plaintext); + PLAIN_LIMIT(plaintext.length); + const { encKey, authKey } = deriveKeys(); + const tag = _computeTag(encKey, authKey, plaintext); + const out = new Uint8Array(plaintext.length + tagLength); + out.set(tag, plaintext.length); + out.set(processSiv(encKey, tag, plaintext)); + encKey.fill(0); + authKey.fill(0); + return out; + }, + decrypt: (ciphertext) => { + bytes3(ciphertext); + CIPHER_LIMIT(ciphertext.length); + const tag = ciphertext.subarray(-tagLength); + const { encKey, authKey } = deriveKeys(); + const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength)); + const expectedTag = _computeTag(encKey, authKey, plaintext); + encKey.fill(0); + authKey.fill(0); + if (!equalBytes2(tag, expectedTag)) + throw new Error("invalid polyval tag"); + return plaintext; + } + }; + }); + + // nip04.ts + function encrypt2(secretKey, pubkey, text) { + const privkey = secretKey instanceof Uint8Array ? bytesToHex2(secretKey) : secretKey; + const key = secp256k1.getSharedSecret(privkey, "02" + pubkey); + const normalizedKey = getNormalizedX(key); + let iv = Uint8Array.from(randomBytes2(16)); + let plaintext = utf8Encoder.encode(text); + let ciphertext = cbc(normalizedKey, iv).encrypt(plaintext); + let ctb64 = base64.encode(new Uint8Array(ciphertext)); + let ivb64 = base64.encode(new Uint8Array(iv.buffer)); + return `${ctb64}?iv=${ivb64}`; + } + function decrypt2(secretKey, pubkey, data) { + const privkey = secretKey instanceof Uint8Array ? bytesToHex2(secretKey) : secretKey; + let [ctb64, ivb64] = data.split("?iv="); + let key = secp256k1.getSharedSecret(privkey, "02" + pubkey); + let normalizedKey = getNormalizedX(key); + let iv = base64.decode(ivb64); + let ciphertext = base64.decode(ctb64); + let plaintext = cbc(normalizedKey, iv).decrypt(ciphertext); + return utf8Decoder.decode(plaintext); + } + function getNormalizedX(key) { + return key.slice(1, 33); + } + + // nip05.ts + var nip05_exports = {}; + __export(nip05_exports, { + NIP05_REGEX: () => NIP05_REGEX, + isNip05: () => isNip05, + isValid: () => isValid, + queryProfile: () => queryProfile, + searchDomain: () => searchDomain, + useFetchImplementation: () => useFetchImplementation + }); + var NIP05_REGEX = /^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/; + var isNip05 = (value) => NIP05_REGEX.test(value || ""); + var _fetch; + try { + _fetch = fetch; + } catch (_) { + null; + } + function useFetchImplementation(fetchImplementation) { + _fetch = fetchImplementation; + } + async function searchDomain(domain, query = "") { + try { + const url = `https://${domain}/.well-known/nostr.json?name=${query}`; + const res = await _fetch(url, { redirect: "manual" }); + if (res.status !== 200) { + throw Error("Wrong response code"); + } + const json = await res.json(); + return json.names; + } catch (_) { + return {}; + } + } + async function queryProfile(fullname) { + const match = fullname.match(NIP05_REGEX); + if (!match) + return null; + const [, name = "_", domain] = match; + try { + const url = `https://${domain}/.well-known/nostr.json?name=${name}`; + const res = await _fetch(url, { redirect: "manual" }); + if (res.status !== 200) { + throw Error("Wrong response code"); + } + const json = await res.json(); + const pubkey = json.names[name]; + return pubkey ? { pubkey, relays: json.relays?.[pubkey] } : null; + } catch (_e) { + return null; + } + } + async function isValid(pubkey, nip05) { + const res = await queryProfile(nip05); + return res ? res.pubkey === pubkey : false; + } + + // nip10.ts + var nip10_exports = {}; + __export(nip10_exports, { + parse: () => parse + }); + function parse(event) { + const result = { + reply: void 0, + root: void 0, + mentions: [], + profiles: [], + quotes: [] + }; + let maybeParent; + let maybeRoot; + for (let i2 = event.tags.length - 1; i2 >= 0; i2--) { + const tag = event.tags[i2]; + if (tag[0] === "e" && tag[1]) { + const [_, eTagEventId, eTagRelayUrl, eTagMarker, eTagAuthor] = tag; + const eventPointer = { + id: eTagEventId, + relays: eTagRelayUrl ? [eTagRelayUrl] : [], + author: eTagAuthor + }; + if (eTagMarker === "root") { + result.root = eventPointer; + continue; + } + if (eTagMarker === "reply") { + result.reply = eventPointer; + continue; + } + if (eTagMarker === "mention") { + result.mentions.push(eventPointer); + continue; + } + if (!maybeParent) { + maybeParent = eventPointer; + } else { + maybeRoot = eventPointer; + } + result.mentions.push(eventPointer); + continue; + } + if (tag[0] === "q" && tag[1]) { + const [_, eTagEventId, eTagRelayUrl] = tag; + result.quotes.push({ + id: eTagEventId, + relays: eTagRelayUrl ? [eTagRelayUrl] : [] + }); + } + if (tag[0] === "p" && tag[1]) { + result.profiles.push({ + pubkey: tag[1], + relays: tag[2] ? [tag[2]] : [] + }); + continue; + } + } + if (!result.root) { + result.root = maybeRoot || maybeParent || result.reply; + } + if (!result.reply) { + result.reply = maybeParent || result.root; + } + ; + [result.reply, result.root].forEach((ref) => { + if (!ref) + return; + let idx = result.mentions.indexOf(ref); + if (idx !== -1) { + result.mentions.splice(idx, 1); + } + if (ref.author) { + let author = result.profiles.find((p) => p.pubkey === ref.author); + if (author && author.relays) { + if (!ref.relays) { + ref.relays = []; + } + author.relays.forEach((url) => { + if (ref.relays?.indexOf(url) === -1) + ref.relays.push(url); + }); + author.relays = ref.relays; + } + } + }); + result.mentions.forEach((ref) => { + if (ref.author) { + let author = result.profiles.find((p) => p.pubkey === ref.author); + if (author && author.relays) { + if (!ref.relays) { + ref.relays = []; + } + author.relays.forEach((url) => { + if (ref.relays.indexOf(url) === -1) + ref.relays.push(url); + }); + author.relays = ref.relays; + } + } + }); + return result; + } + + // nip11.ts + var nip11_exports = {}; + __export(nip11_exports, { + fetchRelayInformation: () => fetchRelayInformation, + useFetchImplementation: () => useFetchImplementation2 + }); + var _fetch2; + try { + _fetch2 = fetch; + } catch { + } + function useFetchImplementation2(fetchImplementation) { + _fetch2 = fetchImplementation; + } + async function fetchRelayInformation(url) { + return await (await fetch(url.replace("ws://", "http://").replace("wss://", "https://"), { + headers: { Accept: "application/nostr+json" } + })).json(); + } + + // nip13.ts + var nip13_exports = {}; + __export(nip13_exports, { + fastEventHash: () => fastEventHash, + getPow: () => getPow, + minePow: () => minePow + }); + function getPow(hex2) { + let count = 0; + for (let i2 = 0; i2 < 64; i2 += 8) { + const nibble = parseInt(hex2.substring(i2, i2 + 8), 16); + if (nibble === 0) { + count += 32; + } else { + count += Math.clz32(nibble); + break; + } + } + return count; + } + function minePow(unsigned, difficulty) { + let count = 0; + const event = unsigned; + const tag = ["nonce", count.toString(), difficulty.toString()]; + event.tags.push(tag); + while (true) { + const now2 = Math.floor(new Date().getTime() / 1e3); + if (now2 !== event.created_at) { + count = 0; + event.created_at = now2; + } + tag[1] = (++count).toString(); + event.id = fastEventHash(event); + if (getPow(event.id) >= difficulty) { + break; + } + } + return event; + } + function fastEventHash(evt) { + return bytesToHex2( + sha2562(utf8Encoder.encode(JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]))) + ); + } + + // nip17.ts + var nip17_exports = {}; + __export(nip17_exports, { + unwrapEvent: () => unwrapEvent2, + unwrapManyEvents: () => unwrapManyEvents2, + wrapEvent: () => wrapEvent2, + wrapManyEvents: () => wrapManyEvents2 + }); + + // nip59.ts + var nip59_exports = {}; + __export(nip59_exports, { + createRumor: () => createRumor, + createSeal: () => createSeal, + createWrap: () => createWrap, + unwrapEvent: () => unwrapEvent, + unwrapManyEvents: () => unwrapManyEvents, + wrapEvent: () => wrapEvent, + wrapManyEvents: () => wrapManyEvents + }); + + // nip44.ts + var nip44_exports = {}; + __export(nip44_exports, { + decrypt: () => decrypt3, + encrypt: () => encrypt3, + getConversationKey: () => getConversationKey, + v2: () => v2 + }); + + // node_modules/@noble/ciphers/esm/_poly1305.js + var u8to16 = (a, i2) => a[i2++] & 255 | (a[i2++] & 255) << 8; + var Poly1305 = class { + constructor(key) { + this.blockLen = 16; + this.outputLen = 16; + this.buffer = new Uint8Array(16); + this.r = new Uint16Array(10); + this.h = new Uint16Array(10); + this.pad = new Uint16Array(8); + this.pos = 0; + this.finished = false; + key = toBytes3(key); + bytes3(key, 32); + const t0 = u8to16(key, 0); + const t1 = u8to16(key, 2); + const t2 = u8to16(key, 4); + const t3 = u8to16(key, 6); + const t4 = u8to16(key, 8); + const t5 = u8to16(key, 10); + const t6 = u8to16(key, 12); + const t7 = u8to16(key, 14); + this.r[0] = t0 & 8191; + this.r[1] = (t0 >>> 13 | t1 << 3) & 8191; + this.r[2] = (t1 >>> 10 | t2 << 6) & 7939; + this.r[3] = (t2 >>> 7 | t3 << 9) & 8191; + this.r[4] = (t3 >>> 4 | t4 << 12) & 255; + this.r[5] = t4 >>> 1 & 8190; + this.r[6] = (t4 >>> 14 | t5 << 2) & 8191; + this.r[7] = (t5 >>> 11 | t6 << 5) & 8065; + this.r[8] = (t6 >>> 8 | t7 << 8) & 8191; + this.r[9] = t7 >>> 5 & 127; + for (let i2 = 0; i2 < 8; i2++) + this.pad[i2] = u8to16(key, 16 + 2 * i2); + } + process(data, offset, isLast = false) { + const hibit = isLast ? 0 : 1 << 11; + const { h, r } = this; + const r0 = r[0]; + const r1 = r[1]; + const r2 = r[2]; + const r3 = r[3]; + const r4 = r[4]; + const r5 = r[5]; + const r6 = r[6]; + const r7 = r[7]; + const r8 = r[8]; + const r9 = r[9]; + const t0 = u8to16(data, offset + 0); + const t1 = u8to16(data, offset + 2); + const t2 = u8to16(data, offset + 4); + const t3 = u8to16(data, offset + 6); + const t4 = u8to16(data, offset + 8); + const t5 = u8to16(data, offset + 10); + const t6 = u8to16(data, offset + 12); + const t7 = u8to16(data, offset + 14); + let h0 = h[0] + (t0 & 8191); + let h1 = h[1] + ((t0 >>> 13 | t1 << 3) & 8191); + let h2 = h[2] + ((t1 >>> 10 | t2 << 6) & 8191); + let h3 = h[3] + ((t2 >>> 7 | t3 << 9) & 8191); + let h4 = h[4] + ((t3 >>> 4 | t4 << 12) & 8191); + let h5 = h[5] + (t4 >>> 1 & 8191); + let h6 = h[6] + ((t4 >>> 14 | t5 << 2) & 8191); + let h7 = h[7] + ((t5 >>> 11 | t6 << 5) & 8191); + let h8 = h[8] + ((t6 >>> 8 | t7 << 8) & 8191); + let h9 = h[9] + (t7 >>> 5 | hibit); + let c = 0; + let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6); + c = d0 >>> 13; + d0 &= 8191; + d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1); + c += d0 >>> 13; + d0 &= 8191; + let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7); + c = d1 >>> 13; + d1 &= 8191; + d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2); + c += d1 >>> 13; + d1 &= 8191; + let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8); + c = d2 >>> 13; + d2 &= 8191; + d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3); + c += d2 >>> 13; + d2 &= 8191; + let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9); + c = d3 >>> 13; + d3 &= 8191; + d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4); + c += d3 >>> 13; + d3 &= 8191; + let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0; + c = d4 >>> 13; + d4 &= 8191; + d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5); + c += d4 >>> 13; + d4 &= 8191; + let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1; + c = d5 >>> 13; + d5 &= 8191; + d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6); + c += d5 >>> 13; + d5 &= 8191; + let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2; + c = d6 >>> 13; + d6 &= 8191; + d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7); + c += d6 >>> 13; + d6 &= 8191; + let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3; + c = d7 >>> 13; + d7 &= 8191; + d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8); + c += d7 >>> 13; + d7 &= 8191; + let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4; + c = d8 >>> 13; + d8 &= 8191; + d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9); + c += d8 >>> 13; + d8 &= 8191; + let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5; + c = d9 >>> 13; + d9 &= 8191; + d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0; + c += d9 >>> 13; + d9 &= 8191; + c = (c << 2) + c | 0; + c = c + d0 | 0; + d0 = c & 8191; + c = c >>> 13; + d1 += c; + h[0] = d0; + h[1] = d1; + h[2] = d2; + h[3] = d3; + h[4] = d4; + h[5] = d5; + h[6] = d6; + h[7] = d7; + h[8] = d8; + h[9] = d9; + } + finalize() { + const { h, pad: pad2 } = this; + const g = new Uint16Array(10); + let c = h[1] >>> 13; + h[1] &= 8191; + for (let i2 = 2; i2 < 10; i2++) { + h[i2] += c; + c = h[i2] >>> 13; + h[i2] &= 8191; + } + h[0] += c * 5; + c = h[0] >>> 13; + h[0] &= 8191; + h[1] += c; + c = h[1] >>> 13; + h[1] &= 8191; + h[2] += c; + g[0] = h[0] + 5; + c = g[0] >>> 13; + g[0] &= 8191; + for (let i2 = 1; i2 < 10; i2++) { + g[i2] = h[i2] + c; + c = g[i2] >>> 13; + g[i2] &= 8191; + } + g[9] -= 1 << 13; + let mask = (c ^ 1) - 1; + for (let i2 = 0; i2 < 10; i2++) + g[i2] &= mask; + mask = ~mask; + for (let i2 = 0; i2 < 10; i2++) + h[i2] = h[i2] & mask | g[i2]; + h[0] = (h[0] | h[1] << 13) & 65535; + h[1] = (h[1] >>> 3 | h[2] << 10) & 65535; + h[2] = (h[2] >>> 6 | h[3] << 7) & 65535; + h[3] = (h[3] >>> 9 | h[4] << 4) & 65535; + h[4] = (h[4] >>> 12 | h[5] << 1 | h[6] << 14) & 65535; + h[5] = (h[6] >>> 2 | h[7] << 11) & 65535; + h[6] = (h[7] >>> 5 | h[8] << 8) & 65535; + h[7] = (h[8] >>> 8 | h[9] << 5) & 65535; + let f = h[0] + pad2[0]; + h[0] = f & 65535; + for (let i2 = 1; i2 < 8; i2++) { + f = (h[i2] + pad2[i2] | 0) + (f >>> 16) | 0; + h[i2] = f & 65535; + } + } + update(data) { + exists3(this); + const { buffer, blockLen } = this; + data = toBytes3(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + for (; blockLen <= len - pos; pos += blockLen) + this.process(data, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(buffer, 0, false); + this.pos = 0; + } + } + return this; + } + destroy() { + this.h.fill(0); + this.r.fill(0); + this.buffer.fill(0); + this.pad.fill(0); + } + digestInto(out) { + exists3(this); + output3(out, this); + this.finished = true; + const { buffer, h } = this; + let { pos } = this; + if (pos) { + buffer[pos++] = 1; + for (; pos < 16; pos++) + buffer[pos] = 0; + this.process(buffer, 0, true); + } + this.finalize(); + let opos = 0; + for (let i2 = 0; i2 < 8; i2++) { + out[opos++] = h[i2] >>> 0; + out[opos++] = h[i2] >>> 8; + } + return out; + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + }; + function wrapConstructorWithKey2(hashCons) { + const hashC = (msg, key) => hashCons(key).update(toBytes3(msg)).digest(); + const tmp = hashCons(new Uint8Array(32)); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (key) => hashCons(key); + return hashC; + } + var poly1305 = wrapConstructorWithKey2((key) => new Poly1305(key)); + + // node_modules/@noble/ciphers/esm/_arx.js + var sigma16 = utf8ToBytes4("expand 16-byte k"); + var sigma32 = utf8ToBytes4("expand 32-byte k"); + var sigma16_32 = u32(sigma16); + var sigma32_32 = u32(sigma32); + function rotl(a, b) { + return a << b | a >>> 32 - b; + } + function isAligned32(b) { + return b.byteOffset % 4 === 0; + } + var BLOCK_LEN = 64; + var BLOCK_LEN32 = 16; + var MAX_COUNTER = 2 ** 32 - 1; + var U32_EMPTY = new Uint32Array(); + function runCipher(core, sigma, key, nonce, data, output4, counter, rounds) { + const len = data.length; + const block = new Uint8Array(BLOCK_LEN); + const b32 = u32(block); + const isAligned = isAligned32(data) && isAligned32(output4); + const d32 = isAligned ? u32(data) : U32_EMPTY; + const o32 = isAligned ? u32(output4) : U32_EMPTY; + for (let pos = 0; pos < len; counter++) { + core(sigma, key, nonce, b32, counter, rounds); + if (counter >= MAX_COUNTER) + throw new Error("arx: counter overflow"); + const take = Math.min(BLOCK_LEN, len - pos); + if (isAligned && take === BLOCK_LEN) { + const pos32 = pos / 4; + if (pos % 4 !== 0) + throw new Error("arx: invalid block position"); + for (let j = 0, posj; j < BLOCK_LEN32; j++) { + posj = pos32 + j; + o32[posj] = d32[posj] ^ b32[j]; + } + pos += BLOCK_LEN; + continue; + } + for (let j = 0, posj; j < take; j++) { + posj = pos + j; + output4[posj] = data[posj] ^ block[j]; + } + pos += take; + } + } + function createCipher(core, opts) { + const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts); + if (typeof core !== "function") + throw new Error("core must be a function"); + number3(counterLength); + number3(rounds); + bool2(counterRight); + bool2(allowShortKeys); + return (key, nonce, data, output4, counter = 0) => { + bytes3(key); + bytes3(nonce); + bytes3(data); + const len = data.length; + if (!output4) + output4 = new Uint8Array(len); + bytes3(output4); + number3(counter); + if (counter < 0 || counter >= MAX_COUNTER) + throw new Error("arx: counter overflow"); + if (output4.length < len) + throw new Error(`arx: output (${output4.length}) is shorter than data (${len})`); + const toClean = []; + let l = key.length, k, sigma; + if (l === 32) { + k = key.slice(); + toClean.push(k); + sigma = sigma32_32; + } else if (l === 16 && allowShortKeys) { + k = new Uint8Array(32); + k.set(key); + k.set(key, 16); + sigma = sigma16_32; + toClean.push(k); + } else { + throw new Error(`arx: invalid 32-byte key, got length=${l}`); + } + if (!isAligned32(nonce)) { + nonce = nonce.slice(); + toClean.push(nonce); + } + const k32 = u32(k); + if (extendNonceFn) { + if (nonce.length !== 24) + throw new Error(`arx: extended nonce must be 24 bytes`); + extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32); + nonce = nonce.subarray(16); + } + const nonceNcLen = 16 - counterLength; + if (nonceNcLen !== nonce.length) + throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`); + if (nonceNcLen !== 12) { + const nc = new Uint8Array(12); + nc.set(nonce, counterRight ? 0 : 12 - nonce.length); + nonce = nc; + toClean.push(nonce); + } + const n32 = u32(nonce); + runCipher(core, sigma, k32, n32, data, output4, counter, rounds); + while (toClean.length > 0) + toClean.pop().fill(0); + return output4; + }; + } + + // node_modules/@noble/ciphers/esm/chacha.js + function chachaCore(s, k, n, out, cnt, rounds = 20) { + let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; + for (let r = 0; r < rounds; r += 2) { + x00 = x00 + x04 | 0; + x12 = rotl(x12 ^ x00, 16); + x08 = x08 + x12 | 0; + x04 = rotl(x04 ^ x08, 12); + x00 = x00 + x04 | 0; + x12 = rotl(x12 ^ x00, 8); + x08 = x08 + x12 | 0; + x04 = rotl(x04 ^ x08, 7); + x01 = x01 + x05 | 0; + x13 = rotl(x13 ^ x01, 16); + x09 = x09 + x13 | 0; + x05 = rotl(x05 ^ x09, 12); + x01 = x01 + x05 | 0; + x13 = rotl(x13 ^ x01, 8); + x09 = x09 + x13 | 0; + x05 = rotl(x05 ^ x09, 7); + x02 = x02 + x06 | 0; + x14 = rotl(x14 ^ x02, 16); + x10 = x10 + x14 | 0; + x06 = rotl(x06 ^ x10, 12); + x02 = x02 + x06 | 0; + x14 = rotl(x14 ^ x02, 8); + x10 = x10 + x14 | 0; + x06 = rotl(x06 ^ x10, 7); + x03 = x03 + x07 | 0; + x15 = rotl(x15 ^ x03, 16); + x11 = x11 + x15 | 0; + x07 = rotl(x07 ^ x11, 12); + x03 = x03 + x07 | 0; + x15 = rotl(x15 ^ x03, 8); + x11 = x11 + x15 | 0; + x07 = rotl(x07 ^ x11, 7); + x00 = x00 + x05 | 0; + x15 = rotl(x15 ^ x00, 16); + x10 = x10 + x15 | 0; + x05 = rotl(x05 ^ x10, 12); + x00 = x00 + x05 | 0; + x15 = rotl(x15 ^ x00, 8); + x10 = x10 + x15 | 0; + x05 = rotl(x05 ^ x10, 7); + x01 = x01 + x06 | 0; + x12 = rotl(x12 ^ x01, 16); + x11 = x11 + x12 | 0; + x06 = rotl(x06 ^ x11, 12); + x01 = x01 + x06 | 0; + x12 = rotl(x12 ^ x01, 8); + x11 = x11 + x12 | 0; + x06 = rotl(x06 ^ x11, 7); + x02 = x02 + x07 | 0; + x13 = rotl(x13 ^ x02, 16); + x08 = x08 + x13 | 0; + x07 = rotl(x07 ^ x08, 12); + x02 = x02 + x07 | 0; + x13 = rotl(x13 ^ x02, 8); + x08 = x08 + x13 | 0; + x07 = rotl(x07 ^ x08, 7); + x03 = x03 + x04 | 0; + x14 = rotl(x14 ^ x03, 16); + x09 = x09 + x14 | 0; + x04 = rotl(x04 ^ x09, 12); + x03 = x03 + x04 | 0; + x14 = rotl(x14 ^ x03, 8); + x09 = x09 + x14 | 0; + x04 = rotl(x04 ^ x09, 7); + } + let oi = 0; + out[oi++] = y00 + x00 | 0; + out[oi++] = y01 + x01 | 0; + out[oi++] = y02 + x02 | 0; + out[oi++] = y03 + x03 | 0; + out[oi++] = y04 + x04 | 0; + out[oi++] = y05 + x05 | 0; + out[oi++] = y06 + x06 | 0; + out[oi++] = y07 + x07 | 0; + out[oi++] = y08 + x08 | 0; + out[oi++] = y09 + x09 | 0; + out[oi++] = y10 + x10 | 0; + out[oi++] = y11 + x11 | 0; + out[oi++] = y12 + x12 | 0; + out[oi++] = y13 + x13 | 0; + out[oi++] = y14 + x14 | 0; + out[oi++] = y15 + x15 | 0; + } + function hchacha(s, k, i2, o32) { + let x00 = s[0], x01 = s[1], x02 = s[2], x03 = s[3], x04 = k[0], x05 = k[1], x06 = k[2], x07 = k[3], x08 = k[4], x09 = k[5], x10 = k[6], x11 = k[7], x12 = i2[0], x13 = i2[1], x14 = i2[2], x15 = i2[3]; + for (let r = 0; r < 20; r += 2) { + x00 = x00 + x04 | 0; + x12 = rotl(x12 ^ x00, 16); + x08 = x08 + x12 | 0; + x04 = rotl(x04 ^ x08, 12); + x00 = x00 + x04 | 0; + x12 = rotl(x12 ^ x00, 8); + x08 = x08 + x12 | 0; + x04 = rotl(x04 ^ x08, 7); + x01 = x01 + x05 | 0; + x13 = rotl(x13 ^ x01, 16); + x09 = x09 + x13 | 0; + x05 = rotl(x05 ^ x09, 12); + x01 = x01 + x05 | 0; + x13 = rotl(x13 ^ x01, 8); + x09 = x09 + x13 | 0; + x05 = rotl(x05 ^ x09, 7); + x02 = x02 + x06 | 0; + x14 = rotl(x14 ^ x02, 16); + x10 = x10 + x14 | 0; + x06 = rotl(x06 ^ x10, 12); + x02 = x02 + x06 | 0; + x14 = rotl(x14 ^ x02, 8); + x10 = x10 + x14 | 0; + x06 = rotl(x06 ^ x10, 7); + x03 = x03 + x07 | 0; + x15 = rotl(x15 ^ x03, 16); + x11 = x11 + x15 | 0; + x07 = rotl(x07 ^ x11, 12); + x03 = x03 + x07 | 0; + x15 = rotl(x15 ^ x03, 8); + x11 = x11 + x15 | 0; + x07 = rotl(x07 ^ x11, 7); + x00 = x00 + x05 | 0; + x15 = rotl(x15 ^ x00, 16); + x10 = x10 + x15 | 0; + x05 = rotl(x05 ^ x10, 12); + x00 = x00 + x05 | 0; + x15 = rotl(x15 ^ x00, 8); + x10 = x10 + x15 | 0; + x05 = rotl(x05 ^ x10, 7); + x01 = x01 + x06 | 0; + x12 = rotl(x12 ^ x01, 16); + x11 = x11 + x12 | 0; + x06 = rotl(x06 ^ x11, 12); + x01 = x01 + x06 | 0; + x12 = rotl(x12 ^ x01, 8); + x11 = x11 + x12 | 0; + x06 = rotl(x06 ^ x11, 7); + x02 = x02 + x07 | 0; + x13 = rotl(x13 ^ x02, 16); + x08 = x08 + x13 | 0; + x07 = rotl(x07 ^ x08, 12); + x02 = x02 + x07 | 0; + x13 = rotl(x13 ^ x02, 8); + x08 = x08 + x13 | 0; + x07 = rotl(x07 ^ x08, 7); + x03 = x03 + x04 | 0; + x14 = rotl(x14 ^ x03, 16); + x09 = x09 + x14 | 0; + x04 = rotl(x04 ^ x09, 12); + x03 = x03 + x04 | 0; + x14 = rotl(x14 ^ x03, 8); + x09 = x09 + x14 | 0; + x04 = rotl(x04 ^ x09, 7); + } + let oi = 0; + o32[oi++] = x00; + o32[oi++] = x01; + o32[oi++] = x02; + o32[oi++] = x03; + o32[oi++] = x12; + o32[oi++] = x13; + o32[oi++] = x14; + o32[oi++] = x15; + } + var chacha20 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 4, + allowShortKeys: false + }); + var xchacha20 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 8, + extendNonceFn: hchacha, + allowShortKeys: false + }); + var ZEROS162 = /* @__PURE__ */ new Uint8Array(16); + var updatePadded = (h, msg) => { + h.update(msg); + const left = msg.length % 16; + if (left) + h.update(ZEROS162.subarray(left)); + }; + var ZEROS322 = /* @__PURE__ */ new Uint8Array(32); + function computeTag2(fn, key, nonce, data, AAD) { + const authKey = fn(key, nonce, ZEROS322); + const h = poly1305.create(authKey); + if (AAD) + updatePadded(h, AAD); + updatePadded(h, data); + const num = new Uint8Array(16); + const view = createView3(num); + setBigUint643(view, 0, BigInt(AAD ? AAD.length : 0), true); + setBigUint643(view, 8, BigInt(data.length), true); + h.update(num); + const res = h.digest(); + authKey.fill(0); + return res; + } + var _poly1305_aead = (xorStream) => (key, nonce, AAD) => { + const tagLength = 16; + bytes3(key, 32); + bytes3(nonce); + return { + encrypt: (plaintext, output4) => { + const plength = plaintext.length; + const clength = plength + tagLength; + if (output4) { + bytes3(output4, clength); + } else { + output4 = new Uint8Array(clength); + } + xorStream(key, nonce, plaintext, output4, 1); + const tag = computeTag2(xorStream, key, nonce, output4.subarray(0, -tagLength), AAD); + output4.set(tag, plength); + return output4; + }, + decrypt: (ciphertext, output4) => { + const clength = ciphertext.length; + const plength = clength - tagLength; + if (clength < tagLength) + throw new Error(`encrypted data must be at least ${tagLength} bytes`); + if (output4) { + bytes3(output4, plength); + } else { + output4 = new Uint8Array(plength); + } + const data = ciphertext.subarray(0, -tagLength); + const passedTag = ciphertext.subarray(-tagLength); + const tag = computeTag2(xorStream, key, nonce, data, AAD); + if (!equalBytes2(passedTag, tag)) + throw new Error("invalid tag"); + xorStream(key, nonce, data, output4, 1); + return output4; + } + }; + }; + var chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16 }, _poly1305_aead(chacha20)); + var xchacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, _poly1305_aead(xchacha20)); + + // node_modules/@noble/hashes/esm/hmac.js + var HMAC2 = class extends Hash2 { + constructor(hash3, _key) { + super(); + this.finished = false; + this.destroyed = false; + assert_default.hash(hash3); + const key = toBytes2(_key); + this.iHash = hash3.create(); + if (typeof this.iHash.update !== "function") + throw new Error("Expected instance of class which extends utils.Hash"); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad2 = new Uint8Array(blockLen); + pad2.set(key.length > blockLen ? hash3.create().update(key).digest() : key); + for (let i2 = 0; i2 < pad2.length; i2++) + pad2[i2] ^= 54; + this.iHash.update(pad2); + this.oHash = hash3.create(); + for (let i2 = 0; i2 < pad2.length; i2++) + pad2[i2] ^= 54 ^ 92; + this.oHash.update(pad2); + pad2.fill(0); + } + update(buf) { + assert_default.exists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + assert_default.exists(this); + assert_default.bytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } + }; + var hmac2 = (hash3, key, message) => new HMAC2(hash3, key).update(message).digest(); + hmac2.create = (hash3, key) => new HMAC2(hash3, key); + + // node_modules/@noble/hashes/esm/hkdf.js + function extract(hash3, ikm, salt) { + assert_default.hash(hash3); + if (salt === void 0) + salt = new Uint8Array(hash3.outputLen); + return hmac2(hash3, toBytes2(salt), toBytes2(ikm)); + } + var HKDF_COUNTER = new Uint8Array([0]); + var EMPTY_BUFFER = new Uint8Array(); + function expand(hash3, prk, info, length = 32) { + assert_default.hash(hash3); + assert_default.number(length); + if (length > 255 * hash3.outputLen) + throw new Error("Length should be <= 255*HashLen"); + const blocks = Math.ceil(length / hash3.outputLen); + if (info === void 0) + info = EMPTY_BUFFER; + const okm = new Uint8Array(blocks * hash3.outputLen); + const HMAC3 = hmac2.create(hash3, prk); + const HMACTmp = HMAC3._cloneInto(); + const T = new Uint8Array(HMAC3.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T).update(info).update(HKDF_COUNTER).digestInto(T); + okm.set(T, hash3.outputLen * counter); + HMAC3._cloneInto(HMACTmp); + } + HMAC3.destroy(); + HMACTmp.destroy(); + T.fill(0); + HKDF_COUNTER.fill(0); + return okm.slice(0, length); + } + + // nip44.ts + var minPlaintextSize = 1; + var maxPlaintextSize = 65535; + function getConversationKey(privkeyA, pubkeyB) { + const sharedX = secp256k1.getSharedSecret(privkeyA, "02" + pubkeyB).subarray(1, 33); + return extract(sha2562, sharedX, "nip44-v2"); + } + function getMessageKeys(conversationKey, nonce) { + const keys = expand(sha2562, conversationKey, nonce, 76); + return { + chacha_key: keys.subarray(0, 32), + chacha_nonce: keys.subarray(32, 44), + hmac_key: keys.subarray(44, 76) + }; + } + function calcPaddedLen(len) { + if (!Number.isSafeInteger(len) || len < 1) + throw new Error("expected positive integer"); + if (len <= 32) + return 32; + const nextPower = 1 << Math.floor(Math.log2(len - 1)) + 1; + const chunk = nextPower <= 256 ? 32 : nextPower / 8; + return chunk * (Math.floor((len - 1) / chunk) + 1); + } + function writeU16BE(num) { + if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize) + throw new Error("invalid plaintext size: must be between 1 and 65535 bytes"); + const arr = new Uint8Array(2); + new DataView(arr.buffer).setUint16(0, num, false); + return arr; + } + function pad(plaintext) { + const unpadded = utf8Encoder.encode(plaintext); + const unpaddedLen = unpadded.length; + const prefix = writeU16BE(unpaddedLen); + const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen); + return concatBytes3(prefix, unpadded, suffix); + } + function unpad(padded) { + const unpaddedLen = new DataView(padded.buffer).getUint16(0); + const unpadded = padded.subarray(2, 2 + unpaddedLen); + if (unpaddedLen < minPlaintextSize || unpaddedLen > maxPlaintextSize || unpadded.length !== unpaddedLen || padded.length !== 2 + calcPaddedLen(unpaddedLen)) + throw new Error("invalid padding"); + return utf8Decoder.decode(unpadded); + } + function hmacAad(key, message, aad) { + if (aad.length !== 32) + throw new Error("AAD associated data must be 32 bytes"); + const combined = concatBytes3(aad, message); + return hmac2(sha2562, key, combined); + } + function decodePayload(payload) { + if (typeof payload !== "string") + throw new Error("payload must be a valid string"); + const plen = payload.length; + if (plen < 132 || plen > 87472) + throw new Error("invalid payload length: " + plen); + if (payload[0] === "#") + throw new Error("unknown encryption version"); + let data; + try { + data = base64.decode(payload); + } catch (error) { + throw new Error("invalid base64: " + error.message); + } + const dlen = data.length; + if (dlen < 99 || dlen > 65603) + throw new Error("invalid data length: " + dlen); + const vers = data[0]; + if (vers !== 2) + throw new Error("unknown encryption version " + vers); + return { + nonce: data.subarray(1, 33), + ciphertext: data.subarray(33, -32), + mac: data.subarray(-32) + }; + } + function encrypt3(plaintext, conversationKey, nonce = randomBytes2(32)) { + const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); + const padded = pad(plaintext); + const ciphertext = chacha20(chacha_key, chacha_nonce, padded); + const mac = hmacAad(hmac_key, ciphertext, nonce); + return base64.encode(concatBytes3(new Uint8Array([2]), nonce, ciphertext, mac)); + } + function decrypt3(payload, conversationKey) { + const { nonce, ciphertext, mac } = decodePayload(payload); + const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); + const calculatedMac = hmacAad(hmac_key, ciphertext, nonce); + if (!equalBytes2(calculatedMac, mac)) + throw new Error("invalid MAC"); + const padded = chacha20(chacha_key, chacha_nonce, ciphertext); + return unpad(padded); + } + var v2 = { + utils: { + getConversationKey, + calcPaddedLen + }, + encrypt: encrypt3, + decrypt: decrypt3 + }; + + // nip59.ts + var TWO_DAYS = 2 * 24 * 60 * 60; + var now = () => Math.round(Date.now() / 1e3); + var randomNow = () => Math.round(now() - Math.random() * TWO_DAYS); + var nip44ConversationKey = (privateKey, publicKey) => getConversationKey(privateKey, publicKey); + var nip44Encrypt = (data, privateKey, publicKey) => encrypt3(JSON.stringify(data), nip44ConversationKey(privateKey, publicKey)); + var nip44Decrypt = (data, privateKey) => JSON.parse(decrypt3(data.content, nip44ConversationKey(privateKey, data.pubkey))); + function createRumor(event, privateKey) { + const rumor = { + created_at: now(), + content: "", + tags: [], + ...event, + pubkey: getPublicKey(privateKey) + }; + rumor.id = getEventHash(rumor); + return rumor; + } + function createSeal(rumor, privateKey, recipientPublicKey) { + return finalizeEvent( + { + kind: Seal, + content: nip44Encrypt(rumor, privateKey, recipientPublicKey), + created_at: randomNow(), + tags: [] + }, + privateKey + ); + } + function createWrap(seal, recipientPublicKey) { + const randomKey = generateSecretKey(); + return finalizeEvent( + { + kind: GiftWrap, + content: nip44Encrypt(seal, randomKey, recipientPublicKey), + created_at: randomNow(), + tags: [["p", recipientPublicKey]] + }, + randomKey + ); + } + function wrapEvent(event, senderPrivateKey, recipientPublicKey) { + const rumor = createRumor(event, senderPrivateKey); + const seal = createSeal(rumor, senderPrivateKey, recipientPublicKey); + return createWrap(seal, recipientPublicKey); + } + function wrapManyEvents(event, senderPrivateKey, recipientsPublicKeys) { + if (!recipientsPublicKeys || recipientsPublicKeys.length === 0) { + throw new Error("At least one recipient is required."); + } + const senderPublicKey = getPublicKey(senderPrivateKey); + const wrappeds = [wrapEvent(event, senderPrivateKey, senderPublicKey)]; + recipientsPublicKeys.forEach((recipientPublicKey) => { + wrappeds.push(wrapEvent(event, senderPrivateKey, recipientPublicKey)); + }); + return wrappeds; + } + function unwrapEvent(wrap, recipientPrivateKey) { + const unwrappedSeal = nip44Decrypt(wrap, recipientPrivateKey); + return nip44Decrypt(unwrappedSeal, recipientPrivateKey); + } + function unwrapManyEvents(wrappedEvents, recipientPrivateKey) { + let unwrappedEvents = []; + wrappedEvents.forEach((e) => { + unwrappedEvents.push(unwrapEvent(e, recipientPrivateKey)); + }); + unwrappedEvents.sort((a, b) => a.created_at - b.created_at); + return unwrappedEvents; + } + + // nip17.ts + function createEvent(recipients, message, conversationTitle, replyTo) { + const baseEvent = { + created_at: Math.ceil(Date.now() / 1e3), + kind: PrivateDirectMessage, + tags: [], + content: message + }; + const recipientsArray = Array.isArray(recipients) ? recipients : [recipients]; + recipientsArray.forEach(({ publicKey, relayUrl }) => { + baseEvent.tags.push(relayUrl ? ["p", publicKey, relayUrl] : ["p", publicKey]); + }); + if (replyTo) { + baseEvent.tags.push(["e", replyTo.eventId, replyTo.relayUrl || "", "reply"]); + } + if (conversationTitle) { + baseEvent.tags.push(["subject", conversationTitle]); + } + return baseEvent; + } + function wrapEvent2(senderPrivateKey, recipient, message, conversationTitle, replyTo) { + const event = createEvent(recipient, message, conversationTitle, replyTo); + return wrapEvent(event, senderPrivateKey, recipient.publicKey); + } + function wrapManyEvents2(senderPrivateKey, recipients, message, conversationTitle, replyTo) { + if (!recipients || recipients.length === 0) { + throw new Error("At least one recipient is required."); + } + const senderPublicKey = getPublicKey(senderPrivateKey); + return [{ publicKey: senderPublicKey }, ...recipients].map( + (recipient) => wrapEvent2(senderPrivateKey, recipient, message, conversationTitle, replyTo) + ); + } + var unwrapEvent2 = unwrapEvent; + var unwrapManyEvents2 = unwrapManyEvents; + + // nip18.ts + var nip18_exports = {}; + __export(nip18_exports, { + finishRepostEvent: () => finishRepostEvent, + getRepostedEvent: () => getRepostedEvent, + getRepostedEventPointer: () => getRepostedEventPointer + }); + function finishRepostEvent(t, reposted, relayUrl, privateKey) { + let kind; + const tags = [...t.tags ?? [], ["e", reposted.id, relayUrl], ["p", reposted.pubkey]]; + if (reposted.kind === ShortTextNote) { + kind = Repost; + } else { + kind = GenericRepost; + tags.push(["k", String(reposted.kind)]); + } + return finalizeEvent( + { + kind, + tags, + content: t.content === "" || reposted.tags?.find((tag) => tag[0] === "-") ? "" : JSON.stringify(reposted), + created_at: t.created_at + }, + privateKey + ); + } + function getRepostedEventPointer(event) { + if (![Repost, GenericRepost].includes(event.kind)) { + return void 0; + } + let lastETag; + let lastPTag; + for (let i2 = event.tags.length - 1; i2 >= 0 && (lastETag === void 0 || lastPTag === void 0); i2--) { + const tag = event.tags[i2]; + if (tag.length >= 2) { + if (tag[0] === "e" && lastETag === void 0) { + lastETag = tag; + } else if (tag[0] === "p" && lastPTag === void 0) { + lastPTag = tag; + } + } + } + if (lastETag === void 0) { + return void 0; + } + return { + id: lastETag[1], + relays: [lastETag[2], lastPTag?.[2]].filter((x) => typeof x === "string"), + author: lastPTag?.[1] + }; + } + function getRepostedEvent(event, { skipVerification } = {}) { + const pointer = getRepostedEventPointer(event); + if (pointer === void 0 || event.content === "") { + return void 0; + } + let repostedEvent; + try { + repostedEvent = JSON.parse(event.content); + } catch (error) { + return void 0; + } + if (repostedEvent.id !== pointer.id) { + return void 0; + } + if (!skipVerification && !verifyEvent(repostedEvent)) { + return void 0; + } + return repostedEvent; + } + + // nip21.ts + var nip21_exports = {}; + __export(nip21_exports, { + NOSTR_URI_REGEX: () => NOSTR_URI_REGEX, + parse: () => parse2, + test: () => test + }); + var NOSTR_URI_REGEX = new RegExp(`nostr:(${BECH32_REGEX.source})`); + function test(value) { + return typeof value === "string" && new RegExp(`^${NOSTR_URI_REGEX.source}$`).test(value); + } + function parse2(uri) { + const match = uri.match(new RegExp(`^${NOSTR_URI_REGEX.source}$`)); + if (!match) + throw new Error(`Invalid Nostr URI: ${uri}`); + return { + uri: match[0], + value: match[1], + decoded: decode(match[1]) + }; + } + + // nip25.ts + var nip25_exports = {}; + __export(nip25_exports, { + finishReactionEvent: () => finishReactionEvent, + getReactedEventPointer: () => getReactedEventPointer + }); + function finishReactionEvent(t, reacted, privateKey) { + const inheritedTags = reacted.tags.filter((tag) => tag.length >= 2 && (tag[0] === "e" || tag[0] === "p")); + return finalizeEvent( + { + ...t, + kind: Reaction, + tags: [...t.tags ?? [], ...inheritedTags, ["e", reacted.id], ["p", reacted.pubkey]], + content: t.content ?? "+" + }, + privateKey + ); + } + function getReactedEventPointer(event) { + if (event.kind !== Reaction) { + return void 0; + } + let lastETag; + let lastPTag; + for (let i2 = event.tags.length - 1; i2 >= 0 && (lastETag === void 0 || lastPTag === void 0); i2--) { + const tag = event.tags[i2]; + if (tag.length >= 2) { + if (tag[0] === "e" && lastETag === void 0) { + lastETag = tag; + } else if (tag[0] === "p" && lastPTag === void 0) { + lastPTag = tag; + } + } + } + if (lastETag === void 0 || lastPTag === void 0) { + return void 0; + } + return { + id: lastETag[1], + relays: [lastETag[2], lastPTag[2]].filter((x) => x !== void 0), + author: lastPTag[1] + }; + } + + // nip27.ts + var nip27_exports = {}; + __export(nip27_exports, { + parse: () => parse3 + }); + var noCharacter = /\W/m; + var noURLCharacter = /\W |\W$|$|,| /m; + function* parse3(content) { + const max = content.length; + let prevIndex = 0; + let index = 0; + while (index < max) { + let u = content.indexOf(":", index); + if (u === -1) { + break; + } + if (content.substring(u - 5, u) === "nostr") { + const m = content.substring(u + 60).match(noCharacter); + const end = m ? u + 60 + m.index : max; + try { + let pointer; + let { data, type } = decode(content.substring(u + 1, end)); + switch (type) { + case "npub": + pointer = { pubkey: data }; + break; + case "nsec": + case "note": + index = end + 1; + continue; + default: + pointer = data; + } + if (prevIndex !== u - 5) { + yield { type: "text", text: content.substring(prevIndex, u - 5) }; + } + yield { type: "reference", pointer }; + index = end; + prevIndex = index; + continue; + } catch (_err) { + index = u + 1; + continue; + } + } else if (content.substring(u - 5, u) === "https" || content.substring(u - 4, u) === "http") { + const m = content.substring(u + 4).match(noURLCharacter); + const end = m ? u + 4 + m.index : max; + const prefixLen = content[u - 1] === "s" ? 5 : 4; + try { + let url = new URL(content.substring(u - prefixLen, end)); + if (url.hostname.indexOf(".") === -1) { + throw new Error("invalid url"); + } + if (prevIndex !== u - prefixLen) { + yield { type: "text", text: content.substring(prevIndex, u - prefixLen) }; + } + if (url.pathname.endsWith(".png") || url.pathname.endsWith(".jpg") || url.pathname.endsWith(".jpeg") || url.pathname.endsWith(".gif") || url.pathname.endsWith(".webp")) { + yield { type: "image", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } + if (url.pathname.endsWith(".mp4") || url.pathname.endsWith(".avi") || url.pathname.endsWith(".webm") || url.pathname.endsWith(".mkv")) { + yield { type: "video", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } + if (url.pathname.endsWith(".mp3") || url.pathname.endsWith(".aac") || url.pathname.endsWith(".ogg") || url.pathname.endsWith(".opus")) { + yield { type: "audio", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } + yield { type: "url", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } catch (_err) { + index = end + 1; + continue; + } + } else if (content.substring(u - 3, u) === "wss" || content.substring(u - 2, u) === "ws") { + const m = content.substring(u + 4).match(noURLCharacter); + const end = m ? u + 4 + m.index : max; + const prefixLen = content[u - 1] === "s" ? 3 : 2; + try { + let url = new URL(content.substring(u - prefixLen, end)); + if (url.hostname.indexOf(".") === -1) { + throw new Error("invalid ws url"); + } + if (prevIndex !== u - prefixLen) { + yield { type: "text", text: content.substring(prevIndex, u - prefixLen) }; + } + yield { type: "relay", url: url.toString() }; + index = end; + prevIndex = index; + continue; + } catch (_err) { + index = end + 1; + continue; + } + } else { + index = u + 1; + continue; + } + } + if (prevIndex !== max) { + yield { type: "text", text: content.substring(prevIndex) }; + } + } + + // nip28.ts + var nip28_exports = {}; + __export(nip28_exports, { + channelCreateEvent: () => channelCreateEvent, + channelHideMessageEvent: () => channelHideMessageEvent, + channelMessageEvent: () => channelMessageEvent, + channelMetadataEvent: () => channelMetadataEvent, + channelMuteUserEvent: () => channelMuteUserEvent + }); + var channelCreateEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finalizeEvent( + { + kind: ChannelCreation, + tags: [...t.tags ?? []], + content, + created_at: t.created_at + }, + privateKey + ); + }; + var channelMetadataEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finalizeEvent( + { + kind: ChannelMetadata, + tags: [["e", t.channel_create_event_id], ...t.tags ?? []], + content, + created_at: t.created_at + }, + privateKey + ); + }; + var channelMessageEvent = (t, privateKey) => { + const tags = [["e", t.channel_create_event_id, t.relay_url, "root"]]; + if (t.reply_to_channel_message_event_id) { + tags.push(["e", t.reply_to_channel_message_event_id, t.relay_url, "reply"]); + } + return finalizeEvent( + { + kind: ChannelMessage, + tags: [...tags, ...t.tags ?? []], + content: t.content, + created_at: t.created_at + }, + privateKey + ); + }; + var channelHideMessageEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finalizeEvent( + { + kind: ChannelHideMessage, + tags: [["e", t.channel_message_event_id], ...t.tags ?? []], + content, + created_at: t.created_at + }, + privateKey + ); + }; + var channelMuteUserEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finalizeEvent( + { + kind: ChannelMuteUser, + tags: [["p", t.pubkey_to_mute], ...t.tags ?? []], + content, + created_at: t.created_at + }, + privateKey + ); + }; + + // nip30.ts + var nip30_exports = {}; + __export(nip30_exports, { + EMOJI_SHORTCODE_REGEX: () => EMOJI_SHORTCODE_REGEX, + matchAll: () => matchAll, + regex: () => regex, + replaceAll: () => replaceAll + }); + var EMOJI_SHORTCODE_REGEX = /:(\w+):/; + var regex = () => new RegExp(`\\B${EMOJI_SHORTCODE_REGEX.source}\\B`, "g"); + function* matchAll(content) { + const matches = content.matchAll(regex()); + for (const match of matches) { + try { + const [shortcode, name] = match; + yield { + shortcode, + name, + start: match.index, + end: match.index + shortcode.length + }; + } catch (_e) { + } + } + } + function replaceAll(content, replacer) { + return content.replaceAll(regex(), (shortcode, name) => { + return replacer({ + shortcode, + name + }); + }); + } + + // nip39.ts + var nip39_exports = {}; + __export(nip39_exports, { + useFetchImplementation: () => useFetchImplementation3, + validateGithub: () => validateGithub + }); + var _fetch3; + try { + _fetch3 = fetch; + } catch { + } + function useFetchImplementation3(fetchImplementation) { + _fetch3 = fetchImplementation; + } + async function validateGithub(pubkey, username, proof) { + try { + let res = await (await _fetch3(`https://gist.github.com/${username}/${proof}/raw`)).text(); + return res === `Verifying that I control the following Nostr public key: ${pubkey}`; + } catch (_) { + return false; + } + } + + // nip47.ts + var nip47_exports = {}; + __export(nip47_exports, { + makeNwcRequestEvent: () => makeNwcRequestEvent, + parseConnectionString: () => parseConnectionString + }); + function parseConnectionString(connectionString) { + const { host, pathname, searchParams } = new URL(connectionString); + const pubkey = pathname || host; + const relay = searchParams.get("relay"); + const secret = searchParams.get("secret"); + if (!pubkey || !relay || !secret) { + throw new Error("invalid connection string"); + } + return { pubkey, relay, secret }; + } + async function makeNwcRequestEvent(pubkey, secretKey, invoice) { + const content = { + method: "pay_invoice", + params: { + invoice + } + }; + const encryptedContent = encrypt2(secretKey, pubkey, JSON.stringify(content)); + const eventTemplate = { + kind: NWCWalletRequest, + created_at: Math.round(Date.now() / 1e3), + content: encryptedContent, + tags: [["p", pubkey]] + }; + return finalizeEvent(eventTemplate, secretKey); + } + + // nip54.ts + var nip54_exports = {}; + __export(nip54_exports, { + normalizeIdentifier: () => normalizeIdentifier + }); + function normalizeIdentifier(name) { + name = name.trim().toLowerCase(); + name = name.normalize("NFKC"); + return Array.from(name).map((char) => { + if (/\p{Letter}/u.test(char) || /\p{Number}/u.test(char)) { + return char; + } + return "-"; + }).join(""); + } + + // nip57.ts + var nip57_exports = {}; + __export(nip57_exports, { + getSatoshisAmountFromBolt11: () => getSatoshisAmountFromBolt11, + getZapEndpoint: () => getZapEndpoint, + makeZapReceipt: () => makeZapReceipt, + makeZapRequest: () => makeZapRequest, + useFetchImplementation: () => useFetchImplementation4, + validateZapRequest: () => validateZapRequest + }); + var _fetch4; + try { + _fetch4 = fetch; + } catch { + } + function useFetchImplementation4(fetchImplementation) { + _fetch4 = fetchImplementation; + } + async function getZapEndpoint(metadata) { + try { + let lnurl = ""; + let { lud06, lud16 } = JSON.parse(metadata.content); + if (lud06) { + let { words } = bech32.decode(lud06, 1e3); + let data = bech32.fromWords(words); + lnurl = utf8Decoder.decode(data); + } else if (lud16) { + let [name, domain] = lud16.split("@"); + lnurl = new URL(`/.well-known/lnurlp/${name}`, `https://${domain}`).toString(); + } else { + return null; + } + let res = await _fetch4(lnurl); + let body = await res.json(); + if (body.allowsNostr && body.nostrPubkey) { + return body.callback; + } + } catch (err) { + } + return null; + } + function makeZapRequest(params) { + let zr = { + kind: 9734, + created_at: Math.round(Date.now() / 1e3), + content: params.comment || "", + tags: [ + ["p", "pubkey" in params ? params.pubkey : params.event.pubkey], + ["amount", params.amount.toString()], + ["relays", ...params.relays] + ] + }; + if ("event" in params) { + zr.tags.push(["e", params.event.id]); + if (isReplaceableKind(params.event.kind)) { + const a = ["a", `${params.event.kind}:${params.event.pubkey}:`]; + zr.tags.push(a); + } else if (isAddressableKind(params.event.kind)) { + let d = params.event.tags.find(([t, v]) => t === "d" && v); + if (!d) + throw new Error("d tag not found or is empty"); + const a = ["a", `${params.event.kind}:${params.event.pubkey}:${d[1]}`]; + zr.tags.push(a); + } + zr.tags.push(["k", params.event.kind.toString()]); + } + return zr; + } + function validateZapRequest(zapRequestString) { + let zapRequest; + try { + zapRequest = JSON.parse(zapRequestString); + } catch (err) { + return "Invalid zap request JSON."; + } + if (!validateEvent(zapRequest)) + return "Zap request is not a valid Nostr event."; + if (!verifyEvent(zapRequest)) + return "Invalid signature on zap request."; + let p = zapRequest.tags.find(([t, v]) => t === "p" && v); + if (!p) + return "Zap request doesn't have a 'p' tag."; + if (!p[1].match(/^[a-f0-9]{64}$/)) + return "Zap request 'p' tag is not valid hex."; + let e = zapRequest.tags.find(([t, v]) => t === "e" && v); + if (e && !e[1].match(/^[a-f0-9]{64}$/)) + return "Zap request 'e' tag is not valid hex."; + let relays = zapRequest.tags.find(([t, v]) => t === "relays" && v); + if (!relays) + return "Zap request doesn't have a 'relays' tag."; + return null; + } + function makeZapReceipt({ + zapRequest, + preimage, + bolt11, + paidAt + }) { + let zr = JSON.parse(zapRequest); + let tagsFromZapRequest = zr.tags.filter(([t]) => t === "e" || t === "p" || t === "a"); + let zap = { + kind: 9735, + created_at: Math.round(paidAt.getTime() / 1e3), + content: "", + tags: [...tagsFromZapRequest, ["P", zr.pubkey], ["bolt11", bolt11], ["description", zapRequest]] + }; + if (preimage) { + zap.tags.push(["preimage", preimage]); + } + return zap; + } + function getSatoshisAmountFromBolt11(bolt11) { + if (bolt11.length < 50) { + return 0; + } + bolt11 = bolt11.substring(0, 50); + const idx = bolt11.lastIndexOf("1"); + if (idx === -1) { + return 0; + } + const hrp = bolt11.substring(0, idx); + if (!hrp.startsWith("lnbc")) { + return 0; + } + const amount = hrp.substring(4); + if (amount.length < 1) { + return 0; + } + const char = amount[amount.length - 1]; + const digit = char.charCodeAt(0) - "0".charCodeAt(0); + const isDigit = digit >= 0 && digit <= 9; + let cutPoint = amount.length - 1; + if (isDigit) { + cutPoint++; + } + if (cutPoint < 1) { + return 0; + } + const num = parseInt(amount.substring(0, cutPoint)); + switch (char) { + case "m": + return num * 1e5; + case "u": + return num * 100; + case "n": + return num / 10; + case "p": + return num / 1e4; + default: + return num * 1e8; + } + } + + // nip98.ts + var nip98_exports = {}; + __export(nip98_exports, { + getToken: () => getToken, + hashPayload: () => hashPayload, + unpackEventFromToken: () => unpackEventFromToken, + validateEvent: () => validateEvent2, + validateEventKind: () => validateEventKind, + validateEventMethodTag: () => validateEventMethodTag, + validateEventPayloadTag: () => validateEventPayloadTag, + validateEventTimestamp: () => validateEventTimestamp, + validateEventUrlTag: () => validateEventUrlTag, + validateToken: () => validateToken + }); + var _authorizationScheme = "Nostr "; + async function getToken(loginUrl, httpMethod, sign, includeAuthorizationScheme = false, payload) { + const event = { + kind: HTTPAuth, + tags: [ + ["u", loginUrl], + ["method", httpMethod] + ], + created_at: Math.round(new Date().getTime() / 1e3), + content: "" + }; + if (payload) { + event.tags.push(["payload", hashPayload(payload)]); + } + const signedEvent = await sign(event); + const authorizationScheme = includeAuthorizationScheme ? _authorizationScheme : ""; + return authorizationScheme + base64.encode(utf8Encoder.encode(JSON.stringify(signedEvent))); + } + async function validateToken(token, url, method) { + const event = await unpackEventFromToken(token).catch((error) => { + throw error; + }); + const valid = await validateEvent2(event, url, method).catch((error) => { + throw error; + }); + return valid; + } + async function unpackEventFromToken(token) { + if (!token) { + throw new Error("Missing token"); + } + token = token.replace(_authorizationScheme, ""); + const eventB64 = utf8Decoder.decode(base64.decode(token)); + if (!eventB64 || eventB64.length === 0 || !eventB64.startsWith("{")) { + throw new Error("Invalid token"); + } + const event = JSON.parse(eventB64); + return event; + } + function validateEventTimestamp(event) { + if (!event.created_at) { + return false; + } + return Math.round(new Date().getTime() / 1e3) - event.created_at < 60; + } + function validateEventKind(event) { + return event.kind === HTTPAuth; + } + function validateEventUrlTag(event, url) { + const urlTag = event.tags.find((t) => t[0] === "u"); + if (!urlTag) { + return false; + } + return urlTag.length > 0 && urlTag[1] === url; + } + function validateEventMethodTag(event, method) { + const methodTag = event.tags.find((t) => t[0] === "method"); + if (!methodTag) { + return false; + } + return methodTag.length > 0 && methodTag[1].toLowerCase() === method.toLowerCase(); + } + function hashPayload(payload) { + const hash3 = sha2562(utf8Encoder.encode(JSON.stringify(payload))); + return bytesToHex2(hash3); + } + function validateEventPayloadTag(event, payload) { + const payloadTag = event.tags.find((t) => t[0] === "payload"); + if (!payloadTag) { + return false; + } + const payloadHash = hashPayload(payload); + return payloadTag.length > 0 && payloadTag[1] === payloadHash; + } + async function validateEvent2(event, url, method, body) { + if (!verifyEvent(event)) { + throw new Error("Invalid nostr event, signature invalid"); + } + if (!validateEventKind(event)) { + throw new Error("Invalid nostr event, kind invalid"); + } + if (!validateEventTimestamp(event)) { + throw new Error("Invalid nostr event, created_at timestamp invalid"); + } + if (!validateEventUrlTag(event, url)) { + throw new Error("Invalid nostr event, url tag invalid"); + } + if (!validateEventMethodTag(event, method)) { + throw new Error("Invalid nostr event, method tag invalid"); + } + if (Boolean(body) && typeof body === "object" && Object.keys(body).length > 0) { + if (!validateEventPayloadTag(event, body)) { + throw new Error("Invalid nostr event, payload tag does not match request body hash"); + } + } + return true; + } + return __toCommonJS(nostr_tools_exports); +})(); diff --git a/node_modules/nostr-tools/lib/nostr.bundle.js.map b/node_modules/nostr-tools/lib/nostr.bundle.js.map new file mode 100644 index 0000000..09cd78a --- /dev/null +++ b/node_modules/nostr-tools/lib/nostr.bundle.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../index.ts", "../node_modules/@noble/curves/node_modules/@noble/hashes/src/_assert.ts", "../node_modules/@noble/curves/node_modules/@noble/hashes/src/crypto.ts", "../node_modules/@noble/curves/node_modules/@noble/hashes/src/utils.ts", "../node_modules/@noble/curves/node_modules/@noble/hashes/src/_sha2.ts", "../node_modules/@noble/curves/node_modules/@noble/hashes/src/sha256.ts", "../node_modules/@noble/curves/src/abstract/utils.ts", "../node_modules/@noble/curves/src/abstract/modular.ts", "../node_modules/@noble/curves/src/abstract/curve.ts", "../node_modules/@noble/curves/src/abstract/weierstrass.ts", "../node_modules/@noble/curves/node_modules/@noble/hashes/src/hmac.ts", "../node_modules/@noble/curves/src/_shortw_utils.ts", "../node_modules/@noble/curves/src/secp256k1.ts", "../node_modules/@noble/hashes/src/crypto.ts", "../node_modules/@noble/hashes/src/utils.ts", "../core.ts", "../node_modules/@noble/hashes/src/_assert.ts", "../node_modules/@noble/hashes/src/_sha2.ts", "../node_modules/@noble/hashes/src/sha256.ts", "../utils.ts", "../pure.ts", "../kinds.ts", "../filter.ts", "../fakejson.ts", "../nip42.ts", "../helpers.ts", "../abstract-relay.ts", "../relay.ts", "../abstract-pool.ts", "../pool.ts", "../nip19.ts", "../node_modules/@scure/base/lib/esm/index.js", "../references.ts", "../nip04.ts", "../node_modules/@noble/ciphers/src/_assert.ts", "../node_modules/@noble/ciphers/src/utils.ts", "../node_modules/@noble/ciphers/src/_polyval.ts", "../node_modules/@noble/ciphers/src/aes.ts", "../nip05.ts", "../nip10.ts", "../nip11.ts", "../nip13.ts", "../nip17.ts", "../nip59.ts", "../nip44.ts", "../node_modules/@noble/ciphers/src/_poly1305.ts", "../node_modules/@noble/ciphers/src/_arx.ts", "../node_modules/@noble/ciphers/src/chacha.ts", "../node_modules/@noble/hashes/src/hmac.ts", "../node_modules/@noble/hashes/src/hkdf.ts", "../nip18.ts", "../nip21.ts", "../nip25.ts", "../nip27.ts", "../nip28.ts", "../nip30.ts", "../nip39.ts", "../nip47.ts", "../nip54.ts", "../nip57.ts", "../nip98.ts"], + "sourcesContent": ["export * from './pure.ts'\nexport { Relay } from './relay.ts'\nexport * from './filter.ts'\nexport { SimplePool } from './pool.ts'\nexport * from './references.ts'\n\nexport * as nip04 from './nip04.ts'\nexport * as nip05 from './nip05.ts'\nexport * as nip10 from './nip10.ts'\nexport * as nip11 from './nip11.ts'\nexport * as nip13 from './nip13.ts'\nexport * as nip17 from './nip17.ts'\nexport * as nip18 from './nip18.ts'\nexport * as nip19 from './nip19.ts'\nexport * as nip21 from './nip21.ts'\nexport * as nip25 from './nip25.ts'\nexport * as nip27 from './nip27.ts'\nexport * as nip28 from './nip28.ts'\nexport * as nip30 from './nip30.ts'\nexport * as nip39 from './nip39.ts'\nexport * as nip42 from './nip42.ts'\nexport * as nip44 from './nip44.ts'\nexport * as nip47 from './nip47.ts'\nexport * as nip54 from './nip54.ts'\nexport * as nip57 from './nip57.ts'\nexport * as nip59 from './nip59.ts'\nexport * as nip98 from './nip98.ts'\n\nexport * as kinds from './kinds.ts'\nexport * as fj from './fakejson.ts'\nexport * as utils from './utils.ts'\n", "function number(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error(`Wrong positive integer: ${n}`);\n}\n\nfunction bool(b: boolean) {\n if (typeof b !== 'boolean') throw new Error(`Expected boolean, not ${b}`);\n}\n\nfunction bytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!(b instanceof Uint8Array)) throw new Error('Expected Uint8Array');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);\n}\n\ntype Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nfunction hash(hash: Hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\n\nfunction exists(instance: any, checkFinished = true) {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\nfunction output(out: any, instance: any) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\n\nexport { number, bool, bytes, hash, exists, output };\n\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n", "// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// See utils.ts for details.\ndeclare const globalThis: Record | undefined;\nexport const crypto =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n", "/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated, we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\nconst u8a = (a: any): a is Uint8Array => a instanceof Uint8Array;\n// Cast array to different type\nexport const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr: TypedArray) =>\n new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\n// Cast array to view\nexport const createView = (arr: TypedArray) =>\n new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word: number, shift: number) => (word << (32 - shift)) | (word >>> shift);\n\n// big-endian hardware is rare. Just in case someone still decides to run hashes:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE) throw new Error('Non little-endian hardware is not supported');\n\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n if (!u8a(bytes)) throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const len = hex.length;\n if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len);\n const array = new Uint8Array(len / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\n\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => {};\n\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n if (!u8a(data)) throw new Error(`expected Uint8Array, got ${typeof data}`);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));\n let pad = 0; // walk through each item, ensure they have proper type\n arrays.forEach((a) => {\n if (!u8a(a)) throw new Error('Uint8Array expected');\n r.set(a, pad);\n pad += a.length;\n });\n return r;\n}\n\n// For runtime check if class implements interface\nexport abstract class Hash> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF> = Hash & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\nconst toStr = {}.toString;\ntype EmptyObj = {};\nexport function checkOpts(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\nexport type CHash = ReturnType;\n\nexport function wrapConstructor>(hashCons: () => Hash) {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function wrapConstructorWithOpts, T extends Object>(\n hashCons: (opts?: T) => Hash\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\nexport function wrapXOFConstructorWithOpts, T extends Object>(\n hashCons: (opts?: T) => HashXOF\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n", "import { exists, output } from './_assert.js';\nimport { Hash, createView, Input, toBytes } from './utils.js';\n\n// Polyfill for Safari 14\nfunction setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n// Base SHA2 class (RFC 6234)\nexport abstract class SHA2> extends Hash {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(\n readonly blockLen: number,\n public outputLen: number,\n readonly padOffset: number,\n readonly isLE: boolean\n ) {\n super();\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array) {\n exists(this);\n output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n}\n", "import { SHA2 } from './_sha2.js';\nimport { rotr, wrapConstructor } from './utils.js';\n\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n\n// Choice: a ? b : c\nconst Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c);\n// Majority function, true if any two inpust is true\nconst Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c);\n\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n// prettier-ignore\nconst IV = /* @__PURE__ */new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nclass SHA256 extends SHA2 {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = IV[0] | 0;\n B = IV[1] | 0;\n C = IV[2] | 0;\n D = IV[3] | 0;\n E = IV[4] | 0;\n F = IV[5] | 0;\n G = IV[6] | 0;\n H = IV[7] | 0;\n\n constructor() {\n super(64, 32, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n A = 0xc1059ed8 | 0;\n B = 0x367cd507 | 0;\n C = 0x3070dd17 | 0;\n D = 0xf70e5939 | 0;\n E = 0xffc00b31 | 0;\n F = 0x68581511 | 0;\n G = 0x64f98fa7 | 0;\n H = 0xbefa4fa4 | 0;\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst u8a = (a: any): a is Uint8Array => a instanceof Uint8Array;\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n (message: Uint8Array | string): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n if (!u8a(bytes)) throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const len = hex.length;\n if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len);\n const array = new Uint8Array(len / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n if (!u8a(bytes)) throw new Error('Uint8Array expected');\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes(numberToHexUnpadded(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n let res: Uint8Array;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n } catch (e) {\n throw new Error(`${title} must be valid hex string, got \"${hex}\". Cause: ${e}`);\n }\n } else if (u8a(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n } else {\n throw new Error(`${title} must be hex string or Uint8Array`);\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);\n return res;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));\n let pad = 0; // walk through each item, ensure they have proper type\n arrays.forEach((a) => {\n if (!u8a(a)) throw new Error('Uint8Array expected');\n r.set(a, pad);\n pad += a.length;\n });\n return r;\n}\n\nexport function equalBytes(b1: Uint8Array, b2: Uint8Array) {\n // We don't care about timing attacks here\n if (b1.length !== b2.length) return false;\n for (let i = 0; i < b1.length; i++) if (b1[i] !== b2[i]) return false;\n return true;\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n: bigint) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number) {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport const bitSet = (n: bigint, pos: number, value: boolean) => {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n};\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number) => (_2n << BigInt(n - 1)) - _1n;\n\n// DRBG\n\nconst u8n = (data?: any) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr: any) => Uint8Array.from(arr); // another shortcut\ntype Pred = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred) => T {\n if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000) throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed: Uint8Array, pred: Pred): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\n// Validating curves and fields\n\nconst validatorFns = {\n bigint: (val: any) => typeof val === 'bigint',\n function: (val: any) => typeof val === 'function',\n boolean: (val: any) => typeof val === 'boolean',\n string: (val: any) => typeof val === 'string',\n stringOrUint8Array: (val: any) => typeof val === 'string' || val instanceof Uint8Array,\n isSafeInteger: (val: any) => Number.isSafeInteger(val),\n array: (val: any) => Array.isArray(val),\n field: (val: any, object: any) => (object as any).Fp.isValid(val),\n hash: (val: any) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap> = { [K in keyof T]?: Validator };\n// type Record = { [P in K]: T; }\n\nexport function validateObject>(\n object: T,\n validators: ValMap,\n optValidators: ValMap = {}\n) {\n const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error(`Invalid validator \"${type}\", expected function`);\n\n const val = object[fieldName as keyof typeof object];\n if (isOptional && val === undefined) return;\n if (!checkVal(val, object)) {\n throw new Error(\n `Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`\n );\n }\n };\n for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\nimport {\n bitMask,\n numberToBytesBE,\n numberToBytesLE,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n validateObject,\n} from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);\n// prettier-ignore\nconst _9n = BigInt(9), _16n = BigInt(16);\n\n// Calculates a modulo b\nexport function mod(a: bigint, b: bigint): bigint {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n if (modulo <= _0n || power < _0n) throw new Error('Expected power/modulo > 0');\n if (modulo === _1n) return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n) res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n// Inverses number over modulo\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) \u2261 1 if a is a square (mod p)\n // (a | p) \u2261 -1 if a is not a square (mod p)\n // (a | p) \u2261 0 if a \u2261 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n\n let Q: bigint, S: number, Z: bigint;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++);\n\n // Step 2: Select a non-square z such that (z | p) \u2261 -1 and set c \u2261 zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++);\n\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast(Fp: IField, n: T) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp: IField, n: T): T {\n // Step 0: Check that n is indeed a square: (n | p) should not be \u2261 -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE)) break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\n\nexport function FpSqrt(P: bigint) {\n // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.\n // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n\n // P \u2261 3 (mod 4)\n // \u221An = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4(Fp: IField, n: T) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Atkin algorithm for q \u2261 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8(Fp: IField, n: T) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // P \u2261 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num: bigint, modulo: bigint) => (mod(num, modulo) & _1n) === _1n;\n\n// Field is not always over prime: for example, Fp2 has ORDER(q)=p^m\nexport interface IField {\n ORDER: bigint;\n BYTES: number;\n BITS: number;\n MASK: bigint;\n ZERO: T;\n ONE: T;\n // 1-arg\n create: (num: T) => T;\n isValid: (num: T) => boolean;\n is0: (num: T) => boolean;\n neg(num: T): T;\n inv(num: T): T;\n sqrt(num: T): T;\n sqr(num: T): T;\n // 2-args\n eql(lhs: T, rhs: T): boolean;\n add(lhs: T, rhs: T): T;\n sub(lhs: T, rhs: T): T;\n mul(lhs: T, rhs: T | bigint): T;\n pow(lhs: T, power: bigint): T;\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n addN(lhs: T, rhs: T): T;\n subN(lhs: T, rhs: T): T;\n mulN(lhs: T, rhs: T | bigint): T;\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway.\n isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2\n // legendre?(num: T): T;\n pow(lhs: T, power: bigint): T;\n invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\nexport function validateField(field: IField) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n } as Record;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(f: IField, num: T, power: bigint): T {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n) throw new Error('Expected power > 0');\n if (power === _0n) return f.ONE;\n if (power === _1n) return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch(f: IField, nums: T[]): T[] {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num)) return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num)) return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\n\nexport function FpDiv(f: IField, lhs: T, rhs: T | bigint): T {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(f: IField) {\n const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic\n return (x: T): boolean => {\n const p = f.pow(x, legendreConst);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField & Required, 'isOdd'>>;\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(\n ORDER: bigint,\n bitLen?: number,\n isLE = false,\n redef: Partial> = {}\n): Readonly {\n if (ORDER <= _0n) throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048) throw new Error('Field lengths over 2048 bytes are not supported');\n const sqrtP = FpSqrt(ORDER);\n const f: Readonly = Object.freeze({\n ORDER,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n\n inv: (num) => invert(num, ORDER),\n sqrt: redef.sqrt || ((n) => sqrtP(f, n)),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n } as FpField);\n return Object.freeze(f);\n}\n\nexport function FpSqrtOdd(Fp: IField, elm: T) {\n if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\n\nexport function FpSqrtEven(Fp: IField, elm: T) {\n if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nexport function hashToPrivateScalar(\n hash: string | Uint8Array,\n groupOrder: bigint,\n isLE = false\n): bigint {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);\n const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\nimport { IField, validateField, nLength } from './modular.js';\nimport { validateObject } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport type AffinePoint = {\n x: T;\n y: T;\n} & { z?: never; t?: never };\n\nexport interface Group> {\n double(): T;\n negate(): T;\n add(other: T): T;\n subtract(other: T): T;\n equals(other: T): boolean;\n multiply(scalar: bigint): T;\n}\n\nexport type GroupConstructor = {\n BASE: T;\n ZERO: T;\n};\nexport type Mapper = (i: T[]) => T[];\n\n// Elliptic curve multiplication of Point by scalar. Fragile.\n// Scalars should always be less than curve order: this should be checked inside of a curve itself.\n// Creates precomputation tables for fast multiplication:\n// - private scalar is split by fixed size windows of W bits\n// - every window point is collected from window's table & added to accumulator\n// - since windows are different, same point inside tables won't be accessed more than once per calc\n// - each multiplication is 'Math.ceil(CURVE_ORDER / \uD835\uDC4A) + 1' point additions (fixed for any scalar)\n// - +1 window is neccessary for wNAF\n// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nexport function wNAF>(c: GroupConstructor, bits: number) {\n const constTimeNegate = (condition: boolean, item: T): T => {\n const neg = item.negate();\n return condition ? neg : item;\n };\n const opts = (W: number) => {\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n };\n return {\n constTimeNegate,\n // non-const time multiplication ladder\n unsafeLadder(elm: T, n: bigint) {\n let p = c.ZERO;\n let d: T = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(\uD835\uDC4A\u22121) * (Math.ceil(\uD835\uDC5B / \uD835\uDC4A) + 1), where:\n * - \uD835\uDC4A is the window size\n * - \uD835\uDC5B is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm: T, W: number): Group[] {\n const { windows, windowSize } = opts(W);\n const points: T[] = [];\n let p: T = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T } {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = opts(W);\n\n let p = c.ZERO;\n let f = c.BASE;\n\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n\n // Shift number by W bits.\n n >>= shiftBy;\n\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n } else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n\n wNAFCached(P: T, precomputesMap: Map, n: bigint, transform: Mapper): { p: T; f: T } {\n // @ts-ignore\n const W: number = P._WINDOW_SIZE || 1;\n // Calculate precomputes on a first run, reuse them after\n let comp = precomputesMap.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W) as T[];\n if (W !== 1) {\n precomputesMap.set(P, transform(comp));\n }\n }\n return this.wNAF(W, comp, n);\n },\n };\n}\n\n// Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.\n// Though generator can be different (Fp2 / Fp6 for BLS).\nexport type BasicCurve = {\n Fp: IField; // Field over which we'll do calculations (Fp)\n n: bigint; // Curve order, total count of valid points in the field\n nBitLength?: number; // bit length of curve order\n nByteLength?: number; // byte length of curve order\n h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation\n hEff?: bigint; // Number to multiply to clear cofactor\n Gx: T; // base point X coordinate\n Gy: T; // base point Y coordinate\n allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey\n};\n\nexport function validateBasic(curve: BasicCurve & T) {\n validateField(curve.Fp);\n validateObject(\n curve,\n {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n },\n {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n }\n );\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n } as const);\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Short Weierstrass curve. The formula is: y\u00B2 = x\u00B3 + ax + b\nimport * as mod from './modular.js';\nimport * as ut from './utils.js';\nimport { CHash, Hex, PrivKey, ensureBytes } from './utils.js';\nimport { Group, GroupConstructor, wNAF, BasicCurve, validateBasic, AffinePoint } from './curve.js';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\ntype EndomorphismOpts = {\n beta: bigint;\n splitScalar: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\nexport type BasicWCurve = BasicCurve & {\n // Params: a, b\n a: T;\n b: T;\n\n // Optional params\n allowedPrivateKeyLengths?: readonly number[]; // for P521\n wrapPrivateKey?: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n endo?: EndomorphismOpts; // Endomorphism options for Koblitz curves\n // When a cofactor != 1, there can be an effective methods to:\n // 1. Determine whether a point is torsion-free\n isTorsionFree?: (c: ProjConstructor, point: ProjPointType) => boolean;\n // 2. Clear torsion component\n clearCofactor?: (c: ProjConstructor, point: ProjPointType) => ProjPointType;\n};\n\ntype Entropy = Hex | true;\nexport type SignOpts = { lowS?: boolean; extraEntropy?: Entropy; prehash?: boolean };\nexport type VerOpts = { lowS?: boolean; prehash?: boolean };\n\n/**\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance of nominative types in TypeScript and interfaces only check for shape, so it's hard to create unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * TODO: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n */\n\n// Instance for 3d XYZ points\nexport interface ProjPointType extends Group> {\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n get x(): T;\n get y(): T;\n multiply(scalar: bigint): ProjPointType;\n toAffine(iz?: T): AffinePoint;\n isTorsionFree(): boolean;\n clearCofactor(): ProjPointType;\n assertValidity(): void;\n hasEvenY(): boolean;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n\n multiplyUnsafe(scalar: bigint): ProjPointType;\n multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined;\n _setWindowSize(windowSize: number): void;\n}\n// Static methods for 3d XYZ points\nexport interface ProjConstructor extends GroupConstructor> {\n new (x: T, y: T, z: T): ProjPointType;\n fromAffine(p: AffinePoint): ProjPointType;\n fromHex(hex: Hex): ProjPointType;\n fromPrivateKey(privateKey: PrivKey): ProjPointType;\n normalizeZ(points: ProjPointType[]): ProjPointType[];\n}\n\nexport type CurvePointsType = BasicWCurve & {\n // Bytes\n fromBytes?: (bytes: Uint8Array) => AffinePoint;\n toBytes?: (c: ProjConstructor, point: ProjPointType, isCompressed: boolean) => Uint8Array;\n};\n\nfunction validatePointOpts(curve: CurvePointsType) {\n const opts = validateBasic(curve);\n ut.validateObject(\n opts,\n {\n a: 'field',\n b: 'field',\n },\n {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n }\n );\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');\n }\n if (\n typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function'\n ) {\n throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts } as const);\n}\n\nexport type CurvePointsRes = {\n ProjectivePoint: ProjConstructor;\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n weierstrassEquation: (x: T) => T;\n isWithinCurveOrder: (num: bigint) => boolean;\n};\n\n// ASN.1 DER encoding utilities\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\nexport const DER = {\n // asn.1 DER encoding utils\n Err: class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n },\n _parseInt(data: Uint8Array): { d: bigint; l: Uint8Array } {\n const { Err: E } = DER;\n if (data.length < 2 || data[0] !== 0x02) throw new E('Invalid signature integer tag');\n const len = data[1];\n const res = data.subarray(2, len + 2);\n if (!len || res.length !== len) throw new E('Invalid signature integer: wrong length');\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n if (res[0] & 0b10000000) throw new E('Invalid signature integer: negative');\n if (res[0] === 0x00 && !(res[1] & 0b10000000))\n throw new E('Invalid signature integer: unnecessary leading zero');\n return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left\n },\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n if (!(data instanceof Uint8Array)) throw new Error('ui8a expected');\n let l = data.length;\n if (l < 2 || data[0] != 0x30) throw new E('Invalid signature tag');\n if (data[1] !== l - 2) throw new E('Invalid signature: incorrect length');\n const { d: r, l: sBytes } = DER._parseInt(data.subarray(2));\n const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);\n if (rBytesLeft.length) throw new E('Invalid signature: left bytes after parsing');\n return { r, s };\n },\n hexFromSig(sig: { r: bigint; s: bigint }): string {\n // Add leading zero if first byte has negative bit enabled. More details in '_parseInt'\n const slice = (s: string): string => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s);\n const h = (num: number | bigint) => {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n };\n const s = slice(h(sig.s));\n const r = slice(h(sig.r));\n const shl = s.length / 2;\n const rhl = r.length / 2;\n const sl = h(shl);\n const rl = h(rhl);\n return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;\n },\n};\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\n\nexport function weierstrassPoints(opts: CurvePointsType) {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n\n const toBytes =\n CURVE.toBytes ||\n ((_c: ProjConstructor, point: ProjPointType, _isCompressed: boolean) => {\n const a = point.toAffine();\n return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes =\n CURVE.fromBytes ||\n ((bytes: Uint8Array) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n\n /**\n * y\u00B2 = x\u00B3 + ax + b: Short weierstrass curve formula\n * @returns y\u00B2\n */\n function weierstrassEquation(x: T): T {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num: bigint): boolean {\n return typeof num === 'bigint' && _0n < num && num < CURVE.n;\n }\n function assertGE(num: bigint) {\n if (!isWithinCurveOrder(num)) throw new Error('Expected valid bigint: 0 < bigint < curve.n');\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key: PrivKey): bigint {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (key instanceof Uint8Array) key = ut.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length)) throw new Error('Invalid key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num: bigint;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n } catch (error) {\n throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);\n }\n if (wrapPrivateKey) num = mod.mod(num, n); // disabled by default, enabled for BLS\n assertGE(num); // num in range [1..N-1]\n return num;\n }\n\n const pointPrecomputes = new Map();\n function assertPrjPoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ProjectivePoint expected');\n }\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) \u220B (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point implements ProjPointType {\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n\n constructor(readonly px: T, readonly py: T, readonly pz: T) {\n if (px == null || !Fp.isValid(px)) throw new Error('x required');\n if (py == null || !Fp.isValid(py)) throw new Error('y required');\n if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n }\n\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p: AffinePoint): Point {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point');\n if (p instanceof Point) throw new Error('projective point not allowed');\n const is0 = (i: T) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n get x(): T {\n return this.toAffine().x;\n }\n get y(): T {\n return this.toAffine().y;\n }\n\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points: Point[]): Point[] {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex: Hex): Point {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey: PrivKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n _WINDOW_SIZE?: number;\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n\n // A point on curve is valid if it conforms to equation.\n assertValidity(): void {\n if (this.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is wrong representation of ZERO and is always invalid.\n if (CURVE.allowInfinityPoint && !Fp.is0(this.py)) return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = this.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y\u00B2\n const right = weierstrassEquation(x); // x\u00B3 + ax + b\n if (!Fp.eql(left, right)) throw new Error('bad point: equation left != right');\n if (!this.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n }\n hasEvenY(): boolean {\n const { y } = this.toAffine();\n if (Fp.isOdd) return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n\n /**\n * Compare one point to another.\n */\n equals(other: Point): boolean {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate(): Point {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other: Point): Point {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n\n subtract(other: Point) {\n return this.add(other.negate());\n }\n\n private is0() {\n return this.equals(Point.ZERO);\n }\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, pointPrecomputes, n, (comp: Point[]) => {\n const toInv = Fp.invertBatch(comp.map((p) => p.pz));\n return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n });\n }\n\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(n: bigint): Point {\n const I = Point.ZERO;\n if (n === _0n) return I;\n assertGE(n); // Will throw on 0\n if (n === _1n) return this;\n const { endo } = CURVE;\n if (!endo) return wnaf.unsafeLadder(this, n);\n\n // Apply endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let k1p = I;\n let k2p = I;\n let d: Point = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) k1p = k1p.add(d);\n if (k2 & _1n) k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg) k1p = k1p.negate();\n if (k2neg) k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar: bigint): Point {\n assertGE(scalar);\n let n = scalar;\n let point: Point, fake: Point; // Fake point is used to const-time mult\n const { endo } = CURVE;\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n } else {\n const { p, f } = this.wNAF(n);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q: Point, a: bigint, b: bigint): Point | undefined {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (\n P: Point,\n a: bigint // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) \u220B (x=x/z, y=y/z)\n toAffine(iz?: T): AffinePoint {\n const { px: x, py: y, pz: z } = this;\n const is0 = this.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0) return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n }\n isTorsionFree(): boolean {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n) return true; // No subgroups, always torsion-free\n if (isTorsionFree) return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor(): Point {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n return this.multiplyUnsafe(CURVE.h);\n }\n\n toRawBytes(isCompressed = true): Uint8Array {\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n return ut.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point as ProjConstructor,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\n\n// Instance\nexport interface SignatureType {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n assertValidity(): void;\n addRecoveryBit(recovery: number): RecoveredSignatureType;\n hasHighS(): boolean;\n normalizeS(): SignatureType;\n recoverPublicKey(msgHash: Hex): ProjPointType;\n toCompactRawBytes(): Uint8Array;\n toCompactHex(): string;\n // DER-encoded\n toDERRawBytes(isCompressed?: boolean): Uint8Array;\n toDERHex(isCompressed?: boolean): string;\n}\nexport type RecoveredSignatureType = SignatureType & {\n readonly recovery: number;\n};\n// Static methods\nexport type SignatureConstructor = {\n new (r: bigint, s: bigint): SignatureType;\n fromCompact(hex: Hex): SignatureType;\n fromDER(hex: Hex): SignatureType;\n};\ntype SignatureLike = { r: bigint; s: bigint };\n\nexport type PubKey = Hex | ProjPointType;\n\nexport type CurveType = BasicWCurve & {\n hash: CHash; // CHash not FHash because we need outputLen for DRBG\n hmac: HmacFnSync;\n randomBytes: (bytesLength?: number) => Uint8Array;\n lowS?: boolean;\n bits2int?: (bytes: Uint8Array) => bigint;\n bits2int_modN?: (bytes: Uint8Array) => bigint;\n};\n\nfunction validateOpts(curve: CurveType) {\n const opts = validateBasic(curve);\n ut.validateObject(\n opts,\n {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n },\n {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n }\n );\n return Object.freeze({ lowS: true, ...opts } as const);\n}\n\nexport type CurveFn = {\n CURVE: ReturnType;\n getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array;\n getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array;\n sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType;\n verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean;\n ProjectivePoint: ProjConstructor;\n Signature: SignatureConstructor;\n utils: {\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n isValidPrivateKey(privateKey: PrivKey): boolean;\n randomPrivateKey: () => Uint8Array;\n precompute: (windowSize?: number, point?: ProjPointType) => ProjPointType;\n };\n};\n\nexport function weierstrass(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType;\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n\n function isValidFieldElement(num: bigint): boolean {\n return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE\n }\n function modN(a: bigint) {\n return mod.mod(a, CURVE_ORDER);\n }\n function invN(a: bigint) {\n return mod.invert(a, CURVE_ORDER);\n }\n\n const {\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed: boolean): Uint8Array {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = ut.concatBytes;\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n } else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes: Uint8Array) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = ut.bytesToNumberBE(tail);\n if (!isValidFieldElement(x)) throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y\u00B2 = x\u00B3 + ax + b\n let y = Fp.sqrt(y2); // y = y\u00B2 ^ (p+1)/4\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd) y = Fp.neg(y);\n return { x, y };\n } else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n } else {\n throw new Error(\n `Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`\n );\n }\n },\n });\n const numToNByteStr = (num: bigint): string =>\n ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n\n function normalizeS(s: bigint) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b: Uint8Array, from: number, to: number) => ut.bytesToNumberBE(b.slice(from, to));\n\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature implements SignatureType {\n constructor(readonly r: bigint, readonly s: bigint, readonly recovery?: number) {\n this.assertValidity();\n }\n\n // pair (bytes of r, bytes of s)\n static fromCompact(hex: Hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex: Hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n\n assertValidity(): void {\n // can use assertGE here\n if (!isWithinCurveOrder(this.r)) throw new Error('r must be 0 < r < CURVE.n');\n if (!isWithinCurveOrder(this.s)) throw new Error('s must be 0 < s < CURVE.n');\n }\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n recoverPublicKey(msgHash: Hex): typeof Point.BASE {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER) throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q) throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n\n // Signatures should be low-s, to prevent malleability.\n hasHighS(): boolean {\n return isBiggerThanHalfOrder(this.s);\n }\n\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n\n // DER-encoded\n toDERRawBytes() {\n return ut.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return ut.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\n\n const utils = {\n isValidPrivateKey(privateKey: PrivKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n } catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: (): Uint8Array => {\n const length = mod.getMinHashLength(CURVE.n);\n return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey: PrivKey, isCompressed = true): Uint8Array {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item: PrivKey | PubKey): boolean {\n const arr = item instanceof Uint8Array;\n const str = typeof item === 'string';\n const len = (arr || str) && (item as Hex).length;\n if (arr) return len === compressedLen || len === uncompressedLen;\n if (str) return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point) return true;\n return false;\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA: PrivKey, publicB: Hex, isCompressed = true): Uint8Array {\n if (isProbPub(privateA)) throw new Error('first arg must be private key');\n if (!isProbPub(publicB)) throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int =\n CURVE.bits2int ||\n function (bytes: Uint8Array): bigint {\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = ut.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN =\n CURVE.bits2int_modN ||\n function (bytes: Uint8Array): bigint {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num: bigint): Uint8Array {\n if (typeof num !== 'bigint') throw new Error('bigint expected');\n if (!(_0n <= num && num < ORDER_MASK))\n throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);\n // works with order, can have different size than numToField!\n return ut.numberToBytesBE(num, CURVE.nByteLength);\n }\n\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.\n // Also it can be bigger for P224 + SHA256\n function prepSig(msgHash: Hex, privateKey: PrivKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null) lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n if (prehash) msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes: Uint8Array): RecoveredSignature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k)) return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n) return;\n // Can use scalar blinding b^-1(bm + bdr) where b \u2208 [1,q\u22121] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n) return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery) as RecoveredSignature; // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts: SignOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts: VerOpts = { lowS: CURVE.lowS, prehash: false };\n\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G \u00D7 k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash: Hex, privKey: PrivKey, opts = defaultSigOpts): RecoveredSignature {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1\u22C5G - U2\u22C5P\n * mod(R.x, n) == r\n * ```\n */\n function verify(\n signature: Hex | SignatureLike,\n msgHash: Hex,\n publicKey: Hex,\n opts = defaultVerOpts\n ): boolean {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n if ('strict' in opts) throw new Error('options.strict was renamed to lowS');\n const { lowS, prehash } = opts;\n\n let _sig: Signature | undefined = undefined;\n let P: ProjPointType;\n try {\n if (typeof sg === 'string' || sg instanceof Uint8Array) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n _sig = Signature.fromDER(sg);\n } catch (derError) {\n if (!(derError instanceof DER.Err)) throw derError;\n _sig = Signature.fromCompact(sg);\n }\n } else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {\n const { r, s } = sg;\n _sig = new Signature(r, s);\n } else {\n throw new Error('PARSE');\n }\n P = Point.fromHex(publicKey);\n } catch (error) {\n if ((error as Error).message === 'PARSE')\n throw new Error(`signature must be Signature instance, Uint8Array or hex string`);\n return false;\n }\n if (lowS && _sig.hasHighS()) return false;\n if (prehash) msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1\u22C5G + u2\u22C5P\n if (!R) return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp: mod.IField, Z: T) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u: T, v: T) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(\n Fp: mod.IField,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n) {\n mod.validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd) throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u: T): { x: T; y: T } => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd!(u) === Fp.isOdd!(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n", "import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js';\nimport { Hash, CHash, Input, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC> extends Hash> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: CHash, _key: Input) {\n super();\n assertHash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf: Input) {\n assertExists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array) {\n assertExists(this);\n assertBytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to?: HMAC): HMAC {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n */\nexport const hmac = (hash: CHash, key: Input, message: Input): Uint8Array =>\n new HMAC(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Input) => new HMAC(hash, key);\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { weierstrass, CurveType } from './abstract/weierstrass.js';\nimport { CHash } from './abstract/utils.js';\n\n// connects noble-curves to noble-hashes\nexport function getHash(hash: CHash) {\n return {\n hash,\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\n// Same API as @noble/hashes, with ability to create curve with custom hash\ntype CurveDef = Readonly>;\nexport function createCurve(curveDef: CurveDef, defHash: CHash) {\n const create = (hash: CHash) => weierstrass({ ...curveDef, ...getHash(hash) });\n return Object.freeze({ ...create(defHash), create });\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { Field, mod, pow2 } from './abstract/modular.js';\nimport { ProjPointType as PointType, mapToCurveSimpleSWU } from './abstract/weierstrass.js';\nimport type { Hex, PrivKey } from './abstract/utils.js';\nimport { bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE } from './abstract/utils.js';\nimport { createHasher, isogenyMap } from './abstract/hash-to-curve.js';\nimport { createCurve } from './_shortw_utils.js';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a: bigint, b: bigint) => (a + b / _2n) / b;\n\n/**\n * \u221An = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y: bigint): bigint {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fp.eql(Fp.sqr(root), y)) throw new Error('Cannot find square root');\n return root;\n}\n\nconst Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n\nexport const secp256k1 = createCurve(\n {\n a: BigInt(0), // equation params: a, b\n b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975\n Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n\n n: secp256k1N, // Curve order, total count of valid points in the field\n // Base point (x, y) aka generator point\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1), // Cofactor\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n /**\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066\n */\n endo: {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k: bigint) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg) k1 = n - k1;\n if (k2neg) k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n },\n sha256\n);\n\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\nconst fe = (x: bigint) => typeof x === 'bigint' && _0n < x && x < secp256k1P;\nconst ge = (x: bigint) => typeof x === 'bigint' && _0n < x && x < secp256k1N;\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {};\nfunction taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point: PointType) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n: bigint) => numberToBytesBE(n, 32);\nconst modP = (x: bigint) => mod(x, secp256k1P);\nconst modN = (x: bigint) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q: PointType, a: bigint, b: bigint) =>\n Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: PrivKey) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'\u22C5G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x: bigint): PointType {\n if (!fe(x)) throw new Error('bad x: need 0 < x < p'); // Fail if x \u2265 p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x\u00B3 + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n) y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args: Uint8Array[]): bigint {\n return modN(bytesToNumberBE(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey: Hex): Uint8Array {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'\u2265n. Ret bytes(d'\u22C5G)\n}\n\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(\n message: Hex,\n privateKey: PrivKey,\n auxRand: Hex = randomBytes(32)\n): Uint8Array {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ bytesToNumberBE(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(bytesToNumberBE(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n) throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'\u22C5G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced');\n return sig;\n}\n\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(bytesToNumberBE(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = bytesToNumberBE(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r \u2265 p.\n if (!fe(r)) return false;\n const s = bytesToNumberBE(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s \u2265 n.\n if (!ge(s)) return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s\u22C5G - e\u22C5P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r) return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) \u2260 r.\n } catch (error) {\n return false;\n }\n}\n\nexport const schnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\n },\n}))();\n\nconst isoMap = /* @__PURE__ */ (() =>\n isogenyMap(\n Fp,\n [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n ].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]]\n ))();\nconst mapSWU = /* @__PURE__ */ (() =>\n mapToCurveSimpleSWU(Fp, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fp.create(BigInt('-11')),\n }))();\nconst htf = /* @__PURE__ */ (() =>\n createHasher(\n secp256k1.ProjectivePoint,\n (scalars: bigint[]) => {\n const { x, y } = mapSWU(Fp.create(scalars[0]));\n return isoMap(x, y);\n },\n {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n }\n ))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n", "// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// See utils.ts for details.\ndeclare const globalThis: Record | undefined;\nexport const crypto =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n", "/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated, we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\nconst u8a = (a: any): a is Uint8Array => a instanceof Uint8Array;\n// Cast array to different type\nexport const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr: TypedArray) =>\n new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\n// Cast array to view\nexport const createView = (arr: TypedArray) =>\n new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word: number, shift: number) => (word << (32 - shift)) | (word >>> shift);\n\n// big-endian hardware is rare. Just in case someone still decides to run hashes:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE) throw new Error('Non little-endian hardware is not supported');\n\nconst hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n if (!u8a(bytes)) throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const len = hex.length;\n if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len);\n const array = new Uint8Array(len / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\n\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => {};\n\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n if (!u8a(data)) throw new Error(`expected Uint8Array, got ${typeof data}`);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));\n let pad = 0; // walk through each item, ensure they have proper type\n arrays.forEach((a) => {\n if (!u8a(a)) throw new Error('Uint8Array expected');\n r.set(a, pad);\n pad += a.length;\n });\n return r;\n}\n\n// For runtime check if class implements interface\nexport abstract class Hash> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF> = Hash & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\n// Check if object doens't have custom constructor (like Uint8Array/Array)\nconst isPlainObject = (obj: any) =>\n Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object;\n\ntype EmptyObj = {};\nexport function checkOpts(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && (typeof opts !== 'object' || !isPlainObject(opts)))\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\nexport type CHash = ReturnType;\n\nexport function wrapConstructor>(hashCons: () => Hash) {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function wrapConstructorWithOpts, T extends Object>(\n hashCons: (opts?: T) => Hash\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\nexport function wrapXOFConstructorWithOpts, T extends Object>(\n hashCons: (opts?: T) => HashXOF\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick\nexport type UnsignedEvent = Pick\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record => obj instanceof Object\n\nexport function validateEvent(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "export function number(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error(`Wrong positive integer: ${n}`);\n}\n\nexport function bool(b: boolean) {\n if (typeof b !== 'boolean') throw new Error(`Expected boolean, not ${b}`);\n}\n\nexport function bytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!(b instanceof Uint8Array)) throw new Error('Expected Uint8Array');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);\n}\n\ntype Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nexport function hash(hash: Hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\n\nexport function exists(instance: any, checkFinished = true) {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\nexport function output(out: any, instance: any) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\n\nconst assert = {\n number,\n bool,\n bytes,\n hash,\n exists,\n output,\n};\n\nexport default assert;\n", "import assert from './_assert.js';\nimport { Hash, createView, Input, toBytes } from './utils.js';\n\n// Polyfill for Safari 14\nfunction setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n// Base SHA2 class (RFC 6234)\nexport abstract class SHA2> extends Hash {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(\n readonly blockLen: number,\n public outputLen: number,\n readonly padOffset: number,\n readonly isLE: boolean\n ) {\n super();\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n assert.exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array) {\n assert.exists(this);\n assert.output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n}\n", "import { SHA2 } from './_sha2.js';\nimport { rotr, wrapConstructor } from './utils.js';\n\n// Choice: a ? b : c\nconst Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c);\n// Majority function, true if any two inpust is true\nconst Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c);\n\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n// prettier-ignore\nconst IV = new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = new Uint32Array(64);\nclass SHA256 extends SHA2 {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = IV[0] | 0;\n B = IV[1] | 0;\n C = IV[2] | 0;\n D = IV[3] | 0;\n E = IV[4] | 0;\n F = IV[5] | 0;\n G = IV[6] | 0;\n H = IV[7] | 0;\n\n constructor() {\n super(64, 32, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n A = 0xc1059ed8 | 0;\n B = 0x367cd507 | 0;\n C = 0x3070dd17 | 0;\n D = 0xf70e5939 | 0;\n E = 0xffc00b31 | 0;\n F = 0x68581511 | 0;\n G = 0x64f98fa7 | 0;\n H = 0xbefa4fa4 | 0;\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = wrapConstructor(() => new SHA256());\nexport const sha224 = wrapConstructor(() => new SHA224());\n", "import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport class QueueNode {\n public value: V\n public next: QueueNode | null = null\n public prev: QueueNode | null = null\n\n constructor(message: V) {\n this.value = message\n }\n}\n\nexport class Queue {\n public first: QueueNode | null\n public last: QueueNode | null\n\n constructor() {\n this.first = null\n this.last = null\n }\n\n enqueue(value: V): boolean {\n const newNode = new QueueNode(value)\n if (!this.last) {\n // list is empty\n this.first = newNode\n this.last = newNode\n } else if (this.last === this.first) {\n // list has a single element\n this.last = newNode\n this.last.prev = this.first\n this.first.next = newNode\n } else {\n // list has elements, add as last\n newNode.prev = this.last\n this.last.next = newNode\n this.last = newNode\n }\n return true\n }\n\n dequeue(): V | null {\n if (!this.first) return null\n\n if (this.first === this.last) {\n const target = this.first\n this.first = null\n this.last = null\n return target.value\n }\n\n const target = this.first\n this.first = target.next\n if (this.first) {\n this.first.prev = null // fix: clean up prev pointer\n }\n\n return target.value\n }\n}\n", "import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n generateSecretKey(): Uint8Array {\n return schnorr.utils.randomPrivateKey()\n }\n getPublicKey(secretKey: Uint8Array): string {\n return bytesToHex(schnorr.getPublicKey(secretKey))\n }\n finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n const event = t as VerifiedEvent\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n event.id = getEventHash(event)\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n event[verifiedSymbol] = true\n return event\n }\n verifyEvent(event: Event): event is VerifiedEvent {\n if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n const hash = getEventHash(event)\n if (hash !== event.id) {\n event[verifiedSymbol] = false\n return false\n }\n\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey)\n event[verifiedSymbol] = valid\n return valid\n } catch (err) {\n event[verifiedSymbol] = false\n return false\n }\n }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind(event: unknown, kind: T | Array): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n", "import { Event } from './core.ts'\nimport { isAddressableKind, isReplaceableKind } from './kinds.ts'\n\nexport type Filter = {\n ids?: string[]\n kinds?: number[]\n authors?: string[]\n since?: number\n until?: number\n limit?: number\n search?: string\n [key: `#${string}`]: string[] | undefined\n}\n\nexport function matchFilter(filter: Filter, event: Event): boolean {\n if (filter.ids && filter.ids.indexOf(event.id) === -1) {\n return false\n }\n if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) {\n return false\n }\n if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) {\n return false\n }\n\n for (let f in filter) {\n if (f[0] === '#') {\n let tagName = f.slice(1)\n let values = filter[`#${tagName}`]\n if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values!.indexOf(v) !== -1)) return false\n }\n }\n\n if (filter.since && event.created_at < filter.since) return false\n if (filter.until && event.created_at > filter.until) return false\n\n return true\n}\n\nexport function matchFilters(filters: Filter[], event: Event): boolean {\n for (let i = 0; i < filters.length; i++) {\n if (matchFilter(filters[i], event)) {\n return true\n }\n }\n return false\n}\n\nexport function mergeFilters(...filters: Filter[]): Filter {\n let result: Filter = {}\n for (let i = 0; i < filters.length; i++) {\n let filter = filters[i]\n Object.entries(filter).forEach(([property, values]) => {\n if (property === 'kinds' || property === 'ids' || property === 'authors' || property[0] === '#') {\n // @ts-ignore\n result[property] = result[property] || []\n // @ts-ignore\n for (let v = 0; v < values.length; v++) {\n // @ts-ignore\n let value = values[v]\n // @ts-ignore\n if (!result[property].includes(value)) result[property].push(value)\n }\n }\n })\n\n if (filter.limit && (!result.limit || filter.limit > result.limit)) result.limit = filter.limit\n if (filter.until && (!result.until || filter.until > result.until)) result.until = filter.until\n if (filter.since && (!result.since || filter.since < result.since)) result.since = filter.since\n }\n\n return result\n}\n\n/**\n * Calculate the intrinsic limit of a filter.\n * This function returns a positive integer, or `Infinity` if there is no intrinsic limit.\n */\nexport function getFilterLimit(filter: Filter): number {\n if (filter.ids && !filter.ids.length) return 0\n if (filter.kinds && !filter.kinds.length) return 0\n if (filter.authors && !filter.authors.length) return 0\n\n for (const [key, value] of Object.entries(filter)) {\n if (key[0] === '#' && Array.isArray(value) && !value.length) return 0\n }\n\n return Math.min(\n // The `limit` property creates an artificial limit.\n Math.max(0, filter.limit ?? Infinity),\n\n // There can only be one event per `id`.\n filter.ids?.length ?? Infinity,\n\n // Replaceable events are limited by the number of authors and kinds.\n filter.authors?.length && filter.kinds?.every(kind => isReplaceableKind(kind))\n ? filter.authors.length * filter.kinds.length\n : Infinity,\n\n // Parameterized replaceable events are limited by the number of authors, kinds, and \"d\" tags.\n filter.authors?.length && filter.kinds?.every(kind => isAddressableKind(kind)) && filter['#d']?.length\n ? filter.authors.length * filter.kinds.length * filter['#d'].length\n : Infinity,\n )\n}\n", "export function getHex64(json: string, field: string): string {\n let len = field.length + 3\n let idx = json.indexOf(`\"${field}\":`) + len\n let s = json.slice(idx).indexOf(`\"`) + idx + 1\n return json.slice(s, s + 64)\n}\n\nexport function getInt(json: string, field: string): number {\n let len = field.length\n let idx = json.indexOf(`\"${field}\":`) + len + 3\n let sliced = json.slice(idx)\n let end = Math.min(sliced.indexOf(','), sliced.indexOf('}'))\n return parseInt(sliced.slice(0, end), 10)\n}\n\nexport function getSubscriptionId(json: string): string | null {\n let idx = json.slice(0, 22).indexOf(`\"EVENT\"`)\n if (idx === -1) return null\n\n let pstart = json.slice(idx + 7 + 1).indexOf(`\"`)\n if (pstart === -1) return null\n let start = idx + 7 + 1 + pstart\n\n let pend = json.slice(start + 1, 80).indexOf(`\"`)\n if (pend === -1) return null\n let end = start + 1 + pend\n\n return json.slice(start + 1, end)\n}\n\nexport function matchEventId(json: string, id: string): boolean {\n return id === getHex64(json, 'id')\n}\n\nexport function matchEventPubkey(json: string, pubkey: string): boolean {\n return pubkey === getHex64(json, 'pubkey')\n}\n\nexport function matchEventKind(json: string, kind: number): boolean {\n return kind === getInt(json, 'kind')\n}\n", "import { EventTemplate } from './core.ts'\nimport { ClientAuth } from './kinds.ts'\n\n/**\n * creates an EventTemplate for an AUTH event to be signed.\n */\nexport function makeAuthEvent(relayURL: string, challenge: string): EventTemplate {\n return {\n kind: ClientAuth,\n created_at: Math.floor(Date.now() / 1000),\n tags: [\n ['relay', relayURL],\n ['challenge', challenge],\n ],\n content: '',\n }\n}\n", "import { verifiedSymbol, type Event, type Nostr, VerifiedEvent } from './core.ts'\n\nexport async function yieldThread() {\n return new Promise(resolve => {\n const ch = new MessageChannel()\n const handler = () => {\n // @ts-ignore (typescript thinks this property should be called `removeListener`, but in fact it's `removeEventListener`)\n ch.port1.removeEventListener('message', handler)\n resolve()\n }\n // @ts-ignore (typescript thinks this property should be called `addListener`, but in fact it's `addEventListener`)\n ch.port1.addEventListener('message', handler)\n ch.port2.postMessage(0)\n ch.port1.start()\n })\n}\n\nexport const alwaysTrue: Nostr['verifyEvent'] = (t: Event): t is VerifiedEvent => {\n t[verifiedSymbol] = true\n return true\n}\n", "/* global WebSocket */\n\nimport type { Event, EventTemplate, VerifiedEvent, Nostr, NostrEvent } from './core.ts'\nimport { matchFilters, type Filter } from './filter.ts'\nimport { getHex64, getSubscriptionId } from './fakejson.ts'\nimport { Queue, normalizeURL } from './utils.ts'\nimport { makeAuthEvent } from './nip42.ts'\nimport { yieldThread } from './helpers.ts'\n\ntype RelayWebSocket = WebSocket & {\n ping?(): void\n on?(event: 'pong', listener: () => void): any\n}\n\nexport type AbstractRelayConstructorOptions = {\n verifyEvent: Nostr['verifyEvent']\n websocketImplementation?: typeof WebSocket\n enablePing?: boolean\n}\n\nexport class SendingOnClosedConnection extends Error {\n constructor(message: string, relay: string) {\n super(`Tried to send message '${message} on a closed connection to ${relay}.`)\n this.name = 'SendingOnClosedConnection'\n }\n}\n\nexport class AbstractRelay {\n public readonly url: string\n private _connected: boolean = false\n\n public onclose: (() => void) | null = null\n public onnotice: (msg: string) => void = msg => console.debug(`NOTICE from ${this.url}: ${msg}`)\n\n public baseEoseTimeout: number = 4400\n public connectionTimeout: number = 4400\n public publishTimeout: number = 4400\n public pingFrequency: number = 20000\n public pingTimeout: number = 20000\n public openSubs: Map = new Map()\n public enablePing: boolean | undefined\n private connectionTimeoutHandle: ReturnType | undefined\n\n private connectionPromise: Promise | undefined\n private openCountRequests = new Map()\n private openEventPublishes = new Map()\n private ws: RelayWebSocket | undefined\n private incomingMessageQueue = new Queue()\n private queueRunning = false\n private challenge: string | undefined\n private authPromise: Promise | undefined\n private serial: number = 0\n private verifyEvent: Nostr['verifyEvent']\n\n private _WebSocket: typeof WebSocket\n\n constructor(url: string, opts: AbstractRelayConstructorOptions) {\n this.url = normalizeURL(url)\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation || WebSocket\n this.enablePing = opts.enablePing\n }\n\n static async connect(url: string, opts: AbstractRelayConstructorOptions): Promise {\n const relay = new AbstractRelay(url, opts)\n await relay.connect()\n return relay\n }\n\n private closeAllSubscriptions(reason: string) {\n for (let [_, sub] of this.openSubs) {\n sub.close(reason)\n }\n this.openSubs.clear()\n\n for (let [_, ep] of this.openEventPublishes) {\n ep.reject(new Error(reason))\n }\n this.openEventPublishes.clear()\n\n for (let [_, cr] of this.openCountRequests) {\n cr.reject(new Error(reason))\n }\n this.openCountRequests.clear()\n }\n\n public get connected(): boolean {\n return this._connected\n }\n\n public async connect(): Promise {\n if (this.connectionPromise) return this.connectionPromise\n\n this.challenge = undefined\n this.authPromise = undefined\n this.connectionPromise = new Promise((resolve, reject) => {\n this.connectionTimeoutHandle = setTimeout(() => {\n reject('connection timed out')\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection timed out')\n }, this.connectionTimeout)\n\n try {\n this.ws = new this._WebSocket(this.url)\n } catch (err) {\n clearTimeout(this.connectionTimeoutHandle)\n reject(err)\n return\n }\n\n this.ws.onopen = () => {\n clearTimeout(this.connectionTimeoutHandle)\n this._connected = true\n if (this.enablePing) {\n this.pingpong()\n }\n resolve()\n }\n\n this.ws.onerror = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket error')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection errored')\n }\n }\n\n this.ws.onclose = ev => {\n clearTimeout(this.connectionTimeoutHandle)\n reject((ev as any).message || 'websocket closed')\n if (this._connected) {\n this._connected = false\n this.connectionPromise = undefined\n this.onclose?.()\n this.closeAllSubscriptions('relay connection closed')\n }\n }\n\n this.ws.onmessage = this._onmessage.bind(this)\n })\n\n return this.connectionPromise\n }\n\n private async waitForPingPong() {\n return new Promise((res, err) => {\n // listen for pong\n ;(this.ws && this.ws.on && this.ws.on('pong', () => res(true))) || err(\"ws can't listen for pong\")\n // send a ping\n this.ws && this.ws.ping && this.ws.ping()\n })\n }\n\n private async waitForDummyReq() {\n return new Promise((resolve, _) => {\n // make a dummy request with expected empty eose reply\n // [\"REQ\", \"_\", {\"ids\":[\"aaaa...aaaa\"]}]\n const sub = this.subscribe([{ ids: ['a'.repeat(64)] }], {\n oneose: () => {\n sub.close()\n resolve(true)\n },\n eoseTimeout: this.pingTimeout + 1000,\n })\n })\n }\n\n // nodejs requires this magic here to ensure connections are closed when internet goes off and stuff\n // in browsers it's done automatically. see https://github.com/nbd-wtf/nostr-tools/issues/491\n private async pingpong() {\n // if the websocket is connected\n if (this.ws?.readyState === 1) {\n // wait for either a ping-pong reply or a timeout\n const result = await Promise.any([\n // browsers don't have ping so use a dummy req\n this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(),\n new Promise(res => setTimeout(() => res(false), this.pingTimeout)),\n ])\n if (result) {\n // schedule another pingpong\n setTimeout(() => this.pingpong(), this.pingFrequency)\n } else {\n // pingpong closing socket\n this.closeAllSubscriptions('pingpong timed out')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n }\n }\n\n private async runQueue() {\n this.queueRunning = true\n while (true) {\n if (false === this.handleNext()) {\n break\n }\n await yieldThread()\n }\n this.queueRunning = false\n }\n\n private handleNext(): undefined | false {\n const json = this.incomingMessageQueue.dequeue()\n if (!json) {\n return false\n }\n\n const subid = getSubscriptionId(json)\n if (subid) {\n const so = this.openSubs.get(subid as string)\n if (!so) {\n // this is an EVENT message, but for a subscription we don't have, so just stop here\n return\n }\n\n // this will be called only when this message is a EVENT message for a subscription we have\n // we do this before parsing the JSON to not have to do that for duplicate events\n // since JSON parsing is slow\n const id = getHex64(json, 'id')\n const alreadyHave = so.alreadyHaveEvent?.(id)\n\n // notify any interested client that the relay has this event\n // (do this after alreadyHaveEvent() because the client may rely on this to answer that)\n so.receivedEvent?.(this, id)\n\n if (alreadyHave) {\n // if we had already seen this event we can just stop here\n return\n }\n }\n\n try {\n let data = JSON.parse(json)\n // we won't do any checks against the data since all failures (i.e. invalid messages from relays)\n // will naturally be caught by the encompassing try..catch block\n\n switch (data[0]) {\n case 'EVENT': {\n const so = this.openSubs.get(data[1] as string) as Subscription\n const event = data[2] as NostrEvent\n if (this.verifyEvent(event) && matchFilters(so.filters, event)) {\n so.onevent(event)\n }\n return\n }\n case 'COUNT': {\n const id: string = data[1]\n const payload = data[2] as { count: number }\n const cr = this.openCountRequests.get(id) as CountResolver\n if (cr) {\n cr.resolve(payload.count)\n this.openCountRequests.delete(id)\n }\n return\n }\n case 'EOSE': {\n const so = this.openSubs.get(data[1] as string)\n if (!so) return\n so.receivedEose()\n return\n }\n case 'OK': {\n const id: string = data[1]\n const ok: boolean = data[2]\n const reason: string = data[3]\n const ep = this.openEventPublishes.get(id) as EventPublishResolver\n if (ep) {\n clearTimeout(ep.timeout)\n if (ok) ep.resolve(reason)\n else ep.reject(new Error(reason))\n this.openEventPublishes.delete(id)\n }\n return\n }\n case 'CLOSED': {\n const id: string = data[1]\n const so = this.openSubs.get(id)\n if (!so) return\n so.closed = true\n so.close(data[2] as string)\n return\n }\n case 'NOTICE':\n this.onnotice(data[1] as string)\n return\n case 'AUTH': {\n this.challenge = data[1] as string\n return\n }\n }\n } catch (err) {\n return\n }\n }\n\n public async send(message: string) {\n if (!this.connectionPromise) throw new SendingOnClosedConnection(message, this.url)\n\n this.connectionPromise.then(() => {\n this.ws?.send(message)\n })\n }\n\n public async auth(signAuthEvent: (evt: EventTemplate) => Promise): Promise {\n const challenge = this.challenge\n if (!challenge) throw new Error(\"can't perform auth, no challenge was received\")\n if (this.authPromise) return this.authPromise\n\n this.authPromise = new Promise(async (resolve, reject) => {\n try {\n let evt = await signAuthEvent(makeAuthEvent(this.url, challenge))\n let timeout = setTimeout(() => {\n let ep = this.openEventPublishes.get(evt.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('auth timed out'))\n this.openEventPublishes.delete(evt.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(evt.id, { resolve, reject, timeout })\n this.send('[\"AUTH\",' + JSON.stringify(evt) + ']')\n } catch (err) {\n console.warn('subscribe auth function failed:', err)\n }\n })\n return this.authPromise\n }\n\n public async publish(event: Event): Promise {\n const ret = new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n const ep = this.openEventPublishes.get(event.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('publish timed out'))\n this.openEventPublishes.delete(event.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(event.id, { resolve, reject, timeout })\n })\n this.send('[\"EVENT\",' + JSON.stringify(event) + ']')\n return ret\n }\n\n public async count(filters: Filter[], params: { id?: string | null }): Promise {\n this.serial++\n const id = params?.id || 'count:' + this.serial\n const ret = new Promise((resolve, reject) => {\n this.openCountRequests.set(id, { resolve, reject })\n })\n this.send('[\"COUNT\",\"' + id + '\",' + JSON.stringify(filters).substring(1))\n return ret\n }\n\n public subscribe(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n const subscription = this.prepareSubscription(filters, params)\n subscription.fire()\n return subscription\n }\n\n public prepareSubscription(\n filters: Filter[],\n params: Partial & { label?: string; id?: string },\n ): Subscription {\n this.serial++\n const id = params.id || (params.label ? params.label + ':' : 'sub:') + this.serial\n const subscription = new Subscription(this, id, filters, params)\n this.openSubs.set(id, subscription)\n return subscription\n }\n\n public close() {\n this.closeAllSubscriptions('relay connection closed by us')\n this._connected = false\n this.ws?.close()\n this.onclose?.()\n }\n\n // this is the function assigned to this.ws.onmessage\n // it's exposed for testing and debugging purposes\n public _onmessage(ev: MessageEvent) {\n this.incomingMessageQueue.enqueue(ev.data as string)\n if (!this.queueRunning) {\n this.runQueue()\n }\n }\n}\n\nexport class Subscription {\n public readonly relay: AbstractRelay\n public readonly id: string\n\n public closed: boolean = false\n public eosed: boolean = false\n public filters: Filter[]\n public alreadyHaveEvent: ((id: string) => boolean) | undefined\n public receivedEvent: ((relay: AbstractRelay, id: string) => void) | undefined\n\n public onevent: (evt: Event) => void\n public oneose: (() => void) | undefined\n public onclose: ((reason: string) => void) | undefined\n\n public eoseTimeout: number\n private eoseTimeoutHandle: ReturnType | undefined\n\n constructor(relay: AbstractRelay, id: string, filters: Filter[], params: SubscriptionParams) {\n this.relay = relay\n this.filters = filters\n this.id = id\n this.alreadyHaveEvent = params.alreadyHaveEvent\n this.receivedEvent = params.receivedEvent\n this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout\n\n this.oneose = params.oneose\n this.onclose = params.onclose\n this.onevent =\n params.onevent ||\n (event => {\n console.warn(\n `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,\n event,\n )\n })\n }\n\n public fire() {\n this.relay.send('[\"REQ\",\"' + this.id + '\",' + JSON.stringify(this.filters).substring(1))\n\n // only now we start counting the eoseTimeout\n this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout)\n }\n\n public receivedEose() {\n if (this.eosed) return\n clearTimeout(this.eoseTimeoutHandle)\n this.eosed = true\n this.oneose?.()\n }\n\n public close(reason: string = 'closed by caller') {\n if (!this.closed && this.relay.connected) {\n // if the connection was closed by the user calling .close() we will send a CLOSE message\n // otherwise this._open will be already set to false so we will skip this\n try {\n this.relay.send('[\"CLOSE\",' + JSON.stringify(this.id) + ']')\n } catch (err) {\n if (err instanceof SendingOnClosedConnection) {\n /* doesn't matter, it's ok */\n } else {\n throw err\n }\n }\n this.closed = true\n }\n this.relay.openSubs.delete(this.id)\n this.onclose?.(reason)\n }\n}\n\nexport type SubscriptionParams = {\n onevent?: (evt: Event) => void\n oneose?: () => void\n onclose?: (reason: string) => void\n alreadyHaveEvent?: (id: string) => boolean\n receivedEvent?: (relay: AbstractRelay, id: string) => void\n eoseTimeout?: number\n}\n\nexport type CountResolver = {\n resolve: (count: number) => void\n reject: (err: Error) => void\n}\n\nexport type EventPublishResolver = {\n resolve: (reason: string) => void\n reject: (err: Error) => void\n timeout: ReturnType\n}\n", "/* global WebSocket */\n\nimport { verifyEvent } from './pure.ts'\nimport { AbstractRelay } from './abstract-relay.ts'\n\nvar _WebSocket: typeof WebSocket\n\ntry {\n _WebSocket = WebSocket\n} catch {}\n\nexport function useWebSocketImplementation(websocketImplementation: any) {\n _WebSocket = websocketImplementation\n}\n\nexport class Relay extends AbstractRelay {\n constructor(url: string) {\n super(url, { verifyEvent, websocketImplementation: _WebSocket })\n }\n\n static async connect(url: string): Promise {\n const relay = new Relay(url)\n await relay.connect()\n return relay\n }\n}\n\nexport type RelayRecord = Record\n\nexport * from './abstract-relay.ts'\n", "/* global WebSocket */\n\nimport {\n AbstractRelay as AbstractRelay,\n SubscriptionParams,\n Subscription,\n type AbstractRelayConstructorOptions,\n} from './abstract-relay.ts'\nimport { normalizeURL } from './utils.ts'\n\nimport type { Event, EventTemplate, Nostr, VerifiedEvent } from './core.ts'\nimport { type Filter } from './filter.ts'\nimport { alwaysTrue } from './helpers.ts'\n\nexport type SubCloser = { close: (reason?: string) => void }\n\nexport type AbstractPoolConstructorOptions = AbstractRelayConstructorOptions & {}\n\nexport type SubscribeManyParams = Omit & {\n maxWait?: number\n onclose?: (reasons: string[]) => void\n onauth?: (event: EventTemplate) => Promise\n // Deprecated: use onauth instead\n doauth?: (event: EventTemplate) => Promise\n id?: string\n label?: string\n}\n\nexport class AbstractSimplePool {\n protected relays: Map = new Map()\n public seenOn: Map> = new Map()\n public trackRelays: boolean = false\n\n public verifyEvent: Nostr['verifyEvent']\n public enablePing: boolean | undefined\n public trustedRelayURLs: Set = new Set()\n\n private _WebSocket?: typeof WebSocket\n\n constructor(opts: AbstractPoolConstructorOptions) {\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation\n this.enablePing = opts.enablePing\n }\n\n async ensureRelay(url: string, params?: { connectionTimeout?: number }): Promise {\n url = normalizeURL(url)\n\n let relay = this.relays.get(url)\n if (!relay) {\n relay = new AbstractRelay(url, {\n verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent,\n websocketImplementation: this._WebSocket,\n enablePing: this.enablePing,\n })\n relay.onclose = () => {\n this.relays.delete(url)\n }\n if (params?.connectionTimeout) relay.connectionTimeout = params.connectionTimeout\n this.relays.set(url, relay)\n }\n await relay.connect()\n\n return relay\n }\n\n close(relays: string[]) {\n relays.map(normalizeURL).forEach(url => {\n this.relays.get(url)?.close()\n this.relays.delete(url)\n })\n }\n\n subscribe(relays: string[], filter: Filter, params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const request: { url: string; filter: Filter }[] = []\n for (let i = 0; i < relays.length; i++) {\n const url = normalizeURL(relays[i])\n if (!request.find(r => r.url === url)) {\n request.push({ url, filter })\n }\n }\n\n return this.subscribeMap(request, params)\n }\n\n subscribeMany(relays: string[], filters: Filter[], params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const request: { url: string; filter: Filter }[] = []\n const uniqUrls: string[] = []\n for (let i = 0; i < relays.length; i++) {\n const url = normalizeURL(relays[i])\n if (uniqUrls.indexOf(url) === -1) {\n for (let f = 0; f < filters.length; f++) {\n request.push({ url, filter: filters[f] })\n }\n }\n }\n\n return this.subscribeMap(request, params)\n }\n\n subscribeMap(requests: { url: string; filter: Filter }[], params: SubscribeManyParams): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n if (this.trackRelays) {\n params.receivedEvent = (relay: AbstractRelay, id: string) => {\n let set = this.seenOn.get(id)\n if (!set) {\n set = new Set()\n this.seenOn.set(id, set)\n }\n set.add(relay)\n }\n }\n\n const _knownIds = new Set()\n const subs: Subscription[] = []\n\n // batch all EOSEs into a single\n const eosesReceived: boolean[] = []\n let handleEose = (i: number) => {\n if (eosesReceived[i]) return // do not act twice for the same relay\n eosesReceived[i] = true\n if (eosesReceived.filter(a => a).length === requests.length) {\n params.oneose?.()\n handleEose = () => {}\n }\n }\n // batch all closes into a single\n const closesReceived: string[] = []\n let handleClose = (i: number, reason: string) => {\n if (closesReceived[i]) return // do not act twice for the same relay\n handleEose(i)\n closesReceived[i] = reason\n if (closesReceived.filter(a => a).length === requests.length) {\n params.onclose?.(closesReceived)\n handleClose = () => {}\n }\n }\n\n const localAlreadyHaveEventHandler = (id: string) => {\n if (params.alreadyHaveEvent?.(id)) {\n return true\n }\n const have = _knownIds.has(id)\n _knownIds.add(id)\n return have\n }\n\n // open a subscription in all given relays\n const allOpened = Promise.all(\n requests.map(async ({ url, filter }, i) => {\n let relay: AbstractRelay\n try {\n relay = await this.ensureRelay(url, {\n connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1000) : undefined,\n })\n } catch (err) {\n handleClose(i, (err as any)?.message || String(err))\n return\n }\n\n let subscription = relay.subscribe([filter], {\n ...params,\n oneose: () => handleEose(i),\n onclose: reason => {\n if (reason.startsWith('auth-required: ') && params.onauth) {\n relay\n .auth(params.onauth)\n .then(() => {\n relay.subscribe([filter], {\n ...params,\n oneose: () => handleEose(i),\n onclose: reason => {\n handleClose(i, reason) // the second time we won't try to auth anymore\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait,\n })\n })\n .catch(err => {\n handleClose(i, `auth was required and attempted, but failed with: ${err}`)\n })\n } else {\n handleClose(i, reason)\n }\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait,\n })\n\n subs.push(subscription)\n }),\n )\n\n return {\n async close(reason?: string) {\n await allOpened\n subs.forEach(sub => {\n sub.close(reason)\n })\n },\n }\n }\n\n subscribeEose(\n relays: string[],\n filter: Filter,\n params: Pick,\n ): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const subcloser = this.subscribe(relays, filter, {\n ...params,\n oneose() {\n subcloser.close('closed automatically on eose')\n },\n })\n return subcloser\n }\n\n subscribeManyEose(\n relays: string[],\n filters: Filter[],\n params: Pick,\n ): SubCloser {\n params.onauth = params.onauth || params.doauth\n\n const subcloser = this.subscribeMany(relays, filters, {\n ...params,\n oneose() {\n subcloser.close('closed automatically on eose')\n },\n })\n return subcloser\n }\n\n async querySync(\n relays: string[],\n filter: Filter,\n params?: Pick,\n ): Promise {\n return new Promise(async resolve => {\n const events: Event[] = []\n this.subscribeEose(relays, filter, {\n ...params,\n onevent(event: Event) {\n events.push(event)\n },\n onclose(_: string[]) {\n resolve(events)\n },\n })\n })\n }\n\n async get(\n relays: string[],\n filter: Filter,\n params?: Pick,\n ): Promise {\n filter.limit = 1\n const events = await this.querySync(relays, filter, params)\n events.sort((a, b) => b.created_at - a.created_at)\n return events[0] || null\n }\n\n publish(\n relays: string[],\n event: Event,\n options?: { onauth?: (evt: EventTemplate) => Promise },\n ): Promise[] {\n return relays.map(normalizeURL).map(async (url, i, arr) => {\n if (arr.indexOf(url) !== i) {\n // duplicate\n return Promise.reject('duplicate url')\n }\n\n let r = await this.ensureRelay(url)\n return r\n .publish(event)\n .catch(async err => {\n if (err instanceof Error && err.message.startsWith('auth-required: ') && options?.onauth) {\n await r.auth(options.onauth)\n return r.publish(event) // retry\n }\n throw err\n })\n .then(reason => {\n if (this.trackRelays) {\n let set = this.seenOn.get(event.id)\n if (!set) {\n set = new Set()\n this.seenOn.set(event.id, set)\n }\n set.add(r)\n }\n return reason\n })\n })\n }\n\n listConnectionStatus(): Map {\n const map = new Map()\n this.relays.forEach((relay, url) => map.set(url, relay.connected))\n\n return map\n }\n\n destroy(): void {\n this.relays.forEach(conn => conn.close())\n this.relays = new Map()\n }\n}\n", "/* global WebSocket */\n\nimport { verifyEvent } from './pure.ts'\nimport { AbstractSimplePool } from './abstract-pool.ts'\n\nvar _WebSocket: typeof WebSocket\n\ntry {\n _WebSocket = WebSocket\n} catch {}\n\nexport function useWebSocketImplementation(websocketImplementation: any) {\n _WebSocket = websocketImplementation\n}\n\nexport class SimplePool extends AbstractSimplePool {\n constructor(options?: { enablePing?: boolean }) {\n super({ verifyEvent, websocketImplementation: _WebSocket, ...options })\n }\n}\n\nexport * from './abstract-pool.ts'\n", "import { bytesToHex, concatBytes, hexToBytes } from '@noble/hashes/utils'\nimport { bech32 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport type NProfile = `nprofile1${string}`\nexport type NEvent = `nevent1${string}`\nexport type NAddr = `naddr1${string}`\nexport type NSec = `nsec1${string}`\nexport type NPub = `npub1${string}`\nexport type Note = `note1${string}`\nexport type Ncryptsec = `ncryptsec1${string}`\n\nexport const NostrTypeGuard = {\n isNProfile: (value?: string | null): value is NProfile => /^nprofile1[a-z\\d]+$/.test(value || ''),\n isNEvent: (value?: string | null): value is NEvent => /^nevent1[a-z\\d]+$/.test(value || ''),\n isNAddr: (value?: string | null): value is NAddr => /^naddr1[a-z\\d]+$/.test(value || ''),\n isNSec: (value?: string | null): value is NSec => /^nsec1[a-z\\d]{58}$/.test(value || ''),\n isNPub: (value?: string | null): value is NPub => /^npub1[a-z\\d]{58}$/.test(value || ''),\n isNote: (value?: string | null): value is Note => /^note1[a-z\\d]+$/.test(value || ''),\n isNcryptsec: (value?: string | null): value is Ncryptsec => /^ncryptsec1[a-z\\d]+$/.test(value || ''),\n}\n\nexport const Bech32MaxSize = 5000\n\n/**\n * Bech32 regex.\n * @see https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32\n */\nexport const BECH32_REGEX = /[\\x21-\\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/\n\nfunction integerToUint8Array(number: number) {\n // Create a Uint8Array with enough space to hold a 32-bit integer (4 bytes).\n const uint8Array = new Uint8Array(4)\n\n // Use bitwise operations to extract the bytes.\n uint8Array[0] = (number >> 24) & 0xff // Most significant byte (MSB)\n uint8Array[1] = (number >> 16) & 0xff\n uint8Array[2] = (number >> 8) & 0xff\n uint8Array[3] = number & 0xff // Least significant byte (LSB)\n\n return uint8Array\n}\n\nexport type ProfilePointer = {\n pubkey: string // hex\n relays?: string[]\n}\n\nexport type EventPointer = {\n id: string // hex\n relays?: string[]\n author?: string\n kind?: number\n}\n\nexport type AddressPointer = {\n identifier: string\n pubkey: string\n kind: number\n relays?: string[]\n}\n\nexport function decodeNostrURI(nip19code: string): ReturnType | { type: 'invalid'; data: null } {\n try {\n if (nip19code.startsWith('nostr:')) nip19code = nip19code.substring(6)\n return decode(nip19code)\n } catch (_err) {\n return { type: 'invalid', data: null }\n }\n}\n\nexport type DecodedNevent = {\n type: 'nevent'\n data: EventPointer\n}\n\nexport type DecodedNprofile = {\n type: 'nprofile'\n data: ProfilePointer\n}\n\nexport type DecodedNaddr = {\n type: 'naddr'\n data: AddressPointer\n}\n\nexport type DecodedNsec = {\n type: 'nsec'\n data: Uint8Array\n}\n\nexport type DecodedNpub = {\n type: 'npub'\n data: string\n}\n\nexport type DecodedNote = {\n type: 'note'\n data: string\n}\n\nexport type DecodedResult = DecodedNevent | DecodedNprofile | DecodedNaddr | DecodedNpub | DecodedNsec | DecodedNote\n\nexport function decode(nip19: NEvent): DecodedNevent\nexport function decode(nip19: NProfile): DecodedNprofile\nexport function decode(nip19: NAddr): DecodedNaddr\nexport function decode(nip19: NSec): DecodedNsec\nexport function decode(nip19: NPub): DecodedNpub\nexport function decode(nip19: Note): DecodedNote\nexport function decode(code: string): DecodedResult\nexport function decode(code: string): DecodedResult {\n let { prefix, words } = bech32.decode(code, Bech32MaxSize)\n let data = new Uint8Array(bech32.fromWords(words))\n\n switch (prefix) {\n case 'nprofile': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nprofile')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n\n return {\n type: 'nprofile',\n data: {\n pubkey: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n case 'nevent': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nevent')\n if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n if (tlv[2] && tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (tlv[3] && tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'nevent',\n data: {\n id: bytesToHex(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n author: tlv[2]?.[0] ? bytesToHex(tlv[2][0]) : undefined,\n kind: tlv[3]?.[0] ? parseInt(bytesToHex(tlv[3][0]), 16) : undefined,\n },\n }\n }\n\n case 'naddr': {\n let tlv = parseTLV(data)\n if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for naddr')\n if (!tlv[2]?.[0]) throw new Error('missing TLV 2 for naddr')\n if (tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n if (!tlv[3]?.[0]) throw new Error('missing TLV 3 for naddr')\n if (tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n return {\n type: 'naddr',\n data: {\n identifier: utf8Decoder.decode(tlv[0][0]),\n pubkey: bytesToHex(tlv[2][0]),\n kind: parseInt(bytesToHex(tlv[3][0]), 16),\n relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n },\n }\n }\n\n case 'nsec':\n return { type: prefix, data }\n\n case 'npub':\n case 'note':\n return { type: prefix, data: bytesToHex(data) }\n\n default:\n throw new Error(`unknown prefix ${prefix}`)\n }\n}\n\ntype TLV = { [t: number]: Uint8Array[] }\n\nfunction parseTLV(data: Uint8Array): TLV {\n let result: TLV = {}\n let rest = data\n while (rest.length > 0) {\n let t = rest[0]\n let l = rest[1]\n let v = rest.slice(2, 2 + l)\n rest = rest.slice(2 + l)\n if (v.length < l) throw new Error(`not enough data to read on TLV ${t}`)\n result[t] = result[t] || []\n result[t].push(v)\n }\n return result\n}\n\nexport function nsecEncode(key: Uint8Array): NSec {\n return encodeBytes('nsec', key)\n}\n\nexport function npubEncode(hex: string): NPub {\n return encodeBytes('npub', hexToBytes(hex))\n}\n\nexport function noteEncode(hex: string): Note {\n return encodeBytes('note', hexToBytes(hex))\n}\n\nfunction encodeBech32(prefix: Prefix, data: Uint8Array): `${Prefix}1${string}` {\n let words = bech32.toWords(data)\n return bech32.encode(prefix, words, Bech32MaxSize) as `${Prefix}1${string}`\n}\n\nexport function encodeBytes(prefix: Prefix, bytes: Uint8Array): `${Prefix}1${string}` {\n return encodeBech32(prefix, bytes)\n}\n\nexport function nprofileEncode(profile: ProfilePointer): NProfile {\n let data = encodeTLV({\n 0: [hexToBytes(profile.pubkey)],\n 1: (profile.relays || []).map(url => utf8Encoder.encode(url)),\n })\n return encodeBech32('nprofile', data)\n}\n\nexport function neventEncode(event: EventPointer): NEvent {\n let kindArray\n if (event.kind !== undefined) {\n kindArray = integerToUint8Array(event.kind)\n }\n\n let data = encodeTLV({\n 0: [hexToBytes(event.id)],\n 1: (event.relays || []).map(url => utf8Encoder.encode(url)),\n 2: event.author ? [hexToBytes(event.author)] : [],\n 3: kindArray ? [new Uint8Array(kindArray)] : [],\n })\n\n return encodeBech32('nevent', data)\n}\n\nexport function naddrEncode(addr: AddressPointer): NAddr {\n let kind = new ArrayBuffer(4)\n new DataView(kind).setUint32(0, addr.kind, false)\n\n let data = encodeTLV({\n 0: [utf8Encoder.encode(addr.identifier)],\n 1: (addr.relays || []).map(url => utf8Encoder.encode(url)),\n 2: [hexToBytes(addr.pubkey)],\n 3: [new Uint8Array(kind)],\n })\n return encodeBech32('naddr', data)\n}\n\nfunction encodeTLV(tlv: TLV): Uint8Array {\n let entries: Uint8Array[] = []\n\n Object.entries(tlv)\n .reverse()\n .forEach(([t, vs]) => {\n vs.forEach(v => {\n let entry = new Uint8Array(v.length + 2)\n entry.set([parseInt(t)], 0)\n entry.set([v.length], 1)\n entry.set(v, 2)\n entries.push(entry)\n })\n })\n\n return concatBytes(...entries)\n}\n", "/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nexport function assertNumber(n) {\n if (!Number.isSafeInteger(n))\n throw new Error(`Wrong integer: ${n}`);\n}\nfunction chain(...args) {\n const wrap = (a, b) => (c) => a(b(c));\n const encode = Array.from(args)\n .reverse()\n .reduce((acc, i) => (acc ? wrap(acc, i.encode) : i.encode), undefined);\n const decode = args.reduce((acc, i) => (acc ? wrap(acc, i.decode) : i.decode), undefined);\n return { encode, decode };\n}\nfunction alphabet(alphabet) {\n return {\n encode: (digits) => {\n if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))\n throw new Error('alphabet.encode input should be an array of numbers');\n return digits.map((i) => {\n assertNumber(i);\n if (i < 0 || i >= alphabet.length)\n throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet.length})`);\n return alphabet[i];\n });\n },\n decode: (input) => {\n if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string'))\n throw new Error('alphabet.decode input should be array of strings');\n return input.map((letter) => {\n if (typeof letter !== 'string')\n throw new Error(`alphabet.decode: not string element=${letter}`);\n const index = alphabet.indexOf(letter);\n if (index === -1)\n throw new Error(`Unknown letter: \"${letter}\". Allowed: ${alphabet}`);\n return index;\n });\n },\n };\n}\nfunction join(separator = '') {\n if (typeof separator !== 'string')\n throw new Error('join separator should be string');\n return {\n encode: (from) => {\n if (!Array.isArray(from) || (from.length && typeof from[0] !== 'string'))\n throw new Error('join.encode input should be array of strings');\n for (let i of from)\n if (typeof i !== 'string')\n throw new Error(`join.encode: non-string input=${i}`);\n return from.join(separator);\n },\n decode: (to) => {\n if (typeof to !== 'string')\n throw new Error('join.decode input should be string');\n return to.split(separator);\n },\n };\n}\nfunction padding(bits, chr = '=') {\n assertNumber(bits);\n if (typeof chr !== 'string')\n throw new Error('padding chr should be string');\n return {\n encode(data) {\n if (!Array.isArray(data) || (data.length && typeof data[0] !== 'string'))\n throw new Error('padding.encode input should be array of strings');\n for (let i of data)\n if (typeof i !== 'string')\n throw new Error(`padding.encode: non-string input=${i}`);\n while ((data.length * bits) % 8)\n data.push(chr);\n return data;\n },\n decode(input) {\n if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string'))\n throw new Error('padding.encode input should be array of strings');\n for (let i of input)\n if (typeof i !== 'string')\n throw new Error(`padding.decode: non-string input=${i}`);\n let end = input.length;\n if ((end * bits) % 8)\n throw new Error('Invalid padding: string should have whole number of bytes');\n for (; end > 0 && input[end - 1] === chr; end--) {\n if (!(((end - 1) * bits) % 8))\n throw new Error('Invalid padding: string has too much padding');\n }\n return input.slice(0, end);\n },\n };\n}\nfunction normalize(fn) {\n if (typeof fn !== 'function')\n throw new Error('normalize fn should be function');\n return { encode: (from) => from, decode: (to) => fn(to) };\n}\nfunction convertRadix(data, from, to) {\n if (from < 2)\n throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`);\n if (to < 2)\n throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`);\n if (!Array.isArray(data))\n throw new Error('convertRadix: data should be array');\n if (!data.length)\n return [];\n let pos = 0;\n const res = [];\n const digits = Array.from(data);\n digits.forEach((d) => {\n assertNumber(d);\n if (d < 0 || d >= from)\n throw new Error(`Wrong integer: ${d}`);\n });\n while (true) {\n let carry = 0;\n let done = true;\n for (let i = pos; i < digits.length; i++) {\n const digit = digits[i];\n const digitBase = from * carry + digit;\n if (!Number.isSafeInteger(digitBase) ||\n (from * carry) / from !== carry ||\n digitBase - digit !== from * carry) {\n throw new Error('convertRadix: carry overflow');\n }\n carry = digitBase % to;\n digits[i] = Math.floor(digitBase / to);\n if (!Number.isSafeInteger(digits[i]) || digits[i] * to + carry !== digitBase)\n throw new Error('convertRadix: carry overflow');\n if (!done)\n continue;\n else if (!digits[i])\n pos = i;\n else\n done = false;\n }\n res.push(carry);\n if (done)\n break;\n }\n for (let i = 0; i < data.length - 1 && data[i] === 0; i++)\n res.push(0);\n return res.reverse();\n}\nconst gcd = (a, b) => (!b ? a : gcd(b, a % b));\nconst radix2carry = (from, to) => from + (to - gcd(from, to));\nfunction convertRadix2(data, from, to, padding) {\n if (!Array.isArray(data))\n throw new Error('convertRadix2: data should be array');\n if (from <= 0 || from > 32)\n throw new Error(`convertRadix2: wrong from=${from}`);\n if (to <= 0 || to > 32)\n throw new Error(`convertRadix2: wrong to=${to}`);\n if (radix2carry(from, to) > 32) {\n throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`);\n }\n let carry = 0;\n let pos = 0;\n const mask = 2 ** to - 1;\n const res = [];\n for (const n of data) {\n assertNumber(n);\n if (n >= 2 ** from)\n throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);\n carry = (carry << from) | n;\n if (pos + from > 32)\n throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);\n pos += from;\n for (; pos >= to; pos -= to)\n res.push(((carry >> (pos - to)) & mask) >>> 0);\n carry &= 2 ** pos - 1;\n }\n carry = (carry << (to - pos)) & mask;\n if (!padding && pos >= from)\n throw new Error('Excess padding');\n if (!padding && carry)\n throw new Error(`Non-zero padding: ${carry}`);\n if (padding && pos > 0)\n res.push(carry >>> 0);\n return res;\n}\nfunction radix(num) {\n assertNumber(num);\n return {\n encode: (bytes) => {\n if (!(bytes instanceof Uint8Array))\n throw new Error('radix.encode input should be Uint8Array');\n return convertRadix(Array.from(bytes), 2 ** 8, num);\n },\n decode: (digits) => {\n if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))\n throw new Error('radix.decode input should be array of strings');\n return Uint8Array.from(convertRadix(digits, num, 2 ** 8));\n },\n };\n}\nfunction radix2(bits, revPadding = false) {\n assertNumber(bits);\n if (bits <= 0 || bits > 32)\n throw new Error('radix2: bits should be in (0..32]');\n if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)\n throw new Error('radix2: carry overflow');\n return {\n encode: (bytes) => {\n if (!(bytes instanceof Uint8Array))\n throw new Error('radix2.encode input should be Uint8Array');\n return convertRadix2(Array.from(bytes), 8, bits, !revPadding);\n },\n decode: (digits) => {\n if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))\n throw new Error('radix2.decode input should be array of strings');\n return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));\n },\n };\n}\nfunction unsafeWrapper(fn) {\n if (typeof fn !== 'function')\n throw new Error('unsafeWrapper fn should be function');\n return function (...args) {\n try {\n return fn.apply(null, args);\n }\n catch (e) { }\n };\n}\nfunction checksum(len, fn) {\n assertNumber(len);\n if (typeof fn !== 'function')\n throw new Error('checksum fn should be function');\n return {\n encode(data) {\n if (!(data instanceof Uint8Array))\n throw new Error('checksum.encode: input should be Uint8Array');\n const checksum = fn(data).slice(0, len);\n const res = new Uint8Array(data.length + len);\n res.set(data);\n res.set(checksum, data.length);\n return res;\n },\n decode(data) {\n if (!(data instanceof Uint8Array))\n throw new Error('checksum.decode: input should be Uint8Array');\n const payload = data.slice(0, -len);\n const newChecksum = fn(payload).slice(0, len);\n const oldChecksum = data.slice(-len);\n for (let i = 0; i < len; i++)\n if (newChecksum[i] !== oldChecksum[i])\n throw new Error('Invalid checksum');\n return payload;\n },\n };\n}\nexport const utils = { alphabet, chain, checksum, radix, radix2, join, padding };\nexport const base16 = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));\nexport const base32 = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join(''));\nexport const base32hex = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join(''));\nexport const base32crockford = chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')));\nexport const base64 = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join(''));\nexport const base64url = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join(''));\nconst genBase58 = (abc) => chain(radix(58), alphabet(abc), join(''));\nexport const base58 = genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');\nexport const base58flickr = genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ');\nexport const base58xrp = genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz');\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\nexport const base58xmr = {\n encode(data) {\n let res = '';\n for (let i = 0; i < data.length; i += 8) {\n const block = data.subarray(i, i + 8);\n res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1');\n }\n return res;\n },\n decode(str) {\n let res = [];\n for (let i = 0; i < str.length; i += 11) {\n const slice = str.slice(i, i + 11);\n const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);\n const block = base58.decode(slice);\n for (let j = 0; j < block.length - blockLen; j++) {\n if (block[j] !== 0)\n throw new Error('base58xmr: wrong padding');\n }\n res = res.concat(Array.from(block.slice(block.length - blockLen)));\n }\n return Uint8Array.from(res);\n },\n};\nexport const base58check = (sha256) => chain(checksum(4, (data) => sha256(sha256(data))), base58);\nconst BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join(''));\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\nfunction bech32Polymod(pre) {\n const b = pre >> 25;\n let chk = (pre & 0x1ffffff) << 5;\n for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n if (((b >> i) & 1) === 1)\n chk ^= POLYMOD_GENERATORS[i];\n }\n return chk;\n}\nfunction bechChecksum(prefix, words, encodingConst = 1) {\n const len = prefix.length;\n let chk = 1;\n for (let i = 0; i < len; i++) {\n const c = prefix.charCodeAt(i);\n if (c < 33 || c > 126)\n throw new Error(`Invalid prefix (${prefix})`);\n chk = bech32Polymod(chk) ^ (c >> 5);\n }\n chk = bech32Polymod(chk);\n for (let i = 0; i < len; i++)\n chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (let v of words)\n chk = bech32Polymod(chk) ^ v;\n for (let i = 0; i < 6; i++)\n chk = bech32Polymod(chk);\n chk ^= encodingConst;\n return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false));\n}\nfunction genBech32(encoding) {\n const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n const _words = radix2(5);\n const fromWords = _words.decode;\n const toWords = _words.encode;\n const fromWordsUnsafe = unsafeWrapper(fromWords);\n function encode(prefix, words, limit = 90) {\n if (typeof prefix !== 'string')\n throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`);\n if (!Array.isArray(words) || (words.length && typeof words[0] !== 'number'))\n throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`);\n const actualLength = prefix.length + 7 + words.length;\n if (limit !== false && actualLength > limit)\n throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n prefix = prefix.toLowerCase();\n return `${prefix}1${BECH_ALPHABET.encode(words)}${bechChecksum(prefix, words, ENCODING_CONST)}`;\n }\n function decode(str, limit = 90) {\n if (typeof str !== 'string')\n throw new Error(`bech32.decode input should be string, not ${typeof str}`);\n if (str.length < 8 || (limit !== false && str.length > limit))\n throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`);\n const lowered = str.toLowerCase();\n if (str !== lowered && str !== str.toUpperCase())\n throw new Error(`String must be lowercase or uppercase`);\n str = lowered;\n const sepIndex = str.lastIndexOf('1');\n if (sepIndex === 0 || sepIndex === -1)\n throw new Error(`Letter \"1\" must be present between prefix and data only`);\n const prefix = str.slice(0, sepIndex);\n const _words = str.slice(sepIndex + 1);\n if (_words.length < 6)\n throw new Error('Data must be at least 6 characters long');\n const words = BECH_ALPHABET.decode(_words).slice(0, -6);\n const sum = bechChecksum(prefix, words, ENCODING_CONST);\n if (!_words.endsWith(sum))\n throw new Error(`Invalid checksum in ${str}: expected \"${sum}\"`);\n return { prefix, words };\n }\n const decodeUnsafe = unsafeWrapper(decode);\n function decodeToBytes(str) {\n const { prefix, words } = decode(str, false);\n return { prefix, words, bytes: fromWords(words) };\n }\n return { encode, decode, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords };\n}\nexport const bech32 = genBech32('bech32');\nexport const bech32m = genBech32('bech32m');\nexport const utf8 = {\n encode: (data) => new TextDecoder().decode(data),\n decode: (str) => new TextEncoder().encode(str),\n};\nexport const hex = chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => {\n if (typeof s !== 'string' || s.length % 2)\n throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);\n return s.toLowerCase();\n}));\nconst CODERS = {\n utf8, hex, base16, base32, base64, base64url, base58, base58xmr\n};\nconst coderTypeError = `Invalid encoding type. Available types: ${Object.keys(CODERS).join(', ')}`;\nexport const bytesToString = (type, bytes) => {\n if (typeof type !== 'string' || !CODERS.hasOwnProperty(type))\n throw new TypeError(coderTypeError);\n if (!(bytes instanceof Uint8Array))\n throw new TypeError('bytesToString() expects Uint8Array');\n return CODERS[type].encode(bytes);\n};\nexport const str = bytesToString;\nexport const stringToBytes = (type, str) => {\n if (!CODERS.hasOwnProperty(type))\n throw new TypeError(coderTypeError);\n if (typeof str !== 'string')\n throw new TypeError('stringToBytes() expects string');\n return CODERS[type].decode(str);\n};\nexport const bytes = stringToBytes;\n", "import { decode, type AddressPointer, type ProfilePointer, type EventPointer } from './nip19.ts'\n\nimport type { Event } from './core.ts'\n\ntype Reference = {\n text: string\n profile?: ProfilePointer\n event?: EventPointer\n address?: AddressPointer\n}\n\nconst mentionRegex = /\\bnostr:((note|npub|naddr|nevent|nprofile)1\\w+)\\b|#\\[(\\d+)\\]/g\n\nexport function parseReferences(evt: Event): Reference[] {\n let references: Reference[] = []\n for (let ref of evt.content.matchAll(mentionRegex)) {\n if (ref[2]) {\n // it's a NIP-27 mention\n try {\n let { type, data } = decode(ref[1])\n switch (type) {\n case 'npub': {\n references.push({\n text: ref[0],\n profile: { pubkey: data as string, relays: [] },\n })\n break\n }\n case 'nprofile': {\n references.push({\n text: ref[0],\n profile: data as ProfilePointer,\n })\n break\n }\n case 'note': {\n references.push({\n text: ref[0],\n event: { id: data as string, relays: [] },\n })\n break\n }\n case 'nevent': {\n references.push({\n text: ref[0],\n event: data as EventPointer,\n })\n break\n }\n case 'naddr': {\n references.push({\n text: ref[0],\n address: data as AddressPointer,\n })\n break\n }\n }\n } catch (err) {\n /***/\n }\n } else if (ref[3]) {\n // it's a NIP-10 mention\n let idx = parseInt(ref[3], 10)\n let tag = evt.tags[idx]\n if (!tag) continue\n\n switch (tag[0]) {\n case 'p': {\n references.push({\n text: ref[0],\n profile: { pubkey: tag[1], relays: tag[2] ? [tag[2]] : [] },\n })\n break\n }\n case 'e': {\n references.push({\n text: ref[0],\n event: { id: tag[1], relays: tag[2] ? [tag[2]] : [] },\n })\n break\n }\n case 'a': {\n try {\n let [kind, pubkey, identifier] = tag[1].split(':')\n references.push({\n text: ref[0],\n address: {\n identifier,\n pubkey,\n kind: parseInt(kind, 10),\n relays: tag[2] ? [tag[2]] : [],\n },\n })\n } catch (err) {\n /***/\n }\n break\n }\n }\n }\n }\n\n return references\n}\n", "import { bytesToHex, randomBytes } from '@noble/hashes/utils'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { cbc } from '@noble/ciphers/aes'\nimport { base64 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport function encrypt(secretKey: string | Uint8Array, pubkey: string, text: string): string {\n const privkey: string = secretKey instanceof Uint8Array ? bytesToHex(secretKey) : secretKey\n const key = secp256k1.getSharedSecret(privkey, '02' + pubkey)\n const normalizedKey = getNormalizedX(key)\n\n let iv = Uint8Array.from(randomBytes(16))\n let plaintext = utf8Encoder.encode(text)\n\n let ciphertext = cbc(normalizedKey, iv).encrypt(plaintext)\n\n let ctb64 = base64.encode(new Uint8Array(ciphertext))\n let ivb64 = base64.encode(new Uint8Array(iv.buffer))\n\n return `${ctb64}?iv=${ivb64}`\n}\n\nexport function decrypt(secretKey: string | Uint8Array, pubkey: string, data: string): string {\n const privkey: string = secretKey instanceof Uint8Array ? bytesToHex(secretKey) : secretKey\n let [ctb64, ivb64] = data.split('?iv=')\n let key = secp256k1.getSharedSecret(privkey, '02' + pubkey)\n let normalizedKey = getNormalizedX(key)\n\n let iv = base64.decode(ivb64)\n let ciphertext = base64.decode(ctb64)\n\n let plaintext = cbc(normalizedKey, iv).decrypt(ciphertext)\n\n return utf8Decoder.decode(plaintext)\n}\n\nfunction getNormalizedX(key: Uint8Array): Uint8Array {\n return key.slice(1, 33)\n}\n", "function number(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error(`positive integer expected, not ${n}`);\n}\n\nfunction bool(b: boolean) {\n if (typeof b !== 'boolean') throw new Error(`boolean expected, not ${b}`);\n}\n\nexport function isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\nfunction bytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\n\nexport type Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nfunction hash(hash: Hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('hash must be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\n\nfunction exists(instance: any, checkFinished = true) {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\nfunction output(out: any, instance: any) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\n\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n", "/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\nimport { bytes as abytes, isBytes } from './_assert.js';\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n// Cast array to different type\nexport const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u16 = (arr: TypedArray) =>\n new Uint16Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 2));\nexport const u32 = (arr: TypedArray) =>\n new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\n// Cast array to view\nexport const createView = (arr: TypedArray) =>\n new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n\n// big-endian hardware is rare. Just in case someone still decides to run ciphers:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE) throw new Error('Non little-endian hardware is not supported');\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 } as const;\nfunction asciiToBase16(char: number): number | undefined {\n if (char >= asciis._0 && char <= asciis._9) return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10);\n return;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => {};\n\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`string expected, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n else if (isBytes(data)) data = data.slice();\n else throw new Error(`Uint8Array expected, got ${typeof data}`);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\nexport function checkOpts(\n defaults: T1,\n opts: T2\n): T1 & T2 {\n if (opts == null || typeof opts !== 'object') throw new Error('options must be defined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array) {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n// For runtime check if class implements interface\nexport abstract class Hash> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n}\n\n// This will allow to re-use with composable things like packed & base encoders\n// Also, we probably can make tags composable\nexport type Cipher = {\n encrypt(plaintext: Uint8Array): Uint8Array;\n decrypt(ciphertext: Uint8Array): Uint8Array;\n};\n\nexport type AsyncCipher = {\n encrypt(plaintext: Uint8Array): Promise;\n decrypt(ciphertext: Uint8Array): Promise;\n};\n\nexport type CipherWithOutput = Cipher & {\n encrypt(plaintext: Uint8Array, output?: Uint8Array): Uint8Array;\n decrypt(ciphertext: Uint8Array, output?: Uint8Array): Uint8Array;\n};\n\n// Params is outside return type, so it is accessible before calling constructor\n// If function support multiple nonceLength's, we return best one\nexport type CipherParams = { blockSize: number; nonceLength?: number; tagLength?: number };\nexport type CipherCons = (key: Uint8Array, ...args: T) => Cipher;\n/**\n * @__NO_SIDE_EFFECTS__\n */\nexport const wrapCipher = , P extends CipherParams>(\n params: P,\n c: C\n): C & P => {\n Object.assign(c, params);\n return c as C & P;\n};\n\nexport type XorStream = (\n key: Uint8Array,\n nonce: Uint8Array,\n data: Uint8Array,\n output?: Uint8Array,\n counter?: number\n) => Uint8Array;\n\n// Polyfill for Safari 14\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\nexport function u64Lengths(ciphertext: Uint8Array, AAD?: Uint8Array) {\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(ciphertext.length), true);\n return num;\n}\n", "import { createView, toBytes, Input, Hash, u32 } from './utils.js';\nimport { bytes as abytes, exists as aexists, output as aoutput } from './_assert.js';\n\n// GHash from AES-GCM and its little-endian \"mirror image\" Polyval from AES-SIV.\n// Implemented in terms of GHash with conversion function for keys\n// GCM GHASH from NIST SP800-38d, SIV from RFC 8452.\n// https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf\n\n// GHASH modulo: x^128 + x^7 + x^2 + x + 1\n// POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1\n\nconst BLOCK_SIZE = 16;\n// TODO: rewrite\n// temporary padding buffer\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\nconst ZEROS32 = u32(ZEROS16);\nconst POLY = 0xe1; // v = 2*v % POLY\n\n// v = 2*v % POLY\n// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x\n// We can multiply any number using montgomery ladder and this function (works as double, add is simple xor)\nconst mul2 = (s0: number, s1: number, s2: number, s3: number) => {\n const hiBit = s3 & 1;\n return {\n s3: (s2 << 31) | (s3 >>> 1),\n s2: (s1 << 31) | (s2 >>> 1),\n s1: (s0 << 31) | (s1 >>> 1),\n s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly\n };\n};\n\nconst swapLE = (n: number) =>\n (((n >>> 0) & 0xff) << 24) |\n (((n >>> 8) & 0xff) << 16) |\n (((n >>> 16) & 0xff) << 8) |\n ((n >>> 24) & 0xff) |\n 0;\n\n/**\n * `mulX_POLYVAL(ByteReverse(H))` from spec\n * @param k mutated in place\n */\nexport function _toGHASHKey(k: Uint8Array): Uint8Array {\n k.reverse();\n const hiBit = k[15] & 1;\n // k >>= 1\n let carry = 0;\n for (let i = 0; i < k.length; i++) {\n const t = k[i];\n k[i] = (t >>> 1) | carry;\n carry = (t & 1) << 7;\n }\n k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000;\n return k;\n}\n\ntype Value = { s0: number; s1: number; s2: number; s3: number };\n\nconst estimateWindow = (bytes: number) => {\n if (bytes > 64 * 1024) return 8;\n if (bytes > 1024) return 4;\n return 2;\n};\n\nclass GHASH implements Hash {\n readonly blockLen = BLOCK_SIZE;\n readonly outputLen = BLOCK_SIZE;\n protected s0 = 0;\n protected s1 = 0;\n protected s2 = 0;\n protected s3 = 0;\n protected finished = false;\n protected t: Value[];\n private W: number;\n private windowSize: number;\n // We select bits per window adaptively based on expectedLength\n constructor(key: Input, expectedLength?: number) {\n key = toBytes(key);\n abytes(key, 16);\n const kView = createView(key);\n let k0 = kView.getUint32(0, false);\n let k1 = kView.getUint32(4, false);\n let k2 = kView.getUint32(8, false);\n let k3 = kView.getUint32(12, false);\n // generate table of doubled keys (half of montgomery ladder)\n const doubles: Value[] = [];\n for (let i = 0; i < 128; i++) {\n doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });\n ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));\n }\n const W = estimateWindow(expectedLength || 1024);\n if (![1, 2, 4, 8].includes(W))\n throw new Error(`ghash: wrong window size=${W}, should be 2, 4 or 8`);\n this.W = W;\n const bits = 128; // always 128 bits;\n const windows = bits / W;\n const windowSize = (this.windowSize = 2 ** W);\n const items: Value[] = [];\n // Create precompute table for window of W bits\n for (let w = 0; w < windows; w++) {\n // truth table: 00, 01, 10, 11\n for (let byte = 0; byte < windowSize; byte++) {\n // prettier-ignore\n let s0 = 0, s1 = 0, s2 = 0, s3 = 0;\n for (let j = 0; j < W; j++) {\n const bit = (byte >>> (W - j - 1)) & 1;\n if (!bit) continue;\n const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];\n (s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3);\n }\n items.push({ s0, s1, s2, s3 });\n }\n }\n this.t = items;\n }\n protected _updateBlock(s0: number, s1: number, s2: number, s3: number) {\n (s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3);\n const { W, t, windowSize } = this;\n // prettier-ignore\n let o0 = 0, o1 = 0, o2 = 0, o3 = 0;\n const mask = (1 << W) - 1; // 2**W will kill performance.\n let w = 0;\n for (const num of [s0, s1, s2, s3]) {\n for (let bytePos = 0; bytePos < 4; bytePos++) {\n const byte = (num >>> (8 * bytePos)) & 0xff;\n for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {\n const bit = (byte >>> (W * bitPos)) & mask;\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];\n (o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3);\n w += 1;\n }\n }\n }\n this.s0 = o0;\n this.s1 = o1;\n this.s2 = o2;\n this.s3 = o3;\n }\n update(data: Input): this {\n data = toBytes(data);\n aexists(this);\n const b32 = u32(data);\n const blocks = Math.floor(data.length / BLOCK_SIZE);\n const left = data.length % BLOCK_SIZE;\n for (let i = 0; i < blocks; i++) {\n this._updateBlock(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]);\n }\n if (left) {\n ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]);\n ZEROS32.fill(0); // clean tmp buffer\n }\n return this;\n }\n destroy() {\n const { t } = this;\n // clean precompute table\n for (const elm of t) {\n (elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0);\n }\n }\n digestInto(out: Uint8Array) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { s0, s1, s2, s3 } = this;\n const o32 = u32(out);\n o32[0] = s0;\n o32[1] = s1;\n o32[2] = s2;\n o32[3] = s3;\n return out;\n }\n digest(): Uint8Array {\n const res = new Uint8Array(BLOCK_SIZE);\n this.digestInto(res);\n this.destroy();\n return res;\n }\n}\n\nclass Polyval extends GHASH {\n constructor(key: Input, expectedLength?: number) {\n key = toBytes(key);\n const ghKey = _toGHASHKey(key.slice());\n super(ghKey, expectedLength);\n ghKey.fill(0);\n }\n update(data: Input): this {\n data = toBytes(data);\n aexists(this);\n const b32 = u32(data);\n const left = data.length % BLOCK_SIZE;\n const blocks = Math.floor(data.length / BLOCK_SIZE);\n for (let i = 0; i < blocks; i++) {\n this._updateBlock(\n swapLE(b32[i * 4 + 3]),\n swapLE(b32[i * 4 + 2]),\n swapLE(b32[i * 4 + 1]),\n swapLE(b32[i * 4 + 0])\n );\n }\n if (left) {\n ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n this._updateBlock(\n swapLE(ZEROS32[3]),\n swapLE(ZEROS32[2]),\n swapLE(ZEROS32[1]),\n swapLE(ZEROS32[0])\n );\n ZEROS32.fill(0); // clean tmp buffer\n }\n return this;\n }\n digestInto(out: Uint8Array) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // tmp ugly hack\n const { s0, s1, s2, s3 } = this;\n const o32 = u32(out);\n o32[0] = s0;\n o32[1] = s1;\n o32[2] = s2;\n o32[3] = s3;\n return out.reverse();\n }\n}\n\nexport type CHash = ReturnType;\nfunction wrapConstructorWithKey>(\n hashCons: (key: Input, expectedLength?: number) => Hash\n) {\n const hashC = (msg: Input, key: Input): Uint8Array =>\n hashCons(key, msg.length).update(toBytes(msg)).digest();\n const tmp = hashCons(new Uint8Array(16), 0);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (key: Input, expectedLength?: number) => hashCons(key, expectedLength);\n return hashC;\n}\n\nexport const ghash = wrapConstructorWithKey(\n (key, expectedLength) => new GHASH(key, expectedLength)\n);\nexport const polyval = wrapConstructorWithKey(\n (key, expectedLength) => new Polyval(key, expectedLength)\n);\n", "// prettier-ignore\nimport {\n wrapCipher, Cipher, CipherWithOutput,\n createView, setBigUint64, equalBytes, u32, u8,\n} from './utils.js';\nimport { ghash, polyval } from './_polyval.js';\nimport { bytes as abytes } from './_assert.js';\n\n/*\nAES (Advanced Encryption Standard) aka Rijndael block cipher.\n\nData is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:\n1. **S-box**, table substitution\n2. **Shift rows**, cyclic shift left of all rows of data array\n3. **Mix columns**, multiplying every column by fixed polynomial\n4. **Add round key**, round_key xor i-th column of array\n\nResources:\n- FIPS-197 https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf\n- Original proposal: https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf\n*/\n\nconst BLOCK_SIZE = 16;\nconst BLOCK_SIZE32 = 4;\nconst EMPTY_BLOCK = new Uint8Array(BLOCK_SIZE);\nconst POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8\n\n// TODO: remove multiplication, binary ops only\nfunction mul2(n: number) {\n return (n << 1) ^ (POLY & -(n >> 7));\n}\n\nfunction mul(a: number, b: number) {\n let res = 0;\n for (; b > 0; b >>= 1) {\n // Montgomery ladder\n res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time).\n a = mul2(a); // a = 2*a\n }\n return res;\n}\n\n// AES S-box is generated using finite field inversion,\n// an affine transform, and xor of a constant 0x63.\nconst sbox = /* @__PURE__ */ (() => {\n let t = new Uint8Array(256);\n for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x)) t[i] = x;\n const box = new Uint8Array(256);\n box[0] = 0x63; // first elm\n for (let i = 0; i < 255; i++) {\n let x = t[255 - i];\n x |= x << 8;\n box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff;\n }\n return box;\n})();\n\n// Inverted S-box\nconst invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));\n\n// Rotate u32 by 8\nconst rotr32_8 = (n: number) => (n << 24) | (n >>> 8);\nconst rotl32_8 = (n: number) => (n << 8) | (n >>> 24);\n\n// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes:\n// - LE instead of BE\n// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23;\n// so index is u16, instead of u8. This speeds up things, unexpectedly\nfunction genTtable(sbox: Uint8Array, fn: (n: number) => number) {\n if (sbox.length !== 256) throw new Error('Wrong sbox length');\n const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));\n const T1 = T0.map(rotl32_8);\n const T2 = T1.map(rotl32_8);\n const T3 = T2.map(rotl32_8);\n const T01 = new Uint32Array(256 * 256);\n const T23 = new Uint32Array(256 * 256);\n const sbox2 = new Uint16Array(256 * 256);\n for (let i = 0; i < 256; i++) {\n for (let j = 0; j < 256; j++) {\n const idx = i * 256 + j;\n T01[idx] = T0[i] ^ T1[j];\n T23[idx] = T2[i] ^ T3[j];\n sbox2[idx] = (sbox[i] << 8) | sbox[j];\n }\n }\n return { sbox, sbox2, T0, T1, T2, T3, T01, T23 };\n}\n\nconst tableEncoding = /* @__PURE__ */ genTtable(\n sbox,\n (s: number) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2)\n);\nconst tableDecoding = /* @__PURE__ */ genTtable(\n invSbox,\n (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14)\n);\n\nconst xPowers = /* @__PURE__ */ (() => {\n const p = new Uint8Array(16);\n for (let i = 0, x = 1; i < 16; i++, x = mul2(x)) p[i] = x;\n return p;\n})();\n\nexport function expandKeyLE(key: Uint8Array): Uint32Array {\n abytes(key);\n const len = key.length;\n if (![16, 24, 32].includes(len))\n throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`);\n const { sbox2 } = tableEncoding;\n const k32 = u32(key);\n const Nk = k32.length;\n const subByte = (n: number) => applySbox(sbox2, n, n, n, n);\n const xk = new Uint32Array(len + 28); // expanded key\n xk.set(k32);\n // 4.3.1 Key expansion\n for (let i = Nk; i < xk.length; i++) {\n let t = xk[i - 1];\n if (i % Nk === 0) t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];\n else if (Nk > 6 && i % Nk === 4) t = subByte(t);\n xk[i] = xk[i - Nk] ^ t;\n }\n return xk;\n}\n\nexport function expandKeyDecLE(key: Uint8Array): Uint32Array {\n const encKey = expandKeyLE(key);\n const xk = encKey.slice();\n const Nk = encKey.length;\n const { sbox2 } = tableEncoding;\n const { T0, T1, T2, T3 } = tableDecoding;\n // Inverse key by chunks of 4 (rounds)\n for (let i = 0; i < Nk; i += 4) {\n for (let j = 0; j < 4; j++) xk[i + j] = encKey[Nk - i - 4 + j];\n }\n encKey.fill(0);\n // apply InvMixColumn except first & last round\n for (let i = 4; i < Nk - 4; i++) {\n const x = xk[i];\n const w = applySbox(sbox2, x, x, x, x);\n xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24];\n }\n return xk;\n}\n\n// Apply tables\nfunction apply0123(\n T01: Uint32Array,\n T23: Uint32Array,\n s0: number,\n s1: number,\n s2: number,\n s3: number\n) {\n return (\n T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^\n T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]\n );\n}\n\nfunction applySbox(sbox2: Uint16Array, s0: number, s1: number, s2: number, s3: number) {\n return (\n sbox2[(s0 & 0xff) | (s1 & 0xff00)] |\n (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16)\n );\n}\n\nfunction encrypt(xk: Uint32Array, s0: number, s1: number, s2: number, s3: number) {\n const { sbox2, T01, T23 } = tableEncoding;\n let k = 0;\n (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);\n (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n }\n // last round (without mixcolumns, so using SBOX2 table)\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\n\nfunction decrypt(xk: Uint32Array, s0: number, s1: number, s2: number, s3: number) {\n const { sbox2, T01, T23 } = tableDecoding;\n let k = 0;\n (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);\n (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n }\n // Last round\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\n\nfunction getDst(len: number, dst?: Uint8Array) {\n if (!dst) return new Uint8Array(len);\n abytes(dst);\n if (dst.length < len)\n throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`);\n return dst;\n}\n\n// TODO: investigate merging with ctr32\nfunction ctrCounter(xk: Uint32Array, nonce: Uint8Array, src: Uint8Array, dst?: Uint8Array) {\n abytes(nonce, BLOCK_SIZE);\n abytes(src);\n const srcLen = src.length;\n dst = getDst(srcLen, dst);\n const ctr = nonce;\n const c32 = u32(ctr);\n // Fill block (empty, ctr=0)\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n const src32 = u32(src);\n const dst32 = u32(dst);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n // Full 128 bit counter with wrap around\n let carry = 1;\n for (let i = ctr.length - 1; i >= 0; i--) {\n carry = (carry + (ctr[i] & 0xff)) | 0;\n ctr[i] = carry & 0xff;\n carry >>>= 8;\n }\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than block)\n // It's possible to handle > u32 fast, but is it worth it?\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];\n }\n return dst;\n}\n\n// AES CTR with overflowing 32 bit counter\n// It's possible to do 32le significantly simpler (and probably faster) by using u32.\n// But, we need both, and perf bottleneck is in ghash anyway.\nfunction ctr32(\n xk: Uint32Array,\n isLE: boolean,\n nonce: Uint8Array,\n src: Uint8Array,\n dst?: Uint8Array\n) {\n abytes(nonce, BLOCK_SIZE);\n abytes(src);\n dst = getDst(src.length, dst);\n const ctr = nonce; // write new value to nonce, so it can be re-used\n const c32 = u32(ctr);\n const view = createView(ctr);\n const src32 = u32(src);\n const dst32 = u32(dst);\n const ctrPos = isLE ? 0 : 12;\n const srcLen = src.length;\n // Fill block (empty, ctr=0)\n let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n ctrNum = (ctrNum + 1) >>> 0; // u32 wrap\n view.setUint32(ctrPos, ctrNum, isLE);\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than a block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];\n }\n return dst;\n}\n\n/**\n * CTR: counter mode. Creates stream cipher.\n * Requires good IV. Parallelizable. OK, but no MAC.\n */\nexport const ctr = wrapCipher(\n { blockSize: 16, nonceLength: 16 },\n function ctr(key: Uint8Array, nonce: Uint8Array): CipherWithOutput {\n abytes(key);\n abytes(nonce, BLOCK_SIZE);\n function processCtr(buf: Uint8Array, dst?: Uint8Array) {\n const xk = expandKeyLE(key);\n const n = nonce.slice();\n const out = ctrCounter(xk, n, buf, dst);\n xk.fill(0);\n n.fill(0);\n return out;\n }\n return {\n encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => processCtr(plaintext, dst),\n decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => processCtr(ciphertext, dst),\n };\n }\n);\n\nfunction validateBlockDecrypt(data: Uint8Array) {\n abytes(data);\n if (data.length % BLOCK_SIZE !== 0) {\n throw new Error(\n `aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`\n );\n }\n}\n\nfunction validateBlockEncrypt(plaintext: Uint8Array, pcks5: boolean, dst?: Uint8Array) {\n let outLen = plaintext.length;\n const remaining = outLen % BLOCK_SIZE;\n if (!pcks5 && remaining !== 0)\n throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding');\n const b = u32(plaintext);\n if (pcks5) {\n let left = BLOCK_SIZE - remaining;\n if (!left) left = BLOCK_SIZE; // if no bytes left, create empty padding block\n outLen = outLen + left;\n }\n const out = getDst(outLen, dst);\n const o = u32(out);\n return { b, o, out };\n}\n\nfunction validatePCKS(data: Uint8Array, pcks5: boolean) {\n if (!pcks5) return data;\n const len = data.length;\n if (!len) throw new Error(`aes/pcks5: empty ciphertext not allowed`);\n const lastByte = data[len - 1];\n if (lastByte <= 0 || lastByte > 16) throw new Error(`aes/pcks5: wrong padding byte: ${lastByte}`);\n const out = data.subarray(0, -lastByte);\n for (let i = 0; i < lastByte; i++)\n if (data[len - i - 1] !== lastByte) throw new Error(`aes/pcks5: wrong padding`);\n return out;\n}\n\nfunction padPCKS(left: Uint8Array) {\n const tmp = new Uint8Array(16);\n const tmp32 = u32(tmp);\n tmp.set(left);\n const paddingByte = BLOCK_SIZE - left.length;\n for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++) tmp[i] = paddingByte;\n return tmp32;\n}\n\nexport type BlockOpts = { disablePadding?: boolean };\n\n/**\n * ECB: Electronic CodeBook. Simple deterministic replacement.\n * Dangerous: always map x to y. See [AES Penguin](https://words.filippo.io/the-ecb-penguin/).\n */\nexport const ecb = wrapCipher(\n { blockSize: 16 },\n function ecb(key: Uint8Array, opts: BlockOpts = {}): CipherWithOutput {\n abytes(key);\n const pcks5 = !opts.disablePadding;\n return {\n encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => {\n abytes(plaintext);\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n const xk = expandKeyLE(key);\n let i = 0;\n for (; i + 4 <= b.length; ) {\n const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n xk.fill(0);\n return _out;\n },\n decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n const out = getDst(ciphertext.length, dst);\n const b = u32(ciphertext);\n const o = u32(out);\n for (let i = 0; i + 4 <= b.length; ) {\n const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n xk.fill(0);\n return validatePCKS(out, pcks5);\n },\n };\n }\n);\n\n/**\n * CBC: Cipher-Block-Chaining. Key is previous round\u2019s block.\n * Fragile: needs proper padding. Unauthenticated: needs MAC.\n */\nexport const cbc = wrapCipher(\n { blockSize: 16, nonceLength: 16 },\n function cbc(key: Uint8Array, iv: Uint8Array, opts: BlockOpts = {}): CipherWithOutput {\n abytes(key);\n abytes(iv, 16);\n const pcks5 = !opts.disablePadding;\n return {\n encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => {\n const xk = expandKeyLE(key);\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n const n32 = u32(iv);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n let i = 0;\n for (; i + 4 <= b.length; ) {\n (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]);\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]);\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n xk.fill(0);\n return _out;\n },\n decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n const n32 = u32(iv);\n const out = getDst(ciphertext.length, dst);\n const b = u32(ciphertext);\n const o = u32(out);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= b.length; ) {\n // prettier-ignore\n const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;\n (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]);\n const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3);\n (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3);\n }\n xk.fill(0);\n return validatePCKS(out, pcks5);\n },\n };\n }\n);\n\n// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen\nfunction computeTag(\n fn: typeof ghash,\n isLE: boolean,\n key: Uint8Array,\n data: Uint8Array,\n AAD?: Uint8Array\n) {\n const h = fn.create(key, data.length + (AAD?.length || 0));\n if (AAD) h.update(AAD);\n h.update(data);\n const num = new Uint8Array(16);\n const view = createView(num);\n if (AAD) setBigUint64(view, 0, BigInt(AAD.length * 8), isLE);\n setBigUint64(view, 8, BigInt(data.length * 8), isLE);\n h.update(num);\n return h.digest();\n}\n\n/**\n * GCM: Galois/Counter Mode.\n * Good, modern version of CTR, parallel, with MAC.\n * Be careful: MACs can be forged.\n */\nexport const gcm = wrapCipher(\n { blockSize: 16, nonceLength: 12, tagLength: 16 },\n function gcm(key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): Cipher {\n abytes(nonce);\n // Nonce can be pretty much anything (even 1 byte). But smaller nonces less secure.\n if (nonce.length === 0) throw new Error('aes/gcm: empty nonce');\n const tagLength = 16;\n function _computeTag(authKey: Uint8Array, tagMask: Uint8Array, data: Uint8Array) {\n const tag = computeTag(ghash, false, authKey, data, AAD);\n for (let i = 0; i < tagMask.length; i++) tag[i] ^= tagMask[i];\n return tag;\n }\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const authKey = EMPTY_BLOCK.slice();\n const counter = EMPTY_BLOCK.slice();\n ctr32(xk, false, counter, counter, authKey);\n if (nonce.length === 12) {\n counter.set(nonce);\n } else {\n // Spec (NIST 800-38d) supports variable size nonce.\n // Not supported for now, but can be useful.\n const nonceLen = EMPTY_BLOCK.slice();\n const view = createView(nonceLen);\n setBigUint64(view, 8, BigInt(nonce.length * 8), false);\n // ghash(nonce || u64be(0) || u64be(nonceLen*8))\n ghash.create(authKey).update(nonce).update(nonceLen).digestInto(counter);\n }\n const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);\n return { xk, authKey, counter, tagMask };\n }\n return {\n encrypt: (plaintext: Uint8Array) => {\n abytes(plaintext);\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const out = new Uint8Array(plaintext.length + tagLength);\n ctr32(xk, false, counter, plaintext, out);\n const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));\n out.set(tag, plaintext.length);\n xk.fill(0);\n return out;\n },\n decrypt: (ciphertext: Uint8Array) => {\n abytes(ciphertext);\n if (ciphertext.length < tagLength)\n throw new Error(`aes/gcm: ciphertext less than tagLen (${tagLength})`);\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = _computeTag(authKey, tagMask, data);\n if (!equalBytes(tag, passedTag)) throw new Error('aes/gcm: invalid ghash tag');\n const out = ctr32(xk, false, counter, data);\n authKey.fill(0);\n tagMask.fill(0);\n xk.fill(0);\n return out;\n },\n };\n }\n);\n\nconst limit = (name: string, min: number, max: number) => (value: number) => {\n if (!Number.isSafeInteger(value) || min > value || value > max)\n throw new Error(`${name}: invalid value=${value}, must be [${min}..${max}]`);\n};\n\n/**\n * AES-GCM-SIV: classic AES-GCM with nonce-misuse resistance.\n * Guarantees that, when a nonce is repeated, the only security loss is that identical\n * plaintexts will produce identical ciphertexts.\n * RFC 8452, https://datatracker.ietf.org/doc/html/rfc8452\n */\nexport const siv = wrapCipher(\n { blockSize: 16, nonceLength: 12, tagLength: 16 },\n function siv(key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): Cipher {\n const tagLength = 16;\n // From RFC 8452: Section 6\n const AAD_LIMIT = limit('AAD', 0, 2 ** 36);\n const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36);\n const NONCE_LIMIT = limit('nonce', 12, 12);\n const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16);\n abytes(nonce);\n NONCE_LIMIT(nonce.length);\n if (AAD) {\n abytes(AAD);\n AAD_LIMIT(AAD.length);\n }\n function deriveKeys() {\n const len = key.length;\n if (len !== 16 && len !== 24 && len !== 32)\n throw new Error(`key length must be 16, 24 or 32 bytes, got: ${len} bytes`);\n const xk = expandKeyLE(key);\n const encKey = new Uint8Array(len);\n const authKey = new Uint8Array(16);\n const n32 = u32(nonce);\n // prettier-ignore\n let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2];\n let counter = 0;\n for (const derivedKey of [authKey, encKey].map(u32)) {\n const d32 = u32(derivedKey);\n for (let i = 0; i < d32.length; i += 2) {\n // aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ...\n const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3);\n d32[i + 0] = o0;\n d32[i + 1] = o1;\n s0 = ++counter; // increment counter inside state\n }\n }\n xk.fill(0);\n return { authKey, encKey: expandKeyLE(encKey) };\n }\n function _computeTag(encKey: Uint32Array, authKey: Uint8Array, data: Uint8Array) {\n const tag = computeTag(polyval, true, authKey, data, AAD);\n // Compute the expected tag by XORing S_s and the nonce, clearing the\n // most significant bit of the last byte and encrypting with the\n // message-encryption key.\n for (let i = 0; i < 12; i++) tag[i] ^= nonce[i];\n tag[15] &= 0x7f; // Clear the highest bit\n // encrypt tag as block\n const t32 = u32(tag);\n // prettier-ignore\n let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3];\n ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3));\n (t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3);\n return tag;\n }\n // actual decrypt/encrypt of message.\n function processSiv(encKey: Uint32Array, tag: Uint8Array, input: Uint8Array) {\n let block = tag.slice();\n block[15] |= 0x80; // Force highest bit\n return ctr32(encKey, true, block, input);\n }\n return {\n encrypt: (plaintext: Uint8Array) => {\n abytes(plaintext);\n PLAIN_LIMIT(plaintext.length);\n const { encKey, authKey } = deriveKeys();\n const tag = _computeTag(encKey, authKey, plaintext);\n const out = new Uint8Array(plaintext.length + tagLength);\n out.set(tag, plaintext.length);\n out.set(processSiv(encKey, tag, plaintext));\n encKey.fill(0);\n authKey.fill(0);\n return out;\n },\n decrypt: (ciphertext: Uint8Array) => {\n abytes(ciphertext);\n CIPHER_LIMIT(ciphertext.length);\n const tag = ciphertext.subarray(-tagLength);\n const { encKey, authKey } = deriveKeys();\n const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength));\n const expectedTag = _computeTag(encKey, authKey, plaintext);\n encKey.fill(0);\n authKey.fill(0);\n if (!equalBytes(tag, expectedTag)) throw new Error('invalid polyval tag');\n return plaintext;\n },\n };\n }\n);\n\nfunction isBytes32(a: unknown): a is Uint8Array {\n return (\n a != null &&\n typeof a === 'object' &&\n (a instanceof Uint32Array || a.constructor.name === 'Uint32Array')\n );\n}\n\nfunction encryptBlock(xk: Uint32Array, block: Uint8Array) {\n abytes(block, 16);\n if (!isBytes32(xk)) throw new Error('_encryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n return block;\n}\n\nfunction decryptBlock(xk: Uint32Array, block: Uint8Array) {\n abytes(block, 16);\n if (!isBytes32(xk)) throw new Error('_decryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n return block;\n}\n\n// Highly unsafe private functions for implementing new modes or ciphers based on AES\n// Can change at any time, no API guarantees\nexport const unsafe = {\n expandKeyLE,\n expandKeyDecLE,\n encrypt,\n decrypt,\n encryptBlock,\n decryptBlock,\n ctrCounter,\n ctr32,\n};\n", "import { ProfilePointer } from './nip19.ts'\n\nexport type Nip05 = `${string}@${string}`\n\n/**\n * NIP-05 regex. The localpart is optional, and should be assumed to be `_` otherwise.\n *\n * - 0: full match\n * - 1: name (optional)\n * - 2: domain\n */\nexport const NIP05_REGEX = /^(?:([\\w.+-]+)@)?([\\w_-]+(\\.[\\w_-]+)+)$/\nexport const isNip05 = (value?: string | null): value is Nip05 => NIP05_REGEX.test(value || '')\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _fetch: any\n\ntry {\n _fetch = fetch\n} catch (_) {\n null\n}\n\nexport function useFetchImplementation(fetchImplementation: unknown) {\n _fetch = fetchImplementation\n}\n\nexport async function searchDomain(domain: string, query = ''): Promise<{ [name: string]: string }> {\n try {\n const url = `https://${domain}/.well-known/nostr.json?name=${query}`\n const res = await _fetch(url, { redirect: 'manual' })\n if (res.status !== 200) {\n throw Error('Wrong response code')\n }\n const json = await res.json()\n return json.names\n } catch (_) {\n return {}\n }\n}\n\nexport async function queryProfile(fullname: string): Promise {\n const match = fullname.match(NIP05_REGEX)\n if (!match) return null\n\n const [, name = '_', domain] = match\n\n try {\n const url = `https://${domain}/.well-known/nostr.json?name=${name}`\n const res = await _fetch(url, { redirect: 'manual' })\n if (res.status !== 200) {\n throw Error('Wrong response code')\n }\n const json = await res.json()\n\n const pubkey = json.names[name]\n return pubkey ? { pubkey, relays: json.relays?.[pubkey] } : null\n } catch (_e) {\n return null\n }\n}\n\nexport async function isValid(pubkey: string, nip05: Nip05): Promise {\n const res = await queryProfile(nip05)\n return res ? res.pubkey === pubkey : false\n}\n", "import type { Event } from './core.ts'\nimport type { EventPointer, ProfilePointer } from './nip19.ts'\n\nexport function parse(event: Pick): {\n /**\n * Pointer to the root of the thread.\n */\n root: EventPointer | undefined\n\n /**\n * Pointer to a \"parent\" event that parsed event replies to (responded to).\n */\n reply: EventPointer | undefined\n\n /**\n * Pointers to events that may or may not be in the reply chain.\n */\n mentions: EventPointer[]\n\n /**\n * Pointers to events that were directly quoted.\n */\n quotes: EventPointer[]\n\n /**\n * List of pubkeys that are involved in the thread in no particular order.\n */\n profiles: ProfilePointer[]\n} {\n const result: ReturnType = {\n reply: undefined,\n root: undefined,\n mentions: [],\n profiles: [],\n quotes: [],\n }\n\n let maybeParent: EventPointer | undefined\n let maybeRoot: EventPointer | undefined\n\n for (let i = event.tags.length - 1; i >= 0; i--) {\n const tag = event.tags[i]\n\n if (tag[0] === 'e' && tag[1]) {\n const [_, eTagEventId, eTagRelayUrl, eTagMarker, eTagAuthor] = tag as [\n string,\n string,\n undefined | string,\n undefined | string,\n undefined | string,\n ]\n\n const eventPointer: EventPointer = {\n id: eTagEventId,\n relays: eTagRelayUrl ? [eTagRelayUrl] : [],\n author: eTagAuthor,\n }\n\n if (eTagMarker === 'root') {\n result.root = eventPointer\n continue\n }\n\n if (eTagMarker === 'reply') {\n result.reply = eventPointer\n continue\n }\n\n if (eTagMarker === 'mention') {\n result.mentions.push(eventPointer)\n continue\n }\n\n if (!maybeParent) {\n maybeParent = eventPointer\n } else {\n maybeRoot = eventPointer\n }\n\n result.mentions.push(eventPointer)\n continue\n }\n\n if (tag[0] === 'q' && tag[1]) {\n const [_, eTagEventId, eTagRelayUrl] = tag as [string, string, undefined | string]\n result.quotes.push({\n id: eTagEventId,\n relays: eTagRelayUrl ? [eTagRelayUrl] : [],\n })\n }\n\n if (tag[0] === 'p' && tag[1]) {\n result.profiles.push({\n pubkey: tag[1],\n relays: tag[2] ? [tag[2]] : [],\n })\n continue\n }\n }\n\n // get legacy (positional) markers, set reply to root and vice-versa if one of them is missing\n if (!result.root) {\n result.root = maybeRoot || maybeParent || result.reply\n }\n if (!result.reply) {\n result.reply = maybeParent || result.root\n }\n\n // remove root and reply from mentions, inherit relay hints from authors if any\n ;[result.reply, result.root].forEach(ref => {\n if (!ref) return\n\n let idx = result.mentions.indexOf(ref)\n if (idx !== -1) {\n result.mentions.splice(idx, 1)\n }\n if (ref.author) {\n let author = result.profiles.find(p => p.pubkey === ref.author)\n if (author && author.relays) {\n if (!ref.relays) {\n ref.relays = []\n }\n author.relays.forEach(url => {\n if (ref.relays!?.indexOf(url) === -1) ref.relays!.push(url)\n })\n author.relays = ref.relays\n }\n }\n })\n\n result.mentions.forEach(ref => {\n if (ref!.author) {\n let author = result.profiles.find(p => p.pubkey === ref.author)\n if (author && author.relays) {\n if (!ref.relays) {\n ref.relays = []\n }\n author.relays.forEach(url => {\n if (ref.relays!.indexOf(url) === -1) ref.relays!.push(url)\n })\n author.relays = ref.relays\n }\n }\n })\n\n return result\n}\n", "var _fetch: any\n\ntry {\n _fetch = fetch\n} catch {}\n\nexport function useFetchImplementation(fetchImplementation: any): void {\n _fetch = fetchImplementation\n}\n\nexport async function fetchRelayInformation(url: string): Promise {\n return (await (\n await fetch(url.replace('ws://', 'http://').replace('wss://', 'https://'), {\n headers: { Accept: 'application/nostr+json' },\n })\n ).json()) as RelayInformation\n}\n\n/**\n * ## Relay Information Document\n\n * Relays may provide server metadata to clients to inform\n * them of capabilities, administrative contacts, and\n * various server attributes. This is made available as a\n * JSON document over HTTP, on the same URI as the relay's\n * websocket.\n\n * Any field may be omitted, and clients MUST ignore any\n * additional fields they do not understand. Relays MUST\n * accept CORS requests by sending\n * `Access-Control-Allow-Origin`,\n * `Access-Control-Allow-Headers`, and\n * `Access-Control-Allow-Methods` headers.\n * @param name string identifying relay\n * @param description string with detailed information\n * @param pubkey administrative contact pubkey\n * @param contact: administrative alternate contact\n * @param supported_nips a list of NIP numbers supported by\n * the relay\n * @param software identifying relay software URL\n * @param version string version identifier\n */\nexport interface BasicRelayInformation {\n // string identifying relay\n name: string\n description: string\n pubkey: string\n contact: string\n supported_nips: number[]\n software: string\n version: string\n // limitation?: Limitations\n}\n\n/**\n * * ## Extra Fields\n\n * * ### Server Limitations\n\n * These are limitations imposed by the relay on clients.\n * Your client should expect that requests which exceed\n * these practical_ limitations are rejected or fail immediately.\n * @param max_message_length this is the maximum number of\n * bytes for incoming JSON that the relay will attempt to\n * decode and act upon. When you send large subscriptions,\n * you will be limited by this value. It also effectively\n * limits the maximum size of any event. Value is calculated\n * from `[` to `]` and is after UTF-8 serialization (so some\n * unicode characters will cost 2-3 bytes). It is equal to\n * the maximum size of the WebSocket message frame.\n * @param max_subscriptions total number of subscriptions\n * that may be active on a single websocket connection to\n * this relay. It's possible that authenticated clients with\n * a (paid) relationship to the relay may have higher limits.\n * @param max_filters maximum number of filter values in\n * each subscription. Must be one or higher.\n * @param max_limit the relay server will clamp each\n * filter's `limit` value to this number.\n * This means the client won't be able to get more than this\n * number of events from a single subscription filter. This\n * clamping is typically done silently by the relay, but\n * with this number, you can know that there are additional\n * results if you narrowed your filter's time range or other\n * parameters.\n * @param max_subid_length maximum length of subscription id as a\n * string.\n * @param min_prefix for `authors` and `ids` filters which\n * are to match against a hex prefix, you must provide at\n * least this many hex digits in the prefix.\n * @param max_event_tags in any event, this is the maximum\n * number of elements in the `tags` list.\n * @param max_content_length maximum number of characters in\n * the `content` field of any event. This is a count of\n * unicode characters. After serializing into JSON it may be\n * larger (in bytes), and is still subject to the\n * max_message_length`, if defined.\n * @param min_pow_difficulty new events will require at\n * least this difficulty of PoW, based on [NIP-13](13.md),\n * or they will be rejected by this server.\n * @param auth_required this relay requires [NIP-42](42.md)\n * authentication to happen before a new connection may\n * perform any other action. Even if set to False,\n * authentication may be required for specific actions.\n * @param restricted_writes: this relay requires some kind\n * of condition to be fulfilled in order to accept events\n * (not necessarily, but including\n * @param payment_required this relay requires payment\n * before a new connection may perform any action.\n * @param created_at_lower_limit: 'created_at' lower limit\n * @param created_at_upper_limit: 'created_at' upper limit\n */\nexport interface Limitations {\n max_message_length: number\n max_subscriptions: number\n max_filters: number\n max_limit: number\n max_subid_length: number\n min_prefix: number\n max_event_tags: number\n max_content_length: number\n min_pow_difficulty: number\n auth_required: boolean\n payment_required: boolean\n created_at_lower_limit: number\n created_at_upper_limit: number\n restricted_writes: boolean\n}\n\nexport interface RetentionDetails {\n kinds: (number | number[])[]\n time?: number | null\n count?: number | null\n}\ntype AnyRetentionDetails = RetentionDetails\n/**\n * ### Event Retention\n\n * There may be a cost associated with storing data forever,\n * so relays may wish to state retention times. The values\n * stated here are defaults for unauthenticated users and\n * visitors. Paid users would likely have other policies.\n\n * Retention times are given in seconds, with `null`\n * indicating infinity. If zero is provided, this means the\n * event will not be stored at all, and preferably an error\n * will be provided when those are received.\n * ```json\n{\n...\n \"retention\": [\n { \"kinds\": [0, 1, [5, 7], [40, 49]], \"time\": 3600 },\n { \"kinds\": [[40000, 49999]], \"time\": 100 },\n { \"kinds\": [[30000, 39999]], \"count\": 1000 },\n { \"time\": 3600, \"count\": 10000 }\n ]\n...\n}\n```\n * @param retention is a list of specifications: each will\n * apply to either all kinds, or a subset of kinds. Ranges\n * may be specified for the kind field as a tuple of\n * inclusive start and end values. Events of indicated kind\n * (or all) are then limited to a `count` and/or time\n * period.\n\n * It is possible to effectively blacklist Nostr-based\n * protocols that rely on a specific `kind` number, by\n * giving a retention time of zero for those `kind` values.\n * While that is unfortunate, it does allow clients to\n * discover servers that will support their protocol quickly\n * via a single HTTP fetch.\n\n * There is no need to specify retention times for\n * _ephemeral events_ as defined in [NIP-16](16.md) since\n * they are not retained.\n */\nexport interface Retention {\n retention: AnyRetentionDetails[]\n}\n\n/**\n * Some relays may be governed by the arbitrary laws of a\n * nation state. This may limit what content can be stored\n * in cleartext on those relays. All clients are encouraged\n * to use encryption to work around this limitation.\n\n * It is not possible to describe the limitations of each\n * country's laws and policies which themselves are\n * typically vague and constantly shifting.\n\n * Therefore, this field allows the relay operator to\n * indicate which countries' laws might end up being\n * enforced on them, and then indirectly on their users'\n * content.\n\n * Users should be able to avoid relays in countries they\n * don't like, and/or select relays in more favourable\n * zones. Exposing this flexibility is up to the client\n * software.\n\n * @param relay_countries a list of two-level ISO country\n * codes (ISO 3166-1 alpha-2) whose laws and policies may\n * affect this relay. `EU` may be used for European Union\n * countries.\n\n * Remember that a relay may be hosted in a country which is\n * not the country of the legal entities who own the relay,\n * so it's very likely a number of countries are involved.\n */\nexport interface ContentLimitations {\n relay_countries: string[]\n}\n\n/**\n * ### Community Preferences\n\n * For public text notes at least, a relay may try to foster\n * a local community. This would encourage users to follow\n * the global feed on that relay, in addition to their usual\n * individual follows. To support this goal, relays MAY\n * specify some of the following values.\n\n * @param language_tags is an ordered list of [IETF\n * language\n * tags](https://en.wikipedia.org/wiki/IETF_language_tag\n * indicating the major languages spoken on the relay.\n * @param tags is a list of limitations on the topics to be\n * discussed. For example `sfw-only` indicates that only\n * \"Safe For Work\" content is encouraged on this relay. This\n * relies on assumptions of what the \"work\" \"community\"\n * feels \"safe\" talking about. In time, a common set of tags\n * may emerge that allow users to find relays that suit\n * their needs, and client software will be able to parse\n * these tags easily. The `bitcoin-only` tag indicates that\n * any _altcoin_, _\"crypto\"_ or _blockchain_ comments will\n * be ridiculed without mercy.\n * @param posting_policy is a link to a human-readable page\n * which specifies the community policies for the relay. In\n * cases where `sfw-only` is True, it's important to link to\n * a page which gets into the specifics of your posting\n * policy.\n\n * The `description` field should be used to describe your\n * community goals and values, in brief. The\n * `posting_policy` is for additional detail and legal\n * terms. Use the `tags` field to signify limitations on\n * content, or topics to be discussed, which could be\n * machine processed by appropriate client software.\n */\nexport interface CommunityPreferences {\n language_tags: string[]\n tags: string[]\n posting_policy: string\n}\n\nexport interface Amount {\n amount: number\n unit: 'msat'\n}\nexport interface PublicationAmount extends Amount {\n kinds: number[]\n}\nexport interface Subscription extends Amount {\n period: number\n}\nexport interface Fees {\n admission: Amount[]\n subscription: Subscription[]\n publication: PublicationAmount[]\n}\n/**\n * Relays that require payments may want to expose their fee\n * schedules.\n */\nexport interface PayToRelay {\n payments_url: string\n fees: Fees\n}\n\n/**\n * A URL pointing to an image to be used as an icon for the\n * relay. Recommended to be squared in shape.\n */\nexport interface Icon {\n icon: string\n}\n\nexport type RelayInformation = BasicRelayInformation &\n Partial & {\n limitation?: Partial\n } & Partial &\n Partial &\n Partial &\n Partial\n", "import { bytesToHex } from '@noble/hashes/utils'\nimport { type UnsignedEvent, type Event } from './pure.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\n/** Get POW difficulty from a Nostr hex ID. */\nexport function getPow(hex: string): number {\n let count = 0\n\n for (let i = 0; i < 64; i += 8) {\n const nibble = parseInt(hex.substring(i, i + 8), 16)\n if (nibble === 0) {\n count += 32\n } else {\n count += Math.clz32(nibble)\n break\n }\n }\n\n return count\n}\n\n/**\n * Mine an event with the desired POW. This function mutates the event.\n * Note that this operation is synchronous and should be run in a worker context to avoid blocking the main thread.\n */\nexport function minePow(unsigned: UnsignedEvent, difficulty: number): Omit {\n let count = 0\n\n const event = unsigned as Omit\n const tag = ['nonce', count.toString(), difficulty.toString()]\n\n event.tags.push(tag)\n\n while (true) {\n const now = Math.floor(new Date().getTime() / 1000)\n\n if (now !== event.created_at) {\n count = 0\n event.created_at = now\n }\n\n tag[1] = (++count).toString()\n\n event.id = fastEventHash(event)\n\n if (getPow(event.id) >= difficulty) {\n break\n }\n }\n\n return event\n}\n\nexport function fastEventHash(evt: UnsignedEvent): string {\n return bytesToHex(\n sha256(utf8Encoder.encode(JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]))),\n )\n}\n", "import { PrivateDirectMessage } from './kinds.ts'\nimport { EventTemplate, NostrEvent, getPublicKey } from './pure.ts'\nimport * as nip59 from './nip59.ts'\n\ntype Recipient = {\n publicKey: string\n relayUrl?: string\n}\n\ntype ReplyTo = {\n eventId: string\n relayUrl?: string\n}\n\nfunction createEvent(\n recipients: Recipient | Recipient[],\n message: string,\n conversationTitle?: string,\n replyTo?: ReplyTo,\n): EventTemplate {\n const baseEvent: EventTemplate = {\n created_at: Math.ceil(Date.now() / 1000),\n kind: PrivateDirectMessage,\n tags: [],\n content: message,\n }\n\n const recipientsArray = Array.isArray(recipients) ? recipients : [recipients]\n\n recipientsArray.forEach(({ publicKey, relayUrl }) => {\n baseEvent.tags.push(relayUrl ? ['p', publicKey, relayUrl] : ['p', publicKey])\n })\n\n if (replyTo) {\n baseEvent.tags.push(['e', replyTo.eventId, replyTo.relayUrl || '', 'reply'])\n }\n\n if (conversationTitle) {\n baseEvent.tags.push(['subject', conversationTitle])\n }\n\n return baseEvent\n}\n\nexport function wrapEvent(\n senderPrivateKey: Uint8Array,\n recipient: Recipient,\n message: string,\n conversationTitle?: string,\n replyTo?: ReplyTo,\n): NostrEvent {\n const event = createEvent(recipient, message, conversationTitle, replyTo)\n return nip59.wrapEvent(event, senderPrivateKey, recipient.publicKey)\n}\n\nexport function wrapManyEvents(\n senderPrivateKey: Uint8Array,\n recipients: Recipient[],\n message: string,\n conversationTitle?: string,\n replyTo?: ReplyTo,\n): NostrEvent[] {\n if (!recipients || recipients.length === 0) {\n throw new Error('At least one recipient is required.')\n }\n\n const senderPublicKey = getPublicKey(senderPrivateKey)\n\n // wrap the event for the sender and then for each recipient\n return [{ publicKey: senderPublicKey }, ...recipients].map(recipient =>\n wrapEvent(senderPrivateKey, recipient, message, conversationTitle, replyTo),\n )\n}\n\nexport const unwrapEvent = nip59.unwrapEvent\n\nexport const unwrapManyEvents = nip59.unwrapManyEvents\n", "import { EventTemplate, UnsignedEvent, NostrEvent } from './core.ts'\nimport { getConversationKey, decrypt, encrypt } from './nip44.ts'\nimport { getEventHash, generateSecretKey, finalizeEvent, getPublicKey } from './pure.ts'\nimport { Seal, GiftWrap } from './kinds.ts'\n\ntype Rumor = UnsignedEvent & { id: string }\n\nconst TWO_DAYS = 2 * 24 * 60 * 60\n\nconst now = () => Math.round(Date.now() / 1000)\nconst randomNow = () => Math.round(now() - Math.random() * TWO_DAYS)\n\nconst nip44ConversationKey = (privateKey: Uint8Array, publicKey: string) => getConversationKey(privateKey, publicKey)\n\nconst nip44Encrypt = (data: EventTemplate, privateKey: Uint8Array, publicKey: string) =>\n encrypt(JSON.stringify(data), nip44ConversationKey(privateKey, publicKey))\n\nconst nip44Decrypt = (data: NostrEvent, privateKey: Uint8Array) =>\n JSON.parse(decrypt(data.content, nip44ConversationKey(privateKey, data.pubkey)))\n\nexport function createRumor(event: Partial, privateKey: Uint8Array): Rumor {\n const rumor = {\n created_at: now(),\n content: '',\n tags: [],\n ...event,\n pubkey: getPublicKey(privateKey),\n } as any\n\n rumor.id = getEventHash(rumor)\n\n return rumor as Rumor\n}\n\nexport function createSeal(rumor: Rumor, privateKey: Uint8Array, recipientPublicKey: string): NostrEvent {\n return finalizeEvent(\n {\n kind: Seal,\n content: nip44Encrypt(rumor, privateKey, recipientPublicKey),\n created_at: randomNow(),\n tags: [],\n },\n privateKey,\n )\n}\n\nexport function createWrap(seal: NostrEvent, recipientPublicKey: string): NostrEvent {\n const randomKey = generateSecretKey()\n\n return finalizeEvent(\n {\n kind: GiftWrap,\n content: nip44Encrypt(seal, randomKey, recipientPublicKey),\n created_at: randomNow(),\n tags: [['p', recipientPublicKey]],\n },\n randomKey,\n ) as NostrEvent\n}\n\nexport function wrapEvent(\n event: Partial,\n senderPrivateKey: Uint8Array,\n recipientPublicKey: string,\n): NostrEvent {\n const rumor = createRumor(event, senderPrivateKey)\n\n const seal = createSeal(rumor, senderPrivateKey, recipientPublicKey)\n return createWrap(seal, recipientPublicKey)\n}\n\nexport function wrapManyEvents(\n event: Partial,\n senderPrivateKey: Uint8Array,\n recipientsPublicKeys: string[],\n): NostrEvent[] {\n if (!recipientsPublicKeys || recipientsPublicKeys.length === 0) {\n throw new Error('At least one recipient is required.')\n }\n\n const senderPublicKey = getPublicKey(senderPrivateKey)\n\n const wrappeds = [wrapEvent(event, senderPrivateKey, senderPublicKey)]\n\n recipientsPublicKeys.forEach(recipientPublicKey => {\n wrappeds.push(wrapEvent(event, senderPrivateKey, recipientPublicKey))\n })\n\n return wrappeds\n}\n\nexport function unwrapEvent(wrap: NostrEvent, recipientPrivateKey: Uint8Array): Rumor {\n const unwrappedSeal = nip44Decrypt(wrap, recipientPrivateKey)\n return nip44Decrypt(unwrappedSeal, recipientPrivateKey)\n}\n\nexport function unwrapManyEvents(wrappedEvents: NostrEvent[], recipientPrivateKey: Uint8Array): Rumor[] {\n let unwrappedEvents: Rumor[] = []\n\n wrappedEvents.forEach(e => {\n unwrappedEvents.push(unwrapEvent(e, recipientPrivateKey))\n })\n\n unwrappedEvents.sort((a, b) => a.created_at - b.created_at)\n\n return unwrappedEvents\n}\n", "import { chacha20 } from '@noble/ciphers/chacha'\nimport { equalBytes } from '@noble/ciphers/utils'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { extract as hkdf_extract, expand as hkdf_expand } from '@noble/hashes/hkdf'\nimport { hmac } from '@noble/hashes/hmac'\nimport { sha256 } from '@noble/hashes/sha256'\nimport { concatBytes, randomBytes } from '@noble/hashes/utils'\nimport { base64 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nconst minPlaintextSize = 0x0001 // 1b msg => padded to 32b\nconst maxPlaintextSize = 0xffff // 65535 (64kb-1) => padded to 64kb\n\nexport function getConversationKey(privkeyA: Uint8Array, pubkeyB: string): Uint8Array {\n const sharedX = secp256k1.getSharedSecret(privkeyA, '02' + pubkeyB).subarray(1, 33)\n return hkdf_extract(sha256, sharedX, 'nip44-v2')\n}\n\nfunction getMessageKeys(\n conversationKey: Uint8Array,\n nonce: Uint8Array,\n): { chacha_key: Uint8Array; chacha_nonce: Uint8Array; hmac_key: Uint8Array } {\n const keys = hkdf_expand(sha256, conversationKey, nonce, 76)\n return {\n chacha_key: keys.subarray(0, 32),\n chacha_nonce: keys.subarray(32, 44),\n hmac_key: keys.subarray(44, 76),\n }\n}\n\nfunction calcPaddedLen(len: number): number {\n if (!Number.isSafeInteger(len) || len < 1) throw new Error('expected positive integer')\n if (len <= 32) return 32\n const nextPower = 1 << (Math.floor(Math.log2(len - 1)) + 1)\n const chunk = nextPower <= 256 ? 32 : nextPower / 8\n return chunk * (Math.floor((len - 1) / chunk) + 1)\n}\n\nfunction writeU16BE(num: number): Uint8Array {\n if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize)\n throw new Error('invalid plaintext size: must be between 1 and 65535 bytes')\n const arr = new Uint8Array(2)\n new DataView(arr.buffer).setUint16(0, num, false)\n return arr\n}\n\nfunction pad(plaintext: string): Uint8Array {\n const unpadded = utf8Encoder.encode(plaintext)\n const unpaddedLen = unpadded.length\n const prefix = writeU16BE(unpaddedLen)\n const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen)\n return concatBytes(prefix, unpadded, suffix)\n}\n\nfunction unpad(padded: Uint8Array): string {\n const unpaddedLen = new DataView(padded.buffer).getUint16(0)\n const unpadded = padded.subarray(2, 2 + unpaddedLen)\n if (\n unpaddedLen < minPlaintextSize ||\n unpaddedLen > maxPlaintextSize ||\n unpadded.length !== unpaddedLen ||\n padded.length !== 2 + calcPaddedLen(unpaddedLen)\n )\n throw new Error('invalid padding')\n return utf8Decoder.decode(unpadded)\n}\n\nfunction hmacAad(key: Uint8Array, message: Uint8Array, aad: Uint8Array): Uint8Array {\n if (aad.length !== 32) throw new Error('AAD associated data must be 32 bytes')\n const combined = concatBytes(aad, message)\n return hmac(sha256, key, combined)\n}\n\n// metadata: always 65b (version: 1b, nonce: 32b, max: 32b)\n// plaintext: 1b to 0xffff\n// padded plaintext: 32b to 0xffff\n// ciphertext: 32b+2 to 0xffff+2\n// raw payload: 99 (65+32+2) to 65603 (65+0xffff+2)\n// compressed payload (base64): 132b to 87472b\nfunction decodePayload(payload: string): { nonce: Uint8Array; ciphertext: Uint8Array; mac: Uint8Array } {\n if (typeof payload !== 'string') throw new Error('payload must be a valid string')\n const plen = payload.length\n if (plen < 132 || plen > 87472) throw new Error('invalid payload length: ' + plen)\n if (payload[0] === '#') throw new Error('unknown encryption version')\n let data: Uint8Array\n try {\n data = base64.decode(payload)\n } catch (error) {\n throw new Error('invalid base64: ' + (error as any).message)\n }\n const dlen = data.length\n if (dlen < 99 || dlen > 65603) throw new Error('invalid data length: ' + dlen)\n const vers = data[0]\n if (vers !== 2) throw new Error('unknown encryption version ' + vers)\n return {\n nonce: data.subarray(1, 33),\n ciphertext: data.subarray(33, -32),\n mac: data.subarray(-32),\n }\n}\n\nexport function encrypt(plaintext: string, conversationKey: Uint8Array, nonce: Uint8Array = randomBytes(32)): string {\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n const padded = pad(plaintext)\n const ciphertext = chacha20(chacha_key, chacha_nonce, padded)\n const mac = hmacAad(hmac_key, ciphertext, nonce)\n return base64.encode(concatBytes(new Uint8Array([2]), nonce, ciphertext, mac))\n}\n\nexport function decrypt(payload: string, conversationKey: Uint8Array): string {\n const { nonce, ciphertext, mac } = decodePayload(payload)\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n const calculatedMac = hmacAad(hmac_key, ciphertext, nonce)\n if (!equalBytes(calculatedMac, mac)) throw new Error('invalid MAC')\n const padded = chacha20(chacha_key, chacha_nonce, ciphertext)\n return unpad(padded)\n}\n\nexport const v2 = {\n utils: {\n getConversationKey,\n calcPaddedLen,\n },\n encrypt,\n decrypt,\n}\n", "import { exists as aexists, bytes as abytes, output as aoutput } from './_assert.js';\nimport { Input, toBytes, Hash } from './utils.js';\n\n// Poly1305 is a fast and parallel secret-key message-authentication code.\n// https://cr.yp.to/mac.html, https://cr.yp.to/mac/poly1305-20050329.pdf\n// https://datatracker.ietf.org/doc/html/rfc8439\n\n// Based on Public Domain poly1305-donna https://github.com/floodyberry/poly1305-donna\nconst u8to16 = (a: Uint8Array, i: number) => (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);\nclass Poly1305 implements Hash {\n readonly blockLen = 16;\n readonly outputLen = 16;\n private buffer = new Uint8Array(16);\n private r = new Uint16Array(10);\n private h = new Uint16Array(10);\n private pad = new Uint16Array(8);\n private pos = 0;\n protected finished = false;\n\n constructor(key: Input) {\n key = toBytes(key);\n abytes(key, 32);\n const t0 = u8to16(key, 0);\n const t1 = u8to16(key, 2);\n const t2 = u8to16(key, 4);\n const t3 = u8to16(key, 6);\n const t4 = u8to16(key, 8);\n const t5 = u8to16(key, 10);\n const t6 = u8to16(key, 12);\n const t7 = u8to16(key, 14);\n\n // https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47\n this.r[0] = t0 & 0x1fff;\n this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this.r[5] = (t4 >>> 1) & 0x1ffe;\n this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this.r[9] = (t7 >>> 5) & 0x007f;\n for (let i = 0; i < 8; i++) this.pad[i] = u8to16(key, 16 + 2 * i);\n }\n\n private process(data: Uint8Array, offset: number, isLast = false) {\n const hibit = isLast ? 0 : 1 << 11;\n const { h, r } = this;\n const r0 = r[0];\n const r1 = r[1];\n const r2 = r[2];\n const r3 = r[3];\n const r4 = r[4];\n const r5 = r[5];\n const r6 = r[6];\n const r7 = r[7];\n const r8 = r[8];\n const r9 = r[9];\n\n const t0 = u8to16(data, offset + 0);\n const t1 = u8to16(data, offset + 2);\n const t2 = u8to16(data, offset + 4);\n const t3 = u8to16(data, offset + 6);\n const t4 = u8to16(data, offset + 8);\n const t5 = u8to16(data, offset + 10);\n const t6 = u8to16(data, offset + 12);\n const t7 = u8to16(data, offset + 14);\n\n let h0 = h[0] + (t0 & 0x1fff);\n let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);\n let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);\n let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);\n let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);\n let h5 = h[5] + ((t4 >>> 1) & 0x1fff);\n let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);\n let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);\n let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);\n let h9 = h[9] + ((t7 >>> 5) | hibit);\n\n let c = 0;\n\n let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);\n c = d0 >>> 13;\n d0 &= 0x1fff;\n d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);\n c += d0 >>> 13;\n d0 &= 0x1fff;\n\n let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);\n c = d1 >>> 13;\n d1 &= 0x1fff;\n d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);\n c += d1 >>> 13;\n d1 &= 0x1fff;\n\n let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);\n c = d2 >>> 13;\n d2 &= 0x1fff;\n d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);\n c += d2 >>> 13;\n d2 &= 0x1fff;\n\n let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);\n c = d3 >>> 13;\n d3 &= 0x1fff;\n d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);\n c += d3 >>> 13;\n d3 &= 0x1fff;\n\n let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;\n c = d4 >>> 13;\n d4 &= 0x1fff;\n d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);\n c += d4 >>> 13;\n d4 &= 0x1fff;\n\n let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;\n c = d5 >>> 13;\n d5 &= 0x1fff;\n d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);\n c += d5 >>> 13;\n d5 &= 0x1fff;\n\n let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;\n c = d6 >>> 13;\n d6 &= 0x1fff;\n d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);\n c += d6 >>> 13;\n d6 &= 0x1fff;\n\n let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;\n c = d7 >>> 13;\n d7 &= 0x1fff;\n d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);\n c += d7 >>> 13;\n d7 &= 0x1fff;\n\n let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;\n c = d8 >>> 13;\n d8 &= 0x1fff;\n d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);\n c += d8 >>> 13;\n d8 &= 0x1fff;\n\n let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;\n c = d9 >>> 13;\n d9 &= 0x1fff;\n d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;\n c += d9 >>> 13;\n d9 &= 0x1fff;\n\n c = ((c << 2) + c) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = c >>> 13;\n d1 += c;\n\n h[0] = d0;\n h[1] = d1;\n h[2] = d2;\n h[3] = d3;\n h[4] = d4;\n h[5] = d5;\n h[6] = d6;\n h[7] = d7;\n h[8] = d8;\n h[9] = d9;\n }\n\n private finalize() {\n const { h, pad } = this;\n const g = new Uint16Array(10);\n let c = h[1] >>> 13;\n h[1] &= 0x1fff;\n for (let i = 2; i < 10; i++) {\n h[i] += c;\n c = h[i] >>> 13;\n h[i] &= 0x1fff;\n }\n h[0] += c * 5;\n c = h[0] >>> 13;\n h[0] &= 0x1fff;\n h[1] += c;\n c = h[1] >>> 13;\n h[1] &= 0x1fff;\n h[2] += c;\n\n g[0] = h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (let i = 1; i < 10; i++) {\n g[i] = h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= 1 << 13;\n\n let mask = (c ^ 1) - 1;\n for (let i = 0; i < 10; i++) g[i] &= mask;\n mask = ~mask;\n for (let i = 0; i < 10; i++) h[i] = (h[i] & mask) | g[i];\n h[0] = (h[0] | (h[1] << 13)) & 0xffff;\n h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;\n h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;\n h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;\n h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;\n h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;\n h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;\n h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;\n\n let f = h[0] + pad[0];\n h[0] = f & 0xffff;\n for (let i = 1; i < 8; i++) {\n f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;\n h[i] = f & 0xffff;\n }\n }\n update(data: Input): this {\n aexists(this);\n const { buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input\n if (take === blockLen) {\n for (; blockLen <= len - pos; pos += blockLen) this.process(data, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(buffer, 0, false);\n this.pos = 0;\n }\n }\n return this;\n }\n destroy() {\n this.h.fill(0);\n this.r.fill(0);\n this.buffer.fill(0);\n this.pad.fill(0);\n }\n digestInto(out: Uint8Array) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { buffer, h } = this;\n let { pos } = this;\n if (pos) {\n buffer[pos++] = 1;\n // buffer.subarray(pos).fill(0);\n for (; pos < 16; pos++) buffer[pos] = 0;\n this.process(buffer, 0, true);\n }\n this.finalize();\n let opos = 0;\n for (let i = 0; i < 8; i++) {\n out[opos++] = h[i] >>> 0;\n out[opos++] = h[i] >>> 8;\n }\n return out;\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n}\n\nexport type CHash = ReturnType;\nexport function wrapConstructorWithKey>(hashCons: (key: Input) => Hash) {\n const hashC = (msg: Input, key: Input): Uint8Array => hashCons(key).update(toBytes(msg)).digest();\n const tmp = hashCons(new Uint8Array(32));\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (key: Input) => hashCons(key);\n return hashC;\n}\n\nexport const poly1305 = wrapConstructorWithKey((key) => new Poly1305(key));\n", "// Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.\nimport { number as anumber, bytes as abytes, bool as abool } from './_assert.js';\nimport { XorStream, checkOpts, u32, utf8ToBytes } from './utils.js';\n\n/*\nRFC8439 requires multi-step cipher stream, where\nauthKey starts with counter: 0, actual msg with counter: 1.\n\nFor this, we need a way to re-use nonce / counter:\n\n const counter = new Uint8Array(4);\n chacha(..., counter, ...); // counter is now 1\n chacha(..., counter, ...); // counter is now 2\n\nThis is complicated:\n\n- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB\n- Original papers don't allow mutating counters\n- Counter overflow is undefined [^1]\n- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it\n- Caveat: Cannot be re-used through all cases:\n- * chacha has (counter | nonce)\n- * xchacha has (nonce16 | counter | nonce16)\n- Idea B: separate nonce / counter and provide separate API for counter re-use\n- Caveat: there are different counter sizes depending on an algorithm.\n- salsa & chacha also differ in structures of key & sigma:\n salsa20: s[0] | k(4) | s[1] | nonce(2) | ctr(2) | s[2] | k(4) | s[3]\n chacha: s(4) | k(8) | ctr(1) | nonce(3)\n chacha20orig: s(4) | k(8) | ctr(2) | nonce(2)\n- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`\n- Caveat: we can't re-use counter array\n\nxchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal\n(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce).\n\n[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/\n[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2\n*/\n\nconst sigma16 = utf8ToBytes('expand 16-byte k');\nconst sigma32 = utf8ToBytes('expand 32-byte k');\nconst sigma16_32 = u32(sigma16);\nconst sigma32_32 = u32(sigma32);\n\nexport function rotl(a: number, b: number): number {\n return (a << b) | (a >>> (32 - b));\n}\n\nexport type CipherCoreFn = (\n sigma: Uint32Array,\n key: Uint32Array,\n nonce: Uint32Array,\n output: Uint32Array,\n counter: number,\n rounds?: number\n) => void;\n\nexport type ExtendNonceFn = (\n sigma: Uint32Array,\n key: Uint32Array,\n input: Uint32Array,\n output: Uint32Array\n) => void;\n\nexport type CipherOpts = {\n allowShortKeys?: boolean; // Original salsa / chacha allow 16-byte keys\n extendNonceFn?: ExtendNonceFn;\n counterLength?: number;\n counterRight?: boolean; // right: nonce|counter; left: counter|nonce\n rounds?: number;\n};\n\n// Is byte array aligned to 4 byte offset (u32)?\nfunction isAligned32(b: Uint8Array) {\n return b.byteOffset % 4 === 0;\n}\n\n// Salsa and Chacha block length is always 512-bit\nconst BLOCK_LEN = 64;\nconst BLOCK_LEN32 = 16;\n\n// new Uint32Array([2**32]) // => Uint32Array(1) [ 0 ]\n// new Uint32Array([2**32-1]) // => Uint32Array(1) [ 4294967295 ]\nconst MAX_COUNTER = 2 ** 32 - 1;\n\nconst U32_EMPTY = new Uint32Array();\nfunction runCipher(\n core: CipherCoreFn,\n sigma: Uint32Array,\n key: Uint32Array,\n nonce: Uint32Array,\n data: Uint8Array,\n output: Uint8Array,\n counter: number,\n rounds: number\n): void {\n const len = data.length;\n const block = new Uint8Array(BLOCK_LEN);\n const b32 = u32(block);\n // Make sure that buffers aligned to 4 bytes\n const isAligned = isAligned32(data) && isAligned32(output);\n const d32 = isAligned ? u32(data) : U32_EMPTY;\n const o32 = isAligned ? u32(output) : U32_EMPTY;\n for (let pos = 0; pos < len; counter++) {\n core(sigma, key, nonce, b32, counter, rounds);\n if (counter >= MAX_COUNTER) throw new Error('arx: counter overflow');\n const take = Math.min(BLOCK_LEN, len - pos);\n // aligned to 4 bytes\n if (isAligned && take === BLOCK_LEN) {\n const pos32 = pos / 4;\n if (pos % 4 !== 0) throw new Error('arx: invalid block position');\n for (let j = 0, posj: number; j < BLOCK_LEN32; j++) {\n posj = pos32 + j;\n o32[posj] = d32[posj] ^ b32[j];\n }\n pos += BLOCK_LEN;\n continue;\n }\n for (let j = 0, posj; j < take; j++) {\n posj = pos + j;\n output[posj] = data[posj] ^ block[j];\n }\n pos += take;\n }\n}\n\nexport function createCipher(core: CipherCoreFn, opts: CipherOpts): XorStream {\n const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts(\n { allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 },\n opts\n );\n if (typeof core !== 'function') throw new Error('core must be a function');\n anumber(counterLength);\n anumber(rounds);\n abool(counterRight);\n abool(allowShortKeys);\n return (\n key: Uint8Array,\n nonce: Uint8Array,\n data: Uint8Array,\n output?: Uint8Array,\n counter = 0\n ): Uint8Array => {\n abytes(key);\n abytes(nonce);\n abytes(data);\n const len = data.length;\n if (!output) output = new Uint8Array(len);\n abytes(output);\n anumber(counter);\n if (counter < 0 || counter >= MAX_COUNTER) throw new Error('arx: counter overflow');\n if (output.length < len)\n throw new Error(`arx: output (${output.length}) is shorter than data (${len})`);\n const toClean = [];\n\n // Key & sigma\n // key=16 -> sigma16, k=key|key\n // key=32 -> sigma32, k=key\n let l = key.length,\n k: Uint8Array,\n sigma: Uint32Array;\n if (l === 32) {\n k = key.slice();\n toClean.push(k);\n sigma = sigma32_32;\n } else if (l === 16 && allowShortKeys) {\n k = new Uint8Array(32);\n k.set(key);\n k.set(key, 16);\n sigma = sigma16_32;\n toClean.push(k);\n } else {\n throw new Error(`arx: invalid 32-byte key, got length=${l}`);\n }\n\n // Nonce\n // salsa20: 8 (8-byte counter)\n // chacha20orig: 8 (8-byte counter)\n // chacha20: 12 (4-byte counter)\n // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)\n // xchacha20: 24 (16 -> hchacha, 8 -> old nonce)\n // Align nonce to 4 bytes\n if (!isAligned32(nonce)) {\n nonce = nonce.slice();\n toClean.push(nonce);\n }\n\n const k32 = u32(k);\n // hsalsa & hchacha: handle extended nonce\n if (extendNonceFn) {\n if (nonce.length !== 24) throw new Error(`arx: extended nonce must be 24 bytes`);\n extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32);\n nonce = nonce.subarray(16);\n }\n\n // Handle nonce counter\n const nonceNcLen = 16 - counterLength;\n if (nonceNcLen !== nonce.length)\n throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);\n\n // Pad counter when nonce is 64 bit\n if (nonceNcLen !== 12) {\n const nc = new Uint8Array(12);\n nc.set(nonce, counterRight ? 0 : 12 - nonce.length);\n nonce = nc;\n toClean.push(nonce);\n }\n const n32 = u32(nonce);\n runCipher(core, sigma, k32, n32, data, output, counter, rounds);\n while (toClean.length > 0) toClean.pop()!.fill(0);\n return output;\n };\n}\n", "// prettier-ignore\nimport {\n wrapCipher, CipherWithOutput, XorStream, createView, equalBytes, setBigUint64,\n} from './utils.js';\nimport { poly1305 } from './_poly1305.js';\nimport { createCipher, rotl } from './_arx.js';\nimport { bytes as abytes } from './_assert.js';\n\n// ChaCha20 stream cipher was released in 2008. ChaCha aims to increase\n// the diffusion per round, but had slightly less cryptanalysis.\n// https://cr.yp.to/chacha.html, http://cr.yp.to/chacha/chacha-20080128.pdf\n\n/**\n * ChaCha core function.\n */\n// prettier-ignore\nfunction chachaCore(\n s: Uint32Array, k: Uint32Array, n: Uint32Array, out: Uint32Array, cnt: number, rounds = 20\n): void {\n let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // \"expa\" \"nd 3\" \"2-by\" \"te k\"\n y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key\n y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key\n y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Counter\tNonce Nonce\n // Save state to temporary variables\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03,\n x04 = y04, x05 = y05, x06 = y06, x07 = y07,\n x08 = y08, x09 = y09, x10 = y10, x11 = y11,\n x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n for (let r = 0; r < rounds; r += 2) {\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);\n\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);\n\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^x02, 8);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);\n\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);\n\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);\n\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);\n\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);\n\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);\n }\n // Write output\n let oi = 0;\n out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0;\n}\n/**\n * hchacha helper method, used primarily in xchacha, to hash\n * key and nonce into key' and nonce'.\n * Same as chachaCore, but there doesn't seem to be a way to move the block\n * out without 25% performance hit.\n */\n// prettier-ignore\nexport function hchacha(\n s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array\n) {\n let x00 = s[0], x01 = s[1], x02 = s[2], x03 = s[3],\n x04 = k[0], x05 = k[1], x06 = k[2], x07 = k[3],\n x08 = k[4], x09 = k[5], x10 = k[6], x11 = k[7],\n x12 = i[0], x13 = i[1], x14 = i[2], x15 = i[3];\n for (let r = 0; r < 20; r += 2) {\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);\n\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);\n\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);\n\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);\n\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);\n\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);\n\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);\n\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);\n }\n let oi = 0;\n o32[oi++] = x00; o32[oi++] = x01;\n o32[oi++] = x02; o32[oi++] = x03;\n o32[oi++] = x12; o32[oi++] = x13;\n o32[oi++] = x14; o32[oi++] = x15;\n}\n/**\n * Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.\n */\nexport const chacha20orig = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n allowShortKeys: true,\n});\n/**\n * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.\n * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.\n */\nexport const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n allowShortKeys: false,\n});\n\n/**\n * XChaCha eXtended-nonce ChaCha. 24-byte nonce.\n * With 24-byte nonce, it's safe to use fill it with random (CSPRNG).\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha\n */\nexport const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n extendNonceFn: hchacha,\n allowShortKeys: false,\n});\n\n/**\n * Reduced 8-round chacha, described in original paper.\n */\nexport const chacha8 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 8,\n});\n\n/**\n * Reduced 12-round chacha, described in original paper.\n */\nexport const chacha12 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 12,\n});\n\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\n// Pad to digest size with zeros\nconst updatePadded = (h: ReturnType, msg: Uint8Array) => {\n h.update(msg);\n const left = msg.length % 16;\n if (left) h.update(ZEROS16.subarray(left));\n};\n\nconst ZEROS32 = /* @__PURE__ */ new Uint8Array(32);\nfunction computeTag(\n fn: XorStream,\n key: Uint8Array,\n nonce: Uint8Array,\n data: Uint8Array,\n AAD?: Uint8Array\n): Uint8Array {\n const authKey = fn(key, nonce, ZEROS32);\n const h = poly1305.create(authKey);\n if (AAD) updatePadded(h, AAD);\n updatePadded(h, data);\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(data.length), true);\n h.update(num);\n const res = h.digest();\n authKey.fill(0);\n return res;\n}\n\n/**\n * AEAD algorithm from RFC 8439.\n * Salsa20 and chacha (RFC 8439) use poly1305 differently.\n * We could have composed them similar to:\n * https://github.com/paulmillr/scure-base/blob/b266c73dde977b1dd7ef40ef7a23cc15aab526b3/index.ts#L250\n * But it's hard because of authKey:\n * In salsa20, authKey changes position in salsa stream.\n * In chacha, authKey can't be computed inside computeTag, it modifies the counter.\n */\nexport const _poly1305_aead =\n (xorStream: XorStream) =>\n (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): CipherWithOutput => {\n const tagLength = 16;\n abytes(key, 32);\n abytes(nonce);\n return {\n encrypt: (plaintext: Uint8Array, output?: Uint8Array) => {\n const plength = plaintext.length;\n const clength = plength + tagLength;\n if (output) {\n abytes(output, clength);\n } else {\n output = new Uint8Array(clength);\n }\n xorStream(key, nonce, plaintext, output, 1);\n const tag = computeTag(xorStream, key, nonce, output.subarray(0, -tagLength), AAD);\n output.set(tag, plength); // append tag\n return output;\n },\n decrypt: (ciphertext: Uint8Array, output?: Uint8Array) => {\n const clength = ciphertext.length;\n const plength = clength - tagLength;\n if (clength < tagLength)\n throw new Error(`encrypted data must be at least ${tagLength} bytes`);\n if (output) {\n abytes(output, plength);\n } else {\n output = new Uint8Array(plength);\n }\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = computeTag(xorStream, key, nonce, data, AAD);\n if (!equalBytes(passedTag, tag)) throw new Error('invalid tag');\n xorStream(key, nonce, data, output, 1);\n return output;\n },\n };\n };\n\n/**\n * ChaCha20-Poly1305 from RFC 8439.\n * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.\n */\nexport const chacha20poly1305 = /* @__PURE__ */ wrapCipher(\n { blockSize: 64, nonceLength: 12, tagLength: 16 },\n _poly1305_aead(chacha20)\n);\n/**\n * XChaCha20-Poly1305 extended-nonce chacha.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha\n * With 24-byte nonce, it's safe to use fill it with random (CSPRNG).\n */\nexport const xchacha20poly1305 = /* @__PURE__ */ wrapCipher(\n { blockSize: 64, nonceLength: 24, tagLength: 16 },\n _poly1305_aead(xchacha20)\n);\n", "import assert from './_assert.js';\nimport { Hash, CHash, Input, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC> extends Hash> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: CHash, _key: Input) {\n super();\n assert.hash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf: Input) {\n assert.exists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array) {\n assert.exists(this);\n assert.bytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to?: HMAC): HMAC {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n */\nexport const hmac = (hash: CHash, key: Input, message: Input): Uint8Array =>\n new HMAC(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Input) => new HMAC(hash, key);\n", "import assert from './_assert.js';\nimport { CHash, Input, toBytes } from './utils.js';\nimport { hmac } from './hmac.js';\n\n// HKDF (RFC 5869)\n// https://soatok.blog/2021/11/17/understanding-hkdf/\n\n/**\n * HKDF-Extract(IKM, salt) -> PRK\n * Arguments position differs from spec (IKM is first one, since it is not optional)\n * @param hash\n * @param ikm\n * @param salt\n * @returns\n */\nexport function extract(hash: CHash, ikm: Input, salt?: Input) {\n assert.hash(hash);\n // NOTE: some libraries treat zero-length array as 'not provided';\n // we don't, since we have undefined as 'not provided'\n // https://github.com/RustCrypto/KDFs/issues/15\n if (salt === undefined) salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros\n return hmac(hash, toBytes(salt), toBytes(ikm));\n}\n\n// HKDF-Expand(PRK, info, L) -> OKM\nconst HKDF_COUNTER = new Uint8Array([0]);\nconst EMPTY_BUFFER = new Uint8Array();\n\n/**\n * HKDF-expand from the spec.\n * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in octets\n */\nexport function expand(hash: CHash, prk: Input, info?: Input, length: number = 32) {\n assert.hash(hash);\n assert.number(length);\n if (length > 255 * hash.outputLen) throw new Error('Length should be <= 255*HashLen');\n const blocks = Math.ceil(length / hash.outputLen);\n if (info === undefined) info = EMPTY_BUFFER;\n // first L(ength) octets of T\n const okm = new Uint8Array(blocks * hash.outputLen);\n // Re-use HMAC instance between blocks\n const HMAC = hmac.create(hash, prk);\n const HMACTmp = HMAC._cloneInto();\n const T = new Uint8Array(HMAC.outputLen);\n for (let counter = 0; counter < blocks; counter++) {\n HKDF_COUNTER[0] = counter + 1;\n // T(0) = empty string (zero length)\n // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)\n HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)\n .update(info)\n .update(HKDF_COUNTER)\n .digestInto(T);\n okm.set(T, hash.outputLen * counter);\n HMAC._cloneInto(HMACTmp);\n }\n HMAC.destroy();\n HMACTmp.destroy();\n T.fill(0);\n HKDF_COUNTER.fill(0);\n return okm.slice(0, length);\n}\n\n/**\n * HKDF (RFC 5869): extract + expand in one step.\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @param info - optional context and application specific information\n * @param length - length of output keying material in octets\n */\nexport const hkdf = (\n hash: CHash,\n ikm: Input,\n salt: Input | undefined,\n info: Input | undefined,\n length: number\n) => expand(hash, extract(hash, ikm, salt), info, length);\n", "import { GenericRepost, Repost, ShortTextNote } from './kinds.ts'\nimport { EventPointer } from './nip19.ts'\nimport { Event, finalizeEvent, verifyEvent } from './pure.ts'\n\nexport type RepostEventTemplate = {\n /**\n * Pass only non-nip18 tags if you have to.\n * Nip18 tags ('e' and 'p' tags pointing to the reposted event) will be added automatically.\n */\n tags?: string[][]\n\n /**\n * Pass an empty string to NOT include the stringified JSON of the reposted event.\n * Any other content will be ignored and replaced with the stringified JSON of the reposted event.\n * @default Stringified JSON of the reposted event\n */\n content?: ''\n\n created_at: number\n}\n\nexport function finishRepostEvent(\n t: RepostEventTemplate,\n reposted: Event,\n relayUrl: string,\n privateKey: Uint8Array,\n): Event {\n let kind: Repost | GenericRepost\n const tags = [...(t.tags ?? []), ['e', reposted.id, relayUrl], ['p', reposted.pubkey]]\n if (reposted.kind === ShortTextNote) {\n kind = Repost\n } else {\n kind = GenericRepost\n tags.push(['k', String(reposted.kind)])\n }\n\n return finalizeEvent(\n {\n kind,\n tags,\n content: t.content === '' || reposted.tags?.find(tag => tag[0] === '-') ? '' : JSON.stringify(reposted),\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\nexport function getRepostedEventPointer(event: Event): undefined | EventPointer {\n if (![Repost, GenericRepost].includes(event.kind)) {\n return undefined\n }\n\n let lastETag: undefined | string[]\n let lastPTag: undefined | string[]\n\n for (let i = event.tags.length - 1; i >= 0 && (lastETag === undefined || lastPTag === undefined); i--) {\n const tag = event.tags[i]\n if (tag.length >= 2) {\n if (tag[0] === 'e' && lastETag === undefined) {\n lastETag = tag\n } else if (tag[0] === 'p' && lastPTag === undefined) {\n lastPTag = tag\n }\n }\n }\n\n if (lastETag === undefined) {\n return undefined\n }\n\n return {\n id: lastETag[1],\n relays: [lastETag[2], lastPTag?.[2]].filter((x): x is string => typeof x === 'string'),\n author: lastPTag?.[1],\n }\n}\n\nexport type GetRepostedEventOptions = {\n skipVerification?: boolean\n}\n\nexport function getRepostedEvent(event: Event, { skipVerification }: GetRepostedEventOptions = {}): undefined | Event {\n const pointer = getRepostedEventPointer(event)\n\n if (pointer === undefined || event.content === '') {\n return undefined\n }\n\n let repostedEvent: undefined | Event\n\n try {\n repostedEvent = JSON.parse(event.content) as Event\n } catch (error) {\n return undefined\n }\n\n if (repostedEvent.id !== pointer.id) {\n return undefined\n }\n\n if (!skipVerification && !verifyEvent(repostedEvent)) {\n return undefined\n }\n\n return repostedEvent\n}\n", "import { AddressPointer, BECH32_REGEX, decode, EventPointer, ProfilePointer } from './nip19.ts'\n\n/** Nostr URI regex, eg `nostr:npub1...` */\nexport const NOSTR_URI_REGEX: RegExp = new RegExp(`nostr:(${BECH32_REGEX.source})`)\n\n/** Test whether the value is a Nostr URI. */\nexport function test(value: unknown): value is `nostr:${string}` {\n return typeof value === 'string' && new RegExp(`^${NOSTR_URI_REGEX.source}$`).test(value)\n}\n\n/** Parsed Nostr URI data. */\nexport interface NostrURI {\n /** Full URI including the `nostr:` protocol. */\n uri: `nostr:${string}`\n /** The bech32-encoded data (eg `npub1...`). */\n value: string\n /** Decoded bech32 string, according to NIP-19. */\n decoded:\n | {\n type: 'nevent'\n data: EventPointer\n }\n | {\n type: 'nprofile'\n data: ProfilePointer\n }\n | {\n type: 'naddr'\n data: AddressPointer\n }\n | {\n type: 'npub'\n data: string\n }\n | {\n type: 'nsec'\n data: Uint8Array\n }\n | {\n type: 'note'\n data: string\n }\n}\n\n/** Parse and decode a Nostr URI. */\nexport function parse(uri: string): NostrURI {\n const match = uri.match(new RegExp(`^${NOSTR_URI_REGEX.source}$`))\n if (!match) throw new Error(`Invalid Nostr URI: ${uri}`)\n return {\n uri: match[0] as `nostr:${string}`,\n value: match[1],\n decoded: decode(match[1]),\n }\n}\n", "import { Event, finalizeEvent } from './pure.ts'\nimport { Reaction } from './kinds.ts'\n\nimport type { EventPointer } from './nip19.ts'\n\nexport type ReactionEventTemplate = {\n /**\n * Pass only non-nip25 tags if you have to. Nip25 tags ('e' and 'p' tags from reacted event) will be added automatically.\n */\n tags?: string[][]\n\n /**\n * @default '+'\n */\n content?: string\n\n created_at: number\n}\n\nexport function finishReactionEvent(t: ReactionEventTemplate, reacted: Event, privateKey: Uint8Array): Event {\n const inheritedTags = reacted.tags.filter(tag => tag.length >= 2 && (tag[0] === 'e' || tag[0] === 'p'))\n\n return finalizeEvent(\n {\n ...t,\n kind: Reaction,\n tags: [...(t.tags ?? []), ...inheritedTags, ['e', reacted.id], ['p', reacted.pubkey]],\n content: t.content ?? '+',\n },\n privateKey,\n )\n}\n\nexport function getReactedEventPointer(event: Event): undefined | EventPointer {\n if (event.kind !== Reaction) {\n return undefined\n }\n\n let lastETag: undefined | string[]\n let lastPTag: undefined | string[]\n\n for (let i = event.tags.length - 1; i >= 0 && (lastETag === undefined || lastPTag === undefined); i--) {\n const tag = event.tags[i]\n if (tag.length >= 2) {\n if (tag[0] === 'e' && lastETag === undefined) {\n lastETag = tag\n } else if (tag[0] === 'p' && lastPTag === undefined) {\n lastPTag = tag\n }\n }\n }\n\n if (lastETag === undefined || lastPTag === undefined) {\n return undefined\n }\n\n return {\n id: lastETag[1],\n relays: [lastETag[2], lastPTag[2]].filter(x => x !== undefined),\n author: lastPTag[1],\n }\n}\n", "import { AddressPointer, EventPointer, ProfilePointer, decode } from './nip19.ts'\n\nexport type Block =\n | {\n type: 'text'\n text: string\n }\n | {\n type: 'reference'\n pointer: ProfilePointer | AddressPointer | EventPointer\n }\n | {\n type: 'url'\n url: string\n }\n | {\n type: 'relay'\n url: string\n }\n | {\n type: 'image'\n url: string\n }\n | {\n type: 'video'\n url: string\n }\n | {\n type: 'audio'\n url: string\n }\n\nconst noCharacter = /\\W/m\nconst noURLCharacter = /\\W |\\W$|$|,| /m\n\nexport function* parse(content: string): Iterable {\n const max = content.length\n let prevIndex = 0\n let index = 0\n while (index < max) {\n let u = content.indexOf(':', index)\n if (u === -1) {\n // reached end\n break\n }\n\n if (content.substring(u - 5, u) === 'nostr') {\n const m = content.substring(u + 60).match(noCharacter)\n const end = m ? u + 60 + m.index! : max\n try {\n let pointer: ProfilePointer | AddressPointer | EventPointer\n let { data, type } = decode(content.substring(u + 1, end))\n\n switch (type) {\n case 'npub':\n pointer = { pubkey: data } as ProfilePointer\n break\n case 'nsec':\n case 'note':\n // ignore this, treat it as not a valid uri\n index = end + 1\n continue\n default:\n pointer = data as any\n }\n\n if (prevIndex !== u - 5) {\n yield { type: 'text', text: content.substring(prevIndex, u - 5) }\n }\n yield { type: 'reference', pointer }\n index = end\n prevIndex = index\n continue\n } catch (_err) {\n // ignore this, not a valid nostr uri\n index = u + 1\n continue\n }\n } else if (content.substring(u - 5, u) === 'https' || content.substring(u - 4, u) === 'http') {\n const m = content.substring(u + 4).match(noURLCharacter)\n const end = m ? u + 4 + m.index! : max\n const prefixLen = content[u - 1] === 's' ? 5 : 4\n try {\n let url = new URL(content.substring(u - prefixLen, end))\n if (url.hostname.indexOf('.') === -1) {\n throw new Error('invalid url')\n }\n\n if (prevIndex !== u - prefixLen) {\n yield { type: 'text', text: content.substring(prevIndex, u - prefixLen) }\n }\n\n if (\n url.pathname.endsWith('.png') ||\n url.pathname.endsWith('.jpg') ||\n url.pathname.endsWith('.jpeg') ||\n url.pathname.endsWith('.gif') ||\n url.pathname.endsWith('.webp')\n ) {\n yield { type: 'image', url: url.toString() }\n index = end\n prevIndex = index\n continue\n }\n if (\n url.pathname.endsWith('.mp4') ||\n url.pathname.endsWith('.avi') ||\n url.pathname.endsWith('.webm') ||\n url.pathname.endsWith('.mkv')\n ) {\n yield { type: 'video', url: url.toString() }\n index = end\n prevIndex = index\n continue\n }\n if (\n url.pathname.endsWith('.mp3') ||\n url.pathname.endsWith('.aac') ||\n url.pathname.endsWith('.ogg') ||\n url.pathname.endsWith('.opus')\n ) {\n yield { type: 'audio', url: url.toString() }\n index = end\n prevIndex = index\n continue\n }\n\n yield { type: 'url', url: url.toString() }\n index = end\n prevIndex = index\n continue\n } catch (_err) {\n // ignore this, not a valid url\n index = end + 1\n continue\n }\n } else if (content.substring(u - 3, u) === 'wss' || content.substring(u - 2, u) === 'ws') {\n const m = content.substring(u + 4).match(noURLCharacter)\n const end = m ? u + 4 + m.index! : max\n const prefixLen = content[u - 1] === 's' ? 3 : 2\n try {\n let url = new URL(content.substring(u - prefixLen, end))\n if (url.hostname.indexOf('.') === -1) {\n throw new Error('invalid ws url')\n }\n\n if (prevIndex !== u - prefixLen) {\n yield { type: 'text', text: content.substring(prevIndex, u - prefixLen) }\n }\n yield { type: 'relay', url: url.toString() }\n index = end\n prevIndex = index\n continue\n } catch (_err) {\n // ignore this, not a valid url\n index = end + 1\n continue\n }\n } else {\n // ignore this, it is nothing\n index = u + 1\n continue\n }\n }\n\n if (prevIndex !== max) {\n yield { type: 'text', text: content.substring(prevIndex) }\n }\n}\n", "import { Event, finalizeEvent } from './pure.ts'\nimport {\n ChannelCreation,\n ChannelHideMessage,\n ChannelMessage,\n ChannelMetadata as KindChannelMetadata,\n ChannelMuteUser,\n} from './kinds.ts'\n\nexport interface ChannelMetadata {\n name: string\n about: string\n picture: string\n}\n\nexport interface ChannelCreateEventTemplate {\n /* JSON string containing ChannelMetadata as defined for Kind 40 and 41 in nip-28. */\n content: string | ChannelMetadata\n created_at: number\n tags?: string[][]\n}\n\nexport interface ChannelMetadataEventTemplate {\n channel_create_event_id: string\n /* JSON string containing ChannelMetadata as defined for Kind 40 and 41 in nip-28. */\n content: string | ChannelMetadata\n created_at: number\n tags?: string[][]\n}\n\nexport interface ChannelMessageEventTemplate {\n channel_create_event_id: string\n reply_to_channel_message_event_id?: string\n relay_url: string\n content: string\n created_at: number\n tags?: string[][]\n}\n\nexport interface ChannelHideMessageEventTemplate {\n channel_message_event_id: string\n content: string | { reason: string }\n created_at: number\n tags?: string[][]\n}\n\nexport interface ChannelMuteUserEventTemplate {\n content: string | { reason: string }\n created_at: number\n pubkey_to_mute: string\n tags?: string[][]\n}\n\nexport const channelCreateEvent = (t: ChannelCreateEventTemplate, privateKey: Uint8Array): Event | undefined => {\n let content: string\n if (typeof t.content === 'object') {\n content = JSON.stringify(t.content)\n } else if (typeof t.content === 'string') {\n content = t.content\n } else {\n return undefined\n }\n\n return finalizeEvent(\n {\n kind: ChannelCreation,\n tags: [...(t.tags ?? [])],\n content: content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\nexport const channelMetadataEvent = (t: ChannelMetadataEventTemplate, privateKey: Uint8Array): Event | undefined => {\n let content: string\n if (typeof t.content === 'object') {\n content = JSON.stringify(t.content)\n } else if (typeof t.content === 'string') {\n content = t.content\n } else {\n return undefined\n }\n\n return finalizeEvent(\n {\n kind: KindChannelMetadata,\n tags: [['e', t.channel_create_event_id], ...(t.tags ?? [])],\n content: content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\nexport const channelMessageEvent = (t: ChannelMessageEventTemplate, privateKey: Uint8Array): Event => {\n const tags = [['e', t.channel_create_event_id, t.relay_url, 'root']]\n\n if (t.reply_to_channel_message_event_id) {\n tags.push(['e', t.reply_to_channel_message_event_id, t.relay_url, 'reply'])\n }\n\n return finalizeEvent(\n {\n kind: ChannelMessage,\n tags: [...tags, ...(t.tags ?? [])],\n content: t.content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\n/* \"e\" tag should be the kind 42 event to hide */\nexport const channelHideMessageEvent = (\n t: ChannelHideMessageEventTemplate,\n privateKey: Uint8Array,\n): Event | undefined => {\n let content: string\n if (typeof t.content === 'object') {\n content = JSON.stringify(t.content)\n } else if (typeof t.content === 'string') {\n content = t.content\n } else {\n return undefined\n }\n\n return finalizeEvent(\n {\n kind: ChannelHideMessage,\n tags: [['e', t.channel_message_event_id], ...(t.tags ?? [])],\n content: content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n\nexport const channelMuteUserEvent = (t: ChannelMuteUserEventTemplate, privateKey: Uint8Array): Event | undefined => {\n let content: string\n if (typeof t.content === 'object') {\n content = JSON.stringify(t.content)\n } else if (typeof t.content === 'string') {\n content = t.content\n } else {\n return undefined\n }\n\n return finalizeEvent(\n {\n kind: ChannelMuteUser,\n tags: [['p', t.pubkey_to_mute], ...(t.tags ?? [])],\n content: content,\n created_at: t.created_at,\n },\n privateKey,\n )\n}\n", "/** Regex for a single emoji shortcode. */\nexport const EMOJI_SHORTCODE_REGEX = /:(\\w+):/\n\n/** Regex to find emoji shortcodes in content. */\nexport const regex = (): RegExp => new RegExp(`\\\\B${EMOJI_SHORTCODE_REGEX.source}\\\\B`, 'g')\n\n/** Represents a Nostr custom emoji. */\nexport interface CustomEmoji {\n /** The matched emoji name with colons. */\n shortcode: `:${string}:`\n /** The matched emoji name without colons. */\n name: string\n}\n\n/** Match result for a custom emoji in text content. */\nexport interface CustomEmojiMatch extends CustomEmoji {\n /** Index where the emoji begins in the text content. */\n start: number\n /** Index where the emoji ends in the text content. */\n end: number\n}\n\n/** Find all custom emoji shortcodes. */\nexport function* matchAll(content: string): Iterable {\n const matches = content.matchAll(regex())\n\n for (const match of matches) {\n try {\n const [shortcode, name] = match\n\n yield {\n shortcode: shortcode as `:${string}:`,\n name,\n start: match.index!,\n end: match.index! + shortcode.length,\n }\n } catch (_e) {\n // do nothing\n }\n }\n}\n\n/** Replace all emoji shortcodes in the content. */\nexport function replaceAll(content: string, replacer: (match: CustomEmoji) => string): string {\n return content.replaceAll(regex(), (shortcode, name) => {\n return replacer({\n shortcode: shortcode as `:${string}:`,\n name,\n })\n })\n}\n", "var _fetch: any\n\ntry {\n _fetch = fetch\n} catch {}\n\nexport function useFetchImplementation(fetchImplementation: any) {\n _fetch = fetchImplementation\n}\n\nexport async function validateGithub(pubkey: string, username: string, proof: string): Promise {\n try {\n let res = await (await _fetch(`https://gist.github.com/${username}/${proof}/raw`)).text()\n return res === `Verifying that I control the following Nostr public key: ${pubkey}`\n } catch (_) {\n return false\n }\n}\n", "import { type VerifiedEvent, finalizeEvent } from './pure.ts'\nimport { NWCWalletRequest } from './kinds.ts'\nimport { encrypt } from './nip04.ts'\n\ninterface NWCConnection {\n pubkey: string\n relay: string\n secret: string\n}\n\nexport function parseConnectionString(connectionString: string): NWCConnection {\n const { host, pathname, searchParams } = new URL(connectionString)\n const pubkey = pathname || host\n const relay = searchParams.get('relay')\n const secret = searchParams.get('secret')\n\n if (!pubkey || !relay || !secret) {\n throw new Error('invalid connection string')\n }\n\n return { pubkey, relay, secret }\n}\n\nexport async function makeNwcRequestEvent(\n pubkey: string,\n secretKey: Uint8Array,\n invoice: string,\n): Promise {\n const content = {\n method: 'pay_invoice',\n params: {\n invoice,\n },\n }\n const encryptedContent = encrypt(secretKey, pubkey, JSON.stringify(content))\n const eventTemplate = {\n kind: NWCWalletRequest,\n created_at: Math.round(Date.now() / 1000),\n content: encryptedContent,\n tags: [['p', pubkey]],\n }\n\n return finalizeEvent(eventTemplate, secretKey)\n}\n", "export function normalizeIdentifier(name: string): string {\n // Trim and lowercase\n name = name.trim().toLowerCase()\n\n // Normalize Unicode to NFKC form\n name = name.normalize('NFKC')\n\n // Convert to array of characters and map each one\n return Array.from(name)\n .map(char => {\n // Check if character is letter or number using Unicode ranges\n if (/\\p{Letter}/u.test(char) || /\\p{Number}/u.test(char)) {\n return char\n }\n\n return '-'\n })\n .join('')\n}\n", "import { bech32 } from '@scure/base'\n\nimport { NostrEvent, validateEvent, verifyEvent, type Event, type EventTemplate } from './pure.ts'\nimport { utf8Decoder } from './utils.ts'\nimport { isReplaceableKind, isAddressableKind } from './kinds.ts'\n\nvar _fetch: any\n\ntry {\n _fetch = fetch\n} catch {}\n\nexport function useFetchImplementation(fetchImplementation: any) {\n _fetch = fetchImplementation\n}\n\nexport async function getZapEndpoint(metadata: Event): Promise {\n try {\n let lnurl: string = ''\n let { lud06, lud16 } = JSON.parse(metadata.content)\n if (lud06) {\n let { words } = bech32.decode(lud06, 1000)\n let data = bech32.fromWords(words)\n lnurl = utf8Decoder.decode(data)\n } else if (lud16) {\n let [name, domain] = lud16.split('@')\n lnurl = new URL(`/.well-known/lnurlp/${name}`, `https://${domain}`).toString()\n } else {\n return null\n }\n\n let res = await _fetch(lnurl)\n let body = await res.json()\n\n if (body.allowsNostr && body.nostrPubkey) {\n return body.callback\n }\n } catch (err) {\n /*-*/\n }\n\n return null\n}\n\ntype ProfileZap = {\n pubkey: string\n amount: number\n comment?: string\n relays: string[]\n}\n\ntype EventZap = {\n event: NostrEvent\n amount: number\n comment?: string\n relays: string[]\n}\n\nexport function makeZapRequest(params: ProfileZap | EventZap): EventTemplate {\n let zr: EventTemplate = {\n kind: 9734,\n created_at: Math.round(Date.now() / 1000),\n content: params.comment || '',\n tags: [\n ['p', 'pubkey' in params ? params.pubkey : params.event.pubkey],\n ['amount', params.amount.toString()],\n ['relays', ...params.relays],\n ],\n }\n\n if ('event' in params) {\n zr.tags.push(['e', params.event.id])\n if (isReplaceableKind(params.event.kind)) {\n const a = ['a', `${params.event.kind}:${params.event.pubkey}:`]\n zr.tags.push(a)\n } else if (isAddressableKind(params.event.kind)) {\n let d = params.event.tags.find(([t, v]) => t === 'd' && v)\n if (!d) throw new Error('d tag not found or is empty')\n const a = ['a', `${params.event.kind}:${params.event.pubkey}:${d[1]}`]\n zr.tags.push(a)\n }\n zr.tags.push(['k', params.event.kind.toString()])\n }\n\n return zr\n}\n\nexport function validateZapRequest(zapRequestString: string): string | null {\n let zapRequest: Event\n\n try {\n zapRequest = JSON.parse(zapRequestString)\n } catch (err) {\n return 'Invalid zap request JSON.'\n }\n\n if (!validateEvent(zapRequest)) return 'Zap request is not a valid Nostr event.'\n\n if (!verifyEvent(zapRequest)) return 'Invalid signature on zap request.'\n\n let p = zapRequest.tags.find(([t, v]) => t === 'p' && v)\n if (!p) return \"Zap request doesn't have a 'p' tag.\"\n if (!p[1].match(/^[a-f0-9]{64}$/)) return \"Zap request 'p' tag is not valid hex.\"\n\n let e = zapRequest.tags.find(([t, v]) => t === 'e' && v)\n if (e && !e[1].match(/^[a-f0-9]{64}$/)) return \"Zap request 'e' tag is not valid hex.\"\n\n let relays = zapRequest.tags.find(([t, v]) => t === 'relays' && v)\n if (!relays) return \"Zap request doesn't have a 'relays' tag.\"\n\n return null\n}\n\nexport function makeZapReceipt({\n zapRequest,\n preimage,\n bolt11,\n paidAt,\n}: {\n zapRequest: string\n preimage?: string\n bolt11: string\n paidAt: Date\n}): EventTemplate {\n let zr: Event = JSON.parse(zapRequest)\n let tagsFromZapRequest = zr.tags.filter(([t]) => t === 'e' || t === 'p' || t === 'a')\n\n let zap: EventTemplate = {\n kind: 9735,\n created_at: Math.round(paidAt.getTime() / 1000),\n content: '',\n tags: [...tagsFromZapRequest, ['P', zr.pubkey], ['bolt11', bolt11], ['description', zapRequest]],\n }\n\n if (preimage) {\n zap.tags.push(['preimage', preimage])\n }\n\n return zap\n}\n\nexport function getSatoshisAmountFromBolt11(bolt11: string): number {\n if (bolt11.length < 50) {\n return 0\n }\n bolt11 = bolt11.substring(0, 50)\n const idx = bolt11.lastIndexOf('1')\n if (idx === -1) {\n return 0\n }\n const hrp = bolt11.substring(0, idx)\n if (!hrp.startsWith('lnbc')) {\n return 0\n }\n const amount = hrp.substring(4) // equivalent to strings.CutPrefix\n\n if (amount.length < 1) {\n return 0\n }\n\n // if last character is a digit, then the amount can just be interpreted as BTC\n const char = amount[amount.length - 1]\n const digit = char.charCodeAt(0) - '0'.charCodeAt(0)\n const isDigit = digit >= 0 && digit <= 9\n\n let cutPoint = amount.length - 1\n if (isDigit) {\n cutPoint++\n }\n\n if (cutPoint < 1) {\n return 0\n }\n\n const num = parseInt(amount.substring(0, cutPoint))\n\n switch (char) {\n case 'm':\n return num * 100000\n case 'u':\n return num * 100\n case 'n':\n return num / 10\n case 'p':\n return num / 10000\n default:\n return num * 100000000\n }\n}\n", "import { sha256 } from '@noble/hashes/sha256'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { base64 } from '@scure/base'\n\nimport { HTTPAuth } from './kinds.ts'\nimport { Event, EventTemplate, verifyEvent } from './pure.ts'\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nconst _authorizationScheme = 'Nostr '\n\n/**\n * Generate token for NIP-98 flow.\n *\n * @example\n * const sign = window.nostr.signEvent\n * await nip98.getToken('https://example.com/login', 'post', (e) => sign(e), true)\n */\nexport async function getToken(\n loginUrl: string,\n httpMethod: string,\n sign: (e: EventTemplate) => Promise | Event,\n includeAuthorizationScheme: boolean = false,\n payload?: Record,\n): Promise {\n const event: EventTemplate = {\n kind: HTTPAuth,\n tags: [\n ['u', loginUrl],\n ['method', httpMethod],\n ],\n created_at: Math.round(new Date().getTime() / 1000),\n content: '',\n }\n\n if (payload) {\n event.tags.push(['payload', hashPayload(payload)])\n }\n\n const signedEvent = await sign(event)\n const authorizationScheme = includeAuthorizationScheme ? _authorizationScheme : ''\n\n return authorizationScheme + base64.encode(utf8Encoder.encode(JSON.stringify(signedEvent)))\n}\n\n/**\n * Validate token for NIP-98 flow.\n *\n * @example\n * await nip98.validateToken('Nostr base64token', 'https://example.com/login', 'post')\n */\nexport async function validateToken(token: string, url: string, method: string): Promise {\n const event = await unpackEventFromToken(token).catch(error => {\n throw error\n })\n\n const valid = await validateEvent(event, url, method).catch(error => {\n throw error\n })\n\n return valid\n}\n\n/**\n * Unpacks an event from a token.\n *\n * @param token - The token to unpack.\n * @returns A promise that resolves to the unpacked event.\n * @throws {Error} If the token is missing, invalid, or cannot be parsed.\n */\nexport async function unpackEventFromToken(token: string): Promise {\n if (!token) {\n throw new Error('Missing token')\n }\n\n token = token.replace(_authorizationScheme, '')\n\n const eventB64 = utf8Decoder.decode(base64.decode(token))\n if (!eventB64 || eventB64.length === 0 || !eventB64.startsWith('{')) {\n throw new Error('Invalid token')\n }\n\n const event = JSON.parse(eventB64) as Event\n\n return event\n}\n\n/**\n * Validates the timestamp of an event.\n * @param event - The event object to validate.\n * @returns A boolean indicating whether the event timestamp is within the last 60 seconds.\n */\nexport function validateEventTimestamp(event: Event): boolean {\n if (!event.created_at) {\n return false\n }\n\n return Math.round(new Date().getTime() / 1000) - event.created_at < 60\n}\n\n/**\n * Validates the kind of an event.\n * @param event The event to validate.\n * @returns A boolean indicating whether the event kind is valid.\n */\nexport function validateEventKind(event: Event): boolean {\n return event.kind === HTTPAuth\n}\n\n/**\n * Validates if the given URL matches the URL tag of the event.\n * @param event - The event object.\n * @param url - The URL to validate.\n * @returns A boolean indicating whether the URL is valid or not.\n */\nexport function validateEventUrlTag(event: Event, url: string): boolean {\n const urlTag = event.tags.find(t => t[0] === 'u')\n\n if (!urlTag) {\n return false\n }\n\n return urlTag.length > 0 && urlTag[1] === url\n}\n\n/**\n * Validates if the given event has a method tag that matches the specified method.\n * @param event - The event to validate.\n * @param method - The method to match against the method tag.\n * @returns A boolean indicating whether the event has a matching method tag.\n */\nexport function validateEventMethodTag(event: Event, method: string): boolean {\n const methodTag = event.tags.find(t => t[0] === 'method')\n\n if (!methodTag) {\n return false\n }\n\n return methodTag.length > 0 && methodTag[1].toLowerCase() === method.toLowerCase()\n}\n\n/**\n * Calculates the hash of a payload.\n * @param payload - The payload to be hashed.\n * @returns The hash value as a string.\n */\nexport function hashPayload(payload: any): string {\n const hash = sha256(utf8Encoder.encode(JSON.stringify(payload)))\n return bytesToHex(hash)\n}\n\n/**\n * Validates the event payload tag against the provided payload.\n * @param event The event object.\n * @param payload The payload to validate.\n * @returns A boolean indicating whether the payload tag is valid.\n */\nexport function validateEventPayloadTag(event: Event, payload: any): boolean {\n const payloadTag = event.tags.find(t => t[0] === 'payload')\n\n if (!payloadTag) {\n return false\n }\n\n const payloadHash = hashPayload(payload)\n return payloadTag.length > 0 && payloadTag[1] === payloadHash\n}\n\n/**\n * Validates a Nostr event for the NIP-98 flow.\n *\n * @param event - The Nostr event to validate.\n * @param url - The URL associated with the event.\n * @param method - The HTTP method associated with the event.\n * @param body - The request body associated with the event (optional).\n * @returns A promise that resolves to a boolean indicating whether the event is valid.\n * @throws An error if the event is invalid.\n */\nexport async function validateEvent(event: Event, url: string, method: string, body?: any): Promise {\n if (!verifyEvent(event)) {\n throw new Error('Invalid nostr event, signature invalid')\n }\n\n if (!validateEventKind(event)) {\n throw new Error('Invalid nostr event, kind invalid')\n }\n\n if (!validateEventTimestamp(event)) {\n throw new Error('Invalid nostr event, created_at timestamp invalid')\n }\n\n if (!validateEventUrlTag(event, url)) {\n throw new Error('Invalid nostr event, url tag invalid')\n }\n\n if (!validateEventMethodTag(event, method)) {\n throw new Error('Invalid nostr event, method tag invalid')\n }\n\n if (Boolean(body) && typeof body === 'object' && Object.keys(body).length > 0) {\n if (!validateEventPayloadTag(event, body)) {\n throw new Error('Invalid nostr event, payload tag does not match request body hash')\n }\n }\n\n return true\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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,KAAK,OAAO,SAAS,YAAY,OAAO,KAAK,IAAI,EAAE,SAAS,GAAG;AAC7E,UAAI,CAAC,wBAAwB,OAAO,IAAI,GAAG;AACzC,cAAM,IAAI,MAAM,mEAAmE;AAAA,MACrF;AAAA,IACF;AAEA,WAAO;AAAA,EACT;", + "names": ["utils_exports", "hash", "pad", "isLE", "i", "i", "concatBytes", "utf8ToBytes", "u8a", "i", "bytes", "hex", "concatBytes", "pad", "utf8ToBytes", "_0n", "_1n", "_2n", "number", "gcd", "Fp", "ge", "i", "_0n", "_1n", "i", "bitLen", "isLE", "_0n", "_1n", "bytes", "isLE", "_1n", "_0n", "_1n", "i", "Fp", "hex", "s", "_0n", "_1n", "_2n", "_3n", "_4n", "toBytes", "concatBytes", "bytes", "Point", "i", "mul", "a", "modN", "number", "getPublicKey", "hash", "randomBytes", "r", "hash", "pad", "i", "hash", "_1n", "_2n", "_3n", "_0n", "concatBytes", "crypto", "u8a", "createView", "rotr", "isLE", "hexes", "i", "bytesToHex", "bytes", "u8a", "hex", "hexToBytes", "utf8ToBytes", "toBytes", "u8a", "concatBytes", "pad", "Hash", "wrapConstructor", "toBytes", "randomBytes", "crypto", "i", "number", "bytes", "hash", "exists", "output", "setBigUint64", "isLE", "SHA2", "Hash", "createView", "toBytes", "i", "Chi", "Maj", "SHA256_K", "IV", "SHA256_W", "SHA256", "SHA2", "i", "rotr", "sha256", "wrapConstructor", "utils_exports", "bytesToHex", "hexToBytes", "target", "bytesToHex", "hash", "sha256", "Date", "Date", "i", "challenge", "challenge", "i", "reason", "_WebSocket", "_WebSocket", "i", "decode", "alphabet", "padding", "bytes", "i", "i", "limit", "decode", "_words", "number", "bytesToHex", "hex", "hexToBytes", "bytes", "concatBytes", "decrypt", "encrypt", "number", "bool", "bytes", "exists", "output", "bytes", "createView", "isLE", "utf8ToBytes", "toBytes", "utf8ToBytes", "equalBytes", "i", "setBigUint64", "isLE", "i", "bytes", "toBytes", "createView", "exists", "output", "BLOCK_SIZE", "POLY", "mul2", "i", "sbox", "sbox2", "bytes", "t0", "t1", "t2", "t3", "ctr", "isLE", "createView", "ecb", "cbc", "setBigUint64", "gcm", "equalBytes", "siv", "encrypt", "bytesToHex", "randomBytes", "decrypt", "i", "useFetchImplementation", "_fetch", "useFetchImplementation", "hex", "i", "now", "bytesToHex", "sha256", "unwrapEvent", "unwrapManyEvents", "wrapEvent", "wrapManyEvents", "decrypt", "encrypt", "i", "toBytes", "bytes", "pad", "exists", "output", "wrapConstructorWithKey", "utf8ToBytes", "output", "number", "bool", "bytes", "i", "ZEROS16", "ZEROS32", "computeTag", "createView", "setBigUint64", "bytes", "output", "equalBytes", "HMAC", "Hash", "hash", "toBytes", "pad", "i", "hmac", "hash", "hmac", "toBytes", "HMAC", "sha256", "concatBytes", "hmac", "encrypt", "randomBytes", "decrypt", "equalBytes", "encrypt", "decrypt", "wrapEvent", "wrapManyEvents", "unwrapEvent", "unwrapManyEvents", "i", "parse", "parse", "i", "parse", "parse", "useFetchImplementation", "_fetch", "useFetchImplementation", "encrypt", "useFetchImplementation", "_fetch", "useFetchImplementation", "validateEvent", "validateEvent", "hash", "sha256", "bytesToHex"] +} diff --git a/node_modules/nostr-tools/lib/types/abstract-pool.d.ts b/node_modules/nostr-tools/lib/types/abstract-pool.d.ts new file mode 100644 index 0000000..7b5ea34 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/abstract-pool.d.ts @@ -0,0 +1,44 @@ +import { AbstractRelay as AbstractRelay, SubscriptionParams, type AbstractRelayConstructorOptions } from './abstract-relay.ts'; +import type { Event, EventTemplate, Nostr, VerifiedEvent } from './core.ts'; +import { type Filter } from './filter.ts'; +export type SubCloser = { + close: (reason?: string) => void; +}; +export type AbstractPoolConstructorOptions = AbstractRelayConstructorOptions & {}; +export type SubscribeManyParams = Omit & { + maxWait?: number; + onclose?: (reasons: string[]) => void; + onauth?: (event: EventTemplate) => Promise; + doauth?: (event: EventTemplate) => Promise; + id?: string; + label?: string; +}; +export declare class AbstractSimplePool { + protected relays: Map; + seenOn: Map>; + trackRelays: boolean; + verifyEvent: Nostr['verifyEvent']; + enablePing: boolean | undefined; + trustedRelayURLs: Set; + private _WebSocket?; + constructor(opts: AbstractPoolConstructorOptions); + ensureRelay(url: string, params?: { + connectionTimeout?: number; + }): Promise; + close(relays: string[]): void; + subscribe(relays: string[], filter: Filter, params: SubscribeManyParams): SubCloser; + subscribeMany(relays: string[], filters: Filter[], params: SubscribeManyParams): SubCloser; + subscribeMap(requests: { + url: string; + filter: Filter; + }[], params: SubscribeManyParams): SubCloser; + subscribeEose(relays: string[], filter: Filter, params: Pick): SubCloser; + subscribeManyEose(relays: string[], filters: Filter[], params: Pick): SubCloser; + querySync(relays: string[], filter: Filter, params?: Pick): Promise; + get(relays: string[], filter: Filter, params?: Pick): Promise; + publish(relays: string[], event: Event, options?: { + onauth?: (evt: EventTemplate) => Promise; + }): Promise[]; + listConnectionStatus(): Map; + destroy(): void; +} diff --git a/node_modules/nostr-tools/lib/types/abstract-relay.d.ts b/node_modules/nostr-tools/lib/types/abstract-relay.d.ts new file mode 100644 index 0000000..26d2bdf --- /dev/null +++ b/node_modules/nostr-tools/lib/types/abstract-relay.d.ts @@ -0,0 +1,96 @@ +import type { Event, EventTemplate, VerifiedEvent, Nostr } from './core.ts'; +import { type Filter } from './filter.ts'; +export type AbstractRelayConstructorOptions = { + verifyEvent: Nostr['verifyEvent']; + websocketImplementation?: typeof WebSocket; + enablePing?: boolean; +}; +export declare class SendingOnClosedConnection extends Error { + constructor(message: string, relay: string); +} +export declare class AbstractRelay { + readonly url: string; + private _connected; + onclose: (() => void) | null; + onnotice: (msg: string) => void; + baseEoseTimeout: number; + connectionTimeout: number; + publishTimeout: number; + pingFrequency: number; + pingTimeout: number; + openSubs: Map; + enablePing: boolean | undefined; + private connectionTimeoutHandle; + private connectionPromise; + private openCountRequests; + private openEventPublishes; + private ws; + private incomingMessageQueue; + private queueRunning; + private challenge; + private authPromise; + private serial; + private verifyEvent; + private _WebSocket; + constructor(url: string, opts: AbstractRelayConstructorOptions); + static connect(url: string, opts: AbstractRelayConstructorOptions): Promise; + private closeAllSubscriptions; + get connected(): boolean; + connect(): Promise; + private waitForPingPong; + private waitForDummyReq; + private pingpong; + private runQueue; + private handleNext; + send(message: string): Promise; + auth(signAuthEvent: (evt: EventTemplate) => Promise): Promise; + publish(event: Event): Promise; + count(filters: Filter[], params: { + id?: string | null; + }): Promise; + subscribe(filters: Filter[], params: Partial & { + label?: string; + id?: string; + }): Subscription; + prepareSubscription(filters: Filter[], params: Partial & { + label?: string; + id?: string; + }): Subscription; + close(): void; + _onmessage(ev: MessageEvent): void; +} +export declare class Subscription { + readonly relay: AbstractRelay; + readonly id: string; + closed: boolean; + eosed: boolean; + filters: Filter[]; + alreadyHaveEvent: ((id: string) => boolean) | undefined; + receivedEvent: ((relay: AbstractRelay, id: string) => void) | undefined; + onevent: (evt: Event) => void; + oneose: (() => void) | undefined; + onclose: ((reason: string) => void) | undefined; + eoseTimeout: number; + private eoseTimeoutHandle; + constructor(relay: AbstractRelay, id: string, filters: Filter[], params: SubscriptionParams); + fire(): void; + receivedEose(): void; + close(reason?: string): void; +} +export type SubscriptionParams = { + onevent?: (evt: Event) => void; + oneose?: () => void; + onclose?: (reason: string) => void; + alreadyHaveEvent?: (id: string) => boolean; + receivedEvent?: (relay: AbstractRelay, id: string) => void; + eoseTimeout?: number; +}; +export type CountResolver = { + resolve: (count: number) => void; + reject: (err: Error) => void; +}; +export type EventPublishResolver = { + resolve: (reason: string) => void; + reject: (err: Error) => void; + timeout: ReturnType; +}; diff --git a/node_modules/nostr-tools/lib/types/benchmarks.d.ts b/node_modules/nostr-tools/lib/types/benchmarks.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/benchmarks.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/core.d.ts b/node_modules/nostr-tools/lib/types/core.d.ts new file mode 100644 index 0000000..161a7d9 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/core.d.ts @@ -0,0 +1,32 @@ +export interface Nostr { + generateSecretKey(): Uint8Array; + getPublicKey(secretKey: Uint8Array): string; + finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent; + verifyEvent(event: Event): event is VerifiedEvent; +} +/** Designates a verified event signature. */ +export declare const verifiedSymbol: unique symbol; +export interface Event { + kind: number; + tags: string[][]; + content: string; + created_at: number; + pubkey: string; + id: string; + sig: string; + [verifiedSymbol]?: boolean; +} +export type NostrEvent = Event; +export type EventTemplate = Pick; +export type UnsignedEvent = Pick; +/** An event whose signature has been verified. */ +export interface VerifiedEvent extends Event { + [verifiedSymbol]: true; +} +export declare function validateEvent(event: T): event is T & UnsignedEvent; +/** + * Sort events in reverse-chronological order by the `created_at` timestamp, + * and then by the event `id` (lexicographically) in case of ties. + * This mutates the array. + */ +export declare function sortEvents(events: Event[]): Event[]; diff --git a/node_modules/nostr-tools/lib/types/core.test.d.ts b/node_modules/nostr-tools/lib/types/core.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/core.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/fakejson.d.ts b/node_modules/nostr-tools/lib/types/fakejson.d.ts new file mode 100644 index 0000000..dbcf177 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/fakejson.d.ts @@ -0,0 +1,6 @@ +export declare function getHex64(json: string, field: string): string; +export declare function getInt(json: string, field: string): number; +export declare function getSubscriptionId(json: string): string | null; +export declare function matchEventId(json: string, id: string): boolean; +export declare function matchEventPubkey(json: string, pubkey: string): boolean; +export declare function matchEventKind(json: string, kind: number): boolean; diff --git a/node_modules/nostr-tools/lib/types/fakejson.test.d.ts b/node_modules/nostr-tools/lib/types/fakejson.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/fakejson.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/filter.d.ts b/node_modules/nostr-tools/lib/types/filter.d.ts new file mode 100644 index 0000000..2117303 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/filter.d.ts @@ -0,0 +1,19 @@ +import { Event } from './core.ts'; +export type Filter = { + ids?: string[]; + kinds?: number[]; + authors?: string[]; + since?: number; + until?: number; + limit?: number; + search?: string; + [key: `#${string}`]: string[] | undefined; +}; +export declare function matchFilter(filter: Filter, event: Event): boolean; +export declare function matchFilters(filters: Filter[], event: Event): boolean; +export declare function mergeFilters(...filters: Filter[]): Filter; +/** + * Calculate the intrinsic limit of a filter. + * This function returns a positive integer, or `Infinity` if there is no intrinsic limit. + */ +export declare function getFilterLimit(filter: Filter): number; diff --git a/node_modules/nostr-tools/lib/types/filter.test.d.ts b/node_modules/nostr-tools/lib/types/filter.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/filter.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/helpers.d.ts b/node_modules/nostr-tools/lib/types/helpers.d.ts new file mode 100644 index 0000000..8a08ccb --- /dev/null +++ b/node_modules/nostr-tools/lib/types/helpers.d.ts @@ -0,0 +1,3 @@ +import { type Nostr } from './core.ts'; +export declare function yieldThread(): Promise; +export declare const alwaysTrue: Nostr['verifyEvent']; diff --git a/node_modules/nostr-tools/lib/types/index.d.ts b/node_modules/nostr-tools/lib/types/index.d.ts new file mode 100644 index 0000000..61e8cbc --- /dev/null +++ b/node_modules/nostr-tools/lib/types/index.d.ts @@ -0,0 +1,29 @@ +export * from './pure.ts'; +export { Relay } from './relay.ts'; +export * from './filter.ts'; +export { SimplePool } from './pool.ts'; +export * from './references.ts'; +export * as nip04 from './nip04.ts'; +export * as nip05 from './nip05.ts'; +export * as nip10 from './nip10.ts'; +export * as nip11 from './nip11.ts'; +export * as nip13 from './nip13.ts'; +export * as nip17 from './nip17.ts'; +export * as nip18 from './nip18.ts'; +export * as nip19 from './nip19.ts'; +export * as nip21 from './nip21.ts'; +export * as nip25 from './nip25.ts'; +export * as nip27 from './nip27.ts'; +export * as nip28 from './nip28.ts'; +export * as nip30 from './nip30.ts'; +export * as nip39 from './nip39.ts'; +export * as nip42 from './nip42.ts'; +export * as nip44 from './nip44.ts'; +export * as nip47 from './nip47.ts'; +export * as nip54 from './nip54.ts'; +export * as nip57 from './nip57.ts'; +export * as nip59 from './nip59.ts'; +export * as nip98 from './nip98.ts'; +export * as kinds from './kinds.ts'; +export * as fj from './fakejson.ts'; +export * as utils from './utils.ts'; diff --git a/node_modules/nostr-tools/lib/types/kinds.d.ts b/node_modules/nostr-tools/lib/types/kinds.d.ts new file mode 100644 index 0000000..d769481 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/kinds.d.ts @@ -0,0 +1,170 @@ +import { NostrEvent } from './pure.ts'; +/** Events are **regular**, which means they're all expected to be stored by relays. */ +export declare function isRegularKind(kind: number): boolean; +/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */ +export declare function isReplaceableKind(kind: number): boolean; +/** Events are **ephemeral**, which means they are not expected to be stored by relays. */ +export declare function isEphemeralKind(kind: number): boolean; +/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */ +export declare function isAddressableKind(kind: number): boolean; +/** Classification of the event kind. */ +export type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'; +/** Determine the classification of this kind of event if known, or `unknown`. */ +export declare function classifyKind(kind: number): KindClassification; +export declare function isKind(event: unknown, kind: T | Array): event is NostrEvent & { + kind: T; +}; +export declare const Metadata = 0; +export type Metadata = typeof Metadata; +export declare const ShortTextNote = 1; +export type ShortTextNote = typeof ShortTextNote; +export declare const RecommendRelay = 2; +export type RecommendRelay = typeof RecommendRelay; +export declare const Contacts = 3; +export type Contacts = typeof Contacts; +export declare const EncryptedDirectMessage = 4; +export type EncryptedDirectMessage = typeof EncryptedDirectMessage; +export declare const EventDeletion = 5; +export type EventDeletion = typeof EventDeletion; +export declare const Repost = 6; +export type Repost = typeof Repost; +export declare const Reaction = 7; +export type Reaction = typeof Reaction; +export declare const BadgeAward = 8; +export type BadgeAward = typeof BadgeAward; +export declare const Seal = 13; +export type Seal = typeof Seal; +export declare const PrivateDirectMessage = 14; +export type PrivateDirectMessage = typeof PrivateDirectMessage; +export declare const GenericRepost = 16; +export type GenericRepost = typeof GenericRepost; +export declare const ChannelCreation = 40; +export type ChannelCreation = typeof ChannelCreation; +export declare const ChannelMetadata = 41; +export type ChannelMetadata = typeof ChannelMetadata; +export declare const ChannelMessage = 42; +export type ChannelMessage = typeof ChannelMessage; +export declare const ChannelHideMessage = 43; +export type ChannelHideMessage = typeof ChannelHideMessage; +export declare const ChannelMuteUser = 44; +export type ChannelMuteUser = typeof ChannelMuteUser; +export declare const OpenTimestamps = 1040; +export type OpenTimestamps = typeof OpenTimestamps; +export declare const GiftWrap = 1059; +export type GiftWrap = typeof GiftWrap; +export declare const FileMetadata = 1063; +export type FileMetadata = typeof FileMetadata; +export declare const LiveChatMessage = 1311; +export type LiveChatMessage = typeof LiveChatMessage; +export declare const ProblemTracker = 1971; +export type ProblemTracker = typeof ProblemTracker; +export declare const Report = 1984; +export type Report = typeof Report; +export declare const Reporting = 1984; +export type Reporting = typeof Reporting; +export declare const Label = 1985; +export type Label = typeof Label; +export declare const CommunityPostApproval = 4550; +export type CommunityPostApproval = typeof CommunityPostApproval; +export declare const JobRequest = 5999; +export type JobRequest = typeof JobRequest; +export declare const JobResult = 6999; +export type JobResult = typeof JobResult; +export declare const JobFeedback = 7000; +export type JobFeedback = typeof JobFeedback; +export declare const ZapGoal = 9041; +export type ZapGoal = typeof ZapGoal; +export declare const ZapRequest = 9734; +export type ZapRequest = typeof ZapRequest; +export declare const Zap = 9735; +export type Zap = typeof Zap; +export declare const Highlights = 9802; +export type Highlights = typeof Highlights; +export declare const Mutelist = 10000; +export type Mutelist = typeof Mutelist; +export declare const Pinlist = 10001; +export type Pinlist = typeof Pinlist; +export declare const RelayList = 10002; +export type RelayList = typeof RelayList; +export declare const BookmarkList = 10003; +export type BookmarkList = typeof BookmarkList; +export declare const CommunitiesList = 10004; +export type CommunitiesList = typeof CommunitiesList; +export declare const PublicChatsList = 10005; +export type PublicChatsList = typeof PublicChatsList; +export declare const BlockedRelaysList = 10006; +export type BlockedRelaysList = typeof BlockedRelaysList; +export declare const SearchRelaysList = 10007; +export type SearchRelaysList = typeof SearchRelaysList; +export declare const InterestsList = 10015; +export type InterestsList = typeof InterestsList; +export declare const UserEmojiList = 10030; +export type UserEmojiList = typeof UserEmojiList; +export declare const DirectMessageRelaysList = 10050; +export type DirectMessageRelaysList = typeof DirectMessageRelaysList; +export declare const FileServerPreference = 10096; +export type FileServerPreference = typeof FileServerPreference; +export declare const NWCWalletInfo = 13194; +export type NWCWalletInfo = typeof NWCWalletInfo; +export declare const LightningPubRPC = 21000; +export type LightningPubRPC = typeof LightningPubRPC; +export declare const ClientAuth = 22242; +export type ClientAuth = typeof ClientAuth; +export declare const NWCWalletRequest = 23194; +export type NWCWalletRequest = typeof NWCWalletRequest; +export declare const NWCWalletResponse = 23195; +export type NWCWalletResponse = typeof NWCWalletResponse; +export declare const NostrConnect = 24133; +export type NostrConnect = typeof NostrConnect; +export declare const HTTPAuth = 27235; +export type HTTPAuth = typeof HTTPAuth; +export declare const Followsets = 30000; +export type Followsets = typeof Followsets; +export declare const Genericlists = 30001; +export type Genericlists = typeof Genericlists; +export declare const Relaysets = 30002; +export type Relaysets = typeof Relaysets; +export declare const Bookmarksets = 30003; +export type Bookmarksets = typeof Bookmarksets; +export declare const Curationsets = 30004; +export type Curationsets = typeof Curationsets; +export declare const ProfileBadges = 30008; +export type ProfileBadges = typeof ProfileBadges; +export declare const BadgeDefinition = 30009; +export type BadgeDefinition = typeof BadgeDefinition; +export declare const Interestsets = 30015; +export type Interestsets = typeof Interestsets; +export declare const CreateOrUpdateStall = 30017; +export type CreateOrUpdateStall = typeof CreateOrUpdateStall; +export declare const CreateOrUpdateProduct = 30018; +export type CreateOrUpdateProduct = typeof CreateOrUpdateProduct; +export declare const LongFormArticle = 30023; +export type LongFormArticle = typeof LongFormArticle; +export declare const DraftLong = 30024; +export type DraftLong = typeof DraftLong; +export declare const Emojisets = 30030; +export type Emojisets = typeof Emojisets; +export declare const Application = 30078; +export type Application = typeof Application; +export declare const LiveEvent = 30311; +export type LiveEvent = typeof LiveEvent; +export declare const UserStatuses = 30315; +export type UserStatuses = typeof UserStatuses; +export declare const ClassifiedListing = 30402; +export type ClassifiedListing = typeof ClassifiedListing; +export declare const DraftClassifiedListing = 30403; +export type DraftClassifiedListing = typeof DraftClassifiedListing; +export declare const Date = 31922; +export type Date = typeof Date; +export declare const Time = 31923; +export type Time = typeof Time; +export declare const Calendar = 31924; +export type Calendar = typeof Calendar; +export declare const CalendarEventRSVP = 31925; +export type CalendarEventRSVP = typeof CalendarEventRSVP; +export declare const Handlerrecommendation = 31989; +export type Handlerrecommendation = typeof Handlerrecommendation; +export declare const Handlerinformation = 31990; +export type Handlerinformation = typeof Handlerinformation; +export declare const CommunityDefinition = 34550; +export type CommunityDefinition = typeof CommunityDefinition; diff --git a/node_modules/nostr-tools/lib/types/kinds.test.d.ts b/node_modules/nostr-tools/lib/types/kinds.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/kinds.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip04.d.ts b/node_modules/nostr-tools/lib/types/nip04.d.ts new file mode 100644 index 0000000..496bbc8 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip04.d.ts @@ -0,0 +1,2 @@ +export declare function encrypt(secretKey: string | Uint8Array, pubkey: string, text: string): string; +export declare function decrypt(secretKey: string | Uint8Array, pubkey: string, data: string): string; diff --git a/node_modules/nostr-tools/lib/types/nip04.test.d.ts b/node_modules/nostr-tools/lib/types/nip04.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip04.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip05.d.ts b/node_modules/nostr-tools/lib/types/nip05.d.ts new file mode 100644 index 0000000..5b4d13f --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip05.d.ts @@ -0,0 +1,17 @@ +import { ProfilePointer } from './nip19.ts'; +export type Nip05 = `${string}@${string}`; +/** + * NIP-05 regex. The localpart is optional, and should be assumed to be `_` otherwise. + * + * - 0: full match + * - 1: name (optional) + * - 2: domain + */ +export declare const NIP05_REGEX: RegExp; +export declare const isNip05: (value?: string | null) => value is Nip05; +export declare function useFetchImplementation(fetchImplementation: unknown): void; +export declare function searchDomain(domain: string, query?: string): Promise<{ + [name: string]: string; +}>; +export declare function queryProfile(fullname: string): Promise; +export declare function isValid(pubkey: string, nip05: Nip05): Promise; diff --git a/node_modules/nostr-tools/lib/types/nip05.test.d.ts b/node_modules/nostr-tools/lib/types/nip05.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip05.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip06.d.ts b/node_modules/nostr-tools/lib/types/nip06.d.ts new file mode 100644 index 0000000..2726dc9 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip06.d.ts @@ -0,0 +1,15 @@ +export declare function privateKeyFromSeedWords(mnemonic: string, passphrase?: string, accountIndex?: number): Uint8Array; +export declare function accountFromSeedWords(mnemonic: string, passphrase?: string, accountIndex?: number): { + privateKey: Uint8Array; + publicKey: string; +}; +export declare function extendedKeysFromSeedWords(mnemonic: string, passphrase?: string, extendedAccountIndex?: number): { + privateExtendedKey: string; + publicExtendedKey: string; +}; +export declare function accountFromExtendedKey(base58key: string, accountIndex?: number): { + privateKey?: Uint8Array; + publicKey: string; +}; +export declare function generateSeedWords(): string; +export declare function validateWords(words: string): boolean; diff --git a/node_modules/nostr-tools/lib/types/nip06.test.d.ts b/node_modules/nostr-tools/lib/types/nip06.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip06.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip07.d.ts b/node_modules/nostr-tools/lib/types/nip07.d.ts new file mode 100644 index 0000000..0511d2d --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip07.d.ts @@ -0,0 +1,13 @@ +import { EventTemplate, VerifiedEvent } from './core.ts'; +export interface WindowNostr { + getPublicKey(): Promise; + signEvent(event: EventTemplate): Promise; + nip04?: { + encrypt(pubkey: string, plaintext: string): Promise; + decrypt(pubkey: string, ciphertext: string): Promise; + }; + nip44?: { + encrypt(pubkey: string, plaintext: string): Promise; + decrypt(pubkey: string, ciphertext: string): Promise; + }; +} diff --git a/node_modules/nostr-tools/lib/types/nip10.d.ts b/node_modules/nostr-tools/lib/types/nip10.d.ts new file mode 100644 index 0000000..b192a06 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip10.d.ts @@ -0,0 +1,24 @@ +import type { Event } from './core.ts'; +import type { EventPointer, ProfilePointer } from './nip19.ts'; +export declare function parse(event: Pick): { + /** + * Pointer to the root of the thread. + */ + root: EventPointer | undefined; + /** + * Pointer to a "parent" event that parsed event replies to (responded to). + */ + reply: EventPointer | undefined; + /** + * Pointers to events that may or may not be in the reply chain. + */ + mentions: EventPointer[]; + /** + * Pointers to events that were directly quoted. + */ + quotes: EventPointer[]; + /** + * List of pubkeys that are involved in the thread in no particular order. + */ + profiles: ProfilePointer[]; +}; diff --git a/node_modules/nostr-tools/lib/types/nip10.test.d.ts b/node_modules/nostr-tools/lib/types/nip10.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip10.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip11.d.ts b/node_modules/nostr-tools/lib/types/nip11.d.ts new file mode 100644 index 0000000..096fba4 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip11.d.ts @@ -0,0 +1,266 @@ +export declare function useFetchImplementation(fetchImplementation: any): void; +export declare function fetchRelayInformation(url: string): Promise; +/** + * ## Relay Information Document + + * Relays may provide server metadata to clients to inform + * them of capabilities, administrative contacts, and + * various server attributes. This is made available as a + * JSON document over HTTP, on the same URI as the relay's + * websocket. + + * Any field may be omitted, and clients MUST ignore any + * additional fields they do not understand. Relays MUST + * accept CORS requests by sending + * `Access-Control-Allow-Origin`, + * `Access-Control-Allow-Headers`, and + * `Access-Control-Allow-Methods` headers. + * @param name string identifying relay + * @param description string with detailed information + * @param pubkey administrative contact pubkey + * @param contact: administrative alternate contact + * @param supported_nips a list of NIP numbers supported by + * the relay + * @param software identifying relay software URL + * @param version string version identifier + */ +export interface BasicRelayInformation { + name: string; + description: string; + pubkey: string; + contact: string; + supported_nips: number[]; + software: string; + version: string; +} +/** + * * ## Extra Fields + + * * ### Server Limitations + + * These are limitations imposed by the relay on clients. + * Your client should expect that requests which exceed + * these practical_ limitations are rejected or fail immediately. + * @param max_message_length this is the maximum number of + * bytes for incoming JSON that the relay will attempt to + * decode and act upon. When you send large subscriptions, + * you will be limited by this value. It also effectively + * limits the maximum size of any event. Value is calculated + * from `[` to `]` and is after UTF-8 serialization (so some + * unicode characters will cost 2-3 bytes). It is equal to + * the maximum size of the WebSocket message frame. + * @param max_subscriptions total number of subscriptions + * that may be active on a single websocket connection to + * this relay. It's possible that authenticated clients with + * a (paid) relationship to the relay may have higher limits. + * @param max_filters maximum number of filter values in + * each subscription. Must be one or higher. + * @param max_limit the relay server will clamp each + * filter's `limit` value to this number. + * This means the client won't be able to get more than this + * number of events from a single subscription filter. This + * clamping is typically done silently by the relay, but + * with this number, you can know that there are additional + * results if you narrowed your filter's time range or other + * parameters. + * @param max_subid_length maximum length of subscription id as a + * string. + * @param min_prefix for `authors` and `ids` filters which + * are to match against a hex prefix, you must provide at + * least this many hex digits in the prefix. + * @param max_event_tags in any event, this is the maximum + * number of elements in the `tags` list. + * @param max_content_length maximum number of characters in + * the `content` field of any event. This is a count of + * unicode characters. After serializing into JSON it may be + * larger (in bytes), and is still subject to the + * max_message_length`, if defined. + * @param min_pow_difficulty new events will require at + * least this difficulty of PoW, based on [NIP-13](13.md), + * or they will be rejected by this server. + * @param auth_required this relay requires [NIP-42](42.md) + * authentication to happen before a new connection may + * perform any other action. Even if set to False, + * authentication may be required for specific actions. + * @param restricted_writes: this relay requires some kind + * of condition to be fulfilled in order to accept events + * (not necessarily, but including + * @param payment_required this relay requires payment + * before a new connection may perform any action. + * @param created_at_lower_limit: 'created_at' lower limit + * @param created_at_upper_limit: 'created_at' upper limit + */ +export interface Limitations { + max_message_length: number; + max_subscriptions: number; + max_filters: number; + max_limit: number; + max_subid_length: number; + min_prefix: number; + max_event_tags: number; + max_content_length: number; + min_pow_difficulty: number; + auth_required: boolean; + payment_required: boolean; + created_at_lower_limit: number; + created_at_upper_limit: number; + restricted_writes: boolean; +} +export interface RetentionDetails { + kinds: (number | number[])[]; + time?: number | null; + count?: number | null; +} +type AnyRetentionDetails = RetentionDetails; +/** + * ### Event Retention + + * There may be a cost associated with storing data forever, + * so relays may wish to state retention times. The values + * stated here are defaults for unauthenticated users and + * visitors. Paid users would likely have other policies. + + * Retention times are given in seconds, with `null` + * indicating infinity. If zero is provided, this means the + * event will not be stored at all, and preferably an error + * will be provided when those are received. + * ```json +{ +... + "retention": [ + { "kinds": [0, 1, [5, 7], [40, 49]], "time": 3600 }, + { "kinds": [[40000, 49999]], "time": 100 }, + { "kinds": [[30000, 39999]], "count": 1000 }, + { "time": 3600, "count": 10000 } + ] +... +} +``` + * @param retention is a list of specifications: each will + * apply to either all kinds, or a subset of kinds. Ranges + * may be specified for the kind field as a tuple of + * inclusive start and end values. Events of indicated kind + * (or all) are then limited to a `count` and/or time + * period. + + * It is possible to effectively blacklist Nostr-based + * protocols that rely on a specific `kind` number, by + * giving a retention time of zero for those `kind` values. + * While that is unfortunate, it does allow clients to + * discover servers that will support their protocol quickly + * via a single HTTP fetch. + + * There is no need to specify retention times for + * _ephemeral events_ as defined in [NIP-16](16.md) since + * they are not retained. + */ +export interface Retention { + retention: AnyRetentionDetails[]; +} +/** + * Some relays may be governed by the arbitrary laws of a + * nation state. This may limit what content can be stored + * in cleartext on those relays. All clients are encouraged + * to use encryption to work around this limitation. + + * It is not possible to describe the limitations of each + * country's laws and policies which themselves are + * typically vague and constantly shifting. + + * Therefore, this field allows the relay operator to + * indicate which countries' laws might end up being + * enforced on them, and then indirectly on their users' + * content. + + * Users should be able to avoid relays in countries they + * don't like, and/or select relays in more favourable + * zones. Exposing this flexibility is up to the client + * software. + + * @param relay_countries a list of two-level ISO country + * codes (ISO 3166-1 alpha-2) whose laws and policies may + * affect this relay. `EU` may be used for European Union + * countries. + + * Remember that a relay may be hosted in a country which is + * not the country of the legal entities who own the relay, + * so it's very likely a number of countries are involved. + */ +export interface ContentLimitations { + relay_countries: string[]; +} +/** + * ### Community Preferences + + * For public text notes at least, a relay may try to foster + * a local community. This would encourage users to follow + * the global feed on that relay, in addition to their usual + * individual follows. To support this goal, relays MAY + * specify some of the following values. + + * @param language_tags is an ordered list of [IETF + * language + * tags](https://en.wikipedia.org/wiki/IETF_language_tag + * indicating the major languages spoken on the relay. + * @param tags is a list of limitations on the topics to be + * discussed. For example `sfw-only` indicates that only + * "Safe For Work" content is encouraged on this relay. This + * relies on assumptions of what the "work" "community" + * feels "safe" talking about. In time, a common set of tags + * may emerge that allow users to find relays that suit + * their needs, and client software will be able to parse + * these tags easily. The `bitcoin-only` tag indicates that + * any _altcoin_, _"crypto"_ or _blockchain_ comments will + * be ridiculed without mercy. + * @param posting_policy is a link to a human-readable page + * which specifies the community policies for the relay. In + * cases where `sfw-only` is True, it's important to link to + * a page which gets into the specifics of your posting + * policy. + + * The `description` field should be used to describe your + * community goals and values, in brief. The + * `posting_policy` is for additional detail and legal + * terms. Use the `tags` field to signify limitations on + * content, or topics to be discussed, which could be + * machine processed by appropriate client software. + */ +export interface CommunityPreferences { + language_tags: string[]; + tags: string[]; + posting_policy: string; +} +export interface Amount { + amount: number; + unit: 'msat'; +} +export interface PublicationAmount extends Amount { + kinds: number[]; +} +export interface Subscription extends Amount { + period: number; +} +export interface Fees { + admission: Amount[]; + subscription: Subscription[]; + publication: PublicationAmount[]; +} +/** + * Relays that require payments may want to expose their fee + * schedules. + */ +export interface PayToRelay { + payments_url: string; + fees: Fees; +} +/** + * A URL pointing to an image to be used as an icon for the + * relay. Recommended to be squared in shape. + */ +export interface Icon { + icon: string; +} +export type RelayInformation = BasicRelayInformation & Partial & { + limitation?: Partial; +} & Partial & Partial & Partial & Partial; +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip11.test.d.ts b/node_modules/nostr-tools/lib/types/nip11.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip11.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip13.d.ts b/node_modules/nostr-tools/lib/types/nip13.d.ts new file mode 100644 index 0000000..f1655f8 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip13.d.ts @@ -0,0 +1,9 @@ +import { type UnsignedEvent, type Event } from './pure.ts'; +/** Get POW difficulty from a Nostr hex ID. */ +export declare function getPow(hex: string): number; +/** + * Mine an event with the desired POW. This function mutates the event. + * Note that this operation is synchronous and should be run in a worker context to avoid blocking the main thread. + */ +export declare function minePow(unsigned: UnsignedEvent, difficulty: number): Omit; +export declare function fastEventHash(evt: UnsignedEvent): string; diff --git a/node_modules/nostr-tools/lib/types/nip13.test.d.ts b/node_modules/nostr-tools/lib/types/nip13.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip13.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip17.d.ts b/node_modules/nostr-tools/lib/types/nip17.d.ts new file mode 100644 index 0000000..ecda52e --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip17.d.ts @@ -0,0 +1,15 @@ +import { NostrEvent } from './pure.ts'; +import * as nip59 from './nip59.ts'; +type Recipient = { + publicKey: string; + relayUrl?: string; +}; +type ReplyTo = { + eventId: string; + relayUrl?: string; +}; +export declare function wrapEvent(senderPrivateKey: Uint8Array, recipient: Recipient, message: string, conversationTitle?: string, replyTo?: ReplyTo): NostrEvent; +export declare function wrapManyEvents(senderPrivateKey: Uint8Array, recipients: Recipient[], message: string, conversationTitle?: string, replyTo?: ReplyTo): NostrEvent[]; +export declare const unwrapEvent: typeof nip59.unwrapEvent; +export declare const unwrapManyEvents: typeof nip59.unwrapManyEvents; +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip17.test.d.ts b/node_modules/nostr-tools/lib/types/nip17.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip17.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip18.d.ts b/node_modules/nostr-tools/lib/types/nip18.d.ts new file mode 100644 index 0000000..9dafa4b --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip18.d.ts @@ -0,0 +1,22 @@ +import { EventPointer } from './nip19.ts'; +import { Event } from './pure.ts'; +export type RepostEventTemplate = { + /** + * Pass only non-nip18 tags if you have to. + * Nip18 tags ('e' and 'p' tags pointing to the reposted event) will be added automatically. + */ + tags?: string[][]; + /** + * Pass an empty string to NOT include the stringified JSON of the reposted event. + * Any other content will be ignored and replaced with the stringified JSON of the reposted event. + * @default Stringified JSON of the reposted event + */ + content?: ''; + created_at: number; +}; +export declare function finishRepostEvent(t: RepostEventTemplate, reposted: Event, relayUrl: string, privateKey: Uint8Array): Event; +export declare function getRepostedEventPointer(event: Event): undefined | EventPointer; +export type GetRepostedEventOptions = { + skipVerification?: boolean; +}; +export declare function getRepostedEvent(event: Event, { skipVerification }?: GetRepostedEventOptions): undefined | Event; diff --git a/node_modules/nostr-tools/lib/types/nip18.test.d.ts b/node_modules/nostr-tools/lib/types/nip18.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip18.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip19.d.ts b/node_modules/nostr-tools/lib/types/nip19.d.ts new file mode 100644 index 0000000..d921cac --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip19.d.ts @@ -0,0 +1,81 @@ +export type NProfile = `nprofile1${string}`; +export type NEvent = `nevent1${string}`; +export type NAddr = `naddr1${string}`; +export type NSec = `nsec1${string}`; +export type NPub = `npub1${string}`; +export type Note = `note1${string}`; +export type Ncryptsec = `ncryptsec1${string}`; +export declare const NostrTypeGuard: { + isNProfile: (value?: string | null) => value is NProfile; + isNEvent: (value?: string | null) => value is NEvent; + isNAddr: (value?: string | null) => value is NAddr; + isNSec: (value?: string | null) => value is NSec; + isNPub: (value?: string | null) => value is NPub; + isNote: (value?: string | null) => value is Note; + isNcryptsec: (value?: string | null) => value is Ncryptsec; +}; +export declare const Bech32MaxSize = 5000; +/** + * Bech32 regex. + * @see https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32 + */ +export declare const BECH32_REGEX: RegExp; +export type ProfilePointer = { + pubkey: string; + relays?: string[]; +}; +export type EventPointer = { + id: string; + relays?: string[]; + author?: string; + kind?: number; +}; +export type AddressPointer = { + identifier: string; + pubkey: string; + kind: number; + relays?: string[]; +}; +export declare function decodeNostrURI(nip19code: string): ReturnType | { + type: 'invalid'; + data: null; +}; +export type DecodedNevent = { + type: 'nevent'; + data: EventPointer; +}; +export type DecodedNprofile = { + type: 'nprofile'; + data: ProfilePointer; +}; +export type DecodedNaddr = { + type: 'naddr'; + data: AddressPointer; +}; +export type DecodedNsec = { + type: 'nsec'; + data: Uint8Array; +}; +export type DecodedNpub = { + type: 'npub'; + data: string; +}; +export type DecodedNote = { + type: 'note'; + data: string; +}; +export type DecodedResult = DecodedNevent | DecodedNprofile | DecodedNaddr | DecodedNpub | DecodedNsec | DecodedNote; +export declare function decode(nip19: NEvent): DecodedNevent; +export declare function decode(nip19: NProfile): DecodedNprofile; +export declare function decode(nip19: NAddr): DecodedNaddr; +export declare function decode(nip19: NSec): DecodedNsec; +export declare function decode(nip19: NPub): DecodedNpub; +export declare function decode(nip19: Note): DecodedNote; +export declare function decode(code: string): DecodedResult; +export declare function nsecEncode(key: Uint8Array): NSec; +export declare function npubEncode(hex: string): NPub; +export declare function noteEncode(hex: string): Note; +export declare function encodeBytes(prefix: Prefix, bytes: Uint8Array): `${Prefix}1${string}`; +export declare function nprofileEncode(profile: ProfilePointer): NProfile; +export declare function neventEncode(event: EventPointer): NEvent; +export declare function naddrEncode(addr: AddressPointer): NAddr; diff --git a/node_modules/nostr-tools/lib/types/nip19.test.d.ts b/node_modules/nostr-tools/lib/types/nip19.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip19.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip21.d.ts b/node_modules/nostr-tools/lib/types/nip21.d.ts new file mode 100644 index 0000000..dd9675c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip21.d.ts @@ -0,0 +1,34 @@ +import { AddressPointer, EventPointer, ProfilePointer } from './nip19.ts'; +/** Nostr URI regex, eg `nostr:npub1...` */ +export declare const NOSTR_URI_REGEX: RegExp; +/** Test whether the value is a Nostr URI. */ +export declare function test(value: unknown): value is `nostr:${string}`; +/** Parsed Nostr URI data. */ +export interface NostrURI { + /** Full URI including the `nostr:` protocol. */ + uri: `nostr:${string}`; + /** The bech32-encoded data (eg `npub1...`). */ + value: string; + /** Decoded bech32 string, according to NIP-19. */ + decoded: { + type: 'nevent'; + data: EventPointer; + } | { + type: 'nprofile'; + data: ProfilePointer; + } | { + type: 'naddr'; + data: AddressPointer; + } | { + type: 'npub'; + data: string; + } | { + type: 'nsec'; + data: Uint8Array; + } | { + type: 'note'; + data: string; + }; +} +/** Parse and decode a Nostr URI. */ +export declare function parse(uri: string): NostrURI; diff --git a/node_modules/nostr-tools/lib/types/nip21.test.d.ts b/node_modules/nostr-tools/lib/types/nip21.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip21.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip25.d.ts b/node_modules/nostr-tools/lib/types/nip25.d.ts new file mode 100644 index 0000000..6a59685 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip25.d.ts @@ -0,0 +1,15 @@ +import { Event } from './pure.ts'; +import type { EventPointer } from './nip19.ts'; +export type ReactionEventTemplate = { + /** + * Pass only non-nip25 tags if you have to. Nip25 tags ('e' and 'p' tags from reacted event) will be added automatically. + */ + tags?: string[][]; + /** + * @default '+' + */ + content?: string; + created_at: number; +}; +export declare function finishReactionEvent(t: ReactionEventTemplate, reacted: Event, privateKey: Uint8Array): Event; +export declare function getReactedEventPointer(event: Event): undefined | EventPointer; diff --git a/node_modules/nostr-tools/lib/types/nip25.test.d.ts b/node_modules/nostr-tools/lib/types/nip25.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip25.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip27.d.ts b/node_modules/nostr-tools/lib/types/nip27.d.ts new file mode 100644 index 0000000..52c2152 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip27.d.ts @@ -0,0 +1,24 @@ +import { AddressPointer, EventPointer, ProfilePointer } from './nip19.ts'; +export type Block = { + type: 'text'; + text: string; +} | { + type: 'reference'; + pointer: ProfilePointer | AddressPointer | EventPointer; +} | { + type: 'url'; + url: string; +} | { + type: 'relay'; + url: string; +} | { + type: 'image'; + url: string; +} | { + type: 'video'; + url: string; +} | { + type: 'audio'; + url: string; +}; +export declare function parse(content: string): Iterable; diff --git a/node_modules/nostr-tools/lib/types/nip27.test.d.ts b/node_modules/nostr-tools/lib/types/nip27.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip27.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip28.d.ts b/node_modules/nostr-tools/lib/types/nip28.d.ts new file mode 100644 index 0000000..9da1f31 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip28.d.ts @@ -0,0 +1,46 @@ +import { Event } from './pure.ts'; +export interface ChannelMetadata { + name: string; + about: string; + picture: string; +} +export interface ChannelCreateEventTemplate { + content: string | ChannelMetadata; + created_at: number; + tags?: string[][]; +} +export interface ChannelMetadataEventTemplate { + channel_create_event_id: string; + content: string | ChannelMetadata; + created_at: number; + tags?: string[][]; +} +export interface ChannelMessageEventTemplate { + channel_create_event_id: string; + reply_to_channel_message_event_id?: string; + relay_url: string; + content: string; + created_at: number; + tags?: string[][]; +} +export interface ChannelHideMessageEventTemplate { + channel_message_event_id: string; + content: string | { + reason: string; + }; + created_at: number; + tags?: string[][]; +} +export interface ChannelMuteUserEventTemplate { + content: string | { + reason: string; + }; + created_at: number; + pubkey_to_mute: string; + tags?: string[][]; +} +export declare const channelCreateEvent: (t: ChannelCreateEventTemplate, privateKey: Uint8Array) => Event | undefined; +export declare const channelMetadataEvent: (t: ChannelMetadataEventTemplate, privateKey: Uint8Array) => Event | undefined; +export declare const channelMessageEvent: (t: ChannelMessageEventTemplate, privateKey: Uint8Array) => Event; +export declare const channelHideMessageEvent: (t: ChannelHideMessageEventTemplate, privateKey: Uint8Array) => Event | undefined; +export declare const channelMuteUserEvent: (t: ChannelMuteUserEventTemplate, privateKey: Uint8Array) => Event | undefined; diff --git a/node_modules/nostr-tools/lib/types/nip28.test.d.ts b/node_modules/nostr-tools/lib/types/nip28.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip28.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip29.d.ts b/node_modules/nostr-tools/lib/types/nip29.d.ts new file mode 100644 index 0000000..1806486 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip29.d.ts @@ -0,0 +1,265 @@ +import { AbstractSimplePool } from './abstract-pool.ts'; +import type { Event, EventTemplate } from './core.ts'; +import { RelayInformation } from './nip11.ts'; +/** + * Represents a NIP29 group. + */ +export type Group = { + relay: string; + metadata: GroupMetadata; + admins?: GroupAdmin[]; + members?: GroupMember[]; + reference: GroupReference; +}; +/** + * Represents the metadata for a NIP29 group. + */ +export type GroupMetadata = { + id: string; + pubkey: string; + name?: string; + picture?: string; + about?: string; + isPublic?: boolean; + isOpen?: boolean; +}; +/** + * Represents a NIP29 group reference. + */ +export type GroupReference = { + id: string; + host: string; +}; +/** + * Represents a NIP29 group member. + */ +export type GroupMember = { + pubkey: string; + label?: string; +}; +/** + * Represents a NIP29 group admin. + */ +export type GroupAdmin = { + pubkey: string; + label?: string; + permissions: GroupAdminPermission[]; +}; +/** + * Represents the permissions that a NIP29 group admin can have. + */ +export declare enum GroupAdminPermission { + /** @deprecated use PutUser instead */ + AddUser = "add-user", + EditMetadata = "edit-metadata", + DeleteEvent = "delete-event", + RemoveUser = "remove-user", + /** @deprecated removed from NIP */ + AddPermission = "add-permission", + /** @deprecated removed from NIP */ + RemovePermission = "remove-permission", + /** @deprecated removed from NIP */ + EditGroupStatus = "edit-group-status", + PutUser = "put-user", + CreateGroup = "create-group", + DeleteGroup = "delete-group", + CreateInvite = "create-invite" +} +/** + * Generates a group metadata event template. + * + * @param group - The group object. + * @returns An event template with the generated group metadata that can be signed later. + */ +export declare function generateGroupMetadataEventTemplate(group: Group): EventTemplate; +/** + * Validates a group metadata event. + * + * @param event - The event to validate. + * @returns A boolean indicating whether the event is valid. + */ +export declare function validateGroupMetadataEvent(event: Event): boolean; +/** + * Generates an event template for group admins. + * + * @param group - The group object. + * @param admins - An array of group admins. + * @returns The generated event template with the group admins that can be signed later. + */ +export declare function generateGroupAdminsEventTemplate(group: Group, admins: GroupAdmin[]): EventTemplate; +/** + * Validates a group admins event. + * + * @param event - The event to validate. + * @returns True if the event is valid, false otherwise. + */ +export declare function validateGroupAdminsEvent(event: Event): boolean; +/** + * Generates an event template for a group with its members. + * + * @param group - The group object. + * @param members - An array of group members. + * @returns The generated event template with the group members that can be signed later. + */ +export declare function generateGroupMembersEventTemplate(group: Group, members: GroupMember[]): EventTemplate; +/** + * Validates a group members event. + * + * @param event - The event to validate. + * @returns Returns `true` if the event is a valid group members event, `false` otherwise. + */ +export declare function validateGroupMembersEvent(event: Event): boolean; +/** + * Returns the normalized relay URL based on the provided group reference. + * + * @param groupReference - The group reference object containing the host. + * @returns The normalized relay URL. + */ +export declare function getNormalizedRelayURLByGroupReference(groupReference: GroupReference): string; +/** + * Fetches relay information by group reference. + * + * @param groupReference The group reference. + * @returns A promise that resolves to the relay information. + */ +export declare function fetchRelayInformationByGroupReference(groupReference: GroupReference): Promise; +/** + * Fetches the group metadata event from the specified pool. + * If the normalizedRelayURL is not provided, it will be obtained using the groupReference. + * If the relayInformation is not provided, it will be fetched using the normalizedRelayURL. + * + * @param {Object} options - The options object. + * @param {AbstractSimplePool} options.pool - The pool to fetch the group metadata event from. + * @param {GroupReference} options.groupReference - The reference to the group. + * @param {string} [options.normalizedRelayURL] - The normalized URL of the relay. + * @param {RelayInformation} [options.relayInformation] - The relay information object. + * @returns {Promise} The group metadata event that can be parsed later to get the group metadata object. + * @throws {Error} If the group is not found on the specified relay. + */ +export declare function fetchGroupMetadataEvent({ pool, groupReference, relayInformation, normalizedRelayURL, }: { + pool: AbstractSimplePool; + groupReference: GroupReference; + normalizedRelayURL?: string; + relayInformation?: RelayInformation; +}): Promise; +/** + * Parses a group metadata event and returns the corresponding GroupMetadata object. + * + * @param event - The event to parse. + * @returns The parsed GroupMetadata object. + * @throws An error if the group metadata event is invalid. + */ +export declare function parseGroupMetadataEvent(event: Event): GroupMetadata; +/** + * Fetches the group admins event from the specified pool. + * If the normalizedRelayURL is not provided, it will be obtained from the groupReference. + * If the relayInformation is not provided, it will be fetched using the normalizedRelayURL. + * + * @param {Object} options - The options object. + * @param {AbstractSimplePool} options.pool - The pool to fetch the group admins event from. + * @param {GroupReference} options.groupReference - The reference to the group. + * @param {string} [options.normalizedRelayURL] - The normalized relay URL. + * @param {RelayInformation} [options.relayInformation] - The relay information. + * @returns {Promise} The group admins event that can be parsed later to get the group admins object. + * @throws {Error} If the group admins event is not found on the specified relay. + */ +export declare function fetchGroupAdminsEvent({ pool, groupReference, relayInformation, normalizedRelayURL, }: { + pool: AbstractSimplePool; + groupReference: GroupReference; + normalizedRelayURL?: string; + relayInformation?: RelayInformation; +}): Promise; +/** + * Parses a group admins event and returns an array of GroupAdmin objects. + * + * @param event - The event to parse. + * @returns An array of GroupAdmin objects. + * @throws Throws an error if the group admins event is invalid. + */ +export declare function parseGroupAdminsEvent(event: Event): GroupAdmin[]; +/** + * Fetches the group members event from the specified relay. + * If the normalizedRelayURL is not provided, it will be obtained using the groupReference. + * If the relayInformation is not provided, it will be fetched using the normalizedRelayURL. + * + * @param {Object} options - The options object. + * @param {AbstractSimplePool} options.pool - The pool object. + * @param {GroupReference} options.groupReference - The group reference object. + * @param {string} [options.normalizedRelayURL] - The normalized relay URL. + * @param {RelayInformation} [options.relayInformation] - The relay information object. + * @returns {Promise} The group members event that can be parsed later to get the group members object. + * @throws {Error} If the group members event is not found. + */ +export declare function fetchGroupMembersEvent({ pool, groupReference, relayInformation, normalizedRelayURL, }: { + pool: AbstractSimplePool; + groupReference: GroupReference; + normalizedRelayURL?: string; + relayInformation?: RelayInformation; +}): Promise; +/** + * Parses a group members event and returns an array of GroupMember objects. + * @param event - The event to parse. + * @returns An array of GroupMember objects. + * @throws Throws an error if the group members event is invalid. + */ +export declare function parseGroupMembersEvent(event: Event): GroupMember[]; +/** + * Fetches and parses the group metadata event, group admins event, and group members event from the specified pool. + * If the normalized relay URL is not provided, it will be obtained using the group reference. + * If the relay information is not provided, it will be fetched using the normalized relay URL. + * + * @param {Object} options - The options for loading the group. + * @param {AbstractSimplePool} options.pool - The pool to load the group from. + * @param {GroupReference} options.groupReference - The reference of the group to load. + * @param {string} [options.normalizedRelayURL] - The normalized URL of the relay to use. + * @param {RelayInformation} [options.relayInformation] - The relay information to use. + * @returns {Promise} A promise that resolves to the loaded group. + */ +export declare function loadGroup({ pool, groupReference, normalizedRelayURL, relayInformation, }: { + pool: AbstractSimplePool; + groupReference: GroupReference; + normalizedRelayURL?: string; + relayInformation?: RelayInformation; +}): Promise; +/** + * Loads a group from the specified pool using the provided group code. + * + * @param {AbstractSimplePool} pool - The pool to load the group from. + * @param {string} code - The code representing the group. + * @returns {Promise} - A promise that resolves to the loaded group. + * @throws {Error} - If the group code is invalid. + */ +export declare function loadGroupFromCode(pool: AbstractSimplePool, code: string): Promise; +/** + * Parses a group code and returns a GroupReference object. + * + * @param code The group code to parse. + * @returns A GroupReference object if the code is valid, otherwise null. + */ +export declare function parseGroupCode(code: string): null | GroupReference; +/** + * Encodes a group reference into a string. + * + * @param gr - The group reference to encode. + * @returns The encoded group reference as a string. + */ +export declare function encodeGroupReference(gr: GroupReference): string; +/** + * Subscribes to relay groups metadata events and calls the provided event handler function + * when an event is received. + * + * @param {Object} options - The options for subscribing to relay groups metadata events. + * @param {AbstractSimplePool} options.pool - The pool to subscribe to. + * @param {string} options.relayURL - The URL of the relay. + * @param {Function} options.onError - The error handler function. + * @param {Function} options.onEvent - The event handler function. + * @param {Function} [options.onConnect] - The connect handler function. + * @returns {Function} - A function to close the subscription + */ +export declare function subscribeRelayGroupsMetadataEvents({ pool, relayURL, onError, onEvent, onConnect, }: { + pool: AbstractSimplePool; + relayURL: string; + onError: (err: Error) => void; + onEvent: (event: Event) => void; + onConnect?: () => void; +}): () => void; diff --git a/node_modules/nostr-tools/lib/types/nip30.d.ts b/node_modules/nostr-tools/lib/types/nip30.d.ts new file mode 100644 index 0000000..d6469fa --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip30.d.ts @@ -0,0 +1,22 @@ +/** Regex for a single emoji shortcode. */ +export declare const EMOJI_SHORTCODE_REGEX: RegExp; +/** Regex to find emoji shortcodes in content. */ +export declare const regex: () => RegExp; +/** Represents a Nostr custom emoji. */ +export interface CustomEmoji { + /** The matched emoji name with colons. */ + shortcode: `:${string}:`; + /** The matched emoji name without colons. */ + name: string; +} +/** Match result for a custom emoji in text content. */ +export interface CustomEmojiMatch extends CustomEmoji { + /** Index where the emoji begins in the text content. */ + start: number; + /** Index where the emoji ends in the text content. */ + end: number; +} +/** Find all custom emoji shortcodes. */ +export declare function matchAll(content: string): Iterable; +/** Replace all emoji shortcodes in the content. */ +export declare function replaceAll(content: string, replacer: (match: CustomEmoji) => string): string; diff --git a/node_modules/nostr-tools/lib/types/nip30.test.d.ts b/node_modules/nostr-tools/lib/types/nip30.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip30.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip39.d.ts b/node_modules/nostr-tools/lib/types/nip39.d.ts new file mode 100644 index 0000000..13d7945 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip39.d.ts @@ -0,0 +1,2 @@ +export declare function useFetchImplementation(fetchImplementation: any): void; +export declare function validateGithub(pubkey: string, username: string, proof: string): Promise; diff --git a/node_modules/nostr-tools/lib/types/nip39.test.d.ts b/node_modules/nostr-tools/lib/types/nip39.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip39.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip40.d.ts b/node_modules/nostr-tools/lib/types/nip40.d.ts new file mode 100644 index 0000000..5301eb1 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip40.d.ts @@ -0,0 +1,10 @@ +import { Event } from './core.ts'; +/** Get the expiration of the event as a `Date` object, if any. */ +declare function getExpiration(event: Event): Date | undefined; +/** Check if the event has expired. */ +declare function isEventExpired(event: Event): boolean; +/** Returns a promise that resolves when the event expires. */ +declare function waitForExpire(event: Event): Promise; +/** Calls the callback when the event expires. */ +declare function onExpire(event: Event, callback: (event: Event) => void): void; +export { getExpiration, isEventExpired, waitForExpire, onExpire }; diff --git a/node_modules/nostr-tools/lib/types/nip40.test.d.ts b/node_modules/nostr-tools/lib/types/nip40.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip40.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip42.d.ts b/node_modules/nostr-tools/lib/types/nip42.d.ts new file mode 100644 index 0000000..7a84633 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip42.d.ts @@ -0,0 +1,5 @@ +import { EventTemplate } from './core.ts'; +/** + * creates an EventTemplate for an AUTH event to be signed. + */ +export declare function makeAuthEvent(relayURL: string, challenge: string): EventTemplate; diff --git a/node_modules/nostr-tools/lib/types/nip42.test.d.ts b/node_modules/nostr-tools/lib/types/nip42.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip42.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip44.d.ts b/node_modules/nostr-tools/lib/types/nip44.d.ts new file mode 100644 index 0000000..74f454f --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip44.d.ts @@ -0,0 +1,13 @@ +export declare function getConversationKey(privkeyA: Uint8Array, pubkeyB: string): Uint8Array; +declare function calcPaddedLen(len: number): number; +export declare function encrypt(plaintext: string, conversationKey: Uint8Array, nonce?: Uint8Array): string; +export declare function decrypt(payload: string, conversationKey: Uint8Array): string; +export declare const v2: { + utils: { + getConversationKey: typeof getConversationKey; + calcPaddedLen: typeof calcPaddedLen; + }; + encrypt: typeof encrypt; + decrypt: typeof decrypt; +}; +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip44.test.d.ts b/node_modules/nostr-tools/lib/types/nip44.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip44.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip46.d.ts b/node_modules/nostr-tools/lib/types/nip46.d.ts new file mode 100644 index 0000000..59ad3f6 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip46.d.ts @@ -0,0 +1,96 @@ +import { EventTemplate, VerifiedEvent } from './core.ts'; +import { AbstractSimplePool } from './abstract-pool.ts'; +import { Signer } from './signer.ts'; +export declare function useFetchImplementation(fetchImplementation: any): void; +export declare const BUNKER_REGEX: RegExp; +export type BunkerPointer = { + relays: string[]; + pubkey: string; + secret: null | string; +}; +export declare function toBunkerURL(bunkerPointer: BunkerPointer): string; +/** This takes either a bunker:// URL or a name@domain.com NIP-05 identifier + and returns a BunkerPointer -- or null in case of error */ +export declare function parseBunkerInput(input: string): Promise; +export declare function queryBunkerProfile(nip05: string): Promise; +export type BunkerSignerParams = { + pool?: AbstractSimplePool; + onauth?: (url: string) => void; +}; +export declare class BunkerSigner implements Signer { + private params; + private pool; + private subCloser; + private isOpen; + private serial; + private idPrefix; + private listeners; + private waitingForAuth; + private secretKey; + private conversationKey; + bp: BunkerPointer; + private cachedPubKey; + /** + * Creates a new instance of the Nip46 class. + * @param relays - An array of relay addresses. + * @param remotePubkey - An optional remote public key. This is the key you want to sign as. + * @param secretKey - An optional key pair. + */ + constructor(clientSecretKey: Uint8Array, bp: BunkerPointer, params?: BunkerSignerParams); + private setupSubscription; + close(): Promise; + sendRequest(method: string, params: string[]): Promise; + /** + * Calls the "connect" method on the bunker. + * The promise will be rejected if the response is not "pong". + */ + ping(): Promise; + /** + * Calls the "connect" method on the bunker. + */ + connect(): Promise; + /** + * Calls the "get_public_key" method on the bunker. + * (before we would return the public key hardcoded in the bunker parameters, but + * that is not correct as that may be the bunker pubkey and the actual signer + * pubkey may be different.) + */ + getPublicKey(): Promise; + /** + * Signs an event using the remote private key. + * @param event - The event to sign. + * @returns A Promise that resolves to the signed event. + */ + signEvent(event: EventTemplate): Promise; + nip04Encrypt(thirdPartyPubkey: string, plaintext: string): Promise; + nip04Decrypt(thirdPartyPubkey: string, ciphertext: string): Promise; + nip44Encrypt(thirdPartyPubkey: string, plaintext: string): Promise; + nip44Decrypt(thirdPartyPubkey: string, ciphertext: string): Promise; +} +/** + * Creates an account with the specified username, domain, and optional email. + * @param bunkerPubkey - The public key of the bunker to use for the create_account call. + * @param username - The username for the account. + * @param domain - The domain for the account. + * @param email - The optional email for the account. + * @param localSecretKey - Optionally pass a local secret key that will be used to communicate with the bunker, + this will default to generating a random key. + * @throws Error if the email is present but invalid. + * @returns A Promise that resolves to the auth_url that the client should follow to create an account. + */ +export declare function createAccount(bunker: BunkerProfile, params: BunkerSignerParams, username: string, domain: string, email?: string, localSecretKey?: Uint8Array): Promise; +/** + * Fetches info on available providers that announce themselves using NIP-89 events. + * @returns A promise that resolves to an array of available bunker objects. + */ +export declare function fetchBunkerProviders(pool: AbstractSimplePool, relays: string[]): Promise; +export type BunkerProfile = { + bunkerPointer: BunkerPointer; + domain: string; + nip05: string; + name: string; + picture: string; + about: string; + website: string; + local: boolean; +}; diff --git a/node_modules/nostr-tools/lib/types/nip47.d.ts b/node_modules/nostr-tools/lib/types/nip47.d.ts new file mode 100644 index 0000000..2c93d3e --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip47.d.ts @@ -0,0 +1,9 @@ +import { type VerifiedEvent } from './pure.ts'; +interface NWCConnection { + pubkey: string; + relay: string; + secret: string; +} +export declare function parseConnectionString(connectionString: string): NWCConnection; +export declare function makeNwcRequestEvent(pubkey: string, secretKey: Uint8Array, invoice: string): Promise; +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip47.test.d.ts b/node_modules/nostr-tools/lib/types/nip47.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip47.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip49.d.ts b/node_modules/nostr-tools/lib/types/nip49.d.ts new file mode 100644 index 0000000..bdd87f8 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip49.d.ts @@ -0,0 +1,3 @@ +import { Ncryptsec } from './nip19.ts'; +export declare function encrypt(sec: Uint8Array, password: string, logn?: number, ksb?: 0x00 | 0x01 | 0x02): Ncryptsec; +export declare function decrypt(ncryptsec: string, password: string): Uint8Array; diff --git a/node_modules/nostr-tools/lib/types/nip49.test.d.ts b/node_modules/nostr-tools/lib/types/nip49.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip49.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip54.d.ts b/node_modules/nostr-tools/lib/types/nip54.d.ts new file mode 100644 index 0000000..3399f9c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip54.d.ts @@ -0,0 +1 @@ +export declare function normalizeIdentifier(name: string): string; diff --git a/node_modules/nostr-tools/lib/types/nip54.test.d.ts b/node_modules/nostr-tools/lib/types/nip54.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip54.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip55.d.ts b/node_modules/nostr-tools/lib/types/nip55.d.ts new file mode 100644 index 0000000..3879694 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip55.d.ts @@ -0,0 +1,30 @@ +type BaseParams = { + callbackUrl?: string; + returnType?: 'signature' | 'event'; + compressionType?: 'none' | 'gzip'; +}; +type PermissionsParams = BaseParams & { + permissions?: { + type: string; + kind?: number; + }[]; +}; +type EventUriParams = BaseParams & { + eventJson: Record; + id?: string; + currentUser?: string; +}; +type EncryptDecryptParams = BaseParams & { + pubKey: string; + content: string; + id?: string; + currentUser?: string; +}; +export declare function getPublicKeyUri({ permissions, ...params }: PermissionsParams): string; +export declare function signEventUri({ eventJson, ...params }: EventUriParams): string; +export declare function encryptNip04Uri(params: EncryptDecryptParams): string; +export declare function decryptNip04Uri(params: EncryptDecryptParams): string; +export declare function encryptNip44Uri(params: EncryptDecryptParams): string; +export declare function decryptNip44Uri(params: EncryptDecryptParams): string; +export declare function decryptZapEventUri({ eventJson, ...params }: EventUriParams): string; +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip55.test.d.ts b/node_modules/nostr-tools/lib/types/nip55.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip55.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip57.d.ts b/node_modules/nostr-tools/lib/types/nip57.d.ts new file mode 100644 index 0000000..072c980 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip57.d.ts @@ -0,0 +1,25 @@ +import { NostrEvent, type Event, type EventTemplate } from './pure.ts'; +export declare function useFetchImplementation(fetchImplementation: any): void; +export declare function getZapEndpoint(metadata: Event): Promise; +type ProfileZap = { + pubkey: string; + amount: number; + comment?: string; + relays: string[]; +}; +type EventZap = { + event: NostrEvent; + amount: number; + comment?: string; + relays: string[]; +}; +export declare function makeZapRequest(params: ProfileZap | EventZap): EventTemplate; +export declare function validateZapRequest(zapRequestString: string): string | null; +export declare function makeZapReceipt({ zapRequest, preimage, bolt11, paidAt, }: { + zapRequest: string; + preimage?: string; + bolt11: string; + paidAt: Date; +}): EventTemplate; +export declare function getSatoshisAmountFromBolt11(bolt11: string): number; +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip57.test.d.ts b/node_modules/nostr-tools/lib/types/nip57.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip57.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip58.d.ts b/node_modules/nostr-tools/lib/types/nip58.d.ts new file mode 100644 index 0000000..ed0fc90 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip58.d.ts @@ -0,0 +1,134 @@ +import { Event, EventTemplate } from './core.ts'; +/** + * Represents the structure for defining a badge within the Nostr network. + * This structure is used to create templates for badge definition events, + * facilitating the recognition and awarding of badges to users for various achievements. + */ +export type BadgeDefinition = { + /** + * A unique identifier for the badge. This is used to distinguish badges + * from one another and should be unique across all badge definitions. + * Typically, this could be a short, descriptive string. + */ + d: string; + /** + * An optional short name for the badge. This provides a human-readable + * title for the badge, making it easier to recognize and refer to. + */ + name?: string; + /** + * An optional description for the badge. This field can be used to + * provide more detailed information about the badge, such as the criteria + * for its awarding or its significance. + */ + description?: string; + /** + * An optional image URL and dimensions for the badge. The first element + * of the tuple is the URL pointing to a high-resolution image representing + * the badge, and the second element specifies the image's dimensions in + * the format "widthxheight". The recommended dimensions are 1024x1024 pixels. + */ + image?: [string, string]; + /** + * An optional list of thumbnail images for the badge. Each element in the + * array is a tuple, where the first element is the URL pointing to a thumbnail + * version of the badge image, and the second element specifies the thumbnail's + * dimensions in the format "widthxheight". Multiple thumbnails can be provided + * to support different display sizes. + */ + thumbs?: Array<[string, string]>; +}; +/** + * Represents the structure for awarding a badge to one or more recipients + * within the Nostr network. This structure is used to create templates for + * badge award events, which are immutable and signify the recognition of + * individuals' achievements or contributions. + */ +export type BadgeAward = { + /** + * A reference to the Badge Definition event. This is typically composed + * of the event ID of the badge definition. It establishes a clear linkage + * between the badge being awarded and its original definition, ensuring + * that recipients are awarded the correct badge. + */ + a: string; + /** + * An array of p tags, each containing a pubkey and its associated relays. + */ + p: string[][]; +}; +/** + * Represents the collection of badges a user chooses to display on their profile. + * This structure is crucial for applications that allow users to showcase achievements + * or recognitions in the form of badges, following the specifications of NIP-58. + */ +export type ProfileBadges = { + /** + * A unique identifier for the profile badges collection. According to NIP-58, + * this should be set to "profile_badges" to differentiate it from other event types. + */ + d: 'profile_badges'; + /** + * A list of badges that the user has elected to display on their profile. Each item + * in the array represents a specific badge, including references to both its definition + * and the award event. + */ + badges: Array<{ + /** + * The event address of the badge definition. This is a reference to the specific badge + * being displayed, linking back to the badge's original definition event. It allows + * clients to fetch and display the badge's details, such as its name, description, + * and image. + */ + a: string; + /** + * The event id of the badge award with corresponding relays. This references the event + * in which the badge was awarded to the user. It is crucial for verifying the + * authenticity of the badge display, ensuring that the user was indeed awarded the + * badge they are choosing to display. + */ + e: string[]; + }>; +}; +/** + * Generates an EventTemplate based on the provided BadgeDefinition. + * + * @param {BadgeDefinition} badgeDefinition - The BadgeDefinition object. + * @returns {EventTemplate} - The generated EventTemplate object. + */ +export declare function generateBadgeDefinitionEventTemplate({ d, description, image, name, thumbs, }: BadgeDefinition): EventTemplate; +/** + * Validates a badge definition event. + * + * @param event - The event to validate. + * @returns A boolean indicating whether the event is a valid badge definition event. + */ +export declare function validateBadgeDefinitionEvent(event: Event): boolean; +/** + * Generates an EventTemplate based on the provided BadgeAward. + * + * @param {BadgeAward} badgeAward - The BadgeAward object. + * @returns {EventTemplate} - The generated EventTemplate object. + */ +export declare function generateBadgeAwardEventTemplate({ a, p }: BadgeAward): EventTemplate; +/** + * Validates a badge award event. + * + * @param event - The event to validate. + * @returns A boolean indicating whether the event is a valid badge award event. + */ +export declare function validateBadgeAwardEvent(event: Event): boolean; +/** + * Generates an EventTemplate based on the provided ProfileBadges. + * + * @param {ProfileBadges} profileBadges - The ProfileBadges object. + * @returns {EventTemplate} - The generated EventTemplate object. + */ +export declare function generateProfileBadgesEventTemplate({ badges }: ProfileBadges): EventTemplate; +/** + * Validates a profile badges event. + * + * @param event - The event to validate. + * @returns A boolean indicating whether the event is a valid profile badges event. + */ +export declare function validateProfileBadgesEvent(event: Event): boolean; diff --git a/node_modules/nostr-tools/lib/types/nip58.test.d.ts b/node_modules/nostr-tools/lib/types/nip58.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip58.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip59.d.ts b/node_modules/nostr-tools/lib/types/nip59.d.ts new file mode 100644 index 0000000..363e4f2 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip59.d.ts @@ -0,0 +1,12 @@ +import { UnsignedEvent, NostrEvent } from './core.ts'; +type Rumor = UnsignedEvent & { + id: string; +}; +export declare function createRumor(event: Partial, privateKey: Uint8Array): Rumor; +export declare function createSeal(rumor: Rumor, privateKey: Uint8Array, recipientPublicKey: string): NostrEvent; +export declare function createWrap(seal: NostrEvent, recipientPublicKey: string): NostrEvent; +export declare function wrapEvent(event: Partial, senderPrivateKey: Uint8Array, recipientPublicKey: string): NostrEvent; +export declare function wrapManyEvents(event: Partial, senderPrivateKey: Uint8Array, recipientsPublicKeys: string[]): NostrEvent[]; +export declare function unwrapEvent(wrap: NostrEvent, recipientPrivateKey: Uint8Array): Rumor; +export declare function unwrapManyEvents(wrappedEvents: NostrEvent[], recipientPrivateKey: Uint8Array): Rumor[]; +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip59.test.d.ts b/node_modules/nostr-tools/lib/types/nip59.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip59.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip75.d.ts b/node_modules/nostr-tools/lib/types/nip75.d.ts new file mode 100644 index 0000000..6dcd017 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip75.d.ts @@ -0,0 +1,61 @@ +import { Event, EventTemplate } from './core.ts'; +/** + * Represents a fundraising goal in the Nostr network as defined by NIP-75. + * This type is used to structure the information needed to create a goal event (`kind:9041`). + */ +export type Goal = { + /** + * A human-readable description of the fundraising goal. + * This content should provide clear information about the purpose of the fundraising. + */ + content: string; + /** + * The target amount for the fundraising goal in milisats. + * This defines the financial target that the fundraiser aims to reach. + */ + amount: string; + /** + * A list of relays where the zaps towards this goal will be sent to and tallied from. + * Each relay is represented by its WebSocket URL. + */ + relays: string[]; + /** + * An optional timestamp (in seconds, UNIX epoch) indicating when the fundraising goal is considered closed. + * Zaps published after this timestamp should not count towards the goal progress. + * If not provided, the goal remains open indefinitely or until manually closed. + */ + closedAt?: number; + /** + * An optional URL to an image related to the goal. + * This can be used to visually represent the goal on client interfaces. + */ + image?: string; + /** + * An optional brief description or summary of the goal. + * This can provide a quick overview of the goal, separate from the detailed `content`. + */ + summary?: string; + /** + * An optional URL related to the goal, providing additional information or actions through an 'r' tag. + * This is a single URL, as per NIP-75 specifications for linking additional resources. + */ + r?: string; + /** + * An optional parameterized replaceable event linked to the goal, specified through an 'a' tag. + * This is a single event id, aligning with NIP-75's allowance for linking to specific events. + */ + a?: string; + /** + * Optional tags specifying multiple beneficiary pubkeys or additional criteria for zapping, + * allowing contributions to be directed towards multiple recipients or according to specific conditions. + */ + zapTags?: string[][]; +}; +/** + * Generates an EventTemplate for a fundraising goal based on the provided ZapGoal object. + * This function is tailored to fit the structure of EventTemplate as defined in the library. + * @param zapGoal The ZapGoal object containing the details of the fundraising goal. + * @returns An EventTemplate object structured for creating a Nostr event. + */ +export declare function generateGoalEventTemplate({ amount, content, relays, a, closedAt, image, r, summary, zapTags, }: Goal): EventTemplate; +export declare function validateZapGoalEvent(event: Event): boolean; diff --git a/node_modules/nostr-tools/lib/types/nip75.test.d.ts b/node_modules/nostr-tools/lib/types/nip75.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip75.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip94.d.ts b/node_modules/nostr-tools/lib/types/nip94.d.ts new file mode 100644 index 0000000..122282c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip94.d.ts @@ -0,0 +1,87 @@ +import { Event, EventTemplate } from './core.ts'; +/** + * Type definition for File Metadata as specified in NIP-94. + * This type is used to represent the metadata associated with a file sharing event (kind: 1063). + */ +export type FileMetadataObject = { + /** + * A description or caption for the file content. + */ + content: string; + /** + * The URL to download the file. + */ + url: string; + /** + * The MIME type of the file, in lowercase. + */ + m: string; + /** + * The SHA-256 hex-encoded string of the file. + */ + x: string; + /** + * The SHA-256 hex-encoded string of the original file, before any transformations done by the upload server. + */ + ox: string; + /** + * Optional: The size of the file in bytes. + */ + size?: string; + /** + * Optional: The dimensions of the file in pixels, in the format "x". + */ + dim?: string; + /** + * Optional: The URI to the magnet file. + */ + magnet?: string; + /** + * Optional: The torrent infohash. + */ + i?: string; + /** + * Optional: The blurhash string to show while the file is being loaded by the client. + */ + blurhash?: string; + /** + * Optional: The URL of the thumbnail image with the same aspect ratio as the original file. + */ + thumb?: string; + /** + * Optional: The URL of a preview image with the same dimensions as the original file. + */ + image?: string; + /** + * Optional: A text excerpt or summary of the file's content. + */ + summary?: string; + /** + * Optional: A description for accessibility, providing context or a brief description of the file. + */ + alt?: string; + /** + * Optional: fallback URLs in case url fails. + */ + fallback?: string[]; +}; +/** + * Generates an event template based on a file metadata object. + * + * @param fileMetadata - The file metadata object. + * @returns The event template. + */ +export declare function generateEventTemplate(fileMetadata: FileMetadataObject): EventTemplate; +/** + * Validates an event to ensure it is a valid file metadata event. + * @param event - The event to validate. + * @returns True if the event is valid, false otherwise. + */ +export declare function validateEvent(event: Event): boolean; +/** + * Parses an event and returns a file metadata object. + * @param event - The event to parse. + * @returns The file metadata object. + * @throws Error if the event is invalid. + */ +export declare function parseEvent(event: Event): FileMetadataObject; diff --git a/node_modules/nostr-tools/lib/types/nip94.test.d.ts b/node_modules/nostr-tools/lib/types/nip94.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip94.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip98.d.ts b/node_modules/nostr-tools/lib/types/nip98.d.ts new file mode 100644 index 0000000..21139f1 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip98.d.ts @@ -0,0 +1,74 @@ +import { Event, EventTemplate } from './pure.ts'; +/** + * Generate token for NIP-98 flow. + * + * @example + * const sign = window.nostr.signEvent + * await nip98.getToken('https://example.com/login', 'post', (e) => sign(e), true) + */ +export declare function getToken(loginUrl: string, httpMethod: string, sign: (e: EventTemplate) => Promise | Event, includeAuthorizationScheme?: boolean, payload?: Record): Promise; +/** + * Validate token for NIP-98 flow. + * + * @example + * await nip98.validateToken('Nostr base64token', 'https://example.com/login', 'post') + */ +export declare function validateToken(token: string, url: string, method: string): Promise; +/** + * Unpacks an event from a token. + * + * @param token - The token to unpack. + * @returns A promise that resolves to the unpacked event. + * @throws {Error} If the token is missing, invalid, or cannot be parsed. + */ +export declare function unpackEventFromToken(token: string): Promise; +/** + * Validates the timestamp of an event. + * @param event - The event object to validate. + * @returns A boolean indicating whether the event timestamp is within the last 60 seconds. + */ +export declare function validateEventTimestamp(event: Event): boolean; +/** + * Validates the kind of an event. + * @param event The event to validate. + * @returns A boolean indicating whether the event kind is valid. + */ +export declare function validateEventKind(event: Event): boolean; +/** + * Validates if the given URL matches the URL tag of the event. + * @param event - The event object. + * @param url - The URL to validate. + * @returns A boolean indicating whether the URL is valid or not. + */ +export declare function validateEventUrlTag(event: Event, url: string): boolean; +/** + * Validates if the given event has a method tag that matches the specified method. + * @param event - The event to validate. + * @param method - The method to match against the method tag. + * @returns A boolean indicating whether the event has a matching method tag. + */ +export declare function validateEventMethodTag(event: Event, method: string): boolean; +/** + * Calculates the hash of a payload. + * @param payload - The payload to be hashed. + * @returns The hash value as a string. + */ +export declare function hashPayload(payload: any): string; +/** + * Validates the event payload tag against the provided payload. + * @param event The event object. + * @param payload The payload to validate. + * @returns A boolean indicating whether the payload tag is valid. + */ +export declare function validateEventPayloadTag(event: Event, payload: any): boolean; +/** + * Validates a Nostr event for the NIP-98 flow. + * + * @param event - The Nostr event to validate. + * @param url - The URL associated with the event. + * @param method - The HTTP method associated with the event. + * @param body - The request body associated with the event (optional). + * @returns A promise that resolves to a boolean indicating whether the event is valid. + * @throws An error if the event is invalid. + */ +export declare function validateEvent(event: Event, url: string, method: string, body?: any): Promise; diff --git a/node_modules/nostr-tools/lib/types/nip98.test.d.ts b/node_modules/nostr-tools/lib/types/nip98.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip98.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nip99.d.ts b/node_modules/nostr-tools/lib/types/nip99.d.ts new file mode 100644 index 0000000..1781733 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip99.d.ts @@ -0,0 +1,92 @@ +import { Event, EventTemplate } from './core.ts'; +/** + * Represents the details of a price. + * @example { amount: '100', currency: 'USD', frequency: 'month' } + * @example { amount: '100', currency: 'EUR' } + */ +export type PriceDetails = { + /** + * The amount of the price. + */ + amount: string; + /** + * The currency of the price in 3-letter ISO 4217 format. + * @example 'USD' + */ + currency: string; + /** + * The optional frequency of payment. + * Can be one of: 'hour', 'day', 'week', 'month', 'year', or a custom string. + */ + frequency?: string; +}; +/** + * Represents a classified listing object. + */ +export type ClassifiedListingObject = { + /** + * Whether the listing is a draft or not. + */ + isDraft: boolean; + /** + * A title of the listing. + */ + title: string; + /** + * A short summary or tagline. + */ + summary: string; + /** + * A description in Markdown format. + */ + content: string; + /** + * Timestamp in unix seconds of when the listing was published. + */ + publishedAt: string; + /** + * Location of the listing. + * @example 'NYC' + */ + location: string; + /** + * Price details. + */ + price: PriceDetails; + /** + * Images of the listing with optional dimensions. + */ + images: Array<{ + url: string; + dimensions?: string; + }>; + /** + * Tags/Hashtags (i.e. categories, keywords, etc.) + */ + hashtags: string[]; + /** + * Other standard tags. + * @example "g", a geohash for more precise location + */ + additionalTags: Record; +}; +/** + * Validates an event to ensure it is a valid classified listing event. + * @param event - The event to validate. + * @returns True if the event is valid, false otherwise. + */ +export declare function validateEvent(event: Event): boolean; +/** + * Parses an event and returns a classified listing object. + * @param event - The event to parse. + * @returns The classified listing object. + * @throws Error if the event is invalid. + */ +export declare function parseEvent(event: Event): ClassifiedListingObject; +/** + * Generates an event template based on a classified listing object. + * + * @param listing - The classified listing object. + * @returns The event template. + */ +export declare function generateEventTemplate(listing: ClassifiedListingObject): EventTemplate; diff --git a/node_modules/nostr-tools/lib/types/nip99.test.d.ts b/node_modules/nostr-tools/lib/types/nip99.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nip99.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/nipb7.d.ts b/node_modules/nostr-tools/lib/types/nipb7.d.ts new file mode 100644 index 0000000..3ba0b33 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nipb7.d.ts @@ -0,0 +1,23 @@ +import { Signer } from './signer.ts'; +export type BlobDescriptor = { + url: string; + sha256: string; + size: number; + type: string; + uploaded: number; +}; +export declare class BlossomClient { + private mediaserver; + private signer; + constructor(mediaserver: string, signer: Signer); + private httpCall; + private authorizationHeader; + private isValid32ByteHex; + check(hash: string): Promise; + uploadBlob(file: File | Blob, contentType?: string): Promise; + uploadFile(file: File): Promise; + download(hash: string): Promise; + downloadAsBlob(hash: string): Promise; + list(): Promise; + delete(hash: string): Promise; +} diff --git a/node_modules/nostr-tools/lib/types/nipb7.test.d.ts b/node_modules/nostr-tools/lib/types/nipb7.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/nipb7.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/pool.d.ts b/node_modules/nostr-tools/lib/types/pool.d.ts new file mode 100644 index 0000000..821c2a9 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/pool.d.ts @@ -0,0 +1,8 @@ +import { AbstractSimplePool } from './abstract-pool.ts'; +export declare function useWebSocketImplementation(websocketImplementation: any): void; +export declare class SimplePool extends AbstractSimplePool { + constructor(options?: { + enablePing?: boolean; + }); +} +export * from './abstract-pool.ts'; diff --git a/node_modules/nostr-tools/lib/types/pool.test.d.ts b/node_modules/nostr-tools/lib/types/pool.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/pool.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/pure.d.ts b/node_modules/nostr-tools/lib/types/pure.d.ts new file mode 100644 index 0000000..f28a9ea --- /dev/null +++ b/node_modules/nostr-tools/lib/types/pure.d.ts @@ -0,0 +1,8 @@ +import { Event, EventTemplate, UnsignedEvent, VerifiedEvent } from './core.ts'; +export declare function serializeEvent(evt: UnsignedEvent): string; +export declare function getEventHash(event: UnsignedEvent): string; +export declare const generateSecretKey: () => Uint8Array; +export declare const getPublicKey: (secretKey: Uint8Array) => string; +export declare const finalizeEvent: (t: EventTemplate, secretKey: Uint8Array) => VerifiedEvent; +export declare const verifyEvent: (event: Event) => event is VerifiedEvent; +export * from './core.ts'; diff --git a/node_modules/nostr-tools/lib/types/pure.test.d.ts b/node_modules/nostr-tools/lib/types/pure.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/pure.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/references.d.ts b/node_modules/nostr-tools/lib/types/references.d.ts new file mode 100644 index 0000000..66346b1 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/references.d.ts @@ -0,0 +1,10 @@ +import { type AddressPointer, type ProfilePointer, type EventPointer } from './nip19.ts'; +import type { Event } from './core.ts'; +type Reference = { + text: string; + profile?: ProfilePointer; + event?: EventPointer; + address?: AddressPointer; +}; +export declare function parseReferences(evt: Event): Reference[]; +export {}; diff --git a/node_modules/nostr-tools/lib/types/references.test.d.ts b/node_modules/nostr-tools/lib/types/references.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/references.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/relay.d.ts b/node_modules/nostr-tools/lib/types/relay.d.ts new file mode 100644 index 0000000..eeb6ce9 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/relay.d.ts @@ -0,0 +1,11 @@ +import { AbstractRelay } from './abstract-relay.ts'; +export declare function useWebSocketImplementation(websocketImplementation: any): void; +export declare class Relay extends AbstractRelay { + constructor(url: string); + static connect(url: string): Promise; +} +export type RelayRecord = Record; +export * from './abstract-relay.ts'; diff --git a/node_modules/nostr-tools/lib/types/relay.test.d.ts b/node_modules/nostr-tools/lib/types/relay.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/relay.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/signer.d.ts b/node_modules/nostr-tools/lib/types/signer.d.ts new file mode 100644 index 0000000..2ea82ab --- /dev/null +++ b/node_modules/nostr-tools/lib/types/signer.d.ts @@ -0,0 +1,11 @@ +import { EventTemplate, VerifiedEvent } from './core.ts'; +export interface Signer { + getPublicKey(): Promise; + signEvent(event: EventTemplate): Promise; +} +export declare class PlainKeySigner implements Signer { + private secretKey; + constructor(secretKey: Uint8Array); + getPublicKey(): Promise; + signEvent(event: EventTemplate): Promise; +} diff --git a/node_modules/nostr-tools/lib/types/test-helpers.d.ts b/node_modules/nostr-tools/lib/types/test-helpers.d.ts new file mode 100644 index 0000000..058ba98 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/test-helpers.d.ts @@ -0,0 +1,13 @@ +import { WebSocket } from 'mock-socket'; +import { type Event } from './pure.ts'; +export declare const MockWebSocketClient: typeof WebSocket; +export declare function buildEvent(params: Partial): Event; +export declare class MockRelay { + private _server; + url: string; + secretKeys: Uint8Array[]; + preloadedEvents: Event[]; + constructor(url?: string | undefined); + get authors(): string[]; + get ids(): string[]; +} diff --git a/node_modules/nostr-tools/lib/types/utils.d.ts b/node_modules/nostr-tools/lib/types/utils.d.ts new file mode 100644 index 0000000..247a52b --- /dev/null +++ b/node_modules/nostr-tools/lib/types/utils.d.ts @@ -0,0 +1,21 @@ +import type { Event } from './core.ts'; +export declare const utf8Decoder: TextDecoder; +export declare const utf8Encoder: TextEncoder; +export { bytesToHex, hexToBytes } from '@noble/hashes/utils'; +export declare function normalizeURL(url: string): string; +export declare function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[]; +export declare function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[]; +export declare function binarySearch(arr: T[], compare: (b: T) => number): [number, boolean]; +export declare class QueueNode { + value: V; + next: QueueNode | null; + prev: QueueNode | null; + constructor(message: V); +} +export declare class Queue { + first: QueueNode | null; + last: QueueNode | null; + constructor(); + enqueue(value: V): boolean; + dequeue(): V | null; +} diff --git a/node_modules/nostr-tools/lib/types/utils.test.d.ts b/node_modules/nostr-tools/lib/types/utils.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-tools/lib/types/utils.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-tools/lib/types/wasm.d.ts b/node_modules/nostr-tools/lib/types/wasm.d.ts new file mode 100644 index 0000000..6d39499 --- /dev/null +++ b/node_modules/nostr-tools/lib/types/wasm.d.ts @@ -0,0 +1,8 @@ +import { Nostr as NostrWasm } from 'nostr-wasm'; +import { EventTemplate, Event, VerifiedEvent } from './core.ts'; +export declare function setNostrWasm(x: NostrWasm): void; +export declare const generateSecretKey: () => Uint8Array; +export declare const getPublicKey: (secretKey: Uint8Array) => string; +export declare const finalizeEvent: (t: EventTemplate, secretKey: Uint8Array) => VerifiedEvent; +export declare const verifyEvent: (event: Event) => event is VerifiedEvent; +export * from './core.ts'; diff --git a/node_modules/nostr-tools/package.json b/node_modules/nostr-tools/package.json new file mode 100644 index 0000000..9961251 --- /dev/null +++ b/node_modules/nostr-tools/package.json @@ -0,0 +1,281 @@ +{ + "type": "module", + "name": "nostr-tools", + "version": "2.16.2", + "description": "Tools for making a Nostr client.", + "repository": { + "type": "git", + "url": "https://github.com/nbd-wtf/nostr-tools.git" + }, + "files": [ + "lib" + ], + "sideEffects": false, + "module": "./lib/esm/index.js", + "main": "./lib/cjs/index.js", + "types": "./lib/types/index.d.ts", + "exports": { + ".": { + "import": "./lib/esm/index.js", + "require": "./lib/cjs/index.js", + "types": "./lib/types/index.d.ts" + }, + "./core": { + "import": "./lib/esm/core.js", + "require": "./lib/cjs/core.js", + "types": "./lib/types/core.d.ts" + }, + "./pure": { + "import": "./lib/esm/pure.js", + "require": "./lib/cjs/pure.js", + "types": "./lib/types/pure.d.ts" + }, + "./wasm": { + "import": "./lib/esm/wasm.js", + "require": "./lib/cjs/wasm.js", + "types": "./lib/types/wasm.d.ts" + }, + "./kinds": { + "import": "./lib/esm/kinds.js", + "require": "./lib/cjs/kinds.js", + "types": "./lib/types/kinds.d.ts" + }, + "./filter": { + "import": "./lib/esm/filter.js", + "require": "./lib/cjs/filter.js", + "types": "./lib/types/filter.d.ts" + }, + "./abstract-relay": { + "import": "./lib/esm/abstract-relay.js", + "require": "./lib/cjs/abstract-relay.js", + "types": "./lib/types/abstract-relay.d.ts" + }, + "./relay": { + "import": "./lib/esm/relay.js", + "require": "./lib/cjs/relay.js", + "types": "./lib/types/relay.d.ts" + }, + "./abstract-pool": { + "import": "./lib/esm/abstract-pool.js", + "require": "./lib/cjs/abstract-pool.js", + "types": "./lib/types/abstract-pool.d.ts" + }, + "./pool": { + "import": "./lib/esm/pool.js", + "require": "./lib/cjs/pool.js", + "types": "./lib/types/pool.d.ts" + }, + "./references": { + "import": "./lib/esm/references.js", + "require": "./lib/cjs/references.js", + "types": "./lib/types/references.d.ts" + }, + "./nip04": { + "import": "./lib/esm/nip04.js", + "require": "./lib/cjs/nip04.js", + "types": "./lib/types/nip04.d.ts" + }, + "./nip05": { + "import": "./lib/esm/nip05.js", + "require": "./lib/cjs/nip05.js", + "types": "./lib/types/nip05.d.ts" + }, + "./nip06": { + "import": "./lib/esm/nip06.js", + "require": "./lib/cjs/nip06.js", + "types": "./lib/types/nip06.d.ts" + }, + "./nip07": { + "types": "./lib/types/nip07.d.ts" + }, + "./nip10": { + "import": "./lib/esm/nip10.js", + "require": "./lib/cjs/nip10.js", + "types": "./lib/types/nip10.d.ts" + }, + "./nip11": { + "import": "./lib/esm/nip11.js", + "require": "./lib/cjs/nip11.js", + "types": "./lib/types/nip11.d.ts" + }, + "./nip13": { + "import": "./lib/esm/nip13.js", + "require": "./lib/cjs/nip13.js", + "types": "./lib/types/nip13.d.ts" + }, + "./nip17": { + "import": "./lib/esm/nip17.js", + "require": "./lib/cjs/nip17.js", + "types": "./lib/types/nip17.d.ts" + }, + "./nip18": { + "import": "./lib/esm/nip18.js", + "require": "./lib/cjs/nip18.js", + "types": "./lib/types/nip18.d.ts" + }, + "./nip19": { + "import": "./lib/esm/nip19.js", + "require": "./lib/cjs/nip19.js", + "types": "./lib/types/nip19.d.ts" + }, + "./nip21": { + "import": "./lib/esm/nip21.js", + "require": "./lib/cjs/nip21.js", + "types": "./lib/types/nip21.d.ts" + }, + "./nip25": { + "import": "./lib/esm/nip25.js", + "require": "./lib/cjs/nip25.js", + "types": "./lib/types/nip25.d.ts" + }, + "./nip27": { + "import": "./lib/esm/nip27.js", + "require": "./lib/cjs/nip27.js", + "types": "./lib/types/nip27.d.ts" + }, + "./nip28": { + "import": "./lib/esm/nip28.js", + "require": "./lib/cjs/nip28.js", + "types": "./lib/types/nip28.d.ts" + }, + "./nip29": { + "import": "./lib/esm/nip29.js", + "require": "./lib/cjs/nip29.js", + "types": "./lib/types/nip29.d.ts" + }, + "./nip30": { + "import": "./lib/esm/nip30.js", + "require": "./lib/cjs/nip30.js", + "types": "./lib/types/nip30.d.ts" + }, + "./nip39": { + "import": "./lib/esm/nip39.js", + "require": "./lib/cjs/nip39.js", + "types": "./lib/types/nip39.d.ts" + }, + "./nip42": { + "import": "./lib/esm/nip42.js", + "require": "./lib/cjs/nip42.js", + "types": "./lib/types/nip42.d.ts" + }, + "./nip44": { + "import": "./lib/esm/nip44.js", + "require": "./lib/cjs/nip44.js", + "types": "./lib/types/nip44.d.ts" + }, + "./nip46": { + "import": "./lib/esm/nip46.js", + "require": "./lib/cjs/nip46.js", + "types": "./lib/types/nip46.d.ts" + }, + "./nip49": { + "import": "./lib/esm/nip49.js", + "require": "./lib/cjs/nip49.js", + "types": "./lib/types/nip49.d.ts" + }, + "./nip54": { + "import": "./lib/esm/nip54.js", + "require": "./lib/cjs/nip54.js", + "types": "./lib/types/nip54.d.ts" + }, + "./nip57": { + "import": "./lib/esm/nip57.js", + "require": "./lib/cjs/nip57.js", + "types": "./lib/types/nip57.d.ts" + }, + "./nip59": { + "import": "./lib/esm/nip59.js", + "require": "./lib/cjs/nip59.js", + "types": "./lib/types/nip59.d.ts" + }, + "./nip58": { + "import": "./lib/esm/nip58.js", + "require": "./lib/cjs/nip58.js", + "types": "./lib/types/nip58.d.ts" + }, + "./nip75": { + "import": "./lib/esm/nip75.js", + "require": "./lib/cjs/nip75.js", + "types": "./lib/types/nip75.d.ts" + }, + "./nip94": { + "import": "./lib/esm/nip94.js", + "require": "./lib/cjs/nip94.js", + "types": "./lib/types/nip94.d.ts" + }, + "./nip98": { + "import": "./lib/esm/nip98.js", + "require": "./lib/cjs/nip98.js", + "types": "./lib/types/nip98.d.ts" + }, + "./nip99": { + "import": "./lib/esm/nip99.js", + "require": "./lib/cjs/nip99.js", + "types": "./lib/types/nip99.d.ts" + }, + "./nipb7": { + "import": "./lib/esm/nipb7.js", + "require": "./lib/cjs/nipb7.js", + "types": "./lib/types/nipb7.d.ts" + }, + "./fakejson": { + "import": "./lib/esm/fakejson.js", + "require": "./lib/cjs/fakejson.js", + "types": "./lib/types/fakejson.d.ts" + }, + "./signer": { + "import": "./lib/esm/signer.js", + "require": "./lib/cjs/signer.js", + "types": "./lib/types/signer.d.ts" + }, + "./utils": { + "import": "./lib/esm/utils.js", + "require": "./lib/cjs/utils.js", + "types": "./lib/types/utils.d.ts" + } + }, + "license": "Unlicense", + "dependencies": { + "@noble/ciphers": "^0.5.1", + "@noble/curves": "1.2.0", + "@noble/hashes": "1.3.1", + "@scure/base": "1.1.1", + "@scure/bip32": "1.3.1", + "@scure/bip39": "1.2.1", + "nostr-wasm": "0.1.0" + }, + "peerDependencies": { + "typescript": ">=5.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + }, + "keywords": [ + "decentralization", + "social", + "censorship-resistance", + "client", + "nostr" + ], + "devDependencies": { + "@types/node": "^18.13.0", + "@types/node-fetch": "^2.6.3", + "@typescript-eslint/eslint-plugin": "^6.5.0", + "@typescript-eslint/parser": "^6.5.0", + "bun-types": "^1.0.18", + "esbuild": "0.16.9", + "eslint": "^8.56.0", + "eslint-config-prettier": "^9.0.0", + "events": "^3.3.0", + "mitata": "^0.1.6", + "mock-socket": "^9.3.1", + "node-fetch": "^2.6.9", + "prettier": "^3.0.3", + "typescript": "^5.8.2" + }, + "scripts": { + "prepublish": "just build" + } +} diff --git a/node_modules/nostr-wasm/README.md b/node_modules/nostr-wasm/README.md new file mode 100644 index 0000000..f646e71 --- /dev/null +++ b/node_modules/nostr-wasm/README.md @@ -0,0 +1,91 @@ +# nostr-wasm + +Nostr signature stuff in WASM based on libsecp256k1. + +## Install + +```sh +yarn install +``` + +## Demo + +A demo application using this package is available at https://nostr-wasm-demo.pages.dev/. + +## Usage + +First, choose which import method suites your needs: + +#### Default + +Import with the WASM binary preloaded and uncompressed. No need to perform `fetch`, but bundle will be larger (+332 KiB). + +```ts +import {initNostrWasm} from 'nostr-wasm' +const nw = await initNostrWasm() +``` + +#### Compressed + +Import with the WASM binary preloaded and gzipped (requires access to `globalThis.DecompressionSteam`). No need to perform `fetch`, but bundle will be still be a bit larger (+175 KiB). + +```ts +import {initNostrWasm} from 'nostr-wasm/gzipped' +const nw = await initNostrWasm() +``` + +#### Headless + +Import without the WASM binary. Produces the smallest bundle size but requires fetching the binary yourself. + +```ts +import {NostrWasm} from 'nostr-wasm/headless' + +// provide the binary (the constructor also accepts raw bytes) +const nw = await NostrWasm(await fetch('secp256k1.wasm')) +``` + +### Using the instance: + +```ts +// generate a random private key +const sec = nw.generateSecretKey() + +// get its corresponding public key +const pubkey = nw.getPublicKey(sec) + +// finalize a nostr event in-place, filling it with id, pubkey and sig +nw.finalizeEvent(event, sec) + +// verify a nostr event checking its id and its signature against the given pubkey +try { + nw.verifyEvent(event) +} catch (err) { + console.log(err) +} +``` + +Caller is responsible for zero-ing out private keys in the Uint8Array it passes. Library only zeroes out the bytes in the copies it makes. + +## Is libsecp256k1 modified? + +No, the library is imported as a git submodule directly from upstream. + +## Building from source + +Prerequisites: + +- [Podman](https://podman.io/) +- [Bun](https://bun.sh/) +- [Just](https://just.systems/) + +```sh +git clone --recurse-submodules https://github.com/fiatjaf/nostr-wasm +cd nostr-wasm +bun install +just +``` + +The WASM binary will be output to `public/out/secp256k1.wasm`. + +The Emscripten-generated js file at `public/out/secp256k1.js` is not needed for production if you are using the provided wrapper. diff --git a/node_modules/nostr-wasm/dist/api/emsimp.d.ts b/node_modules/nostr-wasm/dist/api/emsimp.d.ts new file mode 100644 index 0000000..f6e0d15 --- /dev/null +++ b/node_modules/nostr-wasm/dist/api/emsimp.d.ts @@ -0,0 +1,3 @@ +/// +import type { ImportMapper } from 'src/types'; +export declare const emsimp: (f_map_imports: ImportMapper, label: string) => readonly [WebAssembly.Imports, (d_memory: WebAssembly.Memory) => readonly [ArrayBuffer, Uint8Array, Uint32Array]]; diff --git a/node_modules/nostr-wasm/dist/api/nostr.d.ts b/node_modules/nostr-wasm/dist/api/nostr.d.ts new file mode 100644 index 0000000..df599e3 --- /dev/null +++ b/node_modules/nostr-wasm/dist/api/nostr.d.ts @@ -0,0 +1,45 @@ +/// +/// +type Event = { + id: string; + pubkey: string; + sig: string; + content: string; + kind: number; + created_at: number; + tags: string[][]; +}; +export interface Nostr { + /** + * Generates a new private key using crypto secure random bytes and without modulo bias + * @returns a new private key (32 bytes) + */ + generateSecretKey(): Uint8Array; + /** + * Computes the public key for a given private key + * @param seckey - the private key (32 bytes) + * @returns the public key (32 bytes) + */ + getPublicKey(seckey: Uint8Array): Uint8Array; + /** + * Fills in an event object with pubkey, id and sig. + * @param event - the Nostr event object + * @param seckey - the private key + * @param entropy - optional entropy to use + */ + finalizeEvent(event: Event, seckey: Uint8Array, ent?: Uint8Array): void; + /** + * Verifies if an event's .id property is correct and that the .sig is valid + * @param event - the Nostr event object + * @throws an error with a .message if the event is not valid for any reason + */ + verifyEvent(event: Event): void; +} +/** + * Creates a new instance of the secp256k1 WASM and returns the Nostr wrapper + * @param z_src - a Response containing the WASM binary, a Promise that resolves to one, + * or the raw bytes to the WASM binary as a {@link BufferSource} + * @returns the wrapper API + */ +export declare const NostrWasm: (z_src: Promise | Response | BufferSource) => Promise; +export {}; diff --git a/node_modules/nostr-wasm/dist/api/secp256k1-types.d.ts b/node_modules/nostr-wasm/dist/api/secp256k1-types.d.ts new file mode 100644 index 0000000..b32b62d --- /dev/null +++ b/node_modules/nostr-wasm/dist/api/secp256k1-types.d.ts @@ -0,0 +1,124 @@ +import type { WasmExportsExtension } from '../gen/wasm.js'; +import type { Pointer } from '../types.js'; +export type PointerContext = Pointer<'context'>; +export type PointerSeed = Pointer<'seed'>; +export type PointerXOnlyKey = Pointer<'xonly_key'>; +export type PointerKeypair = Pointer<'keypair'>; +export type PointerSig = Pointer<'signature'>; +export type PointerSha256 = Pointer<'sha256'>; +export declare const enum ByteLens { + PRIVATE_KEY = 32, + KEYPAIR_LIB = 96, + XONLY_KEY_LIB = 64, + BIP340_SIG = 64,// secp256k1_bip340_signature: char [64]; + XONLY_PUBKEY = 32,// serialized + MSG_HASH = 32, + NONCE_ENTROPY = 32, + SHA256_LIB = 104 +} +export declare const enum Flags { + CONTEXT_NONE = 1, + CONTEXT_VERIFY = 257, + CONTEXT_SIGN = 513, + CONTEXT_DECLASSIFY = 1025 +} +export declare const enum BinaryResult { + SUCCESS = 1, + FAILURE = 0 +} +export interface Secp256k1WasmCore extends WasmExportsExtension { + /** Create a secp256k1 context object (in dynamically allocated memory). + * + * This function uses malloc to allocate memory. It is guaranteed that malloc is + * called at most once for every call of this function. If you need to avoid dynamic + * memory allocation entirely, see secp256k1_context_static and the functions in + * secp256k1_preallocated.h. + * + * Returns: a newly created context object. + * In: flags: Always set to SECP256K1_CONTEXT_NONE (see below). + */ + context_create(xm_flags: Flags): PointerContext; + /** Compute the keypair for a secret key. + * + * Returns: 1: secret was valid, keypair is ready to use + * 0: secret was invalid, try again with a different secret + * Args: ctx: pointer to a context object, initialized for signing. + * Out: keypair: pointer to the created keypair. + * In: seckey: pointer to a 32-byte secret key. + */ + keypair_create(ctx: PointerContext, keypair: PointerKeypair, secret: Pointer<32>): BinaryResult; + /** Get the x-only public key from a keypair. + * + * This is the same as calling secp256k1_keypair_pub and then + * secp256k1_xonly_pubkey_from_pubkey. + * + * Returns: 1 always. + * Args: ctx: pointer to a context object. + * Out: pubkey: pointer to an xonly_pubkey object. If 1 is returned, it is set + * to the keypair public key after converting it to an + * xonly_pubkey. If not, it's set to an invalid value. + * pk_parity: Ignored if NULL. Otherwise, pointer to an integer that will be set to the + * pk_parity argument of secp256k1_xonly_pubkey_from_pubkey. + * In: keypair: pointer to a keypair. + */ + keypair_xonly_pub(ctx: PointerContext, pubkey: PointerXOnlyKey, pk_parity: Pointer | null, keypair: PointerKeypair): BinaryResult; + /** Parse a 32-byte sequence into a xonly_pubkey object. + * + * Returns: 1 if the public key was fully valid. + * 0 if the public key could not be parsed or is invalid. + * + * Args: ctx: a secp256k1 context object. + * Out: pubkey: pointer to a pubkey object. If 1 is returned, it is set to a + * parsed version of input. If not, it's set to an invalid value. + * In: input32: pointer to a serialized xonly_pubkey. + */ + xonly_pubkey_parse(ctx: PointerContext, pubkey: PointerXOnlyKey, input32: Pointer<32>): BinaryResult; + /** Serialize an xonly_pubkey object into a 32-byte sequence. + * + * Returns: 1 always. + * + * Args: ctx: a secp256k1 context object. + * Out: output32: a pointer to a 32-byte array to place the serialized key in. + * In: pubkey: a pointer to a secp256k1_xonly_pubkey containing an initialized public key. + */ + xonly_pubkey_serialize(ctx: PointerContext, output32: Pointer<32>, pubkey: PointerXOnlyKey): BinaryResult; + /** Create a Schnorr signature. + * + * Does _not_ strictly follow BIP-340 because it does not verify the resulting + * signature. Instead, you can manually use secp256k1_schnorrsig_verify and + * abort if it fails. + * + * This function only signs 32-byte messages. If you have messages of a + * different size (or the same size but without a context-specific tag + * prefix), it is recommended to create a 32-byte message hash with + * secp256k1_tagged_sha256 and then sign the hash. Tagged hashing allows + * providing an context-specific tag for domain separation. This prevents + * signatures from being valid in multiple contexts by accident. + * + * Returns 1 on success, 0 on failure. + * Args: ctx: pointer to a context object, initialized for signing. + * Out: sig64: pointer to a 64-byte array to store the serialized signature. + * In: msg32: the 32-byte message being signed. + * keypair: pointer to an initialized keypair. + * aux_rand32: 32 bytes of fresh randomness. While recommended to provide + * this, it is only supplemental to security and can be NULL. A + * NULL argument is treated the same as an all-zero one. See + * BIP-340 "Default Signing" for a full explanation of this + * argument and for guidance if randomness is expensive. + */ + schnorrsig_sign32(ctx: PointerContext, sig64: PointerSig, msg32: Pointer<32>, keypair: PointerKeypair, aux_rand32: Pointer<32>): BinaryResult; + /** Verify a Schnorr signature. + * + * Returns: 1: correct signature + * 0: incorrect signature + * Args: ctx: a secp256k1 context object, initialized for verification. + * In: sig64: pointer to the 64-byte signature to verify. + * msg: the message being verified. Can only be NULL if msglen is 0. + * msglen: length of the message + * pubkey: pointer to an x-only public key to verify with (cannot be NULL) + */ + schnorrsig_verify(ctx: PointerContext, sig64: PointerSig, msg32: Pointer<32>, msglen: number, pubkey: PointerXOnlyKey): BinaryResult; + sha256_initialize(hash: PointerSha256): void; + sha256_write(hash: PointerSha256, data: Pointer, size: number): void; + sha256_finalize(hash: PointerSha256, out32: Pointer<32>): void; +} diff --git a/node_modules/nostr-wasm/dist/api/secp256k1.d.ts b/node_modules/nostr-wasm/dist/api/secp256k1.d.ts new file mode 100644 index 0000000..2fb0404 --- /dev/null +++ b/node_modules/nostr-wasm/dist/api/secp256k1.d.ts @@ -0,0 +1,41 @@ +/// +/// +/** + * Wrapper instance providing operations backed by libsecp256k1 WASM module + */ +export interface Secp256k1 { + /** + * Generates a new private key using crypto secure random bytes and without modulo bias + * @returns a new private key (32 bytes) + */ + gen_secret_key(): Uint8Array; + /** + * Computes the public key for a given private key + * @param sk - the private key (32 bytes) + * @returns the public key (32 bytes) + */ + get_public_key(sk: Uint8Array): Uint8Array; + /** + * Signs the given message hash using the given private key. + * @param sk - the private key + * @param hash - the message hash (32 bytes) + * @param entropy - optional entropy to use + * @returns compact signature (64 bytes)` + */ + sign(sk: Uint8Array, hash: Uint8Array, ent?: Uint8Array): Uint8Array; + /** + * Verifies the signature is valid for the given message hash and public key + * @param signature - compact signature (64 bytes) + * @param msg - the message hash (32 bytes) + * @param pk - the public key + */ + verify(signature: Uint8Array, hash: Uint8Array, pk: Uint8Array): boolean; + sha256(message: string): Uint8Array; +} +/** + * Creates a new instance of the secp256k1 WASM and returns its ES wrapper + * @param z_src - a Response containing the WASM binary, a Promise that resolves to one, + * or the raw bytes to the WASM binary as a {@link BufferSource} + * @returns the wrapper API + */ +export declare const WasmSecp256k1: (z_src: Promise | Response | BufferSource) => Promise; diff --git a/node_modules/nostr-wasm/dist/api/types.d.ts b/node_modules/nostr-wasm/dist/api/types.d.ts new file mode 100644 index 0000000..b32b62d --- /dev/null +++ b/node_modules/nostr-wasm/dist/api/types.d.ts @@ -0,0 +1,124 @@ +import type { WasmExportsExtension } from '../gen/wasm.js'; +import type { Pointer } from '../types.js'; +export type PointerContext = Pointer<'context'>; +export type PointerSeed = Pointer<'seed'>; +export type PointerXOnlyKey = Pointer<'xonly_key'>; +export type PointerKeypair = Pointer<'keypair'>; +export type PointerSig = Pointer<'signature'>; +export type PointerSha256 = Pointer<'sha256'>; +export declare const enum ByteLens { + PRIVATE_KEY = 32, + KEYPAIR_LIB = 96, + XONLY_KEY_LIB = 64, + BIP340_SIG = 64,// secp256k1_bip340_signature: char [64]; + XONLY_PUBKEY = 32,// serialized + MSG_HASH = 32, + NONCE_ENTROPY = 32, + SHA256_LIB = 104 +} +export declare const enum Flags { + CONTEXT_NONE = 1, + CONTEXT_VERIFY = 257, + CONTEXT_SIGN = 513, + CONTEXT_DECLASSIFY = 1025 +} +export declare const enum BinaryResult { + SUCCESS = 1, + FAILURE = 0 +} +export interface Secp256k1WasmCore extends WasmExportsExtension { + /** Create a secp256k1 context object (in dynamically allocated memory). + * + * This function uses malloc to allocate memory. It is guaranteed that malloc is + * called at most once for every call of this function. If you need to avoid dynamic + * memory allocation entirely, see secp256k1_context_static and the functions in + * secp256k1_preallocated.h. + * + * Returns: a newly created context object. + * In: flags: Always set to SECP256K1_CONTEXT_NONE (see below). + */ + context_create(xm_flags: Flags): PointerContext; + /** Compute the keypair for a secret key. + * + * Returns: 1: secret was valid, keypair is ready to use + * 0: secret was invalid, try again with a different secret + * Args: ctx: pointer to a context object, initialized for signing. + * Out: keypair: pointer to the created keypair. + * In: seckey: pointer to a 32-byte secret key. + */ + keypair_create(ctx: PointerContext, keypair: PointerKeypair, secret: Pointer<32>): BinaryResult; + /** Get the x-only public key from a keypair. + * + * This is the same as calling secp256k1_keypair_pub and then + * secp256k1_xonly_pubkey_from_pubkey. + * + * Returns: 1 always. + * Args: ctx: pointer to a context object. + * Out: pubkey: pointer to an xonly_pubkey object. If 1 is returned, it is set + * to the keypair public key after converting it to an + * xonly_pubkey. If not, it's set to an invalid value. + * pk_parity: Ignored if NULL. Otherwise, pointer to an integer that will be set to the + * pk_parity argument of secp256k1_xonly_pubkey_from_pubkey. + * In: keypair: pointer to a keypair. + */ + keypair_xonly_pub(ctx: PointerContext, pubkey: PointerXOnlyKey, pk_parity: Pointer | null, keypair: PointerKeypair): BinaryResult; + /** Parse a 32-byte sequence into a xonly_pubkey object. + * + * Returns: 1 if the public key was fully valid. + * 0 if the public key could not be parsed or is invalid. + * + * Args: ctx: a secp256k1 context object. + * Out: pubkey: pointer to a pubkey object. If 1 is returned, it is set to a + * parsed version of input. If not, it's set to an invalid value. + * In: input32: pointer to a serialized xonly_pubkey. + */ + xonly_pubkey_parse(ctx: PointerContext, pubkey: PointerXOnlyKey, input32: Pointer<32>): BinaryResult; + /** Serialize an xonly_pubkey object into a 32-byte sequence. + * + * Returns: 1 always. + * + * Args: ctx: a secp256k1 context object. + * Out: output32: a pointer to a 32-byte array to place the serialized key in. + * In: pubkey: a pointer to a secp256k1_xonly_pubkey containing an initialized public key. + */ + xonly_pubkey_serialize(ctx: PointerContext, output32: Pointer<32>, pubkey: PointerXOnlyKey): BinaryResult; + /** Create a Schnorr signature. + * + * Does _not_ strictly follow BIP-340 because it does not verify the resulting + * signature. Instead, you can manually use secp256k1_schnorrsig_verify and + * abort if it fails. + * + * This function only signs 32-byte messages. If you have messages of a + * different size (or the same size but without a context-specific tag + * prefix), it is recommended to create a 32-byte message hash with + * secp256k1_tagged_sha256 and then sign the hash. Tagged hashing allows + * providing an context-specific tag for domain separation. This prevents + * signatures from being valid in multiple contexts by accident. + * + * Returns 1 on success, 0 on failure. + * Args: ctx: pointer to a context object, initialized for signing. + * Out: sig64: pointer to a 64-byte array to store the serialized signature. + * In: msg32: the 32-byte message being signed. + * keypair: pointer to an initialized keypair. + * aux_rand32: 32 bytes of fresh randomness. While recommended to provide + * this, it is only supplemental to security and can be NULL. A + * NULL argument is treated the same as an all-zero one. See + * BIP-340 "Default Signing" for a full explanation of this + * argument and for guidance if randomness is expensive. + */ + schnorrsig_sign32(ctx: PointerContext, sig64: PointerSig, msg32: Pointer<32>, keypair: PointerKeypair, aux_rand32: Pointer<32>): BinaryResult; + /** Verify a Schnorr signature. + * + * Returns: 1: correct signature + * 0: incorrect signature + * Args: ctx: a secp256k1 context object, initialized for verification. + * In: sig64: pointer to the 64-byte signature to verify. + * msg: the message being verified. Can only be NULL if msglen is 0. + * msglen: length of the message + * pubkey: pointer to an x-only public key to verify with (cannot be NULL) + */ + schnorrsig_verify(ctx: PointerContext, sig64: PointerSig, msg32: Pointer<32>, msglen: number, pubkey: PointerXOnlyKey): BinaryResult; + sha256_initialize(hash: PointerSha256): void; + sha256_write(hash: PointerSha256, data: Pointer, size: number): void; + sha256_finalize(hash: PointerSha256, out32: Pointer<32>): void; +} diff --git a/node_modules/nostr-wasm/dist/api/wasm-env.d.ts b/node_modules/nostr-wasm/dist/api/wasm-env.d.ts new file mode 100644 index 0000000..9b3109a --- /dev/null +++ b/node_modules/nostr-wasm/dist/api/wasm-env.d.ts @@ -0,0 +1,3 @@ +/// +import type { WasmImports } from 'src/types'; +export declare function defineWasmEnv(label: string): readonly [WasmImports, (d_memory: WebAssembly.Memory) => readonly [ArrayBuffer, Uint8Array, Uint32Array]]; diff --git a/node_modules/nostr-wasm/dist/gen/wasm.d.ts b/node_modules/nostr-wasm/dist/gen/wasm.d.ts new file mode 100644 index 0000000..04eb9b8 --- /dev/null +++ b/node_modules/nostr-wasm/dist/gen/wasm.d.ts @@ -0,0 +1,27 @@ +/// +import type { Pointer, WasmImports, WasmExports } from '../types.js'; +export interface WasmImportsExtension extends WasmImports { +} +export interface WasmExportsExtension extends WasmExports { + sha256_initialize: Function; + sha256_write: Function; + sha256_finalize: Function; + context_create: Function; + xonly_pubkey_parse: Function; + xonly_pubkey_serialize: Function; + keypair_create: Function; + keypair_xonly_pub: Function; + schnorrsig_sign32: Function; + schnorrsig_verify: Function; +} +export declare const map_wasm_imports: (g_imports: WasmImportsExtension) => { + a: { + a: () => void; + f: (ip_dst: Pointer, ip_src: Pointer, nb_size: nb_size) => Uint8Array; + d: (nb_size: number) => void; + e: () => number; + c: () => number; + b: (i_fd: number, ip_iov: Pointer, nl_iovs: number, ip_written: Pointer) => 0; + }; +}; +export declare const map_wasm_exports: (g_exports: WebAssembly.Exports) => g_extension; diff --git a/node_modules/nostr-wasm/dist/generate.d.ts b/node_modules/nostr-wasm/dist/generate.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/nostr-wasm/dist/generate.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/nostr-wasm/dist/gzipped.d.ts b/node_modules/nostr-wasm/dist/gzipped.d.ts new file mode 100644 index 0000000..5c30fae --- /dev/null +++ b/node_modules/nostr-wasm/dist/gzipped.d.ts @@ -0,0 +1,3 @@ +export * from './headless.js'; +import { type Nostr } from './api/nostr.js'; +export declare const initNostrWasm: () => Promise; diff --git a/node_modules/nostr-wasm/dist/gzipped.js b/node_modules/nostr-wasm/dist/gzipped.js new file mode 100644 index 0000000..6fd8103 --- /dev/null +++ b/node_modules/nostr-wasm/dist/gzipped.js @@ -0,0 +1,44 @@ +import { N as NostrWasm } from './nostr.js'; + +const sb64_data = "H4sIAAAAAAAAA7S9C3Qc2XUYWPWqqru6q38AGkDjQ+D2I8gBhj/wT40oDV7b8/NoLFmZM0fZn0e7m422oCQCOaHmnG0SLZGi4LOKDceSw5k4EzjrtRCvx4E/WcPyrgR/w+OV15DtTeC1tIY3uw7t4w8c+eTQslZc3c+rrmo0SNo5Hh0RVa9fvXf/777fvc4Hr/4d13Ec929VX1XLy86r3rL9111+1cV/guVlfnOcV315pL/Oq+6y82qwfOPGjRuOVHOwFXf5VbV8w3k1XJb/3OVXveUby+4NdSTnftD9oBO4H3T/Swef/yvHdz/o/teO537Q/Vv073/juN7p+YKrlOsWHc91leM6bj5wHC9yPd8ruXm37CDQoeepiu/nlFKhH7gfcfP5wHfdWi0Xusuu2XorF+XfVXX/tnLcDzmj7n/rjLux86S76Druh53z7t9x8u7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mX/afBI/0jw/pb4gt/2XQAGJ7fxlUAADwCfUfBu0fBu1viMWnQSJCYADEstMgEUnQ/+r/JHiMfxiMf4IAAAAQEBAAxBbSIBFR/lP9+/vEgtMhESGwAGLx6ZCI2Lh/xX8SPNY/ANbfEOv5y+AAxMbTIRFpsP/q/yR4nH8YnH+ClY2dg5OLm4eXT0xcQlJKGiB29dcFDRB7/Xv9BBBLyYBERPg7WBgAADAWAxCrzoBEhIAEiHVnQCLC/ecvAogFZEIiQonGQ/wPyUnjh7VSAwA="; + +const initNostrWasm = async () => { + // get bytes blob from base64 + const atu8_gzipped = new Uint8Array(atob(sb64_data) + .split('') + .map(s => s.charCodeAt(0))); + // read it as a gzip file + const ds_src = new ReadableStream({ + start(d_ctrl) { + d_ctrl.enqueue(atu8_gzipped); + d_ctrl.close(); + } + }); + // and decompress it + const ds_dst = ds_src.pipeThrough(new DecompressionStream('gzip')); + const d_reader = ds_dst.getReader(); + const a_chunks = []; + for (;;) { + const { value: atu8_chunk, done: b_done } = await d_reader.read(); + if (b_done) + break; + a_chunks.push(atu8_chunk); + } + const atu8_gunzipped = concat(a_chunks); + return await NostrWasm(atu8_gunzipped); +}; +function concat(a_buffers) { + let size = 0; + for (const atu8_each of a_buffers) { + size += atu8_each.byteLength; + } + const atu8_out = new Uint8Array(size); + let index = 0; + for (const atu8_each of a_buffers) { + atu8_out.set(atu8_each, index); + index += atu8_each.byteLength; + } + return atu8_out; +} + +export { NostrWasm, initNostrWasm }; diff --git a/node_modules/nostr-wasm/dist/headless.d.ts b/node_modules/nostr-wasm/dist/headless.d.ts new file mode 100644 index 0000000..9abc9b4 --- /dev/null +++ b/node_modules/nostr-wasm/dist/headless.d.ts @@ -0,0 +1,2 @@ +export type { Nostr } from './api/nostr.js'; +export { NostrWasm } from './api/nostr.js'; diff --git a/node_modules/nostr-wasm/dist/main.d.ts b/node_modules/nostr-wasm/dist/main.d.ts new file mode 100644 index 0000000..5c30fae --- /dev/null +++ b/node_modules/nostr-wasm/dist/main.d.ts @@ -0,0 +1,3 @@ +export * from './headless.js'; +import { type Nostr } from './api/nostr.js'; +export declare const initNostrWasm: () => Promise; diff --git a/node_modules/nostr-wasm/dist/main.js b/node_modules/nostr-wasm/dist/main.js new file mode 100644 index 0000000..3007b42 --- /dev/null +++ b/node_modules/nostr-wasm/dist/main.js @@ -0,0 +1,9 @@ +import { N as NostrWasm } from './nostr.js'; + +const sb64_data = "AGFzbQEAAAABZQ9gAn9/AGADf39/AGADf39/AX9gAX8Bf2AFf39/f38Bf2AAAGAEf39/fwF/YAR/f39/AGABfwBgBX9+fn5+AGAFf39/f38AYAJ/fwF/YAJ/fgBgCH9/f39/f39/AX9gA39+fwF+AiUGAWEBYQAFAWEBYgAGAWEBYwAEAWEBZAADAWEBZQADAWEBZgABAzEwCQECAgEBCgADAQECAAEAAQcFAAADCwEDBAMMAQcBDQABAAAACAMDAg4EBAYCAgIIBAUBcAEHBwUEAQEQEAYIAX8BQcCeBgsHPQ8BZwIAAWgAFwFpABoBagAqAWsBAAFsADUBbQAHAW4ADQFvACsBcAA0AXEAMwFyADIBcwAxAXQAMAF1AC8JDAEAQQELBiQoKSwtLgrTlAswdQEBfiAAIAEgBH4gAiADfnwgA0IgiCICIAFCIIgiBH58IANC/////w+DIgMgAUL/////D4MiAX4iBUIgiCADIAR+fCIDQiCIfCABIAJ+IANC/////w+DfCIBQiCIfDcDCCAAIAVC/////w+DIAFCIIaENwMAC+k+AkZ/AX4gACAAKQNgIkkgAq18NwNgIAJBwAAgSadBP3EiCmsiNE8EQCAAQSBqIUUDQCAKIEVqIAEgNBAJGiAAIAAtAFlBEHQgAC0AWEEYdHIgAC0AWkEIdHIiBCAALQBbciIXIAAtAF1BEHQgAC0AXEEYdHIgAC0AXkEIdHIiBSAALQBfciIYQRl3IBhBDndzIBhBA3ZzaiAAKABEIgpBGHQgCkGA/gNxQQh0ciAKQQh2QYD+A3EgCkEYdnJyIh0gACgAICIKQRh0IApBgP4DcUEIdHIgCkEIdkGA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IQEgAkEgayICQR9LDQALCyAAC4AEAQN/IAJBgARPBEAgACABIAIQBSAADwsgACACaiEDAkAgACABc0EDcUUEQAJAIABBA3FFBEAgACECDAELIAJFBEAgACECDAELIAAhAgNAIAIgAS0AADoAACABQQFqIQEgAkEBaiICQQNxRQ0BIAIgA0kNAAsLAkAgA0F8cSIEQcAASQ0AIAIgBEFAaiIFSw0AA0AgAiABKAIANgIAIAIgASgCBDYCBCACIAEoAgg2AgggAiABKAIMNgIMIAIgASgCEDYCECACIAEoAhQ2AhQgAiABKAIYNgIYIAIgASgCHDYCHCACIAEoAiA2AiAgAiABKAIkNgIkIAIgASgCKDYCKCACIAEoAiw2AiwgAiABKAIwNgIwIAIgASgCNDYCNCACIAEoAjg2AjggAiABKAI8NgI8IAFBQGshASACQUBrIgIgBU0NAAsLIAIgBE8NAQNAIAIgASgCADYCACABQQRqIQEgAkEEaiICIARJDQALDAELIANBBEkEQCAAIQIMAQsgACADQQRrIgRLBEAgACECDAELIAAhAgNAIAIgAS0AADoAACACIAEtAAE6AAEgAiABLQACOgACIAIgAS0AAzoAAyABQQRqIQEgAkEEaiICIARNDQALCyACIANJBEADQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADRw0ACwsgAAvqCwIBfxl+IwBB8ANrIgMkACADQUBrIAIpAxgiBEIAIAEpAwAiBUIAEAYgA0HQAWogAikDECIGQgAgASkDCCIKQgAQBiADQcACaiACKQMIIgtCACABKQMQIgdCABAGIANBkANqIAIpAwAiDEIAIAEpAxgiDUIAEAYgA0HgA2ogAikDICIOQgAgASkDICIPQgAQBiADQdADaiADKQPgA0IAQpD6gICAAkIAEAYgA0HQAGogDkIAIAVCABAGIANBkAFqIARCACAKQgAQBiADQZACaiAGQgAgB0IAEAYgA0HwAmogC0IAIA1CABAGIANBsANqIAxCACAPQgAQBiADQcADaiADKQPoA0IAQoCAxJ6AgMAAQgAQBiADQeAAaiAMQgAgBUIAEAYgA0HgAWogDkIAIApCABAGIANBoAFqIARCACA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IBJCNIiEfCINQgBCkPqAgIACQgAQBiAAIAMpA4ACIg4gAykDgAF8IgUgAykD4AJ8IgYgAykDIHwiCiAIIBRUrSATIBRWrSADKQM4IBMgGVStIAMpA/gBIAMpA3h8fHx8IAlCNIh8fCIPQgyGIAhCNIiEfCILQv////////8HgzcDECADQRBqIAQgDVatIAQgB1StIAMpA6gDIAMpA8gBfHwgDEI0iHx8QgBCgIDEnoCAwABCABAGIAAgAykDECIHIBpC/////////weDfCIEIAogC1atIAYgClatIAMpAyggBSAGVq0gAykD6AIgBSAOVK0gAykDiAIgAykDiAF8fHx8fHwgD0I0iHx8IgZCDIYgC0I0iIR8IgVC/////////weDNwMYIAAgEUL///////8/gyAEIAVWrSADKQMYIAQgB1StfCAGQjSIfHxCDIYgBUI0iIR8NwMgIANB8ANqJAALtwIBBX8jAEEQayIFJAAgBSACNgIMIwBB0AFrIgMkACADIAI2AswBIANBoAFqIgJBAEEoEAgaIAMgAygCzAE2AsgBAkBBACABIANByAFqIANB0ABqIAIQHkEASA0AIAAoAkxBAEghByAAIAAoAgAiBkFfcTYCAAJ/AkACQCAAKAIwRQRAIABB0AA2AjAgAEEANgIcIABCADcDECAAKAIsIQQgACADNgIsDAELIAAoAhANAQtBfyAAEB8NARoLIAAgASADQcgBaiADQdAAaiADQaABahAeCyEBIAQEfyAAQQBBACAAKAIkEQIAGiAAQQA2AjAgACAENgIsIABBADYCHCAAKAIUGiAAQgA3AxBBAAUgAQsaIAAgACgCACAGQSBxcjYCACAHDQALIANB0AFqJAAgBUEQaiQAC28BAX8jAEGAAmsiBSQAAkAgAiADTA0AIARBgMAEcQ0AIAUgAUH/AXEgAiADayIDQYACIANBgAJJIgEbEAgaIAFFBEADQCAAIAVBgAIQDyADQYACayIDQf8BSw0ACwsgACAFIAMQDwsgBUGAAmokAAucBAICfwF+IwBBEGsiAyQAIAMgACkDYCIEQiWIPAAKIAMgBEIdiDwACyADIARCLYg8AAkgAyAEQjWIPAAIIAMgBKciAkEDdDoADy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ID2opAwB8fCADQjSIfHwiB0IMhiAEQjSIhCIFIAIpA5APfCIDQgBCkPqAgIACQgAQBiACQaAOaiADIAVUrSACQZgPaikDACAHQjSIfHxCAEKAgMSegIDAAEIAEAYgAkHgCWpCvOH//7///x8gAikDsAoiAyACKQOQEnwiB0L/////////B4MiI30iHEIAIB1CABAGIAJB4AhqQvz///////8fIAIpA+AKIgUgAikDgBJ8IgYgAyAHVq0gAkG4CmopAwAgAkGYEmopAwB8fCIDQgyGIAdCNIiEfCIEQv////////8HgyIifSIaQgAgEEIAEAYgAkHwB2pC/P///////x8gAikDwBEiByACKQPwEXwiCCACKQPQCnwiCSAEIAZUrSAFIAZWrSACQegKaikDACACQYgSaikDAHx8IANCNIh8fCIDQgyGIARCNIiEfCIGQv////////8HgyIgfSIVQgAgEUIAEAYgAkGQB2pC/P///////x8gAikDwAoiBSAOQv7///////8Hg3wiBCAGIAlUrSAIIAlWrSACQdgKaikDACAHIAhWrSACQcgRaikDACACQfgRaikDAHx8fHwgA0I0iHx8IgNCDIYgBkI0iIR8IgdC/////////weDIiF9IhZCACASQgAQBiACQcAGakL8////////ASAXQv///////z+DIAQgB1atIAJByApqKQMAIAQgBVStfCADQjSIfHxCDIYgB0I0iIR8Ih99IhhCACATQgAQBiACQbAGaiACKQPABkIAQpD6gICAAkIAEAYgAkHQCWogHEIAIBNCABAGIAJB0AhqIBpCACAdQgAQBiACQeAHaiAVQgAgEEIAEAYgAkGAB2ogFkIAIBFCABAGIAJBkAZqIBhCACASQgAQBiACQaAGaiACKQPIBkIAQoCAxJ6AgMAAQgAQBiACQcAJaiAcQgAgEkIAEAYgAkHACGogGkIAIBNCABAGIAJB0AdqIBVCACAdQgAQBiACQfAGaiAWQgAgEEIAEAYgAkGABmogGEIAIBFCABAGIAJB8AVqIAIpA9AHIgcgAikDwAh8IgogAikD8AZ8IhQgAikDgAZ8IhcgAikD0AgiBSACKQPQCXwiDyACKQPgB3wiDiACKQOAB3wiCyACKQOQBnwiDCACKQOg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ACACQdgQaikDAHx8IgNCDIaEfCIJQjSIIAYgCVatIAUgBlatIAJByA5qKQMAIAJByBBqKQMAfHwgA0I0iHx8IgNCDIaEfCIGQjSIIAYgDFStIAsgDFatIAJBuA5qKQMAIAcgC1atIAJBiBBqKQMAIAJBuBBqKQMAfHx8fCADQjSIfHwiA0IMhoR8IgVCNIggBSAOVK0gAkGoDmopAwAgBCAOVq18IANCNIh8fEIMhoR8QgN+QgAgCEL/////////B4NCA34iB0IBg30iA0IQiHwiBEIzhkKAgICAgICABIMgA0IMiCIIIAVC/////////weDQgN+fCIDQgGIfCIQQgAgCCAJQv////////8Hg0IDfnwiBUIzhkKAgICAgICABIMgCEKv+P//7///B4MgB3xCAYh8IhNCAYYiC0IAEAYgAkHQDWogA0IzhkKAgICAgICABIMgBkL/////////B4NCA34gCHwiA0IBiHwiEUIAIANCM4ZCgICAgICAgASDIAVCAYh8IhJCAYYiA0IAEAYgAkHgDGogBEIBiCIcQgAgHEIAEAYgAkHQDGogAikD4AxCAEKQ+oCAgAJCABAGIAJBsAxqIARCfoMiDkIAIBNCABAGIAJBkA1qIBBCACADQgAQBiACQcANaiARQgAgEUIAEAYgAkHADGogAkHoDGopAwBCAEKAgMSegIDAAEIAEAYgAkGADmogE0IAIBNCABAGIAJBoAxqIA5CACASQgAQBiACQYANaiAQQgAgEUIBhkIAEAYgAkGQDGogAikDgA0iByACKQOgDHwiDCACKQPADSIFIAIpA7AMfCIIIAIpA5ANfCIJIAIpA8AMfCIGIAIpA6ANIgMgAikD0A18IgQgAikD0Ax8IhlCNIggBCAZVq0gAkHYDGopAwAgAyAEVq0gAkGoDWopAwAgAkHYDWopAwB8fHx8IgNCDIaEfCIaQjSIIAYgGlatIAYgCVStIAJByAxqKQMAIAggCVatIAJBmA1qKQMAIAUgCFatIAJByA1qKQMAIAJBuAxqKQMAfHx8fHx8IANCNIh8fCIDQgyGhHwiBEIEhkLw/////////wCDIBpCMIhCD4OEQgBC0YeAgBBCABAGIAJB8A1qIBJCACALQgAQBiACQYAMaiARQgAgDkIAEAYgAkHwDGogEEIAIBBCABAGIAJB8AtqIAIpA/AMIgUgAikDgAx8IgYgBCAMVK0gByAMVq0gAkGIDWopAwAgAkGoDGopAwB8fCADQjSIfHwiA0IMhiAEQjSIhHwiBEL/////////B4NCAEKQ+oCAgAJCABAGIAJBsA1qIBFCACALQgAQBiACQeANaiASQgAgEkIAEAYgAkHgC2ogEEIAIA5CABAGIAJB0AtqIAQgBlStIAUgBlatIAJB+AxqKQMAIAJBiAxqKQMAfHwgA0I0iHx8IgdCDIYgBEI0iIQiBSACKQPgC3wiA0IAQpD6gICAAkIAEAYgAkHAC2ogAyAFVK0gAkHoC2opAwAgB0I0iHx8QgBCgIDEnoCAwABCABAGIAAgAikDkAwiBSACKQOADnwiBEL/////////B4MgAikD8AUiAyACKQPACXwiB0L/////////B4MiFEIBhnwiFzcDACAAIAIpA/ALIgYgAikD8A18IgogBCAFVK0gAkGYDGopAwAgAkGIDmopAwB8fCIFQgyGIARCNIiEfCIIQv////////8HgyACKQOwCCIEIAIpA7AJfCILIAIpA4AFfCIMIAMgB1atIAIpA/gFIAJByAlqKQMAfHwiA0IMhiAHQjSIhHwiCUL/////////B4MiD0IBhnwiDjcDCCAAIAIpA7ANIgcgAikD4A18IhUgAikD0At8Ig0gCCAKVK0gBiAKVq0gAkH4C2opAwAgAkH4DWopAwB8fCAFQjSIfHwiBUIMhiAIQjSIhHwiCkL/////////B4MgAikDoAgiBiACKQOgCXwiFiACKQOwB3wiGCACKQOQBHwiCCAJIAxUrSALIAxWrSACKQOIBSAEIAtWrSACQbgIaikDACACQbgJaikDAHx8fHwgA0I0iHx8IgNCDIYgCUI0iIR8IglC/////////weDIgtCAYZ8Igw3AxAgACACKQPACyIEIBlC/v///////weDfCIZIAogDVStIA0gFVStIAJB2AtqKQMAIAcgFVatIAJBuA1qKQMAIAJB6A1qKQMAfHx8fCAFQjSIfHwiB0IMhiAKQjSIhHwiDUL/////////B4MgAikDgAQiBSAeQv////////8Hg3wiCiAIIAlWrSAIIBhUrSACKQOYBCAWIBhWrSACKQO4ByAGIBZWrSACQagIaikDACACQagJaikDAHx8fHx8fCADQjSIfHwiA0IMhiAJQjSIhHwiBkL/////////B4MiCEIBhnwiCTcDGCAAIBpC////////P4MgDSAZVK0gAkHIC2opAwAgBCAZVq18IAdCNIh8fEIMhiANQjSIhHwgG0L///////8/gyAGIApUrSACKQOIBCAFIApWrXwgA0I0iHx8QgyGIAZCNIiEfCIGQgGGfCIENwMgIAJBkAlqICFCACAjQgGGIh5CABAGIAJBkAhqICBCACAiQgGGIgNCABAGIAJBoAFqIB9CACAfQgAQBiACQZABaiACKQOgAUIAQpD6gICAAkIAEAYgAkHwAGogI0IAIB9CAYYiG0IAEAYgAkGACGogIUIAIANCABAGIAJBkApqICBCACAgQgAQBiACQYABaiACKQOoAUIAQoCAxJ6AgMAAQgAQBiACQfAJaiAjQgAgI0IAEAYgAkHgAGogIkIAIBtCABAGIAJBoAdqICFCACAgQgGGQgAQBiACQdAAaiACKQNgIgcgAikDoAd8IhUgAikDgAgiBSACKQOQCnwiFiACKQNwfCIYIAIpA4ABfCINIAIpA5AJIgMgAikDkAh8IgogAikDkAF8IhlCNIggCiAZVq0gAikDmAEgAyAKVq0gAkGYCWopAwAgAkGYCGopAwB8fHx8IgNCDIaEfCIaQjSIIA0gGlatIA0gGFStIAIpA4gBIBYgGFatIAIpA3ggBSAWVq0gAkGICGopAwAgAkGYCmopAwB8fHx8fHwgA0I0iHx8IgNCDIaEfCIKQgSGQvD/////////AIMgGkIwiEIPg4RCAELRh4CAEEIAEAYgAkGACWogIkIAIB5CABAGIAJBQGsgIEIAIBtCABAGIAJBoApqICFCACAhQgAQBiACQTBqIAIpA0AiBSACKQOgCnwiDSAKIBVUrSAHIBVWrSACKQNoIAIpA6gHfHwgA0I0iHx8IgNCDIYgCkI0iIR8IgpC/////////weDQgBCkPqAgIACQgAQBiACQfAIaiAgQgAgHkIAEAYgAkGACmogIkIAICJC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ogHkIAIBxCABAGIAJB8AJqIBVCACAQQgAQBiACQfABaiAWQgAgEUIAEAYgAkHgAWogAikD8AIiBSACKQPAA3wiCCACKQPwAXwiCSAEIBdUrSAUIBdWrSACKQOYAiANIBRWrSACKQOIAyAHIA1WrSACKQPYAyACKQPYBHx8fHx8fCADQjSIfHwiA0IMhiAEQjSIhHwiBkL/////////B4NCAEKQ+oCAgAJCABAGIAJBoAVqIB9CACARQgAQBiACQbAEaiAbQgAgEkIAEAYgAkGwA2ogHkIAIBNCABAGIAJB4AJqIBVCACAcQgAQBiACQdABaiAWQgAgEEIAEAYgAkHAAWogAikD0AEiByACKQPgAnwiBCAGIAlUrSAIIAlWrSACKQP4ASAFIAhWrSACKQP4AiACKQPIA3x8fHwgA0I0iHx8IgVCDIYgBkI0iIR8IgNCAEKQ+oCAgAJCABAGIAJBsAFqIAMgBFStIAQgB1StIAIpA9gBIAIpA+gCfHwgBUI0iHx8QgBCgIDEnoCAwABCABAGIABCmtL//5///y8gAikDgAIiBSACKQPABXwiBEL/////////B4MgAikDUCIDIAIpA/AJfCIHQv////////8Hg3x9NwMoIABC+v///////y8gAikDwAQiBiACKQOwBXwiDyACKQPgAXwiDiAEIAVUrSACKQOIAiACKQPIBXx8IgVCDIYgBEI0iIR8IglC/////////weDIAIpAzAiBCACKQOACXwiCyADIAdWrSACKQNYIAJB+AlqKQMAfHwiA0IMhiAHQjSIhHwiDEL/////////B4N8fTcDMCAAQvr///////8vIAIpA7AEIgcgAikDoAV8IhQgAikDsAN8IhcgAikDwAF8IgggCSAOVK0gDiAPVK0gAikD6AEgBiAPVq0gAikDyAQgAikDuAV8fHx8IAVCNIh8fCIFQgyGIAlCNIiEfCIJQv////////8HgyACKQPwCCIGIAIpA4AKfCIPIAIpAxB8Ig4gCyAMVq0gBCALVq0gAikDOCACQYgJaikDAHx8IANCNIh8fCIDQgyGIAxCNIiEfCILQv////////8Hg3x9NwM4IABBQGtC+v///////y8gAikDsAEiBCAKQv////////8Hg3wiDCAIIAlWrSAIIBdUrSACKQPIASAUIBdWrSACKQO4AyAHIBRWrSACKQO4BCACKQOoBXx8fHx8fCAFQjSIfHwiB0IMhiAJQjSIhHwiCEL/////////B4MgAikDACIFIBlC/v///////weDfCIJIAsgDlStIA4gD1StIAIpAxggBiAPVq0gAkH4CGopAwAgAkGICmopAwB8fHx8IANCNIh8fCIDQgyGIAtCNIiEfCIGQv////////8Hg3x9NwMAIABC+v///////wIgGkL///////8/gyAGIAlUrSACKQMIIAUgCVatfCADQjSIfHxCDIYgBkI0iIR8IBhC////////P4MgCCAMVK0gAikDuAEgBCAMVq18IAdCNIh8fEIMhiAIQjSIhHx8fTcDSCACQaASaiQAC+wIAgF/CX4jAEGgAmsiAyQAIANB4AFqIAEgAhAVIANB0AFqIAMpA4ACIgVCAEK//ab+sq7olsAAQgAQBiADQbABaiADKQOIAiIJQgBCv/2m/rKu6JbAAEIAEAYgA0HAAWogBUIAQsS/3YWV48ioxQBCABAGIANBkAFqIAMpA5ACIgdCAEK//ab+sq7olsAAQgAQBiADQaABaiAJQgBCxL/dhZXjyKjFAEIAEAYgA0HwAGogAykDmAIiBEIAQr/9pv6yruiWwABCABAGIANBgAFqIAdCAELEv92FlePIqMUAQgAQBiADQeAAaiAEQgBCxL/dhZXjyKjFAEIAEAYgA0HQAGogByADKQPgASIGIAMpA9ABfCIKIAZUrSADKQPoASIIIAMpA9gBfHwiBiAIVK0gAykD8AEiCyADKQO4ASADKQPIAXx8fCAGIAYgAykDsAF8IgZWrXwgBiAGIAMpA8ABfCIGVq18IgggC1StIAMpA/gBIgsgAykDmAEgAykDqAF8fHwgCCAIIAMpA5ABfCIIVq18IAggCCADKQOgAXwiCFatfCAIIAUgCHwiCFatfCIFIAtUrSADKQN4IAMpA2AiDCADKQOIAXx8fCAFIAUgAykDcHwiBVatfCAFIAUgAykDgAF8IgVWrXwgBSAJfCILIAVUrXwiCXwiBUIAQr/9pv6yruiWwABCABAGIANBMGogBSAJVK0gCSAMVK0gBCADKQNofHx8IglCAEK//ab+sq7olsAAQgAQBiADQUBrIAVCAELEv92FlePIqMUAQgAQBiADQSBqIAlCAELEv92FlePIqMUAQgAQBiADQRBqIAogCiADKQNQfCIKVq0gBiADKQNYfHwiByAGVK0gAykDOCAIIAMpA0h8fHwgByAHIAMpAzB8IgdWrXwgByADKQNAfCIGIAdUrXwiByAIVK0gCyADKQMofHwgB0K//ab+sq7olsAAQgAgBCAJViIBG3wiBCAHVK18IAQgBCADKQMgfCIEVq18IAQgBXwiCCAEVK18IgQgC1StIAGtfCAEIARCxL/dhZXjyKjFAEIAIAEbfCIEVq18IAQgCXwiCyAEVK18IglCAEK//ab+sq7olsAAQgAQBiADIAlCAELEv92FlePIqMUAQgAQBiAAIAYgAykDACIGfCIFIAMpAxggAykDECIEIAp8IgcgBFStfHwiBEK6wKL66py317p/ViAIIAl8IgogBCAFVK0gAykDCCAFIAZUrXx8fCIFQn1WIAkgClatIAUgClStfCIKIAt8IglCf1FxIgFxIgIgBEK7wKL66py317p/VnEgBUJ/USABcXIgAiAHQsCC2YHN0Zfpv39WcXIgCSAKVGqtIgpCv/2m/rKu6JbAAH4iBiAHfCIINwMAIAAgBCAKQsS/3YWV48ioxQB+fCIHIAYgCFatfCIGNwMIIAAgBSAKfCIKIAQgB1atIAYgB1StfHwiBDcDECAAIAUgClatIAQgClStfCAJfDcDGCADQaACaiQAC+0EAQp+IAFBQGspAwAhByABKQM4IQggASkDMCEFIAEpA0ghAiABKQMoIQQgACABKQMYIAEpAxAgASkDCCABKQMAIAEpAyAiCUIwiELRh4CAEH58IgZCNIh8IgNCNIh8IgpCNIh8IgtCNIggCUL///////8/g3wiCUIwiCAKQv////////8HgyIKIAODIAuDQv////////8HUSAJQv///////z9RcSAGQv////////8HgyIGQq74///v//8HVnGthELRh4CAEH4gBnwiBkI0iCADQv////////8Hg3wiA0I0hiAGQv////////8Hg4Q3AAAgACACQv///////z+DIAcgCCAFIAQgAkIwiELRh4CAEH58IgRCNIh8IgJCNIh8IgVCNIh8IgdCNIh8IghCMIggBUL/////////B4MiBSACgyAHg0L/////////B1EgCEL///////8/UXEgBEL/////////B4MiBEKu+P//7///B1ZxrYRC0YeAgBB+IAR8IgRCNIggAkL/////////B4N8IgJCNIYgBEL/////////B4OENwAgIAAgA0IMiEL//////x+DIANCNIggCnwiA0IohoQ3AAggACACQgyIQv//////H4MgAkI0iCAFfCICQiiGhDcAKCAAIANCGIhC/////wCDIAtC/////////weDIANCNIh8IgNCHIaENwAQIAAgAkIYiEL/////AIMgB0L/////////B4MgAkI0iHwiAkIchoQ3ADAgACADQiSIQv//A4MgA0I0iCAJfEIQhoQ3ABggACACQiSIQv//A4MgAkI0iCAIfEIQhoQ3ADgL6gYCAX8JfiMAQYACayIDJAAgA0HwAWogAikDAEIAIAEpAwBCABAGIAAgAykD8AE3AwAgA0HQAWogAikDCEIAIAEpAwBCABAGIANB4AFqIAIpAwBCACABKQMIQgAQBiAAIAMpA9ABIgUgAykD+AF8IgQgAykD4AF8IgY3AwggA0GgAWogAikDEEIAIAEpAwBCABAGIANBsAFqIAIpAwhCACABKQMIQgAQBiADQcABaiACKQMAQgAgASkDEEIAEAYgACADKQPYASAEIAVUrXwiByADKQPoASAEIAZWrXx8IgQgAykDoAF8IgUgAykDsAF8IgYgAykDwAF8Igg3AxAgA0HgAGogAikDGEIAIAEpAwBCABAGIANB8ABqIAIpAxBCACABKQMIQgAQBiADQYABaiACKQMIQgAgASkDEEIAEAYgA0GQAWogAikDAEIAIAEpAxhCABAGIAAgAykDqAEgBCAFVq18IgogBCAHVK18IgQgAykDuAEgBSAGVq18fCIFIAMpA8gBIAYgCFatfHwiBiADKQNgfCIHIAMpA3B8IgggAykDgAF8IgkgAykDkAF8Igs3AxggA0EwaiACKQMYQgAgASkDCEIAEAYgA0FAayACKQMQQgAgASkDEEIAEAYgA0HQAGogAikDCEIAIAEpAxhCABAGIAAgAykDmAEgCSALVq18IgsgBSAGVq0gBCAFVq0gBCAKVK18fCIKIAMpA2ggBiA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////weDIglCACACKQMIIgZCABAGIARBgCNqIA9C/////////weDIhBCACACKQMQIg9CABAGIARBsCJqIBFC/////////weDIhFCACACKQMYIgpCABAGIARB4CFqIBJC////////P4MgDiAWVq0gBEHYJGopAwAgDiATVK18ICBCNIh8fEIMhiAWQjSIhHwiEkIAIAIpAyAiDkIAEAYgBEHQIWogBCkD4CFCAEKQ+oCAgAJCABAGIARBoBlqIBJCACAHQgAQBiAEQeAjaiAIQgAgBkIAEAYgBEGQI2ogCUIAIA9CABAGIARBwCJqIBBCACAKQgAQBiAEQfAhaiARQgAgDkIAEAYgBEHAIWogBEHoIWopAwBCAEKAgMSegIDAAEIAEAYgBEGwGWogEUIAIAdCABAGIARB8CNqIBJCACAGQgAQBiAEQaAjaiAIQgAgD0IAEAYgBEHQImogCUIAIApCABAGIARBgCJqIBBCACAOQgAQBiAEQdAYaiAEKQPQIiIYIAQpA4AifCITIAQpA6AjfCIgIAQpA/AjfCIcIAQpA8AiIhogBCkD8CF8IiMgBCkDkCN8IhsgBCkD4CN8IiIgBCkDoBl8Ih4gBCkDwCF8IiYgBCkDgCMiFyAEKQOwInwiFiAEKQPQI3wiJyAEKQOQGXwiFCAEKQPQIXwiFUI0iCAUIBVWrSAEQdghaikDACAUICdUrSAEQZgZaikDACAWICdWrSAEQdgjaikDACAWIBdUrSAEQYgjaikDACAEQbgiaikDAHx8fHx8fHx8IidCDIaEfCIWQjSIIBYgJlStIB4gJlatIARByCFqKQMAIB4gIlStIARBqBlqKQMAIBsgIlatIARB6CNqKQMAIBsgI1StIARBmCNqKQMAIBogI1atIARByCJqKQMAIARB+CFqKQMAfHx8fHx8fHx8fCAnQjSIfHwiHkIMhoR8IiNCBIZC8P////////8AgyAWQjCIQg+DhEIAQtGHgIAQQgAQBiAEQcAZaiAQQgAgB0IAEAYgBEGAJGogEUIAIAZCABAGIARBsCNqIBJCACAPQgAQBiAEQeAiaiAIQgAgCkIAEAYgBEGQImogCUIAIA5CABAGIARBgBlqIAQpA+AiIi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IARB2BlqKQMAIAYgC1atIARBmCRqKQMAIARByCNqKQMAfHx8fHx8IAlCNIh8fCINQgyGhHwiC0I0iCALIAxUrSAEQegYaikDACAMIBlUrXwgDUI0iHx8QgyGhHxC9v///////wR8IghCMIhC0YeAgBB+IBFC/////////weDIAEpAwAiE31C1rP//9/+/88AfCIJfCIGQv////////8HgyIUQtCHgIAQhSEPIAEpA0giICAHQv///////z+DIAQpA/AZIhwgHkL/////////B4N8IgwgBCkD4BsiIyAEKQOQG3wiDSAEKQOwHHwiECAEKQOAGnwiESAEKQPwGyIbIAQpA6AbfCIZIAQpA6AafCIHIAQpA+AZIg4gBCkDsBt8IgpCNIggCiAOVK0gBEHoGWopAwAgBEG4G2opAwB8fCIiQgyGhHwiDkI0iCAHIA5WrSAHIBlUrSAEQagaaikDACAZIBtUrSAEQfgbaikDACAEQagbaikDAHx8fHwgIkI0iHx8IhlCDIaEfCIHQjSIIAcgEVStIBAgEVatIARBiBpqKQMAIA0gEFatIARBuBxqKQMAIA0gI1StIARB6BtqKQMAIARBmBtqKQMAfHx8fHx8IBlCNIh8fCIQQgyGhHwiDUI0iCAMIA1WrSAEQfgZaikDACAMIBxUrXwgEEI0iHx8QgyGhHx9Qvz///////8BfCEZIAtC/////////weDIAEpAxgiHH1C9v///////88AfCEMIAFBQGspAwAiIyANQv////////8Hg31C/P///////x98IRAgHUL/////////B4MgASkDECIbfUL2////////zwB8IQsgASkDOCIiIAdC/////////weDfUL8////////H3whESASQv////////8HgyABKQMIIh59Qvb////////PAHwhDSABKQMwIiYgDkL/////////B4N9Qvz///////8ffCESIAEpAygiJyAKQv////////8Hg31CvOH//7///x98IR0CQCAUQgBSIA9C/////////wdScQ0AIAZCNIggDXwiByAGhCAHQjSIIAt8IgaEIAZCNIggDHwiCoRC/////////weDIAhC////////P4MgCkI0iHwiDoRCAFIEQCAPIA5CgICAgICAwAeFgyAHgyAGgyAKg0L/////////B1INAQsgGUIwiELRh4CAEH4gHXwiDEL/////////B4MiDULQh4CAEIUhCwJAIA1CAFIgC0L/////////B1JxDQAgDCAMQjSIIBJ8IgyEIAxCNIggEXwiDYQgDUI0iCAQfCIIhEL/////////B4MgGUL///////8/gyAIQjSIfCIJhEIAUgRAIAsgCUKAgICAgIDAB4WDIAyDIA2DIAiDQv////////8HUg0BCyADBEAgAyABKQMoIgs3AwAgAyABKQMwIg03AwggAyABKQM4Igg3AxAgAyABKQNAIgk3AxggAyABKQNIIgw3AyAgAyALIAxCMIhC0YeAgBB+fCILQv////////8HgzcDACADIA0gC0I0iHwiC0L/////////B4M3AwggAyAIIAtCNIh8IgtC/////////weDNwMQIAMgCSALQjSIfCILQv////////8HgzcDGCADIAxC////////P4MgC0I0iHw3AyALIAAgARASDAILIAMEQCADQgA3AwAgA0IANwMgIANCADcDGCADQgA3AxAgA0IANwMICyAAQQE2AnggAEEAQfgAEAgaDAELIABBADYCeCADBEAgAyAINwMgIAMgDDcDGCADIAs3AxAgAyANNwMIIAMgCTcDAAsgBEHAGGogASkDUCIHQgAgDEIAEAYgBEHgF2ogASkDWCIGQgAgC0IAEAYgBEHwFmogASkDYCIPQgAgDUIAEAYgBEHwFWogASkDaCIKQgAgCUIAEAYgBEHgFGogASkDcCIOQgAgCEIAEAYgBEHQFGogBCkD4BRCAEKQ+oCAgAJCABAGIARBsBRqIAdCACAIQgAQBiAEQbAYaiAGQgAgDEIAEAYgBEHQF2ogD0IAIAtCABAGIARB4BZqIApCACANQgAQBiAEQeAVaiAOQgAgCUIAEAYgBEHAFGogBEHoFGopAwBCAEKAgMSegIDAAEIAEAYgBEHQFWogB0IAIAlCABAGIARBoBRqIAZCACAIQgAQBiAEQaAYaiAPQgAgDEIAEAYgBEHAF2ogCkIAIAtCABAGIARB0BZqIA5CACANQgAQBiAEQZAUaiAEKQOgGCIqIAQpA6AUfCIVIAQpA8AXfCIYIAQpA9AWfCIaIAQpA7AYIisgBCkDsBR8IhcgBCkD0Bd8Ih8gBCkD4BZ8IiEgBCkD4BV8IiggBCkDwBR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AEQfAXaiAMQgAgDEIAEAYgBEHwEWogBCkDgBIiFyAEKQPwF3wiFCAKIA9UrSAPIBpUrSAEQfgSaikDACAEQYgXaikDAHx8IBVCNIh8fCIVQgyGIApCNIiEfCIPQv////////8Hg0IAQpD6gICAAkIAEAYgBEHwFGogC0IAIAZCABAGIARBoBZqIA1CACANQgAQBiAEQZARaiAHQgAgDEIAEAYgBEGAEWogDyAUVK0gFCAXVK0gBEGIEmopAwAgBEH4F2opAwB8fCAVQjSIfHwiB0IMhiAPQjSIhCIGIAQpA5ARfCIPQgBCkPqAgIACQgAQBiAEQfAQaiAGIA9WrSAEQZgRaikDACAHQjSIfHxCAEKAgMSegIDAAEIAEAYgBEHQEmpCvOH//7///x8gBCkD4BIiCiAEKQOgFXwiBkL/////////B4N9IgdCACAMQgAQBiAEQeARakL8////////HyAEKQPwESIaIAQpA4AVfCIPIAYgClStIARB6BJqKQMAIARBqBVqKQMAfHwiF0IMhiAGQjSIhHwiCkL/////////B4N9IgZCACALQgAQBiAEQeAQakL8////////HyAEKQPwFCIfIAQpA6AWfCIUIAQpA4ARfCIVIAogD1StIA8gGlStIARB+BFqKQMAIARBiBVqKQMAfHwgF0I0iHx8IhpCDIYgCkI0iIR8IgpC/////////weDfSIPQgAgDUIAEAYgBEGQEGpC/P///////x8gBCkD8BAiFyAYQv7///////8Hg3wiGCAKIBVUrSAUIBVWrSAEQYgRaikDACAUIB9UrSAEQfgUaikDACAEQagWaikDAHx8fHwgGkI0iHx8IhVCDIYgCkI0iIR8IhRC/////////weDfSIKQgAgCUIAEAYgBEHAD2pC/P///////wEgDkL///////8/gyAUIBhUrSAEQfgQaikDACAXIBhWrXwgFUI0iHx8QgyGIBRCNIiEfH0iDkIAIAhCABAGIARBsA9qIAQpA8APQgBCkPqAgIACQgAQBiAEQcASaiAHQgAgCEIAEAYgBEHQEWogBkIAIAxCABAGIARB0BBqIA9CACALQgAQBiAEQYAQaiAKQgAgDUIAEAYgBEGQD2ogDkIAIAlCABAGI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fCIJQv////////8HgyINIAQpA6AJIjAgBCkD0Al8IgYgBCkD0AZ8IgogDiAWVq0gDiAkVK0gBCkDyAcgBEHoCWopAwB8fCAlQjSIfHwiJEIMhiAWQjSIhHwiDkL/////////B4N8IAQpA4ANIiUgBCkDsAx8IhYgBCkD0A18IhogBCkDwAp8IhcgCCAcVK0gEyAcVq0gBEHoCmopAwAgEyApVK0gBEHoDWopAwAgBEGYDWopAwB8fHx8ICpCNIh8fCIpQgyGIAhCNIiEfCITQv////////8HgyIqQgGGfCIxNwMQIAAgBCkDoA4iMiAtQv////////8Hg3wiHCAJIBhUrSAYIB5UrSAEQbgOaikDACAbIB5WrSAEQagQaikDACAbIC5UrSAEQagRaikDACAEQZgSaikDAHx8fHx8fCAvQjSIfHwiG0IMhiAJQjSIhHwiCUL/////////B4MiCCAEKQPABiIeIA9C/v///////weDfCIPIAogDlatIAYgClatIAQpA9gGIAYgMFStIARBqAlqKQMAIARB2AlqKQMAfHx8fCAkQjSIfHwiGEIMhiAOQjSIhHwiBkL/////////B4N8IAQpA7AKIiQgKEL/////////B4N8IgogEyAXVK0gFyAaVK0gBEHICmopAwAgFiAaVq0gBEHYDWopAwAgFiAlVK0gBEGIDWopAwAgBEG4DGopAwB8fHx8fHwgKUI0iHx8IhZCDIYgE0I0iIR8Ig5C/////////weDIhNCAYZ8Iho3AxggACAUQv///////z+DIAkgHFStIARBqA5qKQMAIBwgMlStfCAbQjSIfHxCDIYgCUI0iIR8IgkgB0L///////8/gyAGIA9UrSAEKQPIBiAPIB5UrXwgGEI0iHx8QgyGIAZCNIiEfHwgFUL///////8/gyAKIA5WrSAEQbgKaikDACAKICRUrXwgFkI0iHx8QgyGIA5CNIiEfCIOQgGGfCIWNwMgIARBoAhqIB8gIXwiB0IAIBBCABAGIARBsAdqICsgLHwiBkIAIBFCABAGIARBsAZqICogMXwiD0IAIBJCABAGIARB4AVqIBMgGnwiCkIAIB1CABAGIARBkAVqIA4gFnwiDkIAIBlCABAGIARBgAVqI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ig9CDIYgC0I0iIR8IgtC/////////weDfDcDOCAAQUBrIAQpA/ADIgogIUL/////////B4N8IgkgDCAdVK0gGSAdVq0gBCkDiAQgEiAZVq0gBCkD+AUgDiASVq0gBCkD+AYgBCkD6Ad8fHx8fHwgBkI0iHx8IhJCDIYgDEI0iIR8IgxC/////////weDIAQpAwAiGSAcQv////////8Hg3wiESAHIAtWrSAHIAhUrSAEKQMYIAggDVStIAQpA7gBIA0gE1StIAQpA4gCIAQpA9gCfHx8fHx8IA9CNIh8fCINQgyGIAtCNIiEfCILQv////////8Hg3w3AwAgACAQQv///////z+DIAsgEVStIAQpAwggESAZVK18IA1CNIh8fEIMhiALQjSIhHwgFkL///////8/gyAJIAxWrSAEKQP4AyAJIApUrXwgEkI0iHx8QgyGIAxCNIiEfHw3A0gLIARB8CZqJAALFgBBqJoCQaiZAjYCAEHgmQJBKjYCAAuiAwAgACABKQMgQiiIPAAAIAAgATUCJDwAASAAIAEpAyBCGIg8AAIgACABKQMgQhCIPAADIAAgASkDIEIIiDwABCAAIAEpAyA8AAUgACABKQMYQiyIPAAGIAAgASkDGEIkiDwAByAAIAEpAxhCHIg8AAggACABKQMYQhSIPAAJIAAgASkDGEIMiDwACiAAIAEpAxhCBIg8AAsgACABMwEWQg+DIAEpAxhCBIaEPAAMIAAgASkDEEIoiDwADSAAIAE1AhQ8AA4gACABKQMQQhiIPAAPIAAgASkDEEIQiDwAECAAIAEpAxBCCIg8ABEgACABKQMQPAASIAAgASkDCEIsiDwAEyAAIAEpAwhCJIg8ABQgACABKQMIQhyIPAAVIAAgASkDCEIUiDwAFiAAIAEpAwhCDIg8ABcgACABKQMIQgSIPAAYIAAgATMBBkIPgyABKQMIQgSGhDwAGSAAIAEpAwBCKIg8ABogACABNQIEPAAbIAAgASkDAEIYiDwAHCAAIAEpAwBCEIg8AB0gACABKQMAQgiIPAAeIAAgASkDADwAHwvHAgAgACABMQAfIAExAB5CCIaEIAExAB1CEIaEIAExABxCGIaEIAExABtCIIaEI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wAhCkHokQIpAwAhC0HwkQIpAwAhDEH4kQIpAwAhDSACIAFCP4c3AwAgAiACKQMAIgEgCCADIA2DfIUgAX0gASAEIAMgDIN8hSABfSABIAUgAyALg3yFIAF9IAEgBiADIAqDfIUgAX0gASAHIAMgCYN8hSABfSIBQj6HfCIDQj6HfCIEQj6HfCIFQj6HfCIGQj+HNwMIIAIpAwghByACKQMIIQggAikDCCEOIAIpAwghDyAAIAIpAwggCYMgAUL//////////z+DfCIBQv//////////P4M3AwAgACAHIAqDIANC//////////8/g3wgAUI+h3wiAUL//////////z+DNwMIIAAgCCALgyAEQv//////////P4N8IAFCPod8IgFC//////////8/gzcDECAAIAwgDoMgBUL//////////z+DfCABQj6HfCIBQv//////////P4M3AxggACANIA+DIAZ8IAFCPod8NwMgC8MOAgF/F34jAEHgA2siAyQAIANB4AJqIAIpAwAiCyALQj+HIhMgACkDACIEIARCP4ciBxAGIANBgANqIAIpAwgiDCAMQj+HIhQgASkDACIIIAhCP4ciBRAGIANB8AJqIAIpAxAiDyAPQj+HIhggBCAHEAYgA0GQA2ogAikDGCIQIBBCP4ciGSAIIAUQBiADQcACaiAMIAEpAyAiFUI/hyIHgyALIAApAyAiFkI/hyIFg3wiBCAEQYCSAikDACINIAMpA4ADIgkgAykD4AJ8Igh+fEL//////////z+DfSIOIA5CP4ciF0HYkQIpAwAiBCAEQj+HIgYQBiADQdACaiAHIBCDIAUgD4N8IgUgBSANIAMpA5ADIhEgAykD8AJ8Igd+fEL//////////z+DfSINIA1CP4ciGiAEIAYQBiADQaADaiALIBMgACkDCCIEIARCP4ciBhAGIANBwANqIAwgFCABKQMIIgUgBUI/hyIKEAYgA0GwA2ogDyAYIAQgBhAGIANB0ANqIBAgGSAFIAoQBiADKQPQAyIEIAMpA7ADfCIFIARUrSADKQPYAyADKQO4A3x8IAMpA9ACIgQgB3wiBiAEVK0gAykD2AIgByARVK0gAykDmAMgAykD+AJ8fHx8IgRCPod8IAUgBSAEQgKGIAZCPoiEfCIEVq18IQcgAykDwAMiBiADKQOgA3wiBSAGVK0gAykDyAMgAykDqAN8fCADKQPAAiIGIAh8IhEgBlStIAMpA8gCIAggCVStIAMpA4gDIAMpA+gCfHx8fCIIQj6HfCAFIAhCAoYgEUI+iIR8IgggBVStfCEFIAEpAxghCSABKQMQIQYgACkDGCERIAApAxAhCkHgkQIpAwAiEkIAUgRAIANBsAJqIA4gFyASIBJCP4ciFxAGIANBoAJqIA0gGiASIBcQBiAIIAggAykDsAJ8IghWrSAFIAMpA7gCfHwhBSAEIAQgAykDoAJ8IgRWrSAHIAMpA6gCfHwhBwsgACAIQv//////////P4M3AwAgASAEQv//////////P4M3AwAgA0GQAmogCyATIAogCkI/hyISEAYgA0HwAWogDCAUIAYgBkI/hyITEAYgA0GAAmogDyAYIAogEhAGIANB4AFqIBAgGSAGIBMQBiADKQPgASIKIAMpA4ACfCIGIApUrSADKQPoASADKQOIAnx8IAdCPod8IAYgB0IChiAEQj6IhHwiByAGVK18IQQgAykD8AEiCiADKQOQAnwiBiAKVK0gAykD+AEgAykDmAJ8fCAFQj6HfCAGIAVCAoYgCEI+iIR8IgUgBlStfCEIQeiRAikDACIGQgBSBEAgA0HQAWogBiAGQj+HIgogDiAOQj+HEAYgA0HAAWogBiAKIA0gDUI/hxAGIAMpA8ABIgYgB3wiByAGVK0gAykDyAEgBHx8IQQgAykD0AEiBiAFfCIFIAZUrSADKQPYASAIfHwhCAsgACAFQv//////////P4M3AwggASAHQv//////////P4M3AwggA0GwAWogCyALQj+HIgYgESARQj+HIgoQBiADQZABaiAMIAxCP4ciEiAJIAlCP4ciExAGIANBoAFqIA8gD0I/hyIUIBEgChAGIANBgAFqIBAgEEI/hyIRIAkgExAGIAMpA4ABIgogAykDoAF8IgkgClStIAMpA4gBIAMpA6gBfHwgBEI+h3wgCSAEQgKGIAdCPoiEfCIHIAlUrXwhBCADKQOQASIKIAMpA7ABfCIJIApUrSADKQOYASADKQO4AXx8IAhCPod8IAkgCEIChiAFQj6IhHwiBSAJVK18IQhB8JECKQMAIglCAFIEQCADQfAAaiAJIAlCP4ciCiAOIA5CP4cQBiADQeAAaiAJIAogDSANQj+HEAYgAykDYCIJIAd8IgcgCVStIAMpA2ggBHx8IQQgAykDcCIJIAV8IgUgCVStIAMpA3ggCHx8IQgLIAAgBUL//////////z+DNwMQIAEgB0L//////////z+DNwMQIANB0ABqIAsgBiAWIBZCP4ciCxAGIANBMGogDCASIBUgFUI/hyIMEAYgA0FAayAPIBQgFiALEAYgA0EgaiAQIBEgFSAMEAYgA0H4kQIpAwAiCyALQj+HIgwgDiAOQj+HEAYgA0EQaiALIAwgDSANQj+HEAYgACADKQMwIg8gAykDUHwiDiAIQgKGIAVCPoiEfCIFIAMpAwB8Ig1C//////////8/gzcDGCABIAMpAyAiECADKQNAfCILIARCAoYgB0I+iIR8IgcgAykDEHwiDEL//////////z+DNwMYIAAgBSANVq0gAykDCCAFIA5UrSAOIA9UrSADKQM4IAMpA1h8fCAIQj6HfHx8fEIChiANQj6IhDcDICABIAcgDFatIAMpAxggByALVK0gCyAQVK0gAykDKCADKQNIfHwgBEI+h3x8fHxCAoYgDEI+iIQ3AyAgA0HgA2okAAuhugECAn8tfiMAQYA5ayIEJAAgAigCUCEFAkAgASgCeARAIAAgBTYCeCAEQeA3aiADKQMYIglCACADKQMAIhVCAYYiB0IAEAYgBEHAOGogAykDECIKQgAgAykDCCIGQgGGIgtCABAGIARB0DdqIAMpAyAiF0IAIBdCABAGIARBwDdqIAQpA9A3QgBCkPqAgIACQgAQBiAEQaA3aiAXQgGGIghCACAVQgAQBiAEQfA3aiAJQgAgC0IAEAYgBEGwOGogCkIAIApCABAGIARBsDdqIARB2DdqKQMAQgBCgIDEnoCAwABCABAGIARB8DhqIBVCACAVQgAQBiAEQZA3aiAIQgAgBkIAEAYgBEGAOGogCUIAIApCAYZCABAGIARBgDdqIAQpA5A3IhEgBCkDgDh8IgsgBCkD8DciECAEKQOwOHwiDCAEKQOgN3wiEyAEKQOwN3wiDSAEK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gdC/////////weDNwMQIARB4C5qIAkgFFatIAkgC1StIARBmDFqKQMAIARByDBqKQMAfHwgDEI0iHx8QgBCgIDEnoCAwABCABAGIAAgBCkD4C4iCyAkQv////////8Hg3wiCSAHIAhUrSAGIAhWrSAEQfguaikDACAGIApUrSAEQdgvaikDACAKIBVUrSAEQbgyaikDACAEQegxaikDAHx8fHx8fCAXQjSIfHwiBkIMhiAHQjSIhHwiCkL/////////B4M3AxggACANQv///////z+DIAkgClatIARB6C5qKQMAIAkgC1StfCAGQjSIfHxCDIYgCkI0iIR8NwMgIARBgC5qIAQpA9AyIg0gIkL/////////B4N8IhUgBCkDwDUiFCAEKQOwNnwiCSAEKQPQNHwiCiAEKQPgMnwiBiAEKQPQNSIXIAQpA8A2fCIIIAQpA4AzfCIHIAQpA8AyIgsgBCkD0DZ8IgxCNIggCyAMVq0gBEHIMmopAwAgBEHYNmopAwB8fCISQgyGhHwiC0I0iCAHIAtWrSAHIAhUrSAEQYgzaikDACAIIBdUrSAEQdg1aikDACAEQcg2aikDAHx8fHwgEkI0iHx8IgdCDIaEfCIIQjSIIAYgCFatIAYgClStIARB6DJqKQMAIAkgClatIARB2DRqKQMAIAkgFFStIARByDVqKQMAIARBuDZqKQMAfHx8fHx8IAdCNIh8fCISQgyGhHwiF0L/////////B4MiCUIAIAIpAygiCkIAEAYgBEGwLWogCEL/////////B4MiBkIAIAIpAzAiCEIAEAYgBEHgLGogC0L/////////B4MiB0IAIAIpAzgiC0IAEAYgBEGQLGogDEL/////////B4MiDEIAIAJBQGspAwAiFEIAEAYgBEHAK2ogE0L///////8/gyAVIBdWrSAEQdgyaikDACANIBVWrXwgEkI0iHx8QgyGIBdCNIiEfCIVQgAgAikDSCIXQgAQBiAEQbAraiAEKQPAK0IAQpD6gICAAkIAEAYgBEGQLmogFUIAIApCABAGIARBwC1qIAlCACAIQgAQBiAEQfAsaiAGQgAgC0IAEAYgBEGgLGogB0IAIBRCABAGIARB0CtqIAxCACAXQgAQBiAEQaArai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QdgoaikDACAOIBZUrSAEQfgpaikDACAEQcgqaikDAHx8fHwgFEI0iHx8IgZCDIYgDEI0iIR8IghCAEKQ+oCAgAJCABAGIARBgCdqIAggCVStIAkgClStIARB6ChqKQMAIARB2CpqKQMAfHwgBkI0iHx8QgBCgIDEnoCAwABCABAGIARBoCZqIAQpA4AnIhcgIkL/////////B4N8IgwgBCkDsCkiDiAEKQOAKnwiCSAEKQPwJ3wiCiAEKQOQJ3wiFCAEKQPgJyIPIAQpA6ApfCIHIAQpA6AnfCIVIAQpA/AmIgggBCkD0Cd8IgZCNIggBiAIVK0gBEH4JmopAwAgBEHYJ2opAwB8fCIcQgyGhHwiCEI0iCAIIBVUrSAHIBVWrSAEQagnaikDACAHIA9UrSAEQegnaikDACAEQagpaikDAHx8fHwgHEI0iHx8IhVCDIaEfCIHQjSIIAcgFFStIAogFFatIARBmCdqKQMAIAkgClatIARB+CdqKQMAIAkgDlStIARBuClqKQMAIARBiCpqKQMAfHx8fHx8IBVCNIh8fCIVQgyGhHwiFEL/////////B4MiCUIAIAZCAYZC/v///////w+DIg5CABAGIARB8CVqIAdC/////////weDIgpCACAIQgGGQv7///////8PgyIPQgAQBiAEQcAlaiALQv///////z+DIAwgFFatIARBiCdqKQMAIAwgF1StfCAVQjSIfHxCDIYgFEI0iIR8IhVCACAVQgAQBiAEQbAlaiAEKQPAJUIAQpD6gICAAkIAEAYgBEGQJWogBkL/////////B4MiF0IAIBVCAYYiBkIAEAYgBEHgJWogCUIAIA9CABAGIARB0CZqIApCACAKQgAQBiAEQaAlaiAEQcglaikDAEIAQoCAxJ6AgMAAQgAQBiAEQbAmaiAXQgAgF0IAEAYgBEGAJWogCEL/////////B4MiFEIAIAZCABAGIARB0CVqIAlCACAHQgGGQv7///////8Pg0IAEAYgBEGgJGogBCkDgCUiFiAEKQPQJXwiCCAEKQPgJSIYIAQpA9AmfCIHIAQpA5AlfCILIAQpA6AlfCIPIAQpA6AmIh4gBCkD8CV8IgwgBCkDsCV8Ihx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DACAEQcgjaikDAHx8fHx8fCAHQjSIfHwiBkIMhoR8IgpCNIggCSAKVq0gBEHoGGopAwAgCSAVVK18IAZCNIh8fEIMhoR8Qvb///////8EfCIIQjCIQtGHgIAQfiAMQv////////8HgyABKQMAIg99Qtaz///f/v/PAHwiB3wiG0L/////////B4MiIELQh4CAEIUhGSABKQNIIhwgFkL///////8/gyAEKQPwGSIYIB1C/////////weDfCIJIAQpA+AbIh4gBCkDkBt8IgYgBCkDsBx8IgsgBCkDgBp8IgwgBCkD8BsiIiAEKQOgG3wiFSAEKQOgGnwiFiAEKQPgGSIaIAQpA7AbfCIdQjSIIBogHVatIARB6BlqKQMAIARBuBtqKQMAfHwiGkIMhoR8IiNCNIggFiAjVq0gFSAWVq0gBEGoGmopAwAgFSAiVK0gBEH4G2opAwAgBEGoG2opAwB8fHx8IBpCNIh8fCIVQgyGhHwiGkI0iCAMIBpWrSALIAxWrSAEQYgaaikDACAGIAtWrSAEQbgcaikDACAGIB5UrSAEQegbaikDACAEQZgbaikDAHx8fHx8fCAVQjSIfHwiC0IMhoR8IgZCNIggBiAJVK0gBEH4GWopAwAgCSAYVK18IAtCNIh8fEIMhoR8fUL8////////AXwhFSAKQv////////8HgyABKQMYIhZ9Qvb////////PAHwhCSABQUBrKQMAIhggBkL/////////B4N9Qvz///////8ffCELIBdC/////////weDIAEpAxAiHn1C9v///////88AfCEKIAEpAzgiIiAaQv////////8Hg31C/P///////x98IQwgFEL/////////B4MgASkDCCIafUL2////////zwB8IQYgASkDMCIkICNC/////////weDfUL8////////H3whFCABKQMoIiMgHUL/////////B4N9Qrzh//+///8ffCEXAkAgIEIAUiAZQv////////8HUnENACAbIBtCNIggBnwiG4QgG0I0iCAKfCIdhCAdQjSIIAl8IiCEQv////////8HgyAIQv///////z+DICBCNIh8Ih+EQgBSBEAgGSAfQoCAgICAgMAHhYMgG4MgHYMgIINC/////////wdSDQELIBVCMIhC0YeAgBB+IBd8IglC/////////weDIgZC0IeAgBCFIQoCQCAG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GIAAgBCkDkBQiJiAEKQPQFXwiIUL/////////B4M3A1AgBEHAFmogBkIAIBNCABAGIARBwBVqIAdCACANQgAQBiAEQYAUaiAIQgAgEkIAEAYgBEGQGGogCUIAIBFCABAGIARBsBdqIApCACAQQgAQBiAEQfATaiAEKQOAFCIpIAQpA7AXfCInIAQpA5AYfCIoIB8gIFStIB0gIFatIARBqBhqKQMAIBkgHVatIARBqBRqKQMAIBkgKlStIARByBdqKQMAIARB2BZqKQMAfHx8fHx8ICVCNIh8fCIlQgyGIB9CNIiEfCIZQv////////8Hg0IAQpD6gICAAkIAEAYgACAEKQPAFiIqIAQpA8AVfCIdIAQpA/ATfCIgICEgJlStIARBmBRqKQMAIARB2BVqKQMAfHwiJkIMhiAhQjSIhHwiH0L/////////B4M3A1ggBEGgF2ogCkIAIBNCABAGIARBsBZqIAZCACANQgAQBiAEQbAVaiAHQgAgEkIAEAYgBEHgE2ogCEIAIBFCABAGIARBgBhqIAlCACAQQgAQBiAEQdATaiAEKQOAGCIhIAQpA+ATfCITIBkgKFStICcgKFatIARBmBhqKQMAICcgKVStIARBiBRqKQMAIARBuBdqKQMAfHx8fCAlQjSIfHwiJ0IMhiAZQjSIhHwiGUIAQpD6gICAAkIAEAYgACAEKQOwFiIoIAQpA7AVfCINIAQpA6AXfCISIAQpA9ATfCIRIB8gIFStIB0gIFatIARB+BNqKQMAIB0gKlStIARByBZqKQMAIARByBVqKQMAfHx8fCAmQjSIfHwiHUIMhiAfQjSIhHwiEEL/////////B4M3A2AgBEHAE2ogEyAZVq0gEyAhVK0gBEGIGGopAwAgBEHoE2opAwB8fCAnQjSIfHxCAEKAgMSegIDAAEIAEAYgACAEKQPAEyIZICtC/////////weDfCITIBAgEVStIBEgElStIARB2BNqKQMAIA0gElatIARBqBdqKQMAIA0gKFStIARBuBZqKQMAIARBuBVqKQMAfHx8fHx8IB1CNIh8fCISQgyGIBBCNIiEfCINQv////////8HgzcDaCAAIBtC////////P4MgDSATVK0gBEHIE2opAwAg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akK84f//v///HyAEKQPgEiIRIAQpA6AVfCINQv////////8Hg30iE0IAIAlCABAGIARB4BFqQvz///////8fIAQpA/ARIiAgBCkDgBV8IhIgDSARVK0gBEHoEmopAwAgBEGoFWopAwB8fCIfQgyGIA1CNIiEfCIRQv////////8Hg30iDUIAIApCABAGIARB4BBqQvz///////8fIAQpA/AUIiEgBCkDoBZ8IhsgBCkDgBF8IhkgESASVK0gEiAgVK0gBEH4EWopAwAgBEGIFWopAwB8fCAfQjSIfHwiIEIMhiARQjSIhHwiEUL/////////B4N9IhJCACAGQgAQBiAEQZAQakL8////////HyAEKQPwECIfIB1C/v///////weDfCIdIBEgGVStIBkgG1StIARBiBFqKQMAIBsgIVStIARB+BRqKQMAIARBqBZqKQMAfHx8fCAgQjSIfHwiGUIMhiARQjSIhHwiG0L/////////B4N9IhFCACAHQgAQBiAEQcAPakL8////////ASAQQv///////z+DIBsgHVStIARB+BBqKQMAIB0gH1StfCAZQjSIfHxCDIYgG0I0iIR8fSIQQgAgCEIAEAYgBEGwD2ogBCkDwA9CAEKQ+oCAgAJCABAGIARBwBJqIBNCACAIQgAQBiAEQdARaiANQgAgCUIAEAYgBEHQEGogEkIAIApCABAGIARBgBBqIBFCACAGQgAQBiAEQZAPaiAQQgAgB0IAEAYgBEGgD2ogBEHID2opAwBCAEKAgMSegIDAAEIAEAYgBEGwEmogE0IAIAdCABAGIARBwBFqIA1CACAIQgAQBiAEQcAQaiASQgAgCUIAEAYgBEHwD2ogEUIAIApCABAGIARBgA9qIBBCACAGQgAQBiAEQfAOaiAEKQPAECIqIAQpA8ARfCIZIAQpA/APfCIdIAQpA4APfCIgIAQpA9ARIiwgBCkDwBJ8Ih8gBCkD0BB8IiEgBCkDgBB8IicgBCkDkA98IiggBCkDoA98IiUgBCkD4BEiLSAEKQPQEnwiGyAEKQPgEHwiJiAEKQOQEHwiKSAEKQOwD3wiK0I0iCApICtWrSAEQbgPaikDACAmIClWrSAEQZgQaikDACAbICZWrSAEQegQaikDACA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EKQPYByAEQYgKaikDAHx8IA1CNIh8fCIJQgyGIAZCNIiEIgogBCkD4AZ8IgZCAEKQ+oCAgAJCABAGIARBwAZqIAYgClStIAQpA+gGIAlCNIh8fEIAQoCAxJ6AgMAAQgAQBiAAIAQpA/AOIhEgBCkDsBJ8IgpC/////////weDIgkgBCkDsAgiDiAEKQOgCnwiBkL/////////B4N8IAQpA4ALIh4gBCkD8A18IghC/////////weDIiFCAYZ8Iic3AwAgACAEKQOwESIgIAQpA6ASfCIHIAQpA9AOfCINIAogEVStIARB+A5qKQMAIARBuBJqKQMAfHwiH0IMhiAKQjSIhHwiEUL/////////B4MiCiAEKQPAByIlIAQpA+AJfCIQIAYgDlStIARBuAhqKQMAIARBqApqKQMAfHwiJkIMhiAGQjSIhHwiDkL/////////B4N8IAQpA+ANIikgBCkDkA18Ig8gBCkD4Ap8IhYgCCAeVK0gBEGIC2opAwAgBEH4DWopAwB8fCIqQgyGIAhCNIiEfCIIQv////////8HgyIsQgGGfCItNwMIIAAgBCkDoBEiLiAEKQOQEnwiHiAEKQOgEHwiGiAEKQOwDnwiHSANIBFWrSAHIA1WrSAEQdgOaikDACAHICBUrSAEQbgRaikDACAEQagSaikDAHx8fHwgH0I0iHx8Ii9CDIYgEUI0iIR8IgdC/////////weDIgYgBCkDoAkiMCAEKQPQCXwiDSAEKQPQBnwiESAOIBBUrSAQICVUrSAEKQPIByAEQegJaikDAHx8ICZCNIh8fCIlQgyGIA5CNIiEfCIQQv////////8Hg3wgBCkDgA0iJiAEKQOwDHwiDiAEKQPQDXwiICAEKQPACnwiHyAIIBZUrSAPIBZWrSAEQegKaikDACAPIClUrSAEQegNaikDACAEQZgNaikDAHx8fHwgKkI0iHx8IilCDIYgCEI0iIR8Ig9C/////////weDIipCAYZ8IjE3AxAgACAEKQOgDiIyICtC/////////weDfCIWIAcgHVStIBogHVatIARBuA5qKQMAIBogHlStIARBqBBqKQMAIB4gLlStIARBqBFqKQMAIARBmBJqKQMAfHx8fHx8IC9CNIh8fCIeQgyGIAdCNIiEfCIHQv////////8HgyIIIAQpA8AGIhogEkL+////////B4N8IhIgECARVK0gDSARVq0gBCkD2AYgDSAwVK0gBEGoCWopAwAgBEHYCWopAwB8fHx8ICVCNIh8fCIdQgyGIBBCNIiEfCINQv////////8Hg3wgBCkDsAoiJSAoQv////////8Hg3wiESAPIB9UrSAfICBUrSAEQcgKaikDACAOICBWrSAEQdgNaikDACAOICZUrSAEQYgNaikDACAEQbgMaikDAHx8fHx8fCApQjSIfHwiDkIMhiAPQjSIhHwiEEL/////////B4MiD0IBhnwiIDcDGCAAIBtC////////P4MgByAWVK0gBEGoDmopAwAgFiAyVK18IB5CNIh8fEIMhiAHQjSIhHwiByATQv///////z+DIA0gElStIAQpA8gGIBIgGlStfCAdQjSIfHxCDIYgDUI0iIR8fCAZQv///////z+DIBAgEVStIARBuApqKQMAIBEgJVStfCAOQjSIfHxCDIYgEEI0iIR8IhBCAYZ8Ig43AyAgBEGgCGogISAnfCITQgAgC0IAEAYgBEGwB2ogLCAtfCINQgAgDEIAEAYgBEGwBmogKiAxfCISQgAgFEIAEAYgBEHgBWogDyAgfCIRQgAgF0IAEAYgBEGQBWogDiAQfCIQQgAgFUIAEAYgBEGABWogBCkDkAVCAEKQ+oCAgAJCABAGIARBkAhqIBNCACAVQgAQBiAEQaAHaiANQgAgC0IAEAYgBEGgBmogEkIAIAxCABAGIARB0AVqIBFCACAUQgAQBiAEQeAEaiAQQgAgF0IAEAYgBEHwBGogBCkDmAVCAEKAgMSegIDAAEIAEAYgBEGACGogE0IAIBdCABAGIARBkAdqIA1CACAVQgAQBiAEQZAGaiASQgAgC0IAEAYgBEHABWogEUIAIAxCABAGIARB0ARqIBBCACAUQgAQBiAEQcAEaiAEKQOQBiIoIAQpA5AHfCIPIAQpA8AFfCIWIAQpA9AEfCIeIAQpA6AHIiUgBCkDkAh8IhogBCkDoAZ8IhsgBCkD0AV8IhkgBCkD4AR8Ih0gBCkD8AR8IiAgBCkDsAciJiAE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StfCAUQjSIfHxCDIYgCUI0iIR8fDcDSAsgBEGAOWokAAuaBQEFfgJAIAJBAEoEQCAAIAEgAkEFdEEga0FAcWoiASkDAEL/////////B4M3AwAgACABKQMIQgyGQoDg//////8HgyABKQMAQjSIhDcDCCAAIAEpAxBCGIZCgICA+P///weDIAEpAwhCKIiENwMQIAAgASkDGEIkhkKAgICAgP7/B4MgASkDEEIciIQ3AxggACABKQMYQhCINwMgIAAgASkDIEL/////////B4M3AyggACABKQMoQgyGQoDg//////8HgyABKQMgQjSIhDcDMCAAIAEpAzBCGIZCgICA+P///weDIAEpAyhCKIiENwM4IABBQGsgASkDOEIkhkKAgICAgP7/B4MgASkDMEIciIQ3AwAgACABKQM4QhCINwNIDAELIAAgASACQX9zQQV0QUBxaiIBKQMAQv////////8HgzcDACAAIAEpAwhCDIZCgOD//////weDIAEpAwBCNIiENwMIIAAgASkDEEIYhkKAgID4////B4MgASkDCEIoiIQ3AxAgACABKQMYQiSGQoCAgICA/v8HgyABKQMQQhyIhDcDGCAAIAEpAxhCEIg3AyAgACABKQMgQv////////8HgyIDNwMoIAAgASkDKEIMhkKA4P//////B4MgASkDIEI0iIQiBDcDMCAAIAEpAzBCGIZCgICA+P///weDIAEpAyhCKIiEIgU3AzggAEFAayICIAEpAzhCJIZCgICAgID+/weDIAEpAzBCHIiEIgY3AwAgASkDOCEHIAJC/P///////x8gBn03AwAgAEL8////////HyAFfTcDOCAAQvz///////8fIAR9NwMwIABCvOH//7///x8gA303AyggAEL8////////ASAHQhCIfTcDSAsgAEEANgJQC5YGAQR/IwBBsAFrIggkACAFBH8CQCAHRQRAQQAhBwNAIAcgCGogB0HQkwJqLQAAIAMgB2otAABzOgAAIAggB0EBciIJaiAJQdCTAmotAAAgAyAJai0AAHM6AAAgB0ECaiIHQSBHDQALDAELIAhCwAA3A4gBIAhCuc6w1aShoc8kNwNAIAhCscnv1/Pyt6LMADcDOCAIQrnXvtDczcXRDzcDMCAIQpnk9KaCzp/dzgA3AyggCEEoaiIJIAdBIBAHIAkgCBANQQAhBwNAIAcgCGoiCSAJLQAAIAMgB2otAABzOgAAIAggB0EBciIJaiIKIAotAAAgAyAJai0AAHM6AAAgCCAHQQJyIglqIgogCi0AACADIAlqLQAAczoAACAIIAdBA3IiCWoiCiAKLQAAIAMgCWotAABzOgAAIAdBBGoiB0EgRw0ACwsCQAJAIAZBDUcNACAFLQAAQcIARw0AIAUtAAFByQBHDQAgBS0AAkHQAEcNACAFLQADQTBHDQAgBS0ABEEzRw0AIAUtAAVBNEcNACAFLQAGQTBHDQAgBS0AB0EvRw0AIAUtAAhB7gBHDQAgBS0ACUHvAEcNACAFLQAKQe4ARw0AIAUtAAtB4wBHDQAgBS0ADEHlAEcNACAIQsAANwOIASAIQtS8io3C6Z7Y6AA3A0AgCEKA44WBlszhmtcANwM4IAhC8Yy3/LnWnrGDfzcDMCAIQrW2hbP0/u/fdDcDKAwBCyAIQgA3A4gBIAhCq7OP/JGjs/DbADcDQCAIQv+kuYjFkdqCm383AzggCELy5rvjo6f9p6V/NwMwIAhC58yn0NbQ67O7fzcDKCAIQShqIgMgBSAGEAcgAyAIQZABaiIFEA0gCEIANwOIASAIQquzj/yRo7Pw2wA3A0AgCEL/pLmIxZHagpt/NwM4IAhC8ua746On/aelfzcDMCAIQufMp9DW0Ouzu383AyggAyAFQSAQByADIAVBIBAHCyAIQShqIgMgCEEgEAcgAyAEQSAQByADIAEgAhAHIAMgABANQQEFQQALIQsgCEGwAWokACALC9k9AgV/HH4jAEGgDmsiAiQAIAAgASgCeDYCUCMAQTBrIgQkACAEIAEpA2ggASkDYCABKQNYIAEpA1AgASkDcCILQjCIQtGHgIAQfnwiCkI0iHwiB0I0iHwiDEI0iHwiCEI0iCALQv///////z+DfCILQjCIIAxC/////////weDIgwgB4MgCINC/////////wdRIAtC////////P1FxIApC/////////weDIgpCrvj//+///wdWca2EQtGHgIAQfiAKfCIKQjSIIAdC/////////weDfCIHQjSGQoCAgICAgID4P4MgCkL/////////B4OENw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ECAQQj+HIhEQBiADQeAAaiANIA4gEiAHEAYgA0FAayAPIAggECAREAYgA0EwaiAMIAsgEyATQj+HIgcQBiADQRBqIAkgCiAWIBZCP4ciCxAGIANBIGogDSAOIBMgBxAGIAMgDyAIIBYgCxAGIAMpAwAiCSADKQMgfCIHIAMpA0AiDSADKQNgfCIIIAMpA4ABIg8gAykDoAF8IgsgAykDwAEiDiADKQPgAXwiCiADKQOAAiIMIAMpA6ACfCITQj6IIAwgE1atIAMpA4gCIAMpA6gCfHwiE0IChoR8IgxCPoggCiAMVq0gCiAOVK0gAykDyAEgAykD6AF8fCATQj6HfHwiDkIChoR8IgpCPoggCiALVK0gCyAPVK0gAykDiAEgAykDqAF8fCAOQj6HfHwiD0IChoR8IgtCPoggCCALVq0gCCANVK0gAykDSCADKQNofHwgD0I+h3x8Ig1CAoaEfCIIQj6IIAcgCFatIAcgCVStIAMpAwggAykDKHx8IA1CPod8fEIChoQhFiADKQMQIhMgAykDMHwiByADKQNQIhAgAykDcHwiCSADKQOQASIRIAMpA7ABfCINIAMpA9ABIhUgAykD8AF8Ig8gAykDkAIiDiADKQOwAnwiEkI+iCAOIBJWrSADKQOYAiADKQO4Anx8IhJCAoaEfCIOQj6IIA4gD1StIA8gFVStIAMpA9gBIAMpA/gBfHwgEkI+h3x8IhVCAoaEfCIPQj6IIA0gD1atIA0gEVStIAMpA5gBIAMpA7gBfHwgFUI+h3x8IhFCAoaEfCINQj6IIAkgDVatIAkgEFStIAMpA1ggAykDeHx8IBFCPod8fCIQQgKGhHwiCUI+iCAHIAlWrSAHIBNUrSADKQMYIAMpAzh8fCAQQj6HfHxCAoaEIRMgCEL//////////z+DIRAgCUL//////////z+DIRIgC0L//////////z+DIREgDUL//////////z+DIRQgCkL//////////z+DIRUgD0L//////////z+DIRkgDEL//////////z+DIQcgDkL//////////z+DIQggBkEBaiIGQQpHDQALIAUgExAgIAQgAykDqAM3AyggBCADKQOgAzcDICAEIAMpA5gDNwMYIAQgAykDkAM3AxAgBCADKQOIAzcDCCADQcADaiQAIAQpAxAhByAEKQMYIQggBCkDKCEKIAQpAyAhCyABIAQpAwgiDEL/////////B4M3A1AgASAKQiiGIAtCFoiENwNwIAEgC0IehkKAgICA/P//B4MgCEIgiIQ3A2ggASAIQhSGQoCAwP////8HgyAHQiqIhDcDYCABIAdCCoZCgPj//////weDIAxCNIiENwNYIARBMGokACACQZAMaiABKQNoIgdCACABKQNQIg5CAYYiDEIAEAYgAkHgDWogASkDYCIIQgAgASkDWCILQgGGIglCABAGIAJBsA1qIAEpA3AiE0IAIBNCABAGIAJBoA1qIAIpA7ANQgBCkPqAgIACQgAQBiACQYANaiATQgGGIgpCACAOQgAQBiACQaAMaiAHQgAgCUIAEAYgAkHQDWogCEIAIAhCABAGIAJBkA1qIAJBuA1qKQMAQgBCgIDEnoCAwABCABAGIAJBkA5qIA5CACAOQgAQBiACQfAMaiAKQgAgC0IAEAYgAkGwDGogB0IAIAhCAYZCABAGIAJB0AtqIAIpA/AMIhUgAikDsAx8IgkgAikDoAwiEiACKQPQDXwiDSACKQOADXwiFiACKQOQDXwiECACKQOQDCIUIAIpA+ANfCIPIAIpA6ANfCIRQjSIIA8gEVatIAJBqA1qKQMAIA8gFFStIAJBmAxqKQMAIAJB6A1qKQMAfHx8fCIUQgyGhHwiD0I0iCAPIBBUrSAQIBZUrSACQZgNaikDACANIBZWrSACQYgNaikDACANIBJUrSACQagMaikDACACQdgNaikDAHx8fHx8fCAUQjSIfHwiEEIMhoR8Ig1CBIZC8P////////8AgyAPQjCIQg+DhEIAQtGHgIAQQgAQBiACQYAOaiALQgAgDEIAEAYgAkHgDGogCkIAIAhCABAGIAJBwAxqIAdCACAHQgAQBiACQYAMaiACKQPgDCISIAIpA8AMfCIWIAkgDVatIAkgFVStIAJB+AxqKQMAIAJBuAxqKQMAfHwgEEI0iHx8IhBCDIYgDUI0iIR8IglC/////////weDQgBCkPqAgIACQgAQBiACQcANaiAIQgAgDEIAEAYgAkHwDWogC0IAIAtCABAGIAJB0AxqIApCACAHQgAQBiACQfALaiAJIBZUrSASIBZWrSACQegMaikDACACQcgMaikDAHx8IBBCNIh8fCIKQgyGIAlCNIiEIgwgAikD0Ax8IglCAEKQ+oCAgAJCABAGIAJB4AtqIAkgDFStIAJB2AxqKQMAIApCNIh8fEIAQoCAxJ6AgMAAQgAQBiACQcALaiACKQPgCyIVIBFC/v///////weDfCIWIAIpA8ANIhEgAikD8A18IgogAikD8At8IgwgAikDgAwiEiACKQOADnwiCSACKQPQCyIQIAIpA5AOfCINQjSIIA0gEFStIAJB2AtqKQMAIAJBmA5qKQMAfHwiFEIMhoR8IhBCNIggCSAQVq0gCSASVK0gAkGIDGopAwAgAkGIDmopAwB8fCAUQjSIfHwiEkIMhoR8IglCNIggCSAMVK0gCiAMVq0gAkH4C2opAwAgCiARVK0gAkHIDWopAwAgAkH4DWopAwB8fHx8IBJCNIh8fCISQgyGhHwiEUL/////////B4MiCkIAIA5CABAGIAJBoApqIAlC/////////weDIgxCACALQgAQBiACQYAJaiAQQv////////8HgyIJQgAgCEIAEAYgAkHgB2ogDUL/////////B4MiDUIAIAdCABAGIAJBwAZqIA9C////////P4MgESAWVK0gAkHoC2opAwAgFSAWVq18IBJCNIh8fEIMhiARQjSIhHwiD0IAIBNCABAGIAJBsAZqIAIpA8AGQgBCkPqAgIACQgAQBiACQZAGaiAPQgAgDkIAEAYgAkGwC2ogCkIAIAtCABAGIAJBkApqIAxCACAIQgAQBiACQfAIaiAJQgAgB0IAEAYgAkHQB2ogDUIAIBNCABAGIAJBoAZqIAIpA8gGQgBCgIDEnoCAwABCABAGIAJBwAdqIA1CACAOQgAQBiACQYAGaiAPQgAgC0IAEAYgAkGgC2ogCkIAIAhCABAGIAJBgApqIAxCACAHQgAQBiACQeAIaiAJQgAgE0IAEAYgAkGABGogAikDgAoiHCACKQPgCHwiECACKQOgC3wiESACKQOABnwiFSACKQPwCCIeIAIpA9AHfCISIAIpA5AKfCIUIAIpA7ALfCIZIAIpA5AGfCI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gIACQgAQBiABIAIpA4AIIh0gAikD4AZ8IhUgAikDwAR8IhIgGSAbVK0gAikDCCACKQP4Bnx8IhtCDIYgGUI0iIR8IhRC/////////weDNwMIIAJBkAlqIAxCACAHQgAQBiACQfAHaiAJQgAgCEIAEAYgAkHQBmogDUIAIAtCABAGIAJBsARqIA9CACAOQgAQBiACQbAKaiAKQgAgE0IAEAYgAkGgBGogAikDsAQiCSACKQOwCnwiByARIBhUrSAYIBpUrSACKQPYBCAaIBxUrSACQcgKaikDACACQagJaikDAHx8fHwgF0I0iHx8Ig1CDIYgEUI0iIR8Ig9CAEKQ+oCAgAJCABAGIAEgAikD8AciDiACKQPQBnwiCCACKQOQCXwiCyACKQOgBHwiCiASIBRWrSASIBVUrSACKQPIBCAVIB1UrSACQYgIaikDACACKQPoBnx8fHwgG0I0iHx8IhNCDIYgFEI0iIR8IgxC/////////weDIhw3AxAgAkGQBGogByAPVq0gByAJVK0gAikDuAQgAkG4CmopAwB8fCANQjSIfHxCAEKAgMSegIDAAEIAEAYgASACKQOQBCIJIB5C/////////weDfCIHIAogDFatIAogC1StIAIpA6gEIAggC1atIAJBmAlqKQMAIAggDlStIAIpA/gHIAIpA9gGfHx8fHx8IBNCNIh8fCILQgyGIAxCNIiEfCIIQv////////8HgyIeNwMYIAEgEEL///////8/gyAHIAhWrSACKQOYBCAHIAlUrXwgC0I0iHx8QgyGIAhCNIiEfCIdNwMgIAJB8ANqIAIpA7AFIhAgH0L/////////B4N8Ig4gAikDwAgiDyACKQOgB3wiByACKQPgCXwiCCACKQPABXwiCyACKQPQCCITIAIpA7AHfCIKIAIpA+AFfCIMIAIpA4AEIgkgAikDwAd8Ig1CNIggCSANVq0gAikDiAQgAikDyAd8fCIRQgyGhHwiCUI0iCAJIAxUrSAKIAxWrSACKQPoBSAKIBNUrSACQdgIaikDACACKQO4B3x8fHwgEUI0iHx8IgxCDIaEfCIKQjSIIAogC1StIAggC1atIAIpA8gFIAcgCFatIAJB6AlqKQMAIAcgD1St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ABAGIAJB0AFqIA1CACAKQgAQBiACQeAAaiAOQgAgCUIAEAYgAkHAA2ogB0IAIA9CABAGIAJB8AJqIAtCACATQgAQBiACQdAAaiACKQPAAyIbIAIpA/ACfCIZIAIpA2B8IhogEiAVVK0gESAVVq0gAikDeCAQIBFWrSACKQPYAyAQICBUrSACKQOIAyACKQO4Anx8fHx8fCAYQjSIfHwiGEIMhiASQjSIhHwiEEL/////////B4NCAEKQ+oCAgAJCABAGIAEgAikDoAIiICACKQPQAXwiESACKQNQfCIVIBQgF1StIAIpAxggAikD6AF8fCIXQgyGIBRCNIiEfCISQv////////8HgzcDMCACQeACaiALQgAgCEIAEAYgAkGQAmogDEIAIApCABAGIAJBwAFqIA1CACAJQgAQBiACQUBrIA5CACAPQgAQBiACQbADaiAHQgAgE0IAEAYgAkEwaiACKQNAIgkgAikDsAN8IgcgECAaVK0gGSAaVq0gAikDaCAZIBtUrSACKQPIAyACKQP4Anx8fHwgGEI0iHx8Ig1CDIYgEEI0iIR8Ig9CAEKQ+oCAgAJCABAGIAEgAikDkAIiDiACKQPAAXwiCCACKQPgAnwiCyACKQMwfCIKIBIgFVStIBEgFVatIAIpA1ggESAgVK0gAikDqAIgAikD2AF8fHx8IBdCNIh8fCITQgyGIBJCNIiEfCIMQv////////8HgzcDOCACQSBqIAcgD1atIAcgCVStIAIpA0ggAikDuAN8fCANQjSIfHxCAEKAgMSegIDAAEIAEAYgAyACKQMgIgkgH0L/////////B4N8IgcgCiAMVq0gCiALVK0gAikDOCAIIAtWrSACKQPoAiAIIA5UrSACKQOYAiACKQPIAXx8fHx8fCATQjSIfHwiC0IMhiAMQjSIhHwiCEL/////////B4M3AwAgASAWQv///////z+DIAcgCFatIAIpAyggByAJVK18IAtCNIh8fEIMhiAIQjSIhHw3A0ggAUIANwNwIAFCADcDaCABQgA3A2AgAUIANwNYIAAgHTcDICAAIB43AxggACAcNwMQIAAgASkDCDcDCCAAIAEpAwA3AwAgACABKQNINwNIIABBQGsgAykDADcDACA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rSADQZAnaikDACAJIBJWrSADQbAmaikDACADQeAnaikDAHx8fHx8fCAIQjSIfHwiCEIMhoR8IgpCBIZC8P////////8AgyAYQjCIQg+DhEIAQtGHgIAQQgAQBiADQYgoaiAuQgAgEEIAEAYgA0HoJmogEUIAICpCABAGIANByCZqIClCACApQgAQBiADQYgmaiADKQPoJiIJIAMpA8gmfCILIAogD1StIAwgD1atIANBgCdqKQMAIANBwCZqKQMAfHwgCEI0iHx8IghCDIYgCkI0iIR8IgpC/////////weDQgBCkPqAgIACQgAQBiADQcgnaiAqQgAgEEIAEAYgA0H4J2ogLkIAIC5CABAGIANB2CZqIBFCACApQgAQBiADQfglaiAKIAtUrSAJIAtWrSADQfAmaikDACADQdAmaikDAHx8IAhCNIh8fCIMQgyGIApCNIiEIgkgAykD2CZ8IghCAEKQ+oCAgAJCABAGIANB6CVqIAggCVStIANB4CZqKQMAIAxCNIh8fEIAQoCAxJ6AgMAAQgAQBiADQcglaiADKQPoJSIKIA1C/v///////weDfCIQIAMpA8gnIgwgAykD+Cd8Ig8gAykD+CV8IhIgAykDiCYiCSADKQOIKHwiCyADKQPYJSIIIAMpA5gofCIOQjSIIAggDlatIANB4CVqKQMAIANBoChqKQMAfHwiCEIMhoR8Ig1CNIggCyANVq0gCSALVq0gA0GQJmopAwAgA0GQKGopAwB8fCAIQjSIfHwiCEIMhoR8IgtCNIggCyASVK0gDyASVq0gA0GAJmopAwAgDCAPVq0gA0HQJ2opAwAgA0GAKGopAwB8fHx8IAhCNIh8fCIIQgyGhHwiCUL/////////B4MiKEIAIARBIGoiBSkDACIWQgAQBiADQagkaiALQv////////8HgyIrQgAgBSkDCCIZQgAQBiADQYgjaiANQv////////8HgyIsQgAgBSkDECIXQgAQBiADQeghaiAOQv////////8HgyIjQgAgBSkDGCIUQgAQBiADQcggaiAYQv///////z+DIAkgEFStIANB8CVqKQMAIAogEFatfCAIQjSIfHxCDIYgCUI0iIR8Ih1CACAFKQMgIhxCABAGIANBuCBqIAMpA8ggQgBCkPqAgIACQgAQBiADQZggaiAdQgAgFkIAEAYgA0G4JWogKEIAIBlCABAGIANBmCRqICtCACAXQgAQBiADQfgiaiAsQgAgFEIAEAYgA0HYIWogI0IAIBxCABAGIANBqCBqIANB0CBqKQMAQgBCgIDEnoCAwABCABAGIANByCFqICNCACAWQgAQBiADQYggaiAdQgAgGUIAEAYgA0GoJWogKEIAIBdCABAGIANBiCRqICtCACAUQgAQBiADQegiaiAsQgAgHEIAEAYgA0GIHmogAykDiCQiDCADKQPoInwiGyADKQOoJXwiEyADKQOIIHwiESADKQP4IiIJIAMpA9ghfCIYIAMpA5gkfCIQIAMpA7glfCIPIAMpA5ggfCISIAMpA6ggfCIOIAMpA4gjIgggAykD6CF8Ig0gAykDqCR8IgsgAykDyCV8IgogAykDuCB8IhVCNIggCiAVVq0gA0HAIGopAwAgCiALVK0gA0HQJWopAwAgCyANVK0gA0GwJGopAwAgCCANVq0gA0GQI2opAwAgA0HwIWopAwB8fHx8fHx8fCIIQgyGhHwiH0I0iCAOIB9WrSAOIBJUrSADQbAgaikDACAPIBJWrSADQaAgaikDACAPIBBUrSADQcAlaikDACAQIBhUrSADQaAkaikDACAJIBhWrSADQYAjaikDACADQeAhaikDAHx8fHx8fHx8fHwgCEI0iHx8IghCDIaEfCIKQgSGQvD/////////AIMgH0IwiEIPg4RCAELRh4CAEEIAEAYgA0HYImogLEIAIBZCABAGIANBuCFqICNCACAZQgAQBiADQfgfaiAdQgAgF0IAEAYgA0GYJWogKEIAIBRCABAGIANB+CNqICtCACAcQgAQBiADQegfaiADKQOYJSIJIAMpA/gjfCIOIAMpA/gffCINIAogEVStIBEgE1StIANBkCBqKQMAIBMgG1StIANBsCVqKQMAIAwgG1atIANBkCRqKQMAIANB8CJqKQMAfHx8fHx8IAhCNIh8fCIIQgyGIApCNIiEfCILQv////////8Hg0IAQpD6gICAAkIAEAYgA0HoI2ogK0IAIBZCABAGIANByCJqICxCACAZQgAQBiADQaghaiAjQgAgF0IAEAYgA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x8fHx8fHx8IAhCNIh8fCIIQgyGhHwiCkIEhkLw/////////wCDIBRCMIhCD4OEQgBC0YeAgBBCABAGIANBiCJqICxCACAgQgAQBiADQeggaiAjQgAgGkIAEAYgA0HYHmogHUIAIBZCABAGIANByCRqIChCACAZQgAQBiADQagjaiArQgAgF0IAEAYgA0HIHmogAykDyCQiCSADKQOoI3wiDiADKQPYHnwiDSAKIBNUrSATIBtUrSADQfAeaikDACAbIBxUrSADQeAkaikDACAMIBxWrSADQaAiaikDACADQcAjaikDAHx8fHx8fCAIQjSIfHwiCEIMhiAKQjSIhHwiC0L/////////B4NCAEKQ+oCAgAJCABAGIANBmCNqICtCACAgQgAQBiADQfghaiAsQgAgGkIAEAYgA0HYIGogI0IAIBZCABAGIANBuB5qIB1CACAZQgAQBiADQbgkaiAoQgAgF0IAEAYgA0GoHmogAykDuB4iDCADKQO4JHwiCiALIA1UrSANIA5UrSADQeAeaikDACAJIA5WrSADQdAkaikDACADQbAjaikDAHx8fHwgCEI0iHx8IglCDIYgC0I0iIR8IghCAEKQ+oCAgAJCABAGIANBmB5qIAggClStIAogDFStIANBwB5qKQMAIANBwCRqKQMAfHwgCUI0iHx8QgBCgIDEnoCAwABCABAGIANBuBVqIAMpA7gXIgggAykD+CB8IgxC/////////weDIiBCACApQgAQBiADQYgWaiADKQOIIiIJIAMpA+ggfCIPIAMpA8gefCILIAggDFatIANBwBdqKQMAIANBgCFqKQMAfHwiCEIMhiAMQjSIhHwiCkL/////////B4MiGkIAICpCABAGIANB2BZqIAMpA9ggIgwgAykD+CF8IhIgAykDmCN8Ig4gAykDqB58Ig0gCiALVK0gCyAPVK0gA0HQHmopAwAgCSAPVq0gA0GQImopAwAgA0HwIGopAwB8fHx8IAhCNIh8fCIIQgyGIApCNIiEfCILQv////////8HgyIWQgAgLkIAEAYgA0GoF2ogAykDmB4iCSAQQv////////8Hg3wiCiALIA1UrSANIA5UrSADQbAeaikDACAOIBJUrSADQaAjaikDACAMIBJWrSADQeAgaikDACADQYAiaikDAHx8fHx8fCAIQjSIfHwiCEIMhiALQjSIhHwiDEL/////////B4MiGUIAIDFCABAGIANB6BRqIBRC////////P4MgCiAMVq0gA0GgHmopAwAgCSAKVq18IAhCNIh8fEIMhiAMQjSIhHwiF0IAIDJCABAGIANB2BRqIAMpA+gUQgBCkPqAgIACQgAQBiADQagVaiAgQgAgMkIAEAYgA0H4FWogGkIAIClCABAGIANByBZqIBZCACAqQgAQBiADQZgXaiAZQgAgLkIAEAYgA0G4FGogF0IAIDFCABAGIANByBRqIANB8BRqKQMAQgBCgIDEnoCAwABCABAGIANBmBVqICBCACAxQgAQBiADQegVaiAaQgAgMkIAEAYgA0G4FmogFkIAIClCABAGIANBiBdqIBlCACAqQgAQBiADQagUaiAXQgAgLkIAEAYgA0HIE2ogAykDuBYiDCADKQPoFXwiGyADKQOIF3wiEyADKQOoFHwiESADKQP4FSIJIAMpA6gVfCIYIAMpA8gWfCIQIAMpA5gXfCIPIAMpA7gUfCISIAMpA8gUfCIOIAMpA4gWIgggAykDuBV8Ig0gAykD2BZ8IgsgAykDqBd8IgogAykD2BR8IhxCNIggCiAcVq0gA0HgFGopAwAgCiALVK0gA0GwF2opAwAgCyANVK0gA0HgFmopAwAgCCANVq0gA0GQFmopAwAgA0HAFWopAwB8fHx8fHx8fCIIQgyGhHwiFEI0iCAOIBRWrSAOIBJUrSADQdAUaikDACAPIBJWrSADQcAUaikDACAPIBBUrSADQaAXaikDACAQIBhUrSADQdAWaikDACAJIBhWrSADQYAWaikDACADQbAVaikDAHx8fHx8fHx8fHwgCEI0iHx8IghCDIaEfCIKQgSGQvD/////////AIMgFEIwiEIPg4RCAELRh4CAEEIAEAYgA0GIFWogIEIAIC5CABAGIANB2BVqIBpCACAxQgAQBiADQagWaiAWQgAgMkIAEAYgA0H4FmogGUIAIClCABAGIANBmBRqIBdCACAqQgAQBiADQYgUaiADKQP4FiIJIAMpA6gWfCIOIAMpA5gUfCINIAogEVStIBEgE1StIANBsBRqKQMAIBMgG1StIANBkBdqKQMAIAwgG1atIANBwBZqKQMAIANB8BVqKQMAfHx8fHx8IAhCNIh8fCIIQgyGIApCNIiEfCILQv////////8Hg0IAQpD6gICAAkIAEAYgA0H4FGogIEIAICpCABAGIANByBVqIBpCACAuQgAQBiADQZgWaiAWQgAgMUIAEAYgA0HoFmogGUIAIDJCABAGIANB+BNqIBdCACApQgAQBiADQegTaiADKQP4EyIMIAMpA+gWfCIKIAsgDVStIA0gDlStIANBoBRqKQMAIAkgDlatIANBgBdqKQMAIANBsBZqKQMAfHx8fCAIQjSIfHwiCUIMhiALQjSIhHwiCEIAQpD6gICAAkIAEAYgA0HYE2ogCCAKVK0gCiAMVK0gA0GAFGopAwAgA0HwFmopAwB8fCAJQjSIfHxCAEKAgMSegIDAAEIAEAYgA0GoG2ogAykDuB8iCiAVQv////////8Hg3wiESADKQPIIiIMIAMpA6ghfCIYIAMpA+gjfCIQIAMpA8gffCISIAMpA9giIgkgAykDuCF8Ig4gAykD6B98IgsgAykDiB4iCCADKQPIIXwiDUI0iCAIIA1WrSADQZAeaikDACADQdAhaikDAHx8IghCDIaEfCIPQjSIIAsgD1atIAsgDlStIANB8B9qKQMAIAkgDlatIANB4CJqKQMAIANBwCFqKQMAfHx8fCAIQjSIfHwiCEIMhoR8IgtCNIggCyASVK0gECASVq0gA0HQH2opAwAgECAYVK0gA0HwI2opAwAgDCAYVq0gA0HQImopAwAgA0GwIWopAwB8fHx8fHwgCEI0iHx8IglCDIaEfCIMQv////////8HgyISIAEpAxgiIXwiIkIAIA1C/////////weDIg4gASkDACIkfCIXQgGGIhtCABAGIANBqBxqIAtC/////////weDIg0gASkDECItfCIvQgAgD0L/////////B4MiCyABKQMIIh58IiNCAYYiCEIAEAYgA0GYGmogH0L///////8/gyAMIBFUrSADQcAfaikDACAKIBFWrXwgCUI0iHx8QgyGIAxCNIiEfCIKIAEpAyAiMHwiH0IAIB9CABAGIANBiBpqIAMpA5gaQgBCkPqAgIACQgAQBiADQegZaiAfQgGGIhVCACAXQgAQBiADQZgbaiAiQgAgCEIAEAYgA0GYHGogL0IAIC9CABAGIANB+BlqIANBoBpqKQMAQgBCgIDEnoCAwABCABAGIANB+B1qIBdCACAXQgAQBiADQdgZaiAVQgAgI0IAEAYgA0GIG2ogIkIAIC9CAYZCABAGIANByBlqIAMpA9gZIgwgAykDiBt8IhMgAykDmBsiCSADKQOYHHwiESADKQPoGXwiGCADKQP4GXwiECADKQOoGyIIIAMpA6gcfCIPIAMpA4gafCIZQjSIIA8gGVatIANBkBpqKQMAIAggD1atIANBsBtqKQMAIANBsBxqKQMAfHx8fCIIQgyGhHwiOEI0iCAQIDhWrSAQIBhUrSADQYAaaikDACARIBhWrSADQfAZaikDACAJIBFWrSADQaAbaikDACADQaAcaikDAHx8fHx8fCAIQjSIfHwiCEIMhoR8Ig9CBIZC8P////////8AgyA4QjCIQg+DhEIAQtGHgIAQQgAQBiADQZgdaiAjQgAgG0IAEAYgA0G4GWogFUIAIC9CABAGIANB+BpqICJCACAiQgAQBiADQagZaiADKQO4GSIJIAMpA/gafCIQIA8gE1StIAwgE1atIANB4BlqKQMAIANBkBtqKQMAfHwgCEI0iHx8IghCDIYgD0I0iIR8Ig9C/////////weDQgBCkPqAgIACQgAQBiADQYgcaiAvQgAgG0IAEAYgA0GIHWogI0IAICNCABAGIANBmBlqIBVCACAiQgAQBiADQYgZaiAPIBBUrSAJIBBWrSADQcAZaikDACADQYAbaikDAHx8IAhCNIh8fCIMQgyGIA9CNIiEIgkgAykDmBl8IghCAEKQ+oCAgAJCABAGIANB+BhqIAggCVStIANBoBlqKQMAIAxCNIh8fEIAQoCAxJ6AgMAAQgAQBiADQegaakL8////////HyASfSIdQgAgJEIAEAYgA0H4G2pC/P///////x8gDX0iIEIAIB5CABAGIANB+BxqQvz///////8fIAt9IhpCACAtQgAQBiADQegdakK84f//v///HyAOfSIWQgAgIUIAEAYgA0HoGGpC/P///////wEgCn0iFUIAIDBCABAGIANB2BhqIAMpA+gYQgBCkPqAgIACQgAQBiADQbgYaiAVQgAgJEIAEAYgA0HYGmogHUIAIB5CABAGIANB6BtqICBCACAtQgAQBiADQegcaiAaQgAgIUIAEAYgA0HYHWogFkIAIDBCABAGIANByBhqIANB8BhqKQMAQgBCgIDEnoCAwABCABAGIANByB1qIBZCACAkQgAQBiADQagYaiAVQgAgHkIAEAYgA0HIGmogHUIAIC1CABAGIANB2BtqICBCACAhQgAQBiADQdgcaiAaQgAgMEIAEAYgA0GYGGogAykD2BsiDCADKQPYHHwiGyADKQPIGnwiEyADKQOoGHwiESADKQPoHCIJIAMpA9gdfCIYIAMpA+gbfCIQIAMpA9gafCIPIAMpA7gYfCISIAMpA8gYfCIOIAMpA/gcIgggAykD6B18Ig0gAykD+Bt8IgsgAykD6Bp8IgogAykD2Bh8IitCNIggCiArVq0gA0HgGGopAwAgCiALVK0gA0HwGmopAwAgCyANVK0gA0GAHGopAwAgCCANVq0gA0GAHWopAwAgA0HwHWopAwB8fHx8fHx8fCIIQgyGhHwiKEI0iCAOIChWrSAOIBJUrSADQdAYaikDACAPIBJWrSADQcAYaikDACAPIBBUrSADQeAaaikDACAQIBhUrSADQfAbaikDACAJIBhWrSADQfAcaikDACADQeAdaikDAHx8fHx8fHx8fHwgCEI0iHx8IghCDIaEfCIKQgSGQvD/////////AIMgKEIwiEIPg4RCAELRh4CAEEIAEAYgA0HIHGogGkIAICRCABAGIANBuB1qIBZCACAeQgAQBiADQYgYaiAVQgAgLUIAEAYgA0G4GmogHUIAICFCABAGIANByBtqICBCACAwQgAQBiADQfgXaiADKQO4GiIJIAMpA8gbfCIOIAMpA4gYfCINIAogEVStIBEgE1StIANBsBhqKQMAIBMgG1StIANB0BpqKQMAIAwgG1atIANB4BtqKQMAIANB4BxqKQMAfHx8fHx8IAhCNIh8fCIIQgyGIApCNIiEfCILQv////////8Hg0IAQpD6gICAAkIAEAYgA0G4G2ogIEIAICRCABAGIANBuBxqIBpCACAeQgAQBiADQagdaiAWQgAgLUIAEAYgA0HoF2ogFUIAICFCABAGIANBqBpqIB1CACAwQgAQBiADQdgXaiADKQPoFyIMIAMpA6gafCIKIAsgDVStIA0gDlStIANBkBhqKQMAIAkgDlatIANBwBpqKQMAIANB0BtqKQMAfHx8fCAIQjSIfHwiCUIMhiALQjSIhHwiCEIAQpD6gICAAkIAEAYgA0HIF2ogCCAKVK0gCiAMVK0gA0HwF2opAwAgA0GwGmopAwB8fCAJQjSIfHxCAEKAgMSegIDAAEIAEAYgAyABKQNIIhggFEL///////8/g3wgAykD2BMiCiAcQv////////8Hg3wiEyADKQPIFSIMIAMpA/gUfCIRIAMpA5gWfCIQIAMpA+gTfCIPIAMpA9gVIgkgAykDiBV8IhIgAykDiBR8Ig0gAykDyBMiCCADKQOYFXwiC0I0iCAIIAtWrSADQdATaikDACADQaAVaikDAHx8IghCDIaEfCIOQjSIIA0gDlatIA0gElStIANBkBRqKQMAIAkgElatIANB4BVqKQMAIANBkBVqKQMAfHx8fCAIQjSIfHwiCEIMhoR8Ig1CNIggDSAPVK0gDyAQVK0gA0HwE2opAwAgECARVK0gA0GgFmopAwAgDCARVq0gA0HQFWopAwAgA0GAFWopAwB8fHx8fHwgCEI0iHx8IghCDIaEfCIJQjSIIAkgE1StIANB4BNqKQMAIAogE1atfCAIQjSIfHxCDIaEfCJBQjCIQtGHgIAQfiABKQMoIhAgC0L/////////B4N8Ijl8IgtCNIggASkDMCIPIA5C/////////weDfCJDfCIKIAuEIAEpAzgiEiANQv////////8Hg3wiRCAKQjSIfCIMhCABQUBrKQMAIg4gCUL/////////B4N8IkUgDEI0iHwiCYRC/////////weDIEFC////////P4MgCUI0iHwiCIRQBH9BAQUgC0LQh4CAEIUgCEKAgICAgIDAB4WDIAqDIAyDIAmDQv////////8HUQsiBkEBcyIANgKsKCADNAKsKCEsIAMgADYCrCggA0GYDmogRUIAIAM0AqwoIgh9IgyDIAhCAX0iCSAdICF8g4QiM0IAIAwgOYMgFiAkfCAJg4QiNkIBhiIcQgAQBiADQZgPaiAMIESD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DCADKQP4D3wiESADKQP4CHwiDSADKQOICiIJIAMpA4gQfCILIAMpA4gLIgggAykD6BB8IiBCNIggCCAgVq0gA0GQC2opAwAgA0HwEGopAwB8fCIIQgyGhHwiGkI0iCALIBpWrSAJIAtWrSADQZAKaikDACADQZAQaikDAHx8IAhCNIh8fCIIQgyGhHwiFkI0iCANIBZWrSANIBFUrSADQYAJaikDACAMIBFWrSADQYAPaikDACADQYAQaikDAHx8fHwgCEI0iHx8IghCDIaEfCIJQv////////8HgyIlQgBCtKT//7/+/98AIBd9IiRCABAGIANB6AhqIBZC/////////weDIiZCAEL0////////3wAgI30iLUIAEAYgA0H4CWogGkL/////////B4MiJ0IAQvT////////fACAvfSIeQgAQBiADQfgKaiAgQv////////8HgyIhQgBC9P///////98AICJ9IjBCABAGIANByAZqIBVC////////P4MgCSATVK0gAykD8AcgCiATVq18IAhCNIh8fEIMhiAJQjSIhHwiIkIAQvT///////8FIB99Ih1CABAGIANBuAZqIAMpA8gGQgBCkPqAgIACQgAQBiADQZgGaiAiQgAgJEIAEAYgA0HIB2ogJUIAIC1CABAGIANB2AhqICZCACAeQgAQBiADQegJaiAnQgAgMEIAEAYgA0HoCmogIUIAIB1CABAGIANBqAZqIAMpA9AGQgBCgIDEnoCAwABCABAGIANB2ApqICFCACAkQgAQBiADQYgGaiAiQgAgLUIAEAYgA0G4B2ogJUIAIB5CABAGIANByAhqICZCACAwQgAQBiADQdgJaiAnQgAgHUIAEAYgA0GIBGogAykDyAgiDCADKQPYCXwiFyADKQO4B3wiHyADKQOIBnwiFCADKQPoCSIJIAMpA+gKfCIVIAMpA9gIfCIcIAMpA8gHfCIbIAMpA5gGfCITIAMpA6gGfCIRIAMpA/gJIgggAykD+Ap8Ig0gAykD6Ah8IgsgAykD2Ad8IgogAykDuAZ8IiNCNIggCiAjVq0gAykDwAYgCiALVK0gAykD4AcgCyANVK0gA0HwCGopAwAgCCANVq0gA0GACmopAwAgA0GAC2opAwB8fHx8fHx8fCIIQgyGhHwiL0I0iCARIC9WrSARIBNUrSADKQOwBiATIBtUrSADKQOgBiAbIBxUrSADKQPQByAVIBxWrSADQeAIaikDACAJIBVWrSADQfAJaikDACADQfAKaikDAHx8fHx8fHx8fHwgCEI0iHx8IghCDIaEfCIKQgSGQvD/////////AIMgL0IwiEIPg4RCAELRh4CAEEIAEAYgA0HICWogJ0IAICRCABAGIANByApqICFCACAtQgAQBiADQfgFaiAiQgAgHkIAEAYgA0GoB2ogJUIAIDBCABAGIANBuAhqICZCACAdQgAQBiADQegFaiADKQOoByIJIAMpA7gIfCIRIAMpA/gFfCINIAogFFStIBQgH1StIAMpA5AGIBcgH1atIAMpA8AHIAwgF1atIANB0AhqKQMAIANB4AlqKQMAfHx8fHx8IAhCNIh8fCIIQgyGIApCNIiEfCILQv////////8Hg0IAQpD6gICAAkIAEAYgA0GoCGogJkIAICRCABAGIANBuAlqICdCACAtQgAQBiADQbgKaiAhQgAgHkIAEAYgA0HYBWogIkIAIDBCABAGIANBmAdqICVCACAdQgAQBiADQcgFaiADKQPYBSIMIAMpA5gHfCIKIAsgDVStIA0gEVStIAMpA4AGIAkgEVatIAMpA7AHIANBwAhqKQMAfHx8fCAIQjSIfHwiCUIMhiALQjSIhHwiCEIAQpD6gICAAkIAEAYgA0G4BWogCCAKVK0gCiAMVK0gAykD4AUgAykDoAd8fCAJQjSIfHxCAEKAgMSegIDAAEIAEAYgA0GIB2ogJUIAICBCAYZC/v///////w+DIhtCABAGIANBmAhqICZCACAaQgGGQv7///////8PgyIIQgAQBiADQagFaiAiQgAgIkIAEAYgA0GYBWogAykDqAVCAEKQ+oCAgAJCABAGIANB+ARqICFCACAiQgGGIhxCABAGIANB+AZqICVCACAIQgAQBiADQYgIaiAmQgAgJkIAEAYgA0GIBWogAykDsAVCAEKAgMSegIDAAEIAEAYgA0GoCmogIUIAICFCABAGIANB6ARqICdCACAcQgAQBiADQdgGaiAlQgAgFkIBhkL+////////D4NCABAGIANBCGogAykD6AQiDCADKQPYBnwiEyADKQP4BiIJIAMpA4gIfCIRIAMpA/gEfCINIAMpA4gFfCILIAMpA4gHIgggAykDmAh8IgogAykDmAV8IjBCNIggCiAwVq0gAykDoAUgCCAKVq0gAykDkAcgA0GgCGopAwB8fHx8IghCDIaEfCItQjSIIAsgLVatIAsgDVStIAMpA5AFIA0gEVStIAMpA4AFIAkgEVatIAMpA4AHIANBkAhqKQMAfHx8fHx8IAhCNIh8fCIIQgyGhHwiCkIEhkLw/////////wCDIC1CMIhCD4OEQgBC0YeAgBBCABAGIANBqAlqICdCACAbQgAQBiADQdgEaiAmQgAgHEIAEAYgA0HoBmogJUIAICVCABAGIANByARqIAMpA9gEIgkgAykD6AZ8IgsgCiATVK0gDCATVq0gAykD8AQgAykD4AZ8fCAIQjSIfHwiCEIMhiAKQjSIhHwiCkL/////////B4NCAEKQ+oCAgAJCABAGIANB+AdqICZCACAbQgAQBiADQZgJaiAnQgAgJ0IAEAYgA0G4BGogJUIAIBxCABAGIANBqARqIAogC1StIAkgC1atIAMpA+AEIAMpA/AGfHwgCEI0iHx8IgxCDIYgCkI0iIQiCSADKQO4BHwiCEIAQpD6gICAAkIAEAYgA0GYBGogCCAJVK0gAykDwAQgDEI0iHx8QgBCgIDEnoCAwABCABAGIAMgBjYCrCggA0HYEmpCACAsfSIeIAMpA/gYIg0gGUL+////////B4N8Ih0gAykDiBwiDCADKQOIHXwiESADKQOIGXwiCyADKQOoGSIJIAMpA5gdfCIKIAMpA8gZIgggAykD+B18IiBCNIggCCAgVq0gA0HQGWopAwAgA0GAHmopAwB8fCIIQgyGhHwiGkI0iCAKIBpWrSAJIApWrSADQbAZaikDACADQaAdaikDAHx8IAhCNIh8fCIIQgyGhHwiFkI0iCALIBZWrSALIBFUrSADQZAZaikDACAMIBFWrSADQZAcaikDACADQZAdaikDAHx8fHwgCEI0iHx8IgtCDIaEfCIZQv////////8HgyADKQPIFyIKICtC/////////weDfCIXIAMpA7gcIgwgAykDqB18Ih8gAykDuBt8IhQgAykD2Bd8IhUgAykDyBwiCSADKQO4HXwiHCADKQP4F3wiESADKQOYGCIIIAMpA8gdfCIbQjSIIAggG1atIANBoBhqKQMAIANB0B1qKQMAfHwiCEIMhoR8IhNCNIggESATVq0gESAcVK0gA0GAGGopAwAgCSAcVq0gA0HQHGopAwAgA0HAHWopAwB8fHx8IAhCNIh8fCIIQgyGhHwiEUI0iCARIBVUrSAUIBVWrSADQeAXaikDACAUIB9UrSADQcAbaikDACAMIB9WrSADQcAcaikDACADQbAdaikDAHx8fHx8fCAIQjSIfHwiCUIMhoR8IgxC/////////weDfIMgLEIBfSIcIA5CAYaDhCIlQgAgIEL/////////B4MgG0L/////////B4N8IB6DIBwgEEIBhoOEIiFCAYYiEEIAEAYgA0GIE2ogFkL/////////B4MgEUL/////////B4N8IB6DIBwgEkIBhoOEIiZCACAaQv////////8HgyATQv////////8Hg3wgHoMgHCAPQgGGg4QiJ0IBhiIIQgAQBiADQZgSaiAoQv///////z+DIDhC////////P4N8IBkgHVStIANBgBlqKQMAIA0gHVatfCALQjSIfHxCDIYgGUI0iIR8IAwgF1StIANB0BdqKQMAIAogF1atfCAJQjSIfHxCDIYgDEI0iIR8IB6DIBwgGEIBhoOEIiJCACAiQgAQBiADQYgSaiADKQOYEkIAQpD6gICAAkIAEAYgA0HoEWogIkIBhiIPQgAgIUIAEAYgA0HIEmogJUIAIAhCABAGIANB+BJqICZCACAmQgAQBiADQfgRaiADQaASaikDAEIAQoCAxJ6AgMAAQgAQBiADQbgTaiAhQgAgIUIAEAYgA0HYEWogD0IAICdCABAGIANBuBJqICVCACAmQgGGQgAQBiADQcgRaiADKQPYESIMIAMpA7gSfCISIAMpA8gSIgkgAykD+BJ8Ig4gAykD6BF8Ig0gAykD+BF8IgsgAykD2BIiCCADKQOIE3wiCiADKQOIEnwiHUI0iCAKIB1WrSADQZASaikDACAIIApWrSADQeASaikDACADQZATaikDAHx8fHwiCEIMhoR8Ih5CNIggCyAeVq0gCyANVK0gA0GAEmopAwAgDSAOVK0gA0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FVatIANB0AxqKQMAIAsgDFatIANB4A1qKQMAIAsgDVStIANB8A5qKQMAIAggDVatIANB8A9qKQMAIANB4BBqKQMAfHx8fHx8fHwiCEIMhoR8IhRCNIggDiAUVq0gDiASVK0gA0HADGopAwAgDyASVq0gA0GwDGopAwAgDyAQVK0gA0HQDWopAwAgECAYVK0gA0HgDmopAwAgCSAYVq0gA0HgD2opAwAgA0HQEGopAwB8fHx8fHx8fHx8IAhCNIh8fCIJQgyGhHwiDUIEhkLw/////////wCDIBRCMIhCD4OEQgBC0YeAgBBCABAGIAM0AqwoISAgASADKQOIDCIIIAMpA7gQfCILQv////////8HgyIcNwNQIANBuA9qIDVCACAxQgAQBiADQagQaiA2QgAgLkIAEAYgA0H4C2ogN0IAICpCABAGIANBqA1qIDNCACApQgAQBiADQbgOaiA0QgAgMkIAEAYgA0HoC2ogAykDqA0iDCADKQO4DnwiDyADKQP4C3wiEiANIBFUrSARIBNUrSADQaAMaikDACATIBtUrSADQcANaikDACAKIBtWrSADQdAOaikDACADQdAPaikDAHx8fHx8fCAJQjSIfHwiCUIMhiANQjSIhHwiDkL/////////B4NCAEKQ+oCAgAJCABAGIAEgAykDuA8iDSADKQOoEHwiEyADKQPoC3wiESAIIAtWrSADQZAMaikDACADQcAQaikDAHx8IghCDIYgC0I0iIR8IhhC/////////weDIhs3A1ggA0GoDmogNEIAIDFCABAGIANBqA9qIDVCACAuQgAQBiADQZgQaiA2QgAgKkIAEAYgA0HYC2ogN0IAIClCABAGIANBmA1qIDNCACAyQgAQBiADQcgLaiADKQPYCyILIAMpA5gNfCIQIA4gElStIA8gElatIANBgAxqKQMAIAwgD1atIANBsA1qKQMAIANBwA5qKQMAfHx8fCAJQjSIfHwiCkIMhiAOQjSIhHwiCUIAQpD6gICAAkIAEAYgASADKQOoDyIMIAMpA5gQfCIPIAMpA6gOfCISIAMpA8gLfCIOIBEgGFatIBEgE1StIANB8AtqKQMAIA0gE1atIANBwA9qKQMAIANBsBBqKQMAfHx8fCAIQjSIfHwiCEIMhiAYQjSIhHwiDUL/////////B4MiEzcDYCADQbgLaiAJIBBUrSALIBBWrSADQeALaikDACADQaANaikDAHx8IApCNIh8fEIAQoCAxJ6AgMAAQgAQBiABIAMpA7gLIgkgFUL/////////B4N8IgogDSAOVK0gDiASVK0gA0HQC2opAwAgDyASVq0gA0GwDmopAwAgDCAPVq0gA0GwD2opAwAgA0GgEGopAwB8fHx8fHwgCEI0iHx8IghCDIYgDUI0iIR8IgxC/////////weDIhE3A2ggASAUQv///////z+DIAogDFatIANBwAtqKQMAIAkgClatfCAIQjSIfHxCDIYgDEI0iIR8Ihg3A3AgASADKQOIBCIIIAMpA9gKfCIKQv////////8HgyIPIAMpA8gRIgkgAykDuBN8IgxC/////////weDfCI4NwMAIAEgAykDyAkiCyADKQPICnwiECADKQPoBXwiDiAIIApWrSADKQOQBCADQeAKaikDAHx8IghCDIYgCkI0iIR8Ig1C/////////weDIhIgAykDqBEiCiADKQOoE3wiHyAJIAxWrSADQdARaikDACADQcATaikDAHx8IglCDIYgDEI0iIR8IhRC/////////weDfCIoNwMIIAEgAykDuAkiDCADKQO4CnwiGiADKQOoCHwiFiADKQPIBXwiFSANIA5UrSAOIBBUrSADKQPwBSALIBBWrSADQdAJaikDACADQdAKaikDAHx8fHwgCEI0iHx8IghCDIYgDUI0iIR8IhBC/////////weDIg4gAykD6BIiDSADKQOYE3wiGSADKQOIEXwiFyAUIB9UrSAKIB9WrSADQbARaikDACADQbATaikDAHx8IAlCNIh8fCIJQgyGIBRCNIiEfCIfQv////////8Hg3wiKzcDECABIAMpA7gFIgsgI0L/////////B4N8IhQgECAVVK0gFSAWVK0gAykD0AUgFiAaVK0gA0GwCGopAwAgDCAaVq0gA0HACWopAwAgA0HACmopAwB8fHx8fHwgCEI0iHx8IghCDIYgEEI0iIR8IhVC/////////weDIgogAykD+BAiDCAdQv7///////8Hg3wiECAXIB9WrSAXIBlUrSADQZARaikDACANIBlWrSADQfASaikDACADQaATaikDAHx8fHwgC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QfgCaiAeQgAgIUIAEAYgA0GoAmogGkIAICJCABAGIANB2AFqIBZCACAlQgAQBiADQdgAaiAZQgAgJkIAEAYgA0HIAGogAykD2AEiCSADKQOoAnwiDiADKQNYfCINIAogFFStIBQgH1StIAMpA4ABIBcgH1atIAMpA/ABIAwgF1atIAMpA8ACIAMpA5ADfHx8fHx8IAhCNIh8fCIIQgyGIApCNIiEfCILQv////////8Hg0IAQpD6gICAAkIAEAYgA0G4A2ogJEIAICZCABAGIANB6AJqIB5CACAnQgAQBiADQZgCaiAaQgAgIUIAEAYgA0HIAWogFkIAICJCABAGIANBOGogGUIAICVCABAGIANBKGogAykDOCIMIAMpA8gBfCIKIAsgDVStIA0gDlStIAMpA2AgCSAOVq0gAykD4AEgAykDsAJ8fHx8IAhCNIh8fCIJQgyGIAtCNIiEfCIIQgBCkPqAgIACQgAQBiADQRhqIAggClStIAogDFStIANBQGspAwAgAykD0AF8fCAJQjSIfHxCAEKAgMSegIDAAEIAEAYgAUIAQpKV//+f/v/vACADKQNoIgkgAykD2AN8IgpC/////////weDICBCAX0iEEL/////////B4MiHiADKQMIIgsgAykDqAp8Ig2DIDlCACAgfSIkg4R8fSIIQgGDfSIPQgyIIjlCr/j//+///weDIAh8QgGIIDkgAykD+AIiDCADKQPIA3wiGSADKQNIfCIXIAkgClatIAMpA3AgAykD4AN8fCIJQgyGIApCNIiEfCIUQv////////8HgyAeIAMpA8gEIgogAykDqAl8IhUgCyANVq0gAykDECADQbAKaikDAHx8IghCDIYgDUI0iIR8Ig6DICQgQ4OEfH0iDUIzhkKAgICAgICABIN8IhI3AyggASA5IAMpA+gCIgsgAykDuAN8IiAgAykDmAJ8IhogAykDKHwiHyAUIBdUrSAXIBlUrSADKQNQIAwgGVatIAMpA4ADIAMpA9ADfHx8fCAJQjSIfHwiDEIMhiAUQjSIhHwiFEL/////////B4MgHiADKQP4ByIJIAMpA5gJfCIWIAMpA6gEfCIZIA4gFVStIAogFVatIAMpA9AEIANBsAlqKQMAfHwgCEI0iHx8IghCDIYgDkI0iIR8IhWDICQgRIOEfH0iCkIzhkKAgICAgICABIMgDULy////////7wB8QgGIfCIONwMwIAEgOSADKQMYIg0gHUL/////////B4N8IhcgFCAfVK0gGiAfVq0gAykDMCAaICBUrSADKQOgAiALICBWrSADKQPwAiADKQPAA3x8fHx8fCAMQjSIfHwiC0IMhiAUQjSIhHwiH0L/////////B4MgHiADKQOYBCIMIDBC/v///////weDfCIUIBUgGVStIBYgGVatIAMpA7AEIAkgFlatIANBgAhqKQMAIANBoAlqKQMAfHx8fCAIQjSIfHwiCEIMhiAVQjSIhHwiFYMgJCBFg4R8fSIJQjOGQoCAgICAgIAEgyAKQvL////////vAHxCAYh8Igo3AzggASAPQhCIIC9C////////P4MgLUL///////8/gyAUIBVWrSADKQOgBCAMIBRWrXwgCEI0iHx8QgyGIBVCNIiEfCAQgyAkIEGDhHwgFyAfVq0gAykDICANIBdWrXwgC0I0iHx8QgyGIB9CNIiEfH0iCELy////////BnxCAYgiDDcDSCABQUBrIgAgCEIzhkKAgICAgICABIMgCULy////////7wB8QgGIfCIJNwMAIAMgASgCeCIGNgKsKCABIDggAzQCrCgiCEIBfSILg0IAIAh9IgggBSkDAIOENwMAIAEgCyAogyAFKQMIIAiDhDcDCCABIAsgK4MgBSkDECAIg4Q3AxAgASALICyDIAUpAxggCIOENwMYIAEgCyAjgyAFKQMgIAiDhDcDICADIAY2AqwoIAEgEiADNAKsKCIIQgF9IguDQgAgCH0iCCAFKQMog4Q3AyggASALIA6DIAUpAzAgCIOENwMwIAEgCiALgyAFKQM4IAiDhDcDOCAAIAkgC4MgBykDACAIg4Q3AwAgASALIAyDIAUpA0ggCIOENwNIIAMgBjYCrCggASAYIAM0AqwoIghCAX0iC4MiDjcDcCABIAsgEYMiCjcDaCABIAsgE4MiDDcDYCABIAsgG4MiCTcDWCABIAsgHIMgCEIBg4QiCDcDUCABIA5CMIhC0YeAgBB+IAh8Ig1CNIggCXwiCyANhCALQjSIIAx8IgyEI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IhxC/////////weDNwM4IAVBiARqIBggIFStIBogIFatIAUpA/AFIAUpA6AFfHwgG0I0iHx8QgBCgIDEnoCAwABCABAGIAtBQGsiACAFKQOIBCIYICtC/////////weDfCIbIBwgHVStIB0gH1StIAUpA6AEIB4gH1atIAUpA+AHIBkgHlatIAUpA5AHIAUpA8AGfHx8fHx8IBdCNIh8fCIXQgyGIBxCNIiEfCIZQv////////8HgzcDACALIClC////////P4MgGSAbVK0gBSkDkAQgGCAbVq18IBdCNIh8fEIMhiAZQjSIhHw3A0ggBSACNgLoEyAFQZATaiIIIAspAyA3AwAgBUGIE2oiDCALKQMYNwMAIAVBgBNqIgogCykDEDcDACAFQfgSaiIJIAspAwg3AwAgBSALKQMANwPwEiAFQaATaiALKQMwNwMAIAVBqBNqIAspAzg3AwAgBUGwE2ogACkDADcDACAFQbgTaiALKQNINwMAIAUgCykDKDcDmBMgBUHgE2oiDiANKQNwNwMAIAVByBNqIgQgDSkDWDcDACAFQdATaiIDIA0pA2A3AwAgBUHYE2oiAiANKQNoNwMAIAUgDSkDUDcDwBMgDyAFQeAUaikDADcDICAPIAVB2BRqKQMANwMYIA8gBUHQFGopAwA3AxAgDyAFQcgUaikDADcDCCAPIAUpA8AUNwMAIAVBmBNqIRJBASENA0AgBUHwEmoiACAAIAVBmBJqIA8gDUEobGoQFiALIA1B2ABsaiIAQQA2AlAgACAFKQPwEjcDACAAIAkpAwA3AwggACAKKQMANwMQIAAgDCkDADcDGCAAIAgpAwA3AyAgACASKQMANwMoIAAgEikDCDcDMCAAIBIpAxA3AzggAEFAayASKQMYNwMAIAAgEikDIDcDSCANQQFqIg1BCEcNAAsgBUHIAGogBSkDwBMiKEIAICpCABAGIAVBmAFqIAQpAwAiJEIAIDFCABAGIAVB6AFqIAMpAwAiJkIAIDJCABAGIAVBuAJqIAIpAwAiJ0IAICxCABAGIAVBqANqIA4pAwAiJUIAIC1CABAGIAVBmANqIAUpA6gDQgBCkPqAgIACQgAQBiAFQdgAaiAoQgAg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////8HgzcDCCAFQYgBaiAoQgAgMUIAEAYgBUHYAWogJEIAIDJCABAGIAVBqAJqICZCACAsQgAQBiAFQfgCaiAnQgAgLUIAEAYgBUHoA2ogJUIAICpCABAGIAVBKGogBSkD6AMiGiAFKQP4AnwiICAdIB9UrSAeIB9WrSAFKQPgAyAZIB5WrSAFKQPwAiAFKQOgAnx8fHwgGEI0iHx8IhtCDIYgHUI0iIR8IhhCAEKQ+oCAgAJCABAGIBEgBSkD2AEiGSAFKQOIAXwiHiAFKQOoAnwiHyAFKQMofCIdICEgIlStICIgI1StIAVBQGspAwAgHCAjVq0gBSkD0AEgBSkDgAF8fHx8IBdCNIh8fCIXQgyGICFCNIiEfCIcQv////////8HgzcDECAFQRhqIBggIFStIBogIFatIAUpA/ADIAUpA4ADfHwgG0I0iHx8QgBCgIDEnoCAwABCABAGIBEgBSkDGCIYICtC/////////weDfCIbIBwgHVStIB0gH1StIAUpAzAgHiAfVq0gBSkDsAIgGSAeVq0gBSkD4AEgBSkDkAF8fHx8fHwgF0I0iHx8IhdCDIYgHEI0iIR8IhlC/////////weDNwMYIBEgKUL///////8/gyAZIBtUrSAFKQMgIBggG1atfCAXQjSIfHxCDIYgGUI0iIR8NwMgIAVB8BRqJAAjAEGQEmsiAyQAIAtB6ARqIgIgAikDKCACKQNIIhhCMIhC0YeAgBB+fCIXQv////////8HgzcDKCACIAIpAzAgF0I0iHwiF0L/////////B4M3AzAgAiACKQM4IBdCNIh8IhdC/////////weDNwM4IAJBQGsiACAAKQMAIBdCNIh8IhdC/////////weDNwMAIAIgGEL///////8/gyAXQjSIfDcDSCAPKQOYAiEsIA8pA6ACISogDykDqAIhMSAPKQOwAiEyIA8pA7gCIS1BByEJA0AgCUEHRwRAIANBgBJqIA8gCUEobGoiACkDGCIoQgAgLEIAEAYgA0GwEWogACkDECIkQgAgKkIAEAYgA0HgEGogACkDCCImQgAgMUIAEAYgA0GQEGogACkDACInQgAgMkIAEAYgA0HAD2ogACkDICIlQgAgLUIAEAYgA0GwD2ogAykDwA9CAEKQ+oCAgAJCABAGIANB8BFqICVCACAsQgAQBiADQaARaiAoQgAgKkIAEAYgA0HQEGogJEIAIDFCABAGIANBgBBqICZCACAyQgAQBiADQZAPaiAnQgAgLUIAEAYgA0GgD2ogA0HID2opAwBCAEKAgMSegIDAAEIAEAYgA0HgEWogJ0IAICxCABAGIANBkBFqICVCACAqQgAQBiADQcAQaiAoQgAgMUIAEAYgA0HwD2ogJEIAIDJCABAGIANBgA9qICZCACAtQgAQBiADQfAOaiADKQPwDyIZIAMpA8AQfCIzIAMpA4APfCIrIAMpA5ARfCIjIAMpA9AQIhggAykDoBF8IiIgAykDgBB8IiEgAykDkA98IiAgAykD8BF8Ih4gAykDoA98Ih0gAykDsBEiFyADKQOAEnwiHCADKQPgEHwiGiADKQOQEHwiGyADKQOwD3wiH0I0iCAbIB9WrSADQbgPaikDACAaIBtWrSADQZgQaikDACAaIBxUrSADQegQaikDACAXIBxWrSADQbgRaikDACADQYgSaikDAHx8fHx8fHx8IhdCDIaEfCIpQjSIIB0gKVatIB0gHlStIANBqA9qKQMAIB4gIFStIANB+BFqKQMAICAgIVStIANBmA9qKQMAICEgIlStIANBiBBqKQMAIBggIlatIANB2BBqKQMAIANBqBFqKQMAfHx8fHx8fHx8fCAXQjSIfHwiF0IMhoR8IhtCBIZC8P////////8AgyApQjCIQg+DhEIAQtGHgIAQQgAQBiADQdARaiAmQgAgLEIAEAYgA0GAEWogJ0IAICpCABAGIANBsBBqICVCACAxQgAQBiADQeAPaiAoQgAgMkIAEAYgA0HgDmogJEIAIC1CABAGIANB0A5qIAMpA+AOIhggAykD4A98Ih0gAykDsBB8IhwgGyAjVK0gIyArVK0gA0GYEWopAwAgKyAzVK0gA0GID2opAwAgGSAzVq0gA0H4D2opAwAgA0HIEGopAwB8fHx8fHwgF0I0iHx8IhdCDIYgG0I0iIR8IhpC/////////weDQgBCkPqAgIACQgAQBiADQcARaiAkQgAgLEIAEAYgA0HwEGogJkIAICpCABAGIANBoBBqICdCACAxQgAQBiADQdAPaiAlQgAgMkIAEAYgA0HADmogKEIAIC1CABAGIANBsA5qIAMpA9APIhkgAykDwA58IhsgGiAcVK0gHCAdVK0gA0G4EGopAwAgGCAdVq0gA0HoDmopAwAgA0HoD2opAwB8fHx8IBdCNIh8fCIYQgyGIBpCNIiEfCIXQgBCkPqAgIACQgAQBiADQaAOaiAXIBtUrSAZIBtWrSADQdgPaikDACADQcgOaikDAHx8IBhCNIh8fEIAQoCAxJ6AgMAAQgAQBiApQv///////z+DIAMpA6AOIhsgH0L/////////B4N8IiIgAykD8BAiGSADKQPAEXwiISADKQOgEHwiICADKQOwDnwiHiADKQOAESIYIAMpA9ARfCIfIAMpA9AOfCIaIAMpA/AOIhcgAykD4BF8Ih1CNIggFyAdVq0gA0H4DmopAwAgA0HoEWopAwB8fCIXQgyGhHwiHEI0iCAaIBxWrSAaIB9UrSADQdgOaikDACAYIB9WrSADQYgRaikDACADQdgRaikDAHx8fHwgF0I0iHx8IhdCDIaEfCIaQjSIIBogHlStIB4gIFStIANBuA5qKQMAICAgIVStIANBqBBqKQMAIBkgIVatIANB+BBqKQMAIANByBFqKQMAfHx8fHx8IBdCNIh8fCIXQgyGhHwiGEI0iCAYICJUrSADQagOaikDACAbICJWrXwgF0I0iHx8QgyGhHwhLSAYQv////////8HgyEyIBpC/////////weDITEgHUL/////////B4MhLCAcQv////////8HgyEqCyADQYAOaiAsQgGGIiBCACAyQgAQBiADQbANaiAqQgGGIhdCACAxQgAQBiADQfAMaiAtQgAgLUIAEAYgA0HgDGogAykD8AxCAEKQ+oCAgAJCABAGIANBwAxqICxCACAtQgGGIiJCABAGIANB4A1qIBdCACAyQgAQBiADQaANaiAxQgAgMUIAEAYgA0HQDGogA0H4DGopAwBCAEKAgMSegIDAAEIAEAYgA0GQDmogLEIAICxCABAGIANBsAxqICpCACAiQgAQBiADQYANaiAxQgGGQgAgMkIAEAYgA0GgDGogAykDsAwiGSADKQOADXwiHiADKQPQDCIYIAMpA6ANfCIdIAMpA+ANfCIcIAMpA8AMfCIaIAMpA7ANIhcgAykD4Ax8IhsgAykDgA58Ih9CNIggGyAfVq0gA0GIDmopAwAgFyAbVq0gA0G4DWopAwAgA0HoDGopAwB8fHx8IhdCDIaEfCIhQjSIIBogIVatIBogHFStIANByAxqKQMAIBwgHVStIANB6A1qKQMAIBggHVatIANB2AxqKQMAIANBqA1qKQMAfHx8fHx8IBdCNIh8fCIXQgyGhHwiG0IEhkLw/////////wCDICFCMIhCD4OEQgBC0YeAgBBCABAGIANB0A1qICBCACAqQgAQBiADQfAKaiAxQgAgIkIAEAYgA0HwDWogMkIAIDJCABAGIANB4ApqIAMpA/AKIhggAykD8A18IhogGyAeVK0gGSAeVq0gA0G4DGopAwAgA0GIDWopAwB8fCAXQjSIfHwiF0IMhiAbQjSIhHwiG0L/////////B4NCAEKQ+oCAgAJCABAGIANBkA1qICBCACAxQgAQBiADQcANaiAqQgAgKkIAEAYgA0GwCWogIkIAIDJCABAGIANBoAlqIBogG1atIBggGlatIANB+ApqKQMAIANB+A1qKQMAfHwgF0I0iHx8IhlCDIYgG0I0iIQiGCADKQOwCXwiF0IAQpD6gICAAkIAEAYgA0HwB2ogFyAYVK0gA0G4CWopAwAgGUI0iHx8QgBCgIDEnoCAwABCABAGIANBkAxqIAMpA6AMIhcgAykDkA58IhlC/////////weDIjRCACAyQgAQBiADQdAKaiADKQPgCiIYIAMpA9ANfCIaIBcgGVatIANBqAxqKQMAIANBmA5qKQMAfHwiF0IMhiAZQjSIhHwiG0L/////////B4MiNUIAIDFCABAGIANBkAlqIAMpA5ANIhkgAykDwA18Ih0gAykDoAl8IhwgGiAbVq0gGCAaVq0gA0HoCmopAwAgA0HYDWopAwB8fCAXQjSIfHwiF0IMhiAbQjSIhHwiGkL/////////B4MiLkIAICpCABAGIANB4AdqIAMpA/AHIhggH0L+////////B4N8IhsgGiAcVK0gHCAdVK0gA0GoCWopAwAgGSAdVq0gA0GYDWopAwAgA0HIDWopA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hggK0L/////////B4N8IhsgHCAdVK0gHSAfVK0gAykDqAQgHiAfVq0gA0GICGopAwAgGSAeVq0gA0HICWopAwAgA0GIC2opAwB8fHx8fHwgF0I0iHx8IhdCDIYgHEI0iIR8IhlC/////////weDNwMYIAIgJUL///////8/gyAZIBtUrSADKQOYBCAYIBtWrXwgF0I0iHx8QgyGIBlCNIiEfDcDICADQfADaiADKQOwBSIbIClC/////////weDfCIiIAMpA5AKIhkgAykD0At8IiEgAykD0Ah8IiAgAykDwAV8Ih4gAykDoAoiGCADKQPgC3wiHyADKQPgBXwiGiADKQOABCIXIAMpA/ALfCIdQjSIIBcgHVatIAMpA4gEIANB+AtqKQMAfHwiF0IMhoR8IhxCNIggGiAcVq0gGiAfVK0gAykD6AUgGCAfVq0gA0GoCmopAwAgA0HoC2opAwB8fHx8IBdCNIh8fCIXQgyGhHwiGkI0iCAaIB5UrSAeICBUrSADKQPIBSAgICFUrSADQdgIaikDACAZICFWrSADQZgKaikDACADQdgLaikDAHx8fHx8fCAXQjSIfHwiF0IMhoR8IhhC/////////weDIi5CACACKQMoIi9CABAGIANBoANqIBpC/////////weDIjBCACACKQMwIjZCABAGIANB0AJqIBxC/////////weDIjdCACACKQM4IihCABAGIANBgAJqIB1C/////////weDIiRCACACQUBrIgApAwAiJkIAEAYgA0GwAWogJ0L///////8/gyAYICJUrSADKQO4BSAbICJWrXwgF0I0iHx8QgyGIBhCNIiEfCInQgAgAikDSCIlQgAQBiADQaABaiADKQOwAUIAQpD6gICAAkIAEAYgA0GAAWogJ0IAIC9CABAGIANB4ANqIC5CACA2QgAQBiADQZADaiAwQgAgKEIAEAYgA0HAAmogN0IAICZCABAGIANB8AFqICRCACAlQgAQBiADQZABaiADKQO4AUIAQoCAxJ6AgMAAQgAQBiADQeABaiAkQgAgL0IAEAYgA0HwAGogJ0IAIDZCABAGIANB0ANqIC5CACAoQgAQBiADQYADaiAwQgAgJkIAEAYgA0GwAmogN0IAICVCABAGIANBEGogAykDgAMiGyADKQ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nwiHyADKQMwfCIdICEgIlStICIgI1StIAMpA1ggHCAjVq0gAykDqAIgAykD2AF8fHx8IBdCNIh8fCIXQgyGICFCNIiEfCIcQv////////8HgzcDOCADQSBqIBggIFStIBogIFatIAMpA0ggAykDuAN8fCAbQjSIfHxCAEKAgMSegIDAAEIAEAYgACADKQMgIhggK0L/////////B4N8IhsgHCAdVK0gHSAfVK0gAykDOCAeIB9WrSADKQPoAiAZIB5WrSADKQOYAiADKQPIAXx8fHx8fCAXQjSIfHwiF0IMhiAcQjSIhHwiGUL/////////B4M3AwAgAiApQv///////z+DIBkgG1StIAMpAyggGCAbVq18IBdCNIh8fEIMhiAZQjSIhHw3A0ggCQ0ACyADQZASaiQAIA8gC0GokwIQCiAHQegRaiAHQdgMakGokwIQCiAHQZASaiAHQbANakGokwIQCiAHQbgSaiAHQYgOakGokwIQCiAHQeASaiAHQeAOakGokwIQCiAHQYgTaiAHQbgPakGokwIQCiAHQbATaiAHQZAQakGokwIQCiAHQdgTaiAHQegQakGokwIQCkEBIQQgFCATIBMgFEgbIgBBACAAQQBKGwshAgJAIBBFBEBBACEJDAELIAcgECkDADcDwBwgECkDCCEXIAdB2BxqQgA3AwAgB0IANwPQHCAHIBc3A8gcIAcgECkDEDcDoBwgECkDGCEXIAdBuBxqQgA3AwAgB0IANwOwHCAHIBc3A6gcIAdBkBhqIAdBwBxqQQQQESEJIAdBgBRqIAdBoBxqQQQQESIVIAkgAiACIAlIGyIAIAAgFUgbIQILIAFBATYCeCABQQBB+AAQCCEKAkAgAkUNACAHQbAdaiEOA0AgAiEAAkAgCigCeARAIApBATYCeCAKQQBB+AAQCBoMAQsgCiAKEBILIABBAWshAgJAIARFDQACQCAAIBRKDQAgB0HwA2ogAkECdGooAgAiAUUNAAJAIAFBAEoEQCAHQYgdaiAHQYAMaiABQQFrQQF2QdgAbGpB2AAQCRoMAQsgB0GIHWogB0GADGogAUF/c0EBdkHYAGxqQdgAEAkaIAdCvOH//7///x8gBykDsB19NwOwHSAHQvz///////8fIAcpA7gdfTcDuB0gB0L8////////HyAHKQPAHX03A8AdIAdC/P///////x8gBykDyB19NwPIHSAHQvz///////8BIAcpA9AdfTcD0B0LIAogCiAHQYgdakEAEBYLIAAgE0oNACACQQJ0IAdqKAL0ByIBRQ0AIAdBADYC2B0CQCABQQBKBEAgB0GoHWogB0HAEWogAUEBa0EBdiIBQShsaiIDKQMgNwMAIAdBoB1qIAMpAxg3AwAgB0GYHWogAykDEDcDACAHQZAdaiADKQMINwMAIAcgAykDADcDiB0gDiAHQYAMaiABQdgAbGoiASkDSDcDICAOIAFBQGspAwA3AxggDiABKQM4NwMQIA4gASkDMDcDCCAOIAEpAyg3AwAMAQsgB0GoHWogB0HAEWogAUF/c0EBdiIBQShsaiIDKQMgNwMAIAdBoB1qIAMpAxg3AwAgB0GYHWogAykDEDcDACAHQZAdaiADKQMINwMAIAcgAykDADcDiB0gDiAHQYAMaiABQdgAbGoiASkDSDcDICAOIAFBQGspAwA3AxggDiABKQM4NwMQIA4gASkDMDcDCCAOIAEpAyg3AwAgB0K84f//v///HyAHKQOwHX03A7AdIAdC/P///////x8gBykDuB19NwO4HSAHQvz///////8fIAcpA8AdfTcDwB0gB0L8////////HyAHKQPIHX03A8gdIAdC/P///////wEgBykD0B19NwPQHQsgCiAKIAdBiB1qQQAQFgsCQCAAIAlKDQAgB0GQGGogAkECdGooAgAiA0UNACAHQYgdaiIBQYAIIAMQIyAKIAogASAHQeAcahAiCwJAIAAgFUoNACAHQYAUaiACQQJ0aigCACIDRQ0AIAdBiB1qIgFBgAogAxAjIAogCiABIAdB4BxqECILIABBAUsNAAsgCigCeA0AIAdBQGsgBykD+BwiLkIAIAopA1AiL0IAEAYgB0GQAWogBykD8BwiMEIAIAopA1giNkIAEAYgB0HgAWogBykD6BwiN0IAIAopA2AiKEIAEAYgB0GwAmogBykD4BwiJEIAIAopA2giJkIAEAYgB0GgA2ogBykDgB0iJ0IAIAopA3AiJUIAEAYgB0GQA2ogBykDoANCAEKQ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x8IhdCDIYgGkI0iIR8IiFC/////////weDNwNYIAdB0AFqIDBCACAvQgAQBiAHQaACaiA3QgAgNkIAEAYgB0HwAmogJEIAIChCABAGIAdB4ANqICdCACAmQgAQBiAHQYABaiAuQgAgJUIAEAYgB0EgaiAHKQPgAyIaIAcpA4ABfCIgIB0gH1StIB4gH1atIAcpA9gDIBkgHlatIAcpA8gBIAcpA3h8fHx8IBhCNIh8fCIbQgyGIB1CNIiEfCIYQgBCkPqAgIACQgAQBiAKIAcpA6ACIhkgBykD0AF8Ih4gBykD8AJ8Ih8gBykDIHwiHSAhICJUrSAiICNUrSAHKQM4IBwgI1atIAcpA+gCIAcpA5gCfHx8fCAXQjSIfHwiF0IMhiAhQjSIhHwiHEL/////////B4M3A2AgB0EQaiAYICBUrSAaICBWrSAHKQPoAyAHKQOIAXx8IBtCNIh8fEIAQoCAxJ6AgMAAQgAQBiAKIAcpAxAiGCArQv////////8Hg3wiGyAcIB1UrSAdIB9UrSAHKQMoIB4gH1atIAcpA/gCIBkgHlatIAcpA6gCIAcpA9gBfHx8fHx8IBdCNIh8fCIXQgyGIBxCNIiEfCIZQv////////8HgzcDaCAKIClC////////P4MgGSAbVK0gBykDGCAYIBtWrXwgF0I0iHx8QgyGIBlCNIiEfDcDcAsgB0HgHWokACAGKAL4EA0AIwBBMGsiDCQAIAZB0BBqIgkpAwggCSkDACAJKQMgIhlCMIhC0YeAgBB+fCIYQjSIfCIaQv////////8HgyEdIAkpAxggCSkDECAaQjSIfCIXQjSIfCIbQv////////8HgyEcIBlC////////P4MgG0I0iHwiH0IwiCAbIBogF0L/////////B4MiGYODQv////////8HUSAfQv///////z9RcSAYQv////////8HgyIYQq74///v//8HVnGthKcEQCAYQtGHgIAQfCIXQv////////8HgyEYIB0gF0I0iHwiF0L/////////B4MhHSAZIBdCNIh8IhdC/////////weDIRkgHCAXQjSIfCIXQv////////8HgyEcIBdCNIggH3xC////////P4MhHwsgDCAfQiiINwMoIAwgH0IWhkKAgID+/////z+D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SIfHxCDIaEfCAGKQP4Dn1C/P///////wF8IhdCMIhC0YeAgBB+fEK84f//v///H3wiGkI0iHxC/P///////x98IhsgGoQgHEL/////////B4MgBikD6A59IBtCNIh8Qvz///////8ffCIZhCAYQv////////8HgyAGKQPwDn0gGUI0iHxC/P///////x98IhiEQv////////8HgyAXQv///////z+DIBhCNIh8IheEUAR/QQEFIBpC0IeAgBCFIBdCgICAgICAwAeFgyAbgyAZgyAYg0L/////////B1ELIRYLIAZB4BFqJAAgFgu1FgIDfwt+IwBBoARrIgUkACAFQgA3A1ggBUIANwNQIAVCADcDSCAFQgA3A0ACQCAAKAIARQRAQfOOAiAAKAKsASAAKAKoAREAAEEAIQMMAQsgAUUEQEGYjgIgACgCrAEgACgCqAERAABBACEDDAELIAJFBEBB2I4CIAAoAqwBIAAoAqgBEQAAQQAhAwwBCyADRQRAQYiOAiAAKAKsASAAKAKoAREAAEEAIQMMAQsCQAJAAkAgAykAOCIIQhCIIg0gAykAKCIKQgyGQoDg//////8HgyADKQAgIglCNIiEIgsgCUL/////////B4MiD4SEIAMpADAiCUIYhkKAgID4////B4MgCkIoiIQiEIQgCEIkhkKAgICAgP7/B4MgCUIciIQiEYRQBEBBr48CIAAoAqwBIAAoAqgBEQAADAELIAMpAEAhDiAFQfgCaiADIAVBuAFqEBAgBSgCuAFFBEAgBSkDkAMiCSAFKQOIAyIIIAUpA4ADIgogBSkD+AIiDISEhEIAUg0CC0HgjAIgACgCrAEgACgCqAERAAALQQAhAyAFQdCQAikDADcDkAMgBUHIkAIpAwA3A4gDIAVBwJACKQMANwOAAyAFQbiQAikDADcD+AJC3PP7s+a3HiENQtzSmNDV2O4FIRFC/LeKuLDhoQchEEKfq7aUztvsBiELQpiv4Lexq6ABIQ9CACEKQgAhCEIAIQkMAQtBASEDIA5CAYNQDQAgBSAMQn+FIg5Cvv2m/rKu6JbAAH0iDDcD+AIgBSAKQn+FIhIgDCAOVK18Ig5Cxb/dhZXjyKjFAH0iCjcDgAMgBSAI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Ig2EhIRQGyIDQQFzIgQ2ArgBIAUgCiAFNAK4ASIOQgF9IgiDIg83A9ACIAUgCCALgyIQNwPIAiAFIAggCYMiETcDwAIgBSAIIA2DIA5CAYOEIgo3A7gCIAAgBUG4AWoiACAHECYgBUHgAGogABAlIAUpA5ABIAUpA4gBIAUpA6gBIg5CMIhC0YeAgBB+fCIMQjSIfCIIQv////////8HgyENIAUpA6ABIAUpA5gBIAhCNIh8IhJCNIh8IgtC/////////weDIQkgBSAOQv///////z+DIAtCNIh8Ig5CMIggCyAIIBJC/////////weDIgiDg0L/////////B1EgDkL///////8/UXEgDEL/////////B4MiC0Ku+P//7///B1ZxrYSnBH4gC0LRh4CAEHwiDEL/////////B4MhCyANIAxCNIh8IgxC/////////weDIQ0gCCAMQjSIfCIMQv////////8HgyEIIAkgDEI0iHwiDEL/////////B4MhCSAMQjSIIA58Qv///////z+DBSAOCzcDqAEgBSAJNwOgASAFIAg3A5gBIAUgDTcDkAEgBSALNwOIASALQgGDpwRAQn9CACAQIBGEIA+EIAqEQgBSGyIIIBBCf4UiCyARQn+FIgkgCkJ/hSIKQr79pv6yruiWwAB9Ig0gClStfCIKIAlUrSAKQsW/3YWV48ioxQB9IgkgClStfHwiCiALVK0gCiAKQgJ9IgtWrXwgD31CAn2DIQ8gCCALgyEQIAggCYMhESAIIA2DIQoLIAUpA2ggBSkDYCAFKQOAASIOQjCIQtGHgIAQfnwiDEI0iHwiCEL/////////B4MhCyAFKQN4IAUpA3AgCEI0iHwiEkI0iHwiCUL/////////B4MhDSAFIA5C////////P4MgCUI0iHwiDkIwiCAJIAggEkL/////////B4MiCIODQv////////8HUSAOQv///////z9RcSAMQv////////8HgyIJQq74///v//8HVnGthKcEfiAJQtGHgIAQfCIMQv////////8HgyEJIAsgDEI0iHwiDEL/////////B4MhCyAIIAxCNIh8IgxC/////////weDIQggDSAMQjSIfCIMQv////////8HgyENIAxCNIggDnxC////////P4MFIA4LNwOAASAFIA03A3ggBSAINwNwIAUgCzcDa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ALQjSIhCIJNwM4QQAhAyAEQQA2AlggBCALQv////////8HgyIPNwMwIAQgB0IMhkKA4P//////B4MgCEI0iIQiEDcDECAEIAhC/////////weDIgg3AwggBCANQhCIIhE3AyggBCAGQhiGQoCAgPj///8HgyAHQiiIhCIHNwMYIAQgDUIkhkKAgICAgP7/B4MgBkIciIQiBjcDICAIIBCEIBGEIAeEIAaEUARAQa+PAiAAKAKsASAAKAKoAREAAEEADAELIAtCAYOnBEAgBEL8////////ASAOfTcDUCAEQvz///////8fIAx9NwNIIARC/P///////x8gCn03A0AgBEL8////////HyAJfTcDOCAEQrzh//+///8fIA99NwMwQQEhAwsgAgRAIAIgAzYCAAsgASAEQQhqEBRBAQshBSAEQeAAaiQAIAULmQMCBX8GfiMAQYACayIDJAACQCABRQRAQYiOAiAAKAKsASAAKAKoAREAAAwBCyABQQBB4AAQCCEFIAAoAgBFBEBB844CIAAoAqwBIAAoAqgBEQAADAELIAJFBEBBpo4CIAAoAqwBIAAoAqgBEQAADAELIANB4ABqIgYgAiADQYABaiIHEBAgAyADKAKAAUUgAykDeCIJIAMpA3AiCiADKQNoIgsgAykDYCIMhISEQgBScSIERSICNgKAASADIAkgAzQCgAEiDUIBfSIIgzcDeCADIAggCoM3A3AgAyAIIAuDNwNoIAMgCCAMgyANQgGDhDcDYCAAIAcgBhAmIANBCGoiACAHECUgBSAGECcgBUEgaiAAEBQgAyACNgKAASADKAKAAUEBayEAQeAAIQIDQCABIAEtAAAgAHE6AAAgASABLQABIABxOgABIAEgAS0AAiAAcToAAiABIAEtAAMgAHE6AAMgASABLQAEIABxOgAEIAEgAS0ABSAAcToABSABQQZqIQEgAkEGayICDQALCyADQYACaiQAIAQLywMCAX8IfiMAQeAAayIDJAACQCABRQRAQbeOAiAAKAKsASAAKAKoAREAAEEAIQIMAQsgAUIANwAAIAFCADcAGCABQgA3ABAgAUIANwAIIAJFBEBB+Y0CIAAoAqwBIAAoAqgBEQAAQQAhAgwBCyACKQAQIQQgAikAGCEJIAIpAAghBSACKQAAIQYgAikAICEHIAIpACghCCACKQAwIQogAyACKQA4IgtCEIg3A1AgAyALQiSGQoCAgICA/v8HgyAKQhyIhDcDSCADQUBrIApCGIZCgICA+P///weDIAhCKIiENwMAIAMgCEIMhkKA4P//////B4MgB0I0iIQ3AzhBACECIANBADYCWCADIAdC/////////weDNwMwIAMgBUIMhkKA4P//////B4MgBkI0iIQiBzcDECADIAZC/////////weDIgY3AwggAyAJQhCIIgg3AyggAyAEQhiGQoCAgPj///8HgyAFQiiIhCIFNwMYIAMgCUIkhkKAgICAgP7/B4MgBEIciIQiBDcDICAGIAeEIAiEIAWEIASEUARAQa+PAiAAKAKsASAAKAKoAREAAAwBCyABIANBCGoQGEEBIQILIANB4ABqJAAgAgumzAICBn8zfiMAQYABayIGJAACfyABRQRAQfmNAiAAKAKsASAAKAKoAREAAEEADAELIAFCADcAACABQgA3ADggAUIANwAwIAFCADcAKCABQgA3ACAgAUIANwAYIAFCADcAECABQgA3AAggAkUEQEHIjgIgACgCrAEgACgCqAERAABBAAwBCyAGIAIQGQJAIAYpAwBCr/j//+///wdUDQAgBikDIEL///////8/Ug0AQQAgBikDCCAGKQMQIAYpAxiDg0L/////////B1ENARoLQQAhAiMAQfAGayIEJAAgBkEoaiIFIAYpAwA3AwAgBSAGKQMgNwMgIAUgBikDGDcDGCAFIAYpAxA3AxAgBSAGKQMINwMIIARB2ARqIAYpAxgiIEIAIAYpAwAiIkIBhiIUQgAQBiAEQZgFaiAGKQMQIh9CACAGKQMIIiFCAYYiCUIAEAYgBEGYBmogBikDICIjQgAgI0IAEAYgBEGIBmogBCkDmAZCAEKQ+oCAgAJCABAGIARB+ARqICNCAYYiFUIAICJCABAGIARBiAVqICBCACAJQgAQBiAEQdgFaiAfQgAgH0IAEAYgBEH4BWogBCkDoAZCAEKAgMSegIDAAEIAEAYgBEHoBGogIkIAICJCABAGIARBuAVqIBVCACAhQgAQBiAEQegFaiAgQgAgH0IBhkIAEAYgBEGYBGogBCkDuA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ogJUIAICVCABAGIANB4NoAaiADQYjbAGopAwBCAEKAgMSegIDAAEIAEAYgA0Gg3ABqIClCACApQgAQBiADQcDaAGogFUIAICZCABAGIANBoNsAaiAkQgAgJUIBhkIAEAYgA0Gw2gBqIAMpA8BaIg0gAykDoFt8IhEgAykDsFsiCiADKQPgW3wiDCADKQPQWnwiDyADKQPgWnwiDiADKQPAWyIJIAMpA/BbfCILIAMpA/BafCIQQjSIIAsgEFatIANB+NoAaikDACAJIAtWrSADQcjbAGopAwAgA0H42wBqKQMAfHx8fCIJQgyGhHwiE0I0iCAOIBNWrSAOIA9UrSADQejaAGopAwAgDCAPVq0gA0HY2gBqKQMAIAogDFatIANBuNsAaikDACADQejbAGopAwB8fHx8fHwgCUI0iHx8IglCDIaEfCILQgSGQvD/////////AIMgE0IwiEIPg4RCAELRh4CAEEIAEAYgA0GQ3ABqICZCACAUQgAQBiADQdDZAGogFUIAICVCABAGIANBkNsAaiAkQgAgJEIAEAYgA0HA2QBqIAMpA9BZIgogAykDkFt8Ig4gCyARVK0gDSARVq0gA0HI2gBqKQMAIANBqNsAaikDAHx8IAlCNIh8fCIJQgyGIAtCNIiEfCILQv////////8Hg0IAQpD6gICAAkIAEAYgA0HQ2wBqICVCACAUQgAQBiADQYDcAGogJkIAICZCABAGIANB4NgAaiAVQgAgJEIAEAYgA0HQ2ABqIAsgDlStIAogDlatIANB2NkAaikDACADQZjbAGopAwB8fCAJQjSIfHwiDUIMhiALQjSIhCIKIAMpA+BYfCIJQgBCkPqAgIACQgAQBiADQfDXAGogCSAKVK0gA0Ho2ABqKQMAIA1CNIh8fEIAQoCAxJ6AgMAAQgAQBiADQaDaAGogAykDsFoiCSADKQOgXHwiDUL/////////B4MiHkIAICRCABAGIANBsNkAaiADKQPAWSIKIAMpA5BcfCIOIAkgDVatIANBuNoAaikDACADQajcAGopAwB8fCIJQgyGIA1CNIiEfCILQv////////8HgyIdQgAgJUIAEAYgA0HA2ABqIAMpA9BbIg0gAykDgFx8Igwg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IAlCNIh8fCIKQgyGhHwiDUL/////////B4MiJ0IAIBVCAYZC/v///////w+DIhRCABAGIANB8NQAaiAOQv////////8HgyIqQgAgFkIBhkL+////////D4MiCUIAEAYgA0HA1ABqIBxC////////P4MgDSATVK0gA0GI1gBqKQMAIAsgE1atfCAKQjSIfHxCDIYgDUI0iIR8IjFCACAxQgAQBiADQbDUAGogAykDwFRCAEKQ+oCAgAJCABAGIANBkNQAaiAVQv////////8HgyIyQgAgMUIBhiIVQgAQBiADQeDUAGogJ0IAIAlCABAGIANB0NUAaiAqQgAgKkIAEAYgA0Gg1ABqIANByNQAaikDAEIAQoCAxJ6AgMAAQgAQBiADQbDVAGogMkIAIDJCABAGIANBgNQAaiAWQv////////8HgyIwQgAgFUIAEAYgA0HQ1ABqICdCACAOQgGGQv7///////8Pg0IAEAYgA0Gg0wBqIAMpA4BUIg0gAykD0FR8IhEgAykD4FQiCiADKQPQVXwiDCADKQOQVHwiDyADKQOgVHwiDiADKQOgVSIJIAMpA/BUfCILIAMpA7BUfCIQQjSIIAsgEFatIANBuNQAaikDACAJIAtWrSADQajVAGopAwAgA0H41ABqKQMAfHx8fCIJQgyGhHwiE0I0iCAOIBNWrSAOIA9UrSADQajUAGopAwAgDCAPVq0gA0GY1ABqKQMAIAogDFatIANB6NQAaikDACADQdjVAGopAwB8fHx8fHwgCUI0iHx8IglCDIaEfCILQgSGQvD/////////AIMgE0IwiEIPg4RCAELRh4CAEEIAEAYgA0GQ1QBqIDBCACAUQgAQBiADQfDTAGogKkIAIBVCABAGIANB4NUAaiAnQgAgJ0IAEAYgA0Hg0wBqIAMpA/BTIgogAykD4FV8Ig4gCyARVK0gDSARVq0gA0GI1ABqKQMAIANB2NQAaikDAHx8IAlCNIh8fCIJQgyGIAtCNIiEfCILQv////////8Hg0IAQpD6gICAAkIAEAYgA0GA1QBqICpCACAUQgAQBiADQcDVAGogMEIAIDBCABAGIANB0NMAaiAnQgAgFUIAEAYgA0HA0wBqIAsgDlStIAogDlatIAN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ITIAMpA4BSfCIUIAMpA9BPfCIRIAMpA8BRIgogAykD8FB8IgwgAykD8E98IgsgAykDsE8iCSADKQOAUXwiD0I0iCAJIA9WrSADQbjPAGopAwAgA0GI0QBqKQMAfHwiCUIMhoR8Ig5CNIggCyAOVq0gCyAMVK0gA0H4zwBqKQMAIAogDFatIANByNEAaikDACADQfjQAGopAwB8fHx8IAlCNIh8fCIJQgyGhHwiC0I0iCALIBFUrSARIBRUrSADQdjPAGopAwAgEyAUVq0gA0GI0gBqKQMAIA0gE1atIANBuNEAaikDACADQejQAGopAwB8fHx8fHwgCUI0iHx8IgxCDIaEfCIcIRIgCyENIA4hCiAPIQkgG0L///////8/gyAVIBxWrSADQcjPAGopAwAgECAVVq18IAxCNIh8fEIMhiAcQjSIhHwiKCEYA0AgA0HAzgBqIAlC/////////weDIgxCAYYiFkIAIBJC/////////weDIhpCABAGIANB8M4AaiAKQv////////8HgyIbQgGGIglCACANQv////////8HgyIZQgAQBiADQYDOAGogGEIAIBhCABAGIANB8M0AaiADKQOATkIAQpD6gICAAkIAEAYgA0HQzQBqIAxCACAYQgGGIhdCABAGIANB4M4AaiAJQgAgGkIAEAYgA0GQzwBqIBlCACAZQgAQBiADQeDNAGogA0GIzgBqKQMAQgBCgIDEnoCAwABCABAGIANBkM4AaiAMQgAgDEIAEAYgA0HAzQBqIBtCACAXQgAQBiADQYDPAGogGUIBhkIAIBpCABAGIANBsM0AaiADKQPATSINIAMpA4BPfCIVIAMpA5BPIgogAykD4E18IhMgAykD4E58IhEgAykD0E18IhAgAykD8E4iCSADKQPwTXwiDCADKQPATnwiFEI0iCAMIBRWrSADQcjOAGopAwAgCSAMVq0gA0H4zgBqKQMAIANB+M0AaikDAHx8fHwiCUIMhoR8IhJCNIggECASVq0gECARVK0gA0HYzQBqKQMAIBEgE1StIANB6M4AaikDACAKIBNWrSADQZjPAGopAwAgA0HozQBqKQMAfHx8fHx8IAlCNIh8fCIJQgyGhHwiDEIEhkLw/////////wCDIBJCMIhCD4OEQgBC0YeAgBBCABAGIANBsM4AaiAWQgAgG0IAEAYgA0GgzQBqIBlCACAXQgAQBiADQaDPAGogGkIAIBpCABAGIANBkM0AaiADKQOgTSIKIAMpA6BPfCIQIAwgFVStIA0gFVatIANByM0AaikDACADQYjPAGopAwB8fCAJQjSIfHwiCUIMhiAMQjSIhHwiDEL/////////B4NCAEKQ+oCAgAJCABAGIANBoM4AaiAWQgAgGUIAEAYgA0HQzgBqIBtCACAbQgAQBiADQYDNAGogGkIAIBdCABAGIANB8MwAaiAMIBBUrSAKIBBWrSADQajNAGopAwAgA0GozwBqKQMAfHwgCUI0iHx8Ig1CDIYgDEI0iIQiCiADKQOATXwiCUIAQpD6gICAAkIAEAYgA0HgzABqIAkgClStIANBiM0AaikDACANQjSIfHxCAEKAgMSegIDAAEIAEAYgEkL///////8/gyADKQPgTCIRIBRC/v///////weDfCIWIAMpA6BOIhAgAykD0E58IhUgAykD8Ex8IhMgAykDkE0iDCADKQOwTnwiFCADKQOwTSIKIAMpA5BOfCIJQjSIIAkgClStIANBuM0AaikDACADQZjOAGopAwB8fCINQgyGhHwiCkI0iCAKIBRUrSAMIBRWrSADQZjNAGopAwAgA0G4zgBqKQMAfHwgDUI0iHx8IgxCDIaEfCINQjSIIA0gE1StIBMgFVStIANB+MwAaikDACAQIBVWrSADQajOAGopAwAgA0HYzgBqKQMAfHx8fCAMQjSIfHwiDEIMhoR8IhJCNIggEiAWVK0gA0HozABqKQMAIBEgFlatfCAMQjSIfHxCDIaEfCEYIAJBAWoiAkEDRw0ACyADQdDMAGogCUL/////////B4MiHUIAIBxC/////////weDIitCABAGIANBsMwAaiAKQv////////8HgyIaQgAgC0L/////////B4MiLEIAEAYgA0HwywBqIA1C/////////weDIhlCACAOQv////////8HgyItQgAQBiADQZDLAGogEkL/////////B4MiG0IAIA9C/////////weDIi5CABAGIANBkMoAaiAYQgAgKEIAEAYgA0GAygBqIAMpA5BKQgBCkPqAgIACQgAQBiADQeDJAGogHUIAIChCABAGIANBwMwAaiAaQgAgK0IAEAYgA0GQzABqIBlCACAsQgAQBiADQcDLAGogG0IAIC1CABAGIANB0MoAaiAuQgAgGEIAEAYgA0HwyQBqIANBmMoAaikDAEIAQoCAxJ6AgMAAQgAQBiADQYDLAGogHUIAIC5CABAGIANB0MkAaiAaQgAgKEIAEAYgA0GAzABqIBlCACArQgAQBiADQbDLAGogG0IAICxCABAGIANBwMoAaiAtQgAgGEIAEAYgA0HAyQBqIAMpA7BLIg0gAykDwEp8IhcgAykDgEx8IhIgAykD0El8IhYgAykDwEsiCiADKQPQSnwiFSADKQPwSXwiEyADKQOQTHwiFCADKQPATHwiESADKQPgSXwiDCADKQOASiIJIAMpA5BLfCIPIAMpA/BLfCIOIAMpA7BMfCILIAMpA9BMfCIQQjSIIAsgEFatIANB2MwAaikDACALIA5UrSADQbjMAGopAwAgDiAPVK0gA0H4ywBqKQMAIAkgD1atIANBiMoAaikDACADQZjLAGopAwB8fHx8fHx8fCIJQgyGhHwiHEI0iCAMIBxWrSAMIBFUrSADQejJAGopAwAgESAUVK0gA0HIzABqKQMAIBMgFFatIANBmMwAaikDACATIBVUrSADQfjJAGopAwAgCiAVVq0gA0HIywBqKQMAIANB2MoAaikDAHx8fHx8fHx8fHwgCUI0iHx8IglCDIaEfCILQgSGQvD/////////AIMgHEIwiEIPg4RCAELRh4CAEEIAEAYgA0HgywBqIB1CACAtQgAQBiADQfDKAGogGkIAIC5CABAGIANBsMkAaiAZQgAgKEIAEAYgA0GgywBqIBtCACArQgAQBiADQbDKAGogLEIAIBhCABAGIANBoMkAaiADKQOgSyIKIAMpA7BKfCIMIAMpA7BJfCIPIAsgFlStIBIgFlatIANB2MkAaikDACASIBdUrSADQYjMAGopAwAgDSAXVq0gA0G4ywBqKQMAIANByMoAaikDAHx8fHx8fCAJQjSIfHwiCUIMhiALQjSIhHwiDkL/////////B4NCAEKQ+oCAgAJCABAGIANBoMwAaiAdQgAgLEIAEAYgA0HQywBqIBpCACAtQgAQBiADQeDKAGogGUIAIC5CABAGIANBkMkAaiAbQgAgKEIAEAYgA0GgygBqICtCACAYQgAQBiADQYDJAGogAykDkEkiDSADKQOgSnwiCyAOIA9UrSAMIA9WrSADQbjJAGopAwAgCiAMVq0gA0GoywBqKQMAIANBuMoAaikDAHx8fHwgCUI0iHx8IgpCDIYgDkI0iIR8IglCAEKQ+oCAgAJCABAGIANB8MgAaiAJIAtUrSALIA1UrSADQZjJAGopAwAgA0GoygBqKQMAfHwgCkI0iHx8QgBCgIDEnoCAwABCABAGIBxC////////P4MgAykD8EgiDiAQQv////////8Hg3wiEyADKQPQSyILIAMpA+BKfCIUIAMpA6BMfCIRIAMpA4BJfCIQIAMpA+BLIgogAykD8Ep8IgwgAykDoEl8Ig8gAykDwEkiCSADKQOAS3wiEkI0iCAJIBJWrSADQcjJAGopAwAgA0GIywBqKQMAfHwiCUIMhoR8Ig1CNIggDSAPVK0gDCAPVq0gA0GoyQBqKQMAIAogDFatIANB6MsAaikDACADQfjKAGopAwB8fHx8IAlCNIh8fCIKQgyGhHwiCUI0iCAJIBBUrSAQIBFUrSADQYjJAGopAwAgESAUVK0gA0GozABqKQMAIAsgFFatIANB2MsAaikDACADQejKAGopAwB8fHx8fHwgCkI0iHx8IgtCDIaEfCIKQjSIIAogE1StIANB+MgAaikDACAOIBNWrXwgC0I0iHx8QgyGhHwhGEEAIQIDQCADQYDIAGogEkL/////////B4MiC0IBhiIUQgAgCkL/////////B4MiF0IAEAYgA0GwyABqIA1C/////////weDIhZCAYYiCkIAIAlC/////////weDIhJCABAGIANBwMcAaiAYQgAgGEIAEAYgA0GwxwBqIAMpA8BHQgBCkPqAgIACQgAQBiADQZDHAGogC0IAIBhCAYYiFUIAEAYgA0GgyABqIApCACAXQgAQBiADQdDIAGogEkIAIBJCABAGIANBoMcAaiADQcjHAGopAwBCAEKAgMSegIDAAEIAEAYgA0HQxwBqIAtCACALQgAQBiADQYDHAGogFkIAIBVCABAGIANBwMgAaiASQgGGQgAgF0IAEAYgA0HwxgBqIAMpA4BHIg0gAykDwEh8IhEgAykD0EgiCiADKQOgR3wiECADKQOgSHwiDCADKQOQR3wiDiADKQOwSCIJIAMpA7BHfCILIAMpA4BIfCIPQjSIIAsgD1atIANBiMgAaikDACAJIAtWrSADQbjIAGopAwAgA0G4xwBqKQMAfHx8fCIJQgyGhHwiE0I0iCAOIBNWrSAMIA5WrSADQZjHAGopAwAgDCAQVK0gA0GoyABqKQMAIAogEFatIANB2MgAaikDACADQajHAGopAwB8fHx8fHwgCUI0iHx8IglCDIaEfCILQgSGQvD/////////AIMgE0IwiEIPg4RCAELRh4CAEEIAEAYgA0HwxwBqIBRCACAWQgAQBiADQeDGAGogEkIAIBVCABAGIANB4MgAaiAXQgAgF0IAEAYgA0HQxgBqIAMpA+BGIgogAykD4Eh8Ig4gCyARVK0gDSARVq0gA0GIxwBqKQMAIANByMgAaikDAHx8IAlCNIh8fCIJQgyGIAtCNIiEfCILQv////////8Hg0IAQpD6gICAAkIAEAYgA0HgxwBqIBRCACASQgAQBiADQZDIAGogFkIAIBZCABAGIANBwMYAaiAXQgAgFUIAEAYgA0GwxgBqIAsgDlStIAogDlatIANB6MYAaikDACADQejIAGopAwB8fCAJQjSIfHwiDUIMhiALQjSIhCIKIAMpA8BGfCIJQgBCkPqAgIACQgAQBiADQaDGAGogCSAKVK0gA0HIxgBqKQMAIA1CNIh8fEIAQoCAxJ6AgMAAQgAQBiATQv///////z+DIAMpA6BGIg4gD0L+////////B4N8IhEgAykD4EciCyADKQOQSHwiECADKQOwRnwiDCADKQPQRiIKIAMpA/BHfCIPIAMpA/BGIgkgAykD0Ed8IhJCNIggCSASVq0gA0H4xgBqKQMAIANB2McAaikDAHx8IglCDIaEfCINQjSIIA0gD1StIAogD1atIANB2MYAaikDACADQfjHAGopAwB8fCAJQjSIfHwiCkIMhoR8IglCNIggCSAMVK0gDCAQVK0gA0G4xgBqKQMAIAsgEFatIANB6McAaikDACADQZjIAGopAwB8fHx8IApCNIh8fCILQgyGhHwiCkI0iCAKIBFUrSADQajGAGopAwAgDiARVq18IAtCNIh8fEIMhoR8IRggAkEBaiICQQNHDQALIANBgMYAaiASQv////////8HgyIdQgAgK0IAEAYgA0HQxQBqIA1C/////////weDIhpCACAsQgAQBiADQYDFAGogCUL/////////B4MiGUIAIC1CABAGIANBkMQAaiAKQv////////8HgyIbQgAgLkIAEAYgA0HQwwBqIBhCACAoQgAQBiADQcDDAGogAykD0ENCAEKQ+oCAgAJCABAGIANBkMYAaiAdQgAgKEIAEAYgA0HwxQBqIBpCACArQgAQBiADQbDFAGogGUIAICxCABAGIANB0MQAaiAbQgAgLUIAEAYgA0GgwwBqIC5CACAYQgAQBiADQbDDAGogA0HYwwBqKQMAQgBCgIDEnoCAwABCABAGIANBgMQAaiAdQgAgLkIAEAYgA0HgxQBqIBpCACAoQgAQBiADQaDFAGogGUIAICtCABAGIANBwMQAaiAbQgAgLEIAEAYgA0GQwwBqIC1CACAYQgAQBiADQYDDAGogAykDwEQiDSADKQOQQ3wiFyADKQOgRXwiEiADKQPgRXwiFiADKQPQRCIKIAMpA6BDfCIVIAMpA7BDfCITIAMpA7BFfCIUIAMpA/BFfCIRIAMpA5BGfCIMIAMpA8BDIgkgAykDkER8Ig8gAykDgEV8Ig4gAykD0EV8IgsgAykDgEZ8IhBCNIggCyAQVq0gA0GIxgBqKQMAIAsgDlStIANB2MUAaikDACAOIA9UrSADQYjFAGopAwAgCSAPVq0gA0HIwwBqKQMAIANBmMQAaikDAHx8fHx8fHx8IglCDIaEfCIcQjSIIAwgHFatIAwgEVStIANBmMYAaikDACARIBRUrSADQfjFAGopAwAgEyAUVq0gA0G4xQBqKQMAIBMgFVStIANBuMMAaikDACAKIBVWrSADQdjEAGopAwAgA0GowwBqKQMAfHx8fHx8fHx8fCAJQjSIfHwiCUIMhoR8IgtCBIZC8P////////8AgyAcQjCIQg+DhEIAQtGHgIAQQgAQBiADQfDEAGogHUIAIC1CABAGIANB8MMAaiAaQgAgLkIAEAYgA0GQxQBqIBlCACAoQgAQBiADQbDEAGogG0IAICtCABAGIANB8MIAaiAsQgAgGEIAEAYgA0HgwgBqIAMpA7BEIgogAykD8EJ8IgwgAykDkEV8Ig8gCyAWVK0gEiAWVq0gA0HoxQBqKQMAIBIgF1StIANBqMUAaikDACANIBdWrSADQcjEAGopAwAgA0GYwwBqKQMAfHx8fHx8IAlCNIh8fCIJQgyGIAtCNIiEfCIOQv////////8Hg0IAQpD6gICAAkIAEAYgA0HAxQBqIB1CACAsQgAQBiADQeDEAGogGkIAIC1CABAGIANB4MMAaiAZQgAgLkIAEAYgA0GgxABqIBtCACAoQgAQBiADQdDCAGogK0IAIBhCABAGIANBwMIAaiADKQOgRCINIAMpA9BCfCILIA4gD1StIAwgD1atIANBmMUAaikDACAKIAxWrSADQbjEAGopAwAgA0H4wgBqKQMAfHx8fCAJQjSIfHwiCkIMhiAOQjSIhHwiCUIAQpD6gICAAkIAEAYgA0GwwgBqIAkgC1StIAsgDVStIANBqMQAaikDACADQdjCAGopAwB8fCAKQjSIfHxCAEKAgMSegIDAAEIAEAYgHEL///////8/gyADKQOwQiIOIBBC/////////weDfCITIAMpA+BEIgsgAykD4EN8IhQgAykDwEV8IhEgAykDwEJ8IhAgAykD8EQiCiADKQPwQ3wiDCADKQPgQnwiDyADKQOAQyIJIAMpA4BEfCISQjSIIAkgElatIANBiMMAaikDACADQYjEAGopAwB8fCIJQgyGhHwiDUI0iCANIA9UrSAMIA9WrSADQejCAGopAwAgCiAMVq0gA0H4xABqKQMAIANB+MMAaikDAHx8fHwgCUI0iHx8IgpCDIaEfCIJQjSIIAkgEFStIBAgEVStIANByMIAaikDACARIBRUrSADQcjFAGopAwAgCyAUVq0gA0HoxABqKQMAIANB6MMAaikDAHx8fHx8fCAKQjSIfHwiC0IMhoR8IgpCNIggCiATVK0gA0G4wgBqKQMAIA4gE1atfCALQjSIfHxCDIaEfCEYQQEhAgNAIANBwMEAaiASQv////////8HgyILQgGGIhRCACAKQv////////8HgyIXQgAQBiADQfDBAGogDUL/////////B4MiFkIBhiIKQgAgCUL/////////B4MiEkIAEAYgA0GAwQBqIBhCACAYQgAQBiADQfDAAGogAykDgEFCAEKQ+oCAgAJCABAGIANB0MAAaiALQgAgGEIBhiIVQgAQBiADQeDBAGogCkIAIBdCABAGIANBkMIAaiASQgAgEkIAEAYgA0HgwABqIANBiMEAaikDAEIAQoCAxJ6AgMAAQgAQBiADQZDBAGogC0IAIAtCABAGIANBwMAAaiAWQgAgFUIAEAYgA0GAwgBqIBJCAYZCACAXQgAQBiADQbDAAGogAykDwEAiDSADKQOAQnwiESADKQOQQiIKIAMpA+BAfCIQIAMpA+BBfCIMIAMpA9BAfCIOIAMpA/BBIgkgAykD8EB8IgsgAykDwEF8Ig9CNIggCyAPVq0gA0HIwQBqKQMAIAkgC1atIANB+MEAaikDACADQfjAAGopAwB8fHx8IglCDIaEfCITQjSIIA4gE1atIAwgDlatIANB2MAAaikDACAMIBBUrSADQejBAGopAwAgCiAQVq0gA0GYwgBqKQMAIANB6MAAaikDAHx8fHx8fCAJQjSIfHwiCUIMhoR8IgtCBIZC8P////////8AgyATQjCIQg+DhEIAQtGHgIAQQgAQBiADQbDBAGogFEIAIBZCABAGIANBoMAAaiASQgAgFUIAEAYgA0GgwgBqIBdCACAXQgAQBiADQZDAAGogAykDoEAiCiADKQOgQnwiDiALIBFUrSANIBFWrSADQcjAAGopAwAgA0GIwgBqKQMAfHwgCUI0iHx8IglCDIYgC0I0iIR8IgtC/////////weDQgBCkPqAgIACQgAQBiADQaDBAGogFEIAIBJCABAGIANB0MEAaiAWQgAgFkIAEAYgA0GAQGsgF0IAIBVCABAGIANB8D9qIAsgDlStIAogDlatIANBqMAAaikDACADQajCAGopAwB8fCAJQjSIfHwiDUIMhiALQjSIhCIKIAMpA4BAfCIJQgBCkPqAgIACQgAQBiADQeA/aiAJIApUrSADQYjAAGopAwAgDUI0iHx8QgBCgIDEnoCAwABCABAGIBNC////////P4MgAykD4D8iDiAPQv7///////8Hg3wiESADKQOgQSILIAMpA9BBfCIQIAMpA/A/fCIMIAMpA5BAIgogAykDsEF8Ig8gAykDsEAiCSADKQOQQXwiEkI0iCAJIBJWrSADQbjAAGopAwAgA0GYwQBqKQMAfHwiCUIMhoR8Ig1CNIggDSAPVK0gCiAPVq0gA0GYwABqKQMAIANBuMEAaikDAHx8IAlCNIh8fCIKQgyGhHwiCUI0iCAJIAxUrSAMIBBUrSADQfg/aikDACALIBBWrSADQajBAGopAwAgA0HYwQBqKQMAfHx8fCAKQjSIfHwiC0IMhoR8IgpCNIggCiARVK0gA0HoP2opAwAgDiARVq18IAtCNIh8fEIMhoR8IRggAkEBcSEHQQAhAiAHDQALIANBwD9qIBJC/////////weDIh1CACAnQgAQBiADQZA/aiANQv////////8HgyIaQgAgKkIAEAYgA0HAPmogCUL/////////B4MiGUIAIDBCABAGIANB0D1qIApC/////////weDIhxCACAyQgAQBiADQZA9aiAYQgAgMUIAEAYgA0GAPWogAykDkD1CAEKQ+oCAgAJCABAGIANB0D9qIB1CACAxQgAQBiADQbA/aiAaQgAgJ0IAEAYgA0HwPmogGUIAICpCABAGIANBkD5qIBxCACAwQgAQBiADQeA8aiAyQgAgGEIAEAYgA0HwPGogA0GYPWopAwBCAEKAgMSegIDAAEIAEAYgA0HAPWogHUIAIDJCABAGIANBoD9qIBpCACAxQgAQBiADQeA+aiAZQgAgJ0IAEAYgA0GAPmogHEIAICpCABAGIANB0DxqIDBCACAYQgAQBiADQcA8aiADKQOAPiINIAMpA9A8fCIXIAMpA+A+fCISIAMpA6A/fCIWIAMpA5A+IgogAykD4Dx8IhUgAykD8Dx8IhMgAykD8D58IhQgAykDsD98IhAgAykD0D98IgwgAykDgD0iCSADKQPQPXwiDyADKQPAPnwiDiADKQOQP3wiCyADKQPAP3wiEUI0iCALIBFWrSADQcg/aikDACALIA5UrSADQZg/aikDACAOIA9UrSADQcg+aikDACAJIA9WrSADQYg9aikDACADQdg9aikDAHx8fHx8fHx8IglCDIaEfCIbQjSIIAwgG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IBRUrSADQYg8aikDACATIBRWrSADQYg/aikDACANIBNWrSADQag+aikDACADQag9aikDAHx8fHx8fCAJQjSIfHwiDEIMhoR8IhwhEiALIQ0gDiEKIA8hCSAbQv///////z+DIBUgHFatIANB+DtqKQMAIBAgFVatfCAMQjSIfHxCDIYgHEI0iIR8Ih8hGANAIANBgDtqIAlC/////////weDIgxCAYYiFkIAIBJC/////////weDIhpCABAGIANBsDtqIApC/////////weDIhtCAYYiCUIAIA1C/////////weDIhlCABAGIANBwDpqIBhCACAYQgAQBiADQbA6aiADKQPAOkIAQpD6gICAAkIAEAYgA0GQOmogDEIAIBhCAYYiF0IAEAYgA0GgO2ogCUIAIBpCABAGIANB0DtqIBlCACAZQgAQBiADQaA6aiADQcg6aikDAEIAQoCAxJ6AgMAAQgAQBiADQdA6aiAMQgAgDEIAEAYgA0GAOmogG0IAIBdCABAGIANBwDtqIBlCAYZCACAaQgAQBiADQfA5aiADKQOAOiINIAMpA8A7fCIVIAMpA9A7IgogAykDoDp8IhMgAykDoDt8IhEgAykDkDp8IhAgAykDsDsiCSADKQOwOnwiDCADKQOAO3wiFEI0iCAMIBRWrSADQYg7aikDACAJIAxWrSADQbg7aikDACADQbg6aikDAHx8fHwiCUIMhoR8IhJCNIggECASVq0gECARVK0gA0GYOmopAwAgESATVK0gA0GoO2opAwAgCiATVq0gA0HYO2opAwAgA0GoOmopAwB8fHx8fHwgCUI0iHx8IglCDIaEfCIMQgSGQvD/////////AIMgEkIwiEIPg4RCAELRh4CAEEIAEAYgA0HwOmogFkIAIBtCABAGIANB4DlqIBlCACAXQgAQBiADQeA7aiAaQgAgGkIAEAYgA0HQOWogAykD4DkiCiADKQPgO3wiECAMIBVUrSANIBVWrSADQYg6aikDACADQcg7aikDAHx8IAlCNIh8fCIJQgyGIAxCNIiEfCIMQv////////8Hg0IAQpD6gICAAkIAEAYgA0HgOmogFkIAIBlCABAGIANBkDtqIBtCACAbQgAQBiADQcA5aiAaQgAgF0IAEAYgA0GwOWogDCAQVK0gCiAQVq0gA0HoOWopAwAgA0HoO2opAwB8fCAJQjSIfHwiDUIMhiAMQjSIhCIKIAMpA8A5fCIJQgBCkPqAgIACQgAQBiADQaA5aiAJIApUrSADQcg5aikDACANQjSIfHxCAEKAgMSegIDAAEIAEAYgEkL///////8/gyADKQOgOSIRIBRC/v///////weDfCIWIAMpA+A6IhAgAykDkDt8IhUgAykDsDl8IhMgAykD0DkiDCADKQPwOnwiFCADKQPwOSIKIAMpA9A6fCIJQjSIIAkgClStIANB+DlqKQMAIANB2DpqKQMAfHwiDUIMhoR8IgpCNIggCiAUVK0gDCAUVq0gA0HYOWopAwAgA0H4OmopAwB8fCANQjSIfHwiDEIMhoR8Ig1CNIggDSATVK0gEyAVVK0gA0G4OWopAwAgECAVVq0gA0HoOmopAwAgA0GYO2opAwB8fHx8IAxCNIh8fCIMQgyGhHwiEkI0iCASIBZUrSADQag5aikDACARIBZWrXwgDEI0iHx8QgyGhHwhGCACQQFqIgJBC0cNAAsgA0GQOWogCUL/////////B4MiIUIAIBxC/////////weDIiJCABAGIANB8DhqIApC/////////weDIiNCACALQv////////8HgyIeQgAQBiADQbA4aiANQv////////8HgyIdQgAgDkL/////////B4MiGkIAEAYgA0HQN2ogEkL/////////B4MiGUIAIA9C/////////weDIhxCABAGIANB0DZqIBhCACAfQgAQBiADQcA2aiADKQPQNkIAQpD6gICAAkIAEAYgA0GgNmogIUIAIB9CABAGIANBgDlqICNCACAiQgAQBiADQdA4aiAdQgAgHkIAEAYgA0GAOGogGUIAIBpCABAGIANBkDdqIBxCACAYQgAQBiADQbA2aiADQdg2aikDAEIAQoCAxJ6AgMAAQgAQBiADQcA3aiAhQgAgHEIAEAYgA0GQNmogI0IAIB9CABAGIANBwDhqIB1CACAiQgAQBiADQfA3aiAZQgAgHkIAEAYgA0GAN2ogGkIAIBhCABAGIANBgDZqIAMpA/A3Ig0gAykDgDd8IhcgAykDwDh8IhIgAykDkDZ8IhYgAykDgDgiCiADKQOQN3wiFSADKQOwNnwiEyADKQPQOHwiFCADKQOAOXwiECADKQOgNnwiDCADKQPANiIJIAMpA9A3fCIPIAMpA7A4fCIOIAMpA/A4fCILIAMpA5A5fCIRQjSIIAsgEVatIANBmDlqKQMAIAsgDlStIANB+DhqKQMAIA4gD1StIANBuDhqKQMAIAkgD1atIANByDZqKQMAIANB2DdqKQMAfHx8fHx8fHwiCUIMhoR8IhtCNIggDCAbVq0gDCAQVK0gA0GoNmopAwAgECAUVK0gA0GIOWopAwAgEyAUVq0gA0HYOGopAwAgEyAVVK0gA0G4NmopAwAgCiAVVq0gA0GIOGopAwAgA0GYN2opAwB8fHx8fHx8fHx8IAlCNIh8fCIJQgyGhHwiC0IEhkLw/////////wCDIBtCMIhCD4OEQgBC0YeAgBBCABAGIANBoDhqICFCACAaQgAQBiADQbA3aiAjQgAgHEIAEAYgA0HwNWogHUIAIB9CABAGIANB4DdqIBlCACAiQgAQBiADQfA2aiAeQgAgGEIAEAYgA0HgNWogAykD4DciCiADKQPwNnwiDCADKQPwNXwiDyALIBZUrSASIBZWrSADQZg2aikDACASIBdUrSADQcg4aikDACANIBdWrSADQfg3aikDACADQYg3aikDAHx8fHx8fCAJQjSIfHwiCUIMhiALQjSIhHwiDkL/////////B4NCAEKQ+oCAgAJCABAGIANB4DhqICFCACAeQgAQBiADQZA4aiAjQgAgGkIAEAYgA0GgN2ogHUIAIBxCABAGIANB0DVqIBlCACAfQgAQBiADQeA2aiAiQgAgGEIAEAYgA0HANWogAykD0DUiDSADKQPgNnwiCyAOIA9UrSAMIA9WrSADQfg1aikDACAKIAxWrSADQeg3aikDACADQfg2aikDAHx8fHwgCUI0iHx8IgpCDIYgDkI0iIR8IglCAEKQ+oCAgAJCABAGIANBsDVqIAkgC1StIAsgDVStIANB2DVqKQMAIANB6DZqKQMAfHwgCkI0iHx8QgBCgIDEnoCAwABCABAGQQAhAiADKQOwNSIQIBFC/////////weDfCIVIAMpA5A4Ig0gAykDoDd8IhMgAykD4Dh8IhQgAykDwDV8IhEgAykDoDgiCiADKQOwN3wiDCADKQPgNXwiCyADKQOANiIJIAMpA8A3fCIPQjSIIAkgD1atIANBiDZqKQMAIANByDdqKQMAfHwiCUIMhoR8Ig5CNIggCyAOVq0gCyAMVK0gA0HoNWopAwAgCiAMVq0gA0GoOGopAwAgA0G4N2opAwB8fHx8IAlCNIh8fCIJQgyGhHwiC0I0iCALIBFUrSARIBRUrSADQcg1aikDACATIBRWrSADQeg4aikDACANIBNWrSADQZg4aikDACADQag3aikDAHx8fHx8fCAJQjSIfHwiDEIMhoR8IhwhEiALIQ0gDiEKIA8hCSAbQv///////z+DIBUgHFatIANBuDVqKQMAIBAgFVatfCAMQjSIfHxCDIYgHEI0iIR8IjMhGANAIANBwDRqIAlC/////////weDIgxCAYYiFkIAIBJC/////////weDIhpCABAGIANB8DRqIApC/////////weDIhtCAYYiCUIAIA1C/////////weDIhlCABAGIANBgDRqIBhCACAYQgAQBiADQfAzaiADKQOANEIAQpD6gICAAkIAEAYgA0HQM2ogDEIAIBhCAYYiF0IAEAYgA0HgNGogCUIAIBpCABAGIANBkDVqIBlCACAZQgAQBiADQeAzaiADQYg0aikDAEIAQoCAxJ6AgMAAQgAQBiADQZA0aiAMQgAgDEIAEAYgA0HAM2ogG0IAIBdCABAGIANBgDVqIBlCAYZCACAaQgAQBiADQbAzaiADKQPAMyINIAMpA4A1fCIVIAMpA5A1IgogAykD4DN8IhMgAykD4DR8IhEgAykD0DN8IhAgAykD8DQiCSADKQPwM3wiDCADKQPANHwiFEI0iCAMIBRWrSADQcg0aikDACAJIAxWrSADQfg0aikDACADQfgzaikDAHx8fHwiCUIMhoR8IhJCNIggECASVq0gECARVK0gA0HYM2opAwAgESATVK0gA0HoNGopAwAgCiATVq0gA0GYNWopAwAgA0HoM2opAwB8fHx8fHwgCUI0iHx8IglCDIaEfCIMQgSGQvD/////////AIMgEkIwiEIPg4RCAELRh4CAEEIAEAYgA0GwNGogFkIAIBtCABAGIANBoDNqIBlCACAXQgAQBiADQaA1aiAaQgAgGkIAEAYgA0GQM2ogAykDoDMiCiADKQOgNXwiECAMIBVUrSANIBVWrSADQcgzaikDACADQYg1aikDAHx8IAlCNIh8fCIJQgyGIAxCNIiEfCIMQv////////8Hg0IAQpD6gICAAkIAEAYgA0GgNGogFkIAIBlCABAGIANB0DRqIBtCACAbQgAQBiADQYAzaiAaQgAgF0IAEAYgA0HwMmogDCAQVK0gCiAQVq0gA0GoM2opAwAgA0GoNWopAwB8fCAJQjSIfHwiDUIMhiAMQjSIhCIKIAMpA4AzfCIJQgBCkPqAgIACQgAQBiADQeAyaiAJIApUrSADQYgzaikDACANQjSIfHxCAEKAgMSegIDAAEIAEAYgEkL///////8/gyADKQPgMiIRIBRC/v///////weDfCIWIAMpA6A0IhAgAykD0DR8IhUgAykD8DJ8IhMgAykDkDMiDCADKQOwNHwiFCADKQOwMyIKIAMpA5A0fCIJQjSIIAkgClStIANBuDNqKQMAIANBmDRqKQMAfHwiDUIMhoR8IgpCNIggCiAUVK0gDCAUVq0gA0GYM2opAwAgA0G4NGopAwB8fCANQjSIfHwiDEIMhoR8Ig1CNIggDSATVK0gEyAVVK0gA0H4MmopAwAgECAVVq0gA0GoNGopAwAgA0HYNGopAwB8fHx8IAxCNIh8fCIMQgyGhHwiEkI0iCASIBZUrSADQegyaikDACARIBZWrXwgDEI0iHx8QgyGhHwhGCACQQFqIgJBFkcNAAsgA0HQMmogCUL/////////B4MiHUIAIBxC/////////weDIjVCABAGIANBsDJqIApC/////////weDIhpCACALQv////////8HgyI2QgAQBiADQfAxaiANQv////////8HgyIZQgAgDkL/////////B4MiN0IAEAYgA0GQMWogEkL/////////B4MiHEIAIA9C/////////weDIjhCABAGIANBkDBqIBhCACAzQgAQBiADQYAwaiADKQOQMEIAQpD6gICAAkIAEAYgA0HgL2ogHUIAIDNCABAGIANBwDJqIBpCACA1QgAQBiADQZAyaiAZQgAgNkIAEAYgA0HAMWogHEIAIDdCABAGIANB0DBqIDhCACAYQgAQBiADQfAvai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rSADQagxaikDACADQbgwaikDAHx8fHwgCUI0iHx8IgpCDIYgDkI0iIR8IglCAEKQ+oCAgAJCABAGIANB8C5qIAkgC1StIAsgDVStIANBmC9qKQMAIANBqDBqKQMAfHwgCkI0iHx8QgBCgIDEnoCAwABCABAGQQAhAiADKQPwLiIQIBFC/////////weDfCIVIAMpA9AxIg0gAykD4DB8IhMgAykDoDJ8IhQgAykDgC98IhEgAykD4DEiCiADKQPwMHwiDCADKQOgL3wiCyADKQPALyIJIAMpA4AxfCIPQjSIIAkgD1atIANByC9qKQMAIANBiDFqKQMAfHwiCUIMhoR8Ig5CNIggCyAOVq0gCyAMVK0gA0GoL2opAwAgCiAMVq0gA0HoMWopAwAgA0H4MGopAwB8fHx8IAlCNIh8fCIJQgyGhHwiC0I0iCALIBFUrSARIBRUrSADQYgvaikDACATIBRWrSADQagyaikDACANIBNWrSADQdgxaikDACADQegwaikDAHx8fHx8fCAJQjSIfHwiDEIMhoR8IhwhEiALIQ0gDiEKIA8hCSAbQv///////z+DIBUgHFatIANB+C5qKQMAIBAgFVatfCAMQjSIfHxCDIYgHEI0iIR8IjQhGANAIANBgC5qIAlC/////////weDIgxCAYYiFkIAIBJC/////////weDIhpCABAGIANBsC5qIApC/////////weDIhtCAYYiCUIAIA1C/////////weDIhlCABAGIANBwC1qIBhCACAYQgAQBiADQbAtaiADKQPALUIAQpD6gICAAkIAEAYgA0GQLWogDEIAIBhCAYYiF0IAEAYgA0GgLmogCUIAIBpCABAGIANB0C5qIBlCACAZQgAQBiADQaAtaiADQcgtaikDAEIAQoCAxJ6AgMAAQgAQBiADQdAtaiAMQgAgDEIAEAYgA0GALWogG0IAIBdCABAGIANBwC5qIBlCAYZCACAaQgAQBiADQfAsaiADKQOALSINIAMpA8AufCIVIAMpA9AuIgogAykDoC18IhMgAykDoC58IhEgAykDkC18IhAgAykDsC4iCSADKQOwLXwiDCADKQOALnwiFEI0iCAMIBRWrSADQYguaikDACAJIAxWrSADQbguaikDACADQbgtaikDAHx8fHwiCUIMhoR8IhJCNIggECASVq0gECARVK0gA0GYLWopAwAgESATVK0gA0GoLmopAwAgCiATVq0gA0HYLmopAwAgA0GoLWopAwB8fHx8fHwgCUI0iHx8IglCDIaEfCIMQgSGQvD/////////AIMgEkIwiEIPg4RCAELRh4CAEEIAEAYgA0HwLWogFkIAIBtCABAGIANB4CxqIBlCACAXQgAQBiADQeAuaiAaQgAgGkIAEAYgA0HQLGogAykD4CwiCiADKQPgLnwiECAMIBVUrSANIBVWrSADQYgtaikDACADQcguaikDAHx8IAlCNIh8fCIJQgyGIAxCNIiEfCIMQv////////8Hg0IAQpD6gICAAkIAEAYgA0HgLWogFkIAIBlCABAGIANBkC5qIBtCACAbQgAQBiADQcAsaiAaQgAgF0IAEAYgA0GwLGogDCAQVK0gCiAQVq0gA0HoLGopAwAgA0HoLmopAwB8fCAJQjSIfHwiDUIMhiAMQjSIhCIKIAMpA8AsfCIJQgBCkPqAgIACQgAQBiADQaAsaiAJIApUrSADQcgsaikDACANQjSIfHxCAEKAgMSegIDAAEIAEAYgEkL///////8/gyADKQOgLCIRIBRC/v///////weDfCIWIAMpA+AtIhAgAykDkC58IhUgAykDsCx8IhMgAykD0CwiDCADKQPwLXwiFCADKQPwLCIKIAMpA9AtfCIJQjSIIAkgClStIANB+CxqKQMAIANB2C1qKQMAfHwiDUIMhoR8IgpCNIggCiAUVK0gDCAUVq0gA0HYLGopAwAgA0H4LWopAwB8fCANQjSIfHwiDEIMhoR8Ig1CNIggDSATVK0gEyAVVK0gA0G4LGopAwAgECAVVq0gA0HoLWopAwAgA0GYLmopAwB8fHx8IAxCNIh8fCIMQgyGhHwiEkI0iCASIBZUrSADQagsaikDACARIBZWrXwgDEI0iHx8QgyGhHwhGCACQQFqIgJBLEcNAAsgA0GQLGogCUL/////////B4MiHUIAIBxC/////////weDIjlCABAGIANB8CtqIApC/////////weDIhpCACALQv////////8HgyI6QgAQBiADQbAraiANQv////////8HgyIZQgAgDkL/////////B4MiO0IAEAYgA0HQKmogEkL/////////B4MiHEIAIA9C/////////weDIiBCABAGIANB0ClqIBhCACA0QgAQBiADQcApaiADKQPQKUIAQpD6gICAAkIAEAYgA0GgKWogHUIAIDRCABAGIANBgCxqIBpCACA5QgAQBiADQdAraiAZQgAgOkIAEAYgA0GAK2ogHEIAIDtCABAGIANBkCpqICBCACAYQgAQBiADQbApaiADQdgpaikDAEIAQoCAxJ6AgMAAQgAQBiADQcAqaiAdQgAgIEIAEAYgA0GQKWogGkIAIDRCABAGIANBwCtqIBlCACA5QgAQBiADQfAqaiAcQgAgOkIAEAYgA0GAKmogO0IAIBhCABAGIANBgClqIAMpA/AqIg0gAykDgCp8IhcgAykDwCt8IhIgAykDkCl8IhYgAykDgCsiCiADKQOQKnwiFSADKQOwKXwiEyADKQPQK3wiFCADKQOALHwiECADKQOgKXwiDCADKQPAKSIJIAMpA9AqfCIPIAMpA7ArfCIOIAMpA/ArfCILIAMpA5AsfCIRQjSIIAsgEVatIANBmCxqKQMAIAsgDlStIANB+CtqKQMAIA4gD1StIANBuCtqKQMAIAkgD1atIANByClqKQMAIANB2CpqKQMAfHx8fHx8fHwiCUIMhoR8IhtCNIggDCAbVq0gDCAQVK0gA0GoKWopAwAgECAUVK0gA0GILGopAwAgEyAUVq0gA0HYK2opAwAgEyAVVK0gA0G4KWopAwAgCiAVVq0gA0GIK2opAwAgA0GYKmopAwB8fHx8fHx8fHx8IAlCNIh8fCIJQgyGhHwiC0IEhkLw/////////wCDIBtCMIhCD4OEQgBC0YeAgBBCABAGIANBoCtqIB1CACA7QgAQBiADQbAqaiAaQgAgIEIAEAYgA0HwKGogGUIAIDRCABAGIANB4CpqIBxCACA5QgAQBiADQfApaiA6QgAgGEIAEAYgA0HgKGogAykD4CoiCiADKQPwKXwiDCADKQPwKHwiDyALIBZUrSASIBZWrSADQZgpaikDACASIBdUrSADQcgraikDACANIBdWrSADQfgqaikDACADQYgqaikDAHx8fHx8fCAJQjSIfHwiCUIMhiALQjSIhHwiDkL/////////B4NCAEKQ+oCAgAJCABAGIANB4CtqIB1CACA6QgAQBiADQZAraiAaQgAgO0IAEAYgA0GgKmogGUIAICBCABAGIANB0ChqIBxCACA0QgAQBiADQeApaiA5QgAgGEIAEAYgA0HAKGogAykD0CgiDSADKQPgKXwiCyAOIA9UrSAMIA9WrSADQfgoaikDACAKIAxWrSADQegqaikDACADQfgpaikDAHx8fHwgCUI0iHx8IgpCDIYgDkI0iIR8IglCAEKQ+oCAgAJCABAGIANBsChqIAkgC1StIAsgDVStIANB2ChqKQMAIANB6ClqKQMAfHwgCkI0iHx8QgBCgIDEnoCAwABCABAGQQAhAiADKQOwKCIQIBFC/////////weDfCIVIAMpA5ArIg0gAykDoCp8IhMgAykD4Ct8IhQgAykDwCh8IhEgAykDoCsiCiADKQOwKnwiDCADKQPgKHwiCyADKQOAKSIJIAMpA8AqfCIPQjSIIAkgD1atIANBiClqKQMAIANByCpqKQMAfHwiCUIMhoR8Ig5CNIggCyAOVq0gCyAMVK0gA0HoKGopAwAgCiAMVq0gA0GoK2opAwAgA0G4KmopAwB8fHx8IAlCNIh8fCIJQgyGhHwiC0I0iCALIBFUrSARIBRUrSADQcgoaikDACATIBRWrSADQegraikDACANIBNWrSADQZgraikDACADQagqaikDAHx8fHx8fCAJQjSIfHwiDEIMhoR8IhwhEiALIQ0gDiEKIA8hCSAbQv///////z+DIBUgHFatIANBuChqKQMAIBAgFVatfCAMQjSIfHxCDIYgHEI0iIR8Ih8hGANAIANBwCdqIAlC/////////weDIgxCAYYiFkIAIBJC/////////weDIhpCABAGIANB8CdqIApC/////////weDIhtCAYYiCUIAIA1C/////////weDIhlCABAGIANBgCdqIBhCACAYQgAQBiADQfAmaiADKQOAJ0IAQpD6gICAAkIAEAYgA0HQJmogDEIAIBhCAYYiF0IAEAYgA0HgJ2ogCUIAIBpCABAGIANBkChqIBlCACAZQgAQBiADQeAmaiADQYgnaikDAEIAQoCAxJ6AgMAAQgAQBiADQZAnaiAMQgAgDEIAEAYgA0HAJm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AxCNIh8fCIMQgyGhHwiEkI0iCASIBZUrSADQeglaikDACARIBZWrXwgDEI0iHx8QgyGhHwhGCACQQFqIgJB2ABHDQALIANB0CVqIAlC/////////weDIiFCACAcQv////////8HgyIiQgAQBiADQbAlaiAKQv////////8HgyIjQgAgC0L/////////B4MiHkIAEAYgA0HwJGogDUL/////////B4MiHUIAIA5C/////////weDIhpCABAGIANBkCRqIBJC/////////weDIhlCACAPQv////////8HgyIbQgAQBiADQZAjaiAYQgAgH0IAEAYgA0GAI2ogAykDkCNCAEKQ+oCAgAJCABAGIANB4CJqICFCACAfQgAQBiADQcAlaiAjQgAgIkIAEAYgA0GQJWogHUIAIB5CABAGIANBwCRqIBlCACAaQgAQBiADQdAjaiAbQgAgGEIAEAYgA0HwImogA0GYI2opAwBCAEKAgMSegIDAAEIAEAYgA0GAJGogIUIAIBtCABAGIANB0CJqICNCACAfQgAQBiADQYAlaiAdQgAgIkIAEAYgA0GwJGogGUIAIB5CABAGIANBwCNqIBpCACAYQgAQBiADQcAiaiADKQOwJCINIAMpA8AjfCIXIAMpA4AlfCISIAMpA9AifCIWIAMpA8AkIgogAykD0CN8IhUgAykD8CJ8IhMgAykDkCV8IhQgAykDwCV8IhEgAykD4CJ8IgwgAykDgCMiCSADKQOQJHwiDyADKQPwJHwiDiADKQOwJXwiCyADKQPQJXwiEEI0iCALIBBWrSADQdglaikDACALIA5UrSADQbglaikDACAOIA9UrSADQfgkaikDACAJIA9WrSADQYgjaikDACADQZgkaikDAHx8fHx8fHx8IglCDIaEfCIcQjSIIAwgHFatIAwgEVStIANB6CJqKQMAIBEgFFStIANByCVqKQMAIBMgFFatIANBmCVqKQMAIBMgFVStIANB+CJqKQMAIAogFVatIANByCRqKQMAIANB2CNqKQMAfHx8fHx8fHx8fCAJQjSIfHwiCUIMhoR8IgtCBIZC8P////////8AgyAcQjCIQg+DhEIAQtGHgIAQQgAQBiADQeAkaiAhQgAgGkIAEAYgA0HwI2ogI0IAIBtCABAGIANBsCJqIB1CACAfQgAQBiADQaAkaiAZQgAgIkIAEAYgA0GwI2ogHkIAIBhCABAGIANBoCJqIAMpA6AkIgogAykDsCN8IgwgAykDsCJ8Ig8gCyAWVK0gEiAWVq0gA0HYImopAwAgEiAXVK0gA0GIJWopAwAgDSAXVq0gA0G4JGopAwAgA0HII2opAwB8fHx8fHwgCUI0iHx8IglCDIYgC0I0iIR8Ig5C/////////weDQgBCkPqAgIACQgAQBiADQaAlaiAhQgAgHkIAEAYgA0HQJGogI0IAIBpCABAGIANB4CNqIB1CACAbQgAQBiADQZAiaiAZQgAgH0IAEAYgA0GgI2ogIkIAIBhCABAGIANBgCJqIAMpA5AiIg0gAykDoCN8IgsgDiAPVK0gDCAPVq0gA0G4ImopAwAgCiAMVq0gA0GoJGopAwAgA0G4I2opAwB8fHx8IAlCNIh8fCIKQgyGIA5CNIiEfCIJQgBCkPqAgIACQgAQBiADQfAhaiAJIAtUrSALIA1UrSADQZgiaikDACADQagjaikDAHx8IApCNIh8fEIAQoCAxJ6AgMAAQgAQBiAcQv///////z+DIAMpA/AhIg4gEEL/////////B4N8IhMgAykD0CQiCyADKQPgI3wiFCADKQOgJXwiESADKQOAInwiECADKQPgJCIKIAMpA/AjfCIMIAMpA6AifCIPIAMpA8AiIgkgAykDgCR8IhJCNIggCSASVq0gA0HIImopAwAgA0GIJGopAwB8fCIJQgyGhHwiDUI0iCANIA9UrSAMIA9WrSADQagiaikDACAKIAxWrSADQegkaikDACADQfgjaikDAHx8fHwgCUI0iHx8IgpCDIaEfCIJQjSIIAkgEFStIBAgEVStIANBiCJqKQMAIBEgFFStIANBqCVqKQMAIAsgFFatIANB2CRqKQMAIANB6CNqKQMAfHx8fHx8IApCNIh8fCILQgyGhHwiCkI0iCAKIBNUrSADQfghaikDACAOIBNWrXwgC0I0iHx8QgyGhHwhGEEAIQIDQCADQYAhaiASQv////////8HgyILQgGGIhRCACAKQv////////8HgyIXQgAQBiADQbAhaiANQv////////8HgyIWQgGGIgpCACAJQv////////8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SADKQPQIHwiEkI0iCAJIBJWrSADQfgfaikDACADQdggaikDAHx8IglCDIaEfCINQjSIIA0gD1StIAogD1atIANB2B9qKQMAIANB+CBqKQMAfHwgCUI0iHx8IgpCDIaEfCIJQjSIIAkgDFStIAwgEFStIANBuB9qKQMAIAsgEFatIANB6CBqKQMAIANBmCFqKQMAfHx8fCAKQjSIfHwiC0IMhoR8IgpCNIggCiARVK0gA0GoH2opAwAgDiARVq18IAtCNIh8fEIMhoR8IRggAkEBaiICQSxHDQALIANBgB9qIBJC/////////weDIh1CACA5QgAQBiADQdAeaiANQv////////8HgyIaQgAgOkIAEAYgA0GAHmogCUL/////////B4MiGUIAIDtCABAGIANBkB1qIApC/////////weDIhtCACAgQgAQBiADQdAcaiAYQgAgNEIAEAYgA0HAHGogAykD0BxCAEKQ+oCAgAJCABAGIANBkB9qIB1CACA0QgAQBiADQfAeaiAaQgAgOUIAEAYgA0GwHmogGUIAIDpCABAGIANB0B1qIBtCACA7QgAQBiADQaAcaiAgQgAgGEIAEAYgA0GwHGogA0HYHGopAwBCAEKAgMSegIDAAEIAEAYgA0GAHWogHUIAICBCABAGIANB4B5qIBpCACA0QgAQBiADQaAeaiAZQgAgOUIAEAYgA0HAHWogG0IAIDpCABAGIANBkBxqIDtCACAYQgAQBiADQYAcaiADKQPAHSINIAMpA5AcfCIXIAMpA6AefCISIAMpA+AefCIWIAMpA9AdIgogAykDoBx8IhUgAykDsBx8IhMgAykDsB58IhQgAykD8B58IhEgAykDkB98IgwgAykDwBwiCSADKQOQHXwiDyADKQOAHnwiDiADKQPQHnwiCyADKQOAH3wiEEI0iCALIBBWrSADQYgfaikDACALIA5UrSADQdgeaikDACAOIA9UrSADQYgeaikDACAJIA9WrSADQcgcaikDACADQZgdaikDAHx8fHx8fHx8IglCDIaEfCIcQjSIIAwgHFatIAwgEVStIANBmB9qKQMAIBEgFFStIANB+B5qKQMAIBMgFFatIANBuB5qKQMAIBMgFVStIANBuBxqKQMAIAogFVatIANB2B1qK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HwiCkI0iCAKIBNUrSADQbgbaikDACAOIBNWrXwgC0I0iHx8QgyGhHwhGEEAIQIDQCADQcAaaiASQv////////8HgyILQgGGIhRCACAKQv////////8HgyIXQgAQBiADQfAaaiANQv////////8HgyIWQgGGIgpCACAJQv////////8HgyISQgAQBiADQYAaaiAYQgAgGEIAEAYgA0HwGWogAykDgBpCAEKQ+oCAgAJCABAGIANB0BlqIAtCACAYQgGGIhVCABAGIANB4BpqIApCACAXQgAQBiADQZAbaiASQgAgEkIAEAYgA0HgGWogA0GIGmopAwBCAEKAgMSegIDAAEIAEAYgA0GQGmogC0IAIAtCABAGIANBwBlqIBZCACAVQgAQBiADQYAbaiASQgGGQgAgF0IAEAYgA0GwGWogAykDwBkiDSADKQOAG3wiESADKQOQGyIKIAMpA+AZfCIQIAMpA+AafCIMIAMpA9AZfCIOIAMpA/AaIgkgAykD8Bl8IgsgAykDwBp8Ig9CNIggCyAPVq0gA0HIGmopAwAgCSALVq0gA0H4GmopAwAgA0H4GWopAwB8fHx8IglCDIaEfCITQjSIIA4gE1atIAwgDlatIANB2BlqKQMAIAwgEFStIANB6BpqKQMAIAogEFatIANBmBtqKQMAIANB6BlqKQMAfHx8fHx8IAlCNIh8fCIJQgyGhHwiC0IEhkLw/////////wCDIBNCMIhCD4OEQgBC0YeAgBBCABAGIANBsBpqIBRCACAWQgAQBiADQaAZaiASQgAgFUIAEAYgA0GgG2ogF0IAIBdCABAGIANBkBlqIAMpA6AZIgogAykDoBt8Ig4gCyARVK0gDSARVq0gA0HIGWopAwAgA0GIG2opAwB8fCAJQjSIfHwiCUIMhiALQjSIhHwiC0L/////////B4NCAEKQ+oCAgAJCABAGIANBoBpqIBRCACASQgAQBiADQdAaaiAWQgAgFkIAEAYgA0GAGWogF0IAIBVCABAGIANB8BhqIAsgDlStIAogDlatIANBqBlqKQMAIANBqBtqKQMAfHwgCUI0iHx8Ig1CDIYgC0I0iIQiCiADKQOAGXwiCUIAQpD6gICAAkIAEAYgA0HgGGogCSAKVK0gA0GIGWopAwAgDUI0iHx8QgBCgIDEnoCAwABCABAGIBNC////////P4MgAykD4BgiDiAPQv7///////8Hg3wiESADKQOgGiILIAMpA9AafCIQIAMpA/AYfCIMIAMpA5AZIgogAykDsBp8Ig8gAykDsBkiCSADKQOQGnwiEkI0iCAJIBJWrSADQbgZaikDACADQZgaaikDAHx8IglCDIaEfCINQjSIIA0gD1StIAogD1atIANBmBlqKQMAIANBuBpqKQMAfHwgCUI0iHx8IgpCDIaEfCIJQjSIIAkgDFStIAwgEFStIANB+BhqKQMAIAsgEFatIANBqBpqKQMAIANB2BpqKQMAfHx8fCAKQjSIfHwiC0IMhoR8IgpCNIggCiARVK0gA0HoGGopAwAgDiARVq18IAtCNIh8fEIMhoR8IRggAkEBaiICQQNHDQALIANBwBhqIBJC/////////weDIh1CACArQgAQBiADQZAYaiANQv////////8HgyIaQgAgLEIAEAYgA0HAF2ogCUL/////////B4MiGUIAIC1CABAGIANB0BZqIApC/////////weDIhtCACAuQgAQBiADQZAWaiAYQgAgKEIAEAYgA0GAFmogAykDkBZCAEKQ+oCAgAJCABAGIANB0BhqIB1CACAoQgAQBiADQbAYaiAaQgAgK0IAEAYgA0HwF2ogGUIAICxCABAGIANBkBdqIBtCACAtQgAQBiADQeAVaiAuQgAgGEIAEAYgA0HwFWogA0GYFmopAwBCAEKAgMSegIDAAEIAEAYgA0HAFmogHUIAIC5CABAGIANBoBhqIBpCACAoQgAQBiADQeAXaiAZQgAgK0IAEAYgA0GAF2ogG0IAICxCABAGIANB0BVqIC1CACAYQgAQBiADQcAVaiADKQOAFyINIAMpA9AVfCIXIAMpA+AXfCISIAMpA6AYfCIWIAMpA5AXIgogAykD4BV8IhUgAykD8BV8IhMgAykD8Bd8IhQgAykDsBh8IhEgAykD0Bh8IgwgAykDgBYiCSADKQPQFnwiDyADKQPAF3wiDiADKQOQGHwiCyADKQPAGHwiEEI0iCALIBBWrSADQcgYaikDACALIA5UrSADQZgYaikDACAOIA9UrSADQcgX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AKIAxWrSADQbgXaikDACADQbgWaikDAHx8fHwgCUI0iHx8IgpCDIaEfCIJQjSIIAkgEFStIBAgEVStIANBiBVqKQMAIBEgFFStIANBiBhqKQMAIAsgFFatIANBqBdqKQMAIANBqBZqKQMAfHx8fHx8IApCNIh8fCILQgyGhHwiCkI0iCAKIBNUrSADQfgUaikDACAOIBNWrXwgC0I0iHx8QgyGhHwhGEEAIQIDQCADQYAUaiASQv////////8HgyILQgGGIhRCACAKQv////////8HgyIXQgAQBiADQbAUaiANQv////////8HgyIWQgGGIgpCACAJQv////////8HgyISQgAQBiADQcATaiAYQgAgGEIAEAYgA0GwE2ogAykDwBNCAEKQ+oCAgAJCABAGIANBkBNqIAtCACAYQgGGIhVCABAGIANBoBRqIApCACAXQgAQBiADQdAUaiASQgAgEkIAEAYgA0GgE2ogA0HIE2opAwBCAEKAgMSegIDAAEIAEAYgA0HQE2ogC0IAIAtCABAGIANBgBNqIBZCACAVQgAQBiADQcAUaiASQgGGQgAgF0IAEAYgA0HwEmogAykDgBMiDSADKQPAFHwiESADKQPQFCIKIAMpA6ATfCIQIAMpA6AUfCIMIAMpA5ATfCIOIAMpA7AUIgkgAykDsBN8IgsgAykDgBR8Ig9CNIggCyAPVq0gA0GIFGopAwAgCSALVq0gA0G4FGopAwAgA0G4E2opAwB8fHx8IglCDIaEfCITQjSIIA4gE1atIAwgDlatIANBmBNqKQMAIAwgEFStIANBqBRqKQMAIAogEFatIANB2BRqKQMAIANBqBNqKQMAfHx8fHx8IAlCNIh8fCIJQgyGhHwiC0IEhkLw/////////wCDIBNCMIhCD4OEQgBC0YeAgBBCABAGIANB8BNqIBRCACAWQgAQBiADQeASaiASQgAgFUIAEAYgA0HgFGogF0IAIBdCABAGIANB0BJqIAMpA+ASIgogAykD4BR8Ig4gCyARVK0gDSARVq0gA0GIE2opAwAgA0HIFGopAwB8fCAJQjSIfHwiCUIMhiALQjSIhHwiC0L/////////B4NCAEKQ+oCAgAJCABAGIANB4BNqIBRCACASQgAQBiADQZAUaiAWQgAgFkIAEAYgA0HAEmogF0IAIBVCABAGIANBsBJqIAsgDlStIAogDlatIANB6BJqKQMAIANB6BRqKQMAfHwgCUI0iHx8Ig1CDIYgC0I0iIQiCiADKQPAEnwiCUIAQpD6gICAAkIAEAYgA0GgEmogCSAKVK0gA0HIEmopAwAgDUI0iHx8QgBCgIDEnoCAwABCABAGIBNC////////P4MgAykDoBIiDiAPQv7///////8Hg3wiESADKQPgEyILIAMpA5AUfCIQIAMpA7ASfCIMIAMpA9ASIgogAykD8BN8Ig8gAykD8BIiCSADKQPQE3wiEkI0iCAJIBJWrSADQfgSaikDACADQdgTaikDAHx8IglCDIaEfCINQjSIIA0gD1StIAogD1atIANB2BJqKQMAIANB+BNqKQMAfHwgCUI0iHx8IgpCDIaEfCIJQjSIIAkgDFStIAwgEFStIANBuBJqKQMAIAsgEFatIANB6BNqKQMAIANBmBRqKQMAfHx8fCAKQjSIfHwiC0IMhoR8IgpCNIggCiARVK0gA0GoEmopAwAgDiARVq18IAtCNIh8fEIMhoR8IRggAkEBaiICQRdHDQALIANBgBJqIBJC/////////weDIh1CACA1QgAQBiADQdARaiANQv////////8HgyIaQgAgNkIAEAYgA0GAEWogCUL/////////B4MiGUIAIDdCABAGIANBkBBqIApC/////////weDIhtCACA4QgAQBiADQdAPaiAYQgAgM0IAEAYgA0HAD2ogAykD0A9CAEKQ+oCAgAJCABAGIANBkBJqIB1CACAzQgAQBiADQfARaiAaQgAgNUIAEAYgA0GwEWogGUIAIDZCABAGIANB0BBqIBtCACA3QgAQBiADQaAPaiA4QgAgGEIAEAYgA0GwD2ogA0HYD2opAwBCAEKAgMSegIDAAEIAEAYgA0GAEGogHUIAIDhCABAGIANB4BFqIBpCACAzQgAQBiADQaARaiAZQgAgNUIAEAYgA0HAEGogG0IAIDZCABAGIANBkA9qIDdCACAYQgAQBiADQYAPaiADKQPAECINIAMpA5APfCIXIAMpA6ARfCISIAMpA+ARfCIWIAMpA9AQIgogAykDoA98IhUgAykDsA98IhMgAykDsBF8IhQgAykD8BF8IhEgAykDkBJ8IgwgAykDwA8iCSADKQOQEHwiDyADKQOAEXwiDiADKQPQEXwiCyADKQOAEnwiEEI0iCALIBBWrSADQYgSaikDACALIA5UrSADQdgRaikDACAOIA9UrSADQYgRaikDACAJIA9WrSADQcgPaikDACADQZgQaikDAHx8fHx8fHx8IglCDIaEfCIcQjSIIAwgHFatIAwgEVStIANBmBJqKQMAIBEgFFStIANB+BFqKQMAIBMgFFatIANBuBFqKQMAIBMgFVStIANBuA9qKQMAIAogFVatIANB2BBqKQMAIANBqA9qKQMAfHx8fHx8fHx8fCAJQjSIfHwiCUIMhoR8IgtCBIZC8P////////8AgyAcQjCIQg+DhEIAQtGHgIAQQgAQBiADQfAQaiAdQgAgN0IAEAYgA0HwD2ogGkIAIDhCABAGIANBkBFqIBlCACAzQgAQBiADQbAQaiAbQgAgNUIAEAYgA0HwDmogNkIAIBhCABAGIANB4A5qIAMpA7AQIgogAykD8A58IgwgAykDkBF8Ig8gCyAWVK0gEiAWVq0gA0HoEWopAwAgEiAXVK0gA0GoEWopAwAgDSAXVq0gA0HIEGopAwAgA0GYD2opAwB8fHx8fHwgCUI0iHx8IglCDIYgC0I0iIR8Ig5C/////////weDQgBCkPqAgIACQgAQBiADQcARaiAdQgAgNkIAEAYgA0HgEGogGkIAIDdCABAGIANB4A9qIBlCACA4QgAQBiADQaAQaiAbQgAgM0IAEAYgA0HQDmogNUIAIBhCABAGIANBwA5qIAMpA6AQIg0gAykD0A58IgsgDiAPVK0gDCAPVq0gA0GYEWopAwAgCiAMVq0gA0G4EGopAwAgA0H4DmopAwB8fHx8IAlCNIh8fCIKQgyGIA5CNIiEfCIJQgBCkPqAgIACQgAQBiADQbAOaiAJIAtUrSALIA1UrSADQagQaikDACADQdgOaikDAHx8IApCNIh8fEIAQoCAxJ6AgMAAQgAQBiAcQv///////z+DIAMpA7AOIg4gEEL/////////B4N8IhMgAykD4BAiCyADKQPgD3wiFCADKQPAEXwiESADKQPADnwiECADKQPwECIKIAMpA/APfCIMIAMpA+AOfCIPIAMpA4APIgkgAykDgBB8IhJCNIggCSASVq0gA0GID2opAwAgA0GIEGopAwB8fCIJQgyGhHwiDUI0iCANIA9UrSAMIA9WrSADQegOaikDACAKIAxWrSADQfgQaikDACADQfgPaikDAHx8fHwgCUI0iHx8IgpCDIaEfCIJQjSIIAkgEFStIBAgEVStIANByA5qKQMAIBEgFFStIANByBFqKQMAIAsgFFatIANB6BBqKQMAIANB6A9qKQMAfHx8fHx8IApCNIh8fCILQgyGhHwiCkI0iCAKIBNUrSADQbgOaikDACAOIBNWrXwgC0I0iHx8QgyGhHwhGEEAIQIDQCADQcANaiASQv////////8HgyILQgGGIhRCACAKQv////////8HgyIXQgAQBiADQfANaiANQv////////8HgyIWQgGGIgpCACAJQv////////8HgyISQgAQBiADQYANaiAYQgAgGEIAEAYgA0HwDGogAykDgA1CAEKQ+oCAgAJCABAGIANB0AxqIAtCACAYQgGGIhVCABAGIANB4A1qIApCACAXQgAQBiADQZAOaiASQgAgEkIAEAYgA0HgDGogA0GIDWopAwBCAEKAgMSegIDAAEIAEAYgA0GQDWogC0IAIAtCABAGIANBwAxqIBZCACAVQgAQBiADQYAOaiASQgGGQgAgF0IAEAYgA0GwDGogAykDwAwiDSADKQOADnwiESADKQOQDiIKIAMpA+AMfCIQIAMpA+ANfCIMIAMpA9AMfCIOIAMpA/ANIgkgAykD8Ax8IgsgAykDwA18Ig9CNIggCyAPVq0gA0HIDWopAwAgCSALVq0gA0H4DWopAwAgA0H4DGopAwB8fHx8IglCDIaEfCITQjSIIA4gE1atIAwgDlatIANB2AxqKQMAIAwgEFStIANB6A1qKQMAIAogEFatIANBmA5qKQMAIANB6AxqKQMAfHx8fHx8IAlCNIh8fCIJQgyGhHwiC0IEhkLw/////////wCDIBNCMIhCD4OEQgBC0YeAgBBCABAGIANBsA1qIBRCACAWQgAQBiADQaAMaiASQgAgFUIAEAYgA0GgDmogF0IAIBdCABAGIANBkAxqIAMpA6AMIgogAykDoA58Ig4gCyARVK0gDSARVq0gA0HIDGopAwAgA0GIDmopAwB8fCAJQjSIfHwiCUIMhiALQjSIhHwiC0L/////////B4NCAEKQ+oCAgAJCABAGIANBoA1qIBRCACASQgAQBiADQdANaiAWQgAgFkIAEAYgA0GADGogF0IAIBVCABAGIANB8AtqIAsgDlStIAogDlatIANBqAxqKQMAIANBqA5qKQMAfHwgCUI0iHx8Ig1CDIYgC0I0iIQiCiADKQOADHwiCUIAQpD6gICAAkIAEAYgA0HgC2ogCSAKVK0gA0GIDGopAwAgDUI0iHx8QgBCgIDEnoCAwABCABAGIBNC////////P4MgAykD4AsiDiAPQv7///////8Hg3wiESADKQOgDSILIAMpA9ANfCIQIAMpA/ALfCIMIAMpA5AMIgogAykDsA18Ig8gAykDsAwiCSADKQOQDXwiEkI0iCAJIBJWrSADQbgMaikDACADQZgNaikDAHx8IglCDIaEfCINQjSIIA0gD1StIAogD1atIANBmAxqKQMAIANBuA1qKQMAfHwgCUI0iHx8IgpCDIaEfCIJQjSIIAkgDFStIAwgEFStIANB+AtqKQMAIAsgEFatIANBqA1qKQMAIANB2A1qKQMAfHx8fCAKQjSIfHwiC0IMhoR8IgpCNIggCiARVK0gA0HoC2opAwAgDiARVq18IAtCNIh8fEIMhoR8IRggAkEBaiICQQZHDQALIANBwAtqIBJC/////////weDIh1CACAnQgAQBiADQZALaiANQv////////8HgyIaQgAgKkIAEAYgA0HACmogCUL/////////B4MiGUIAIDBCABAGIANB0AlqIApC/////////weDIhtCACAyQgAQBiADQZAJaiAYQgAgMUIAEAYgA0GACWogAykDkAlCAEKQ+oCAgAJCABAGIANB0AtqIB1CACAxQgAQBiADQbALaiAaQgAgJ0IAEAYgA0HwCmogGUIAICpCABAGIANBkApqIBtCACAwQgAQBiADQeAIaiAyQgAgGEIAEAYgA0HwCGogA0GYCWopAwBCAEKAgMSegIDAAEIAEAYgA0HACWogHUIAIDJCABAGIANBoAtqIBpCACAxQgAQBiADQeAK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aiAJIAtUrSALIA1UrSADQegJaikDACADKQPoB3x8IApCNIh8fEIAQoCAxJ6AgMAAQgAQBiADQYAHaiADKQOQByILIBBC/////////weDfCITIAMpA6AKIg0gAykDoAl8IhEgAykDgAt8IhAgAykD0Ad8IgwgAykDsAoiCiADKQOwCXwiDyADKQOQCHwiDiADKQPACCIJIAMpA8AJfCIWQjSIIAkgFlatIANByAhqKQMAIANByAlqKQMAfHwiCUIMhoR8IhVCNIggDiAVVq0gDiAPVK0gA0GYCGopAwAgCiAPVq0gA0G4CmopAwAgA0G4CWopAwB8fHx8IAlCNIh8fCIJQgyGhHwiDkI0iCAMIA5WrSAMIBBUrSADKQPYByAQIBFUrSADQYgLaikDACANIBFWrSADQagKaikDACADQagJaikDAHx8fHx8fCAJQjSIfHwiCkIMhoR8Ig1C/////////weDIhdCACAWQgGGQv7///////8PgyIUQgAQBiADQcAHaiAOQv////////8HgyISQgAgFUIBhkL+////////D4MiCUIAEAYgA0HABmogHEL///////8/gyANIBNUrSADKQOYByALIBNWrXwgCkI0iHx8QgyGIA1CNIiEfCINQgAgDUIAEAYgA0GwBmogAykDwAZCAEKQ+oCAgAJCABAGIANBkAZqIBZC/////////weDIgpCACANQgGGIhZCABAGIANB8AZqIBdCACAJQgAQBiADQbAHaiASQgAgEkIAEAYgA0GgBmogAykDyAZCAEKAgMSegIDAAEIAEAYgA0GwCGogCkIAIApCABAGIANBgAZqIBVC/////////weDIhVCACAWQgAQBiADQdAGaiAXQgAgDkIBhkL+////////D4NCABAGIANBoAVqIAMpA4AGIg0gAykD0AZ8IhEgAykD8AYiCiADKQOwB3wiECADKQOQBnwiDCADKQOgBnwiDiADKQOAByIJIAMpA8AHfCILIAMpA7AGfCIPQjSIIAsgD1atIAMpA7gGIAkgC1atIAMpA4gHIAMpA8gHfHx8fCIJQgyGhHwiE0I0iCAOIBNWrSAMIA5WrSADKQOoBiAMIBBUrSADKQOYBiAKIBBWrSADKQP4BiADKQO4B3x8fHx8fCAJQjSIfHwiCUIMhoR8IgtCBIZC8P////////8AgyATQjCIQg+DhEIAQtGHgIAQQgAQBiADQYAIaiAVQgAgFEIAEAYgA0HwBWogEkIAIBZCABAGIANB4AZqIBdCACAXQgAQBiADQeAFaiADKQPwBSIKIAMpA+AGfCIOIAsgEVStIA0gEVatIAMpA4gGIAMpA9gGfHwgCUI0iHx8IglCDIYgC0I0iIR8IgtC/////////weDQgBCkPqAgIACQgAQBiADQaAHaiASQgAgFEIAEAYgA0HwB2ogFUIAIBVCABAGIANB0AVqIBdCACAWQgAQBiADQcAFaiALIA5UrSAKIA5WrSADKQP4BSADKQPoBnx8IAlCNIh8fCINQgyGIAtCNIiEIgogAykD0AV8IglCAEKQ+oCAgAJCABAGIANBsAVqIAkgClStIAMpA9gFIA1CNIh8fEIAQoCAxJ6AgMAAQgAQBiADQdAEaiADKQOwBSILIA9C/v///////weDfCIQIAMpA6AHIg0gAykD8Ad8IgwgAykDwAV8Ig8gAykD4AUiCiADKQOACHwiDiADKQOgBSIJIAMpA7AIfCIUQjSIIAkgFFatIAMpA6gFIANBuAhqKQMAfHwiCUIMhoR8IhFCNIggDiARVq0gCiAOVq0gAykD6AUgA0GICGopAwB8fCAJQjSIfHwiCUIMhoR8Ig5CNIggDiAPVK0gDCAPVq0gAykDyAUgDCANVK0gAykDqAcgAykD+Ad8fHx8IAlCNIh8fCIKQgyGhHwiDUL/////////B4MiGUIAIBRCAYZC/v///////w+DIhVCABAGIANBoARqIA5C/////////weDIhtCACARQgGGQv7///////8PgyIJQgAQBiADQfADaiATQv///////z+DIA0gEFStIAMpA7gFIAsgEFatfCAKQjSIfHxCDIYgDUI0iIR8Ig1CACANQgAQBiADQeADaiADKQPwA0IAQpD6gICAAkIAEAYgA0HAA2ogFEL/////////B4MiCkIAIA1CAYYiF0IAEAYgA0GQBGogGUIAIAlCABAGIANBgAVqIBtCACAbQgAQBiADQdADaiADKQP4A0IAQoCAxJ6AgMAAQgAQBiADQeAEaiAKQgAgCkIAEAYgA0GwA2ogEUL/////////B4MiEkIAIBdCABAGIANBgARqIBlCACAOQgGGQv7///////8Pg0IAEAYgA0HQAmogAykDsAMiCyADKQOABHwiECADKQOQBCIKIAMpA4AFfCIMIAMpA8ADfCIPIAMpA9ADfCIOIAMpA9AEIgkgAykDoAR8Ig0gAykD4AN8IhNCNIggDSATVq0gAykD6AMgCSANVq0gAykD2AQgAykDqAR8fHx8IglCDIaEfCIWQjSIIA4gFlatIA4gD1StIAMpA9gDIAwgD1atIAMpA8gDIAogDFatIAMpA5gEIAMpA4gFfHx8fHx8IAlCNIh8fCIKQgyGhHwiD0IEhkLw/////////wCDIBZCMIhCD4OEQgBC0YeAgBBCABAGIAUgAykD0AIiCSADKQPgBHwiDEL/////////B4MiHDcDKCADQcAEaiASQgAgFUIAEAYgA0GgA2ogG0IAIBdCABAGIANBkAVqIBlCACAZQgAQBiADQZADaiADKQOgAyINIAMpA5AFfCIOIA8gEFStIAsgEFatIAMpA7gDIAMpA4gEfHwgCkI0iHx8IgpCDIYgD0I0iIR8IgtC/////////weDQgBCkPqAgIACQgAQBiAFIAMpA5ADIg8gAykDwAR8IhQgCSAMVq0gAykD2AIgAykD6AR8fCIJQgyGIAxCNIiEfCIRQv////////8HgyIdNwMwIANBsARqIBtCACAVQgAQBiADQfAEaiASQgAgEkIAEAYgA0GAA2ogGUIAIBdCABAGIANB8AJqIAsgDlStIA0gDlatIAMpA6gDIAMpA5gFfHwgCkI0iHx8Ig5CDIYgC0I0iIQiCyADKQOAA3wiCkIAQpD6gICAAkIAEAYgBSADKQOwBCINIAMpA/AEfCIQIAMpA/ACfCIMIBEgFFStIA8gFFatIAMpA5gDIAMpA8gEfHwgCUI0iHx8IglCDIYgEUI0iIR8Ig9C/////////weDIhU3AzggA0HgAmogCiALVK0gAykDiAMgDkI0iHx8QgBCgIDEnoCAwABCABAGIAUgAykD4AIiCiATQv7///////8Hg3wiCyAMIA9WrSAMIBBUrSADKQP4AiANIBBWrSADKQO4BCADKQP4BHx8fHwgCUI0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ETIAMpA5ACIRQgAykDUCEbIAMpA/gBIREgAykDOCEQIAMpA/ABIQkgAykDMCEcIAMpA6gCIQwgAykD6AEhDyADKQOgAiEOIAMpA+ABIRcgAykDGCELIAMpAxAhDSADKQMAIRIgAykDCCEKIANBsNwAaiQAICYgCSAcfCIWIBQgG3wiFEI0iCAUIBtUrSATIBV8fCIJQgyGhHwiFUL/////////B4N9ICkgFEL/////////B4N9IC8gGkL///////8/gyASIBlC/v///////weDfCITIA0gDiAXfCIUfCIOIBUgFlStIBYgHFStIBAgEXx8IAlCNIh8fCIJQgyGIBVCNIiEfCINQjSIIA0gDlStIA4gFFStIAsgFCAXVK0gDCAPfHx8fCAJQjSIfHwiCUIMhoR8Ig9CNIggDyATVK0gCiASIBNWrXwgCUI0iHx8QgyGhHx9Qvz///////8BfCIJQjCIQtGHgIAQfnxCvOH//7///x98Ig5CNIh8Qvz///////8ffCILIA6EICUgDUL/////////B4N9IAtCNIh8Qvz///////8ffCINhCAkIA9C/////////weDfSANQjSIfEL8////////H3wiCoRC/////////weDIAlC////////P4MgCkI0iHwiCYRQBH9BAQUgDkLQh4CAEIUgCUKAgICAgIDAB4WDIAuDIA2DIAqDQv////////8HUQshAiAFKQMwIAUpAyggBSkDSCIOQjCIQtGHgIAQfnwiC0I0iHwiDEL/////////B4MhDSAFKQNAIAUpAzggDEI0iHwiCUI0iHwiD0L/////////B4MhCiAFIA5C////////P4MgD0I0iHwiEEIwiCAPIAwgCUL/////////B4MiDoODQv////////8HUSAQQv///////z9RcSALQv////////8HgyILQq74///v//8HVnGthKcEfiALQtGHgIAQfCIJQv////////8HgyELIA0gCUI0iHwiCUL/////////B4MhDSAOIAlCNIh8IglC/////////weDIQ4gCiAJQjSIfCIJQv////////8HgyEKIAlCNIggEHxC////////P4MFIBALNwNIIAUgCjcDQCAFIA43AzggBSANNwMwIAUgCzcDKCAFKQMoIgmnQQFxBEAgBUK84f//v///HyAJfTcDKCAFQvz///////8fIAUpAzB9NwMwIAVC/P///////x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cwoAAAMAAAAAAAAAAQBB4JACC27winjLuu4IKwUq4HCPMvoeUMXEIap3K6XbtAai6mvjQpgX+BZbgQIAn5WN4tyyDQD8mwIHC4cOAFwpBlrFugsA3Pl+Zr55AAC41BD7j9AHAMSZQVVoigQAtBf9qAgRDgDAv0/aVUYMAKMmd9o6SABB2JECCwgv/P///v///wBB+ZECCx8BAAAAAAAAz8raLeL2xyfD5L8KqX9UbyiIDgHWfkPkAEGokgIL2gEsVrE9qM1l1200dAfFCiiK/v///////////////////zGw20WaIJPof8rocRSKqj0V64SS5JBs6M1r1Kch0oYwcX/Eiq60cRXGBvWdrAgSIsTkvwqpf1RvKIgOAdZ+Q+RyvSMbfJYC33hmgSDqIi4SWmQSiAIcJqXgMFzATK1jU+4BlXEobAkAE1yZWC9RBwBJ8JzpNDQMAOp5ROYGcQAAfGUraul6AABU8WnPyeLlcnSARB+QuiXEiPRhxwtepdyq969pJwqlFEJJUDAzNDAvbm9uY2UAAADwiwBBkJQCC0EZAAoAGRkZAAAAAAUAAAAAAAAJAAAAAAsAAAAAAAAAABkAEQoZGRkDCgcAAQAJCxgAAAkGCwAACwAGGQAAABkZGQBB4ZQCCyEOAAAAAAAAAAAZAAoNGRkZAA0AAAIACQ4AAAAJAA4AAA4AQZuVAgsBDABBp5UCCxUTAAAAABMAAAAACQwAAAAAAAwAAAwAQdWVAgsBEABB4ZUCCxUPAAAABA8AAAAACRAAAAAAABAAABAAQY+WAgsBEgBBm5YCCx4RAAAAABEAAAAACRIAAAAAABIAABIAABoAAAAaGhoAQdKWAgsOGgAAABoaGgAAAAAAAAkAQYOXAgsBFABBj5cCCxUXAAAAABcAAAAACRQAAAAAABQAABQAQb2XAgsBFgBByZcCCycVAAAAABUAAAAACRYAAAAAABYAABYAADAxMjM0NTY3ODlBQkNERUYAQfCXAgsBBQBB/JcCCwEEAEGUmAILCgUAAAAGAAAAyIwAQayYAgsBAgBBvJgCCwj//////////wBBgJkCCwNAjwE="; + +const initNostrWasm = () => NostrWasm(new Uint8Array(atob(sb64_data) + .split('') + .map(s => s.charCodeAt(0)))); + +export { NostrWasm, initNostrWasm }; diff --git a/node_modules/nostr-wasm/dist/nostr.js b/node_modules/nostr-wasm/dist/nostr.js new file mode 100644 index 0000000..f5ba47e --- /dev/null +++ b/node_modules/nostr-wasm/dist/nostr.js @@ -0,0 +1,248 @@ +function defineWasmEnv(label) { + label += ': '; + let AB_HEAP; + let ATU8_HEAP; + let ATU32_HEAP; + // eslint-disable-next-line no-console + const console_out = (s_channel, s_out) => console[s_channel](label + s_out.replace(/\0/g, '\n')); + let s_error = ''; + // for converting bytes to text + const utf8 = new TextDecoder(); + const h_fds = { + // stdout + 1(s_out) { + console_out('debug', s_out); + }, + // stderr + 2(s_out) { + console_out('error', (s_error = s_out)); + } + }; + const imports = { + abort() { + throw Error(label + (s_error || 'An unknown error occurred')); + }, + memcpy: (ip_dst, ip_src, nb_size) => ATU8_HEAP.copyWithin(ip_dst, ip_src, ip_src + nb_size), + resize(w) { + throw Error(label + `Out of memory (resizing ${w})`); + }, + write(i_fd, ip_iov, nl_iovs, ip_written) { + // output string + let s_out = ''; + // track number of bytes read from buffers + let cb_read = 0; + // each pending iov + for (let i_iov = 0; i_iov < nl_iovs; i_iov++) { + // start of buffer in memory + const ip_start = ATU32_HEAP[ip_iov >> 2]; + // size of buffer + const nb_len = ATU32_HEAP[(ip_iov + 4) >> 2]; + ip_iov += 8; + // extract text from buffer + s_out += utf8.decode(ATU8_HEAP.subarray(ip_start, ip_start + nb_len)); + // update number of bytes read + cb_read += nb_len; + } + // route to fd + if (h_fds[i_fd]) { + h_fds[i_fd](s_out); + } + else { + // no fd found + throw new Error(`libsecp256k1 tried writing to non-open file descriptor: ${i_fd}\n${s_out}`); + } + // write bytes read + ATU32_HEAP[ip_written >> 2] = cb_read; + // no error + return 0; + } + }; + return [ + imports, + (d_memory) => [ + (AB_HEAP = d_memory.buffer), + (ATU8_HEAP = new Uint8Array(AB_HEAP)), + (ATU32_HEAP = new Uint32Array(AB_HEAP)) + ] + ]; +} + +/* +* ================================ +* GENERATED FILE WARNING +* Do not edit this file manually. +* ================================ +*/ +const map_wasm_imports = (g_imports) => ({ + a: { + a: g_imports.abort, + f: g_imports.memcpy, + d: g_imports.resize, + e: () => 52, // _fd_close, + c: () => 70, // _fd_seek, + b: g_imports.write, + }, +}); +const map_wasm_exports = (g_exports) => ({ + malloc: g_exports['i'], + free: g_exports['j'], + sha256_initialize: g_exports['l'], + sha256_write: g_exports['m'], + sha256_finalize: g_exports['n'], + context_create: g_exports['o'], + xonly_pubkey_parse: g_exports['p'], + xonly_pubkey_serialize: g_exports['q'], + keypair_create: g_exports['r'], + keypair_xonly_pub: g_exports['s'], + schnorrsig_sign32: g_exports['t'], + schnorrsig_verify: g_exports['u'], + sbrk: g_exports['sbrk'], + memory: g_exports['g'], + init: () => g_exports['h'](), +}); + +/** + * Creates a new instance of the secp256k1 WASM and returns the Nostr wrapper + * @param z_src - a Response containing the WASM binary, a Promise that resolves to one, + * or the raw bytes to the WASM binary as a {@link BufferSource} + * @returns the wrapper API + */ +const NostrWasm = async (z_src) => { + // prepare the runtime + const [defs, f_bind_heap] = defineWasmEnv('nostr-wasm'); + const g_imports = map_wasm_imports(defs); + // prep the wasm module + let d_wasm; + // instantiate wasm binary by streaming the response bytes + if (z_src instanceof Response || z_src instanceof Promise) { + d_wasm = await WebAssembly.instantiateStreaming(z_src, g_imports); + } + else { + // instantiate using raw binary + d_wasm = await WebAssembly.instantiate(z_src, g_imports); + } + // create the exports struct + const g_wasm = map_wasm_exports(d_wasm.instance.exports); + // bind the heap and ref its view(s) + const [, ATU8_HEAP] = f_bind_heap(g_wasm.memory); + // call into the wasm module's init method + g_wasm.init(); + const ip_sk = g_wasm.malloc(32 /* ByteLens.PRIVATE_KEY */); + const ip_ent = g_wasm.malloc(32 /* ByteLens.NONCE_ENTROPY */); + const ip_msg_hash = g_wasm.malloc(32 /* ByteLens.MSG_HASH */); + // scratch spaces + const ip_pubkey_scratch = g_wasm.malloc(32 /* ByteLens.XONLY_PUBKEY */); + const ip_sig_scratch = g_wasm.malloc(64 /* ByteLens.BIP340_SIG */); + // library handle: secp256k1_keypair; + const ip_keypair = g_wasm.malloc(96 /* ByteLens.KEYPAIR_LIB */); + // library handle: secp256k1_xonly_pubkey; + const ip_xonly_pubkey = g_wasm.malloc(64 /* ByteLens.XONLY_KEY_LIB */); + // library handle: secp256k1_sha256; + const ip_sha256 = g_wasm.malloc(104 /* ByteLens.SHA256_LIB */); + // create a reusable context + const ip_ctx = g_wasm.context_create(513 /* Flags.CONTEXT_SIGN */ | 257 /* Flags.CONTEXT_VERIFY */); + // an encoder for hashing strings + const utf8 = new TextEncoder(); + /** + * Puts the given private key into program memory, runs the given callback, then zeroes out the key + * @param atu8_sk - the private key + * @param f_use - callback to use the key + * @returns whatever the callback returns + */ + const with_keypair = (atu8_sk, f_use) => { + // prep callback return + let w_return; + // in case of any exception.. + try { + // copy input bytes into place + ATU8_HEAP.set(atu8_sk, ip_sk); + // instantiate keypair + g_wasm.keypair_create(ip_ctx, ip_keypair, ip_sk); + // use private key + w_return = f_use(); + } + finally { + // zero-out private key and keypair + ATU8_HEAP.fill(1, ip_sk, ip_sk + 32 /* ByteLens.PRIVATE_KEY */); + ATU8_HEAP.fill(2, ip_keypair, ip_keypair + 96 /* ByteLens.KEYPAIR_LIB */); + } + // forward result + return w_return; + }; + const compute_event_id = (event) => { + const message = utf8.encode(`[0,"${event.pubkey}",${event.created_at},${event.kind},${JSON.stringify(event.tags)},${JSON.stringify(event.content)}]`); + const ip_message = g_wasm.malloc(message.length); + ATU8_HEAP.set(message, ip_message); + g_wasm.sha256_initialize(ip_sha256); + g_wasm.sha256_write(ip_sha256, ip_message, message.length); + g_wasm.sha256_finalize(ip_sha256, ip_msg_hash); + g_wasm.free(ip_message); + return ATU8_HEAP.slice(ip_msg_hash, ip_msg_hash + 32 /* ByteLens.MSG_HASH */); + }; + return { + generateSecretKey: () => crypto.getRandomValues(new Uint8Array(32 /* ByteLens.PRIVATE_KEY */)), + getPublicKey(sk) { + if (1 /* BinaryResult.SUCCESS */ !== + with_keypair(sk, () => g_wasm.keypair_xonly_pub(ip_ctx, ip_xonly_pubkey, null, ip_keypair))) { + throw Error('failed to get pubkey from keypair'); + } + // serialize the public key + g_wasm.xonly_pubkey_serialize(ip_ctx, ip_pubkey_scratch, ip_xonly_pubkey); + // extract result + return ATU8_HEAP.slice(ip_pubkey_scratch, ip_pubkey_scratch + 32 /* ByteLens.XONLY_PUBKEY */); + }, + finalizeEvent(event, seckey, ent) { + with_keypair(seckey, () => { + // get public key (as in getPublicKey function above) + g_wasm.keypair_xonly_pub(ip_ctx, ip_xonly_pubkey, null, ip_keypair); + g_wasm.xonly_pubkey_serialize(ip_ctx, ip_pubkey_scratch, ip_xonly_pubkey); + const pubkey = ATU8_HEAP.slice(ip_pubkey_scratch, ip_pubkey_scratch + 32 /* ByteLens.XONLY_PUBKEY */); + event.pubkey = toHex(pubkey); + // compute event id + event.id = toHex(compute_event_id(event)); + // copy entropy bytes into place, if they are provided + if (!ent && crypto.getRandomValues) { + ATU8_HEAP.set(crypto.getRandomValues(new Uint8Array(32)), ip_ent); + } + // perform signature (ip_msg_hash is already set from procedure above) + if (1 /* BinaryResult.SUCCESS */ !== + g_wasm.schnorrsig_sign32(ip_ctx, ip_sig_scratch, ip_msg_hash, ip_keypair, ip_ent)) { + throw Error('failed to sign'); + } + }); + const sig = ATU8_HEAP.slice(ip_sig_scratch, ip_sig_scratch + 64 /* ByteLens.BIP340_SIG */); + event.sig = toHex(sig); + }, + verifyEvent(event) { + const id = fromHex(event.id); + // check event hash + const computed = compute_event_id(event); + for (let i = 0; i < id.length; i++) { + if (id[i] !== computed[i]) + throw Error('id is invalid'); + } + // copy event data into place + ATU8_HEAP.set(fromHex(event.sig), ip_sig_scratch); + ATU8_HEAP.set(fromHex(event.id), ip_msg_hash); + ATU8_HEAP.set(fromHex(event.pubkey), ip_pubkey_scratch); + // parse the public key + if (1 /* BinaryResult.SUCCESS */ !== + g_wasm.xonly_pubkey_parse(ip_ctx, ip_xonly_pubkey, ip_pubkey_scratch)) { + throw Error('pubkey is invalid'); + } + // verify the signature + if (1 /* BinaryResult.SUCCESS */ !== + g_wasm.schnorrsig_verify(ip_ctx, ip_sig_scratch, ip_msg_hash, 32 /* ByteLens.MSG_HASH */, ip_xonly_pubkey)) { + throw Error('signature is invalid'); + } + } + }; +}; +function toHex(bytes) { + return bytes.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), ''); +} +function fromHex(hex) { + return new Uint8Array(hex.length / 2).map((_, i) => parseInt(hex.slice(i * 2, i * 2 + 2), 16)); +} + +export { NostrWasm as N }; diff --git a/node_modules/nostr-wasm/dist/secp256k1.js b/node_modules/nostr-wasm/dist/secp256k1.js new file mode 100644 index 0000000..c8fc21e --- /dev/null +++ b/node_modules/nostr-wasm/dist/secp256k1.js @@ -0,0 +1,230 @@ +const emsimp = (f_map_imports, s_tag) => { + s_tag += ': '; + let AB_HEAP; + let ATU8_HEAP; + let ATU32_HEAP; + // eslint-disable-next-line no-console + const console_out = (s_channel, s_out) => console[s_channel](s_tag + s_out.replace(/\0/g, '\n')); + let s_error = ''; + // for converting bytes to text + const utf8 = new TextDecoder(); + const h_fds = { + // stdout + 1(s_out) { + console_out('debug', s_out); + }, + // stderr + 2(s_out) { + console_out('error', (s_error = s_out)); + } + }; + const g_imports = f_map_imports({ + abort() { + throw Error(s_tag + (s_error || 'An unknown error occurred')); + }, + memcpy: (ip_dst, ip_src, nb_size) => ATU8_HEAP.copyWithin(ip_dst, ip_src, ip_src + nb_size), + resize(_) { + throw Error(s_tag + 'Out of memory'); + }, + write(i_fd, ip_iov, nl_iovs, ip_written) { + // output string + let s_out = ''; + // track number of bytes read from buffers + let cb_read = 0; + // each pending iov + for (let i_iov = 0; i_iov < nl_iovs; i_iov++) { + // start of buffer in memory + const ip_start = ATU32_HEAP[ip_iov >> 2]; + // size of buffer + const nb_len = ATU32_HEAP[(ip_iov + 4) >> 2]; + ip_iov += 8; + // extract text from buffer + s_out += utf8.decode(ATU8_HEAP.subarray(ip_start, ip_start + nb_len)); + // update number of bytes read + cb_read += nb_len; + } + // route to fd + if (h_fds[i_fd]) { + h_fds[i_fd](s_out); + } + else { + // no fd found + throw new Error(`libsecp256k1 tried writing to non-open file descriptor: ${i_fd}\n${s_out}`); + } + // write bytes read + ATU32_HEAP[ip_written >> 2] = cb_read; + // no error + return 0; + } + }); + return [ + g_imports, + (d_memory) => [ + (AB_HEAP = d_memory.buffer), + (ATU8_HEAP = new Uint8Array(AB_HEAP)), + (ATU32_HEAP = new Uint32Array(AB_HEAP)) + ] + ]; +}; + +/* +* ================================ +* GENERATED FILE WARNING +* Do not edit this file manually. +* ================================ +*/ +const map_wasm_imports = (g_imports) => ({ + a: { + a: g_imports.abort, + f: g_imports.memcpy, + d: g_imports.resize, + e: () => 52, // _fd_close, + c: () => 70, // _fd_seek, + b: g_imports.write, + }, +}); +const map_wasm_exports = (g_exports) => ({ + malloc: g_exports['i'], + free: g_exports['j'], + sha256_initialize: g_exports['l'], + sha256_write: g_exports['m'], + sha256_finalize: g_exports['n'], + context_create: g_exports['o'], + xonly_pubkey_parse: g_exports['p'], + xonly_pubkey_serialize: g_exports['q'], + keypair_create: g_exports['r'], + keypair_xonly_pub: g_exports['s'], + schnorrsig_sign32: g_exports['t'], + schnorrsig_verify: g_exports['u'], + sbrk: g_exports['sbrk'], + memory: g_exports['g'], + init: () => g_exports['h'](), +}); + +const S_TAG_BIP340_VERIFY = 'BIP340 verify: '; +const S_REASON_INVALID_SK = 'Invalid private key'; +const S_REASON_INVALID_PK = 'Invalid public key'; +/** + * Creates a new instance of the secp256k1 WASM and returns its ES wrapper + * @param z_src - a Response containing the WASM binary, a Promise that resolves to one, + * or the raw bytes to the WASM binary as a {@link BufferSource} + * @returns the wrapper API + */ +const WasmSecp256k1 = async (z_src) => { + // prepare the runtime + const [g_imports, f_bind_heap] = emsimp(map_wasm_imports, 'wasm-secp256k1'); + // prep the wasm module + let d_wasm; + // instantiate wasm binary by streaming the response bytes + if (z_src instanceof Response || z_src instanceof Promise) { + d_wasm = await WebAssembly.instantiateStreaming(z_src, g_imports); + } + else { + // instantiate using raw binary + d_wasm = await WebAssembly.instantiate(z_src, g_imports); + } + // create the libsecp256k1 exports struct + const g_wasm = map_wasm_exports(d_wasm.instance.exports); + // bind the heap and ref its view(s) + const [, ATU8_HEAP] = f_bind_heap(g_wasm.memory); + // call into the wasm module's init method + g_wasm.init(); + const ip_sk = g_wasm.malloc(32 /* ByteLens.PRIVATE_KEY */); + const ip_ent = g_wasm.malloc(32 /* ByteLens.NONCE_ENTROPY */); + const ip_msg_hash = g_wasm.malloc(32 /* ByteLens.MSG_HASH */); + // scratch spaces + const ip_pubkey_scratch = g_wasm.malloc(32 /* ByteLens.XONLY_PUBKEY */); + const ip_sig_scratch = g_wasm.malloc(64 /* ByteLens.BIP340_SIG */); + // library handle: secp256k1_keypair; + const ip_keypair = g_wasm.malloc(96 /* ByteLens.KEYPAIR_LIB */); + // library handle: secp256k1_xonly_pubkey; + const ip_xonly_pubkey = g_wasm.malloc(64 /* ByteLens.XONLY_KEY_LIB */); + // library handle: secp256k1_sha256; + const ip_sha256 = g_wasm.malloc(104 /* ByteLens.SHA256_LIB */); + // create a reusable context + const ip_ctx = g_wasm.context_create(513 /* Flags.CONTEXT_SIGN */ | 257 /* Flags.CONTEXT_VERIFY */); + // an encoder for hashing strings + const utf8 = new TextEncoder(); + /** + * Puts the given private key into program memory, runs the given callback, then zeroes out the key + * @param atu8_sk - the private key + * @param f_use - callback to use the key + * @returns whatever the callback returns + */ + const with_keypair = (atu8_sk, f_use) => { + // prep callback return + let w_return; + // in case of any exception.. + try { + // copy input bytes into place + ATU8_HEAP.set(atu8_sk, ip_sk); + // instantiate keypair + g_wasm.keypair_create(ip_ctx, ip_keypair, ip_sk); + // use private key + w_return = f_use(); + } + finally { + // zero-out private key and keypair + ATU8_HEAP.fill(1, ip_sk, ip_sk + 32 /* ByteLens.PRIVATE_KEY */); + ATU8_HEAP.fill(2, ip_keypair, ip_keypair + 96 /* ByteLens.KEYPAIR_LIB */); + } + // forward result + return w_return; + }; + return { + gen_secret_key: () => crypto.getRandomValues(new Uint8Array(32 /* ByteLens.PRIVATE_KEY */)), + get_public_key(atu8_sk) { + // while using the private key, compute its corresponding public key; from the docs: + if (1 /* BinaryResult.SUCCESS */ !== + with_keypair(atu8_sk, () => g_wasm.keypair_xonly_pub(ip_ctx, ip_xonly_pubkey, null, ip_keypair))) { + throw Error('sk_to_pk: ' + S_REASON_INVALID_SK); + } + // serialize the public key + g_wasm.xonly_pubkey_serialize(ip_ctx, ip_pubkey_scratch, ip_xonly_pubkey); + // extract result + return ATU8_HEAP.slice(ip_pubkey_scratch, ip_pubkey_scratch + 32 /* ByteLens.XONLY_PUBKEY */); + }, + sign(atu8_sk, atu8_hash, atu8_ent) { + // copy message hash bytes into place + ATU8_HEAP.set(atu8_hash, ip_msg_hash); + // copy entropy bytes into place + if (!atu8_ent && crypto.getRandomValues) { + ATU8_HEAP.set(crypto.getRandomValues(new Uint8Array(32)), ip_ent); + } + // while using the private key, sign the given message hash + if (1 /* BinaryResult.SUCCESS */ !== + with_keypair(atu8_sk, () => g_wasm.schnorrsig_sign32(ip_ctx, ip_sig_scratch, ip_msg_hash, ip_keypair, ip_ent))) { + throw Error('BIP-340 sign: ' + S_REASON_INVALID_SK); + } + // return serialized signature + return ATU8_HEAP.slice(ip_sig_scratch, ip_sig_scratch + 64 /* ByteLens.BIP340_SIG */); + }, + verify(atu8_signature, atu8_hash, atu8_pk) { + // copy signature bytes into place + ATU8_HEAP.set(atu8_signature, ip_sig_scratch); + // copy message hash bytes into place + ATU8_HEAP.set(atu8_hash, ip_msg_hash); + // copy pubkey bytes into place + ATU8_HEAP.set(atu8_pk, ip_pubkey_scratch); + // parse the public key + if (1 /* BinaryResult.SUCCESS */ !== + g_wasm.xonly_pubkey_parse(ip_ctx, ip_xonly_pubkey, ip_pubkey_scratch)) { + throw Error(S_TAG_BIP340_VERIFY + S_REASON_INVALID_PK); + } + // verify the signature + return (1 /* BinaryResult.SUCCESS */ === + g_wasm.schnorrsig_verify(ip_ctx, ip_sig_scratch, ip_msg_hash, 32 /* ByteLens.MSG_HASH */, ip_xonly_pubkey)); + }, + sha256(message) { + const ip_message = g_wasm.malloc(message.length); + const data = utf8.encode(message); + ATU8_HEAP.set(data, ip_message); + g_wasm.sha256_initialize(ip_sha256); + g_wasm.sha256_write(ip_sha256, ip_message, message.length); + g_wasm.sha256_finalize(ip_sha256, ip_msg_hash); + return ATU8_HEAP.slice(ip_msg_hash, ip_msg_hash + 32 /* ByteLens.MSG_HASH */); + } + }; +}; + +export { WasmSecp256k1 as W }; diff --git a/node_modules/nostr-wasm/dist/types.d.ts b/node_modules/nostr-wasm/dist/types.d.ts new file mode 100644 index 0000000..4a0860e --- /dev/null +++ b/node_modules/nostr-wasm/dist/types.d.ts @@ -0,0 +1,22 @@ +/// +export type Pointer = number & { + POINTER_TYPE: w_subtype; +}; +export type ByteSize = number; +export type ByteDelta = number; +export type ByteOffset = number; +export type FileDescriptor = number; +export type SeekWhence = number; +export interface WasmImports { + abort: () => void; + memcpy: (ip_dst: Pointer, ip_src: Pointer, nb_size: nb_size) => Uint8Array; + resize: (nb_size: ByteSize) => void; + write: (i_fd: FileDescriptor, ip_iov: Pointer, nl_iovs: number, ip_written: Pointer) => 0; +} +export interface WasmExports { + malloc: (nb_size: nb_size) => Pointer extends w_pointer_type ? Pointer : w_pointer_type; + free: (ip_ptr: Pointer) => void; + sbrk: (nb_change: ByteDelta) => Pointer; + memory: WebAssembly.Memory; + init: VoidFunction; +} diff --git a/node_modules/nostr-wasm/package.json b/node_modules/nostr-wasm/package.json new file mode 100644 index 0000000..e7e4a02 --- /dev/null +++ b/node_modules/nostr-wasm/package.json @@ -0,0 +1,37 @@ +{ + "name": "nostr-wasm", + "description": "nostr stuff in wasm", + "version": "0.1.0", + "type": "module", + "main": "dist/main.js", + "files": [ + "dist/", + "public/" + ], + "exports": { + ".": "./dist/main.js", + "./headless": "./dist/headless.js", + "./gzipped": "./dist/gzipped.js" + }, + "author": "fiatjaf ", + "license": "MIT", + "dependencies": {}, + "devDependencies": { + "@blake.regalia/tsconfig": "^0.1.2", + "@rollup/plugin-typescript": "^11.1.5", + "@rollup/plugin-wasm": "^6.2.2", + "@rollup/pluginutils": "^5.0.5", + "@types/node": "^20.8.10", + "@types/web": "^0.0.119", + "@typescript-eslint/eslint-plugin": "^6.13.2", + "@typescript-eslint/parser": "^6.13.2", + "acorn": "^8.11.2", + "eslint": "^8.52.0", + "eslint-plugin-unused-imports": "^3.0.0", + "rollup": "^4.2.0", + "typescript": "^5.2.2" + }, + "publishConfig": { + "access": "public" + } +} diff --git a/node_modules/nostr-wasm/public/out/secp256k1.js b/node_modules/nostr-wasm/public/out/secp256k1.js new file mode 100644 index 0000000..6ec189c --- /dev/null +++ b/node_modules/nostr-wasm/public/out/secp256k1.js @@ -0,0 +1 @@ +var Module=globalThis.Module||{};var ENVIRONMENT_IS_NODE=typeof process=="object";if(ENVIRONMENT_IS_NODE){var fs=require("fs");Module["wasm"]=fs.readFileSync(__dirname+"/secp256k1.wasm")}var out=text=>console.log(text);var err=text=>console.error(text);function ready(){}function abort(what){throw what}var HEAP8,HEAP16,HEAP32,HEAPU8,HEAPU16,HEAPU32,HEAPF32,HEAPF64,wasmMemory;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b)}var noExitRuntime=Module["noExitRuntime"]||true;var _abort=()=>{abort("")};var _emscripten_memcpy_js=(dest,src,num)=>HEAPU8.copyWithin(dest,src,src+num);var abortOnCannotGrowMemory=requestedSize=>{abort("OOM")};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;abortOnCannotGrowMemory(requestedSize)};var UTF8Decoder=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):undefined;var UTF8ArrayToString=(heapOrArray,idx,maxBytesToRead)=>{var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heapOrArray[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx>10,56320|ch&1023)}}return str};var UTF8ToString=(ptr,maxBytesToRead)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):"";var SYSCALLS={varargs:undefined,get(){var ret=HEAP32[+SYSCALLS.varargs>>2];SYSCALLS.varargs+=4;return ret},getp(){return SYSCALLS.get()},getStr(ptr){var ret=UTF8ToString(ptr);return ret}};var _fd_close=fd=>52;var convertI32PairToI53Checked=(lo,hi)=>hi+2097152>>>0<4194305-!!lo?(lo>>>0)+hi*4294967296:NaN;function _fd_seek(fd,offset_low,offset_high,whence,newOffset){var offset=convertI32PairToI53Checked(offset_low,offset_high);return 70}var printCharBuffers=[null,[],[]];var printChar=(stream,curr)=>{var buffer=printCharBuffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer,0));buffer.length=0}else{buffer.push(curr)}};var _fd_write=(fd,iov,iovcnt,pnum)=>{var num=0;for(var i=0;i>2];var len=HEAPU32[iov+4>>2];iov+=8;for(var j=0;j>2]=num;return 0};var wasmImports={a:_abort,f:_emscripten_memcpy_js,d:_emscripten_resize_heap,e:_fd_close,c:_fd_seek,b:_fd_write};function initRuntime(wasmExports){wasmExports["h"]()}var imports={"a":wasmImports};var _malloc,_free,_secp256k1_sha256_initialize,_secp256k1_sha256_write,_secp256k1_sha256_finalize,_secp256k1_context_create,_secp256k1_xonly_pubkey_parse,_secp256k1_xonly_pubkey_serialize,_secp256k1_keypair_create,_secp256k1_keypair_xonly_pub,_secp256k1_schnorrsig_sign32,_secp256k1_schnorrsig_verify,_sbrk;WebAssembly.instantiate(Module["wasm"],imports).then(output=>{var wasmExports=output.instance.exports;_malloc=wasmExports["i"];_free=wasmExports["j"];_secp256k1_sha256_initialize=wasmExports["l"];_secp256k1_sha256_write=wasmExports["m"];_secp256k1_sha256_finalize=wasmExports["n"];_secp256k1_context_create=wasmExports["o"];_secp256k1_xonly_pubkey_parse=wasmExports["p"];_secp256k1_xonly_pubkey_serialize=wasmExports["q"];_secp256k1_keypair_create=wasmExports["r"];_secp256k1_keypair_xonly_pub=wasmExports["s"];_secp256k1_schnorrsig_sign32=wasmExports["t"];_secp256k1_schnorrsig_verify=wasmExports["u"];_sbrk=wasmExports["sbrk"];wasmMemory=wasmExports["g"];updateMemoryViews();initRuntime(wasmExports);ready()}); diff --git a/node_modules/nostr-wasm/public/out/secp256k1.wasm b/node_modules/nostr-wasm/public/out/secp256k1.wasm new file mode 100755 index 0000000000000000000000000000000000000000..84cf20cc1bd3cffb6888831ff3306e22055ef290 GIT binary patch literal 217781 zcmcG%3zQt$dEZz4nCYJB>6rmA00!^sUI07T1$MD70Hl^&)L1035*e;&9UeL_t&%w2 z3}kz;T(5Xeu#2Vuu0|)a)UqBP$}-(@6mhJGa_iw}Bqd_&={XJ^H6_O$M`YBF6MLj1 zTWwRv2bLIZe*f>gx2AhA3#^lP$w61$y7zm3-~H~RZYAIR@jqWklBDow=Uyz{x|O_G zx)uK|+>0wSWK1q)>X|;#8qnEEJ|GDHM}JQm9NMNvT#S zl}j^)N}*0sl2l8j;%vD*Su7T-<%z<}g-T_jTqw-XPgbEk>wRXjR(a1{;m-l!rQ~qo zzecwYjpV7qE6J0Ek0(zQUQI3*{!;Sz z)J!4C3bo18OXtpCcx?K&zOQ!iFBJ-Jq)A#x%WtH`wDiW!w6vVAHj8ONKV`dri~r_s zH%pX-%fcJY37)4Vn%!)w#Z5pI-=MMAxY<mUa0bz0y3a-~S}k`Hy3r|J3SC=-D^D(p=1rd~3Rx z&3^00`M31i$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bO001rk74Fjy0S65L1Hi)L006L1pH6rH)ITx*M2hTw<{?4)-vBtof6Ryg z05|~lA2TfA6OjNSS*hUgU^b{C)<{^R%;V6pz?eB$TH%)-jX&cVsW%_AZz zCN3cf5V`s%3KAgl`j7kq5J~wC4iEQFVWB=hqcH%Hs!szLI6$Q9Q^NfBHwhpTkO2-4 JAsi3({{W5$BgOy# literal 0 HcmV?d00001 diff --git a/node_modules/object-inspect/.eslintrc b/node_modules/object-inspect/.eslintrc new file mode 100644 index 0000000..21f9039 --- /dev/null +++ b/node_modules/object-inspect/.eslintrc @@ -0,0 +1,53 @@ +{ + "root": true, + "extends": "@ljharb", + "rules": { + "complexity": 0, + "func-style": [2, "declaration"], + "indent": [2, 4], + "max-lines": 1, + "max-lines-per-function": 1, + "max-params": [2, 4], + "max-statements": 0, + "max-statements-per-line": [2, { "max": 2 }], + "no-magic-numbers": 0, + "no-param-reassign": 1, + "strict": 0, // TODO + }, + "overrides": [ + { + "files": ["test/**", "test-*", "example/**"], + "extends": "@ljharb/eslint-config/tests", + "rules": { + "id-length": 0, + }, + }, + { + "files": ["example/**"], + "rules": { + "no-console": 0, + }, + }, + { + "files": ["test/browser/**"], + "env": { + "browser": true, + }, + }, + { + "files": ["test/bigint*"], + "rules": { + "new-cap": [2, { "capIsNewExceptions": ["BigInt"] }], + }, + }, + { + "files": "index.js", + "globals": { + "HTMLElement": false, + }, + "rules": { + "no-use-before-define": 1, + }, + }, + ], +} diff --git a/node_modules/object-inspect/.github/FUNDING.yml b/node_modules/object-inspect/.github/FUNDING.yml new file mode 100644 index 0000000..730276b --- /dev/null +++ b/node_modules/object-inspect/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/object-inspect +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/object-inspect/.nycrc b/node_modules/object-inspect/.nycrc new file mode 100644 index 0000000..58a5db7 --- /dev/null +++ b/node_modules/object-inspect/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "instrumentation": false, + "sourceMap": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "example", + "test", + "test-core-js.js" + ] +} diff --git a/node_modules/object-inspect/CHANGELOG.md b/node_modules/object-inspect/CHANGELOG.md new file mode 100644 index 0000000..bdf9002 --- /dev/null +++ b/node_modules/object-inspect/CHANGELOG.md @@ -0,0 +1,424 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.13.4](https://github.com/inspect-js/object-inspect/compare/v1.13.3...v1.13.4) - 2025-02-04 + +### Commits + +- [Fix] avoid being fooled by a `Symbol.toStringTag` [`fa5870d`](https://github.com/inspect-js/object-inspect/commit/fa5870da468a525d2f20193700f70752f506cbf7) +- [Tests] fix tests in node v6.0 - v6.4 [`2abfe1b`](https://github.com/inspect-js/object-inspect/commit/2abfe1bc3c69f9293c07c5cd65a9d7d87a628b84) +- [Dev Deps] update `es-value-fixtures`, `for-each`, `has-symbols` [`3edfb01`](https://github.com/inspect-js/object-inspect/commit/3edfb01cc8cce220fba0dfdfe2dc8bc955758cdd) + +## [v1.13.3](https://github.com/inspect-js/object-inspect/compare/v1.13.2...v1.13.3) - 2024-11-09 + +### Commits + +- [actions] split out node 10-20, and 20+ [`44395a8`](https://github.com/inspect-js/object-inspect/commit/44395a8fc1deda6718a5e125e86b9ffcaa1c7580) +- [Fix] `quoteStyle`: properly escape only the containing quotes [`5137f8f`](https://github.com/inspect-js/object-inspect/commit/5137f8f7bea69a7fc671bb683fd35f244f38fc52) +- [Refactor] clean up `quoteStyle` code [`450680c`](https://github.com/inspect-js/object-inspect/commit/450680cd50de4e689ee3b8e1d6db3a1bcf3fc18c) +- [Tests] add `quoteStyle` escaping tests [`e997c59`](https://github.com/inspect-js/object-inspect/commit/e997c595aeaea84fd98ca35d7e1c3b5ab3ae26e0) +- [Dev Deps] update `auto-changelog`, `es-value-fixtures`, `tape` [`d5a469c`](https://github.com/inspect-js/object-inspect/commit/d5a469c99ec07ccaeafc36ac4b36a93285086d48) +- [Tests] replace `aud` with `npm audit` [`fb7815f`](https://github.com/inspect-js/object-inspect/commit/fb7815f9b72cae277a04f65bbb0543f85b88be62) +- [Dev Deps] update `mock-property` [`11c817b`](https://github.com/inspect-js/object-inspect/commit/11c817bf10392aa017755962ba6bc89d731359ee) + +## [v1.13.2](https://github.com/inspect-js/object-inspect/compare/v1.13.1...v1.13.2) - 2024-06-21 + +### Commits + +- [readme] update badges [`8a51e6b`](https://github.com/inspect-js/object-inspect/commit/8a51e6bedaf389ec40cc4659e9df53e8543d176e) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`ef05f58`](https://github.com/inspect-js/object-inspect/commit/ef05f58c9761a41416ab907299bf0fa79517014b) +- [Dev Deps] update `error-cause`, `has-tostringtag`, `tape` [`c0c6c26`](https://github.com/inspect-js/object-inspect/commit/c0c6c26c44cee6671f7c5d43d2b91d27c5c00d90) +- [Fix] Don't throw when `global` is not defined [`d4d0965`](https://github.com/inspect-js/object-inspect/commit/d4d096570f7dbd0e03266a96de11d05eb7b63e0f) +- [meta] add missing `engines.node` [`17a352a`](https://github.com/inspect-js/object-inspect/commit/17a352af6fe1ba6b70a19081674231eb1a50c940) +- [Dev Deps] update `globalthis` [`9c08884`](https://github.com/inspect-js/object-inspect/commit/9c08884aa662a149e2f11403f413927736b97da7) +- [Dev Deps] update `error-cause` [`6af352d`](https://github.com/inspect-js/object-inspect/commit/6af352d7c3929a4cc4c55768c27bf547a5e900f4) +- [Dev Deps] update `npmignore` [`94e617d`](https://github.com/inspect-js/object-inspect/commit/94e617d38831722562fa73dff4c895746861d267) +- [Dev Deps] update `mock-property` [`2ac24d7`](https://github.com/inspect-js/object-inspect/commit/2ac24d7e58cd388ad093c33249e413e05bbfd6c3) +- [Dev Deps] update `tape` [`46125e5`](https://github.com/inspect-js/object-inspect/commit/46125e58f1d1dcfb170ed3d1ea69da550ea8d77b) + +## [v1.13.1](https://github.com/inspect-js/object-inspect/compare/v1.13.0...v1.13.1) - 2023-10-19 + +### Commits + +- [Fix] in IE 8, global can !== window despite them being prototypes of each other [`30d0859`](https://github.com/inspect-js/object-inspect/commit/30d0859dc4606cf75c2410edcd5d5c6355f8d372) + +## [v1.13.0](https://github.com/inspect-js/object-inspect/compare/v1.12.3...v1.13.0) - 2023-10-14 + +### Commits + +- [New] add special handling for the global object [`431bab2`](https://github.com/inspect-js/object-inspect/commit/431bab21a490ee51d35395966a504501e8c685da) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`fd4f619`](https://github.com/inspect-js/object-inspect/commit/fd4f6193562b4b0e95dcf5c0201b4e8cbbc4f58d) +- [Dev Deps] update `mock-property`, `tape` [`b453f6c`](https://github.com/inspect-js/object-inspect/commit/b453f6ceeebf8a1b738a1029754092e0367a4134) +- [Dev Deps] update `error-cause` [`e8ffc57`](https://github.com/inspect-js/object-inspect/commit/e8ffc577d73b92bb6a4b00c44f14e3319e374888) +- [Dev Deps] update `tape` [`054b8b9`](https://github.com/inspect-js/object-inspect/commit/054b8b9b98633284cf989e582450ebfbbe53503c) +- [Dev Deps] temporarily remove `aud` due to breaking change in transitive deps [`2476845`](https://github.com/inspect-js/object-inspect/commit/2476845e0678dd290c541c81cd3dec8420782c52) +- [Dev Deps] pin `glob`, since v10.3.8+ requires a broken `jackspeak` [`383fa5e`](https://github.com/inspect-js/object-inspect/commit/383fa5eebc0afd705cc778a4b49d8e26452e49a8) +- [Dev Deps] pin `jackspeak` since 2.1.2+ depends on npm aliases, which kill the install process in npm < 6 [`68c244c`](https://github.com/inspect-js/object-inspect/commit/68c244c5174cdd877e5dcb8ee90aa3f44b2f25be) + +## [v1.12.3](https://github.com/inspect-js/object-inspect/compare/v1.12.2...v1.12.3) - 2023-01-12 + +### Commits + +- [Fix] in eg FF 24, collections lack forEach [`75fc226`](https://github.com/inspect-js/object-inspect/commit/75fc22673c82d45f28322b1946bb0eb41b672b7f) +- [actions] update rebase action to use reusable workflow [`250a277`](https://github.com/inspect-js/object-inspect/commit/250a277a095e9dacc029ab8454dcfc15de549dcd) +- [Dev Deps] update `aud`, `es-value-fixtures`, `tape` [`66a19b3`](https://github.com/inspect-js/object-inspect/commit/66a19b3209ccc3c5ef4b34c3cb0160e65d1ce9d5) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `error-cause` [`c43d332`](https://github.com/inspect-js/object-inspect/commit/c43d3324b48384a16fd3dc444e5fc589d785bef3) +- [Tests] add `@pkgjs/support` to `postlint` [`e2618d2`](https://github.com/inspect-js/object-inspect/commit/e2618d22a7a3fa361b6629b53c1752fddc9c4d80) + +## [v1.12.2](https://github.com/inspect-js/object-inspect/compare/v1.12.1...v1.12.2) - 2022-05-26 + +### Commits + +- [Fix] use `util.inspect` for a custom inspection symbol method [`e243bf2`](https://github.com/inspect-js/object-inspect/commit/e243bf2eda6c4403ac6f1146fddb14d12e9646c1) +- [meta] add support info [`ca20ba3`](https://github.com/inspect-js/object-inspect/commit/ca20ba35713c17068ca912a86c542f5e8acb656c) +- [Fix] ignore `cause` in node v16.9 and v16.10 where it has a bug [`86aa553`](https://github.com/inspect-js/object-inspect/commit/86aa553a4a455562c2c56f1540f0bf857b9d314b) + +## [v1.12.1](https://github.com/inspect-js/object-inspect/compare/v1.12.0...v1.12.1) - 2022-05-21 + +### Commits + +- [Tests] use `mock-property` [`4ec8893`](https://github.com/inspect-js/object-inspect/commit/4ec8893ea9bfd28065ca3638cf6762424bf44352) +- [meta] use `npmignore` to autogenerate an npmignore file [`07f868c`](https://github.com/inspect-js/object-inspect/commit/07f868c10bd25a9d18686528339bb749c211fc9a) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`b05244b`](https://github.com/inspect-js/object-inspect/commit/b05244b4f331e00c43b3151bc498041be77ccc91) +- [Dev Deps] update `@ljharb/eslint-config`, `error-cause`, `es-value-fixtures`, `functions-have-names`, `tape` [`d037398`](https://github.com/inspect-js/object-inspect/commit/d037398dcc5d531532e4c19c4a711ed677f579c1) +- [Fix] properly handle callable regexes in older engines [`848fe48`](https://github.com/inspect-js/object-inspect/commit/848fe48bd6dd0064ba781ee6f3c5e54a94144c37) + +## [v1.12.0](https://github.com/inspect-js/object-inspect/compare/v1.11.1...v1.12.0) - 2021-12-18 + +### Commits + +- [New] add `numericSeparator` boolean option [`2d2d537`](https://github.com/inspect-js/object-inspect/commit/2d2d537f5359a4300ce1c10241369f8024f89e11) +- [Robustness] cache more prototype methods [`191533d`](https://github.com/inspect-js/object-inspect/commit/191533da8aec98a05eadd73a5a6e979c9c8653e8) +- [New] ensure an Error’s `cause` is displayed [`53bc2ce`](https://github.com/inspect-js/object-inspect/commit/53bc2cee4e5a9cc4986f3cafa22c0685f340715e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`bc164b6`](https://github.com/inspect-js/object-inspect/commit/bc164b6e2e7d36b263970f16f54de63048b84a36) +- [Robustness] cache `RegExp.prototype.test` [`a314ab8`](https://github.com/inspect-js/object-inspect/commit/a314ab8271b905cbabc594c82914d2485a8daf12) +- [meta] fix auto-changelog settings [`5ed0983`](https://github.com/inspect-js/object-inspect/commit/5ed0983be72f73e32e2559997517a95525c7e20d) + +## [v1.11.1](https://github.com/inspect-js/object-inspect/compare/v1.11.0...v1.11.1) - 2021-12-05 + +### Commits + +- [meta] add `auto-changelog` [`7dbdd22`](https://github.com/inspect-js/object-inspect/commit/7dbdd228401d6025d8b7391476d88aee9ea9bbdf) +- [actions] reuse common workflows [`c8823bc`](https://github.com/inspect-js/object-inspect/commit/c8823bc0a8790729680709d45fb6e652432e91aa) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`7532b12`](https://github.com/inspect-js/object-inspect/commit/7532b120598307497b712890f75af8056f6d37a6) +- [Refactor] use `has-tostringtag` to behave correctly in the presence of symbol shams [`94abb5d`](https://github.com/inspect-js/object-inspect/commit/94abb5d4e745bf33253942dea86b3e538d2ff6c6) +- [actions] update codecov uploader [`5ed5102`](https://github.com/inspect-js/object-inspect/commit/5ed51025267a00e53b1341357315490ac4eb0874) +- [Dev Deps] update `eslint`, `tape` [`37b2ad2`](https://github.com/inspect-js/object-inspect/commit/37b2ad26c08d94bfd01d5d07069a0b28ef4e2ad7) +- [meta] add `sideEffects` flag [`d341f90`](https://github.com/inspect-js/object-inspect/commit/d341f905ef8bffa6a694cda6ddc5ba343532cd4f) + +## [v1.11.0](https://github.com/inspect-js/object-inspect/compare/v1.10.3...v1.11.0) - 2021-07-12 + +### Commits + +- [New] `customInspect`: add `symbol` option, to mimic modern util.inspect behavior [`e973a6e`](https://github.com/inspect-js/object-inspect/commit/e973a6e21f8140c5837cf25e9d89bdde88dc3120) +- [Dev Deps] update `eslint` [`05f1cb3`](https://github.com/inspect-js/object-inspect/commit/05f1cb3cbcfe1f238e8b51cf9bc294305b7ed793) + +## [v1.10.3](https://github.com/inspect-js/object-inspect/compare/v1.10.2...v1.10.3) - 2021-05-07 + +### Commits + +- [Fix] handle core-js Symbol shams [`4acfc2c`](https://github.com/inspect-js/object-inspect/commit/4acfc2c4b503498759120eb517abad6d51c9c5d6) +- [readme] update badges [`95c323a`](https://github.com/inspect-js/object-inspect/commit/95c323ad909d6cbabb95dd6015c190ba6db9c1f2) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud` [`cb38f48`](https://github.com/inspect-js/object-inspect/commit/cb38f485de6ec7a95109b5a9bbd0a1deba2f6611) + +## [v1.10.2](https://github.com/inspect-js/object-inspect/compare/v1.10.1...v1.10.2) - 2021-04-17 + +### Commits + +- [Fix] use a robust check for a boxed Symbol [`87f12d6`](https://github.com/inspect-js/object-inspect/commit/87f12d6e69ce530be04659c81a4cd502943acac5) + +## [v1.10.1](https://github.com/inspect-js/object-inspect/compare/v1.10.0...v1.10.1) - 2021-04-17 + +### Commits + +- [Fix] use a robust check for a boxed bigint [`d5ca829`](https://github.com/inspect-js/object-inspect/commit/d5ca8298b6d2e5c7b9334a5b21b96ed95d225c91) + +## [v1.10.0](https://github.com/inspect-js/object-inspect/compare/v1.9.0...v1.10.0) - 2021-04-17 + +### Commits + +- [Tests] increase coverage [`d8abb8a`](https://github.com/inspect-js/object-inspect/commit/d8abb8a62c2f084919df994a433b346e0d87a227) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`4bfec2e`](https://github.com/inspect-js/object-inspect/commit/4bfec2e30aaef6ddef6cbb1448306f9f8b9520b7) +- [New] respect `Symbol.toStringTag` on objects [`799b58f`](https://github.com/inspect-js/object-inspect/commit/799b58f536a45e4484633a8e9daeb0330835f175) +- [Fix] do not allow Symbol.toStringTag to masquerade as builtins [`d6c5b37`](https://github.com/inspect-js/object-inspect/commit/d6c5b37d7e94427796b82432fb0c8964f033a6ab) +- [New] add `WeakRef` support [`b6d898e`](https://github.com/inspect-js/object-inspect/commit/b6d898ee21868c780a7ee66b28532b5b34ed7f09) +- [meta] do not publish github action workflow files [`918cdfc`](https://github.com/inspect-js/object-inspect/commit/918cdfc4b6fe83f559ff6ef04fe66201e3ff5cbd) +- [meta] create `FUNDING.yml` [`0bb5fc5`](https://github.com/inspect-js/object-inspect/commit/0bb5fc516dbcd2cd728bd89cee0b580acc5ce301) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`22c8dc0`](https://github.com/inspect-js/object-inspect/commit/22c8dc0cac113d70f4781e49a950070923a671be) +- [meta] use `prepublishOnly` script for npm 7+ [`e52ee09`](https://github.com/inspect-js/object-inspect/commit/e52ee09e8050b8dbac94ef57f786675567728223) +- [Dev Deps] update `eslint` [`7c4e6fd`](https://github.com/inspect-js/object-inspect/commit/7c4e6fdedcd27cc980e13c9ad834d05a96f3d40c) + +## [v1.9.0](https://github.com/inspect-js/object-inspect/compare/v1.8.0...v1.9.0) - 2020-11-30 + +### Commits + +- [Tests] migrate tests to Github Actions [`d262251`](https://github.com/inspect-js/object-inspect/commit/d262251e13e16d3490b5473672f6b6d6ff86675d) +- [New] add enumerable own Symbols to plain object output [`ee60c03`](https://github.com/inspect-js/object-inspect/commit/ee60c033088cff9d33baa71e59a362a541b48284) +- [Tests] add passing tests [`01ac3e4`](https://github.com/inspect-js/object-inspect/commit/01ac3e4b5a30f97875a63dc9b1416b3bd626afc9) +- [actions] add "Require Allow Edits" action [`c2d7746`](https://github.com/inspect-js/object-inspect/commit/c2d774680cde4ca4af332d84d4121b26f798ba9e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `core-js` [`70058de`](https://github.com/inspect-js/object-inspect/commit/70058de1579fc54d1d15ed6c2dbe246637ce70ff) +- [Fix] hex characters in strings should be uppercased, to match node `assert` [`6ab8faa`](https://github.com/inspect-js/object-inspect/commit/6ab8faaa0abc08fe7a8e2afd8b39c6f1f0e00113) +- [Tests] run `nyc` on all tests [`4c47372`](https://github.com/inspect-js/object-inspect/commit/4c473727879ddc8e28b599202551ddaaf07b6210) +- [Tests] node 0.8 has an unpredictable property order; fix `groups` test by removing property [`f192069`](https://github.com/inspect-js/object-inspect/commit/f192069a978a3b60e6f0e0d45ac7df260ab9a778) +- [New] add enumerable properties to Function inspect result, per node’s `assert` [`fd38e1b`](https://github.com/inspect-js/object-inspect/commit/fd38e1bc3e2a1dc82091ce3e021917462eee64fc) +- [Tests] fix tests for node < 10, due to regex match `groups` [`2ac6462`](https://github.com/inspect-js/object-inspect/commit/2ac6462cc4f72eaa0b63a8cfee9aabe3008b2330) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`44b59e2`](https://github.com/inspect-js/object-inspect/commit/44b59e2676a7f825ef530dfd19dafb599e3b9456) +- [Robustness] cache `Symbol.prototype.toString` [`f3c2074`](https://github.com/inspect-js/object-inspect/commit/f3c2074d8f32faf8292587c07c9678ea931703dd) +- [Dev Deps] update `eslint` [`9411294`](https://github.com/inspect-js/object-inspect/commit/94112944b9245e3302e25453277876402d207e7f) +- [meta] `require-allow-edits` no longer requires an explicit github token [`36c0220`](https://github.com/inspect-js/object-inspect/commit/36c02205de3c2b0e84d53777c5c9fd54a36c48ab) +- [actions] update rebase checkout action to v2 [`55a39a6`](https://github.com/inspect-js/object-inspect/commit/55a39a64e944f19c6a7d8efddf3df27700f20d14) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`f59fd3c`](https://github.com/inspect-js/object-inspect/commit/f59fd3cf406c3a7c7ece140904a80bbc6bacfcca) +- [Dev Deps] update `eslint` [`a492bec`](https://github.com/inspect-js/object-inspect/commit/a492becec644b0155c9c4bc1caf6f9fac11fb2c7) + +## [v1.8.0](https://github.com/inspect-js/object-inspect/compare/v1.7.0...v1.8.0) - 2020-06-18 + +### Fixed + +- [New] add `indent` option [`#27`](https://github.com/inspect-js/object-inspect/issues/27) + +### Commits + +- [Tests] add codecov [`4324cbb`](https://github.com/inspect-js/object-inspect/commit/4324cbb1a2bd7710822a4151ff373570db22453e) +- [New] add `maxStringLength` option [`b3995cb`](https://github.com/inspect-js/object-inspect/commit/b3995cb71e15b5ee127a3094c43994df9d973502) +- [New] add `customInspect` option, to disable custom inspect methods [`28b9179`](https://github.com/inspect-js/object-inspect/commit/28b9179ee802bb3b90810100c11637db90c2fb6d) +- [Tests] add Date and RegExp tests [`3b28eca`](https://github.com/inspect-js/object-inspect/commit/3b28eca57b0367aeadffac604ea09e8bdae7d97b) +- [actions] add automatic rebasing / merge commit blocking [`0d9c6c0`](https://github.com/inspect-js/object-inspect/commit/0d9c6c044e83475ff0bfffb9d35b149834c83a2e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `tape`; add `aud` [`7c204f2`](https://github.com/inspect-js/object-inspect/commit/7c204f22b9e41bc97147f4d32d4cb045b17769a6) +- [readme] fix repo URLs, remove testling [`34ca9a0`](https://github.com/inspect-js/object-inspect/commit/34ca9a0dabfe75bd311f806a326fadad029909a3) +- [Fix] when truncating a deep array, note it as `[Array]` instead of just `[Object]` [`f74c82d`](https://github.com/inspect-js/object-inspect/commit/f74c82dd0b35386445510deb250f34c41be3ec0e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`1a8a5ea`](https://github.com/inspect-js/object-inspect/commit/1a8a5ea069ea2bee89d77caedad83ffa23d35711) +- [Fix] do not be fooled by a function’s own `toString` method [`7cb5c65`](https://github.com/inspect-js/object-inspect/commit/7cb5c657a976f94715c19c10556a30f15bb7d5d7) +- [patch] indicate explicitly that anon functions are anonymous, to match node [`81ebdd4`](https://github.com/inspect-js/object-inspect/commit/81ebdd4215005144074bbdff3f6bafa01407910a) +- [Dev Deps] loosen the `core-js` dep [`e7472e8`](https://github.com/inspect-js/object-inspect/commit/e7472e8e242117670560bd995830c2a4d12080f5) +- [Dev Deps] update `tape` [`699827e`](https://github.com/inspect-js/object-inspect/commit/699827e6b37258b5203c33c78c009bf4b0e6a66d) +- [meta] add `safe-publish-latest` [`c5d2868`](https://github.com/inspect-js/object-inspect/commit/c5d2868d6eb33c472f37a20f89ceef2787046088) +- [Dev Deps] update `@ljharb/eslint-config` [`9199501`](https://github.com/inspect-js/object-inspect/commit/919950195d486114ccebacbdf9d74d7f382693b0) + +## [v1.7.0](https://github.com/inspect-js/object-inspect/compare/v1.6.0...v1.7.0) - 2019-11-10 + +### Commits + +- [Tests] use shared travis-ci configs [`19899ed`](https://github.com/inspect-js/object-inspect/commit/19899edbf31f4f8809acf745ce34ad1ce1bfa63b) +- [Tests] add linting [`a00f057`](https://github.com/inspect-js/object-inspect/commit/a00f057d917f66ea26dd37769c6b810ec4af97e8) +- [Tests] lint last file [`2698047`](https://github.com/inspect-js/object-inspect/commit/2698047b58af1e2e88061598ef37a75f228dddf6) +- [Tests] up to `node` `v12.7`, `v11.15`, `v10.16`, `v8.16`, `v6.17` [`589e87a`](https://github.com/inspect-js/object-inspect/commit/589e87a99cadcff4b600e6a303418e9d922836e8) +- [New] add support for `WeakMap` and `WeakSet` [`3ddb3e4`](https://github.com/inspect-js/object-inspect/commit/3ddb3e4e0c8287130c61a12e0ed9c104b1549306) +- [meta] clean up license so github can detect it properly [`27527bb`](https://github.com/inspect-js/object-inspect/commit/27527bb801520c9610c68cc3b55d6f20a2bee56d) +- [Tests] cover `util.inspect.custom` [`36d47b9`](https://github.com/inspect-js/object-inspect/commit/36d47b9c59056a57ef2f1491602c726359561800) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `tape` [`b614eaa`](https://github.com/inspect-js/object-inspect/commit/b614eaac901da0e5c69151f534671f990a94cace) +- [Tests] fix coverage thresholds [`7b7b176`](https://github.com/inspect-js/object-inspect/commit/7b7b176e15f8bd6e8b2f261ff5a493c2fe78d9c2) +- [Tests] bigint tests now can run on unflagged node [`063af31`](https://github.com/inspect-js/object-inspect/commit/063af31ce9cd13c202e3b67c07ba06dc9b7c0f81) +- [Refactor] add early bailout to `isMap` and `isSet` checks [`fc51047`](https://github.com/inspect-js/object-inspect/commit/fc5104714a3671d37e225813db79470d6335683b) +- [meta] add `funding` field [`7f9953a`](https://github.com/inspect-js/object-inspect/commit/7f9953a113eec7b064a6393cf9f90ba15f1d131b) +- [Tests] Fix invalid strict-mode syntax with hexadecimal [`a8b5425`](https://github.com/inspect-js/object-inspect/commit/a8b542503b4af1599a275209a1a99f5fdedb1ead) +- [Dev Deps] update `@ljharb/eslint-config` [`98df157`](https://github.com/inspect-js/object-inspect/commit/98df1577314d9188a3fc3f17fdcf2fba697ae1bd) +- add copyright to LICENSE [`bb69fd0`](https://github.com/inspect-js/object-inspect/commit/bb69fd017a062d299e44da1f9b2c7dcd67f621e6) +- [Tests] use `npx aud` in `posttest` [`4838353`](https://github.com/inspect-js/object-inspect/commit/4838353593974cf7f905b9ef04c03c094f0cdbe2) +- [Tests] move `0.6` to allowed failures, because it won‘t build on travis [`1bff32a`](https://github.com/inspect-js/object-inspect/commit/1bff32aa52e8aea687f0856b28ba754b3e43ebf7) + +## [v1.6.0](https://github.com/inspect-js/object-inspect/compare/v1.5.0...v1.6.0) - 2018-05-02 + +### Commits + +- [New] add support for boxed BigInt primitives [`356c66a`](https://github.com/inspect-js/object-inspect/commit/356c66a410e7aece7162c8319880a5ef647beaa9) +- [Tests] up to `node` `v10.0`, `v9.11`, `v8.11`, `v6.14`, `v4.9` [`c77b65b`](https://github.com/inspect-js/object-inspect/commit/c77b65bba593811b906b9ec57561c5cba92e2db3) +- [New] Add support for upcoming `BigInt` [`1ac548e`](https://github.com/inspect-js/object-inspect/commit/1ac548e4b27e26466c28c9a5e63e5d4e0591c31f) +- [Tests] run bigint tests in CI with --harmony-bigint flag [`d31b738`](https://github.com/inspect-js/object-inspect/commit/d31b73831880254b5c6cf5691cda9a149fbc5f04) +- [Dev Deps] update `core-js`, `tape` [`ff9eff6`](https://github.com/inspect-js/object-inspect/commit/ff9eff67113341ee1aaf80c1c22d683f43bfbccf) +- [Docs] fix example to use `safer-buffer` [`48cae12`](https://github.com/inspect-js/object-inspect/commit/48cae12a73ec6cacc955175bc56bbe6aee6a211f) + +## [v1.5.0](https://github.com/inspect-js/object-inspect/compare/v1.4.1...v1.5.0) - 2017-12-25 + +### Commits + +- [New] add `quoteStyle` option [`f5a72d2`](https://github.com/inspect-js/object-inspect/commit/f5a72d26edb3959b048f74c056ca7100a6b091e4) +- [Tests] add more test coverage [`30ebe4e`](https://github.com/inspect-js/object-inspect/commit/30ebe4e1fa943b99ecbb85be7614256d536e2759) +- [Tests] require 0.6 to pass [`99a008c`](https://github.com/inspect-js/object-inspect/commit/99a008ccace189a60fd7da18bf00e32c9572b980) + +## [v1.4.1](https://github.com/inspect-js/object-inspect/compare/v1.4.0...v1.4.1) - 2017-12-19 + +### Commits + +- [Tests] up to `node` `v9.3`, `v8.9`, `v6.12` [`6674476`](https://github.com/inspect-js/object-inspect/commit/6674476cc56acaac1bde96c84fed5ef631911906) +- [Fix] `inspect(Object(-0))` should be “Object(-0)”, not “Object(0)” [`d0a031f`](https://github.com/inspect-js/object-inspect/commit/d0a031f1cbb3024ee9982bfe364dd18a7e4d1bd3) + +## [v1.4.0](https://github.com/inspect-js/object-inspect/compare/v1.3.0...v1.4.0) - 2017-10-24 + +### Commits + +- [Tests] add `npm run coverage` [`3b48fb2`](https://github.com/inspect-js/object-inspect/commit/3b48fb25db037235eeb808f0b2830aad7aa36f70) +- [Tests] remove commented-out osx builds [`71e24db`](https://github.com/inspect-js/object-inspect/commit/71e24db8ad6ee3b9b381c5300b0475f2ba595a73) +- [New] add support for `util.inspect.custom`, in node only. [`20cca77`](https://github.com/inspect-js/object-inspect/commit/20cca7762d7e17f15b21a90793dff84acce155df) +- [Tests] up to `node` `v8.6`; use `nvm install-latest-npm` to ensure new npm doesn’t break old node [`252952d`](https://github.com/inspect-js/object-inspect/commit/252952d230d8065851dd3d4d5fe8398aae068529) +- [Tests] up to `node` `v8.8` [`4aa868d`](https://github.com/inspect-js/object-inspect/commit/4aa868d3a62914091d489dd6ec6eed194ee67cd3) +- [Dev Deps] update `core-js`, `tape` [`59483d1`](https://github.com/inspect-js/object-inspect/commit/59483d1df418f852f51fa0db7b24aa6b0209a27a) + +## [v1.3.0](https://github.com/inspect-js/object-inspect/compare/v1.2.2...v1.3.0) - 2017-07-31 + +### Fixed + +- [Fix] Map/Set: work around core-js bug < v2.5.0 [`#9`](https://github.com/inspect-js/object-inspect/issues/9) + +### Commits + +- [New] add support for arrays with additional object keys [`0d19937`](https://github.com/inspect-js/object-inspect/commit/0d199374ee37959e51539616666f420ccb29acb9) +- [Tests] up to `node` `v8.2`, `v7.10`, `v6.11`; fix new npm breaking on older nodes [`e24784a`](https://github.com/inspect-js/object-inspect/commit/e24784a90c49117787157a12a63897c49cf89bbb) +- Only apps should have lockfiles [`c6faebc`](https://github.com/inspect-js/object-inspect/commit/c6faebcb2ee486a889a4a1c4d78c0776c7576185) +- [Dev Deps] update `tape` [`7345a0a`](https://github.com/inspect-js/object-inspect/commit/7345a0aeba7e91b888a079c10004d17696a7f586) + +## [v1.2.2](https://github.com/inspect-js/object-inspect/compare/v1.2.1...v1.2.2) - 2017-03-24 + +### Commits + +- [Tests] up to `node` `v7.7`, `v6.10`, `v4.8`; improve test matrix [`a2ddc15`](https://github.com/inspect-js/object-inspect/commit/a2ddc15a1f2c65af18076eea1c0eb9cbceb478a0) +- [Tests] up to `node` `v7.0`, `v6.9`, `v5.12`, `v4.6`, `io.js` `v3.3`; improve test matrix [`a48949f`](https://github.com/inspect-js/object-inspect/commit/a48949f6b574b2d4d2298109d8e8d0eb3e7a83e7) +- [Performance] check for primitive types as early as possible. [`3b8092a`](https://github.com/inspect-js/object-inspect/commit/3b8092a2a4deffd0575f94334f00194e2d48dad3) +- [Refactor] remove unneeded `else`s. [`7255034`](https://github.com/inspect-js/object-inspect/commit/725503402e08de4f96f6bf2d8edef44ac36f26b6) +- [Refactor] avoid recreating `lowbyte` function every time. [`81edd34`](https://github.com/inspect-js/object-inspect/commit/81edd3475bd15bdd18e84de7472033dcf5004aaa) +- [Fix] differentiate -0 from 0 [`521d345`](https://github.com/inspect-js/object-inspect/commit/521d3456b009da7bf1c5785c8a9df5a9f8718264) +- [Refactor] move object key gathering into separate function [`aca6265`](https://github.com/inspect-js/object-inspect/commit/aca626536eaeef697196c6e9db3e90e7e0355b6a) +- [Refactor] consolidate wrapping logic for boxed primitives into a function. [`4e440cd`](https://github.com/inspect-js/object-inspect/commit/4e440cd9065df04802a2a1dead03f48c353ca301) +- [Robustness] use `typeof` instead of comparing to literal `undefined` [`5ca6f60`](https://github.com/inspect-js/object-inspect/commit/5ca6f601937506daff8ed2fcf686363b55807b69) +- [Refactor] consolidate Map/Set notations. [`4e576e5`](https://github.com/inspect-js/object-inspect/commit/4e576e5d7ed2f9ec3fb7f37a0d16732eb10758a9) +- [Tests] ensure that this function remains anonymous, despite ES6 name inference. [`7540ae5`](https://github.com/inspect-js/object-inspect/commit/7540ae591278756db614fa4def55ca413150e1a3) +- [Refactor] explicitly coerce Error objects to strings. [`7f4ca84`](https://github.com/inspect-js/object-inspect/commit/7f4ca8424ee8dc2c0ca5a422d94f7fac40327261) +- [Refactor] split up `var` declarations for debuggability [`6f2c11e`](https://github.com/inspect-js/object-inspect/commit/6f2c11e6a85418586a00292dcec5e97683f89bc3) +- [Robustness] cache `Object.prototype.toString` [`df44a20`](https://github.com/inspect-js/object-inspect/commit/df44a20adfccf31529d60d1df2079bfc3c836e27) +- [Dev Deps] update `tape` [`3ec714e`](https://github.com/inspect-js/object-inspect/commit/3ec714eba57bc3f58a6eb4fca1376f49e70d300a) +- [Dev Deps] update `tape` [`beb72d9`](https://github.com/inspect-js/object-inspect/commit/beb72d969653747d7cde300393c28755375329b0) + +## [v1.2.1](https://github.com/inspect-js/object-inspect/compare/v1.2.0...v1.2.1) - 2016-04-09 + +### Fixed + +- [Fix] fix Boolean `false` object inspection. [`#7`](https://github.com/substack/object-inspect/pull/7) + +## [v1.2.0](https://github.com/inspect-js/object-inspect/compare/v1.1.0...v1.2.0) - 2016-04-09 + +### Fixed + +- [New] add support for inspecting String/Number/Boolean objects. [`#6`](https://github.com/inspect-js/object-inspect/issues/6) + +### Commits + +- [Dev Deps] update `tape` [`742caa2`](https://github.com/inspect-js/object-inspect/commit/742caa262cf7af4c815d4821c8bd0129c1446432) + +## [v1.1.0](https://github.com/inspect-js/object-inspect/compare/1.0.2...v1.1.0) - 2015-12-14 + +### Merged + +- [New] add ES6 Map/Set support. [`#4`](https://github.com/inspect-js/object-inspect/pull/4) + +### Fixed + +- [New] add ES6 Map/Set support. [`#3`](https://github.com/inspect-js/object-inspect/issues/3) + +### Commits + +- Update `travis.yml` to test on bunches of `iojs` and `node` versions. [`4c1fd65`](https://github.com/inspect-js/object-inspect/commit/4c1fd65cc3bd95307e854d114b90478324287fd2) +- [Dev Deps] update `tape` [`88a907e`](https://github.com/inspect-js/object-inspect/commit/88a907e33afbe408e4b5d6e4e42a33143f88848c) + +## [1.0.2](https://github.com/inspect-js/object-inspect/compare/1.0.1...1.0.2) - 2015-08-07 + +### Commits + +- [Fix] Cache `Object.prototype.hasOwnProperty` in case it's deleted later. [`1d0075d`](https://github.com/inspect-js/object-inspect/commit/1d0075d3091dc82246feeb1f9871cb2b8ed227b3) +- [Dev Deps] Update `tape` [`ca8d5d7`](https://github.com/inspect-js/object-inspect/commit/ca8d5d75635ddbf76f944e628267581e04958457) +- gitignore node_modules since this is a reusable modules. [`ed41407`](https://github.com/inspect-js/object-inspect/commit/ed41407811743ca530cdeb28f982beb96026af82) + +## [1.0.1](https://github.com/inspect-js/object-inspect/compare/1.0.0...1.0.1) - 2015-07-19 + +### Commits + +- Make `inspect` work with symbol primitives and objects, including in node 0.11 and 0.12. [`ddf1b94`](https://github.com/inspect-js/object-inspect/commit/ddf1b94475ab951f1e3bccdc0a48e9073cfbfef4) +- bump tape [`103d674`](https://github.com/inspect-js/object-inspect/commit/103d67496b504bdcfdd765d303a773f87ec106e2) +- use newer travis config [`d497276`](https://github.com/inspect-js/object-inspect/commit/d497276c1da14234bb5098a59cf20de75fbc316a) + +## [1.0.0](https://github.com/inspect-js/object-inspect/compare/0.4.0...1.0.0) - 2014-08-05 + +### Commits + +- error inspect works properly [`260a22d`](https://github.com/inspect-js/object-inspect/commit/260a22d134d3a8a482c67d52091c6040c34f4299) +- seen coverage [`57269e8`](https://github.com/inspect-js/object-inspect/commit/57269e8baa992a7439047f47325111fdcbcb8417) +- htmlelement instance coverage [`397ffe1`](https://github.com/inspect-js/object-inspect/commit/397ffe10a1980350868043ef9de65686d438979f) +- more element coverage [`6905cc2`](https://github.com/inspect-js/object-inspect/commit/6905cc2f7df35600177e613b0642b4df5efd3eca) +- failing test for type errors [`385b615`](https://github.com/inspect-js/object-inspect/commit/385b6152e49b51b68449a662f410b084ed7c601a) +- fn name coverage [`edc906d`](https://github.com/inspect-js/object-inspect/commit/edc906d40fca6b9194d304062c037ee8e398c4c2) +- server-side element test [`362d1d3`](https://github.com/inspect-js/object-inspect/commit/362d1d3e86f187651c29feeb8478110afada385b) +- custom inspect fn [`e89b0f6`](https://github.com/inspect-js/object-inspect/commit/e89b0f6fe6d5e03681282af83732a509160435a6) +- fixed browser test [`b530882`](https://github.com/inspect-js/object-inspect/commit/b5308824a1c8471c5617e394766a03a6977102a9) +- depth test, matches node [`1cfd9e0`](https://github.com/inspect-js/object-inspect/commit/1cfd9e0285a4ae1dff44101ad482915d9bf47e48) +- exercise hasOwnProperty path [`8d753fb`](https://github.com/inspect-js/object-inspect/commit/8d753fb362a534fa1106e4d80f2ee9bea06a66d9) +- more cases covered for errors [`c5c46a5`](https://github.com/inspect-js/object-inspect/commit/c5c46a569ec4606583497e8550f0d8c7ad39a4a4) +- \W obj key test case [`b0eceee`](https://github.com/inspect-js/object-inspect/commit/b0eceeea6e0eb94d686c1046e99b9e25e5005f75) +- coverage for explicit depth param [`e12b91c`](https://github.com/inspect-js/object-inspect/commit/e12b91cd59683362f3a0e80f46481a0211e26c15) + +## [0.4.0](https://github.com/inspect-js/object-inspect/compare/0.3.1...0.4.0) - 2014-03-21 + +### Commits + +- passing lowbyte interpolation test [`b847511`](https://github.com/inspect-js/object-inspect/commit/b8475114f5def7e7961c5353d48d3d8d9a520985) +- lowbyte test [`4a2b0e1`](https://github.com/inspect-js/object-inspect/commit/4a2b0e142667fc933f195472759385ac08f3946c) + +## [0.3.1](https://github.com/inspect-js/object-inspect/compare/0.3.0...0.3.1) - 2014-03-04 + +### Commits + +- sort keys [`a07b19c`](https://github.com/inspect-js/object-inspect/commit/a07b19cc3b1521a82d4fafb6368b7a9775428a05) + +## [0.3.0](https://github.com/inspect-js/object-inspect/compare/0.2.0...0.3.0) - 2014-03-04 + +### Commits + +- [] and {} instead of [ ] and { } [`654c44b`](https://github.com/inspect-js/object-inspect/commit/654c44b2865811f3519e57bb8526e0821caf5c6b) + +## [0.2.0](https://github.com/inspect-js/object-inspect/compare/0.1.3...0.2.0) - 2014-03-04 + +### Commits + +- failing holes test [`99cdfad`](https://github.com/inspect-js/object-inspect/commit/99cdfad03c6474740275a75636fe6ca86c77737a) +- regex already work [`e324033`](https://github.com/inspect-js/object-inspect/commit/e324033267025995ec97d32ed0a65737c99477a6) +- failing undef/null test [`1f88a00`](https://github.com/inspect-js/object-inspect/commit/1f88a00265d3209719dda8117b7e6360b4c20943) +- holes in the all example [`7d345f3`](https://github.com/inspect-js/object-inspect/commit/7d345f3676dcbe980cff89a4f6c243269ebbb709) +- check for .inspect(), fixes Buffer use-case [`c3f7546`](https://github.com/inspect-js/object-inspect/commit/c3f75466dbca125347d49847c05262c292f12b79) +- fixes for holes [`ce25f73`](https://github.com/inspect-js/object-inspect/commit/ce25f736683de4b92ff27dc5471218415e2d78d8) +- weird null behavior [`405c1ea`](https://github.com/inspect-js/object-inspect/commit/405c1ea72cd5a8cf3b498c3eaa903d01b9fbcab5) +- tape is actually a devDependency, upgrade [`703b0ce`](https://github.com/inspect-js/object-inspect/commit/703b0ce6c5817b4245a082564bccd877e0bb6990) +- put date in the example [`a342219`](https://github.com/inspect-js/object-inspect/commit/a3422190eeaa013215f46df2d0d37b48595ac058) +- passing the null test [`4ab737e`](https://github.com/inspect-js/object-inspect/commit/4ab737ebf862a75d247ebe51e79307a34d6380d4) + +## [0.1.3](https://github.com/inspect-js/object-inspect/compare/0.1.1...0.1.3) - 2013-07-26 + +### Commits + +- special isElement() check [`882768a`](https://github.com/inspect-js/object-inspect/commit/882768a54035d30747be9de1baf14e5aa0daa128) +- oh right old IEs don't have indexOf either [`36d1275`](https://github.com/inspect-js/object-inspect/commit/36d12756c38b08a74370b0bb696c809e529913a5) + +## [0.1.1](https://github.com/inspect-js/object-inspect/compare/0.1.0...0.1.1) - 2013-07-26 + +### Commits + +- tests! [`4422fd9`](https://github.com/inspect-js/object-inspect/commit/4422fd95532c2745aa6c4f786f35f1090be29998) +- fix for ie<9, doesn't have hasOwnProperty [`6b7d611`](https://github.com/inspect-js/object-inspect/commit/6b7d61183050f6da801ea04473211da226482613) +- fix for all IEs: no f.name [`4e0c2f6`](https://github.com/inspect-js/object-inspect/commit/4e0c2f6dfd01c306d067d7163319acc97c94ee50) +- badges [`5ed0d88`](https://github.com/inspect-js/object-inspect/commit/5ed0d88e4e407f9cb327fa4a146c17921f9680f3) + +## [0.1.0](https://github.com/inspect-js/object-inspect/compare/0.0.0...0.1.0) - 2013-07-26 + +### Commits + +- [Function] for functions [`ad5c485`](https://github.com/inspect-js/object-inspect/commit/ad5c485098fc83352cb540a60b2548ca56820e0b) + +## 0.0.0 - 2013-07-26 + +### Commits + +- working browser example [`34be6b6`](https://github.com/inspect-js/object-inspect/commit/34be6b6548f9ce92bdc3c27572857ba0c4a1218d) +- package.json etc [`cad51f2`](https://github.com/inspect-js/object-inspect/commit/cad51f23fc6bcf1a456ed6abe16088256c2f632f) +- docs complete [`b80cce2`](https://github.com/inspect-js/object-inspect/commit/b80cce2490c4e7183a9ee11ea89071f0abec4446) +- circular example [`4b4a7b9`](https://github.com/inspect-js/object-inspect/commit/4b4a7b92209e4e6b4630976cb6bcd17d14165a59) +- string rep [`7afb479`](https://github.com/inspect-js/object-inspect/commit/7afb479baa798d27f09e0a178b72ea327f60f5c8) diff --git a/node_modules/object-inspect/LICENSE b/node_modules/object-inspect/LICENSE new file mode 100644 index 0000000..ca64cc1 --- /dev/null +++ b/node_modules/object-inspect/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 James Halliday + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/object-inspect/example/all.js b/node_modules/object-inspect/example/all.js new file mode 100644 index 0000000..2f3355c --- /dev/null +++ b/node_modules/object-inspect/example/all.js @@ -0,0 +1,23 @@ +'use strict'; + +var inspect = require('../'); +var Buffer = require('safer-buffer').Buffer; + +var holes = ['a', 'b']; +holes[4] = 'e'; +holes[6] = 'g'; + +var obj = { + a: 1, + b: [3, 4, undefined, null], + c: undefined, + d: null, + e: { + regex: /^x/i, + buf: Buffer.from('abc'), + holes: holes + }, + now: new Date() +}; +obj.self = obj; +console.log(inspect(obj)); diff --git a/node_modules/object-inspect/example/circular.js b/node_modules/object-inspect/example/circular.js new file mode 100644 index 0000000..487a7c1 --- /dev/null +++ b/node_modules/object-inspect/example/circular.js @@ -0,0 +1,6 @@ +'use strict'; + +var inspect = require('../'); +var obj = { a: 1, b: [3, 4] }; +obj.c = obj; +console.log(inspect(obj)); diff --git a/node_modules/object-inspect/example/fn.js b/node_modules/object-inspect/example/fn.js new file mode 100644 index 0000000..9b5db8d --- /dev/null +++ b/node_modules/object-inspect/example/fn.js @@ -0,0 +1,5 @@ +'use strict'; + +var inspect = require('../'); +var obj = [1, 2, function f(n) { return n + 5; }, 4]; +console.log(inspect(obj)); diff --git a/node_modules/object-inspect/example/inspect.js b/node_modules/object-inspect/example/inspect.js new file mode 100644 index 0000000..e2df7c9 --- /dev/null +++ b/node_modules/object-inspect/example/inspect.js @@ -0,0 +1,10 @@ +'use strict'; + +/* eslint-env browser */ +var inspect = require('../'); + +var d = document.createElement('div'); +d.setAttribute('id', 'beep'); +d.innerHTML = 'woooiiiii'; + +console.log(inspect([d, { a: 3, b: 4, c: [5, 6, [7, [8, [9]]]] }])); diff --git a/node_modules/object-inspect/index.js b/node_modules/object-inspect/index.js new file mode 100644 index 0000000..a4b2d4c --- /dev/null +++ b/node_modules/object-inspect/index.js @@ -0,0 +1,544 @@ +var hasMap = typeof Map === 'function' && Map.prototype; +var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; +var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; +var mapForEach = hasMap && Map.prototype.forEach; +var hasSet = typeof Set === 'function' && Set.prototype; +var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null; +var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null; +var setForEach = hasSet && Set.prototype.forEach; +var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype; +var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; +var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype; +var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; +var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype; +var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; +var booleanValueOf = Boolean.prototype.valueOf; +var objectToString = Object.prototype.toString; +var functionToString = Function.prototype.toString; +var $match = String.prototype.match; +var $slice = String.prototype.slice; +var $replace = String.prototype.replace; +var $toUpperCase = String.prototype.toUpperCase; +var $toLowerCase = String.prototype.toLowerCase; +var $test = RegExp.prototype.test; +var $concat = Array.prototype.concat; +var $join = Array.prototype.join; +var $arrSlice = Array.prototype.slice; +var $floor = Math.floor; +var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null; +var gOPS = Object.getOwnPropertySymbols; +var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null; +var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object'; +// ie, `has-tostringtag/shams +var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol') + ? Symbol.toStringTag + : null; +var isEnumerable = Object.prototype.propertyIsEnumerable; + +var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ( + [].__proto__ === Array.prototype // eslint-disable-line no-proto + ? function (O) { + return O.__proto__; // eslint-disable-line no-proto + } + : null +); + +function addNumericSeparator(num, str) { + if ( + num === Infinity + || num === -Infinity + || num !== num + || (num && num > -1000 && num < 1000) + || $test.call(/e/, str) + ) { + return str; + } + var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; + if (typeof num === 'number') { + var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num) + if (int !== num) { + var intStr = String(int); + var dec = $slice.call(str, intStr.length + 1); + return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, ''); + } + } + return $replace.call(str, sepRegex, '$&_'); +} + +var utilInspect = require('./util.inspect'); +var inspectCustom = utilInspect.custom; +var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; + +var quotes = { + __proto__: null, + 'double': '"', + single: "'" +}; +var quoteREs = { + __proto__: null, + 'double': /(["\\])/g, + single: /(['\\])/g +}; + +module.exports = function inspect_(obj, options, depth, seen) { + var opts = options || {}; + + if (has(opts, 'quoteStyle') && !has(quotes, opts.quoteStyle)) { + throw new TypeError('option "quoteStyle" must be "single" or "double"'); + } + if ( + has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number' + ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity + : opts.maxStringLength !== null + ) + ) { + throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); + } + var customInspect = has(opts, 'customInspect') ? opts.customInspect : true; + if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') { + throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`'); + } + + if ( + has(opts, 'indent') + && opts.indent !== null + && opts.indent !== '\t' + && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0) + ) { + throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); + } + if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') { + throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); + } + var numericSeparator = opts.numericSeparator; + + if (typeof obj === 'undefined') { + return 'undefined'; + } + if (obj === null) { + return 'null'; + } + if (typeof obj === 'boolean') { + return obj ? 'true' : 'false'; + } + + if (typeof obj === 'string') { + return inspectString(obj, opts); + } + if (typeof obj === 'number') { + if (obj === 0) { + return Infinity / obj > 0 ? '0' : '-0'; + } + var str = String(obj); + return numericSeparator ? addNumericSeparator(obj, str) : str; + } + if (typeof obj === 'bigint') { + var bigIntStr = String(obj) + 'n'; + return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; + } + + var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth; + if (typeof depth === 'undefined') { depth = 0; } + if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') { + return isArray(obj) ? '[Array]' : '[Object]'; + } + + var indent = getIndent(opts, depth); + + if (typeof seen === 'undefined') { + seen = []; + } else if (indexOf(seen, obj) >= 0) { + return '[Circular]'; + } + + function inspect(value, from, noIndent) { + if (from) { + seen = $arrSlice.call(seen); + seen.push(from); + } + if (noIndent) { + var newOpts = { + depth: opts.depth + }; + if (has(opts, 'quoteStyle')) { + newOpts.quoteStyle = opts.quoteStyle; + } + return inspect_(value, newOpts, depth + 1, seen); + } + return inspect_(value, opts, depth + 1, seen); + } + + if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable + var name = nameOf(obj); + var keys = arrObjKeys(obj, inspect); + return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : ''); + } + if (isSymbol(obj)) { + var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj); + return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString; + } + if (isElement(obj)) { + var s = '<' + $toLowerCase.call(String(obj.nodeName)); + var attrs = obj.attributes || []; + for (var i = 0; i < attrs.length; i++) { + s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts); + } + s += '>'; + if (obj.childNodes && obj.childNodes.length) { s += '...'; } + s += ''; + return s; + } + if (isArray(obj)) { + if (obj.length === 0) { return '[]'; } + var xs = arrObjKeys(obj, inspect); + if (indent && !singleLineValues(xs)) { + return '[' + indentedJoin(xs, indent) + ']'; + } + return '[ ' + $join.call(xs, ', ') + ' ]'; + } + if (isError(obj)) { + var parts = arrObjKeys(obj, inspect); + if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) { + return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }'; + } + if (parts.length === 0) { return '[' + String(obj) + ']'; } + return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }'; + } + if (typeof obj === 'object' && customInspect) { + if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) { + return utilInspect(obj, { depth: maxDepth - depth }); + } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') { + return obj.inspect(); + } + } + if (isMap(obj)) { + var mapParts = []; + if (mapForEach) { + mapForEach.call(obj, function (value, key) { + mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj)); + }); + } + return collectionOf('Map', mapSize.call(obj), mapParts, indent); + } + if (isSet(obj)) { + var setParts = []; + if (setForEach) { + setForEach.call(obj, function (value) { + setParts.push(inspect(value, obj)); + }); + } + return collectionOf('Set', setSize.call(obj), setParts, indent); + } + if (isWeakMap(obj)) { + return weakCollectionOf('WeakMap'); + } + if (isWeakSet(obj)) { + return weakCollectionOf('WeakSet'); + } + if (isWeakRef(obj)) { + return weakCollectionOf('WeakRef'); + } + if (isNumber(obj)) { + return markBoxed(inspect(Number(obj))); + } + if (isBigInt(obj)) { + return markBoxed(inspect(bigIntValueOf.call(obj))); + } + if (isBoolean(obj)) { + return markBoxed(booleanValueOf.call(obj)); + } + if (isString(obj)) { + return markBoxed(inspect(String(obj))); + } + // note: in IE 8, sometimes `global !== window` but both are the prototypes of each other + /* eslint-env browser */ + if (typeof window !== 'undefined' && obj === window) { + return '{ [object Window] }'; + } + if ( + (typeof globalThis !== 'undefined' && obj === globalThis) + || (typeof global !== 'undefined' && obj === global) + ) { + return '{ [object globalThis] }'; + } + if (!isDate(obj) && !isRegExp(obj)) { + var ys = arrObjKeys(obj, inspect); + var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; + var protoTag = obj instanceof Object ? '' : 'null prototype'; + var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : ''; + var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : ''; + var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : ''); + if (ys.length === 0) { return tag + '{}'; } + if (indent) { + return tag + '{' + indentedJoin(ys, indent) + '}'; + } + return tag + '{ ' + $join.call(ys, ', ') + ' }'; + } + return String(obj); +}; + +function wrapQuotes(s, defaultStyle, opts) { + var style = opts.quoteStyle || defaultStyle; + var quoteChar = quotes[style]; + return quoteChar + s + quoteChar; +} + +function quote(s) { + return $replace.call(String(s), /"/g, '"'); +} + +function canTrustToString(obj) { + return !toStringTag || !(typeof obj === 'object' && (toStringTag in obj || typeof obj[toStringTag] !== 'undefined')); +} +function isArray(obj) { return toStr(obj) === '[object Array]' && canTrustToString(obj); } +function isDate(obj) { return toStr(obj) === '[object Date]' && canTrustToString(obj); } +function isRegExp(obj) { return toStr(obj) === '[object RegExp]' && canTrustToString(obj); } +function isError(obj) { return toStr(obj) === '[object Error]' && canTrustToString(obj); } +function isString(obj) { return toStr(obj) === '[object String]' && canTrustToString(obj); } +function isNumber(obj) { return toStr(obj) === '[object Number]' && canTrustToString(obj); } +function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && canTrustToString(obj); } + +// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives +function isSymbol(obj) { + if (hasShammedSymbols) { + return obj && typeof obj === 'object' && obj instanceof Symbol; + } + if (typeof obj === 'symbol') { + return true; + } + if (!obj || typeof obj !== 'object' || !symToString) { + return false; + } + try { + symToString.call(obj); + return true; + } catch (e) {} + return false; +} + +function isBigInt(obj) { + if (!obj || typeof obj !== 'object' || !bigIntValueOf) { + return false; + } + try { + bigIntValueOf.call(obj); + return true; + } catch (e) {} + return false; +} + +var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; }; +function has(obj, key) { + return hasOwn.call(obj, key); +} + +function toStr(obj) { + return objectToString.call(obj); +} + +function nameOf(f) { + if (f.name) { return f.name; } + var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/); + if (m) { return m[1]; } + return null; +} + +function indexOf(xs, x) { + if (xs.indexOf) { return xs.indexOf(x); } + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) { return i; } + } + return -1; +} + +function isMap(x) { + if (!mapSize || !x || typeof x !== 'object') { + return false; + } + try { + mapSize.call(x); + try { + setSize.call(x); + } catch (s) { + return true; + } + return x instanceof Map; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakMap(x) { + if (!weakMapHas || !x || typeof x !== 'object') { + return false; + } + try { + weakMapHas.call(x, weakMapHas); + try { + weakSetHas.call(x, weakSetHas); + } catch (s) { + return true; + } + return x instanceof WeakMap; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakRef(x) { + if (!weakRefDeref || !x || typeof x !== 'object') { + return false; + } + try { + weakRefDeref.call(x); + return true; + } catch (e) {} + return false; +} + +function isSet(x) { + if (!setSize || !x || typeof x !== 'object') { + return false; + } + try { + setSize.call(x); + try { + mapSize.call(x); + } catch (m) { + return true; + } + return x instanceof Set; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakSet(x) { + if (!weakSetHas || !x || typeof x !== 'object') { + return false; + } + try { + weakSetHas.call(x, weakSetHas); + try { + weakMapHas.call(x, weakMapHas); + } catch (s) { + return true; + } + return x instanceof WeakSet; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isElement(x) { + if (!x || typeof x !== 'object') { return false; } + if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) { + return true; + } + return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function'; +} + +function inspectString(str, opts) { + if (str.length > opts.maxStringLength) { + var remaining = str.length - opts.maxStringLength; + var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : ''); + return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; + } + var quoteRE = quoteREs[opts.quoteStyle || 'single']; + quoteRE.lastIndex = 0; + // eslint-disable-next-line no-control-regex + var s = $replace.call($replace.call(str, quoteRE, '\\$1'), /[\x00-\x1f]/g, lowbyte); + return wrapQuotes(s, 'single', opts); +} + +function lowbyte(c) { + var n = c.charCodeAt(0); + var x = { + 8: 'b', + 9: 't', + 10: 'n', + 12: 'f', + 13: 'r' + }[n]; + if (x) { return '\\' + x; } + return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16)); +} + +function markBoxed(str) { + return 'Object(' + str + ')'; +} + +function weakCollectionOf(type) { + return type + ' { ? }'; +} + +function collectionOf(type, size, entries, indent) { + var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', '); + return type + ' (' + size + ') {' + joinedEntries + '}'; +} + +function singleLineValues(xs) { + for (var i = 0; i < xs.length; i++) { + if (indexOf(xs[i], '\n') >= 0) { + return false; + } + } + return true; +} + +function getIndent(opts, depth) { + var baseIndent; + if (opts.indent === '\t') { + baseIndent = '\t'; + } else if (typeof opts.indent === 'number' && opts.indent > 0) { + baseIndent = $join.call(Array(opts.indent + 1), ' '); + } else { + return null; + } + return { + base: baseIndent, + prev: $join.call(Array(depth + 1), baseIndent) + }; +} + +function indentedJoin(xs, indent) { + if (xs.length === 0) { return ''; } + var lineJoiner = '\n' + indent.prev + indent.base; + return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev; +} + +function arrObjKeys(obj, inspect) { + var isArr = isArray(obj); + var xs = []; + if (isArr) { + xs.length = obj.length; + for (var i = 0; i < obj.length; i++) { + xs[i] = has(obj, i) ? inspect(obj[i], obj) : ''; + } + } + var syms = typeof gOPS === 'function' ? gOPS(obj) : []; + var symMap; + if (hasShammedSymbols) { + symMap = {}; + for (var k = 0; k < syms.length; k++) { + symMap['$' + syms[k]] = syms[k]; + } + } + + for (var key in obj) { // eslint-disable-line no-restricted-syntax + if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) { + // this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section + continue; // eslint-disable-line no-restricted-syntax, no-continue + } else if ($test.call(/[^\w$]/, key)) { + xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj)); + } else { + xs.push(key + ': ' + inspect(obj[key], obj)); + } + } + if (typeof gOPS === 'function') { + for (var j = 0; j < syms.length; j++) { + if (isEnumerable.call(obj, syms[j])) { + xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj)); + } + } + } + return xs; +} diff --git a/node_modules/object-inspect/package-support.json b/node_modules/object-inspect/package-support.json new file mode 100644 index 0000000..5cc12d0 --- /dev/null +++ b/node_modules/object-inspect/package-support.json @@ -0,0 +1,20 @@ +{ + "versions": [ + { + "version": "*", + "target": { + "node": "all" + }, + "response": { + "type": "time-permitting" + }, + "backing": { + "npm-funding": true, + "donations": [ + "https://github.com/ljharb", + "https://tidelift.com/funding/github/npm/object-inspect" + ] + } + } + ] +} diff --git a/node_modules/object-inspect/package.json b/node_modules/object-inspect/package.json new file mode 100644 index 0000000..9fd97ff --- /dev/null +++ b/node_modules/object-inspect/package.json @@ -0,0 +1,105 @@ +{ + "name": "object-inspect", + "version": "1.13.4", + "description": "string representations of objects in node and the browser", + "main": "index.js", + "sideEffects": false, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.1", + "@pkgjs/support": "^0.0.6", + "auto-changelog": "^2.5.0", + "core-js": "^2.6.12", + "error-cause": "^1.0.8", + "es-value-fixtures": "^1.7.1", + "eslint": "=8.8.0", + "for-each": "^0.3.4", + "functions-have-names": "^1.2.3", + "glob": "=10.3.7", + "globalthis": "^1.0.4", + "has-symbols": "^1.1.0", + "has-tostringtag": "^1.0.2", + "in-publish": "^2.0.1", + "jackspeak": "=2.1.1", + "make-arrow-function": "^1.2.0", + "mock-property": "^1.1.0", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "safer-buffer": "^2.1.2", + "semver": "^6.3.1", + "string.prototype.repeat": "^1.0.0", + "tape": "^5.9.0" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "pretest": "npm run lint", + "lint": "eslint --ext=js,mjs .", + "postlint": "npx @pkgjs/support validate", + "test": "npm run tests-only && npm run test:corejs", + "tests-only": "nyc tape 'test/*.js'", + "test:corejs": "nyc tape test-core-js.js 'test/*.js'", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "testling": { + "files": [ + "test/*.js", + "test/browser/*.js" + ], + "browsers": [ + "ie/6..latest", + "chrome/latest", + "firefox/latest", + "safari/latest", + "opera/latest", + "iphone/latest", + "ipad/latest", + "android/latest" + ] + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/object-inspect.git" + }, + "homepage": "https://github.com/inspect-js/object-inspect", + "keywords": [ + "inspect", + "util.inspect", + "object", + "stringify", + "pretty" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "browser": { + "./util.inspect.js": false + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "./test-core-js.js" + ] + }, + "support": true, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/object-inspect/readme.markdown b/node_modules/object-inspect/readme.markdown new file mode 100644 index 0000000..f91617d --- /dev/null +++ b/node_modules/object-inspect/readme.markdown @@ -0,0 +1,84 @@ +# object-inspect [![Version Badge][npm-version-svg]][package-url] + +string representations of objects in node and the browser + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +# example + +## circular + +``` js +var inspect = require('object-inspect'); +var obj = { a: 1, b: [3,4] }; +obj.c = obj; +console.log(inspect(obj)); +``` + +## dom element + +``` js +var inspect = require('object-inspect'); + +var d = document.createElement('div'); +d.setAttribute('id', 'beep'); +d.innerHTML = 'woooiiiii'; + +console.log(inspect([ d, { a: 3, b : 4, c: [5,6,[7,[8,[9]]]] } ])); +``` + +output: + +``` +[
...
, { a: 3, b: 4, c: [ 5, 6, [ 7, [ 8, [ ... ] ] ] ] } ] +``` + +# methods + +``` js +var inspect = require('object-inspect') +``` + +## var s = inspect(obj, opts={}) + +Return a string `s` with the string representation of `obj` up to a depth of `opts.depth`. + +Additional options: + - `quoteStyle`: must be "single" or "double", if present. Default `'single'` for strings, `'double'` for HTML elements. + - `maxStringLength`: must be `0`, a positive integer, `Infinity`, or `null`, if present. Default `Infinity`. + - `customInspect`: When `true`, a custom inspect method function will be invoked (either undere the `util.inspect.custom` symbol, or the `inspect` property). When the string `'symbol'`, only the symbol method will be invoked. Default `true`. + - `indent`: must be "\t", `null`, or a positive integer. Default `null`. + - `numericSeparator`: must be a boolean, if present. Default `false`. If `true`, all numbers will be printed with numeric separators (eg, `1234.5678` will be printed as `'1_234.567_8'`) + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install object-inspect +``` + +# license + +MIT + +[package-url]: https://npmjs.org/package/object-inspect +[npm-version-svg]: https://versionbadg.es/inspect-js/object-inspect.svg +[deps-svg]: https://david-dm.org/inspect-js/object-inspect.svg +[deps-url]: https://david-dm.org/inspect-js/object-inspect +[dev-deps-svg]: https://david-dm.org/inspect-js/object-inspect/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/object-inspect#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/object-inspect.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/object-inspect.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/object-inspect.svg +[downloads-url]: https://npm-stat.com/charts.html?package=object-inspect +[codecov-image]: https://codecov.io/gh/inspect-js/object-inspect/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/object-inspect/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/object-inspect +[actions-url]: https://github.com/inspect-js/object-inspect/actions diff --git a/node_modules/object-inspect/test-core-js.js b/node_modules/object-inspect/test-core-js.js new file mode 100644 index 0000000..e53c400 --- /dev/null +++ b/node_modules/object-inspect/test-core-js.js @@ -0,0 +1,26 @@ +'use strict'; + +require('core-js'); + +var inspect = require('./'); +var test = require('tape'); + +test('Maps', function (t) { + t.equal(inspect(new Map([[1, 2]])), 'Map (1) {1 => 2}'); + t.end(); +}); + +test('WeakMaps', function (t) { + t.equal(inspect(new WeakMap([[{}, 2]])), 'WeakMap { ? }'); + t.end(); +}); + +test('Sets', function (t) { + t.equal(inspect(new Set([[1, 2]])), 'Set (1) {[ 1, 2 ]}'); + t.end(); +}); + +test('WeakSets', function (t) { + t.equal(inspect(new WeakSet([[1, 2]])), 'WeakSet { ? }'); + t.end(); +}); diff --git a/node_modules/object-inspect/test/bigint.js b/node_modules/object-inspect/test/bigint.js new file mode 100644 index 0000000..4ecc31d --- /dev/null +++ b/node_modules/object-inspect/test/bigint.js @@ -0,0 +1,58 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var hasToStringTag = require('has-tostringtag/shams')(); + +test('bigint', { skip: typeof BigInt === 'undefined' }, function (t) { + t.test('primitives', function (st) { + st.plan(3); + + st.equal(inspect(BigInt(-256)), '-256n'); + st.equal(inspect(BigInt(0)), '0n'); + st.equal(inspect(BigInt(256)), '256n'); + }); + + t.test('objects', function (st) { + st.plan(3); + + st.equal(inspect(Object(BigInt(-256))), 'Object(-256n)'); + st.equal(inspect(Object(BigInt(0))), 'Object(0n)'); + st.equal(inspect(Object(BigInt(256))), 'Object(256n)'); + }); + + t.test('syntactic primitives', function (st) { + st.plan(3); + + /* eslint-disable no-new-func */ + st.equal(inspect(Function('return -256n')()), '-256n'); + st.equal(inspect(Function('return 0n')()), '0n'); + st.equal(inspect(Function('return 256n')()), '256n'); + }); + + t.test('toStringTag', { skip: !hasToStringTag }, function (st) { + st.plan(1); + + var faker = {}; + faker[Symbol.toStringTag] = 'BigInt'; + st.equal( + inspect(faker), + '{ [Symbol(Symbol.toStringTag)]: \'BigInt\' }', + 'object lying about being a BigInt inspects as an object' + ); + }); + + t.test('numericSeparator', function (st) { + st.equal(inspect(BigInt(0), { numericSeparator: false }), '0n', '0n, numericSeparator false'); + st.equal(inspect(BigInt(0), { numericSeparator: true }), '0n', '0n, numericSeparator true'); + + st.equal(inspect(BigInt(1234), { numericSeparator: false }), '1234n', '1234n, numericSeparator false'); + st.equal(inspect(BigInt(1234), { numericSeparator: true }), '1_234n', '1234n, numericSeparator true'); + st.equal(inspect(BigInt(-1234), { numericSeparator: false }), '-1234n', '1234n, numericSeparator false'); + st.equal(inspect(BigInt(-1234), { numericSeparator: true }), '-1_234n', '1234n, numericSeparator true'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/browser/dom.js b/node_modules/object-inspect/test/browser/dom.js new file mode 100644 index 0000000..210c0b2 --- /dev/null +++ b/node_modules/object-inspect/test/browser/dom.js @@ -0,0 +1,15 @@ +var inspect = require('../../'); +var test = require('tape'); + +test('dom element', function (t) { + t.plan(1); + + var d = document.createElement('div'); + d.setAttribute('id', 'beep'); + d.innerHTML = 'woooiiiii'; + + t.equal( + inspect([d, { a: 3, b: 4, c: [5, 6, [7, [8, [9]]]] }]), + '[
...
, { a: 3, b: 4, c: [ 5, 6, [ 7, [ 8, [Object] ] ] ] } ]' + ); +}); diff --git a/node_modules/object-inspect/test/circular.js b/node_modules/object-inspect/test/circular.js new file mode 100644 index 0000000..5df4233 --- /dev/null +++ b/node_modules/object-inspect/test/circular.js @@ -0,0 +1,16 @@ +var inspect = require('../'); +var test = require('tape'); + +test('circular', function (t) { + t.plan(2); + var obj = { a: 1, b: [3, 4] }; + obj.c = obj; + t.equal(inspect(obj), '{ a: 1, b: [ 3, 4 ], c: [Circular] }'); + + var double = {}; + double.a = [double]; + double.b = {}; + double.b.inner = double.b; + double.b.obj = double; + t.equal(inspect(double), '{ a: [ [Circular] ], b: { inner: [Circular], obj: [Circular] } }'); +}); diff --git a/node_modules/object-inspect/test/deep.js b/node_modules/object-inspect/test/deep.js new file mode 100644 index 0000000..99ce32a --- /dev/null +++ b/node_modules/object-inspect/test/deep.js @@ -0,0 +1,12 @@ +var inspect = require('../'); +var test = require('tape'); + +test('deep', function (t) { + t.plan(4); + var obj = [[[[[[500]]]]]]; + t.equal(inspect(obj), '[ [ [ [ [ [Array] ] ] ] ] ]'); + t.equal(inspect(obj, { depth: 4 }), '[ [ [ [ [Array] ] ] ] ]'); + t.equal(inspect(obj, { depth: 2 }), '[ [ [Array] ] ]'); + + t.equal(inspect([[[{ a: 1 }]]], { depth: 3 }), '[ [ [ [Object] ] ] ]'); +}); diff --git a/node_modules/object-inspect/test/element.js b/node_modules/object-inspect/test/element.js new file mode 100644 index 0000000..47fa9e2 --- /dev/null +++ b/node_modules/object-inspect/test/element.js @@ -0,0 +1,53 @@ +var inspect = require('../'); +var test = require('tape'); + +test('element', function (t) { + t.plan(3); + var elem = { + nodeName: 'div', + attributes: [{ name: 'class', value: 'row' }], + getAttribute: function (key) { return key; }, + childNodes: [] + }; + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); + t.deepEqual(inspect(obj, { quoteStyle: 'single' }), "[ 1,
, 3 ]"); + t.deepEqual(inspect(obj, { quoteStyle: 'double' }), '[ 1,
, 3 ]'); +}); + +test('element no attr', function (t) { + t.plan(1); + var elem = { + nodeName: 'div', + getAttribute: function (key) { return key; }, + childNodes: [] + }; + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); +}); + +test('element with contents', function (t) { + t.plan(1); + var elem = { + nodeName: 'div', + getAttribute: function (key) { return key; }, + childNodes: [{ nodeName: 'b' }] + }; + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
...
, 3 ]'); +}); + +test('element instance', function (t) { + t.plan(1); + var h = global.HTMLElement; + global.HTMLElement = function (name, attr) { + this.nodeName = name; + this.attributes = attr; + }; + global.HTMLElement.prototype.getAttribute = function () {}; + + var elem = new global.HTMLElement('div', []); + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); + global.HTMLElement = h; +}); diff --git a/node_modules/object-inspect/test/err.js b/node_modules/object-inspect/test/err.js new file mode 100644 index 0000000..cc1d884 --- /dev/null +++ b/node_modules/object-inspect/test/err.js @@ -0,0 +1,48 @@ +var test = require('tape'); +var ErrorWithCause = require('error-cause/Error'); + +var inspect = require('../'); + +test('type error', function (t) { + t.plan(1); + var aerr = new TypeError(); + aerr.foo = 555; + aerr.bar = [1, 2, 3]; + + var berr = new TypeError('tuv'); + berr.baz = 555; + + var cerr = new SyntaxError(); + cerr.message = 'whoa'; + cerr['a-b'] = 5; + + var withCause = new ErrorWithCause('foo', { cause: 'bar' }); + var withCausePlus = new ErrorWithCause('foo', { cause: 'bar' }); + withCausePlus.foo = 'bar'; + var withUndefinedCause = new ErrorWithCause('foo', { cause: undefined }); + var withEnumerableCause = new Error('foo'); + withEnumerableCause.cause = 'bar'; + + var obj = [ + new TypeError(), + new TypeError('xxx'), + aerr, + berr, + cerr, + withCause, + withCausePlus, + withUndefinedCause, + withEnumerableCause + ]; + t.equal(inspect(obj), '[ ' + [ + '[TypeError]', + '[TypeError: xxx]', + '{ [TypeError] foo: 555, bar: [ 1, 2, 3 ] }', + '{ [TypeError: tuv] baz: 555 }', + '{ [SyntaxError: whoa] message: \'whoa\', \'a-b\': 5 }', + 'cause' in Error.prototype ? '[Error: foo]' : '{ [Error: foo] [cause]: \'bar\' }', + '{ [Error: foo] ' + ('cause' in Error.prototype ? '' : '[cause]: \'bar\', ') + 'foo: \'bar\' }', + 'cause' in Error.prototype ? '[Error: foo]' : '{ [Error: foo] [cause]: undefined }', + '{ [Error: foo] cause: \'bar\' }' + ].join(', ') + ' ]'); +}); diff --git a/node_modules/object-inspect/test/fakes.js b/node_modules/object-inspect/test/fakes.js new file mode 100644 index 0000000..a65c08c --- /dev/null +++ b/node_modules/object-inspect/test/fakes.js @@ -0,0 +1,29 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var hasToStringTag = require('has-tostringtag/shams')(); +var forEach = require('for-each'); + +test('fakes', { skip: !hasToStringTag }, function (t) { + forEach([ + 'Array', + 'Boolean', + 'Date', + 'Error', + 'Number', + 'RegExp', + 'String' + ], function (expected) { + var faker = {}; + faker[Symbol.toStringTag] = expected; + + t.equal( + inspect(faker), + '{ [Symbol(Symbol.toStringTag)]: \'' + expected + '\' }', + 'faker masquerading as ' + expected + ' is not shown as one' + ); + }); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/fn.js b/node_modules/object-inspect/test/fn.js new file mode 100644 index 0000000..de3ca62 --- /dev/null +++ b/node_modules/object-inspect/test/fn.js @@ -0,0 +1,76 @@ +var inspect = require('../'); +var test = require('tape'); +var arrow = require('make-arrow-function')(); +var functionsHaveConfigurableNames = require('functions-have-names').functionsHaveConfigurableNames(); + +test('function', function (t) { + t.plan(1); + var obj = [1, 2, function f(n) { return n; }, 4]; + t.equal(inspect(obj), '[ 1, 2, [Function: f], 4 ]'); +}); + +test('function name', function (t) { + t.plan(1); + var f = (function () { + return function () {}; + }()); + f.toString = function toStr() { return 'function xxx () {}'; }; + var obj = [1, 2, f, 4]; + t.equal(inspect(obj), '[ 1, 2, [Function (anonymous)] { toString: [Function: toStr] }, 4 ]'); +}); + +test('anon function', function (t) { + var f = (function () { + return function () {}; + }()); + var obj = [1, 2, f, 4]; + t.equal(inspect(obj), '[ 1, 2, [Function (anonymous)], 4 ]'); + + t.end(); +}); + +test('arrow function', { skip: !arrow }, function (t) { + t.equal(inspect(arrow), '[Function (anonymous)]'); + + t.end(); +}); + +test('truly nameless function', { skip: !arrow || !functionsHaveConfigurableNames }, function (t) { + function f() {} + Object.defineProperty(f, 'name', { value: false }); + t.equal(f.name, false); + t.equal( + inspect(f), + '[Function: f]', + 'named function with falsy `.name` does not hide its original name' + ); + + function g() {} + Object.defineProperty(g, 'name', { value: true }); + t.equal(g.name, true); + t.equal( + inspect(g), + '[Function: true]', + 'named function with truthy `.name` hides its original name' + ); + + var anon = function () {}; // eslint-disable-line func-style + Object.defineProperty(anon, 'name', { value: null }); + t.equal(anon.name, null); + t.equal( + inspect(anon), + '[Function (anonymous)]', + 'anon function with falsy `.name` does not hide its anonymity' + ); + + var anon2 = function () {}; // eslint-disable-line func-style + Object.defineProperty(anon2, 'name', { value: 1 }); + t.equal(anon2.name, 1); + t.equal( + inspect(anon2), + '[Function: 1]', + 'anon function with truthy `.name` hides its anonymity' + ); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/global.js b/node_modules/object-inspect/test/global.js new file mode 100644 index 0000000..c57216a --- /dev/null +++ b/node_modules/object-inspect/test/global.js @@ -0,0 +1,17 @@ +'use strict'; + +var inspect = require('../'); + +var test = require('tape'); +var globalThis = require('globalthis')(); + +test('global object', function (t) { + /* eslint-env browser */ + var expected = typeof window === 'undefined' ? 'globalThis' : 'Window'; + t.equal( + inspect([globalThis]), + '[ { [object ' + expected + '] } ]' + ); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/has.js b/node_modules/object-inspect/test/has.js new file mode 100644 index 0000000..01800de --- /dev/null +++ b/node_modules/object-inspect/test/has.js @@ -0,0 +1,15 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var mockProperty = require('mock-property'); + +test('when Object#hasOwnProperty is deleted', function (t) { + t.plan(1); + var arr = [1, , 3]; // eslint-disable-line no-sparse-arrays + + t.teardown(mockProperty(Array.prototype, 1, { value: 2 })); // this is needed to account for "in" vs "hasOwnProperty" + t.teardown(mockProperty(Object.prototype, 'hasOwnProperty', { 'delete': true })); + + t.equal(inspect(arr), '[ 1, , 3 ]'); +}); diff --git a/node_modules/object-inspect/test/holes.js b/node_modules/object-inspect/test/holes.js new file mode 100644 index 0000000..87fc8c8 --- /dev/null +++ b/node_modules/object-inspect/test/holes.js @@ -0,0 +1,15 @@ +var test = require('tape'); +var inspect = require('../'); + +var xs = ['a', 'b']; +xs[5] = 'f'; +xs[7] = 'j'; +xs[8] = 'k'; + +test('holes', function (t) { + t.plan(1); + t.equal( + inspect(xs), + "[ 'a', 'b', , , , 'f', , 'j', 'k' ]" + ); +}); diff --git a/node_modules/object-inspect/test/indent-option.js b/node_modules/object-inspect/test/indent-option.js new file mode 100644 index 0000000..89d8fce --- /dev/null +++ b/node_modules/object-inspect/test/indent-option.js @@ -0,0 +1,271 @@ +var test = require('tape'); +var forEach = require('for-each'); + +var inspect = require('../'); + +test('bad indent options', function (t) { + forEach([ + undefined, + true, + false, + -1, + 1.2, + Infinity, + -Infinity, + NaN + ], function (indent) { + t['throws']( + function () { inspect('', { indent: indent }); }, + TypeError, + inspect(indent) + ' is invalid' + ); + }); + + t.end(); +}); + +test('simple object with indent', function (t) { + t.plan(2); + + var obj = { a: 1, b: 2 }; + + var expectedSpaces = [ + '{', + ' a: 1,', + ' b: 2', + '}' + ].join('\n'); + var expectedTabs = [ + '{', + ' a: 1,', + ' b: 2', + '}' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('two deep object with indent', function (t) { + t.plan(2); + + var obj = { a: 1, b: { c: 3, d: 4 } }; + + var expectedSpaces = [ + '{', + ' a: 1,', + ' b: {', + ' c: 3,', + ' d: 4', + ' }', + '}' + ].join('\n'); + var expectedTabs = [ + '{', + ' a: 1,', + ' b: {', + ' c: 3,', + ' d: 4', + ' }', + '}' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('simple array with all single line elements', function (t) { + t.plan(2); + + var obj = [1, 2, 3, 'asdf\nsdf']; + + var expected = '[ 1, 2, 3, \'asdf\\nsdf\' ]'; + + t.equal(inspect(obj, { indent: 2 }), expected, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expected, 'tabs'); +}); + +test('array with complex elements', function (t) { + t.plan(2); + + var obj = [1, { a: 1, b: { c: 1 } }, 'asdf\nsdf']; + + var expectedSpaces = [ + '[', + ' 1,', + ' {', + ' a: 1,', + ' b: {', + ' c: 1', + ' }', + ' },', + ' \'asdf\\nsdf\'', + ']' + ].join('\n'); + var expectedTabs = [ + '[', + ' 1,', + ' {', + ' a: 1,', + ' b: {', + ' c: 1', + ' }', + ' },', + ' \'asdf\\nsdf\'', + ']' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('values', function (t) { + t.plan(2); + var obj = [{}, [], { 'a-b': 5 }]; + + var expectedSpaces = [ + '[', + ' {},', + ' [],', + ' {', + ' \'a-b\': 5', + ' }', + ']' + ].join('\n'); + var expectedTabs = [ + '[', + ' {},', + ' [],', + ' {', + ' \'a-b\': 5', + ' }', + ']' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('Map', { skip: typeof Map !== 'function' }, function (t) { + var map = new Map(); + map.set({ a: 1 }, ['b']); + map.set(3, NaN); + + var expectedStringSpaces = [ + 'Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + '}' + ].join('\n'); + var expectedStringTabs = [ + 'Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + '}' + ].join('\n'); + var expectedStringTabsDoubleQuotes = [ + 'Map (2) {', + ' { a: 1 } => [ "b" ],', + ' 3 => NaN', + '}' + ].join('\n'); + + t.equal( + inspect(map, { indent: 2 }), + expectedStringSpaces, + 'Map keys are not indented (two)' + ); + t.equal( + inspect(map, { indent: '\t' }), + expectedStringTabs, + 'Map keys are not indented (tabs)' + ); + t.equal( + inspect(map, { indent: '\t', quoteStyle: 'double' }), + expectedStringTabsDoubleQuotes, + 'Map keys are not indented (tabs + double quotes)' + ); + + t.equal(inspect(new Map(), { indent: 2 }), 'Map (0) {}', 'empty Map should show as empty (two)'); + t.equal(inspect(new Map(), { indent: '\t' }), 'Map (0) {}', 'empty Map should show as empty (tabs)'); + + var nestedMap = new Map(); + nestedMap.set(nestedMap, map); + var expectedNestedSpaces = [ + 'Map (1) {', + ' [Circular] => Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + ' }', + '}' + ].join('\n'); + var expectedNestedTabs = [ + 'Map (1) {', + ' [Circular] => Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + ' }', + '}' + ].join('\n'); + t.equal(inspect(nestedMap, { indent: 2 }), expectedNestedSpaces, 'Map containing a Map should work (two)'); + t.equal(inspect(nestedMap, { indent: '\t' }), expectedNestedTabs, 'Map containing a Map should work (tabs)'); + + t.end(); +}); + +test('Set', { skip: typeof Set !== 'function' }, function (t) { + var set = new Set(); + set.add({ a: 1 }); + set.add(['b']); + var expectedStringSpaces = [ + 'Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + '}' + ].join('\n'); + var expectedStringTabs = [ + 'Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + '}' + ].join('\n'); + t.equal(inspect(set, { indent: 2 }), expectedStringSpaces, 'new Set([{ a: 1 }, ["b"]]) should show size and contents (two)'); + t.equal(inspect(set, { indent: '\t' }), expectedStringTabs, 'new Set([{ a: 1 }, ["b"]]) should show size and contents (tabs)'); + + t.equal(inspect(new Set(), { indent: 2 }), 'Set (0) {}', 'empty Set should show as empty (two)'); + t.equal(inspect(new Set(), { indent: '\t' }), 'Set (0) {}', 'empty Set should show as empty (tabs)'); + + var nestedSet = new Set(); + nestedSet.add(set); + nestedSet.add(nestedSet); + var expectedNestedSpaces = [ + 'Set (2) {', + ' Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + ' },', + ' [Circular]', + '}' + ].join('\n'); + var expectedNestedTabs = [ + 'Set (2) {', + ' Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + ' },', + ' [Circular]', + '}' + ].join('\n'); + t.equal(inspect(nestedSet, { indent: 2 }), expectedNestedSpaces, 'Set containing a Set should work (two)'); + t.equal(inspect(nestedSet, { indent: '\t' }), expectedNestedTabs, 'Set containing a Set should work (tabs)'); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/inspect.js b/node_modules/object-inspect/test/inspect.js new file mode 100644 index 0000000..1abf81b --- /dev/null +++ b/node_modules/object-inspect/test/inspect.js @@ -0,0 +1,139 @@ +var test = require('tape'); +var hasSymbols = require('has-symbols/shams')(); +var utilInspect = require('../util.inspect'); +var repeat = require('string.prototype.repeat'); + +var inspect = require('..'); + +test('inspect', function (t) { + t.plan(5); + + var obj = [{ inspect: function xyzInspect() { return '!XYZ¡'; } }, []]; + var stringResult = '[ !XYZ¡, [] ]'; + var falseResult = '[ { inspect: [Function: xyzInspect] }, [] ]'; + + t.equal(inspect(obj), stringResult); + t.equal(inspect(obj, { customInspect: true }), stringResult); + t.equal(inspect(obj, { customInspect: 'symbol' }), falseResult); + t.equal(inspect(obj, { customInspect: false }), falseResult); + t['throws']( + function () { inspect(obj, { customInspect: 'not a boolean or "symbol"' }); }, + TypeError, + '`customInspect` must be a boolean or the string "symbol"' + ); +}); + +test('inspect custom symbol', { skip: !hasSymbols || !utilInspect || !utilInspect.custom }, function (t) { + t.plan(4); + + var obj = { inspect: function stringInspect() { return 'string'; } }; + obj[utilInspect.custom] = function custom() { return 'symbol'; }; + + var symbolResult = '[ symbol, [] ]'; + var stringResult = '[ string, [] ]'; + var falseResult = '[ { inspect: [Function: stringInspect]' + (utilInspect.custom ? ', [' + inspect(utilInspect.custom) + ']: [Function: custom]' : '') + ' }, [] ]'; + + var symbolStringFallback = utilInspect.custom ? symbolResult : stringResult; + var symbolFalseFallback = utilInspect.custom ? symbolResult : falseResult; + + t.equal(inspect([obj, []]), symbolStringFallback); + t.equal(inspect([obj, []], { customInspect: true }), symbolStringFallback); + t.equal(inspect([obj, []], { customInspect: 'symbol' }), symbolFalseFallback); + t.equal(inspect([obj, []], { customInspect: false }), falseResult); +}); + +test('symbols', { skip: !hasSymbols }, function (t) { + t.plan(2); + + var obj = { a: 1 }; + obj[Symbol('test')] = 2; + obj[Symbol.iterator] = 3; + Object.defineProperty(obj, Symbol('non-enum'), { + enumerable: false, + value: 4 + }); + + if (typeof Symbol.iterator === 'symbol') { + t.equal(inspect(obj), '{ a: 1, [Symbol(test)]: 2, [Symbol(Symbol.iterator)]: 3 }', 'object with symbols'); + t.equal(inspect([obj, []]), '[ { a: 1, [Symbol(test)]: 2, [Symbol(Symbol.iterator)]: 3 }, [] ]', 'object with symbols in array'); + } else { + // symbol sham key ordering is unreliable + t.match( + inspect(obj), + /^(?:{ a: 1, \[Symbol\(test\)\]: 2, \[Symbol\(Symbol.iterator\)\]: 3 }|{ a: 1, \[Symbol\(Symbol.iterator\)\]: 3, \[Symbol\(test\)\]: 2 })$/, + 'object with symbols (nondeterministic symbol sham key ordering)' + ); + t.match( + inspect([obj, []]), + /^\[ (?:{ a: 1, \[Symbol\(test\)\]: 2, \[Symbol\(Symbol.iterator\)\]: 3 }|{ a: 1, \[Symbol\(Symbol.iterator\)\]: 3, \[Symbol\(test\)\]: 2 }), \[\] \]$/, + 'object with symbols in array (nondeterministic symbol sham key ordering)' + ); + } +}); + +test('maxStringLength', function (t) { + t['throws']( + function () { inspect('', { maxStringLength: -1 }); }, + TypeError, + 'maxStringLength must be >= 0, or Infinity, not negative' + ); + + var str = repeat('a', 1e8); + + t.equal( + inspect([str], { maxStringLength: 10 }), + '[ \'aaaaaaaaaa\'... 99999990 more characters ]', + 'maxStringLength option limits output' + ); + + t.equal( + inspect(['f'], { maxStringLength: null }), + '[ \'\'... 1 more character ]', + 'maxStringLength option accepts `null`' + ); + + t.equal( + inspect([str], { maxStringLength: Infinity }), + '[ \'' + str + '\' ]', + 'maxStringLength option accepts ∞' + ); + + t.end(); +}); + +test('inspect options', { skip: !utilInspect.custom }, function (t) { + var obj = {}; + obj[utilInspect.custom] = function () { + return JSON.stringify(arguments); + }; + t.equal( + inspect(obj), + utilInspect(obj, { depth: 5 }), + 'custom symbols will use node\'s inspect' + ); + t.equal( + inspect(obj, { depth: 2 }), + utilInspect(obj, { depth: 2 }), + 'a reduced depth will be passed to node\'s inspect' + ); + t.equal( + inspect({ d1: obj }, { depth: 3 }), + '{ d1: ' + utilInspect(obj, { depth: 2 }) + ' }', + 'deep objects will receive a reduced depth' + ); + t.equal( + inspect({ d1: obj }, { depth: 1 }), + '{ d1: [Object] }', + 'unlike nodejs inspect, customInspect will not be used once the depth is exceeded.' + ); + t.end(); +}); + +test('inspect URL', { skip: typeof URL === 'undefined' }, function (t) { + t.match( + inspect(new URL('https://nodejs.org')), + /nodejs\.org/, // Different environments stringify it differently + 'url can be inspected' + ); + t.end(); +}); diff --git a/node_modules/object-inspect/test/lowbyte.js b/node_modules/object-inspect/test/lowbyte.js new file mode 100644 index 0000000..68a345d --- /dev/null +++ b/node_modules/object-inspect/test/lowbyte.js @@ -0,0 +1,12 @@ +var test = require('tape'); +var inspect = require('../'); + +var obj = { x: 'a\r\nb', y: '\x05! \x1f \x12' }; + +test('interpolate low bytes', function (t) { + t.plan(1); + t.equal( + inspect(obj), + "{ x: 'a\\r\\nb', y: '\\x05! \\x1F \\x12' }" + ); +}); diff --git a/node_modules/object-inspect/test/number.js b/node_modules/object-inspect/test/number.js new file mode 100644 index 0000000..8f287e8 --- /dev/null +++ b/node_modules/object-inspect/test/number.js @@ -0,0 +1,58 @@ +var test = require('tape'); +var v = require('es-value-fixtures'); +var forEach = require('for-each'); + +var inspect = require('../'); + +test('negative zero', function (t) { + t.equal(inspect(0), '0', 'inspect(0) === "0"'); + t.equal(inspect(Object(0)), 'Object(0)', 'inspect(Object(0)) === "Object(0)"'); + + t.equal(inspect(-0), '-0', 'inspect(-0) === "-0"'); + t.equal(inspect(Object(-0)), 'Object(-0)', 'inspect(Object(-0)) === "Object(-0)"'); + + t.end(); +}); + +test('numericSeparator', function (t) { + forEach(v.nonBooleans, function (nonBoolean) { + t['throws']( + function () { inspect(true, { numericSeparator: nonBoolean }); }, + TypeError, + inspect(nonBoolean) + ' is not a boolean' + ); + }); + + t.test('3 digit numbers', function (st) { + var failed = false; + for (var i = -999; i < 1000; i += 1) { + var actual = inspect(i); + var actualSepNo = inspect(i, { numericSeparator: false }); + var actualSepYes = inspect(i, { numericSeparator: true }); + var expected = String(i); + if (actual !== expected || actualSepNo !== expected || actualSepYes !== expected) { + failed = true; + t.equal(actual, expected); + t.equal(actualSepNo, expected); + t.equal(actualSepYes, expected); + } + } + + st.notOk(failed, 'all 3 digit numbers passed'); + + st.end(); + }); + + t.equal(inspect(1e3), '1000', '1000'); + t.equal(inspect(1e3, { numericSeparator: false }), '1000', '1000, numericSeparator false'); + t.equal(inspect(1e3, { numericSeparator: true }), '1_000', '1000, numericSeparator true'); + t.equal(inspect(-1e3), '-1000', '-1000'); + t.equal(inspect(-1e3, { numericSeparator: false }), '-1000', '-1000, numericSeparator false'); + t.equal(inspect(-1e3, { numericSeparator: true }), '-1_000', '-1000, numericSeparator true'); + + t.equal(inspect(1234.5678, { numericSeparator: true }), '1_234.567_8', 'fractional numbers get separators'); + t.equal(inspect(1234.56789, { numericSeparator: true }), '1_234.567_89', 'fractional numbers get separators'); + t.equal(inspect(1234.567891, { numericSeparator: true }), '1_234.567_891', 'fractional numbers get separators'); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/quoteStyle.js b/node_modules/object-inspect/test/quoteStyle.js new file mode 100644 index 0000000..da23e63 --- /dev/null +++ b/node_modules/object-inspect/test/quoteStyle.js @@ -0,0 +1,26 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); + +test('quoteStyle option', function (t) { + t['throws'](function () { inspect(null, { quoteStyle: false }); }, 'false is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: true }); }, 'true is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: '' }); }, '"" is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: {} }); }, '{} is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: [] }); }, '[] is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: 42 }); }, '42 is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: NaN }); }, 'NaN is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: function () {} }); }, 'a function is not a valid value'); + + t.equal(inspect('"', { quoteStyle: 'single' }), '\'"\'', 'double quote, quoteStyle: "single"'); + t.equal(inspect('"', { quoteStyle: 'double' }), '"\\""', 'double quote, quoteStyle: "double"'); + + t.equal(inspect('\'', { quoteStyle: 'single' }), '\'\\\'\'', 'single quote, quoteStyle: "single"'); + t.equal(inspect('\'', { quoteStyle: 'double' }), '"\'"', 'single quote, quoteStyle: "double"'); + + t.equal(inspect('`', { quoteStyle: 'single' }), '\'`\'', 'backtick, quoteStyle: "single"'); + t.equal(inspect('`', { quoteStyle: 'double' }), '"`"', 'backtick, quoteStyle: "double"'); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/toStringTag.js b/node_modules/object-inspect/test/toStringTag.js new file mode 100644 index 0000000..95f8270 --- /dev/null +++ b/node_modules/object-inspect/test/toStringTag.js @@ -0,0 +1,40 @@ +'use strict'; + +var test = require('tape'); +var hasToStringTag = require('has-tostringtag/shams')(); + +var inspect = require('../'); + +test('Symbol.toStringTag', { skip: !hasToStringTag }, function (t) { + t.plan(4); + + var obj = { a: 1 }; + t.equal(inspect(obj), '{ a: 1 }', 'object, no Symbol.toStringTag'); + + obj[Symbol.toStringTag] = 'foo'; + t.equal(inspect(obj), '{ a: 1, [Symbol(Symbol.toStringTag)]: \'foo\' }', 'object with Symbol.toStringTag'); + + t.test('null objects', { skip: 'toString' in { __proto__: null } }, function (st) { + st.plan(2); + + var dict = { __proto__: null, a: 1 }; + st.equal(inspect(dict), '[Object: null prototype] { a: 1 }', 'null object with Symbol.toStringTag'); + + dict[Symbol.toStringTag] = 'Dict'; + st.equal(inspect(dict), '[Dict: null prototype] { a: 1, [Symbol(Symbol.toStringTag)]: \'Dict\' }', 'null object with Symbol.toStringTag'); + }); + + t.test('instances', function (st) { + st.plan(4); + + function C() { + this.a = 1; + } + st.equal(Object.prototype.toString.call(new C()), '[object Object]', 'instance, no toStringTag, Object.prototype.toString'); + st.equal(inspect(new C()), 'C { a: 1 }', 'instance, no toStringTag'); + + C.prototype[Symbol.toStringTag] = 'Class!'; + st.equal(Object.prototype.toString.call(new C()), '[object Class!]', 'instance, with toStringTag, Object.prototype.toString'); + st.equal(inspect(new C()), 'C [Class!] { a: 1 }', 'instance, with toStringTag'); + }); +}); diff --git a/node_modules/object-inspect/test/undef.js b/node_modules/object-inspect/test/undef.js new file mode 100644 index 0000000..e3f4961 --- /dev/null +++ b/node_modules/object-inspect/test/undef.js @@ -0,0 +1,12 @@ +var test = require('tape'); +var inspect = require('../'); + +var obj = { a: 1, b: [3, 4, undefined, null], c: undefined, d: null }; + +test('undef and null', function (t) { + t.plan(1); + t.equal( + inspect(obj), + '{ a: 1, b: [ 3, 4, undefined, null ], c: undefined, d: null }' + ); +}); diff --git a/node_modules/object-inspect/test/values.js b/node_modules/object-inspect/test/values.js new file mode 100644 index 0000000..15986cd --- /dev/null +++ b/node_modules/object-inspect/test/values.js @@ -0,0 +1,261 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var mockProperty = require('mock-property'); +var hasSymbols = require('has-symbols/shams')(); +var hasToStringTag = require('has-tostringtag/shams')(); +var forEach = require('for-each'); +var semver = require('semver'); + +test('values', function (t) { + t.plan(1); + var obj = [{}, [], { 'a-b': 5 }]; + t.equal(inspect(obj), '[ {}, [], { \'a-b\': 5 } ]'); +}); + +test('arrays with properties', function (t) { + t.plan(1); + var arr = [3]; + arr.foo = 'bar'; + var obj = [1, 2, arr]; + obj.baz = 'quux'; + obj.index = -1; + t.equal(inspect(obj), '[ 1, 2, [ 3, foo: \'bar\' ], baz: \'quux\', index: -1 ]'); +}); + +test('has', function (t) { + t.plan(1); + t.teardown(mockProperty(Object.prototype, 'hasOwnProperty', { 'delete': true })); + + t.equal(inspect({ a: 1, b: 2 }), '{ a: 1, b: 2 }'); +}); + +test('indexOf seen', function (t) { + t.plan(1); + var xs = [1, 2, 3, {}]; + xs.push(xs); + + var seen = []; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[ 1, 2, 3, {}, [Circular] ]' + ); +}); + +test('seen seen', function (t) { + t.plan(1); + var xs = [1, 2, 3]; + + var seen = [xs]; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[Circular]' + ); +}); + +test('seen seen seen', function (t) { + t.plan(1); + var xs = [1, 2, 3]; + + var seen = [5, xs]; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[Circular]' + ); +}); + +test('symbols', { skip: !hasSymbols }, function (t) { + var sym = Symbol('foo'); + t.equal(inspect(sym), 'Symbol(foo)', 'Symbol("foo") should be "Symbol(foo)"'); + if (typeof sym === 'symbol') { + // Symbol shams are incapable of differentiating boxed from unboxed symbols + t.equal(inspect(Object(sym)), 'Object(Symbol(foo))', 'Object(Symbol("foo")) should be "Object(Symbol(foo))"'); + } + + t.test('toStringTag', { skip: !hasToStringTag }, function (st) { + st.plan(1); + + var faker = {}; + faker[Symbol.toStringTag] = 'Symbol'; + st.equal( + inspect(faker), + '{ [Symbol(Symbol.toStringTag)]: \'Symbol\' }', + 'object lying about being a Symbol inspects as an object' + ); + }); + + t.end(); +}); + +test('Map', { skip: typeof Map !== 'function' }, function (t) { + var map = new Map(); + map.set({ a: 1 }, ['b']); + map.set(3, NaN); + var expectedString = 'Map (2) {' + inspect({ a: 1 }) + ' => ' + inspect(['b']) + ', 3 => NaN}'; + t.equal(inspect(map), expectedString, 'new Map([[{ a: 1 }, ["b"]], [3, NaN]]) should show size and contents'); + t.equal(inspect(new Map()), 'Map (0) {}', 'empty Map should show as empty'); + + var nestedMap = new Map(); + nestedMap.set(nestedMap, map); + t.equal(inspect(nestedMap), 'Map (1) {[Circular] => ' + expectedString + '}', 'Map containing a Map should work'); + + t.end(); +}); + +test('WeakMap', { skip: typeof WeakMap !== 'function' }, function (t) { + var map = new WeakMap(); + map.set({ a: 1 }, ['b']); + var expectedString = 'WeakMap { ? }'; + t.equal(inspect(map), expectedString, 'new WeakMap([[{ a: 1 }, ["b"]]]) should not show size or contents'); + t.equal(inspect(new WeakMap()), 'WeakMap { ? }', 'empty WeakMap should not show as empty'); + + t.end(); +}); + +test('Set', { skip: typeof Set !== 'function' }, function (t) { + var set = new Set(); + set.add({ a: 1 }); + set.add(['b']); + var expectedString = 'Set (2) {' + inspect({ a: 1 }) + ', ' + inspect(['b']) + '}'; + t.equal(inspect(set), expectedString, 'new Set([{ a: 1 }, ["b"]]) should show size and contents'); + t.equal(inspect(new Set()), 'Set (0) {}', 'empty Set should show as empty'); + + var nestedSet = new Set(); + nestedSet.add(set); + nestedSet.add(nestedSet); + t.equal(inspect(nestedSet), 'Set (2) {' + expectedString + ', [Circular]}', 'Set containing a Set should work'); + + t.end(); +}); + +test('WeakSet', { skip: typeof WeakSet !== 'function' }, function (t) { + var map = new WeakSet(); + map.add({ a: 1 }); + var expectedString = 'WeakSet { ? }'; + t.equal(inspect(map), expectedString, 'new WeakSet([{ a: 1 }]) should not show size or contents'); + t.equal(inspect(new WeakSet()), 'WeakSet { ? }', 'empty WeakSet should not show as empty'); + + t.end(); +}); + +test('WeakRef', { skip: typeof WeakRef !== 'function' }, function (t) { + var ref = new WeakRef({ a: 1 }); + var expectedString = 'WeakRef { ? }'; + t.equal(inspect(ref), expectedString, 'new WeakRef({ a: 1 }) should not show contents'); + + t.end(); +}); + +test('FinalizationRegistry', { skip: typeof FinalizationRegistry !== 'function' }, function (t) { + var registry = new FinalizationRegistry(function () {}); + var expectedString = 'FinalizationRegistry [FinalizationRegistry] {}'; + t.equal(inspect(registry), expectedString, 'new FinalizationRegistry(function () {}) should work normallys'); + + t.end(); +}); + +test('Strings', function (t) { + var str = 'abc'; + + t.equal(inspect(str), "'" + str + "'", 'primitive string shows as such'); + t.equal(inspect(str, { quoteStyle: 'single' }), "'" + str + "'", 'primitive string shows as such, single quoted'); + t.equal(inspect(str, { quoteStyle: 'double' }), '"' + str + '"', 'primitive string shows as such, double quoted'); + t.equal(inspect(Object(str)), 'Object(' + inspect(str) + ')', 'String object shows as such'); + t.equal(inspect(Object(str), { quoteStyle: 'single' }), 'Object(' + inspect(str, { quoteStyle: 'single' }) + ')', 'String object shows as such, single quoted'); + t.equal(inspect(Object(str), { quoteStyle: 'double' }), 'Object(' + inspect(str, { quoteStyle: 'double' }) + ')', 'String object shows as such, double quoted'); + + t.end(); +}); + +test('Numbers', function (t) { + var num = 42; + + t.equal(inspect(num), String(num), 'primitive number shows as such'); + t.equal(inspect(Object(num)), 'Object(' + inspect(num) + ')', 'Number object shows as such'); + + t.end(); +}); + +test('Booleans', function (t) { + t.equal(inspect(true), String(true), 'primitive true shows as such'); + t.equal(inspect(Object(true)), 'Object(' + inspect(true) + ')', 'Boolean object true shows as such'); + + t.equal(inspect(false), String(false), 'primitive false shows as such'); + t.equal(inspect(Object(false)), 'Object(' + inspect(false) + ')', 'Boolean false object shows as such'); + + t.end(); +}); + +test('Date', function (t) { + var now = new Date(); + t.equal(inspect(now), String(now), 'Date shows properly'); + t.equal(inspect(new Date(NaN)), 'Invalid Date', 'Invalid Date shows properly'); + + t.end(); +}); + +test('RegExps', function (t) { + t.equal(inspect(/a/g), '/a/g', 'regex shows properly'); + t.equal(inspect(new RegExp('abc', 'i')), '/abc/i', 'new RegExp shows properly'); + + var match = 'abc abc'.match(/[ab]+/); + delete match.groups; // for node < 10 + t.equal(inspect(match), '[ \'ab\', index: 0, input: \'abc abc\' ]', 'RegExp match object shows properly'); + + t.end(); +}); + +test('Proxies', { skip: typeof Proxy !== 'function' || !hasToStringTag }, function (t) { + var target = { proxy: true }; + var fake = new Proxy(target, { has: function () { return false; } }); + + // needed to work around a weird difference in node v6.0 - v6.4 where non-present properties are not logged + var isNode60 = semver.satisfies(process.version, '6.0 - 6.4'); + + forEach([ + 'Boolean', + 'Number', + 'String', + 'Symbol', + 'Date' + ], function (tag) { + target[Symbol.toStringTag] = tag; + + t.equal( + inspect(fake), + '{ ' + (isNode60 ? '' : 'proxy: true, ') + '[Symbol(Symbol.toStringTag)]: \'' + tag + '\' }', + 'Proxy for + ' + tag + ' shows as the target, which has no slots' + ); + }); + + t.end(); +}); + +test('fakers', { skip: !hasToStringTag }, function (t) { + var target = { proxy: false }; + + forEach([ + 'Boolean', + 'Number', + 'String', + 'Symbol', + 'Date' + ], function (tag) { + target[Symbol.toStringTag] = tag; + + t.equal( + inspect(target), + '{ proxy: false, [Symbol(Symbol.toStringTag)]: \'' + tag + '\' }', + 'Object pretending to be ' + tag + ' does not trick us' + ); + }); + + t.end(); +}); diff --git a/node_modules/object-inspect/util.inspect.js b/node_modules/object-inspect/util.inspect.js new file mode 100644 index 0000000..7784fab --- /dev/null +++ b/node_modules/object-inspect/util.inspect.js @@ -0,0 +1 @@ +module.exports = require('util').inspect; diff --git a/node_modules/on-finished/HISTORY.md b/node_modules/on-finished/HISTORY.md new file mode 100644 index 0000000..1917595 --- /dev/null +++ b/node_modules/on-finished/HISTORY.md @@ -0,0 +1,98 @@ +2.4.1 / 2022-02-22 +================== + + * Fix error on early async hooks implementations + +2.4.0 / 2022-02-21 +================== + + * Prevent loss of async hooks context + +2.3.0 / 2015-05-26 +================== + + * Add defined behavior for HTTP `CONNECT` requests + * Add defined behavior for HTTP `Upgrade` requests + * deps: ee-first@1.1.1 + +2.2.1 / 2015-04-22 +================== + + * Fix `isFinished(req)` when data buffered + +2.2.0 / 2014-12-22 +================== + + * Add message object to callback arguments + +2.1.1 / 2014-10-22 +================== + + * Fix handling of pipelined requests + +2.1.0 / 2014-08-16 +================== + + * Check if `socket` is detached + * Return `undefined` for `isFinished` if state unknown + +2.0.0 / 2014-08-16 +================== + + * Add `isFinished` function + * Move to `jshttp` organization + * Remove support for plain socket argument + * Rename to `on-finished` + * Support both `req` and `res` as arguments + * deps: ee-first@1.0.5 + +1.2.2 / 2014-06-10 +================== + + * Reduce listeners added to emitters + - avoids "event emitter leak" warnings when used multiple times on same request + +1.2.1 / 2014-06-08 +================== + + * Fix returned value when already finished + +1.2.0 / 2014-06-05 +================== + + * Call callback when called on already-finished socket + +1.1.4 / 2014-05-27 +================== + + * Support node.js 0.8 + +1.1.3 / 2014-04-30 +================== + + * Make sure errors passed as instanceof `Error` + +1.1.2 / 2014-04-18 +================== + + * Default the `socket` to passed-in object + +1.1.1 / 2014-01-16 +================== + + * Rename module to `finished` + +1.1.0 / 2013-12-25 +================== + + * Call callback when called on already-errored socket + +1.0.1 / 2013-12-20 +================== + + * Actually pass the error to the callback + +1.0.0 / 2013-12-20 +================== + + * Initial release diff --git a/node_modules/on-finished/LICENSE b/node_modules/on-finished/LICENSE new file mode 100644 index 0000000..5931fd2 --- /dev/null +++ b/node_modules/on-finished/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 Jonathan Ong +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/on-finished/README.md b/node_modules/on-finished/README.md new file mode 100644 index 0000000..8973cde --- /dev/null +++ b/node_modules/on-finished/README.md @@ -0,0 +1,162 @@ +# on-finished + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +Execute a callback when a HTTP request closes, finishes, or errors. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install on-finished +``` + +## API + +```js +var onFinished = require('on-finished') +``` + +### onFinished(res, listener) + +Attach a listener to listen for the response to finish. The listener will +be invoked only once when the response finished. If the response finished +to an error, the first argument will contain the error. If the response +has already finished, the listener will be invoked. + +Listening to the end of a response would be used to close things associated +with the response, like open files. + +Listener is invoked as `listener(err, res)`. + + + +```js +onFinished(res, function (err, res) { + // clean up open fds, etc. + // err contains the error if request error'd +}) +``` + +### onFinished(req, listener) + +Attach a listener to listen for the request to finish. The listener will +be invoked only once when the request finished. If the request finished +to an error, the first argument will contain the error. If the request +has already finished, the listener will be invoked. + +Listening to the end of a request would be used to know when to continue +after reading the data. + +Listener is invoked as `listener(err, req)`. + + + +```js +var data = '' + +req.setEncoding('utf8') +req.on('data', function (str) { + data += str +}) + +onFinished(req, function (err, req) { + // data is read unless there is err +}) +``` + +### onFinished.isFinished(res) + +Determine if `res` is already finished. This would be useful to check and +not even start certain operations if the response has already finished. + +### onFinished.isFinished(req) + +Determine if `req` is already finished. This would be useful to check and +not even start certain operations if the request has already finished. + +## Special Node.js requests + +### HTTP CONNECT method + +The meaning of the `CONNECT` method from RFC 7231, section 4.3.6: + +> The CONNECT method requests that the recipient establish a tunnel to +> the destination origin server identified by the request-target and, +> if successful, thereafter restrict its behavior to blind forwarding +> of packets, in both directions, until the tunnel is closed. Tunnels +> are commonly used to create an end-to-end virtual connection, through +> one or more proxies, which can then be secured using TLS (Transport +> Layer Security, [RFC5246]). + +In Node.js, these request objects come from the `'connect'` event on +the HTTP server. + +When this module is used on a HTTP `CONNECT` request, the request is +considered "finished" immediately, **due to limitations in the Node.js +interface**. This means if the `CONNECT` request contains a request entity, +the request will be considered "finished" even before it has been read. + +There is no such thing as a response object to a `CONNECT` request in +Node.js, so there is no support for one. + +### HTTP Upgrade request + +The meaning of the `Upgrade` header from RFC 7230, section 6.1: + +> The "Upgrade" header field is intended to provide a simple mechanism +> for transitioning from HTTP/1.1 to some other protocol on the same +> connection. + +In Node.js, these request objects come from the `'upgrade'` event on +the HTTP server. + +When this module is used on a HTTP request with an `Upgrade` header, the +request is considered "finished" immediately, **due to limitations in the +Node.js interface**. This means if the `Upgrade` request contains a request +entity, the request will be considered "finished" even before it has been +read. + +There is no such thing as a response object to a `Upgrade` request in +Node.js, so there is no support for one. + +## Example + +The following code ensures that file descriptors are always closed +once the response finishes. + +```js +var destroy = require('destroy') +var fs = require('fs') +var http = require('http') +var onFinished = require('on-finished') + +http.createServer(function onRequest (req, res) { + var stream = fs.createReadStream('package.json') + stream.pipe(res) + onFinished(res, function () { + destroy(stream) + }) +}) +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/on-finished/master?label=ci +[ci-url]: https://github.com/jshttp/on-finished/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/on-finished/master +[coveralls-url]: https://coveralls.io/r/jshttp/on-finished?branch=master +[node-image]: https://badgen.net/npm/node/on-finished +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/on-finished +[npm-url]: https://npmjs.org/package/on-finished +[npm-version-image]: https://badgen.net/npm/v/on-finished diff --git a/node_modules/on-finished/index.js b/node_modules/on-finished/index.js new file mode 100644 index 0000000..e68df7b --- /dev/null +++ b/node_modules/on-finished/index.js @@ -0,0 +1,234 @@ +/*! + * on-finished + * Copyright(c) 2013 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = onFinished +module.exports.isFinished = isFinished + +/** + * Module dependencies. + * @private + */ + +var asyncHooks = tryRequireAsyncHooks() +var first = require('ee-first') + +/** + * Variables. + * @private + */ + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) } + +/** + * Invoke callback when the response has finished, useful for + * cleaning up resources afterwards. + * + * @param {object} msg + * @param {function} listener + * @return {object} + * @public + */ + +function onFinished (msg, listener) { + if (isFinished(msg) !== false) { + defer(listener, null, msg) + return msg + } + + // attach the listener to the message + attachListener(msg, wrap(listener)) + + return msg +} + +/** + * Determine if message is already finished. + * + * @param {object} msg + * @return {boolean} + * @public + */ + +function isFinished (msg) { + var socket = msg.socket + + if (typeof msg.finished === 'boolean') { + // OutgoingMessage + return Boolean(msg.finished || (socket && !socket.writable)) + } + + if (typeof msg.complete === 'boolean') { + // IncomingMessage + return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable)) + } + + // don't know + return undefined +} + +/** + * Attach a finished listener to the message. + * + * @param {object} msg + * @param {function} callback + * @private + */ + +function attachFinishedListener (msg, callback) { + var eeMsg + var eeSocket + var finished = false + + function onFinish (error) { + eeMsg.cancel() + eeSocket.cancel() + + finished = true + callback(error) + } + + // finished on first message event + eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish) + + function onSocket (socket) { + // remove listener + msg.removeListener('socket', onSocket) + + if (finished) return + if (eeMsg !== eeSocket) return + + // finished on first socket event + eeSocket = first([[socket, 'error', 'close']], onFinish) + } + + if (msg.socket) { + // socket already assigned + onSocket(msg.socket) + return + } + + // wait for socket to be assigned + msg.on('socket', onSocket) + + if (msg.socket === undefined) { + // istanbul ignore next: node.js 0.8 patch + patchAssignSocket(msg, onSocket) + } +} + +/** + * Attach the listener to the message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function attachListener (msg, listener) { + var attached = msg.__onFinished + + // create a private single listener with queue + if (!attached || !attached.queue) { + attached = msg.__onFinished = createListener(msg) + attachFinishedListener(msg, attached) + } + + attached.queue.push(listener) +} + +/** + * Create listener on message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function createListener (msg) { + function listener (err) { + if (msg.__onFinished === listener) msg.__onFinished = null + if (!listener.queue) return + + var queue = listener.queue + listener.queue = null + + for (var i = 0; i < queue.length; i++) { + queue[i](err, msg) + } + } + + listener.queue = [] + + return listener +} + +/** + * Patch ServerResponse.prototype.assignSocket for node.js 0.8. + * + * @param {ServerResponse} res + * @param {function} callback + * @private + */ + +// istanbul ignore next: node.js 0.8 patch +function patchAssignSocket (res, callback) { + var assignSocket = res.assignSocket + + if (typeof assignSocket !== 'function') return + + // res.on('socket', callback) is broken in 0.8 + res.assignSocket = function _assignSocket (socket) { + assignSocket.call(this, socket) + callback(socket) + } +} + +/** + * Try to require async_hooks + * @private + */ + +function tryRequireAsyncHooks () { + try { + return require('async_hooks') + } catch (e) { + return {} + } +} + +/** + * Wrap function with async resource, if possible. + * AsyncResource.bind static method backported. + * @private + */ + +function wrap (fn) { + var res + + // create anonymous resource + if (asyncHooks.AsyncResource) { + res = new asyncHooks.AsyncResource(fn.name || 'bound-anonymous-fn') + } + + // incompatible node.js + if (!res || !res.runInAsyncScope) { + return fn + } + + // return bound function + return res.runInAsyncScope.bind(res, fn, null) +} diff --git a/node_modules/on-finished/package.json b/node_modules/on-finished/package.json new file mode 100644 index 0000000..644cd81 --- /dev/null +++ b/node_modules/on-finished/package.json @@ -0,0 +1,39 @@ +{ + "name": "on-finished", + "description": "Execute a callback when a request closes, finishes, or errors", + "version": "2.4.1", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "jshttp/on-finished", + "dependencies": { + "ee-first": "1.1.1" + }, + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.1", + "nyc": "15.1.0" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/once/LICENSE b/node_modules/once/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/once/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/once/README.md b/node_modules/once/README.md new file mode 100644 index 0000000..1f1ffca --- /dev/null +++ b/node_modules/once/README.md @@ -0,0 +1,79 @@ +# once + +Only call a function once. + +## usage + +```javascript +var once = require('once') + +function load (file, cb) { + cb = once(cb) + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Or add to the Function.prototype in a responsible way: + +```javascript +// only has to be done once +require('once').proto() + +function load (file, cb) { + cb = cb.once() + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Ironically, the prototype feature makes this module twice as +complicated as necessary. + +To check whether you function has been called, use `fn.called`. Once the +function is called for the first time the return value of the original +function is saved in `fn.value` and subsequent calls will continue to +return this value. + +```javascript +var once = require('once') + +function load (cb) { + cb = once(cb) + var stream = createStream() + stream.once('data', cb) + stream.once('end', function () { + if (!cb.called) cb(new Error('not found')) + }) +} +``` + +## `once.strict(func)` + +Throw an error if the function is called twice. + +Some functions are expected to be called only once. Using `once` for them would +potentially hide logical errors. + +In the example below, the `greet` function has to call the callback only once: + +```javascript +function greet (name, cb) { + // return is missing from the if statement + // when no name is passed, the callback is called twice + if (!name) cb('Hello anonymous') + cb('Hello ' + name) +} + +function log (msg) { + console.log(msg) +} + +// this will print 'Hello anonymous' but the logical error will be missed +greet(null, once(msg)) + +// once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time +greet(null, once.strict(msg)) +``` diff --git a/node_modules/once/once.js b/node_modules/once/once.js new file mode 100644 index 0000000..2354067 --- /dev/null +++ b/node_modules/once/once.js @@ -0,0 +1,42 @@ +var wrappy = require('wrappy') +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) + +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) + +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} + +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} diff --git a/node_modules/once/package.json b/node_modules/once/package.json new file mode 100644 index 0000000..16815b2 --- /dev/null +++ b/node_modules/once/package.json @@ -0,0 +1,33 @@ +{ + "name": "once", + "version": "1.4.0", + "description": "Run a function exactly one time", + "main": "once.js", + "directories": { + "test": "test" + }, + "dependencies": { + "wrappy": "1" + }, + "devDependencies": { + "tap": "^7.0.1" + }, + "scripts": { + "test": "tap test/*.js" + }, + "files": [ + "once.js" + ], + "repository": { + "type": "git", + "url": "git://github.com/isaacs/once" + }, + "keywords": [ + "once", + "function", + "one", + "single" + ], + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC" +} diff --git a/node_modules/parseurl/HISTORY.md b/node_modules/parseurl/HISTORY.md new file mode 100644 index 0000000..8e40954 --- /dev/null +++ b/node_modules/parseurl/HISTORY.md @@ -0,0 +1,58 @@ +1.3.3 / 2019-04-15 +================== + + * Fix Node.js 0.8 return value inconsistencies + +1.3.2 / 2017-09-09 +================== + + * perf: reduce overhead for full URLs + * perf: unroll the "fast-path" `RegExp` + +1.3.1 / 2016-01-17 +================== + + * perf: enable strict mode + +1.3.0 / 2014-08-09 +================== + + * Add `parseurl.original` for parsing `req.originalUrl` with fallback + * Return `undefined` if `req.url` is `undefined` + +1.2.0 / 2014-07-21 +================== + + * Cache URLs based on original value + * Remove no-longer-needed URL mis-parse work-around + * Simplify the "fast-path" `RegExp` + +1.1.3 / 2014-07-08 +================== + + * Fix typo + +1.1.2 / 2014-07-08 +================== + + * Seriously fix Node.js 0.8 compatibility + +1.1.1 / 2014-07-08 +================== + + * Fix Node.js 0.8 compatibility + +1.1.0 / 2014-07-08 +================== + + * Incorporate URL href-only parse fast-path + +1.0.1 / 2014-03-08 +================== + + * Add missing `require` + +1.0.0 / 2014-03-08 +================== + + * Genesis from `connect` diff --git a/node_modules/parseurl/LICENSE b/node_modules/parseurl/LICENSE new file mode 100644 index 0000000..27653d3 --- /dev/null +++ b/node_modules/parseurl/LICENSE @@ -0,0 +1,24 @@ + +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014-2017 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/parseurl/README.md b/node_modules/parseurl/README.md new file mode 100644 index 0000000..443e716 --- /dev/null +++ b/node_modules/parseurl/README.md @@ -0,0 +1,133 @@ +# parseurl + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Parse a URL with memoization. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install parseurl +``` + +## API + +```js +var parseurl = require('parseurl') +``` + +### parseurl(req) + +Parse the URL of the given request object (looks at the `req.url` property) +and return the result. The result is the same as `url.parse` in Node.js core. +Calling this function multiple times on the same `req` where `req.url` does +not change will return a cached parsed object, rather than parsing again. + +### parseurl.original(req) + +Parse the original URL of the given request object and return the result. +This works by trying to parse `req.originalUrl` if it is a string, otherwise +parses `req.url`. The result is the same as `url.parse` in Node.js core. +Calling this function multiple times on the same `req` where `req.originalUrl` +does not change will return a cached parsed object, rather than parsing again. + +## Benchmark + +```bash +$ npm run-script bench + +> parseurl@1.3.3 bench nodejs-parseurl +> node benchmark/index.js + + http_parser@2.8.0 + node@10.6.0 + v8@6.7.288.46-node.13 + uv@1.21.0 + zlib@1.2.11 + ares@1.14.0 + modules@64 + nghttp2@1.32.0 + napi@3 + openssl@1.1.0h + icu@61.1 + unicode@10.0 + cldr@33.0 + tz@2018c + +> node benchmark/fullurl.js + + Parsing URL "http://localhost:8888/foo/bar?user=tj&pet=fluffy" + + 4 tests completed. + + fasturl x 2,207,842 ops/sec ±3.76% (184 runs sampled) + nativeurl - legacy x 507,180 ops/sec ±0.82% (191 runs sampled) + nativeurl - whatwg x 290,044 ops/sec ±1.96% (189 runs sampled) + parseurl x 488,907 ops/sec ±2.13% (192 runs sampled) + +> node benchmark/pathquery.js + + Parsing URL "/foo/bar?user=tj&pet=fluffy" + + 4 tests completed. + + fasturl x 3,812,564 ops/sec ±3.15% (188 runs sampled) + nativeurl - legacy x 2,651,631 ops/sec ±1.68% (189 runs sampled) + nativeurl - whatwg x 161,837 ops/sec ±2.26% (189 runs sampled) + parseurl x 4,166,338 ops/sec ±2.23% (184 runs sampled) + +> node benchmark/samerequest.js + + Parsing URL "/foo/bar?user=tj&pet=fluffy" on same request object + + 4 tests completed. + + fasturl x 3,821,651 ops/sec ±2.42% (185 runs sampled) + nativeurl - legacy x 2,651,162 ops/sec ±1.90% (187 runs sampled) + nativeurl - whatwg x 175,166 ops/sec ±1.44% (188 runs sampled) + parseurl x 14,912,606 ops/sec ±3.59% (183 runs sampled) + +> node benchmark/simplepath.js + + Parsing URL "/foo/bar" + + 4 tests completed. + + fasturl x 12,421,765 ops/sec ±2.04% (191 runs sampled) + nativeurl - legacy x 7,546,036 ops/sec ±1.41% (188 runs sampled) + nativeurl - whatwg x 198,843 ops/sec ±1.83% (189 runs sampled) + parseurl x 24,244,006 ops/sec ±0.51% (194 runs sampled) + +> node benchmark/slash.js + + Parsing URL "/" + + 4 tests completed. + + fasturl x 17,159,456 ops/sec ±3.25% (188 runs sampled) + nativeurl - legacy x 11,635,097 ops/sec ±3.79% (184 runs sampled) + nativeurl - whatwg x 240,693 ops/sec ±0.83% (189 runs sampled) + parseurl x 42,279,067 ops/sec ±0.55% (190 runs sampled) +``` + +## License + + [MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/pillarjs/parseurl/master +[coveralls-url]: https://coveralls.io/r/pillarjs/parseurl?branch=master +[node-image]: https://badgen.net/npm/node/parseurl +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/parseurl +[npm-url]: https://npmjs.org/package/parseurl +[npm-version-image]: https://badgen.net/npm/v/parseurl +[travis-image]: https://badgen.net/travis/pillarjs/parseurl/master +[travis-url]: https://travis-ci.org/pillarjs/parseurl diff --git a/node_modules/parseurl/index.js b/node_modules/parseurl/index.js new file mode 100644 index 0000000..ece7223 --- /dev/null +++ b/node_modules/parseurl/index.js @@ -0,0 +1,158 @@ +/*! + * parseurl + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var url = require('url') +var parse = url.parse +var Url = url.Url + +/** + * Module exports. + * @public + */ + +module.exports = parseurl +module.exports.original = originalurl + +/** + * Parse the `req` url with memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @public + */ + +function parseurl (req) { + var url = req.url + + if (url === undefined) { + // URL is undefined + return undefined + } + + var parsed = req._parsedUrl + + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed + } + + // Parse the URL + parsed = fastparse(url) + parsed._raw = url + + return (req._parsedUrl = parsed) +}; + +/** + * Parse the `req` original url with fallback and memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @public + */ + +function originalurl (req) { + var url = req.originalUrl + + if (typeof url !== 'string') { + // Fallback + return parseurl(req) + } + + var parsed = req._parsedOriginalUrl + + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed + } + + // Parse the URL + parsed = fastparse(url) + parsed._raw = url + + return (req._parsedOriginalUrl = parsed) +}; + +/** + * Parse the `str` url with fast-path short-cut. + * + * @param {string} str + * @return {Object} + * @private + */ + +function fastparse (str) { + if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) { + return parse(str) + } + + var pathname = str + var query = null + var search = null + + // This takes the regexp from https://github.com/joyent/node/pull/7878 + // Which is /^(\/[^?#\s]*)(\?[^#\s]*)?$/ + // And unrolls it into a for loop + for (var i = 1; i < str.length; i++) { + switch (str.charCodeAt(i)) { + case 0x3f: /* ? */ + if (search === null) { + pathname = str.substring(0, i) + query = str.substring(i + 1) + search = str.substring(i) + } + break + case 0x09: /* \t */ + case 0x0a: /* \n */ + case 0x0c: /* \f */ + case 0x0d: /* \r */ + case 0x20: /* */ + case 0x23: /* # */ + case 0xa0: + case 0xfeff: + return parse(str) + } + } + + var url = Url !== undefined + ? new Url() + : {} + + url.path = str + url.href = str + url.pathname = pathname + + if (search !== null) { + url.query = query + url.search = search + } + + return url +} + +/** + * Determine if parsed is still fresh for url. + * + * @param {string} url + * @param {object} parsedUrl + * @return {boolean} + * @private + */ + +function fresh (url, parsedUrl) { + return typeof parsedUrl === 'object' && + parsedUrl !== null && + (Url === undefined || parsedUrl instanceof Url) && + parsedUrl._raw === url +} diff --git a/node_modules/parseurl/package.json b/node_modules/parseurl/package.json new file mode 100644 index 0000000..6b443ca --- /dev/null +++ b/node_modules/parseurl/package.json @@ -0,0 +1,40 @@ +{ + "name": "parseurl", + "description": "parse a url with memoization", + "version": "1.3.3", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "repository": "pillarjs/parseurl", + "license": "MIT", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "5.16.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.17.1", + "eslint-plugin-node": "7.0.1", + "eslint-plugin-promise": "4.1.1", + "eslint-plugin-standard": "4.0.0", + "fast-url-parser": "1.1.3", + "istanbul": "0.4.5", + "mocha": "6.1.3" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint .", + "test": "mocha --check-leaks --bail --reporter spec test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --check-leaks --reporter dot test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --check-leaks --reporter spec test/" + } +} diff --git a/node_modules/path-to-regexp/LICENSE b/node_modules/path-to-regexp/LICENSE new file mode 100644 index 0000000..983fbe8 --- /dev/null +++ b/node_modules/path-to-regexp/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Blake Embrey (hello@blakeembrey.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/path-to-regexp/Readme.md b/node_modules/path-to-regexp/Readme.md new file mode 100644 index 0000000..a0f9698 --- /dev/null +++ b/node_modules/path-to-regexp/Readme.md @@ -0,0 +1,216 @@ +# Path-to-RegExp + +> Turn a path string such as `/user/:name` into a regular expression. + +[![NPM version][npm-image]][npm-url] +[![NPM downloads][downloads-image]][downloads-url] +[![Build status][build-image]][build-url] +[![Build coverage][coverage-image]][coverage-url] +[![License][license-image]][license-url] + +## Installation + +``` +npm install path-to-regexp --save +``` + +## Usage + +```js +const { + match, + pathToRegexp, + compile, + parse, + stringify, +} = require("path-to-regexp"); +``` + +### Parameters + +Parameters match arbitrary strings in a path by matching up to the end of the segment, or up to any proceeding tokens. They are defined by prefixing a colon to the parameter name (`:foo`). Parameter names can use any valid JavaScript identifier, or be double quoted to use other characters (`:"param-name"`). + +```js +const fn = match("/:foo/:bar"); + +fn("/test/route"); +//=> { path: '/test/route', params: { foo: 'test', bar: 'route' } } +``` + +### Wildcard + +Wildcard parameters match one or more characters across multiple segments. They are defined the same way as regular parameters, but are prefixed with an asterisk (`*foo`). + +```js +const fn = match("/*splat"); + +fn("/bar/baz"); +//=> { path: '/bar/baz', params: { splat: [ 'bar', 'baz' ] } } +``` + +### Optional + +Braces can be used to define parts of the path that are optional. + +```js +const fn = match("/users{/:id}/delete"); + +fn("/users/delete"); +//=> { path: '/users/delete', params: {} } + +fn("/users/123/delete"); +//=> { path: '/users/123/delete', params: { id: '123' } } +``` + +## Match + +The `match` function returns a function for matching strings against a path: + +- **path** String or array of strings. +- **options** _(optional)_ (Extends [pathToRegexp](#pathToRegexp) options) + - **decode** Function for decoding strings to params, or `false` to disable all processing. (default: `decodeURIComponent`) + +```js +const fn = match("/foo/:bar"); +``` + +**Please note:** `path-to-regexp` is intended for ordered data (e.g. paths, hosts). It can not handle arbitrarily ordered data (e.g. query strings, URL fragments, JSON, etc). + +## PathToRegexp + +The `pathToRegexp` function returns a regular expression for matching strings against paths. It + +- **path** String or array of strings. +- **options** _(optional)_ (See [parse](#parse) for more options) + - **sensitive** Regexp will be case sensitive. (default: `false`) + - **end** Validate the match reaches the end of the string. (default: `true`) + - **delimiter** The default delimiter for segments, e.g. `[^/]` for `:named` parameters. (default: `'/'`) + - **trailing** Allows optional trailing delimiter to match. (default: `true`) + +```js +const { regexp, keys } = pathToRegexp("/foo/:bar"); +``` + +## Compile ("Reverse" Path-To-RegExp) + +The `compile` function will return a function for transforming parameters into a valid path: + +- **path** A string. +- **options** (See [parse](#parse) for more options) + - **delimiter** The default delimiter for segments, e.g. `[^/]` for `:named` parameters. (default: `'/'`) + - **encode** Function for encoding input strings for output into the path, or `false` to disable entirely. (default: `encodeURIComponent`) + +```js +const toPath = compile("/user/:id"); + +toPath({ id: "name" }); //=> "/user/name" +toPath({ id: "café" }); //=> "/user/caf%C3%A9" + +const toPathRepeated = compile("/*segment"); + +toPathRepeated({ segment: ["foo"] }); //=> "/foo" +toPathRepeated({ segment: ["a", "b", "c"] }); //=> "/a/b/c" + +// When disabling `encode`, you need to make sure inputs are encoded correctly. No arrays are accepted. +const toPathRaw = compile("/user/:id", { encode: false }); + +toPathRaw({ id: "%3A%2F" }); //=> "/user/%3A%2F" +``` + +## Stringify + +Transform `TokenData` (a sequence of tokens) back into a Path-to-RegExp string. + +- **data** A `TokenData` instance + +```js +const data = new TokenData([ + { type: "text", value: "/" }, + { type: "param", name: "foo" }, +]); + +const path = stringify(data); //=> "/:foo" +``` + +## Developers + +- If you are rewriting paths with match and compile, consider using `encode: false` and `decode: false` to keep raw paths passed around. +- To ensure matches work on paths containing characters usually encoded, such as emoji, consider using [encodeurl](https://github.com/pillarjs/encodeurl) for `encodePath`. + +### Parse + +The `parse` function accepts a string and returns `TokenData`, the set of tokens and other metadata parsed from the input string. `TokenData` is can used with `match` and `compile`. + +- **path** A string. +- **options** _(optional)_ + - **encodePath** A function for encoding input strings. (default: `x => x`, recommended: [`encodeurl`](https://github.com/pillarjs/encodeurl)) + +### Tokens + +`TokenData` is a sequence of tokens, currently of types `text`, `parameter`, `wildcard`, or `group`. + +### Custom path + +In some applications, you may not be able to use the `path-to-regexp` syntax, but still want to use this library for `match` and `compile`. For example: + +```js +import { TokenData, match } from "path-to-regexp"; + +const tokens = [ + { type: "text", value: "/" }, + { type: "parameter", name: "foo" }, +]; +const path = new TokenData(tokens); +const fn = match(path); + +fn("/test"); //=> { path: '/test', index: 0, params: { foo: 'test' } } +``` + +## Errors + +An effort has been made to ensure ambiguous paths from previous releases throw an error. This means you might be seeing an error when things worked before. + +### Unexpected `?` or `+` + +In past releases, `?`, `*`, and `+` were used to denote optional or repeating parameters. As an alternative, try these: + +- For optional (`?`), use an empty segment in a group such as `/:file{.:ext}`. +- For repeating (`+`), only wildcard matching is supported, such as `/*path`. +- For optional repeating (`*`), use a group and a wildcard parameter such as `/files{/*path}`. + +### Unexpected `(`, `)`, `[`, `]`, etc. + +Previous versions of Path-to-RegExp used these for RegExp features. This version no longer supports them so they've been reserved to avoid ambiguity. To use these characters literally, escape them with a backslash, e.g. `"\\("`. + +### Missing parameter name + +Parameter names must be provided after `:` or `*`, and they must be a valid JavaScript identifier. If you want an parameter name that isn't a JavaScript identifier, such as starting with a number, you can wrap the name in quotes like `:"my-name"`. + +### Unterminated quote + +Parameter names can be wrapped in double quote characters, and this error means you forgot to close the quote character. + +### Express <= 4.x + +Path-To-RegExp breaks compatibility with Express <= `4.x` in the following ways: + +- The wildcard `*` must have a name, matching the behavior of parameters `:`. +- The optional character `?` is no longer supported, use braces instead: `/:file{.:ext}`. +- Regexp characters are not supported. +- Some characters have been reserved to avoid confusion during upgrade (`()[]?+!`). +- Parameter names now support valid JavaScript identifiers, or quoted like `:"this"`. + +## License + +MIT + +[npm-image]: https://img.shields.io/npm/v/path-to-regexp +[npm-url]: https://npmjs.org/package/path-to-regexp +[downloads-image]: https://img.shields.io/npm/dm/path-to-regexp +[downloads-url]: https://npmjs.org/package/path-to-regexp +[build-image]: https://img.shields.io/github/actions/workflow/status/pillarjs/path-to-regexp/ci.yml?branch=master +[build-url]: https://github.com/pillarjs/path-to-regexp/actions/workflows/ci.yml?query=branch%3Amaster +[coverage-image]: https://img.shields.io/codecov/c/gh/pillarjs/path-to-regexp +[coverage-url]: https://codecov.io/gh/pillarjs/path-to-regexp +[license-image]: http://img.shields.io/npm/l/path-to-regexp.svg?style=flat +[license-url]: LICENSE.md diff --git a/node_modules/path-to-regexp/dist/index.d.ts b/node_modules/path-to-regexp/dist/index.d.ts new file mode 100644 index 0000000..b0f3e93 --- /dev/null +++ b/node_modules/path-to-regexp/dist/index.d.ts @@ -0,0 +1,136 @@ +/** + * Encode a string into another string. + */ +export type Encode = (value: string) => string; +/** + * Decode a string into another string. + */ +export type Decode = (value: string) => string; +export interface ParseOptions { + /** + * A function for encoding input strings. + */ + encodePath?: Encode; +} +export interface PathToRegexpOptions { + /** + * Matches the path completely without trailing characters. (default: `true`) + */ + end?: boolean; + /** + * Allows optional trailing delimiter to match. (default: `true`) + */ + trailing?: boolean; + /** + * Match will be case sensitive. (default: `false`) + */ + sensitive?: boolean; + /** + * The default delimiter for segments. (default: `'/'`) + */ + delimiter?: string; +} +export interface MatchOptions extends PathToRegexpOptions { + /** + * Function for decoding strings for params, or `false` to disable entirely. (default: `decodeURIComponent`) + */ + decode?: Decode | false; +} +export interface CompileOptions { + /** + * Function for encoding input strings for output into the path, or `false` to disable entirely. (default: `encodeURIComponent`) + */ + encode?: Encode | false; + /** + * The default delimiter for segments. (default: `'/'`) + */ + delimiter?: string; +} +/** + * Plain text. + */ +export interface Text { + type: "text"; + value: string; +} +/** + * A parameter designed to match arbitrary text within a segment. + */ +export interface Parameter { + type: "param"; + name: string; +} +/** + * A wildcard parameter designed to match multiple segments. + */ +export interface Wildcard { + type: "wildcard"; + name: string; +} +/** + * A set of possible tokens to expand when matching. + */ +export interface Group { + type: "group"; + tokens: Token[]; +} +/** + * A token that corresponds with a regexp capture. + */ +export type Key = Parameter | Wildcard; +/** + * A sequence of `path-to-regexp` keys that match capturing groups. + */ +export type Keys = Array; +/** + * A sequence of path match characters. + */ +export type Token = Text | Parameter | Wildcard | Group; +/** + * Tokenized path instance. + */ +export declare class TokenData { + readonly tokens: Token[]; + constructor(tokens: Token[]); +} +/** + * Parse a string for the raw tokens. + */ +export declare function parse(str: string, options?: ParseOptions): TokenData; +/** + * Compile a string to a template function for the path. + */ +export declare function compile

(path: Path, options?: CompileOptions & ParseOptions): (data?: P) => string; +export type ParamData = Partial>; +export type PathFunction

= (data?: P) => string; +/** + * A match result contains data about the path match. + */ +export interface MatchResult

{ + path: string; + params: P; +} +/** + * A match is either `false` (no match) or a match result. + */ +export type Match

= false | MatchResult

; +/** + * The match function takes a string and returns whether it matched the path. + */ +export type MatchFunction

= (path: string) => Match

; +/** + * Supported path types. + */ +export type Path = string | TokenData; +/** + * Transform a path into a match function. + */ +export declare function match

(path: Path | Path[], options?: MatchOptions & ParseOptions): MatchFunction

; +export declare function pathToRegexp(path: Path | Path[], options?: PathToRegexpOptions & ParseOptions): { + regexp: RegExp; + keys: Keys; +}; +/** + * Stringify token data into a path string. + */ +export declare function stringify(data: TokenData): string; diff --git a/node_modules/path-to-regexp/dist/index.js b/node_modules/path-to-regexp/dist/index.js new file mode 100644 index 0000000..49694bd --- /dev/null +++ b/node_modules/path-to-regexp/dist/index.js @@ -0,0 +1,403 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TokenData = void 0; +exports.parse = parse; +exports.compile = compile; +exports.match = match; +exports.pathToRegexp = pathToRegexp; +exports.stringify = stringify; +const DEFAULT_DELIMITER = "/"; +const NOOP_VALUE = (value) => value; +const ID_START = /^[$_\p{ID_Start}]$/u; +const ID_CONTINUE = /^[$\u200c\u200d\p{ID_Continue}]$/u; +const DEBUG_URL = "https://git.new/pathToRegexpError"; +const SIMPLE_TOKENS = { + // Groups. + "{": "{", + "}": "}", + // Reserved. + "(": "(", + ")": ")", + "[": "[", + "]": "]", + "+": "+", + "?": "?", + "!": "!", +}; +/** + * Escape text for stringify to path. + */ +function escapeText(str) { + return str.replace(/[{}()\[\]+?!:*]/g, "\\$&"); +} +/** + * Escape a regular expression string. + */ +function escape(str) { + return str.replace(/[.+*?^${}()[\]|/\\]/g, "\\$&"); +} +/** + * Tokenize input string. + */ +function* lexer(str) { + const chars = [...str]; + let i = 0; + function name() { + let value = ""; + if (ID_START.test(chars[++i])) { + value += chars[i]; + while (ID_CONTINUE.test(chars[++i])) { + value += chars[i]; + } + } + else if (chars[i] === '"') { + let pos = i; + while (i < chars.length) { + if (chars[++i] === '"') { + i++; + pos = 0; + break; + } + if (chars[i] === "\\") { + value += chars[++i]; + } + else { + value += chars[i]; + } + } + if (pos) { + throw new TypeError(`Unterminated quote at ${pos}: ${DEBUG_URL}`); + } + } + if (!value) { + throw new TypeError(`Missing parameter name at ${i}: ${DEBUG_URL}`); + } + return value; + } + while (i < chars.length) { + const value = chars[i]; + const type = SIMPLE_TOKENS[value]; + if (type) { + yield { type, index: i++, value }; + } + else if (value === "\\") { + yield { type: "ESCAPED", index: i++, value: chars[i++] }; + } + else if (value === ":") { + const value = name(); + yield { type: "PARAM", index: i, value }; + } + else if (value === "*") { + const value = name(); + yield { type: "WILDCARD", index: i, value }; + } + else { + yield { type: "CHAR", index: i, value: chars[i++] }; + } + } + return { type: "END", index: i, value: "" }; +} +class Iter { + constructor(tokens) { + this.tokens = tokens; + } + peek() { + if (!this._peek) { + const next = this.tokens.next(); + this._peek = next.value; + } + return this._peek; + } + tryConsume(type) { + const token = this.peek(); + if (token.type !== type) + return; + this._peek = undefined; // Reset after consumed. + return token.value; + } + consume(type) { + const value = this.tryConsume(type); + if (value !== undefined) + return value; + const { type: nextType, index } = this.peek(); + throw new TypeError(`Unexpected ${nextType} at ${index}, expected ${type}: ${DEBUG_URL}`); + } + text() { + let result = ""; + let value; + while ((value = this.tryConsume("CHAR") || this.tryConsume("ESCAPED"))) { + result += value; + } + return result; + } +} +/** + * Tokenized path instance. + */ +class TokenData { + constructor(tokens) { + this.tokens = tokens; + } +} +exports.TokenData = TokenData; +/** + * Parse a string for the raw tokens. + */ +function parse(str, options = {}) { + const { encodePath = NOOP_VALUE } = options; + const it = new Iter(lexer(str)); + function consume(endType) { + const tokens = []; + while (true) { + const path = it.text(); + if (path) + tokens.push({ type: "text", value: encodePath(path) }); + const param = it.tryConsume("PARAM"); + if (param) { + tokens.push({ + type: "param", + name: param, + }); + continue; + } + const wildcard = it.tryConsume("WILDCARD"); + if (wildcard) { + tokens.push({ + type: "wildcard", + name: wildcard, + }); + continue; + } + const open = it.tryConsume("{"); + if (open) { + tokens.push({ + type: "group", + tokens: consume("}"), + }); + continue; + } + it.consume(endType); + return tokens; + } + } + const tokens = consume("END"); + return new TokenData(tokens); +} +/** + * Compile a string to a template function for the path. + */ +function compile(path, options = {}) { + const { encode = encodeURIComponent, delimiter = DEFAULT_DELIMITER } = options; + const data = path instanceof TokenData ? path : parse(path, options); + const fn = tokensToFunction(data.tokens, delimiter, encode); + return function path(data = {}) { + const [path, ...missing] = fn(data); + if (missing.length) { + throw new TypeError(`Missing parameters: ${missing.join(", ")}`); + } + return path; + }; +} +function tokensToFunction(tokens, delimiter, encode) { + const encoders = tokens.map((token) => tokenToFunction(token, delimiter, encode)); + return (data) => { + const result = [""]; + for (const encoder of encoders) { + const [value, ...extras] = encoder(data); + result[0] += value; + result.push(...extras); + } + return result; + }; +} +/** + * Convert a single token into a path building function. + */ +function tokenToFunction(token, delimiter, encode) { + if (token.type === "text") + return () => [token.value]; + if (token.type === "group") { + const fn = tokensToFunction(token.tokens, delimiter, encode); + return (data) => { + const [value, ...missing] = fn(data); + if (!missing.length) + return [value]; + return [""]; + }; + } + const encodeValue = encode || NOOP_VALUE; + if (token.type === "wildcard" && encode !== false) { + return (data) => { + const value = data[token.name]; + if (value == null) + return ["", token.name]; + if (!Array.isArray(value) || value.length === 0) { + throw new TypeError(`Expected "${token.name}" to be a non-empty array`); + } + return [ + value + .map((value, index) => { + if (typeof value !== "string") { + throw new TypeError(`Expected "${token.name}/${index}" to be a string`); + } + return encodeValue(value); + }) + .join(delimiter), + ]; + }; + } + return (data) => { + const value = data[token.name]; + if (value == null) + return ["", token.name]; + if (typeof value !== "string") { + throw new TypeError(`Expected "${token.name}" to be a string`); + } + return [encodeValue(value)]; + }; +} +/** + * Transform a path into a match function. + */ +function match(path, options = {}) { + const { decode = decodeURIComponent, delimiter = DEFAULT_DELIMITER } = options; + const { regexp, keys } = pathToRegexp(path, options); + const decoders = keys.map((key) => { + if (decode === false) + return NOOP_VALUE; + if (key.type === "param") + return decode; + return (value) => value.split(delimiter).map(decode); + }); + return function match(input) { + const m = regexp.exec(input); + if (!m) + return false; + const path = m[0]; + const params = Object.create(null); + for (let i = 1; i < m.length; i++) { + if (m[i] === undefined) + continue; + const key = keys[i - 1]; + const decoder = decoders[i - 1]; + params[key.name] = decoder(m[i]); + } + return { path, params }; + }; +} +function pathToRegexp(path, options = {}) { + const { delimiter = DEFAULT_DELIMITER, end = true, sensitive = false, trailing = true, } = options; + const keys = []; + const sources = []; + const flags = sensitive ? "" : "i"; + const paths = Array.isArray(path) ? path : [path]; + const items = paths.map((path) => path instanceof TokenData ? path : parse(path, options)); + for (const { tokens } of items) { + for (const seq of flatten(tokens, 0, [])) { + const regexp = sequenceToRegExp(seq, delimiter, keys); + sources.push(regexp); + } + } + let pattern = `^(?:${sources.join("|")})`; + if (trailing) + pattern += `(?:${escape(delimiter)}$)?`; + pattern += end ? "$" : `(?=${escape(delimiter)}|$)`; + const regexp = new RegExp(pattern, flags); + return { regexp, keys }; +} +/** + * Generate a flat list of sequence tokens from the given tokens. + */ +function* flatten(tokens, index, init) { + if (index === tokens.length) { + return yield init; + } + const token = tokens[index]; + if (token.type === "group") { + const fork = init.slice(); + for (const seq of flatten(token.tokens, 0, fork)) { + yield* flatten(tokens, index + 1, seq); + } + } + else { + init.push(token); + } + yield* flatten(tokens, index + 1, init); +} +/** + * Transform a flat sequence of tokens into a regular expression. + */ +function sequenceToRegExp(tokens, delimiter, keys) { + let result = ""; + let backtrack = ""; + let isSafeSegmentParam = true; + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + if (token.type === "text") { + result += escape(token.value); + backtrack += token.value; + isSafeSegmentParam || (isSafeSegmentParam = token.value.includes(delimiter)); + continue; + } + if (token.type === "param" || token.type === "wildcard") { + if (!isSafeSegmentParam && !backtrack) { + throw new TypeError(`Missing text after "${token.name}": ${DEBUG_URL}`); + } + if (token.type === "param") { + result += `(${negate(delimiter, isSafeSegmentParam ? "" : backtrack)}+)`; + } + else { + result += `([\\s\\S]+)`; + } + keys.push(token); + backtrack = ""; + isSafeSegmentParam = false; + continue; + } + } + return result; +} +function negate(delimiter, backtrack) { + if (backtrack.length < 2) { + if (delimiter.length < 2) + return `[^${escape(delimiter + backtrack)}]`; + return `(?:(?!${escape(delimiter)})[^${escape(backtrack)}])`; + } + if (delimiter.length < 2) { + return `(?:(?!${escape(backtrack)})[^${escape(delimiter)}])`; + } + return `(?:(?!${escape(backtrack)}|${escape(delimiter)})[\\s\\S])`; +} +/** + * Stringify token data into a path string. + */ +function stringify(data) { + return data.tokens + .map(function stringifyToken(token, index, tokens) { + if (token.type === "text") + return escapeText(token.value); + if (token.type === "group") { + return `{${token.tokens.map(stringifyToken).join("")}}`; + } + const isSafe = isNameSafe(token.name) && isNextNameSafe(tokens[index + 1]); + const key = isSafe ? token.name : JSON.stringify(token.name); + if (token.type === "param") + return `:${key}`; + if (token.type === "wildcard") + return `*${key}`; + throw new TypeError(`Unexpected token: ${token}`); + }) + .join(""); +} +function isNameSafe(name) { + const [first, ...rest] = name; + if (!ID_START.test(first)) + return false; + return rest.every((char) => ID_CONTINUE.test(char)); +} +function isNextNameSafe(token) { + if ((token === null || token === void 0 ? void 0 : token.type) !== "text") + return true; + return !ID_CONTINUE.test(token.value[0]); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/path-to-regexp/dist/index.js.map b/node_modules/path-to-regexp/dist/index.js.map new file mode 100644 index 0000000..d5054f9 --- /dev/null +++ b/node_modules/path-to-regexp/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"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I,CAAC,IAAI,cAAc,CAAC,MAAM,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC;QAC9D,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAE7D,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO;YAAE,OAAO,IAAI,GAAG,EAAE,CAAC;QAC7C,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU;YAAE,OAAO,IAAI,GAAG,EAAE,CAAC;QAChD,MAAM,IAAI,SAAS,CAAC,qBAAqB,KAAK,EAAE,CAAC,CAAC;IACpD,CAAC,CAAC;SACD,IAAI,CAAC,EAAE,CAAC,CAAC;AACd,CAAC;AAED,SAAS,UAAU,CAAC,IAAY;IAC9B,MAAM,CAAC,KAAK,EAAE,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC;IAC9B,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IACxC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AACtD,CAAC;AAED,SAAS,cAAc,CAAC,KAAwB;IAC9C,IAAI,CAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,IAAI,MAAK,MAAM;QAAE,OAAO,IAAI,CAAC;IACxC,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["const DEFAULT_DELIMITER = \"/\";\nconst NOOP_VALUE = (value: string) => value;\nconst ID_START = /^[$_\\p{ID_Start}]$/u;\nconst ID_CONTINUE = /^[$\\u200c\\u200d\\p{ID_Continue}]$/u;\nconst DEBUG_URL = \"https://git.new/pathToRegexpError\";\n\n/**\n * Encode a string into another string.\n */\nexport type Encode = (value: string) => string;\n\n/**\n * Decode a string into another string.\n */\nexport type Decode = (value: string) => string;\n\nexport interface ParseOptions {\n /**\n * A function for encoding input strings.\n */\n encodePath?: Encode;\n}\n\nexport interface PathToRegexpOptions {\n /**\n * Matches the path completely without trailing characters. (default: `true`)\n */\n end?: boolean;\n /**\n * Allows optional trailing delimiter to match. (default: `true`)\n */\n trailing?: boolean;\n /**\n * Match will be case sensitive. (default: `false`)\n */\n sensitive?: boolean;\n /**\n * The default delimiter for segments. (default: `'/'`)\n */\n delimiter?: string;\n}\n\nexport interface MatchOptions extends PathToRegexpOptions {\n /**\n * Function for decoding strings for params, or `false` to disable entirely. (default: `decodeURIComponent`)\n */\n decode?: Decode | false;\n}\n\nexport interface CompileOptions {\n /**\n * Function for encoding input strings for output into the path, or `false` to disable entirely. (default: `encodeURIComponent`)\n */\n encode?: Encode | false;\n /**\n * The default delimiter for segments. (default: `'/'`)\n */\n delimiter?: string;\n}\n\ntype TokenType =\n | \"{\"\n | \"}\"\n | \"WILDCARD\"\n | \"PARAM\"\n | \"CHAR\"\n | \"ESCAPED\"\n | \"END\"\n // Reserved for use or ambiguous due to past use.\n | \"(\"\n | \")\"\n | \"[\"\n | \"]\"\n | \"+\"\n | \"?\"\n | \"!\";\n\n/**\n * Tokenizer results.\n */\ninterface LexToken {\n type: TokenType;\n index: number;\n value: string;\n}\n\nconst SIMPLE_TOKENS: Record = {\n // Groups.\n \"{\": \"{\",\n \"}\": \"}\",\n // Reserved.\n \"(\": \"(\",\n \")\": \")\",\n \"[\": \"[\",\n \"]\": \"]\",\n \"+\": \"+\",\n \"?\": \"?\",\n \"!\": \"!\",\n};\n\n/**\n * Escape text for stringify to path.\n */\nfunction escapeText(str: string) {\n return str.replace(/[{}()\\[\\]+?!:*]/g, \"\\\\$&\");\n}\n\n/**\n * Escape a regular expression string.\n */\nfunction escape(str: string) {\n return str.replace(/[.+*?^${}()[\\]|/\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Tokenize input string.\n */\nfunction* lexer(str: string): Generator {\n const chars = [...str];\n let i = 0;\n\n function name() {\n let value = \"\";\n\n if (ID_START.test(chars[++i])) {\n value += chars[i];\n while (ID_CONTINUE.test(chars[++i])) {\n value += chars[i];\n }\n } else if (chars[i] === '\"') {\n let pos = i;\n\n while (i < chars.length) {\n if (chars[++i] === '\"') {\n i++;\n pos = 0;\n break;\n }\n\n if (chars[i] === \"\\\\\") {\n value += chars[++i];\n } else {\n value += chars[i];\n }\n }\n\n if (pos) {\n throw new TypeError(`Unterminated quote at ${pos}: ${DEBUG_URL}`);\n }\n }\n\n if (!value) {\n throw new TypeError(`Missing parameter name at ${i}: ${DEBUG_URL}`);\n }\n\n return value;\n }\n\n while (i < chars.length) {\n const value = chars[i];\n const type = SIMPLE_TOKENS[value];\n\n if (type) {\n yield { type, index: i++, value };\n } else if (value === \"\\\\\") {\n yield { type: \"ESCAPED\", index: i++, value: chars[i++] };\n } else if (value === \":\") {\n const value = name();\n yield { type: \"PARAM\", index: i, value };\n } else if (value === \"*\") {\n const value = name();\n yield { type: \"WILDCARD\", index: i, value };\n } else {\n yield { type: \"CHAR\", index: i, value: chars[i++] };\n }\n }\n\n return { type: \"END\", index: i, value: \"\" };\n}\n\nclass Iter {\n private _peek?: LexToken;\n\n constructor(private tokens: Generator) {}\n\n peek(): LexToken {\n if (!this._peek) {\n const next = this.tokens.next();\n this._peek = next.value;\n }\n return this._peek;\n }\n\n tryConsume(type: TokenType): string | undefined {\n const token = this.peek();\n if (token.type !== type) return;\n this._peek = undefined; // Reset after consumed.\n return token.value;\n }\n\n consume(type: TokenType): string {\n const value = this.tryConsume(type);\n if (value !== undefined) return value;\n const { type: nextType, index } = this.peek();\n throw new TypeError(\n `Unexpected ${nextType} at ${index}, expected ${type}: ${DEBUG_URL}`,\n );\n }\n\n text(): string {\n let result = \"\";\n let value: string | undefined;\n while ((value = this.tryConsume(\"CHAR\") || this.tryConsume(\"ESCAPED\"))) {\n result += value;\n }\n return result;\n }\n}\n\n/**\n * Plain text.\n */\nexport interface Text {\n type: \"text\";\n value: string;\n}\n\n/**\n * A parameter designed to match arbitrary text within a segment.\n */\nexport interface Parameter {\n type: \"param\";\n name: string;\n}\n\n/**\n * A wildcard parameter designed to match multiple segments.\n */\nexport interface Wildcard {\n type: \"wildcard\";\n name: string;\n}\n\n/**\n * A set of possible tokens to expand when matching.\n */\nexport interface Group {\n type: \"group\";\n tokens: Token[];\n}\n\n/**\n * A token that corresponds with a regexp capture.\n */\nexport type Key = Parameter | Wildcard;\n\n/**\n * A sequence of `path-to-regexp` keys that match capturing groups.\n */\nexport type Keys = Array;\n\n/**\n * A sequence of path match characters.\n */\nexport type Token = Text | Parameter | Wildcard | Group;\n\n/**\n * Tokenized path instance.\n */\nexport class TokenData {\n constructor(public readonly tokens: Token[]) {}\n}\n\n/**\n * Parse a string for the raw tokens.\n */\nexport function parse(str: string, options: ParseOptions = {}): TokenData {\n const { encodePath = NOOP_VALUE } = options;\n const it = new Iter(lexer(str));\n\n function consume(endType: TokenType): Token[] {\n const tokens: Token[] = [];\n\n while (true) {\n const path = it.text();\n if (path) tokens.push({ type: \"text\", value: encodePath(path) });\n\n const param = it.tryConsume(\"PARAM\");\n if (param) {\n tokens.push({\n type: \"param\",\n name: param,\n });\n continue;\n }\n\n const wildcard = it.tryConsume(\"WILDCARD\");\n if (wildcard) {\n tokens.push({\n type: \"wildcard\",\n name: wildcard,\n });\n continue;\n }\n\n const open = it.tryConsume(\"{\");\n if (open) {\n tokens.push({\n type: \"group\",\n tokens: consume(\"}\"),\n });\n continue;\n }\n\n it.consume(endType);\n return tokens;\n }\n }\n\n const tokens = consume(\"END\");\n return new TokenData(tokens);\n}\n\n/**\n * Compile a string to a template function for the path.\n */\nexport function compile

(\n path: Path,\n options: CompileOptions & ParseOptions = {},\n) {\n const { encode = encodeURIComponent, delimiter = DEFAULT_DELIMITER } =\n options;\n const data = path instanceof TokenData ? path : parse(path, options);\n const fn = tokensToFunction(data.tokens, delimiter, encode);\n\n return function path(data: P = {} as P) {\n const [path, ...missing] = fn(data);\n if (missing.length) {\n throw new TypeError(`Missing parameters: ${missing.join(\", \")}`);\n }\n return path;\n };\n}\n\nexport type ParamData = Partial>;\nexport type PathFunction

= (data?: P) => string;\n\nfunction tokensToFunction(\n tokens: Token[],\n delimiter: string,\n encode: Encode | false,\n) {\n const encoders = tokens.map((token) =>\n tokenToFunction(token, delimiter, encode),\n );\n\n return (data: ParamData) => {\n const result: string[] = [\"\"];\n\n for (const encoder of encoders) {\n const [value, ...extras] = encoder(data);\n result[0] += value;\n result.push(...extras);\n }\n\n return result;\n };\n}\n\n/**\n * Convert a single token into a path building function.\n */\nfunction tokenToFunction(\n token: Token,\n delimiter: string,\n encode: Encode | false,\n): (data: ParamData) => string[] {\n if (token.type === \"text\") return () => [token.value];\n\n if (token.type === \"group\") {\n const fn = tokensToFunction(token.tokens, delimiter, encode);\n\n return (data) => {\n const [value, ...missing] = fn(data);\n if (!missing.length) return [value];\n return [\"\"];\n };\n }\n\n const encodeValue = encode || NOOP_VALUE;\n\n if (token.type === \"wildcard\" && encode !== false) {\n return (data) => {\n const value = data[token.name];\n if (value == null) return [\"\", token.name];\n\n if (!Array.isArray(value) || value.length === 0) {\n throw new TypeError(`Expected \"${token.name}\" to be a non-empty array`);\n }\n\n return [\n value\n .map((value, index) => {\n if (typeof value !== \"string\") {\n throw new TypeError(\n `Expected \"${token.name}/${index}\" to be a string`,\n );\n }\n\n return encodeValue(value);\n })\n .join(delimiter),\n ];\n };\n }\n\n return (data) => {\n const value = data[token.name];\n if (value == null) return [\"\", token.name];\n\n if (typeof value !== \"string\") {\n throw new TypeError(`Expected \"${token.name}\" to be a string`);\n }\n\n return [encodeValue(value)];\n };\n}\n\n/**\n * A match result contains data about the path match.\n */\nexport interface MatchResult

{\n path: string;\n params: P;\n}\n\n/**\n * A match is either `false` (no match) or a match result.\n */\nexport type Match

= false | MatchResult

;\n\n/**\n * The match function takes a string and returns whether it matched the path.\n */\nexport type MatchFunction

= (path: string) => Match

;\n\n/**\n * Supported path types.\n */\nexport type Path = string | TokenData;\n\n/**\n * Transform a path into a match function.\n */\nexport function match

(\n path: Path | Path[],\n options: MatchOptions & ParseOptions = {},\n): MatchFunction

{\n const { decode = decodeURIComponent, delimiter = DEFAULT_DELIMITER } =\n options;\n const { regexp, keys } = pathToRegexp(path, options);\n\n const decoders = keys.map((key) => {\n if (decode === false) return NOOP_VALUE;\n if (key.type === \"param\") return decode;\n return (value: string) => value.split(delimiter).map(decode);\n });\n\n return function match(input: string) {\n const m = regexp.exec(input);\n if (!m) return false;\n\n const path = m[0];\n const params = Object.create(null);\n\n for (let i = 1; i < m.length; i++) {\n if (m[i] === undefined) continue;\n\n const key = keys[i - 1];\n const decoder = decoders[i - 1];\n params[key.name] = decoder(m[i]);\n }\n\n return { path, params };\n };\n}\n\nexport function pathToRegexp(\n path: Path | Path[],\n options: PathToRegexpOptions & ParseOptions = {},\n) {\n const {\n delimiter = DEFAULT_DELIMITER,\n end = true,\n sensitive = false,\n trailing = true,\n } = options;\n const keys: Keys = [];\n const sources: string[] = [];\n const flags = sensitive ? \"\" : \"i\";\n const paths = Array.isArray(path) ? path : [path];\n const items = paths.map((path) =>\n path instanceof TokenData ? path : parse(path, options),\n );\n\n for (const { tokens } of items) {\n for (const seq of flatten(tokens, 0, [])) {\n const regexp = sequenceToRegExp(seq, delimiter, keys);\n sources.push(regexp);\n }\n }\n\n let pattern = `^(?:${sources.join(\"|\")})`;\n if (trailing) pattern += `(?:${escape(delimiter)}$)?`;\n pattern += end ? \"$\" : `(?=${escape(delimiter)}|$)`;\n\n const regexp = new RegExp(pattern, flags);\n return { regexp, keys };\n}\n\n/**\n * Flattened token set.\n */\ntype Flattened = Text | Parameter | Wildcard;\n\n/**\n * Generate a flat list of sequence tokens from the given tokens.\n */\nfunction* flatten(\n tokens: Token[],\n index: number,\n init: Flattened[],\n): Generator {\n if (index === tokens.length) {\n return yield init;\n }\n\n const token = tokens[index];\n\n if (token.type === \"group\") {\n const fork = init.slice();\n for (const seq of flatten(token.tokens, 0, fork)) {\n yield* flatten(tokens, index + 1, seq);\n }\n } else {\n init.push(token);\n }\n\n yield* flatten(tokens, index + 1, init);\n}\n\n/**\n * Transform a flat sequence of tokens into a regular expression.\n */\nfunction sequenceToRegExp(tokens: Flattened[], delimiter: string, keys: Keys) {\n let result = \"\";\n let backtrack = \"\";\n let isSafeSegmentParam = true;\n\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i];\n\n if (token.type === \"text\") {\n result += escape(token.value);\n backtrack += token.value;\n isSafeSegmentParam ||= token.value.includes(delimiter);\n continue;\n }\n\n if (token.type === \"param\" || token.type === \"wildcard\") {\n if (!isSafeSegmentParam && !backtrack) {\n throw new TypeError(`Missing text after \"${token.name}\": ${DEBUG_URL}`);\n }\n\n if (token.type === \"param\") {\n result += `(${negate(delimiter, isSafeSegmentParam ? \"\" : backtrack)}+)`;\n } else {\n result += `([\\\\s\\\\S]+)`;\n }\n\n keys.push(token);\n backtrack = \"\";\n isSafeSegmentParam = false;\n continue;\n }\n }\n\n return result;\n}\n\nfunction negate(delimiter: string, backtrack: string) {\n if (backtrack.length < 2) {\n if (delimiter.length < 2) return `[^${escape(delimiter + backtrack)}]`;\n return `(?:(?!${escape(delimiter)})[^${escape(backtrack)}])`;\n }\n if (delimiter.length < 2) {\n return `(?:(?!${escape(backtrack)})[^${escape(delimiter)}])`;\n }\n return `(?:(?!${escape(backtrack)}|${escape(delimiter)})[\\\\s\\\\S])`;\n}\n\n/**\n * Stringify token data into a path string.\n */\nexport function stringify(data: TokenData) {\n return data.tokens\n .map(function stringifyToken(token, index, tokens): string {\n if (token.type === \"text\") return escapeText(token.value);\n if (token.type === \"group\") {\n return `{${token.tokens.map(stringifyToken).join(\"\")}}`;\n }\n\n const isSafe =\n isNameSafe(token.name) && isNextNameSafe(tokens[index + 1]);\n const key = isSafe ? token.name : JSON.stringify(token.name);\n\n if (token.type === \"param\") return `:${key}`;\n if (token.type === \"wildcard\") return `*${key}`;\n throw new TypeError(`Unexpected token: ${token}`);\n })\n .join(\"\");\n}\n\nfunction isNameSafe(name: string) {\n const [first, ...rest] = name;\n if (!ID_START.test(first)) return false;\n return rest.every((char) => ID_CONTINUE.test(char));\n}\n\nfunction isNextNameSafe(token: Token | undefined) {\n if (token?.type !== \"text\") return true;\n return !ID_CONTINUE.test(token.value[0]);\n}\n"]} \ No newline at end of file diff --git a/node_modules/path-to-regexp/package.json b/node_modules/path-to-regexp/package.json new file mode 100644 index 0000000..d4b35ca --- /dev/null +++ b/node_modules/path-to-regexp/package.json @@ -0,0 +1,62 @@ +{ + "name": "path-to-regexp", + "version": "8.2.0", + "description": "Express style path to RegExp utility", + "keywords": [ + "express", + "regexp", + "route", + "routing" + ], + "repository": { + "type": "git", + "url": "https://github.com/pillarjs/path-to-regexp.git" + }, + "license": "MIT", + "exports": "./dist/index.js", + "main": "dist/index.js", + "typings": "dist/index.d.ts", + "files": [ + "dist/" + ], + "scripts": { + "bench": "vitest bench", + "build": "ts-scripts build", + "format": "ts-scripts format", + "lint": "ts-scripts lint", + "prepare": "ts-scripts install && npm run build", + "size": "size-limit", + "specs": "ts-scripts specs", + "test": "ts-scripts test && npm run size" + }, + "devDependencies": { + "@borderless/ts-scripts": "^0.15.0", + "@size-limit/preset-small-lib": "^11.1.2", + "@types/node": "^22.7.2", + "@types/semver": "^7.3.1", + "@vitest/coverage-v8": "^2.1.1", + "recheck": "^4.4.5", + "size-limit": "^11.1.2", + "typescript": "^5.5.3" + }, + "engines": { + "node": ">=16" + }, + "publishConfig": { + "access": "public" + }, + "size-limit": [ + { + "path": "dist/index.js", + "limit": "2.2 kB" + } + ], + "ts-scripts": { + "dist": [ + "dist" + ], + "project": [ + "tsconfig.build.json" + ] + } +} diff --git a/node_modules/picocolors/LICENSE b/node_modules/picocolors/LICENSE new file mode 100644 index 0000000..46c9b95 --- /dev/null +++ b/node_modules/picocolors/LICENSE @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) 2021-2024 Oleksii Raspopov, Kostiantyn Denysov, Anton Verinov + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/picocolors/README.md b/node_modules/picocolors/README.md new file mode 100644 index 0000000..8e47aa8 --- /dev/null +++ b/node_modules/picocolors/README.md @@ -0,0 +1,21 @@ +# picocolors + +The tiniest and the fastest library for terminal output formatting with ANSI colors. + +```javascript +import pc from "picocolors" + +console.log( + pc.green(`How are ${pc.italic(`you`)} doing?`) +) +``` + +- **No dependencies.** +- **14 times** smaller and **2 times** faster than chalk. +- Used by popular tools like PostCSS, SVGO, Stylelint, and Browserslist. +- Node.js v6+ & browsers support. Support for both CJS and ESM projects. +- TypeScript type declarations included. +- [`NO_COLOR`](https://no-color.org/) friendly. + +## Docs +Read **[full docs](https://github.com/alexeyraspopov/picocolors#readme)** on GitHub. diff --git a/node_modules/picocolors/package.json b/node_modules/picocolors/package.json new file mode 100644 index 0000000..372d4b6 --- /dev/null +++ b/node_modules/picocolors/package.json @@ -0,0 +1,25 @@ +{ + "name": "picocolors", + "version": "1.1.1", + "main": "./picocolors.js", + "types": "./picocolors.d.ts", + "browser": { + "./picocolors.js": "./picocolors.browser.js" + }, + "sideEffects": false, + "description": "The tiniest and the fastest library for terminal output formatting with ANSI colors", + "files": [ + "picocolors.*", + "types.d.ts" + ], + "keywords": [ + "terminal", + "colors", + "formatting", + "cli", + "console" + ], + "author": "Alexey Raspopov", + "repository": "alexeyraspopov/picocolors", + "license": "ISC" +} diff --git a/node_modules/picocolors/picocolors.browser.js b/node_modules/picocolors/picocolors.browser.js new file mode 100644 index 0000000..9dcf637 --- /dev/null +++ b/node_modules/picocolors/picocolors.browser.js @@ -0,0 +1,4 @@ +var x=String; +var create=function() {return {isColorSupported:false,reset:x,bold:x,dim:x,italic:x,underline:x,inverse:x,hidden:x,strikethrough:x,black:x,red:x,green:x,yellow:x,blue:x,magenta:x,cyan:x,white:x,gray:x,bgBlack:x,bgRed:x,bgGreen:x,bgYellow:x,bgBlue:x,bgMagenta:x,bgCyan:x,bgWhite:x,blackBright:x,redBright:x,greenBright:x,yellowBright:x,blueBright:x,magentaBright:x,cyanBright:x,whiteBright:x,bgBlackBright:x,bgRedBright:x,bgGreenBright:x,bgYellowBright:x,bgBlueBright:x,bgMagentaBright:x,bgCyanBright:x,bgWhiteBright:x}}; +module.exports=create(); +module.exports.createColors = create; diff --git a/node_modules/picocolors/picocolors.d.ts b/node_modules/picocolors/picocolors.d.ts new file mode 100644 index 0000000..94e146a --- /dev/null +++ b/node_modules/picocolors/picocolors.d.ts @@ -0,0 +1,5 @@ +import { Colors } from "./types" + +declare const picocolors: Colors & { createColors: (enabled?: boolean) => Colors } + +export = picocolors diff --git a/node_modules/picocolors/picocolors.js b/node_modules/picocolors/picocolors.js new file mode 100644 index 0000000..e32df85 --- /dev/null +++ b/node_modules/picocolors/picocolors.js @@ -0,0 +1,75 @@ +let p = process || {}, argv = p.argv || [], env = p.env || {} +let isColorSupported = + !(!!env.NO_COLOR || argv.includes("--no-color")) && + (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI) + +let formatter = (open, close, replace = open) => + input => { + let string = "" + input, index = string.indexOf(close, open.length) + return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close + } + +let replaceClose = (string, close, replace, index) => { + let result = "", cursor = 0 + do { + result += string.substring(cursor, index) + replace + cursor = index + close.length + index = string.indexOf(close, cursor) + } while (~index) + return result + string.substring(cursor) +} + +let createColors = (enabled = isColorSupported) => { + let f = enabled ? formatter : () => String + return { + isColorSupported: enabled, + reset: f("\x1b[0m", "\x1b[0m"), + bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"), + dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"), + italic: f("\x1b[3m", "\x1b[23m"), + underline: f("\x1b[4m", "\x1b[24m"), + inverse: f("\x1b[7m", "\x1b[27m"), + hidden: f("\x1b[8m", "\x1b[28m"), + strikethrough: f("\x1b[9m", "\x1b[29m"), + + black: f("\x1b[30m", "\x1b[39m"), + red: f("\x1b[31m", "\x1b[39m"), + green: f("\x1b[32m", "\x1b[39m"), + yellow: f("\x1b[33m", "\x1b[39m"), + blue: f("\x1b[34m", "\x1b[39m"), + magenta: f("\x1b[35m", "\x1b[39m"), + cyan: f("\x1b[36m", "\x1b[39m"), + white: f("\x1b[37m", "\x1b[39m"), + gray: f("\x1b[90m", "\x1b[39m"), + + bgBlack: f("\x1b[40m", "\x1b[49m"), + bgRed: f("\x1b[41m", "\x1b[49m"), + bgGreen: f("\x1b[42m", "\x1b[49m"), + bgYellow: f("\x1b[43m", "\x1b[49m"), + bgBlue: f("\x1b[44m", "\x1b[49m"), + bgMagenta: f("\x1b[45m", "\x1b[49m"), + bgCyan: f("\x1b[46m", "\x1b[49m"), + bgWhite: f("\x1b[47m", "\x1b[49m"), + + blackBright: f("\x1b[90m", "\x1b[39m"), + redBright: f("\x1b[91m", "\x1b[39m"), + greenBright: f("\x1b[92m", "\x1b[39m"), + yellowBright: f("\x1b[93m", "\x1b[39m"), + blueBright: f("\x1b[94m", "\x1b[39m"), + magentaBright: f("\x1b[95m", "\x1b[39m"), + cyanBright: f("\x1b[96m", "\x1b[39m"), + whiteBright: f("\x1b[97m", "\x1b[39m"), + + bgBlackBright: f("\x1b[100m", "\x1b[49m"), + bgRedBright: f("\x1b[101m", "\x1b[49m"), + bgGreenBright: f("\x1b[102m", "\x1b[49m"), + bgYellowBright: f("\x1b[103m", "\x1b[49m"), + bgBlueBright: f("\x1b[104m", "\x1b[49m"), + bgMagentaBright: f("\x1b[105m", "\x1b[49m"), + bgCyanBright: f("\x1b[106m", "\x1b[49m"), + bgWhiteBright: f("\x1b[107m", "\x1b[49m"), + } +} + +module.exports = createColors() +module.exports.createColors = createColors diff --git a/node_modules/picocolors/types.d.ts b/node_modules/picocolors/types.d.ts new file mode 100644 index 0000000..cd1aec4 --- /dev/null +++ b/node_modules/picocolors/types.d.ts @@ -0,0 +1,51 @@ +export type Formatter = (input: string | number | null | undefined) => string + +export interface Colors { + isColorSupported: boolean + + reset: Formatter + bold: Formatter + dim: Formatter + italic: Formatter + underline: Formatter + inverse: Formatter + hidden: Formatter + strikethrough: Formatter + + black: Formatter + red: Formatter + green: Formatter + yellow: Formatter + blue: Formatter + magenta: Formatter + cyan: Formatter + white: Formatter + gray: Formatter + + bgBlack: Formatter + bgRed: Formatter + bgGreen: Formatter + bgYellow: Formatter + bgBlue: Formatter + bgMagenta: Formatter + bgCyan: Formatter + bgWhite: Formatter + + blackBright: Formatter + redBright: Formatter + greenBright: Formatter + yellowBright: Formatter + blueBright: Formatter + magentaBright: Formatter + cyanBright: Formatter + whiteBright: Formatter + + bgBlackBright: Formatter + bgRedBright: Formatter + bgGreenBright: Formatter + bgYellowBright: Formatter + bgBlueBright: Formatter + bgMagentaBright: Formatter + bgCyanBright: Formatter + bgWhiteBright: Formatter +} diff --git a/node_modules/proxy-addr/HISTORY.md b/node_modules/proxy-addr/HISTORY.md new file mode 100644 index 0000000..8480242 --- /dev/null +++ b/node_modules/proxy-addr/HISTORY.md @@ -0,0 +1,161 @@ +2.0.7 / 2021-05-31 +================== + + * deps: forwarded@0.2.0 + - Use `req.socket` over deprecated `req.connection` + +2.0.6 / 2020-02-24 +================== + + * deps: ipaddr.js@1.9.1 + +2.0.5 / 2019-04-16 +================== + + * deps: ipaddr.js@1.9.0 + +2.0.4 / 2018-07-26 +================== + + * deps: ipaddr.js@1.8.0 + +2.0.3 / 2018-02-19 +================== + + * deps: ipaddr.js@1.6.0 + +2.0.2 / 2017-09-24 +================== + + * deps: forwarded@~0.1.2 + - perf: improve header parsing + - perf: reduce overhead when no `X-Forwarded-For` header + +2.0.1 / 2017-09-10 +================== + + * deps: forwarded@~0.1.1 + - Fix trimming leading / trailing OWS + - perf: hoist regular expression + * deps: ipaddr.js@1.5.2 + +2.0.0 / 2017-08-08 +================== + + * Drop support for Node.js below 0.10 + +1.1.5 / 2017-07-25 +================== + + * Fix array argument being altered + * deps: ipaddr.js@1.4.0 + +1.1.4 / 2017-03-24 +================== + + * deps: ipaddr.js@1.3.0 + +1.1.3 / 2017-01-14 +================== + + * deps: ipaddr.js@1.2.0 + +1.1.2 / 2016-05-29 +================== + + * deps: ipaddr.js@1.1.1 + - Fix IPv6-mapped IPv4 validation edge cases + +1.1.1 / 2016-05-03 +================== + + * Fix regression matching mixed versions against multiple subnets + +1.1.0 / 2016-05-01 +================== + + * Fix accepting various invalid netmasks + - IPv4 netmasks must be contingous + - IPv6 addresses cannot be used as a netmask + * deps: ipaddr.js@1.1.0 + +1.0.10 / 2015-12-09 +=================== + + * deps: ipaddr.js@1.0.5 + - Fix regression in `isValid` with non-string arguments + +1.0.9 / 2015-12-01 +================== + + * deps: ipaddr.js@1.0.4 + - Fix accepting some invalid IPv6 addresses + - Reject CIDRs with negative or overlong masks + * perf: enable strict mode + +1.0.8 / 2015-05-10 +================== + + * deps: ipaddr.js@1.0.1 + +1.0.7 / 2015-03-16 +================== + + * deps: ipaddr.js@0.1.9 + - Fix OOM on certain inputs to `isValid` + +1.0.6 / 2015-02-01 +================== + + * deps: ipaddr.js@0.1.8 + +1.0.5 / 2015-01-08 +================== + + * deps: ipaddr.js@0.1.6 + +1.0.4 / 2014-11-23 +================== + + * deps: ipaddr.js@0.1.5 + - Fix edge cases with `isValid` + +1.0.3 / 2014-09-21 +================== + + * Use `forwarded` npm module + +1.0.2 / 2014-09-18 +================== + + * Fix a global leak when multiple subnets are trusted + * Support Node.js 0.6 + * deps: ipaddr.js@0.1.3 + +1.0.1 / 2014-06-03 +================== + + * Fix links in npm package + +1.0.0 / 2014-05-08 +================== + + * Add `trust` argument to determine proxy trust on + * Accepts custom function + * Accepts IPv4/IPv6 address(es) + * Accepts subnets + * Accepts pre-defined names + * Add optional `trust` argument to `proxyaddr.all` to + stop at first untrusted + * Add `proxyaddr.compile` to pre-compile `trust` function + to make subsequent calls faster + +0.0.1 / 2014-05-04 +================== + + * Fix bad npm publish + +0.0.0 / 2014-05-04 +================== + + * Initial release diff --git a/node_modules/proxy-addr/LICENSE b/node_modules/proxy-addr/LICENSE new file mode 100644 index 0000000..cab251c --- /dev/null +++ b/node_modules/proxy-addr/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2016 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/proxy-addr/README.md b/node_modules/proxy-addr/README.md new file mode 100644 index 0000000..69c0b63 --- /dev/null +++ b/node_modules/proxy-addr/README.md @@ -0,0 +1,139 @@ +# proxy-addr + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Determine address of proxied request + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install proxy-addr +``` + +## API + +```js +var proxyaddr = require('proxy-addr') +``` + +### proxyaddr(req, trust) + +Return the address of the request, using the given `trust` parameter. + +The `trust` argument is a function that returns `true` if you trust +the address, `false` if you don't. The closest untrusted address is +returned. + +```js +proxyaddr(req, function (addr) { return addr === '127.0.0.1' }) +proxyaddr(req, function (addr, i) { return i < 1 }) +``` + +The `trust` arugment may also be a single IP address string or an +array of trusted addresses, as plain IP addresses, CIDR-formatted +strings, or IP/netmask strings. + +```js +proxyaddr(req, '127.0.0.1') +proxyaddr(req, ['127.0.0.0/8', '10.0.0.0/8']) +proxyaddr(req, ['127.0.0.0/255.0.0.0', '192.168.0.0/255.255.0.0']) +``` + +This module also supports IPv6. Your IPv6 addresses will be normalized +automatically (i.e. `fe80::00ed:1` equals `fe80:0:0:0:0:0:ed:1`). + +```js +proxyaddr(req, '::1') +proxyaddr(req, ['::1/128', 'fe80::/10']) +``` + +This module will automatically work with IPv4-mapped IPv6 addresses +as well to support node.js in IPv6-only mode. This means that you do +not have to specify both `::ffff:a00:1` and `10.0.0.1`. + +As a convenience, this module also takes certain pre-defined names +in addition to IP addresses, which expand into IP addresses: + +```js +proxyaddr(req, 'loopback') +proxyaddr(req, ['loopback', 'fc00:ac:1ab5:fff::1/64']) +``` + + * `loopback`: IPv4 and IPv6 loopback addresses (like `::1` and + `127.0.0.1`). + * `linklocal`: IPv4 and IPv6 link-local addresses (like + `fe80::1:1:1:1` and `169.254.0.1`). + * `uniquelocal`: IPv4 private addresses and IPv6 unique-local + addresses (like `fc00:ac:1ab5:fff::1` and `192.168.0.1`). + +When `trust` is specified as a function, it will be called for each +address to determine if it is a trusted address. The function is +given two arguments: `addr` and `i`, where `addr` is a string of +the address to check and `i` is a number that represents the distance +from the socket address. + +### proxyaddr.all(req, [trust]) + +Return all the addresses of the request, optionally stopping at the +first untrusted. This array is ordered from closest to furthest +(i.e. `arr[0] === req.connection.remoteAddress`). + +```js +proxyaddr.all(req) +``` + +The optional `trust` argument takes the same arguments as `trust` +does in `proxyaddr(req, trust)`. + +```js +proxyaddr.all(req, 'loopback') +``` + +### proxyaddr.compile(val) + +Compiles argument `val` into a `trust` function. This function takes +the same arguments as `trust` does in `proxyaddr(req, trust)` and +returns a function suitable for `proxyaddr(req, trust)`. + +```js +var trust = proxyaddr.compile('loopback') +var addr = proxyaddr(req, trust) +``` + +This function is meant to be optimized for use against every request. +It is recommend to compile a trust function up-front for the trusted +configuration and pass that to `proxyaddr(req, trust)` for each request. + +## Testing + +```sh +$ npm test +``` + +## Benchmarks + +```sh +$ npm run-script bench +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/proxy-addr/master?label=ci +[ci-url]: https://github.com/jshttp/proxy-addr/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/proxy-addr/master +[coveralls-url]: https://coveralls.io/r/jshttp/proxy-addr?branch=master +[node-image]: https://badgen.net/npm/node/proxy-addr +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/proxy-addr +[npm-url]: https://npmjs.org/package/proxy-addr +[npm-version-image]: https://badgen.net/npm/v/proxy-addr diff --git a/node_modules/proxy-addr/index.js b/node_modules/proxy-addr/index.js new file mode 100644 index 0000000..a909b05 --- /dev/null +++ b/node_modules/proxy-addr/index.js @@ -0,0 +1,327 @@ +/*! + * proxy-addr + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = proxyaddr +module.exports.all = alladdrs +module.exports.compile = compile + +/** + * Module dependencies. + * @private + */ + +var forwarded = require('forwarded') +var ipaddr = require('ipaddr.js') + +/** + * Variables. + * @private + */ + +var DIGIT_REGEXP = /^[0-9]+$/ +var isip = ipaddr.isValid +var parseip = ipaddr.parse + +/** + * Pre-defined IP ranges. + * @private + */ + +var IP_RANGES = { + linklocal: ['169.254.0.0/16', 'fe80::/10'], + loopback: ['127.0.0.1/8', '::1/128'], + uniquelocal: ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fc00::/7'] +} + +/** + * Get all addresses in the request, optionally stopping + * at the first untrusted. + * + * @param {Object} request + * @param {Function|Array|String} [trust] + * @public + */ + +function alladdrs (req, trust) { + // get addresses + var addrs = forwarded(req) + + if (!trust) { + // Return all addresses + return addrs + } + + if (typeof trust !== 'function') { + trust = compile(trust) + } + + for (var i = 0; i < addrs.length - 1; i++) { + if (trust(addrs[i], i)) continue + + addrs.length = i + 1 + } + + return addrs +} + +/** + * Compile argument into trust function. + * + * @param {Array|String} val + * @private + */ + +function compile (val) { + if (!val) { + throw new TypeError('argument is required') + } + + var trust + + if (typeof val === 'string') { + trust = [val] + } else if (Array.isArray(val)) { + trust = val.slice() + } else { + throw new TypeError('unsupported trust argument') + } + + for (var i = 0; i < trust.length; i++) { + val = trust[i] + + if (!Object.prototype.hasOwnProperty.call(IP_RANGES, val)) { + continue + } + + // Splice in pre-defined range + val = IP_RANGES[val] + trust.splice.apply(trust, [i, 1].concat(val)) + i += val.length - 1 + } + + return compileTrust(compileRangeSubnets(trust)) +} + +/** + * Compile `arr` elements into range subnets. + * + * @param {Array} arr + * @private + */ + +function compileRangeSubnets (arr) { + var rangeSubnets = new Array(arr.length) + + for (var i = 0; i < arr.length; i++) { + rangeSubnets[i] = parseipNotation(arr[i]) + } + + return rangeSubnets +} + +/** + * Compile range subnet array into trust function. + * + * @param {Array} rangeSubnets + * @private + */ + +function compileTrust (rangeSubnets) { + // Return optimized function based on length + var len = rangeSubnets.length + return len === 0 + ? trustNone + : len === 1 + ? trustSingle(rangeSubnets[0]) + : trustMulti(rangeSubnets) +} + +/** + * Parse IP notation string into range subnet. + * + * @param {String} note + * @private + */ + +function parseipNotation (note) { + var pos = note.lastIndexOf('/') + var str = pos !== -1 + ? note.substring(0, pos) + : note + + if (!isip(str)) { + throw new TypeError('invalid IP address: ' + str) + } + + var ip = parseip(str) + + if (pos === -1 && ip.kind() === 'ipv6' && ip.isIPv4MappedAddress()) { + // Store as IPv4 + ip = ip.toIPv4Address() + } + + var max = ip.kind() === 'ipv6' + ? 128 + : 32 + + var range = pos !== -1 + ? note.substring(pos + 1, note.length) + : null + + if (range === null) { + range = max + } else if (DIGIT_REGEXP.test(range)) { + range = parseInt(range, 10) + } else if (ip.kind() === 'ipv4' && isip(range)) { + range = parseNetmask(range) + } else { + range = null + } + + if (range <= 0 || range > max) { + throw new TypeError('invalid range on address: ' + note) + } + + return [ip, range] +} + +/** + * Parse netmask string into CIDR range. + * + * @param {String} netmask + * @private + */ + +function parseNetmask (netmask) { + var ip = parseip(netmask) + var kind = ip.kind() + + return kind === 'ipv4' + ? ip.prefixLengthFromSubnetMask() + : null +} + +/** + * Determine address of proxied request. + * + * @param {Object} request + * @param {Function|Array|String} trust + * @public + */ + +function proxyaddr (req, trust) { + if (!req) { + throw new TypeError('req argument is required') + } + + if (!trust) { + throw new TypeError('trust argument is required') + } + + var addrs = alladdrs(req, trust) + var addr = addrs[addrs.length - 1] + + return addr +} + +/** + * Static trust function to trust nothing. + * + * @private + */ + +function trustNone () { + return false +} + +/** + * Compile trust function for multiple subnets. + * + * @param {Array} subnets + * @private + */ + +function trustMulti (subnets) { + return function trust (addr) { + if (!isip(addr)) return false + + var ip = parseip(addr) + var ipconv + var kind = ip.kind() + + for (var i = 0; i < subnets.length; i++) { + var subnet = subnets[i] + var subnetip = subnet[0] + var subnetkind = subnetip.kind() + var subnetrange = subnet[1] + var trusted = ip + + if (kind !== subnetkind) { + if (subnetkind === 'ipv4' && !ip.isIPv4MappedAddress()) { + // Incompatible IP addresses + continue + } + + if (!ipconv) { + // Convert IP to match subnet IP kind + ipconv = subnetkind === 'ipv4' + ? ip.toIPv4Address() + : ip.toIPv4MappedAddress() + } + + trusted = ipconv + } + + if (trusted.match(subnetip, subnetrange)) { + return true + } + } + + return false + } +} + +/** + * Compile trust function for single subnet. + * + * @param {Object} subnet + * @private + */ + +function trustSingle (subnet) { + var subnetip = subnet[0] + var subnetkind = subnetip.kind() + var subnetisipv4 = subnetkind === 'ipv4' + var subnetrange = subnet[1] + + return function trust (addr) { + if (!isip(addr)) return false + + var ip = parseip(addr) + var kind = ip.kind() + + if (kind !== subnetkind) { + if (subnetisipv4 && !ip.isIPv4MappedAddress()) { + // Incompatible IP addresses + return false + } + + // Convert IP to match subnet IP kind + ip = subnetisipv4 + ? ip.toIPv4Address() + : ip.toIPv4MappedAddress() + } + + return ip.match(subnetip, subnetrange) + } +} diff --git a/node_modules/proxy-addr/package.json b/node_modules/proxy-addr/package.json new file mode 100644 index 0000000..24ba8f7 --- /dev/null +++ b/node_modules/proxy-addr/package.json @@ -0,0 +1,47 @@ +{ + "name": "proxy-addr", + "description": "Determine address of proxied request", + "version": "2.0.7", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "ip", + "proxy", + "x-forwarded-for" + ], + "repository": "jshttp/proxy-addr", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "devDependencies": { + "benchmark": "2.1.4", + "beautify-benchmark": "0.2.4", + "deep-equal": "1.0.1", + "eslint": "7.26.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.23.4", + "eslint-plugin-markdown": "2.2.0", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "4.3.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "8.4.0", + "nyc": "15.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.10" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/qs/.editorconfig b/node_modules/qs/.editorconfig new file mode 100644 index 0000000..6adecfb --- /dev/null +++ b/node_modules/qs/.editorconfig @@ -0,0 +1,46 @@ +root = true + +[*] +indent_style = space +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 160 +quote_type = single + +[test/*] +max_line_length = off + +[LICENSE.md] +indent_size = off + +[*.md] +max_line_length = off + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[LICENSE] +indent_size = 2 +max_line_length = off + +[coverage/**/*] +indent_size = off +indent_style = off +indent = off +max_line_length = off + +[.nycrc] +indent_style = tab + +[tea.yaml] +indent_size = 2 diff --git a/node_modules/qs/.eslintrc b/node_modules/qs/.eslintrc new file mode 100644 index 0000000..a89f60e --- /dev/null +++ b/node_modules/qs/.eslintrc @@ -0,0 +1,39 @@ +{ + "root": true, + + "extends": "@ljharb", + + "ignorePatterns": [ + "dist/", + ], + + "rules": { + "complexity": 0, + "consistent-return": 1, + "func-name-matching": 0, + "id-length": [2, { "min": 1, "max": 25, "properties": "never" }], + "indent": [2, 4], + "max-lines": 0, + "max-lines-per-function": [2, { "max": 150 }], + "max-params": [2, 18], + "max-statements": [2, 100], + "multiline-comment-style": 0, + "no-continue": 1, + "no-magic-numbers": 0, + "no-restricted-syntax": [2, "BreakStatement", "DebuggerStatement", "ForInStatement", "LabeledStatement", "WithStatement"], + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "function-paren-newline": 0, + "max-lines-per-function": 0, + "max-statements": 0, + "no-buffer-constructor": 0, + "no-extend-native": 0, + "no-throw-literal": 0, + }, + }, + ], +} diff --git a/node_modules/qs/.github/FUNDING.yml b/node_modules/qs/.github/FUNDING.yml new file mode 100644 index 0000000..0355f4f --- /dev/null +++ b/node_modules/qs/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/qs +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/qs/.nycrc b/node_modules/qs/.nycrc new file mode 100644 index 0000000..1d57cab --- /dev/null +++ b/node_modules/qs/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "dist" + ] +} diff --git a/node_modules/qs/CHANGELOG.md b/node_modules/qs/CHANGELOG.md new file mode 100644 index 0000000..dc8e879 --- /dev/null +++ b/node_modules/qs/CHANGELOG.md @@ -0,0 +1,622 @@ +## **6.14.0** +- [New] `parse`: add `throwOnParameterLimitExceeded` option (#517) +- [Refactor] `parse`: use `utils.combine` more +- [patch] `parse`: add explicit `throwOnLimitExceeded` default +- [actions] use shared action; re-add finishers +- [meta] Fix changelog formatting bug +- [Deps] update `side-channel` +- [Dev Deps] update `es-value-fixtures`, `has-bigints`, `has-proto`, `has-symbols` +- [Tests] increase coverage + +## **6.13.1** +- [Fix] `stringify`: avoid a crash when a `filter` key is `null` +- [Fix] `utils.merge`: functions should not be stringified into keys +- [Fix] `parse`: avoid a crash with interpretNumericEntities: true, comma: true, and iso charset +- [Fix] `stringify`: ensure a non-string `filter` does not crash +- [Refactor] use `__proto__` syntax instead of `Object.create` for null objects +- [Refactor] misc cleanup +- [Tests] `utils.merge`: add some coverage +- [Tests] fix a test case +- [actions] split out node 10-20, and 20+ +- [Dev Deps] update `es-value-fixtures`, `mock-property`, `object-inspect`, `tape` + +## **6.13.0** +- [New] `parse`: add `strictDepth` option (#511) +- [Tests] use `npm audit` instead of `aud` + +## **6.12.3** +- [Fix] `parse`: properly account for `strictNullHandling` when `allowEmptyArrays` +- [meta] fix changelog indentation + +## **6.12.2** +- [Fix] `parse`: parse encoded square brackets (#506) +- [readme] add CII best practices badge + +## **6.12.1** +- [Fix] `parse`: Disable `decodeDotInKeys` by default to restore previous behavior (#501) +- [Performance] `utils`: Optimize performance under large data volumes, reduce memory usage, and speed up processing (#502) +- [Refactor] `utils`: use `+=` +- [Tests] increase coverage + +## **6.12.0** + +- [New] `parse`/`stringify`: add `decodeDotInKeys`/`encodeDotKeys` options (#488) +- [New] `parse`: add `duplicates` option +- [New] `parse`/`stringify`: add `allowEmptyArrays` option to allow [] in object values (#487) +- [Refactor] `parse`/`stringify`: move allowDots config logic to its own variable +- [Refactor] `stringify`: move option-handling code into `normalizeStringifyOptions` +- [readme] update readme, add logos (#484) +- [readme] `stringify`: clarify default `arrayFormat` behavior +- [readme] fix line wrapping +- [readme] remove dead badges +- [Deps] update `side-channel` +- [meta] make the dist build 50% smaller +- [meta] add `sideEffects` flag +- [meta] run build in prepack, not prepublish +- [Tests] `parse`: remove useless tests; add coverage +- [Tests] `stringify`: increase coverage +- [Tests] use `mock-property` +- [Tests] `stringify`: improve coverage +- [Dev Deps] update `@ljharb/eslint-config `, `aud`, `has-override-mistake`, `has-property-descriptors`, `mock-property`, `npmignore`, `object-inspect`, `tape` +- [Dev Deps] pin `glob`, since v10.3.8+ requires a broken `jackspeak` +- [Dev Deps] pin `jackspeak` since 2.1.2+ depends on npm aliases, which kill the install process in npm < 6 + +## **6.11.2** +- [Fix] `parse`: Fix parsing when the global Object prototype is frozen (#473) +- [Tests] add passing test cases with empty keys (#473) + +## **6.11.1** +- [Fix] `stringify`: encode comma values more consistently (#463) +- [readme] add usage of `filter` option for injecting custom serialization, i.e. of custom types (#447) +- [meta] remove extraneous code backticks (#457) +- [meta] fix changelog markdown +- [actions] update checkout action +- [actions] restrict action permissions +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `object-inspect`, `tape` + +## **6.11.0** +- [New] [Fix] `stringify`: revert 0e903c0; add `commaRoundTrip` option (#442) +- [readme] fix version badge + +## **6.10.5** +- [Fix] `stringify`: with `arrayFormat: comma`, properly include an explicit `[]` on a single-item array (#434) + +## **6.10.4** +- [Fix] `stringify`: with `arrayFormat: comma`, include an explicit `[]` on a single-item array (#441) +- [meta] use `npmignore` to autogenerate an npmignore file +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `has-symbol`, `object-inspect`, `tape` + +## **6.10.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [actions] reuse common workflows +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `object-inspect`, `tape` + +## **6.10.2** +- [Fix] `stringify`: actually fix cyclic references (#426) +- [Fix] `stringify`: avoid encoding arrayformat comma when `encodeValuesOnly = true` (#424) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] add note and links for coercing primitive values (#408) +- [actions] update codecov uploader +- [actions] update workflows +- [Tests] clean up stringify tests slightly +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `object-inspect`, `safe-publish-latest`, `tape` + +## **6.10.1** +- [Fix] `stringify`: avoid exception on repeated object values (#402) + +## **6.10.0** +- [New] `stringify`: throw on cycles, instead of an infinite loop (#395, #394, #393) +- [New] `parse`: add `allowSparse` option for collapsing arrays with missing indices (#312) +- [meta] fix README.md (#399) +- [meta] only run `npm run dist` in publish, not install +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `has-symbols`, `tape` +- [Tests] fix tests on node v0.6 +- [Tests] use `ljharb/actions/node/install` instead of `ljharb/actions/node/run` +- [Tests] Revert "[meta] ignore eclint transitive audit warning" + +## **6.9.7** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] `stringify`: avoid encoding arrayformat comma when `encodeValuesOnly = true` (#424) +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] add note and links for coercing primitive values (#408) +- [Tests] clean up stringify tests slightly +- [meta] fix README.md (#399) +- Revert "[meta] ignore eclint transitive audit warning" +- [actions] backport actions from main +- [Dev Deps] backport updates from main + +## **6.9.6** +- [Fix] restore `dist` dir; mistakenly removed in d4f6c32 + +## **6.9.5** +- [Fix] `stringify`: do not encode parens for RFC1738 +- [Fix] `stringify`: fix arrayFormat comma with empty array/objects (#350) +- [Refactor] `format`: remove `util.assign` call +- [meta] add "Allow Edits" workflow; update rebase workflow +- [actions] switch Automatic Rebase workflow to `pull_request_target` event +- [Tests] `stringify`: add tests for #378 +- [Tests] migrate tests to Github Actions +- [Tests] run `nyc` on all tests; use `tape` runner +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `browserify`, `mkdirp`, `object-inspect`, `tape`; add `aud` + +## **6.9.4** +- [Fix] `stringify`: when `arrayFormat` is `comma`, respect `serializeDate` (#364) +- [Refactor] `stringify`: reduce branching (part of #350) +- [Refactor] move `maybeMap` to `utils` +- [Dev Deps] update `browserify`, `tape` + +## **6.9.3** +- [Fix] proper comma parsing of URL-encoded commas (#361) +- [Fix] parses comma delimited array while having percent-encoded comma treated as normal text (#336) + +## **6.9.2** +- [Fix] `parse`: Fix parsing array from object with `comma` true (#359) +- [Fix] `parse`: throw a TypeError instead of an Error for bad charset (#349) +- [meta] ignore eclint transitive audit warning +- [meta] fix indentation in package.json +- [meta] add tidelift marketing copy +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `object-inspect`, `has-symbols`, `tape`, `mkdirp`, `iconv-lite` +- [actions] add automatic rebasing / merge commit blocking + +## **6.9.1** +- [Fix] `parse`: with comma true, handle field that holds an array of arrays (#335) +- [Fix] `parse`: with comma true, do not split non-string values (#334) +- [meta] add `funding` field +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` +- [Tests] use shared travis-ci config + +## **6.9.0** +- [New] `parse`/`stringify`: Pass extra key/value argument to `decoder` (#333) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `evalmd` +- [Tests] `parse`: add passing `arrayFormat` tests +- [Tests] add `posttest` using `npx aud` to run `npm audit` without a lockfile +- [Tests] up to `node` `v12.10`, `v11.15`, `v10.16`, `v8.16` +- [Tests] `Buffer.from` in node v5.0-v5.9 and v4.0-v4.4 requires a TypedArray + +## **6.8.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Fix] `stringify`: avoid encoding arrayformat comma when `encodeValuesOnly = true` (#424) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Tests] clean up stringify tests slightly +- [Docs] add note and links for coercing primitive values (#408) +- [meta] fix README.md (#399) +- [actions] backport actions from main +- [Dev Deps] backport updates from main +- [Refactor] `stringify`: reduce branching +- [meta] do not publish workflow files + +## **6.8.2** +- [Fix] proper comma parsing of URL-encoded commas (#361) +- [Fix] parses comma delimited array while having percent-encoded comma treated as normal text (#336) + +## **6.8.1** +- [Fix] `parse`: Fix parsing array from object with `comma` true (#359) +- [Fix] `parse`: throw a TypeError instead of an Error for bad charset (#349) +- [Fix] `parse`: with comma true, handle field that holds an array of arrays (#335) +- [fix] `parse`: with comma true, do not split non-string values (#334) +- [meta] add tidelift marketing copy +- [meta] add `funding` field +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`, `safe-publish-latest`, `evalmd`, `has-symbols`, `iconv-lite`, `mkdirp`, `object-inspect` +- [Tests] `parse`: add passing `arrayFormat` tests +- [Tests] use shared travis-ci configs +- [Tests] `Buffer.from` in node v5.0-v5.9 and v4.0-v4.4 requires a TypedArray +- [actions] add automatic rebasing / merge commit blocking + +## **6.8.0** +- [New] add `depth=false` to preserve the original key; [Fix] `depth=0` should preserve the original key (#326) +- [New] [Fix] stringify symbols and bigints +- [Fix] ensure node 0.12 can stringify Symbols +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Refactor] `formats`: tiny bit of cleanup. +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `browserify`, `safe-publish-latest`, `iconv-lite`, `tape` +- [Tests] add tests for `depth=0` and `depth=false` behavior, both current and intuitive/intended (#326) +- [Tests] use `eclint` instead of `editorconfig-tools` +- [docs] readme: add security note +- [meta] add github sponsorship +- [meta] add FUNDING.yml +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause + +## **6.7.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] `stringify`: avoid encoding arrayformat comma when `encodeValuesOnly = true` (#424) +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] add note and links for coercing primitive values (#408) +- [meta] fix README.md (#399) +- [meta] do not publish workflow files +- [actions] backport actions from main +- [Dev Deps] backport updates from main +- [Tests] use `nyc` for coverage +- [Tests] clean up stringify tests slightly + +## **6.7.2** +- [Fix] proper comma parsing of URL-encoded commas (#361) +- [Fix] parses comma delimited array while having percent-encoded comma treated as normal text (#336) + +## **6.7.1** +- [Fix] `parse`: Fix parsing array from object with `comma` true (#359) +- [Fix] `parse`: with comma true, handle field that holds an array of arrays (#335) +- [fix] `parse`: with comma true, do not split non-string values (#334) +- [Fix] `parse`: throw a TypeError instead of an Error for bad charset (#349) +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Refactor] `formats`: tiny bit of cleanup. +- readme: add security note +- [meta] add tidelift marketing copy +- [meta] add `funding` field +- [meta] add FUNDING.yml +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`, `safe-publish-latest`, `evalmd`, `iconv-lite`, `mkdirp`, `object-inspect`, `browserify` +- [Tests] `parse`: add passing `arrayFormat` tests +- [Tests] use shared travis-ci configs +- [Tests] `Buffer.from` in node v5.0-v5.9 and v4.0-v4.4 requires a TypedArray +- [Tests] add tests for `depth=0` and `depth=false` behavior, both current and intuitive/intended +- [Tests] use `eclint` instead of `editorconfig-tools` +- [actions] add automatic rebasing / merge commit blocking + +## **6.7.0** +- [New] `stringify`/`parse`: add `comma` as an `arrayFormat` option (#276, #219) +- [Fix] correctly parse nested arrays (#212) +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source, also with an array source +- [Robustness] `stringify`: cache `Object.prototype.hasOwnProperty` +- [Refactor] `utils`: `isBuffer`: small tweak; add tests +- [Refactor] use cached `Array.isArray` +- [Refactor] `parse`/`stringify`: make a function to normalize the options +- [Refactor] `utils`: reduce observable [[Get]]s +- [Refactor] `stringify`/`utils`: cache `Array.isArray` +- [Tests] always use `String(x)` over `x.toString()` +- [Tests] fix Buffer tests to work in node < 4.5 and node < 5.10 +- [Tests] temporarily allow coverage to fail + +## **6.6.1** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] correctly parse nested arrays +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Robustness] `stringify`: cache `Object.prototype.hasOwnProperty` +- [Refactor] `formats`: tiny bit of cleanup. +- [Refactor] `utils`: `isBuffer`: small tweak; add tests +- [Refactor]: `stringify`/`utils`: cache `Array.isArray` +- [Refactor] `utils`: reduce observable [[Get]]s +- [Refactor] use cached `Array.isArray` +- [Refactor] `parse`/`stringify`: make a function to normalize the options +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] do not publish workflow files +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [meta] Fixes typo in CHANGELOG.md +- [actions] backport actions from main +- [Tests] fix Buffer tests to work in node < 4.5 and node < 5.10 +- [Tests] always use `String(x)` over `x.toString()` +- [Dev Deps] backport from main + +## **6.6.0** +- [New] Add support for iso-8859-1, utf8 "sentinel" and numeric entities (#268) +- [New] move two-value combine to a `utils` function (#189) +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` (#260) +- [Fix] `stringify`: do not crash in an obscure combo of `interpretNumericEntities`, a bad custom `decoder`, & `iso-8859-1` +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [Refactor] `parse`: only need to reassign the var once +- [Refactor] `parse`/`stringify`: clean up `charset` options checking; fix defaults +- [Refactor] add missing defaults +- [Refactor] `parse`: one less `concat` call +- [Refactor] `utils`: `compactQueue`: make it explicitly side-effecting +- [Dev Deps] update `browserify`, `eslint`, `@ljharb/eslint-config`, `iconv-lite`, `safe-publish-latest`, `tape` +- [Tests] up to `node` `v10.10`, `v9.11`, `v8.12`, `v6.14`, `v4.9`; pin included builds to LTS + +## **6.5.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] correctly parse nested arrays +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Refactor] `utils`: reduce observable [[Get]]s +- [Refactor] use cached `Array.isArray` +- [Refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [Refactor] `parse`: only need to reassign the var once +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] Clean up license text so it’s properly detected as BSD-3-Clause +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] always use `String(x)` over `x.toString()` +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + +## **6.5.2** +- [Fix] use `safer-buffer` instead of `Buffer` constructor +- [Refactor] utils: `module.exports` one thing, instead of mutating `exports` (#230) +- [Dev Deps] update `browserify`, `eslint`, `iconv-lite`, `safer-buffer`, `tape`, `browserify` + +## **6.5.1** +- [Fix] Fix parsing & compacting very deep objects (#224) +- [Refactor] name utils functions +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` +- [Tests] up to `node` `v8.4`; use `nvm install-latest-npm` so newer npm doesn’t break older node +- [Tests] Use precise dist for Node.js 0.6 runtime (#225) +- [Tests] make 0.6 required, now that it’s passing +- [Tests] on `node` `v8.2`; fix npm on node 0.6 + +## **6.5.0** +- [New] add `utils.assign` +- [New] pass default encoder/decoder to custom encoder/decoder functions (#206) +- [New] `parse`/`stringify`: add `ignoreQueryPrefix`/`addQueryPrefix` options, respectively (#213) +- [Fix] Handle stringifying empty objects with addQueryPrefix (#217) +- [Fix] do not mutate `options` argument (#207) +- [Refactor] `parse`: cache index to reuse in else statement (#182) +- [Docs] add various badges to readme (#208) +- [Dev Deps] update `eslint`, `browserify`, `iconv-lite`, `tape` +- [Tests] up to `node` `v8.1`, `v7.10`, `v6.11`; npm v4.6 breaks on node < v1; npm v5+ breaks on node < v4 +- [Tests] add `editorconfig-tools` + +## **6.4.1** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] use `safer-buffer` instead of `Buffer` constructor +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Refactor] use cached `Array.isArray` +- [Refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + +## **6.4.0** +- [New] `qs.stringify`: add `encodeValuesOnly` option +- [Fix] follow `allowPrototypes` option during merge (#201, #201) +- [Fix] support keys starting with brackets (#202, #200) +- [Fix] chmod a-x +- [Dev Deps] update `eslint` +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds +- [eslint] reduce warnings + +## **6.3.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Refactor] use cached `Array.isArray` +- [Refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] use `safer-buffer` instead of `Buffer` constructor +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + +## **6.3.2** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Dev Deps] update `eslint` +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.3.1** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties (thanks, @snyk!) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `browserify`, `iconv-lite`, `qs-iconv`, `tape` +- [Tests] on all node minors; improve test matrix +- [Docs] document stringify option `allowDots` (#195) +- [Docs] add empty object and array values example (#195) +- [Docs] Fix minor inconsistency/typo (#192) +- [Docs] document stringify option `sort` (#191) +- [Refactor] `stringify`: throw faster with an invalid encoder +- [Refactor] remove unnecessary escapes (#184) +- Remove contributing.md, since `qs` is no longer part of `hapi` (#183) + +## **6.3.0** +- [New] Add support for RFC 1738 (#174, #173) +- [New] `stringify`: Add `serializeDate` option to customize Date serialization (#159) +- [Fix] ensure `utils.merge` handles merging two arrays +- [Refactor] only constructors should be capitalized +- [Refactor] capitalized var names are for constructors only +- [Refactor] avoid using a sparse array +- [Robustness] `formats`: cache `String#replace` +- [Dev Deps] update `browserify`, `eslint`, `@ljharb/eslint-config`; add `safe-publish-latest` +- [Tests] up to `node` `v6.8`, `v4.6`; improve test matrix +- [Tests] flesh out arrayLimit/arrayFormat tests (#107) +- [Tests] skip Object.create tests when null objects are not available +- [Tests] Turn on eslint for test files (#175) + +## **6.2.4** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Refactor] use cached `Array.isArray` +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] use `safer-buffer` instead of `Buffer` constructor +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + +## **6.2.3** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.2.2** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties + +## **6.2.1** +- [Fix] ensure `key[]=x&key[]&key[]=y` results in 3, not 2, values +- [Refactor] Be explicit and use `Object.prototype.hasOwnProperty.call` +- [Tests] remove `parallelshell` since it does not reliably report failures +- [Tests] up to `node` `v6.3`, `v5.12` +- [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config`, `qs-iconv` + +## [**6.2.0**](https://github.com/ljharb/qs/issues?milestone=36&state=closed) +- [New] pass Buffers to the encoder/decoder directly (#161) +- [New] add "encoder" and "decoder" options, for custom param encoding/decoding (#160) +- [Fix] fix compacting of nested sparse arrays (#150) + +## **6.1.2** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.1.1** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties + +## [**6.1.0**](https://github.com/ljharb/qs/issues?milestone=35&state=closed) +- [New] allowDots option for `stringify` (#151) +- [Fix] "sort" option should work at a depth of 3 or more (#151) +- [Fix] Restore `dist` directory; will be removed in v7 (#148) + +## **6.0.4** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.0.3** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties +- [Fix] Restore `dist` directory; will be removed in v7 (#148) + +## [**6.0.2**](https://github.com/ljharb/qs/issues?milestone=33&state=closed) +- Revert ES6 requirement and restore support for node down to v0.8. + +## [**6.0.1**](https://github.com/ljharb/qs/issues?milestone=32&state=closed) +- [**#127**](https://github.com/ljharb/qs/pull/127) Fix engines definition in package.json + +## [**6.0.0**](https://github.com/ljharb/qs/issues?milestone=31&state=closed) +- [**#124**](https://github.com/ljharb/qs/issues/124) Use ES6 and drop support for node < v4 + +## **5.2.1** +- [Fix] ensure `key[]=x&key[]&key[]=y` results in 3, not 2, values + +## [**5.2.0**](https://github.com/ljharb/qs/issues?milestone=30&state=closed) +- [**#64**](https://github.com/ljharb/qs/issues/64) Add option to sort object keys in the query string + +## [**5.1.0**](https://github.com/ljharb/qs/issues?milestone=29&state=closed) +- [**#117**](https://github.com/ljharb/qs/issues/117) make URI encoding stringified results optional +- [**#106**](https://github.com/ljharb/qs/issues/106) Add flag `skipNulls` to optionally skip null values in stringify + +## [**5.0.0**](https://github.com/ljharb/qs/issues?milestone=28&state=closed) +- [**#114**](https://github.com/ljharb/qs/issues/114) default allowDots to false +- [**#100**](https://github.com/ljharb/qs/issues/100) include dist to npm + +## [**4.0.0**](https://github.com/ljharb/qs/issues?milestone=26&state=closed) +- [**#98**](https://github.com/ljharb/qs/issues/98) make returning plain objects and allowing prototype overwriting properties optional + +## [**3.1.0**](https://github.com/ljharb/qs/issues?milestone=24&state=closed) +- [**#89**](https://github.com/ljharb/qs/issues/89) Add option to disable "Transform dot notation to bracket notation" + +## [**3.0.0**](https://github.com/ljharb/qs/issues?milestone=23&state=closed) +- [**#80**](https://github.com/ljharb/qs/issues/80) qs.parse silently drops properties +- [**#77**](https://github.com/ljharb/qs/issues/77) Perf boost +- [**#60**](https://github.com/ljharb/qs/issues/60) Add explicit option to disable array parsing +- [**#74**](https://github.com/ljharb/qs/issues/74) Bad parse when turning array into object +- [**#81**](https://github.com/ljharb/qs/issues/81) Add a `filter` option +- [**#68**](https://github.com/ljharb/qs/issues/68) Fixed issue with recursion and passing strings into objects. +- [**#66**](https://github.com/ljharb/qs/issues/66) Add mixed array and object dot notation support Closes: #47 +- [**#76**](https://github.com/ljharb/qs/issues/76) RFC 3986 +- [**#85**](https://github.com/ljharb/qs/issues/85) No equal sign +- [**#84**](https://github.com/ljharb/qs/issues/84) update license attribute + +## [**2.4.1**](https://github.com/ljharb/qs/issues?milestone=20&state=closed) +- [**#73**](https://github.com/ljharb/qs/issues/73) Property 'hasOwnProperty' of object # is not a function + +## [**2.4.0**](https://github.com/ljharb/qs/issues?milestone=19&state=closed) +- [**#70**](https://github.com/ljharb/qs/issues/70) Add arrayFormat option + +## [**2.3.3**](https://github.com/ljharb/qs/issues?milestone=18&state=closed) +- [**#59**](https://github.com/ljharb/qs/issues/59) make sure array indexes are >= 0, closes #57 +- [**#58**](https://github.com/ljharb/qs/issues/58) make qs usable for browser loader + +## [**2.3.2**](https://github.com/ljharb/qs/issues?milestone=17&state=closed) +- [**#55**](https://github.com/ljharb/qs/issues/55) allow merging a string into an object + +## [**2.3.1**](https://github.com/ljharb/qs/issues?milestone=16&state=closed) +- [**#52**](https://github.com/ljharb/qs/issues/52) Return "undefined" and "false" instead of throwing "TypeError". + +## [**2.3.0**](https://github.com/ljharb/qs/issues?milestone=15&state=closed) +- [**#50**](https://github.com/ljharb/qs/issues/50) add option to omit array indices, closes #46 + +## [**2.2.5**](https://github.com/ljharb/qs/issues?milestone=14&state=closed) +- [**#39**](https://github.com/ljharb/qs/issues/39) Is there an alternative to Buffer.isBuffer? +- [**#49**](https://github.com/ljharb/qs/issues/49) refactor utils.merge, fixes #45 +- [**#41**](https://github.com/ljharb/qs/issues/41) avoid browserifying Buffer, for #39 + +## [**2.2.4**](https://github.com/ljharb/qs/issues?milestone=13&state=closed) +- [**#38**](https://github.com/ljharb/qs/issues/38) how to handle object keys beginning with a number + +## [**2.2.3**](https://github.com/ljharb/qs/issues?milestone=12&state=closed) +- [**#37**](https://github.com/ljharb/qs/issues/37) parser discards first empty value in array +- [**#36**](https://github.com/ljharb/qs/issues/36) Update to lab 4.x + +## [**2.2.2**](https://github.com/ljharb/qs/issues?milestone=11&state=closed) +- [**#33**](https://github.com/ljharb/qs/issues/33) Error when plain object in a value +- [**#34**](https://github.com/ljharb/qs/issues/34) use Object.prototype.hasOwnProperty.call instead of obj.hasOwnProperty +- [**#24**](https://github.com/ljharb/qs/issues/24) Changelog? Semver? + +## [**2.2.1**](https://github.com/ljharb/qs/issues?milestone=10&state=closed) +- [**#32**](https://github.com/ljharb/qs/issues/32) account for circular references properly, closes #31 +- [**#31**](https://github.com/ljharb/qs/issues/31) qs.parse stackoverflow on circular objects + +## [**2.2.0**](https://github.com/ljharb/qs/issues?milestone=9&state=closed) +- [**#26**](https://github.com/ljharb/qs/issues/26) Don't use Buffer global if it's not present +- [**#30**](https://github.com/ljharb/qs/issues/30) Bug when merging non-object values into arrays +- [**#29**](https://github.com/ljharb/qs/issues/29) Don't call Utils.clone at the top of Utils.merge +- [**#23**](https://github.com/ljharb/qs/issues/23) Ability to not limit parameters? + +## [**2.1.0**](https://github.com/ljharb/qs/issues?milestone=8&state=closed) +- [**#22**](https://github.com/ljharb/qs/issues/22) Enable using a RegExp as delimiter + +## [**2.0.0**](https://github.com/ljharb/qs/issues?milestone=7&state=closed) +- [**#18**](https://github.com/ljharb/qs/issues/18) Why is there arrayLimit? +- [**#20**](https://github.com/ljharb/qs/issues/20) Configurable parametersLimit +- [**#21**](https://github.com/ljharb/qs/issues/21) make all limits optional, for #18, for #20 + +## [**1.2.2**](https://github.com/ljharb/qs/issues?milestone=6&state=closed) +- [**#19**](https://github.com/ljharb/qs/issues/19) Don't overwrite null values + +## [**1.2.1**](https://github.com/ljharb/qs/issues?milestone=5&state=closed) +- [**#16**](https://github.com/ljharb/qs/issues/16) ignore non-string delimiters +- [**#15**](https://github.com/ljharb/qs/issues/15) Close code block + +## [**1.2.0**](https://github.com/ljharb/qs/issues?milestone=4&state=closed) +- [**#12**](https://github.com/ljharb/qs/issues/12) Add optional delim argument +- [**#13**](https://github.com/ljharb/qs/issues/13) fix #11: flattened keys in array are now correctly parsed + +## [**1.1.0**](https://github.com/ljharb/qs/issues?milestone=3&state=closed) +- [**#7**](https://github.com/ljharb/qs/issues/7) Empty values of a POST array disappear after being submitted +- [**#9**](https://github.com/ljharb/qs/issues/9) Should not omit equals signs (=) when value is null +- [**#6**](https://github.com/ljharb/qs/issues/6) Minor grammar fix in README + +## [**1.0.2**](https://github.com/ljharb/qs/issues?milestone=2&state=closed) +- [**#5**](https://github.com/ljharb/qs/issues/5) array holes incorrectly copied into object on large index diff --git a/node_modules/qs/LICENSE.md b/node_modules/qs/LICENSE.md new file mode 100644 index 0000000..fecf6b6 --- /dev/null +++ b/node_modules/qs/LICENSE.md @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2014, Nathan LaFreniere and other [contributors](https://github.com/ljharb/qs/graphs/contributors) +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/qs/README.md b/node_modules/qs/README.md new file mode 100644 index 0000000..22c411d --- /dev/null +++ b/node_modules/qs/README.md @@ -0,0 +1,733 @@ +

+ qs +

+ +# qs [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/9058/badge)](https://bestpractices.coreinfrastructure.org/projects/9058) + +[![npm badge][npm-badge-png]][package-url] + +A querystring parsing and stringifying library with some added security. + +Lead Maintainer: [Jordan Harband](https://github.com/ljharb) + +The **qs** module was originally created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring). + +## Usage + +```javascript +var qs = require('qs'); +var assert = require('assert'); + +var obj = qs.parse('a=c'); +assert.deepEqual(obj, { a: 'c' }); + +var str = qs.stringify(obj); +assert.equal(str, 'a=c'); +``` + +### Parsing Objects + +[](#preventEval) +```javascript +qs.parse(string, [options]); +``` + +**qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`. +For example, the string `'foo[bar]=baz'` converts to: + +```javascript +assert.deepEqual(qs.parse('foo[bar]=baz'), { + foo: { + bar: 'baz' + } +}); +``` + +When using the `plainObjects` option the parsed value is returned as a null object, created via `{ __proto__: null }` and as such you should be aware that prototype methods will not exist on it and a user may set those names to whatever value they like: + +```javascript +var nullObject = qs.parse('a[hasOwnProperty]=b', { plainObjects: true }); +assert.deepEqual(nullObject, { a: { hasOwnProperty: 'b' } }); +``` + +By default parameters that would overwrite properties on the object prototype are ignored, if you wish to keep the data from those fields either use `plainObjects` as mentioned above, or set `allowPrototypes` to `true` which will allow user input to overwrite those properties. +*WARNING* It is generally a bad idea to enable this option as it can cause problems when attempting to use the properties that have been overwritten. +Always be careful with this option. + +```javascript +var protoObject = qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }); +assert.deepEqual(protoObject, { a: { hasOwnProperty: 'b' } }); +``` + +URI encoded strings work too: + +```javascript +assert.deepEqual(qs.parse('a%5Bb%5D=c'), { + a: { b: 'c' } +}); +``` + +You can also nest your objects, like `'foo[bar][baz]=foobarbaz'`: + +```javascript +assert.deepEqual(qs.parse('foo[bar][baz]=foobarbaz'), { + foo: { + bar: { + baz: 'foobarbaz' + } + } +}); +``` + +By default, when nesting objects **qs** will only parse up to 5 children deep. +This means if you attempt to parse a string like `'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be: + +```javascript +var expected = { + a: { + b: { + c: { + d: { + e: { + f: { + '[g][h][i]': 'j' + } + } + } + } + } + } +}; +var string = 'a[b][c][d][e][f][g][h][i]=j'; +assert.deepEqual(qs.parse(string), expected); +``` + +This depth can be overridden by passing a `depth` option to `qs.parse(string, [options])`: + +```javascript +var deep = qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 }); +assert.deepEqual(deep, { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } }); +``` + +You can configure **qs** to throw an error when parsing nested input beyond this depth using the `strictDepth` option (defaulted to false): + +```javascript +try { + qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1, strictDepth: true }); +} catch (err) { + assert(err instanceof RangeError); + assert.strictEqual(err.message, 'Input depth exceeded depth option of 1 and strictDepth is true'); +} +``` + +The depth limit helps mitigate abuse when **qs** is used to parse user input, and it is recommended to keep it a reasonably small number. The strictDepth option adds a layer of protection by throwing an error when the limit is exceeded, allowing you to catch and handle such cases. + +For similar reasons, by default **qs** will only parse up to 1000 parameters. This can be overridden by passing a `parameterLimit` option: + +```javascript +var limited = qs.parse('a=b&c=d', { parameterLimit: 1 }); +assert.deepEqual(limited, { a: 'b' }); +``` + +If you want an error to be thrown whenever the a limit is exceeded (eg, `parameterLimit`, `arrayLimit`), set the `throwOnLimitExceeded` option to `true`. This option will generate a descriptive error if the query string exceeds a configured limit. +```javascript +try { + qs.parse('a=1&b=2&c=3&d=4', { parameterLimit: 3, throwOnLimitExceeded: true }); +} catch (err) { + assert(err instanceof Error); + assert.strictEqual(err.message, 'Parameter limit exceeded. Only 3 parameters allowed.'); +} +``` + +When `throwOnLimitExceeded` is set to `false` (default), **qs** will parse up to the specified `parameterLimit` and ignore the rest without throwing an error. + +To bypass the leading question mark, use `ignoreQueryPrefix`: + +```javascript +var prefixed = qs.parse('?a=b&c=d', { ignoreQueryPrefix: true }); +assert.deepEqual(prefixed, { a: 'b', c: 'd' }); +``` + +An optional delimiter can also be passed: + +```javascript +var delimited = qs.parse('a=b;c=d', { delimiter: ';' }); +assert.deepEqual(delimited, { a: 'b', c: 'd' }); +``` + +Delimiters can be a regular expression too: + +```javascript +var regexed = qs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ }); +assert.deepEqual(regexed, { a: 'b', c: 'd', e: 'f' }); +``` + +Option `allowDots` can be used to enable dot notation: + +```javascript +var withDots = qs.parse('a.b=c', { allowDots: true }); +assert.deepEqual(withDots, { a: { b: 'c' } }); +``` + +Option `decodeDotInKeys` can be used to decode dots in keys +Note: it implies `allowDots`, so `parse` will error if you set `decodeDotInKeys` to `true`, and `allowDots` to `false`. + +```javascript +var withDots = qs.parse('name%252Eobj.first=John&name%252Eobj.last=Doe', { decodeDotInKeys: true }); +assert.deepEqual(withDots, { 'name.obj': { first: 'John', last: 'Doe' }}); +``` + +Option `allowEmptyArrays` can be used to allowing empty array values in object +```javascript +var withEmptyArrays = qs.parse('foo[]&bar=baz', { allowEmptyArrays: true }); +assert.deepEqual(withEmptyArrays, { foo: [], bar: 'baz' }); +``` + +Option `duplicates` can be used to change the behavior when duplicate keys are encountered +```javascript +assert.deepEqual(qs.parse('foo=bar&foo=baz'), { foo: ['bar', 'baz'] }); +assert.deepEqual(qs.parse('foo=bar&foo=baz', { duplicates: 'combine' }), { foo: ['bar', 'baz'] }); +assert.deepEqual(qs.parse('foo=bar&foo=baz', { duplicates: 'first' }), { foo: 'bar' }); +assert.deepEqual(qs.parse('foo=bar&foo=baz', { duplicates: 'last' }), { foo: 'baz' }); +``` + +If you have to deal with legacy browsers or services, there's also support for decoding percent-encoded octets as iso-8859-1: + +```javascript +var oldCharset = qs.parse('a=%A7', { charset: 'iso-8859-1' }); +assert.deepEqual(oldCharset, { a: '§' }); +``` + +Some services add an initial `utf8=✓` value to forms so that old Internet Explorer versions are more likely to submit the form as utf-8. +Additionally, the server can check the value against wrong encodings of the checkmark character and detect that a query string or `application/x-www-form-urlencoded` body was *not* sent as utf-8, eg. if the form had an `accept-charset` parameter or the containing page had a different character set. + +**qs** supports this mechanism via the `charsetSentinel` option. +If specified, the `utf8` parameter will be omitted from the returned object. +It will be used to switch to `iso-8859-1`/`utf-8` mode depending on how the checkmark is encoded. + +**Important**: When you specify both the `charset` option and the `charsetSentinel` option, the `charset` will be overridden when the request contains a `utf8` parameter from which the actual charset can be deduced. +In that sense the `charset` will behave as the default charset rather than the authoritative charset. + +```javascript +var detectedAsUtf8 = qs.parse('utf8=%E2%9C%93&a=%C3%B8', { + charset: 'iso-8859-1', + charsetSentinel: true +}); +assert.deepEqual(detectedAsUtf8, { a: 'ø' }); + +// Browsers encode the checkmark as ✓ when submitting as iso-8859-1: +var detectedAsIso8859_1 = qs.parse('utf8=%26%2310003%3B&a=%F8', { + charset: 'utf-8', + charsetSentinel: true +}); +assert.deepEqual(detectedAsIso8859_1, { a: 'ø' }); +``` + +If you want to decode the `&#...;` syntax to the actual character, you can specify the `interpretNumericEntities` option as well: + +```javascript +var detectedAsIso8859_1 = qs.parse('a=%26%239786%3B', { + charset: 'iso-8859-1', + interpretNumericEntities: true +}); +assert.deepEqual(detectedAsIso8859_1, { a: '☺' }); +``` + +It also works when the charset has been detected in `charsetSentinel` mode. + +### Parsing Arrays + +**qs** can also parse arrays using a similar `[]` notation: + +```javascript +var withArray = qs.parse('a[]=b&a[]=c'); +assert.deepEqual(withArray, { a: ['b', 'c'] }); +``` + +You may specify an index as well: + +```javascript +var withIndexes = qs.parse('a[1]=c&a[0]=b'); +assert.deepEqual(withIndexes, { a: ['b', 'c'] }); +``` + +Note that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number to create an array. +When creating arrays with specific indices, **qs** will compact a sparse array to only the existing values preserving their order: + +```javascript +var noSparse = qs.parse('a[1]=b&a[15]=c'); +assert.deepEqual(noSparse, { a: ['b', 'c'] }); +``` + +You may also use `allowSparse` option to parse sparse arrays: + +```javascript +var sparseArray = qs.parse('a[1]=2&a[3]=5', { allowSparse: true }); +assert.deepEqual(sparseArray, { a: [, '2', , '5'] }); +``` + +Note that an empty string is also a value, and will be preserved: + +```javascript +var withEmptyString = qs.parse('a[]=&a[]=b'); +assert.deepEqual(withEmptyString, { a: ['', 'b'] }); + +var withIndexedEmptyString = qs.parse('a[0]=b&a[1]=&a[2]=c'); +assert.deepEqual(withIndexedEmptyString, { a: ['b', '', 'c'] }); +``` + +**qs** will also limit specifying indices in an array to a maximum index of `20`. +Any array members with an index of greater than `20` will instead be converted to an object with the index as the key. +This is needed to handle cases when someone sent, for example, `a[999999999]` and it will take significant time to iterate over this huge array. + +```javascript +var withMaxIndex = qs.parse('a[100]=b'); +assert.deepEqual(withMaxIndex, { a: { '100': 'b' } }); +``` + +This limit can be overridden by passing an `arrayLimit` option: + +```javascript +var withArrayLimit = qs.parse('a[1]=b', { arrayLimit: 0 }); +assert.deepEqual(withArrayLimit, { a: { '1': 'b' } }); +``` + +If you want to throw an error whenever the array limit is exceeded, set the `throwOnLimitExceeded` option to `true`. This option will generate a descriptive error if the query string exceeds a configured limit. +```javascript +try { + qs.parse('a[1]=b', { arrayLimit: 0, throwOnLimitExceeded: true }); +} catch (err) { + assert(err instanceof Error); + assert.strictEqual(err.message, 'Array limit exceeded. Only 0 elements allowed in an array.'); +} +``` + +When `throwOnLimitExceeded` is set to `false` (default), **qs** will parse up to the specified `arrayLimit` and if the limit is exceeded, the array will instead be converted to an object with the index as the key + +To disable array parsing entirely, set `parseArrays` to `false`. + +```javascript +var noParsingArrays = qs.parse('a[]=b', { parseArrays: false }); +assert.deepEqual(noParsingArrays, { a: { '0': 'b' } }); +``` + +If you mix notations, **qs** will merge the two items into an object: + +```javascript +var mixedNotation = qs.parse('a[0]=b&a[b]=c'); +assert.deepEqual(mixedNotation, { a: { '0': 'b', b: 'c' } }); +``` + +You can also create arrays of objects: + +```javascript +var arraysOfObjects = qs.parse('a[][b]=c'); +assert.deepEqual(arraysOfObjects, { a: [{ b: 'c' }] }); +``` + +Some people use comma to join array, **qs** can parse it: +```javascript +var arraysOfObjects = qs.parse('a=b,c', { comma: true }) +assert.deepEqual(arraysOfObjects, { a: ['b', 'c'] }) +``` +(_this cannot convert nested objects, such as `a={b:1},{c:d}`_) + +### Parsing primitive/scalar values (numbers, booleans, null, etc) + +By default, all values are parsed as strings. +This behavior will not change and is explained in [issue #91](https://github.com/ljharb/qs/issues/91). + +```javascript +var primitiveValues = qs.parse('a=15&b=true&c=null'); +assert.deepEqual(primitiveValues, { a: '15', b: 'true', c: 'null' }); +``` + +If you wish to auto-convert values which look like numbers, booleans, and other values into their primitive counterparts, you can use the [query-types Express JS middleware](https://github.com/xpepermint/query-types) which will auto-convert all request query parameters. + +### Stringifying + +[](#preventEval) +```javascript +qs.stringify(object, [options]); +``` + +When stringifying, **qs** by default URI encodes output. Objects are stringified as you would expect: + +```javascript +assert.equal(qs.stringify({ a: 'b' }), 'a=b'); +assert.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); +``` + +This encoding can be disabled by setting the `encode` option to `false`: + +```javascript +var unencoded = qs.stringify({ a: { b: 'c' } }, { encode: false }); +assert.equal(unencoded, 'a[b]=c'); +``` + +Encoding can be disabled for keys by setting the `encodeValuesOnly` option to `true`: +```javascript +var encodedValues = qs.stringify( + { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, + { encodeValuesOnly: true } +); +assert.equal(encodedValues,'a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h'); +``` + +This encoding can also be replaced by a custom encoding method set as `encoder` option: + +```javascript +var encoded = qs.stringify({ a: { b: 'c' } }, { encoder: function (str) { + // Passed in values `a`, `b`, `c` + return // Return encoded string +}}) +``` + +_(Note: the `encoder` option does not apply if `encode` is `false`)_ + +Analogue to the `encoder` there is a `decoder` option for `parse` to override decoding of properties and values: + +```javascript +var decoded = qs.parse('x=z', { decoder: function (str) { + // Passed in values `x`, `z` + return // Return decoded string +}}) +``` + +You can encode keys and values using different logic by using the type argument provided to the encoder: + +```javascript +var encoded = qs.stringify({ a: { b: 'c' } }, { encoder: function (str, defaultEncoder, charset, type) { + if (type === 'key') { + return // Encoded key + } else if (type === 'value') { + return // Encoded value + } +}}) +``` + +The type argument is also provided to the decoder: + +```javascript +var decoded = qs.parse('x=z', { decoder: function (str, defaultDecoder, charset, type) { + if (type === 'key') { + return // Decoded key + } else if (type === 'value') { + return // Decoded value + } +}}) +``` + +Examples beyond this point will be shown as though the output is not URI encoded for clarity. +Please note that the return values in these cases *will* be URI encoded during real usage. + +When arrays are stringified, they follow the `arrayFormat` option, which defaults to `indices`: + +```javascript +qs.stringify({ a: ['b', 'c', 'd'] }); +// 'a[0]=b&a[1]=c&a[2]=d' +``` + +You may override this by setting the `indices` option to `false`, or to be more explicit, the `arrayFormat` option to `repeat`: + +```javascript +qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }); +// 'a=b&a=c&a=d' +``` + +You may use the `arrayFormat` option to specify the format of the output array: + +```javascript +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }) +// 'a[0]=b&a[1]=c' +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }) +// 'a[]=b&a[]=c' +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }) +// 'a=b&a=c' +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'comma' }) +// 'a=b,c' +``` + +Note: when using `arrayFormat` set to `'comma'`, you can also pass the `commaRoundTrip` option set to `true` or `false`, to append `[]` on single-item arrays, so that they can round trip through a parse. + +When objects are stringified, by default they use bracket notation: + +```javascript +qs.stringify({ a: { b: { c: 'd', e: 'f' } } }); +// 'a[b][c]=d&a[b][e]=f' +``` + +You may override this to use dot notation by setting the `allowDots` option to `true`: + +```javascript +qs.stringify({ a: { b: { c: 'd', e: 'f' } } }, { allowDots: true }); +// 'a.b.c=d&a.b.e=f' +``` + +You may encode the dot notation in the keys of object with option `encodeDotInKeys` by setting it to `true`: +Note: it implies `allowDots`, so `stringify` will error if you set `decodeDotInKeys` to `true`, and `allowDots` to `false`. +Caveat: when `encodeValuesOnly` is `true` as well as `encodeDotInKeys`, only dots in keys and nothing else will be encoded. +```javascript +qs.stringify({ "name.obj": { "first": "John", "last": "Doe" } }, { allowDots: true, encodeDotInKeys: true }) +// 'name%252Eobj.first=John&name%252Eobj.last=Doe' +``` + +You may allow empty array values by setting the `allowEmptyArrays` option to `true`: +```javascript +qs.stringify({ foo: [], bar: 'baz' }, { allowEmptyArrays: true }); +// 'foo[]&bar=baz' +``` + +Empty strings and null values will omit the value, but the equals sign (=) remains in place: + +```javascript +assert.equal(qs.stringify({ a: '' }), 'a='); +``` + +Key with no values (such as an empty object or array) will return nothing: + +```javascript +assert.equal(qs.stringify({ a: [] }), ''); +assert.equal(qs.stringify({ a: {} }), ''); +assert.equal(qs.stringify({ a: [{}] }), ''); +assert.equal(qs.stringify({ a: { b: []} }), ''); +assert.equal(qs.stringify({ a: { b: {}} }), ''); +``` + +Properties that are set to `undefined` will be omitted entirely: + +```javascript +assert.equal(qs.stringify({ a: null, b: undefined }), 'a='); +``` + +The query string may optionally be prepended with a question mark: + +```javascript +assert.equal(qs.stringify({ a: 'b', c: 'd' }, { addQueryPrefix: true }), '?a=b&c=d'); +``` + +The delimiter may be overridden with stringify as well: + +```javascript +assert.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d'); +``` + +If you only want to override the serialization of `Date` objects, you can provide a `serializeDate` option: + +```javascript +var date = new Date(7); +assert.equal(qs.stringify({ a: date }), 'a=1970-01-01T00:00:00.007Z'.replace(/:/g, '%3A')); +assert.equal( + qs.stringify({ a: date }, { serializeDate: function (d) { return d.getTime(); } }), + 'a=7' +); +``` + +You may use the `sort` option to affect the order of parameter keys: + +```javascript +function alphabeticalSort(a, b) { + return a.localeCompare(b); +} +assert.equal(qs.stringify({ a: 'c', z: 'y', b : 'f' }, { sort: alphabeticalSort }), 'a=c&b=f&z=y'); +``` + +Finally, you can use the `filter` option to restrict which keys will be included in the stringified output. +If you pass a function, it will be called for each key to obtain the replacement value. +Otherwise, if you pass an array, it will be used to select properties and array indices for stringification: + +```javascript +function filterFunc(prefix, value) { + if (prefix == 'b') { + // Return an `undefined` value to omit a property. + return; + } + if (prefix == 'e[f]') { + return value.getTime(); + } + if (prefix == 'e[g][0]') { + return value * 2; + } + return value; +} +qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: filterFunc }); +// 'a=b&c=d&e[f]=123&e[g][0]=4' +qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] }); +// 'a=b&e=f' +qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] }); +// 'a[0]=b&a[2]=d' +``` + +You could also use `filter` to inject custom serialization for user defined types. +Consider you're working with some api that expects query strings of the format for ranges: + +``` +https://domain.com/endpoint?range=30...70 +``` + +For which you model as: + +```javascript +class Range { + constructor(from, to) { + this.from = from; + this.to = to; + } +} +``` + +You could _inject_ a custom serializer to handle values of this type: + +```javascript +qs.stringify( + { + range: new Range(30, 70), + }, + { + filter: (prefix, value) => { + if (value instanceof Range) { + return `${value.from}...${value.to}`; + } + // serialize the usual way + return value; + }, + } +); +// range=30...70 +``` + +### Handling of `null` values + +By default, `null` values are treated like empty strings: + +```javascript +var withNull = qs.stringify({ a: null, b: '' }); +assert.equal(withNull, 'a=&b='); +``` + +Parsing does not distinguish between parameters with and without equal signs. +Both are converted to empty strings. + +```javascript +var equalsInsensitive = qs.parse('a&b='); +assert.deepEqual(equalsInsensitive, { a: '', b: '' }); +``` + +To distinguish between `null` values and empty strings use the `strictNullHandling` flag. In the result string the `null` +values have no `=` sign: + +```javascript +var strictNull = qs.stringify({ a: null, b: '' }, { strictNullHandling: true }); +assert.equal(strictNull, 'a&b='); +``` + +To parse values without `=` back to `null` use the `strictNullHandling` flag: + +```javascript +var parsedStrictNull = qs.parse('a&b=', { strictNullHandling: true }); +assert.deepEqual(parsedStrictNull, { a: null, b: '' }); +``` + +To completely skip rendering keys with `null` values, use the `skipNulls` flag: + +```javascript +var nullsSkipped = qs.stringify({ a: 'b', c: null}, { skipNulls: true }); +assert.equal(nullsSkipped, 'a=b'); +``` + +If you're communicating with legacy systems, you can switch to `iso-8859-1` using the `charset` option: + +```javascript +var iso = qs.stringify({ æ: 'æ' }, { charset: 'iso-8859-1' }); +assert.equal(iso, '%E6=%E6'); +``` + +Characters that don't exist in `iso-8859-1` will be converted to numeric entities, similar to what browsers do: + +```javascript +var numeric = qs.stringify({ a: '☺' }, { charset: 'iso-8859-1' }); +assert.equal(numeric, 'a=%26%239786%3B'); +``` + +You can use the `charsetSentinel` option to announce the character by including an `utf8=✓` parameter with the proper encoding if the checkmark, similar to what Ruby on Rails and others do when submitting forms. + +```javascript +var sentinel = qs.stringify({ a: '☺' }, { charsetSentinel: true }); +assert.equal(sentinel, 'utf8=%E2%9C%93&a=%E2%98%BA'); + +var isoSentinel = qs.stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'iso-8859-1' }); +assert.equal(isoSentinel, 'utf8=%26%2310003%3B&a=%E6'); +``` + +### Dealing with special character sets + +By default the encoding and decoding of characters is done in `utf-8`, and `iso-8859-1` support is also built in via the `charset` parameter. + +If you wish to encode querystrings to a different character set (i.e. +[Shift JIS](https://en.wikipedia.org/wiki/Shift_JIS)) you can use the +[`qs-iconv`](https://github.com/martinheidegger/qs-iconv) library: + +```javascript +var encoder = require('qs-iconv/encoder')('shift_jis'); +var shiftJISEncoded = qs.stringify({ a: 'こんにちは!' }, { encoder: encoder }); +assert.equal(shiftJISEncoded, 'a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I'); +``` + +This also works for decoding of query strings: + +```javascript +var decoder = require('qs-iconv/decoder')('shift_jis'); +var obj = qs.parse('a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I', { decoder: decoder }); +assert.deepEqual(obj, { a: 'こんにちは!' }); +``` + +### RFC 3986 and RFC 1738 space encoding + +RFC3986 used as default option and encodes ' ' to *%20* which is backward compatible. +In the same time, output can be stringified as per RFC1738 with ' ' equal to '+'. + +``` +assert.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); +assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC3986' }), 'a=b%20c'); +assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC1738' }), 'a=b+c'); +``` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +## qs for enterprise + +Available as part of the Tidelift Subscription + +The maintainers of qs and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. +Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. +[Learn more.](https://tidelift.com/subscription/pkg/npm-qs?utm_source=npm-qs&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + +[package-url]: https://npmjs.org/package/qs +[npm-version-svg]: https://versionbadg.es/ljharb/qs.svg +[deps-svg]: https://david-dm.org/ljharb/qs.svg +[deps-url]: https://david-dm.org/ljharb/qs +[dev-deps-svg]: https://david-dm.org/ljharb/qs/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/qs#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/qs.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/qs.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/qs.svg +[downloads-url]: https://npm-stat.com/charts.html?package=qs +[codecov-image]: https://codecov.io/gh/ljharb/qs/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/qs/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/qs +[actions-url]: https://github.com/ljharb/qs/actions + +## Acknowledgements + +qs logo by [NUMI](https://github.com/numi-hq/open-design): + +[NUMI Logo](https://numi.tech/?ref=qs) diff --git a/node_modules/qs/dist/qs.js b/node_modules/qs/dist/qs.js new file mode 100644 index 0000000..f37989a --- /dev/null +++ b/node_modules/qs/dist/qs.js @@ -0,0 +1,141 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Qs = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i-1)return e.split(",");if(t.throwOnLimitExceeded&&r>=t.arrayLimit)throw new RangeError("Array limit exceeded. Only "+t.arrayLimit+" element"+(1===t.arrayLimit?"":"s")+" allowed in an array.");return e},isoSentinel="utf8=%26%2310003%3B",charsetSentinel="utf8=%E2%9C%93",parseValues=function parseQueryStringValues(e,t){var r={__proto__:null},i=t.ignoreQueryPrefix?e.replace(/^\?/,""):e;i=i.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var a=t.parameterLimit===1/0?void 0:t.parameterLimit,o=i.split(t.delimiter,t.throwOnLimitExceeded?a+1:a);if(t.throwOnLimitExceeded&&o.length>a)throw new RangeError("Parameter limit exceeded. Only "+a+" parameter"+(1===a?"":"s")+" allowed.");var l,n=-1,s=t.charset;if(t.charsetSentinel)for(l=0;l-1&&(p=isArray(p)?[p]:p);var f=has.call(r,d);f&&"combine"===t.duplicates?r[d]=utils.combine(r[d],p):f&&"last"!==t.duplicates||(r[d]=p)}return r},parseObject=function(e,t,r,i){var a=0;if(e.length>0&&"[]"===e[e.length-1]){var o=e.slice(0,-1).join("");a=Array.isArray(t)&&t[o]?t[o].length:0}for(var l=i?t:parseArrayValue(t,r,a),n=e.length-1;n>=0;--n){var s,d=e[n];if("[]"===d&&r.parseArrays)s=r.allowEmptyArrays&&(""===l||r.strictNullHandling&&null===l)?[]:utils.combine([],l);else{s=r.plainObjects?{__proto__:null}:{};var p="["===d.charAt(0)&&"]"===d.charAt(d.length-1)?d.slice(1,-1):d,c=r.decodeDotInKeys?p.replace(/%2E/g,"."):p,u=parseInt(c,10);r.parseArrays||""!==c?!isNaN(u)&&d!==c&&String(u)===c&&u>=0&&r.parseArrays&&u<=r.arrayLimit?(s=[])[u]=l:"__proto__"!==c&&(s[c]=l):s={0:l}}l=s}return l},parseKeys=function parseQueryStringKeys(e,t,r,i){if(e){var a=r.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,o=/(\[[^[\]]*])/g,l=r.depth>0&&/(\[[^[\]]*])/.exec(a),n=l?a.slice(0,l.index):a,s=[];if(n){if(!r.plainObjects&&has.call(Object.prototype,n)&&!r.allowPrototypes)return;s.push(n)}for(var d=0;r.depth>0&&null!==(l=o.exec(a))&&d0?g.join(",")||null:void 0}];else if(isArray(f))S=f;else{var N=Object.keys(g);S=u?N.sort(u):N}var T=l?String(r).replace(/\./g,"%2E"):String(r),O=o&&isArray(g)&&1===g.length?T+"[]":T;if(a&&isArray(g)&&0===g.length)return O+"[]";for(var k=0;k0?c+y:""}; + +},{"1":1,"46":46,"5":5}],5:[function(require,module,exports){ +"use strict";var formats=require(1),has=Object.prototype.hasOwnProperty,isArray=Array.isArray,hexTable=function(){for(var e=[],r=0;r<256;++r)e.push("%"+((r<16?"0":"")+r.toString(16)).toUpperCase());return e}(),compactQueue=function compactQueue(e){for(;e.length>1;){var r=e.pop(),t=r.obj[r.prop];if(isArray(t)){for(var o=[],n=0;n=limit?a.slice(i,i+limit):a,p=[],f=0;f=48&&s<=57||s>=65&&s<=90||s>=97&&s<=122||n===formats.RFC1738&&(40===s||41===s)?p[p.length]=u.charAt(f):s<128?p[p.length]=hexTable[s]:s<2048?p[p.length]=hexTable[192|s>>6]+hexTable[128|63&s]:s<55296||s>=57344?p[p.length]=hexTable[224|s>>12]+hexTable[128|s>>6&63]+hexTable[128|63&s]:(f+=1,s=65536+((1023&s)<<10|1023&u.charCodeAt(f)),p[p.length]=hexTable[240|s>>18]+hexTable[128|s>>12&63]+hexTable[128|s>>6&63]+hexTable[128|63&s])}c+=p.join("")}return c},compact=function compact(e){for(var r=[{obj:{o:e},prop:"o"}],t=[],o=0;o-1?callBindBasic([t]):t}; + +},{"10":10,"25":25}],25:[function(require,module,exports){ +"use strict";var undefined,$Object=require(22),$Error=require(16),$EvalError=require(15),$RangeError=require(17),$ReferenceError=require(18),$SyntaxError=require(19),$TypeError=require(20),$URIError=require(21),abs=require(34),floor=require(35),max=require(37),min=require(38),pow=require(39),round=require(40),sign=require(41),$Function=Function,getEvalledConstructor=function(r){try{return $Function('"use strict"; return ('+r+").constructor;")()}catch(r){}},$gOPD=require(30),$defineProperty=require(14),throwTypeError=function(){throw new $TypeError},ThrowTypeError=$gOPD?function(){try{return throwTypeError}catch(r){try{return $gOPD(arguments,"callee").get}catch(r){return throwTypeError}}}():throwTypeError,hasSymbols=require(31)(),getProto=require(28),$ObjectGPO=require(26),$ReflectGPO=require(27),$apply=require(8),$call=require(9),needsEval={},TypedArray="undefined"!=typeof Uint8Array&&getProto?getProto(Uint8Array):undefined,INTRINSICS={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?undefined:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?undefined:ArrayBuffer,"%ArrayIteratorPrototype%":hasSymbols&&getProto?getProto([][Symbol.iterator]()):undefined,"%AsyncFromSyncIteratorPrototype%":undefined,"%AsyncFunction%":needsEval,"%AsyncGenerator%":needsEval,"%AsyncGeneratorFunction%":needsEval,"%AsyncIteratorPrototype%":needsEval,"%Atomics%":"undefined"==typeof Atomics?undefined:Atomics,"%BigInt%":"undefined"==typeof BigInt?undefined:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?undefined:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?undefined:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?undefined:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":$Error,"%eval%":eval,"%EvalError%":$EvalError,"%Float32Array%":"undefined"==typeof Float32Array?undefined:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?undefined:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?undefined:FinalizationRegistry,"%Function%":$Function,"%GeneratorFunction%":needsEval,"%Int8Array%":"undefined"==typeof Int8Array?undefined:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?undefined:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?undefined:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":hasSymbols&&getProto?getProto(getProto([][Symbol.iterator]())):undefined,"%JSON%":"object"==typeof JSON?JSON:undefined,"%Map%":"undefined"==typeof Map?undefined:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&hasSymbols&&getProto?getProto((new Map)[Symbol.iterator]()):undefined,"%Math%":Math,"%Number%":Number,"%Object%":$Object,"%Object.getOwnPropertyDescriptor%":$gOPD,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?undefined:Promise,"%Proxy%":"undefined"==typeof Proxy?undefined:Proxy,"%RangeError%":$RangeError,"%ReferenceError%":$ReferenceError,"%Reflect%":"undefined"==typeof Reflect?undefined:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?undefined:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&hasSymbols&&getProto?getProto((new Set)[Symbol.iterator]()):undefined,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?undefined:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":hasSymbols&&getProto?getProto(""[Symbol.iterator]()):undefined,"%Symbol%":hasSymbols?Symbol:undefined,"%SyntaxError%":$SyntaxError,"%ThrowTypeError%":ThrowTypeError,"%TypedArray%":TypedArray,"%TypeError%":$TypeError,"%Uint8Array%":"undefined"==typeof Uint8Array?undefined:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?undefined:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?undefined:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?undefined:Uint32Array,"%URIError%":$URIError,"%WeakMap%":"undefined"==typeof WeakMap?undefined:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?undefined:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?undefined:WeakSet,"%Function.prototype.call%":$call,"%Function.prototype.apply%":$apply,"%Object.defineProperty%":$defineProperty,"%Object.getPrototypeOf%":$ObjectGPO,"%Math.abs%":abs,"%Math.floor%":floor,"%Math.max%":max,"%Math.min%":min,"%Math.pow%":pow,"%Math.round%":round,"%Math.sign%":sign,"%Reflect.getPrototypeOf%":$ReflectGPO};if(getProto)try{null.error}catch(r){var errorProto=getProto(getProto(r));INTRINSICS["%Error.prototype%"]=errorProto}var doEval=function doEval(r){var e;if("%AsyncFunction%"===r)e=getEvalledConstructor("async function () {}");else if("%GeneratorFunction%"===r)e=getEvalledConstructor("function* () {}");else if("%AsyncGeneratorFunction%"===r)e=getEvalledConstructor("async function* () {}");else if("%AsyncGenerator%"===r){var t=doEval("%AsyncGeneratorFunction%");t&&(e=t.prototype)}else if("%AsyncIteratorPrototype%"===r){var o=doEval("%AsyncGenerator%");o&&getProto&&(e=getProto(o.prototype))}return INTRINSICS[r]=e,e},LEGACY_ALIASES={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},bind=require(24),hasOwn=require(33),$concat=bind.call($call,Array.prototype.concat),$spliceApply=bind.call($apply,Array.prototype.splice),$replace=bind.call($call,String.prototype.replace),$strSlice=bind.call($call,String.prototype.slice),$exec=bind.call($call,RegExp.prototype.exec),rePropName=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,reEscapeChar=/\\(\\)?/g,stringToPath=function stringToPath(r){var e=$strSlice(r,0,1),t=$strSlice(r,-1);if("%"===e&&"%"!==t)throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`");if("%"===t&&"%"!==e)throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`");var o=[];return $replace(r,rePropName,(function(r,e,t,n){o[o.length]=t?$replace(n,reEscapeChar,"$1"):e||r})),o},getBaseIntrinsic=function getBaseIntrinsic(r,e){var t,o=r;if(hasOwn(LEGACY_ALIASES,o)&&(o="%"+(t=LEGACY_ALIASES[o])[0]+"%"),hasOwn(INTRINSICS,o)){var n=INTRINSICS[o];if(n===needsEval&&(n=doEval(o)),void 0===n&&!e)throw new $TypeError("intrinsic "+r+" exists, but is not available. Please file an issue!");return{alias:t,name:o,value:n}}throw new $SyntaxError("intrinsic "+r+" does not exist!")};module.exports=function GetIntrinsic(r,e){if("string"!=typeof r||0===r.length)throw new $TypeError("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof e)throw new $TypeError('"allowMissing" argument must be a boolean');if(null===$exec(/^%?[^%]*%?$/,r))throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var t=stringToPath(r),o=t.length>0?t[0]:"",n=getBaseIntrinsic("%"+o+"%",e),a=n.name,i=n.value,y=!1,p=n.alias;p&&(o=p[0],$spliceApply(t,$concat([0,1],p)));for(var s=1,d=!0;s=t.length){var c=$gOPD(i,f);i=(d=!!c)&&"get"in c&&!("originalValue"in c.get)?c.get:i[f]}else d=hasOwn(i,f),i=i[f];d&&!y&&(INTRINSICS[a]=i)}}return i}; + +},{"14":14,"15":15,"16":16,"17":17,"18":18,"19":19,"20":20,"21":21,"22":22,"24":24,"26":26,"27":27,"28":28,"30":30,"31":31,"33":33,"34":34,"35":35,"37":37,"38":38,"39":39,"40":40,"41":41,"8":8,"9":9}],13:[function(require,module,exports){ +"use strict";var hasProtoAccessor,callBind=require(10),gOPD=require(30);try{hasProtoAccessor=[].__proto__===Array.prototype}catch(t){if(!t||"object"!=typeof t||!("code"in t)||"ERR_PROTO_ACCESS"!==t.code)throw t}var desc=!!hasProtoAccessor&&gOPD&&gOPD(Object.prototype,"__proto__"),$Object=Object,$getPrototypeOf=$Object.getPrototypeOf;module.exports=desc&&"function"==typeof desc.get?callBind([desc.get]):"function"==typeof $getPrototypeOf&&function getDunder(t){return $getPrototypeOf(null==t?t:$Object(t))}; + +},{"10":10,"30":30}],30:[function(require,module,exports){ +"use strict";var $gOPD=require(29);if($gOPD)try{$gOPD([],"length")}catch(g){$gOPD=null}module.exports=$gOPD; + +},{"29":29}],14:[function(require,module,exports){ +"use strict";var $defineProperty=Object.defineProperty||!1;if($defineProperty)try{$defineProperty({},"a",{value:1})}catch(e){$defineProperty=!1}module.exports=$defineProperty; + +},{}],15:[function(require,module,exports){ +"use strict";module.exports=EvalError; + +},{}],16:[function(require,module,exports){ +"use strict";module.exports=Error; + +},{}],17:[function(require,module,exports){ +"use strict";module.exports=RangeError; + +},{}],18:[function(require,module,exports){ +"use strict";module.exports=ReferenceError; + +},{}],19:[function(require,module,exports){ +"use strict";module.exports=SyntaxError; + +},{}],21:[function(require,module,exports){ +"use strict";module.exports=URIError; + +},{}],22:[function(require,module,exports){ +"use strict";module.exports=Object; + +},{}],23:[function(require,module,exports){ +"use strict";var ERROR_MESSAGE="Function.prototype.bind called on incompatible ",toStr=Object.prototype.toString,max=Math.max,funcType="[object Function]",concatty=function concatty(t,n){for(var r=[],o=0;o-1e3&&t<1e3||$test.call(/e/,e))return e;var r=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof t){var n=t<0?-$floor(-t):$floor(t);if(n!==t){var o=String(n),i=$slice.call(e,o.length+1);return $replace.call(o,r,"$&_")+"."+$replace.call($replace.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return $replace.call(e,r,"$&_")}var utilInspect=require(6),inspectCustom=utilInspect.custom,inspectSymbol=isSymbol(inspectCustom)?inspectCustom:null,quotes={__proto__:null,double:'"',single:"'"},quoteREs={__proto__:null,double:/(["\\])/g,single:/(['\\])/g};function wrapQuotes(t,e,r){var n=r.quoteStyle||e,o=quotes[n];return o+t+o}function quote(t){return $replace.call(String(t),/"/g,""")}function isArray(t){return!("[object Array]"!==toStr(t)||toStringTag&&"object"==typeof t&&toStringTag in t)}function isDate(t){return!("[object Date]"!==toStr(t)||toStringTag&&"object"==typeof t&&toStringTag in t)}function isRegExp(t){return!("[object RegExp]"!==toStr(t)||toStringTag&&"object"==typeof t&&toStringTag in t)}function isError(t){return!("[object Error]"!==toStr(t)||toStringTag&&"object"==typeof t&&toStringTag in t)}function isString(t){return!("[object String]"!==toStr(t)||toStringTag&&"object"==typeof t&&toStringTag in t)}function isNumber(t){return!("[object Number]"!==toStr(t)||toStringTag&&"object"==typeof t&&toStringTag in t)}function isBoolean(t){return!("[object Boolean]"!==toStr(t)||toStringTag&&"object"==typeof t&&toStringTag in t)}function isSymbol(t){if(hasShammedSymbols)return t&&"object"==typeof t&&t instanceof Symbol;if("symbol"==typeof t)return!0;if(!t||"object"!=typeof t||!symToString)return!1;try{return symToString.call(t),!0}catch(t){}return!1}function isBigInt(t){if(!t||"object"!=typeof t||!bigIntValueOf)return!1;try{return bigIntValueOf.call(t),!0}catch(t){}return!1}module.exports=function inspect_(t,e,r,n){var o=e||{};if(has(o,"quoteStyle")&&!has(quotes,o.quoteStyle))throw new TypeError('option "quoteStyle" must be "single" or "double"');if(has(o,"maxStringLength")&&("number"==typeof o.maxStringLength?o.maxStringLength<0&&o.maxStringLength!==1/0:null!==o.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var i=!has(o,"customInspect")||o.customInspect;if("boolean"!=typeof i&&"symbol"!==i)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(has(o,"indent")&&null!==o.indent&&"\t"!==o.indent&&!(parseInt(o.indent,10)===o.indent&&o.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(has(o,"numericSeparator")&&"boolean"!=typeof o.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var a=o.numericSeparator;if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return inspectString(t,o);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var c=String(t);return a?addNumericSeparator(t,c):c}if("bigint"==typeof t){var l=String(t)+"n";return a?addNumericSeparator(t,l):l}var p=void 0===o.depth?5:o.depth;if(void 0===r&&(r=0),r>=p&&p>0&&"object"==typeof t)return isArray(t)?"[Array]":"[Object]";var u=getIndent(o,r);if(void 0===n)n=[];else if(indexOf(n,t)>=0)return"[Circular]";function inspect(t,e,i){if(e&&(n=$arrSlice.call(n)).push(e),i){var a={depth:o.depth};return has(o,"quoteStyle")&&(a.quoteStyle=o.quoteStyle),inspect_(t,a,r+1,n)}return inspect_(t,o,r+1,n)}if("function"==typeof t&&!isRegExp(t)){var s=nameOf(t),f=arrObjKeys(t,inspect);return"[Function"+(s?": "+s:" (anonymous)")+"]"+(f.length>0?" { "+$join.call(f,", ")+" }":"")}if(isSymbol(t)){var y=hasShammedSymbols?$replace.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):symToString.call(t);return"object"!=typeof t||hasShammedSymbols?y:markBoxed(y)}if(isElement(t)){for(var S="<"+$toLowerCase.call(String(t.nodeName)),g=t.attributes||[],b=0;b"}if(isArray(t)){if(0===t.length)return"[]";var m=arrObjKeys(t,inspect);return u&&!singleLineValues(m)?"["+indentedJoin(m,u)+"]":"[ "+$join.call(m,", ")+" ]"}if(isError(t)){var h=arrObjKeys(t,inspect);return"cause"in Error.prototype||!("cause"in t)||isEnumerable.call(t,"cause")?0===h.length?"["+String(t)+"]":"{ ["+String(t)+"] "+$join.call(h,", ")+" }":"{ ["+String(t)+"] "+$join.call($concat.call("[cause]: "+inspect(t.cause),h),", ")+" }"}if("object"==typeof t&&i){if(inspectSymbol&&"function"==typeof t[inspectSymbol]&&utilInspect)return utilInspect(t,{depth:p-r});if("symbol"!==i&&"function"==typeof t.inspect)return t.inspect()}if(isMap(t)){var d=[];return mapForEach&&mapForEach.call(t,(function(e,r){d.push(inspect(r,t,!0)+" => "+inspect(e,t))})),collectionOf("Map",mapSize.call(t),d,u)}if(isSet(t)){var j=[];return setForEach&&setForEach.call(t,(function(e){j.push(inspect(e,t))})),collectionOf("Set",setSize.call(t),j,u)}if(isWeakMap(t))return weakCollectionOf("WeakMap");if(isWeakSet(t))return weakCollectionOf("WeakSet");if(isWeakRef(t))return weakCollectionOf("WeakRef");if(isNumber(t))return markBoxed(inspect(Number(t)));if(isBigInt(t))return markBoxed(inspect(bigIntValueOf.call(t)));if(isBoolean(t))return markBoxed(booleanValueOf.call(t));if(isString(t))return markBoxed(inspect(String(t)));if("undefined"!=typeof window&&t===window)return"{ [object Window] }";if("undefined"!=typeof globalThis&&t===globalThis||"undefined"!=typeof global&&t===global)return"{ [object globalThis] }";if(!isDate(t)&&!isRegExp(t)){var O=arrObjKeys(t,inspect),w=gPO?gPO(t)===Object.prototype:t instanceof Object||t.constructor===Object,$=t instanceof Object?"":"null prototype",k=!w&&toStringTag&&Object(t)===t&&toStringTag in t?$slice.call(toStr(t),8,-1):$?"Object":"",v=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(k||$?"["+$join.call($concat.call([],k||[],$||[]),": ")+"] ":"");return 0===O.length?v+"{}":u?v+"{"+indentedJoin(O,u)+"}":v+"{ "+$join.call(O,", ")+" }"}return String(t)};var hasOwn=Object.prototype.hasOwnProperty||function(t){return t in this};function has(t,e){return hasOwn.call(t,e)}function toStr(t){return objectToString.call(t)}function nameOf(t){if(t.name)return t.name;var e=$match.call(functionToString.call(t),/^function\s*([\w$]+)/);return e?e[1]:null}function indexOf(t,e){if(t.indexOf)return t.indexOf(e);for(var r=0,n=t.length;re.maxStringLength){var r=t.length-e.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return inspectString($slice.call(t,0,e.maxStringLength),e)+n}var o=quoteREs[e.quoteStyle||"single"];return o.lastIndex=0,wrapQuotes($replace.call($replace.call(t,o,"\\$1"),/[\x00-\x1f]/g,lowbyte),"single",e)}function lowbyte(t){var e=t.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[e];return r?"\\"+r:"\\x"+(e<16?"0":"")+$toUpperCase.call(e.toString(16))}function markBoxed(t){return"Object("+t+")"}function weakCollectionOf(t){return t+" { ? }"}function collectionOf(t,e,r,n){return t+" ("+e+") {"+(n?indentedJoin(r,n):$join.call(r,", "))+"}"}function singleLineValues(t){for(var e=0;e=0)return!1;return!0}function getIndent(t,e){var r;if("\t"===t.indent)r="\t";else{if(!("number"==typeof t.indent&&t.indent>0))return null;r=$join.call(Array(t.indent+1)," ")}return{base:r,prev:$join.call(Array(e+1),r)}}function indentedJoin(t,e){if(0===t.length)return"";var r="\n"+e.prev+e.base;return r+$join.call(t,","+r)+"\n"+e.prev}function arrObjKeys(t,e){var r=isArray(t),n=[];if(r){n.length=t.length;for(var o=0;o -1) { + return val.split(','); + } + + if (options.throwOnLimitExceeded && currentArrayLength >= options.arrayLimit) { + throw new RangeError('Array limit exceeded. Only ' + options.arrayLimit + ' element' + (options.arrayLimit === 1 ? '' : 's') + ' allowed in an array.'); + } + + return val; +}; + +// This is what browsers will submit when the ✓ character occurs in an +// application/x-www-form-urlencoded body and the encoding of the page containing +// the form is iso-8859-1, or when the submitted form has an accept-charset +// attribute of iso-8859-1. Presumably also with other charsets that do not contain +// the ✓ character, such as us-ascii. +var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓') + +// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded. +var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓') + +var parseValues = function parseQueryStringValues(str, options) { + var obj = { __proto__: null }; + + var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; + cleanStr = cleanStr.replace(/%5B/gi, '[').replace(/%5D/gi, ']'); + + var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; + var parts = cleanStr.split( + options.delimiter, + options.throwOnLimitExceeded ? limit + 1 : limit + ); + + if (options.throwOnLimitExceeded && parts.length > limit) { + throw new RangeError('Parameter limit exceeded. Only ' + limit + ' parameter' + (limit === 1 ? '' : 's') + ' allowed.'); + } + + var skipIndex = -1; // Keep track of where the utf8 sentinel was found + var i; + + var charset = options.charset; + if (options.charsetSentinel) { + for (i = 0; i < parts.length; ++i) { + if (parts[i].indexOf('utf8=') === 0) { + if (parts[i] === charsetSentinel) { + charset = 'utf-8'; + } else if (parts[i] === isoSentinel) { + charset = 'iso-8859-1'; + } + skipIndex = i; + i = parts.length; // The eslint settings do not allow break; + } + } + } + + for (i = 0; i < parts.length; ++i) { + if (i === skipIndex) { + continue; + } + var part = parts[i]; + + var bracketEqualsPos = part.indexOf(']='); + var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; + + var key; + var val; + if (pos === -1) { + key = options.decoder(part, defaults.decoder, charset, 'key'); + val = options.strictNullHandling ? null : ''; + } else { + key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key'); + + val = utils.maybeMap( + parseArrayValue( + part.slice(pos + 1), + options, + isArray(obj[key]) ? obj[key].length : 0 + ), + function (encodedVal) { + return options.decoder(encodedVal, defaults.decoder, charset, 'value'); + } + ); + } + + if (val && options.interpretNumericEntities && charset === 'iso-8859-1') { + val = interpretNumericEntities(String(val)); + } + + if (part.indexOf('[]=') > -1) { + val = isArray(val) ? [val] : val; + } + + var existing = has.call(obj, key); + if (existing && options.duplicates === 'combine') { + obj[key] = utils.combine(obj[key], val); + } else if (!existing || options.duplicates === 'last') { + obj[key] = val; + } + } + + return obj; +}; + +var parseObject = function (chain, val, options, valuesParsed) { + var currentArrayLength = 0; + if (chain.length > 0 && chain[chain.length - 1] === '[]') { + var parentKey = chain.slice(0, -1).join(''); + currentArrayLength = Array.isArray(val) && val[parentKey] ? val[parentKey].length : 0; + } + + var leaf = valuesParsed ? val : parseArrayValue(val, options, currentArrayLength); + + for (var i = chain.length - 1; i >= 0; --i) { + var obj; + var root = chain[i]; + + if (root === '[]' && options.parseArrays) { + obj = options.allowEmptyArrays && (leaf === '' || (options.strictNullHandling && leaf === null)) + ? [] + : utils.combine([], leaf); + } else { + obj = options.plainObjects ? { __proto__: null } : {}; + var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; + var decodedRoot = options.decodeDotInKeys ? cleanRoot.replace(/%2E/g, '.') : cleanRoot; + var index = parseInt(decodedRoot, 10); + if (!options.parseArrays && decodedRoot === '') { + obj = { 0: leaf }; + } else if ( + !isNaN(index) + && root !== decodedRoot + && String(index) === decodedRoot + && index >= 0 + && (options.parseArrays && index <= options.arrayLimit) + ) { + obj = []; + obj[index] = leaf; + } else if (decodedRoot !== '__proto__') { + obj[decodedRoot] = leaf; + } + } + + leaf = obj; + } + + return leaf; +}; + +var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { + if (!givenKey) { + return; + } + + // Transform dot notation to bracket notation + var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; + + // The regex chunks + + var brackets = /(\[[^[\]]*])/; + var child = /(\[[^[\]]*])/g; + + // Get the parent + + var segment = options.depth > 0 && brackets.exec(key); + var parent = segment ? key.slice(0, segment.index) : key; + + // Stash the parent if it exists + + var keys = []; + if (parent) { + // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties + if (!options.plainObjects && has.call(Object.prototype, parent)) { + if (!options.allowPrototypes) { + return; + } + } + + keys.push(parent); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) { + i += 1; + if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { + if (!options.allowPrototypes) { + return; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, check strictDepth option for throw, else just add whatever is left + + if (segment) { + if (options.strictDepth === true) { + throw new RangeError('Input depth exceeded depth option of ' + options.depth + ' and strictDepth is true'); + } + keys.push('[' + key.slice(segment.index) + ']'); + } + + return parseObject(keys, val, options, valuesParsed); +}; + +var normalizeParseOptions = function normalizeParseOptions(opts) { + if (!opts) { + return defaults; + } + + if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') { + throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided'); + } + + if (typeof opts.decodeDotInKeys !== 'undefined' && typeof opts.decodeDotInKeys !== 'boolean') { + throw new TypeError('`decodeDotInKeys` option can only be `true` or `false`, when provided'); + } + + if (opts.decoder !== null && typeof opts.decoder !== 'undefined' && typeof opts.decoder !== 'function') { + throw new TypeError('Decoder has to be a function.'); + } + + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + + if (typeof opts.throwOnLimitExceeded !== 'undefined' && typeof opts.throwOnLimitExceeded !== 'boolean') { + throw new TypeError('`throwOnLimitExceeded` option must be a boolean'); + } + + var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; + + var duplicates = typeof opts.duplicates === 'undefined' ? defaults.duplicates : opts.duplicates; + + if (duplicates !== 'combine' && duplicates !== 'first' && duplicates !== 'last') { + throw new TypeError('The duplicates option must be either combine, first, or last'); + } + + var allowDots = typeof opts.allowDots === 'undefined' ? opts.decodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + + return { + allowDots: allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, + allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse, + arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, + decodeDotInKeys: typeof opts.decodeDotInKeys === 'boolean' ? opts.decodeDotInKeys : defaults.decodeDotInKeys, + decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, + delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, + // eslint-disable-next-line no-implicit-coercion, no-extra-parens + depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth, + duplicates: duplicates, + ignoreQueryPrefix: opts.ignoreQueryPrefix === true, + interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, + parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, + parseArrays: opts.parseArrays !== false, + plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, + strictDepth: typeof opts.strictDepth === 'boolean' ? !!opts.strictDepth : defaults.strictDepth, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling, + throwOnLimitExceeded: typeof opts.throwOnLimitExceeded === 'boolean' ? opts.throwOnLimitExceeded : false + }; +}; + +module.exports = function (str, opts) { + var options = normalizeParseOptions(opts); + + if (str === '' || str === null || typeof str === 'undefined') { + return options.plainObjects ? { __proto__: null } : {}; + } + + var tempObj = typeof str === 'string' ? parseValues(str, options) : str; + var obj = options.plainObjects ? { __proto__: null } : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string'); + obj = utils.merge(obj, newObj, options); + } + + if (options.allowSparse === true) { + return obj; + } + + return utils.compact(obj); +}; diff --git a/node_modules/qs/lib/stringify.js b/node_modules/qs/lib/stringify.js new file mode 100644 index 0000000..2666eaf --- /dev/null +++ b/node_modules/qs/lib/stringify.js @@ -0,0 +1,356 @@ +'use strict'; + +var getSideChannel = require('side-channel'); +var utils = require('./utils'); +var formats = require('./formats'); +var has = Object.prototype.hasOwnProperty; + +var arrayPrefixGenerators = { + brackets: function brackets(prefix) { + return prefix + '[]'; + }, + comma: 'comma', + indices: function indices(prefix, key) { + return prefix + '[' + key + ']'; + }, + repeat: function repeat(prefix) { + return prefix; + } +}; + +var isArray = Array.isArray; +var push = Array.prototype.push; +var pushToArray = function (arr, valueOrArray) { + push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); +}; + +var toISO = Date.prototype.toISOString; + +var defaultFormat = formats['default']; +var defaults = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: 'indices', + charset: 'utf-8', + charsetSentinel: false, + commaRoundTrip: false, + delimiter: '&', + encode: true, + encodeDotInKeys: false, + encoder: utils.encode, + encodeValuesOnly: false, + filter: void undefined, + format: defaultFormat, + formatter: formats.formatters[defaultFormat], + // deprecated + indices: false, + serializeDate: function serializeDate(date) { + return toISO.call(date); + }, + skipNulls: false, + strictNullHandling: false +}; + +var isNonNullishPrimitive = function isNonNullishPrimitive(v) { + return typeof v === 'string' + || typeof v === 'number' + || typeof v === 'boolean' + || typeof v === 'symbol' + || typeof v === 'bigint'; +}; + +var sentinel = {}; + +var stringify = function stringify( + object, + prefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + sideChannel +) { + var obj = object; + + var tmpSc = sideChannel; + var step = 0; + var findFlag = false; + while ((tmpSc = tmpSc.get(sentinel)) !== void undefined && !findFlag) { + // Where object last appeared in the ref tree + var pos = tmpSc.get(object); + step += 1; + if (typeof pos !== 'undefined') { + if (pos === step) { + throw new RangeError('Cyclic object value'); + } else { + findFlag = true; // Break while + } + } + if (typeof tmpSc.get(sentinel) === 'undefined') { + step = 0; + } + } + + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate(obj); + } else if (generateArrayPrefix === 'comma' && isArray(obj)) { + obj = utils.maybeMap(obj, function (value) { + if (value instanceof Date) { + return serializeDate(value); + } + return value; + }); + } + + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix; + } + + obj = ''; + } + + if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { + if (encoder) { + var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format); + return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))]; + } + return [formatter(prefix) + '=' + formatter(String(obj))]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys; + if (generateArrayPrefix === 'comma' && isArray(obj)) { + // we need to join elements in + if (encodeValuesOnly && encoder) { + obj = utils.maybeMap(obj, encoder); + } + objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; + } else if (isArray(filter)) { + objKeys = filter; + } else { + var keys = Object.keys(obj); + objKeys = sort ? keys.sort(sort) : keys; + } + + var encodedPrefix = encodeDotInKeys ? String(prefix).replace(/\./g, '%2E') : String(prefix); + + var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encodedPrefix + '[]' : encodedPrefix; + + if (allowEmptyArrays && isArray(obj) && obj.length === 0) { + return adjustedPrefix + '[]'; + } + + for (var j = 0; j < objKeys.length; ++j) { + var key = objKeys[j]; + var value = typeof key === 'object' && key && typeof key.value !== 'undefined' + ? key.value + : obj[key]; + + if (skipNulls && value === null) { + continue; + } + + var encodedKey = allowDots && encodeDotInKeys ? String(key).replace(/\./g, '%2E') : String(key); + var keyPrefix = isArray(obj) + ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, encodedKey) : adjustedPrefix + : adjustedPrefix + (allowDots ? '.' + encodedKey : '[' + encodedKey + ']'); + + sideChannel.set(object, step); + var valueSideChannel = getSideChannel(); + valueSideChannel.set(sentinel, sideChannel); + pushToArray(values, stringify( + value, + keyPrefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + generateArrayPrefix === 'comma' && encodeValuesOnly && isArray(obj) ? null : encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); + } + + return values; +}; + +var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { + if (!opts) { + return defaults; + } + + if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') { + throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided'); + } + + if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') { + throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided'); + } + + if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { + throw new TypeError('Encoder has to be a function.'); + } + + var charset = opts.charset || defaults.charset; + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + + var format = formats['default']; + if (typeof opts.format !== 'undefined') { + if (!has.call(formats.formatters, opts.format)) { + throw new TypeError('Unknown format option provided.'); + } + format = opts.format; + } + var formatter = formats.formatters[format]; + + var filter = defaults.filter; + if (typeof opts.filter === 'function' || isArray(opts.filter)) { + filter = opts.filter; + } + + var arrayFormat; + if (opts.arrayFormat in arrayPrefixGenerators) { + arrayFormat = opts.arrayFormat; + } else if ('indices' in opts) { + arrayFormat = opts.indices ? 'indices' : 'repeat'; + } else { + arrayFormat = defaults.arrayFormat; + } + + if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { + throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); + } + + var allowDots = typeof opts.allowDots === 'undefined' ? opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + + return { + addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, + allowDots: allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + arrayFormat: arrayFormat, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys, + encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter: filter, + format: format, + formatter: formatter, + serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, + sort: typeof opts.sort === 'function' ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; + +module.exports = function (object, opts) { + var obj = object; + var options = normalizeStringifyOptions(opts); + + var objKeys; + var filter; + + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } else if (isArray(options.filter)) { + filter = options.filter; + objKeys = filter; + } + + var keys = []; + + if (typeof obj !== 'object' || obj === null) { + return ''; + } + + var generateArrayPrefix = arrayPrefixGenerators[options.arrayFormat]; + var commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip; + + if (!objKeys) { + objKeys = Object.keys(obj); + } + + if (options.sort) { + objKeys.sort(options.sort); + } + + var sideChannel = getSideChannel(); + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + var value = obj[key]; + + if (options.skipNulls && value === null) { + continue; + } + pushToArray(keys, stringify( + value, + key, + generateArrayPrefix, + commaRoundTrip, + options.allowEmptyArrays, + options.strictNullHandling, + options.skipNulls, + options.encodeDotInKeys, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); + } + + var joined = keys.join(options.delimiter); + var prefix = options.addQueryPrefix === true ? '?' : ''; + + if (options.charsetSentinel) { + if (options.charset === 'iso-8859-1') { + // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark + prefix += 'utf8=%26%2310003%3B&'; + } else { + // encodeURIComponent('✓') + prefix += 'utf8=%E2%9C%93&'; + } + } + + return joined.length > 0 ? prefix + joined : ''; +}; diff --git a/node_modules/qs/lib/utils.js b/node_modules/qs/lib/utils.js new file mode 100644 index 0000000..2905ff0 --- /dev/null +++ b/node_modules/qs/lib/utils.js @@ -0,0 +1,268 @@ +'use strict'; + +var formats = require('./formats'); + +var has = Object.prototype.hasOwnProperty; +var isArray = Array.isArray; + +var hexTable = (function () { + var array = []; + for (var i = 0; i < 256; ++i) { + array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + } + + return array; +}()); + +var compactQueue = function compactQueue(queue) { + while (queue.length > 1) { + var item = queue.pop(); + var obj = item.obj[item.prop]; + + if (isArray(obj)) { + var compacted = []; + + for (var j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== 'undefined') { + compacted.push(obj[j]); + } + } + + item.obj[item.prop] = compacted; + } + } +}; + +var arrayToObject = function arrayToObject(source, options) { + var obj = options && options.plainObjects ? { __proto__: null } : {}; + for (var i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; + } + } + + return obj; +}; + +var merge = function merge(target, source, options) { + /* eslint no-param-reassign: 0 */ + if (!source) { + return target; + } + + if (typeof source !== 'object' && typeof source !== 'function') { + if (isArray(target)) { + target.push(source); + } else if (target && typeof target === 'object') { + if ( + (options && (options.plainObjects || options.allowPrototypes)) + || !has.call(Object.prototype, source) + ) { + target[source] = true; + } + } else { + return [target, source]; + } + + return target; + } + + if (!target || typeof target !== 'object') { + return [target].concat(source); + } + + var mergeTarget = target; + if (isArray(target) && !isArray(source)) { + mergeTarget = arrayToObject(target, options); + } + + if (isArray(target) && isArray(source)) { + source.forEach(function (item, i) { + if (has.call(target, i)) { + var targetItem = target[i]; + if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { + target[i] = merge(targetItem, item, options); + } else { + target.push(item); + } + } else { + target[i] = item; + } + }); + return target; + } + + return Object.keys(source).reduce(function (acc, key) { + var value = source[key]; + + if (has.call(acc, key)) { + acc[key] = merge(acc[key], value, options); + } else { + acc[key] = value; + } + return acc; + }, mergeTarget); +}; + +var assign = function assignSingleSource(target, source) { + return Object.keys(source).reduce(function (acc, key) { + acc[key] = source[key]; + return acc; + }, target); +}; + +var decode = function (str, defaultDecoder, charset) { + var strWithoutPlus = str.replace(/\+/g, ' '); + if (charset === 'iso-8859-1') { + // unescape never throws, no try...catch needed: + return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); + } + // utf-8 + try { + return decodeURIComponent(strWithoutPlus); + } catch (e) { + return strWithoutPlus; + } +}; + +var limit = 1024; + +/* eslint operator-linebreak: [2, "before"] */ + +var encode = function encode(str, defaultEncoder, charset, kind, format) { + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + var string = str; + if (typeof str === 'symbol') { + string = Symbol.prototype.toString.call(str); + } else if (typeof str !== 'string') { + string = String(str); + } + + if (charset === 'iso-8859-1') { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { + return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; + }); + } + + var out = ''; + for (var j = 0; j < string.length; j += limit) { + var segment = string.length >= limit ? string.slice(j, j + limit) : string; + var arr = []; + + for (var i = 0; i < segment.length; ++i) { + var c = segment.charCodeAt(i); + if ( + c === 0x2D // - + || c === 0x2E // . + || c === 0x5F // _ + || c === 0x7E // ~ + || (c >= 0x30 && c <= 0x39) // 0-9 + || (c >= 0x41 && c <= 0x5A) // a-z + || (c >= 0x61 && c <= 0x7A) // A-Z + || (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( ) + ) { + arr[arr.length] = segment.charAt(i); + continue; + } + + if (c < 0x80) { + arr[arr.length] = hexTable[c]; + continue; + } + + if (c < 0x800) { + arr[arr.length] = hexTable[0xC0 | (c >> 6)] + + hexTable[0x80 | (c & 0x3F)]; + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + arr[arr.length] = hexTable[0xE0 | (c >> 12)] + + hexTable[0x80 | ((c >> 6) & 0x3F)] + + hexTable[0x80 | (c & 0x3F)]; + continue; + } + + i += 1; + c = 0x10000 + (((c & 0x3FF) << 10) | (segment.charCodeAt(i) & 0x3FF)); + + arr[arr.length] = hexTable[0xF0 | (c >> 18)] + + hexTable[0x80 | ((c >> 12) & 0x3F)] + + hexTable[0x80 | ((c >> 6) & 0x3F)] + + hexTable[0x80 | (c & 0x3F)]; + } + + out += arr.join(''); + } + + return out; +}; + +var compact = function compact(value) { + var queue = [{ obj: { o: value }, prop: 'o' }]; + var refs = []; + + for (var i = 0; i < queue.length; ++i) { + var item = queue[i]; + var obj = item.obj[item.prop]; + + var keys = Object.keys(obj); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + var val = obj[key]; + if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { + queue.push({ obj: obj, prop: key }); + refs.push(val); + } + } + } + + compactQueue(queue); + + return value; +}; + +var isRegExp = function isRegExp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + +var isBuffer = function isBuffer(obj) { + if (!obj || typeof obj !== 'object') { + return false; + } + + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +}; + +var combine = function combine(a, b) { + return [].concat(a, b); +}; + +var maybeMap = function maybeMap(val, fn) { + if (isArray(val)) { + var mapped = []; + for (var i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i])); + } + return mapped; + } + return fn(val); +}; + +module.exports = { + arrayToObject: arrayToObject, + assign: assign, + combine: combine, + compact: compact, + decode: decode, + encode: encode, + isBuffer: isBuffer, + isRegExp: isRegExp, + maybeMap: maybeMap, + merge: merge +}; diff --git a/node_modules/qs/package.json b/node_modules/qs/package.json new file mode 100644 index 0000000..e4144d0 --- /dev/null +++ b/node_modules/qs/package.json @@ -0,0 +1,93 @@ +{ + "name": "qs", + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "homepage": "https://github.com/ljharb/qs", + "version": "6.14.0", + "repository": { + "type": "git", + "url": "https://github.com/ljharb/qs.git" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "main": "lib/index.js", + "sideEffects": false, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "keywords": [ + "querystring", + "qs", + "query", + "url", + "parse", + "stringify" + ], + "engines": { + "node": ">=0.6" + }, + "dependencies": { + "side-channel": "^1.1.0" + }, + "devDependencies": { + "@browserify/envify": "^6.0.0", + "@browserify/uglifyify": "^6.0.0", + "@ljharb/eslint-config": "^21.1.1", + "browserify": "^16.5.2", + "bundle-collapser": "^1.4.0", + "common-shakeify": "~1.0.0", + "eclint": "^2.8.1", + "es-value-fixtures": "^1.7.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "glob": "=10.3.7", + "has-bigints": "^1.1.0", + "has-override-mistake": "^1.0.1", + "has-property-descriptors": "^1.0.2", + "has-proto": "^1.2.0", + "has-symbols": "^1.1.0", + "iconv-lite": "^0.5.1", + "in-publish": "^2.0.1", + "jackspeak": "=2.1.1", + "mkdirp": "^0.5.5", + "mock-property": "^1.1.0", + "module-deps": "^6.2.3", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.3", + "qs-iconv": "^1.0.4", + "safe-publish-latest": "^2.0.0", + "safer-buffer": "^2.1.2", + "tape": "^5.9.0", + "unassertify": "^3.0.1" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated && npm run dist", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run --silent readme && npm run --silent lint", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/**/*.js'", + "posttest": "npx npm@'>=10.2' audit --production", + "readme": "evalmd README.md", + "postlint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git' | grep -v dist/)", + "lint": "eslint --ext=js,mjs .", + "dist": "mkdirp dist && browserify --standalone Qs -g unassertify -g @browserify/envify -g [@browserify/uglifyify --mangle.keep_fnames --compress.keep_fnames --format.indent_level=1 --compress.arrows=false --compress.passes=4 --compress.typeofs=false] -p common-shakeify -p bundle-collapser/plugin lib/index.js > dist/qs.js" + }, + "license": "BSD-3-Clause", + "publishConfig": { + "ignore": [ + "!dist/*", + "bower.json", + "component.json", + ".github/workflows", + "logos", + "tea.yaml" + ] + } +} diff --git a/node_modules/qs/test/empty-keys-cases.js b/node_modules/qs/test/empty-keys-cases.js new file mode 100644 index 0000000..2b1190e --- /dev/null +++ b/node_modules/qs/test/empty-keys-cases.js @@ -0,0 +1,267 @@ +'use strict'; + +module.exports = { + emptyTestCases: [ + { + input: '&', + withEmptyKeys: {}, + stringifyOutput: { + brackets: '', + indices: '', + repeat: '' + }, + noEmptyKeys: {} + }, + { + input: '&&', + withEmptyKeys: {}, + stringifyOutput: { + brackets: '', + indices: '', + repeat: '' + }, + noEmptyKeys: {} + }, + { + input: '&=', + withEmptyKeys: { '': '' }, + stringifyOutput: { + brackets: '=', + indices: '=', + repeat: '=' + }, + noEmptyKeys: {} + }, + { + input: '&=&', + withEmptyKeys: { '': '' }, + stringifyOutput: { + brackets: '=', + indices: '=', + repeat: '=' + }, + noEmptyKeys: {} + }, + { + input: '&=&=', + withEmptyKeys: { '': ['', ''] }, + stringifyOutput: { + brackets: '[]=&[]=', + indices: '[0]=&[1]=', + repeat: '=&=' + }, + noEmptyKeys: {} + }, + { + input: '&=&=&', + withEmptyKeys: { '': ['', ''] }, + stringifyOutput: { + brackets: '[]=&[]=', + indices: '[0]=&[1]=', + repeat: '=&=' + }, + noEmptyKeys: {} + }, + { + input: '=', + withEmptyKeys: { '': '' }, + noEmptyKeys: {}, + stringifyOutput: { + brackets: '=', + indices: '=', + repeat: '=' + } + }, + { + input: '=&', + withEmptyKeys: { '': '' }, + stringifyOutput: { + brackets: '=', + indices: '=', + repeat: '=' + }, + noEmptyKeys: {} + }, + { + input: '=&&&', + withEmptyKeys: { '': '' }, + stringifyOutput: { + brackets: '=', + indices: '=', + repeat: '=' + }, + noEmptyKeys: {} + }, + { + input: '=&=&=&', + withEmptyKeys: { '': ['', '', ''] }, + stringifyOutput: { + brackets: '[]=&[]=&[]=', + indices: '[0]=&[1]=&[2]=', + repeat: '=&=&=' + }, + noEmptyKeys: {} + }, + { + input: '=&a[]=b&a[1]=c', + withEmptyKeys: { '': '', a: ['b', 'c'] }, + stringifyOutput: { + brackets: '=&a[]=b&a[]=c', + indices: '=&a[0]=b&a[1]=c', + repeat: '=&a=b&a=c' + }, + noEmptyKeys: { a: ['b', 'c'] } + }, + { + input: '=a', + withEmptyKeys: { '': 'a' }, + noEmptyKeys: {}, + stringifyOutput: { + brackets: '=a', + indices: '=a', + repeat: '=a' + } + }, + { + input: 'a==a', + withEmptyKeys: { a: '=a' }, + noEmptyKeys: { a: '=a' }, + stringifyOutput: { + brackets: 'a==a', + indices: 'a==a', + repeat: 'a==a' + } + }, + { + input: '=&a[]=b', + withEmptyKeys: { '': '', a: ['b'] }, + stringifyOutput: { + brackets: '=&a[]=b', + indices: '=&a[0]=b', + repeat: '=&a=b' + }, + noEmptyKeys: { a: ['b'] } + }, + { + input: '=&a[]=b&a[]=c&a[2]=d', + withEmptyKeys: { '': '', a: ['b', 'c', 'd'] }, + stringifyOutput: { + brackets: '=&a[]=b&a[]=c&a[]=d', + indices: '=&a[0]=b&a[1]=c&a[2]=d', + repeat: '=&a=b&a=c&a=d' + }, + noEmptyKeys: { a: ['b', 'c', 'd'] } + }, + { + input: '=a&=b', + withEmptyKeys: { '': ['a', 'b'] }, + stringifyOutput: { + brackets: '[]=a&[]=b', + indices: '[0]=a&[1]=b', + repeat: '=a&=b' + }, + noEmptyKeys: {} + }, + { + input: '=a&foo=b', + withEmptyKeys: { '': 'a', foo: 'b' }, + noEmptyKeys: { foo: 'b' }, + stringifyOutput: { + brackets: '=a&foo=b', + indices: '=a&foo=b', + repeat: '=a&foo=b' + } + }, + { + input: 'a[]=b&a=c&=', + withEmptyKeys: { '': '', a: ['b', 'c'] }, + stringifyOutput: { + brackets: '=&a[]=b&a[]=c', + indices: '=&a[0]=b&a[1]=c', + repeat: '=&a=b&a=c' + }, + noEmptyKeys: { a: ['b', 'c'] } + }, + { + input: 'a[]=b&a=c&=', + withEmptyKeys: { '': '', a: ['b', 'c'] }, + stringifyOutput: { + brackets: '=&a[]=b&a[]=c', + indices: '=&a[0]=b&a[1]=c', + repeat: '=&a=b&a=c' + }, + noEmptyKeys: { a: ['b', 'c'] } + }, + { + input: 'a[0]=b&a=c&=', + withEmptyKeys: { '': '', a: ['b', 'c'] }, + stringifyOutput: { + brackets: '=&a[]=b&a[]=c', + indices: '=&a[0]=b&a[1]=c', + repeat: '=&a=b&a=c' + }, + noEmptyKeys: { a: ['b', 'c'] } + }, + { + input: 'a=b&a[]=c&=', + withEmptyKeys: { '': '', a: ['b', 'c'] }, + stringifyOutput: { + brackets: '=&a[]=b&a[]=c', + indices: '=&a[0]=b&a[1]=c', + repeat: '=&a=b&a=c' + }, + noEmptyKeys: { a: ['b', 'c'] } + }, + { + input: 'a=b&a[0]=c&=', + withEmptyKeys: { '': '', a: ['b', 'c'] }, + stringifyOutput: { + brackets: '=&a[]=b&a[]=c', + indices: '=&a[0]=b&a[1]=c', + repeat: '=&a=b&a=c' + }, + noEmptyKeys: { a: ['b', 'c'] } + }, + { + input: '[]=a&[]=b& []=1', + withEmptyKeys: { '': ['a', 'b'], ' ': ['1'] }, + stringifyOutput: { + brackets: '[]=a&[]=b& []=1', + indices: '[0]=a&[1]=b& [0]=1', + repeat: '=a&=b& =1' + }, + noEmptyKeys: { 0: 'a', 1: 'b', ' ': ['1'] } + }, + { + input: '[0]=a&[1]=b&a[0]=1&a[1]=2', + withEmptyKeys: { '': ['a', 'b'], a: ['1', '2'] }, + noEmptyKeys: { 0: 'a', 1: 'b', a: ['1', '2'] }, + stringifyOutput: { + brackets: '[]=a&[]=b&a[]=1&a[]=2', + indices: '[0]=a&[1]=b&a[0]=1&a[1]=2', + repeat: '=a&=b&a=1&a=2' + } + }, + { + input: '[deep]=a&[deep]=2', + withEmptyKeys: { '': { deep: ['a', '2'] } + }, + stringifyOutput: { + brackets: '[deep][]=a&[deep][]=2', + indices: '[deep][0]=a&[deep][1]=2', + repeat: '[deep]=a&[deep]=2' + }, + noEmptyKeys: { deep: ['a', '2'] } + }, + { + input: '%5B0%5D=a&%5B1%5D=b', + withEmptyKeys: { '': ['a', 'b'] }, + stringifyOutput: { + brackets: '[]=a&[]=b', + indices: '[0]=a&[1]=b', + repeat: '=a&=b' + }, + noEmptyKeys: { 0: 'a', 1: 'b' } + } + ] +}; diff --git a/node_modules/qs/test/parse.js b/node_modules/qs/test/parse.js new file mode 100644 index 0000000..32cdfd8 --- /dev/null +++ b/node_modules/qs/test/parse.js @@ -0,0 +1,1276 @@ +'use strict'; + +var test = require('tape'); +var hasPropertyDescriptors = require('has-property-descriptors')(); +var iconv = require('iconv-lite'); +var mockProperty = require('mock-property'); +var hasOverrideMistake = require('has-override-mistake')(); +var SaferBuffer = require('safer-buffer').Buffer; +var v = require('es-value-fixtures'); +var inspect = require('object-inspect'); +var emptyTestCases = require('./empty-keys-cases').emptyTestCases; +var hasProto = require('has-proto')(); + +var qs = require('../'); +var utils = require('../lib/utils'); + +test('parse()', function (t) { + t.test('parses a simple string', function (st) { + st.deepEqual(qs.parse('0=foo'), { 0: 'foo' }); + st.deepEqual(qs.parse('foo=c++'), { foo: 'c ' }); + st.deepEqual(qs.parse('a[>=]=23'), { a: { '>=': '23' } }); + st.deepEqual(qs.parse('a[<=>]==23'), { a: { '<=>': '=23' } }); + st.deepEqual(qs.parse('a[==]=23'), { a: { '==': '23' } }); + st.deepEqual(qs.parse('foo', { strictNullHandling: true }), { foo: null }); + st.deepEqual(qs.parse('foo'), { foo: '' }); + st.deepEqual(qs.parse('foo='), { foo: '' }); + st.deepEqual(qs.parse('foo=bar'), { foo: 'bar' }); + st.deepEqual(qs.parse(' foo = bar = baz '), { ' foo ': ' bar = baz ' }); + st.deepEqual(qs.parse('foo=bar=baz'), { foo: 'bar=baz' }); + st.deepEqual(qs.parse('foo=bar&bar=baz'), { foo: 'bar', bar: 'baz' }); + st.deepEqual(qs.parse('foo2=bar2&baz2='), { foo2: 'bar2', baz2: '' }); + st.deepEqual(qs.parse('foo=bar&baz', { strictNullHandling: true }), { foo: 'bar', baz: null }); + st.deepEqual(qs.parse('foo=bar&baz'), { foo: 'bar', baz: '' }); + st.deepEqual(qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World'), { + cht: 'p3', + chd: 't:60,40', + chs: '250x100', + chl: 'Hello|World' + }); + st.end(); + }); + + t.test('comma: false', function (st) { + st.deepEqual(qs.parse('a[]=b&a[]=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[0]=b&a[1]=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b,c'), { a: 'b,c' }); + st.deepEqual(qs.parse('a=b&a=c'), { a: ['b', 'c'] }); + st.end(); + }); + + t.test('comma: true', function (st) { + st.deepEqual(qs.parse('a[]=b&a[]=c', { comma: true }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { comma: true }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b,c', { comma: true }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b&a=c', { comma: true }), { a: ['b', 'c'] }); + st.end(); + }); + + t.test('allows enabling dot notation', function (st) { + st.deepEqual(qs.parse('a.b=c'), { 'a.b': 'c' }); + st.deepEqual(qs.parse('a.b=c', { allowDots: true }), { a: { b: 'c' } }); + + st.end(); + }); + + t.test('decode dot keys correctly', function (st) { + st.deepEqual( + qs.parse('name%252Eobj.first=John&name%252Eobj.last=Doe', { allowDots: false, decodeDotInKeys: false }), + { 'name%2Eobj.first': 'John', 'name%2Eobj.last': 'Doe' }, + 'with allowDots false and decodeDotInKeys false' + ); + st.deepEqual( + qs.parse('name.obj.first=John&name.obj.last=Doe', { allowDots: true, decodeDotInKeys: false }), + { name: { obj: { first: 'John', last: 'Doe' } } }, + 'with allowDots false and decodeDotInKeys false' + ); + st.deepEqual( + qs.parse('name%252Eobj.first=John&name%252Eobj.last=Doe', { allowDots: true, decodeDotInKeys: false }), + { 'name%2Eobj': { first: 'John', last: 'Doe' } }, + 'with allowDots true and decodeDotInKeys false' + ); + st.deepEqual( + qs.parse('name%252Eobj.first=John&name%252Eobj.last=Doe', { allowDots: true, decodeDotInKeys: true }), + { 'name.obj': { first: 'John', last: 'Doe' } }, + 'with allowDots true and decodeDotInKeys true' + ); + + st.deepEqual( + qs.parse( + 'name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe', + { allowDots: false, decodeDotInKeys: false } + ), + { 'name%2Eobj%2Esubobject.first%2Egodly%2Ename': 'John', 'name%2Eobj%2Esubobject.last': 'Doe' }, + 'with allowDots false and decodeDotInKeys false' + ); + st.deepEqual( + qs.parse( + 'name.obj.subobject.first.godly.name=John&name.obj.subobject.last=Doe', + { allowDots: true, decodeDotInKeys: false } + ), + { name: { obj: { subobject: { first: { godly: { name: 'John' } }, last: 'Doe' } } } }, + 'with allowDots true and decodeDotInKeys false' + ); + st.deepEqual( + qs.parse( + 'name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe', + { allowDots: true, decodeDotInKeys: true } + ), + { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, + 'with allowDots true and decodeDotInKeys true' + ); + st.deepEqual( + qs.parse('name%252Eobj.first=John&name%252Eobj.last=Doe'), + { 'name%2Eobj.first': 'John', 'name%2Eobj.last': 'Doe' }, + 'with allowDots and decodeDotInKeys undefined' + ); + + st.end(); + }); + + t.test('decodes dot in key of object, and allow enabling dot notation when decodeDotInKeys is set to true and allowDots is undefined', function (st) { + st.deepEqual( + qs.parse( + 'name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe', + { decodeDotInKeys: true } + ), + { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, + 'with allowDots undefined and decodeDotInKeys true' + ); + + st.end(); + }); + + t.test('throws when decodeDotInKeys is not of type boolean', function (st) { + st['throws']( + function () { qs.parse('foo[]&bar=baz', { decodeDotInKeys: 'foobar' }); }, + TypeError + ); + + st['throws']( + function () { qs.parse('foo[]&bar=baz', { decodeDotInKeys: 0 }); }, + TypeError + ); + st['throws']( + function () { qs.parse('foo[]&bar=baz', { decodeDotInKeys: NaN }); }, + TypeError + ); + + st['throws']( + function () { qs.parse('foo[]&bar=baz', { decodeDotInKeys: null }); }, + TypeError + ); + + st.end(); + }); + + t.test('allows empty arrays in obj values', function (st) { + st.deepEqual(qs.parse('foo[]&bar=baz', { allowEmptyArrays: true }), { foo: [], bar: 'baz' }); + st.deepEqual(qs.parse('foo[]&bar=baz', { allowEmptyArrays: false }), { foo: [''], bar: 'baz' }); + + st.end(); + }); + + t.test('throws when allowEmptyArrays is not of type boolean', function (st) { + st['throws']( + function () { qs.parse('foo[]&bar=baz', { allowEmptyArrays: 'foobar' }); }, + TypeError + ); + + st['throws']( + function () { qs.parse('foo[]&bar=baz', { allowEmptyArrays: 0 }); }, + TypeError + ); + st['throws']( + function () { qs.parse('foo[]&bar=baz', { allowEmptyArrays: NaN }); }, + TypeError + ); + + st['throws']( + function () { qs.parse('foo[]&bar=baz', { allowEmptyArrays: null }); }, + TypeError + ); + + st.end(); + }); + + t.test('allowEmptyArrays + strictNullHandling', function (st) { + st.deepEqual( + qs.parse('testEmptyArray[]', { strictNullHandling: true, allowEmptyArrays: true }), + { testEmptyArray: [] } + ); + + st.end(); + }); + + t.deepEqual(qs.parse('a[b]=c'), { a: { b: 'c' } }, 'parses a single nested string'); + t.deepEqual(qs.parse('a[b][c]=d'), { a: { b: { c: 'd' } } }, 'parses a double nested string'); + t.deepEqual( + qs.parse('a[b][c][d][e][f][g][h]=i'), + { a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } }, + 'defaults to a depth of 5' + ); + + t.test('only parses one level when depth = 1', function (st) { + st.deepEqual(qs.parse('a[b][c]=d', { depth: 1 }), { a: { b: { '[c]': 'd' } } }); + st.deepEqual(qs.parse('a[b][c][d]=e', { depth: 1 }), { a: { b: { '[c][d]': 'e' } } }); + st.end(); + }); + + t.test('uses original key when depth = 0', function (st) { + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { depth: 0 }), { 'a[0]': 'b', 'a[1]': 'c' }); + st.deepEqual(qs.parse('a[0][0]=b&a[0][1]=c&a[1]=d&e=2', { depth: 0 }), { 'a[0][0]': 'b', 'a[0][1]': 'c', 'a[1]': 'd', e: '2' }); + st.end(); + }); + + t.test('uses original key when depth = false', function (st) { + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { depth: false }), { 'a[0]': 'b', 'a[1]': 'c' }); + st.deepEqual(qs.parse('a[0][0]=b&a[0][1]=c&a[1]=d&e=2', { depth: false }), { 'a[0][0]': 'b', 'a[0][1]': 'c', 'a[1]': 'd', e: '2' }); + st.end(); + }); + + t.deepEqual(qs.parse('a=b&a=c'), { a: ['b', 'c'] }, 'parses a simple array'); + + t.test('parses an explicit array', function (st) { + st.deepEqual(qs.parse('a[]=b'), { a: ['b'] }); + st.deepEqual(qs.parse('a[]=b&a[]=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a[]=c&a[]=d'), { a: ['b', 'c', 'd'] }); + st.end(); + }); + + t.test('parses a mix of simple and explicit arrays', function (st) { + st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[0]=b&a=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b&a[0]=c'), { a: ['b', 'c'] }); + + st.deepEqual(qs.parse('a[1]=b&a=c', { arrayLimit: 20 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a=c', { arrayLimit: 0 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] }); + + st.deepEqual(qs.parse('a=b&a[1]=c', { arrayLimit: 20 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b&a[]=c', { arrayLimit: 0 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] }); + + st.end(); + }); + + t.test('parses a nested array', function (st) { + st.deepEqual(qs.parse('a[b][]=c&a[b][]=d'), { a: { b: ['c', 'd'] } }); + st.deepEqual(qs.parse('a[>=]=25'), { a: { '>=': '25' } }); + st.end(); + }); + + t.test('allows to specify array indices', function (st) { + st.deepEqual(qs.parse('a[1]=c&a[0]=b&a[2]=d'), { a: ['b', 'c', 'd'] }); + st.deepEqual(qs.parse('a[1]=c&a[0]=b'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[1]=c', { arrayLimit: 20 }), { a: ['c'] }); + st.deepEqual(qs.parse('a[1]=c', { arrayLimit: 0 }), { a: { 1: 'c' } }); + st.deepEqual(qs.parse('a[1]=c'), { a: ['c'] }); + st.end(); + }); + + t.test('limits specific array indices to arrayLimit', function (st) { + st.deepEqual(qs.parse('a[20]=a', { arrayLimit: 20 }), { a: ['a'] }); + st.deepEqual(qs.parse('a[21]=a', { arrayLimit: 20 }), { a: { 21: 'a' } }); + + st.deepEqual(qs.parse('a[20]=a'), { a: ['a'] }); + st.deepEqual(qs.parse('a[21]=a'), { a: { 21: 'a' } }); + st.end(); + }); + + t.deepEqual(qs.parse('a[12b]=c'), { a: { '12b': 'c' } }, 'supports keys that begin with a number'); + + t.test('supports encoded = signs', function (st) { + st.deepEqual(qs.parse('he%3Dllo=th%3Dere'), { 'he=llo': 'th=ere' }); + st.end(); + }); + + t.test('is ok with url encoded strings', function (st) { + st.deepEqual(qs.parse('a[b%20c]=d'), { a: { 'b c': 'd' } }); + st.deepEqual(qs.parse('a[b]=c%20d'), { a: { b: 'c d' } }); + st.end(); + }); + + t.test('allows brackets in the value', function (st) { + st.deepEqual(qs.parse('pets=["tobi"]'), { pets: '["tobi"]' }); + st.deepEqual(qs.parse('operators=[">=", "<="]'), { operators: '[">=", "<="]' }); + st.end(); + }); + + t.test('allows empty values', function (st) { + st.deepEqual(qs.parse(''), {}); + st.deepEqual(qs.parse(null), {}); + st.deepEqual(qs.parse(undefined), {}); + st.end(); + }); + + t.test('transforms arrays to objects', function (st) { + st.deepEqual(qs.parse('foo[0]=bar&foo[bad]=baz'), { foo: { 0: 'bar', bad: 'baz' } }); + st.deepEqual(qs.parse('foo[bad]=baz&foo[0]=bar'), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar'), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo[]=bar&foo[bad]=baz'), { foo: { 0: 'bar', bad: 'baz' } }); + st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo'), { foo: { bad: 'baz', 0: 'bar', 1: 'foo' } }); + st.deepEqual(qs.parse('foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb'), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + + st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: false }), { a: { 0: 'b', t: 'u' } }); + st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: true }), { a: { 0: 'b', t: 'u', hasOwnProperty: 'c' } }); + st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: false }), { a: { 0: 'b', x: 'y' } }); + st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: true }), { a: { 0: 'b', hasOwnProperty: 'c', x: 'y' } }); + st.end(); + }); + + t.test('transforms arrays to objects (dot notation)', function (st) { + st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: 'baz' } }); + st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad.boo=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: { boo: 'baz' } } }); + st.deepEqual(qs.parse('foo[0][0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [[{ baz: 'bar' }]], fool: { bad: 'baz' } }); + st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15'], bar: '2' }] }); + st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].baz[1]=16&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15', '16'], bar: '2' }] }); + st.deepEqual(qs.parse('foo.bad=baz&foo[0]=bar', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo[]=bar&foo.bad=baz', { allowDots: true }), { foo: { 0: 'bar', bad: 'baz' } }); + st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar&foo[]=foo', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar', 1: 'foo' } }); + st.deepEqual(qs.parse('foo[0].a=a&foo[0].b=b&foo[1].a=aa&foo[1].b=bb', { allowDots: true }), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + st.end(); + }); + + t.test('correctly prunes undefined values when converting an array to an object', function (st) { + st.deepEqual(qs.parse('a[2]=b&a[99999999]=c'), { a: { 2: 'b', 99999999: 'c' } }); + st.end(); + }); + + t.test('supports malformed uri characters', function (st) { + st.deepEqual(qs.parse('{%:%}', { strictNullHandling: true }), { '{%:%}': null }); + st.deepEqual(qs.parse('{%:%}='), { '{%:%}': '' }); + st.deepEqual(qs.parse('foo=%:%}'), { foo: '%:%}' }); + st.end(); + }); + + t.test('doesn\'t produce empty keys', function (st) { + st.deepEqual(qs.parse('_r=1&'), { _r: '1' }); + st.end(); + }); + + t.test('cannot access Object prototype', function (st) { + qs.parse('constructor[prototype][bad]=bad'); + qs.parse('bad[constructor][prototype][bad]=bad'); + st.equal(typeof Object.prototype.bad, 'undefined'); + st.end(); + }); + + t.test('parses arrays of objects', function (st) { + st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] }); + st.deepEqual(qs.parse('a[0][b]=c'), { a: [{ b: 'c' }] }); + st.end(); + }); + + t.test('allows for empty strings in arrays', function (st) { + st.deepEqual(qs.parse('a[]=b&a[]=&a[]=c'), { a: ['b', '', 'c'] }); + + st.deepEqual( + qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', { strictNullHandling: true, arrayLimit: 20 }), + { a: ['b', null, 'c', ''] }, + 'with arrayLimit 20 + array indices: null then empty string works' + ); + st.deepEqual( + qs.parse('a[]=b&a[]&a[]=c&a[]=', { strictNullHandling: true, arrayLimit: 0 }), + { a: ['b', null, 'c', ''] }, + 'with arrayLimit 0 + array brackets: null then empty string works' + ); + + st.deepEqual( + qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', { strictNullHandling: true, arrayLimit: 20 }), + { a: ['b', '', 'c', null] }, + 'with arrayLimit 20 + array indices: empty string then null works' + ); + st.deepEqual( + qs.parse('a[]=b&a[]=&a[]=c&a[]', { strictNullHandling: true, arrayLimit: 0 }), + { a: ['b', '', 'c', null] }, + 'with arrayLimit 0 + array brackets: empty string then null works' + ); + + st.deepEqual( + qs.parse('a[]=&a[]=b&a[]=c'), + { a: ['', 'b', 'c'] }, + 'array brackets: empty strings work' + ); + st.end(); + }); + + t.test('compacts sparse arrays', function (st) { + st.deepEqual(qs.parse('a[10]=1&a[2]=2', { arrayLimit: 20 }), { a: ['2', '1'] }); + st.deepEqual(qs.parse('a[1][b][2][c]=1', { arrayLimit: 20 }), { a: [{ b: [{ c: '1' }] }] }); + st.deepEqual(qs.parse('a[1][2][3][c]=1', { arrayLimit: 20 }), { a: [[[{ c: '1' }]]] }); + st.deepEqual(qs.parse('a[1][2][3][c][1]=1', { arrayLimit: 20 }), { a: [[[{ c: ['1'] }]]] }); + st.end(); + }); + + t.test('parses sparse arrays', function (st) { + /* eslint no-sparse-arrays: 0 */ + st.deepEqual(qs.parse('a[4]=1&a[1]=2', { allowSparse: true }), { a: [, '2', , , '1'] }); + st.deepEqual(qs.parse('a[1][b][2][c]=1', { allowSparse: true }), { a: [, { b: [, , { c: '1' }] }] }); + st.deepEqual(qs.parse('a[1][2][3][c]=1', { allowSparse: true }), { a: [, [, , [, , , { c: '1' }]]] }); + st.deepEqual(qs.parse('a[1][2][3][c][1]=1', { allowSparse: true }), { a: [, [, , [, , , { c: [, '1'] }]]] }); + st.end(); + }); + + t.test('parses semi-parsed strings', function (st) { + st.deepEqual(qs.parse({ 'a[b]': 'c' }), { a: { b: 'c' } }); + st.deepEqual(qs.parse({ 'a[b]': 'c', 'a[d]': 'e' }), { a: { b: 'c', d: 'e' } }); + st.end(); + }); + + t.test('parses buffers correctly', function (st) { + var b = SaferBuffer.from('test'); + st.deepEqual(qs.parse({ a: b }), { a: b }); + st.end(); + }); + + t.test('parses jquery-param strings', function (st) { + // readable = 'filter[0][]=int1&filter[0][]==&filter[0][]=77&filter[]=and&filter[2][]=int2&filter[2][]==&filter[2][]=8' + var encoded = 'filter%5B0%5D%5B%5D=int1&filter%5B0%5D%5B%5D=%3D&filter%5B0%5D%5B%5D=77&filter%5B%5D=and&filter%5B2%5D%5B%5D=int2&filter%5B2%5D%5B%5D=%3D&filter%5B2%5D%5B%5D=8'; + var expected = { filter: [['int1', '=', '77'], 'and', ['int2', '=', '8']] }; + st.deepEqual(qs.parse(encoded), expected); + st.end(); + }); + + t.test('continues parsing when no parent is found', function (st) { + st.deepEqual(qs.parse('[]=&a=b'), { 0: '', a: 'b' }); + st.deepEqual(qs.parse('[]&a=b', { strictNullHandling: true }), { 0: null, a: 'b' }); + st.deepEqual(qs.parse('[foo]=bar'), { foo: 'bar' }); + st.end(); + }); + + t.test('does not error when parsing a very long array', function (st) { + var str = 'a[]=a'; + while (Buffer.byteLength(str) < 128 * 1024) { + str = str + '&' + str; + } + + st.doesNotThrow(function () { + qs.parse(str); + }); + + st.end(); + }); + + t.test('does not throw when a native prototype has an enumerable property', function (st) { + st.intercept(Object.prototype, 'crash', { value: '' }); + st.intercept(Array.prototype, 'crash', { value: '' }); + + st.doesNotThrow(qs.parse.bind(null, 'a=b')); + st.deepEqual(qs.parse('a=b'), { a: 'b' }); + st.doesNotThrow(qs.parse.bind(null, 'a[][b]=c')); + st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] }); + + st.end(); + }); + + t.test('parses a string with an alternative string delimiter', function (st) { + st.deepEqual(qs.parse('a=b;c=d', { delimiter: ';' }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('parses a string with an alternative RegExp delimiter', function (st) { + st.deepEqual(qs.parse('a=b; c=d', { delimiter: /[;,] */ }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('does not use non-splittable objects as delimiters', function (st) { + st.deepEqual(qs.parse('a=b&c=d', { delimiter: true }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('allows overriding parameter limit', function (st) { + st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: 1 }), { a: 'b' }); + st.end(); + }); + + t.test('allows setting the parameter limit to Infinity', function (st) { + st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: Infinity }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('allows overriding array limit', function (st) { + st.deepEqual(qs.parse('a[0]=b', { arrayLimit: -1 }), { a: { 0: 'b' } }); + st.deepEqual(qs.parse('a[0]=b', { arrayLimit: 0 }), { a: ['b'] }); + + st.deepEqual(qs.parse('a[-1]=b', { arrayLimit: -1 }), { a: { '-1': 'b' } }); + st.deepEqual(qs.parse('a[-1]=b', { arrayLimit: 0 }), { a: { '-1': 'b' } }); + + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayLimit: -1 }), { a: { 0: 'b', 1: 'c' } }); + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayLimit: 0 }), { a: { 0: 'b', 1: 'c' } }); + + st.end(); + }); + + t.test('allows disabling array parsing', function (st) { + var indices = qs.parse('a[0]=b&a[1]=c', { parseArrays: false }); + st.deepEqual(indices, { a: { 0: 'b', 1: 'c' } }); + st.equal(Array.isArray(indices.a), false, 'parseArrays:false, indices case is not an array'); + + var emptyBrackets = qs.parse('a[]=b', { parseArrays: false }); + st.deepEqual(emptyBrackets, { a: { 0: 'b' } }); + st.equal(Array.isArray(emptyBrackets.a), false, 'parseArrays:false, empty brackets case is not an array'); + + st.end(); + }); + + t.test('allows for query string prefix', function (st) { + st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' }); + st.deepEqual(qs.parse('foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' }); + st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: false }), { '?foo': 'bar' }); + + st.end(); + }); + + t.test('parses an object', function (st) { + var input = { + 'user[name]': { 'pop[bob]': 3 }, + 'user[email]': null + }; + + var expected = { + user: { + name: { 'pop[bob]': 3 }, + email: null + } + }; + + var result = qs.parse(input); + + st.deepEqual(result, expected); + st.end(); + }); + + t.test('parses string with comma as array divider', function (st) { + st.deepEqual(qs.parse('foo=bar,tee', { comma: true }), { foo: ['bar', 'tee'] }); + st.deepEqual(qs.parse('foo[bar]=coffee,tee', { comma: true }), { foo: { bar: ['coffee', 'tee'] } }); + st.deepEqual(qs.parse('foo=', { comma: true }), { foo: '' }); + st.deepEqual(qs.parse('foo', { comma: true }), { foo: '' }); + st.deepEqual(qs.parse('foo', { comma: true, strictNullHandling: true }), { foo: null }); + + // test cases inversed from from stringify tests + st.deepEqual(qs.parse('a[0]=c'), { a: ['c'] }); + st.deepEqual(qs.parse('a[]=c'), { a: ['c'] }); + st.deepEqual(qs.parse('a[]=c', { comma: true }), { a: ['c'] }); + + st.deepEqual(qs.parse('a[0]=c&a[1]=d'), { a: ['c', 'd'] }); + st.deepEqual(qs.parse('a[]=c&a[]=d'), { a: ['c', 'd'] }); + st.deepEqual(qs.parse('a=c,d', { comma: true }), { a: ['c', 'd'] }); + + st.end(); + }); + + t.test('parses values with comma as array divider', function (st) { + st.deepEqual(qs.parse({ foo: 'bar,tee' }, { comma: false }), { foo: 'bar,tee' }); + st.deepEqual(qs.parse({ foo: 'bar,tee' }, { comma: true }), { foo: ['bar', 'tee'] }); + st.end(); + }); + + t.test('use number decoder, parses string that has one number with comma option enabled', function (st) { + var decoder = function (str, defaultDecoder, charset, type) { + if (!isNaN(Number(str))) { + return parseFloat(str); + } + return defaultDecoder(str, defaultDecoder, charset, type); + }; + + st.deepEqual(qs.parse('foo=1', { comma: true, decoder: decoder }), { foo: 1 }); + st.deepEqual(qs.parse('foo=0', { comma: true, decoder: decoder }), { foo: 0 }); + + st.end(); + }); + + t.test('parses brackets holds array of arrays when having two parts of strings with comma as array divider', function (st) { + st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=4,5,6', { comma: true }), { foo: [['1', '2', '3'], ['4', '5', '6']] }); + st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=', { comma: true }), { foo: [['1', '2', '3'], ''] }); + st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=,', { comma: true }), { foo: [['1', '2', '3'], ['', '']] }); + st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=a', { comma: true }), { foo: [['1', '2', '3'], 'a'] }); + + st.end(); + }); + + t.test('parses url-encoded brackets holds array of arrays when having two parts of strings with comma as array divider', function (st) { + st.deepEqual(qs.parse('foo%5B%5D=1,2,3&foo%5B%5D=4,5,6', { comma: true }), { foo: [['1', '2', '3'], ['4', '5', '6']] }); + st.deepEqual(qs.parse('foo%5B%5D=1,2,3&foo%5B%5D=', { comma: true }), { foo: [['1', '2', '3'], ''] }); + st.deepEqual(qs.parse('foo%5B%5D=1,2,3&foo%5B%5D=,', { comma: true }), { foo: [['1', '2', '3'], ['', '']] }); + st.deepEqual(qs.parse('foo%5B%5D=1,2,3&foo%5B%5D=a', { comma: true }), { foo: [['1', '2', '3'], 'a'] }); + + st.end(); + }); + + t.test('parses comma delimited array while having percent-encoded comma treated as normal text', function (st) { + st.deepEqual(qs.parse('foo=a%2Cb', { comma: true }), { foo: 'a,b' }); + st.deepEqual(qs.parse('foo=a%2C%20b,d', { comma: true }), { foo: ['a, b', 'd'] }); + st.deepEqual(qs.parse('foo=a%2C%20b,c%2C%20d', { comma: true }), { foo: ['a, b', 'c, d'] }); + + st.end(); + }); + + t.test('parses an object in dot notation', function (st) { + var input = { + 'user.name': { 'pop[bob]': 3 }, + 'user.email.': null + }; + + var expected = { + user: { + name: { 'pop[bob]': 3 }, + email: null + } + }; + + var result = qs.parse(input, { allowDots: true }); + + st.deepEqual(result, expected); + st.end(); + }); + + t.test('parses an object and not child values', function (st) { + var input = { + 'user[name]': { 'pop[bob]': { test: 3 } }, + 'user[email]': null + }; + + var expected = { + user: { + name: { 'pop[bob]': { test: 3 } }, + email: null + } + }; + + var result = qs.parse(input); + + st.deepEqual(result, expected); + st.end(); + }); + + t.test('does not blow up when Buffer global is missing', function (st) { + var restore = mockProperty(global, 'Buffer', { 'delete': true }); + + var result = qs.parse('a=b&c=d'); + + restore(); + + st.deepEqual(result, { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('does not crash when parsing circular references', function (st) { + var a = {}; + a.b = a; + + var parsed; + + st.doesNotThrow(function () { + parsed = qs.parse({ 'foo[bar]': 'baz', 'foo[baz]': a }); + }); + + st.equal('foo' in parsed, true, 'parsed has "foo" property'); + st.equal('bar' in parsed.foo, true); + st.equal('baz' in parsed.foo, true); + st.equal(parsed.foo.bar, 'baz'); + st.deepEqual(parsed.foo.baz, a); + st.end(); + }); + + t.test('does not crash when parsing deep objects', function (st) { + var parsed; + var str = 'foo'; + + for (var i = 0; i < 5000; i++) { + str += '[p]'; + } + + str += '=bar'; + + st.doesNotThrow(function () { + parsed = qs.parse(str, { depth: 5000 }); + }); + + st.equal('foo' in parsed, true, 'parsed has "foo" property'); + + var depth = 0; + var ref = parsed.foo; + while ((ref = ref.p)) { + depth += 1; + } + + st.equal(depth, 5000, 'parsed is 5000 properties deep'); + + st.end(); + }); + + t.test('parses null objects correctly', { skip: !hasProto }, function (st) { + var a = { __proto__: null, b: 'c' }; + + st.deepEqual(qs.parse(a), { b: 'c' }); + var result = qs.parse({ a: a }); + st.equal('a' in result, true, 'result has "a" property'); + st.deepEqual(result.a, a); + st.end(); + }); + + t.test('parses dates correctly', function (st) { + var now = new Date(); + st.deepEqual(qs.parse({ a: now }), { a: now }); + st.end(); + }); + + t.test('parses regular expressions correctly', function (st) { + var re = /^test$/; + st.deepEqual(qs.parse({ a: re }), { a: re }); + st.end(); + }); + + t.test('does not allow overwriting prototype properties', function (st) { + st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: false }), {}); + st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: false }), {}); + + st.deepEqual( + qs.parse('toString', { allowPrototypes: false }), + {}, + 'bare "toString" results in {}' + ); + + st.end(); + }); + + t.test('can allow overwriting prototype properties', function (st) { + st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }), { a: { hasOwnProperty: 'b' } }); + st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: true }), { hasOwnProperty: 'b' }); + + st.deepEqual( + qs.parse('toString', { allowPrototypes: true }), + { toString: '' }, + 'bare "toString" results in { toString: "" }' + ); + + st.end(); + }); + + t.test('does not crash when the global Object prototype is frozen', { skip: !hasPropertyDescriptors || !hasOverrideMistake }, function (st) { + // We can't actually freeze the global Object prototype as that will interfere with other tests, and once an object is frozen, it + // can't be unfrozen. Instead, we add a new non-writable property to simulate this. + st.teardown(mockProperty(Object.prototype, 'frozenProp', { value: 'foo', nonWritable: true, nonEnumerable: true })); + + st['throws']( + function () { + var obj = {}; + obj.frozenProp = 'bar'; + }, + // node < 6 has a different error message + /^TypeError: Cannot assign to read only property 'frozenProp' of (?:object '#'|#)/, + 'regular assignment of an inherited non-writable property throws' + ); + + var parsed; + st.doesNotThrow( + function () { + parsed = qs.parse('frozenProp', { allowPrototypes: false }); + }, + 'parsing a nonwritable Object.prototype property does not throw' + ); + + st.deepEqual(parsed, {}, 'bare "frozenProp" results in {}'); + + st.end(); + }); + + t.test('params starting with a closing bracket', function (st) { + st.deepEqual(qs.parse(']=toString'), { ']': 'toString' }); + st.deepEqual(qs.parse(']]=toString'), { ']]': 'toString' }); + st.deepEqual(qs.parse(']hello]=toString'), { ']hello]': 'toString' }); + st.end(); + }); + + t.test('params starting with a starting bracket', function (st) { + st.deepEqual(qs.parse('[=toString'), { '[': 'toString' }); + st.deepEqual(qs.parse('[[=toString'), { '[[': 'toString' }); + st.deepEqual(qs.parse('[hello[=toString'), { '[hello[': 'toString' }); + st.end(); + }); + + t.test('add keys to objects', function (st) { + st.deepEqual( + qs.parse('a[b]=c&a=d'), + { a: { b: 'c', d: true } }, + 'can add keys to objects' + ); + + st.deepEqual( + qs.parse('a[b]=c&a=toString'), + { a: { b: 'c' } }, + 'can not overwrite prototype' + ); + + st.deepEqual( + qs.parse('a[b]=c&a=toString', { allowPrototypes: true }), + { a: { b: 'c', toString: true } }, + 'can overwrite prototype with allowPrototypes true' + ); + + st.deepEqual( + qs.parse('a[b]=c&a=toString', { plainObjects: true }), + { __proto__: null, a: { __proto__: null, b: 'c', toString: true } }, + 'can overwrite prototype with plainObjects true' + ); + + st.end(); + }); + + t.test('dunder proto is ignored', function (st) { + var payload = 'categories[__proto__]=login&categories[__proto__]&categories[length]=42'; + var result = qs.parse(payload, { allowPrototypes: true }); + + st.deepEqual( + result, + { + categories: { + length: '42' + } + }, + 'silent [[Prototype]] payload' + ); + + var plainResult = qs.parse(payload, { allowPrototypes: true, plainObjects: true }); + + st.deepEqual( + plainResult, + { + __proto__: null, + categories: { + __proto__: null, + length: '42' + } + }, + 'silent [[Prototype]] payload: plain objects' + ); + + var query = qs.parse('categories[__proto__]=cats&categories[__proto__]=dogs&categories[some][json]=toInject', { allowPrototypes: true }); + + st.notOk(Array.isArray(query.categories), 'is not an array'); + st.notOk(query.categories instanceof Array, 'is not instanceof an array'); + st.deepEqual(query.categories, { some: { json: 'toInject' } }); + st.equal(JSON.stringify(query.categories), '{"some":{"json":"toInject"}}', 'stringifies as a non-array'); + + st.deepEqual( + qs.parse('foo[__proto__][hidden]=value&foo[bar]=stuffs', { allowPrototypes: true }), + { + foo: { + bar: 'stuffs' + } + }, + 'hidden values' + ); + + st.deepEqual( + qs.parse('foo[__proto__][hidden]=value&foo[bar]=stuffs', { allowPrototypes: true, plainObjects: true }), + { + __proto__: null, + foo: { + __proto__: null, + bar: 'stuffs' + } + }, + 'hidden values: plain objects' + ); + + st.end(); + }); + + t.test('can return null objects', { skip: !hasProto }, function (st) { + var expected = { + __proto__: null, + a: { + __proto__: null, + b: 'c', + hasOwnProperty: 'd' + } + }; + st.deepEqual(qs.parse('a[b]=c&a[hasOwnProperty]=d', { plainObjects: true }), expected); + st.deepEqual(qs.parse(null, { plainObjects: true }), { __proto__: null }); + var expectedArray = { + __proto__: null, + a: { + __proto__: null, + 0: 'b', + c: 'd' + } + }; + st.deepEqual(qs.parse('a[]=b&a[c]=d', { plainObjects: true }), expectedArray); + st.end(); + }); + + t.test('can parse with custom encoding', function (st) { + st.deepEqual(qs.parse('%8c%a7=%91%e5%8d%e3%95%7b', { + decoder: function (str) { + var reg = /%([0-9A-F]{2})/ig; + var result = []; + var parts = reg.exec(str); + while (parts) { + result.push(parseInt(parts[1], 16)); + parts = reg.exec(str); + } + return String(iconv.decode(SaferBuffer.from(result), 'shift_jis')); + } + }), { 県: '大阪府' }); + st.end(); + }); + + t.test('receives the default decoder as a second argument', function (st) { + st.plan(1); + qs.parse('a', { + decoder: function (str, defaultDecoder) { + st.equal(defaultDecoder, utils.decode); + } + }); + st.end(); + }); + + t.test('throws error with wrong decoder', function (st) { + st['throws'](function () { + qs.parse({}, { decoder: 'string' }); + }, new TypeError('Decoder has to be a function.')); + st.end(); + }); + + t.test('does not mutate the options argument', function (st) { + var options = {}; + qs.parse('a[b]=true', options); + st.deepEqual(options, {}); + st.end(); + }); + + t.test('throws if an invalid charset is specified', function (st) { + st['throws'](function () { + qs.parse('a=b', { charset: 'foobar' }); + }, new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined')); + st.end(); + }); + + t.test('parses an iso-8859-1 string if asked to', function (st) { + st.deepEqual(qs.parse('%A2=%BD', { charset: 'iso-8859-1' }), { '¢': '½' }); + st.end(); + }); + + var urlEncodedCheckmarkInUtf8 = '%E2%9C%93'; + var urlEncodedOSlashInUtf8 = '%C3%B8'; + var urlEncodedNumCheckmark = '%26%2310003%3B'; + var urlEncodedNumSmiley = '%26%239786%3B'; + + t.test('prefers an utf-8 charset specified by the utf8 sentinel to a default charset of iso-8859-1', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedCheckmarkInUtf8 + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'iso-8859-1' }), { ø: 'ø' }); + st.end(); + }); + + t.test('prefers an iso-8859-1 charset specified by the utf8 sentinel to a default charset of utf-8', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedNumCheckmark + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'utf-8' }), { 'ø': 'ø' }); + st.end(); + }); + + t.test('does not require the utf8 sentinel to be defined before the parameters whose decoding it affects', function (st) { + st.deepEqual(qs.parse('a=' + urlEncodedOSlashInUtf8 + '&utf8=' + urlEncodedNumCheckmark, { charsetSentinel: true, charset: 'utf-8' }), { a: 'ø' }); + st.end(); + }); + + t.test('ignores an utf8 sentinel with an unknown value', function (st) { + st.deepEqual(qs.parse('utf8=foo&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'utf-8' }), { ø: 'ø' }); + st.end(); + }); + + t.test('uses the utf8 sentinel to switch to utf-8 when no default charset is given', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedCheckmarkInUtf8 + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true }), { ø: 'ø' }); + st.end(); + }); + + t.test('uses the utf8 sentinel to switch to iso-8859-1 when no default charset is given', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedNumCheckmark + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true }), { 'ø': 'ø' }); + st.end(); + }); + + t.test('interprets numeric entities in iso-8859-1 when `interpretNumericEntities`', function (st) { + st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'iso-8859-1', interpretNumericEntities: true }), { foo: '☺' }); + st.end(); + }); + + t.test('handles a custom decoder returning `null`, in the `iso-8859-1` charset, when `interpretNumericEntities`', function (st) { + st.deepEqual(qs.parse('foo=&bar=' + urlEncodedNumSmiley, { + charset: 'iso-8859-1', + decoder: function (str, defaultDecoder, charset) { + return str ? defaultDecoder(str, defaultDecoder, charset) : null; + }, + interpretNumericEntities: true + }), { foo: null, bar: '☺' }); + st.end(); + }); + + t.test('does not interpret numeric entities in iso-8859-1 when `interpretNumericEntities` is absent', function (st) { + st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'iso-8859-1' }), { foo: '☺' }); + st.end(); + }); + + t.test('does not interpret numeric entities when the charset is utf-8, even when `interpretNumericEntities`', function (st) { + st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'utf-8', interpretNumericEntities: true }), { foo: '☺' }); + st.end(); + }); + + t.test('interpretNumericEntities with comma:true and iso charset does not crash', function (st) { + st.deepEqual( + qs.parse('b&a[]=1,' + urlEncodedNumSmiley, { comma: true, charset: 'iso-8859-1', interpretNumericEntities: true }), + { b: '', a: ['1,☺'] } + ); + + st.end(); + }); + + t.test('does not interpret %uXXXX syntax in iso-8859-1 mode', function (st) { + st.deepEqual(qs.parse('%u263A=%u263A', { charset: 'iso-8859-1' }), { '%u263A': '%u263A' }); + st.end(); + }); + + t.test('allows for decoding keys and values differently', function (st) { + var decoder = function (str, defaultDecoder, charset, type) { + if (type === 'key') { + return defaultDecoder(str, defaultDecoder, charset, type).toLowerCase(); + } + if (type === 'value') { + return defaultDecoder(str, defaultDecoder, charset, type).toUpperCase(); + } + throw 'this should never happen! type: ' + type; + }; + + st.deepEqual(qs.parse('KeY=vAlUe', { decoder: decoder }), { key: 'VALUE' }); + st.end(); + }); + + t.test('parameter limit tests', function (st) { + st.test('does not throw error when within parameter limit', function (sst) { + var result = qs.parse('a=1&b=2&c=3', { parameterLimit: 5, throwOnLimitExceeded: true }); + sst.deepEqual(result, { a: '1', b: '2', c: '3' }, 'parses without errors'); + sst.end(); + }); + + st.test('throws error when throwOnLimitExceeded is present but not boolean', function (sst) { + sst['throws']( + function () { + qs.parse('a=1&b=2&c=3&d=4&e=5&f=6', { parameterLimit: 3, throwOnLimitExceeded: 'true' }); + }, + new TypeError('`throwOnLimitExceeded` option must be a boolean'), + 'throws error when throwOnLimitExceeded is present and not boolean' + ); + sst.end(); + }); + + st.test('throws error when parameter limit exceeded', function (sst) { + sst['throws']( + function () { + qs.parse('a=1&b=2&c=3&d=4&e=5&f=6', { parameterLimit: 3, throwOnLimitExceeded: true }); + }, + new RangeError('Parameter limit exceeded. Only 3 parameters allowed.'), + 'throws error when parameter limit is exceeded' + ); + sst.end(); + }); + + st.test('silently truncates when throwOnLimitExceeded is not given', function (sst) { + var result = qs.parse('a=1&b=2&c=3&d=4&e=5', { parameterLimit: 3 }); + sst.deepEqual(result, { a: '1', b: '2', c: '3' }, 'parses and truncates silently'); + sst.end(); + }); + + st.test('silently truncates when parameter limit exceeded without error', function (sst) { + var result = qs.parse('a=1&b=2&c=3&d=4&e=5', { parameterLimit: 3, throwOnLimitExceeded: false }); + sst.deepEqual(result, { a: '1', b: '2', c: '3' }, 'parses and truncates silently'); + sst.end(); + }); + + st.test('allows unlimited parameters when parameterLimit set to Infinity', function (sst) { + var result = qs.parse('a=1&b=2&c=3&d=4&e=5&f=6', { parameterLimit: Infinity }); + sst.deepEqual(result, { a: '1', b: '2', c: '3', d: '4', e: '5', f: '6' }, 'parses all parameters without truncation'); + sst.end(); + }); + + st.end(); + }); + + t.test('array limit tests', function (st) { + st.test('does not throw error when array is within limit', function (sst) { + var result = qs.parse('a[]=1&a[]=2&a[]=3', { arrayLimit: 5, throwOnLimitExceeded: true }); + sst.deepEqual(result, { a: ['1', '2', '3'] }, 'parses array without errors'); + sst.end(); + }); + + st.test('throws error when throwOnLimitExceeded is present but not boolean for array limit', function (sst) { + sst['throws']( + function () { + qs.parse('a[]=1&a[]=2&a[]=3&a[]=4', { arrayLimit: 3, throwOnLimitExceeded: 'true' }); + }, + new TypeError('`throwOnLimitExceeded` option must be a boolean'), + 'throws error when throwOnLimitExceeded is present and not boolean for array limit' + ); + sst.end(); + }); + + st.test('throws error when array limit exceeded', function (sst) { + sst['throws']( + function () { + qs.parse('a[]=1&a[]=2&a[]=3&a[]=4', { arrayLimit: 3, throwOnLimitExceeded: true }); + }, + new RangeError('Array limit exceeded. Only 3 elements allowed in an array.'), + 'throws error when array limit is exceeded' + ); + sst.end(); + }); + + st.test('converts array to object if length is greater than limit', function (sst) { + var result = qs.parse('a[1]=1&a[2]=2&a[3]=3&a[4]=4&a[5]=5&a[6]=6', { arrayLimit: 5 }); + + sst.deepEqual(result, { a: { 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6' } }, 'parses into object if array length is greater than limit'); + sst.end(); + }); + + st.end(); + }); + + t.end(); +}); + +test('parses empty keys', function (t) { + emptyTestCases.forEach(function (testCase) { + t.test('skips empty string key with ' + testCase.input, function (st) { + st.deepEqual(qs.parse(testCase.input), testCase.noEmptyKeys); + + st.end(); + }); + }); +}); + +test('`duplicates` option', function (t) { + v.nonStrings.concat('not a valid option').forEach(function (invalidOption) { + if (typeof invalidOption !== 'undefined') { + t['throws']( + function () { qs.parse('', { duplicates: invalidOption }); }, + TypeError, + 'throws on invalid option: ' + inspect(invalidOption) + ); + } + }); + + t.deepEqual( + qs.parse('foo=bar&foo=baz'), + { foo: ['bar', 'baz'] }, + 'duplicates: default, combine' + ); + + t.deepEqual( + qs.parse('foo=bar&foo=baz', { duplicates: 'combine' }), + { foo: ['bar', 'baz'] }, + 'duplicates: combine' + ); + + t.deepEqual( + qs.parse('foo=bar&foo=baz', { duplicates: 'first' }), + { foo: 'bar' }, + 'duplicates: first' + ); + + t.deepEqual( + qs.parse('foo=bar&foo=baz', { duplicates: 'last' }), + { foo: 'baz' }, + 'duplicates: last' + ); + + t.end(); +}); + +test('qs strictDepth option - throw cases', function (t) { + t.test('throws an exception when depth exceeds the limit with strictDepth: true', function (st) { + st['throws']( + function () { + qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1, strictDepth: true }); + }, + RangeError, + 'throws RangeError' + ); + st.end(); + }); + + t.test('throws an exception for multiple nested arrays with strictDepth: true', function (st) { + st['throws']( + function () { + qs.parse('a[0][1][2][3][4]=b', { depth: 3, strictDepth: true }); + }, + RangeError, + 'throws RangeError' + ); + st.end(); + }); + + t.test('throws an exception for nested objects and arrays with strictDepth: true', function (st) { + st['throws']( + function () { + qs.parse('a[b][c][0][d][e]=f', { depth: 3, strictDepth: true }); + }, + RangeError, + 'throws RangeError' + ); + st.end(); + }); + + t.test('throws an exception for different types of values with strictDepth: true', function (st) { + st['throws']( + function () { + qs.parse('a[b][c][d][e]=true&a[b][c][d][f]=42', { depth: 3, strictDepth: true }); + }, + RangeError, + 'throws RangeError' + ); + st.end(); + }); + +}); + +test('qs strictDepth option - non-throw cases', function (t) { + t.test('when depth is 0 and strictDepth true, do not throw', function (st) { + st.doesNotThrow( + function () { + qs.parse('a[b][c][d][e]=true&a[b][c][d][f]=42', { depth: 0, strictDepth: true }); + }, + RangeError, + 'does not throw RangeError' + ); + st.end(); + }); + + t.test('parses successfully when depth is within the limit with strictDepth: true', function (st) { + st.doesNotThrow( + function () { + var result = qs.parse('a[b]=c', { depth: 1, strictDepth: true }); + st.deepEqual(result, { a: { b: 'c' } }, 'parses correctly'); + } + ); + st.end(); + }); + + t.test('does not throw an exception when depth exceeds the limit with strictDepth: false', function (st) { + st.doesNotThrow( + function () { + var result = qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 }); + st.deepEqual(result, { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } }, 'parses with depth limit'); + } + ); + st.end(); + }); + + t.test('parses successfully when depth is within the limit with strictDepth: false', function (st) { + st.doesNotThrow( + function () { + var result = qs.parse('a[b]=c', { depth: 1 }); + st.deepEqual(result, { a: { b: 'c' } }, 'parses correctly'); + } + ); + st.end(); + }); + + t.test('does not throw when depth is exactly at the limit with strictDepth: true', function (st) { + st.doesNotThrow( + function () { + var result = qs.parse('a[b][c]=d', { depth: 2, strictDepth: true }); + st.deepEqual(result, { a: { b: { c: 'd' } } }, 'parses correctly'); + } + ); + st.end(); + }); +}); diff --git a/node_modules/qs/test/stringify.js b/node_modules/qs/test/stringify.js new file mode 100644 index 0000000..7253144 --- /dev/null +++ b/node_modules/qs/test/stringify.js @@ -0,0 +1,1306 @@ +'use strict'; + +var test = require('tape'); +var qs = require('../'); +var utils = require('../lib/utils'); +var iconv = require('iconv-lite'); +var SaferBuffer = require('safer-buffer').Buffer; +var hasSymbols = require('has-symbols'); +var mockProperty = require('mock-property'); +var emptyTestCases = require('./empty-keys-cases').emptyTestCases; +var hasProto = require('has-proto')(); +var hasBigInt = require('has-bigints')(); + +test('stringify()', function (t) { + t.test('stringifies a querystring object', function (st) { + st.equal(qs.stringify({ a: 'b' }), 'a=b'); + st.equal(qs.stringify({ a: 1 }), 'a=1'); + st.equal(qs.stringify({ a: 1, b: 2 }), 'a=1&b=2'); + st.equal(qs.stringify({ a: 'A_Z' }), 'a=A_Z'); + st.equal(qs.stringify({ a: '€' }), 'a=%E2%82%AC'); + st.equal(qs.stringify({ a: '' }), 'a=%EE%80%80'); + st.equal(qs.stringify({ a: 'א' }), 'a=%D7%90'); + st.equal(qs.stringify({ a: '𐐷' }), 'a=%F0%90%90%B7'); + st.end(); + }); + + t.test('stringifies falsy values', function (st) { + st.equal(qs.stringify(undefined), ''); + st.equal(qs.stringify(null), ''); + st.equal(qs.stringify(null, { strictNullHandling: true }), ''); + st.equal(qs.stringify(false), ''); + st.equal(qs.stringify(0), ''); + st.end(); + }); + + t.test('stringifies symbols', { skip: !hasSymbols() }, function (st) { + st.equal(qs.stringify(Symbol.iterator), ''); + st.equal(qs.stringify([Symbol.iterator]), '0=Symbol%28Symbol.iterator%29'); + st.equal(qs.stringify({ a: Symbol.iterator }), 'a=Symbol%28Symbol.iterator%29'); + st.equal( + qs.stringify({ a: [Symbol.iterator] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), + 'a[]=Symbol%28Symbol.iterator%29' + ); + st.end(); + }); + + t.test('stringifies bigints', { skip: !hasBigInt }, function (st) { + var three = BigInt(3); + var encodeWithN = function (value, defaultEncoder, charset) { + var result = defaultEncoder(value, defaultEncoder, charset); + return typeof value === 'bigint' ? result + 'n' : result; + }; + st.equal(qs.stringify(three), ''); + st.equal(qs.stringify([three]), '0=3'); + st.equal(qs.stringify([three], { encoder: encodeWithN }), '0=3n'); + st.equal(qs.stringify({ a: three }), 'a=3'); + st.equal(qs.stringify({ a: three }, { encoder: encodeWithN }), 'a=3n'); + st.equal( + qs.stringify({ a: [three] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), + 'a[]=3' + ); + st.equal( + qs.stringify({ a: [three] }, { encodeValuesOnly: true, encoder: encodeWithN, arrayFormat: 'brackets' }), + 'a[]=3n' + ); + st.end(); + }); + + t.test('encodes dot in key of object when encodeDotInKeys and allowDots is provided', function (st) { + st.equal( + qs.stringify( + { 'name.obj': { first: 'John', last: 'Doe' } }, + { allowDots: false, encodeDotInKeys: false } + ), + 'name.obj%5Bfirst%5D=John&name.obj%5Blast%5D=Doe', + 'with allowDots false and encodeDotInKeys false' + ); + st.equal( + qs.stringify( + { 'name.obj': { first: 'John', last: 'Doe' } }, + { allowDots: true, encodeDotInKeys: false } + ), + 'name.obj.first=John&name.obj.last=Doe', + 'with allowDots true and encodeDotInKeys false' + ); + st.equal( + qs.stringify( + { 'name.obj': { first: 'John', last: 'Doe' } }, + { allowDots: false, encodeDotInKeys: true } + ), + 'name%252Eobj%5Bfirst%5D=John&name%252Eobj%5Blast%5D=Doe', + 'with allowDots false and encodeDotInKeys true' + ); + st.equal( + qs.stringify( + { 'name.obj': { first: 'John', last: 'Doe' } }, + { allowDots: true, encodeDotInKeys: true } + ), + 'name%252Eobj.first=John&name%252Eobj.last=Doe', + 'with allowDots true and encodeDotInKeys true' + ); + + st.equal( + qs.stringify( + { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, + { allowDots: false, encodeDotInKeys: false } + ), + 'name.obj.subobject%5Bfirst.godly.name%5D=John&name.obj.subobject%5Blast%5D=Doe', + 'with allowDots false and encodeDotInKeys false' + ); + st.equal( + qs.stringify( + { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, + { allowDots: true, encodeDotInKeys: false } + ), + 'name.obj.subobject.first.godly.name=John&name.obj.subobject.last=Doe', + 'with allowDots false and encodeDotInKeys false' + ); + st.equal( + qs.stringify( + { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, + { allowDots: false, encodeDotInKeys: true } + ), + 'name%252Eobj%252Esubobject%5Bfirst.godly.name%5D=John&name%252Eobj%252Esubobject%5Blast%5D=Doe', + 'with allowDots false and encodeDotInKeys true' + ); + st.equal( + qs.stringify( + { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, + { allowDots: true, encodeDotInKeys: true } + ), + 'name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe', + 'with allowDots true and encodeDotInKeys true' + ); + + st.end(); + }); + + t.test('should encode dot in key of object, and automatically set allowDots to `true` when encodeDotInKeys is true and allowDots in undefined', function (st) { + st.equal( + qs.stringify( + { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, + { encodeDotInKeys: true } + ), + 'name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe', + 'with allowDots undefined and encodeDotInKeys true' + ); + st.end(); + }); + + t.test('should encode dot in key of object when encodeDotInKeys and allowDots is provided, and nothing else when encodeValuesOnly is provided', function (st) { + st.equal( + qs.stringify({ 'name.obj': { first: 'John', last: 'Doe' } }, { + encodeDotInKeys: true, allowDots: true, encodeValuesOnly: true + }), + 'name%2Eobj.first=John&name%2Eobj.last=Doe' + ); + + st.equal( + qs.stringify({ 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, { allowDots: true, encodeDotInKeys: true, encodeValuesOnly: true }), + 'name%2Eobj%2Esubobject.first%2Egodly%2Ename=John&name%2Eobj%2Esubobject.last=Doe' + ); + + st.end(); + }); + + t.test('throws when `commaRoundTrip` is not a boolean', function (st) { + st['throws']( + function () { qs.stringify({}, { commaRoundTrip: 'not a boolean' }); }, + TypeError, + 'throws when `commaRoundTrip` is not a boolean' + ); + + st.end(); + }); + + t.test('throws when `encodeDotInKeys` is not a boolean', function (st) { + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { encodeDotInKeys: 'foobar' }); }, + TypeError + ); + + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { encodeDotInKeys: 0 }); }, + TypeError + ); + + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { encodeDotInKeys: NaN }); }, + TypeError + ); + + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { encodeDotInKeys: null }); }, + TypeError + ); + + st.end(); + }); + + t.test('adds query prefix', function (st) { + st.equal(qs.stringify({ a: 'b' }, { addQueryPrefix: true }), '?a=b'); + st.end(); + }); + + t.test('with query prefix, outputs blank string given an empty object', function (st) { + st.equal(qs.stringify({}, { addQueryPrefix: true }), ''); + st.end(); + }); + + t.test('stringifies nested falsy values', function (st) { + st.equal(qs.stringify({ a: { b: { c: null } } }), 'a%5Bb%5D%5Bc%5D='); + st.equal(qs.stringify({ a: { b: { c: null } } }, { strictNullHandling: true }), 'a%5Bb%5D%5Bc%5D'); + st.equal(qs.stringify({ a: { b: { c: false } } }), 'a%5Bb%5D%5Bc%5D=false'); + st.end(); + }); + + t.test('stringifies a nested object', function (st) { + st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); + st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }), 'a%5Bb%5D%5Bc%5D%5Bd%5D=e'); + st.end(); + }); + + t.test('`allowDots` option: stringifies a nested object with dots notation', function (st) { + st.equal(qs.stringify({ a: { b: 'c' } }, { allowDots: true }), 'a.b=c'); + st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }, { allowDots: true }), 'a.b.c.d=e'); + st.end(); + }); + + t.test('stringifies an array value', function (st) { + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'indices' }), + 'a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d', + 'indices => indices' + ); + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'brackets' }), + 'a%5B%5D=b&a%5B%5D=c&a%5B%5D=d', + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'comma' }), + 'a=b%2Cc%2Cd', + 'comma => comma' + ); + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'comma', commaRoundTrip: true }), + 'a=b%2Cc%2Cd', + 'comma round trip => comma' + ); + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }), + 'a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d', + 'default => indices' + ); + st.end(); + }); + + t.test('`skipNulls` option', function (st) { + st.equal( + qs.stringify({ a: 'b', c: null }, { skipNulls: true }), + 'a=b', + 'omits nulls when asked' + ); + + st.equal( + qs.stringify({ a: { b: 'c', d: null } }, { skipNulls: true }), + 'a%5Bb%5D=c', + 'omits nested nulls when asked' + ); + + st.end(); + }); + + t.test('omits array indices when asked', function (st) { + st.equal(qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }), 'a=b&a=c&a=d'); + + st.end(); + }); + + t.test('omits object key/value pair when value is empty array', function (st) { + st.equal(qs.stringify({ a: [], b: 'zz' }), 'b=zz'); + + st.end(); + }); + + t.test('should not omit object key/value pair when value is empty array and when asked', function (st) { + st.equal(qs.stringify({ a: [], b: 'zz' }), 'b=zz'); + st.equal(qs.stringify({ a: [], b: 'zz' }, { allowEmptyArrays: false }), 'b=zz'); + st.equal(qs.stringify({ a: [], b: 'zz' }, { allowEmptyArrays: true }), 'a[]&b=zz'); + + st.end(); + }); + + t.test('should throw when allowEmptyArrays is not of type boolean', function (st) { + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { allowEmptyArrays: 'foobar' }); }, + TypeError + ); + + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { allowEmptyArrays: 0 }); }, + TypeError + ); + + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { allowEmptyArrays: NaN }); }, + TypeError + ); + + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { allowEmptyArrays: null }); }, + TypeError + ); + + st.end(); + }); + + t.test('allowEmptyArrays + strictNullHandling', function (st) { + st.equal( + qs.stringify( + { testEmptyArray: [] }, + { strictNullHandling: true, allowEmptyArrays: true } + ), + 'testEmptyArray[]' + ); + + st.end(); + }); + + t.test('stringifies an array value with one item vs multiple items', function (st) { + st.test('non-array item', function (s2t) { + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a=c'); + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a=c'); + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c'); + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true }), 'a=c'); + + s2t.end(); + }); + + st.test('array with a single item', function (s2t) { + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[0]=c'); + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[]=c'); + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c'); + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'comma', commaRoundTrip: true }), 'a[]=c'); // so it parses back as an array + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true }), 'a[0]=c'); + + s2t.end(); + }); + + st.test('array with multiple items', function (s2t) { + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[0]=c&a[1]=d'); + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[]=c&a[]=d'); + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c,d'); + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'comma', commaRoundTrip: true }), 'a=c,d'); + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true }), 'a[0]=c&a[1]=d'); + + s2t.end(); + }); + + st.test('array with multiple items with a comma inside', function (s2t) { + s2t.equal(qs.stringify({ a: ['c,d', 'e'] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c%2Cd,e'); + s2t.equal(qs.stringify({ a: ['c,d', 'e'] }, { arrayFormat: 'comma' }), 'a=c%2Cd%2Ce'); + + s2t.equal(qs.stringify({ a: ['c,d', 'e'] }, { encodeValuesOnly: true, arrayFormat: 'comma', commaRoundTrip: true }), 'a=c%2Cd,e'); + s2t.equal(qs.stringify({ a: ['c,d', 'e'] }, { arrayFormat: 'comma', commaRoundTrip: true }), 'a=c%2Cd%2Ce'); + + s2t.end(); + }); + + st.end(); + }); + + t.test('stringifies a nested array value', function (st) { + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[b][0]=c&a[b][1]=d'); + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[b][]=c&a[b][]=d'); + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a[b]=c,d'); + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true }), 'a[b][0]=c&a[b][1]=d'); + st.end(); + }); + + t.test('stringifies comma and empty array values', function (st) { + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'indices' }), 'a[0]=,&a[1]=&a[2]=c,d%'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'brackets' }), 'a[]=,&a[]=&a[]=c,d%'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'comma' }), 'a=,,,c,d%'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'repeat' }), 'a=,&a=&a=c,d%'); + + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[0]=%2C&a[1]=&a[2]=c%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[]=%2C&a[]=&a[]=c%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=%2C,,c%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: true, arrayFormat: 'repeat' }), 'a=%2C&a=&a=c%2Cd%25'); + + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: false, arrayFormat: 'indices' }), 'a%5B0%5D=%2C&a%5B1%5D=&a%5B2%5D=c%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: false, arrayFormat: 'brackets' }), 'a%5B%5D=%2C&a%5B%5D=&a%5B%5D=c%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: false, arrayFormat: 'comma' }), 'a=%2C%2C%2Cc%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: false, arrayFormat: 'repeat' }), 'a=%2C&a=&a=c%2Cd%25'); + + st.end(); + }); + + t.test('stringifies comma and empty non-array values', function (st) { + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: false, arrayFormat: 'indices' }), 'a=,&b=&c=c,d%'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: false, arrayFormat: 'brackets' }), 'a=,&b=&c=c,d%'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: false, arrayFormat: 'comma' }), 'a=,&b=&c=c,d%'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: false, arrayFormat: 'repeat' }), 'a=,&b=&c=c,d%'); + + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: true, arrayFormat: 'indices' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: true, arrayFormat: 'repeat' }), 'a=%2C&b=&c=c%2Cd%25'); + + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: false, arrayFormat: 'indices' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: false, arrayFormat: 'brackets' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: false, arrayFormat: 'comma' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: false, arrayFormat: 'repeat' }), 'a=%2C&b=&c=c%2Cd%25'); + + st.end(); + }); + + t.test('stringifies a nested array value with dots notation', function (st) { + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encodeValuesOnly: true, arrayFormat: 'indices' } + ), + 'a.b[0]=c&a.b[1]=d', + 'indices: stringifies with dots + indices' + ); + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encodeValuesOnly: true, arrayFormat: 'brackets' } + ), + 'a.b[]=c&a.b[]=d', + 'brackets: stringifies with dots + brackets' + ); + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encodeValuesOnly: true, arrayFormat: 'comma' } + ), + 'a.b=c,d', + 'comma: stringifies with dots + comma' + ); + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encodeValuesOnly: true } + ), + 'a.b[0]=c&a.b[1]=d', + 'default: stringifies with dots + indices' + ); + st.end(); + }); + + t.test('stringifies an object inside an array', function (st) { + st.equal( + qs.stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'indices', encodeValuesOnly: true }), + 'a[0][b]=c', + 'indices => indices' + ); + st.equal( + qs.stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'repeat', encodeValuesOnly: true }), + 'a[b]=c', + 'repeat => repeat' + ); + st.equal( + qs.stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'brackets', encodeValuesOnly: true }), + 'a[][b]=c', + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: [{ b: 'c' }] }, { encodeValuesOnly: true }), + 'a[0][b]=c', + 'default => indices' + ); + + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'indices', encodeValuesOnly: true }), + 'a[0][b][c][0]=1', + 'indices => indices' + ); + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'repeat', encodeValuesOnly: true }), + 'a[b][c]=1', + 'repeat => repeat' + ); + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'brackets', encodeValuesOnly: true }), + 'a[][b][c][]=1', + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }, { encodeValuesOnly: true }), + 'a[0][b][c][0]=1', + 'default => indices' + ); + + st.end(); + }); + + t.test('stringifies an array with mixed objects and primitives', function (st) { + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), + 'a[0][b]=1&a[1]=2&a[2]=3', + 'indices => indices' + ); + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), + 'a[][b]=1&a[]=2&a[]=3', + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), + '???', + 'brackets => brackets', + { skip: 'TODO: figure out what this should do' } + ); + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true }), + 'a[0][b]=1&a[1]=2&a[2]=3', + 'default => indices' + ); + + st.end(); + }); + + t.test('stringifies an object inside an array with dots notation', function (st) { + st.equal( + qs.stringify( + { a: [{ b: 'c' }] }, + { allowDots: true, encode: false, arrayFormat: 'indices' } + ), + 'a[0].b=c', + 'indices => indices' + ); + st.equal( + qs.stringify( + { a: [{ b: 'c' }] }, + { allowDots: true, encode: false, arrayFormat: 'brackets' } + ), + 'a[].b=c', + 'brackets => brackets' + ); + st.equal( + qs.stringify( + { a: [{ b: 'c' }] }, + { allowDots: true, encode: false } + ), + 'a[0].b=c', + 'default => indices' + ); + + st.equal( + qs.stringify( + { a: [{ b: { c: [1] } }] }, + { allowDots: true, encode: false, arrayFormat: 'indices' } + ), + 'a[0].b.c[0]=1', + 'indices => indices' + ); + st.equal( + qs.stringify( + { a: [{ b: { c: [1] } }] }, + { allowDots: true, encode: false, arrayFormat: 'brackets' } + ), + 'a[].b.c[]=1', + 'brackets => brackets' + ); + st.equal( + qs.stringify( + { a: [{ b: { c: [1] } }] }, + { allowDots: true, encode: false } + ), + 'a[0].b.c[0]=1', + 'default => indices' + ); + + st.end(); + }); + + t.test('does not omit object keys when indices = false', function (st) { + st.equal(qs.stringify({ a: [{ b: 'c' }] }, { indices: false }), 'a%5Bb%5D=c'); + st.end(); + }); + + t.test('uses indices notation for arrays when indices=true', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { indices: true }), 'a%5B0%5D=b&a%5B1%5D=c'); + st.end(); + }); + + t.test('uses indices notation for arrays when no arrayFormat is specified', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }), 'a%5B0%5D=b&a%5B1%5D=c'); + st.end(); + }); + + t.test('uses indices notation for arrays when arrayFormat=indices', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }), 'a%5B0%5D=b&a%5B1%5D=c'); + st.end(); + }); + + t.test('uses repeat notation for arrays when arrayFormat=repeat', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }), 'a=b&a=c'); + st.end(); + }); + + t.test('uses brackets notation for arrays when arrayFormat=brackets', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }), 'a%5B%5D=b&a%5B%5D=c'); + st.end(); + }); + + t.test('stringifies a complicated object', function (st) { + st.equal(qs.stringify({ a: { b: 'c', d: 'e' } }), 'a%5Bb%5D=c&a%5Bd%5D=e'); + st.end(); + }); + + t.test('stringifies an empty value', function (st) { + st.equal(qs.stringify({ a: '' }), 'a='); + st.equal(qs.stringify({ a: null }, { strictNullHandling: true }), 'a'); + + st.equal(qs.stringify({ a: '', b: '' }), 'a=&b='); + st.equal(qs.stringify({ a: null, b: '' }, { strictNullHandling: true }), 'a&b='); + + st.equal(qs.stringify({ a: { b: '' } }), 'a%5Bb%5D='); + st.equal(qs.stringify({ a: { b: null } }, { strictNullHandling: true }), 'a%5Bb%5D'); + st.equal(qs.stringify({ a: { b: null } }, { strictNullHandling: false }), 'a%5Bb%5D='); + + st.end(); + }); + + t.test('stringifies an empty array in different arrayFormat', function (st) { + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false }), 'b[0]=&c=c'); + // arrayFormat default + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'indices' }), 'b[0]=&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets' }), 'b[]=&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'repeat' }), 'b=&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma' }), 'b=&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', commaRoundTrip: true }), 'b[]=&c=c'); + // with strictNullHandling + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'indices', strictNullHandling: true }), 'b[0]&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets', strictNullHandling: true }), 'b[]&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'repeat', strictNullHandling: true }), 'b&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', strictNullHandling: true }), 'b&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', strictNullHandling: true, commaRoundTrip: true }), 'b[]&c=c'); + // with skipNulls + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'indices', skipNulls: true }), 'c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets', skipNulls: true }), 'c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'repeat', skipNulls: true }), 'c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', skipNulls: true }), 'c=c'); + + st.end(); + }); + + t.test('stringifies a null object', { skip: !hasProto }, function (st) { + st.equal(qs.stringify({ __proto__: null, a: 'b' }), 'a=b'); + st.end(); + }); + + t.test('returns an empty string for invalid input', function (st) { + st.equal(qs.stringify(undefined), ''); + st.equal(qs.stringify(false), ''); + st.equal(qs.stringify(null), ''); + st.equal(qs.stringify(''), ''); + st.end(); + }); + + t.test('stringifies an object with a null object as a child', { skip: !hasProto }, function (st) { + st.equal(qs.stringify({ a: { __proto__: null, b: 'c' } }), 'a%5Bb%5D=c'); + st.end(); + }); + + t.test('drops keys with a value of undefined', function (st) { + st.equal(qs.stringify({ a: undefined }), ''); + + st.equal(qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: true }), 'a%5Bc%5D'); + st.equal(qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: false }), 'a%5Bc%5D='); + st.equal(qs.stringify({ a: { b: undefined, c: '' } }), 'a%5Bc%5D='); + st.end(); + }); + + t.test('url encodes values', function (st) { + st.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); + st.end(); + }); + + t.test('stringifies a date', function (st) { + var now = new Date(); + var str = 'a=' + encodeURIComponent(now.toISOString()); + st.equal(qs.stringify({ a: now }), str); + st.end(); + }); + + t.test('stringifies the weird object from qs', function (st) { + st.equal(qs.stringify({ 'my weird field': '~q1!2"\'w$5&7/z8)?' }), 'my%20weird%20field=~q1%212%22%27w%245%267%2Fz8%29%3F'); + st.end(); + }); + + t.test('skips properties that are part of the object prototype', function (st) { + st.intercept(Object.prototype, 'crash', { value: 'test' }); + + st.equal(qs.stringify({ a: 'b' }), 'a=b'); + st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); + + st.end(); + }); + + t.test('stringifies boolean values', function (st) { + st.equal(qs.stringify({ a: true }), 'a=true'); + st.equal(qs.stringify({ a: { b: true } }), 'a%5Bb%5D=true'); + st.equal(qs.stringify({ b: false }), 'b=false'); + st.equal(qs.stringify({ b: { c: false } }), 'b%5Bc%5D=false'); + st.end(); + }); + + t.test('stringifies buffer values', function (st) { + st.equal(qs.stringify({ a: SaferBuffer.from('test') }), 'a=test'); + st.equal(qs.stringify({ a: { b: SaferBuffer.from('test') } }), 'a%5Bb%5D=test'); + st.end(); + }); + + t.test('stringifies an object using an alternative delimiter', function (st) { + st.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d'); + st.end(); + }); + + t.test('does not blow up when Buffer global is missing', function (st) { + var restore = mockProperty(global, 'Buffer', { 'delete': true }); + + var result = qs.stringify({ a: 'b', c: 'd' }); + + restore(); + + st.equal(result, 'a=b&c=d'); + st.end(); + }); + + t.test('does not crash when parsing circular references', function (st) { + var a = {}; + a.b = a; + + st['throws']( + function () { qs.stringify({ 'foo[bar]': 'baz', 'foo[baz]': a }); }, + /RangeError: Cyclic object value/, + 'cyclic values throw' + ); + + var circular = { + a: 'value' + }; + circular.a = circular; + st['throws']( + function () { qs.stringify(circular); }, + /RangeError: Cyclic object value/, + 'cyclic values throw' + ); + + var arr = ['a']; + st.doesNotThrow( + function () { qs.stringify({ x: arr, y: arr }); }, + 'non-cyclic values do not throw' + ); + + st.end(); + }); + + t.test('non-circular duplicated references can still work', function (st) { + var hourOfDay = { + 'function': 'hour_of_day' + }; + + var p1 = { + 'function': 'gte', + arguments: [hourOfDay, 0] + }; + var p2 = { + 'function': 'lte', + arguments: [hourOfDay, 23] + }; + + st.equal( + qs.stringify({ filters: { $and: [p1, p2] } }, { encodeValuesOnly: true, arrayFormat: 'indices' }), + 'filters[$and][0][function]=gte&filters[$and][0][arguments][0][function]=hour_of_day&filters[$and][0][arguments][1]=0&filters[$and][1][function]=lte&filters[$and][1][arguments][0][function]=hour_of_day&filters[$and][1][arguments][1]=23' + ); + st.equal( + qs.stringify({ filters: { $and: [p1, p2] } }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), + 'filters[$and][][function]=gte&filters[$and][][arguments][][function]=hour_of_day&filters[$and][][arguments][]=0&filters[$and][][function]=lte&filters[$and][][arguments][][function]=hour_of_day&filters[$and][][arguments][]=23' + ); + st.equal( + qs.stringify({ filters: { $and: [p1, p2] } }, { encodeValuesOnly: true, arrayFormat: 'repeat' }), + 'filters[$and][function]=gte&filters[$and][arguments][function]=hour_of_day&filters[$and][arguments]=0&filters[$and][function]=lte&filters[$and][arguments][function]=hour_of_day&filters[$and][arguments]=23' + ); + + st.end(); + }); + + t.test('selects properties when filter=array', function (st) { + st.equal(qs.stringify({ a: 'b' }, { filter: ['a'] }), 'a=b'); + st.equal(qs.stringify({ a: 1 }, { filter: [] }), ''); + + st.equal( + qs.stringify( + { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, + { filter: ['a', 'b', 0, 2], arrayFormat: 'indices' } + ), + 'a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3', + 'indices => indices' + ); + st.equal( + qs.stringify( + { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, + { filter: ['a', 'b', 0, 2], arrayFormat: 'brackets' } + ), + 'a%5Bb%5D%5B%5D=1&a%5Bb%5D%5B%5D=3', + 'brackets => brackets' + ); + st.equal( + qs.stringify( + { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, + { filter: ['a', 'b', 0, 2] } + ), + 'a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3', + 'default => indices' + ); + + st.end(); + }); + + t.test('supports custom representations when filter=function', function (st) { + var calls = 0; + var obj = { a: 'b', c: 'd', e: { f: new Date(1257894000000) } }; + var filterFunc = function (prefix, value) { + calls += 1; + if (calls === 1) { + st.equal(prefix, '', 'prefix is empty'); + st.equal(value, obj); + } else if (prefix === 'c') { + return void 0; + } else if (value instanceof Date) { + st.equal(prefix, 'e[f]'); + return value.getTime(); + } + return value; + }; + + st.equal(qs.stringify(obj, { filter: filterFunc }), 'a=b&e%5Bf%5D=1257894000000'); + st.equal(calls, 5); + st.end(); + }); + + t.test('can disable uri encoding', function (st) { + st.equal(qs.stringify({ a: 'b' }, { encode: false }), 'a=b'); + st.equal(qs.stringify({ a: { b: 'c' } }, { encode: false }), 'a[b]=c'); + st.equal(qs.stringify({ a: 'b', c: null }, { strictNullHandling: true, encode: false }), 'a=b&c'); + st.end(); + }); + + t.test('can sort the keys', function (st) { + var sort = function (a, b) { + return a.localeCompare(b); + }; + st.equal(qs.stringify({ a: 'c', z: 'y', b: 'f' }, { sort: sort }), 'a=c&b=f&z=y'); + st.equal(qs.stringify({ a: 'c', z: { j: 'a', i: 'b' }, b: 'f' }, { sort: sort }), 'a=c&b=f&z%5Bi%5D=b&z%5Bj%5D=a'); + st.end(); + }); + + t.test('can sort the keys at depth 3 or more too', function (st) { + var sort = function (a, b) { + return a.localeCompare(b); + }; + st.equal( + qs.stringify( + { a: 'a', z: { zj: { zjb: 'zjb', zja: 'zja' }, zi: { zib: 'zib', zia: 'zia' } }, b: 'b' }, + { sort: sort, encode: false } + ), + 'a=a&b=b&z[zi][zia]=zia&z[zi][zib]=zib&z[zj][zja]=zja&z[zj][zjb]=zjb' + ); + st.equal( + qs.stringify( + { a: 'a', z: { zj: { zjb: 'zjb', zja: 'zja' }, zi: { zib: 'zib', zia: 'zia' } }, b: 'b' }, + { sort: null, encode: false } + ), + 'a=a&z[zj][zjb]=zjb&z[zj][zja]=zja&z[zi][zib]=zib&z[zi][zia]=zia&b=b' + ); + st.end(); + }); + + t.test('can stringify with custom encoding', function (st) { + st.equal(qs.stringify({ 県: '大阪府', '': '' }, { + encoder: function (str) { + if (str.length === 0) { + return ''; + } + var buf = iconv.encode(str, 'shiftjis'); + var result = []; + for (var i = 0; i < buf.length; ++i) { + result.push(buf.readUInt8(i).toString(16)); + } + return '%' + result.join('%'); + } + }), '%8c%a7=%91%e5%8d%e3%95%7b&='); + st.end(); + }); + + t.test('receives the default encoder as a second argument', function (st) { + st.plan(8); + + qs.stringify({ a: 1, b: new Date(), c: true, d: [1] }, { + encoder: function (str) { + st.match(typeof str, /^(?:string|number|boolean)$/); + return ''; + } + }); + + st.end(); + }); + + t.test('receives the default encoder as a second argument', function (st) { + st.plan(2); + + qs.stringify({ a: 1 }, { + encoder: function (str, defaultEncoder) { + st.equal(defaultEncoder, utils.encode); + } + }); + + st.end(); + }); + + t.test('throws error with wrong encoder', function (st) { + st['throws'](function () { + qs.stringify({}, { encoder: 'string' }); + }, new TypeError('Encoder has to be a function.')); + st.end(); + }); + + t.test('can use custom encoder for a buffer object', { skip: typeof Buffer === 'undefined' }, function (st) { + st.equal(qs.stringify({ a: SaferBuffer.from([1]) }, { + encoder: function (buffer) { + if (typeof buffer === 'string') { + return buffer; + } + return String.fromCharCode(buffer.readUInt8(0) + 97); + } + }), 'a=b'); + + st.equal(qs.stringify({ a: SaferBuffer.from('a b') }, { + encoder: function (buffer) { + return buffer; + } + }), 'a=a b'); + st.end(); + }); + + t.test('serializeDate option', function (st) { + var date = new Date(); + st.equal( + qs.stringify({ a: date }), + 'a=' + date.toISOString().replace(/:/g, '%3A'), + 'default is toISOString' + ); + + var mutatedDate = new Date(); + mutatedDate.toISOString = function () { + throw new SyntaxError(); + }; + st['throws'](function () { + mutatedDate.toISOString(); + }, SyntaxError); + st.equal( + qs.stringify({ a: mutatedDate }), + 'a=' + Date.prototype.toISOString.call(mutatedDate).replace(/:/g, '%3A'), + 'toISOString works even when method is not locally present' + ); + + var specificDate = new Date(6); + st.equal( + qs.stringify( + { a: specificDate }, + { serializeDate: function (d) { return d.getTime() * 7; } } + ), + 'a=42', + 'custom serializeDate function called' + ); + + st.equal( + qs.stringify( + { a: [date] }, + { + serializeDate: function (d) { return d.getTime(); }, + arrayFormat: 'comma' + } + ), + 'a=' + date.getTime(), + 'works with arrayFormat comma' + ); + st.equal( + qs.stringify( + { a: [date] }, + { + serializeDate: function (d) { return d.getTime(); }, + arrayFormat: 'comma', + commaRoundTrip: true + } + ), + 'a%5B%5D=' + date.getTime(), + 'works with arrayFormat comma' + ); + + st.end(); + }); + + t.test('RFC 1738 serialization', function (st) { + st.equal(qs.stringify({ a: 'b c' }, { format: qs.formats.RFC1738 }), 'a=b+c'); + st.equal(qs.stringify({ 'a b': 'c d' }, { format: qs.formats.RFC1738 }), 'a+b=c+d'); + st.equal(qs.stringify({ 'a b': SaferBuffer.from('a b') }, { format: qs.formats.RFC1738 }), 'a+b=a+b'); + + st.equal(qs.stringify({ 'foo(ref)': 'bar' }, { format: qs.formats.RFC1738 }), 'foo(ref)=bar'); + + st.end(); + }); + + t.test('RFC 3986 spaces serialization', function (st) { + st.equal(qs.stringify({ a: 'b c' }, { format: qs.formats.RFC3986 }), 'a=b%20c'); + st.equal(qs.stringify({ 'a b': 'c d' }, { format: qs.formats.RFC3986 }), 'a%20b=c%20d'); + st.equal(qs.stringify({ 'a b': SaferBuffer.from('a b') }, { format: qs.formats.RFC3986 }), 'a%20b=a%20b'); + + st.end(); + }); + + t.test('Backward compatibility to RFC 3986', function (st) { + st.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); + st.equal(qs.stringify({ 'a b': SaferBuffer.from('a b') }), 'a%20b=a%20b'); + + st.end(); + }); + + t.test('Edge cases and unknown formats', function (st) { + ['UFO1234', false, 1234, null, {}, []].forEach(function (format) { + st['throws']( + function () { + qs.stringify({ a: 'b c' }, { format: format }); + }, + new TypeError('Unknown format option provided.') + ); + }); + st.end(); + }); + + t.test('encodeValuesOnly', function (st) { + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, + { encodeValuesOnly: true, arrayFormat: 'indices' } + ), + 'a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h', + 'encodeValuesOnly + indices' + ); + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, + { encodeValuesOnly: true, arrayFormat: 'brackets' } + ), + 'a=b&c[]=d&c[]=e%3Df&f[][]=g&f[][]=h', + 'encodeValuesOnly + brackets' + ); + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, + { encodeValuesOnly: true, arrayFormat: 'repeat' } + ), + 'a=b&c=d&c=e%3Df&f=g&f=h', + 'encodeValuesOnly + repeat' + ); + + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e'], f: [['g'], ['h']] }, + { arrayFormat: 'indices' } + ), + 'a=b&c%5B0%5D=d&c%5B1%5D=e&f%5B0%5D%5B0%5D=g&f%5B1%5D%5B0%5D=h', + 'no encodeValuesOnly + indices' + ); + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e'], f: [['g'], ['h']] }, + { arrayFormat: 'brackets' } + ), + 'a=b&c%5B%5D=d&c%5B%5D=e&f%5B%5D%5B%5D=g&f%5B%5D%5B%5D=h', + 'no encodeValuesOnly + brackets' + ); + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e'], f: [['g'], ['h']] }, + { arrayFormat: 'repeat' } + ), + 'a=b&c=d&c=e&f=g&f=h', + 'no encodeValuesOnly + repeat' + ); + + st.end(); + }); + + t.test('encodeValuesOnly - strictNullHandling', function (st) { + st.equal( + qs.stringify( + { a: { b: null } }, + { encodeValuesOnly: true, strictNullHandling: true } + ), + 'a[b]' + ); + st.end(); + }); + + t.test('throws if an invalid charset is specified', function (st) { + st['throws'](function () { + qs.stringify({ a: 'b' }, { charset: 'foobar' }); + }, new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined')); + st.end(); + }); + + t.test('respects a charset of iso-8859-1', function (st) { + st.equal(qs.stringify({ æ: 'æ' }, { charset: 'iso-8859-1' }), '%E6=%E6'); + st.end(); + }); + + t.test('encodes unrepresentable chars as numeric entities in iso-8859-1 mode', function (st) { + st.equal(qs.stringify({ a: '☺' }, { charset: 'iso-8859-1' }), 'a=%26%239786%3B'); + st.end(); + }); + + t.test('respects an explicit charset of utf-8 (the default)', function (st) { + st.equal(qs.stringify({ a: 'æ' }, { charset: 'utf-8' }), 'a=%C3%A6'); + st.end(); + }); + + t.test('`charsetSentinel` option', function (st) { + st.equal( + qs.stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'utf-8' }), + 'utf8=%E2%9C%93&a=%C3%A6', + 'adds the right sentinel when instructed to and the charset is utf-8' + ); + + st.equal( + qs.stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'iso-8859-1' }), + 'utf8=%26%2310003%3B&a=%E6', + 'adds the right sentinel when instructed to and the charset is iso-8859-1' + ); + + st.end(); + }); + + t.test('does not mutate the options argument', function (st) { + var options = {}; + qs.stringify({}, options); + st.deepEqual(options, {}); + st.end(); + }); + + t.test('strictNullHandling works with custom filter', function (st) { + var filter = function (prefix, value) { + return value; + }; + + var options = { strictNullHandling: true, filter: filter }; + st.equal(qs.stringify({ key: null }, options), 'key'); + st.end(); + }); + + t.test('strictNullHandling works with null serializeDate', function (st) { + var serializeDate = function () { + return null; + }; + var options = { strictNullHandling: true, serializeDate: serializeDate }; + var date = new Date(); + st.equal(qs.stringify({ key: date }, options), 'key'); + st.end(); + }); + + t.test('allows for encoding keys and values differently', function (st) { + var encoder = function (str, defaultEncoder, charset, type) { + if (type === 'key') { + return defaultEncoder(str, defaultEncoder, charset, type).toLowerCase(); + } + if (type === 'value') { + return defaultEncoder(str, defaultEncoder, charset, type).toUpperCase(); + } + throw 'this should never happen! type: ' + type; + }; + + st.deepEqual(qs.stringify({ KeY: 'vAlUe' }, { encoder: encoder }), 'key=VALUE'); + st.end(); + }); + + t.test('objects inside arrays', function (st) { + var obj = { a: { b: { c: 'd', e: 'f' } } }; + var withArray = { a: { b: [{ c: 'd', e: 'f' }] } }; + + st.equal(qs.stringify(obj, { encode: false }), 'a[b][c]=d&a[b][e]=f', 'no array, no arrayFormat'); + st.equal(qs.stringify(obj, { encode: false, arrayFormat: 'brackets' }), 'a[b][c]=d&a[b][e]=f', 'no array, bracket'); + st.equal(qs.stringify(obj, { encode: false, arrayFormat: 'indices' }), 'a[b][c]=d&a[b][e]=f', 'no array, indices'); + st.equal(qs.stringify(obj, { encode: false, arrayFormat: 'repeat' }), 'a[b][c]=d&a[b][e]=f', 'no array, repeat'); + st.equal(qs.stringify(obj, { encode: false, arrayFormat: 'comma' }), 'a[b][c]=d&a[b][e]=f', 'no array, comma'); + + st.equal(qs.stringify(withArray, { encode: false }), 'a[b][0][c]=d&a[b][0][e]=f', 'array, no arrayFormat'); + st.equal(qs.stringify(withArray, { encode: false, arrayFormat: 'brackets' }), 'a[b][][c]=d&a[b][][e]=f', 'array, bracket'); + st.equal(qs.stringify(withArray, { encode: false, arrayFormat: 'indices' }), 'a[b][0][c]=d&a[b][0][e]=f', 'array, indices'); + st.equal(qs.stringify(withArray, { encode: false, arrayFormat: 'repeat' }), 'a[b][c]=d&a[b][e]=f', 'array, repeat'); + st.equal( + qs.stringify(withArray, { encode: false, arrayFormat: 'comma' }), + '???', + 'array, comma', + { skip: 'TODO: figure out what this should do' } + ); + + st.end(); + }); + + t.test('stringifies sparse arrays', function (st) { + /* eslint no-sparse-arrays: 0 */ + st.equal(qs.stringify({ a: [, '2', , , '1'] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[1]=2&a[4]=1'); + st.equal(qs.stringify({ a: [, '2', , , '1'] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[]=2&a[]=1'); + st.equal(qs.stringify({ a: [, '2', , , '1'] }, { encodeValuesOnly: true, arrayFormat: 'repeat' }), 'a=2&a=1'); + + st.equal(qs.stringify({ a: [, { b: [, , { c: '1' }] }] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[1][b][2][c]=1'); + st.equal(qs.stringify({ a: [, { b: [, , { c: '1' }] }] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[][b][][c]=1'); + st.equal(qs.stringify({ a: [, { b: [, , { c: '1' }] }] }, { encodeValuesOnly: true, arrayFormat: 'repeat' }), 'a[b][c]=1'); + + st.equal(qs.stringify({ a: [, [, , [, , , { c: '1' }]]] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[1][2][3][c]=1'); + st.equal(qs.stringify({ a: [, [, , [, , , { c: '1' }]]] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[][][][c]=1'); + st.equal(qs.stringify({ a: [, [, , [, , , { c: '1' }]]] }, { encodeValuesOnly: true, arrayFormat: 'repeat' }), 'a[c]=1'); + + st.equal(qs.stringify({ a: [, [, , [, , , { c: [, '1'] }]]] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[1][2][3][c][1]=1'); + st.equal(qs.stringify({ a: [, [, , [, , , { c: [, '1'] }]]] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[][][][c][]=1'); + st.equal(qs.stringify({ a: [, [, , [, , , { c: [, '1'] }]]] }, { encodeValuesOnly: true, arrayFormat: 'repeat' }), 'a[c]=1'); + + st.end(); + }); + + t.test('encodes a very long string', function (st) { + var chars = []; + var expected = []; + for (var i = 0; i < 5e3; i++) { + chars.push(' ' + i); + + expected.push('%20' + i); + } + + var obj = { + foo: chars.join('') + }; + + st.equal( + qs.stringify(obj, { arrayFormat: 'brackets', charset: 'utf-8' }), + 'foo=' + expected.join('') + ); + + st.end(); + }); + + t.end(); +}); + +test('stringifies empty keys', function (t) { + emptyTestCases.forEach(function (testCase) { + t.test('stringifies an object with empty string key with ' + testCase.input, function (st) { + st.deepEqual( + qs.stringify(testCase.withEmptyKeys, { encode: false, arrayFormat: 'indices' }), + testCase.stringifyOutput.indices, + 'test case: ' + testCase.input + ', indices' + ); + st.deepEqual( + qs.stringify(testCase.withEmptyKeys, { encode: false, arrayFormat: 'brackets' }), + testCase.stringifyOutput.brackets, + 'test case: ' + testCase.input + ', brackets' + ); + st.deepEqual( + qs.stringify(testCase.withEmptyKeys, { encode: false, arrayFormat: 'repeat' }), + testCase.stringifyOutput.repeat, + 'test case: ' + testCase.input + ', repeat' + ); + + st.end(); + }); + }); + + t.test('edge case with object/arrays', function (st) { + st.deepEqual(qs.stringify({ '': { '': [2, 3] } }, { encode: false }), '[][0]=2&[][1]=3'); + st.deepEqual(qs.stringify({ '': { '': [2, 3], a: 2 } }, { encode: false }), '[][0]=2&[][1]=3&[a]=2'); + st.deepEqual(qs.stringify({ '': { '': [2, 3] } }, { encode: false, arrayFormat: 'indices' }), '[][0]=2&[][1]=3'); + st.deepEqual(qs.stringify({ '': { '': [2, 3], a: 2 } }, { encode: false, arrayFormat: 'indices' }), '[][0]=2&[][1]=3&[a]=2'); + + st.end(); + }); + + t.test('stringifies non-string keys', function (st) { + var actual = qs.stringify({ a: 'b', 'false': {} }, { + filter: ['a', false, null], + allowDots: true, + encodeDotInKeys: true + }); + + st.equal(actual, 'a=b', 'stringifies correctly'); + + st.end(); + }); +}); diff --git a/node_modules/qs/test/utils.js b/node_modules/qs/test/utils.js new file mode 100644 index 0000000..3933516 --- /dev/null +++ b/node_modules/qs/test/utils.js @@ -0,0 +1,262 @@ +'use strict'; + +var test = require('tape'); +var inspect = require('object-inspect'); +var SaferBuffer = require('safer-buffer').Buffer; +var forEach = require('for-each'); +var v = require('es-value-fixtures'); + +var utils = require('../lib/utils'); + +test('merge()', function (t) { + t.deepEqual(utils.merge(null, true), [null, true], 'merges true into null'); + + t.deepEqual(utils.merge(null, [42]), [null, 42], 'merges null into an array'); + + t.deepEqual(utils.merge({ a: 'b' }, { a: 'c' }), { a: ['b', 'c'] }, 'merges two objects with the same key'); + + var oneMerged = utils.merge({ foo: 'bar' }, { foo: { first: '123' } }); + t.deepEqual(oneMerged, { foo: ['bar', { first: '123' }] }, 'merges a standalone and an object into an array'); + + var twoMerged = utils.merge({ foo: ['bar', { first: '123' }] }, { foo: { second: '456' } }); + t.deepEqual(twoMerged, { foo: { 0: 'bar', 1: { first: '123' }, second: '456' } }, 'merges a standalone and two objects into an array'); + + var sandwiched = utils.merge({ foo: ['bar', { first: '123', second: '456' }] }, { foo: 'baz' }); + t.deepEqual(sandwiched, { foo: ['bar', { first: '123', second: '456' }, 'baz'] }, 'merges an object sandwiched by two standalones into an array'); + + var nestedArrays = utils.merge({ foo: ['baz'] }, { foo: ['bar', 'xyzzy'] }); + t.deepEqual(nestedArrays, { foo: ['baz', 'bar', 'xyzzy'] }); + + var noOptionsNonObjectSource = utils.merge({ foo: 'baz' }, 'bar'); + t.deepEqual(noOptionsNonObjectSource, { foo: 'baz', bar: true }); + + var func = function f() {}; + t.deepEqual( + utils.merge(func, { foo: 'bar' }), + [func, { foo: 'bar' }], + 'functions can not be merged into' + ); + + func.bar = 'baz'; + t.deepEqual( + utils.merge({ foo: 'bar' }, func), + { foo: 'bar', bar: 'baz' }, + 'functions can be merge sources' + ); + + t.test( + 'avoids invoking array setters unnecessarily', + { skip: typeof Object.defineProperty !== 'function' }, + function (st) { + var setCount = 0; + var getCount = 0; + var observed = []; + Object.defineProperty(observed, 0, { + get: function () { + getCount += 1; + return { bar: 'baz' }; + }, + set: function () { setCount += 1; } + }); + utils.merge(observed, [null]); + st.equal(setCount, 0); + st.equal(getCount, 1); + observed[0] = observed[0]; // eslint-disable-line no-self-assign + st.equal(setCount, 1); + st.equal(getCount, 2); + st.end(); + } + ); + + t.end(); +}); + +test('assign()', function (t) { + var target = { a: 1, b: 2 }; + var source = { b: 3, c: 4 }; + var result = utils.assign(target, source); + + t.equal(result, target, 'returns the target'); + t.deepEqual(target, { a: 1, b: 3, c: 4 }, 'target and source are merged'); + t.deepEqual(source, { b: 3, c: 4 }, 'source is untouched'); + + t.end(); +}); + +test('combine()', function (t) { + t.test('both arrays', function (st) { + var a = [1]; + var b = [2]; + var combined = utils.combine(a, b); + + st.deepEqual(a, [1], 'a is not mutated'); + st.deepEqual(b, [2], 'b is not mutated'); + st.notEqual(a, combined, 'a !== combined'); + st.notEqual(b, combined, 'b !== combined'); + st.deepEqual(combined, [1, 2], 'combined is a + b'); + + st.end(); + }); + + t.test('one array, one non-array', function (st) { + var aN = 1; + var a = [aN]; + var bN = 2; + var b = [bN]; + + var combinedAnB = utils.combine(aN, b); + st.deepEqual(b, [bN], 'b is not mutated'); + st.notEqual(aN, combinedAnB, 'aN + b !== aN'); + st.notEqual(a, combinedAnB, 'aN + b !== a'); + st.notEqual(bN, combinedAnB, 'aN + b !== bN'); + st.notEqual(b, combinedAnB, 'aN + b !== b'); + st.deepEqual([1, 2], combinedAnB, 'first argument is array-wrapped when not an array'); + + var combinedABn = utils.combine(a, bN); + st.deepEqual(a, [aN], 'a is not mutated'); + st.notEqual(aN, combinedABn, 'a + bN !== aN'); + st.notEqual(a, combinedABn, 'a + bN !== a'); + st.notEqual(bN, combinedABn, 'a + bN !== bN'); + st.notEqual(b, combinedABn, 'a + bN !== b'); + st.deepEqual([1, 2], combinedABn, 'second argument is array-wrapped when not an array'); + + st.end(); + }); + + t.test('neither is an array', function (st) { + var combined = utils.combine(1, 2); + st.notEqual(1, combined, '1 + 2 !== 1'); + st.notEqual(2, combined, '1 + 2 !== 2'); + st.deepEqual([1, 2], combined, 'both arguments are array-wrapped when not an array'); + + st.end(); + }); + + t.end(); +}); + +test('decode', function (t) { + t.equal( + utils.decode('a+b'), + 'a b', + 'decodes + to space' + ); + + t.equal( + utils.decode('name%2Eobj'), + 'name.obj', + 'decodes a string' + ); + t.equal( + utils.decode('name%2Eobj%2Efoo', null, 'iso-8859-1'), + 'name.obj.foo', + 'decodes a string in iso-8859-1' + ); + + t.end(); +}); + +test('encode', function (t) { + forEach(v.nullPrimitives, function (nullish) { + t['throws']( + function () { utils.encode(nullish); }, + TypeError, + inspect(nullish) + ' is not a string' + ); + }); + + t.equal(utils.encode(''), '', 'empty string returns itself'); + t.deepEqual(utils.encode([]), [], 'empty array returns itself'); + t.deepEqual(utils.encode({ length: 0 }), { length: 0 }, 'empty arraylike returns itself'); + + t.test('symbols', { skip: !v.hasSymbols }, function (st) { + st.equal(utils.encode(Symbol('x')), 'Symbol%28x%29', 'symbol is encoded'); + + st.end(); + }); + + t.equal( + utils.encode('(abc)'), + '%28abc%29', + 'encodes parentheses' + ); + t.equal( + utils.encode({ toString: function () { return '(abc)'; } }), + '%28abc%29', + 'toStrings and encodes parentheses' + ); + + t.equal( + utils.encode('abc 123 💩', null, 'iso-8859-1'), + 'abc%20123%20%26%2355357%3B%26%2356489%3B', + 'encodes in iso-8859-1' + ); + + var longString = ''; + var expectedString = ''; + for (var i = 0; i < 1500; i++) { + longString += ' '; + expectedString += '%20'; + } + + t.equal( + utils.encode(longString), + expectedString, + 'encodes a long string' + ); + + t.equal( + utils.encode('\x28\x29'), + '%28%29', + 'encodes parens normally' + ); + t.equal( + utils.encode('\x28\x29', null, null, null, 'RFC1738'), + '()', + 'does not encode parens in RFC1738' + ); + + // todo RFC1738 format + + t.equal( + utils.encode('Āက豈'), + '%C4%80%E1%80%80%EF%A4%80', + 'encodes multibyte chars' + ); + + t.equal( + utils.encode('\uD83D \uDCA9'), + '%F0%9F%90%A0%F0%BA%90%80', + 'encodes lone surrogates' + ); + + t.end(); +}); + +test('isBuffer()', function (t) { + forEach([null, undefined, true, false, '', 'abc', 42, 0, NaN, {}, [], function () {}, /a/g], function (x) { + t.equal(utils.isBuffer(x), false, inspect(x) + ' is not a buffer'); + }); + + var fakeBuffer = { constructor: Buffer }; + t.equal(utils.isBuffer(fakeBuffer), false, 'fake buffer is not a buffer'); + + var saferBuffer = SaferBuffer.from('abc'); + t.equal(utils.isBuffer(saferBuffer), true, 'SaferBuffer instance is a buffer'); + + var buffer = Buffer.from && Buffer.alloc ? Buffer.from('abc') : new Buffer('abc'); + t.equal(utils.isBuffer(buffer), true, 'real Buffer instance is a buffer'); + t.end(); +}); + +test('isRegExp()', function (t) { + t.equal(utils.isRegExp(/a/g), true, 'RegExp is a RegExp'); + t.equal(utils.isRegExp(new RegExp('a', 'g')), true, 'new RegExp is a RegExp'); + t.equal(utils.isRegExp(new Date()), false, 'Date is not a RegExp'); + + forEach(v.primitives, function (primitive) { + t.equal(utils.isRegExp(primitive), false, inspect(primitive) + ' is not a RegExp'); + }); + + t.end(); +}); diff --git a/node_modules/range-parser/HISTORY.md b/node_modules/range-parser/HISTORY.md new file mode 100644 index 0000000..70a973d --- /dev/null +++ b/node_modules/range-parser/HISTORY.md @@ -0,0 +1,56 @@ +1.2.1 / 2019-05-10 +================== + + * Improve error when `str` is not a string + +1.2.0 / 2016-06-01 +================== + + * Add `combine` option to combine overlapping ranges + +1.1.0 / 2016-05-13 +================== + + * Fix incorrectly returning -1 when there is at least one valid range + * perf: remove internal function + +1.0.3 / 2015-10-29 +================== + + * perf: enable strict mode + +1.0.2 / 2014-09-08 +================== + + * Support Node.js 0.6 + +1.0.1 / 2014-09-07 +================== + + * Move repository to jshttp + +1.0.0 / 2013-12-11 +================== + + * Add repository to package.json + * Add MIT license + +0.0.4 / 2012-06-17 +================== + + * Change ret -1 for unsatisfiable and -2 when invalid + +0.0.3 / 2012-06-17 +================== + + * Fix last-byte-pos default to len - 1 + +0.0.2 / 2012-06-14 +================== + + * Add `.type` + +0.0.1 / 2012-06-11 +================== + + * Initial release diff --git a/node_modules/range-parser/LICENSE b/node_modules/range-parser/LICENSE new file mode 100644 index 0000000..3599954 --- /dev/null +++ b/node_modules/range-parser/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012-2014 TJ Holowaychuk +Copyright (c) 2015-2016 Douglas Christopher Wilson + +```js +var parseRange = require('range-parser') +``` + +### parseRange(size, header, options) + +Parse the given `header` string where `size` is the maximum size of the resource. +An array of ranges will be returned or negative numbers indicating an error parsing. + + * `-2` signals a malformed header string + * `-1` signals an unsatisfiable range + + + +```js +// parse header from request +var range = parseRange(size, req.headers.range) + +// the type of the range +if (range.type === 'bytes') { + // the ranges + range.forEach(function (r) { + // do something with r.start and r.end + }) +} +``` + +#### Options + +These properties are accepted in the options object. + +##### combine + +Specifies if overlapping & adjacent ranges should be combined, defaults to `false`. +When `true`, ranges will be combined and returned as if they were specified that +way in the header. + + + +```js +parseRange(100, 'bytes=50-55,0-10,5-10,56-60', { combine: true }) +// => [ +// { start: 0, end: 10 }, +// { start: 50, end: 60 } +// ] +``` + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/range-parser/master +[coveralls-url]: https://coveralls.io/r/jshttp/range-parser?branch=master +[node-image]: https://badgen.net/npm/node/range-parser +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/range-parser +[npm-url]: https://npmjs.org/package/range-parser +[npm-version-image]: https://badgen.net/npm/v/range-parser +[travis-image]: https://badgen.net/travis/jshttp/range-parser/master +[travis-url]: https://travis-ci.org/jshttp/range-parser diff --git a/node_modules/range-parser/index.js b/node_modules/range-parser/index.js new file mode 100644 index 0000000..b7dc5c0 --- /dev/null +++ b/node_modules/range-parser/index.js @@ -0,0 +1,162 @@ +/*! + * range-parser + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = rangeParser + +/** + * Parse "Range" header `str` relative to the given file `size`. + * + * @param {Number} size + * @param {String} str + * @param {Object} [options] + * @return {Array} + * @public + */ + +function rangeParser (size, str, options) { + if (typeof str !== 'string') { + throw new TypeError('argument str must be a string') + } + + var index = str.indexOf('=') + + if (index === -1) { + return -2 + } + + // split the range string + var arr = str.slice(index + 1).split(',') + var ranges = [] + + // add ranges type + ranges.type = str.slice(0, index) + + // parse all ranges + for (var i = 0; i < arr.length; i++) { + var range = arr[i].split('-') + var start = parseInt(range[0], 10) + var end = parseInt(range[1], 10) + + // -nnn + if (isNaN(start)) { + start = size - end + end = size - 1 + // nnn- + } else if (isNaN(end)) { + end = size - 1 + } + + // limit last-byte-pos to current length + if (end > size - 1) { + end = size - 1 + } + + // invalid or unsatisifiable + if (isNaN(start) || isNaN(end) || start > end || start < 0) { + continue + } + + // add range + ranges.push({ + start: start, + end: end + }) + } + + if (ranges.length < 1) { + // unsatisifiable + return -1 + } + + return options && options.combine + ? combineRanges(ranges) + : ranges +} + +/** + * Combine overlapping & adjacent ranges. + * @private + */ + +function combineRanges (ranges) { + var ordered = ranges.map(mapWithIndex).sort(sortByRangeStart) + + for (var j = 0, i = 1; i < ordered.length; i++) { + var range = ordered[i] + var current = ordered[j] + + if (range.start > current.end + 1) { + // next range + ordered[++j] = range + } else if (range.end > current.end) { + // extend range + current.end = range.end + current.index = Math.min(current.index, range.index) + } + } + + // trim ordered array + ordered.length = j + 1 + + // generate combined range + var combined = ordered.sort(sortByRangeIndex).map(mapWithoutIndex) + + // copy ranges type + combined.type = ranges.type + + return combined +} + +/** + * Map function to add index value to ranges. + * @private + */ + +function mapWithIndex (range, index) { + return { + start: range.start, + end: range.end, + index: index + } +} + +/** + * Map function to remove index value from ranges. + * @private + */ + +function mapWithoutIndex (range) { + return { + start: range.start, + end: range.end + } +} + +/** + * Sort function to sort ranges by index. + * @private + */ + +function sortByRangeIndex (a, b) { + return a.index - b.index +} + +/** + * Sort function to sort ranges by start position. + * @private + */ + +function sortByRangeStart (a, b) { + return a.start - b.start +} diff --git a/node_modules/range-parser/package.json b/node_modules/range-parser/package.json new file mode 100644 index 0000000..abea6d8 --- /dev/null +++ b/node_modules/range-parser/package.json @@ -0,0 +1,44 @@ +{ + "name": "range-parser", + "author": "TJ Holowaychuk (http://tjholowaychuk.com)", + "description": "Range header field string parser", + "version": "1.2.1", + "contributors": [ + "Douglas Christopher Wilson ", + "James Wyatt Cready ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "keywords": [ + "range", + "parser", + "http" + ], + "repository": "jshttp/range-parser", + "devDependencies": { + "deep-equal": "1.0.1", + "eslint": "5.16.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-markdown": "1.0.0", + "eslint-plugin-import": "2.17.2", + "eslint-plugin-node": "8.0.1", + "eslint-plugin-promise": "4.1.1", + "eslint-plugin-standard": "4.0.0", + "mocha": "6.1.4", + "nyc": "14.1.1" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "test-travis": "nyc --reporter=text npm test" + } +} diff --git a/node_modules/raw-body/HISTORY.md b/node_modules/raw-body/HISTORY.md new file mode 100644 index 0000000..a53dc9c --- /dev/null +++ b/node_modules/raw-body/HISTORY.md @@ -0,0 +1,325 @@ +3.0.0 / 2024-07-25 +================== + + * deps: iconv-lite@0.6.3 + - Fix HKSCS encoding to prefer Big5 codes + - Fix minor issue in UTF-32 decoder's endianness detection code + - Update 'gb18030' encoding to :2005 edition + +3.0.0-beta.1 / 2023-02-21 +========================= + + * Change TypeScript argument to `NodeJS.ReadableStream` interface + * Drop support for Node.js 0.8 + * deps: iconv-lite@0.5.2 + - Add encoding cp720 + - Add encoding UTF-32 + +2.5.2 / 2023-02-21 +================== + + * Fix error message for non-stream argument + +2.5.1 / 2022-02-28 +================== + + * Fix error on early async hooks implementations + +2.5.0 / 2022-02-21 +================== + + * Prevent loss of async hooks context + * Prevent hanging when stream is not readable + * deps: http-errors@2.0.0 + - deps: depd@2.0.0 + - deps: statuses@2.0.1 + +2.4.3 / 2022-02-14 +================== + + * deps: bytes@3.1.2 + +2.4.2 / 2021-11-16 +================== + + * deps: bytes@3.1.1 + * deps: http-errors@1.8.1 + - deps: setprototypeof@1.2.0 + - deps: toidentifier@1.0.1 + +2.4.1 / 2019-06-25 +================== + + * deps: http-errors@1.7.3 + - deps: inherits@2.0.4 + +2.4.0 / 2019-04-17 +================== + + * deps: bytes@3.1.0 + - Add petabyte (`pb`) support + * deps: http-errors@1.7.2 + - Set constructor name when possible + - deps: setprototypeof@1.1.1 + - deps: statuses@'>= 1.5.0 < 2' + * deps: iconv-lite@0.4.24 + - Added encoding MIK + +2.3.3 / 2018-05-08 +================== + + * deps: http-errors@1.6.3 + - deps: depd@~1.1.2 + - deps: setprototypeof@1.1.0 + - deps: statuses@'>= 1.3.1 < 2' + * deps: iconv-lite@0.4.23 + - Fix loading encoding with year appended + - Fix deprecation warnings on Node.js 10+ + +2.3.2 / 2017-09-09 +================== + + * deps: iconv-lite@0.4.19 + - Fix ISO-8859-1 regression + - Update Windows-1255 + +2.3.1 / 2017-09-07 +================== + + * deps: bytes@3.0.0 + * deps: http-errors@1.6.2 + - deps: depd@1.1.1 + * perf: skip buffer decoding on overage chunk + +2.3.0 / 2017-08-04 +================== + + * Add TypeScript definitions + * Use `http-errors` for standard emitted errors + * deps: bytes@2.5.0 + * deps: iconv-lite@0.4.18 + - Add support for React Native + - Add a warning if not loaded as utf-8 + - Fix CESU-8 decoding in Node.js 8 + - Improve speed of ISO-8859-1 encoding + +2.2.0 / 2017-01-02 +================== + + * deps: iconv-lite@0.4.15 + - Added encoding MS-31J + - Added encoding MS-932 + - Added encoding MS-936 + - Added encoding MS-949 + - Added encoding MS-950 + - Fix GBK/GB18030 handling of Euro character + +2.1.7 / 2016-06-19 +================== + + * deps: bytes@2.4.0 + * perf: remove double-cleanup on happy path + +2.1.6 / 2016-03-07 +================== + + * deps: bytes@2.3.0 + - Drop partial bytes on all parsed units + - Fix parsing byte string that looks like hex + +2.1.5 / 2015-11-30 +================== + + * deps: bytes@2.2.0 + * deps: iconv-lite@0.4.13 + +2.1.4 / 2015-09-27 +================== + + * Fix masking critical errors from `iconv-lite` + * deps: iconv-lite@0.4.12 + - Fix CESU-8 decoding in Node.js 4.x + +2.1.3 / 2015-09-12 +================== + + * Fix sync callback when attaching data listener causes sync read + - Node.js 0.10 compatibility issue + +2.1.2 / 2015-07-05 +================== + + * Fix error stack traces to skip `makeError` + * deps: iconv-lite@0.4.11 + - Add encoding CESU-8 + +2.1.1 / 2015-06-14 +================== + + * Use `unpipe` module for unpiping requests + +2.1.0 / 2015-05-28 +================== + + * deps: iconv-lite@0.4.10 + - Improved UTF-16 endianness detection + - Leading BOM is now removed when decoding + - The encoding UTF-16 without BOM now defaults to UTF-16LE when detection fails + +2.0.2 / 2015-05-21 +================== + + * deps: bytes@2.1.0 + - Slight optimizations + +2.0.1 / 2015-05-10 +================== + + * Fix a false-positive when unpiping in Node.js 0.8 + +2.0.0 / 2015-05-08 +================== + + * Return a promise without callback instead of thunk + * deps: bytes@2.0.1 + - units no longer case sensitive when parsing + +1.3.4 / 2015-04-15 +================== + + * Fix hanging callback if request aborts during read + * deps: iconv-lite@0.4.8 + - Add encoding alias UNICODE-1-1-UTF-7 + +1.3.3 / 2015-02-08 +================== + + * deps: iconv-lite@0.4.7 + - Gracefully support enumerables on `Object.prototype` + +1.3.2 / 2015-01-20 +================== + + * deps: iconv-lite@0.4.6 + - Fix rare aliases of single-byte encodings + +1.3.1 / 2014-11-21 +================== + + * deps: iconv-lite@0.4.5 + - Fix Windows-31J and X-SJIS encoding support + +1.3.0 / 2014-07-20 +================== + + * Fully unpipe the stream on error + - Fixes `Cannot switch to old mode now` error on Node.js 0.10+ + +1.2.3 / 2014-07-20 +================== + + * deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + +1.2.2 / 2014-06-19 +================== + + * Send invalid encoding error to callback + +1.2.1 / 2014-06-15 +================== + + * deps: iconv-lite@0.4.3 + - Added encodings UTF-16BE and UTF-16 with BOM + +1.2.0 / 2014-06-13 +================== + + * Passing string as `options` interpreted as encoding + * Support all encodings from `iconv-lite` + +1.1.7 / 2014-06-12 +================== + + * use `string_decoder` module from npm + +1.1.6 / 2014-05-27 +================== + + * check encoding for old streams1 + * support node.js < 0.10.6 + +1.1.5 / 2014-05-14 +================== + + * bump bytes + +1.1.4 / 2014-04-19 +================== + + * allow true as an option + * bump bytes + +1.1.3 / 2014-03-02 +================== + + * fix case when length=null + +1.1.2 / 2013-12-01 +================== + + * be less strict on state.encoding check + +1.1.1 / 2013-11-27 +================== + + * add engines + +1.1.0 / 2013-11-27 +================== + + * add err.statusCode and err.type + * allow for encoding option to be true + * pause the stream instead of dumping on error + * throw if the stream's encoding is set + +1.0.1 / 2013-11-19 +================== + + * dont support streams1, throw if dev set encoding + +1.0.0 / 2013-11-17 +================== + + * rename `expected` option to `length` + +0.2.0 / 2013-11-15 +================== + + * republish + +0.1.1 / 2013-11-15 +================== + + * use bytes + +0.1.0 / 2013-11-11 +================== + + * generator support + +0.0.3 / 2013-10-10 +================== + + * update repo + +0.0.2 / 2013-09-14 +================== + + * dump stream on bad headers + * listen to events after defining received and buffers + +0.0.1 / 2013-09-14 +================== + + * Initial release diff --git a/node_modules/raw-body/LICENSE b/node_modules/raw-body/LICENSE new file mode 100644 index 0000000..1029a7a --- /dev/null +++ b/node_modules/raw-body/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2013-2014 Jonathan Ong +Copyright (c) 2014-2022 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/raw-body/README.md b/node_modules/raw-body/README.md new file mode 100644 index 0000000..d9b36d6 --- /dev/null +++ b/node_modules/raw-body/README.md @@ -0,0 +1,223 @@ +# raw-body + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build status][github-actions-ci-image]][github-actions-ci-url] +[![Test coverage][coveralls-image]][coveralls-url] + +Gets the entire buffer of a stream either as a `Buffer` or a string. +Validates the stream's length against an expected length and maximum limit. +Ideal for parsing request bodies. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install raw-body +``` + +### TypeScript + +This module includes a [TypeScript](https://www.typescriptlang.org/) +declaration file to enable auto complete in compatible editors and type +information for TypeScript projects. This module depends on the Node.js +types, so install `@types/node`: + +```sh +$ npm install @types/node +``` + +## API + +```js +var getRawBody = require('raw-body') +``` + +### getRawBody(stream, [options], [callback]) + +**Returns a promise if no callback specified and global `Promise` exists.** + +Options: + +- `length` - The length of the stream. + If the contents of the stream do not add up to this length, + an `400` error code is returned. +- `limit` - The byte limit of the body. + This is the number of bytes or any string format supported by + [bytes](https://www.npmjs.com/package/bytes), + for example `1000`, `'500kb'` or `'3mb'`. + If the body ends up being larger than this limit, + a `413` error code is returned. +- `encoding` - The encoding to use to decode the body into a string. + By default, a `Buffer` instance will be returned when no encoding is specified. + Most likely, you want `utf-8`, so setting `encoding` to `true` will decode as `utf-8`. + You can use any type of encoding supported by [iconv-lite](https://www.npmjs.org/package/iconv-lite#readme). + +You can also pass a string in place of options to just specify the encoding. + +If an error occurs, the stream will be paused, everything unpiped, +and you are responsible for correctly disposing the stream. +For HTTP requests, you may need to finish consuming the stream if +you want to keep the socket open for future requests. For streams +that use file descriptors, you should `stream.destroy()` or +`stream.close()` to prevent leaks. + +## Errors + +This module creates errors depending on the error condition during reading. +The error may be an error from the underlying Node.js implementation, but is +otherwise an error created by this module, which has the following attributes: + + * `limit` - the limit in bytes + * `length` and `expected` - the expected length of the stream + * `received` - the received bytes + * `encoding` - the invalid encoding + * `status` and `statusCode` - the corresponding status code for the error + * `type` - the error type + +### Types + +The errors from this module have a `type` property which allows for the programmatic +determination of the type of error returned. + +#### encoding.unsupported + +This error will occur when the `encoding` option is specified, but the value does +not map to an encoding supported by the [iconv-lite](https://www.npmjs.org/package/iconv-lite#readme) +module. + +#### entity.too.large + +This error will occur when the `limit` option is specified, but the stream has +an entity that is larger. + +#### request.aborted + +This error will occur when the request stream is aborted by the client before +reading the body has finished. + +#### request.size.invalid + +This error will occur when the `length` option is specified, but the stream has +emitted more bytes. + +#### stream.encoding.set + +This error will occur when the given stream has an encoding set on it, making it +a decoded stream. The stream should not have an encoding set and is expected to +emit `Buffer` objects. + +#### stream.not.readable + +This error will occur when the given stream is not readable. + +## Examples + +### Simple Express example + +```js +var contentType = require('content-type') +var express = require('express') +var getRawBody = require('raw-body') + +var app = express() + +app.use(function (req, res, next) { + getRawBody(req, { + length: req.headers['content-length'], + limit: '1mb', + encoding: contentType.parse(req).parameters.charset + }, function (err, string) { + if (err) return next(err) + req.text = string + next() + }) +}) + +// now access req.text +``` + +### Simple Koa example + +```js +var contentType = require('content-type') +var getRawBody = require('raw-body') +var koa = require('koa') + +var app = koa() + +app.use(function * (next) { + this.text = yield getRawBody(this.req, { + length: this.req.headers['content-length'], + limit: '1mb', + encoding: contentType.parse(this.req).parameters.charset + }) + yield next +}) + +// now access this.text +``` + +### Using as a promise + +To use this library as a promise, simply omit the `callback` and a promise is +returned, provided that a global `Promise` is defined. + +```js +var getRawBody = require('raw-body') +var http = require('http') + +var server = http.createServer(function (req, res) { + getRawBody(req) + .then(function (buf) { + res.statusCode = 200 + res.end(buf.length + ' bytes submitted') + }) + .catch(function (err) { + res.statusCode = 500 + res.end(err.message) + }) +}) + +server.listen(3000) +``` + +### Using with TypeScript + +```ts +import * as getRawBody from 'raw-body'; +import * as http from 'http'; + +const server = http.createServer((req, res) => { + getRawBody(req) + .then((buf) => { + res.statusCode = 200; + res.end(buf.length + ' bytes submitted'); + }) + .catch((err) => { + res.statusCode = err.statusCode; + res.end(err.message); + }); +}); + +server.listen(3000); +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/raw-body.svg +[npm-url]: https://npmjs.org/package/raw-body +[node-version-image]: https://img.shields.io/node/v/raw-body.svg +[node-version-url]: https://nodejs.org/en/download/ +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/raw-body/master.svg +[coveralls-url]: https://coveralls.io/r/stream-utils/raw-body?branch=master +[downloads-image]: https://img.shields.io/npm/dm/raw-body.svg +[downloads-url]: https://npmjs.org/package/raw-body +[github-actions-ci-image]: https://img.shields.io/github/actions/workflow/status/stream-utils/raw-body/ci.yml?branch=master&label=ci +[github-actions-ci-url]: https://github.com/jshttp/stream-utils/raw-body?query=workflow%3Aci diff --git a/node_modules/raw-body/SECURITY.md b/node_modules/raw-body/SECURITY.md new file mode 100644 index 0000000..2421efc --- /dev/null +++ b/node_modules/raw-body/SECURITY.md @@ -0,0 +1,24 @@ +# Security Policies and Procedures + +## Reporting a Bug + +The `raw-body` team and community take all security bugs seriously. Thank you +for improving the security of Express. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing the current owners of `raw-body`. This information +can be found in the npm registry using the command `npm owner ls raw-body`. +If unsure or unable to get the information from the above, open an issue +in the [project issue tracker](https://github.com/stream-utils/raw-body/issues) +asking for the current contact information. + +To ensure the timely response to your report, please ensure that the entirety +of the report is contained within the email body and not solely behind a web +link or an attachment. + +At least one owner will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. After the initial reply to your report, the owners will +endeavor to keep you informed of the progress towards a fix and full +announcement, and may ask for additional information or guidance. diff --git a/node_modules/raw-body/index.d.ts b/node_modules/raw-body/index.d.ts new file mode 100644 index 0000000..b504611 --- /dev/null +++ b/node_modules/raw-body/index.d.ts @@ -0,0 +1,85 @@ +declare namespace getRawBody { + export type Encoding = string | true; + + export interface Options { + /** + * The expected length of the stream. + */ + length?: number | string | null; + /** + * The byte limit of the body. This is the number of bytes or any string + * format supported by `bytes`, for example `1000`, `'500kb'` or `'3mb'`. + */ + limit?: number | string | null; + /** + * The encoding to use to decode the body into a string. By default, a + * `Buffer` instance will be returned when no encoding is specified. Most + * likely, you want `utf-8`, so setting encoding to `true` will decode as + * `utf-8`. You can use any type of encoding supported by `iconv-lite`. + */ + encoding?: Encoding | null; + } + + export interface RawBodyError extends Error { + /** + * The limit in bytes. + */ + limit?: number; + /** + * The expected length of the stream. + */ + length?: number; + expected?: number; + /** + * The received bytes. + */ + received?: number; + /** + * The encoding. + */ + encoding?: string; + /** + * The corresponding status code for the error. + */ + status: number; + statusCode: number; + /** + * The error type. + */ + type: string; + } +} + +/** + * Gets the entire buffer of a stream either as a `Buffer` or a string. + * Validates the stream's length against an expected length and maximum + * limit. Ideal for parsing request bodies. + */ +declare function getRawBody( + stream: NodeJS.ReadableStream, + callback: (err: getRawBody.RawBodyError, body: Buffer) => void +): void; + +declare function getRawBody( + stream: NodeJS.ReadableStream, + options: (getRawBody.Options & { encoding: getRawBody.Encoding }) | getRawBody.Encoding, + callback: (err: getRawBody.RawBodyError, body: string) => void +): void; + +declare function getRawBody( + stream: NodeJS.ReadableStream, + options: getRawBody.Options, + callback: (err: getRawBody.RawBodyError, body: Buffer) => void +): void; + +declare function getRawBody( + stream: NodeJS.ReadableStream, + options: (getRawBody.Options & { encoding: getRawBody.Encoding }) | getRawBody.Encoding +): Promise; + +declare function getRawBody( + stream: NodeJS.ReadableStream, + options?: getRawBody.Options +): Promise; + +export = getRawBody; diff --git a/node_modules/raw-body/index.js b/node_modules/raw-body/index.js new file mode 100644 index 0000000..9cdcd12 --- /dev/null +++ b/node_modules/raw-body/index.js @@ -0,0 +1,336 @@ +/*! + * raw-body + * Copyright(c) 2013-2014 Jonathan Ong + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var asyncHooks = tryRequireAsyncHooks() +var bytes = require('bytes') +var createError = require('http-errors') +var iconv = require('iconv-lite') +var unpipe = require('unpipe') + +/** + * Module exports. + * @public + */ + +module.exports = getRawBody + +/** + * Module variables. + * @private + */ + +var ICONV_ENCODING_MESSAGE_REGEXP = /^Encoding not recognized: / + +/** + * Get the decoder for a given encoding. + * + * @param {string} encoding + * @private + */ + +function getDecoder (encoding) { + if (!encoding) return null + + try { + return iconv.getDecoder(encoding) + } catch (e) { + // error getting decoder + if (!ICONV_ENCODING_MESSAGE_REGEXP.test(e.message)) throw e + + // the encoding was not found + throw createError(415, 'specified encoding unsupported', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } +} + +/** + * Get the raw body of a stream (typically HTTP). + * + * @param {object} stream + * @param {object|string|function} [options] + * @param {function} [callback] + * @public + */ + +function getRawBody (stream, options, callback) { + var done = callback + var opts = options || {} + + // light validation + if (stream === undefined) { + throw new TypeError('argument stream is required') + } else if (typeof stream !== 'object' || stream === null || typeof stream.on !== 'function') { + throw new TypeError('argument stream must be a stream') + } + + if (options === true || typeof options === 'string') { + // short cut for encoding + opts = { + encoding: options + } + } + + if (typeof options === 'function') { + done = options + opts = {} + } + + // validate callback is a function, if provided + if (done !== undefined && typeof done !== 'function') { + throw new TypeError('argument callback must be a function') + } + + // require the callback without promises + if (!done && !global.Promise) { + throw new TypeError('argument callback is required') + } + + // get encoding + var encoding = opts.encoding !== true + ? opts.encoding + : 'utf-8' + + // convert the limit to an integer + var limit = bytes.parse(opts.limit) + + // convert the expected length to an integer + var length = opts.length != null && !isNaN(opts.length) + ? parseInt(opts.length, 10) + : null + + if (done) { + // classic callback style + return readStream(stream, encoding, length, limit, wrap(done)) + } + + return new Promise(function executor (resolve, reject) { + readStream(stream, encoding, length, limit, function onRead (err, buf) { + if (err) return reject(err) + resolve(buf) + }) + }) +} + +/** + * Halt a stream. + * + * @param {Object} stream + * @private + */ + +function halt (stream) { + // unpipe everything from the stream + unpipe(stream) + + // pause stream + if (typeof stream.pause === 'function') { + stream.pause() + } +} + +/** + * Read the data from the stream. + * + * @param {object} stream + * @param {string} encoding + * @param {number} length + * @param {number} limit + * @param {function} callback + * @public + */ + +function readStream (stream, encoding, length, limit, callback) { + var complete = false + var sync = true + + // check the length and limit options. + // note: we intentionally leave the stream paused, + // so users should handle the stream themselves. + if (limit !== null && length !== null && length > limit) { + return done(createError(413, 'request entity too large', { + expected: length, + length: length, + limit: limit, + type: 'entity.too.large' + })) + } + + // streams1: assert request encoding is buffer. + // streams2+: assert the stream encoding is buffer. + // stream._decoder: streams1 + // state.encoding: streams2 + // state.decoder: streams2, specifically < 0.10.6 + var state = stream._readableState + if (stream._decoder || (state && (state.encoding || state.decoder))) { + // developer error + return done(createError(500, 'stream encoding should not be set', { + type: 'stream.encoding.set' + })) + } + + if (typeof stream.readable !== 'undefined' && !stream.readable) { + return done(createError(500, 'stream is not readable', { + type: 'stream.not.readable' + })) + } + + var received = 0 + var decoder + + try { + decoder = getDecoder(encoding) + } catch (err) { + return done(err) + } + + var buffer = decoder + ? '' + : [] + + // attach listeners + stream.on('aborted', onAborted) + stream.on('close', cleanup) + stream.on('data', onData) + stream.on('end', onEnd) + stream.on('error', onEnd) + + // mark sync section complete + sync = false + + function done () { + var args = new Array(arguments.length) + + // copy arguments + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + // mark complete + complete = true + + if (sync) { + process.nextTick(invokeCallback) + } else { + invokeCallback() + } + + function invokeCallback () { + cleanup() + + if (args[0]) { + // halt the stream on error + halt(stream) + } + + callback.apply(null, args) + } + } + + function onAborted () { + if (complete) return + + done(createError(400, 'request aborted', { + code: 'ECONNABORTED', + expected: length, + length: length, + received: received, + type: 'request.aborted' + })) + } + + function onData (chunk) { + if (complete) return + + received += chunk.length + + if (limit !== null && received > limit) { + done(createError(413, 'request entity too large', { + limit: limit, + received: received, + type: 'entity.too.large' + })) + } else if (decoder) { + buffer += decoder.write(chunk) + } else { + buffer.push(chunk) + } + } + + function onEnd (err) { + if (complete) return + if (err) return done(err) + + if (length !== null && received !== length) { + done(createError(400, 'request size did not match content length', { + expected: length, + length: length, + received: received, + type: 'request.size.invalid' + })) + } else { + var string = decoder + ? buffer + (decoder.end() || '') + : Buffer.concat(buffer) + done(null, string) + } + } + + function cleanup () { + buffer = null + + stream.removeListener('aborted', onAborted) + stream.removeListener('data', onData) + stream.removeListener('end', onEnd) + stream.removeListener('error', onEnd) + stream.removeListener('close', cleanup) + } +} + +/** + * Try to require async_hooks + * @private + */ + +function tryRequireAsyncHooks () { + try { + return require('async_hooks') + } catch (e) { + return {} + } +} + +/** + * Wrap function with async resource, if possible. + * AsyncResource.bind static method backported. + * @private + */ + +function wrap (fn) { + var res + + // create anonymous resource + if (asyncHooks.AsyncResource) { + res = new asyncHooks.AsyncResource(fn.name || 'bound-anonymous-fn') + } + + // incompatible node.js + if (!res || !res.runInAsyncScope) { + return fn + } + + // return bound function + return res.runInAsyncScope.bind(res, fn, null) +} diff --git a/node_modules/raw-body/package.json b/node_modules/raw-body/package.json new file mode 100644 index 0000000..5bc7165 --- /dev/null +++ b/node_modules/raw-body/package.json @@ -0,0 +1,50 @@ +{ + "name": "raw-body", + "description": "Get and validate the raw body of a readable stream.", + "version": "3.0.0", + "author": "Jonathan Ong (http://jongleberry.com)", + "contributors": [ + "Douglas Christopher Wilson ", + "Raynos " + ], + "license": "MIT", + "repository": "stream-utils/raw-body", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.6.3", + "unpipe": "1.0.0" + }, + "devDependencies": { + "bluebird": "3.7.2", + "eslint": "8.57.0", + "eslint-config-standard": "15.0.1", + "eslint-plugin-import": "2.29.1", + "eslint-plugin-markdown": "3.0.0", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "6.6.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "10.7.0", + "nyc": "17.0.0", + "readable-stream": "2.3.7", + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "SECURITY.md", + "index.d.ts", + "index.js" + ], + "scripts": { + "lint": "eslint .", + "test": "mocha --trace-deprecation --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/router/HISTORY.md b/node_modules/router/HISTORY.md new file mode 100644 index 0000000..b292257 --- /dev/null +++ b/node_modules/router/HISTORY.md @@ -0,0 +1,228 @@ +2.2.0 / 2025-03-26 +================== + +* Remove `setImmediate` support check +* Restore `debug` dependency + +2.1.0 / 2025-02-10 +================== + +* Updated `engines` field to Node@18 or higher +* Remove `Object.setPrototypeOf` polyfill +* Use `Array.flat` instead of `array-flatten` package +* Replace `methods` dependency with standard library +* deps: parseurl@^1.3.3 +* deps: is-promise@^4.0.0 +* Replace `utils-merge` dependency with `Object.assign` +* deps: Remove unused dep `after` + +2.0.0 / 2024-09-09 +================== + +* Drop support for node <18 +* deps: path-to-regexp@^8.0.0 + - Drop support for partial capture group `router.route('/user(s?)/:user/:op')` but still have optional non-capture `/user{s}/:user/:op` + - `:name?` becomes `{:name}` + - `:name*` becomes `*name`. + - The splat change also changes splat from strings to an array of strings + - Optional splats become `{*name}` + - `:name+` becomes `*name` and thus equivalent to `*name` so I dropped those tests + - Strings as regular expressions are fully removed, need to be converted to native regular expressions + +2.0.0-beta.2 / 2024-03-20 +========================= + +This incorporates all changes after 1.3.5 up to 1.3.8. + + * Add support for returned, rejected Promises to `router.param` + +2.0.0-beta.1 / 2020-03-29 +========================= + +This incorporates all changes after 1.3.3 up to 1.3.5. + + * Internalize private `router.process_params` method + * Remove `debug` dependency + * deps: array-flatten@3.0.0 + * deps: parseurl@~1.3.3 + * deps: path-to-regexp@3.2.0 + - Add new `?`, `*`, and `+` parameter modifiers. + - Matching group expressions are only RegExp syntax. + `(*)` is no longer valid and must be written as `(.*)`, for example. + - Named matching groups no longer available by position in `req.params`. + `/:foo(.*)` only captures as `req.params.foo` and not available as + `req.params[0]`. + - Regular expressions can only be used in a matching group. + `/\\d+` is no longer valid and must be written as `/(\\d+)`. + - Matching groups are now literal regular expressions. + `:foo` named captures can no longer be included inside a capture group. + - Special `*` path segment behavior removed. + `/foo/*/bar` will match a literal `*` as the middle segment. + * deps: setprototypeof@1.2.0 + +2.0.0-alpha.1 / 2018-07-27 +========================== + + * Add basic support for returned, rejected Promises + - Rejected Promises from middleware functions `next(error)` + * Drop support for Node.js below 0.10 + * deps: debug@3.1.0 + - Add `DEBUG_HIDE_DATE` environment variable + - Change timer to per-namespace instead of global + - Change non-TTY date format + - Remove `DEBUG_FD` environment variable support + - Support 256 namespace colors + +1.3.8 / 2023-02-24 +================== + + * Fix routing requests without method + +1.3.7 / 2022-04-28 +================== + + * Fix hanging on large stack of sync routes + +1.3.6 / 2021-11-15 +================== + + * Fix handling very large stacks of sync middleware + * deps: safe-buffer@5.2.1 + +1.3.5 / 2020-03-24 +================== + + * Fix incorrect middleware execution with unanchored `RegExp`s + * perf: use plain object for internal method map + +1.3.4 / 2020-01-24 +================== + + * deps: array-flatten@3.0.0 + * deps: parseurl@~1.3.3 + * deps: setprototypeof@1.2.0 + +1.3.3 / 2018-07-06 +================== + + * Fix JSDoc for `Router` constructor + +1.3.2 / 2017-09-24 +================== + + * deps: debug@2.6.9 + * deps: parseurl@~1.3.2 + - perf: reduce overhead for full URLs + - perf: unroll the "fast-path" `RegExp` + * deps: setprototypeof@1.1.0 + * deps: utils-merge@1.0.1 + +1.3.1 / 2017-05-19 +================== + + * deps: debug@2.6.8 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@2.0.0 + +1.3.0 / 2017-02-25 +================== + + * Add `next("router")` to exit from router + * Fix case where `router.use` skipped requests routes did not + * Use `%o` in path debug to tell types apart + * deps: setprototypeof@1.0.3 + * perf: add fast match path for `*` route + +1.2.0 / 2017-02-17 +================== + + * Skip routing when `req.url` is not set + * deps: debug@2.6.1 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable set to `3` or higher + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + +1.1.5 / 2017-01-28 +================== + + * deps: array-flatten@2.1.1 + * deps: setprototypeof@1.0.2 + - Fix using fallback even when native method exists + +1.1.4 / 2016-01-21 +================== + + * deps: array-flatten@2.0.0 + * deps: methods@~1.1.2 + - perf: enable strict mode + * deps: parseurl@~1.3.1 + - perf: enable strict mode + +1.1.3 / 2015-08-02 +================== + + * Fix infinite loop condition using `mergeParams: true` + * Fix inner numeric indices incorrectly altering parent `req.params` + * deps: array-flatten@1.1.1 + - perf: enable strict mode + * deps: path-to-regexp@0.1.7 + - Fix regression with escaped round brackets and matching groups + +1.1.2 / 2015-07-06 +================== + + * Fix hiding platform issues with `decodeURIComponent` + - Only `URIError`s are a 400 + * Fix using `*` before params in routes + * Fix using capture groups before params in routes + * deps: path-to-regexp@0.1.6 + * perf: enable strict mode + * perf: remove argument reassignments in routing + * perf: skip attempting to decode zero length string + * perf: use plain for loops + +1.1.1 / 2015-05-25 +================== + + * Fix issue where `next('route')` in `router.param` would incorrectly skip values + * deps: array-flatten@1.1.0 + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + +1.1.0 / 2015-04-22 +================== + + * Use `setprototypeof` instead of `__proto__` + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + +1.0.0 / 2015-01-13 +================== + + * Fix crash from error within `OPTIONS` response handler + * deps: array-flatten@1.0.2 + - Remove redundant code path + +1.0.0-beta.3 / 2015-01-11 +========================= + + * Fix duplicate methods appearing in OPTIONS responses + * Fix OPTIONS responses to include the HEAD method properly + * Remove support for leading colon in `router.param(name, fn)` + * Use `array-flatten` for flattening arrays + * deps: debug@~2.1.1 + * deps: methods@~1.1.1 + +1.0.0-beta.2 / 2014-11-19 +========================= + + * Match routes iteratively to prevent stack overflows + +1.0.0-beta.1 / 2014-11-16 +========================= + + * Initial release ported from Express 4.x + - Altered to work without Express diff --git a/node_modules/router/LICENSE b/node_modules/router/LICENSE new file mode 100644 index 0000000..237e1b6 --- /dev/null +++ b/node_modules/router/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 Roman Shtylman +Copyright (c) 2014-2022 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/router/README.md b/node_modules/router/README.md new file mode 100644 index 0000000..218fd57 --- /dev/null +++ b/node_modules/router/README.md @@ -0,0 +1,416 @@ +# router + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Simple middleware-style router + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +$ npm install router +``` + +## API + +```js +var finalhandler = require('finalhandler') +var http = require('http') +var Router = require('router') + +var router = Router() +router.get('/', function (req, res) { + res.setHeader('Content-Type', 'text/plain; charset=utf-8') + res.end('Hello World!') +}) + +var server = http.createServer(function (req, res) { + router(req, res, finalhandler(req, res)) +}) + +server.listen(3000) +``` + +This module is currently an extracted version from the Express project, +but with the main change being it can be used with a plain `http.createServer` +object or other web frameworks by removing Express-specific API calls. + +## Router(options) + +Options + +- `strict` - When `false` trailing slashes are optional (default: `false`) +- `caseSensitive` - When `true` the routing will be case sensitive. (default: `false`) +- `mergeParams` - When `true` any `req.params` passed to the router will be + merged into the router's `req.params`. (default: `false`) ([example](#example-using-mergeparams)) + +Returns a function with the signature `router(req, res, callback)` where +`callback([err])` must be provided to handle errors and fall-through from +not handling requests. + +### router.use([path], ...middleware) + +Use the given [middleware function](#middleware) for all http methods on the +given `path`, defaulting to the root path. + +`router` does not automatically see `use` as a handler. As such, it will not +consider it one for handling `OPTIONS` requests. + +* Note: If a `path` is specified, that `path` is stripped from the start of + `req.url`. + + + +```js +router.use(function (req, res, next) { + // do your things + + // continue to the next middleware + // the request will stall if this is not called + next() + + // note: you should NOT call `next` if you have begun writing to the response +}) +``` + +[Middleware](#middleware) can themselves use `next('router')` at any time to +exit the current router instance completely, invoking the top-level callback. + +### router\[method](path, ...[middleware], handler) + +The [http methods](https://github.com/jshttp/methods/blob/master/index.js) provide +the routing functionality in `router`. + +Method middleware and handlers follow usual [middleware](#middleware) behavior, +except they will only be called when the method and path match the request. + + + +```js +// handle a `GET` request +router.get('/', function (req, res) { + res.setHeader('Content-Type', 'text/plain; charset=utf-8') + res.end('Hello World!') +}) +``` + +[Middleware](#middleware) given before the handler have one additional trick, +they may invoke `next('route')`. Calling `next('route')` bypasses the remaining +middleware and the handler mounted for this route, passing the request to the +next route suitable for handling this request. + +Route handlers and middleware can themselves use `next('router')` at any time +to exit the current router instance completely, invoking the top-level callback. + +### router.param(name, param_middleware) + +Maps the specified path parameter `name` to a specialized param-capturing middleware. + +This function positions the middleware in the same stack as `.use`. + +The function can optionally return a `Promise` object. If a `Promise` object +is returned from the function, the router will attach an `onRejected` callback +using `.then`. If the promise is rejected, `next` will be called with the +rejected value, or an error if the value is falsy. + +Parameter mapping is used to provide pre-conditions to routes +which use normalized placeholders. For example a _:user_id_ parameter +could automatically load a user's information from the database without +any additional code: + + + +```js +router.param('user_id', function (req, res, next, id) { + User.find(id, function (err, user) { + if (err) { + return next(err) + } else if (!user) { + return next(new Error('failed to load user')) + } + req.user = user + + // continue processing the request + next() + }) +}) +``` + +### router.route(path) + +Creates an instance of a single `Route` for the given `path`. +(See `Router.Route` below) + +Routes can be used to handle http `methods` with their own, optional middleware. + +Using `router.route(path)` is a recommended approach to avoiding duplicate +route naming and thus typo errors. + + + +```js +var api = router.route('/api/') +``` + +## Router.Route(path) + +Represents a single route as an instance that can be used to handle http +`methods` with it's own, optional middleware. + +### route\[method](handler) + +These are functions which you can directly call on a route to register a new +`handler` for the `method` on the route. + + + +```js +// handle a `GET` request +var status = router.route('/status') + +status.get(function (req, res) { + res.setHeader('Content-Type', 'text/plain; charset=utf-8') + res.end('All Systems Green!') +}) +``` + +### route.all(handler) + +Adds a handler for all HTTP methods to this route. + +The handler can behave like middleware and call `next` to continue processing +rather than responding. + + + +```js +router.route('/') + .all(function (req, res, next) { + next() + }) + .all(checkSomething) + .get(function (req, res) { + res.setHeader('Content-Type', 'text/plain; charset=utf-8') + res.end('Hello World!') + }) +``` + +## Middleware + +Middleware (and method handlers) are functions that follow specific function +parameters and have defined behavior when used with `router`. The most common +format is with three parameters - "req", "res" and "next". + +- `req` - This is a [HTTP incoming message](https://nodejs.org/api/http.html#http_http_incomingmessage) instance. +- `res` - This is a [HTTP server response](https://nodejs.org/api/http.html#http_class_http_serverresponse) instance. +- `next` - Calling this function that tells `router` to proceed to the next matching middleware or method handler. It accepts an error as the first argument. + +The function can optionally return a `Promise` object. If a `Promise` object +is returned from the function, the router will attach an `onRejected` callback +using `.then`. If the promise is rejected, `next` will be called with the +rejected value, or an error if the value is falsy. + +Middleware and method handlers can also be defined with four arguments. When +the function has four parameters defined, the first argument is an error and +subsequent arguments remain, becoming - "err", "req", "res", "next". These +functions are "error handling middleware", and can be used for handling +errors that occurred in previous handlers (E.g. from calling `next(err)`). +This is most used when you want to define arbitrary rendering of errors. + + + +```js +router.get('/error_route', function (req, res, next) { + return next(new Error('Bad Request')) +}) + +router.use(function (err, req, res, next) { + res.end(err.message) //= > "Bad Request" +}) +``` + +Error handling middleware will **only** be invoked when an error was given. As +long as the error is in the pipeline, normal middleware and handlers will be +bypassed - only error handling middleware will be invoked with an error. + +## Examples + +```js +// import our modules +var http = require('http') +var Router = require('router') +var finalhandler = require('finalhandler') +var compression = require('compression') +var bodyParser = require('body-parser') + +// store our message to display +var message = 'Hello World!' + +// initialize the router & server and add a final callback. +var router = Router() +var server = http.createServer(function onRequest (req, res) { + router(req, res, finalhandler(req, res)) +}) + +// use some middleware and compress all outgoing responses +router.use(compression()) + +// handle `GET` requests to `/message` +router.get('/message', function (req, res) { + res.statusCode = 200 + res.setHeader('Content-Type', 'text/plain; charset=utf-8') + res.end(message + '\n') +}) + +// create and mount a new router for our API +var api = Router() +router.use('/api/', api) + +// add a body parsing middleware to our API +api.use(bodyParser.json()) + +// handle `PATCH` requests to `/api/set-message` +api.patch('/set-message', function (req, res) { + if (req.body.value) { + message = req.body.value + + res.statusCode = 200 + res.setHeader('Content-Type', 'text/plain; charset=utf-8') + res.end(message + '\n') + } else { + res.statusCode = 400 + res.setHeader('Content-Type', 'text/plain; charset=utf-8') + res.end('Invalid API Syntax\n') + } +}) + +// make our http server listen to connections +server.listen(8080) +``` + +You can get the message by running this command in your terminal, + or navigating to `127.0.0.1:8080` in a web browser. +```bash +curl http://127.0.0.1:8080 +``` + +You can set the message by sending it a `PATCH` request via this command: +```bash +curl http://127.0.0.1:8080/api/set-message -X PATCH -H "Content-Type: application/json" -d '{"value":"Cats!"}' +``` + +### Example using mergeParams + +```js +var http = require('http') +var Router = require('router') +var finalhandler = require('finalhandler') + +// this example is about the mergeParams option +var opts = { mergeParams: true } + +// make a router with out special options +var router = Router(opts) +var server = http.createServer(function onRequest (req, res) { + // set something to be passed into the router + req.params = { type: 'kitten' } + + router(req, res, finalhandler(req, res)) +}) + +router.get('/', function (req, res) { + res.statusCode = 200 + res.setHeader('Content-Type', 'text/plain; charset=utf-8') + + // with respond with the the params that were passed in + res.end(req.params.type + '\n') +}) + +// make another router with our options +var handler = Router(opts) + +// mount our new router to a route that accepts a param +router.use('/:path', handler) + +handler.get('/', function (req, res) { + res.statusCode = 200 + res.setHeader('Content-Type', 'text/plain; charset=utf-8') + + // will respond with the param of the router's parent route + res.end(req.params.path + '\n') +}) + +// make our http server listen to connections +server.listen(8080) +``` + +Now you can get the type, or what path you are requesting: +```bash +curl http://127.0.0.1:8080 +> kitten +curl http://127.0.0.1:8080/such_path +> such_path +``` + +### Example of advanced `.route()` usage + +This example shows how to implement routes where there is a custom +handler to execute when the path matched, but no methods matched. +Without any special handling, this would be treated as just a +generic non-match by `router` (which typically results in a 404), +but with a custom handler, a `405 Method Not Allowed` can be sent. + +```js +var http = require('http') +var finalhandler = require('finalhandler') +var Router = require('router') + +// create the router and server +var router = new Router() +var server = http.createServer(function onRequest (req, res) { + router(req, res, finalhandler(req, res)) +}) + +// register a route and add all methods +router.route('/pet/:id') + .get(function (req, res) { + // this is GET /pet/:id + res.setHeader('Content-Type', 'application/json') + res.end(JSON.stringify({ name: 'tobi' })) + }) + .delete(function (req, res) { + // this is DELETE /pet/:id + res.end() + }) + .all(function (req, res) { + // this is called for all other methods not + // defined above for /pet/:id + res.statusCode = 405 + res.end() + }) + +// make our http server listen to connections +server.listen(8080) +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/pillarjs/router/master?label=ci +[ci-url]: https://github.com/pillarjs/router/actions/workflows/ci.yml +[npm-image]: https://img.shields.io/npm/v/router.svg +[npm-url]: https://npmjs.org/package/router +[node-version-image]: https://img.shields.io/node/v/router.svg +[node-version-url]: http://nodejs.org/download/ +[coveralls-image]: https://img.shields.io/coveralls/pillarjs/router/master.svg +[coveralls-url]: https://coveralls.io/r/pillarjs/router?branch=master +[downloads-image]: https://img.shields.io/npm/dm/router.svg +[downloads-url]: https://npmjs.org/package/router diff --git a/node_modules/router/index.js b/node_modules/router/index.js new file mode 100644 index 0000000..4358aeb --- /dev/null +++ b/node_modules/router/index.js @@ -0,0 +1,748 @@ +/*! + * router + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +const isPromise = require('is-promise') +const Layer = require('./lib/layer') +const { METHODS } = require('node:http') +const parseUrl = require('parseurl') +const Route = require('./lib/route') +const debug = require('debug')('router') +const deprecate = require('depd')('router') + +/** + * Module variables. + * @private + */ + +const slice = Array.prototype.slice +const flatten = Array.prototype.flat +const methods = METHODS.map((method) => method.toLowerCase()) + +/** + * Expose `Router`. + */ + +module.exports = Router + +/** + * Expose `Route`. + */ + +module.exports.Route = Route + +/** + * Initialize a new `Router` with the given `options`. + * + * @param {object} [options] + * @return {Router} which is a callable function + * @public + */ + +function Router (options) { + if (!(this instanceof Router)) { + return new Router(options) + } + + const opts = options || {} + + function router (req, res, next) { + router.handle(req, res, next) + } + + // inherit from the correct prototype + Object.setPrototypeOf(router, this) + + router.caseSensitive = opts.caseSensitive + router.mergeParams = opts.mergeParams + router.params = {} + router.strict = opts.strict + router.stack = [] + + return router +} + +/** + * Router prototype inherits from a Function. + */ + +/* istanbul ignore next */ +Router.prototype = function () {} + +/** + * Map the given param placeholder `name`(s) to the given callback. + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code. + * + * The callback uses the same signature as middleware, the only difference + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * Just like in middleware, you must either respond to the request or call next + * to avoid stalling the request. + * + * router.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * return next(err) + * } else if (!user) { + * return next(new Error('failed to load user')) + * } + * req.user = user + * next() + * }) + * }) + * + * @param {string} name + * @param {function} fn + * @public + */ + +Router.prototype.param = function param (name, fn) { + if (!name) { + throw new TypeError('argument name is required') + } + + if (typeof name !== 'string') { + throw new TypeError('argument name must be a string') + } + + if (!fn) { + throw new TypeError('argument fn is required') + } + + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + let params = this.params[name] + + if (!params) { + params = this.params[name] = [] + } + + params.push(fn) + + return this +} + +/** + * Dispatch a req, res into the router. + * + * @private + */ + +Router.prototype.handle = function handle (req, res, callback) { + if (!callback) { + throw new TypeError('argument callback is required') + } + + debug('dispatching %s %s', req.method, req.url) + + let idx = 0 + let methods + const protohost = getProtohost(req.url) || '' + let removed = '' + const self = this + let slashAdded = false + let sync = 0 + const paramcalled = {} + + // middleware and routes + const stack = this.stack + + // manage inter-router variables + const parentParams = req.params + const parentUrl = req.baseUrl || '' + let done = restore(callback, req, 'baseUrl', 'next', 'params') + + // setup next layer + req.next = next + + // for options requests, respond with a default if nothing else responds + if (req.method === 'OPTIONS') { + methods = [] + done = wrap(done, generateOptionsResponder(res, methods)) + } + + // setup basic req values + req.baseUrl = parentUrl + req.originalUrl = req.originalUrl || req.url + + next() + + function next (err) { + let layerError = err === 'route' + ? null + : err + + // remove added slash + if (slashAdded) { + req.url = req.url.slice(1) + slashAdded = false + } + + // restore altered req.url + if (removed.length !== 0) { + req.baseUrl = parentUrl + req.url = protohost + removed + req.url.slice(protohost.length) + removed = '' + } + + // signal to exit router + if (layerError === 'router') { + setImmediate(done, null) + return + } + + // no more matching layers + if (idx >= stack.length) { + setImmediate(done, layerError) + return + } + + // max sync stack + if (++sync > 100) { + return setImmediate(next, err) + } + + // get pathname of request + const path = getPathname(req) + + if (path == null) { + return done(layerError) + } + + // find next matching layer + let layer + let match + let route + + while (match !== true && idx < stack.length) { + layer = stack[idx++] + match = matchLayer(layer, path) + route = layer.route + + if (typeof match !== 'boolean') { + // hold on to layerError + layerError = layerError || match + } + + if (match !== true) { + continue + } + + if (!route) { + // process non-route handlers normally + continue + } + + if (layerError) { + // routes do not match with a pending error + match = false + continue + } + + const method = req.method + const hasMethod = route._handlesMethod(method) + + // build up automatic options response + if (!hasMethod && method === 'OPTIONS' && methods) { + methods.push.apply(methods, route._methods()) + } + + // don't even bother matching route + if (!hasMethod && method !== 'HEAD') { + match = false + } + } + + // no match + if (match !== true) { + return done(layerError) + } + + // store route for dispatch on change + if (route) { + req.route = route + } + + // Capture one-time layer values + req.params = self.mergeParams + ? mergeParams(layer.params, parentParams) + : layer.params + const layerPath = layer.path + + // this should be done for the layer + processParams(self.params, layer, paramcalled, req, res, function (err) { + if (err) { + next(layerError || err) + } else if (route) { + layer.handleRequest(req, res, next) + } else { + trimPrefix(layer, layerError, layerPath, path) + } + + sync = 0 + }) + } + + function trimPrefix (layer, layerError, layerPath, path) { + if (layerPath.length !== 0) { + // Validate path is a prefix match + if (layerPath !== path.substring(0, layerPath.length)) { + next(layerError) + return + } + + // Validate path breaks on a path separator + const c = path[layerPath.length] + if (c && c !== '/') { + next(layerError) + return + } + + // Trim off the part of the url that matches the route + // middleware (.use stuff) needs to have the path stripped + debug('trim prefix (%s) from url %s', layerPath, req.url) + removed = layerPath + req.url = protohost + req.url.slice(protohost.length + removed.length) + + // Ensure leading slash + if (!protohost && req.url[0] !== '/') { + req.url = '/' + req.url + slashAdded = true + } + + // Setup base URL (no trailing slash) + req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' + ? removed.substring(0, removed.length - 1) + : removed) + } + + debug('%s %s : %s', layer.name, layerPath, req.originalUrl) + + if (layerError) { + layer.handleError(layerError, req, res, next) + } else { + layer.handleRequest(req, res, next) + } + } +} + +/** + * Use the given middleware function, with optional path, defaulting to "/". + * + * Use (like `.all`) will run for any http METHOD, but it will not add + * handlers for those methods so OPTIONS requests will not consider `.use` + * functions even if they could respond. + * + * The other difference is that _route_ path is stripped and not visible + * to the handler function. The main effect of this feature is that mounted + * handlers can operate without any code changes regardless of the "prefix" + * pathname. + * + * @public + */ + +Router.prototype.use = function use (handler) { + let offset = 0 + let path = '/' + + // default path to '/' + // disambiguate router.use([handler]) + if (typeof handler !== 'function') { + let arg = handler + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0] + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1 + path = handler + } + } + + const callbacks = flatten.call(slice.call(arguments, offset), Infinity) + + if (callbacks.length === 0) { + throw new TypeError('argument handler is required') + } + + for (let i = 0; i < callbacks.length; i++) { + const fn = callbacks[i] + + if (typeof fn !== 'function') { + throw new TypeError('argument handler must be a function') + } + + // add the middleware + debug('use %o %s', path, fn.name || '') + + const layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: false, + end: false + }, fn) + + layer.route = undefined + + this.stack.push(layer) + } + + return this +} + +/** + * Create a new Route for the given path. + * + * Each route contains a separate middleware stack and VERB handlers. + * + * See the Route api documentation for details on adding handlers + * and middleware to routes. + * + * @param {string} path + * @return {Route} + * @public + */ + +Router.prototype.route = function route (path) { + const route = new Route(path) + + const layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: this.strict, + end: true + }, handle) + + function handle (req, res, next) { + route.dispatch(req, res, next) + } + + layer.route = route + + this.stack.push(layer) + return route +} + +// create Router#VERB functions +methods.concat('all').forEach(function (method) { + Router.prototype[method] = function (path) { + const route = this.route(path) + route[method].apply(route, slice.call(arguments, 1)) + return this + } +}) + +/** + * Generate a callback that will make an OPTIONS response. + * + * @param {OutgoingMessage} res + * @param {array} methods + * @private + */ + +function generateOptionsResponder (res, methods) { + return function onDone (fn, err) { + if (err || methods.length === 0) { + return fn(err) + } + + trySendOptionsResponse(res, methods, fn) + } +} + +/** + * Get pathname of request. + * + * @param {IncomingMessage} req + * @private + */ + +function getPathname (req) { + try { + return parseUrl(req).pathname + } catch (err) { + return undefined + } +} + +/** + * Get get protocol + host for a URL. + * + * @param {string} url + * @private + */ + +function getProtohost (url) { + if (typeof url !== 'string' || url.length === 0 || url[0] === '/') { + return undefined + } + + const searchIndex = url.indexOf('?') + const pathLength = searchIndex !== -1 + ? searchIndex + : url.length + const fqdnIndex = url.substring(0, pathLength).indexOf('://') + + return fqdnIndex !== -1 + ? url.substring(0, url.indexOf('/', 3 + fqdnIndex)) + : undefined +} + +/** + * Match path to a layer. + * + * @param {Layer} layer + * @param {string} path + * @private + */ + +function matchLayer (layer, path) { + try { + return layer.match(path) + } catch (err) { + return err + } +} + +/** + * Merge params with parent params + * + * @private + */ + +function mergeParams (params, parent) { + if (typeof parent !== 'object' || !parent) { + return params + } + + // make copy of parent for base + const obj = Object.assign({}, parent) + + // simple non-numeric merging + if (!(0 in params) || !(0 in parent)) { + return Object.assign(obj, params) + } + + let i = 0 + let o = 0 + + // determine numeric gap in params + while (i in params) { + i++ + } + + // determine numeric gap in parent + while (o in parent) { + o++ + } + + // offset numeric indices in params before merge + for (i--; i >= 0; i--) { + params[i + o] = params[i] + + // create holes for the merge when necessary + if (i < o) { + delete params[i] + } + } + + return Object.assign(obj, params) +} + +/** + * Process any parameters for the layer. + * + * @private + */ + +function processParams (params, layer, called, req, res, done) { + // captured parameters from the layer, keys and values + const keys = layer.keys + + // fast track + if (!keys || keys.length === 0) { + return done() + } + + let i = 0 + let paramIndex = 0 + let key + let paramVal + let paramCallbacks + let paramCalled + + // process params in order + // param callbacks can be async + function param (err) { + if (err) { + return done(err) + } + + if (i >= keys.length) { + return done() + } + + paramIndex = 0 + key = keys[i++] + paramVal = req.params[key] + paramCallbacks = params[key] + paramCalled = called[key] + + if (paramVal === undefined || !paramCallbacks) { + return param() + } + + // param previously called with same value or error occurred + if (paramCalled && (paramCalled.match === paramVal || + (paramCalled.error && paramCalled.error !== 'route'))) { + // restore value + req.params[key] = paramCalled.value + + // next param + return param(paramCalled.error) + } + + called[key] = paramCalled = { + error: null, + match: paramVal, + value: paramVal + } + + paramCallback() + } + + // single param callbacks + function paramCallback (err) { + const fn = paramCallbacks[paramIndex++] + + // store updated value + paramCalled.value = req.params[key] + + if (err) { + // store error + paramCalled.error = err + param(err) + return + } + + if (!fn) return param() + + try { + const ret = fn(req, res, paramCallback, paramVal, key) + if (isPromise(ret)) { + if (!(ret instanceof Promise)) { + deprecate('parameters that are Promise-like are deprecated, use a native Promise instead') + } + + ret.then(null, function (error) { + paramCallback(error || new Error('Rejected promise')) + }) + } + } catch (e) { + paramCallback(e) + } + } + + param() +} + +/** + * Restore obj props after function + * + * @private + */ + +function restore (fn, obj) { + const props = new Array(arguments.length - 2) + const vals = new Array(arguments.length - 2) + + for (let i = 0; i < props.length; i++) { + props[i] = arguments[i + 2] + vals[i] = obj[props[i]] + } + + return function () { + // restore vals + for (let i = 0; i < props.length; i++) { + obj[props[i]] = vals[i] + } + + return fn.apply(this, arguments) + } +} + +/** + * Send an OPTIONS response. + * + * @private + */ + +function sendOptionsResponse (res, methods) { + const options = Object.create(null) + + // build unique method map + for (let i = 0; i < methods.length; i++) { + options[methods[i]] = true + } + + // construct the allow list + const allow = Object.keys(options).sort().join(', ') + + // send response + res.setHeader('Allow', allow) + res.setHeader('Content-Length', Buffer.byteLength(allow)) + res.setHeader('Content-Type', 'text/plain') + res.setHeader('X-Content-Type-Options', 'nosniff') + res.end(allow) +} + +/** + * Try to send an OPTIONS response. + * + * @private + */ + +function trySendOptionsResponse (res, methods, next) { + try { + sendOptionsResponse(res, methods) + } catch (err) { + next(err) + } +} + +/** + * Wrap a function + * + * @private + */ + +function wrap (old, fn) { + return function proxy () { + const args = new Array(arguments.length + 1) + + args[0] = old + for (let i = 0, len = arguments.length; i < len; i++) { + args[i + 1] = arguments[i] + } + + fn.apply(this, args) + } +} diff --git a/node_modules/router/lib/layer.js b/node_modules/router/lib/layer.js new file mode 100644 index 0000000..6a4408f --- /dev/null +++ b/node_modules/router/lib/layer.js @@ -0,0 +1,247 @@ +/*! + * router + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +const isPromise = require('is-promise') +const pathRegexp = require('path-to-regexp') +const debug = require('debug')('router:layer') +const deprecate = require('depd')('router') + +/** + * Module variables. + * @private + */ + +const TRAILING_SLASH_REGEXP = /\/+$/ +const MATCHING_GROUP_REGEXP = /\((?:\?<(.*?)>)?(?!\?)/g + +/** + * Expose `Layer`. + */ + +module.exports = Layer + +function Layer (path, options, fn) { + if (!(this instanceof Layer)) { + return new Layer(path, options, fn) + } + + debug('new %o', path) + const opts = options || {} + + this.handle = fn + this.keys = [] + this.name = fn.name || '' + this.params = undefined + this.path = undefined + this.slash = path === '/' && opts.end === false + + function matcher (_path) { + if (_path instanceof RegExp) { + const keys = [] + let name = 0 + let m + // eslint-disable-next-line no-cond-assign + while (m = MATCHING_GROUP_REGEXP.exec(_path.source)) { + keys.push({ + name: m[1] || name++, + offset: m.index + }) + } + + return function regexpMatcher (p) { + const match = _path.exec(p) + if (!match) { + return false + } + + const params = {} + for (let i = 1; i < match.length; i++) { + const key = keys[i - 1] + const prop = key.name + const val = decodeParam(match[i]) + + if (val !== undefined) { + params[prop] = val + } + } + + return { + params, + path: match[0] + } + } + } + + return pathRegexp.match((opts.strict ? _path : loosen(_path)), { + sensitive: opts.sensitive, + end: opts.end, + trailing: !opts.strict, + decode: decodeParam + }) + } + this.matchers = Array.isArray(path) ? path.map(matcher) : [matcher(path)] +} + +/** + * Handle the error for the layer. + * + * @param {Error} error + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handleError = function handleError (error, req, res, next) { + const fn = this.handle + + if (fn.length !== 4) { + // not a standard error handler + return next(error) + } + + try { + // invoke function + const ret = fn(error, req, res, next) + + // wait for returned promise + if (isPromise(ret)) { + if (!(ret instanceof Promise)) { + deprecate('handlers that are Promise-like are deprecated, use a native Promise instead') + } + + ret.then(null, function (error) { + next(error || new Error('Rejected promise')) + }) + } + } catch (err) { + next(err) + } +} + +/** + * Handle the request for the layer. + * + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handleRequest = function handleRequest (req, res, next) { + const fn = this.handle + + if (fn.length > 3) { + // not a standard request handler + return next() + } + + try { + // invoke function + const ret = fn(req, res, next) + + // wait for returned promise + if (isPromise(ret)) { + if (!(ret instanceof Promise)) { + deprecate('handlers that are Promise-like are deprecated, use a native Promise instead') + } + + ret.then(null, function (error) { + next(error || new Error('Rejected promise')) + }) + } + } catch (err) { + next(err) + } +} + +/** + * Check if this route matches `path`, if so + * populate `.params`. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +Layer.prototype.match = function match (path) { + let match + + if (path != null) { + // fast path non-ending match for / (any path matches) + if (this.slash) { + this.params = {} + this.path = '' + return true + } + + let i = 0 + while (!match && i < this.matchers.length) { + // match the path + match = this.matchers[i](path) + i++ + } + } + + if (!match) { + this.params = undefined + this.path = undefined + return false + } + + // store values + this.params = match.params + this.path = match.path + this.keys = Object.keys(match.params) + + return true +} + +/** + * Decode param value. + * + * @param {string} val + * @return {string} + * @private + */ + +function decodeParam (val) { + if (typeof val !== 'string' || val.length === 0) { + return val + } + + try { + return decodeURIComponent(val) + } catch (err) { + if (err instanceof URIError) { + err.message = 'Failed to decode param \'' + val + '\'' + err.status = 400 + } + + throw err + } +} + +/** + * Loosens the given path for path-to-regexp matching. + */ +function loosen (path) { + if (path instanceof RegExp || path === '/') { + return path + } + + return Array.isArray(path) + ? path.map(function (p) { return loosen(p) }) + : String(path).replace(TRAILING_SLASH_REGEXP, '') +} diff --git a/node_modules/router/lib/route.js b/node_modules/router/lib/route.js new file mode 100644 index 0000000..1887d78 --- /dev/null +++ b/node_modules/router/lib/route.js @@ -0,0 +1,242 @@ +/*! + * router + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +const debug = require('debug')('router:route') +const Layer = require('./layer') +const { METHODS } = require('node:http') + +/** + * Module variables. + * @private + */ + +const slice = Array.prototype.slice +const flatten = Array.prototype.flat +const methods = METHODS.map((method) => method.toLowerCase()) + +/** + * Expose `Route`. + */ + +module.exports = Route + +/** + * Initialize `Route` with the given `path`, + * + * @param {String} path + * @api private + */ + +function Route (path) { + debug('new %o', path) + this.path = path + this.stack = [] + + // route handlers for various http methods + this.methods = Object.create(null) +} + +/** + * @private + */ + +Route.prototype._handlesMethod = function _handlesMethod (method) { + if (this.methods._all) { + return true + } + + // normalize name + let name = typeof method === 'string' + ? method.toLowerCase() + : method + + if (name === 'head' && !this.methods.head) { + name = 'get' + } + + return Boolean(this.methods[name]) +} + +/** + * @return {array} supported HTTP methods + * @private + */ + +Route.prototype._methods = function _methods () { + const methods = Object.keys(this.methods) + + // append automatic head + if (this.methods.get && !this.methods.head) { + methods.push('head') + } + + for (let i = 0; i < methods.length; i++) { + // make upper case + methods[i] = methods[i].toUpperCase() + } + + return methods +} + +/** + * dispatch req, res into this route + * + * @private + */ + +Route.prototype.dispatch = function dispatch (req, res, done) { + let idx = 0 + const stack = this.stack + let sync = 0 + + if (stack.length === 0) { + return done() + } + + let method = typeof req.method === 'string' + ? req.method.toLowerCase() + : req.method + + if (method === 'head' && !this.methods.head) { + method = 'get' + } + + req.route = this + + next() + + function next (err) { + // signal to exit route + if (err && err === 'route') { + return done() + } + + // signal to exit router + if (err && err === 'router') { + return done(err) + } + + // no more matching layers + if (idx >= stack.length) { + return done(err) + } + + // max sync stack + if (++sync > 100) { + return setImmediate(next, err) + } + + let layer + let match + + // find next matching layer + while (match !== true && idx < stack.length) { + layer = stack[idx++] + match = !layer.method || layer.method === method + } + + // no match + if (match !== true) { + return done(err) + } + + if (err) { + layer.handleError(err, req, res, next) + } else { + layer.handleRequest(req, res, next) + } + + sync = 0 + } +} + +/** + * Add a handler for all HTTP verbs to this route. + * + * Behaves just like middleware and can respond or call `next` + * to continue processing. + * + * You can use multiple `.all` call to add multiple handlers. + * + * function check_something(req, res, next){ + * next() + * } + * + * function validate_user(req, res, next){ + * next() + * } + * + * route + * .all(validate_user) + * .all(check_something) + * .get(function(req, res, next){ + * res.send('hello world') + * }) + * + * @param {array|function} handler + * @return {Route} for chaining + * @api public + */ + +Route.prototype.all = function all (handler) { + const callbacks = flatten.call(slice.call(arguments), Infinity) + + if (callbacks.length === 0) { + throw new TypeError('argument handler is required') + } + + for (let i = 0; i < callbacks.length; i++) { + const fn = callbacks[i] + + if (typeof fn !== 'function') { + throw new TypeError('argument handler must be a function') + } + + const layer = Layer('/', {}, fn) + layer.method = undefined + + this.methods._all = true + this.stack.push(layer) + } + + return this +} + +methods.forEach(function (method) { + Route.prototype[method] = function (handler) { + const callbacks = flatten.call(slice.call(arguments), Infinity) + + if (callbacks.length === 0) { + throw new TypeError('argument handler is required') + } + + for (let i = 0; i < callbacks.length; i++) { + const fn = callbacks[i] + + if (typeof fn !== 'function') { + throw new TypeError('argument handler must be a function') + } + + debug('%s %s', method, this.path) + + const layer = Layer('/', {}, fn) + layer.method = method + + this.methods[method] = true + this.stack.push(layer) + } + + return this + } +}) diff --git a/node_modules/router/package.json b/node_modules/router/package.json new file mode 100644 index 0000000..123eca2 --- /dev/null +++ b/node_modules/router/package.json @@ -0,0 +1,44 @@ +{ + "name": "router", + "description": "Simple middleware-style router", + "version": "2.2.0", + "author": "Douglas Christopher Wilson ", + "contributors": [ + "Blake Embrey " + ], + "license": "MIT", + "repository": "pillarjs/router", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "devDependencies": { + "finalhandler": "^2.1.0", + "mocha": "10.2.0", + "nyc": "15.1.0", + "run-series": "^1.1.9", + "standard": "^17.1.0", + "supertest": "6.3.3" + }, + "files": [ + "lib/", + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 18" + }, + "scripts": { + "lint": "standard", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test:debug": "mocha --reporter spec --bail --check-leaks test/ --inspect --inspect-brk", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=text npm test", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/safe-buffer/LICENSE b/node_modules/safe-buffer/LICENSE new file mode 100644 index 0000000..0c068ce --- /dev/null +++ b/node_modules/safe-buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/safe-buffer/README.md b/node_modules/safe-buffer/README.md new file mode 100644 index 0000000..e9a81af --- /dev/null +++ b/node_modules/safe-buffer/README.md @@ -0,0 +1,584 @@ +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/safe-buffer +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg +[npm-url]: https://npmjs.org/package/safe-buffer +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg +[downloads-url]: https://npmjs.org/package/safe-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Safer Node.js Buffer API + +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** + +**Uses the built-in implementation when available.** + +## install + +``` +npm install safe-buffer +``` + +## usage + +The goal of this package is to provide a safe replacement for the node.js `Buffer`. + +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to +the top of your node.js modules: + +```js +var Buffer = require('safe-buffer').Buffer + +// Existing buffer code will continue to work without issues: + +new Buffer('hey', 'utf8') +new Buffer([1, 2, 3], 'utf8') +new Buffer(obj) +new Buffer(16) // create an uninitialized buffer (potentially unsafe) + +// But you can use these new explicit APIs to make clear what you want: + +Buffer.from('hey', 'utf8') // convert from many types to a Buffer +Buffer.alloc(16) // create a zero-filled buffer (safe) +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) +``` + +## api + +### Class Method: Buffer.from(array) + + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} Default: `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a `TypedArray` instance, +the newly created `Buffer` will share the same allocated memory as the +TypedArray. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `str`. If +provided, the `encoding` parameter identifies the character encoding. +If not provided, `encoding` defaults to `'utf8'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of +size `Buffer.poolSize` that is used as a pool for the fast allocation of new +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +Use of this pre-allocated internal memory pool is a key difference between +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The +difference is subtle but can be important when an application requires the +additional performance that `Buffer.allocUnsafe(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` objects. + +However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.read(); + // allocate for retained data + const sb = Buffer.allocUnsafeSlow(10); + // copy the data into the new allocation + data.copy(sb, 0, 0, 10); + store.push(sb); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/node_modules/safe-buffer/index.d.ts b/node_modules/safe-buffer/index.d.ts new file mode 100644 index 0000000..e9fed80 --- /dev/null +++ b/node_modules/safe-buffer/index.d.ts @@ -0,0 +1,187 @@ +declare module "safe-buffer" { + export class Buffer { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; + } +} \ No newline at end of file diff --git a/node_modules/safe-buffer/index.js b/node_modules/safe-buffer/index.js new file mode 100644 index 0000000..f8d3ec9 --- /dev/null +++ b/node_modules/safe-buffer/index.js @@ -0,0 +1,65 @@ +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/node_modules/safe-buffer/package.json b/node_modules/safe-buffer/package.json new file mode 100644 index 0000000..f2869e2 --- /dev/null +++ b/node_modules/safe-buffer/package.json @@ -0,0 +1,51 @@ +{ + "name": "safe-buffer", + "description": "Safer Node.js Buffer API", + "version": "5.2.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "devDependencies": { + "standard": "*", + "tape": "^5.0.0" + }, + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/node_modules/safer-buffer/LICENSE b/node_modules/safer-buffer/LICENSE new file mode 100644 index 0000000..4fe9e6f --- /dev/null +++ b/node_modules/safer-buffer/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Nikita Skovoroda + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/safer-buffer/Porting-Buffer.md b/node_modules/safer-buffer/Porting-Buffer.md new file mode 100644 index 0000000..68d86ba --- /dev/null +++ b/node_modules/safer-buffer/Porting-Buffer.md @@ -0,0 +1,268 @@ +# Porting to the Buffer.from/Buffer.alloc API + + +## Overview + +- [Variant 1: Drop support for Node.js ≤ 4.4.x and 5.0.0 — 5.9.x.](#variant-1) (*recommended*) +- [Variant 2: Use a polyfill](#variant-2) +- [Variant 3: manual detection, with safeguards](#variant-3) + +### Finding problematic bits of code using grep + +Just run `grep -nrE '[^a-zA-Z](Slow)?Buffer\s*\(' --exclude-dir node_modules`. + +It will find all the potentially unsafe places in your own code (with some considerably unlikely +exceptions). + +### Finding problematic bits of code using Node.js 8 + +If you’re using Node.js ≥ 8.0.0 (which is recommended), Node.js exposes multiple options that help with finding the relevant pieces of code: + +- `--trace-warnings` will make Node.js show a stack trace for this warning and other warnings that are printed by Node.js. +- `--trace-deprecation` does the same thing, but only for deprecation warnings. +- `--pending-deprecation` will show more types of deprecation warnings. In particular, it will show the `Buffer()` deprecation warning, even on Node.js 8. + +You can set these flags using an environment variable: + +```console +$ export NODE_OPTIONS='--trace-warnings --pending-deprecation' +$ cat example.js +'use strict'; +const foo = new Buffer('foo'); +$ node example.js +(node:7147) [DEP0005] DeprecationWarning: The Buffer() and new Buffer() constructors are not recommended for use due to security and usability concerns. Please use the new Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() construction methods instead. + at showFlaggedDeprecation (buffer.js:127:13) + at new Buffer (buffer.js:148:3) + at Object. (/path/to/example.js:2:13) + [... more stack trace lines ...] +``` + +### Finding problematic bits of code using linters + +Eslint rules [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) +or +[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) +also find calls to deprecated `Buffer()` API. Those rules are included in some pre-sets. + +There is a drawback, though, that it doesn't always +[work correctly](https://github.com/chalker/safer-buffer#why-not-safe-buffer) when `Buffer` is +overriden e.g. with a polyfill, so recommended is a combination of this and some other method +described above. + + +## Variant 1: Drop support for Node.js ≤ 4.4.x and 5.0.0 — 5.9.x. + +This is the recommended solution nowadays that would imply only minimal overhead. + +The Node.js 5.x release line has been unsupported since July 2016, and the Node.js 4.x release line reaches its End of Life in April 2018 (→ [Schedule](https://github.com/nodejs/Release#release-schedule)). This means that these versions of Node.js will *not* receive any updates, even in case of security issues, so using these release lines should be avoided, if at all possible. + +What you would do in this case is to convert all `new Buffer()` or `Buffer()` calls to use `Buffer.alloc()` or `Buffer.from()`, in the following way: + +- For `new Buffer(number)`, replace it with `Buffer.alloc(number)`. +- For `new Buffer(string)` (or `new Buffer(string, encoding)`), replace it with `Buffer.from(string)` (or `Buffer.from(string, encoding)`). +- For all other combinations of arguments (these are much rarer), also replace `new Buffer(...arguments)` with `Buffer.from(...arguments)`. + +Note that `Buffer.alloc()` is also _faster_ on the current Node.js versions than +`new Buffer(size).fill(0)`, which is what you would otherwise need to ensure zero-filling. + +Enabling eslint rule [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) +or +[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) +is recommended to avoid accidential unsafe Buffer API usage. + +There is also a [JSCodeshift codemod](https://github.com/joyeecheung/node-dep-codemod#dep005) +for automatically migrating Buffer constructors to `Buffer.alloc()` or `Buffer.from()`. +Note that it currently only works with cases where the arguments are literals or where the +constructor is invoked with two arguments. + +_If you currently support those older Node.js versions and dropping them would be a semver-major change +for you, or if you support older branches of your packages, consider using [Variant 2](#variant-2) +or [Variant 3](#variant-3) on older branches, so people using those older branches will also receive +the fix. That way, you will eradicate potential issues caused by unguarded Buffer API usage and +your users will not observe a runtime deprecation warning when running your code on Node.js 10._ + + +## Variant 2: Use a polyfill + +Utilize [safer-buffer](https://www.npmjs.com/package/safer-buffer) as a polyfill to support older +Node.js versions. + +You would take exacly the same steps as in [Variant 1](#variant-1), but with a polyfill +`const Buffer = require('safer-buffer').Buffer` in all files where you use the new `Buffer` api. + +Make sure that you do not use old `new Buffer` API — in any files where the line above is added, +using old `new Buffer()` API will _throw_. It will be easy to notice that in CI, though. + +Alternatively, you could use [buffer-from](https://www.npmjs.com/package/buffer-from) and/or +[buffer-alloc](https://www.npmjs.com/package/buffer-alloc) [ponyfills](https://ponyfill.com/) — +those are great, the only downsides being 4 deps in the tree and slightly more code changes to +migrate off them (as you would be using e.g. `Buffer.from` under a different name). If you need only +`Buffer.from` polyfilled — `buffer-from` alone which comes with no extra dependencies. + +_Alternatively, you could use [safe-buffer](https://www.npmjs.com/package/safe-buffer) — it also +provides a polyfill, but takes a different approach which has +[it's drawbacks](https://github.com/chalker/safer-buffer#why-not-safe-buffer). It will allow you +to also use the older `new Buffer()` API in your code, though — but that's arguably a benefit, as +it is problematic, can cause issues in your code, and will start emitting runtime deprecation +warnings starting with Node.js 10._ + +Note that in either case, it is important that you also remove all calls to the old Buffer +API manually — just throwing in `safe-buffer` doesn't fix the problem by itself, it just provides +a polyfill for the new API. I have seen people doing that mistake. + +Enabling eslint rule [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) +or +[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) +is recommended. + +_Don't forget to drop the polyfill usage once you drop support for Node.js < 4.5.0._ + + +## Variant 3 — manual detection, with safeguards + +This is useful if you create Buffer instances in only a few places (e.g. one), or you have your own +wrapper around them. + +### Buffer(0) + +This special case for creating empty buffers can be safely replaced with `Buffer.concat([])`, which +returns the same result all the way down to Node.js 0.8.x. + +### Buffer(notNumber) + +Before: + +```js +var buf = new Buffer(notNumber, encoding); +``` + +After: + +```js +var buf; +if (Buffer.from && Buffer.from !== Uint8Array.from) { + buf = Buffer.from(notNumber, encoding); +} else { + if (typeof notNumber === 'number') + throw new Error('The "size" argument must be of type number.'); + buf = new Buffer(notNumber, encoding); +} +``` + +`encoding` is optional. + +Note that the `typeof notNumber` before `new Buffer` is required (for cases when `notNumber` argument is not +hard-coded) and _is not caused by the deprecation of Buffer constructor_ — it's exactly _why_ the +Buffer constructor is deprecated. Ecosystem packages lacking this type-check caused numereous +security issues — situations when unsanitized user input could end up in the `Buffer(arg)` create +problems ranging from DoS to leaking sensitive information to the attacker from the process memory. + +When `notNumber` argument is hardcoded (e.g. literal `"abc"` or `[0,1,2]`), the `typeof` check can +be omitted. + +Also note that using TypeScript does not fix this problem for you — when libs written in +`TypeScript` are used from JS, or when user input ends up there — it behaves exactly as pure JS, as +all type checks are translation-time only and are not present in the actual JS code which TS +compiles to. + +### Buffer(number) + +For Node.js 0.10.x (and below) support: + +```js +var buf; +if (Buffer.alloc) { + buf = Buffer.alloc(number); +} else { + buf = new Buffer(number); + buf.fill(0); +} +``` + +Otherwise (Node.js ≥ 0.12.x): + +```js +const buf = Buffer.alloc ? Buffer.alloc(number) : new Buffer(number).fill(0); +``` + +## Regarding Buffer.allocUnsafe + +Be extra cautious when using `Buffer.allocUnsafe`: + * Don't use it if you don't have a good reason to + * e.g. you probably won't ever see a performance difference for small buffers, in fact, those + might be even faster with `Buffer.alloc()`, + * if your code is not in the hot code path — you also probably won't notice a difference, + * keep in mind that zero-filling minimizes the potential risks. + * If you use it, make sure that you never return the buffer in a partially-filled state, + * if you are writing to it sequentially — always truncate it to the actuall written length + +Errors in handling buffers allocated with `Buffer.allocUnsafe` could result in various issues, +ranged from undefined behaviour of your code to sensitive data (user input, passwords, certs) +leaking to the remote attacker. + +_Note that the same applies to `new Buffer` usage without zero-filling, depending on the Node.js +version (and lacking type checks also adds DoS to the list of potential problems)._ + + +## FAQ + + +### What is wrong with the `Buffer` constructor? + +The `Buffer` constructor could be used to create a buffer in many different ways: + +- `new Buffer(42)` creates a `Buffer` of 42 bytes. Before Node.js 8, this buffer contained + *arbitrary memory* for performance reasons, which could include anything ranging from + program source code to passwords and encryption keys. +- `new Buffer('abc')` creates a `Buffer` that contains the UTF-8-encoded version of + the string `'abc'`. A second argument could specify another encoding: For example, + `new Buffer(string, 'base64')` could be used to convert a Base64 string into the original + sequence of bytes that it represents. +- There are several other combinations of arguments. + +This meant that, in code like `var buffer = new Buffer(foo);`, *it is not possible to tell +what exactly the contents of the generated buffer are* without knowing the type of `foo`. + +Sometimes, the value of `foo` comes from an external source. For example, this function +could be exposed as a service on a web server, converting a UTF-8 string into its Base64 form: + +``` +function stringToBase64(req, res) { + // The request body should have the format of `{ string: 'foobar' }` + const rawBytes = new Buffer(req.body.string) + const encoded = rawBytes.toString('base64') + res.end({ encoded: encoded }) +} +``` + +Note that this code does *not* validate the type of `req.body.string`: + +- `req.body.string` is expected to be a string. If this is the case, all goes well. +- `req.body.string` is controlled by the client that sends the request. +- If `req.body.string` is the *number* `50`, the `rawBytes` would be 50 bytes: + - Before Node.js 8, the content would be uninitialized + - After Node.js 8, the content would be `50` bytes with the value `0` + +Because of the missing type check, an attacker could intentionally send a number +as part of the request. Using this, they can either: + +- Read uninitialized memory. This **will** leak passwords, encryption keys and other + kinds of sensitive information. (Information leak) +- Force the program to allocate a large amount of memory. For example, when specifying + `500000000` as the input value, each request will allocate 500MB of memory. + This can be used to either exhaust the memory available of a program completely + and make it crash, or slow it down significantly. (Denial of Service) + +Both of these scenarios are considered serious security issues in a real-world +web server context. + +when using `Buffer.from(req.body.string)` instead, passing a number will always +throw an exception instead, giving a controlled behaviour that can always be +handled by the program. + + +### The `Buffer()` constructor has been deprecated for a while. Is this really an issue? + +Surveys of code in the `npm` ecosystem have shown that the `Buffer()` constructor is still +widely used. This includes new code, and overall usage of such code has actually been +*increasing*. diff --git a/node_modules/safer-buffer/Readme.md b/node_modules/safer-buffer/Readme.md new file mode 100644 index 0000000..14b0822 --- /dev/null +++ b/node_modules/safer-buffer/Readme.md @@ -0,0 +1,156 @@ +# safer-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![javascript style guide][standard-image]][standard-url] [![Security Responsible Disclosure][secuirty-image]][secuirty-url] + +[travis-image]: https://travis-ci.org/ChALkeR/safer-buffer.svg?branch=master +[travis-url]: https://travis-ci.org/ChALkeR/safer-buffer +[npm-image]: https://img.shields.io/npm/v/safer-buffer.svg +[npm-url]: https://npmjs.org/package/safer-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com +[secuirty-image]: https://img.shields.io/badge/Security-Responsible%20Disclosure-green.svg +[secuirty-url]: https://github.com/nodejs/security-wg/blob/master/processes/responsible_disclosure_template.md + +Modern Buffer API polyfill without footguns, working on Node.js from 0.8 to current. + +## How to use? + +First, port all `Buffer()` and `new Buffer()` calls to `Buffer.alloc()` and `Buffer.from()` API. + +Then, to achieve compatibility with outdated Node.js versions (`<4.5.0` and 5.x `<5.9.0`), use +`const Buffer = require('safer-buffer').Buffer` in all files where you make calls to the new +Buffer API. _Use `var` instead of `const` if you need that for your Node.js version range support._ + +Also, see the +[porting Buffer](https://github.com/ChALkeR/safer-buffer/blob/master/Porting-Buffer.md) guide. + +## Do I need it? + +Hopefully, not — dropping support for outdated Node.js versions should be fine nowdays, and that +is the recommended path forward. You _do_ need to port to the `Buffer.alloc()` and `Buffer.from()` +though. + +See the [porting guide](https://github.com/ChALkeR/safer-buffer/blob/master/Porting-Buffer.md) +for a better description. + +## Why not [safe-buffer](https://npmjs.com/safe-buffer)? + +_In short: while `safe-buffer` serves as a polyfill for the new API, it allows old API usage and +itself contains footguns._ + +`safe-buffer` could be used safely to get the new API while still keeping support for older +Node.js versions (like this module), but while analyzing ecosystem usage of the old Buffer API +I found out that `safe-buffer` is itself causing problems in some cases. + +For example, consider the following snippet: + +```console +$ cat example.unsafe.js +console.log(Buffer(20)) +$ ./node-v6.13.0-linux-x64/bin/node example.unsafe.js + +$ standard example.unsafe.js +standard: Use JavaScript Standard Style (https://standardjs.com) + /home/chalker/repo/safer-buffer/example.unsafe.js:2:13: 'Buffer()' was deprecated since v6. Use 'Buffer.alloc()' or 'Buffer.from()' (use 'https://www.npmjs.com/package/safe-buffer' for '<4.5.0') instead. +``` + +This is allocates and writes to console an uninitialized chunk of memory. +[standard](https://www.npmjs.com/package/standard) linter (among others) catch that and warn people +to avoid using unsafe API. + +Let's now throw in `safe-buffer`! + +```console +$ cat example.safe-buffer.js +const Buffer = require('safe-buffer').Buffer +console.log(Buffer(20)) +$ standard example.safe-buffer.js +$ ./node-v6.13.0-linux-x64/bin/node example.safe-buffer.js + +``` + +See the problem? Adding in `safe-buffer` _magically removes the lint warning_, but the behavior +remains identiсal to what we had before, and when launched on Node.js 6.x LTS — this dumps out +chunks of uninitialized memory. +_And this code will still emit runtime warnings on Node.js 10.x and above._ + +That was done by design. I first considered changing `safe-buffer`, prohibiting old API usage or +emitting warnings on it, but that significantly diverges from `safe-buffer` design. After some +discussion, it was decided to move my approach into a separate package, and _this is that separate +package_. + +This footgun is not imaginary — I observed top-downloaded packages doing that kind of thing, +«fixing» the lint warning by blindly including `safe-buffer` without any actual changes. + +Also in some cases, even if the API _was_ migrated to use of safe Buffer API — a random pull request +can bring unsafe Buffer API usage back to the codebase by adding new calls — and that could go +unnoticed even if you have a linter prohibiting that (becase of the reason stated above), and even +pass CI. _I also observed that being done in popular packages._ + +Some examples: + * [webdriverio](https://github.com/webdriverio/webdriverio/commit/05cbd3167c12e4930f09ef7cf93b127ba4effae4#diff-124380949022817b90b622871837d56cR31) + (a module with 548 759 downloads/month), + * [websocket-stream](https://github.com/maxogden/websocket-stream/commit/c9312bd24d08271687d76da0fe3c83493871cf61) + (218 288 d/m, fix in [maxogden/websocket-stream#142](https://github.com/maxogden/websocket-stream/pull/142)), + * [node-serialport](https://github.com/node-serialport/node-serialport/commit/e8d9d2b16c664224920ce1c895199b1ce2def48c) + (113 138 d/m, fix in [node-serialport/node-serialport#1510](https://github.com/node-serialport/node-serialport/pull/1510)), + * [karma](https://github.com/karma-runner/karma/commit/3d94b8cf18c695104ca195334dc75ff054c74eec) + (3 973 193 d/m, fix in [karma-runner/karma#2947](https://github.com/karma-runner/karma/pull/2947)), + * [spdy-transport](https://github.com/spdy-http2/spdy-transport/commit/5375ac33f4a62a4f65bcfc2827447d42a5dbe8b1) + (5 970 727 d/m, fix in [spdy-http2/spdy-transport#53](https://github.com/spdy-http2/spdy-transport/pull/53)). + * And there are a lot more over the ecosystem. + +I filed a PR at +[mysticatea/eslint-plugin-node#110](https://github.com/mysticatea/eslint-plugin-node/pull/110) to +partially fix that (for cases when that lint rule is used), but it is a semver-major change for +linter rules and presets, so it would take significant time for that to reach actual setups. +_It also hasn't been released yet (2018-03-20)._ + +Also, `safer-buffer` discourages the usage of `.allocUnsafe()`, which is often done by a mistake. +It still supports it with an explicit concern barier, by placing it under +`require('safer-buffer/dangereous')`. + +## But isn't throwing bad? + +Not really. It's an error that could be noticed and fixed early, instead of causing havoc later like +unguarded `new Buffer()` calls that end up receiving user input can do. + +This package affects only the files where `var Buffer = require('safer-buffer').Buffer` was done, so +it is really simple to keep track of things and make sure that you don't mix old API usage with that. +Also, CI should hint anything that you might have missed. + +New commits, if tested, won't land new usage of unsafe Buffer API this way. +_Node.js 10.x also deals with that by printing a runtime depecation warning._ + +### Would it affect third-party modules? + +No, unless you explicitly do an awful thing like monkey-patching or overriding the built-in `Buffer`. +Don't do that. + +### But I don't want throwing… + +That is also fine! + +Also, it could be better in some cases when you don't comprehensive enough test coverage. + +In that case — just don't override `Buffer` and use +`var SaferBuffer = require('safer-buffer').Buffer` instead. + +That way, everything using `Buffer` natively would still work, but there would be two drawbacks: + +* `Buffer.from`/`Buffer.alloc` won't be polyfilled — use `SaferBuffer.from` and + `SaferBuffer.alloc` instead. +* You are still open to accidentally using the insecure deprecated API — use a linter to catch that. + +Note that using a linter to catch accidential `Buffer` constructor usage in this case is strongly +recommended. `Buffer` is not overriden in this usecase, so linters won't get confused. + +## «Without footguns»? + +Well, it is still possible to do _some_ things with `Buffer` API, e.g. accessing `.buffer` property +on older versions and duping things from there. You shouldn't do that in your code, probabably. + +The intention is to remove the most significant footguns that affect lots of packages in the +ecosystem, and to do it in the proper way. + +Also, this package doesn't protect against security issues affecting some Node.js versions, so for +usage in your own production code, it is still recommended to update to a Node.js version +[supported by upstream](https://github.com/nodejs/release#release-schedule). diff --git a/node_modules/safer-buffer/dangerous.js b/node_modules/safer-buffer/dangerous.js new file mode 100644 index 0000000..ca41fdc --- /dev/null +++ b/node_modules/safer-buffer/dangerous.js @@ -0,0 +1,58 @@ +/* eslint-disable node/no-deprecated-api */ + +'use strict' + +var buffer = require('buffer') +var Buffer = buffer.Buffer +var safer = require('./safer.js') +var Safer = safer.Buffer + +var dangerous = {} + +var key + +for (key in safer) { + if (!safer.hasOwnProperty(key)) continue + dangerous[key] = safer[key] +} + +var Dangereous = dangerous.Buffer = {} + +// Copy Safer API +for (key in Safer) { + if (!Safer.hasOwnProperty(key)) continue + Dangereous[key] = Safer[key] +} + +// Copy those missing unsafe methods, if they are present +for (key in Buffer) { + if (!Buffer.hasOwnProperty(key)) continue + if (Dangereous.hasOwnProperty(key)) continue + Dangereous[key] = Buffer[key] +} + +if (!Dangereous.allocUnsafe) { + Dangereous.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) + } + if (size < 0 || size >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } + return Buffer(size) + } +} + +if (!Dangereous.allocUnsafeSlow) { + Dangereous.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) + } + if (size < 0 || size >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } + return buffer.SlowBuffer(size) + } +} + +module.exports = dangerous diff --git a/node_modules/safer-buffer/package.json b/node_modules/safer-buffer/package.json new file mode 100644 index 0000000..d452b04 --- /dev/null +++ b/node_modules/safer-buffer/package.json @@ -0,0 +1,34 @@ +{ + "name": "safer-buffer", + "version": "2.1.2", + "description": "Modern Buffer API polyfill without footguns", + "main": "safer.js", + "scripts": { + "browserify-test": "browserify --external tape tests.js > browserify-tests.js && tape browserify-tests.js", + "test": "standard && tape tests.js" + }, + "author": { + "name": "Nikita Skovoroda", + "email": "chalkerx@gmail.com", + "url": "https://github.com/ChALkeR" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/ChALkeR/safer-buffer.git" + }, + "bugs": { + "url": "https://github.com/ChALkeR/safer-buffer/issues" + }, + "devDependencies": { + "standard": "^11.0.1", + "tape": "^4.9.0" + }, + "files": [ + "Porting-Buffer.md", + "Readme.md", + "tests.js", + "dangerous.js", + "safer.js" + ] +} diff --git a/node_modules/safer-buffer/safer.js b/node_modules/safer-buffer/safer.js new file mode 100644 index 0000000..37c7e1a --- /dev/null +++ b/node_modules/safer-buffer/safer.js @@ -0,0 +1,77 @@ +/* eslint-disable node/no-deprecated-api */ + +'use strict' + +var buffer = require('buffer') +var Buffer = buffer.Buffer + +var safer = {} + +var key + +for (key in buffer) { + if (!buffer.hasOwnProperty(key)) continue + if (key === 'SlowBuffer' || key === 'Buffer') continue + safer[key] = buffer[key] +} + +var Safer = safer.Buffer = {} +for (key in Buffer) { + if (!Buffer.hasOwnProperty(key)) continue + if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue + Safer[key] = Buffer[key] +} + +safer.Buffer.prototype = Buffer.prototype + +if (!Safer.from || Safer.from === Uint8Array.from) { + Safer.from = function (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) + } + if (value && typeof value.length === 'undefined') { + throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) + } + return Buffer(value, encodingOrOffset, length) + } +} + +if (!Safer.alloc) { + Safer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) + } + if (size < 0 || size >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } + var buf = Buffer(size) + if (!fill || fill.length === 0) { + buf.fill(0) + } else if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + return buf + } +} + +if (!safer.kStringMaxLength) { + try { + safer.kStringMaxLength = process.binding('buffer').kStringMaxLength + } catch (e) { + // we can't determine kStringMaxLength in environments where process.binding + // is unsupported, so let's not set it + } +} + +if (!safer.constants) { + safer.constants = { + MAX_LENGTH: safer.kMaxLength + } + if (safer.kStringMaxLength) { + safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength + } +} + +module.exports = safer diff --git a/node_modules/safer-buffer/tests.js b/node_modules/safer-buffer/tests.js new file mode 100644 index 0000000..7ed2777 --- /dev/null +++ b/node_modules/safer-buffer/tests.js @@ -0,0 +1,406 @@ +/* eslint-disable node/no-deprecated-api */ + +'use strict' + +var test = require('tape') + +var buffer = require('buffer') + +var index = require('./') +var safer = require('./safer') +var dangerous = require('./dangerous') + +/* Inheritance tests */ + +test('Default is Safer', function (t) { + t.equal(index, safer) + t.notEqual(safer, dangerous) + t.notEqual(index, dangerous) + t.end() +}) + +test('Is not a function', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(typeof impl, 'object') + t.equal(typeof impl.Buffer, 'object') + }); + [buffer].forEach(function (impl) { + t.equal(typeof impl, 'object') + t.equal(typeof impl.Buffer, 'function') + }) + t.end() +}) + +test('Constructor throws', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.throws(function () { impl.Buffer() }) + t.throws(function () { impl.Buffer(0) }) + t.throws(function () { impl.Buffer('a') }) + t.throws(function () { impl.Buffer('a', 'utf-8') }) + t.throws(function () { return new impl.Buffer() }) + t.throws(function () { return new impl.Buffer(0) }) + t.throws(function () { return new impl.Buffer('a') }) + t.throws(function () { return new impl.Buffer('a', 'utf-8') }) + }) + t.end() +}) + +test('Safe methods exist', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(typeof impl.Buffer.alloc, 'function', 'alloc') + t.equal(typeof impl.Buffer.from, 'function', 'from') + }) + t.end() +}) + +test('Unsafe methods exist only in Dangerous', function (t) { + [index, safer].forEach(function (impl) { + t.equal(typeof impl.Buffer.allocUnsafe, 'undefined') + t.equal(typeof impl.Buffer.allocUnsafeSlow, 'undefined') + }); + [dangerous].forEach(function (impl) { + t.equal(typeof impl.Buffer.allocUnsafe, 'function') + t.equal(typeof impl.Buffer.allocUnsafeSlow, 'function') + }) + t.end() +}) + +test('Generic methods/properties are defined and equal', function (t) { + ['poolSize', 'isBuffer', 'concat', 'byteLength'].forEach(function (method) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer[method], buffer.Buffer[method], method) + t.notEqual(typeof impl.Buffer[method], 'undefined', method) + }) + }) + t.end() +}) + +test('Built-in buffer static methods/properties are inherited', function (t) { + Object.keys(buffer).forEach(function (method) { + if (method === 'SlowBuffer' || method === 'Buffer') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl[method], buffer[method], method) + t.notEqual(typeof impl[method], 'undefined', method) + }) + }) + t.end() +}) + +test('Built-in Buffer static methods/properties are inherited', function (t) { + Object.keys(buffer.Buffer).forEach(function (method) { + if (method === 'allocUnsafe' || method === 'allocUnsafeSlow') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer[method], buffer.Buffer[method], method) + t.notEqual(typeof impl.Buffer[method], 'undefined', method) + }) + }) + t.end() +}) + +test('.prototype property of Buffer is inherited', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer.prototype, buffer.Buffer.prototype, 'prototype') + t.notEqual(typeof impl.Buffer.prototype, 'undefined', 'prototype') + }) + t.end() +}) + +test('All Safer methods are present in Dangerous', function (t) { + Object.keys(safer).forEach(function (method) { + if (method === 'Buffer') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl[method], safer[method], method) + if (method !== 'kStringMaxLength') { + t.notEqual(typeof impl[method], 'undefined', method) + } + }) + }) + Object.keys(safer.Buffer).forEach(function (method) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer[method], safer.Buffer[method], method) + t.notEqual(typeof impl.Buffer[method], 'undefined', method) + }) + }) + t.end() +}) + +test('Safe methods from Dangerous methods are present in Safer', function (t) { + Object.keys(dangerous).forEach(function (method) { + if (method === 'Buffer') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl[method], dangerous[method], method) + if (method !== 'kStringMaxLength') { + t.notEqual(typeof impl[method], 'undefined', method) + } + }) + }) + Object.keys(dangerous.Buffer).forEach(function (method) { + if (method === 'allocUnsafe' || method === 'allocUnsafeSlow') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer[method], dangerous.Buffer[method], method) + t.notEqual(typeof impl.Buffer[method], 'undefined', method) + }) + }) + t.end() +}) + +/* Behaviour tests */ + +test('Methods return Buffers', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0, 10))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0, 'a'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(10))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(10, 'x'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(9, 'ab'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from(''))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('string'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('string', 'utf-8'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from([0, 42, 3]))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from(new Uint8Array([0, 42, 3])))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from([]))) + }); + ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { + t.ok(buffer.Buffer.isBuffer(dangerous.Buffer[method](0))) + t.ok(buffer.Buffer.isBuffer(dangerous.Buffer[method](10))) + }) + t.end() +}) + +test('Constructor is buffer.Buffer', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer.alloc(0).constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(0, 10).constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(0, 'a').constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(10).constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(10, 'x').constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(9, 'ab').constructor, buffer.Buffer) + t.equal(impl.Buffer.from('').constructor, buffer.Buffer) + t.equal(impl.Buffer.from('string').constructor, buffer.Buffer) + t.equal(impl.Buffer.from('string', 'utf-8').constructor, buffer.Buffer) + t.equal(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64').constructor, buffer.Buffer) + t.equal(impl.Buffer.from([0, 42, 3]).constructor, buffer.Buffer) + t.equal(impl.Buffer.from(new Uint8Array([0, 42, 3])).constructor, buffer.Buffer) + t.equal(impl.Buffer.from([]).constructor, buffer.Buffer) + }); + [0, 10, 100].forEach(function (arg) { + t.equal(dangerous.Buffer.allocUnsafe(arg).constructor, buffer.Buffer) + t.equal(dangerous.Buffer.allocUnsafeSlow(arg).constructor, buffer.SlowBuffer(0).constructor) + }) + t.end() +}) + +test('Invalid calls throw', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.throws(function () { impl.Buffer.from(0) }) + t.throws(function () { impl.Buffer.from(10) }) + t.throws(function () { impl.Buffer.from(10, 'utf-8') }) + t.throws(function () { impl.Buffer.from('string', 'invalid encoding') }) + t.throws(function () { impl.Buffer.from(-10) }) + t.throws(function () { impl.Buffer.from(1e90) }) + t.throws(function () { impl.Buffer.from(Infinity) }) + t.throws(function () { impl.Buffer.from(-Infinity) }) + t.throws(function () { impl.Buffer.from(NaN) }) + t.throws(function () { impl.Buffer.from(null) }) + t.throws(function () { impl.Buffer.from(undefined) }) + t.throws(function () { impl.Buffer.from() }) + t.throws(function () { impl.Buffer.from({}) }) + t.throws(function () { impl.Buffer.alloc('') }) + t.throws(function () { impl.Buffer.alloc('string') }) + t.throws(function () { impl.Buffer.alloc('string', 'utf-8') }) + t.throws(function () { impl.Buffer.alloc('b25ldHdvdGhyZWU=', 'base64') }) + t.throws(function () { impl.Buffer.alloc(-10) }) + t.throws(function () { impl.Buffer.alloc(1e90) }) + t.throws(function () { impl.Buffer.alloc(2 * (1 << 30)) }) + t.throws(function () { impl.Buffer.alloc(Infinity) }) + t.throws(function () { impl.Buffer.alloc(-Infinity) }) + t.throws(function () { impl.Buffer.alloc(null) }) + t.throws(function () { impl.Buffer.alloc(undefined) }) + t.throws(function () { impl.Buffer.alloc() }) + t.throws(function () { impl.Buffer.alloc([]) }) + t.throws(function () { impl.Buffer.alloc([0, 42, 3]) }) + t.throws(function () { impl.Buffer.alloc({}) }) + }); + ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { + t.throws(function () { dangerous.Buffer[method]('') }) + t.throws(function () { dangerous.Buffer[method]('string') }) + t.throws(function () { dangerous.Buffer[method]('string', 'utf-8') }) + t.throws(function () { dangerous.Buffer[method](2 * (1 << 30)) }) + t.throws(function () { dangerous.Buffer[method](Infinity) }) + if (dangerous.Buffer[method] === buffer.Buffer.allocUnsafe) { + t.skip('Skipping, older impl of allocUnsafe coerced negative sizes to 0') + } else { + t.throws(function () { dangerous.Buffer[method](-10) }) + t.throws(function () { dangerous.Buffer[method](-1e90) }) + t.throws(function () { dangerous.Buffer[method](-Infinity) }) + } + t.throws(function () { dangerous.Buffer[method](null) }) + t.throws(function () { dangerous.Buffer[method](undefined) }) + t.throws(function () { dangerous.Buffer[method]() }) + t.throws(function () { dangerous.Buffer[method]([]) }) + t.throws(function () { dangerous.Buffer[method]([0, 42, 3]) }) + t.throws(function () { dangerous.Buffer[method]({}) }) + }) + t.end() +}) + +test('Buffers have appropriate lengths', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer.alloc(0).length, 0) + t.equal(impl.Buffer.alloc(10).length, 10) + t.equal(impl.Buffer.from('').length, 0) + t.equal(impl.Buffer.from('string').length, 6) + t.equal(impl.Buffer.from('string', 'utf-8').length, 6) + t.equal(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64').length, 11) + t.equal(impl.Buffer.from([0, 42, 3]).length, 3) + t.equal(impl.Buffer.from(new Uint8Array([0, 42, 3])).length, 3) + t.equal(impl.Buffer.from([]).length, 0) + }); + ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { + t.equal(dangerous.Buffer[method](0).length, 0) + t.equal(dangerous.Buffer[method](10).length, 10) + }) + t.end() +}) + +test('Buffers have appropriate lengths (2)', function (t) { + t.equal(index.Buffer.alloc, safer.Buffer.alloc) + t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) + var ok = true; + [ safer.Buffer.alloc, + dangerous.Buffer.allocUnsafe, + dangerous.Buffer.allocUnsafeSlow + ].forEach(function (method) { + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 1e5) + var buf = method(length) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + } + }) + t.ok(ok) + t.end() +}) + +test('.alloc(size) is zero-filled and has correct length', function (t) { + t.equal(index.Buffer.alloc, safer.Buffer.alloc) + t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) + var ok = true + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 2e6) + var buf = index.Buffer.alloc(length) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + var j + for (j = 0; j < length; j++) { + if (buf[j] !== 0) ok = false + } + buf.fill(1) + for (j = 0; j < length; j++) { + if (buf[j] !== 1) ok = false + } + } + t.ok(ok) + t.end() +}) + +test('.allocUnsafe / .allocUnsafeSlow are fillable and have correct lengths', function (t) { + ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { + var ok = true + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 2e6) + var buf = dangerous.Buffer[method](length) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + buf.fill(0, 0, length) + var j + for (j = 0; j < length; j++) { + if (buf[j] !== 0) ok = false + } + buf.fill(1, 0, length) + for (j = 0; j < length; j++) { + if (buf[j] !== 1) ok = false + } + } + t.ok(ok, method) + }) + t.end() +}) + +test('.alloc(size, fill) is `fill`-filled', function (t) { + t.equal(index.Buffer.alloc, safer.Buffer.alloc) + t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) + var ok = true + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 2e6) + var fill = Math.round(Math.random() * 255) + var buf = index.Buffer.alloc(length, fill) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + for (var j = 0; j < length; j++) { + if (buf[j] !== fill) ok = false + } + } + t.ok(ok) + t.end() +}) + +test('.alloc(size, fill) is `fill`-filled', function (t) { + t.equal(index.Buffer.alloc, safer.Buffer.alloc) + t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) + var ok = true + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 2e6) + var fill = Math.round(Math.random() * 255) + var buf = index.Buffer.alloc(length, fill) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + for (var j = 0; j < length; j++) { + if (buf[j] !== fill) ok = false + } + } + t.ok(ok) + t.deepEqual(index.Buffer.alloc(9, 'a'), index.Buffer.alloc(9, 97)) + t.notDeepEqual(index.Buffer.alloc(9, 'a'), index.Buffer.alloc(9, 98)) + + var tmp = new buffer.Buffer(2) + tmp.fill('ok') + if (tmp[1] === tmp[0]) { + // Outdated Node.js + t.deepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('ooooo')) + } else { + t.deepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('okoko')) + } + t.notDeepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('kokok')) + + t.end() +}) + +test('safer.Buffer.from returns results same as Buffer constructor', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.deepEqual(impl.Buffer.from(''), new buffer.Buffer('')) + t.deepEqual(impl.Buffer.from('string'), new buffer.Buffer('string')) + t.deepEqual(impl.Buffer.from('string', 'utf-8'), new buffer.Buffer('string', 'utf-8')) + t.deepEqual(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'), new buffer.Buffer('b25ldHdvdGhyZWU=', 'base64')) + t.deepEqual(impl.Buffer.from([0, 42, 3]), new buffer.Buffer([0, 42, 3])) + t.deepEqual(impl.Buffer.from(new Uint8Array([0, 42, 3])), new buffer.Buffer(new Uint8Array([0, 42, 3]))) + t.deepEqual(impl.Buffer.from([]), new buffer.Buffer([])) + }) + t.end() +}) + +test('safer.Buffer.from returns consistent results', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.deepEqual(impl.Buffer.from(''), impl.Buffer.alloc(0)) + t.deepEqual(impl.Buffer.from([]), impl.Buffer.alloc(0)) + t.deepEqual(impl.Buffer.from(new Uint8Array([])), impl.Buffer.alloc(0)) + t.deepEqual(impl.Buffer.from('string', 'utf-8'), impl.Buffer.from('string')) + t.deepEqual(impl.Buffer.from('string'), impl.Buffer.from([115, 116, 114, 105, 110, 103])) + t.deepEqual(impl.Buffer.from('string'), impl.Buffer.from(impl.Buffer.from('string'))) + t.deepEqual(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'), impl.Buffer.from('onetwothree')) + t.notDeepEqual(impl.Buffer.from('b25ldHdvdGhyZWU='), impl.Buffer.from('onetwothree')) + }) + t.end() +}) diff --git a/node_modules/semver/LICENSE b/node_modules/semver/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/semver/README.md b/node_modules/semver/README.md new file mode 100644 index 0000000..e952215 --- /dev/null +++ b/node_modules/semver/README.md @@ -0,0 +1,664 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Install + +```bash +npm install semver +```` + +## Usage + +As a node module: + +```js +const semver = require('semver') + +semver.valid('1.2.3') // '1.2.3' +semver.valid('a.b.c') // null +semver.clean(' =v1.2.3 ') // '1.2.3' +semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true +semver.gt('1.2.3', '9.8.7') // false +semver.lt('1.2.3', '9.8.7') // true +semver.minVersion('>=1.0.0') // '1.0.0' +semver.valid(semver.coerce('v2')) // '2.0.0' +semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' +``` + +You can also just load the module for the function that you care about if +you'd like to minimize your footprint. + +```js +// load the whole API at once in a single object +const semver = require('semver') + +// or just load the bits you need +// all of them listed here, just pick and choose what you want + +// classes +const SemVer = require('semver/classes/semver') +const Comparator = require('semver/classes/comparator') +const Range = require('semver/classes/range') + +// functions for working with versions +const semverParse = require('semver/functions/parse') +const semverValid = require('semver/functions/valid') +const semverClean = require('semver/functions/clean') +const semverInc = require('semver/functions/inc') +const semverDiff = require('semver/functions/diff') +const semverMajor = require('semver/functions/major') +const semverMinor = require('semver/functions/minor') +const semverPatch = require('semver/functions/patch') +const semverPrerelease = require('semver/functions/prerelease') +const semverCompare = require('semver/functions/compare') +const semverRcompare = require('semver/functions/rcompare') +const semverCompareLoose = require('semver/functions/compare-loose') +const semverCompareBuild = require('semver/functions/compare-build') +const semverSort = require('semver/functions/sort') +const semverRsort = require('semver/functions/rsort') + +// low-level comparators between versions +const semverGt = require('semver/functions/gt') +const semverLt = require('semver/functions/lt') +const semverEq = require('semver/functions/eq') +const semverNeq = require('semver/functions/neq') +const semverGte = require('semver/functions/gte') +const semverLte = require('semver/functions/lte') +const semverCmp = require('semver/functions/cmp') +const semverCoerce = require('semver/functions/coerce') + +// working with ranges +const semverSatisfies = require('semver/functions/satisfies') +const semverMaxSatisfying = require('semver/ranges/max-satisfying') +const semverMinSatisfying = require('semver/ranges/min-satisfying') +const semverToComparators = require('semver/ranges/to-comparators') +const semverMinVersion = require('semver/ranges/min-version') +const semverValidRange = require('semver/ranges/valid') +const semverOutside = require('semver/ranges/outside') +const semverGtr = require('semver/ranges/gtr') +const semverLtr = require('semver/ranges/ltr') +const semverIntersects = require('semver/ranges/intersects') +const semverSimplifyRange = require('semver/ranges/simplify') +const semverRangeSubset = require('semver/ranges/subset') +``` + +As a command-line utility: + +``` +$ semver -h + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, prerelease, or release. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-n <0|1> + This is the base to be used for the prerelease identifier. + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them. +``` + +## Versions + +A "version" is described by the `v2.0.0` specification found at +. + +A leading `"="` or `"v"` character is stripped off and ignored. +Support for stripping a leading "v" is kept for compatibility with `v1.0.0` of the SemVer +specification but should not be used anymore. + +## Ranges + +A `version range` is a set of `comparators` that specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. The comparator `>1` is equivalent to `>=2.0.0` and +would match the versions `2.0.0` and `3.1.0`, but not the versions +`1.0.1` or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. +Version `3.4.5` *would* satisfy the range because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose of this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range-matching +semantics. + +Second, a user who has opted into using a prerelease version has +indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +Note that this behavior can be suppressed (treating all prerelease +versions as if they were normal versions, for range-matching) +by setting the `includePrerelease` flag on the options +object to any +[functions](https://github.com/npm/node-semver#functions) that do +range matching. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta') +// '1.2.4-beta.0' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```bash +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +To get out of the prerelease phase, use the `release` option: + +```bash +$ semver 1.2.4-beta.1 -i release +1.2.4 +``` + +#### Prerelease Identifier Base + +The method `.inc` takes an optional parameter 'identifierBase' string +that will let you let your prerelease number as zero-based or one-based. +Set to `false` to omit the prerelease number altogether. +If you do not specify this parameter, it will default to zero-based. + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta', '1') +// '1.2.4-beta.1' +``` + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta', false) +// '1.2.4-beta' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta -n 1 +1.2.4-beta.1 +``` + +```bash +$ semver 1.2.3 -i prerelease --preid beta -n false +1.2.4-beta +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0-0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any non-prerelease version satisfies, unless + `includePrerelease` is specified, in which case any version at all + satisfies) +* `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0-0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero element in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0-0` +* `^0.2.3` := `>=0.2.3 <0.3.0-0` +* `^0.0.3` := `>=0.0.3 <0.0.4-0` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0-0` +* `^0.0.x` := `>=0.0.0 <0.1.0-0` +* `^0.0` := `>=0.0.0 <0.1.0-0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0-0` +* `^0.x` := `>=0.0.0 <1.0.0-0` + +### Range Grammar + +Putting all this together, here is a Backus-Naur grammar for ranges, +for the benefit of parser authors: + +```bnf +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +## Functions + +All methods and classes take a final `options` object argument. All +options in this object are `false` by default. The options supported +are: + +- `loose`: Be more forgiving about not-quite-valid semver strings. + (Any resulting output will always be 100% strict compliant, of + course.) For backwards compatibility reasons, if the `options` + argument is a boolean value instead of an object, it is interpreted + to be the `loose` param. +- `includePrerelease`: Set to suppress the [default + behavior](https://github.com/npm/node-semver#prerelease-tags) of + excluding prerelease tagged versions from ranges unless they are + explicitly opted into. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, releaseType, options, identifier, identifierBase)`: + Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, `prerelease`, or `release`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, `prerelease` will work the + same as `prepatch`. It increments the patch version and then makes a + prerelease. If the input version is already a prerelease it simply + increments it. + * `release` will remove any prerelease part of the version. + * `identifier` can be used to prefix `premajor`, `preminor`, + `prepatch`, or `prerelease` version increments. `identifierBase` + is the base to be used for the `prerelease` identifier. +* `prerelease(v)`: Returns an array of prerelease components, or null + if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. +* `intersects(r1, r2, loose)`: Return true if the two supplied ranges + or comparators intersect. +* `parse(v)`: Attempt to parse a string as a semantic version, returning either + a `SemVer` object or `null`. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of `compare`. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions + are equal. Sorts in ascending order if passed to `Array.sort()`. +* `compareLoose(v1, v2)`: Short for `compare(v1, v2, { loose: true })`. +* `diff(v1, v2)`: Returns the difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + +### Sorting + +* `sort(versions)`: Returns a sorted array of versions based on the `compareBuild` + function. +* `rsort(versions)`: The reverse of `sort`. Returns an array of versions based on + the `compareBuild` function in descending order. + +### Comparators + +* `intersects(comparator)`: Return true if the comparators intersect + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid. +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `minSatisfying(versions, range)`: Return the lowest version in the list + that satisfies the range, or `null` if none of them do. +* `minVersion(range)`: Return the lowest version that can match + the given range. +* `gtr(version, range)`: Return `true` if the version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if the version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) +* `intersects(range)`: Return true if any of the range comparators intersect. +* `simplifyRange(versions, range)`: Return a "simplified" range that + matches the same items in the `versions` list as the range specified. Note + that it does *not* guarantee that it would match the same versions in all + cases, only for the set of versions provided. This is useful when + generating ranges by joining together multiple versions with `||` + programmatically, to provide the user with something a bit more + ergonomic. If the provided range is shorter in string-length than the + generated range, then that is returned. +* `subset(subRange, superRange)`: Return `true` if the `subRange` range is + entirely contained by the `superRange` range. + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. + +### Coercion + +* `coerce(version, options)`: Coerces a string to semver if possible + +This aims to provide a very forgiving translation of a non-semver string to +semver. It looks for the first digit in a string and consumes all +remaining characters which satisfy at least a partial semver (e.g., `1`, +`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer +versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All +surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes +`3.4.0`). Only text which lacks digits will fail coercion (`version one` +is not valid). The maximum length for any semver component considered for +coercion is 16 characters; longer components will be ignored +(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any +semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value +components are invalid (`9999999999999999.4.7.4` is likely invalid). + +If the `options.rtl` flag is set, then `coerce` will return the right-most +coercible tuple that does not share an ending index with a longer coercible +tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not +`4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of +any other overlapping SemVer tuple. + +If the `options.includePrerelease` flag is set, then the `coerce` result will contain +prerelease and build parts of a version. For example, `1.2.3.4-rc.1+rev.2` +will preserve prerelease `rc.1` and build `rev.2` in the result. + +### Clean + +* `clean(version)`: Clean a string to be a valid semver if possible + +This will return a cleaned and trimmed semver version. If the provided +version is not valid a null will be returned. This does not work for +ranges. + +ex. +* `s.clean(' = v 2.1.5foo')`: `null` +* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean(' = v 2.1.5-foo')`: `null` +* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean('=v2.1.5')`: `'2.1.5'` +* `s.clean(' =v2.1.5')`: `'2.1.5'` +* `s.clean(' 2.1.5 ')`: `'2.1.5'` +* `s.clean('~1.0.0')`: `null` + +## Constants + +As a convenience, helper constants are exported to provide information about what `node-semver` supports: + +### `RELEASE_TYPES` + +- major +- premajor +- minor +- preminor +- patch +- prepatch +- prerelease + +``` +const semver = require('semver'); + +if (semver.RELEASE_TYPES.includes(arbitraryUserInput)) { + console.log('This is a valid release type!'); +} else { + console.warn('This is NOT a valid release type!'); +} +``` + +### `SEMVER_SPEC_VERSION` + +2.0.0 + +``` +const semver = require('semver'); + +console.log('We are currently using the semver specification version:', semver.SEMVER_SPEC_VERSION); +``` + +## Exported Modules + + + +You may pull in just the part of this semver utility that you need if you +are sensitive to packing and tree-shaking concerns. The main +`require('semver')` export uses getter functions to lazily load the parts +of the API that are used. + +The following modules are available: + +* `require('semver')` +* `require('semver/classes')` +* `require('semver/classes/comparator')` +* `require('semver/classes/range')` +* `require('semver/classes/semver')` +* `require('semver/functions/clean')` +* `require('semver/functions/cmp')` +* `require('semver/functions/coerce')` +* `require('semver/functions/compare')` +* `require('semver/functions/compare-build')` +* `require('semver/functions/compare-loose')` +* `require('semver/functions/diff')` +* `require('semver/functions/eq')` +* `require('semver/functions/gt')` +* `require('semver/functions/gte')` +* `require('semver/functions/inc')` +* `require('semver/functions/lt')` +* `require('semver/functions/lte')` +* `require('semver/functions/major')` +* `require('semver/functions/minor')` +* `require('semver/functions/neq')` +* `require('semver/functions/parse')` +* `require('semver/functions/patch')` +* `require('semver/functions/prerelease')` +* `require('semver/functions/rcompare')` +* `require('semver/functions/rsort')` +* `require('semver/functions/satisfies')` +* `require('semver/functions/sort')` +* `require('semver/functions/valid')` +* `require('semver/ranges/gtr')` +* `require('semver/ranges/intersects')` +* `require('semver/ranges/ltr')` +* `require('semver/ranges/max-satisfying')` +* `require('semver/ranges/min-satisfying')` +* `require('semver/ranges/min-version')` +* `require('semver/ranges/outside')` +* `require('semver/ranges/simplify')` +* `require('semver/ranges/subset')` +* `require('semver/ranges/to-comparators')` +* `require('semver/ranges/valid')` + diff --git a/node_modules/semver/bin/semver.js b/node_modules/semver/bin/semver.js new file mode 100755 index 0000000..dbb1bf5 --- /dev/null +++ b/node_modules/semver/bin/semver.js @@ -0,0 +1,191 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +'use strict' + +const argv = process.argv.slice(2) + +let versions = [] + +const range = [] + +let inc = null + +const version = require('../package.json').version + +let loose = false + +let includePrerelease = false + +let coerce = false + +let rtl = false + +let identifier + +let identifierBase + +const semver = require('../') +const parseOptions = require('../internal/parse-options') + +let reverse = false + +let options = {} + +const main = () => { + if (!argv.length) { + return help() + } + while (argv.length) { + let a = argv.shift() + const indexOfEqualSign = a.indexOf('=') + if (indexOfEqualSign !== -1) { + const value = a.slice(indexOfEqualSign + 1) + a = a.slice(0, indexOfEqualSign) + argv.unshift(value) + } + switch (a) { + case '-rv': case '-rev': case '--rev': case '--reverse': + reverse = true + break + case '-l': case '--loose': + loose = true + break + case '-p': case '--include-prerelease': + includePrerelease = true + break + case '-v': case '--version': + versions.push(argv.shift()) + break + case '-i': case '--inc': case '--increment': + switch (argv[0]) { + case 'major': case 'minor': case 'patch': case 'prerelease': + case 'premajor': case 'preminor': case 'prepatch': + case 'release': + inc = argv.shift() + break + default: + inc = 'patch' + break + } + break + case '--preid': + identifier = argv.shift() + break + case '-r': case '--range': + range.push(argv.shift()) + break + case '-n': + identifierBase = argv.shift() + if (identifierBase === 'false') { + identifierBase = false + } + break + case '-c': case '--coerce': + coerce = true + break + case '--rtl': + rtl = true + break + case '--ltr': + rtl = false + break + case '-h': case '--help': case '-?': + return help() + default: + versions.push(a) + break + } + } + + options = parseOptions({ loose, includePrerelease, rtl }) + + versions = versions.map((v) => { + return coerce ? (semver.coerce(v, options) || { version: v }).version : v + }).filter((v) => { + return semver.valid(v) + }) + if (!versions.length) { + return fail() + } + if (inc && (versions.length !== 1 || range.length)) { + return failInc() + } + + for (let i = 0, l = range.length; i < l; i++) { + versions = versions.filter((v) => { + return semver.satisfies(v, range[i], options) + }) + if (!versions.length) { + return fail() + } + } + versions + .sort((a, b) => semver[reverse ? 'rcompare' : 'compare'](a, b, options)) + .map(v => semver.clean(v, options)) + .map(v => inc ? semver.inc(v, inc, options, identifier, identifierBase) : v) + .forEach(v => console.log(v)) +} + +const failInc = () => { + console.error('--inc can only be used on a single version with no range') + fail() +} + +const fail = () => process.exit(1) + +const help = () => console.log( +`SemVer ${version} + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, prerelease, or release. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +-n + Base number to be used for the prerelease identifier. + Can be either 0 or 1, or false to omit the number altogether. + Defaults to 0. + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them.`) + +main() diff --git a/node_modules/semver/classes/comparator.js b/node_modules/semver/classes/comparator.js new file mode 100644 index 0000000..647c1f0 --- /dev/null +++ b/node_modules/semver/classes/comparator.js @@ -0,0 +1,143 @@ +'use strict' + +const ANY = Symbol('SemVer ANY') +// hoisted class for cyclic dependency +class Comparator { + static get ANY () { + return ANY + } + + constructor (comp, options) { + options = parseOptions(options) + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + comp = comp.trim().split(/\s+/).join(' ') + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) + } + + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + const m = comp.match(r) + + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) + } + + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } + } + + toString () { + return this.value + } + + test (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY || version === ANY) { + return true + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + return cmp(version, this.operator, this.semver, this.options) + } + + intersects (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range(this.value, options).test(comp.semver) + } + + options = parseOptions(options) + + // Special cases where nothing can possibly be lower + if (options.includePrerelease && + (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { + return false + } + if (!options.includePrerelease && + (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { + return false + } + + // Same direction increasing (> or >=) + if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { + return true + } + // Same direction decreasing (< or <=) + if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { + return true + } + // same SemVer and both sides are inclusive (<= or >=) + if ( + (this.semver.version === comp.semver.version) && + this.operator.includes('=') && comp.operator.includes('=')) { + return true + } + // opposite directions less than + if (cmp(this.semver, '<', comp.semver, options) && + this.operator.startsWith('>') && comp.operator.startsWith('<')) { + return true + } + // opposite directions greater than + if (cmp(this.semver, '>', comp.semver, options) && + this.operator.startsWith('<') && comp.operator.startsWith('>')) { + return true + } + return false + } +} + +module.exports = Comparator + +const parseOptions = require('../internal/parse-options') +const { safeRe: re, t } = require('../internal/re') +const cmp = require('../functions/cmp') +const debug = require('../internal/debug') +const SemVer = require('./semver') +const Range = require('./range') diff --git a/node_modules/semver/classes/index.js b/node_modules/semver/classes/index.js new file mode 100644 index 0000000..91c24ec --- /dev/null +++ b/node_modules/semver/classes/index.js @@ -0,0 +1,7 @@ +'use strict' + +module.exports = { + SemVer: require('./semver.js'), + Range: require('./range.js'), + Comparator: require('./comparator.js'), +} diff --git a/node_modules/semver/classes/range.js b/node_modules/semver/classes/range.js new file mode 100644 index 0000000..f80c235 --- /dev/null +++ b/node_modules/semver/classes/range.js @@ -0,0 +1,556 @@ +'use strict' + +const SPACE_CHARACTERS = /\s+/g + +// hoisted class for cyclic dependency +class Range { + constructor (range, options) { + options = parseOptions(options) + + if (range instanceof Range) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range(range.raw, options) + } + } + + if (range instanceof Comparator) { + // just put it in the set and return + this.raw = range.value + this.set = [[range]] + this.formatted = undefined + return this + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First reduce all whitespace as much as possible so we do not have to rely + // on potentially slow regexes like \s*. This is then stored and used for + // future error messages as well. + this.raw = range.trim().replace(SPACE_CHARACTERS, ' ') + + // First, split on || + this.set = this.raw + .split('||') + // map the range to a 2d array of comparators + .map(r => this.parseRange(r.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length) + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${this.raw}`) + } + + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0] + this.set = this.set.filter(c => !isNullSet(c[0])) + if (this.set.length === 0) { + this.set = [first] + } else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c] + break + } + } + } + } + + this.formatted = undefined + } + + get range () { + if (this.formatted === undefined) { + this.formatted = '' + for (let i = 0; i < this.set.length; i++) { + if (i > 0) { + this.formatted += '||' + } + const comps = this.set[i] + for (let k = 0; k < comps.length; k++) { + if (k > 0) { + this.formatted += ' ' + } + this.formatted += comps[k].toString().trim() + } + } + } + return this.formatted + } + + format () { + return this.range + } + + toString () { + return this.range + } + + parseRange (range) { + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = + (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | + (this.options.loose && FLAG_LOOSE) + const memoKey = memoOpts + ':' + range + const cached = cache.get(memoKey) + if (cached) { + return cached + } + + const loose = this.options.loose + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) + debug('hyphen replace', range) + + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[t.TILDETRIM], tildeTrimReplace) + debug('tilde trim', range) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[t.CARETTRIM], caretTrimReplace) + debug('caret trim', range) + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + let rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + + if (loose) { + // in loose mode, throw out any that are not valid comparators + rangeList = rangeList.filter(comp => { + debug('loose invalid filter', comp, this.options) + return !!comp.match(re[t.COMPARATORLOOSE]) + }) + } + debug('range list', rangeList) + + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + const rangeMap = new Map() + const comparators = rangeList.map(comp => new Comparator(comp, this.options)) + for (const comp of comparators) { + if (isNullSet(comp)) { + return [comp] + } + rangeMap.set(comp.value, comp) + } + if (rangeMap.size > 1 && rangeMap.has('')) { + rangeMap.delete('') + } + + const result = [...rangeMap.values()] + cache.set(memoKey, result) + return result + } + + intersects (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } + + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false + } +} + +module.exports = Range + +const LRU = require('../internal/lrucache') +const cache = new LRU() + +const parseOptions = require('../internal/parse-options') +const Comparator = require('./comparator') +const debug = require('../internal/debug') +const SemVer = require('./semver') +const { + safeRe: re, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace, +} = require('../internal/re') +const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants') + +const isNullSet = c => c.value === '<0.0.0-0' +const isAny = c => c.value === '' + +// take a set of comparators and determine whether there +// exists a version which can satisfy it +const isSatisfiable = (comparators, options) => { + let result = true + const remainingComparators = comparators.slice() + let testComparator = remainingComparators.pop() + + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }) + + testComparator = remainingComparators.pop() + } + + return result +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +const parseComparator = (comp, options) => { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} + +const isX = id => !id || id.toLowerCase() === 'x' || id === '*' + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 +// ~0.0.1 --> >=0.0.1 <0.1.0-0 +const replaceTildes = (comp, options) => { + return comp + .trim() + .split(/\s+/) + .map((c) => replaceTilde(c, options)) + .join(' ') +} + +const replaceTilde = (comp, options) => { + const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] + return comp.replace(r, (_, M, m, p, pr) => { + debug('tilde', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0` + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` + } else if (pr) { + debug('replaceTilde pr', pr) + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0` + } + + debug('tilde return', ret) + return ret + }) +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 +// ^1.2.3 --> >=1.2.3 <2.0.0-0 +// ^1.2.0 --> >=1.2.0 <2.0.0-0 +// ^0.0.1 --> >=0.0.1 <0.0.2-0 +// ^0.1.0 --> >=0.1.0 <0.2.0-0 +const replaceCarets = (comp, options) => { + return comp + .trim() + .split(/\s+/) + .map((c) => replaceCaret(c, options)) + .join(' ') +} + +const replaceCaret = (comp, options) => { + debug('caret', comp, options) + const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] + const z = options.includePrerelease ? '-0' : '' + return comp.replace(r, (_, M, m, p, pr) => { + debug('caret', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0` + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0` + } + } + + debug('caret return', ret) + return ret + }) +} + +const replaceXRanges = (comp, options) => { + debug('replaceXRanges', comp, options) + return comp + .split(/\s+/) + .map((c) => replaceXRange(c, options)) + .join(' ') +} + +const replaceXRange = (comp, options) => { + comp = comp.trim() + const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + const xM = isX(M) + const xm = xM || isX(m) + const xp = xm || isX(p) + const anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' + } + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : '' + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + + if (gtlt === '<') { + pr = '-0' + } + + ret = `${gtlt + M}.${m}.${p}${pr}` + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0` + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +const replaceStars = (comp, options) => { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp + .trim() + .replace(re[t.STAR], '') +} + +const replaceGTE0 = (comp, options) => { + debug('replaceGTE0', comp, options) + return comp + .trim() + .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') +} + +// This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0-0 +// TODO build? +const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr) => { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}` + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` + } else if (fpr) { + from = `>=${from}` + } else { + from = `>=${from}${incPr ? '-0' : ''}` + } + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0` + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0` + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}` + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0` + } else { + to = `<=${to}` + } + + return `${from} ${to}`.trim() +} + +const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === Comparator.ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true +} diff --git a/node_modules/semver/classes/semver.js b/node_modules/semver/classes/semver.js new file mode 100644 index 0000000..2efba0f --- /dev/null +++ b/node_modules/semver/classes/semver.js @@ -0,0 +1,319 @@ +'use strict' + +const debug = require('../internal/debug') +const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants') +const { safeRe: re, t } = require('../internal/re') + +const parseOptions = require('../internal/parse-options') +const { compareIdentifiers } = require('../internal/identifiers') +class SemVer { + constructor (version, options) { + options = parseOptions(options) + + if (version instanceof SemVer) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ) + } + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease + + const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) + } + + this.raw = version + + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() + } + + format () { + this.version = `${this.major}.${this.minor}.${this.patch}` + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}` + } + return this.version + } + + toString () { + return this.version + } + + compare (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer(other, this.options) + } + + if (other.version === this.version) { + return 0 + } + + return this.compareMain(other) || this.comparePre(other) + } + + compareMain (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } + + comparePre (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + let i = 0 + do { + const a = this.prerelease[i] + const b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + compareBuild (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + let i = 0 + do { + const a = this.build[i] + const b = other.build[i] + debug('build compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier, identifierBase) { + if (release.startsWith('pre')) { + if (!identifier && identifierBase === false) { + throw new Error('invalid increment argument: identifier is empty') + } + // Avoid an invalid semver results + if (identifier) { + const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]) + if (!match || match[1] !== identifier) { + throw new Error(`invalid identifier: ${identifier}`) + } + } + } + + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier, identifierBase) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier, identifierBase) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier, identifierBase) + this.inc('pre', identifier, identifierBase) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier, identifierBase) + } + this.inc('pre', identifier, identifierBase) + break + case 'release': + if (this.prerelease.length === 0) { + throw new Error(`version ${this.raw} is not a prerelease`) + } + this.prerelease.length = 0 + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': { + const base = Number(identifierBase) ? 1 : 0 + + if (this.prerelease.length === 0) { + this.prerelease = [base] + } else { + let i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + if (identifier === this.prerelease.join('.') && identifierBase === false) { + throw new Error('invalid increment argument: identifier already exists') + } + this.prerelease.push(base) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + let prerelease = [identifier, base] + if (identifierBase === false) { + prerelease = [identifier] + } + if (compareIdentifiers(this.prerelease[0], identifier) === 0) { + if (isNaN(this.prerelease[1])) { + this.prerelease = prerelease + } + } else { + this.prerelease = prerelease + } + } + break + } + default: + throw new Error(`invalid increment argument: ${release}`) + } + this.raw = this.format() + if (this.build.length) { + this.raw += `+${this.build.join('.')}` + } + return this + } +} + +module.exports = SemVer diff --git a/node_modules/semver/functions/clean.js b/node_modules/semver/functions/clean.js new file mode 100644 index 0000000..79703d6 --- /dev/null +++ b/node_modules/semver/functions/clean.js @@ -0,0 +1,8 @@ +'use strict' + +const parse = require('./parse') +const clean = (version, options) => { + const s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} +module.exports = clean diff --git a/node_modules/semver/functions/cmp.js b/node_modules/semver/functions/cmp.js new file mode 100644 index 0000000..77487dc --- /dev/null +++ b/node_modules/semver/functions/cmp.js @@ -0,0 +1,54 @@ +'use strict' + +const eq = require('./eq') +const neq = require('./neq') +const gt = require('./gt') +const gte = require('./gte') +const lt = require('./lt') +const lte = require('./lte') + +const cmp = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a === b + + case '!==': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } +} +module.exports = cmp diff --git a/node_modules/semver/functions/coerce.js b/node_modules/semver/functions/coerce.js new file mode 100644 index 0000000..cfe0275 --- /dev/null +++ b/node_modules/semver/functions/coerce.js @@ -0,0 +1,62 @@ +'use strict' + +const SemVer = require('../classes/semver') +const parse = require('./parse') +const { safeRe: re, t } = require('../internal/re') + +const coerce = (version, options) => { + if (version instanceof SemVer) { + return version + } + + if (typeof version === 'number') { + version = String(version) + } + + if (typeof version !== 'string') { + return null + } + + options = options || {} + + let match = null + if (!options.rtl) { + match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL] + let next + while ((next = coerceRtlRegex.exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next + } + coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length + } + // leave it in a clean state + coerceRtlRegex.lastIndex = -1 + } + + if (match === null) { + return null + } + + const major = match[2] + const minor = match[3] || '0' + const patch = match[4] || '0' + const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '' + const build = options.includePrerelease && match[6] ? `+${match[6]}` : '' + + return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) +} +module.exports = coerce diff --git a/node_modules/semver/functions/compare-build.js b/node_modules/semver/functions/compare-build.js new file mode 100644 index 0000000..99157cf --- /dev/null +++ b/node_modules/semver/functions/compare-build.js @@ -0,0 +1,9 @@ +'use strict' + +const SemVer = require('../classes/semver') +const compareBuild = (a, b, loose) => { + const versionA = new SemVer(a, loose) + const versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) +} +module.exports = compareBuild diff --git a/node_modules/semver/functions/compare-loose.js b/node_modules/semver/functions/compare-loose.js new file mode 100644 index 0000000..7531634 --- /dev/null +++ b/node_modules/semver/functions/compare-loose.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const compareLoose = (a, b) => compare(a, b, true) +module.exports = compareLoose diff --git a/node_modules/semver/functions/compare.js b/node_modules/semver/functions/compare.js new file mode 100644 index 0000000..63d8090 --- /dev/null +++ b/node_modules/semver/functions/compare.js @@ -0,0 +1,7 @@ +'use strict' + +const SemVer = require('../classes/semver') +const compare = (a, b, loose) => + new SemVer(a, loose).compare(new SemVer(b, loose)) + +module.exports = compare diff --git a/node_modules/semver/functions/diff.js b/node_modules/semver/functions/diff.js new file mode 100644 index 0000000..04e064e --- /dev/null +++ b/node_modules/semver/functions/diff.js @@ -0,0 +1,60 @@ +'use strict' + +const parse = require('./parse.js') + +const diff = (version1, version2) => { + const v1 = parse(version1, null, true) + const v2 = parse(version2, null, true) + const comparison = v1.compare(v2) + + if (comparison === 0) { + return null + } + + const v1Higher = comparison > 0 + const highVersion = v1Higher ? v1 : v2 + const lowVersion = v1Higher ? v2 : v1 + const highHasPre = !!highVersion.prerelease.length + const lowHasPre = !!lowVersion.prerelease.length + + if (lowHasPre && !highHasPre) { + // Going from prerelease -> no prerelease requires some special casing + + // If the low version has only a major, then it will always be a major + // Some examples: + // 1.0.0-1 -> 1.0.0 + // 1.0.0-1 -> 1.1.1 + // 1.0.0-1 -> 2.0.0 + if (!lowVersion.patch && !lowVersion.minor) { + return 'major' + } + + // If the main part has no difference + if (lowVersion.compareMain(highVersion) === 0) { + if (lowVersion.minor && !lowVersion.patch) { + return 'minor' + } + return 'patch' + } + } + + // add the `pre` prefix if we are going to a prerelease version + const prefix = highHasPre ? 'pre' : '' + + if (v1.major !== v2.major) { + return prefix + 'major' + } + + if (v1.minor !== v2.minor) { + return prefix + 'minor' + } + + if (v1.patch !== v2.patch) { + return prefix + 'patch' + } + + // high and low are preleases + return 'prerelease' +} + +module.exports = diff diff --git a/node_modules/semver/functions/eq.js b/node_modules/semver/functions/eq.js new file mode 100644 index 0000000..5f0eead --- /dev/null +++ b/node_modules/semver/functions/eq.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const eq = (a, b, loose) => compare(a, b, loose) === 0 +module.exports = eq diff --git a/node_modules/semver/functions/gt.js b/node_modules/semver/functions/gt.js new file mode 100644 index 0000000..84a57dd --- /dev/null +++ b/node_modules/semver/functions/gt.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const gt = (a, b, loose) => compare(a, b, loose) > 0 +module.exports = gt diff --git a/node_modules/semver/functions/gte.js b/node_modules/semver/functions/gte.js new file mode 100644 index 0000000..7c52bdf --- /dev/null +++ b/node_modules/semver/functions/gte.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const gte = (a, b, loose) => compare(a, b, loose) >= 0 +module.exports = gte diff --git a/node_modules/semver/functions/inc.js b/node_modules/semver/functions/inc.js new file mode 100644 index 0000000..ff999e9 --- /dev/null +++ b/node_modules/semver/functions/inc.js @@ -0,0 +1,21 @@ +'use strict' + +const SemVer = require('../classes/semver') + +const inc = (version, release, options, identifier, identifierBase) => { + if (typeof (options) === 'string') { + identifierBase = identifier + identifier = options + options = undefined + } + + try { + return new SemVer( + version instanceof SemVer ? version.version : version, + options + ).inc(release, identifier, identifierBase).version + } catch (er) { + return null + } +} +module.exports = inc diff --git a/node_modules/semver/functions/lt.js b/node_modules/semver/functions/lt.js new file mode 100644 index 0000000..2fb32a0 --- /dev/null +++ b/node_modules/semver/functions/lt.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const lt = (a, b, loose) => compare(a, b, loose) < 0 +module.exports = lt diff --git a/node_modules/semver/functions/lte.js b/node_modules/semver/functions/lte.js new file mode 100644 index 0000000..da9ee8f --- /dev/null +++ b/node_modules/semver/functions/lte.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const lte = (a, b, loose) => compare(a, b, loose) <= 0 +module.exports = lte diff --git a/node_modules/semver/functions/major.js b/node_modules/semver/functions/major.js new file mode 100644 index 0000000..e6d08dc --- /dev/null +++ b/node_modules/semver/functions/major.js @@ -0,0 +1,5 @@ +'use strict' + +const SemVer = require('../classes/semver') +const major = (a, loose) => new SemVer(a, loose).major +module.exports = major diff --git a/node_modules/semver/functions/minor.js b/node_modules/semver/functions/minor.js new file mode 100644 index 0000000..9e70ffd --- /dev/null +++ b/node_modules/semver/functions/minor.js @@ -0,0 +1,5 @@ +'use strict' + +const SemVer = require('../classes/semver') +const minor = (a, loose) => new SemVer(a, loose).minor +module.exports = minor diff --git a/node_modules/semver/functions/neq.js b/node_modules/semver/functions/neq.js new file mode 100644 index 0000000..84326b7 --- /dev/null +++ b/node_modules/semver/functions/neq.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const neq = (a, b, loose) => compare(a, b, loose) !== 0 +module.exports = neq diff --git a/node_modules/semver/functions/parse.js b/node_modules/semver/functions/parse.js new file mode 100644 index 0000000..d544d33 --- /dev/null +++ b/node_modules/semver/functions/parse.js @@ -0,0 +1,18 @@ +'use strict' + +const SemVer = require('../classes/semver') +const parse = (version, options, throwErrors = false) => { + if (version instanceof SemVer) { + return version + } + try { + return new SemVer(version, options) + } catch (er) { + if (!throwErrors) { + return null + } + throw er + } +} + +module.exports = parse diff --git a/node_modules/semver/functions/patch.js b/node_modules/semver/functions/patch.js new file mode 100644 index 0000000..7675162 --- /dev/null +++ b/node_modules/semver/functions/patch.js @@ -0,0 +1,5 @@ +'use strict' + +const SemVer = require('../classes/semver') +const patch = (a, loose) => new SemVer(a, loose).patch +module.exports = patch diff --git a/node_modules/semver/functions/prerelease.js b/node_modules/semver/functions/prerelease.js new file mode 100644 index 0000000..b8fe1db --- /dev/null +++ b/node_modules/semver/functions/prerelease.js @@ -0,0 +1,8 @@ +'use strict' + +const parse = require('./parse') +const prerelease = (version, options) => { + const parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} +module.exports = prerelease diff --git a/node_modules/semver/functions/rcompare.js b/node_modules/semver/functions/rcompare.js new file mode 100644 index 0000000..8e1c222 --- /dev/null +++ b/node_modules/semver/functions/rcompare.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const rcompare = (a, b, loose) => compare(b, a, loose) +module.exports = rcompare diff --git a/node_modules/semver/functions/rsort.js b/node_modules/semver/functions/rsort.js new file mode 100644 index 0000000..5d3d200 --- /dev/null +++ b/node_modules/semver/functions/rsort.js @@ -0,0 +1,5 @@ +'use strict' + +const compareBuild = require('./compare-build') +const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) +module.exports = rsort diff --git a/node_modules/semver/functions/satisfies.js b/node_modules/semver/functions/satisfies.js new file mode 100644 index 0000000..a0264a2 --- /dev/null +++ b/node_modules/semver/functions/satisfies.js @@ -0,0 +1,12 @@ +'use strict' + +const Range = require('../classes/range') +const satisfies = (version, range, options) => { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} +module.exports = satisfies diff --git a/node_modules/semver/functions/sort.js b/node_modules/semver/functions/sort.js new file mode 100644 index 0000000..edb24b1 --- /dev/null +++ b/node_modules/semver/functions/sort.js @@ -0,0 +1,5 @@ +'use strict' + +const compareBuild = require('./compare-build') +const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) +module.exports = sort diff --git a/node_modules/semver/functions/valid.js b/node_modules/semver/functions/valid.js new file mode 100644 index 0000000..0db67ed --- /dev/null +++ b/node_modules/semver/functions/valid.js @@ -0,0 +1,8 @@ +'use strict' + +const parse = require('./parse') +const valid = (version, options) => { + const v = parse(version, options) + return v ? v.version : null +} +module.exports = valid diff --git a/node_modules/semver/index.js b/node_modules/semver/index.js new file mode 100644 index 0000000..285662a --- /dev/null +++ b/node_modules/semver/index.js @@ -0,0 +1,91 @@ +'use strict' + +// just pre-load all the stuff that index.js lazily exports +const internalRe = require('./internal/re') +const constants = require('./internal/constants') +const SemVer = require('./classes/semver') +const identifiers = require('./internal/identifiers') +const parse = require('./functions/parse') +const valid = require('./functions/valid') +const clean = require('./functions/clean') +const inc = require('./functions/inc') +const diff = require('./functions/diff') +const major = require('./functions/major') +const minor = require('./functions/minor') +const patch = require('./functions/patch') +const prerelease = require('./functions/prerelease') +const compare = require('./functions/compare') +const rcompare = require('./functions/rcompare') +const compareLoose = require('./functions/compare-loose') +const compareBuild = require('./functions/compare-build') +const sort = require('./functions/sort') +const rsort = require('./functions/rsort') +const gt = require('./functions/gt') +const lt = require('./functions/lt') +const eq = require('./functions/eq') +const neq = require('./functions/neq') +const gte = require('./functions/gte') +const lte = require('./functions/lte') +const cmp = require('./functions/cmp') +const coerce = require('./functions/coerce') +const Comparator = require('./classes/comparator') +const Range = require('./classes/range') +const satisfies = require('./functions/satisfies') +const toComparators = require('./ranges/to-comparators') +const maxSatisfying = require('./ranges/max-satisfying') +const minSatisfying = require('./ranges/min-satisfying') +const minVersion = require('./ranges/min-version') +const validRange = require('./ranges/valid') +const outside = require('./ranges/outside') +const gtr = require('./ranges/gtr') +const ltr = require('./ranges/ltr') +const intersects = require('./ranges/intersects') +const simplifyRange = require('./ranges/simplify') +const subset = require('./ranges/subset') +module.exports = { + parse, + valid, + clean, + inc, + diff, + major, + minor, + patch, + prerelease, + compare, + rcompare, + compareLoose, + compareBuild, + sort, + rsort, + gt, + lt, + eq, + neq, + gte, + lte, + cmp, + coerce, + Comparator, + Range, + satisfies, + toComparators, + maxSatisfying, + minSatisfying, + minVersion, + validRange, + outside, + gtr, + ltr, + intersects, + simplifyRange, + subset, + SemVer, + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + RELEASE_TYPES: constants.RELEASE_TYPES, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, +} diff --git a/node_modules/semver/internal/constants.js b/node_modules/semver/internal/constants.js new file mode 100644 index 0000000..6d1db91 --- /dev/null +++ b/node_modules/semver/internal/constants.js @@ -0,0 +1,37 @@ +'use strict' + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +const SEMVER_SPEC_VERSION = '2.0.0' + +const MAX_LENGTH = 256 +const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || +/* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +const MAX_SAFE_COMPONENT_LENGTH = 16 + +// Max safe length for a build identifier. The max length minus 6 characters for +// the shortest version with a build 0.0.0+BUILD. +const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 + +const RELEASE_TYPES = [ + 'major', + 'premajor', + 'minor', + 'preminor', + 'patch', + 'prepatch', + 'prerelease', +] + +module.exports = { + MAX_LENGTH, + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_SAFE_INTEGER, + RELEASE_TYPES, + SEMVER_SPEC_VERSION, + FLAG_INCLUDE_PRERELEASE: 0b001, + FLAG_LOOSE: 0b010, +} diff --git a/node_modules/semver/internal/debug.js b/node_modules/semver/internal/debug.js new file mode 100644 index 0000000..20d1e9d --- /dev/null +++ b/node_modules/semver/internal/debug.js @@ -0,0 +1,11 @@ +'use strict' + +const debug = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) +) ? (...args) => console.error('SEMVER', ...args) + : () => {} + +module.exports = debug diff --git a/node_modules/semver/internal/identifiers.js b/node_modules/semver/internal/identifiers.js new file mode 100644 index 0000000..a4613de --- /dev/null +++ b/node_modules/semver/internal/identifiers.js @@ -0,0 +1,25 @@ +'use strict' + +const numeric = /^[0-9]+$/ +const compareIdentifiers = (a, b) => { + const anum = numeric.test(a) + const bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} + +const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) + +module.exports = { + compareIdentifiers, + rcompareIdentifiers, +} diff --git a/node_modules/semver/internal/lrucache.js b/node_modules/semver/internal/lrucache.js new file mode 100644 index 0000000..b8bf526 --- /dev/null +++ b/node_modules/semver/internal/lrucache.js @@ -0,0 +1,42 @@ +'use strict' + +class LRUCache { + constructor () { + this.max = 1000 + this.map = new Map() + } + + get (key) { + const value = this.map.get(key) + if (value === undefined) { + return undefined + } else { + // Remove the key from the map and add it to the end + this.map.delete(key) + this.map.set(key, value) + return value + } + } + + delete (key) { + return this.map.delete(key) + } + + set (key, value) { + const deleted = this.delete(key) + + if (!deleted && value !== undefined) { + // If cache is full, delete the least recently used item + if (this.map.size >= this.max) { + const firstKey = this.map.keys().next().value + this.delete(firstKey) + } + + this.map.set(key, value) + } + + return this + } +} + +module.exports = LRUCache diff --git a/node_modules/semver/internal/parse-options.js b/node_modules/semver/internal/parse-options.js new file mode 100644 index 0000000..5295454 --- /dev/null +++ b/node_modules/semver/internal/parse-options.js @@ -0,0 +1,17 @@ +'use strict' + +// parse out just the options we care about +const looseOption = Object.freeze({ loose: true }) +const emptyOpts = Object.freeze({ }) +const parseOptions = options => { + if (!options) { + return emptyOpts + } + + if (typeof options !== 'object') { + return looseOption + } + + return options +} +module.exports = parseOptions diff --git a/node_modules/semver/internal/re.js b/node_modules/semver/internal/re.js new file mode 100644 index 0000000..4758c58 --- /dev/null +++ b/node_modules/semver/internal/re.js @@ -0,0 +1,223 @@ +'use strict' + +const { + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_LENGTH, +} = require('./constants') +const debug = require('./debug') +exports = module.exports = {} + +// The actual regexps go on exports.re +const re = exports.re = [] +const safeRe = exports.safeRe = [] +const src = exports.src = [] +const safeSrc = exports.safeSrc = [] +const t = exports.t = {} +let R = 0 + +const LETTERDASHNUMBER = '[a-zA-Z0-9-]' + +// Replace some greedy regex tokens to prevent regex dos issues. These regex are +// used internally via the safeRe object since all inputs in this library get +// normalized first to trim and collapse all extra whitespace. The original +// regexes are exported for userland consumption and lower level usage. A +// future breaking change could export the safer regex only with a note that +// all input should have extra whitespace removed. +const safeRegexReplacements = [ + ['\\s', 1], + ['\\d', MAX_LENGTH], + [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], +] + +const makeSafeRegex = (value) => { + for (const [token, max] of safeRegexReplacements) { + value = value + .split(`${token}*`).join(`${token}{0,${max}}`) + .split(`${token}+`).join(`${token}{1,${max}}`) + } + return value +} + +const createToken = (name, value, isGlobal) => { + const safe = makeSafeRegex(value) + const index = R++ + debug(name, index, value) + t[name] = index + src[index] = value + safeSrc[index] = safe + re[index] = new RegExp(value, isGlobal ? 'g' : undefined) + safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) +} + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') +createToken('NUMERICIDENTIFIERLOOSE', '\\d+') + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) + +// ## Main Version +// Three dot-separated numeric identifiers. + +createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`) + +createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. +// Non-numberic identifiers include numberic identifiers but can be longer. +// Therefore non-numberic identifiers must go first. + +createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER] +}|${src[t.NUMERICIDENTIFIER]})`) + +createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER] +}|${src[t.NUMERICIDENTIFIERLOOSE]})`) + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) + +createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`) + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`) + +createToken('FULL', `^${src[t.FULLPLAIN]}$`) + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`) + +createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) + +createToken('GTLT', '((?:<|>)?=?)') + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) +createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) + +createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) +createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +createToken('COERCEPLAIN', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`) +createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`) +createToken('COERCEFULL', src[t.COERCEPLAIN] + + `(?:${src[t.PRERELEASE]})?` + + `(?:${src[t.BUILD]})?` + + `(?:$|[^\\d])`) +createToken('COERCERTL', src[t.COERCE], true) +createToken('COERCERTLFULL', src[t.COERCEFULL], true) + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +createToken('LONETILDE', '(?:~>?)') + +createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) +exports.tildeTrimReplace = '$1~' + +createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) +createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +createToken('LONECARET', '(?:\\^)') + +createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) +exports.caretTrimReplace = '$1^' + +createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) +createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) +createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) +exports.comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`) + +createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`) + +// Star ranges basically just allow anything at all. +createToken('STAR', '(<|>)?=?\\s*\\*') +// >=0.0.0 is like a star +createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') +createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') diff --git a/node_modules/semver/package.json b/node_modules/semver/package.json new file mode 100644 index 0000000..1fbef5a --- /dev/null +++ b/node_modules/semver/package.json @@ -0,0 +1,78 @@ +{ + "name": "semver", + "version": "7.7.2", + "description": "The semantic version parser used by npm.", + "main": "index.js", + "scripts": { + "test": "tap", + "snap": "tap", + "lint": "npm run eslint", + "postlint": "template-oss-check", + "lintfix": "npm run eslint -- --fix", + "posttest": "npm run lint", + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" + }, + "devDependencies": { + "@npmcli/eslint-config": "^5.0.0", + "@npmcli/template-oss": "4.24.3", + "benchmark": "^2.1.4", + "tap": "^16.0.0" + }, + "license": "ISC", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/node-semver.git" + }, + "bin": { + "semver": "bin/semver.js" + }, + "files": [ + "bin/", + "lib/", + "classes/", + "functions/", + "internal/", + "ranges/", + "index.js", + "preload.js", + "range.bnf" + ], + "tap": { + "timeout": 30, + "coverage-map": "map.js", + "nyc-arg": [ + "--exclude", + "tap-snapshots/**" + ] + }, + "engines": { + "node": ">=10" + }, + "author": "GitHub Inc.", + "templateOSS": { + "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", + "version": "4.24.3", + "engines": ">=10", + "distPaths": [ + "classes/", + "functions/", + "internal/", + "ranges/", + "index.js", + "preload.js", + "range.bnf" + ], + "allowPaths": [ + "/classes/", + "/functions/", + "/internal/", + "/ranges/", + "/index.js", + "/preload.js", + "/range.bnf", + "/benchmarks" + ], + "publish": "true" + } +} diff --git a/node_modules/semver/preload.js b/node_modules/semver/preload.js new file mode 100644 index 0000000..e6c47b9 --- /dev/null +++ b/node_modules/semver/preload.js @@ -0,0 +1,4 @@ +'use strict' + +// XXX remove in v8 or beyond +module.exports = require('./index.js') diff --git a/node_modules/semver/range.bnf b/node_modules/semver/range.bnf new file mode 100644 index 0000000..d4c6ae0 --- /dev/null +++ b/node_modules/semver/range.bnf @@ -0,0 +1,16 @@ +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | [1-9] ( [0-9] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ diff --git a/node_modules/semver/ranges/gtr.js b/node_modules/semver/ranges/gtr.js new file mode 100644 index 0000000..0e7601f --- /dev/null +++ b/node_modules/semver/ranges/gtr.js @@ -0,0 +1,6 @@ +'use strict' + +// Determine if version is greater than all the versions possible in the range. +const outside = require('./outside') +const gtr = (version, range, options) => outside(version, range, '>', options) +module.exports = gtr diff --git a/node_modules/semver/ranges/intersects.js b/node_modules/semver/ranges/intersects.js new file mode 100644 index 0000000..917be7e --- /dev/null +++ b/node_modules/semver/ranges/intersects.js @@ -0,0 +1,9 @@ +'use strict' + +const Range = require('../classes/range') +const intersects = (r1, r2, options) => { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2, options) +} +module.exports = intersects diff --git a/node_modules/semver/ranges/ltr.js b/node_modules/semver/ranges/ltr.js new file mode 100644 index 0000000..aa5e568 --- /dev/null +++ b/node_modules/semver/ranges/ltr.js @@ -0,0 +1,6 @@ +'use strict' + +const outside = require('./outside') +// Determine if version is less than all the versions possible in the range +const ltr = (version, range, options) => outside(version, range, '<', options) +module.exports = ltr diff --git a/node_modules/semver/ranges/max-satisfying.js b/node_modules/semver/ranges/max-satisfying.js new file mode 100644 index 0000000..01fe5ae --- /dev/null +++ b/node_modules/semver/ranges/max-satisfying.js @@ -0,0 +1,27 @@ +'use strict' + +const SemVer = require('../classes/semver') +const Range = require('../classes/range') + +const maxSatisfying = (versions, range, options) => { + let max = null + let maxSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} +module.exports = maxSatisfying diff --git a/node_modules/semver/ranges/min-satisfying.js b/node_modules/semver/ranges/min-satisfying.js new file mode 100644 index 0000000..af89c8e --- /dev/null +++ b/node_modules/semver/ranges/min-satisfying.js @@ -0,0 +1,26 @@ +'use strict' + +const SemVer = require('../classes/semver') +const Range = require('../classes/range') +const minSatisfying = (versions, range, options) => { + let min = null + let minSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} +module.exports = minSatisfying diff --git a/node_modules/semver/ranges/min-version.js b/node_modules/semver/ranges/min-version.js new file mode 100644 index 0000000..09a65aa --- /dev/null +++ b/node_modules/semver/ranges/min-version.js @@ -0,0 +1,63 @@ +'use strict' + +const SemVer = require('../classes/semver') +const Range = require('../classes/range') +const gt = require('../functions/gt') + +const minVersion = (range, loose) => { + range = new Range(range, loose) + + let minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } + + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + + minver = null + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let setMin = null + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt(compver, setMin)) { + setMin = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } + }) + if (setMin && (!minver || gt(minver, setMin))) { + minver = setMin + } + } + + if (minver && range.test(minver)) { + return minver + } + + return null +} +module.exports = minVersion diff --git a/node_modules/semver/ranges/outside.js b/node_modules/semver/ranges/outside.js new file mode 100644 index 0000000..ca74421 --- /dev/null +++ b/node_modules/semver/ranges/outside.js @@ -0,0 +1,82 @@ +'use strict' + +const SemVer = require('../classes/semver') +const Comparator = require('../classes/comparator') +const { ANY } = Comparator +const Range = require('../classes/range') +const satisfies = require('../functions/satisfies') +const gt = require('../functions/gt') +const lt = require('../functions/lt') +const lte = require('../functions/lte') +const gte = require('../functions/gte') + +const outside = (version, range, hilo, options) => { + version = new SemVer(version, options) + range = new Range(range, options) + + let gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisfies the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let high = null + let low = null + + comparators.forEach((comparator) => { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true +} + +module.exports = outside diff --git a/node_modules/semver/ranges/simplify.js b/node_modules/semver/ranges/simplify.js new file mode 100644 index 0000000..262732e --- /dev/null +++ b/node_modules/semver/ranges/simplify.js @@ -0,0 +1,49 @@ +'use strict' + +// given a set of versions and a range, create a "simplified" range +// that includes the same versions that the original range does +// If the original range is shorter than the simplified one, return that. +const satisfies = require('../functions/satisfies.js') +const compare = require('../functions/compare.js') +module.exports = (versions, range, options) => { + const set = [] + let first = null + let prev = null + const v = versions.sort((a, b) => compare(a, b, options)) + for (const version of v) { + const included = satisfies(version, range, options) + if (included) { + prev = version + if (!first) { + first = version + } + } else { + if (prev) { + set.push([first, prev]) + } + prev = null + first = null + } + } + if (first) { + set.push([first, null]) + } + + const ranges = [] + for (const [min, max] of set) { + if (min === max) { + ranges.push(min) + } else if (!max && min === v[0]) { + ranges.push('*') + } else if (!max) { + ranges.push(`>=${min}`) + } else if (min === v[0]) { + ranges.push(`<=${max}`) + } else { + ranges.push(`${min} - ${max}`) + } + } + const simplified = ranges.join(' || ') + const original = typeof range.raw === 'string' ? range.raw : String(range) + return simplified.length < original.length ? simplified : range +} diff --git a/node_modules/semver/ranges/subset.js b/node_modules/semver/ranges/subset.js new file mode 100644 index 0000000..2c49aef --- /dev/null +++ b/node_modules/semver/ranges/subset.js @@ -0,0 +1,249 @@ +'use strict' + +const Range = require('../classes/range.js') +const Comparator = require('../classes/comparator.js') +const { ANY } = Comparator +const satisfies = require('../functions/satisfies.js') +const compare = require('../functions/compare.js') + +// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: +// - Every simple range `r1, r2, ...` is a null set, OR +// - Every simple range `r1, r2, ...` which is not a null set is a subset of +// some `R1, R2, ...` +// +// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: +// - If c is only the ANY comparator +// - If C is only the ANY comparator, return true +// - Else if in prerelease mode, return false +// - else replace c with `[>=0.0.0]` +// - If C is only the ANY comparator +// - if in prerelease mode, return true +// - else replace C with `[>=0.0.0]` +// - Let EQ be the set of = comparators in c +// - If EQ is more than one, return true (null set) +// - Let GT be the highest > or >= comparator in c +// - Let LT be the lowest < or <= comparator in c +// - If GT and LT, and GT.semver > LT.semver, return true (null set) +// - If any C is a = range, and GT or LT are set, return false +// - If EQ +// - If GT, and EQ does not satisfy GT, return true (null set) +// - If LT, and EQ does not satisfy LT, return true (null set) +// - If EQ satisfies every C, return true +// - Else return false +// - If GT +// - If GT.semver is lower than any > or >= comp in C, return false +// - If GT is >=, and GT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the GT.semver tuple, return false +// - If LT +// - If LT.semver is greater than any < or <= comp in C, return false +// - If LT is <=, and LT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the LT.semver tuple, return false +// - Else return true + +const subset = (sub, dom, options = {}) => { + if (sub === dom) { + return true + } + + sub = new Range(sub, options) + dom = new Range(dom, options) + let sawNonNull = false + + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options) + sawNonNull = sawNonNull || isSub !== null + if (isSub) { + continue OUTER + } + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) { + return false + } + } + return true +} + +const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] +const minimumVersion = [new Comparator('>=0.0.0')] + +const simpleSubset = (sub, dom, options) => { + if (sub === dom) { + return true + } + + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) { + return true + } else if (options.includePrerelease) { + sub = minimumVersionWithPreRelease + } else { + sub = minimumVersion + } + } + + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) { + return true + } else { + dom = minimumVersion + } + } + + const eqSet = new Set() + let gt, lt + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') { + gt = higherGT(gt, c, options) + } else if (c.operator === '<' || c.operator === '<=') { + lt = lowerLT(lt, c, options) + } else { + eqSet.add(c.semver) + } + } + + if (eqSet.size > 1) { + return null + } + + let gtltComp + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options) + if (gtltComp > 0) { + return null + } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { + return null + } + } + + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) { + return null + } + + if (lt && !satisfies(eq, String(lt), options)) { + return null + } + + for (const c of dom) { + if (!satisfies(eq, String(c), options)) { + return false + } + } + + return true + } + + let higher, lower + let hasDomLT, hasDomGT + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options) + if (higher === c && higher !== gt) { + return false + } + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { + return false + } + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options) + if (lower === c && lower !== lt) { + return false + } + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { + return false + } + } + if (!c.operator && (lt || gt) && gtltComp !== 0) { + return false + } + } + + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) { + return false + } + + if (lt && hasDomGT && !gt && gtltComp !== 0) { + return false + } + + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) { + return false + } + + return true +} + +// >=1.2.3 is lower than >1.2.3 +const higherGT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a +} + +// <=1.2.3 is higher than <1.2.3 +const lowerLT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a +} + +module.exports = subset diff --git a/node_modules/semver/ranges/to-comparators.js b/node_modules/semver/ranges/to-comparators.js new file mode 100644 index 0000000..5be2519 --- /dev/null +++ b/node_modules/semver/ranges/to-comparators.js @@ -0,0 +1,10 @@ +'use strict' + +const Range = require('../classes/range') + +// Mostly just for testing and legacy API reasons +const toComparators = (range, options) => + new Range(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) + +module.exports = toComparators diff --git a/node_modules/semver/ranges/valid.js b/node_modules/semver/ranges/valid.js new file mode 100644 index 0000000..cc6b0e9 --- /dev/null +++ b/node_modules/semver/ranges/valid.js @@ -0,0 +1,13 @@ +'use strict' + +const Range = require('../classes/range') +const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} +module.exports = validRange diff --git a/node_modules/send/HISTORY.md b/node_modules/send/HISTORY.md new file mode 100644 index 0000000..958b934 --- /dev/null +++ b/node_modules/send/HISTORY.md @@ -0,0 +1,580 @@ +1.2.0 / 2025-03-27 +================== + + * deps: + * `mime-types@^3.0.1` + * `fresh@^2.0.0` + * removed `destroy` + * remove `getHeaderNames()` polyfill and refactor `clearHeaders()` + +1.1.0 / 2024-09-10 +================== + +* Changes from 0.19.0 + +1.0.0 / 2024-07-25 +================== + + * Drop support for Node.js <18.0 + * `statuses@^2.0.1` + * `range-parser@^1.2.1` + * `on-finished@^2.4.1` + * `ms@^2.1.3` + * `mime-types@^2.1.35` + * `http-errors@^2.0.0` + * `fresh@^0.5.2` + * `etag@^1.8.1` + * `escape-html@^1.0.3` + * `encodeurl@^2.0.0` + * `destroy@^1.2.0` + * `debug@^4.3.5` + +1.0.0-beta.2 / 2024-03-04 +========================= + + * Changes from 0.18.0 + +1.0.0-beta.1 / 2022-02-04 +========================= + + * Drop support for Node.js 0.8 + * Remove `hidden` option -- use `dotfiles` option + * Remove `from` alias to `root` -- use `root` directly + * Remove `send.etag()` -- use `etag` in `options` + * Remove `send.index()` -- use `index` in `options` + * Remove `send.maxage()` -- use `maxAge` in `options` + * Remove `send.root()` -- use `root` in `options` + * Use `mime-types` for file to content type mapping -- removed `send.mime` + * deps: debug@3.1.0 + - Add `DEBUG_HIDE_DATE` environment variable + - Change timer to per-namespace instead of global + - Change non-TTY date format + - Remove `DEBUG_FD` environment variable support + - Support 256 namespace colors + +0.19.0 / 2024-09-10 +=================== + +* Remove link renderization in html while redirecting + +0.18.0 / 2022-03-23 +=================== + + * Fix emitted 416 error missing headers property + * Limit the headers removed for 304 response + * deps: depd@2.0.0 + - Replace internal `eval` usage with `Function` constructor + - Use instance methods on `process` to check for listeners + * deps: destroy@1.2.0 + * deps: http-errors@2.0.0 + - deps: depd@2.0.0 + - deps: statuses@2.0.1 + * deps: on-finished@2.4.1 + * deps: statuses@2.0.1 + +0.17.2 / 2021-12-11 +=================== + + * pref: ignore empty http tokens + * deps: http-errors@1.8.1 + - deps: inherits@2.0.4 + - deps: toidentifier@1.0.1 + - deps: setprototypeof@1.2.0 + * deps: ms@2.1.3 + +0.17.1 / 2019-05-10 +=================== + + * Set stricter CSP header in redirect & error responses + * deps: range-parser@~1.2.1 + +0.17.0 / 2019-05-03 +=================== + + * deps: http-errors@~1.7.2 + - Set constructor name when possible + - Use `toidentifier` module to make class names + - deps: depd@~1.1.2 + - deps: setprototypeof@1.1.1 + - deps: statuses@'>= 1.5.0 < 2' + * deps: mime@1.6.0 + - Add extensions for JPEG-2000 images + - Add new `font/*` types from IANA + - Add WASM mapping + - Update `.bdoc` to `application/bdoc` + - Update `.bmp` to `image/bmp` + - Update `.m4a` to `audio/mp4` + - Update `.rtf` to `application/rtf` + - Update `.wav` to `audio/wav` + - Update `.xml` to `application/xml` + - Update generic extensions to `application/octet-stream`: + `.deb`, `.dll`, `.dmg`, `.exe`, `.iso`, `.msi` + - Use mime-score module to resolve extension conflicts + * deps: ms@2.1.1 + - Add `week`/`w` support + - Fix negative number handling + * deps: statuses@~1.5.0 + * perf: remove redundant `path.normalize` call + +0.16.2 / 2018-02-07 +=================== + + * Fix incorrect end tag in default error & redirects + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: statuses@~1.4.0 + +0.16.1 / 2017-09-29 +=================== + + * Fix regression in edge-case behavior for empty `path` + +0.16.0 / 2017-09-27 +=================== + + * Add `immutable` option + * Fix missing `` in default error & redirects + * Use instance methods on steam to check for listeners + * deps: mime@1.4.1 + - Add 70 new types for file extensions + - Set charset as "UTF-8" for .js and .json + * perf: improve path validation speed + +0.15.6 / 2017-09-22 +=================== + + * deps: debug@2.6.9 + * perf: improve `If-Match` token parsing + +0.15.5 / 2017-09-20 +=================== + + * deps: etag@~1.8.1 + - perf: replace regular expression with substring + * deps: fresh@0.5.2 + - Fix handling of modified headers with invalid dates + - perf: improve ETag match loop + - perf: improve `If-None-Match` token parsing + +0.15.4 / 2017-08-05 +=================== + + * deps: debug@2.6.8 + * deps: depd@~1.1.1 + - Remove unnecessary `Buffer` loading + * deps: http-errors@~1.6.2 + - deps: depd@1.1.1 + +0.15.3 / 2017-05-16 +=================== + + * deps: debug@2.6.7 + - deps: ms@2.0.0 + * deps: ms@2.0.0 + +0.15.2 / 2017-04-26 +=================== + + * deps: debug@2.6.4 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@0.7.3 + * deps: ms@1.0.0 + +0.15.1 / 2017-03-04 +=================== + + * Fix issue when `Date.parse` does not return `NaN` on invalid date + * Fix strict violation in broken environments + +0.15.0 / 2017-02-25 +=================== + + * Support `If-Match` and `If-Unmodified-Since` headers + * Add `res` and `path` arguments to `directory` event + * Remove usage of `res._headers` private field + - Improves compatibility with Node.js 8 nightly + * Send complete HTML document in redirect & error responses + * Set default CSP header in redirect & error responses + * Use `res.getHeaderNames()` when available + * Use `res.headersSent` when available + * deps: debug@2.6.1 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable set to `3` or higher + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + * deps: etag@~1.8.0 + * deps: fresh@0.5.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - perf: delay reading header values until needed + - perf: enable strict mode + - perf: hoist regular expressions + - perf: remove duplicate conditional + - perf: remove unnecessary boolean coercions + - perf: skip checking modified time if ETag check failed + - perf: skip parsing `If-None-Match` when no `ETag` header + - perf: use `Date.parse` instead of `new Date` + * deps: http-errors@~1.6.1 + - Make `message` property enumerable for `HttpError`s + - deps: setprototypeof@1.0.3 + +0.14.2 / 2017-01-23 +=================== + + * deps: http-errors@~1.5.1 + - deps: inherits@2.0.3 + - deps: setprototypeof@1.0.2 + - deps: statuses@'>= 1.3.1 < 2' + * deps: ms@0.7.2 + * deps: statuses@~1.3.1 + +0.14.1 / 2016-06-09 +=================== + + * Fix redirect error when `path` contains raw non-URL characters + * Fix redirect when `path` starts with multiple forward slashes + +0.14.0 / 2016-06-06 +=================== + + * Add `acceptRanges` option + * Add `cacheControl` option + * Attempt to combine multiple ranges into single range + * Correctly inherit from `Stream` class + * Fix `Content-Range` header in 416 responses when using `start`/`end` options + * Fix `Content-Range` header missing from default 416 responses + * Ignore non-byte `Range` headers + * deps: http-errors@~1.5.0 + - Add `HttpError` export, for `err instanceof createError.HttpError` + - Support new code `421 Misdirected Request` + - Use `setprototypeof` module to replace `__proto__` setting + - deps: inherits@2.0.1 + - deps: statuses@'>= 1.3.0 < 2' + - perf: enable strict mode + * deps: range-parser@~1.2.0 + - Fix incorrectly returning -1 when there is at least one valid range + - perf: remove internal function + * deps: statuses@~1.3.0 + - Add `421 Misdirected Request` + - perf: enable strict mode + * perf: remove argument reassignment + +0.13.2 / 2016-03-05 +=================== + + * Fix invalid `Content-Type` header when `send.mime.default_type` unset + +0.13.1 / 2016-01-16 +=================== + + * deps: depd@~1.1.0 + - Support web browser loading + - perf: enable strict mode + * deps: destroy@~1.0.4 + - perf: enable strict mode + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: range-parser@~1.0.3 + - perf: enable strict mode + +0.13.0 / 2015-06-16 +=================== + + * Allow Node.js HTTP server to set `Date` response header + * Fix incorrectly removing `Content-Location` on 304 response + * Improve the default redirect response headers + * Send appropriate headers on default error response + * Use `http-errors` for standard emitted errors + * Use `statuses` instead of `http` module for status messages + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Improve stat performance by removing hashing + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * perf: enable strict mode + * perf: remove unnecessary array allocations + +0.12.3 / 2015-05-13 +=================== + + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: etag@~1.6.0 + - Improve support for JXcore + - Support "fake" stats objects in environments without `fs` + * deps: ms@0.7.1 + - Prevent extraordinarily long inputs + * deps: on-finished@~2.2.1 + +0.12.2 / 2015-03-13 +=================== + + * Throw errors early for invalid `extensions` or `index` options + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + +0.12.1 / 2015-02-17 +=================== + + * Fix regression sending zero-length files + +0.12.0 / 2015-02-16 +=================== + + * Always read the stat size from the file + * Fix mutating passed-in `options` + * deps: mime@1.3.4 + +0.11.1 / 2015-01-20 +=================== + + * Fix `root` path disclosure + +0.11.0 / 2015-01-05 +=================== + + * deps: debug@~2.1.1 + * deps: etag@~1.5.1 + - deps: crc@3.2.1 + * deps: ms@0.7.0 + - Add `milliseconds` + - Add `msecs` + - Add `secs` + - Add `mins` + - Add `hrs` + - Add `yrs` + * deps: on-finished@~2.2.0 + +0.10.1 / 2014-10-22 +=================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + +0.10.0 / 2014-10-15 +=================== + + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: etag@~1.5.0 + - Improve string performance + - Slightly improve speed for weak ETags over 1KB + +0.9.3 / 2014-09-24 +================== + + * deps: etag@~1.4.0 + - Support "fake" stats objects + +0.9.2 / 2014-09-15 +================== + + * deps: depd@0.4.5 + * deps: etag@~1.3.1 + * deps: range-parser@~1.0.2 + +0.9.1 / 2014-09-07 +================== + + * deps: fresh@0.2.4 + +0.9.0 / 2014-09-07 +================== + + * Add `lastModified` option + * Use `etag` to generate `ETag` header + * deps: debug@~2.0.0 + +0.8.5 / 2014-09-04 +================== + + * Fix malicious path detection for empty string path + +0.8.4 / 2014-09-04 +================== + + * Fix a path traversal issue when using `root` + +0.8.3 / 2014-08-16 +================== + + * deps: destroy@1.0.3 + - renamed from dethroy + * deps: on-finished@2.1.0 + +0.8.2 / 2014-08-14 +================== + + * Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + * deps: dethroy@1.0.2 + +0.8.1 / 2014-08-05 +================== + + * Fix `extensions` behavior when file already has extension + +0.8.0 / 2014-08-05 +================== + + * Add `extensions` option + +0.7.4 / 2014-08-04 +================== + + * Fix serving index files without root dir + +0.7.3 / 2014-07-29 +================== + + * Fix incorrect 403 on Windows and Node.js 0.11 + +0.7.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + +0.7.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + +0.7.0 / 2014-07-20 +================== + + * Deprecate `hidden` option; use `dotfiles` option + * Add `dotfiles` option + * deps: debug@1.0.4 + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + +0.6.0 / 2014-07-11 +================== + + * Deprecate `from` option; use `root` option + * Deprecate `send.etag()` -- use `etag` in `options` + * Deprecate `send.hidden()` -- use `hidden` in `options` + * Deprecate `send.index()` -- use `index` in `options` + * Deprecate `send.maxage()` -- use `maxAge` in `options` + * Deprecate `send.root()` -- use `root` in `options` + * Cap `maxAge` value to 1 year + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + +0.5.0 / 2014-06-28 +================== + + * Accept string for `maxAge` (converted by `ms`) + * Add `headers` event + * Include link in default redirect response + * Use `EventEmitter.listenerCount` to count listeners + +0.4.3 / 2014-06-11 +================== + + * Do not throw un-catchable error on file open race condition + * Use `escape-html` for HTML escaping + * deps: debug@1.0.2 + - fix some debugging output colors on node.js 0.8 + * deps: finished@1.2.2 + * deps: fresh@0.2.2 + +0.4.2 / 2014-06-09 +================== + + * fix "event emitter leak" warnings + * deps: debug@1.0.1 + * deps: finished@1.2.1 + +0.4.1 / 2014-06-02 +================== + + * Send `max-age` in `Cache-Control` in correct format + +0.4.0 / 2014-05-27 +================== + + * Calculate ETag with md5 for reduced collisions + * Fix wrong behavior when index file matches directory + * Ignore stream errors after request ends + - Goodbye `EBADF, read` + * Skip directories in index file search + * deps: debug@0.8.1 + +0.3.0 / 2014-04-24 +================== + + * Fix sending files with dots without root set + * Coerce option types + * Accept API options in options object + * Set etags to "weak" + * Include file path in etag + * Make "Can't set headers after they are sent." catchable + * Send full entity-body for multi range requests + * Default directory access to 403 when index disabled + * Support multiple index paths + * Support "If-Range" header + * Control whether to generate etags + * deps: mime@1.2.11 + +0.2.0 / 2014-01-29 +================== + + * update range-parser and fresh + +0.1.4 / 2013-08-11 +================== + + * update fresh + +0.1.3 / 2013-07-08 +================== + + * Revert "Fix fd leak" + +0.1.2 / 2013-07-03 +================== + + * Fix fd leak + +0.1.0 / 2012-08-25 +================== + + * add options parameter to send() that is passed to fs.createReadStream() [kanongil] + +0.0.4 / 2012-08-16 +================== + + * allow custom "Accept-Ranges" definition + +0.0.3 / 2012-07-16 +================== + + * fix normalization of the root directory. Closes #3 + +0.0.2 / 2012-07-09 +================== + + * add passing of req explicitly for now (YUCK) + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/send/LICENSE b/node_modules/send/LICENSE new file mode 100644 index 0000000..b6ea1c1 --- /dev/null +++ b/node_modules/send/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk +Copyright (c) 2014-2022 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/send/README.md b/node_modules/send/README.md new file mode 100644 index 0000000..350fccd --- /dev/null +++ b/node_modules/send/README.md @@ -0,0 +1,317 @@ +# send + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![CI][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Send is a library for streaming files from the file system as a http response +supporting partial responses (Ranges), conditional-GET negotiation (If-Match, +If-Unmodified-Since, If-None-Match, If-Modified-Since), high test coverage, +and granular events which may be leveraged to take appropriate actions in your +application or framework. + +Looking to serve up entire folders mapped to URLs? Try [serve-static](https://www.npmjs.org/package/serve-static). + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +$ npm install send +``` + +## API + +```js +var send = require('send') +``` + +### send(req, path, [options]) + +Create a new `SendStream` for the given path to send to a `res`. The `req` is +the Node.js HTTP request and the `path` is a urlencoded path to send (urlencoded, +not the actual file-system path). + +#### Options + +##### acceptRanges + +Enable or disable accepting ranged requests, defaults to true. +Disabling this will not send `Accept-Ranges` and ignore the contents +of the `Range` request header. + +##### cacheControl + +Enable or disable setting `Cache-Control` response header, defaults to +true. Disabling this will ignore the `immutable` and `maxAge` options. + +##### dotfiles + +Set how "dotfiles" are treated when encountered. A dotfile is a file +or directory that begins with a dot ("."). Note this check is done on +the path itself without checking if the path actually exists on the +disk. If `root` is specified, only the dotfiles above the root are +checked (i.e. the root itself can be within a dotfile when set +to "deny"). + + - `'allow'` No special treatment for dotfiles. + - `'deny'` Send a 403 for any request for a dotfile. + - `'ignore'` Pretend like the dotfile does not exist and 404. + +The default value is _similar_ to `'ignore'`, with the exception that +this default will not ignore the files within a directory that begins +with a dot, for backward-compatibility. + +##### end + +Byte offset at which the stream ends, defaults to the length of the file +minus 1. The end is inclusive in the stream, meaning `end: 3` will include +the 4th byte in the stream. + +##### etag + +Enable or disable etag generation, defaults to true. + +##### extensions + +If a given file doesn't exist, try appending one of the given extensions, +in the given order. By default, this is disabled (set to `false`). An +example value that will serve extension-less HTML files: `['html', 'htm']`. +This is skipped if the requested file already has an extension. + +##### immutable + +Enable or disable the `immutable` directive in the `Cache-Control` response +header, defaults to `false`. If set to `true`, the `maxAge` option should +also be specified to enable caching. The `immutable` directive will prevent +supported clients from making conditional requests during the life of the +`maxAge` option to check if the file has changed. + +##### index + +By default send supports "index.html" files, to disable this +set `false` or to supply a new index pass a string or an array +in preferred order. + +##### lastModified + +Enable or disable `Last-Modified` header, defaults to true. Uses the file +system's last modified value. + +##### maxAge + +Provide a max-age in milliseconds for http caching, defaults to 0. +This can also be a string accepted by the +[ms](https://www.npmjs.org/package/ms#readme) module. + +##### root + +Serve files relative to `path`. + +##### start + +Byte offset at which the stream starts, defaults to 0. The start is inclusive, +meaning `start: 2` will include the 3rd byte in the stream. + +#### Events + +The `SendStream` is an event emitter and will emit the following events: + + - `error` an error occurred `(err)` + - `directory` a directory was requested `(res, path)` + - `file` a file was requested `(path, stat)` + - `headers` the headers are about to be set on a file `(res, path, stat)` + - `stream` file streaming has started `(stream)` + - `end` streaming has completed + +#### .pipe + +The `pipe` method is used to pipe the response into the Node.js HTTP response +object, typically `send(req, path, options).pipe(res)`. + +## Error-handling + +By default when no `error` listeners are present an automatic response will be +made, otherwise you have full control over the response, aka you may show a 5xx +page etc. + +## Caching + +It does _not_ perform internal caching, you should use a reverse proxy cache +such as Varnish for this, or those fancy things called CDNs. If your +application is small enough that it would benefit from single-node memory +caching, it's small enough that it does not need caching at all ;). + +## Debugging + +To enable `debug()` instrumentation output export __DEBUG__: + +``` +$ DEBUG=send node app +``` + +## Running tests + +``` +$ npm install +$ npm test +``` + +## Examples + +### Serve a specific file + +This simple example will send a specific file to all requests. + +```js +var http = require('http') +var send = require('send') + +var server = http.createServer(function onRequest (req, res) { + send(req, '/path/to/index.html') + .pipe(res) +}) + +server.listen(3000) +``` + +### Serve all files from a directory + +This simple example will just serve up all the files in a +given directory as the top-level. For example, a request +`GET /foo.txt` will send back `/www/public/foo.txt`. + +```js +var http = require('http') +var parseUrl = require('parseurl') +var send = require('send') + +var server = http.createServer(function onRequest (req, res) { + send(req, parseUrl(req).pathname, { root: '/www/public' }) + .pipe(res) +}) + +server.listen(3000) +``` + +### Custom file types + +```js +var extname = require('path').extname +var http = require('http') +var parseUrl = require('parseurl') +var send = require('send') + +var server = http.createServer(function onRequest (req, res) { + send(req, parseUrl(req).pathname, { root: '/www/public' }) + .on('headers', function (res, path) { + switch (extname(path)) { + case '.x-mt': + case '.x-mtt': + // custom type for these extensions + res.setHeader('Content-Type', 'application/x-my-type') + break + } + }) + .pipe(res) +}) + +server.listen(3000) +``` + +### Custom directory index view + +This is an example of serving up a structure of directories with a +custom function to render a listing of a directory. + +```js +var http = require('http') +var fs = require('fs') +var parseUrl = require('parseurl') +var send = require('send') + +// Transfer arbitrary files from within /www/example.com/public/* +// with a custom handler for directory listing +var server = http.createServer(function onRequest (req, res) { + send(req, parseUrl(req).pathname, { index: false, root: '/www/public' }) + .once('directory', directory) + .pipe(res) +}) + +server.listen(3000) + +// Custom directory handler +function directory (res, path) { + var stream = this + + // redirect to trailing slash for consistent url + if (!stream.hasTrailingSlash()) { + return stream.redirect(path) + } + + // get directory list + fs.readdir(path, function onReaddir (err, list) { + if (err) return stream.error(err) + + // render an index for the directory + res.setHeader('Content-Type', 'text/plain; charset=UTF-8') + res.end(list.join('\n') + '\n') + }) +} +``` + +### Serving from a root directory with custom error-handling + +```js +var http = require('http') +var parseUrl = require('parseurl') +var send = require('send') + +var server = http.createServer(function onRequest (req, res) { + // your custom error-handling logic: + function error (err) { + res.statusCode = err.status || 500 + res.end(err.message) + } + + // your custom headers + function headers (res, path, stat) { + // serve all files for download + res.setHeader('Content-Disposition', 'attachment') + } + + // your custom directory handling logic: + function redirect () { + res.statusCode = 301 + res.setHeader('Location', req.url + '/') + res.end('Redirecting to ' + req.url + '/') + } + + // transfer arbitrary files from within + // /www/example.com/public/* + send(req, parseUrl(req).pathname, { root: '/www/public' }) + .on('error', error) + .on('directory', redirect) + .on('headers', headers) + .pipe(res) +}) + +server.listen(3000) +``` + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/pillarjs/send/master +[coveralls-url]: https://coveralls.io/r/pillarjs/send?branch=master +[github-actions-ci-image]: https://badgen.net/github/checks/pillarjs/send/master?label=linux +[github-actions-ci-url]: https://github.com/pillarjs/send/actions/workflows/ci.yml +[node-image]: https://badgen.net/npm/node/send +[node-url]: https://nodejs.org/en/download/ +[npm-downloads-image]: https://badgen.net/npm/dm/send +[npm-url]: https://npmjs.org/package/send +[npm-version-image]: https://badgen.net/npm/v/send diff --git a/node_modules/send/index.js b/node_modules/send/index.js new file mode 100644 index 0000000..1655053 --- /dev/null +++ b/node_modules/send/index.js @@ -0,0 +1,997 @@ +/*! + * send + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var debug = require('debug')('send') +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') +var etag = require('etag') +var fresh = require('fresh') +var fs = require('fs') +var mime = require('mime-types') +var ms = require('ms') +var onFinished = require('on-finished') +var parseRange = require('range-parser') +var path = require('path') +var statuses = require('statuses') +var Stream = require('stream') +var util = require('util') + +/** + * Path function references. + * @private + */ + +var extname = path.extname +var join = path.join +var normalize = path.normalize +var resolve = path.resolve +var sep = path.sep + +/** + * Regular expression for identifying a bytes Range header. + * @private + */ + +var BYTES_RANGE_REGEXP = /^ *bytes=/ + +/** + * Maximum value allowed for the max age. + * @private + */ + +var MAX_MAXAGE = 60 * 60 * 24 * 365 * 1000 // 1 year + +/** + * Regular expression to match a path with a directory up component. + * @private + */ + +var UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/ + +/** + * Module exports. + * @public + */ + +module.exports = send + +/** + * Return a `SendStream` for `req` and `path`. + * + * @param {object} req + * @param {string} path + * @param {object} [options] + * @return {SendStream} + * @public + */ + +function send (req, path, options) { + return new SendStream(req, path, options) +} + +/** + * Initialize a `SendStream` with the given `path`. + * + * @param {Request} req + * @param {String} path + * @param {object} [options] + * @private + */ + +function SendStream (req, path, options) { + Stream.call(this) + + var opts = options || {} + + this.options = opts + this.path = path + this.req = req + + this._acceptRanges = opts.acceptRanges !== undefined + ? Boolean(opts.acceptRanges) + : true + + this._cacheControl = opts.cacheControl !== undefined + ? Boolean(opts.cacheControl) + : true + + this._etag = opts.etag !== undefined + ? Boolean(opts.etag) + : true + + this._dotfiles = opts.dotfiles !== undefined + ? opts.dotfiles + : 'ignore' + + if (this._dotfiles !== 'ignore' && this._dotfiles !== 'allow' && this._dotfiles !== 'deny') { + throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"') + } + + this._extensions = opts.extensions !== undefined + ? normalizeList(opts.extensions, 'extensions option') + : [] + + this._immutable = opts.immutable !== undefined + ? Boolean(opts.immutable) + : false + + this._index = opts.index !== undefined + ? normalizeList(opts.index, 'index option') + : ['index.html'] + + this._lastModified = opts.lastModified !== undefined + ? Boolean(opts.lastModified) + : true + + this._maxage = opts.maxAge || opts.maxage + this._maxage = typeof this._maxage === 'string' + ? ms(this._maxage) + : Number(this._maxage) + this._maxage = !isNaN(this._maxage) + ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE) + : 0 + + this._root = opts.root + ? resolve(opts.root) + : null +} + +/** + * Inherits from `Stream`. + */ + +util.inherits(SendStream, Stream) + +/** + * Emit error with `status`. + * + * @param {number} status + * @param {Error} [err] + * @private + */ + +SendStream.prototype.error = function error (status, err) { + // emit if listeners instead of responding + if (hasListeners(this, 'error')) { + return this.emit('error', createHttpError(status, err)) + } + + var res = this.res + var msg = statuses.message[status] || String(status) + var doc = createHtmlDocument('Error', escapeHtml(msg)) + + // clear existing headers + clearHeaders(res) + + // add error headers + if (err && err.headers) { + setHeaders(res, err.headers) + } + + // send basic response + res.statusCode = status + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(doc)) + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') + res.end(doc) +} + +/** + * Check if the pathname ends with "/". + * + * @return {boolean} + * @private + */ + +SendStream.prototype.hasTrailingSlash = function hasTrailingSlash () { + return this.path[this.path.length - 1] === '/' +} + +/** + * Check if this is a conditional GET request. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isConditionalGET = function isConditionalGET () { + return this.req.headers['if-match'] || + this.req.headers['if-unmodified-since'] || + this.req.headers['if-none-match'] || + this.req.headers['if-modified-since'] +} + +/** + * Check if the request preconditions failed. + * + * @return {boolean} + * @private + */ + +SendStream.prototype.isPreconditionFailure = function isPreconditionFailure () { + var req = this.req + var res = this.res + + // if-match + var match = req.headers['if-match'] + if (match) { + var etag = res.getHeader('ETag') + return !etag || (match !== '*' && parseTokenList(match).every(function (match) { + return match !== etag && match !== 'W/' + etag && 'W/' + match !== etag + })) + } + + // if-unmodified-since + var unmodifiedSince = parseHttpDate(req.headers['if-unmodified-since']) + if (!isNaN(unmodifiedSince)) { + var lastModified = parseHttpDate(res.getHeader('Last-Modified')) + return isNaN(lastModified) || lastModified > unmodifiedSince + } + + return false +} + +/** + * Strip various content header fields for a change in entity. + * + * @private + */ + +SendStream.prototype.removeContentHeaderFields = function removeContentHeaderFields () { + var res = this.res + + res.removeHeader('Content-Encoding') + res.removeHeader('Content-Language') + res.removeHeader('Content-Length') + res.removeHeader('Content-Range') + res.removeHeader('Content-Type') +} + +/** + * Respond with 304 not modified. + * + * @api private + */ + +SendStream.prototype.notModified = function notModified () { + var res = this.res + debug('not modified') + this.removeContentHeaderFields() + res.statusCode = 304 + res.end() +} + +/** + * Raise error that headers already sent. + * + * @api private + */ + +SendStream.prototype.headersAlreadySent = function headersAlreadySent () { + var err = new Error('Can\'t set headers after they are sent.') + debug('headers already sent') + this.error(500, err) +} + +/** + * Check if the request is cacheable, aka + * responded with 2xx or 304 (see RFC 2616 section 14.2{5,6}). + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isCachable = function isCachable () { + var statusCode = this.res.statusCode + return (statusCode >= 200 && statusCode < 300) || + statusCode === 304 +} + +/** + * Handle stat() error. + * + * @param {Error} error + * @private + */ + +SendStream.prototype.onStatError = function onStatError (error) { + switch (error.code) { + case 'ENAMETOOLONG': + case 'ENOENT': + case 'ENOTDIR': + this.error(404, error) + break + default: + this.error(500, error) + break + } +} + +/** + * Check if the cache is fresh. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isFresh = function isFresh () { + return fresh(this.req.headers, { + etag: this.res.getHeader('ETag'), + 'last-modified': this.res.getHeader('Last-Modified') + }) +} + +/** + * Check if the range is fresh. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isRangeFresh = function isRangeFresh () { + var ifRange = this.req.headers['if-range'] + + if (!ifRange) { + return true + } + + // if-range as etag + if (ifRange.indexOf('"') !== -1) { + var etag = this.res.getHeader('ETag') + return Boolean(etag && ifRange.indexOf(etag) !== -1) + } + + // if-range as modified date + var lastModified = this.res.getHeader('Last-Modified') + return parseHttpDate(lastModified) <= parseHttpDate(ifRange) +} + +/** + * Redirect to path. + * + * @param {string} path + * @private + */ + +SendStream.prototype.redirect = function redirect (path) { + var res = this.res + + if (hasListeners(this, 'directory')) { + this.emit('directory', res, path) + return + } + + if (this.hasTrailingSlash()) { + this.error(403) + return + } + + var loc = encodeUrl(collapseLeadingSlashes(this.path + '/')) + var doc = createHtmlDocument('Redirecting', 'Redirecting to ' + escapeHtml(loc)) + + // redirect + res.statusCode = 301 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(doc)) + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') + res.setHeader('Location', loc) + res.end(doc) +} + +/** + * Pipe to `res. + * + * @param {Stream} res + * @return {Stream} res + * @api public + */ + +SendStream.prototype.pipe = function pipe (res) { + // root path + var root = this._root + + // references + this.res = res + + // decode the path + var path = decode(this.path) + if (path === -1) { + this.error(400) + return res + } + + // null byte(s) + if (~path.indexOf('\0')) { + this.error(400) + return res + } + + var parts + if (root !== null) { + // normalize + if (path) { + path = normalize('.' + sep + path) + } + + // malicious path + if (UP_PATH_REGEXP.test(path)) { + debug('malicious path "%s"', path) + this.error(403) + return res + } + + // explode path parts + parts = path.split(sep) + + // join / normalize from optional root dir + path = normalize(join(root, path)) + } else { + // ".." is malicious without "root" + if (UP_PATH_REGEXP.test(path)) { + debug('malicious path "%s"', path) + this.error(403) + return res + } + + // explode path parts + parts = normalize(path).split(sep) + + // resolve the path + path = resolve(path) + } + + // dotfile handling + if (containsDotFile(parts)) { + debug('%s dotfile "%s"', this._dotfiles, path) + switch (this._dotfiles) { + case 'allow': + break + case 'deny': + this.error(403) + return res + case 'ignore': + default: + this.error(404) + return res + } + } + + // index file support + if (this._index.length && this.hasTrailingSlash()) { + this.sendIndex(path) + return res + } + + this.sendFile(path) + return res +} + +/** + * Transfer `path`. + * + * @param {String} path + * @api public + */ + +SendStream.prototype.send = function send (path, stat) { + var len = stat.size + var options = this.options + var opts = {} + var res = this.res + var req = this.req + var ranges = req.headers.range + var offset = options.start || 0 + + if (res.headersSent) { + // impossible to send now + this.headersAlreadySent() + return + } + + debug('pipe "%s"', path) + + // set header fields + this.setHeader(path, stat) + + // set content-type + this.type(path) + + // conditional GET support + if (this.isConditionalGET()) { + if (this.isPreconditionFailure()) { + this.error(412) + return + } + + if (this.isCachable() && this.isFresh()) { + this.notModified() + return + } + } + + // adjust len to start/end options + len = Math.max(0, len - offset) + if (options.end !== undefined) { + var bytes = options.end - offset + 1 + if (len > bytes) len = bytes + } + + // Range support + if (this._acceptRanges && BYTES_RANGE_REGEXP.test(ranges)) { + // parse + ranges = parseRange(len, ranges, { + combine: true + }) + + // If-Range support + if (!this.isRangeFresh()) { + debug('range stale') + ranges = -2 + } + + // unsatisfiable + if (ranges === -1) { + debug('range unsatisfiable') + + // Content-Range + res.setHeader('Content-Range', contentRange('bytes', len)) + + // 416 Requested Range Not Satisfiable + return this.error(416, { + headers: { 'Content-Range': res.getHeader('Content-Range') } + }) + } + + // valid (syntactically invalid/multiple ranges are treated as a regular response) + if (ranges !== -2 && ranges.length === 1) { + debug('range %j', ranges) + + // Content-Range + res.statusCode = 206 + res.setHeader('Content-Range', contentRange('bytes', len, ranges[0])) + + // adjust for requested range + offset += ranges[0].start + len = ranges[0].end - ranges[0].start + 1 + } + } + + // clone options + for (var prop in options) { + opts[prop] = options[prop] + } + + // set read options + opts.start = offset + opts.end = Math.max(offset, offset + len - 1) + + // content-length + res.setHeader('Content-Length', len) + + // HEAD support + if (req.method === 'HEAD') { + res.end() + return + } + + this.stream(path, opts) +} + +/** + * Transfer file for `path`. + * + * @param {String} path + * @api private + */ +SendStream.prototype.sendFile = function sendFile (path) { + var i = 0 + var self = this + + debug('stat "%s"', path) + fs.stat(path, function onstat (err, stat) { + var pathEndsWithSep = path[path.length - 1] === sep + if (err && err.code === 'ENOENT' && !extname(path) && !pathEndsWithSep) { + // not found, check extensions + return next(err) + } + if (err) return self.onStatError(err) + if (stat.isDirectory()) return self.redirect(path) + if (pathEndsWithSep) return self.error(404) + self.emit('file', path, stat) + self.send(path, stat) + }) + + function next (err) { + if (self._extensions.length <= i) { + return err + ? self.onStatError(err) + : self.error(404) + } + + var p = path + '.' + self._extensions[i++] + + debug('stat "%s"', p) + fs.stat(p, function (err, stat) { + if (err) return next(err) + if (stat.isDirectory()) return next() + self.emit('file', p, stat) + self.send(p, stat) + }) + } +} + +/** + * Transfer index for `path`. + * + * @param {String} path + * @api private + */ +SendStream.prototype.sendIndex = function sendIndex (path) { + var i = -1 + var self = this + + function next (err) { + if (++i >= self._index.length) { + if (err) return self.onStatError(err) + return self.error(404) + } + + var p = join(path, self._index[i]) + + debug('stat "%s"', p) + fs.stat(p, function (err, stat) { + if (err) return next(err) + if (stat.isDirectory()) return next() + self.emit('file', p, stat) + self.send(p, stat) + }) + } + + next() +} + +/** + * Stream `path` to the response. + * + * @param {String} path + * @param {Object} options + * @api private + */ + +SendStream.prototype.stream = function stream (path, options) { + var self = this + var res = this.res + + // pipe + var stream = fs.createReadStream(path, options) + this.emit('stream', stream) + stream.pipe(res) + + // cleanup + function cleanup () { + stream.destroy() + } + + // response finished, cleanup + onFinished(res, cleanup) + + // error handling + stream.on('error', function onerror (err) { + // clean up stream early + cleanup() + + // error + self.onStatError(err) + }) + + // end + stream.on('end', function onend () { + self.emit('end') + }) +} + +/** + * Set content-type based on `path` + * if it hasn't been explicitly set. + * + * @param {String} path + * @api private + */ + +SendStream.prototype.type = function type (path) { + var res = this.res + + if (res.getHeader('Content-Type')) return + + var ext = extname(path) + var type = mime.contentType(ext) || 'application/octet-stream' + + debug('content-type %s', type) + res.setHeader('Content-Type', type) +} + +/** + * Set response header fields, most + * fields may be pre-defined. + * + * @param {String} path + * @param {Object} stat + * @api private + */ + +SendStream.prototype.setHeader = function setHeader (path, stat) { + var res = this.res + + this.emit('headers', res, path, stat) + + if (this._acceptRanges && !res.getHeader('Accept-Ranges')) { + debug('accept ranges') + res.setHeader('Accept-Ranges', 'bytes') + } + + if (this._cacheControl && !res.getHeader('Cache-Control')) { + var cacheControl = 'public, max-age=' + Math.floor(this._maxage / 1000) + + if (this._immutable) { + cacheControl += ', immutable' + } + + debug('cache-control %s', cacheControl) + res.setHeader('Cache-Control', cacheControl) + } + + if (this._lastModified && !res.getHeader('Last-Modified')) { + var modified = stat.mtime.toUTCString() + debug('modified %s', modified) + res.setHeader('Last-Modified', modified) + } + + if (this._etag && !res.getHeader('ETag')) { + var val = etag(stat) + debug('etag %s', val) + res.setHeader('ETag', val) + } +} + +/** + * Clear all headers from a response. + * + * @param {object} res + * @private + */ + +function clearHeaders (res) { + for (const header of res.getHeaderNames()) { + res.removeHeader(header) + } +} + +/** + * Collapse all leading slashes into a single slash + * + * @param {string} str + * @private + */ +function collapseLeadingSlashes (str) { + for (var i = 0; i < str.length; i++) { + if (str[i] !== '/') { + break + } + } + + return i > 1 + ? '/' + str.substr(i) + : str +} + +/** + * Determine if path parts contain a dotfile. + * + * @api private + */ + +function containsDotFile (parts) { + for (var i = 0; i < parts.length; i++) { + var part = parts[i] + if (part.length > 1 && part[0] === '.') { + return true + } + } + + return false +} + +/** + * Create a Content-Range header. + * + * @param {string} type + * @param {number} size + * @param {array} [range] + */ + +function contentRange (type, size, range) { + return type + ' ' + (range ? range.start + '-' + range.end : '*') + '/' + size +} + +/** + * Create a minimal HTML document. + * + * @param {string} title + * @param {string} body + * @private + */ + +function createHtmlDocument (title, body) { + return '\n' + + '\n' + + '\n' + + '\n' + + '' + title + '\n' + + '\n' + + '\n' + + '
' + body + '
\n' + + '\n' + + '\n' +} + +/** + * Create a HttpError object from simple arguments. + * + * @param {number} status + * @param {Error|object} err + * @private + */ + +function createHttpError (status, err) { + if (!err) { + return createError(status) + } + + return err instanceof Error + ? createError(status, err, { expose: false }) + : createError(status, err) +} + +/** + * decodeURIComponent. + * + * Allows V8 to only deoptimize this fn instead of all + * of send(). + * + * @param {String} path + * @api private + */ + +function decode (path) { + try { + return decodeURIComponent(path) + } catch (err) { + return -1 + } +} + +/** + * Determine if emitter has listeners of a given type. + * + * The way to do this check is done three different ways in Node.js >= 0.10 + * so this consolidates them into a minimal set using instance methods. + * + * @param {EventEmitter} emitter + * @param {string} type + * @returns {boolean} + * @private + */ + +function hasListeners (emitter, type) { + var count = typeof emitter.listenerCount !== 'function' + ? emitter.listeners(type).length + : emitter.listenerCount(type) + + return count > 0 +} + +/** + * Normalize the index option into an array. + * + * @param {boolean|string|array} val + * @param {string} name + * @private + */ + +function normalizeList (val, name) { + var list = [].concat(val || []) + + for (var i = 0; i < list.length; i++) { + if (typeof list[i] !== 'string') { + throw new TypeError(name + ' must be array of strings or false') + } + } + + return list +} + +/** + * Parse an HTTP Date into a number. + * + * @param {string} date + * @private + */ + +function parseHttpDate (date) { + var timestamp = date && Date.parse(date) + + return typeof timestamp === 'number' + ? timestamp + : NaN +} + +/** + * Parse a HTTP token list. + * + * @param {string} str + * @private + */ + +function parseTokenList (str) { + var end = 0 + var list = [] + var start = 0 + + // gather tokens + for (var i = 0, len = str.length; i < len; i++) { + switch (str.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1 + } + break + case 0x2c: /* , */ + if (start !== end) { + list.push(str.substring(start, end)) + } + start = end = i + 1 + break + default: + end = i + 1 + break + } + } + + // final token + if (start !== end) { + list.push(str.substring(start, end)) + } + + return list +} + +/** + * Set an object of headers on a response. + * + * @param {object} res + * @param {object} headers + * @private + */ + +function setHeaders (res, headers) { + var keys = Object.keys(headers) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + res.setHeader(key, headers[key]) + } +} diff --git a/node_modules/send/package.json b/node_modules/send/package.json new file mode 100644 index 0000000..d6a969a --- /dev/null +++ b/node_modules/send/package.json @@ -0,0 +1,60 @@ +{ + "name": "send", + "description": "Better streaming static file server with Range and conditional-GET support", + "version": "1.2.0", + "author": "TJ Holowaychuk ", + "contributors": [ + "Douglas Christopher Wilson ", + "James Wyatt Cready ", + "Jesús Leganés Combarro " + ], + "license": "MIT", + "repository": "pillarjs/send", + "keywords": [ + "static", + "file", + "server" + ], + "dependencies": { + "debug": "^4.3.5", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "mime-types": "^3.0.1", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.1" + }, + "devDependencies": { + "after": "^0.8.2", + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "^10.7.0", + "nyc": "^17.0.0", + "supertest": "6.2.2" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 18" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --check-leaks --reporter spec", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/serve-static/HISTORY.md b/node_modules/serve-static/HISTORY.md new file mode 100644 index 0000000..a3f174e --- /dev/null +++ b/node_modules/serve-static/HISTORY.md @@ -0,0 +1,516 @@ +2.2.0 / 2025-03-27 +================== + +* deps: send@^1.2.0 + +2.1.0 / 2024-09-10 +=================== + +* Changes from 1.16.0 +* deps: send@^1.2.0 + +2.0.0 / 2024-08-23 +================== + +* deps: + * parseurl@^1.3.3 + * excape-html@^1.0.3 + * encodeurl@^2.0.0 + * supertest@^6.3.4 + * safe-buffer@^5.2.1 + * nyc@^17.0.0 + * mocha@^10.7.0 +* Changes from 1.x + +2.0.0-beta.2 / 2024-03-20 +========================= + + * deps: send@1.0.0-beta.2 + +2.0.0-beta.1 / 2022-02-05 +========================= + + * Change `dotfiles` option default to `'ignore'` + * Drop support for Node.js 0.8 + * Remove `hidden` option; use `dotfiles` option instead + * Remove `mime` export; use `mime-types` package instead + * deps: send@1.0.0-beta.1 + - Use `mime-types` for file to content type mapping + - deps: debug@3.1.0 + +1.16.0 / 2024-09-10 +=================== + +* Remove link renderization in html while redirecting + +1.15.0 / 2022-03-24 +=================== + + * deps: send@0.18.0 + - Fix emitted 416 error missing headers property + - Limit the headers removed for 304 response + - deps: depd@2.0.0 + - deps: destroy@1.2.0 + - deps: http-errors@2.0.0 + - deps: on-finished@2.4.1 + - deps: statuses@2.0.1 + +1.14.2 / 2021-12-15 +=================== + + * deps: send@0.17.2 + - deps: http-errors@1.8.1 + - deps: ms@2.1.3 + - pref: ignore empty http tokens + +1.14.1 / 2019-05-10 +=================== + + * Set stricter CSP header in redirect response + * deps: send@0.17.1 + - deps: range-parser@~1.2.1 + +1.14.0 / 2019-05-07 +=================== + + * deps: parseurl@~1.3.3 + * deps: send@0.17.0 + - deps: http-errors@~1.7.2 + - deps: mime@1.6.0 + - deps: ms@2.1.1 + - deps: statuses@~1.5.0 + - perf: remove redundant `path.normalize` call + +1.13.2 / 2018-02-07 +=================== + + * Fix incorrect end tag in redirects + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: send@0.16.2 + - deps: depd@~1.1.2 + - deps: encodeurl@~1.0.2 + - deps: statuses@~1.4.0 + +1.13.1 / 2017-09-29 +=================== + + * Fix regression when `root` is incorrectly set to a file + * deps: send@0.16.1 + +1.13.0 / 2017-09-27 +=================== + + * deps: send@0.16.0 + - Add 70 new types for file extensions + - Add `immutable` option + - Fix missing `` in default error & redirects + - Set charset as "UTF-8" for .js and .json + - Use instance methods on steam to check for listeners + - deps: mime@1.4.1 + - perf: improve path validation speed + +1.12.6 / 2017-09-22 +=================== + + * deps: send@0.15.6 + - deps: debug@2.6.9 + - perf: improve `If-Match` token parsing + * perf: improve slash collapsing + +1.12.5 / 2017-09-21 +=================== + + * deps: parseurl@~1.3.2 + - perf: reduce overhead for full URLs + - perf: unroll the "fast-path" `RegExp` + * deps: send@0.15.5 + - Fix handling of modified headers with invalid dates + - deps: etag@~1.8.1 + - deps: fresh@0.5.2 + +1.12.4 / 2017-08-05 +=================== + + * deps: send@0.15.4 + - deps: debug@2.6.8 + - deps: depd@~1.1.1 + - deps: http-errors@~1.6.2 + +1.12.3 / 2017-05-16 +=================== + + * deps: send@0.15.3 + - deps: debug@2.6.7 + +1.12.2 / 2017-04-26 +=================== + + * deps: send@0.15.2 + - deps: debug@2.6.4 + +1.12.1 / 2017-03-04 +=================== + + * deps: send@0.15.1 + - Fix issue when `Date.parse` does not return `NaN` on invalid date + - Fix strict violation in broken environments + +1.12.0 / 2017-02-25 +=================== + + * Send complete HTML document in redirect response + * Set default CSP header in redirect response + * deps: send@0.15.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - Remove usage of `res._headers` private field + - Support `If-Match` and `If-Unmodified-Since` headers + - Use `res.getHeaderNames()` when available + - Use `res.headersSent` when available + - deps: debug@2.6.1 + - deps: etag@~1.8.0 + - deps: fresh@0.5.0 + - deps: http-errors@~1.6.1 + +1.11.2 / 2017-01-23 +=================== + + * deps: send@0.14.2 + - deps: http-errors@~1.5.1 + - deps: ms@0.7.2 + - deps: statuses@~1.3.1 + +1.11.1 / 2016-06-10 +=================== + + * Fix redirect error when `req.url` contains raw non-URL characters + * deps: send@0.14.1 + +1.11.0 / 2016-06-07 +=================== + + * Use status code 301 for redirects + * deps: send@0.14.0 + - Add `acceptRanges` option + - Add `cacheControl` option + - Attempt to combine multiple ranges into single range + - Correctly inherit from `Stream` class + - Fix `Content-Range` header in 416 responses when using `start`/`end` options + - Fix `Content-Range` header missing from default 416 responses + - Ignore non-byte `Range` headers + - deps: http-errors@~1.5.0 + - deps: range-parser@~1.2.0 + - deps: statuses@~1.3.0 + - perf: remove argument reassignment + +1.10.3 / 2016-05-30 +=================== + + * deps: send@0.13.2 + - Fix invalid `Content-Type` header when `send.mime.default_type` unset + +1.10.2 / 2016-01-19 +=================== + + * deps: parseurl@~1.3.1 + - perf: enable strict mode + +1.10.1 / 2016-01-16 +=================== + + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: send@0.13.1 + - deps: depd@~1.1.0 + - deps: destroy@~1.0.4 + - deps: escape-html@~1.0.3 + - deps: range-parser@~1.0.3 + +1.10.0 / 2015-06-17 +=================== + + * Add `fallthrough` option + - Allows declaring this middleware is the final destination + - Provides better integration with Express patterns + * Fix reading options from options prototype + * Improve the default redirect response headers + * deps: escape-html@1.0.2 + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + * perf: enable strict mode + * perf: remove argument reassignment + +1.9.3 / 2015-05-14 +================== + + * deps: send@0.12.3 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: etag@~1.6.0 + - deps: ms@0.7.1 + - deps: on-finished@~2.2.1 + +1.9.2 / 2015-03-14 +================== + + * deps: send@0.12.2 + - Throw errors early for invalid `extensions` or `index` options + - deps: debug@~2.1.3 + +1.9.1 / 2015-02-17 +================== + + * deps: send@0.12.1 + - Fix regression sending zero-length files + +1.9.0 / 2015-02-16 +================== + + * deps: send@0.12.0 + - Always read the stat size from the file + - Fix mutating passed-in `options` + - deps: mime@1.3.4 + +1.8.1 / 2015-01-20 +================== + + * Fix redirect loop in Node.js 0.11.14 + * deps: send@0.11.1 + - Fix root path disclosure + +1.8.0 / 2015-01-05 +================== + + * deps: send@0.11.0 + - deps: debug@~2.1.1 + - deps: etag@~1.5.1 + - deps: ms@0.7.0 + - deps: on-finished@~2.2.0 + +1.7.2 / 2015-01-02 +================== + + * Fix potential open redirect when mounted at root + +1.7.1 / 2014-10-22 +================== + + * deps: send@0.10.1 + - deps: on-finished@~2.1.1 + +1.7.0 / 2014-10-15 +================== + + * deps: send@0.10.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + +1.6.5 / 2015-02-04 +================== + + * Fix potential open redirect when mounted at root + - Back-ported from v1.7.2 + +1.6.4 / 2014-10-08 +================== + + * Fix redirect loop when index file serving disabled + +1.6.3 / 2014-09-24 +================== + + * deps: send@0.9.3 + - deps: etag@~1.4.0 + +1.6.2 / 2014-09-15 +================== + + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + +1.6.1 / 2014-09-07 +================== + + * deps: send@0.9.1 + - deps: fresh@0.2.4 + +1.6.0 / 2014-09-07 +================== + + * deps: send@0.9.0 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + +1.5.4 / 2014-09-04 +================== + + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + +1.5.3 / 2014-08-17 +================== + + * deps: send@0.8.3 + +1.5.2 / 2014-08-14 +================== + + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + +1.5.1 / 2014-08-09 +================== + + * Fix parsing of weird `req.originalUrl` values + * deps: parseurl@~1.3.0 + * deps: utils-merge@1.0.0 + +1.5.0 / 2014-08-05 +================== + + * deps: send@0.8.1 + - Add `extensions` option + +1.4.4 / 2014-08-04 +================== + + * deps: send@0.7.4 + - Fix serving index files without root dir + +1.4.3 / 2014-07-29 +================== + + * deps: send@0.7.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + +1.4.2 / 2014-07-27 +================== + + * deps: send@0.7.2 + - deps: depd@0.4.4 + +1.4.1 / 2014-07-26 +================== + + * deps: send@0.7.1 + - deps: depd@0.4.3 + +1.4.0 / 2014-07-21 +================== + + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - deps: debug@1.0.4 + - deps: depd@0.4.2 + +1.3.2 / 2014-07-11 +================== + + * deps: send@0.6.0 + - Cap `maxAge` value to 1 year + - deps: debug@1.0.3 + +1.3.1 / 2014-07-09 +================== + + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + +1.3.0 / 2014-06-28 +================== + + * Add `setHeaders` option + * Include HTML link in redirect response + * deps: send@0.5.0 + - Accept string for `maxAge` (converted by `ms`) + +1.2.3 / 2014-06-11 +================== + + * deps: send@0.4.3 + - Do not throw un-catchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + +1.2.2 / 2014-06-09 +================== + + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: debug@1.0.1 + - deps: finished@1.2.1 + +1.2.1 / 2014-06-02 +================== + + * use `escape-html` for escaping + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + +1.2.0 / 2014-05-29 +================== + + * deps: send@0.4.0 + - Calculate ETag with md5 for reduced collisions + - Fix wrong behavior when index file matches directory + - Ignore stream errors after request ends + - Skip directories in index file search + - deps: debug@0.8.1 + +1.1.0 / 2014-04-24 +================== + + * Accept options directly to `send` module + * deps: send@0.3.0 + +1.0.4 / 2014-04-07 +================== + + * Resolve relative paths at middleware setup + * Use parseurl to parse the URL from request + +1.0.3 / 2014-03-20 +================== + + * Do not rely on connect-like environments + +1.0.2 / 2014-03-06 +================== + + * deps: send@0.2.0 + +1.0.1 / 2014-03-05 +================== + + * Add mime export for back-compat + +1.0.0 / 2014-03-05 +================== + + * Genesis from `connect` diff --git a/node_modules/serve-static/LICENSE b/node_modules/serve-static/LICENSE new file mode 100644 index 0000000..cbe62e8 --- /dev/null +++ b/node_modules/serve-static/LICENSE @@ -0,0 +1,25 @@ +(The MIT License) + +Copyright (c) 2010 Sencha Inc. +Copyright (c) 2011 LearnBoost +Copyright (c) 2011 TJ Holowaychuk +Copyright (c) 2014-2016 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/serve-static/README.md b/node_modules/serve-static/README.md new file mode 100644 index 0000000..70f01c3 --- /dev/null +++ b/node_modules/serve-static/README.md @@ -0,0 +1,253 @@ +# serve-static + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![CI][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install serve-static +``` + +## API + +```js +var serveStatic = require('serve-static') +``` + +### serveStatic(root, options) + +Create a new middleware function to serve files from within a given root +directory. The file to serve will be determined by combining `req.url` +with the provided root directory. When a file is not found, instead of +sending a 404 response, this module will instead call `next()` to move on +to the next middleware, allowing for stacking and fall-backs. + +#### Options + +##### acceptRanges + +Enable or disable accepting ranged requests, defaults to true. +Disabling this will not send `Accept-Ranges` and ignore the contents +of the `Range` request header. + +##### cacheControl + +Enable or disable setting `Cache-Control` response header, defaults to +true. Disabling this will ignore the `immutable` and `maxAge` options. + +##### dotfiles + +Set how "dotfiles" are treated when encountered. A dotfile is a file +or directory that begins with a dot ("."). Note this check is done on +the path itself without checking if the path actually exists on the +disk. If `root` is specified, only the dotfiles above the root are +checked (i.e. the root itself can be within a dotfile when set +to "deny"). + + - `'allow'` No special treatment for dotfiles. + - `'deny'` Deny a request for a dotfile and 403/`next()`. + - `'ignore'` Pretend like the dotfile does not exist and 404/`next()`. + +The default value is `'ignore'`. + +##### etag + +Enable or disable etag generation, defaults to true. + +##### extensions + +Set file extension fallbacks. When set, if a file is not found, the given +extensions will be added to the file name and search for. The first that +exists will be served. Example: `['html', 'htm']`. + +The default value is `false`. + +##### fallthrough + +Set the middleware to have client errors fall-through as just unhandled +requests, otherwise forward a client error. The difference is that client +errors like a bad request or a request to a non-existent file will cause +this middleware to simply `next()` to your next middleware when this value +is `true`. When this value is `false`, these errors (even 404s), will invoke +`next(err)`. + +Typically `true` is desired such that multiple physical directories can be +mapped to the same web address or for routes to fill in non-existent files. + +The value `false` can be used if this middleware is mounted at a path that +is designed to be strictly a single file system directory, which allows for +short-circuiting 404s for less overhead. This middleware will also reply to +all methods. + +The default value is `true`. + +##### immutable + +Enable or disable the `immutable` directive in the `Cache-Control` response +header, defaults to `false`. If set to `true`, the `maxAge` option should +also be specified to enable caching. The `immutable` directive will prevent +supported clients from making conditional requests during the life of the +`maxAge` option to check if the file has changed. + +##### index + +By default this module will send "index.html" files in response to a request +on a directory. To disable this set `false` or to supply a new index pass a +string or an array in preferred order. + +##### lastModified + +Enable or disable `Last-Modified` header, defaults to true. Uses the file +system's last modified value. + +##### maxAge + +Provide a max-age in milliseconds for http caching, defaults to 0. This +can also be a string accepted by the [ms](https://www.npmjs.org/package/ms#readme) +module. + +##### redirect + +Redirect to trailing "/" when the pathname is a dir. Defaults to `true`. + +##### setHeaders + +Function to set custom headers on response. Alterations to the headers need to +occur synchronously. The function is called as `fn(res, path, stat)`, where +the arguments are: + + - `res` the response object + - `path` the file path that is being sent + - `stat` the stat object of the file that is being sent + +## Examples + +### Serve files with vanilla node.js http server + +```js +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +// Serve up public/ftp folder +var serve = serveStatic('public/ftp', { index: ['index.html', 'index.htm'] }) + +// Create server +var server = http.createServer(function onRequest (req, res) { + serve(req, res, finalhandler(req, res)) +}) + +// Listen +server.listen(3000) +``` + +### Serve all files as downloads + +```js +var contentDisposition = require('content-disposition') +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +// Serve up public/ftp folder +var serve = serveStatic('public/ftp', { + index: false, + setHeaders: setHeaders +}) + +// Set header to force download +function setHeaders (res, path) { + res.setHeader('Content-Disposition', contentDisposition(path)) +} + +// Create server +var server = http.createServer(function onRequest (req, res) { + serve(req, res, finalhandler(req, res)) +}) + +// Listen +server.listen(3000) +``` + +### Serving using express + +#### Simple + +This is a simple example of using Express. + +```js +var express = require('express') +var serveStatic = require('serve-static') + +var app = express() + +app.use(serveStatic('public/ftp', { index: ['default.html', 'default.htm'] })) +app.listen(3000) +``` + +#### Multiple roots + +This example shows a simple way to search through multiple directories. +Files are searched for in `public-optimized/` first, then `public/` second +as a fallback. + +```js +var express = require('express') +var path = require('path') +var serveStatic = require('serve-static') + +var app = express() + +app.use(serveStatic(path.join(__dirname, 'public-optimized'))) +app.use(serveStatic(path.join(__dirname, 'public'))) +app.listen(3000) +``` + +#### Different settings for paths + +This example shows how to set a different max age depending on the served +file. In this example, HTML files are not cached, while everything else +is for 1 day. + +```js +var express = require('express') +var path = require('path') +var serveStatic = require('serve-static') + +var app = express() + +app.use(serveStatic(path.join(__dirname, 'public'), { + maxAge: '1d', + setHeaders: setCustomCacheControl +})) + +app.listen(3000) + +function setCustomCacheControl (res, file) { + if (path.extname(file) === '.html') { + // Custom Cache-Control for HTML files + res.setHeader('Cache-Control', 'public, max-age=0') + } +} +``` + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/serve-static/master +[coveralls-url]: https://coveralls.io/r/expressjs/serve-static?branch=master +[github-actions-ci-image]: https://badgen.net/github/checks/expressjs/serve-static/master?label=linux +[github-actions-ci-url]: https://github.com/expressjs/serve-static/actions/workflows/ci.yml +[node-image]: https://badgen.net/npm/node/serve-static +[node-url]: https://nodejs.org/en/download/ +[npm-downloads-image]: https://badgen.net/npm/dm/serve-static +[npm-url]: https://npmjs.org/package/serve-static +[npm-version-image]: https://badgen.net/npm/v/serve-static diff --git a/node_modules/serve-static/index.js b/node_modules/serve-static/index.js new file mode 100644 index 0000000..1bee463 --- /dev/null +++ b/node_modules/serve-static/index.js @@ -0,0 +1,208 @@ +/*! + * serve-static + * Copyright(c) 2010 Sencha Inc. + * Copyright(c) 2011 TJ Holowaychuk + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') +var parseUrl = require('parseurl') +var resolve = require('path').resolve +var send = require('send') +var url = require('url') + +/** + * Module exports. + * @public + */ + +module.exports = serveStatic + +/** + * @param {string} root + * @param {object} [options] + * @return {function} + * @public + */ + +function serveStatic (root, options) { + if (!root) { + throw new TypeError('root path required') + } + + if (typeof root !== 'string') { + throw new TypeError('root path must be a string') + } + + // copy options object + var opts = Object.create(options || null) + + // fall-though + var fallthrough = opts.fallthrough !== false + + // default redirect + var redirect = opts.redirect !== false + + // headers listener + var setHeaders = opts.setHeaders + + if (setHeaders && typeof setHeaders !== 'function') { + throw new TypeError('option setHeaders must be function') + } + + // setup options for send + opts.maxage = opts.maxage || opts.maxAge || 0 + opts.root = resolve(root) + + // construct directory listener + var onDirectory = redirect + ? createRedirectDirectoryListener() + : createNotFoundDirectoryListener() + + return function serveStatic (req, res, next) { + if (req.method !== 'GET' && req.method !== 'HEAD') { + if (fallthrough) { + return next() + } + + // method not allowed + res.statusCode = 405 + res.setHeader('Allow', 'GET, HEAD') + res.setHeader('Content-Length', '0') + res.end() + return + } + + var forwardError = !fallthrough + var originalUrl = parseUrl.original(req) + var path = parseUrl(req).pathname + + // make sure redirect occurs at mount + if (path === '/' && originalUrl.pathname.substr(-1) !== '/') { + path = '' + } + + // create send stream + var stream = send(req, path, opts) + + // add directory handler + stream.on('directory', onDirectory) + + // add headers listener + if (setHeaders) { + stream.on('headers', setHeaders) + } + + // add file listener for fallthrough + if (fallthrough) { + stream.on('file', function onFile () { + // once file is determined, always forward error + forwardError = true + }) + } + + // forward errors + stream.on('error', function error (err) { + if (forwardError || !(err.statusCode < 500)) { + next(err) + return + } + + next() + }) + + // pipe + stream.pipe(res) + } +} + +/** + * Collapse all leading slashes into a single slash + * @private + */ +function collapseLeadingSlashes (str) { + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) !== 0x2f /* / */) { + break + } + } + + return i > 1 + ? '/' + str.substr(i) + : str +} + +/** + * Create a minimal HTML document. + * + * @param {string} title + * @param {string} body + * @private + */ + +function createHtmlDocument (title, body) { + return '\n' + + '\n' + + '\n' + + '\n' + + '' + title + '\n' + + '\n' + + '\n' + + '
' + body + '
\n' + + '\n' + + '\n' +} + +/** + * Create a directory listener that just 404s. + * @private + */ + +function createNotFoundDirectoryListener () { + return function notFound () { + this.error(404) + } +} + +/** + * Create a directory listener that performs a redirect. + * @private + */ + +function createRedirectDirectoryListener () { + return function redirect (res) { + if (this.hasTrailingSlash()) { + this.error(404) + return + } + + // get original URL + var originalUrl = parseUrl.original(this.req) + + // append trailing slash + originalUrl.path = null + originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + '/') + + // reformat the URL + var loc = encodeUrl(url.format(originalUrl)) + var doc = createHtmlDocument('Redirecting', 'Redirecting to ' + escapeHtml(loc)) + + // send redirect response + res.statusCode = 301 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(doc)) + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') + res.setHeader('Location', loc) + res.end(doc) + } +} diff --git a/node_modules/serve-static/package.json b/node_modules/serve-static/package.json new file mode 100644 index 0000000..38d3365 --- /dev/null +++ b/node_modules/serve-static/package.json @@ -0,0 +1,41 @@ +{ + "name": "serve-static", + "description": "Serve static files", + "version": "2.2.0", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "repository": "expressjs/serve-static", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "^10.7.0", + "nyc": "^17.0.0", + "supertest": "^6.3.4" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 18" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/setprototypeof/LICENSE b/node_modules/setprototypeof/LICENSE new file mode 100644 index 0000000..61afa2f --- /dev/null +++ b/node_modules/setprototypeof/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2015, Wes Todd + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/setprototypeof/README.md b/node_modules/setprototypeof/README.md new file mode 100644 index 0000000..791eeff --- /dev/null +++ b/node_modules/setprototypeof/README.md @@ -0,0 +1,31 @@ +# Polyfill for `Object.setPrototypeOf` + +[![NPM Version](https://img.shields.io/npm/v/setprototypeof.svg)](https://npmjs.org/package/setprototypeof) +[![NPM Downloads](https://img.shields.io/npm/dm/setprototypeof.svg)](https://npmjs.org/package/setprototypeof) +[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](https://github.com/standard/standard) + +A simple cross platform implementation to set the prototype of an instianted object. Supports all modern browsers and at least back to IE8. + +## Usage: + +``` +$ npm install --save setprototypeof +``` + +```javascript +var setPrototypeOf = require('setprototypeof') + +var obj = {} +setPrototypeOf(obj, { + foo: function () { + return 'bar' + } +}) +obj.foo() // bar +``` + +TypeScript is also supported: + +```typescript +import setPrototypeOf from 'setprototypeof' +``` diff --git a/node_modules/setprototypeof/index.d.ts b/node_modules/setprototypeof/index.d.ts new file mode 100644 index 0000000..f108ecd --- /dev/null +++ b/node_modules/setprototypeof/index.d.ts @@ -0,0 +1,2 @@ +declare function setPrototypeOf(o: any, proto: object | null): any; +export = setPrototypeOf; diff --git a/node_modules/setprototypeof/index.js b/node_modules/setprototypeof/index.js new file mode 100644 index 0000000..c527055 --- /dev/null +++ b/node_modules/setprototypeof/index.js @@ -0,0 +1,17 @@ +'use strict' +/* eslint no-proto: 0 */ +module.exports = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties) + +function setProtoOf (obj, proto) { + obj.__proto__ = proto + return obj +} + +function mixinProperties (obj, proto) { + for (var prop in proto) { + if (!Object.prototype.hasOwnProperty.call(obj, prop)) { + obj[prop] = proto[prop] + } + } + return obj +} diff --git a/node_modules/setprototypeof/package.json b/node_modules/setprototypeof/package.json new file mode 100644 index 0000000..f20915b --- /dev/null +++ b/node_modules/setprototypeof/package.json @@ -0,0 +1,38 @@ +{ + "name": "setprototypeof", + "version": "1.2.0", + "description": "A small polyfill for Object.setprototypeof", + "main": "index.js", + "typings": "index.d.ts", + "scripts": { + "test": "standard && mocha", + "testallversions": "npm run node010 && npm run node4 && npm run node6 && npm run node9 && npm run node11", + "testversion": "docker run -it --rm -v $(PWD):/usr/src/app -w /usr/src/app node:${NODE_VER} npm install mocha@${MOCHA_VER:-latest} && npm t", + "node010": "NODE_VER=0.10 MOCHA_VER=3 npm run testversion", + "node4": "NODE_VER=4 npm run testversion", + "node6": "NODE_VER=6 npm run testversion", + "node9": "NODE_VER=9 npm run testversion", + "node11": "NODE_VER=11 npm run testversion", + "prepublishOnly": "npm t", + "postpublish": "git push origin && git push origin --tags" + }, + "repository": { + "type": "git", + "url": "https://github.com/wesleytodd/setprototypeof.git" + }, + "keywords": [ + "polyfill", + "object", + "setprototypeof" + ], + "author": "Wes Todd", + "license": "ISC", + "bugs": { + "url": "https://github.com/wesleytodd/setprototypeof/issues" + }, + "homepage": "https://github.com/wesleytodd/setprototypeof", + "devDependencies": { + "mocha": "^6.1.4", + "standard": "^13.0.2" + } +} diff --git a/node_modules/setprototypeof/test/index.js b/node_modules/setprototypeof/test/index.js new file mode 100644 index 0000000..afeb4dd --- /dev/null +++ b/node_modules/setprototypeof/test/index.js @@ -0,0 +1,24 @@ +'use strict' +/* eslint-env mocha */ +/* eslint no-proto: 0 */ +var assert = require('assert') +var setPrototypeOf = require('..') + +describe('setProtoOf(obj, proto)', function () { + it('should merge objects', function () { + var obj = { a: 1, b: 2 } + var proto = { b: 3, c: 4 } + var mergeObj = setPrototypeOf(obj, proto) + + if (Object.getPrototypeOf) { + assert.strictEqual(Object.getPrototypeOf(obj), proto) + } else if ({ __proto__: [] } instanceof Array) { + assert.strictEqual(obj.__proto__, proto) + } else { + assert.strictEqual(obj.a, 1) + assert.strictEqual(obj.b, 2) + assert.strictEqual(obj.c, 4) + } + assert.strictEqual(mergeObj, obj) + }) +}) diff --git a/node_modules/side-channel-list/.editorconfig b/node_modules/side-channel-list/.editorconfig new file mode 100644 index 0000000..72e0eba --- /dev/null +++ b/node_modules/side-channel-list/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = tab +indent_size = 2 +trim_trailing_whitespace = true diff --git a/node_modules/side-channel-list/.eslintrc b/node_modules/side-channel-list/.eslintrc new file mode 100644 index 0000000..93978e7 --- /dev/null +++ b/node_modules/side-channel-list/.eslintrc @@ -0,0 +1,11 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-lines-per-function": 0, + "multiline-comment-style": 1, + "new-cap": [2, { "capIsNewExceptions": ["GetIntrinsic"] }], + }, +} diff --git a/node_modules/side-channel-list/.github/FUNDING.yml b/node_modules/side-channel-list/.github/FUNDING.yml new file mode 100644 index 0000000..eaff735 --- /dev/null +++ b/node_modules/side-channel-list/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/side-channel-list +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/side-channel-list/.nycrc b/node_modules/side-channel-list/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/node_modules/side-channel-list/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/side-channel-list/CHANGELOG.md b/node_modules/side-channel-list/CHANGELOG.md new file mode 100644 index 0000000..2ec51b7 --- /dev/null +++ b/node_modules/side-channel-list/CHANGELOG.md @@ -0,0 +1,15 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## v1.0.0 - 2024-12-10 + +### Commits + +- Initial implementation, tests, readme, types [`5d6baee`](https://github.com/ljharb/side-channel-list/commit/5d6baee5c9054a1238007f5a1dfc109a7a816251) +- Initial commit [`3ae784c`](https://github.com/ljharb/side-channel-list/commit/3ae784c63a47895fbaeed2a91ab54a8029a7a100) +- npm init [`07055a4`](https://github.com/ljharb/side-channel-list/commit/07055a4d139895565b199dba5fe2479c1a1b9e28) +- Only apps should have lockfiles [`9573058`](https://github.com/ljharb/side-channel-list/commit/9573058a47494e2d68f8c6c77b5d7fbe441949c1) diff --git a/node_modules/side-channel-list/LICENSE b/node_modules/side-channel-list/LICENSE new file mode 100644 index 0000000..f82f389 --- /dev/null +++ b/node_modules/side-channel-list/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/side-channel-list/README.md b/node_modules/side-channel-list/README.md new file mode 100644 index 0000000..d9c7a13 --- /dev/null +++ b/node_modules/side-channel-list/README.md @@ -0,0 +1,62 @@ +# side-channel-list [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Store information about any JS value in a side channel, using a linked list. + +Warning: this implementation will leak memory until you `delete` the `key`. +Use [`side-channel`](https://npmjs.com/side-channel) for the best available strategy. + +## Getting started + +```sh +npm install --save side-channel-list +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const getSideChannelList = require('side-channel-list'); + +const channel = getSideChannelList(); + +const key = {}; +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); + +channel.set(key, 42); + +channel.assert(key); // does not throw +assert.equal(channel.has(key), true); +assert.equal(channel.get(key), 42); + +channel.delete(key); +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/side-channel-list +[npm-version-svg]: https://versionbadg.es/ljharb/side-channel-list.svg +[deps-svg]: https://david-dm.org/ljharb/side-channel-list.svg +[deps-url]: https://david-dm.org/ljharb/side-channel-list +[dev-deps-svg]: https://david-dm.org/ljharb/side-channel-list/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/side-channel-list#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/side-channel-list.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/side-channel-list.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/side-channel-list.svg +[downloads-url]: https://npm-stat.com/charts.html?package=side-channel-list +[codecov-image]: https://codecov.io/gh/ljharb/side-channel-list/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/side-channel-list/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/side-channel-list +[actions-url]: https://github.com/ljharb/side-channel-list/actions diff --git a/node_modules/side-channel-list/index.d.ts b/node_modules/side-channel-list/index.d.ts new file mode 100644 index 0000000..c9cabc8 --- /dev/null +++ b/node_modules/side-channel-list/index.d.ts @@ -0,0 +1,13 @@ +declare namespace getSideChannelList { + type Channel = { + assert: (key: K) => void; + has: (key: K) => boolean; + get: (key: K) => V | undefined; + set: (key: K, value: V) => void; + delete: (key: K) => boolean; + }; +} + +declare function getSideChannelList(): getSideChannelList.Channel; + +export = getSideChannelList; diff --git a/node_modules/side-channel-list/index.js b/node_modules/side-channel-list/index.js new file mode 100644 index 0000000..8d6f98c --- /dev/null +++ b/node_modules/side-channel-list/index.js @@ -0,0 +1,113 @@ +'use strict'; + +var inspect = require('object-inspect'); + +var $TypeError = require('es-errors/type'); + +/* +* This function traverses the list returning the node corresponding to the given key. +* +* That node is also moved to the head of the list, so that if it's accessed again we don't need to traverse the whole list. +* By doing so, all the recently used nodes can be accessed relatively quickly. +*/ +/** @type {import('./list.d.ts').listGetNode} */ +// eslint-disable-next-line consistent-return +var listGetNode = function (list, key, isDelete) { + /** @type {typeof list | NonNullable<(typeof list)['next']>} */ + var prev = list; + /** @type {(typeof list)['next']} */ + var curr; + // eslint-disable-next-line eqeqeq + for (; (curr = prev.next) != null; prev = curr) { + if (curr.key === key) { + prev.next = curr.next; + if (!isDelete) { + // eslint-disable-next-line no-extra-parens + curr.next = /** @type {NonNullable} */ (list.next); + list.next = curr; // eslint-disable-line no-param-reassign + } + return curr; + } + } +}; + +/** @type {import('./list.d.ts').listGet} */ +var listGet = function (objects, key) { + if (!objects) { + return void undefined; + } + var node = listGetNode(objects, key); + return node && node.value; +}; +/** @type {import('./list.d.ts').listSet} */ +var listSet = function (objects, key, value) { + var node = listGetNode(objects, key); + if (node) { + node.value = value; + } else { + // Prepend the new node to the beginning of the list + objects.next = /** @type {import('./list.d.ts').ListNode} */ ({ // eslint-disable-line no-param-reassign, no-extra-parens + key: key, + next: objects.next, + value: value + }); + } +}; +/** @type {import('./list.d.ts').listHas} */ +var listHas = function (objects, key) { + if (!objects) { + return false; + } + return !!listGetNode(objects, key); +}; +/** @type {import('./list.d.ts').listDelete} */ +// eslint-disable-next-line consistent-return +var listDelete = function (objects, key) { + if (objects) { + return listGetNode(objects, key, true); + } +}; + +/** @type {import('.')} */ +module.exports = function getSideChannelList() { + /** @typedef {ReturnType} Channel */ + /** @typedef {Parameters[0]} K */ + /** @typedef {Parameters[1]} V */ + + /** @type {import('./list.d.ts').RootNode | undefined} */ var $o; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + var root = $o && $o.next; + var deletedNode = listDelete($o, key); + if (deletedNode && root && root === deletedNode) { + $o = void undefined; + } + return !!deletedNode; + }, + get: function (key) { + return listGet($o, key); + }, + has: function (key) { + return listHas($o, key); + }, + set: function (key, value) { + if (!$o) { + // Initialize the linked list as an empty node, so that we don't have to special-case handling of the first node: we can always refer to it as (previous node).next, instead of something like (list).head + $o = { + next: void undefined + }; + } + // eslint-disable-next-line no-extra-parens + listSet(/** @type {NonNullable} */ ($o), key, value); + } + }; + // @ts-expect-error TODO: figure out why this is erroring + return channel; +}; diff --git a/node_modules/side-channel-list/list.d.ts b/node_modules/side-channel-list/list.d.ts new file mode 100644 index 0000000..2c759e2 --- /dev/null +++ b/node_modules/side-channel-list/list.d.ts @@ -0,0 +1,14 @@ +type ListNode = { + key: K; + next: undefined | ListNode; + value: T; +}; +type RootNode = { + next: undefined | ListNode; +}; + +export function listGetNode(list: RootNode, key: ListNode['key'], isDelete?: boolean): ListNode | undefined; +export function listGet(objects: undefined | RootNode, key: ListNode['key']): T | undefined; +export function listSet(objects: RootNode, key: ListNode['key'], value: T): void; +export function listHas(objects: undefined | RootNode, key: ListNode['key']): boolean; +export function listDelete(objects: undefined | RootNode, key: ListNode['key']): ListNode | undefined; diff --git a/node_modules/side-channel-list/package.json b/node_modules/side-channel-list/package.json new file mode 100644 index 0000000..ba0f5c5 --- /dev/null +++ b/node_modules/side-channel-list/package.json @@ -0,0 +1,77 @@ +{ + "name": "side-channel-list", + "version": "1.0.0", + "description": "Store information about any JS value in a side channel, using a linked list", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "types": "./index.d.ts", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "evalmd README.md && eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>= 10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/side-channel-list.git" + }, + "keywords": [], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/side-channel-list/issues" + }, + "homepage": "https://github.com/ljharb/side-channel-list#readme", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.1", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.2", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.6.5", + "auto-changelog": "^2.5.0", + "eclint": "^2.8.1", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/side-channel-list/test/index.js b/node_modules/side-channel-list/test/index.js new file mode 100644 index 0000000..3ad4368 --- /dev/null +++ b/node_modules/side-channel-list/test/index.js @@ -0,0 +1,104 @@ +'use strict'; + +var test = require('tape'); + +var getSideChannelList = require('../'); + +test('getSideChannelList', function (t) { + t.test('export', function (st) { + st.equal(typeof getSideChannelList, 'function', 'is a function'); + + st.equal(getSideChannelList.length, 0, 'takes no arguments'); + + var channel = getSideChannelList(); + st.ok(channel, 'is truthy'); + st.equal(typeof channel, 'object', 'is an object'); + st.end(); + }); + + t.test('assert', function (st) { + var channel = getSideChannelList(); + st['throws']( + function () { channel.assert({}); }, + TypeError, + 'nonexistent value throws' + ); + + var o = {}; + channel.set(o, 'data'); + st.doesNotThrow(function () { channel.assert(o); }, 'existent value noops'); + + st.end(); + }); + + t.test('has', function (st) { + var channel = getSideChannelList(); + /** @type {unknown[]} */ var o = []; + + st.equal(channel.has(o), false, 'nonexistent value yields false'); + + channel.set(o, 'foo'); + st.equal(channel.has(o), true, 'existent value yields true'); + + st.equal(channel.has('abc'), false, 'non object value non existent yields false'); + + channel.set('abc', 'foo'); + st.equal(channel.has('abc'), true, 'non object value that exists yields true'); + + st.end(); + }); + + t.test('get', function (st) { + var channel = getSideChannelList(); + var o = {}; + st.equal(channel.get(o), undefined, 'nonexistent value yields undefined'); + + var data = {}; + channel.set(o, data); + st.equal(channel.get(o), data, '"get" yields data set by "set"'); + + st.end(); + }); + + t.test('set', function (st) { + var channel = getSideChannelList(); + var o = function () {}; + st.equal(channel.get(o), undefined, 'value not set'); + + channel.set(o, 42); + st.equal(channel.get(o), 42, 'value was set'); + + channel.set(o, Infinity); + st.equal(channel.get(o), Infinity, 'value was set again'); + + var o2 = {}; + channel.set(o2, 17); + st.equal(channel.get(o), Infinity, 'o is not modified'); + st.equal(channel.get(o2), 17, 'o2 is set'); + + channel.set(o, 14); + st.equal(channel.get(o), 14, 'o is modified'); + st.equal(channel.get(o2), 17, 'o2 is not modified'); + + st.end(); + }); + + t.test('delete', function (st) { + var channel = getSideChannelList(); + var o = {}; + st.equal(channel['delete']({}), false, 'nonexistent value yields false'); + + channel.set(o, 42); + st.equal(channel.has(o), true, 'value is set'); + + st.equal(channel['delete']({}), false, 'nonexistent value still yields false'); + + st.equal(channel['delete'](o), true, 'deleted value yields true'); + + st.equal(channel.has(o), false, 'value is no longer set'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/side-channel-list/tsconfig.json b/node_modules/side-channel-list/tsconfig.json new file mode 100644 index 0000000..d9a6668 --- /dev/null +++ b/node_modules/side-channel-list/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/side-channel-map/.editorconfig b/node_modules/side-channel-map/.editorconfig new file mode 100644 index 0000000..72e0eba --- /dev/null +++ b/node_modules/side-channel-map/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = tab +indent_size = 2 +trim_trailing_whitespace = true diff --git a/node_modules/side-channel-map/.eslintrc b/node_modules/side-channel-map/.eslintrc new file mode 100644 index 0000000..93978e7 --- /dev/null +++ b/node_modules/side-channel-map/.eslintrc @@ -0,0 +1,11 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-lines-per-function": 0, + "multiline-comment-style": 1, + "new-cap": [2, { "capIsNewExceptions": ["GetIntrinsic"] }], + }, +} diff --git a/node_modules/side-channel-map/.github/FUNDING.yml b/node_modules/side-channel-map/.github/FUNDING.yml new file mode 100644 index 0000000..f2891bd --- /dev/null +++ b/node_modules/side-channel-map/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/side-channel-map +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/side-channel-map/.nycrc b/node_modules/side-channel-map/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/node_modules/side-channel-map/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/side-channel-map/CHANGELOG.md b/node_modules/side-channel-map/CHANGELOG.md new file mode 100644 index 0000000..b6ccea9 --- /dev/null +++ b/node_modules/side-channel-map/CHANGELOG.md @@ -0,0 +1,22 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.1](https://github.com/ljharb/side-channel-map/compare/v1.0.0...v1.0.1) - 2024-12-10 + +### Commits + +- [Deps] update `call-bound` [`6d05aaa`](https://github.com/ljharb/side-channel-map/commit/6d05aaa4ce5f2be4e7825df433d650696f0ba40f) +- [types] fix generics ordering [`11c0184`](https://github.com/ljharb/side-channel-map/commit/11c0184132ac11fdc16857e12682e148e5e9ee74) + +## v1.0.0 - 2024-12-10 + +### Commits + +- Initial implementation, tests, readme, types [`ad877b4`](https://github.com/ljharb/side-channel-map/commit/ad877b42926d46d63fff76a2bd01d2b4a01959a9) +- Initial commit [`28f8879`](https://github.com/ljharb/side-channel-map/commit/28f8879c512abe8fcf9b6a4dc7754a0287e5eba4) +- npm init [`2c9604e`](https://github.com/ljharb/side-channel-map/commit/2c9604e5aa40223e425ea7cea78f8a07697504bd) +- Only apps should have lockfiles [`5e7ba9c`](https://github.com/ljharb/side-channel-map/commit/5e7ba9cffe3ef42095815adc8ac1255b49bbadf5) diff --git a/node_modules/side-channel-map/LICENSE b/node_modules/side-channel-map/LICENSE new file mode 100644 index 0000000..f82f389 --- /dev/null +++ b/node_modules/side-channel-map/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/side-channel-map/README.md b/node_modules/side-channel-map/README.md new file mode 100644 index 0000000..8fa6f77 --- /dev/null +++ b/node_modules/side-channel-map/README.md @@ -0,0 +1,62 @@ +# side-channel-map [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Store information about any JS value in a side channel, using a Map. + +Warning: if the `key` is an object, this implementation will leak memory until you `delete` it. +Use [`side-channel`](https://npmjs.com/side-channel) for the best available strategy. + +## Getting started + +```sh +npm install --save side-channel-map +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const getSideChannelMap = require('side-channel-map'); + +const channel = getSideChannelMap(); + +const key = {}; +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); + +channel.set(key, 42); + +channel.assert(key); // does not throw +assert.equal(channel.has(key), true); +assert.equal(channel.get(key), 42); + +channel.delete(key); +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/side-channel-map +[npm-version-svg]: https://versionbadg.es/ljharb/side-channel-map.svg +[deps-svg]: https://david-dm.org/ljharb/side-channel-map.svg +[deps-url]: https://david-dm.org/ljharb/side-channel-map +[dev-deps-svg]: https://david-dm.org/ljharb/side-channel-map/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/side-channel-map#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/side-channel-map.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/side-channel-map.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/side-channel-map.svg +[downloads-url]: https://npm-stat.com/charts.html?package=side-channel-map +[codecov-image]: https://codecov.io/gh/ljharb/side-channel-map/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/side-channel-map/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/side-channel-map +[actions-url]: https://github.com/ljharb/side-channel-map/actions diff --git a/node_modules/side-channel-map/index.d.ts b/node_modules/side-channel-map/index.d.ts new file mode 100644 index 0000000..de33e89 --- /dev/null +++ b/node_modules/side-channel-map/index.d.ts @@ -0,0 +1,15 @@ +declare namespace getSideChannelMap { + type Channel = { + assert: (key: K) => void; + has: (key: K) => boolean; + get: (key: K) => V | undefined; + set: (key: K, value: V) => void; + delete: (key: K) => boolean; + }; +} + +declare function getSideChannelMap(): getSideChannelMap.Channel; + +declare const x: false | typeof getSideChannelMap; + +export = x; diff --git a/node_modules/side-channel-map/index.js b/node_modules/side-channel-map/index.js new file mode 100644 index 0000000..e111100 --- /dev/null +++ b/node_modules/side-channel-map/index.js @@ -0,0 +1,68 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var callBound = require('call-bound'); +var inspect = require('object-inspect'); + +var $TypeError = require('es-errors/type'); +var $Map = GetIntrinsic('%Map%', true); + +/** @type {(thisArg: Map, key: K) => V} */ +var $mapGet = callBound('Map.prototype.get', true); +/** @type {(thisArg: Map, key: K, value: V) => void} */ +var $mapSet = callBound('Map.prototype.set', true); +/** @type {(thisArg: Map, key: K) => boolean} */ +var $mapHas = callBound('Map.prototype.has', true); +/** @type {(thisArg: Map, key: K) => boolean} */ +var $mapDelete = callBound('Map.prototype.delete', true); +/** @type {(thisArg: Map) => number} */ +var $mapSize = callBound('Map.prototype.size', true); + +/** @type {import('.')} */ +module.exports = !!$Map && /** @type {Exclude} */ function getSideChannelMap() { + /** @typedef {ReturnType} Channel */ + /** @typedef {Parameters[0]} K */ + /** @typedef {Parameters[1]} V */ + + /** @type {Map | undefined} */ var $m; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + if ($m) { + var result = $mapDelete($m, key); + if ($mapSize($m) === 0) { + $m = void undefined; + } + return result; + } + return false; + }, + get: function (key) { // eslint-disable-line consistent-return + if ($m) { + return $mapGet($m, key); + } + }, + has: function (key) { + if ($m) { + return $mapHas($m, key); + } + return false; + }, + set: function (key, value) { + if (!$m) { + // @ts-expect-error TS can't handle narrowing a variable inside a closure + $m = new $Map(); + } + $mapSet($m, key, value); + } + }; + + // @ts-expect-error TODO: figure out why TS is erroring here + return channel; +}; diff --git a/node_modules/side-channel-map/package.json b/node_modules/side-channel-map/package.json new file mode 100644 index 0000000..18e8080 --- /dev/null +++ b/node_modules/side-channel-map/package.json @@ -0,0 +1,80 @@ +{ + "name": "side-channel-map", + "version": "1.0.1", + "description": "Store information about any JS value in a side channel, using a Map", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "types": "./index.d.ts", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "evalmd README.md && eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>= 10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/side-channel-map.git" + }, + "keywords": [], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/side-channel-map/issues" + }, + "homepage": "https://github.com/ljharb/side-channel-map#readme", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.1", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.2", + "@types/get-intrinsic": "^1.2.3", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.6.5", + "auto-changelog": "^2.5.0", + "eclint": "^2.8.1", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/side-channel-map/test/index.js b/node_modules/side-channel-map/test/index.js new file mode 100644 index 0000000..1743323 --- /dev/null +++ b/node_modules/side-channel-map/test/index.js @@ -0,0 +1,114 @@ +'use strict'; + +var test = require('tape'); + +var getSideChannelMap = require('../'); + +test('getSideChannelMap', { skip: typeof Map !== 'function' }, function (t) { + var getSideChannel = getSideChannelMap || function () { + throw new EvalError('should never happen'); + }; + + t.test('export', function (st) { + st.equal(typeof getSideChannel, 'function', 'is a function'); + + st.equal(getSideChannel.length, 0, 'takes no arguments'); + + var channel = getSideChannel(); + st.ok(channel, 'is truthy'); + st.equal(typeof channel, 'object', 'is an object'); + st.end(); + }); + + t.test('assert', function (st) { + var channel = getSideChannel(); + st['throws']( + function () { channel.assert({}); }, + TypeError, + 'nonexistent value throws' + ); + + var o = {}; + channel.set(o, 'data'); + st.doesNotThrow(function () { channel.assert(o); }, 'existent value noops'); + + st.end(); + }); + + t.test('has', function (st) { + var channel = getSideChannel(); + /** @type {unknown[]} */ var o = []; + + st.equal(channel.has(o), false, 'nonexistent value yields false'); + + channel.set(o, 'foo'); + st.equal(channel.has(o), true, 'existent value yields true'); + + st.equal(channel.has('abc'), false, 'non object value non existent yields false'); + + channel.set('abc', 'foo'); + st.equal(channel.has('abc'), true, 'non object value that exists yields true'); + + st.end(); + }); + + t.test('get', function (st) { + var channel = getSideChannel(); + var o = {}; + st.equal(channel.get(o), undefined, 'nonexistent value yields undefined'); + + var data = {}; + channel.set(o, data); + st.equal(channel.get(o), data, '"get" yields data set by "set"'); + + st.end(); + }); + + t.test('set', function (st) { + var channel = getSideChannel(); + var o = function () {}; + st.equal(channel.get(o), undefined, 'value not set'); + + channel.set(o, 42); + st.equal(channel.get(o), 42, 'value was set'); + + channel.set(o, Infinity); + st.equal(channel.get(o), Infinity, 'value was set again'); + + var o2 = {}; + channel.set(o2, 17); + st.equal(channel.get(o), Infinity, 'o is not modified'); + st.equal(channel.get(o2), 17, 'o2 is set'); + + channel.set(o, 14); + st.equal(channel.get(o), 14, 'o is modified'); + st.equal(channel.get(o2), 17, 'o2 is not modified'); + + st.end(); + }); + + t.test('delete', function (st) { + var channel = getSideChannel(); + var o = {}; + st.equal(channel['delete']({}), false, 'nonexistent value yields false'); + + channel.set(o, 42); + st.equal(channel.has(o), true, 'value is set'); + + st.equal(channel['delete']({}), false, 'nonexistent value still yields false'); + + st.equal(channel['delete'](o), true, 'deleted value yields true'); + + st.equal(channel.has(o), false, 'value is no longer set'); + + st.end(); + }); + + t.end(); +}); + +test('getSideChannelMap, no Maps', { skip: typeof Map === 'function' }, function (t) { + t.equal(getSideChannelMap, false, 'is false'); + + t.end(); +}); diff --git a/node_modules/side-channel-map/tsconfig.json b/node_modules/side-channel-map/tsconfig.json new file mode 100644 index 0000000..d9a6668 --- /dev/null +++ b/node_modules/side-channel-map/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/side-channel-weakmap/.editorconfig b/node_modules/side-channel-weakmap/.editorconfig new file mode 100644 index 0000000..72e0eba --- /dev/null +++ b/node_modules/side-channel-weakmap/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = tab +indent_size = 2 +trim_trailing_whitespace = true diff --git a/node_modules/side-channel-weakmap/.eslintrc b/node_modules/side-channel-weakmap/.eslintrc new file mode 100644 index 0000000..9b13ad8 --- /dev/null +++ b/node_modules/side-channel-weakmap/.eslintrc @@ -0,0 +1,12 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": 0, + "max-lines-per-function": 0, + "multiline-comment-style": 1, + "new-cap": [2, { "capIsNewExceptions": ["GetIntrinsic"] }], + }, +} diff --git a/node_modules/side-channel-weakmap/.github/FUNDING.yml b/node_modules/side-channel-weakmap/.github/FUNDING.yml new file mode 100644 index 0000000..2ae71cd --- /dev/null +++ b/node_modules/side-channel-weakmap/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/side-channel-weakmap +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/side-channel-weakmap/.nycrc b/node_modules/side-channel-weakmap/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/node_modules/side-channel-weakmap/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/side-channel-weakmap/CHANGELOG.md b/node_modules/side-channel-weakmap/CHANGELOG.md new file mode 100644 index 0000000..aba7ab0 --- /dev/null +++ b/node_modules/side-channel-weakmap/CHANGELOG.md @@ -0,0 +1,28 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.2](https://github.com/ljharb/side-channel-weakmap/compare/v1.0.1...v1.0.2) - 2024-12-10 + +### Commits + +- [types] fix generics ordering [`1b62e94`](https://github.com/ljharb/side-channel-weakmap/commit/1b62e94a2ad6ed30b640ba73c4a2535836c67289) + +## [v1.0.1](https://github.com/ljharb/side-channel-weakmap/compare/v1.0.0...v1.0.1) - 2024-12-10 + +### Commits + +- [types] fix generics ordering [`08a4a5d`](https://github.com/ljharb/side-channel-weakmap/commit/08a4a5dbffedc3ebc79f1aaaf5a3dd6d2196dc1b) +- [Deps] update `side-channel-map` [`b53fe44`](https://github.com/ljharb/side-channel-weakmap/commit/b53fe447dfdd3a9aebedfd015b384eac17fce916) + +## v1.0.0 - 2024-12-10 + +### Commits + +- Initial implementation, tests, readme, types [`53c0fa4`](https://github.com/ljharb/side-channel-weakmap/commit/53c0fa4788435a006f58b9d7b43cb65989ecee49) +- Initial commit [`a157947`](https://github.com/ljharb/side-channel-weakmap/commit/a157947f26fcaf2c4a941d3a044e76bf67343532) +- npm init [`54dfc55`](https://github.com/ljharb/side-channel-weakmap/commit/54dfc55bafb16265910d5aad4e743c43aee5bbbb) +- Only apps should have lockfiles [`0ddd6c7`](https://github.com/ljharb/side-channel-weakmap/commit/0ddd6c7b07fe8ee04d67b2e9f7255af7ce62c07d) diff --git a/node_modules/side-channel-weakmap/LICENSE b/node_modules/side-channel-weakmap/LICENSE new file mode 100644 index 0000000..3900dd7 --- /dev/null +++ b/node_modules/side-channel-weakmap/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/side-channel-weakmap/README.md b/node_modules/side-channel-weakmap/README.md new file mode 100644 index 0000000..856ee36 --- /dev/null +++ b/node_modules/side-channel-weakmap/README.md @@ -0,0 +1,62 @@ +# side-channel-weakmap [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Store information about any JS value in a side channel. Uses WeakMap if available. + +Warning: this implementation will leak memory until you `delete` the `key`. +Use [`side-channel`](https://npmjs.com/side-channel) for the best available strategy. + +## Getting started + +```sh +npm install --save side-channel-weakmap +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const getSideChannelList = require('side-channel-weakmap'); + +const channel = getSideChannelList(); + +const key = {}; +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); + +channel.set(key, 42); + +channel.assert(key); // does not throw +assert.equal(channel.has(key), true); +assert.equal(channel.get(key), 42); + +channel.delete(key); +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/side-channel-weakmap +[npm-version-svg]: https://versionbadg.es/ljharb/side-channel-weakmap.svg +[deps-svg]: https://david-dm.org/ljharb/side-channel-weakmap.svg +[deps-url]: https://david-dm.org/ljharb/side-channel-weakmap +[dev-deps-svg]: https://david-dm.org/ljharb/side-channel-weakmap/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/side-channel-weakmap#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/side-channel-weakmap.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/side-channel-weakmap.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/side-channel-weakmap.svg +[downloads-url]: https://npm-stat.com/charts.html?package=side-channel-weakmap +[codecov-image]: https://codecov.io/gh/ljharb/side-channel-weakmap/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/side-channel-weakmap/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/side-channel-weakmap +[actions-url]: https://github.com/ljharb/side-channel-weakmap/actions diff --git a/node_modules/side-channel-weakmap/index.d.ts b/node_modules/side-channel-weakmap/index.d.ts new file mode 100644 index 0000000..ce1bc2a --- /dev/null +++ b/node_modules/side-channel-weakmap/index.d.ts @@ -0,0 +1,15 @@ +declare namespace getSideChannelWeakMap { + type Channel = { + assert: (key: K) => void; + has: (key: K) => boolean; + get: (key: K) => V | undefined; + set: (key: K, value: V) => void; + delete: (key: K) => boolean; + } +} + +declare function getSideChannelWeakMap(): getSideChannelWeakMap.Channel; + +declare const x: false | typeof getSideChannelWeakMap; + +export = x; diff --git a/node_modules/side-channel-weakmap/index.js b/node_modules/side-channel-weakmap/index.js new file mode 100644 index 0000000..e5b8183 --- /dev/null +++ b/node_modules/side-channel-weakmap/index.js @@ -0,0 +1,84 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var callBound = require('call-bound'); +var inspect = require('object-inspect'); +var getSideChannelMap = require('side-channel-map'); + +var $TypeError = require('es-errors/type'); +var $WeakMap = GetIntrinsic('%WeakMap%', true); + +/** @type {(thisArg: WeakMap, key: K) => V} */ +var $weakMapGet = callBound('WeakMap.prototype.get', true); +/** @type {(thisArg: WeakMap, key: K, value: V) => void} */ +var $weakMapSet = callBound('WeakMap.prototype.set', true); +/** @type {(thisArg: WeakMap, key: K) => boolean} */ +var $weakMapHas = callBound('WeakMap.prototype.has', true); +/** @type {(thisArg: WeakMap, key: K) => boolean} */ +var $weakMapDelete = callBound('WeakMap.prototype.delete', true); + +/** @type {import('.')} */ +module.exports = $WeakMap + ? /** @type {Exclude} */ function getSideChannelWeakMap() { + /** @typedef {ReturnType} Channel */ + /** @typedef {Parameters[0]} K */ + /** @typedef {Parameters[1]} V */ + + /** @type {WeakMap | undefined} */ var $wm; + /** @type {Channel | undefined} */ var $m; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapDelete($wm, key); + } + } else if (getSideChannelMap) { + if ($m) { + return $m['delete'](key); + } + } + return false; + }, + get: function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapGet($wm, key); + } + } + return $m && $m.get(key); + }, + has: function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapHas($wm, key); + } + } + return !!$m && $m.has(key); + }, + set: function (key, value) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if (!$wm) { + $wm = new $WeakMap(); + } + $weakMapSet($wm, key, value); + } else if (getSideChannelMap) { + if (!$m) { + $m = getSideChannelMap(); + } + // eslint-disable-next-line no-extra-parens + /** @type {NonNullable} */ ($m).set(key, value); + } + } + }; + + // @ts-expect-error TODO: figure out why this is erroring + return channel; + } + : getSideChannelMap; diff --git a/node_modules/side-channel-weakmap/package.json b/node_modules/side-channel-weakmap/package.json new file mode 100644 index 0000000..9ef6583 --- /dev/null +++ b/node_modules/side-channel-weakmap/package.json @@ -0,0 +1,87 @@ +{ + "name": "side-channel-weakmap", + "version": "1.0.2", + "description": "Store information about any JS value in a side channel. Uses WeakMap if available.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "types": "./index.d.ts", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/side-channel-weakmap.git" + }, + "keywords": [ + "weakmap", + "map", + "side", + "channel", + "metadata" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/side-channel-weakmap/issues" + }, + "homepage": "https://github.com/ljharb/side-channel-weakmap#readme", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.1", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.2", + "@types/call-bind": "^1.0.5", + "@types/get-intrinsic": "^1.2.3", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.6.5", + "auto-changelog": "^2.5.0", + "eclint": "^2.8.1", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/side-channel-weakmap/test/index.js b/node_modules/side-channel-weakmap/test/index.js new file mode 100644 index 0000000..a01248b --- /dev/null +++ b/node_modules/side-channel-weakmap/test/index.js @@ -0,0 +1,114 @@ +'use strict'; + +var test = require('tape'); + +var getSideChannelWeakMap = require('../'); + +test('getSideChannelMap', { skip: typeof WeakMap !== 'function' && typeof Map !== 'function' }, function (t) { + var getSideChannel = getSideChannelWeakMap || function () { + throw new EvalError('should never happen'); + }; + + t.test('export', function (st) { + st.equal(typeof getSideChannel, 'function', 'is a function'); + + st.equal(getSideChannel.length, 0, 'takes no arguments'); + + var channel = getSideChannel(); + st.ok(channel, 'is truthy'); + st.equal(typeof channel, 'object', 'is an object'); + st.end(); + }); + + t.test('assert', function (st) { + var channel = getSideChannel(); + st['throws']( + function () { channel.assert({}); }, + TypeError, + 'nonexistent value throws' + ); + + var o = {}; + channel.set(o, 'data'); + st.doesNotThrow(function () { channel.assert(o); }, 'existent value noops'); + + st.end(); + }); + + t.test('has', function (st) { + var channel = getSideChannel(); + /** @type {unknown[]} */ var o = []; + + st.equal(channel.has(o), false, 'nonexistent value yields false'); + + channel.set(o, 'foo'); + st.equal(channel.has(o), true, 'existent value yields true'); + + st.equal(channel.has('abc'), false, 'non object value non existent yields false'); + + channel.set('abc', 'foo'); + st.equal(channel.has('abc'), true, 'non object value that exists yields true'); + + st.end(); + }); + + t.test('get', function (st) { + var channel = getSideChannel(); + var o = {}; + st.equal(channel.get(o), undefined, 'nonexistent value yields undefined'); + + var data = {}; + channel.set(o, data); + st.equal(channel.get(o), data, '"get" yields data set by "set"'); + + st.end(); + }); + + t.test('set', function (st) { + var channel = getSideChannel(); + var o = function () {}; + st.equal(channel.get(o), undefined, 'value not set'); + + channel.set(o, 42); + st.equal(channel.get(o), 42, 'value was set'); + + channel.set(o, Infinity); + st.equal(channel.get(o), Infinity, 'value was set again'); + + var o2 = {}; + channel.set(o2, 17); + st.equal(channel.get(o), Infinity, 'o is not modified'); + st.equal(channel.get(o2), 17, 'o2 is set'); + + channel.set(o, 14); + st.equal(channel.get(o), 14, 'o is modified'); + st.equal(channel.get(o2), 17, 'o2 is not modified'); + + st.end(); + }); + + t.test('delete', function (st) { + var channel = getSideChannel(); + var o = {}; + st.equal(channel['delete']({}), false, 'nonexistent value yields false'); + + channel.set(o, 42); + st.equal(channel.has(o), true, 'value is set'); + + st.equal(channel['delete']({}), false, 'nonexistent value still yields false'); + + st.equal(channel['delete'](o), true, 'deleted value yields true'); + + st.equal(channel.has(o), false, 'value is no longer set'); + + st.end(); + }); + + t.end(); +}); + +test('getSideChannelMap, no WeakMaps and/or Maps', { skip: typeof WeakMap === 'function' || typeof Map === 'function' }, function (t) { + t.equal(getSideChannelWeakMap, false, 'is false'); + + t.end(); +}); diff --git a/node_modules/side-channel-weakmap/tsconfig.json b/node_modules/side-channel-weakmap/tsconfig.json new file mode 100644 index 0000000..d9a6668 --- /dev/null +++ b/node_modules/side-channel-weakmap/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/side-channel/.editorconfig b/node_modules/side-channel/.editorconfig new file mode 100644 index 0000000..72e0eba --- /dev/null +++ b/node_modules/side-channel/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = tab +indent_size = 2 +trim_trailing_whitespace = true diff --git a/node_modules/side-channel/.eslintrc b/node_modules/side-channel/.eslintrc new file mode 100644 index 0000000..9b13ad8 --- /dev/null +++ b/node_modules/side-channel/.eslintrc @@ -0,0 +1,12 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": 0, + "max-lines-per-function": 0, + "multiline-comment-style": 1, + "new-cap": [2, { "capIsNewExceptions": ["GetIntrinsic"] }], + }, +} diff --git a/node_modules/side-channel/.github/FUNDING.yml b/node_modules/side-channel/.github/FUNDING.yml new file mode 100644 index 0000000..2a94840 --- /dev/null +++ b/node_modules/side-channel/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/side-channel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/side-channel/.nycrc b/node_modules/side-channel/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/node_modules/side-channel/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/side-channel/CHANGELOG.md b/node_modules/side-channel/CHANGELOG.md new file mode 100644 index 0000000..58e378c --- /dev/null +++ b/node_modules/side-channel/CHANGELOG.md @@ -0,0 +1,110 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.0](https://github.com/ljharb/side-channel/compare/v1.0.6...v1.1.0) - 2024-12-11 + +### Commits + +- [Refactor] extract implementations to `side-channel-weakmap`, `side-channel-map`, `side-channel-list` [`ada5955`](https://github.com/ljharb/side-channel/commit/ada595549a5c4c6c853756d598846b180941c6da) +- [New] add `channel.delete` [`c01d2d3`](https://github.com/ljharb/side-channel/commit/c01d2d3fd51dbb1ce6da72ad7916e61bd6172aad) +- [types] improve types [`0c54356`](https://github.com/ljharb/side-channel/commit/0c5435651417df41b8cc1a5f7cdce8bffae68cde) +- [readme] add content [`be24868`](https://github.com/ljharb/side-channel/commit/be248682ac294b0e22c883092c45985aa91c490a) +- [actions] split out node 10-20, and 20+ [`c4488e2`](https://github.com/ljharb/side-channel/commit/c4488e241ef3d49a19fe266ac830a2e644305911) +- [types] use shared tsconfig [`0e0d57c`](https://github.com/ljharb/side-channel/commit/0e0d57c2ff17c7b45c6cbd43ebcf553edc9e3adc) +- [Dev Deps] update `@ljharb/eslint-config`, `@ljharb/tsconfig`, `@types/get-intrinsic`, `@types/object-inspect`, `@types/tape`, `auto-changelog`, `tape` [`fb4f622`](https://github.com/ljharb/side-channel/commit/fb4f622e64a99a1e40b6e5cd7691674a9dc429e4) +- [Deps] update `call-bind`, `get-intrinsic`, `object-inspect` [`b78336b`](https://github.com/ljharb/side-channel/commit/b78336b886172d1b457d414ac9e28de8c5fecc78) +- [Tests] replace `aud` with `npm audit` [`ee3ab46`](https://github.com/ljharb/side-channel/commit/ee3ab4690d954311c35115651bcfd45edd205aa1) +- [Dev Deps] add missing peer dep [`c03e21a`](https://github.com/ljharb/side-channel/commit/c03e21a7def3b67cdc15ae22316884fefcb2f6a8) + +## [v1.0.6](https://github.com/ljharb/side-channel/compare/v1.0.5...v1.0.6) - 2024-02-29 + +### Commits + +- add types [`9beef66`](https://github.com/ljharb/side-channel/commit/9beef6643e6d717ea57bedabf86448123a7dd9e9) +- [meta] simplify `exports` [`4334cf9`](https://github.com/ljharb/side-channel/commit/4334cf9df654151504c383b62a2f9ebdc8d9d5ac) +- [Deps] update `call-bind` [`d6043c4`](https://github.com/ljharb/side-channel/commit/d6043c4d8f4d7be9037dd0f0419c7a2e0e39ec6a) +- [Dev Deps] update `tape` [`6aca376`](https://github.com/ljharb/side-channel/commit/6aca3761868dc8cd5ff7fd9799bf6b95e09a6eb0) + +## [v1.0.5](https://github.com/ljharb/side-channel/compare/v1.0.4...v1.0.5) - 2024-02-06 + +### Commits + +- [actions] reuse common workflows [`3d2e1ff`](https://github.com/ljharb/side-channel/commit/3d2e1ffd16dd6eaaf3e40ff57951f840d2d63c04) +- [meta] use `npmignore` to autogenerate an npmignore file [`04296ea`](https://github.com/ljharb/side-channel/commit/04296ea17d1544b0a5d20fd5bfb31aa4f6513eb9) +- [meta] add `.editorconfig`; add `eclint` [`130f0a6`](https://github.com/ljharb/side-channel/commit/130f0a6adbc04d385c7456a601d38344dce3d6a9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `safe-publish-latest`, `tape` [`d480c2f`](https://github.com/ljharb/side-channel/commit/d480c2fbe757489ae9b4275491ffbcc3ac4725e9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`ecbe70e`](https://github.com/ljharb/side-channel/commit/ecbe70e53a418234081a77971fec1fdfae20c841) +- [actions] update rebase action [`75240b9`](https://github.com/ljharb/side-channel/commit/75240b9963b816e8846400d2287cb68f88c7fba7) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `npmignore`, `tape` [`ae8d281`](https://github.com/ljharb/side-channel/commit/ae8d281572430099109870fd9430d2ca3f320b8d) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`7125b88`](https://github.com/ljharb/side-channel/commit/7125b885fd0eacad4fee9b073b72d14065ece278) +- [Deps] update `call-bind`, `get-intrinsic`, `object-inspect` [`82577c9`](https://github.com/ljharb/side-channel/commit/82577c9796304519139a570f82a317211b5f3b86) +- [Deps] update `call-bind`, `get-intrinsic`, `object-inspect` [`550aadf`](https://github.com/ljharb/side-channel/commit/550aadf20475a6081fd70304cc54f77259a5c8a8) +- [Tests] increase coverage [`5130877`](https://github.com/ljharb/side-channel/commit/5130877a7b27c862e64e6d1c12a178b28808859d) +- [Deps] update `get-intrinsic`, `object-inspect` [`ba0194c`](https://github.com/ljharb/side-channel/commit/ba0194c505b1a8a0427be14cadd5b8a46d4d01b8) +- [meta] add missing `engines.node` [`985fd24`](https://github.com/ljharb/side-channel/commit/985fd249663cb06617a693a94fe08cad12f5cb70) +- [Refactor] use `es-errors`, so things that only need those do not need `get-intrinsic` [`40227a8`](https://github.com/ljharb/side-channel/commit/40227a87b01709ad2c0eebf87eb4223a800099b9) +- [Deps] update `get-intrinsic` [`a989b40`](https://github.com/ljharb/side-channel/commit/a989b4024958737ae7be9fbffdeff2078f33a0fd) +- [Deps] update `object-inspect` [`aec42d2`](https://github.com/ljharb/side-channel/commit/aec42d2ec541a31aaa02475692c87d489237d9a3) + +## [v1.0.4](https://github.com/ljharb/side-channel/compare/v1.0.3...v1.0.4) - 2020-12-29 + +### Commits + +- [Tests] migrate tests to Github Actions [`10909cb`](https://github.com/ljharb/side-channel/commit/10909cbf8ce9c0bf96f604cf13d7ffd5a22c2d40) +- [Refactor] Use a linked list rather than an array, and move accessed nodes to the beginning [`195613f`](https://github.com/ljharb/side-channel/commit/195613f28b5c1e6072ef0b61b5beebaf2b6a304e) +- [meta] do not publish github action workflow files [`290ec29`](https://github.com/ljharb/side-channel/commit/290ec29cd21a60585145b4a7237ec55228c52c27) +- [Tests] run `nyc` on all tests; use `tape` runner [`ea6d030`](https://github.com/ljharb/side-channel/commit/ea6d030ff3fe6be2eca39e859d644c51ecd88869) +- [actions] add "Allow Edits" workflow [`d464d8f`](https://github.com/ljharb/side-channel/commit/d464d8fe52b5eddf1504a0ed97f0941a90f32c15) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog` [`02daca8`](https://github.com/ljharb/side-channel/commit/02daca87c6809821c97be468d1afa2f5ef447383) +- [Refactor] use `call-bind` and `get-intrinsic` instead of `es-abstract` [`e09d481`](https://github.com/ljharb/side-channel/commit/e09d481528452ebafa5cdeae1af665c35aa2deee) +- [Deps] update `object.assign` [`ee83aa8`](https://github.com/ljharb/side-channel/commit/ee83aa81df313b5e46319a63adb05cf0c179079a) +- [actions] update rebase action to use checkout v2 [`7726b0b`](https://github.com/ljharb/side-channel/commit/7726b0b058b632fccea709f58960871defaaa9d7) + +## [v1.0.3](https://github.com/ljharb/side-channel/compare/v1.0.2...v1.0.3) - 2020-08-23 + +### Commits + +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`1f10561`](https://github.com/ljharb/side-channel/commit/1f105611ef3acf32dec8032ae5c0baa5e56bb868) +- [Deps] update `es-abstract`, `object-inspect` [`bc20159`](https://github.com/ljharb/side-channel/commit/bc201597949a505e37cef9eaf24c7010831e6f03) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`b9b2b22`](https://github.com/ljharb/side-channel/commit/b9b2b225f9e0ea72a6ec2b89348f0bd690bc9ed1) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`7055ab4`](https://github.com/ljharb/side-channel/commit/7055ab4de0860606efd2003674a74f1fe6ebc07e) +- [Dev Deps] update `auto-changelog`; add `aud` [`d278c37`](https://github.com/ljharb/side-channel/commit/d278c37d08227be4f84aa769fcd919e73feeba40) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`3bcf982`](https://github.com/ljharb/side-channel/commit/3bcf982faa122745b39c33ce83d32fdf003741c6) +- [Tests] only audit prod deps [`18d01c4`](https://github.com/ljharb/side-channel/commit/18d01c4015b82a3d75044c4d5ba7917b2eac01ec) +- [Deps] update `es-abstract` [`6ab096d`](https://github.com/ljharb/side-channel/commit/6ab096d9de2b482cf5e0717e34e212f5b2b9bc9a) +- [Dev Deps] update `tape` [`9dc174c`](https://github.com/ljharb/side-channel/commit/9dc174cc651dfd300b4b72da936a0a7eda5f9452) +- [Deps] update `es-abstract` [`431d0f0`](https://github.com/ljharb/side-channel/commit/431d0f0ff11fbd2ae6f3115582a356d3a1cfce82) +- [Deps] update `es-abstract` [`49869fd`](https://github.com/ljharb/side-channel/commit/49869fd323bf4453f0ba515c0fb265cf5ab7b932) +- [meta] Add package.json to package's exports [`77d9cdc`](https://github.com/ljharb/side-channel/commit/77d9cdceb2a9e47700074f2ae0c0a202e7dac0d4) + +## [v1.0.2](https://github.com/ljharb/side-channel/compare/v1.0.1...v1.0.2) - 2019-12-20 + +### Commits + +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`4a526df`](https://github.com/ljharb/side-channel/commit/4a526df44e4701566ed001ec78546193f818b082) +- [Deps] update `es-abstract` [`d4f6e62`](https://github.com/ljharb/side-channel/commit/d4f6e629b6fb93a07415db7f30d3c90fd7f264fe) + +## [v1.0.1](https://github.com/ljharb/side-channel/compare/v1.0.0...v1.0.1) - 2019-12-01 + +### Commits + +- [Fix] add missing "exports" [`d212907`](https://github.com/ljharb/side-channel/commit/d2129073abf0701a5343bf28aa2145617604dc2e) + +## v1.0.0 - 2019-12-01 + +### Commits + +- Initial implementation [`dbebd3a`](https://github.com/ljharb/side-channel/commit/dbebd3a4b5ed64242f9a6810efe7c4214cd8cde4) +- Initial tests [`73bdefe`](https://github.com/ljharb/side-channel/commit/73bdefe568c9076cf8c0b8719bc2141aec0e19b8) +- Initial commit [`43c03e1`](https://github.com/ljharb/side-channel/commit/43c03e1c2849ec50a87b7a5cd76238a62b0b8770) +- npm init [`5c090a7`](https://github.com/ljharb/side-channel/commit/5c090a765d66a5527d9889b89aeff78dee91348c) +- [meta] add `auto-changelog` [`a5c4e56`](https://github.com/ljharb/side-channel/commit/a5c4e5675ec02d5eb4d84b4243aeea2a1d38fbec) +- [actions] add automatic rebasing / merge commit blocking [`bab1683`](https://github.com/ljharb/side-channel/commit/bab1683d8f9754b086e94397699fdc645e0d7077) +- [meta] add `funding` field; create FUNDING.yml [`63d7aea`](https://github.com/ljharb/side-channel/commit/63d7aeaf34f5650650ae97ca4b9fae685bd0937c) +- [Tests] add `npm run lint` [`46a5a81`](https://github.com/ljharb/side-channel/commit/46a5a81705cd2664f83df232c01dbbf2ee952885) +- Only apps should have lockfiles [`8b16b03`](https://github.com/ljharb/side-channel/commit/8b16b0305f00895d90c4e2e5773c854cfea0e448) +- [meta] add `safe-publish-latest` [`2f098ef`](https://github.com/ljharb/side-channel/commit/2f098ef092a39399cfe548b19a1fc03c2fd2f490) diff --git a/node_modules/side-channel/LICENSE b/node_modules/side-channel/LICENSE new file mode 100644 index 0000000..3900dd7 --- /dev/null +++ b/node_modules/side-channel/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/side-channel/README.md b/node_modules/side-channel/README.md new file mode 100644 index 0000000..cc7e103 --- /dev/null +++ b/node_modules/side-channel/README.md @@ -0,0 +1,61 @@ +# side-channel [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Store information about any JS value in a side channel. Uses WeakMap if available. + +Warning: in an environment that lacks `WeakMap`, this implementation will leak memory until you `delete` the `key`. + +## Getting started + +```sh +npm install --save side-channel +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const getSideChannel = require('side-channel'); + +const channel = getSideChannel(); + +const key = {}; +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); + +channel.set(key, 42); + +channel.assert(key); // does not throw +assert.equal(channel.has(key), true); +assert.equal(channel.get(key), 42); + +channel.delete(key); +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/side-channel +[npm-version-svg]: https://versionbadg.es/ljharb/side-channel.svg +[deps-svg]: https://david-dm.org/ljharb/side-channel.svg +[deps-url]: https://david-dm.org/ljharb/side-channel +[dev-deps-svg]: https://david-dm.org/ljharb/side-channel/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/side-channel#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/side-channel.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/side-channel.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/side-channel.svg +[downloads-url]: https://npm-stat.com/charts.html?package=side-channel +[codecov-image]: https://codecov.io/gh/ljharb/side-channel/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/side-channel/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/side-channel +[actions-url]: https://github.com/ljharb/side-channel/actions diff --git a/node_modules/side-channel/index.d.ts b/node_modules/side-channel/index.d.ts new file mode 100644 index 0000000..18c6317 --- /dev/null +++ b/node_modules/side-channel/index.d.ts @@ -0,0 +1,14 @@ +import getSideChannelList from 'side-channel-list'; +import getSideChannelMap from 'side-channel-map'; +import getSideChannelWeakMap from 'side-channel-weakmap'; + +declare namespace getSideChannel { + type Channel = + | getSideChannelList.Channel + | ReturnType, false>> + | ReturnType, false>>; +} + +declare function getSideChannel(): getSideChannel.Channel; + +export = getSideChannel; diff --git a/node_modules/side-channel/index.js b/node_modules/side-channel/index.js new file mode 100644 index 0000000..a8a9b05 --- /dev/null +++ b/node_modules/side-channel/index.js @@ -0,0 +1,43 @@ +'use strict'; + +var $TypeError = require('es-errors/type'); +var inspect = require('object-inspect'); +var getSideChannelList = require('side-channel-list'); +var getSideChannelMap = require('side-channel-map'); +var getSideChannelWeakMap = require('side-channel-weakmap'); + +var makeChannel = getSideChannelWeakMap || getSideChannelMap || getSideChannelList; + +/** @type {import('.')} */ +module.exports = function getSideChannel() { + /** @typedef {ReturnType} Channel */ + + /** @type {Channel | undefined} */ var $channelData; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + return !!$channelData && $channelData['delete'](key); + }, + get: function (key) { + return $channelData && $channelData.get(key); + }, + has: function (key) { + return !!$channelData && $channelData.has(key); + }, + set: function (key, value) { + if (!$channelData) { + $channelData = makeChannel(); + } + + $channelData.set(key, value); + } + }; + // @ts-expect-error TODO: figure out why this is erroring + return channel; +}; diff --git a/node_modules/side-channel/package.json b/node_modules/side-channel/package.json new file mode 100644 index 0000000..30fa42c --- /dev/null +++ b/node_modules/side-channel/package.json @@ -0,0 +1,85 @@ +{ + "name": "side-channel", + "version": "1.1.0", + "description": "Store information about any JS value in a side channel. Uses WeakMap if available.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "types": "./index.d.ts", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/side-channel.git" + }, + "keywords": [ + "weakmap", + "map", + "side", + "channel", + "metadata" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/side-channel/issues" + }, + "homepage": "https://github.com/ljharb/side-channel#readme", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.1", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.2", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.6.5", + "auto-changelog": "^2.5.0", + "eclint": "^2.8.1", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/side-channel/test/index.js b/node_modules/side-channel/test/index.js new file mode 100644 index 0000000..bd1e7c2 --- /dev/null +++ b/node_modules/side-channel/test/index.js @@ -0,0 +1,104 @@ +'use strict'; + +var test = require('tape'); + +var getSideChannel = require('../'); + +test('getSideChannel', function (t) { + t.test('export', function (st) { + st.equal(typeof getSideChannel, 'function', 'is a function'); + + st.equal(getSideChannel.length, 0, 'takes no arguments'); + + var channel = getSideChannel(); + st.ok(channel, 'is truthy'); + st.equal(typeof channel, 'object', 'is an object'); + st.end(); + }); + + t.test('assert', function (st) { + var channel = getSideChannel(); + st['throws']( + function () { channel.assert({}); }, + TypeError, + 'nonexistent value throws' + ); + + var o = {}; + channel.set(o, 'data'); + st.doesNotThrow(function () { channel.assert(o); }, 'existent value noops'); + + st.end(); + }); + + t.test('has', function (st) { + var channel = getSideChannel(); + /** @type {unknown[]} */ var o = []; + + st.equal(channel.has(o), false, 'nonexistent value yields false'); + + channel.set(o, 'foo'); + st.equal(channel.has(o), true, 'existent value yields true'); + + st.equal(channel.has('abc'), false, 'non object value non existent yields false'); + + channel.set('abc', 'foo'); + st.equal(channel.has('abc'), true, 'non object value that exists yields true'); + + st.end(); + }); + + t.test('get', function (st) { + var channel = getSideChannel(); + var o = {}; + st.equal(channel.get(o), undefined, 'nonexistent value yields undefined'); + + var data = {}; + channel.set(o, data); + st.equal(channel.get(o), data, '"get" yields data set by "set"'); + + st.end(); + }); + + t.test('set', function (st) { + var channel = getSideChannel(); + var o = function () {}; + st.equal(channel.get(o), undefined, 'value not set'); + + channel.set(o, 42); + st.equal(channel.get(o), 42, 'value was set'); + + channel.set(o, Infinity); + st.equal(channel.get(o), Infinity, 'value was set again'); + + var o2 = {}; + channel.set(o2, 17); + st.equal(channel.get(o), Infinity, 'o is not modified'); + st.equal(channel.get(o2), 17, 'o2 is set'); + + channel.set(o, 14); + st.equal(channel.get(o), 14, 'o is modified'); + st.equal(channel.get(o2), 17, 'o2 is not modified'); + + st.end(); + }); + + t.test('delete', function (st) { + var channel = getSideChannel(); + var o = {}; + st.equal(channel['delete']({}), false, 'nonexistent value yields false'); + + channel.set(o, 42); + st.equal(channel.has(o), true, 'value is set'); + + st.equal(channel['delete']({}), false, 'nonexistent value still yields false'); + + st.equal(channel['delete'](o), true, 'deleted value yields true'); + + st.equal(channel.has(o), false, 'value is no longer set'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/side-channel/tsconfig.json b/node_modules/side-channel/tsconfig.json new file mode 100644 index 0000000..d9a6668 --- /dev/null +++ b/node_modules/side-channel/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/statuses/HISTORY.md b/node_modules/statuses/HISTORY.md new file mode 100644 index 0000000..dc549b8 --- /dev/null +++ b/node_modules/statuses/HISTORY.md @@ -0,0 +1,87 @@ +2.0.2 / 2025-06-06 +================== + + * Migrate to `String.prototype.slice()` + +2.0.1 / 2021-01-03 +================== + + * Fix returning values from `Object.prototype` + +2.0.0 / 2020-04-19 +================== + + * Drop support for Node.js 0.6 + * Fix messaging casing of `418 I'm a Teapot` + * Remove code 306 + * Remove `status[code]` exports; use `status.message[code]` + * Remove `status[msg]` exports; use `status.code[msg]` + * Rename `425 Unordered Collection` to standard `425 Too Early` + * Rename `STATUS_CODES` export to `message` + * Return status message for `statuses(code)` when given code + +1.5.0 / 2018-03-27 +================== + + * Add `103 Early Hints` + +1.4.0 / 2017-10-20 +================== + + * Add `STATUS_CODES` export + +1.3.1 / 2016-11-11 +================== + + * Fix return type in JSDoc + +1.3.0 / 2016-05-17 +================== + + * Add `421 Misdirected Request` + * perf: enable strict mode + +1.2.1 / 2015-02-01 +================== + + * Fix message for status 451 + - `451 Unavailable For Legal Reasons` + +1.2.0 / 2014-09-28 +================== + + * Add `208 Already Repored` + * Add `226 IM Used` + * Add `306 (Unused)` + * Add `415 Unable For Legal Reasons` + * Add `508 Loop Detected` + +1.1.1 / 2014-09-24 +================== + + * Add missing 308 to `codes.json` + +1.1.0 / 2014-09-21 +================== + + * Add `codes.json` for universal support + +1.0.4 / 2014-08-20 +================== + + * Package cleanup + +1.0.3 / 2014-06-08 +================== + + * Add 308 to `.redirect` category + +1.0.2 / 2014-03-13 +================== + + * Add `.retry` category + +1.0.1 / 2014-03-12 +================== + + * Initial release diff --git a/node_modules/statuses/LICENSE b/node_modules/statuses/LICENSE new file mode 100644 index 0000000..28a3161 --- /dev/null +++ b/node_modules/statuses/LICENSE @@ -0,0 +1,23 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2016 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/statuses/README.md b/node_modules/statuses/README.md new file mode 100644 index 0000000..89d542f --- /dev/null +++ b/node_modules/statuses/README.md @@ -0,0 +1,139 @@ +# statuses + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] +[![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer] + +HTTP status utility for node. + +This module provides a list of status codes and messages sourced from +a few different projects: + + * The [IANA Status Code Registry](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml) + * The [Node.js project](https://nodejs.org/) + * The [NGINX project](https://www.nginx.com/) + * The [Apache HTTP Server project](https://httpd.apache.org/) + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install statuses +``` + +## API + + + +```js +var status = require('statuses') +``` + +### status(code) + +Returns the status message string for a known HTTP status code. The code +may be a number or a string. An error is thrown for an unknown status code. + + + +```js +status(403) // => 'Forbidden' +status('403') // => 'Forbidden' +status(306) // throws +``` + +### status(msg) + +Returns the numeric status code for a known HTTP status message. The message +is case-insensitive. An error is thrown for an unknown status message. + + + +```js +status('forbidden') // => 403 +status('Forbidden') // => 403 +status('foo') // throws +``` + +### status.codes + +Returns an array of all the status codes as `Integer`s. + +### status.code[msg] + +Returns the numeric status code for a known status message (in lower-case), +otherwise `undefined`. + + + +```js +status['not found'] // => 404 +``` + +### status.empty[code] + +Returns `true` if a status code expects an empty body. + + + +```js +status.empty[200] // => undefined +status.empty[204] // => true +status.empty[304] // => true +``` + +### status.message[code] + +Returns the string message for a known numeric status code, otherwise +`undefined`. This object is the same format as the +[Node.js http module `http.STATUS_CODES`](https://nodejs.org/dist/latest/docs/api/http.html#http_http_status_codes). + + + +```js +status.message[404] // => 'Not Found' +``` + +### status.redirect[code] + +Returns `true` if a status code is a valid redirect status. + + + +```js +status.redirect[200] // => undefined +status.redirect[301] // => true +``` + +### status.retry[code] + +Returns `true` if you should retry the rest. + + + +```js +status.retry[501] // => undefined +status.retry[503] // => true +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/statuses/master?label=ci +[ci-url]: https://github.com/jshttp/statuses/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/statuses/master +[coveralls-url]: https://coveralls.io/r/jshttp/statuses?branch=master +[node-version-image]: https://badgen.net/npm/node/statuses +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/statuses +[npm-url]: https://npmjs.org/package/statuses +[npm-version-image]: https://badgen.net/npm/v/statuses +[ossf-scorecard-badge]: https://api.securityscorecards.dev/projects/github.com/jshttp/statuses/badge +[ossf-scorecard-visualizer]: https://kooltheba.github.io/openssf-scorecard-api-visualizer/#/projects/github.com/jshttp/statuses diff --git a/node_modules/statuses/codes.json b/node_modules/statuses/codes.json new file mode 100644 index 0000000..1333ed1 --- /dev/null +++ b/node_modules/statuses/codes.json @@ -0,0 +1,65 @@ +{ + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "103": "Early Hints", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a Teapot", + "421": "Misdirected Request", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Too Early", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "510": "Not Extended", + "511": "Network Authentication Required" +} diff --git a/node_modules/statuses/index.js b/node_modules/statuses/index.js new file mode 100644 index 0000000..ea351c5 --- /dev/null +++ b/node_modules/statuses/index.js @@ -0,0 +1,146 @@ +/*! + * statuses + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var codes = require('./codes.json') + +/** + * Module exports. + * @public + */ + +module.exports = status + +// status code to message map +status.message = codes + +// status message (lower-case) to code map +status.code = createMessageToStatusCodeMap(codes) + +// array of status codes +status.codes = createStatusCodeList(codes) + +// status codes for redirects +status.redirect = { + 300: true, + 301: true, + 302: true, + 303: true, + 305: true, + 307: true, + 308: true +} + +// status codes for empty bodies +status.empty = { + 204: true, + 205: true, + 304: true +} + +// status codes for when you should retry the request +status.retry = { + 502: true, + 503: true, + 504: true +} + +/** + * Create a map of message to status code. + * @private + */ + +function createMessageToStatusCodeMap (codes) { + var map = {} + + Object.keys(codes).forEach(function forEachCode (code) { + var message = codes[code] + var status = Number(code) + + // populate map + map[message.toLowerCase()] = status + }) + + return map +} + +/** + * Create a list of all status codes. + * @private + */ + +function createStatusCodeList (codes) { + return Object.keys(codes).map(function mapCode (code) { + return Number(code) + }) +} + +/** + * Get the status code for given message. + * @private + */ + +function getStatusCode (message) { + var msg = message.toLowerCase() + + if (!Object.prototype.hasOwnProperty.call(status.code, msg)) { + throw new Error('invalid status message: "' + message + '"') + } + + return status.code[msg] +} + +/** + * Get the status message for given code. + * @private + */ + +function getStatusMessage (code) { + if (!Object.prototype.hasOwnProperty.call(status.message, code)) { + throw new Error('invalid status code: ' + code) + } + + return status.message[code] +} + +/** + * Get the status code. + * + * Given a number, this will throw if it is not a known status + * code, otherwise the code will be returned. Given a string, + * the string will be parsed for a number and return the code + * if valid, otherwise will lookup the code assuming this is + * the status message. + * + * @param {string|number} code + * @returns {number} + * @public + */ + +function status (code) { + if (typeof code === 'number') { + return getStatusMessage(code) + } + + if (typeof code !== 'string') { + throw new TypeError('code must be a number or string') + } + + // '403' + var n = parseInt(code, 10) + if (!isNaN(n)) { + return getStatusMessage(n) + } + + return getStatusCode(code) +} diff --git a/node_modules/statuses/package.json b/node_modules/statuses/package.json new file mode 100644 index 0000000..b5d016e --- /dev/null +++ b/node_modules/statuses/package.json @@ -0,0 +1,49 @@ +{ + "name": "statuses", + "description": "HTTP status utility", + "version": "2.0.2", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "repository": "jshttp/statuses", + "license": "MIT", + "keywords": [ + "http", + "status", + "code" + ], + "files": [ + "HISTORY.md", + "index.js", + "codes.json", + "LICENSE" + ], + "devDependencies": { + "csv-parse": "4.16.3", + "eslint": "7.19.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.31.0", + "eslint-plugin-markdown": "1.0.2", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "4.3.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "8.4.0", + "nyc": "15.1.0", + "raw-body": "2.5.2", + "stream-to-array": "2.3.0" + }, + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "build": "node scripts/build.js", + "fetch": "node scripts/fetch-apache.js && node scripts/fetch-iana.js && node scripts/fetch-nginx.js && node scripts/fetch-node.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "update": "npm run fetch && npm run build", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/toidentifier/HISTORY.md b/node_modules/toidentifier/HISTORY.md new file mode 100644 index 0000000..cb7cc89 --- /dev/null +++ b/node_modules/toidentifier/HISTORY.md @@ -0,0 +1,9 @@ +1.0.1 / 2021-11-14 +================== + + * pref: enable strict mode + +1.0.0 / 2018-07-09 +================== + + * Initial release diff --git a/node_modules/toidentifier/LICENSE b/node_modules/toidentifier/LICENSE new file mode 100644 index 0000000..de22d15 --- /dev/null +++ b/node_modules/toidentifier/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/toidentifier/README.md b/node_modules/toidentifier/README.md new file mode 100644 index 0000000..57e8a78 --- /dev/null +++ b/node_modules/toidentifier/README.md @@ -0,0 +1,61 @@ +# toidentifier + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][codecov-image]][codecov-url] + +> Convert a string of words to a JavaScript identifier + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +$ npm install toidentifier +``` + +## Example + +```js +var toIdentifier = require('toidentifier') + +console.log(toIdentifier('Bad Request')) +// => "BadRequest" +``` + +## API + +This CommonJS module exports a single default function: `toIdentifier`. + +### toIdentifier(string) + +Given a string as the argument, it will be transformed according to +the following rules and the new string will be returned: + +1. Split into words separated by space characters (`0x20`). +2. Upper case the first character of each word. +3. Join the words together with no separator. +4. Remove all non-word (`[0-9a-z_]`) characters. + +## License + +[MIT](LICENSE) + +[codecov-image]: https://img.shields.io/codecov/c/github/component/toidentifier.svg +[codecov-url]: https://codecov.io/gh/component/toidentifier +[downloads-image]: https://img.shields.io/npm/dm/toidentifier.svg +[downloads-url]: https://npmjs.org/package/toidentifier +[github-actions-ci-image]: https://img.shields.io/github/workflow/status/component/toidentifier/ci/master?label=ci +[github-actions-ci-url]: https://github.com/component/toidentifier?query=workflow%3Aci +[npm-image]: https://img.shields.io/npm/v/toidentifier.svg +[npm-url]: https://npmjs.org/package/toidentifier + + +## + +[npm]: https://www.npmjs.com/ + +[yarn]: https://yarnpkg.com/ diff --git a/node_modules/toidentifier/index.js b/node_modules/toidentifier/index.js new file mode 100644 index 0000000..9295d02 --- /dev/null +++ b/node_modules/toidentifier/index.js @@ -0,0 +1,32 @@ +/*! + * toidentifier + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = toIdentifier + +/** + * Trasform the given string into a JavaScript identifier + * + * @param {string} str + * @returns {string} + * @public + */ + +function toIdentifier (str) { + return str + .split(' ') + .map(function (token) { + return token.slice(0, 1).toUpperCase() + token.slice(1) + }) + .join('') + .replace(/[^ _0-9a-z]/gi, '') +} diff --git a/node_modules/toidentifier/package.json b/node_modules/toidentifier/package.json new file mode 100644 index 0000000..42db1a6 --- /dev/null +++ b/node_modules/toidentifier/package.json @@ -0,0 +1,38 @@ +{ + "name": "toidentifier", + "description": "Convert a string of words to a JavaScript identifier", + "version": "1.0.1", + "author": "Douglas Christopher Wilson ", + "contributors": [ + "Douglas Christopher Wilson ", + "Nick Baugh (http://niftylettuce.com/)" + ], + "repository": "component/toidentifier", + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.3", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "4.3.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.1.3", + "nyc": "15.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "license": "MIT", + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/type-is/HISTORY.md b/node_modules/type-is/HISTORY.md new file mode 100644 index 0000000..6812655 --- /dev/null +++ b/node_modules/type-is/HISTORY.md @@ -0,0 +1,292 @@ +2.0.1 / 2025-03-27 +========== + +2.0.0 / 2024-08-31 +========== + + * Drop node <18 + * Use `content-type@^1.0.5` and `media-typer@^1.0.0` for type validation + - No behavior changes, upgrades `media-typer` + * deps: mime-types@^3.0.0 + - Add `application/toml` with extension `.toml` + - Add `application/ubjson` with extension `.ubj` + - Add `application/x-keepass2` with extension `.kdbx` + - Add deprecated iWorks mime types and extensions + - Add extension `.amr` to `audio/amr` + - Add extension `.cjs` to `application/node` + - Add extension `.dbf` to `application/vnd.dbf` + - Add extension `.m4s` to `video/iso.segment` + - Add extension `.mvt` to `application/vnd.mapbox-vector-tile` + - Add extension `.mxmf` to `audio/mobile-xmf` + - Add extension `.opus` to `audio/ogg` + - Add extension `.rar` to `application/vnd.rar` + - Add extension `.td` to `application/urc-targetdesc+xml` + - Add extension `.trig` to `application/trig` + - Add extensions from IANA for `application/*+xml` types + - Add `image/avif` with extension `.avif` + - Add `image/ktx2` with extension `.ktx2` + - Add `image/vnd.ms-dds` with extension `.dds` + - Add new upstream MIME types + - Fix extension of `application/vnd.apple.keynote` to be `.key` + - Remove ambigious extensions from IANA for `application/*+xml` types + - Update primary extension to `.es` for `application/ecmascript` + +1.6.18 / 2019-04-26 +=================== + + * Fix regression passing request object to `typeis.is` + +1.6.17 / 2019-04-25 +=================== + + * deps: mime-types@~2.1.24 + - Add Apple file extensions from IANA + - Add extension `.csl` to `application/vnd.citationstyles.style+xml` + - Add extension `.es` to `application/ecmascript` + - Add extension `.nq` to `application/n-quads` + - Add extension `.nt` to `application/n-triples` + - Add extension `.owl` to `application/rdf+xml` + - Add extensions `.siv` and `.sieve` to `application/sieve` + - Add extensions from IANA for `image/*` types + - Add extensions from IANA for `model/*` types + - Add extensions to HEIC image types + - Add new mime types + - Add `text/mdx` with extension `.mdx` + * perf: prevent internal `throw` on invalid type + +1.6.16 / 2018-02-16 +=================== + + * deps: mime-types@~2.1.18 + - Add `application/raml+yaml` with extension `.raml` + - Add `application/wasm` with extension `.wasm` + - Add `text/shex` with extension `.shex` + - Add extensions for JPEG-2000 images + - Add extensions from IANA for `message/*` types + - Add extension `.mjs` to `application/javascript` + - Add extension `.wadl` to `application/vnd.sun.wadl+xml` + - Add extension `.gz` to `application/gzip` + - Add glTF types and extensions + - Add new mime types + - Update extensions `.md` and `.markdown` to be `text/markdown` + - Update font MIME types + - Update `text/hjson` to registered `application/hjson` + +1.6.15 / 2017-03-31 +=================== + + * deps: mime-types@~2.1.15 + - Add new mime types + +1.6.14 / 2016-11-18 +=================== + + * deps: mime-types@~2.1.13 + - Add new mime types + +1.6.13 / 2016-05-18 +=================== + + * deps: mime-types@~2.1.11 + - Add new mime types + +1.6.12 / 2016-02-28 +=================== + + * deps: mime-types@~2.1.10 + - Add new mime types + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + +1.6.11 / 2016-01-29 +=================== + + * deps: mime-types@~2.1.9 + - Add new mime types + +1.6.10 / 2015-12-01 +=================== + + * deps: mime-types@~2.1.8 + - Add new mime types + +1.6.9 / 2015-09-27 +================== + + * deps: mime-types@~2.1.7 + - Add new mime types + +1.6.8 / 2015-09-04 +================== + + * deps: mime-types@~2.1.6 + - Add new mime types + +1.6.7 / 2015-08-20 +================== + + * Fix type error when given invalid type to match against + * deps: mime-types@~2.1.5 + - Add new mime types + +1.6.6 / 2015-07-31 +================== + + * deps: mime-types@~2.1.4 + - Add new mime types + +1.6.5 / 2015-07-16 +================== + + * deps: mime-types@~2.1.3 + - Add new mime types + +1.6.4 / 2015-07-01 +================== + + * deps: mime-types@~2.1.2 + - Add new mime types + * perf: enable strict mode + * perf: remove argument reassignment + +1.6.3 / 2015-06-08 +================== + + * deps: mime-types@~2.1.1 + - Add new mime types + * perf: reduce try block size + * perf: remove bitwise operations + +1.6.2 / 2015-05-10 +================== + + * deps: mime-types@~2.0.11 + - Add new mime types + +1.6.1 / 2015-03-13 +================== + + * deps: mime-types@~2.0.10 + - Add new mime types + +1.6.0 / 2015-02-12 +================== + + * fix false-positives in `hasBody` `Transfer-Encoding` check + * support wildcard for both type and subtype (`*/*`) + +1.5.7 / 2015-02-09 +================== + + * fix argument reassignment + * deps: mime-types@~2.0.9 + - Add new mime types + +1.5.6 / 2015-01-29 +================== + + * deps: mime-types@~2.0.8 + - Add new mime types + +1.5.5 / 2014-12-30 +================== + + * deps: mime-types@~2.0.7 + - Add new mime types + - Fix missing extensions + - Fix various invalid MIME type entries + - Remove example template MIME types + - deps: mime-db@~1.5.0 + +1.5.4 / 2014-12-10 +================== + + * deps: mime-types@~2.0.4 + - Add new mime types + - deps: mime-db@~1.3.0 + +1.5.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - Add new mime types + - deps: mime-db@~1.2.0 + +1.5.2 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - Add new mime types + - deps: mime-db@~1.1.0 + +1.5.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + * deps: media-typer@0.3.0 + * deps: mime-types@~2.0.1 + - Support Node.js 0.6 + +1.5.0 / 2014-09-05 +================== + + * fix `hasbody` to be true for `content-length: 0` + +1.4.0 / 2014-09-02 +================== + + * update mime-types + +1.3.2 / 2014-06-24 +================== + + * use `~` range on mime-types + +1.3.1 / 2014-06-19 +================== + + * fix global variable leak + +1.3.0 / 2014-06-19 +================== + + * improve type parsing + + - invalid media type never matches + - media type not case-sensitive + - extra LWS does not affect results + +1.2.2 / 2014-06-19 +================== + + * fix behavior on unknown type argument + +1.2.1 / 2014-06-03 +================== + + * switch dependency from `mime` to `mime-types@1.0.0` + +1.2.0 / 2014-05-11 +================== + + * support suffix matching: + + - `+json` matches `application/vnd+json` + - `*/vnd+json` matches `application/vnd+json` + - `application/*+json` matches `application/vnd+json` + +1.1.0 / 2014-04-12 +================== + + * add non-array values support + * expose internal utilities: + + - `.is()` + - `.hasBody()` + - `.normalize()` + - `.match()` + +1.0.1 / 2014-03-30 +================== + + * add `multipart` as a shorthand diff --git a/node_modules/type-is/LICENSE b/node_modules/type-is/LICENSE new file mode 100644 index 0000000..386b7b6 --- /dev/null +++ b/node_modules/type-is/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014-2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/type-is/README.md b/node_modules/type-is/README.md new file mode 100644 index 0000000..d23946e --- /dev/null +++ b/node_modules/type-is/README.md @@ -0,0 +1,198 @@ +# type-is + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Infer the content-type of a request. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install type-is +``` + +## API + +```js +var http = require('http') +var typeis = require('type-is') + +http.createServer(function (req, res) { + var istext = typeis(req, ['text/*']) + res.end('you ' + (istext ? 'sent' : 'did not send') + ' me text') +}) +``` + +### typeis(request, types) + +Checks if the `request` is one of the `types`. If the request has no body, +even if there is a `Content-Type` header, then `null` is returned. If the +`Content-Type` header is invalid or does not matches any of the `types`, then +`false` is returned. Otherwise, a string of the type that matched is returned. + +The `request` argument is expected to be a Node.js HTTP request. The `types` +argument is an array of type strings. + +Each type in the `types` array can be one of the following: + +- A file extension name such as `json`. This name will be returned if matched. +- A mime type such as `application/json`. +- A mime type with a wildcard such as `*/*` or `*/json` or `application/*`. + The full mime type will be returned if matched. +- A suffix such as `+json`. This can be combined with a wildcard such as + `*/vnd+json` or `application/*+json`. The full mime type will be returned + if matched. + +Some examples to illustrate the inputs and returned value: + +```js +// req.headers.content-type = 'application/json' + +typeis(req, ['json']) // => 'json' +typeis(req, ['html', 'json']) // => 'json' +typeis(req, ['application/*']) // => 'application/json' +typeis(req, ['application/json']) // => 'application/json' + +typeis(req, ['html']) // => false +``` + +### typeis.hasBody(request) + +Returns a Boolean if the given `request` has a body, regardless of the +`Content-Type` header. + +Having a body has no relation to how large the body is (it may be 0 bytes). +This is similar to how file existence works. If a body does exist, then this +indicates that there is data to read from the Node.js request stream. + +```js +if (typeis.hasBody(req)) { + // read the body, since there is one + + req.on('data', function (chunk) { + // ... + }) +} +``` + +### typeis.is(mediaType, types) + +Checks if the `mediaType` is one of the `types`. If the `mediaType` is invalid +or does not matches any of the `types`, then `false` is returned. Otherwise, a +string of the type that matched is returned. + +The `mediaType` argument is expected to be a +[media type](https://tools.ietf.org/html/rfc6838) string. The `types` argument +is an array of type strings. + +Each type in the `types` array can be one of the following: + +- A file extension name such as `json`. This name will be returned if matched. +- A mime type such as `application/json`. +- A mime type with a wildcard such as `*/*` or `*/json` or `application/*`. + The full mime type will be returned if matched. +- A suffix such as `+json`. This can be combined with a wildcard such as + `*/vnd+json` or `application/*+json`. The full mime type will be returned + if matched. + +Some examples to illustrate the inputs and returned value: + +```js +var mediaType = 'application/json' + +typeis.is(mediaType, ['json']) // => 'json' +typeis.is(mediaType, ['html', 'json']) // => 'json' +typeis.is(mediaType, ['application/*']) // => 'application/json' +typeis.is(mediaType, ['application/json']) // => 'application/json' + +typeis.is(mediaType, ['html']) // => false +``` + +### typeis.match(expected, actual) + +Match the type string `expected` with `actual`, taking in to account wildcards. +A wildcard can only be in the type of the subtype part of a media type and only +in the `expected` value (as `actual` should be the real media type to match). A +suffix can still be included even with a wildcard subtype. If an input is +malformed, `false` will be returned. + +```js +typeis.match('text/html', 'text/html') // => true +typeis.match('*/html', 'text/html') // => true +typeis.match('text/*', 'text/html') // => true +typeis.match('*/*', 'text/html') // => true +typeis.match('*/*+json', 'application/x-custom+json') // => true +``` + +### typeis.normalize(type) + +Normalize a `type` string. This works by performing the following: + +- If the `type` is not a string, `false` is returned. +- If the string starts with `+` (so it is a `+suffix` shorthand like `+json`), + then it is expanded to contain the complete wildcard notation of `*/*+suffix`. +- If the string contains a `/`, then it is returned as the type. +- Else the string is assumed to be a file extension and the mapped media type is + returned, or `false` is there is no mapping. + +This includes two special mappings: + +- `'multipart'` -> `'multipart/*'` +- `'urlencoded'` -> `'application/x-www-form-urlencoded'` + +## Examples + +### Example body parser + +```js +var express = require('express') +var typeis = require('type-is') + +var app = express() + +app.use(function bodyParser (req, res, next) { + if (!typeis.hasBody(req)) { + return next() + } + + switch (typeis(req, ['urlencoded', 'json', 'multipart'])) { + case 'urlencoded': + // parse urlencoded body + throw new Error('implement urlencoded body parsing') + case 'json': + // parse json body + throw new Error('implement json body parsing') + case 'multipart': + // parse multipart body + throw new Error('implement multipart body parsing') + default: + // 415 error code + res.statusCode = 415 + res.end() + break + } +}) +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/type-is/master?label=ci +[ci-url]: https://github.com/jshttp/type-is/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/type-is/master +[coveralls-url]: https://coveralls.io/r/jshttp/type-is?branch=master +[node-version-image]: https://badgen.net/npm/node/type-is +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/type-is +[npm-url]: https://npmjs.org/package/type-is +[npm-version-image]: https://badgen.net/npm/v/type-is +[travis-image]: https://badgen.net/travis/jshttp/type-is/master +[travis-url]: https://travis-ci.org/jshttp/type-is diff --git a/node_modules/type-is/index.js b/node_modules/type-is/index.js new file mode 100644 index 0000000..e773845 --- /dev/null +++ b/node_modules/type-is/index.js @@ -0,0 +1,250 @@ +/*! + * type-is + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var contentType = require('content-type') +var mime = require('mime-types') +var typer = require('media-typer') + +/** + * Module exports. + * @public + */ + +module.exports = typeofrequest +module.exports.is = typeis +module.exports.hasBody = hasbody +module.exports.normalize = normalize +module.exports.match = mimeMatch + +/** + * Compare a `value` content-type with `types`. + * Each `type` can be an extension like `html`, + * a special shortcut like `multipart` or `urlencoded`, + * or a mime type. + * + * If no types match, `false` is returned. + * Otherwise, the first `type` that matches is returned. + * + * @param {String} value + * @param {Array} types + * @public + */ + +function typeis (value, types_) { + var i + var types = types_ + + // remove parameters and normalize + var val = tryNormalizeType(value) + + // no type or invalid + if (!val) { + return false + } + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length - 1) + for (i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } + + // no types, return the content type + if (!types || !types.length) { + return val + } + + var type + for (i = 0; i < types.length; i++) { + if (mimeMatch(normalize(type = types[i]), val)) { + return type[0] === '+' || type.indexOf('*') !== -1 + ? val + : type + } + } + + // no matches + return false +} + +/** + * Check if a request has a request body. + * A request with a body __must__ either have `transfer-encoding` + * or `content-length` headers set. + * http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3 + * + * @param {Object} request + * @return {Boolean} + * @public + */ + +function hasbody (req) { + return req.headers['transfer-encoding'] !== undefined || + !isNaN(req.headers['content-length']) +} + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains any of the give mime `type`s. + * If there is no request body, `null` is returned. + * If there is no content type, `false` is returned. + * Otherwise, it returns the first `type` that matches. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * this.is('html'); // => 'html' + * this.is('text/html'); // => 'text/html' + * this.is('text/*', 'application/json'); // => 'text/html' + * + * // When Content-Type is application/json + * this.is('json', 'urlencoded'); // => 'json' + * this.is('application/json'); // => 'application/json' + * this.is('html', 'application/*'); // => 'application/json' + * + * this.is('html'); // => false + * + * @param {Object} req + * @param {(String|Array)} types... + * @return {(String|false|null)} + * @public + */ + +function typeofrequest (req, types_) { + // no body + if (!hasbody(req)) return null + // support flattened arguments + var types = arguments.length > 2 + ? Array.prototype.slice.call(arguments, 1) + : types_ + // request content type + var value = req.headers['content-type'] + + return typeis(value, types) +} + +/** + * Normalize a mime type. + * If it's a shorthand, expand it to a valid mime type. + * + * In general, you probably want: + * + * var type = is(req, ['urlencoded', 'json', 'multipart']); + * + * Then use the appropriate body parsers. + * These three are the most common request body types + * and are thus ensured to work. + * + * @param {String} type + * @return {String|false|null} + * @public + */ + +function normalize (type) { + if (typeof type !== 'string') { + // invalid type + return false + } + + switch (type) { + case 'urlencoded': + return 'application/x-www-form-urlencoded' + case 'multipart': + return 'multipart/*' + } + + if (type[0] === '+') { + // "+json" -> "*/*+json" expando + return '*/*' + type + } + + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if `expected` mime type + * matches `actual` mime type with + * wildcard and +suffix support. + * + * @param {String} expected + * @param {String} actual + * @return {Boolean} + * @public + */ + +function mimeMatch (expected, actual) { + // invalid type + if (expected === false) { + return false + } + + // split types + var actualParts = actual.split('/') + var expectedParts = expected.split('/') + + // invalid format + if (actualParts.length !== 2 || expectedParts.length !== 2) { + return false + } + + // validate type + if (expectedParts[0] !== '*' && expectedParts[0] !== actualParts[0]) { + return false + } + + // validate suffix wildcard + if (expectedParts[1].slice(0, 2) === '*+') { + return expectedParts[1].length <= actualParts[1].length + 1 && + expectedParts[1].slice(1) === actualParts[1].slice(1 - expectedParts[1].length) + } + + // validate subtype + if (expectedParts[1] !== '*' && expectedParts[1] !== actualParts[1]) { + return false + } + + return true +} + +/** + * Normalize a type and remove parameters. + * + * @param {string} value + * @return {(string|null)} + * @private + */ +function normalizeType (value) { + // Parse the type + var type = contentType.parse(value).type + + return typer.test(type) ? type : null +} + +/** + * Try to normalize a type and remove parameters. + * + * @param {string} value + * @return {(string|null)} + * @private + */ +function tryNormalizeType (value) { + try { + return value ? normalizeType(value) : null + } catch (err) { + return null + } +} diff --git a/node_modules/type-is/package.json b/node_modules/type-is/package.json new file mode 100644 index 0000000..08586d2 --- /dev/null +++ b/node_modules/type-is/package.json @@ -0,0 +1,47 @@ +{ + "name": "type-is", + "description": "Infer the content-type of a request.", + "version": "2.0.1", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "jshttp/type-is", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.1", + "nyc": "15.1.0" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test:debug": "mocha --reporter spec --check-leaks --inspect --inspect-brk test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + }, + "keywords": [ + "content", + "type", + "checking" + ] +} diff --git a/node_modules/unpipe/HISTORY.md b/node_modules/unpipe/HISTORY.md new file mode 100644 index 0000000..85e0f8d --- /dev/null +++ b/node_modules/unpipe/HISTORY.md @@ -0,0 +1,4 @@ +1.0.0 / 2015-06-14 +================== + + * Initial release diff --git a/node_modules/unpipe/LICENSE b/node_modules/unpipe/LICENSE new file mode 100644 index 0000000..aed0138 --- /dev/null +++ b/node_modules/unpipe/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/unpipe/README.md b/node_modules/unpipe/README.md new file mode 100644 index 0000000..e536ad2 --- /dev/null +++ b/node_modules/unpipe/README.md @@ -0,0 +1,43 @@ +# unpipe + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Unpipe a stream from all destinations. + +## Installation + +```sh +$ npm install unpipe +``` + +## API + +```js +var unpipe = require('unpipe') +``` + +### unpipe(stream) + +Unpipes all destinations from a given stream. With stream 2+, this is +equivalent to `stream.unpipe()`. When used with streams 1 style streams +(typically Node.js 0.8 and below), this module attempts to undo the +actions done in `stream.pipe(dest)`. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/unpipe.svg +[npm-url]: https://npmjs.org/package/unpipe +[node-image]: https://img.shields.io/node/v/unpipe.svg +[node-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/stream-utils/unpipe.svg +[travis-url]: https://travis-ci.org/stream-utils/unpipe +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/unpipe.svg +[coveralls-url]: https://coveralls.io/r/stream-utils/unpipe?branch=master +[downloads-image]: https://img.shields.io/npm/dm/unpipe.svg +[downloads-url]: https://npmjs.org/package/unpipe diff --git a/node_modules/unpipe/index.js b/node_modules/unpipe/index.js new file mode 100644 index 0000000..15c3d97 --- /dev/null +++ b/node_modules/unpipe/index.js @@ -0,0 +1,69 @@ +/*! + * unpipe + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = unpipe + +/** + * Determine if there are Node.js pipe-like data listeners. + * @private + */ + +function hasPipeDataListeners(stream) { + var listeners = stream.listeners('data') + + for (var i = 0; i < listeners.length; i++) { + if (listeners[i].name === 'ondata') { + return true + } + } + + return false +} + +/** + * Unpipe a stream from all destinations. + * + * @param {object} stream + * @public + */ + +function unpipe(stream) { + if (!stream) { + throw new TypeError('argument stream is required') + } + + if (typeof stream.unpipe === 'function') { + // new-style + stream.unpipe() + return + } + + // Node.js 0.8 hack + if (!hasPipeDataListeners(stream)) { + return + } + + var listener + var listeners = stream.listeners('close') + + for (var i = 0; i < listeners.length; i++) { + listener = listeners[i] + + if (listener.name !== 'cleanup' && listener.name !== 'onclose') { + continue + } + + // invoke the listener + listener.call(stream) + } +} diff --git a/node_modules/unpipe/package.json b/node_modules/unpipe/package.json new file mode 100644 index 0000000..a2b7358 --- /dev/null +++ b/node_modules/unpipe/package.json @@ -0,0 +1,27 @@ +{ + "name": "unpipe", + "description": "Unpipe a stream from all destinations", + "version": "1.0.0", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "repository": "stream-utils/unpipe", + "devDependencies": { + "istanbul": "0.3.15", + "mocha": "2.2.5", + "readable-stream": "1.1.13" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/node_modules/vary/HISTORY.md b/node_modules/vary/HISTORY.md new file mode 100644 index 0000000..f6cbcf7 --- /dev/null +++ b/node_modules/vary/HISTORY.md @@ -0,0 +1,39 @@ +1.1.2 / 2017-09-23 +================== + + * perf: improve header token parsing speed + +1.1.1 / 2017-03-20 +================== + + * perf: hoist regular expression + +1.1.0 / 2015-09-29 +================== + + * Only accept valid field names in the `field` argument + - Ensures the resulting string is a valid HTTP header value + +1.0.1 / 2015-07-08 +================== + + * Fix setting empty header from empty `field` + * perf: enable strict mode + * perf: remove argument reassignments + +1.0.0 / 2014-08-10 +================== + + * Accept valid `Vary` header string as `field` + * Add `vary.append` for low-level string manipulation + * Move to `jshttp` orgainzation + +0.1.0 / 2014-06-05 +================== + + * Support array of fields to set + +0.0.0 / 2014-06-04 +================== + + * Initial release diff --git a/node_modules/vary/LICENSE b/node_modules/vary/LICENSE new file mode 100644 index 0000000..84441fb --- /dev/null +++ b/node_modules/vary/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/vary/README.md b/node_modules/vary/README.md new file mode 100644 index 0000000..cc000b3 --- /dev/null +++ b/node_modules/vary/README.md @@ -0,0 +1,101 @@ +# vary + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Manipulate the HTTP Vary header + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install vary +``` + +## API + + + +```js +var vary = require('vary') +``` + +### vary(res, field) + +Adds the given header `field` to the `Vary` response header of `res`. +This can be a string of a single field, a string of a valid `Vary` +header, or an array of multiple fields. + +This will append the header if not already listed, otherwise leaves +it listed in the current location. + + + +```js +// Append "Origin" to the Vary header of the response +vary(res, 'Origin') +``` + +### vary.append(header, field) + +Adds the given header `field` to the `Vary` response header string `header`. +This can be a string of a single field, a string of a valid `Vary` header, +or an array of multiple fields. + +This will append the header if not already listed, otherwise leaves +it listed in the current location. The new header string is returned. + + + +```js +// Get header string appending "Origin" to "Accept, User-Agent" +vary.append('Accept, User-Agent', 'Origin') +``` + +## Examples + +### Updating the Vary header when content is based on it + +```js +var http = require('http') +var vary = require('vary') + +http.createServer(function onRequest (req, res) { + // about to user-agent sniff + vary(res, 'User-Agent') + + var ua = req.headers['user-agent'] || '' + var isMobile = /mobi|android|touch|mini/i.test(ua) + + // serve site, depending on isMobile + res.setHeader('Content-Type', 'text/html') + res.end('You are (probably) ' + (isMobile ? '' : 'not ') + 'a mobile user') +}) +``` + +## Testing + +```sh +$ npm test +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/vary.svg +[npm-url]: https://npmjs.org/package/vary +[node-version-image]: https://img.shields.io/node/v/vary.svg +[node-version-url]: https://nodejs.org/en/download +[travis-image]: https://img.shields.io/travis/jshttp/vary/master.svg +[travis-url]: https://travis-ci.org/jshttp/vary +[coveralls-image]: https://img.shields.io/coveralls/jshttp/vary/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/vary +[downloads-image]: https://img.shields.io/npm/dm/vary.svg +[downloads-url]: https://npmjs.org/package/vary diff --git a/node_modules/vary/index.js b/node_modules/vary/index.js new file mode 100644 index 0000000..5b5e741 --- /dev/null +++ b/node_modules/vary/index.js @@ -0,0 +1,149 @@ +/*! + * vary + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = vary +module.exports.append = append + +/** + * RegExp to match field-name in RFC 7230 sec 3.2 + * + * field-name = token + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + */ + +var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/ + +/** + * Append a field to a vary header. + * + * @param {String} header + * @param {String|Array} field + * @return {String} + * @public + */ + +function append (header, field) { + if (typeof header !== 'string') { + throw new TypeError('header argument is required') + } + + if (!field) { + throw new TypeError('field argument is required') + } + + // get fields array + var fields = !Array.isArray(field) + ? parse(String(field)) + : field + + // assert on invalid field names + for (var j = 0; j < fields.length; j++) { + if (!FIELD_NAME_REGEXP.test(fields[j])) { + throw new TypeError('field argument contains an invalid header name') + } + } + + // existing, unspecified vary + if (header === '*') { + return header + } + + // enumerate current values + var val = header + var vals = parse(header.toLowerCase()) + + // unspecified vary + if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) { + return '*' + } + + for (var i = 0; i < fields.length; i++) { + var fld = fields[i].toLowerCase() + + // append value (case-preserving) + if (vals.indexOf(fld) === -1) { + vals.push(fld) + val = val + ? val + ', ' + fields[i] + : fields[i] + } + } + + return val +} + +/** + * Parse a vary header into an array. + * + * @param {String} header + * @return {Array} + * @private + */ + +function parse (header) { + var end = 0 + var list = [] + var start = 0 + + // gather tokens + for (var i = 0, len = header.length; i < len; i++) { + switch (header.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1 + } + break + case 0x2c: /* , */ + list.push(header.substring(start, end)) + start = end = i + 1 + break + default: + end = i + 1 + break + } + } + + // final token + list.push(header.substring(start, end)) + + return list +} + +/** + * Mark that a request is varied on a header field. + * + * @param {Object} res + * @param {String|Array} field + * @public + */ + +function vary (res, field) { + if (!res || !res.getHeader || !res.setHeader) { + // quack quack + throw new TypeError('res argument is required') + } + + // get existing header + var val = res.getHeader('Vary') || '' + var header = Array.isArray(val) + ? val.join(', ') + : String(val) + + // set new header + if ((val = append(header, field))) { + res.setHeader('Vary', val) + } +} diff --git a/node_modules/vary/package.json b/node_modules/vary/package.json new file mode 100644 index 0000000..028f72a --- /dev/null +++ b/node_modules/vary/package.json @@ -0,0 +1,43 @@ +{ + "name": "vary", + "description": "Manipulate the HTTP Vary header", + "version": "1.1.2", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "http", + "res", + "vary" + ], + "repository": "jshttp/vary", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "2.5.3", + "supertest": "1.1.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/node_modules/wrappy/LICENSE b/node_modules/wrappy/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/wrappy/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/wrappy/README.md b/node_modules/wrappy/README.md new file mode 100644 index 0000000..98eab25 --- /dev/null +++ b/node_modules/wrappy/README.md @@ -0,0 +1,36 @@ +# wrappy + +Callback wrapping utility + +## USAGE + +```javascript +var wrappy = require("wrappy") + +// var wrapper = wrappy(wrapperFunction) + +// make sure a cb is called only once +// See also: http://npm.im/once for this specific use case +var once = wrappy(function (cb) { + var called = false + return function () { + if (called) return + called = true + return cb.apply(this, arguments) + } +}) + +function printBoo () { + console.log('boo') +} +// has some rando property +printBoo.iAmBooPrinter = true + +var onlyPrintOnce = once(printBoo) + +onlyPrintOnce() // prints 'boo' +onlyPrintOnce() // does nothing + +// random property is retained! +assert.equal(onlyPrintOnce.iAmBooPrinter, true) +``` diff --git a/node_modules/wrappy/package.json b/node_modules/wrappy/package.json new file mode 100644 index 0000000..1307520 --- /dev/null +++ b/node_modules/wrappy/package.json @@ -0,0 +1,29 @@ +{ + "name": "wrappy", + "version": "1.0.2", + "description": "Callback wrapping utility", + "main": "wrappy.js", + "files": [ + "wrappy.js" + ], + "directories": { + "test": "test" + }, + "dependencies": {}, + "devDependencies": { + "tap": "^2.3.1" + }, + "scripts": { + "test": "tap --coverage test/*.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/npm/wrappy" + }, + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC", + "bugs": { + "url": "https://github.com/npm/wrappy/issues" + }, + "homepage": "https://github.com/npm/wrappy" +} diff --git a/node_modules/wrappy/wrappy.js b/node_modules/wrappy/wrappy.js new file mode 100644 index 0000000..bb7e7d6 --- /dev/null +++ b/node_modules/wrappy/wrappy.js @@ -0,0 +1,33 @@ +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +module.exports = wrappy +function wrappy (fn, cb) { + if (fn && cb) return wrappy(fn)(cb) + + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') + + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k] + }) + + return wrapper + + function wrapper() { + var args = new Array(arguments.length) + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + var ret = fn.apply(this, args) + var cb = args[args.length-1] + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k] + }) + } + return ret + } +} diff --git a/nostr-oidc-bridge.code-workspace b/nostr-oidc-bridge.code-workspace index 640a9d8..fae2cb4 100644 --- a/nostr-oidc-bridge.code-workspace +++ b/nostr-oidc-bridge.code-workspace @@ -7,5 +7,8 @@ "path": "../nostr-login" } ], - "settings": {} + "settings": { + "liveServer.settings.multiRootWorkspaceName": "nostr-oidc-bridge", + "liveServer.settings.port": 5501 + } } \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..1199aa2 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1145 @@ +{ + "name": "nostr-oidc-bridge", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "nostr-oidc-bridge", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "ejs": "^3.1.10", + "express": "^5.1.0", + "jsonwebtoken": "^9.0.2", + "nostr-tools": "^2.16.2" + } + }, + "node_modules/@noble/ciphers": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-0.5.3.tgz", + "integrity": "sha512-B0+6IIHiqEs3BPMT0hcRmHvEj2QHOLu+uwt+tqDDeVd0oyVzh7BPrDcPjRnV1PV/5LaknXJJQvOuRGR0zQJz+w==", + "license": "MIT", + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/curves": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.2.0.tgz", + "integrity": "sha512-oYclrNgRaM9SsBUBVbb8M6DTV7ZHRTKugureoYEncY5c65HOmRzvSiTE3y5CYaPYJA/GVkrhXEoF0M3Ya9PMnw==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.3.2" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/curves/node_modules/@noble/hashes": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.2.tgz", + "integrity": "sha512-MVC8EAQp7MvEcm30KWENFjgR+Mkmf+D189XJTkFIlwohU5hcBbn1ZkKq7KVTi2Hme3PMGF390DaL52beVrIihQ==", + "license": "MIT", + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.1.tgz", + "integrity": "sha512-EbqwksQwz9xDRGfDST86whPBgM65E0OH/pCgqW0GBVzO22bNE+NuIbeTb714+IfSjU3aRk47EUvXIb5bTsenKA==", + "license": "MIT", + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/base": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@scure/base/-/base-1.1.1.tgz", + "integrity": "sha512-ZxOhsSyxYwLJj3pLZCefNitxsj093tb2vq90mp2txoYeBqbcjDjqFhyM8eUjq/uFm6zJ+mUuqxlS2FkuSY1MTA==", + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ], + "license": "MIT" + }, + "node_modules/@scure/bip32": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-1.3.1.tgz", + "integrity": "sha512-osvveYtyzdEVbt3OfwwXFr4P2iVBL5u1Q3q4ONBfDY/UpOuXmOlbgwc1xECEboY8wIays8Yt6onaWMUdUbfl0A==", + "license": "MIT", + "dependencies": { + "@noble/curves": "~1.1.0", + "@noble/hashes": "~1.3.1", + "@scure/base": "~1.1.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip32/node_modules/@noble/curves": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.1.0.tgz", + "integrity": "sha512-091oBExgENk/kGj3AZmtBDMpxQPDtxQABR2B9lb1JbVTs6ytdzZNwvhxQ4MWasRNEzlbEH8jCWFCwhF/Obj5AA==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.3.1" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip39": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-1.2.1.tgz", + "integrity": "sha512-Z3/Fsz1yr904dduJD0NpiyRHhRYHdcnyh73FZWiV+/qhWi83wNJ3NWolYqCEN+ZWsUz2TWwajJggcRE9r1zUYg==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "~1.3.0", + "@scure/base": "~1.1.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/async": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", + "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", + "license": "MIT" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT" + }, + "node_modules/body-parser": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.0.tgz", + "integrity": "sha512-02qvAaxv8tp7fBa/mw1ga98OGm+eCbqzJOKoRt70sLmfEEi+jyBYVTDGfCL/k06/4EMk/z01gCe7HoCH/f2LTg==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^1.0.5", + "debug": "^4.4.0", + "http-errors": "^2.0.0", + "iconv-lite": "^0.6.3", + "on-finished": "^2.4.1", + "qs": "^6.14.0", + "raw-body": "^3.0.0", + "type-is": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/brace-expansion": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", + "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.0.tgz", + "integrity": "sha512-Au9nRL8VNUut/XSzbQA38+M78dzP4D+eqg3gfJHMIHHYa3bg067xj1KxMUWj+VULbiZMowKngFFbKczUrNJ1mg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/debug": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz", + "integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/ejs": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz", + "integrity": "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==", + "license": "Apache-2.0", + "dependencies": { + "jake": "^10.8.5" + }, + "bin": { + "ejs": "bin/cli.js" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz", + "integrity": "sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.0", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/filelist": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.4.tgz", + "integrity": "sha512-w1cEuf3S+DrLCQL7ET6kz+gmlJdbq9J7yXCSjK/OZCPA+qEN1WyF4ZAf0YYJa4/shHJra2t/d/r8SV4Ji+x+8Q==", + "license": "Apache-2.0", + "dependencies": { + "minimatch": "^5.0.1" + } + }, + "node_modules/finalhandler": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.0.tgz", + "integrity": "sha512-/t88Ty3d5JWQbWYgaOGCCYfXRwV1+be02WqYYlL6h0lEiUAMPM8o8qKGO01YIkOHzka2up08wvgYD0mDiI+q3Q==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "license": "MIT", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/http-errors/node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/jake": { + "version": "10.9.4", + "resolved": "https://registry.npmjs.org/jake/-/jake-10.9.4.tgz", + "integrity": "sha512-wpHYzhxiVQL+IV05BLE2Xn34zW1S223hvjtqk0+gsPrwd/8JNLXJgZZM/iPFsYc1xyphF+6M6EvdE5E9MBGkDA==", + "license": "Apache-2.0", + "dependencies": { + "async": "^3.2.6", + "filelist": "^1.0.4", + "picocolors": "^1.1.1" + }, + "bin": { + "jake": "bin/cli.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/jsonwebtoken": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz", + "integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==", + "license": "MIT", + "dependencies": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=12", + "npm": ">=6" + } + }, + "node_modules/jwa": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.2.tgz", + "integrity": "sha512-eeH5JO+21J78qMvTIDdBXidBd6nG2kZjg5Ohz/1fpa28Z4CcsWUzJ1ZZyFq/3z3N17aZy+ZuBoHljASbL1WfOw==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", + "license": "MIT", + "dependencies": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==", + "license": "MIT" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==", + "license": "MIT" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==", + "license": "MIT" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==", + "license": "MIT" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", + "license": "MIT" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==", + "license": "MIT" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==", + "license": "MIT" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.1.tgz", + "integrity": "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minimatch": { + "version": "5.1.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz", + "integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/nostr-tools": { + "version": "2.16.2", + "resolved": "https://registry.npmjs.org/nostr-tools/-/nostr-tools-2.16.2.tgz", + "integrity": "sha512-ZxH9EbSt5ypURZj2TGNJxZd0Omb5ag5KZSu8IyJMCdLyg2KKz+2GA0sP/cSawCQEkyviIN4eRT4G2gB/t9lMRw==", + "license": "Unlicense", + "dependencies": { + "@noble/ciphers": "^0.5.1", + "@noble/curves": "1.2.0", + "@noble/hashes": "1.3.1", + "@scure/base": "1.1.1", + "@scure/bip32": "1.3.1", + "@scure/bip39": "1.2.1", + "nostr-wasm": "0.1.0" + }, + "peerDependencies": { + "typescript": ">=5.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/nostr-wasm": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/nostr-wasm/-/nostr-wasm-0.1.0.tgz", + "integrity": "sha512-78BTryCLcLYv96ONU8Ws3Q1JzjlAt+43pWQhIl86xZmWeegYCNLPml7yQ+gG3vR6V5h4XGj+TxO+SS5dsThQIA==", + "license": "MIT" + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.2.0.tgz", + "integrity": "sha512-TdrF7fW9Rphjq4RjrW0Kp2AW0Ahwu9sRGTkS6bvDi0SCwZlEZYmcfDbEsTz8RVk0EHIS/Vd1bv3JhG+1xZuAyQ==", + "license": "MIT", + "engines": { + "node": ">=16" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.0.tgz", + "integrity": "sha512-RmkhL8CAyCRPXCE28MMH0z2PNWQBNk2Q09ZdxM9IOOXwxwZbN+qbWaatPkdkWIKL2ZVDImrN/pK5HTRz2PcS4g==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.6.3", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.7.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz", + "integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.0.tgz", + "integrity": "sha512-uaW0WwXKpL9blXE2o0bRhoL2EGXIrZxQ2ZQ4mgcfoBxdFmQold+qWsD2jLrfZ0trjKL6vOw0j//eAwcALFjKSw==", + "license": "MIT", + "dependencies": { + "debug": "^4.3.5", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "mime-types": "^3.0.1", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/serve-static": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.0.tgz", + "integrity": "sha512-61g9pCh0Vnh7IutZjtLGGpTA355+OPn2TyDv/6ivP2h/AdAVX9azsoxmg2/M6nZeQZNYBEwIcsne1mJd9oQItQ==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/type-is": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", + "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", + "license": "MIT", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + } + } +} diff --git a/package.json b/package.json index adc4760..b84c537 100644 --- a/package.json +++ b/package.json @@ -1,22 +1,20 @@ { -"type": "module", + "type": "module", "name": "nostr-oidc-bridge", "version": "1.0.0", - "description": "", - "main": "index.js", + "description": "Nostr OpenID Connect Bridge for OAuth2 authentication", + "main": "app.js", "scripts": { + "start": "node app.js", "test": "echo \"Error: no test specified\" && exit 1" }, - "keywords": [], + "keywords": ["nostr", "oidc", "oauth2", "authentication"], "author": "", "license": "ISC", "dependencies": { "ejs": "^3.1.10", "express": "^5.1.0", - "jose": "^6.0.12", "jsonwebtoken": "^9.0.2", - "nostr-tools": "^2.16.2", - "oidc-provider": "^9.4.0", - "ws": "^8.18.3" + "nostr-tools": "^2.16.2" } }